diff options
Diffstat (limited to 'security/nss/lib/softoken')
43 files changed, 0 insertions, 36620 deletions
diff --git a/security/nss/lib/softoken/Makefile b/security/nss/lib/softoken/Makefile deleted file mode 100644 index fa3b20648..000000000 --- a/security/nss/lib/softoken/Makefile +++ /dev/null @@ -1,91 +0,0 @@ -#! gmake -# -# 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. -# - -####################################################################### -# (1) Include initial platform-independent assignments (MANDATORY). # -####################################################################### - -include manifest.mn - -####################################################################### -# (2) Include "global" configuration information. (OPTIONAL) # -####################################################################### - -include $(CORE_DEPTH)/coreconf/config.mk - -####################################################################### -# (3) Include "component" configuration information. (OPTIONAL) # -####################################################################### - - - -####################################################################### -# (4) Include "local" platform-dependent assignments (OPTIONAL). # -####################################################################### - -include config.mk - -####################################################################### -# (5) Execute "global" rules. (OPTIONAL) # -####################################################################### - -include $(CORE_DEPTH)/coreconf/rules.mk - -####################################################################### -# (6) Execute "component" rules. (OPTIONAL) # -####################################################################### - - - -####################################################################### -# (7) Execute "local" rules. (OPTIONAL). # -####################################################################### - -export:: private_export - -# On AIX 4.3, IBM xlC_r compiler (version 3.6.6) cannot compile -# pkcs11c.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)/pkcs11.o: pkcs11.c - @$(MAKE_OBJDIR) - $(CC) -o $@ -c -O2 $(CFLAGS) $< -$(OBJDIR)/pkcs11c.o: pkcs11c.c - @$(MAKE_OBJDIR) - $(CC) -o $@ -c -O2 $(CFLAGS) $< -endif -endif -endif diff --git a/security/nss/lib/softoken/alghmac.c b/security/nss/lib/softoken/alghmac.c deleted file mode 100644 index fb22fbd9c..000000000 --- a/security/nss/lib/softoken/alghmac.c +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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. - */ - -#include "sechash.h" -#include "secport.h" -#include "alghmac.h" -#include "secerr.h" - -#define HMAC_PAD_SIZE 64 - -struct HMACContextStr { - void *hash; - const SECHashObject *hashobj; - unsigned char ipad[HMAC_PAD_SIZE]; - unsigned char opad[HMAC_PAD_SIZE]; -}; - -void -HMAC_Destroy(HMACContext *cx) -{ - if (cx == NULL) - return; - - if (cx->hash != NULL) - cx->hashobj->destroy(cx->hash, PR_TRUE); - PORT_ZFree(cx, sizeof(HMACContext)); -} - -HMACContext * -HMAC_Create(const SECHashObject *hash_obj, const unsigned char *secret, - unsigned int secret_len, PRBool isFIPS) -{ - HMACContext *cx; - unsigned int i; - unsigned char hashed_secret[HASH_LENGTH_MAX]; - - /* required by FIPS 198 Section 3 */ - if (isFIPS && secret_len < hash_obj->length/2) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; - } - cx = (HMACContext*)PORT_ZAlloc(sizeof(HMACContext)); - if (cx == NULL) - return NULL; - cx->hashobj = hash_obj; - - cx->hash = cx->hashobj->create(); - if (cx->hash == NULL) - goto loser; - - if (secret_len > HMAC_PAD_SIZE) { - cx->hashobj->begin( cx->hash); - cx->hashobj->update(cx->hash, secret, secret_len); - PORT_Assert(cx->hashobj->length <= sizeof hashed_secret); - cx->hashobj->end( cx->hash, hashed_secret, &secret_len, - sizeof hashed_secret); - if (secret_len != cx->hashobj->length) - goto loser; - secret = (const unsigned char *)&hashed_secret[0]; - } - - PORT_Memset(cx->ipad, 0x36, sizeof cx->ipad); - PORT_Memset(cx->opad, 0x5c, sizeof cx->opad); - - /* fold secret into padding */ - for (i = 0; i < secret_len; i++) { - cx->ipad[i] ^= secret[i]; - cx->opad[i] ^= secret[i]; - } - PORT_Memset(hashed_secret, 0, sizeof hashed_secret); - return cx; - -loser: - PORT_Memset(hashed_secret, 0, sizeof hashed_secret); - HMAC_Destroy(cx); - return NULL; -} - -void -HMAC_Begin(HMACContext *cx) -{ - /* start inner hash */ - cx->hashobj->begin(cx->hash); - cx->hashobj->update(cx->hash, cx->ipad, sizeof(cx->ipad)); -} - -void -HMAC_Update(HMACContext *cx, const unsigned char *data, unsigned int data_len) -{ - cx->hashobj->update(cx->hash, data, data_len); -} - -SECStatus -HMAC_Finish(HMACContext *cx, unsigned char *result, unsigned int *result_len, - unsigned int max_result_len) -{ - if (max_result_len < cx->hashobj->length) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - cx->hashobj->end(cx->hash, result, result_len, max_result_len); - if (*result_len != cx->hashobj->length) - return SECFailure; - - cx->hashobj->begin(cx->hash); - cx->hashobj->update(cx->hash, cx->opad, sizeof(cx->opad)); - cx->hashobj->update(cx->hash, result, *result_len); - cx->hashobj->end(cx->hash, result, result_len, max_result_len); - return SECSuccess; -} - -HMACContext * -HMAC_Clone(HMACContext *cx) -{ - HMACContext *newcx; - - newcx = (HMACContext*)PORT_ZAlloc(sizeof(HMACContext)); - if (newcx == NULL) - goto loser; - - newcx->hashobj = cx->hashobj; - newcx->hash = cx->hashobj->clone(cx->hash); - if (newcx->hash == NULL) - goto loser; - PORT_Memcpy(newcx->ipad, cx->ipad, sizeof(cx->ipad)); - PORT_Memcpy(newcx->opad, cx->opad, sizeof(cx->opad)); - return newcx; - -loser: - HMAC_Destroy(newcx); - return NULL; -} diff --git a/security/nss/lib/softoken/alghmac.h b/security/nss/lib/softoken/alghmac.h deleted file mode 100644 index fe1ff59d2..000000000 --- a/security/nss/lib/softoken/alghmac.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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 _ALGHMAC_H_ -#define _ALGHMAC_H_ - -typedef struct HMACContextStr HMACContext; - -SEC_BEGIN_PROTOS - -/* destroy HMAC context */ -extern void -HMAC_Destroy(HMACContext *cx); - -/* create HMAC context - * hashObj hash object from SECRawHashObjects[] - * secret the secret with which the HMAC is performed. - * secret_len the length of the secret. - * isFIPS true if conforming to FIPS 198. - * - * NULL is returned if an error occurs. - */ -extern HMACContext * -HMAC_Create(const SECHashObject *hashObj, const unsigned char *secret, - unsigned int secret_len, PRBool isFIPS); - -/* reset HMAC for a fresh round */ -extern void -HMAC_Begin(HMACContext *cx); - -/* update HMAC - * cx HMAC Context - * data the data to perform HMAC on - * data_len the length of the data to process - */ -extern void -HMAC_Update(HMACContext *cx, const unsigned char *data, unsigned int data_len); - -/* Finish HMAC -- place the results within result - * cx HMAC context - * result buffer for resulting hmac'd data - * result_len where the resultant hmac length is stored - * max_result_len maximum possible length that can be stored in result - */ -extern SECStatus -HMAC_Finish(HMACContext *cx, unsigned char *result, unsigned int *result_len, - unsigned int max_result_len); - -/* clone a copy of the HMAC state. this is usefult when you would - * need to keep a running hmac but also need to extract portions - * partway through the process. - */ -extern HMACContext * -HMAC_Clone(HMACContext *cx); - -SEC_END_PROTOS - -#endif diff --git a/security/nss/lib/softoken/cdbhdl.h b/security/nss/lib/softoken/cdbhdl.h deleted file mode 100644 index d3a3f7c8d..000000000 --- a/security/nss/lib/softoken/cdbhdl.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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. - */ -/* - * cdbhdl.h - certificate database handle - * private to the certdb module - * - * $Id$ - */ -#ifndef _CDBHDL_H_ -#define _CDBHDL_H_ - -#include "nspr.h" -#include "mcom_db.h" -#include "pcertt.h" - -/* - * Handle structure for open certificate databases - */ -struct NSSLOWCERTCertDBHandleStr { - DB *permCertDB; - PZMonitor *dbMon; - PRBool dbVerify; -}; - -#ifdef DBM_USING_NSPR -#define NO_RDONLY PR_RDONLY -#define NO_RDWR PR_RDWR -#define NO_CREATE (PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE) -#else -#define NO_RDONLY O_RDONLY -#define NO_RDWR O_RDWR -#define NO_CREATE (O_RDWR | O_CREAT | O_TRUNC) -#endif - -typedef DB * (*rdbfunc)(const char *appName, const char *prefix, - const char *type, int flags); -typedef int (*rdbstatusfunc)(void); - -#define RDB_FAIL 1 -#define RDB_RETRY 2 - -DB * rdbopen(const char *appName, const char *prefix, - const char *type, int flags, int *status); - -DB *dbsopen (const char *dbname , int flags, int mode, DBTYPE type, - const void * appData); -SECStatus db_Copy(DB *dest,DB *src); -int db_BeginTransaction(DB *db); -int db_FinishTransaction(DB *db, PRBool abort); -int db_InitComplete(DB *db); - -#endif diff --git a/security/nss/lib/softoken/config.mk b/security/nss/lib/softoken/config.mk deleted file mode 100644 index adf0ea0df..000000000 --- a/security/nss/lib/softoken/config.mk +++ /dev/null @@ -1,98 +0,0 @@ -# -# 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. -# - -# $(PROGRAM) has explicit dependencies on $(EXTRA_LIBS) -CRYPTOLIB=$(DIST)/lib/$(LIB_PREFIX)freebl.$(LIB_SUFFIX) -CRYPTODIR=../freebl -ifdef MOZILLA_SECURITY_BUILD - CRYPTOLIB=$(DIST)/lib/$(LIB_PREFIX)crypto.$(LIB_SUFFIX) - CRYPTODIR=../crypto -endif - -EXTRA_LIBS += \ - $(CRYPTOLIB) \ - $(DIST)/lib/$(LIB_PREFIX)secutil.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)dbm.$(LIB_SUFFIX) \ - $(NULL) - -# can't do this in manifest.mn because OS_TARGET isn't defined there. -ifeq (,$(filter-out WIN%,$(OS_TARGET))) - -# don't want the 32 in the shared library name -SHARED_LIBRARY = $(OBJDIR)/$(DLL_PREFIX)$(LIBRARY_NAME)$(LIBRARY_VERSION).$(DLL_SUFFIX) -IMPORT_LIBRARY = $(OBJDIR)/$(IMPORT_LIB_PREFIX)$(LIBRARY_NAME)$(LIBRARY_VERSION)$(IMPORT_LIB_SUFFIX) - -RES = $(OBJDIR)/$(LIBRARY_NAME).res -RESNAME = $(LIBRARY_NAME).rc - -ifdef NS_USE_GCC -EXTRA_SHARED_LIBS += \ - -L$(DIST)/lib \ - -lplc4 \ - -lplds4 \ - -lnspr4 \ - $(NULL) -else # ! NS_USE_GCC - -EXTRA_SHARED_LIBS += \ - $(DIST)/lib/$(NSPR31_LIB_PREFIX)plc4.lib \ - $(DIST)/lib/$(NSPR31_LIB_PREFIX)plds4.lib \ - $(DIST)/lib/$(NSPR31_LIB_PREFIX)nspr4.lib \ - $(NULL) -endif # NS_USE_GCC - -else - -# $(PROGRAM) has NO explicit dependencies on $(EXTRA_SHARED_LIBS) -# $(EXTRA_SHARED_LIBS) come before $(OS_LIBS), except on AIX. -EXTRA_SHARED_LIBS += \ - -L$(DIST)/lib/ \ - -lplc4 \ - -lplds4 \ - -lnspr4 \ - $(NULL) -endif - -ifeq ($(OS_TARGET),SunOS) -ifndef USE_64 -ifeq ($(CPU_ARCH),sparc) -# The -R '$ORIGIN' linker option instructs libsoftokn3.so to search for its -# dependencies (libfreebl_*.so) in the same directory where it resides. -MKSHLIB += -R '$$ORIGIN' -endif -endif -endif - -ifeq ($(OS_TARGET),WINCE) -DEFINES += -DDBM_USING_NSPR -endif diff --git a/security/nss/lib/softoken/dbinit.c b/security/nss/lib/softoken/dbinit.c deleted file mode 100644 index 1dddb6035..000000000 --- a/security/nss/lib/softoken/dbinit.c +++ /dev/null @@ -1,418 +0,0 @@ -/* - * NSS utility functions - * - * 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. - * - # $Id$ - */ - -#include <ctype.h> -#include "seccomon.h" -#include "prinit.h" -#include "prprf.h" -#include "prmem.h" -#include "pcertt.h" -#include "lowkeyi.h" -#include "pcert.h" -#include "cdbhdl.h" -#include "pkcs11i.h" - -static char * -pk11_certdb_name_cb(void *arg, int dbVersion) -{ - const char *configdir = (const char *)arg; - const char *dbver; - char *smpname = NULL; - char *dbname = NULL; - - switch (dbVersion) { - case 8: - dbver = "8"; - break; - case 7: - dbver = "7"; - break; - case 6: - dbver = "6"; - break; - case 5: - dbver = "5"; - break; - case 4: - default: - dbver = ""; - break; - } - - /* make sure we return something allocated with PORT_ so we have properly - * matched frees at the end */ - smpname = PR_smprintf(CERT_DB_FMT, configdir, dbver); - if (smpname) { - dbname = PORT_Strdup(smpname); - PR_smprintf_free(smpname); - } - return dbname; -} - -static char * -pk11_keydb_name_cb(void *arg, int dbVersion) -{ - const char *configdir = (const char *)arg; - const char *dbver; - char *smpname = NULL; - char *dbname = NULL; - - switch (dbVersion) { - case 4: - dbver = "4"; - break; - case 3: - dbver = "3"; - break; - case 1: - dbver = "1"; - break; - case 2: - default: - dbver = ""; - break; - } - - smpname = PR_smprintf(KEY_DB_FMT, configdir, dbver); - if (smpname) { - dbname = PORT_Strdup(smpname); - PR_smprintf_free(smpname); - } - return dbname; -} - -/* for now... we need to define vendor specific codes here. - */ -#define CKR_CERTDB_FAILED CKR_DEVICE_ERROR -#define CKR_KEYDB_FAILED CKR_DEVICE_ERROR - -const char * -pk11_EvaluateConfigDir(const char *configdir,char **appName) -{ - if (PORT_Strncmp(configdir, MULTIACCESS, sizeof(MULTIACCESS)-1) == 0) { - char *cdir; - - *appName = PORT_Strdup(configdir+sizeof(MULTIACCESS)-1); - if (*appName == NULL) { - return configdir; - } - cdir = *appName; - while (*cdir && *cdir != ':') { - cdir++; - } - if (*cdir == ':') { - *cdir = 0; - cdir++; - } - configdir = cdir; - } - return configdir; -} - -static CK_RV -pk11_OpenCertDB(const char * configdir, const char *prefix, PRBool readOnly, - NSSLOWCERTCertDBHandle **certdbPtr) -{ - NSSLOWCERTCertDBHandle *certdb = NULL; - CK_RV crv = CKR_CERTDB_FAILED; - SECStatus rv; - char * name = NULL; - char * appName = NULL; - - if (prefix == NULL) { - prefix = ""; - } - - configdir = pk11_EvaluateConfigDir(configdir, &appName); - - name = PR_smprintf("%s" PATH_SEPARATOR "%s",configdir,prefix); - if (name == NULL) goto loser; - - certdb = (NSSLOWCERTCertDBHandle*)PORT_ZAlloc(sizeof(NSSLOWCERTCertDBHandle)); - if (certdb == NULL) - goto loser; - -/* fix when we get the DB in */ - rv = nsslowcert_OpenCertDB(certdb, readOnly, appName, prefix, - pk11_certdb_name_cb, (void *)name, PR_FALSE); - if (rv == SECSuccess) { - crv = CKR_OK; - *certdbPtr = certdb; - certdb = NULL; - } -loser: - if (certdb) PR_Free(certdb); - if (name) PR_smprintf_free(name); - if (appName) PORT_Free(appName); - return crv; -} - -static CK_RV -pk11_OpenKeyDB(const char * configdir, const char *prefix, PRBool readOnly, - NSSLOWKEYDBHandle **keydbPtr) -{ - NSSLOWKEYDBHandle *keydb; - char * name = NULL; - char * appName = NULL; - - if (prefix == NULL) { - prefix = ""; - } - configdir = pk11_EvaluateConfigDir(configdir, &appName); - - name = PR_smprintf("%s" PATH_SEPARATOR "%s",configdir,prefix); - if (name == NULL) - return SECFailure; - keydb = nsslowkey_OpenKeyDB(readOnly, appName, prefix, - pk11_keydb_name_cb, (void *)name); - PR_smprintf_free(name); - if (appName) PORT_Free(appName); - if (keydb == NULL) - return CKR_KEYDB_FAILED; - *keydbPtr = keydb; - - return CKR_OK; -} - - -/* - * OK there are now lots of options here, lets go through them all: - * - * configdir - base directory where all the cert, key, and module datbases live. - * certPrefix - prefix added to the beginning of the cert database example: " - * "https-server1-" - * keyPrefix - prefix added to the beginning of the key database example: " - * "https-server1-" - * secmodName - name of the security module database (usually "secmod.db"). - * readOnly - Boolean: true if the databases are to be openned read only. - * nocertdb - Don't open the cert DB and key DB's, just initialize the - * Volatile certdb. - * nomoddb - Don't open the security module DB, just initialize the - * PKCS #11 module. - * forceOpen - Continue to force initializations even if the databases cannot - * be opened. - */ -CK_RV -pk11_DBInit(const char *configdir, const char *certPrefix, - const char *keyPrefix, PRBool readOnly, - PRBool noCertDB, PRBool noKeyDB, PRBool forceOpen, - NSSLOWCERTCertDBHandle **certdbPtr, NSSLOWKEYDBHandle **keydbPtr) -{ - CK_RV crv = CKR_OK; - - - if (!noCertDB) { - crv = pk11_OpenCertDB(configdir, certPrefix, readOnly, certdbPtr); - if (crv != CKR_OK) { - if (!forceOpen) goto loser; - crv = CKR_OK; - } - } - if (!noKeyDB) { - - crv = pk11_OpenKeyDB(configdir, keyPrefix, readOnly, keydbPtr); - if (crv != CKR_OK) { - if (!forceOpen) goto loser; - crv = CKR_OK; - } - } - - -loser: - return crv; -} - - -void -pk11_DBShutdown(NSSLOWCERTCertDBHandle *certHandle, - NSSLOWKEYDBHandle *keyHandle) -{ - if (certHandle) { - nsslowcert_ClosePermCertDB(certHandle); - PORT_Free(certHandle); - certHandle= NULL; - } - - if (keyHandle) { - nsslowkey_CloseKeyDB(keyHandle); - keyHandle= NULL; - } -} - -static int rdbmapflags(int flags); -static rdbfunc pk11_rdbfunc = NULL; -static rdbstatusfunc pk11_rdbstatusfunc = NULL; - -/* NOTE: SHLIB_SUFFIX is defined on the command line */ -#define RDBLIB SHLIB_PREFIX"rdb."SHLIB_SUFFIX - -DB * rdbopen(const char *appName, const char *prefix, - const char *type, int flags, int *status) -{ - PRLibrary *lib; - DB *db; - - if (pk11_rdbfunc) { - db = (*pk11_rdbfunc)(appName,prefix,type,rdbmapflags(flags)); - if (!db && status && pk11_rdbstatusfunc) { - *status = (*pk11_rdbstatusfunc)(); - } - return db; - } - - /* - * try to open the library. - */ - lib = PR_LoadLibrary(RDBLIB); - - if (!lib) { - return NULL; - } - - /* get the entry points */ - pk11_rdbstatusfunc = (rdbstatusfunc) PR_FindSymbol(lib,"rdbstatus"); - pk11_rdbfunc = (rdbfunc) PR_FindSymbol(lib,"rdbopen"); - if (pk11_rdbfunc) { - db = (*pk11_rdbfunc)(appName,prefix,type,rdbmapflags(flags)); - if (!db && status && pk11_rdbstatusfunc) { - *status = (*pk11_rdbstatusfunc)(); - } - return db; - } - - /* couldn't find the entry point, unload the library and fail */ - PR_UnloadLibrary(lib); - return NULL; -} - -/* - * the following data structures are from rdb.h. - */ -struct RDBStr { - DB db; - int (*xactstart)(DB *db); - int (*xactdone)(DB *db, PRBool abort); - int version; - int (*dbinitcomplete)(DB *db); -}; - -#define DB_RDB ((DBTYPE) 0xff) -#define RDB_RDONLY 1 -#define RDB_RDWR 2 -#define RDB_CREATE 4 - -static int -rdbmapflags(int flags) { - switch (flags) { - case NO_RDONLY: - return RDB_RDONLY; - case NO_RDWR: - return RDB_RDWR; - case NO_CREATE: - return RDB_CREATE; - default: - break; - } - return 0; -} - - -PRBool -db_IsRDB(DB *db) -{ - return (PRBool) db->type == DB_RDB; -} - -int -db_BeginTransaction(DB *db) -{ - struct RDBStr *rdb = (struct RDBStr *)db; - if (db->type != DB_RDB) { - return 0; - } - - return rdb->xactstart(db); -} - -int -db_FinishTransaction(DB *db, PRBool abort) -{ - struct RDBStr *rdb = (struct RDBStr *)db; - if (db->type != DB_RDB) { - return 0; - } - - return rdb->xactdone(db, abort); -} - -int -db_InitComplete(DB *db) -{ - struct RDBStr *rdb = (struct RDBStr *)db; - if (db->type != DB_RDB) { - return 0; - } - /* we should have addes a version number to the RDBS structure. Since we - * didn't, we detect that we have and 'extended' structure if the rdbstatus - * func exists */ - if (!pk11_rdbstatusfunc) { - return 0; - } - - return rdb->dbinitcomplete(db); -} - - - -SECStatus -db_Copy(DB *dest,DB *src) -{ - int ret; - DBT key,data; - ret = (*src->seq)(src, &key, &data, R_FIRST); - if (ret) { - return SECSuccess; - } - - do { - (void)(*dest->put)(dest,&key,&data, R_NOOVERWRITE); - } while ( (*src->seq)(src, &key, &data, R_NEXT) == 0); - (void)(*dest->sync)(dest,0); - - return SECSuccess; -} - diff --git a/security/nss/lib/softoken/dbmshim.c b/security/nss/lib/softoken/dbmshim.c deleted file mode 100644 index a085765c6..000000000 --- a/security/nss/lib/softoken/dbmshim.c +++ /dev/null @@ -1,661 +0,0 @@ -/* - * 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. - */ - -/* - * Berkeley DB 1.85 Shim code to handle blobs. - * - * $Id$ - */ -#include "mcom_db.h" -#include "secitem.h" -#include "secder.h" -#include "prprf.h" -#include "cdbhdl.h" - -/* Call to PK11_FreeSlot below */ - -#include "pcertt.h" -#include "secasn1.h" -#include "secerr.h" -#include "nssb64.h" -#include "blapi.h" -#include "sechash.h" - -#include "pkcs11i.h" - -/* - * Blob block: - * Byte 0 CERTDB Version -+ -+ - * Byte 1 certDBEntryTypeBlob | BLOB_HEAD_LEN | - * Byte 2 flags (always '0'); | | - * Byte 3 reserved (always '0'); -+ | - * Byte 4 LSB length | <--BLOB_LENGTH_START | BLOB_BUF_LEN - * Byte 5 . | | - * Byte 6 . | BLOB_LENGTH_LEN | - * Byte 7 MSB length | | - * Byte 8 blob_filename -+ -+ <-- BLOB_NAME_START | - * Byte 9 . | BLOB_NAME_LEN | - * . . | | - * Byte 37 . -+ -+ - */ -#define DBS_BLOCK_SIZE (16*1024) /* 16 k */ -#define DBS_MAX_ENTRY_SIZE (DBS_BLOCK_SIZE - (2048)) /* 14 k */ -#define DBS_CACHE_SIZE DBS_BLOCK_SIZE*8 -#define ROUNDDIV(x,y) (x+(y-1))/y -#define BLOB_HEAD_LEN 4 -#define BLOB_LENGTH_START BLOB_HEAD_LEN -#define BLOB_LENGTH_LEN 4 -#define BLOB_NAME_START BLOB_LENGTH_START+BLOB_LENGTH_LEN -#define BLOB_NAME_LEN 1+ROUNDDIV(SHA1_LENGTH,3)*4+1 -#define BLOB_BUF_LEN BLOB_HEAD_LEN+BLOB_LENGTH_LEN+BLOB_NAME_LEN - -/* a Shim data structure. This data structure has a db built into it. */ -typedef struct DBSStr DBS; - -struct DBSStr { - DB db; - char *blobdir; - int mode; - PRBool readOnly; - PRFileMap *dbs_mapfile; - unsigned char *dbs_addr; - PRUint32 dbs_len; - char staticBlobArea[BLOB_BUF_LEN]; -}; - - - -/* - * return true if the Datablock contains a blobtype - */ -static PRBool -dbs_IsBlob(DBT *blobData) -{ - unsigned char *addr = (unsigned char *)blobData->data; - if (blobData->size < BLOB_BUF_LEN) { - return PR_FALSE; - } - return addr && ((certDBEntryType) addr[1] == certDBEntryTypeBlob); -} - -/* - * extract the filename in the blob of the real data set. - * This value is not malloced (does not need to be freed by the caller. - */ -static const char * -dbs_getBlobFileName(DBT *blobData) -{ - char *addr = (char *)blobData->data; - - return &addr[BLOB_NAME_START]; -} - -/* - * extract the size of the actual blob from the blob record - */ -static PRUint32 -dbs_getBlobSize(DBT *blobData) -{ - unsigned char *addr = (unsigned char *)blobData->data; - - return (PRUint32)(addr[BLOB_LENGTH_START+3] << 24) | - (addr[BLOB_LENGTH_START+2] << 16) | - (addr[BLOB_LENGTH_START+1] << 8) | - addr[BLOB_LENGTH_START]; -} - - -/* We are using base64 data for the filename, but base64 data can include a - * '/' which is interpreted as a path separator on many platforms. Replace it - * with an inocuous '-'. We don't need to convert back because we never actual - * decode the filename. - */ - -static void -dbs_replaceSlash(char *cp, int len) -{ - while (len--) { - if (*cp == '/') *cp = '-'; - cp++; - } -} - -/* - * create a blob record from a key, data and return it in blobData. - * NOTE: The data element is static data (keeping with the dbm model). - */ -static void -dbs_mkBlob(DBS *dbsp,const DBT *key, const DBT *data, DBT *blobData) -{ - unsigned char sha1_data[SHA1_LENGTH]; - char *b = dbsp->staticBlobArea; - PRUint32 length = data->size; - SECItem sha1Item; - - b[0] = CERT_DB_FILE_VERSION; /* certdb version number */ - b[1] = (char) certDBEntryTypeBlob; /* type */ - b[2] = 0; /* flags */ - b[3] = 0; /* reserved */ - b[BLOB_LENGTH_START] = length & 0xff; - b[BLOB_LENGTH_START+1] = (length >> 8) & 0xff; - b[BLOB_LENGTH_START+2] = (length >> 16) & 0xff; - b[BLOB_LENGTH_START+3] = (length >> 24) & 0xff; - sha1Item.data = sha1_data; - sha1Item.len = SHA1_LENGTH; - SHA1_HashBuf(sha1_data,key->data,key->size); - b[BLOB_NAME_START]='b'; /* Make sure we start with a alpha */ - NSSBase64_EncodeItem(NULL,&b[BLOB_NAME_START+1],BLOB_NAME_LEN-1,&sha1Item); - b[BLOB_BUF_LEN-1] = 0; - dbs_replaceSlash(&b[BLOB_NAME_START+1],BLOB_NAME_LEN-1); - blobData->data = b; - blobData->size = BLOB_BUF_LEN; - return; -} - - -/* - * construct a path to the actual blob. The string returned must be - * freed by the caller with PR_smprintf_free. - * - * Note: this file does lots of consistancy checks on the DBT. The - * routines that call this depend on these checks, so they don't worry - * about them (success of this routine implies a good blobdata record). - */ -static char * -dbs_getBlobFilePath(char *blobdir,DBT *blobData) -{ - const char *name; - - if (blobdir == NULL) { - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - return NULL; - } - if (!dbs_IsBlob(blobData)) { - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - return NULL; - } - name = dbs_getBlobFileName(blobData); - if (!name || *name == 0) { - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - return NULL; - } - return PR_smprintf("%s" PATH_SEPARATOR "%s", blobdir, name); -} - -/* - * Delete a blob file pointed to by the blob record. - */ -static void -dbs_removeBlob(DBS *dbsp, DBT *blobData) -{ - char *file; - - file = dbs_getBlobFilePath(dbsp->blobdir, blobData); - if (!file) { - return; - } - PR_Delete(file); - PR_smprintf_free(file); -} - -/* - * Directory modes are slightly different, the 'x' bit needs to be on to - * access them. Copy all the read bits to 'x' bits - */ -static int -dbs_DirMode(int mode) -{ - int x_bits = (mode >> 2) & 0111; - return mode | x_bits; -} - -/* - * write a data blob to it's file. blobdData is the blob record that will be - * stored in the database. data is the actual data to go out on disk. - */ -static int -dbs_writeBlob(DBS *dbsp, int mode, DBT *blobData, const DBT *data) -{ - char *file = NULL; - PRFileDesc *filed; - PRStatus status; - int len; - int error = 0; - - file = dbs_getBlobFilePath(dbsp->blobdir, blobData); - if (!file) { - goto loser; - } - if (PR_Access(dbsp->blobdir, PR_ACCESS_EXISTS) != PR_SUCCESS) { - status = PR_MkDir(dbsp->blobdir,dbs_DirMode(mode)); - if (status != PR_SUCCESS) { - goto loser; - } - } - filed = PR_OpenFile(file,PR_CREATE_FILE|PR_TRUNCATE|PR_WRONLY, mode); - if (filed == NULL) { - error = PR_GetError(); - goto loser; - } - len = PR_Write(filed,data->data,data->size); - error = PR_GetError(); - PR_Close(filed); - if (len < (int)data->size) { - goto loser; - } - PR_smprintf_free(file); - return 0; - -loser: - if (file) { - PR_Delete(file); - PR_smprintf_free(file); - } - /* don't let close or delete reset the error */ - PR_SetError(error,0); - return -1; -} - - -/* - * we need to keep a address map in memory between calls to DBM. - * remember what we have mapped can close it when we get another dbm - * call. - * - * NOTE: Not all platforms support mapped files. This code is designed to - * detect this at runtime. If map files aren't supported the OS will indicate - * this by failing the PR_Memmap call. In this case we emulate mapped files - * by just reading in the file into regular memory. We signal this state by - * making dbs_mapfile NULL and dbs_addr non-NULL. - */ - -static void -dbs_freemap(DBS *dbsp) -{ - if (dbsp->dbs_mapfile) { - PR_MemUnmap(dbsp->dbs_addr,dbsp->dbs_len); - PR_CloseFileMap(dbsp->dbs_mapfile); - dbsp->dbs_mapfile = NULL; - dbsp->dbs_addr = NULL; - dbsp->dbs_len = 0; - } else if (dbsp->dbs_addr) { - PORT_Free(dbsp->dbs_addr); - dbsp->dbs_addr = NULL; - dbsp->dbs_len = 0; - } - return; -} - -static void -dbs_setmap(DBS *dbsp, PRFileMap *mapfile, unsigned char *addr, PRUint32 len) -{ - dbsp->dbs_mapfile = mapfile; - dbsp->dbs_addr = addr; - dbsp->dbs_len = len; -} - -/* - * platforms that cannot map the file need to read it into a temp buffer. - */ -static unsigned char * -dbs_EmulateMap(PRFileDesc *filed, int len) -{ - unsigned char *addr; - PRInt32 dataRead; - - addr = PORT_Alloc(len); - if (addr == NULL) { - return NULL; - } - - dataRead = PR_Read(filed,addr,len); - if (dataRead != len) { - PORT_Free(addr); - if (dataRead > 0) { - /* PR_Read didn't set an error, we need to */ - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - } - return NULL; - } - - return addr; -} - - -/* - * pull a database record off the disk - * data points to the blob record on input and the real record (if we could - * read it) on output. if there is an error data is not modified. - */ -static int -dbs_readBlob(DBS *dbsp, DBT *data) -{ - char *file = NULL; - PRFileDesc *filed = NULL; - PRFileMap *mapfile = NULL; - unsigned char *addr = NULL; - int error; - int len = -1; - - file = dbs_getBlobFilePath(dbsp->blobdir, data); - if (!file) { - goto loser; - } - filed = PR_OpenFile(file,PR_RDONLY,0); - PR_smprintf_free(file); file = NULL; - if (filed == NULL) { - goto loser; - } - - len = dbs_getBlobSize(data); - mapfile = PR_CreateFileMap(filed, len, PR_PROT_READONLY); - if (mapfile == NULL) { - /* USE PR_GetError instead of PORT_GetError here - * because we are getting the error from PR_xxx - * function */ - if (PR_GetError() != PR_NOT_IMPLEMENTED_ERROR) { - goto loser; - } - addr = dbs_EmulateMap(filed, len); - } else { - addr = PR_MemMap(mapfile, 0, len); - } - if (addr == NULL) { - goto loser; - } - PR_Close(filed); - dbs_setmap(dbsp,mapfile,addr,len); - - data->data = addr; - data->size = len; - return 0; - -loser: - /* preserve the error code */ - error = PR_GetError(); - if (addr) { - if (mapfile) { - PORT_Assert(len != -1); - PR_MemUnmap(addr,len); - } else { - PORT_Free(addr); - } - } - if (mapfile) { - PR_CloseFileMap(mapfile); - } - if (filed) { - PR_Close(filed); - } - PR_SetError(error,0); - return -1; -} - -/* - * actual DBM shims - */ -static int -dbs_get(const DB *dbs, const DBT *key, DBT *data, unsigned int flags) -{ - int ret; - DBS *dbsp = (DBS *)dbs; - DB *db = (DB *)dbs->internal; - - - dbs_freemap(dbsp); - - ret = (* db->get)(db, key, data, flags); - if ((ret == 0) && dbs_IsBlob(data)) { - ret = dbs_readBlob(dbsp,data); - } - - return(ret); -} - -static int -dbs_put(const DB *dbs, DBT *key, const DBT *data, unsigned int flags) -{ - DBT blob; - int ret = 0; - DBS *dbsp = (DBS *)dbs; - DB *db = (DB *)dbs->internal; - - dbs_freemap(dbsp); - - /* If the db is readonly, just pass the data down to rdb and let it fail */ - if (!dbsp->readOnly) { - DBT oldData; - int ret1; - - /* make sure the current record is deleted if it's a blob */ - ret1 = (*db->get)(db,key,&oldData,0); - if ((ret1 == 0) && flags == R_NOOVERWRITE) { - /* let DBM return the error to maintain consistancy */ - return (* db->put)(db, key, data, flags); - } - if ((ret1 == 0) && dbs_IsBlob(&oldData)) { - dbs_removeBlob(dbsp, &oldData); - } - - if (data->size > DBS_MAX_ENTRY_SIZE) { - dbs_mkBlob(dbsp,key,data,&blob); - ret = dbs_writeBlob(dbsp, dbsp->mode, &blob, data); - data = &blob; - } - } - - if (ret == 0) { - ret = (* db->put)(db, key, data, flags); - } - return(ret); -} - -static int -dbs_sync(const DB *dbs, unsigned int flags) -{ - DB *db = (DB *)dbs->internal; - DBS *dbsp = (DBS *)dbs; - - dbs_freemap(dbsp); - - return (* db->sync)(db, flags); -} - -static int -dbs_del(const DB *dbs, const DBT *key, unsigned int flags) -{ - int ret; - DBS *dbsp = (DBS *)dbs; - DB *db = (DB *)dbs->internal; - - dbs_freemap(dbsp); - - if (!dbsp->readOnly) { - DBT oldData; - ret = (*db->get)(db,key,&oldData,0); - if ((ret == 0) && dbs_IsBlob(&oldData)) { - dbs_removeBlob(dbsp,&oldData); - } - } - - return (* db->del)(db, key, flags); -} - -static int -dbs_seq(const DB *dbs, DBT *key, DBT *data, unsigned int flags) -{ - int ret; - DBS *dbsp = (DBS *)dbs; - DB *db = (DB *)dbs->internal; - - dbs_freemap(dbsp); - - ret = (* db->seq)(db, key, data, flags); - if ((ret == 0) && dbs_IsBlob(data)) { - /* don't return a blob read as an error so traversals keep going */ - (void) dbs_readBlob(dbsp,data); - } - - return(ret); -} - -static int -dbs_close(DB *dbs) -{ - DBS *dbsp = (DBS *)dbs; - DB *db = (DB *)dbs->internal; - int ret; - - dbs_freemap(dbsp); - ret = (* db->close)(db); - PORT_Free(dbsp->blobdir); - PORT_Free(dbsp); - return ret; -} - -static int -dbs_fd(const DB *dbs) -{ - DB *db = (DB *)dbs->internal; - - return (* db->fd)(db); -} - -/* - * the naming convention we use is - * change the .xxx into .dir. (for nss it's always .db); - * if no .extension exists or is equal to .dir, add a .dir - * the returned data must be freed. - */ -#define DIRSUFFIX ".dir" -static char * -dbs_mkBlobDirName(const char *dbname) -{ - int dbname_len = PORT_Strlen(dbname); - int dbname_end = dbname_len; - const char *cp; - char *blobDir = NULL; - - /* scan back from the end looking for either a directory separator, a '.', - * or the end of the string. NOTE: Windows should check for both separators - * here. For now this is safe because we know NSS always uses a '.' - */ - for (cp = &dbname[dbname_len]; - (cp > dbname) && (*cp != '.') && (*cp != *PATH_SEPARATOR) ; - cp--) - /* Empty */ ; - if (*cp == '.') { - dbname_end = cp - dbname; - if (PORT_Strcmp(cp,DIRSUFFIX) == 0) { - dbname_end = dbname_len; - } - } - blobDir = PORT_ZAlloc(dbname_end+sizeof(DIRSUFFIX)); - if (blobDir == NULL) { - return NULL; - } - PORT_Memcpy(blobDir,dbname,dbname_end); - PORT_Memcpy(&blobDir[dbname_end],DIRSUFFIX,sizeof(DIRSUFFIX)); - return blobDir; -} - -#define DBM_DEFAULT 0 -static const HASHINFO dbs_hashInfo = { - DBS_BLOCK_SIZE, /* bucket size, must be greater than = to - * or maximum entry size (+ header) - * we allow before blobing */ - DBM_DEFAULT, /* Fill Factor */ - DBM_DEFAULT, /* number of elements */ - DBS_CACHE_SIZE, /* cache size */ - DBM_DEFAULT, /* hash function */ - DBM_DEFAULT, /* byte order */ -}; - -/* - * the open function. NOTE: this is the only exposed function in this file. - * everything else is called through the function table pointer. - */ -DB * -dbsopen(const char *dbname, int flags, int mode, DBTYPE type, - const void *userData) -{ - DB *db = NULL,*dbs = NULL; - DBS *dbsp = NULL; - - /* NOTE: we are overriding userData with dbs_hashInfo. since all known - * callers pass 0, this is ok, otherwise we should merge the two */ - - dbsp = (DBS *)PORT_ZAlloc(sizeof(DBS)); - if (!dbsp) { - return NULL; - } - dbs = &dbsp->db; - - dbsp->blobdir=dbs_mkBlobDirName(dbname); - if (dbsp->blobdir == NULL) { - goto loser; - } - dbsp->mode = mode; - dbsp->readOnly = (PRBool)(flags == NO_RDONLY); - dbsp->dbs_mapfile = NULL; - dbsp->dbs_addr = NULL; - dbsp->dbs_len = 0; - - /* the real dbm call */ - db = dbopen(dbname, flags, mode, type, &dbs_hashInfo); - if (db == NULL) { - goto loser; - } - dbs->internal = (void *) db; - dbs->type = type; - dbs->close = dbs_close; - dbs->get = dbs_get; - dbs->del = dbs_del; - dbs->put = dbs_put; - dbs->seq = dbs_seq; - dbs->sync = dbs_sync; - dbs->fd = dbs_fd; - - return dbs; -loser: - if (db) { - (*db->close)(db); - } - if (dbsp && dbsp->blobdir) { - PORT_Free(dbsp->blobdir); - } - if (dbsp) { - PORT_Free(dbsp); - } - return NULL; -} diff --git a/security/nss/lib/softoken/ecdecode.c b/security/nss/lib/softoken/ecdecode.c deleted file mode 100644 index 1d952a789..000000000 --- a/security/nss/lib/softoken/ecdecode.c +++ /dev/null @@ -1,685 +0,0 @@ -/* - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * 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 Elliptic Curve Cryptography library. - * - * The Initial Developer of the Original Code is Sun Microsystems, Inc. - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com> and - * Douglas Stebila <douglas@stebila.ca>, Sun Microsystems Laboratories - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - */ - -#ifdef NSS_ENABLE_ECC - -#include "blapi.h" -#include "secoid.h" -#include "secitem.h" -#include "secerr.h" -#include "ec.h" -#include "ecl-curve.h" - -#define CHECK_OK(func) if (func == NULL) goto cleanup -#define CHECK_SEC_OK(func) if (SECSuccess != (rv = func)) goto cleanup - -/* Initializes a SECItem from a hexadecimal string */ -static SECItem * -hexString2SECItem(PRArenaPool *arena, SECItem *item, const char *str) -{ - int i = 0; - int byteval = 0; - int tmp = PORT_Strlen(str); - - if ((tmp % 2) != 0) return NULL; - - item->data = (unsigned char *) PORT_ArenaAlloc(arena, tmp/2); - if (item->data == NULL) return NULL; - item->len = tmp/2; - - while (str[i]) { - if ((str[i] >= '0') && (str[i] <= '9')) - tmp = str[i] - '0'; - else if ((str[i] >= 'a') && (str[i] <= 'f')) - tmp = str[i] - 'a' + 10; - else if ((str[i] >= 'A') && (str[i] <= 'F')) - tmp = str[i] - 'A' + 10; - else - return NULL; - - byteval = byteval * 16 + tmp; - if ((i % 2) != 0) { - item->data[i/2] = byteval; - byteval = 0; - } - i++; - } - - return item; -} - -/* Copy all of the fields from srcParams into dstParams - */ -SECStatus -EC_CopyParams(PRArenaPool *arena, ECParams *dstParams, - const ECParams *srcParams) -{ - SECStatus rv = SECFailure; - - dstParams->arena = arena; - dstParams->type = srcParams->type; - dstParams->fieldID.size = srcParams->fieldID.size; - dstParams->fieldID.type = srcParams->fieldID.type; - if (srcParams->fieldID.type == ec_field_GFp) { - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->fieldID.u.prime, - &srcParams->fieldID.u.prime)); - } else { - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->fieldID.u.poly, - &srcParams->fieldID.u.poly)); - } - dstParams->fieldID.k1 = srcParams->fieldID.k1; - dstParams->fieldID.k2 = srcParams->fieldID.k2; - dstParams->fieldID.k3 = srcParams->fieldID.k3; - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->curve.a, - &srcParams->curve.a)); - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->curve.b, - &srcParams->curve.b)); - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->curve.seed, - &srcParams->curve.seed)); - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->base, - &srcParams->base)); - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->order, - &srcParams->order)); - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->DEREncoding, - &srcParams->DEREncoding)); - dstParams->name = srcParams->name; - CHECK_SEC_OK(SECITEM_CopyItem(arena, &dstParams->curveOID, - &srcParams->curveOID)); - dstParams->cofactor = srcParams->cofactor; - - return SECSuccess; - -cleanup: - return SECFailure; -} - -SECStatus -EC_FillParams(PRArenaPool *arena, const SECItem *encodedParams, - ECParams *params) -{ - SECOidTag tag; - SECItem oid = { siBuffer, NULL, 0}; - const ECCurveParams *curveParams; - char genenc[2 + 2 * 2 * MAX_ECKEY_LEN]; - -#if EC_DEBUG - int i; - - printf("Encoded params in EC_DecodeParams: "); - for (i = 0; i < encodedParams->len; i++) { - printf("%02x:", encodedParams->data[i]); - } - printf("\n"); -#endif - - if ((encodedParams->len != ANSI_X962_CURVE_OID_TOTAL_LEN) && - (encodedParams->len != SECG_CURVE_OID_TOTAL_LEN)) { - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - return SECFailure; - }; - - oid.len = encodedParams->len - 2; - oid.data = encodedParams->data + 2; - if ((encodedParams->data[0] != SEC_ASN1_OBJECT_ID) || - ((tag = SECOID_FindOIDTag(&oid)) == SEC_OID_UNKNOWN)) { - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - return SECFailure; - } - - params->arena = arena; - params->cofactor = 0; - params->type = ec_params_named; - params->name = ECCurve_noName; - - /* For named curves, fill out curveOID */ - params->curveOID.len = oid.len; - params->curveOID.data = (unsigned char *) PORT_ArenaAlloc(arena, oid.len); - if (params->curveOID.data == NULL) goto cleanup; - memcpy(params->curveOID.data, oid.data, oid.len); - -#if EC_DEBUG - printf("Curve: %s\n", SECOID_FindOIDTagDescription(tag)); -#endif - - switch (tag) { - -#define GF2M_POPULATE \ - if ((params->name < ECCurve_noName) || \ - (params->name > ECCurve_pastLastCurve)) goto cleanup; \ - CHECK_OK(curveParams); \ - params->fieldID.size = curveParams->size; \ - params->fieldID.type = ec_field_GF2m; \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->fieldID.u.poly, \ - curveParams->irr)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->curve.a, \ - curveParams->curvea)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->curve.b, \ - curveParams->curveb)); \ - genenc[0] = '0'; \ - genenc[1] = '4'; \ - genenc[2] = '\0'; \ - CHECK_OK(strcat(genenc, curveParams->genx)); \ - CHECK_OK(strcat(genenc, curveParams->geny)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->base, \ - genenc)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->order, \ - curveParams->order)); \ - params->cofactor = curveParams->cofactor; - - case SEC_OID_ANSIX962_EC_C2PNB163V1: - /* Populate params for c2pnb163v1 */ - params->name = ECCurve_X9_62_CHAR2_PNB163V1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2PNB163V2: - /* Populate params for c2pnb163v2 */ - params->name = ECCurve_X9_62_CHAR2_PNB163V2; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2PNB163V3: - /* Populate params for c2pnb163v3 */ - params->name = ECCurve_X9_62_CHAR2_PNB163V3; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2PNB176V1: - /* Populate params for c2pnb176v1 */ - params->name = ECCurve_X9_62_CHAR2_PNB176V1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB191V1: - /* Populate params for c2tnb191v1 */ - params->name = ECCurve_X9_62_CHAR2_TNB191V1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB191V2: - /* Populate params for c2tnb191v2 */ - params->name = ECCurve_X9_62_CHAR2_TNB191V2; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB191V3: - /* Populate params for c2tnb191v3 */ - params->name = ECCurve_X9_62_CHAR2_TNB191V3; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2PNB208W1: - /* Populate params for c2pnb208w1 */ - params->name = ECCurve_X9_62_CHAR2_PNB208W1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB239V1: - /* Populate params for c2tnb239v1 */ - params->name = ECCurve_X9_62_CHAR2_TNB239V1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB239V2: - /* Populate params for c2tnb239v2 */ - params->name = ECCurve_X9_62_CHAR2_TNB239V2; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB239V3: - /* Populate params for c2tnb239v3 */ - params->name = ECCurve_X9_62_CHAR2_TNB239V3; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2PNB272W1: - /* Populate params for c2pnb272w1 */ - params->name = ECCurve_X9_62_CHAR2_PNB272W1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2PNB304W1: - /* Populate params for c2pnb304w1 */ - params->name = ECCurve_X9_62_CHAR2_PNB304W1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB359V1: - /* Populate params for c2tnb359v1 */ - params->name = ECCurve_X9_62_CHAR2_TNB359V1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2PNB368W1: - /* Populate params for c2pnb368w1 */ - params->name = ECCurve_X9_62_CHAR2_PNB368W1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_ANSIX962_EC_C2TNB431R1: - /* Populate params for c2tnb431r1 */ - params->name = ECCurve_X9_62_CHAR2_TNB431R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT113R1: - /* Populate params for sect113r1 */ - params->name = ECCurve_SECG_CHAR2_113R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT113R2: - /* Populate params for sect113r2 */ - params->name = ECCurve_SECG_CHAR2_113R2; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT131R1: - /* Populate params for sect131r1 */ - params->name = ECCurve_SECG_CHAR2_131R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT131R2: - /* Populate params for sect131r2 */ - params->name = ECCurve_SECG_CHAR2_131R2; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT163K1: - /* Populate params for sect163k1 - * (the NIST K-163 curve) - */ - params->name = ECCurve_SECG_CHAR2_163K1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT163R1: - /* Populate params for sect163r1 */ - params->name = ECCurve_SECG_CHAR2_163R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT163R2: - /* Populate params for sect163r2 - * (the NIST B-163 curve) - */ - params->name = ECCurve_SECG_CHAR2_163R2; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT193R1: - /* Populate params for sect193r1 */ - params->name = ECCurve_SECG_CHAR2_193R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT193R2: - /* Populate params for sect193r2 */ - params->name = ECCurve_SECG_CHAR2_193R2; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT233K1: - /* Populate params for sect233k1 - * (the NIST K-233 curve) - */ - params->name = ECCurve_SECG_CHAR2_233K1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT233R1: - /* Populate params for sect233r1 - * (the NIST B-233 curve) - */ - params->name = ECCurve_SECG_CHAR2_233R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT239K1: - /* Populate params for sect239k1 */ - params->name = ECCurve_SECG_CHAR2_239K1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT283K1: - /* Populate params for sect283k1 - * (the NIST K-283 curve) - */ - params->name = ECCurve_SECG_CHAR2_283K1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT283R1: - /* Populate params for sect283r1 - * (the NIST B-283 curve) - */ - params->name = ECCurve_SECG_CHAR2_283R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT409K1: - /* Populate params for sect409k1 - * (the NIST K-409 curve) - */ - params->name = ECCurve_SECG_CHAR2_409K1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT409R1: - /* Populate params for sect409r1 - * (the NIST B-409 curve) - */ - params->name = ECCurve_SECG_CHAR2_409R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT571K1: - /* Populate params for sect571k1 - * (the NIST K-571 curve) - */ - params->name = ECCurve_SECG_CHAR2_571K1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - - case SEC_OID_SECG_EC_SECT571R1: - /* Populate params for sect571r1 - * (the NIST B-571 curve) - */ - params->name = ECCurve_SECG_CHAR2_571R1; - curveParams = ecCurve_map[params->name]; - GF2M_POPULATE - break; - -#define GFP_POPULATE \ - if ((params->name < ECCurve_noName) || \ - (params->name > ECCurve_pastLastCurve)) goto cleanup; \ - CHECK_OK(curveParams); \ - params->fieldID.size = curveParams->size; \ - params->fieldID.type = ec_field_GFp; \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->fieldID.u.prime, \ - curveParams->irr)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->curve.a, \ - curveParams->curvea)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->curve.b, \ - curveParams->curveb)); \ - genenc[0] = '0'; \ - genenc[1] = '4'; \ - genenc[2] = '\0'; \ - CHECK_OK(strcat(genenc, curveParams->genx)); \ - CHECK_OK(strcat(genenc, curveParams->geny)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->base, \ - genenc)); \ - CHECK_OK(hexString2SECItem(params->arena, ¶ms->order, \ - curveParams->order)); \ - params->cofactor = curveParams->cofactor; - - case SEC_OID_ANSIX962_EC_PRIME192V1: - /* Populate params for prime192v1 aka secp192r1 - * (the NIST P-192 curve) - */ - params->name = ECCurve_X9_62_PRIME_192V1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_ANSIX962_EC_PRIME192V2: - /* Populate params for prime192v2 */ - params->name = ECCurve_X9_62_PRIME_192V2; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_ANSIX962_EC_PRIME192V3: - /* Populate params for prime192v3 */ - params->name = ECCurve_X9_62_PRIME_192V3; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_ANSIX962_EC_PRIME239V1: - /* Populate params for prime239v1 */ - params->name = ECCurve_X9_62_PRIME_239V1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_ANSIX962_EC_PRIME239V2: - /* Populate params for prime239v2 */ - params->name = ECCurve_X9_62_PRIME_239V2; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_ANSIX962_EC_PRIME239V3: - /* Populate params for prime239v3 */ - params->name = ECCurve_X9_62_PRIME_239V3; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_ANSIX962_EC_PRIME256V1: - /* Populate params for prime256v1 aka secp256r1 - * (the NIST P-256 curve) - */ - params->name = ECCurve_X9_62_PRIME_256V1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP112R1: - /* Populate params for secp112r1 */ - params->name = ECCurve_SECG_PRIME_112R1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP112R2: - /* Populate params for secp112r2 */ - params->name = ECCurve_SECG_PRIME_112R2; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP128R1: - /* Populate params for secp128r1 */ - params->name = ECCurve_SECG_PRIME_128R1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP128R2: - /* Populate params for secp128r2 */ - params->name = ECCurve_SECG_PRIME_128R2; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP160K1: - /* Populate params for secp160k1 */ - params->name = ECCurve_SECG_PRIME_160K1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP160R1: - /* Populate params for secp160r1 */ - params->name = ECCurve_SECG_PRIME_160R1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP160R2: - /* Populate params for secp160r1 */ - params->name = ECCurve_SECG_PRIME_160R2; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP192K1: - /* Populate params for secp192k1 */ - params->name = ECCurve_SECG_PRIME_192K1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP224K1: - /* Populate params for secp224k1 */ - params->name = ECCurve_SECG_PRIME_224K1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP224R1: - /* Populate params for secp224r1 - * (the NIST P-224 curve) - */ - params->name = ECCurve_SECG_PRIME_224R1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP256K1: - /* Populate params for secp256k1 */ - params->name = ECCurve_SECG_PRIME_256K1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP384R1: - /* Populate params for secp384r1 - * (the NIST P-384 curve) - */ - params->name = ECCurve_SECG_PRIME_384R1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - case SEC_OID_SECG_EC_SECP521R1: - /* Populate params for secp521r1 - * (the NIST P-521 curve) - */ - params->name = ECCurve_SECG_PRIME_521R1; - curveParams = ecCurve_map[params->name]; - GFP_POPULATE - break; - - default: - break; - }; - -cleanup: - if (!params->cofactor) { - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); -#if EC_DEBUG - printf("Unrecognized curve, returning NULL params\n"); -#endif - return SECFailure; - } - - return SECSuccess; -} - -SECStatus -EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams) -{ - PRArenaPool *arena; - ECParams *params; - SECStatus rv = SECFailure; - - /* Initialize an arena for the ECParams structure */ - if (!(arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE))) - return SECFailure; - - params = (ECParams *)PORT_ArenaZAlloc(arena, sizeof(ECParams)); - if (!params) { - PORT_FreeArena(arena, PR_TRUE); - return SECFailure; - } - - /* Copy the encoded params */ - SECITEM_AllocItem(arena, &(params->DEREncoding), - encodedParams->len); - memcpy(params->DEREncoding.data, encodedParams->data, encodedParams->len); - - /* Fill out the rest of the ECParams structure based on - * the encoded params - */ - rv = EC_FillParams(arena, encodedParams, params); - if (rv == SECFailure) { - PORT_FreeArena(arena, PR_TRUE); - return SECFailure; - } else { - *ecparams = params;; - return SECSuccess; - } -} - -#endif /* NSS_ENABLE_ECC */ diff --git a/security/nss/lib/softoken/fipstest.c b/security/nss/lib/softoken/fipstest.c deleted file mode 100644 index 8fe4f567e..000000000 --- a/security/nss/lib/softoken/fipstest.c +++ /dev/null @@ -1,1093 +0,0 @@ -/* - * PKCS #11 FIPS Power-Up Self Test. - * - * 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. - * - * $Id$ - */ - -#include "softoken.h" /* Required for RC2-ECB, RC2-CBC, RC4, DES-ECB, */ - /* DES-CBC, DES3-ECB, DES3-CBC, RSA */ - /* and DSA. */ -#include "seccomon.h" /* Required for RSA and DSA. */ -#include "lowkeyi.h" /* Required for RSA and DSA. */ -#include "pkcs11.h" /* Required for PKCS #11. */ -#include "secerr.h" - -/* FIPS preprocessor directives for RC2-ECB and RC2-CBC. */ -#define FIPS_RC2_KEY_LENGTH 5 /* 40-bits */ -#define FIPS_RC2_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_RC2_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for RC4. */ -#define FIPS_RC4_KEY_LENGTH 5 /* 40-bits */ -#define FIPS_RC4_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_RC4_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for DES-ECB and DES-CBC. */ -#define FIPS_DES_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_DES_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for DES3-CBC and DES3-ECB. */ -#define FIPS_DES3_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_DES3_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for MD2. */ -#define FIPS_MD2_HASH_MESSAGE_LENGTH 64 /* 512-bits */ - - -/* FIPS preprocessor directives for MD5. */ -#define FIPS_MD5_HASH_MESSAGE_LENGTH 64 /* 512-bits */ - - -/* FIPS preprocessor directives for SHA-1. */ -#define FIPS_SHA1_HASH_MESSAGE_LENGTH 64 /* 512-bits */ - - -/* FIPS preprocessor directives for RSA. */ -#define FIPS_RSA_TYPE siBuffer -#define FIPS_RSA_PUBLIC_EXPONENT_LENGTH 1 /* 8-bits */ -#define FIPS_RSA_PRIVATE_VERSION_LENGTH 1 /* 8-bits */ -#define FIPS_RSA_MESSAGE_LENGTH 16 /* 128-bits */ -#define FIPS_RSA_COEFFICIENT_LENGTH 32 /* 256-bits */ -#define FIPS_RSA_PRIME0_LENGTH 33 /* 264-bits */ -#define FIPS_RSA_PRIME1_LENGTH 33 /* 264-bits */ -#define FIPS_RSA_EXPONENT0_LENGTH 33 /* 264-bits */ -#define FIPS_RSA_EXPONENT1_LENGTH 33 /* 264-bits */ -#define FIPS_RSA_PRIVATE_EXPONENT_LENGTH 64 /* 512-bits */ -#define FIPS_RSA_ENCRYPT_LENGTH 64 /* 512-bits */ -#define FIPS_RSA_DECRYPT_LENGTH 64 /* 512-bits */ -#define FIPS_RSA_CRYPTO_LENGTH 64 /* 512-bits */ -#define FIPS_RSA_SIGNATURE_LENGTH 64 /* 512-bits */ -#define FIPS_RSA_MODULUS_LENGTH 65 /* 520-bits */ - - -/* FIPS preprocessor directives for DSA. */ -#define FIPS_DSA_TYPE siBuffer -#define FIPS_DSA_DIGEST_LENGTH 20 /* 160-bits */ -#define FIPS_DSA_SUBPRIME_LENGTH 20 /* 160-bits */ -#define FIPS_DSA_SIGNATURE_LENGTH 40 /* 320-bits */ -#define FIPS_DSA_PRIME_LENGTH 64 /* 512-bits */ -#define FIPS_DSA_BASE_LENGTH 64 /* 512-bits */ - -static CK_RV -pk11_fips_RC2_PowerUpSelfTest( void ) -{ - /* RC2 Known Key (40-bits). */ - static const PRUint8 rc2_known_key[] = { "RSARC" }; - - /* RC2-CBC Known Initialization Vector (64-bits). */ - static const PRUint8 rc2_cbc_known_initialization_vector[] = {"Security"}; - - /* RC2 Known Plaintext (64-bits). */ - static const PRUint8 rc2_ecb_known_plaintext[] = {"Netscape"}; - static const PRUint8 rc2_cbc_known_plaintext[] = {"Netscape"}; - - /* RC2 Known Ciphertext (64-bits). */ - static const PRUint8 rc2_ecb_known_ciphertext[] = { - 0x1a,0x71,0x33,0x54,0x8d,0x5c,0xd2,0x30}; - static const PRUint8 rc2_cbc_known_ciphertext[] = { - 0xff,0x41,0xdb,0x94,0x8a,0x4c,0x33,0xb3}; - - /* RC2 variables. */ - PRUint8 rc2_computed_ciphertext[FIPS_RC2_ENCRYPT_LENGTH]; - PRUint8 rc2_computed_plaintext[FIPS_RC2_DECRYPT_LENGTH]; - RC2Context * rc2_context; - unsigned int rc2_bytes_encrypted; - unsigned int rc2_bytes_decrypted; - SECStatus rc2_status; - - - /******************************************************/ - /* RC2-ECB Single-Round Known Answer Encryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - NULL, NSS_RC2, - FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Encrypt( rc2_context, rc2_computed_ciphertext, - &rc2_bytes_encrypted, FIPS_RC2_ENCRYPT_LENGTH, - rc2_ecb_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_encrypted != FIPS_RC2_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_ciphertext, rc2_ecb_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* RC2-ECB Single-Round Known Answer Decryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - NULL, NSS_RC2, - FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Decrypt( rc2_context, rc2_computed_plaintext, - &rc2_bytes_decrypted, FIPS_RC2_DECRYPT_LENGTH, - rc2_ecb_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_decrypted != FIPS_RC2_DECRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_plaintext, rc2_ecb_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* RC2-CBC Single-Round Known Answer Encryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - rc2_cbc_known_initialization_vector, - NSS_RC2_CBC, FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Encrypt( rc2_context, rc2_computed_ciphertext, - &rc2_bytes_encrypted, FIPS_RC2_ENCRYPT_LENGTH, - rc2_cbc_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_encrypted != FIPS_RC2_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_ciphertext, rc2_cbc_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* RC2-CBC Single-Round Known Answer Decryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - rc2_cbc_known_initialization_vector, - NSS_RC2_CBC, FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Decrypt( rc2_context, rc2_computed_plaintext, - &rc2_bytes_decrypted, FIPS_RC2_DECRYPT_LENGTH, - rc2_cbc_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_decrypted != FIPS_RC2_DECRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_plaintext, rc2_ecb_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -pk11_fips_RC4_PowerUpSelfTest( void ) -{ - /* RC4 Known Key (40-bits). */ - static const PRUint8 rc4_known_key[] = { "RSARC" }; - - /* RC4 Known Plaintext (64-bits). */ - static const PRUint8 rc4_known_plaintext[] = { "Netscape" }; - - /* RC4 Known Ciphertext (64-bits). */ - static const PRUint8 rc4_known_ciphertext[] = { - 0x29,0x33,0xc7,0x9a,0x9d,0x6c,0x09,0xdd}; - - /* RC4 variables. */ - PRUint8 rc4_computed_ciphertext[FIPS_RC4_ENCRYPT_LENGTH]; - PRUint8 rc4_computed_plaintext[FIPS_RC4_DECRYPT_LENGTH]; - RC4Context * rc4_context; - unsigned int rc4_bytes_encrypted; - unsigned int rc4_bytes_decrypted; - SECStatus rc4_status; - - - /**************************************************/ - /* RC4 Single-Round Known Answer Encryption Test: */ - /**************************************************/ - - rc4_context = RC4_CreateContext( rc4_known_key, FIPS_RC4_KEY_LENGTH ); - - if( rc4_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc4_status = RC4_Encrypt( rc4_context, rc4_computed_ciphertext, - &rc4_bytes_encrypted, FIPS_RC4_ENCRYPT_LENGTH, - rc4_known_plaintext, FIPS_RC4_DECRYPT_LENGTH ); - - RC4_DestroyContext( rc4_context, PR_TRUE ); - - if( ( rc4_status != SECSuccess ) || - ( rc4_bytes_encrypted != FIPS_RC4_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( rc4_computed_ciphertext, rc4_known_ciphertext, - FIPS_RC4_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /**************************************************/ - /* RC4 Single-Round Known Answer Decryption Test: */ - /**************************************************/ - - rc4_context = RC4_CreateContext( rc4_known_key, FIPS_RC4_KEY_LENGTH ); - - if( rc4_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc4_status = RC4_Decrypt( rc4_context, rc4_computed_plaintext, - &rc4_bytes_decrypted, FIPS_RC4_DECRYPT_LENGTH, - rc4_known_ciphertext, FIPS_RC4_ENCRYPT_LENGTH ); - - RC4_DestroyContext( rc4_context, PR_TRUE ); - - if( ( rc4_status != SECSuccess ) || - ( rc4_bytes_decrypted != FIPS_RC4_DECRYPT_LENGTH ) || - ( PORT_Memcmp( rc4_computed_plaintext, rc4_known_plaintext, - FIPS_RC4_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -pk11_fips_DES_PowerUpSelfTest( void ) -{ - /* DES Known Key (56-bits). */ - static const PRUint8 des_known_key[] = { "ANSI DES" }; - - /* DES-CBC Known Initialization Vector (64-bits). */ - static const PRUint8 des_cbc_known_initialization_vector[] = { "Security" }; - - /* DES Known Plaintext (64-bits). */ - static const PRUint8 des_ecb_known_plaintext[] = { "Netscape" }; - static const PRUint8 des_cbc_known_plaintext[] = { "Netscape" }; - - /* DES Known Ciphertext (64-bits). */ - static const PRUint8 des_ecb_known_ciphertext[] = { - 0x26,0x14,0xe9,0xc3,0x28,0x80,0x50,0xb0}; - static const PRUint8 des_cbc_known_ciphertext[] = { - 0x5e,0x95,0x94,0x5d,0x76,0xa2,0xd3,0x7d}; - - /* DES variables. */ - PRUint8 des_computed_ciphertext[FIPS_DES_ENCRYPT_LENGTH]; - PRUint8 des_computed_plaintext[FIPS_DES_DECRYPT_LENGTH]; - DESContext * des_context; - unsigned int des_bytes_encrypted; - unsigned int des_bytes_decrypted; - SECStatus des_status; - - - /******************************************************/ - /* DES-ECB Single-Round Known Answer Encryption Test: */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, NULL, NSS_DES, PR_TRUE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Encrypt( des_context, des_computed_ciphertext, - &des_bytes_encrypted, FIPS_DES_ENCRYPT_LENGTH, - des_ecb_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_encrypted != FIPS_DES_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_ciphertext, des_ecb_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* DES-ECB Single-Round Known Answer Decryption Test: */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, NULL, NSS_DES, PR_FALSE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Decrypt( des_context, des_computed_plaintext, - &des_bytes_decrypted, FIPS_DES_DECRYPT_LENGTH, - des_ecb_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_decrypted != FIPS_DES_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_plaintext, des_ecb_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* DES-CBC Single-Round Known Answer Encryption Test. */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, - des_cbc_known_initialization_vector, - NSS_DES_CBC, PR_TRUE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Encrypt( des_context, des_computed_ciphertext, - &des_bytes_encrypted, FIPS_DES_ENCRYPT_LENGTH, - des_cbc_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_encrypted != FIPS_DES_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_ciphertext, des_cbc_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* DES-CBC Single-Round Known Answer Decryption Test. */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, - des_cbc_known_initialization_vector, - NSS_DES_CBC, PR_FALSE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Decrypt( des_context, des_computed_plaintext, - &des_bytes_decrypted, FIPS_DES_DECRYPT_LENGTH, - des_cbc_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_decrypted != FIPS_DES_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_plaintext, des_cbc_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -pk11_fips_DES3_PowerUpSelfTest( void ) -{ - /* DES3 Known Key (56-bits). */ - static const PRUint8 des3_known_key[] = { "ANSI Triple-DES Key Data" }; - - /* DES3-CBC Known Initialization Vector (64-bits). */ - static const PRUint8 des3_cbc_known_initialization_vector[] = { "Security" }; - - /* DES3 Known Plaintext (64-bits). */ - static const PRUint8 des3_ecb_known_plaintext[] = { "Netscape" }; - static const PRUint8 des3_cbc_known_plaintext[] = { "Netscape" }; - - /* DES3 Known Ciphertext (64-bits). */ - static const PRUint8 des3_ecb_known_ciphertext[] = { - 0x55,0x8e,0xad,0x3c,0xee,0x49,0x69,0xbe}; - static const PRUint8 des3_cbc_known_ciphertext[] = { - 0x43,0xdc,0x6a,0xc1,0xaf,0xa6,0x32,0xf5}; - - /* DES3 variables. */ - PRUint8 des3_computed_ciphertext[FIPS_DES3_ENCRYPT_LENGTH]; - PRUint8 des3_computed_plaintext[FIPS_DES3_DECRYPT_LENGTH]; - DESContext * des3_context; - unsigned int des3_bytes_encrypted; - unsigned int des3_bytes_decrypted; - SECStatus des3_status; - - - /*******************************************************/ - /* DES3-ECB Single-Round Known Answer Encryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, NULL, - NSS_DES_EDE3, PR_TRUE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext, - &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH, - des3_ecb_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_ciphertext, des3_ecb_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /*******************************************************/ - /* DES3-ECB Single-Round Known Answer Decryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, NULL, - NSS_DES_EDE3, PR_FALSE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Decrypt( des3_context, des3_computed_plaintext, - &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH, - des3_ecb_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_plaintext, des3_ecb_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /*******************************************************/ - /* DES3-CBC Single-Round Known Answer Encryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, - des3_cbc_known_initialization_vector, - NSS_DES_EDE3_CBC, PR_TRUE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext, - &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH, - des3_cbc_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_ciphertext, des3_cbc_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /*******************************************************/ - /* DES3-CBC Single-Round Known Answer Decryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, - des3_cbc_known_initialization_vector, - NSS_DES_EDE3_CBC, PR_FALSE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Decrypt( des3_context, des3_computed_plaintext, - &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH, - des3_cbc_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_plaintext, des3_cbc_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -pk11_fips_MD2_PowerUpSelfTest( void ) -{ - /* MD2 Known Hash Message (512-bits). */ - static const PRUint8 md2_known_hash_message[] = { - "The test message for the MD2, MD5, and SHA-1 hashing algorithms." }; - - /* MD2 Known Digest Message (128-bits). */ - static const PRUint8 md2_known_digest[] = { - 0x41,0x5a,0x12,0xb2,0x3f,0x28,0x97,0x17, - 0x0c,0x71,0x4e,0xcc,0x40,0xc8,0x1d,0x1b}; - - /* MD2 variables. */ - MD2Context * md2_context; - unsigned int md2_bytes_hashed; - PRUint8 md2_computed_digest[MD2_LENGTH]; - - - /***********************************************/ - /* MD2 Single-Round Known Answer Hashing Test. */ - /***********************************************/ - - md2_context = MD2_NewContext(); - - if( md2_context == NULL ) - return( CKR_HOST_MEMORY ); - - MD2_Begin( md2_context ); - - MD2_Update( md2_context, md2_known_hash_message, - FIPS_MD2_HASH_MESSAGE_LENGTH ); - - MD2_End( md2_context, md2_computed_digest, &md2_bytes_hashed, MD2_LENGTH ); - - MD2_DestroyContext( md2_context , PR_TRUE ); - - if( ( md2_bytes_hashed != MD2_LENGTH ) || - ( PORT_Memcmp( md2_computed_digest, md2_known_digest, - MD2_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -pk11_fips_MD5_PowerUpSelfTest( void ) -{ - /* MD5 Known Hash Message (512-bits). */ - static const PRUint8 md5_known_hash_message[] = { - "The test message for the MD2, MD5, and SHA-1 hashing algorithms." }; - - /* MD5 Known Digest Message (128-bits). */ - static const PRUint8 md5_known_digest[] = { - 0x25,0xc8,0xc0,0x10,0xc5,0x6e,0x68,0x28, - 0x28,0xa4,0xa5,0xd2,0x98,0x9a,0xea,0x2d}; - - /* MD5 variables. */ - PRUint8 md5_computed_digest[MD5_LENGTH]; - SECStatus md5_status; - - - /***********************************************/ - /* MD5 Single-Round Known Answer Hashing Test. */ - /***********************************************/ - - md5_status = MD5_HashBuf( md5_computed_digest, md5_known_hash_message, - FIPS_MD5_HASH_MESSAGE_LENGTH ); - - if( ( md5_status != SECSuccess ) || - ( PORT_Memcmp( md5_computed_digest, md5_known_digest, - MD5_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -pk11_fips_SHA1_PowerUpSelfTest( void ) -{ - /* SHA-1 Known Hash Message (512-bits). */ - static const PRUint8 sha1_known_hash_message[] = { - "The test message for the MD2, MD5, and SHA-1 hashing algorithms." }; - - /* SHA-1 Known Digest Message (160-bits). */ - static const PRUint8 sha1_known_digest[] = { - 0x0a,0x6d,0x07,0xba,0x1e,0xbd,0x8a,0x1b, - 0x72,0xf6,0xc7,0x22,0xf1,0x27,0x9f,0xf0, - 0xe0,0x68,0x47,0x7a}; - - /* SHA-1 variables. */ - PRUint8 sha1_computed_digest[SHA1_LENGTH]; - SECStatus sha1_status; - - - /*************************************************/ - /* SHA-1 Single-Round Known Answer Hashing Test. */ - /*************************************************/ - - sha1_status = SHA1_HashBuf( sha1_computed_digest, sha1_known_hash_message, - FIPS_SHA1_HASH_MESSAGE_LENGTH ); - - if( ( sha1_status != SECSuccess ) || - ( PORT_Memcmp( sha1_computed_digest, sha1_known_digest, - SHA1_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -pk11_fips_RSA_PowerUpSelfTest( void ) -{ - /* RSA Known Modulus used in both Public/Private Key Values (520-bits). */ - static const PRUint8 rsa_modulus[FIPS_RSA_MODULUS_LENGTH] = { - 0x00,0xa1,0xe9,0x5e,0x66,0x88,0xe2,0xf2, - 0x2b,0xe7,0x70,0x36,0x33,0xbc,0xeb,0x55, - 0x55,0xf1,0x60,0x18,0x3c,0xfb,0xd2,0x79, - 0xf6,0xc4,0xb8,0x09,0xe3,0x12,0xf6,0x63, - 0x6d,0xc7,0x8e,0x19,0xc0,0x0e,0x10,0x78, - 0xc1,0xfe,0x2a,0x41,0x74,0x2d,0xf7,0xc4, - 0x69,0xa7,0x3c,0xbc,0x8a,0xc8,0x31,0x2b, - 0x4f,0x60,0xf0,0xf1,0xec,0x5a,0x29,0xec, - 0x6b}; - - /* RSA Known Public Key Values (8-bits). */ - static const PRUint8 rsa_public_exponent[] = { 0x03 }; - - /* RSA Known Private Key Values (version is 8-bits), */ - /* (private exponent is 512-bits), */ - /* (private prime0 is 264-bits), */ - /* (private prime1 is 264-bits), */ - /* (private prime exponent0 is 264-bits), */ - /* (private prime exponent1 is 264-bits), */ - /* and (private coefficient is 256-bits). */ - static const PRUint8 rsa_version[] = { 0x00 }; - static const PRUint8 rsa_private_exponent[FIPS_RSA_PRIVATE_EXPONENT_LENGTH] = { - 0x6b,0xf0,0xe9,0x99,0xb0,0x97,0x4c,0x1d, - 0x44,0xf5,0x79,0x77,0xd3,0x47,0x8e,0x39, - 0x4b,0x95,0x65,0x7d,0xfd,0x36,0xfb,0xf9, - 0xd8,0x7a,0xb1,0x42,0x0c,0xa4,0x42,0x48, - 0x20,0x1c,0x6b,0x7d,0x5d,0xa3,0x58,0xd6, - 0x95,0xd6,0x41,0xe3,0xd6,0x73,0xad,0xdb, - 0x3b,0x89,0x00,0x8a,0xcd,0x1d,0xb9,0x06, - 0xac,0xac,0x0e,0x02,0x72,0x1c,0xf8,0xab }; - static const PRUint8 rsa_prime0[FIPS_RSA_PRIME0_LENGTH] = { - 0x00,0xd2,0x2c,0x9d,0xef,0x7c,0x8f,0x58, - 0x93,0x19,0xa1,0x77,0x0e,0x38,0x3e,0x85, - 0xb4,0xaf,0xcc,0x99,0xa5,0x43,0xbf,0x97, - 0xdc,0x46,0xb8,0x3f,0x6e,0x85,0x18,0x00, - 0x81}; - static const PRUint8 rsa_prime1[FIPS_RSA_PRIME1_LENGTH] = { - 0x00,0xc5,0x36,0xda,0x94,0x85,0x0c,0x1a, - 0xed,0x03,0xc7,0x67,0x90,0x34,0x0b,0xb9, - 0xec,0x1e,0x22,0xa2,0x15,0x50,0xc4,0xfd, - 0xe9,0x17,0x36,0x9d,0x7a,0x29,0xe6,0x76, - 0xeb}; - static const PRUint8 rsa_exponent0[FIPS_RSA_EXPONENT0_LENGTH] = { - 0x00,0x8c,0x1d,0xbe,0x9f,0xa8, - 0x5f,0x90,0x62,0x11,0x16,0x4f, - 0x5e,0xd0,0x29,0xae,0x78,0x75, - 0x33,0x11,0x18,0xd7,0xd5,0x0f, - 0xe8,0x2f,0x25,0x7f,0x9f,0x03, - 0x65,0x55,0xab}; - static const PRUint8 rsa_exponent1[FIPS_RSA_EXPONENT1_LENGTH] = { - 0x00,0x83,0x79,0xe7,0x0d,0xae, - 0x08,0x11,0xf3,0x57,0xda,0x45, - 0x0a,0xcd,0x5d,0x26,0x9d,0x69, - 0x6c,0x6c,0x0e,0x35,0xd8,0xa9, - 0x46,0x0f,0x79,0xbe,0x51,0x71, - 0x44,0x4f,0x47}; - static const PRUint8 rsa_coefficient[FIPS_RSA_COEFFICIENT_LENGTH] = { - 0x54,0x8d,0xb8,0xdc,0x8b,0xde,0xbb, - 0x08,0xc9,0x67,0xb7,0xa9,0x5f,0xa5, - 0xc4,0x5e,0x67,0xaa,0xfe,0x1a,0x08, - 0xeb,0x48,0x43,0xcb,0xb0,0xb9,0x38, - 0x3a,0x31,0x39,0xde}; - - - /* RSA Known Plaintext (512-bits). */ - static const PRUint8 rsa_known_plaintext[] = { - "Known plaintext utilized for RSA" - " Encryption and Decryption test." }; - - /* RSA Known Ciphertext (512-bits). */ - static const PRUint8 rsa_known_ciphertext[] = { - 0x12,0x80,0x3a,0x53,0xee,0x93,0x81,0xa5, - 0xf7,0x40,0xc5,0xb1,0xef,0xd9,0x27,0xaf, - 0xef,0x4b,0x87,0x44,0x00,0xd0,0xda,0xcf, - 0x10,0x57,0x4c,0xd5,0xc3,0xed,0x84,0xdc, - 0x74,0x03,0x19,0x69,0x2c,0xd6,0x54,0x3e, - 0xd2,0xe3,0x90,0xb6,0x67,0x91,0x2f,0x1f, - 0x54,0x13,0x99,0x00,0x0b,0xfd,0x52,0x7f, - 0xd8,0xc6,0xdb,0x8a,0xfe,0x06,0xf3,0xb1}; - - /* RSA Known Message (128-bits). */ - static const PRUint8 rsa_known_message[] = { "Netscape Forever" }; - - /* RSA Known Signed Hash (512-bits). */ - static const PRUint8 rsa_known_signature[] = { - 0x27,0x23,0xa6,0x71,0x57,0xc8,0x70,0x5f, - 0x70,0x0e,0x06,0x7b,0x96,0x6a,0xaa,0x41, - 0x6e,0xab,0x67,0x4b,0x5f,0x76,0xc4,0x53, - 0x23,0xd7,0x57,0x7a,0x3a,0xbc,0x4c,0x27, - 0x65,0xca,0xde,0x9f,0xd3,0x1d,0xa4,0x5a, - 0xf9,0x8f,0xb2,0x05,0xa3,0x86,0xf9,0x66, - 0x55,0x4c,0x68,0x50,0x66,0xa4,0xe9,0x17, - 0x45,0x11,0xb8,0x1a,0xfc,0xbc,0x79,0x3b}; - - - static const RSAPublicKey bl_public_key = { NULL, - { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus, FIPS_RSA_MODULUS_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent, FIPS_RSA_PUBLIC_EXPONENT_LENGTH } - }; - static const RSAPrivateKey bl_private_key = { NULL, - { FIPS_RSA_TYPE, (unsigned char *)rsa_version, FIPS_RSA_PRIVATE_VERSION_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus, FIPS_RSA_MODULUS_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent, FIPS_RSA_PUBLIC_EXPONENT_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_private_exponent, FIPS_RSA_PRIVATE_EXPONENT_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_prime0, FIPS_RSA_PRIME0_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_prime1, FIPS_RSA_PRIME1_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent0, FIPS_RSA_EXPONENT0_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent1, FIPS_RSA_EXPONENT1_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_coefficient, FIPS_RSA_COEFFICIENT_LENGTH } - }; - - /* RSA variables. */ -#ifdef CREATE_TEMP_ARENAS - PLArenaPool * rsa_public_arena; - PLArenaPool * rsa_private_arena; -#endif - NSSLOWKEYPublicKey * rsa_public_key; - NSSLOWKEYPrivateKey * rsa_private_key; - unsigned int rsa_bytes_signed; - SECStatus rsa_status; - - NSSLOWKEYPublicKey low_public_key = { NULL, NSSLOWKEYRSAKey, }; - NSSLOWKEYPrivateKey low_private_key = { NULL, NSSLOWKEYRSAKey, }; - PRUint8 rsa_computed_ciphertext[FIPS_RSA_ENCRYPT_LENGTH]; - PRUint8 rsa_computed_plaintext[FIPS_RSA_DECRYPT_LENGTH]; - PRUint8 rsa_computed_signature[FIPS_RSA_SIGNATURE_LENGTH]; - - /****************************************/ - /* Compose RSA Public/Private Key Pair. */ - /****************************************/ - - low_public_key.u.rsa = bl_public_key; - low_private_key.u.rsa = bl_private_key; - - rsa_public_key = &low_public_key; - rsa_private_key = &low_private_key; - -#ifdef CREATE_TEMP_ARENAS - /* Create some space for the RSA public key. */ - rsa_public_arena = PORT_NewArena( NSS_SOFTOKEN_DEFAULT_CHUNKSIZE ); - - if( rsa_public_arena == NULL ) { - PORT_SetError( SEC_ERROR_NO_MEMORY ); - return( CKR_HOST_MEMORY ); - } - - /* Create some space for the RSA private key. */ - rsa_private_arena = PORT_NewArena( NSS_SOFTOKEN_DEFAULT_CHUNKSIZE ); - - if( rsa_private_arena == NULL ) { - PORT_FreeArena( rsa_public_arena, PR_TRUE ); - PORT_SetError( SEC_ERROR_NO_MEMORY ); - return( CKR_HOST_MEMORY ); - } - - rsa_public_key->arena = rsa_public_arena; - rsa_private_key->arena = rsa_private_arena; -#endif - - /**************************************************/ - /* RSA Single-Round Known Answer Encryption Test. */ - /**************************************************/ - - /* Perform RSA Public Key Encryption. */ - rsa_status = RSA_PublicKeyOp(&rsa_public_key->u.rsa, - rsa_computed_ciphertext, rsa_known_plaintext); - - if( ( rsa_status != SECSuccess ) || - ( PORT_Memcmp( rsa_computed_ciphertext, rsa_known_ciphertext, - FIPS_RSA_ENCRYPT_LENGTH ) != 0 ) ) - goto rsa_loser; - - /**************************************************/ - /* RSA Single-Round Known Answer Decryption Test. */ - /**************************************************/ - - /* Perform RSA Private Key Decryption. */ - rsa_status = RSA_PrivateKeyOp(&rsa_private_key->u.rsa, - rsa_computed_plaintext, rsa_known_ciphertext); - - if( ( rsa_status != SECSuccess ) || - ( PORT_Memcmp( rsa_computed_plaintext, rsa_known_plaintext, - FIPS_RSA_DECRYPT_LENGTH ) != 0 ) ) - goto rsa_loser; - - - /*************************************************/ - /* RSA Single-Round Known Answer Signature Test. */ - /*************************************************/ - - /* Perform RSA signature with the RSA private key. */ - rsa_status = RSA_Sign( rsa_private_key, rsa_computed_signature, - &rsa_bytes_signed, - FIPS_RSA_SIGNATURE_LENGTH, (unsigned char *)rsa_known_message, - FIPS_RSA_MESSAGE_LENGTH ); - - if( ( rsa_status != SECSuccess ) || - ( rsa_bytes_signed != FIPS_RSA_SIGNATURE_LENGTH ) || - ( PORT_Memcmp( rsa_computed_signature, rsa_known_signature, - FIPS_RSA_SIGNATURE_LENGTH ) != 0 ) ) - goto rsa_loser; - - - /****************************************************/ - /* RSA Single-Round Known Answer Verification Test. */ - /****************************************************/ - - /* Perform RSA verification with the RSA public key. */ - rsa_status = RSA_CheckSign( rsa_public_key, - rsa_computed_signature, - FIPS_RSA_SIGNATURE_LENGTH, - (unsigned char *)rsa_known_message, - FIPS_RSA_MESSAGE_LENGTH ); - - if( rsa_status != SECSuccess ) - goto rsa_loser; - - /* Dispose of all RSA key material. */ - nsslowkey_DestroyPublicKey( rsa_public_key ); - nsslowkey_DestroyPrivateKey( rsa_private_key ); - - return( CKR_OK ); - - -rsa_loser: - - nsslowkey_DestroyPublicKey( rsa_public_key ); - nsslowkey_DestroyPrivateKey( rsa_private_key ); - - return( CKR_DEVICE_ERROR ); -} - - -static CK_RV -pk11_fips_DSA_PowerUpSelfTest( void ) -{ - /* DSA Known P (512-bits), Q (160-bits), and G (512-bits) Values. */ - static const PRUint8 dsa_P[] = { - 0x8d,0xf2,0xa4,0x94,0x49,0x22,0x76,0xaa, - 0x3d,0x25,0x75,0x9b,0xb0,0x68,0x69,0xcb, - 0xea,0xc0,0xd8,0x3a,0xfb,0x8d,0x0c,0xf7, - 0xcb,0xb8,0x32,0x4f,0x0d,0x78,0x82,0xe5, - 0xd0,0x76,0x2f,0xc5,0xb7,0x21,0x0e,0xaf, - 0xc2,0xe9,0xad,0xac,0x32,0xab,0x7a,0xac, - 0x49,0x69,0x3d,0xfb,0xf8,0x37,0x24,0xc2, - 0xec,0x07,0x36,0xee,0x31,0xc8,0x02,0x91}; - static const PRUint8 dsa_Q[] = { - 0xc7,0x73,0x21,0x8c,0x73,0x7e,0xc8,0xee, - 0x99,0x3b,0x4f,0x2d,0xed,0x30,0xf4,0x8e, - 0xda,0xce,0x91,0x5f}; - static const PRUint8 dsa_G[] = { - 0x62,0x6d,0x02,0x78,0x39,0xea,0x0a,0x13, - 0x41,0x31,0x63,0xa5,0x5b,0x4c,0xb5,0x00, - 0x29,0x9d,0x55,0x22,0x95,0x6c,0xef,0xcb, - 0x3b,0xff,0x10,0xf3,0x99,0xce,0x2c,0x2e, - 0x71,0xcb,0x9d,0xe5,0xfa,0x24,0xba,0xbf, - 0x58,0xe5,0xb7,0x95,0x21,0x92,0x5c,0x9c, - 0xc4,0x2e,0x9f,0x6f,0x46,0x4b,0x08,0x8c, - 0xc5,0x72,0xaf,0x53,0xe6,0xd7,0x88,0x02}; - - /* DSA Known Random Values (known random key block is 160-bits) */ - /* and (known random signature block is 160-bits). */ - static const PRUint8 dsa_known_random_key_block[] = { - "Mozilla Rules World!"}; - static const PRUint8 dsa_known_random_signature_block[] = { - "Random DSA Signature"}; - - /* DSA Known Digest (160-bits) */ - static const PRUint8 dsa_known_digest[] = { "DSA Signature Digest" }; - - /* DSA Known Signature (320-bits). */ - static const PRUint8 dsa_known_signature[] = { - 0x39,0x0d,0x84,0xb1,0xf7,0x52,0x89,0xba, - 0xec,0x1e,0xa8,0xe2,0x00,0x8e,0x37,0x8f, - 0xc2,0xf5,0xf8,0x70,0x11,0xa8,0xc7,0x02, - 0x0e,0x75,0xcf,0x6b,0x54,0x4a,0x52,0xe8, - 0xd8,0x6d,0x4a,0xe8,0xee,0x56,0x8e,0x59}; - - /* DSA variables. */ - DSAPrivateKey * dsa_private_key; - SECStatus dsa_status; - SECItem dsa_signature_item; - SECItem dsa_digest_item; - DSAPublicKey dsa_public_key; - PRUint8 dsa_computed_signature[FIPS_DSA_SIGNATURE_LENGTH]; - static const PQGParams dsa_pqg = { NULL, - { FIPS_DSA_TYPE, (unsigned char *)dsa_P, FIPS_DSA_PRIME_LENGTH }, - { FIPS_DSA_TYPE, (unsigned char *)dsa_Q, FIPS_DSA_SUBPRIME_LENGTH }, - { FIPS_DSA_TYPE, (unsigned char *)dsa_G, FIPS_DSA_BASE_LENGTH }}; - - /*******************************************/ - /* Generate a DSA public/private key pair. */ - /*******************************************/ - - /* Generate a DSA public/private key pair. */ - - dsa_status = DSA_NewKeyFromSeed(&dsa_pqg, dsa_known_random_key_block, - &dsa_private_key); - - if( dsa_status != SECSuccess ) - return( CKR_HOST_MEMORY ); - - /* construct public key from private key. */ - dsa_public_key.params = dsa_private_key->params; - dsa_public_key.publicValue = dsa_private_key->publicValue; - - /*************************************************/ - /* DSA Single-Round Known Answer Signature Test. */ - /*************************************************/ - - dsa_signature_item.data = dsa_computed_signature; - dsa_signature_item.len = sizeof dsa_computed_signature; - - dsa_digest_item.data = (unsigned char *)dsa_known_digest; - dsa_digest_item.len = SHA1_LENGTH; - - /* Perform DSA signature process. */ - dsa_status = DSA_SignDigestWithSeed( dsa_private_key, - &dsa_signature_item, - &dsa_digest_item, - dsa_known_random_signature_block ); - - if( ( dsa_status != SECSuccess ) || - ( dsa_signature_item.len != FIPS_DSA_SIGNATURE_LENGTH ) || - ( PORT_Memcmp( dsa_computed_signature, dsa_known_signature, - FIPS_DSA_SIGNATURE_LENGTH ) != 0 ) ) { - dsa_status = SECFailure; - } else { - - /****************************************************/ - /* DSA Single-Round Known Answer Verification Test. */ - /****************************************************/ - - /* Perform DSA verification process. */ - dsa_status = DSA_VerifyDigest( &dsa_public_key, - &dsa_signature_item, - &dsa_digest_item); - } - - PORT_FreeArena(dsa_private_key->params.arena, PR_TRUE); - /* Don't free public key, it uses same arena as private key */ - - /* Verify DSA signature. */ - if( dsa_status != SECSuccess ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); - - -} - - -CK_RV -pk11_fipsPowerUpSelfTest( void ) -{ - CK_RV rv; - - /* RC2 Power-Up SelfTest(s). */ - rv = pk11_fips_RC2_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* RC4 Power-Up SelfTest(s). */ - rv = pk11_fips_RC4_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* DES Power-Up SelfTest(s). */ - rv = pk11_fips_DES_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* DES3 Power-Up SelfTest(s). */ - rv = pk11_fips_DES3_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* MD2 Power-Up SelfTest(s). */ - rv = pk11_fips_MD2_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* MD5 Power-Up SelfTest(s). */ - rv = pk11_fips_MD5_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* SHA-1 Power-Up SelfTest(s). */ - rv = pk11_fips_SHA1_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* RSA Power-Up SelfTest(s). */ - rv = pk11_fips_RSA_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* DSA Power-Up SelfTest(s). */ - rv = pk11_fips_DSA_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* Passed Power-Up SelfTest(s). */ - return( CKR_OK ); -} - diff --git a/security/nss/lib/softoken/fipstokn.c b/security/nss/lib/softoken/fipstokn.c deleted file mode 100644 index c33670451..000000000 --- a/security/nss/lib/softoken/fipstokn.c +++ /dev/null @@ -1,993 +0,0 @@ -/* - * 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. - */ -/* - * This file implements PKCS 11 on top of our existing security modules - * - * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. - * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login - * (unless you've enabled FIPS). It supports Public Key ops, and all they - * bulk ciphers and hashes. It can also support Private Key ops for imported - * Private keys. It does not have any token storage. - * slot 2 is our private key support. It requires a login before use. It - * can store Private Keys and Certs as token objects. Currently only private - * keys and their associated Certificates are saved on the token. - * - * In this implementation, session objects are only visible to the session - * that created or generated them. - */ -#include "seccomon.h" -#include "softoken.h" -#include "lowkeyi.h" -#include "pcert.h" -#include "pkcs11.h" -#include "pkcs11i.h" - - -/* - * ******************** Password Utilities ******************************* - */ -static PRBool isLoggedIn = PR_FALSE; -static PRBool fatalError = PR_FALSE; - -/* Fips required checks before any useful crypto graphic services */ -static CK_RV pk11_fipsCheck(void) { - if (isLoggedIn != PR_TRUE) - return CKR_USER_NOT_LOGGED_IN; - if (fatalError) - return CKR_DEVICE_ERROR; - return CKR_OK; -} - - -#define PK11_FIPSCHECK() \ - CK_RV rv; \ - if ((rv = pk11_fipsCheck()) != CKR_OK) return rv; - -#define PK11_FIPSFATALCHECK() \ - if (fatalError) return CKR_DEVICE_ERROR; - - -/* grab an attribute out of a raw template */ -void * -fc_getAttribute(CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, CK_ATTRIBUTE_TYPE type) -{ - int i; - - for (i=0; i < (int) ulCount; i++) { - if (pTemplate[i].type == type) { - return pTemplate[i].pValue; - } - } - return NULL; -} - - -#define __PASTE(x,y) x##y - -/* ------------- forward declare all the NSC_ functions ------------- */ -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - -#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(NS,name) -#define CK_NEED_ARG_LIST 1 - -#include "pkcs11f.h" - -/* ------------- forward declare all the FIPS functions ------------- */ -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - -#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(F,name) -#define CK_NEED_ARG_LIST 1 - -#include "pkcs11f.h" - -/* ------------- build the CK_CRYPTO_TABLE ------------------------- */ -static CK_FUNCTION_LIST pk11_fipsTable = { - { 1, 10 }, - -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - -#define CK_PKCS11_FUNCTION_INFO(name) __PASTE(F,name), - - -#include "pkcs11f.h" - -}; - -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - - -#undef __PASTE - -static CK_RV -fips_login_if_key_object(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) -{ - CK_RV rv; - CK_OBJECT_CLASS objClass; - CK_ATTRIBUTE class; - class.type = CKA_CLASS; - class.pValue = &objClass; - class.ulValueLen = sizeof(objClass); - rv = NSC_GetAttributeValue(hSession, hObject, &class, 1); - if (rv == CKR_OK) { - if ((objClass == CKO_PRIVATE_KEY) || (objClass == CKO_SECRET_KEY)) { - rv = pk11_fipsCheck(); - } - } - return rv; -} - - -/********************************************************************** - * - * Start of PKCS 11 functions - * - **********************************************************************/ -/* return the function list */ -CK_RV FC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) { - *pFunctionList = &pk11_fipsTable; - return CKR_OK; -} - -/* sigh global so pkcs11 can read it */ -PRBool nsf_init = PR_FALSE; - -/* FC_Initialize initializes the PKCS #11 library. */ -CK_RV FC_Initialize(CK_VOID_PTR pReserved) { - CK_RV crv; - - if (nsf_init) { - return CKR_CRYPTOKI_ALREADY_INITIALIZED; - } - - crv = nsc_CommonInitialize(pReserved, PR_TRUE); - - /* not an 'else' rv can be set by either PK11_LowInit or PK11_SlotInit*/ - if (crv != CKR_OK) { - fatalError = PR_TRUE; - return crv; - } - - fatalError = PR_FALSE; /* any error has been reset */ - - crv = pk11_fipsPowerUpSelfTest(); - if (crv != CKR_OK) { - nsc_CommonFinalize(NULL, PR_TRUE); - fatalError = PR_TRUE; - return crv; - } - nsf_init = PR_TRUE; - - return CKR_OK; -} - -/*FC_Finalize indicates that an application is done with the PKCS #11 library.*/ -CK_RV FC_Finalize (CK_VOID_PTR pReserved) { - CK_RV crv; - if (!nsf_init) { - return CKR_OK; - } - crv = nsc_CommonFinalize (pReserved, PR_TRUE); - nsf_init = (PRBool) !(crv == CKR_OK); - return crv; -} - - -/* FC_GetInfo returns general information about PKCS #11. */ -CK_RV FC_GetInfo(CK_INFO_PTR pInfo) { - return NSC_GetInfo(pInfo); -} - -/* FC_GetSlotList obtains a list of slots in the system. */ -CK_RV FC_GetSlotList(CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) { - return nsc_CommonGetSlotList(tokenPresent,pSlotList,pulCount, - NSC_FIPS_MODULE); -} - -/* FC_GetSlotInfo obtains information about a particular slot in the system. */ -CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { - - CK_RV crv; - - crv = NSC_GetSlotInfo(slotID,pInfo); - if (crv != CKR_OK) { - return crv; - } - - return CKR_OK; -} - - -/*FC_GetTokenInfo obtains information about a particular token in the system.*/ - CK_RV FC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo) { - CK_RV crv; - - crv = NSC_GetTokenInfo(slotID,pInfo); - pInfo->flags |= CKF_RNG | CKF_LOGIN_REQUIRED; - return crv; - -} - - - -/*FC_GetMechanismList obtains a list of mechanism types supported by a token.*/ - CK_RV FC_GetMechanismList(CK_SLOT_ID slotID, - CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pusCount) { - PK11_FIPSFATALCHECK(); - if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID; - /* FIPS Slot supports all functions */ - return NSC_GetMechanismList(slotID,pMechanismList,pusCount); -} - - -/* FC_GetMechanismInfo obtains information about a particular mechanism - * possibly supported by a token. */ - CK_RV FC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, - CK_MECHANISM_INFO_PTR pInfo) { - PK11_FIPSFATALCHECK(); - if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID; - /* FIPS Slot supports all functions */ - return NSC_GetMechanismInfo(slotID,type,pInfo); -} - - -/* FC_InitToken initializes a token. */ - CK_RV FC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin, - CK_ULONG usPinLen,CK_CHAR_PTR pLabel) { - return CKR_HOST_MEMORY; /*is this the right function for not implemented*/ -} - - -/* FC_InitPIN initializes the normal user's PIN. */ - CK_RV FC_InitPIN(CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pPin, CK_ULONG ulPinLen) { - return NSC_InitPIN(hSession,pPin,ulPinLen); -} - - -/* FC_SetPIN modifies the PIN of user that is currently logged in. */ -/* NOTE: This is only valid for the PRIVATE_KEY_SLOT */ - CK_RV FC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, - CK_ULONG usOldLen, CK_CHAR_PTR pNewPin, CK_ULONG usNewLen) { - CK_RV rv; - if ((rv = pk11_fipsCheck()) != CKR_OK) return rv; - return NSC_SetPIN(hSession,pOldPin,usOldLen,pNewPin,usNewLen); -} - -/* FC_OpenSession opens a session between an application and a token. */ - CK_RV FC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, - CK_VOID_PTR pApplication,CK_NOTIFY Notify,CK_SESSION_HANDLE_PTR phSession) { - PK11_FIPSFATALCHECK(); - return NSC_OpenSession(slotID,flags,pApplication,Notify,phSession); -} - - -/* FC_CloseSession closes a session between an application and a token. */ - CK_RV FC_CloseSession(CK_SESSION_HANDLE hSession) { - return NSC_CloseSession(hSession); -} - - -/* FC_CloseAllSessions closes all sessions with a token. */ - CK_RV FC_CloseAllSessions (CK_SLOT_ID slotID) { - return NSC_CloseAllSessions (slotID); -} - - -/* FC_GetSessionInfo obtains information about the session. */ - CK_RV FC_GetSessionInfo(CK_SESSION_HANDLE hSession, - CK_SESSION_INFO_PTR pInfo) { - CK_RV rv; - PK11_FIPSFATALCHECK(); - - rv = NSC_GetSessionInfo(hSession,pInfo); - if (rv == CKR_OK) { - if ((isLoggedIn) && (pInfo->state == CKS_RO_PUBLIC_SESSION)) { - pInfo->state = CKS_RO_USER_FUNCTIONS; - } - if ((isLoggedIn) && (pInfo->state == CKS_RW_PUBLIC_SESSION)) { - pInfo->state = CKS_RW_USER_FUNCTIONS; - } - } - return rv; -} - -/* FC_Login logs a user into a token. */ - CK_RV FC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, - CK_CHAR_PTR pPin, CK_ULONG usPinLen) { - CK_RV rv; - PK11_FIPSFATALCHECK(); - rv = NSC_Login(hSession,userType,pPin,usPinLen); - if (rv == CKR_OK) - isLoggedIn = PR_TRUE; - else if (rv == CKR_USER_ALREADY_LOGGED_IN) - { - isLoggedIn = PR_TRUE; - - /* Provide FIPS PUB 140-1 power-up self-tests on demand. */ - rv = pk11_fipsPowerUpSelfTest(); - if (rv == CKR_OK) - return CKR_USER_ALREADY_LOGGED_IN; - else - fatalError = PR_TRUE; - } - return rv; -} - -/* FC_Logout logs a user out from a token. */ - CK_RV FC_Logout(CK_SESSION_HANDLE hSession) { - PK11_FIPSCHECK(); - - rv = NSC_Logout(hSession); - isLoggedIn = PR_FALSE; - return rv; -} - - -/* FC_CreateObject creates a new object. */ - CK_RV FC_CreateObject(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject) { - CK_OBJECT_CLASS * classptr; - PK11_FIPSCHECK(); - classptr = (CK_OBJECT_CLASS *)fc_getAttribute(pTemplate,ulCount,CKA_CLASS); - if (classptr == NULL) return CKR_TEMPLATE_INCOMPLETE; - - /* FIPS can't create keys from raw key material */ - if ((*classptr == CKO_SECRET_KEY) || (*classptr == CKO_PRIVATE_KEY)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - return NSC_CreateObject(hSession,pTemplate,ulCount,phObject); -} - - - - - -/* FC_CopyObject copies an object, creating a new object for the copy. */ - CK_RV FC_CopyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG usCount, - CK_OBJECT_HANDLE_PTR phNewObject) { - CK_RV rv; - PK11_FIPSFATALCHECK(); - rv = fips_login_if_key_object(hSession, hObject); - if (rv != CKR_OK) { - return rv; - } - return NSC_CopyObject(hSession,hObject,pTemplate,usCount,phNewObject); -} - - -/* FC_DestroyObject destroys an object. */ - CK_RV FC_DestroyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject) { - CK_RV rv; - PK11_FIPSFATALCHECK(); - rv = fips_login_if_key_object(hSession, hObject); - if (rv != CKR_OK) { - return rv; - } - return NSC_DestroyObject(hSession,hObject); -} - - -/* FC_GetObjectSize gets the size of an object in bytes. */ - CK_RV FC_GetObjectSize(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pusSize) { - CK_RV rv; - PK11_FIPSFATALCHECK(); - rv = fips_login_if_key_object(hSession, hObject); - if (rv != CKR_OK) { - return rv; - } - return NSC_GetObjectSize(hSession, hObject, pusSize); -} - - -/* FC_GetAttributeValue obtains the value of one or more object attributes. */ - CK_RV FC_GetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG usCount) { - CK_RV rv; - PK11_FIPSFATALCHECK(); - rv = fips_login_if_key_object(hSession, hObject); - if (rv != CKR_OK) { - return rv; - } - return NSC_GetAttributeValue(hSession,hObject,pTemplate,usCount); -} - - -/* FC_SetAttributeValue modifies the value of one or more object attributes */ - CK_RV FC_SetAttributeValue (CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG usCount) { - CK_RV rv; - PK11_FIPSFATALCHECK(); - rv = fips_login_if_key_object(hSession, hObject); - if (rv != CKR_OK) { - return rv; - } - return NSC_SetAttributeValue(hSession,hObject,pTemplate,usCount); -} - - - -/* FC_FindObjectsInit initializes a search for token and session objects - * that match a template. */ - CK_RV FC_FindObjectsInit(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate,CK_ULONG usCount) { - /* let publically readable object be found */ - int i; - CK_RV rv; - PRBool needLogin = PR_FALSE; - - PK11_FIPSFATALCHECK(); - - for (i=0; i < usCount; i++) { - CK_OBJECT_CLASS class; - if (pTemplate[i].type != CKA_CLASS) { - continue; - } - if (pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS)) { - continue; - } - if (pTemplate[i].pValue == NULL) { - continue; - } - class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; - if ((class == CKO_PRIVATE_KEY) || (class == CKO_SECRET_KEY)) { - needLogin = PR_TRUE; - break; - } - } - if (needLogin) { - if ((rv = pk11_fipsCheck()) != CKR_OK) return rv; - } - return NSC_FindObjectsInit(hSession,pTemplate,usCount); -} - - -/* FC_FindObjects continues a search for token and session objects - * that match a template, obtaining additional object handles. */ - CK_RV FC_FindObjects(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE_PTR phObject,CK_ULONG usMaxObjectCount, - CK_ULONG_PTR pusObjectCount) { - /* let publically readable object be found */ - PK11_FIPSFATALCHECK(); - return NSC_FindObjects(hSession,phObject,usMaxObjectCount, - pusObjectCount); -} - - -/* - ************** Crypto Functions: Encrypt ************************ - */ - -/* FC_EncryptInit initializes an encryption operation. */ - CK_RV FC_EncryptInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { - PK11_FIPSCHECK(); - return NSC_EncryptInit(hSession,pMechanism,hKey); -} - -/* FC_Encrypt encrypts single-part data. */ - CK_RV FC_Encrypt (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG usDataLen, CK_BYTE_PTR pEncryptedData, - CK_ULONG_PTR pusEncryptedDataLen) { - PK11_FIPSCHECK(); - return NSC_Encrypt(hSession,pData,usDataLen,pEncryptedData, - pusEncryptedDataLen); -} - - -/* FC_EncryptUpdate continues a multiple-part encryption operation. */ - CK_RV FC_EncryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, CK_ULONG usPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pusEncryptedPartLen) { - PK11_FIPSCHECK(); - return NSC_EncryptUpdate(hSession,pPart,usPartLen,pEncryptedPart, - pusEncryptedPartLen); -} - - -/* FC_EncryptFinal finishes a multiple-part encryption operation. */ - CK_RV FC_EncryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pusLastEncryptedPartLen) { - - PK11_FIPSCHECK(); - return NSC_EncryptFinal(hSession,pLastEncryptedPart, - pusLastEncryptedPartLen); -} - -/* - ************** Crypto Functions: Decrypt ************************ - */ - - -/* FC_DecryptInit initializes a decryption operation. */ - CK_RV FC_DecryptInit( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { - PK11_FIPSCHECK(); - return NSC_DecryptInit(hSession,pMechanism,hKey); -} - -/* FC_Decrypt decrypts encrypted data in a single part. */ - CK_RV FC_Decrypt(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData,CK_ULONG usEncryptedDataLen,CK_BYTE_PTR pData, - CK_ULONG_PTR pusDataLen) { - PK11_FIPSCHECK(); - return NSC_Decrypt(hSession,pEncryptedData,usEncryptedDataLen,pData, - pusDataLen); -} - - -/* FC_DecryptUpdate continues a multiple-part decryption operation. */ - CK_RV FC_DecryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG usEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pusPartLen) { - PK11_FIPSCHECK(); - return NSC_DecryptUpdate(hSession,pEncryptedPart,usEncryptedPartLen, - pPart,pusPartLen); -} - - -/* FC_DecryptFinal finishes a multiple-part decryption operation. */ - CK_RV FC_DecryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastPart, CK_ULONG_PTR pusLastPartLen) { - PK11_FIPSCHECK(); - return NSC_DecryptFinal(hSession,pLastPart,pusLastPartLen); -} - - -/* - ************** Crypto Functions: Digest (HASH) ************************ - */ - -/* FC_DigestInit initializes a message-digesting operation. */ - CK_RV FC_DigestInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism) { - PK11_FIPSFATALCHECK(); - return NSC_DigestInit(hSession, pMechanism); -} - - -/* FC_Digest digests data in a single part. */ - CK_RV FC_Digest(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, CK_ULONG usDataLen, CK_BYTE_PTR pDigest, - CK_ULONG_PTR pusDigestLen) { - PK11_FIPSFATALCHECK(); - return NSC_Digest(hSession,pData,usDataLen,pDigest,pusDigestLen); -} - - -/* FC_DigestUpdate continues a multiple-part message-digesting operation. */ - CK_RV FC_DigestUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG usPartLen) { - PK11_FIPSFATALCHECK(); - return NSC_DigestUpdate(hSession,pPart,usPartLen); -} - - -/* FC_DigestFinal finishes a multiple-part message-digesting operation. */ - CK_RV FC_DigestFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pDigest, - CK_ULONG_PTR pusDigestLen) { - PK11_FIPSFATALCHECK(); - return NSC_DigestFinal(hSession,pDigest,pusDigestLen); -} - - -/* - ************** Crypto Functions: Sign ************************ - */ - -/* FC_SignInit initializes a signature (private key encryption) operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature */ - CK_RV FC_SignInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { - PK11_FIPSCHECK(); - return NSC_SignInit(hSession,pMechanism,hKey); -} - - -/* FC_Sign signs (encrypts with private key) data in a single part, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature */ - CK_RV FC_Sign(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData,CK_ULONG usDataLen,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pusSignatureLen) { - PK11_FIPSCHECK(); - return NSC_Sign(hSession,pData,usDataLen,pSignature,pusSignatureLen); -} - - -/* FC_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature */ - CK_RV FC_SignUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG usPartLen) { - PK11_FIPSCHECK(); - return NSC_SignUpdate(hSession,pPart,usPartLen); -} - - -/* FC_SignFinal finishes a multiple-part signature operation, - * returning the signature. */ - CK_RV FC_SignFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pusSignatureLen) { - PK11_FIPSCHECK(); - return NSC_SignFinal(hSession,pSignature,pusSignatureLen); -} - -/* - ************** Crypto Functions: Sign Recover ************************ - */ -/* FC_SignRecoverInit initializes a signature operation, - * where the (digest) data can be recovered from the signature. - * E.g. encryption with the user's private key */ - CK_RV FC_SignRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) { - PK11_FIPSCHECK(); - return NSC_SignRecoverInit(hSession,pMechanism,hKey); -} - - -/* FC_SignRecover signs data in a single operation - * where the (digest) data can be recovered from the signature. - * E.g. encryption with the user's private key */ - CK_RV FC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pusSignatureLen) { - PK11_FIPSCHECK(); - return NSC_SignRecover(hSession,pData,usDataLen,pSignature,pusSignatureLen); -} - -/* - ************** Crypto Functions: verify ************************ - */ - -/* FC_VerifyInit initializes a verification operation, - * where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature (e.g. DSA) */ - CK_RV FC_VerifyInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) { - PK11_FIPSCHECK(); - return NSC_VerifyInit(hSession,pMechanism,hKey); -} - - -/* FC_Verify verifies a signature in a single-part operation, - * where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature */ - CK_RV FC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG usSignatureLen) { - /* make sure we're legal */ - PK11_FIPSCHECK(); - return NSC_Verify(hSession,pData,usDataLen,pSignature,usSignatureLen); -} - - -/* FC_VerifyUpdate continues a multiple-part verification operation, - * where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature */ - CK_RV FC_VerifyUpdate( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG usPartLen) { - PK11_FIPSCHECK(); - return NSC_VerifyUpdate(hSession,pPart,usPartLen); -} - - -/* FC_VerifyFinal finishes a multiple-part verification operation, - * checking the signature. */ - CK_RV FC_VerifyFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG usSignatureLen) { - PK11_FIPSCHECK(); - return NSC_VerifyFinal(hSession,pSignature,usSignatureLen); -} - -/* - ************** Crypto Functions: Verify Recover ************************ - */ - -/* FC_VerifyRecoverInit initializes a signature verification operation, - * where the data is recovered from the signature. - * E.g. Decryption with the user's public key */ - CK_RV FC_VerifyRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) { - PK11_FIPSCHECK(); - return NSC_VerifyRecoverInit(hSession,pMechanism,hKey); -} - - -/* FC_VerifyRecover verifies a signature in a single-part operation, - * where the data is recovered from the signature. - * E.g. Decryption with the user's public key */ - CK_RV FC_VerifyRecover(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG usSignatureLen, - CK_BYTE_PTR pData,CK_ULONG_PTR pusDataLen) { - PK11_FIPSCHECK(); - return NSC_VerifyRecover(hSession,pSignature,usSignatureLen,pData, - pusDataLen); -} - -/* - **************************** Key Functions: ************************ - */ - -/* FC_GenerateKey generates a secret key, creating a new key object. */ - CK_RV FC_GenerateKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phKey) { - CK_BBOOL *boolptr; - - PK11_FIPSCHECK(); - - /* all secret keys must be sensitive, if the upper level code tries to say - * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate, ulCount, CKA_SENSITIVE); - if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - } - - return NSC_GenerateKey(hSession,pMechanism,pTemplate,ulCount,phKey); -} - - -/* FC_GenerateKeyPair generates a public-key/private-key pair, - * creating new key objects. */ - CK_RV FC_GenerateKeyPair (CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG usPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG usPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, - CK_OBJECT_HANDLE_PTR phPrivateKey) { - CK_BBOOL *boolptr; - - PK11_FIPSCHECK(); - - /* all private keys must be sensitive, if the upper level code tries to say - * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pPrivateKeyTemplate, - usPrivateKeyAttributeCount, CKA_SENSITIVE); - if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - } - return NSC_GenerateKeyPair (hSession,pMechanism,pPublicKeyTemplate, - usPublicKeyAttributeCount,pPrivateKeyTemplate, - usPrivateKeyAttributeCount,phPublicKey,phPrivateKey); -} - - -/* FC_WrapKey wraps (i.e., encrypts) a key. */ - CK_RV FC_WrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, - CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pusWrappedKeyLen) { - PK11_FIPSCHECK(); - return NSC_WrapKey(hSession,pMechanism,hWrappingKey,hKey,pWrappedKey, - pusWrappedKeyLen); -} - - -/* FC_UnwrapKey unwraps (decrypts) a wrapped key, creating a new key object. */ - CK_RV FC_UnwrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, - CK_BYTE_PTR pWrappedKey, CK_ULONG usWrappedKeyLen, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG usAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) { - CK_BBOOL *boolptr; - - PK11_FIPSCHECK(); - - /* all secret keys must be sensitive, if the upper level code tries to say - * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate, - usAttributeCount, CKA_SENSITIVE); - if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - } - return NSC_UnwrapKey(hSession,pMechanism,hUnwrappingKey,pWrappedKey, - usWrappedKeyLen,pTemplate,usAttributeCount,phKey); -} - - -/* FC_DeriveKey derives a key from a base key, creating a new key object. */ - CK_RV FC_DeriveKey( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG usAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) { - CK_BBOOL *boolptr; - - PK11_FIPSCHECK(); - - /* all secret keys must be sensitive, if the upper level code tries to say - * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate, - usAttributeCount, CKA_SENSITIVE); - if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - } - return NSC_DeriveKey(hSession,pMechanism,hBaseKey,pTemplate, - usAttributeCount, phKey); -} - -/* - **************************** Radom Functions: ************************ - */ - -/* FC_SeedRandom mixes additional seed material into the token's random number - * generator. */ - CK_RV FC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, - CK_ULONG usSeedLen) { - CK_RV crv; - - PK11_FIPSFATALCHECK(); - crv = NSC_SeedRandom(hSession,pSeed,usSeedLen); - if (crv != CKR_OK) { - fatalError = PR_TRUE; - } - return crv; -} - - -/* FC_GenerateRandom generates random data. */ - CK_RV FC_GenerateRandom(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pRandomData, CK_ULONG usRandomLen) { - CK_RV crv; - - PK11_FIPSFATALCHECK(); - crv = NSC_GenerateRandom(hSession,pRandomData,usRandomLen); - if (crv != CKR_OK) { - fatalError = PR_TRUE; - } - return crv; -} - - -/* FC_GetFunctionStatus obtains an updated status of a function running - * in parallel with an application. */ - CK_RV FC_GetFunctionStatus(CK_SESSION_HANDLE hSession) { - PK11_FIPSCHECK(); - return NSC_GetFunctionStatus(hSession); -} - - -/* FC_CancelFunction cancels a function running in parallel */ - CK_RV FC_CancelFunction(CK_SESSION_HANDLE hSession) { - PK11_FIPSCHECK(); - return NSC_CancelFunction(hSession); -} - -/* - **************************** Version 1.1 Functions: ************************ - */ - -/* FC_GetOperationState saves the state of the cryptographic - *operation in a session. */ -CK_RV FC_GetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) { - PK11_FIPSFATALCHECK(); - return NSC_GetOperationState(hSession,pOperationState,pulOperationStateLen); -} - - -/* FC_SetOperationState restores the state of the cryptographic operation - * in a session. */ -CK_RV FC_SetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, - CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) { - PK11_FIPSFATALCHECK(); - return NSC_SetOperationState(hSession,pOperationState,ulOperationStateLen, - hEncryptionKey,hAuthenticationKey); -} - -/* FC_FindObjectsFinal finishes a search for token and session objects. */ -CK_RV FC_FindObjectsFinal(CK_SESSION_HANDLE hSession) { - /* let publically readable object be found */ - PK11_FIPSFATALCHECK(); - return NSC_FindObjectsFinal(hSession); -} - - -/* Dual-function cryptographic operations */ - -/* FC_DigestEncryptUpdate continues a multiple-part digesting and encryption - * operation. */ -CK_RV FC_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) { - PK11_FIPSCHECK(); - return NSC_DigestEncryptUpdate(hSession,pPart,ulPartLen,pEncryptedPart, - pulEncryptedPartLen); -} - - -/* FC_DecryptDigestUpdate continues a multiple-part decryption and digesting - * operation. */ -CK_RV FC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { - - PK11_FIPSCHECK(); - return NSC_DecryptDigestUpdate(hSession, pEncryptedPart,ulEncryptedPartLen, - pPart,pulPartLen); -} - -/* FC_SignEncryptUpdate continues a multiple-part signing and encryption - * operation. */ -CK_RV FC_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) { - - PK11_FIPSCHECK(); - return NSC_SignEncryptUpdate(hSession,pPart,ulPartLen,pEncryptedPart, - pulEncryptedPartLen); -} - -/* FC_DecryptVerifyUpdate continues a multiple-part decryption and verify - * operation. */ -CK_RV FC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, - CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { - - PK11_FIPSCHECK(); - return NSC_DecryptVerifyUpdate(hSession,pEncryptedData,ulEncryptedDataLen, - pData,pulDataLen); -} - - -/* FC_DigestKey continues a multi-part message-digesting operation, - * by digesting the value of a secret key as part of the data already digested. - */ -CK_RV FC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { - PK11_FIPSCHECK(); - return NSC_DigestKey(hSession,hKey); -} - - -CK_RV FC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, - CK_VOID_PTR pReserved) -{ - return NSC_WaitForSlotEvent(flags, pSlot, pReserved); -} diff --git a/security/nss/lib/softoken/keydb.c b/security/nss/lib/softoken/keydb.c deleted file mode 100644 index 92ea37d25..000000000 --- a/security/nss/lib/softoken/keydb.c +++ /dev/null @@ -1,2683 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - * - * Private Key Database code - * - * $Id$ - */ - -#include "lowkeyi.h" -#include "seccomon.h" -#include "sechash.h" -#include "secder.h" -#include "secasn1.h" -#include "secoid.h" -#include "blapi.h" -#include "secitem.h" -#include "pcert.h" -#include "mcom_db.h" -#include "lowpbe.h" -#include "secerr.h" -#include "cdbhdl.h" - -#include "keydbi.h" - -#ifdef NSS_ENABLE_ECC -extern SECStatus EC_FillParams(PRArenaPool *arena, - const SECItem *encodedParams, - ECParams *params); -#endif - -/* - * Record keys for keydb - */ -#define SALT_STRING "global-salt" -#define VERSION_STRING "Version" -#define KEYDB_PW_CHECK_STRING "password-check" -#define KEYDB_PW_CHECK_LEN 14 -#define KEYDB_FAKE_PW_CHECK_STRING "fake-password-check" -#define KEYDB_FAKE_PW_CHECK_LEN 19 - -/* Size of the global salt for key database */ -#define SALT_LENGTH 16 - -const SEC_ASN1Template nsslowkey_AttributeTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYAttribute) }, - { SEC_ASN1_OBJECT_ID, offsetof(NSSLOWKEYAttribute, attrType) }, - { SEC_ASN1_SET_OF, offsetof(NSSLOWKEYAttribute, attrValue), - SEC_AnyTemplate }, - { 0 } -}; - -const SEC_ASN1Template nsslowkey_SetOfAttributeTemplate[] = { - { SEC_ASN1_SET_OF, 0, nsslowkey_AttributeTemplate }, -}; -/* ASN1 Templates for new decoder/encoder */ -const SEC_ASN1Template nsslowkey_PrivateKeyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYPrivateKeyInfo) }, - { SEC_ASN1_INTEGER, - offsetof(NSSLOWKEYPrivateKeyInfo,version) }, - { SEC_ASN1_INLINE, - offsetof(NSSLOWKEYPrivateKeyInfo,algorithm), - SECOID_AlgorithmIDTemplate }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYPrivateKeyInfo,privateKey) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSLOWKEYPrivateKeyInfo, attributes), - nsslowkey_SetOfAttributeTemplate }, - { 0 } -}; - -const SEC_ASN1Template nsslowkey_PointerToPrivateKeyInfoTemplate[] = { - { SEC_ASN1_POINTER, 0, nsslowkey_PrivateKeyInfoTemplate } -}; - -const SEC_ASN1Template nsslowkey_EncryptedPrivateKeyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYEncryptedPrivateKeyInfo) }, - { SEC_ASN1_INLINE, - offsetof(NSSLOWKEYEncryptedPrivateKeyInfo,algorithm), - SECOID_AlgorithmIDTemplate }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYEncryptedPrivateKeyInfo,encryptedData) }, - { 0 } -}; - -const SEC_ASN1Template nsslowkey_PointerToEncryptedPrivateKeyInfoTemplate[] = { - { SEC_ASN1_POINTER, 0, nsslowkey_EncryptedPrivateKeyInfoTemplate } -}; - - -/* ====== Default key databse encryption algorithm ====== */ - -static SECOidTag defaultKeyDBAlg = SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC; - -/* - * Default algorithm for encrypting data in the key database - */ -SECOidTag -nsslowkey_GetDefaultKeyDBAlg(void) -{ - return(defaultKeyDBAlg); -} - -void -nsslowkey_SetDefaultKeyDBAlg(SECOidTag alg) -{ - defaultKeyDBAlg = alg; - - return; -} - -static void -sec_destroy_dbkey(NSSLOWKEYDBKey *dbkey) -{ - if ( dbkey && dbkey->arena ) { - PORT_FreeArena(dbkey->arena, PR_FALSE); - } -} - -static void -free_dbt(DBT *dbt) -{ - if ( dbt ) { - PORT_Free(dbt->data); - PORT_Free(dbt); - } - - return; -} - -/* - * format of key database entries for version 3 of database: - * byte offset field - * ----------- ----- - * 0 version - * 1 salt-len - * 2 nn-len - * 3.. salt-data - * ... nickname - * ... encrypted-key-data - */ -static DBT * -encode_dbkey(NSSLOWKEYDBKey *dbkey,unsigned char version) -{ - DBT *bufitem = NULL; - unsigned char *buf; - int nnlen; - char *nn; - - bufitem = (DBT *)PORT_ZAlloc(sizeof(DBT)); - if ( bufitem == NULL ) { - goto loser; - } - - if ( dbkey->nickname ) { - nn = dbkey->nickname; - nnlen = PORT_Strlen(nn) + 1; - } else { - nn = ""; - nnlen = 1; - } - - /* compute the length of the record */ - /* 1 + 1 + 1 == version number header + salt length + nn len */ - bufitem->size = dbkey->salt.len + nnlen + dbkey->derPK.len + 1 + 1 + 1; - - bufitem->data = (void *)PORT_ZAlloc(bufitem->size); - if ( bufitem->data == NULL ) { - goto loser; - } - - buf = (unsigned char *)bufitem->data; - - /* set version number */ - buf[0] = version; - - /* set length of salt */ - PORT_Assert(dbkey->salt.len < 256); - buf[1] = dbkey->salt.len; - - /* set length of nickname */ - PORT_Assert(nnlen < 256); - buf[2] = nnlen; - - /* copy salt */ - PORT_Memcpy(&buf[3], dbkey->salt.data, dbkey->salt.len); - - /* copy nickname */ - PORT_Memcpy(&buf[3 + dbkey->salt.len], nn, nnlen); - - /* copy encrypted key */ - PORT_Memcpy(&buf[3 + dbkey->salt.len + nnlen], dbkey->derPK.data, - dbkey->derPK.len); - - return(bufitem); - -loser: - if ( bufitem ) { - free_dbt(bufitem); - } - - return(NULL); -} - -static NSSLOWKEYDBKey * -decode_dbkey(DBT *bufitem, int expectedVersion) -{ - NSSLOWKEYDBKey *dbkey; - PLArenaPool *arena = NULL; - unsigned char *buf; - int version; - int keyoff; - int nnlen; - int saltoff; - - buf = (unsigned char *)bufitem->data; - - version = buf[0]; - - if ( version != expectedVersion ) { - goto loser; - } - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - dbkey = (NSSLOWKEYDBKey *)PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYDBKey)); - if ( dbkey == NULL ) { - goto loser; - } - - dbkey->arena = arena; - dbkey->salt.data = NULL; - dbkey->derPK.data = NULL; - - dbkey->salt.len = buf[1]; - dbkey->salt.data = (unsigned char *)PORT_ArenaZAlloc(arena, dbkey->salt.len); - if ( dbkey->salt.data == NULL ) { - goto loser; - } - - saltoff = 2; - keyoff = 2 + dbkey->salt.len; - - if ( expectedVersion >= 3 ) { - nnlen = buf[2]; - if ( nnlen ) { - dbkey->nickname = (char *)PORT_ArenaZAlloc(arena, nnlen + 1); - if ( dbkey->nickname ) { - PORT_Memcpy(dbkey->nickname, &buf[keyoff+1], nnlen); - } - } - keyoff += ( nnlen + 1 ); - saltoff = 3; - } - - PORT_Memcpy(dbkey->salt.data, &buf[saltoff], dbkey->salt.len); - - dbkey->derPK.len = bufitem->size - keyoff; - dbkey->derPK.data = (unsigned char *)PORT_ArenaZAlloc(arena,dbkey->derPK.len); - if ( dbkey->derPK.data == NULL ) { - goto loser; - } - - PORT_Memcpy(dbkey->derPK.data, &buf[keyoff], dbkey->derPK.len); - - return(dbkey); - -loser: - - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -static NSSLOWKEYDBKey * -get_dbkey(NSSLOWKEYDBHandle *handle, DBT *index) -{ - NSSLOWKEYDBKey *dbkey; - DBT entry; - int ret; - - /* get it from the database */ - ret = (* handle->db->get)(handle->db, index, &entry, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return NULL; - } - - /* set up dbkey struct */ - - dbkey = decode_dbkey(&entry, handle->version); - - return(dbkey); -} - -static SECStatus -put_dbkey(NSSLOWKEYDBHandle *handle, DBT *index, NSSLOWKEYDBKey *dbkey, PRBool update) -{ - DBT *keydata = NULL; - int status; - - keydata = encode_dbkey(dbkey, handle->version); - if ( keydata == NULL ) { - goto loser; - } - - /* put it in the database */ - if ( update ) { - status = (* handle->db->put)(handle->db, index, keydata, 0); - } else { - status = (* handle->db->put)(handle->db, index, keydata, - R_NOOVERWRITE); - } - - if ( status ) { - goto loser; - } - - /* sync the database */ - status = (* handle->db->sync)(handle->db, 0); - if ( status ) { - goto loser; - } - - free_dbt(keydata); - return(SECSuccess); - -loser: - if ( keydata ) { - free_dbt(keydata); - } - - return(SECFailure); -} - -SECStatus -nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, - SECStatus (* keyfunc)(DBT *k, DBT *d, void *pdata), - void *udata ) -{ - DBT data; - DBT key; - SECStatus status; - int ret; - - if (handle == NULL) { - return(SECFailure); - } - - ret = (* handle->db->seq)(handle->db, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); - } - - do { - /* skip version record */ - if ( data.size > 1 ) { - if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) { - if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) { - continue; - } - } - - /* skip password check */ - if ( key.size == KEYDB_PW_CHECK_LEN ) { - if ( PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING, - KEYDB_PW_CHECK_LEN) == 0 ) { - continue; - } - } - - status = (* keyfunc)(&key, &data, udata); - if (status != SECSuccess) { - return(status); - } - } - } while ( (* handle->db->seq)(handle->db, &key, &data, R_NEXT) == 0 ); - - return(SECSuccess); -} - -typedef struct keyNode { - struct keyNode *next; - DBT key; -} keyNode; - -typedef struct { - PLArenaPool *arena; - keyNode *head; -} keyList; - -static SECStatus -sec_add_key_to_list(DBT *key, DBT *data, void *arg) -{ - keyList *keylist; - keyNode *node; - void *keydata; - - keylist = (keyList *)arg; - - /* allocate the node struct */ - node = (keyNode*)PORT_ArenaZAlloc(keylist->arena, sizeof(keyNode)); - if ( node == NULL ) { - return(SECFailure); - } - - /* allocate room for key data */ - keydata = PORT_ArenaZAlloc(keylist->arena, key->size); - if ( keydata == NULL ) { - return(SECFailure); - } - - /* link node into list */ - node->next = keylist->head; - keylist->head = node; - - /* copy key into node */ - PORT_Memcpy(keydata, key->data, key->size); - node->key.size = key->size; - node->key.data = keydata; - - return(SECSuccess); -} - -static SECItem * -decodeKeyDBGlobalSalt(DBT *saltData) -{ - SECItem *saltitem; - - saltitem = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if ( saltitem == NULL ) { - return(NULL); - } - - saltitem->data = (unsigned char *)PORT_ZAlloc(saltData->size); - if ( saltitem->data == NULL ) { - PORT_Free(saltitem); - return(NULL); - } - - saltitem->len = saltData->size; - PORT_Memcpy(saltitem->data, saltData->data, saltitem->len); - - return(saltitem); -} - -static SECItem * -GetKeyDBGlobalSalt(NSSLOWKEYDBHandle *handle) -{ - DBT saltKey; - DBT saltData; - int ret; - - saltKey.data = SALT_STRING; - saltKey.size = sizeof(SALT_STRING) - 1; - - ret = (* handle->db->get)(handle->db, &saltKey, &saltData, 0); - if ( ret ) { - return(NULL); - } - - return(decodeKeyDBGlobalSalt(&saltData)); -} - -static SECStatus -StoreKeyDBGlobalSalt(NSSLOWKEYDBHandle *handle) -{ - DBT saltKey; - DBT saltData; - int status; - - saltKey.data = SALT_STRING; - saltKey.size = sizeof(SALT_STRING) - 1; - - saltData.data = (void *)handle->global_salt->data; - saltData.size = handle->global_salt->len; - - /* put global salt into the database now */ - status = (* handle->db->put)( handle->db, &saltKey, &saltData, 0); - if ( status ) { - return(SECFailure); - } - - return(SECSuccess); -} - -static SECStatus -makeGlobalVersion(NSSLOWKEYDBHandle *handle) -{ - unsigned char version; - DBT versionData; - DBT versionKey; - int status; - - version = NSSLOWKEY_DB_FILE_VERSION; - versionData.data = &version; - versionData.size = 1; - versionKey.data = VERSION_STRING; - versionKey.size = sizeof(VERSION_STRING)-1; - - /* put version string into the database now */ - status = (* handle->db->put)(handle->db, &versionKey, &versionData, 0); - if ( status ) { - return(SECFailure); - } - handle->version = version; - - return(SECSuccess); -} - - -static SECStatus -makeGlobalSalt(NSSLOWKEYDBHandle *handle) -{ - DBT saltKey; - DBT saltData; - unsigned char saltbuf[16]; - int status; - - saltKey.data = SALT_STRING; - saltKey.size = sizeof(SALT_STRING) - 1; - - saltData.data = (void *)saltbuf; - saltData.size = sizeof(saltbuf); - RNG_GenerateGlobalRandomBytes(saltbuf, sizeof(saltbuf)); - - /* put global salt into the database now */ - status = (* handle->db->put)( handle->db, &saltKey, &saltData, 0); - if ( status ) { - return(SECFailure); - } - - return(SECSuccess); -} - -static SECStatus -ChangeKeyDBPasswordAlg(NSSLOWKEYDBHandle *handle, - SECItem *oldpwitem, SECItem *newpwitem, - SECOidTag new_algorithm); -/* - * Second pass of updating the key db. This time we have a password. - */ -static SECStatus -nsslowkey_UpdateKeyDBPass2(NSSLOWKEYDBHandle *handle, SECItem *pwitem) -{ - SECStatus rv; - - rv = ChangeKeyDBPasswordAlg(handle, pwitem, pwitem, - nsslowkey_GetDefaultKeyDBAlg()); - - return(rv); -} - -static SECStatus -encodePWCheckEntry(PLArenaPool *arena, SECItem *entry, SECOidTag alg, - SECItem *encCheck); - -static unsigned char -nsslowkey_version(DB *db) -{ - DBT versionKey; - DBT versionData; - int ret; - versionKey.data = VERSION_STRING; - versionKey.size = sizeof(VERSION_STRING)-1; - - /* lookup version string in database */ - ret = (* db->get)( db, &versionKey, &versionData, 0 ); - - /* error accessing the database */ - if ( ret < 0 ) { - return 255; - } - - if ( ret >= 1 ) { - return 0; - } - return *( (unsigned char *)versionData.data); -} - -static PRBool -seckey_HasAServerKey(DB *db) -{ - DBT key; - DBT data; - int ret; - PRBool found = PR_FALSE; - - ret = (* db->seq)(db, &key, &data, R_FIRST); - if ( ret ) { - return PR_FALSE; - } - - do { - /* skip version record */ - if ( data.size > 1 ) { - /* skip salt */ - if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) { - if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) { - continue; - } - } - /* skip pw check entry */ - if ( key.size == KEYDB_PW_CHECK_LEN ) { - if ( PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING, - KEYDB_PW_CHECK_LEN) == 0 ) { - continue; - } - } - - /* keys stored by nickname will have 0 as the last byte of the - * db key. Other keys must be stored by modulus. We will not - * update those because they are left over from a keygen that - * never resulted in a cert. - */ - if ( ((unsigned char *)key.data)[key.size-1] != 0 ) { - continue; - } - - if (PORT_Strcmp(key.data,"Server-Key") == 0) { - found = PR_TRUE; - break; - } - - } - } while ( (* db->seq)(db, &key, &data, R_NEXT) == 0 ); - - return found; -} -/* - * currently updates key database from v2 to v3 - */ -static SECStatus -nsslowkey_UpdateKeyDBPass1(NSSLOWKEYDBHandle *handle) -{ - SECStatus rv; - DBT checkKey; - DBT checkData; - DBT saltKey; - DBT saltData; - DBT key; - DBT data; - unsigned char version; - SECItem *rc4key = NULL; - NSSLOWKEYDBKey *dbkey = NULL; - SECItem *oldSalt = NULL; - int ret; - SECItem checkitem; - - if ( handle->updatedb == NULL ) { - return(SECSuccess); - } - - /* - * check the version record - */ - version = nsslowkey_version(handle->updatedb); - if (version != 2) { - goto done; - } - - saltKey.data = SALT_STRING; - saltKey.size = sizeof(SALT_STRING) - 1; - - ret = (* handle->updatedb->get)(handle->updatedb, &saltKey, &saltData, 0); - if ( ret ) { - /* no salt in old db, so it is corrupted */ - goto done; - } - - oldSalt = decodeKeyDBGlobalSalt(&saltData); - if ( oldSalt == NULL ) { - /* bad salt in old db, so it is corrupted */ - goto done; - } - - /* - * look for a pw check entry - */ - checkKey.data = KEYDB_PW_CHECK_STRING; - checkKey.size = KEYDB_PW_CHECK_LEN; - - ret = (* handle->updatedb->get)(handle->updatedb, &checkKey, - &checkData, 0 ); - if (ret) { - /* - * if we have a key, but no KEYDB_PW_CHECK_STRING, then this must - * be an old server database, and it does have a password associated - * with it. Put a fake entry in so we can identify this db when we do - * get the password for it. - */ - if (seckey_HasAServerKey(handle->updatedb)) { - DBT fcheckKey; - DBT fcheckData; - - /* - * include a fake string - */ - fcheckKey.data = KEYDB_FAKE_PW_CHECK_STRING; - fcheckKey.size = KEYDB_FAKE_PW_CHECK_LEN; - fcheckData.data = "1"; - fcheckData.size = 1; - /* put global salt into the new database now */ - ret = (* handle->db->put)( handle->db, &saltKey, &saltData, 0); - if ( ret ) { - goto done; - } - ret = (* handle->db->put)( handle->db, &fcheckKey, &fcheckData, 0); - if ( ret ) { - goto done; - } - } else { - goto done; - } - } else { - /* put global salt into the new database now */ - ret = (* handle->db->put)( handle->db, &saltKey, &saltData, 0); - if ( ret ) { - goto done; - } - - dbkey = decode_dbkey(&checkData, 2); - if ( dbkey == NULL ) { - goto done; - } - checkitem = dbkey->derPK; - dbkey->derPK.data = NULL; - - /* format the new pw check entry */ - rv = encodePWCheckEntry(NULL, &dbkey->derPK, SEC_OID_RC4, &checkitem); - if ( rv != SECSuccess ) { - goto done; - } - - rv = put_dbkey(handle, &checkKey, dbkey, PR_TRUE); - if ( rv != SECSuccess ) { - goto done; - } - - /* free the dbkey */ - sec_destroy_dbkey(dbkey); - dbkey = NULL; - } - - - /* now traverse the database */ - ret = (* handle->updatedb->seq)(handle->updatedb, &key, &data, R_FIRST); - if ( ret ) { - goto done; - } - - do { - /* skip version record */ - if ( data.size > 1 ) { - /* skip salt */ - if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) { - if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) { - continue; - } - } - /* skip pw check entry */ - if ( key.size == checkKey.size ) { - if ( PORT_Memcmp(key.data, checkKey.data, key.size) == 0 ) { - continue; - } - } - - /* keys stored by nickname will have 0 as the last byte of the - * db key. Other keys must be stored by modulus. We will not - * update those because they are left over from a keygen that - * never resulted in a cert. - */ - if ( ((unsigned char *)key.data)[key.size-1] != 0 ) { - continue; - } - - dbkey = decode_dbkey(&data, 2); - if ( dbkey == NULL ) { - continue; - } - - /* This puts the key into the new database with the same - * index (nickname) that it had before. The second pass - * of the update will have the password. It will decrypt - * and re-encrypt the entries using a new algorithm. - */ - dbkey->nickname = (char *)key.data; - rv = put_dbkey(handle, &key, dbkey, PR_FALSE); - dbkey->nickname = NULL; - - sec_destroy_dbkey(dbkey); - } - } while ( (* handle->updatedb->seq)(handle->updatedb, &key, &data, - R_NEXT) == 0 ); - - dbkey = NULL; - -done: - /* sync the database */ - ret = (* handle->db->sync)(handle->db, 0); - - (* handle->updatedb->close)(handle->updatedb); - handle->updatedb = NULL; - - if ( rc4key ) { - SECITEM_FreeItem(rc4key, PR_TRUE); - } - - if ( oldSalt ) { - SECITEM_FreeItem(oldSalt, PR_TRUE); - } - - if ( dbkey ) { - sec_destroy_dbkey(dbkey); - } - - return(SECSuccess); -} - -static SECStatus -openNewDB(const char *appName, const char *prefix, const char *dbname, - NSSLOWKEYDBHandle *handle, NSSLOWKEYDBNameFunc namecb, void *cbarg) -{ - SECStatus rv = SECFailure; - int status = RDB_FAIL; - char *updname = NULL; - DB *updatedb = NULL; - PRBool updated = PR_FALSE; - int ret; - - if (appName) { - handle->db = rdbopen( appName, prefix, "key", NO_CREATE, &status); - } else { - handle->db = dbopen( dbname, NO_CREATE, 0600, DB_HASH, 0 ); - } - /* if create fails then we lose */ - if ( handle->db == NULL ) { - return (status == RDB_RETRY) ? SECWouldBlock: SECFailure; - } - - rv = db_BeginTransaction(handle->db); - if (rv != SECSuccess) { - db_InitComplete(handle->db); - return rv; - } - - /* force a transactional read, which will verify that one and only one - * process attempts the update. */ - if (nsslowkey_version(handle->db) == NSSLOWKEY_DB_FILE_VERSION) { - /* someone else has already updated the database for us */ - db_FinishTransaction(handle->db, PR_FALSE); - db_InitComplete(handle->db); - return SECSuccess; - } - - /* - * if we are creating a multiaccess database, see if there is a - * local database we can update from. - */ - if (appName) { - updatedb = dbopen( dbname, NO_RDONLY, 0600, DB_HASH, 0 ); - if (updatedb) { - handle->version = nsslowkey_version(updatedb); - if (handle->version != NSSLOWKEY_DB_FILE_VERSION) { - (updatedb->close)(updatedb); - } else { - db_Copy(handle->db, updatedb); - (updatedb->close)(updatedb); - db_FinishTransaction(handle->db,PR_FALSE); - db_InitComplete(handle->db); - return SECSuccess; - } - } - } - - /* update the version number */ - rv = makeGlobalVersion(handle); - if ( rv != SECSuccess ) { - goto loser; - } - - /* - * try to update from v2 db - */ - updname = (*namecb)(cbarg, 2); - if ( updname != NULL ) { - handle->updatedb = dbopen( updname, NO_RDONLY, 0600, DB_HASH, 0 ); - PORT_Free( updname ); - - if ( handle->updatedb ) { - /* - * Try to update the db using a null password. If the db - * doesn't have a password, then this will work. If it does - * have a password, then this will fail and we will do the - * update later - */ - rv = nsslowkey_UpdateKeyDBPass1(handle); - if ( rv == SECSuccess ) { - updated = PR_TRUE; - } - } - - } - - /* we are using the old salt if we updated from an old db */ - if ( ! updated ) { - rv = makeGlobalSalt(handle); - if ( rv != SECSuccess ) { - goto loser; - } - } - - /* sync the database */ - ret = (* handle->db->sync)(handle->db, 0); - if ( ret ) { - rv = SECFailure; - goto loser; - } - rv = SECSuccess; - -loser: - db_FinishTransaction(handle->db, rv != SECSuccess); - db_InitComplete(handle->db); - return rv; -} - - -static DB * -openOldDB(const char *appName, const char *prefix, const char *dbname, - PRBool openflags, int *version) { - DB *db = NULL; - - if (appName) { - db = rdbopen( appName, prefix, "key", openflags, NULL); - } else { - db = dbopen( dbname, openflags, 0600, DB_HASH, 0 ); - } - - /* check for correct version number */ - if (db != NULL) { - *version = nsslowkey_version(db); - if (*version != NSSLOWKEY_DB_FILE_VERSION ) { - /* bogus version number record, reset the database */ - (* db->close)( db ); - db = NULL; - } - } - return db; -} - -NSSLOWKEYDBHandle * -nsslowkey_OpenKeyDB(PRBool readOnly, const char *appName, const char *prefix, - NSSLOWKEYDBNameFunc namecb, void *cbarg) -{ - NSSLOWKEYDBHandle *handle; - SECStatus rv; - int openflags; - char *dbname = NULL; - - handle = (NSSLOWKEYDBHandle *)PORT_ZAlloc (sizeof(NSSLOWKEYDBHandle)); - if (handle == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; - } - - openflags = readOnly ? NO_RDONLY : NO_RDWR; - - dbname = (*namecb)(cbarg, NSSLOWKEY_DB_FILE_VERSION); - if ( dbname == NULL ) { - goto loser; - } - - handle->appname = appName ? PORT_Strdup(appName) : NULL ; - handle->dbname = (appName == NULL) ? PORT_Strdup(dbname) : - (prefix ? PORT_Strdup(prefix) : NULL); - handle->readOnly = readOnly; - - - handle->db = openOldDB(appName, prefix, dbname, openflags, - &handle->version); - if (handle->version == 255) { - goto loser; - } - - - /* if first open fails, try to create a new DB */ - if ( handle->db == NULL ) { - if ( readOnly ) { - goto loser; - } - - rv = openNewDB(appName, prefix, dbname, handle, namecb, cbarg); - /* two processes started to initialize the database at the same time. - * The multiprocess code blocked the second one, then had it retry to - * see if it can just open the database normally */ - if (rv == SECWouldBlock) { - handle->db = openOldDB(appName,prefix,dbname, - openflags, &handle->version); - if (handle->db == NULL) { - goto loser; - } - } else if (rv != SECSuccess) { - goto loser; - } - - } - - handle->global_salt = GetKeyDBGlobalSalt(handle); - if ( dbname ) - PORT_Free( dbname ); - return handle; - -loser: - - if ( dbname ) - PORT_Free( dbname ); - PORT_SetError(SEC_ERROR_BAD_DATABASE); - - if ( handle->db ) { - (* handle->db->close)(handle->db); - } - if ( handle->updatedb ) { - (* handle->updatedb->close)(handle->updatedb); - } - PORT_Free(handle); - return NULL; -} - -/* - * Close the database - */ -void -nsslowkey_CloseKeyDB(NSSLOWKEYDBHandle *handle) -{ - if (handle != NULL) { - if (handle->db != NULL) { - (* handle->db->close)(handle->db); - } - if (handle->dbname) PORT_Free(handle->dbname); - if (handle->appname) PORT_Free(handle->appname); - if (handle->global_salt) { - SECITEM_FreeItem(handle->global_salt,PR_TRUE); - } - - PORT_Free(handle); - } -} - -/* Get the key database version */ -int -nsslowkey_GetKeyDBVersion(NSSLOWKEYDBHandle *handle) -{ - PORT_Assert(handle != NULL); - - return handle->version; -} - -/* - * Delete a private key that was stored in the database - */ -SECStatus -nsslowkey_DeleteKey(NSSLOWKEYDBHandle *handle, SECItem *pubkey) -{ - DBT namekey; - int ret; - - if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); - } - - /* set up db key and data */ - namekey.data = pubkey->data; - namekey.size = pubkey->len; - - /* delete it from the database */ - ret = (* handle->db->del)(handle->db, &namekey, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); - } - - /* sync the database */ - ret = (* handle->db->sync)(handle->db, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); - } - - return(SECSuccess); -} - -/* - * Store a key in the database, indexed by its public key modulus.(value!) - */ -SECStatus -nsslowkey_StoreKeyByPublicKey(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SECItem *arg) -{ - return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, - nickname, arg, nsslowkey_GetDefaultKeyDBAlg(),PR_FALSE); -} - -SECStatus -nsslowkey_UpdateNickname(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SECItem *arg) -{ - return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, - nickname, arg, nsslowkey_GetDefaultKeyDBAlg(),PR_TRUE); -} - -/* see if the symetric CKA_ID already Exists. - */ -PRBool -nsslowkey_KeyForIDExists(NSSLOWKEYDBHandle *handle, SECItem *id) -{ - DBT namekey; - DBT dummy; - int status; - - namekey.data = (char *)id->data; - namekey.size = id->len; - status = (* handle->db->get)(handle->db, &namekey, &dummy, 0); - if ( status ) { - return PR_FALSE; - } - - return PR_TRUE; -} - -/* see if the public key for this cert is in the database filed - * by modulus - */ -PRBool -nsslowkey_KeyForCertExists(NSSLOWKEYDBHandle *handle, NSSLOWCERTCertificate *cert) -{ - NSSLOWKEYPublicKey *pubkey = NULL; - DBT namekey; - DBT dummy; - int status; - - /* get cert's public key */ - pubkey = nsslowcert_ExtractPublicKey(cert); - if ( pubkey == NULL ) { - return PR_FALSE; - } - - /* TNH - make key from NSSLOWKEYPublicKey */ - switch (pubkey->keyType) { - case NSSLOWKEYRSAKey: - namekey.data = pubkey->u.rsa.modulus.data; - namekey.size = pubkey->u.rsa.modulus.len; - break; - case NSSLOWKEYDSAKey: - namekey.data = pubkey->u.dsa.publicValue.data; - namekey.size = pubkey->u.dsa.publicValue.len; - break; - case NSSLOWKEYDHKey: - namekey.data = pubkey->u.dh.publicValue.data; - namekey.size = pubkey->u.dh.publicValue.len; - break; -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - namekey.data = pubkey->u.ec.publicValue.data; - namekey.size = pubkey->u.ec.publicValue.len; - break; -#endif /* NSS_ENABLE_ECC */ - default: - /* XXX We don't do Fortezza or DH yet. */ - return PR_FALSE; - } - - if (handle->version != 3) { - unsigned char buf[SHA1_LENGTH]; - SHA1_HashBuf(buf,namekey.data,namekey.size); - /* NOTE: don't use pubkey after this! it's now thrashed */ - PORT_Memcpy(namekey.data,buf,sizeof(buf)); - namekey.size = sizeof(buf); - } - - status = (* handle->db->get)(handle->db, &namekey, &dummy, 0); - /* some databases have the key stored as a signed value */ - if (status) { - unsigned char *buf = (unsigned char *)PORT_Alloc(namekey.size+1); - if (buf) { - PORT_Memcpy(&buf[1], namekey.data, namekey.size); - buf[0] = 0; - namekey.data = buf; - namekey.size ++; - status = (* handle->db->get)(handle->db, &namekey, &dummy, 0); - PORT_Free(buf); - } - } - nsslowkey_DestroyPublicKey(pubkey); - if ( status ) { - return PR_FALSE; - } - - return PR_TRUE; -} - -/* - * check to see if the user has a password - */ -SECStatus -nsslowkey_HasKeyDBPassword(NSSLOWKEYDBHandle *handle) -{ - DBT checkkey, checkdata; - int ret; - - if (handle == NULL) { - return(SECFailure); - } - - checkkey.data = KEYDB_PW_CHECK_STRING; - checkkey.size = KEYDB_PW_CHECK_LEN; - - ret = (* handle->db->get)(handle->db, &checkkey, &checkdata, 0 ); - if ( ret ) { - /* see if this was an updated DB first */ - checkkey.data = KEYDB_FAKE_PW_CHECK_STRING; - checkkey.size = KEYDB_FAKE_PW_CHECK_LEN; - ret = (* handle->db->get)(handle->db, &checkkey, &checkdata, 0 ); - if ( ret ) { - return(SECFailure); - } - } - - return(SECSuccess); -} - -/* - * Set up the password checker in the key database. - * This is done by encrypting a known plaintext with the user's key. - */ -SECStatus -nsslowkey_SetKeyDBPassword(NSSLOWKEYDBHandle *handle, SECItem *pwitem) -{ - return nsslowkey_SetKeyDBPasswordAlg(handle, pwitem, - nsslowkey_GetDefaultKeyDBAlg()); -} - -static SECStatus -HashPassword(unsigned char *hashresult, char *pw, SECItem *salt) -{ - SHA1Context *cx; - unsigned int outlen; - cx = SHA1_NewContext(); - if ( cx == NULL ) { - return(SECFailure); - } - - SHA1_Begin(cx); - if ( ( salt != NULL ) && ( salt->data != NULL ) ) { - SHA1_Update(cx, salt->data, salt->len); - } - - SHA1_Update(cx, (unsigned char *)pw, PORT_Strlen(pw)); - SHA1_End(cx, hashresult, &outlen, SHA1_LENGTH); - - SHA1_DestroyContext(cx, PR_TRUE); - - return(SECSuccess); -} - -SECItem * -nsslowkey_HashPassword(char *pw, SECItem *salt) -{ - SECItem *pwitem; - SECStatus rv; - - pwitem = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if ( pwitem == NULL ) { - return(NULL); - } - pwitem->len = SHA1_LENGTH; - pwitem->data = (unsigned char *)PORT_ZAlloc(SHA1_LENGTH); - if ( pwitem->data == NULL ) { - PORT_Free(pwitem); - return(NULL); - } - if ( pw ) { - rv = HashPassword(pwitem->data, pw, salt); - if ( rv != SECSuccess ) { - SECITEM_ZfreeItem(pwitem, PR_TRUE); - return(NULL); - } - } - - return(pwitem); -} - -/* Derive the actual password value for the database from a pw string */ -SECItem * -nsslowkey_DeriveKeyDBPassword(NSSLOWKEYDBHandle *keydb, char *pw) -{ - PORT_Assert(keydb != NULL); - PORT_Assert(pw != NULL); - if (keydb == NULL || pw == NULL) return(NULL); - - return nsslowkey_HashPassword(pw, keydb->global_salt); -} - -#if 0 -/* Appears obsolete - TNH */ -/* get the algorithm with which a private key - * is encrypted. - */ -SECOidTag -seckey_get_private_key_algorithm(NSSLOWKEYDBHandle *keydb, DBT *index) -{ - NSSLOWKEYDBKey *dbkey = NULL; - SECOidTag algorithm = SEC_OID_UNKNOWN; - NSSLOWKEYEncryptedPrivateKeyInfo *epki = NULL; - PLArenaPool *poolp = NULL; - SECStatus rv; - - poolp = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if(poolp == NULL) - return (SECOidTag)SECFailure; /* TNH - this is bad */ - - dbkey = get_dbkey(keydb, index); - if(dbkey == NULL) - return (SECOidTag)SECFailure; - - epki = (NSSLOWKEYEncryptedPrivateKeyInfo *)PORT_ArenaZAlloc(poolp, - sizeof(NSSLOWKEYEncryptedPrivateKeyInfo)); - if(epki == NULL) - goto loser; - rv = SEC_ASN1DecodeItem(poolp, epki, - nsslowkey_EncryptedPrivateKeyInfoTemplate, &dbkey->derPK); - if(rv == SECFailure) - goto loser; - - algorithm = SECOID_GetAlgorithmTag(&epki->algorithm); - - /* let success fall through */ -loser: - if(poolp != NULL) - PORT_FreeArena(poolp, PR_TRUE);\ - if(dbkey != NULL) - sec_destroy_dbkey(dbkey); - - return algorithm; -} -#endif - -/* - * Derive an RC4 key from a password key and a salt. This - * was the method to used to encrypt keys in the version 2? - * database - */ -SECItem * -seckey_create_rc4_key(SECItem *pwitem, SECItem *salt) -{ - MD5Context *md5 = NULL; - unsigned int part; - SECStatus rv = SECFailure; - SECItem *key = NULL; - - key = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(key != NULL) - { - key->data = (unsigned char *)PORT_ZAlloc(sizeof(unsigned char) * - MD5_LENGTH); - key->len = MD5_LENGTH; - if(key->data != NULL) - { - md5 = MD5_NewContext(); - if ( md5 != NULL ) - { - MD5_Begin(md5); - MD5_Update(md5, salt->data, salt->len); - MD5_Update(md5, pwitem->data, pwitem->len); - MD5_End(md5, key->data, &part, MD5_LENGTH); - MD5_DestroyContext(md5, PR_TRUE); - rv = SECSuccess; - } - } - - if(rv != SECSuccess) - { - SECITEM_FreeItem(key, PR_TRUE); - key = NULL; - } - } - - return key; -} - -SECItem * -seckey_create_rc4_salt(void) -{ - SECItem *salt = NULL; - SECStatus rv = SECFailure; - - salt = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(salt == NULL) - return NULL; - - salt->data = (unsigned char *)PORT_ZAlloc(sizeof(unsigned char) * - SALT_LENGTH); - if(salt->data != NULL) - { - salt->len = SALT_LENGTH; - RNG_GenerateGlobalRandomBytes(salt->data, salt->len); - rv = SECSuccess; - } - - if(rv == SECFailure) - { - SECITEM_FreeItem(salt, PR_TRUE); - salt = NULL; - } - - return salt; -} - -SECItem * -seckey_rc4_decode(SECItem *key, SECItem *src) -{ - SECItem *dest = NULL; - RC4Context *ctxt = NULL; - SECStatus rv = SECFailure; - - if((key == NULL) || (src == NULL)) - return NULL; - - dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest == NULL) - return NULL; - - dest->data = (unsigned char *)PORT_ZAlloc(sizeof(unsigned char) * - (src->len + 64)); /* TNH - padding? */ - if(dest->data != NULL) - { - ctxt = RC4_CreateContext(key->data, key->len); - if(ctxt != NULL) - { - rv = RC4_Decrypt(ctxt, dest->data, &dest->len, - src->len + 64, src->data, src->len); - RC4_DestroyContext(ctxt, PR_TRUE); - } - } - - if(rv == SECFailure) - if(dest != NULL) - { - SECITEM_FreeItem(dest, PR_TRUE); - dest = NULL; - } - - return dest; -} - - -#ifdef EC_DEBUG -#define SEC_PRINT(str1, str2, num, sitem) \ - printf("pkcs11c.c:%s:%s (keytype=%d) [len=%d]\n", \ - str1, str2, num, sitem->len); \ - for (i = 0; i < sitem->len; i++) { \ - printf("%02x:", sitem->data[i]); \ - } \ - printf("\n") -#else -#define SEC_PRINT(a, b, c, d) -#endif /* EC_DEBUG */ - -/* TNH - keydb is unused */ -/* TNH - the pwitem should be the derived key for RC4 */ -NSSLOWKEYEncryptedPrivateKeyInfo * -seckey_encrypt_private_key( - NSSLOWKEYPrivateKey *pk, SECItem *pwitem, NSSLOWKEYDBHandle *keydb, - SECOidTag algorithm, SECItem **salt) -{ - NSSLOWKEYEncryptedPrivateKeyInfo *epki = NULL; - NSSLOWKEYPrivateKeyInfo *pki = NULL; - SECStatus rv = SECFailure; - PLArenaPool *temparena = NULL, *permarena = NULL; - SECItem *der_item = NULL; - NSSPKCS5PBEParameter *param = NULL; - SECItem *dummy = NULL, *dest = NULL; - SECAlgorithmID *algid; -#ifdef NSS_ENABLE_ECC - SECItem *fordebug = NULL; - int savelen; - int i; -#endif - - *salt = NULL; - permarena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if(permarena == NULL) - return NULL; - - temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if(temparena == NULL) - goto loser; - - /* allocate structures */ - epki = (NSSLOWKEYEncryptedPrivateKeyInfo *)PORT_ArenaZAlloc(permarena, - sizeof(NSSLOWKEYEncryptedPrivateKeyInfo)); - pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, - sizeof(NSSLOWKEYPrivateKeyInfo)); - der_item = (SECItem *)PORT_ArenaZAlloc(temparena, sizeof(SECItem)); - if((epki == NULL) || (pki == NULL) || (der_item == NULL)) - goto loser; - - epki->arena = permarena; - - /* setup private key info */ - dummy = SEC_ASN1EncodeInteger(temparena, &(pki->version), - NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); - if(dummy == NULL) - goto loser; - - /* Encode the key, and set the algorithm (with params) */ - switch (pk->keyType) { - case NSSLOWKEYRSAKey: - prepare_low_rsa_priv_key_for_asn1(pk); - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - nsslowkey_RSAPrivateKeyTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_PKCS1_RSA_ENCRYPTION, 0); - if (rv == SECFailure) { - goto loser; - } - - break; - case NSSLOWKEYDSAKey: - prepare_low_dsa_priv_key_for_asn1(pk); - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - nsslowkey_DSAPrivateKeyTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - prepare_low_pqg_params_for_asn1(&pk->u.dsa.params); - dummy = SEC_ASN1EncodeItem(temparena, NULL, &pk->u.dsa.params, - nsslowkey_PQGParamsTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_ANSIX9_DSA_SIGNATURE, dummy); - if (rv == SECFailure) { - goto loser; - } - - break; - case NSSLOWKEYDHKey: - prepare_low_dh_priv_key_for_asn1(pk); - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - nsslowkey_DHPrivateKeyTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_X942_DIFFIE_HELMAN_KEY, dummy); - if (rv == SECFailure) { - goto loser; - } - break; -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - prepare_low_ec_priv_key_for_asn1(pk); - /* Public value is encoded as a bit string so adjust length - * to be in bits before ASN encoding and readjust - * immediately after. - * - * Since the SECG specification recommends not including the - * parameters as part of ECPrivateKey, we zero out the curveOID - * length before encoding and restore it later. - */ - pk->u.ec.publicValue.len <<= 3; - savelen = pk->u.ec.ecParams.curveOID.len; - pk->u.ec.ecParams.curveOID.len = 0; - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - nsslowkey_ECPrivateKeyTemplate); - pk->u.ec.ecParams.curveOID.len = savelen; - pk->u.ec.publicValue.len >>= 3; - - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - dummy = &pk->u.ec.ecParams.DEREncoding; - - /* At this point dummy should contain the encoded params */ - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_ANSIX962_EC_PUBLIC_KEY, dummy); - - if (rv == SECFailure) { - goto loser; - } - - fordebug = &(pki->privateKey); - SEC_PRINT("seckey_encrypt_private_key()", "PrivateKey", - pk->keyType, fordebug); - - break; -#endif /* NSS_ENABLE_ECC */ - default: - /* We don't support DH or Fortezza private keys yet */ - PORT_Assert(PR_FALSE); - break; - } - - /* setup encrypted private key info */ - dummy = SEC_ASN1EncodeItem(temparena, der_item, pki, - nsslowkey_PrivateKeyInfoTemplate); - - SEC_PRINT("seckey_encrypt_private_key()", "PrivateKeyInfo", - pk->keyType, der_item); - - if(dummy == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECFailure; /* assume failure */ - *salt = seckey_create_rc4_salt(); - if (*salt == NULL) { - goto loser; - } - - param = nsspkcs5_NewParam(algorithm,*salt,1); - if (param == NULL) { - goto loser; - } - - dest = nsspkcs5_CipherData(param, pwitem, der_item, PR_TRUE, NULL); - if (dest == NULL) { - goto loser; - } - - rv = SECITEM_CopyItem(permarena, &epki->encryptedData, dest); - if (rv != SECSuccess) { - goto loser; - } - - algid = nsspkcs5_CreateAlgorithmID(permarena, algorithm, param); - if (algid == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECOID_CopyAlgorithmID(permarena, &epki->algorithm, algid); - SECOID_DestroyAlgorithmID(algid, PR_TRUE); - -loser: - if(dest != NULL) - SECITEM_FreeItem(dest, PR_TRUE); - - if(param != NULL) - nsspkcs5_DestroyPBEParameter(param); - - /* let success fall through */ - - if(rv == SECFailure) - { - PORT_FreeArena(permarena, PR_TRUE); - epki = NULL; - if(*salt != NULL) - SECITEM_FreeItem(*salt, PR_TRUE); - } - - if(temparena != NULL) - PORT_FreeArena(temparena, PR_TRUE); - - return epki; -} - -static SECStatus -seckey_put_private_key(NSSLOWKEYDBHandle *keydb, DBT *index, SECItem *pwitem, - NSSLOWKEYPrivateKey *pk, char *nickname, PRBool update, - SECOidTag algorithm) -{ - NSSLOWKEYDBKey *dbkey = NULL; - NSSLOWKEYEncryptedPrivateKeyInfo *epki = NULL; - PLArenaPool *temparena = NULL, *permarena = NULL; - SECItem *dummy = NULL; - SECItem *salt = NULL; - SECStatus rv = SECFailure; - - if((keydb == NULL) || (index == NULL) || (pwitem == NULL) || - (pk == NULL)) - return SECFailure; - - permarena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if(permarena == NULL) - return SECFailure; - - dbkey = (NSSLOWKEYDBKey *)PORT_ArenaZAlloc(permarena, sizeof(NSSLOWKEYDBKey)); - if(dbkey == NULL) - goto loser; - dbkey->arena = permarena; - dbkey->nickname = nickname; - - /* TNH - for RC4, the salt should be created here */ - - epki = seckey_encrypt_private_key(pk, pwitem, keydb, algorithm, &salt); - if(epki == NULL) - goto loser; - temparena = epki->arena; - - if(salt != NULL) - { - rv = SECITEM_CopyItem(permarena, &(dbkey->salt), salt); - SECITEM_ZfreeItem(salt, PR_TRUE); - } - - dummy = SEC_ASN1EncodeItem(permarena, &(dbkey->derPK), epki, - nsslowkey_EncryptedPrivateKeyInfoTemplate); - if(dummy == NULL) - rv = SECFailure; - else - rv = put_dbkey(keydb, index, dbkey, update); - - /* let success fall through */ -loser: - if(rv != SECSuccess) - if(permarena != NULL) - PORT_FreeArena(permarena, PR_TRUE); - if(temparena != NULL) - PORT_FreeArena(temparena, PR_TRUE); - - return rv; -} - -/* - * Store a key in the database, indexed by its public key modulus. - * Note that the nickname is optional. It was only used by keyutil. - */ -SECStatus -nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SECItem *pwitem, - SECOidTag algorithm, - PRBool update) -{ - DBT namekey; - SECStatus rv; - - if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); - } - - /* set up db key and data */ - namekey.data = pubKeyData->data; - namekey.size = pubKeyData->len; - - /* encrypt the private key */ - rv = seckey_put_private_key(handle, &namekey, pwitem, privkey, nickname, - update, algorithm); - - return(rv); -} - -NSSLOWKEYPrivateKey * -seckey_decrypt_private_key(NSSLOWKEYEncryptedPrivateKeyInfo *epki, - SECItem *pwitem) -{ - NSSLOWKEYPrivateKey *pk = NULL; - NSSLOWKEYPrivateKeyInfo *pki = NULL; - SECStatus rv = SECFailure; - SECOidTag algorithm; - PLArenaPool *temparena = NULL, *permarena = NULL; - SECItem *salt = NULL, *dest = NULL, *key = NULL; - NSSPKCS5PBEParameter *param; -#ifdef NSS_ENABLE_ECC - ECPrivateKey *ecpriv; - SECItem *fordebug = NULL; - int i; -#endif - - if((epki == NULL) || (pwitem == NULL)) - goto loser; - - temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - permarena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if((temparena == NULL) || (permarena == NULL)) - goto loser; - - /* allocate temporary items */ - pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, - sizeof(NSSLOWKEYPrivateKeyInfo)); - - /* allocate permanent arena items */ - pk = (NSSLOWKEYPrivateKey *)PORT_ArenaZAlloc(permarena, - sizeof(NSSLOWKEYPrivateKey)); - - if((pk == NULL) || (pki == NULL)) - goto loser; - - pk->arena = permarena; - - algorithm = SECOID_GetAlgorithmTag(&(epki->algorithm)); - switch(algorithm) - { - case SEC_OID_RC4: - salt = SECITEM_DupItem(&epki->algorithm.parameters); - if(salt != NULL) - { - key = seckey_create_rc4_key(pwitem, salt); - if(key != NULL) - { - dest = seckey_rc4_decode(key, &epki->encryptedData); - } - } - if(salt != NULL) - SECITEM_ZfreeItem(salt, PR_TRUE); - if(key != NULL) - SECITEM_ZfreeItem(key, PR_TRUE); - break; - default: - /* we depend on the fact that if this key was encoded with - * DES, that the pw was also encoded with DES, so we don't have - * to do the update here, the password code will handle it. */ - param = nsspkcs5_AlgidToParam(&epki->algorithm); - if (param == NULL) { - break; - } - dest = nsspkcs5_CipherData(param, pwitem, &epki->encryptedData, - PR_FALSE, NULL); - nsspkcs5_DestroyPBEParameter(param); - break; - } - - if(dest != NULL) - { - SEC_PRINT("seckey_decrypt_private_key()", "PrivateKeyInfo", -1, - dest); - - rv = SEC_ASN1DecodeItem(temparena, pki, - nsslowkey_PrivateKeyInfoTemplate, dest); - if(rv == SECSuccess) - { - switch(SECOID_GetAlgorithmTag(&pki->algorithm)) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - pk->keyType = NSSLOWKEYRSAKey; - prepare_low_rsa_priv_key_for_asn1(pk); - rv = SEC_ASN1DecodeItem(permarena, pk, - nsslowkey_RSAPrivateKeyTemplate, - &pki->privateKey); - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - pk->keyType = NSSLOWKEYDSAKey; - prepare_low_dsa_priv_key_for_asn1(pk); - rv = SEC_ASN1DecodeItem(permarena, pk, - nsslowkey_DSAPrivateKeyTemplate, - &pki->privateKey); - if (rv != SECSuccess) - goto loser; - prepare_low_pqg_params_for_asn1(&pk->u.dsa.params); - rv = SEC_ASN1DecodeItem(permarena, &pk->u.dsa.params, - nsslowkey_PQGParamsTemplate, - &pki->algorithm.parameters); - break; - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - pk->keyType = NSSLOWKEYDHKey; - prepare_low_dh_priv_key_for_asn1(pk); - rv = SEC_ASN1DecodeItem(permarena, pk, - nsslowkey_DHPrivateKeyTemplate, - &pki->privateKey); - break; -#ifdef NSS_ENABLE_ECC - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - pk->keyType = NSSLOWKEYECKey; - prepare_low_ec_priv_key_for_asn1(pk); - - fordebug = &pki->privateKey; - SEC_PRINT("seckey_decrypt_private_key()", "PrivateKey", - pk->keyType, fordebug); - rv = SEC_ASN1DecodeItem(permarena, pk, - nsslowkey_ECPrivateKeyTemplate, - &pki->privateKey); - if (rv != SECSuccess) - goto loser; - - prepare_low_ecparams_for_asn1(&pk->u.ec.ecParams); - - rv = SECITEM_CopyItem(permarena, - &pk->u.ec.ecParams.DEREncoding, - &pki->algorithm.parameters); - - if (rv != SECSuccess) - goto loser; - - /* Fill out the rest of EC params */ - rv = EC_FillParams(permarena, &pk->u.ec.ecParams.DEREncoding, - &pk->u.ec.ecParams); - - /* - * NOTE: Encoding of the publicValue is optional - * so we need to be able to regenerate the publicValue - * from the base point and the private key. - * - * XXX This part of the code needs more testing. - */ - if (pk->u.ec.publicValue.len == 0) { - rv = EC_NewKeyFromSeed(&pk->u.ec.ecParams, - &ecpriv, pk->u.ec.privateValue.data, - pk->u.ec.privateValue.len); - if (rv == SECSuccess) { - SECITEM_CopyItem(permarena, &pk->u.ec.publicValue, - &(ecpriv->publicValue)); - PORT_FreeArena(ecpriv->ecParams.arena, PR_TRUE); - } - } else { - /* If publicValue was filled as part of DER decoding, - * change length in bits to length in bytes. - */ - pk->u.ec.publicValue.len >>= 3; - } - - break; -#endif /* NSS_ENABLE_ECC */ - default: - rv = SECFailure; - break; - } - } - else if(PORT_GetError() == SEC_ERROR_BAD_DER) - { - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - goto loser; - } - } - - /* let success fall through */ -loser: - if(temparena != NULL) - PORT_FreeArena(temparena, PR_TRUE); - if(dest != NULL) - SECITEM_ZfreeItem(dest, PR_TRUE); - - if(rv != SECSuccess) - { - if(permarena != NULL) - PORT_FreeArena(permarena, PR_TRUE); - pk = NULL; - } - - return pk; -} - -static NSSLOWKEYPrivateKey * -seckey_decode_encrypted_private_key(NSSLOWKEYDBKey *dbkey, SECItem *pwitem) -{ - NSSLOWKEYPrivateKey *pk = NULL; - NSSLOWKEYEncryptedPrivateKeyInfo *epki; - PLArenaPool *temparena = NULL; - SECStatus rv; - SECOidTag algorithm; - - if( ( dbkey == NULL ) || ( pwitem == NULL ) ) { - return NULL; - } - - temparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if(temparena == NULL) { - return NULL; - } - - epki = (NSSLOWKEYEncryptedPrivateKeyInfo *) - PORT_ArenaZAlloc(temparena, sizeof(NSSLOWKEYEncryptedPrivateKeyInfo)); - - if(epki == NULL) { - goto loser; - } - - rv = SEC_ASN1DecodeItem(temparena, epki, - nsslowkey_EncryptedPrivateKeyInfoTemplate, - &(dbkey->derPK)); - if(rv != SECSuccess) { - goto loser; - } - - algorithm = SECOID_GetAlgorithmTag(&(epki->algorithm)); - switch(algorithm) - { - case SEC_OID_RC4: - /* TNH - this code should derive the actual RC4 key from salt and - pwitem */ - rv = SECITEM_CopyItem(temparena, &(epki->algorithm.parameters), - &(dbkey->salt)); - break; - default: - break; - } - - pk = seckey_decrypt_private_key(epki, pwitem); - - /* let success fall through */ -loser: - - PORT_FreeArena(temparena, PR_TRUE); - return pk; -} - -NSSLOWKEYPrivateKey * -seckey_get_private_key(NSSLOWKEYDBHandle *keydb, DBT *index, char **nickname, - SECItem *pwitem) -{ - NSSLOWKEYDBKey *dbkey = NULL; - NSSLOWKEYPrivateKey *pk = NULL; - - if( ( keydb == NULL ) || ( index == NULL ) || ( pwitem == NULL ) ) { - return NULL; - } - - dbkey = get_dbkey(keydb, index); - if(dbkey == NULL) { - goto loser; - } - - if ( nickname ) { - if ( dbkey->nickname && ( dbkey->nickname[0] != 0 ) ) { - *nickname = PORT_Strdup(dbkey->nickname); - } else { - *nickname = NULL; - } - } - - pk = seckey_decode_encrypted_private_key(dbkey, pwitem); - - /* let success fall through */ -loser: - - if ( dbkey != NULL ) { - sec_destroy_dbkey(dbkey); - } - - return pk; -} - -/* - * used by pkcs11 to import keys into it's object format... In the future - * we really need a better way to tie in... - */ -NSSLOWKEYPrivateKey * -nsslowkey_DecryptKey(DBT *key, SECItem *pwitem, - NSSLOWKEYDBHandle *handle) { - return seckey_get_private_key(handle,key,NULL,pwitem); -} - -/* - * Find a key in the database, indexed by its public key modulus - * This is used to find keys that have been stored before their - * certificate arrives. Once the certificate arrives the key - * is looked up by the public modulus in the certificate, and the - * re-stored by its nickname. - */ -NSSLOWKEYPrivateKey * -nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus, - SECItem *pwitem) -{ - DBT namekey; - NSSLOWKEYPrivateKey *pk = NULL; - - if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return NULL; - } - - /* set up db key */ - namekey.data = modulus->data; - namekey.size = modulus->len; - - pk = seckey_get_private_key(handle, &namekey, NULL, pwitem); - - /* no need to free dbkey, since its on the stack, and the data it - * points to is owned by the database - */ - return(pk); -} - -char * -nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, - SECItem *modulus, SECItem *pwitem) -{ - DBT namekey; - NSSLOWKEYPrivateKey *pk = NULL; - char *nickname = NULL; - - if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return NULL; - } - - /* set up db key */ - namekey.data = modulus->data; - namekey.size = modulus->len; - - pk = seckey_get_private_key(handle, &namekey, &nickname, pwitem); - if (pk) { - nsslowkey_DestroyPrivateKey(pk); - } - - /* no need to free dbkey, since its on the stack, and the data it - * points to is owned by the database - */ - return(nickname); -} -/* ===== ENCODING ROUTINES ===== */ - -static SECStatus -encodePWCheckEntry(PLArenaPool *arena, SECItem *entry, SECOidTag alg, - SECItem *encCheck) -{ - SECOidData *oidData; - SECStatus rv; - - oidData = SECOID_FindOIDByTag(alg); - if ( oidData == NULL ) { - rv = SECFailure; - goto loser; - } - - entry->len = 1 + oidData->oid.len + encCheck->len; - if ( arena ) { - entry->data = (unsigned char *)PORT_ArenaAlloc(arena, entry->len); - } else { - entry->data = (unsigned char *)PORT_Alloc(entry->len); - } - - if ( entry->data == NULL ) { - goto loser; - } - - /* first length of oid */ - entry->data[0] = (unsigned char)oidData->oid.len; - /* next oid itself */ - PORT_Memcpy(&entry->data[1], oidData->oid.data, oidData->oid.len); - /* finally the encrypted check string */ - PORT_Memcpy(&entry->data[1+oidData->oid.len], encCheck->data, - encCheck->len); - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * Set up the password checker in the key database. - * This is done by encrypting a known plaintext with the user's key. - */ -SECStatus -nsslowkey_SetKeyDBPasswordAlg(NSSLOWKEYDBHandle *handle, - SECItem *pwitem, SECOidTag algorithm) -{ - DBT checkkey; - NSSPKCS5PBEParameter *param = NULL; - SECStatus rv = SECFailure; - NSSLOWKEYDBKey *dbkey = NULL; - PLArenaPool *arena; - SECItem *salt = NULL; - SECItem *dest = NULL, test_key; - - if (handle == NULL) { - return(SECFailure); - } - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - rv = SECFailure; - goto loser; - } - - dbkey = (NSSLOWKEYDBKey *)PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYDBKey)); - if ( dbkey == NULL ) { - rv = SECFailure; - goto loser; - } - - dbkey->arena = arena; - - /* encrypt key */ - checkkey.data = test_key.data = (unsigned char *)KEYDB_PW_CHECK_STRING; - checkkey.size = test_key.len = KEYDB_PW_CHECK_LEN; - - salt = seckey_create_rc4_salt(); - if(salt == NULL) { - rv = SECFailure; - goto loser; - } - - param = nsspkcs5_NewParam(algorithm, salt, 1); - if (param == NULL) { - rv = SECFailure; - goto loser; - } - - dest = nsspkcs5_CipherData(param, pwitem, &test_key, PR_TRUE, NULL); - if (dest == NULL) - { - rv = SECFailure; - goto loser; - } - - rv = SECITEM_CopyItem(arena, &dbkey->salt, salt); - if (rv == SECFailure) { - goto loser; - } - - rv = encodePWCheckEntry(arena, &dbkey->derPK, algorithm, dest); - - if ( rv != SECSuccess ) { - goto loser; - } - - rv = put_dbkey(handle, &checkkey, dbkey, PR_TRUE); - - /* let success fall through */ -loser: - if ( arena != NULL ) { - PORT_FreeArena(arena, PR_TRUE); - } - - if ( dest != NULL ) { - SECITEM_ZfreeItem(dest, PR_TRUE); - } - - if ( salt != NULL ) { - SECITEM_ZfreeItem(salt, PR_TRUE); - } - - if (param != NULL) { - nsspkcs5_DestroyPBEParameter(param); - } - - return(rv); -} - -static SECStatus -seckey_CheckKeyDB1Password(NSSLOWKEYDBHandle *handle, SECItem *pwitem) -{ - SECStatus rv = SECFailure; - keyList keylist; - keyNode *node = NULL; - NSSLOWKEYPrivateKey *privkey = NULL; - - - /* - * first find a key - */ - - /* traverse the database, collecting the keys of all records */ - keylist.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( keylist.arena == NULL ) - { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(SECFailure); - } - keylist.head = NULL; - - /* TNH - TraverseKeys should not be public, since it exposes - the underlying DBT data type. */ - rv = nsslowkey_TraverseKeys(handle, sec_add_key_to_list, (void *)&keylist); - if ( rv != SECSuccess ) - goto done; - - /* just get the first key from the list */ - node = keylist.head; - - /* no private keys, accept any password */ - if (node == NULL) { - rv = SECSuccess; - goto done; - } - privkey = seckey_get_private_key(handle, &node->key, NULL, pwitem); - if (privkey == NULL) { - rv = SECFailure; - goto done; - } - - /* if we can decrypt the private key, then we had the correct password */ - rv = SECSuccess; - nsslowkey_DestroyPrivateKey(privkey); - -done: - - /* free the arena */ - if ( keylist.arena ) { - PORT_FreeArena(keylist.arena, PR_FALSE); - } - - return(rv); -} - -/* - * check to see if the user has typed the right password - */ -SECStatus -nsslowkey_CheckKeyDBPassword(NSSLOWKEYDBHandle *handle, SECItem *pwitem) -{ - DBT checkkey; - DBT checkdata; - NSSPKCS5PBEParameter *param = NULL; - SECStatus rv = SECFailure; - NSSLOWKEYDBKey *dbkey = NULL; - SECItem *key = NULL; - SECItem *dest = NULL; - SECOidTag algorithm; - SECItem oid; - SECItem encstring; - PRBool update = PR_FALSE; - int ret; - - if (handle == NULL) { - goto loser; - } - - checkkey.data = KEYDB_PW_CHECK_STRING; - checkkey.size = KEYDB_PW_CHECK_LEN; - - dbkey = get_dbkey(handle, &checkkey); - - if ( dbkey == NULL ) { - checkkey.data = KEYDB_FAKE_PW_CHECK_STRING; - checkkey.size = KEYDB_FAKE_PW_CHECK_LEN; - ret = (* handle->db->get)(handle->db, &checkkey, - &checkdata, 0 ); - if (ret) { - goto loser; - } - /* if we have the fake PW_CHECK, then try to decode the key - * rather than the pwcheck item. - */ - rv = seckey_CheckKeyDB1Password(handle,pwitem); - if (rv == SECSuccess) { - /* OK we have enough to complete our conversion */ - nsslowkey_UpdateKeyDBPass2(handle,pwitem); - } - return rv; - } - - /* build the oid item */ - oid.len = dbkey->derPK.data[0]; - oid.data = &dbkey->derPK.data[1]; - - /* make sure entry is the correct length - * since we are probably using a block cipher, the block will be - * padded, so we may get a bit more than the exact size we need. - */ - if ( dbkey->derPK.len < (KEYDB_PW_CHECK_LEN + 1 + oid.len ) ) { - goto loser; - } - - /* find the algorithm tag */ - algorithm = SECOID_FindOIDTag(&oid); - - /* make a secitem of the encrypted check string */ - encstring.len = dbkey->derPK.len - ( oid.len + 1 ); - encstring.data = &dbkey->derPK.data[oid.len+1]; - encstring.type = 0; - - switch(algorithm) - { - case SEC_OID_RC4: - key = seckey_create_rc4_key(pwitem, &dbkey->salt); - if(key != NULL) { - dest = seckey_rc4_decode(key, &encstring); - SECITEM_FreeItem(key, PR_TRUE); - } - break; - default: - param = nsspkcs5_NewParam(algorithm, &dbkey->salt, 1); - if (param != NULL) { - /* Decrypt - this function implements a workaround for - * a previous coding error. It will decrypt values using - * DES rather than 3DES, if the initial try at 3DES - * decryption fails. In this case, the update flag is - * set to TRUE. This indication is used later to force - * an update of the database to "real" 3DES encryption. - */ - dest = nsspkcs5_CipherData(param, pwitem, - &encstring, PR_FALSE, &update); - nsspkcs5_DestroyPBEParameter(param); - } - break; - } - - if(dest == NULL) { - goto loser; - } - - if ((dest->len == KEYDB_PW_CHECK_LEN) && - (PORT_Memcmp(dest->data, - KEYDB_PW_CHECK_STRING, KEYDB_PW_CHECK_LEN) == 0)) { - rv = SECSuccess; - /* we succeeded */ - if ( algorithm == SEC_OID_RC4 ) { - /* partially updated database */ - nsslowkey_UpdateKeyDBPass2(handle, pwitem); - } - /* Force an update of the password to remove the incorrect DES - * encryption (see the note above) - */ - if (update && - (algorithm == SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC)) { - /* data base was encoded with DES not triple des, fix it */ - nsslowkey_UpdateKeyDBPass2(handle,pwitem); - } - } - -loser: - sec_destroy_dbkey(dbkey); - if(dest != NULL) { - SECITEM_ZfreeItem(dest, PR_TRUE); - } - - return(rv); -} - -/* - * Change the database password and/or algorithm. This internal - * routine does not check the old password. That must be done by - * the caller. - */ -static SECStatus -ChangeKeyDBPasswordAlg(NSSLOWKEYDBHandle *handle, - SECItem *oldpwitem, SECItem *newpwitem, - SECOidTag new_algorithm) -{ - SECStatus rv; - keyList keylist; - keyNode *node = NULL; - NSSLOWKEYPrivateKey *privkey = NULL; - char *nickname; - DBT newkey; - int ret; - - /* traverse the database, collecting the keys of all records */ - keylist.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( keylist.arena == NULL ) - { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(SECFailure); - } - keylist.head = NULL; - - rv = db_BeginTransaction(handle->db); - if (rv != SECSuccess) { - goto loser; - } - - /* TNH - TraverseKeys should not be public, since it exposes - the underlying DBT data type. */ - rv = nsslowkey_TraverseKeys(handle, sec_add_key_to_list, (void *)&keylist); - if ( rv != SECSuccess ) - goto loser; - - /* walk the list, re-encrypting each entry */ - node = keylist.head; - while ( node != NULL ) - { - privkey = seckey_get_private_key(handle, &node->key, &nickname, - oldpwitem); - - if (privkey == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - rv = SECFailure; - goto loser; - } - - /* delete the old record */ - ret = (* handle->db->del)(handle->db, &node->key, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - rv = SECFailure; - goto loser; - } - - /* get the public key, which we use as the database index */ - - switch (privkey->keyType) { - case NSSLOWKEYRSAKey: - newkey.data = privkey->u.rsa.modulus.data; - newkey.size = privkey->u.rsa.modulus.len; - break; - case NSSLOWKEYDSAKey: - newkey.data = privkey->u.dsa.publicValue.data; - newkey.size = privkey->u.dsa.publicValue.len; - break; - case NSSLOWKEYDHKey: - newkey.data = privkey->u.dh.publicValue.data; - newkey.size = privkey->u.dh.publicValue.len; - break; -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - newkey.data = privkey->u.ec.publicValue.data; - newkey.size = privkey->u.ec.publicValue.len; - break; -#endif /* NSS_ENABLE_ECC */ - default: - /* should we continue here and loose the key? */ - PORT_SetError(SEC_ERROR_BAD_DATABASE); - rv = SECFailure; - goto loser; - } - - rv = seckey_put_private_key(handle, &newkey, newpwitem, privkey, - nickname, PR_TRUE, new_algorithm); - - if ( rv != SECSuccess ) - { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - rv = SECFailure; - goto loser; - } - - /* next node */ - node = node->next; - } - - rv = nsslowkey_SetKeyDBPasswordAlg(handle, newpwitem, new_algorithm); - -loser: - - db_FinishTransaction(handle->db,rv != SECSuccess); - - /* free the arena */ - if ( keylist.arena ) { - PORT_FreeArena(keylist.arena, PR_FALSE); - } - - return(rv); -} - -/* - * Re-encrypt the entire key database with a new password. - * NOTE: The really should create a new database rather than doing it - * in place in the original - */ -SECStatus -nsslowkey_ChangeKeyDBPassword(NSSLOWKEYDBHandle *handle, - SECItem *oldpwitem, SECItem *newpwitem) -{ - SECStatus rv; - - if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - rv = SECFailure; - goto loser; - } - - rv = nsslowkey_CheckKeyDBPassword(handle, oldpwitem); - if ( rv != SECSuccess ) { - return(SECFailure); /* return rv? */ - } - - rv = ChangeKeyDBPasswordAlg(handle, oldpwitem, newpwitem, - nsslowkey_GetDefaultKeyDBAlg()); - -loser: - return(rv); -} - - -#define MAX_DB_SIZE 0xffff -/* - * Clear out all the keys in the existing database - */ -SECStatus -nsslowkey_ResetKeyDB(NSSLOWKEYDBHandle *handle) -{ - SECStatus rv; - int ret; - int errors = 0; - - if ( handle->db == NULL ) { - return(SECSuccess); - } - - if (handle->readOnly) { - /* set an error code */ - return SECFailure; - } - - if (handle->appname == NULL && handle->dbname == NULL) { - return SECFailure; - } - - (* handle->db->close)(handle->db); - if (handle->appname) { - handle->db= - rdbopen(handle->appname, handle->dbname, "key", NO_CREATE, NULL); - } else { - handle->db = dbopen( handle->dbname, NO_CREATE, 0600, DB_HASH, 0 ); - } - if (handle->db == NULL) { - /* set an error code */ - return SECFailure; - } - - rv = makeGlobalVersion(handle); - if ( rv != SECSuccess ) { - errors++; - goto done; - } - - if (handle->global_salt) { - rv = StoreKeyDBGlobalSalt(handle); - } else { - rv = makeGlobalSalt(handle); - if ( rv == SECSuccess ) { - handle->global_salt = GetKeyDBGlobalSalt(handle); - } - } - if ( rv != SECSuccess ) { - errors++; - } - -done: - /* sync the database */ - ret = (* handle->db->sync)(handle->db, 0); - db_InitComplete(handle->db); - - return (errors == 0 ? SECSuccess : SECFailure); -} diff --git a/security/nss/lib/softoken/keydbi.h b/security/nss/lib/softoken/keydbi.h deleted file mode 100644 index 583efcb8a..000000000 --- a/security/nss/lib/softoken/keydbi.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * private.h - Private data structures for the software token library - * - * 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. - * - * $Id$ - */ - -#ifndef _KEYDBI_H_ -#define _KEYDBI_H_ - -#include "nspr.h" -#include "seccomon.h" -#include "mcom_db.h" - -/* - * Handle structure for open key databases - */ -struct NSSLOWKEYDBHandleStr { - DB *db; - DB *updatedb; /* used when updating an old version */ - SECItem *global_salt; /* password hashing salt for this db */ - int version; /* version of the database */ - char *appname; /* multiaccess app name */ - char *dbname; /* name of the openned DB */ - PRBool readOnly; /* is the DB read only */ -}; - -/* -** Typedef for callback for traversing key database. -** "key" is the key used to index the data in the database (nickname) -** "data" is the key data -** "pdata" is the user's data -*/ -typedef SECStatus (* NSSLOWKEYTraverseKeysFunc)(DBT *key, DBT *data, void *pdata); - - -SEC_BEGIN_PROTOS - -/* -** Traverse the entire key database, and pass the nicknames and keys to a -** user supplied function. -** "f" is the user function to call for each key -** "udata" is the user's data, which is passed through to "f" -*/ -extern SECStatus nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, - NSSLOWKEYTraverseKeysFunc f, - void *udata); - -SEC_END_PROTOS - -#endif /* _KEYDBI_H_ */ diff --git a/security/nss/lib/softoken/lowcert.c b/security/nss/lib/softoken/lowcert.c deleted file mode 100644 index 1ef4021fb..000000000 --- a/security/nss/lib/softoken/lowcert.c +++ /dev/null @@ -1,625 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - */ - -/* - * Certificate handling code - * - * $Id$ - */ - -#include "seccomon.h" -#include "secder.h" -#include "nssilock.h" -#include "prmon.h" -#include "prtime.h" -#include "lowkeyi.h" -#include "pcert.h" -#include "secasn1.h" -#include "secoid.h" - -#ifdef NSS_ENABLE_ECC -extern SECStatus EC_FillParams(PRArenaPool *arena, - const SECItem *encodedParams, - ECParams *params); -#endif - -static const SEC_ASN1Template nsslowcert_SubjectPublicKeyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWCERTSubjectPublicKeyInfo) }, - { SEC_ASN1_INLINE, offsetof(NSSLOWCERTSubjectPublicKeyInfo,algorithm), - SECOID_AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, - offsetof(NSSLOWCERTSubjectPublicKeyInfo,subjectPublicKey), }, - { 0, } -}; - -static const SEC_ASN1Template nsslowcert_RSAPublicKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPublicKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.modulus), }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.publicExponent), }, - { 0, } -}; -static const SEC_ASN1Template nsslowcert_DSAPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dsa.publicValue), }, - { 0, } -}; -static const SEC_ASN1Template nsslowcert_DHPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dh.publicValue), }, - { 0, } -}; - -/* - * See bugzilla bug 125359 - * Since NSS (via PKCS#11) wants to handle big integers as unsigned ints, - * all of the templates above that en/decode into integers must be converted - * from ASN.1's signed integer type. This is done by marking either the - * source or destination (encoding or decoding, respectively) type as - * siUnsignedInteger. - */ - -static void -prepare_low_rsa_pub_key_for_asn1(NSSLOWKEYPublicKey *pubk) -{ - pubk->u.rsa.modulus.type = siUnsignedInteger; - pubk->u.rsa.publicExponent.type = siUnsignedInteger; -} - -static void -prepare_low_dsa_pub_key_for_asn1(NSSLOWKEYPublicKey *pubk) -{ - pubk->u.dsa.publicValue.type = siUnsignedInteger; - pubk->u.dsa.params.prime.type = siUnsignedInteger; - pubk->u.dsa.params.subPrime.type = siUnsignedInteger; - pubk->u.dsa.params.base.type = siUnsignedInteger; -} - -static void -prepare_low_dh_pub_key_for_asn1(NSSLOWKEYPublicKey *pubk) -{ - pubk->u.dh.prime.type = siUnsignedInteger; - pubk->u.dh.base.type = siUnsignedInteger; - pubk->u.dh.publicValue.type = siUnsignedInteger; -} - -/* - * Allow use of default cert database, so that apps(such as mozilla) don't - * have to pass the handle all over the place. - */ -static NSSLOWCERTCertDBHandle *default_pcert_db_handle = 0; - -void -nsslowcert_SetDefaultCertDB(NSSLOWCERTCertDBHandle *handle) -{ - default_pcert_db_handle = handle; - - return; -} - -NSSLOWCERTCertDBHandle * -nsslowcert_GetDefaultCertDB(void) -{ - return(default_pcert_db_handle); -} - -/* - * simple cert decoder to avoid the cost of asn1 engine - */ -static unsigned char * -nsslowcert_dataStart(unsigned char *buf, unsigned int length, - unsigned int *data_length, PRBool includeTag, - unsigned char* rettag) { - unsigned char tag; - unsigned int used_length= 0; - - tag = buf[used_length++]; - - if (rettag) { - *rettag = tag; - } - - /* blow out when we come to the end */ - if (tag == 0) { - return NULL; - } - - *data_length = buf[used_length++]; - - if (*data_length&0x80) { - int len_count = *data_length & 0x7f; - - *data_length = 0; - - while (len_count-- > 0) { - *data_length = (*data_length << 8) | buf[used_length++]; - } - } - - if (*data_length > (length-used_length) ) { - *data_length = length-used_length; - return NULL; - } - if (includeTag) *data_length += used_length; - - return (buf + (includeTag ? 0 : used_length)); -} - -static void SetTimeType(SECItem* item, unsigned char tagtype) -{ - switch (tagtype) { - case SEC_ASN1_UTC_TIME: - item->type = siUTCTime; - break; - - case SEC_ASN1_GENERALIZED_TIME: - item->type = siGeneralizedTime; - break; - - default: - PORT_Assert(0); - break; - } -} - -static int -nsslowcert_GetValidityFields(unsigned char *buf,int buf_length, - SECItem *notBefore, SECItem *notAfter) -{ - unsigned char tagtype; - notBefore->data = nsslowcert_dataStart(buf,buf_length, - ¬Before->len,PR_FALSE, &tagtype); - if (notBefore->data == NULL) return SECFailure; - SetTimeType(notBefore, tagtype); - buf_length -= (notBefore->data-buf) + notBefore->len; - buf = notBefore->data + notBefore->len; - notAfter->data = nsslowcert_dataStart(buf,buf_length, - ¬After->len,PR_FALSE, &tagtype); - if (notAfter->data == NULL) return SECFailure; - SetTimeType(notAfter, tagtype); - return SECSuccess; -} - -static int -nsslowcert_GetCertFields(unsigned char *cert,int cert_length, - SECItem *issuer, SECItem *serial, SECItem *derSN, SECItem *subject, - SECItem *valid, SECItem *subjkey) -{ - unsigned char *buf; - unsigned int buf_length; - unsigned char *dummy; - unsigned int dummylen; - - /* get past the signature wrap */ - buf = nsslowcert_dataStart(cert,cert_length,&buf_length,PR_FALSE, NULL); - if (buf == NULL) return SECFailure; - /* get into the raw cert data */ - buf = nsslowcert_dataStart(buf,buf_length,&buf_length,PR_FALSE, NULL); - if (buf == NULL) return SECFailure; - /* skip past any optional version number */ - if ((buf[0] & 0xa0) == 0xa0) { - dummy = nsslowcert_dataStart(buf,buf_length,&dummylen,PR_FALSE, NULL); - if (dummy == NULL) return SECFailure; - buf_length -= (dummy-buf) + dummylen; - buf = dummy + dummylen; - } - /* serial number */ - if (derSN) { - derSN->data=nsslowcert_dataStart(buf,buf_length,&derSN->len,PR_TRUE, NULL); - } - serial->data = nsslowcert_dataStart(buf,buf_length,&serial->len,PR_FALSE, NULL); - if (serial->data == NULL) return SECFailure; - buf_length -= (serial->data-buf) + serial->len; - buf = serial->data + serial->len; - /* skip the OID */ - dummy = nsslowcert_dataStart(buf,buf_length,&dummylen,PR_FALSE, NULL); - if (dummy == NULL) return SECFailure; - buf_length -= (dummy-buf) + dummylen; - buf = dummy + dummylen; - /* issuer */ - issuer->data = nsslowcert_dataStart(buf,buf_length,&issuer->len,PR_TRUE, NULL); - if (issuer->data == NULL) return SECFailure; - buf_length -= (issuer->data-buf) + issuer->len; - buf = issuer->data + issuer->len; - - /* only wanted issuer/SN */ - if (valid == NULL) { - return SECSuccess; - } - /* validity */ - valid->data = nsslowcert_dataStart(buf,buf_length,&valid->len,PR_FALSE, NULL); - if (valid->data == NULL) return SECFailure; - buf_length -= (valid->data-buf) + valid->len; - buf = valid->data + valid->len; - /*subject */ - subject->data=nsslowcert_dataStart(buf,buf_length,&subject->len,PR_TRUE, NULL); - if (subject->data == NULL) return SECFailure; - buf_length -= (subject->data-buf) + subject->len; - buf = subject->data + subject->len; - /* subject key info */ - subjkey->data=nsslowcert_dataStart(buf,buf_length,&subjkey->len,PR_TRUE, NULL); - if (subjkey->data == NULL) return SECFailure; - buf_length -= (subjkey->data-buf) + subjkey->len; - buf = subjkey->data + subjkey->len; - return SECSuccess; -} - -SECStatus -nsslowcert_GetCertTimes(NSSLOWCERTCertificate *c, PRTime *notBefore, PRTime *notAfter) -{ - int rv; - NSSLOWCERTValidity validity; - - rv = nsslowcert_GetValidityFields(c->validity.data,c->validity.len, - &validity.notBefore,&validity.notAfter); - if (rv != SECSuccess) { - return rv; - } - - /* convert DER not-before time */ - rv = CERT_DecodeTimeChoice(notBefore, &validity.notBefore); - if (rv) { - return(SECFailure); - } - - /* convert DER not-after time */ - rv = CERT_DecodeTimeChoice(notAfter, &validity.notAfter); - if (rv) { - return(SECFailure); - } - - return(SECSuccess); -} - -/* - * is certa newer than certb? If one is expired, pick the other one. - */ -PRBool -nsslowcert_IsNewer(NSSLOWCERTCertificate *certa, NSSLOWCERTCertificate *certb) -{ - PRTime notBeforeA, notAfterA, notBeforeB, notAfterB, now; - SECStatus rv; - PRBool newerbefore, newerafter; - - rv = nsslowcert_GetCertTimes(certa, ¬BeforeA, ¬AfterA); - if ( rv != SECSuccess ) { - return(PR_FALSE); - } - - rv = nsslowcert_GetCertTimes(certb, ¬BeforeB, ¬AfterB); - if ( rv != SECSuccess ) { - return(PR_TRUE); - } - - newerbefore = PR_FALSE; - if ( LL_CMP(notBeforeA, >, notBeforeB) ) { - newerbefore = PR_TRUE; - } - - newerafter = PR_FALSE; - if ( LL_CMP(notAfterA, >, notAfterB) ) { - newerafter = PR_TRUE; - } - - if ( newerbefore && newerafter ) { - return(PR_TRUE); - } - - if ( ( !newerbefore ) && ( !newerafter ) ) { - return(PR_FALSE); - } - - /* get current time */ - now = PR_Now(); - - if ( newerbefore ) { - /* cert A was issued after cert B, but expires sooner */ - /* if A is expired, then pick B */ - if ( LL_CMP(notAfterA, <, now ) ) { - return(PR_FALSE); - } - return(PR_TRUE); - } else { - /* cert B was issued after cert A, but expires sooner */ - /* if B is expired, then pick A */ - if ( LL_CMP(notAfterB, <, now ) ) { - return(PR_TRUE); - } - return(PR_FALSE); - } -} - -#define SOFT_DEFAULT_CHUNKSIZE 2048 - - -static SECStatus -nsslowcert_KeyFromIssuerAndSN(PRArenaPool *arena, SECItem *issuer, SECItem *sn, - SECItem *key) -{ - unsigned int len = sn->len + issuer->len; - - - if (arena) { - key->data = (unsigned char*)PORT_ArenaAlloc(arena, len); - } else { - if (len > key->len) { - key->data = (unsigned char*)PORT_ArenaAlloc(arena, len); - } - } - if ( !key->data ) { - goto loser; - } - - key->len = len; - /* copy the serialNumber */ - PORT_Memcpy(key->data, sn->data, sn->len); - - /* copy the issuer */ - PORT_Memcpy(&key->data[sn->len], issuer->data, issuer->len); - - return(SECSuccess); - -loser: - return(SECFailure); -} - - - -/* - * take a DER certificate and decode it into a certificate structure - */ -NSSLOWCERTCertificate * -nsslowcert_DecodeDERCertificate(SECItem *derSignedCert, char *nickname) -{ - NSSLOWCERTCertificate *cert; - int rv; - - /* allocate the certificate structure */ - cert = nsslowcert_CreateCert(); - - if ( !cert ) { - goto loser; - } - - /* point to passed in DER data */ - cert->derCert = *derSignedCert; - cert->nickname = NULL; - cert->certKey.data = NULL; - cert->referenceCount = 1; - - /* decode the certificate info */ - rv = nsslowcert_GetCertFields(cert->derCert.data, cert->derCert.len, - &cert->derIssuer, &cert->serialNumber, &cert->derSN, &cert->derSubject, - &cert->validity, &cert->derSubjKeyInfo); - - /* cert->subjectKeyID; x509v3 subject key identifier */ - cert->subjectKeyID.data = NULL; - cert->subjectKeyID.len = 0; - cert->dbEntry = NULL; - cert ->trust = NULL; - - /* generate and save the database key for the cert */ - cert->certKey.data = cert->certKeySpace; - cert->certKey.len = sizeof(cert->certKeySpace); - rv = nsslowcert_KeyFromIssuerAndSN(NULL, &cert->derIssuer, - &cert->serialNumber, &cert->certKey); - if ( rv ) { - goto loser; - } - - /* set the nickname */ - if ( nickname == NULL ) { - cert->nickname = NULL; - } else { - /* copy and install the nickname */ - cert->nickname = pkcs11_copyNickname(nickname,cert->nicknameSpace, - sizeof(cert->nicknameSpace)); - } - -#ifdef FIXME - /* initialize the subjectKeyID */ - rv = cert_GetKeyID(cert); - if ( rv != SECSuccess ) { - goto loser; - } - - /* set the email address */ - cert->emailAddr = CERT_GetCertificateEmailAddress(cert); - -#endif - - cert->referenceCount = 1; - - return(cert); - -loser: - if (cert) { - nsslowcert_DestroyCertificate(cert); - } - - return(0); -} - -char * -nsslowcert_FixupEmailAddr(char *emailAddr) -{ - char *retaddr; - char *str; - - if ( emailAddr == NULL ) { - return(NULL); - } - - /* copy the string */ - str = retaddr = PORT_Strdup(emailAddr); - if ( str == NULL ) { - return(NULL); - } - - /* make it lower case */ - while ( *str ) { - *str = tolower( *str ); - str++; - } - - return(retaddr); -} - - -/* - * Generate a database key, based on serial number and issuer, from a - * DER certificate. - */ -SECStatus -nsslowcert_KeyFromDERCert(PRArenaPool *arena, SECItem *derCert, SECItem *key) -{ - int rv; - NSSLOWCERTCertKey certkey; - - PORT_Memset(&certkey, 0, sizeof(NSSLOWCERTCertKey)); - - rv = nsslowcert_GetCertFields(derCert->data, derCert->len, - &certkey.derIssuer, &certkey.serialNumber, NULL, NULL, NULL, NULL); - - if ( rv ) { - goto loser; - } - - return(nsslowcert_KeyFromIssuerAndSN(arena, &certkey.derIssuer, - &certkey.serialNumber, key)); -loser: - return(SECFailure); -} - -NSSLOWKEYPublicKey * -nsslowcert_ExtractPublicKey(NSSLOWCERTCertificate *cert) -{ - NSSLOWCERTSubjectPublicKeyInfo spki; - NSSLOWKEYPublicKey *pubk; - SECItem os; - SECStatus rv; - PRArenaPool *arena; - SECOidTag tag; - SECItem newDerSubjKeyInfo; - - arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) - return NULL; - - pubk = (NSSLOWKEYPublicKey *) - PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYPublicKey)); - if (pubk == NULL) { - PORT_FreeArena (arena, PR_FALSE); - return NULL; - } - - pubk->arena = arena; - PORT_Memset(&spki,0,sizeof(spki)); - - /* copy the DER into the arena, since Quick DER returns data that points - into the DER input, which may get freed by the caller */ - rv = SECITEM_CopyItem(arena, &newDerSubjKeyInfo, &cert->derSubjKeyInfo); - if ( rv != SECSuccess ) { - PORT_FreeArena (arena, PR_FALSE); - return NULL; - } - - /* we haven't bothered decoding the spki struct yet, do it now */ - rv = SEC_QuickDERDecodeItem(arena, &spki, - nsslowcert_SubjectPublicKeyInfoTemplate, &newDerSubjKeyInfo); - if (rv != SECSuccess) { - PORT_FreeArena (arena, PR_FALSE); - return NULL; - } - - /* Convert bit string length from bits to bytes */ - os = spki.subjectPublicKey; - DER_ConvertBitString (&os); - - tag = SECOID_GetAlgorithmTag(&spki.algorithm); - switch ( tag ) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - pubk->keyType = NSSLOWKEYRSAKey; - prepare_low_rsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, - nsslowcert_RSAPublicKeyTemplate, &os); - if (rv == SECSuccess) - return pubk; - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - pubk->keyType = NSSLOWKEYDSAKey; - prepare_low_dsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, - nsslowcert_DSAPublicKeyTemplate, &os); - if (rv == SECSuccess) return pubk; - break; - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - pubk->keyType = NSSLOWKEYDHKey; - prepare_low_dh_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, - nsslowcert_DHPublicKeyTemplate, &os); - if (rv == SECSuccess) return pubk; - break; -#ifdef NSS_ENABLE_ECC - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - pubk->keyType = NSSLOWKEYECKey; - /* Since PKCS#11 directly takes the DER encoding of EC params - * and public value, we don't need any decoding here. - */ - rv = SECITEM_CopyItem(arena, &pubk->u.ec.ecParams.DEREncoding, - &spki.algorithm.parameters); - if ( rv != SECSuccess ) - break; - - /* Fill out the rest of the ecParams structure - * based on the encoded params - */ - if (EC_FillParams(arena, &pubk->u.ec.ecParams.DEREncoding, - &pubk->u.ec.ecParams) != SECSuccess) - break; - - rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, &os); - if (rv == SECSuccess) return pubk; - break; -#endif /* NSS_ENABLE_ECC */ - default: - rv = SECFailure; - break; - } - - nsslowkey_DestroyPublicKey (pubk); - return NULL; -} - diff --git a/security/nss/lib/softoken/lowkey.c b/security/nss/lib/softoken/lowkey.c deleted file mode 100644 index 0b36b6e4a..000000000 --- a/security/nss/lib/softoken/lowkey.c +++ /dev/null @@ -1,492 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - */ -#include "lowkeyi.h" -#include "secoid.h" -#include "secitem.h" -#include "secder.h" -#include "base64.h" -#include "secasn1.h" -#include "pcert.h" -#include "secerr.h" - -#ifdef NSS_ENABLE_ECC -extern SECStatus EC_CopyParams(PRArenaPool *arena, - ECParams *dstParams, - const ECParams *srcParams); -#endif - -const SEC_ASN1Template nsslowkey_PQGParamsTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PQGParams) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,prime) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,base) }, - { 0, } -}; - -const SEC_ASN1Template nsslowkey_RSAPrivateKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.version) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.modulus) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.publicExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.privateExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.coefficient) }, - { 0 } -}; - - -const SEC_ASN1Template nsslowkey_DSAPrivateKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.publicValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.privateValue) }, - { 0, } -}; - -const SEC_ASN1Template nsslowkey_DSAPrivateKeyExportTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.privateValue) }, -}; - -const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.publicValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.privateValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.base) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.prime) }, - { 0, } -}; - -#ifdef NSS_ENABLE_ECC - -/* XXX This is just a placeholder for later when we support - * generic curves and need full-blown support for parsing EC - * parameters. For now, we only support named curves in which - * EC params are simply encoded as an object ID and we don't - * use nsslowkey_ECParamsTemplate. - */ -const SEC_ASN1Template nsslowkey_ECParamsTemplate[] = { - { SEC_ASN1_CHOICE, offsetof(ECParams,type), NULL, sizeof(ECParams) }, - { SEC_ASN1_OBJECT_ID, offsetof(ECParams,curveOID), NULL, ec_params_named }, - { 0, } -}; - - -/* NOTE: The SECG specification allows the private key structure - * to contain curve parameters but recommends that they be stored - * in the PrivateKeyAlgorithmIdentifier field of the PrivateKeyInfo - * instead. - */ -const SEC_ASN1Template nsslowkey_ECPrivateKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.ec.version) }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYPrivateKey,u.ec.privateValue) }, - /* XXX The following template works for now since we only - * support named curves for which the parameters are - * encoded as an object ID. When we support generic curves, - * we'll need to define nsslowkey_ECParamsTemplate - */ -#if 1 - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSLOWKEYPrivateKey,u.ec.ecParams.curveOID), - SEC_ObjectIDTemplate }, -#else - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSLOWKEYPrivateKey,u.ec.ecParams), - nsslowkey_ECParamsTemplate }, -#endif - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(NSSLOWKEYPrivateKey,u.ec.publicValue), - SEC_BitStringTemplate }, - { 0, } -}; -#endif /* NSS_ENABLE_ECC */ -/* - * See bugzilla bug 125359 - * Since NSS (via PKCS#11) wants to handle big integers as unsigned ints, - * all of the templates above that en/decode into integers must be converted - * from ASN.1's signed integer type. This is done by marking either the - * source or destination (encoding or decoding, respectively) type as - * siUnsignedInteger. - */ - -void -prepare_low_rsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key) -{ - key->u.rsa.modulus.type = siUnsignedInteger; - key->u.rsa.publicExponent.type = siUnsignedInteger; - key->u.rsa.privateExponent.type = siUnsignedInteger; - key->u.rsa.prime1.type = siUnsignedInteger; - key->u.rsa.prime2.type = siUnsignedInteger; - key->u.rsa.exponent1.type = siUnsignedInteger; - key->u.rsa.exponent2.type = siUnsignedInteger; - key->u.rsa.coefficient.type = siUnsignedInteger; -} - -void -prepare_low_pqg_params_for_asn1(PQGParams *params) -{ - params->prime.type = siUnsignedInteger; - params->subPrime.type = siUnsignedInteger; - params->base.type = siUnsignedInteger; -} - -void -prepare_low_dsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key) -{ - key->u.dsa.publicValue.type = siUnsignedInteger; - key->u.dsa.privateValue.type = siUnsignedInteger; - key->u.dsa.params.prime.type = siUnsignedInteger; - key->u.dsa.params.subPrime.type = siUnsignedInteger; - key->u.dsa.params.base.type = siUnsignedInteger; -} - -void -prepare_low_dsa_priv_key_export_for_asn1(NSSLOWKEYPrivateKey *key) -{ - key->u.dsa.privateValue.type = siUnsignedInteger; -} - -void -prepare_low_dh_priv_key_for_asn1(NSSLOWKEYPrivateKey *key) -{ - key->u.dh.prime.type = siUnsignedInteger; - key->u.dh.base.type = siUnsignedInteger; - key->u.dh.publicValue.type = siUnsignedInteger; - key->u.dh.privateValue.type = siUnsignedInteger; -} - -#ifdef NSS_ENABLE_ECC -void -prepare_low_ecparams_for_asn1(ECParams *params) -{ - params->DEREncoding.type = siUnsignedInteger; - params->curveOID.type = siUnsignedInteger; -} - -void -prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key) -{ - key->u.ec.version.type = siUnsignedInteger; - key->u.ec.ecParams.DEREncoding.type = siUnsignedInteger; - key->u.ec.ecParams.curveOID.type = siUnsignedInteger; - key->u.ec.privateValue.type = siUnsignedInteger; - key->u.ec.publicValue.type = siUnsignedInteger; -} -#endif /* NSS_ENABLE_ECC */ - -void -nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *privk) -{ - if (privk && privk->arena) { - PORT_FreeArena(privk->arena, PR_TRUE); - } -} - -void -nsslowkey_DestroyPublicKey(NSSLOWKEYPublicKey *pubk) -{ - if (pubk && pubk->arena) { - PORT_FreeArena(pubk->arena, PR_FALSE); - } -} -unsigned -nsslowkey_PublicModulusLen(NSSLOWKEYPublicKey *pubk) -{ - unsigned char b0; - - /* interpret modulus length as key strength... in - * fortezza that's the public key length */ - - switch (pubk->keyType) { - case NSSLOWKEYRSAKey: - b0 = pubk->u.rsa.modulus.data[0]; - return b0 ? pubk->u.rsa.modulus.len : pubk->u.rsa.modulus.len - 1; - default: - break; - } - return 0; -} - -unsigned -nsslowkey_PrivateModulusLen(NSSLOWKEYPrivateKey *privk) -{ - - unsigned char b0; - - switch (privk->keyType) { - case NSSLOWKEYRSAKey: - b0 = privk->u.rsa.modulus.data[0]; - return b0 ? privk->u.rsa.modulus.len : privk->u.rsa.modulus.len - 1; - default: - break; - } - return 0; -} - -NSSLOWKEYPublicKey * -nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privk) -{ - NSSLOWKEYPublicKey *pubk; - PLArenaPool *arena; - - - arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; - } - - switch(privk->keyType) { - case NSSLOWKEYRSAKey: - case NSSLOWKEYNullKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof (NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - if (privk->keyType == NSSLOWKEYNullKey) return pubk; - rv = SECITEM_CopyItem(arena, &pubk->u.rsa.modulus, - &privk->u.rsa.modulus); - if (rv == SECSuccess) { - rv = SECITEM_CopyItem (arena, &pubk->u.rsa.publicExponent, - &privk->u.rsa.publicExponent); - if (rv == SECSuccess) - return pubk; - } - nsslowkey_DestroyPublicKey (pubk); - } else { - PORT_SetError (SEC_ERROR_NO_MEMORY); - } - break; - case NSSLOWKEYDSAKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.publicValue, - &privk->u.dsa.publicValue); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.prime, - &privk->u.dsa.params.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.subPrime, - &privk->u.dsa.params.subPrime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.base, - &privk->u.dsa.params.base); - if (rv == SECSuccess) return pubk; - } - break; - case NSSLOWKEYDHKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.publicValue, - &privk->u.dh.publicValue); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.prime, - &privk->u.dh.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.base, - &privk->u.dh.base); - if (rv == SECSuccess) return pubk; - } - break; -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, - &privk->u.ec.publicValue); - if (rv != SECSuccess) break; - pubk->u.ec.ecParams.arena = arena; - /* Copy the rest of the params */ - rv = EC_CopyParams(arena, &(pubk->u.ec.ecParams), - &(privk->u.ec.ecParams)); - if (rv == SECSuccess) return pubk; - } - break; -#endif /* NSS_ENABLE_ECC */ - /* No Fortezza in Low Key implementations (Fortezza keys aren't - * stored in our data base */ - default: - break; - } - - PORT_FreeArena (arena, PR_FALSE); - return NULL; -} - -NSSLOWKEYPrivateKey * -nsslowkey_CopyPrivateKey(NSSLOWKEYPrivateKey *privKey) -{ - NSSLOWKEYPrivateKey *returnKey = NULL; - SECStatus rv = SECFailure; - PLArenaPool *poolp; - - if(!privKey) { - return NULL; - } - - poolp = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if(!poolp) { - return NULL; - } - - returnKey = (NSSLOWKEYPrivateKey*)PORT_ArenaZAlloc(poolp, sizeof(NSSLOWKEYPrivateKey)); - if(!returnKey) { - rv = SECFailure; - goto loser; - } - - returnKey->keyType = privKey->keyType; - returnKey->arena = poolp; - - switch(privKey->keyType) { - case NSSLOWKEYRSAKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.modulus), - &(privKey->u.rsa.modulus)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.version), - &(privKey->u.rsa.version)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.publicExponent), - &(privKey->u.rsa.publicExponent)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.privateExponent), - &(privKey->u.rsa.privateExponent)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.prime1), - &(privKey->u.rsa.prime1)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.prime2), - &(privKey->u.rsa.prime2)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.exponent1), - &(privKey->u.rsa.exponent1)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.exponent2), - &(privKey->u.rsa.exponent2)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.coefficient), - &(privKey->u.rsa.coefficient)); - if(rv != SECSuccess) break; - break; - case NSSLOWKEYDSAKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.publicValue), - &(privKey->u.dsa.publicValue)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.privateValue), - &(privKey->u.dsa.privateValue)); - if(rv != SECSuccess) break; - returnKey->u.dsa.params.arena = poolp; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.prime), - &(privKey->u.dsa.params.prime)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.subPrime), - &(privKey->u.dsa.params.subPrime)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.base), - &(privKey->u.dsa.params.base)); - if(rv != SECSuccess) break; - break; - case NSSLOWKEYDHKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.publicValue), - &(privKey->u.dh.publicValue)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.privateValue), - &(privKey->u.dh.privateValue)); - if(rv != SECSuccess) break; - returnKey->u.dsa.params.arena = poolp; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.prime), - &(privKey->u.dh.prime)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.base), - &(privKey->u.dh.base)); - if(rv != SECSuccess) break; - break; -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.version), - &(privKey->u.ec.version)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.publicValue), - &(privKey->u.ec.publicValue)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.privateValue), - &(privKey->u.ec.privateValue)); - if(rv != SECSuccess) break; - returnKey->u.ec.ecParams.arena = poolp; - /* Copy the rest of the params */ - rv = EC_CopyParams(poolp, &(returnKey->u.ec.ecParams), - &(privKey->u.ec.ecParams)); - if (rv != SECSuccess) break; - break; -#endif /* NSS_ENABLE_ECC */ - default: - rv = SECFailure; - } - -loser: - - if(rv != SECSuccess) { - PORT_FreeArena(poolp, PR_TRUE); - returnKey = NULL; - } - - return returnKey; -} diff --git a/security/nss/lib/softoken/lowkeyi.h b/security/nss/lib/softoken/lowkeyi.h deleted file mode 100644 index 870ccf4d1..000000000 --- a/security/nss/lib/softoken/lowkeyi.h +++ /dev/null @@ -1,277 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - * - * key.h - public data structures and prototypes for the private key library - * - * $Id$ - */ - -#ifndef _LOWKEYI_H_ -#define _LOWKEYI_H_ - -#include "prtypes.h" -#include "seccomon.h" -#include "secoidt.h" -#include "pcertt.h" -#include "lowkeyti.h" - -SEC_BEGIN_PROTOS - -/* - * See bugzilla bug 125359 - * Since NSS (via PKCS#11) wants to handle big integers as unsigned ints, - * all of the templates above that en/decode into integers must be converted - * from ASN.1's signed integer type. This is done by marking either the - * source or destination (encoding or decoding, respectively) type as - * siUnsignedInteger. - */ -extern void prepare_low_rsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key); -extern void prepare_low_pqg_params_for_asn1(PQGParams *params); -extern void prepare_low_dsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key); -extern void prepare_low_dsa_priv_key_export_for_asn1(NSSLOWKEYPrivateKey *key); -extern void prepare_low_dh_priv_key_for_asn1(NSSLOWKEYPrivateKey *key); -#ifdef NSS_ENABLE_ECC -extern void prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key); -extern void prepare_low_ecparams_for_asn1(ECParams *params); -#endif /* NSS_ENABLE_ECC */ - -typedef char * (* NSSLOWKEYDBNameFunc)(void *arg, int dbVersion); - -/* -** Open a key database. -*/ -extern NSSLOWKEYDBHandle *nsslowkey_OpenKeyDB(PRBool readOnly, - const char *domain, - const char *prefix, - NSSLOWKEYDBNameFunc namecb, - void *cbarg); - - -/* - * Clear out all the keys in the existing database - */ -extern SECStatus nsslowkey_ResetKeyDB(NSSLOWKEYDBHandle *handle); - -/* -** Close the specified key database. -*/ -extern void nsslowkey_CloseKeyDB(NSSLOWKEYDBHandle *handle); - -/* - * Get the version number of the database - */ -extern int nsslowkey_GetKeyDBVersion(NSSLOWKEYDBHandle *handle); - -/* -** Support a default key database. -*/ -extern void nsslowkey_SetDefaultKeyDB(NSSLOWKEYDBHandle *handle); -extern NSSLOWKEYDBHandle *nsslowkey_GetDefaultKeyDB(void); - -/* set the alg id of the key encryption algorithm */ -extern void nsslowkey_SetDefaultKeyDBAlg(SECOidTag alg); - -/* - * given a password and salt, produce a hash of the password - */ -extern SECItem *nsslowkey_HashPassword(char *pw, SECItem *salt); - -/* - * Derive the actual password value for a key database from the - * password string value. The derivation uses global salt value - * stored in the key database. - */ -extern SECItem * -nsslowkey_DeriveKeyDBPassword(NSSLOWKEYDBHandle *handle, char *pw); - -/* -** Delete a key from the database -*/ -extern SECStatus nsslowkey_DeleteKey(NSSLOWKEYDBHandle *handle, - SECItem *pubkey); - -/* -** Store a key in the database, indexed by its public key modulus. -** "pk" is the private key to store -** "f" is a the callback function for getting the password -** "arg" is the argument for the callback -*/ -extern SECStatus nsslowkey_StoreKeyByPublicKey(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *pk, - SECItem *pubKeyData, - char *nickname, - SECItem *arg); - -/* does the key for this cert exist in the database filed by modulus */ -extern PRBool nsslowkey_KeyForCertExists(NSSLOWKEYDBHandle *handle, - NSSLOWCERTCertificate *cert); -/* does a key with this ID already exist? */ -extern PRBool nsslowkey_KeyForIDExists(NSSLOWKEYDBHandle *handle, SECItem *id); - - -extern SECStatus nsslowkey_HasKeyDBPassword(NSSLOWKEYDBHandle *handle); -extern SECStatus nsslowkey_SetKeyDBPassword(NSSLOWKEYDBHandle *handle, - SECItem *pwitem); -extern SECStatus nsslowkey_CheckKeyDBPassword(NSSLOWKEYDBHandle *handle, - SECItem *pwitem); -extern SECStatus nsslowkey_ChangeKeyDBPassword(NSSLOWKEYDBHandle *handle, - SECItem *oldpwitem, - SECItem *newpwitem); - -/* -** Destroy a private key object. -** "key" the object -** "freeit" if PR_TRUE then free the object as well as its sub-objects -*/ -extern void nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *key); - -/* -** Destroy a public key object. -** "key" the object -** "freeit" if PR_TRUE then free the object as well as its sub-objects -*/ -extern void nsslowkey_DestroyPublicKey(NSSLOWKEYPublicKey *key); - -/* -** Return the modulus length of "pubKey". -*/ -extern unsigned int nsslowkey_PublicModulusLen(NSSLOWKEYPublicKey *pubKey); - - -/* -** Return the modulus length of "privKey". -*/ -extern unsigned int nsslowkey_PrivateModulusLen(NSSLOWKEYPrivateKey *privKey); - - -/* -** Convert a low private key "privateKey" into a public low key -*/ -extern NSSLOWKEYPublicKey - *nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privateKey); - -/* - * Set the Key Database password. - * handle is a handle to the key database - * pwitem is the new password - * algorithm is the algorithm by which the key database - * password is to be encrypted. - * On failure, SECFailure is returned, otherwise SECSuccess is - * returned. - */ -extern SECStatus -nsslowkey_SetKeyDBPasswordAlg(NSSLOWKEYDBHandle *handle, - SECItem *pwitem, - SECOidTag algorithm); - -/* Check the key database password. - * handle is a handle to the key database - * pwitem is the suspect password - * algorithm is the algorithm by which the key database - * password is to be encrypted. - * The password is checked against plaintext to see if it is the - * actual password. If it is not, SECFailure is returned. - */ -extern SECStatus -nsslowkey_CheckKeyDBPasswordAlg(NSSLOWKEYDBHandle *handle, - SECItem *pwitem, - SECOidTag algorithm); - -/* Change the key database password and/or algorithm by which - * the password is stored with. - * handle is a handle to the key database - * old_pwitem is the current password - * new_pwitem is the new password - * old_algorithm is the algorithm by which the key database - * password is currently encrypted. - * new_algorithm is the algorithm with which the new password - * is to be encrypted. - * A return of anything but SECSuccess indicates failure. - */ -extern SECStatus -nsslowkey_ChangeKeyDBPasswordAlg(NSSLOWKEYDBHandle *handle, - SECItem *oldpwitem, SECItem *newpwitem, - SECOidTag old_algorithm); - -SECStatus -nsslowkey_UpdateNickname(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SECItem *arg); - -/* Store key by modulus and specify an encryption algorithm to use. - * handle is the pointer to the key database, - * privkey is the private key to be stored, - * f and arg are the function and arguments to the callback - * to get a password, - * algorithm is the algorithm which the privKey is to be stored. - * A return of anything but SECSuccess indicates failure. - */ -extern SECStatus -nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SECItem *arg, - SECOidTag algorithm, - PRBool update); - -/* Find key by modulus. This function is the inverse of store key - * by modulus. An attempt to locate the key with "modulus" is - * performed. If the key is found, the private key is returned, - * else NULL is returned. - * modulus is the modulus to locate - */ -extern NSSLOWKEYPrivateKey * -nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus, - SECItem *arg); - -extern char * -nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, - SECItem *modulus, SECItem *pwitem); - - -/* Make a copy of a low private key in it's own arena. - * a return of NULL indicates an error. - */ -extern NSSLOWKEYPrivateKey * -nsslowkey_CopyPrivateKey(NSSLOWKEYPrivateKey *privKey); - - -SEC_END_PROTOS - -#endif /* _LOWKEYI_H_ */ diff --git a/security/nss/lib/softoken/lowkeyti.h b/security/nss/lib/softoken/lowkeyti.h deleted file mode 100644 index 933ad051b..000000000 --- a/security/nss/lib/softoken/lowkeyti.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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 _LOWKEYTI_H_ -#define _LOWKEYTI_H_ 1 - -#include "blapit.h" -#include "prtypes.h" -#include "plarena.h" -#include "secitem.h" -#include "secasn1t.h" -#include "secoidt.h" -/*#include "secmodt.h" -#include "pkcs11t.h" */ - - -/* - * a key in/for the data base - */ -struct NSSLOWKEYDBKeyStr { - PLArenaPool *arena; - int version; - char *nickname; - SECItem salt; - SECItem derPK; -}; -typedef struct NSSLOWKEYDBKeyStr NSSLOWKEYDBKey; - -typedef struct NSSLOWKEYDBHandleStr NSSLOWKEYDBHandle; - -#ifdef NSS_USE_KEY4_DB -#define NSSLOWKEY_DB_FILE_VERSION 4 -#else -#define NSSLOWKEY_DB_FILE_VERSION 3 -#endif - -#define NSSLOWKEY_VERSION 0 /* what we *create* */ - -/* -** Typedef for callback to get a password "key". -*/ -extern const SEC_ASN1Template nsslowkey_PQGParamsTemplate[]; -extern const SEC_ASN1Template nsslowkey_RSAPrivateKeyTemplate[]; -extern const SEC_ASN1Template nsslowkey_DSAPrivateKeyTemplate[]; -extern const SEC_ASN1Template nsslowkey_DSAPrivateKeyExportTemplate[]; -extern const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[]; -extern const SEC_ASN1Template nsslowkey_DHPrivateKeyExportTemplate[]; -#ifdef NSS_ENABLE_ECC -#define NSSLOWKEY_EC_PRIVATE_KEY_VERSION 1 /* as per SECG 1 C.4 */ -extern const SEC_ASN1Template nsslowkey_ECParamsTemplate[]; -extern const SEC_ASN1Template nsslowkey_ECPrivateKeyTemplate[]; -#endif /* NSS_ENABLE_ECC */ - -extern const SEC_ASN1Template nsslowkey_PrivateKeyInfoTemplate[]; -extern const SEC_ASN1Template nsslowkey_EncryptedPrivateKeyInfoTemplate[]; - -/* - * PKCS #8 attributes - */ -struct NSSLOWKEYAttributeStr { - SECItem attrType; - SECItem *attrValue; -}; -typedef struct NSSLOWKEYAttributeStr NSSLOWKEYAttribute; - -/* -** A PKCS#8 private key info object -*/ -struct NSSLOWKEYPrivateKeyInfoStr { - PLArenaPool *arena; - SECItem version; - SECAlgorithmID algorithm; - SECItem privateKey; - NSSLOWKEYAttribute **attributes; -}; -typedef struct NSSLOWKEYPrivateKeyInfoStr NSSLOWKEYPrivateKeyInfo; -#define NSSLOWKEY_PRIVATE_KEY_INFO_VERSION 0 /* what we *create* */ - -/* -** A PKCS#8 private key info object -*/ -struct NSSLOWKEYEncryptedPrivateKeyInfoStr { - PLArenaPool *arena; - SECAlgorithmID algorithm; - SECItem encryptedData; -}; -typedef struct NSSLOWKEYEncryptedPrivateKeyInfoStr NSSLOWKEYEncryptedPrivateKeyInfo; - - -typedef enum { - NSSLOWKEYNullKey = 0, - NSSLOWKEYRSAKey = 1, - NSSLOWKEYDSAKey = 2, - NSSLOWKEYDHKey = 4, - NSSLOWKEYECKey = 5 -} NSSLOWKEYType; - -/* -** An RSA public key object. -*/ -struct NSSLOWKEYPublicKeyStr { - PLArenaPool *arena; - NSSLOWKEYType keyType ; - union { - RSAPublicKey rsa; - DSAPublicKey dsa; - DHPublicKey dh; - ECPublicKey ec; - } u; -}; -typedef struct NSSLOWKEYPublicKeyStr NSSLOWKEYPublicKey; - -/* -** Low Level private key object -** This is only used by the raw Crypto engines (crypto), keydb (keydb), -** and PKCS #11. Everyone else uses the high level key structure. -*/ -struct NSSLOWKEYPrivateKeyStr { - PLArenaPool *arena; - NSSLOWKEYType keyType; - union { - RSAPrivateKey rsa; - DSAPrivateKey dsa; - DHPrivateKey dh; - ECPrivateKey ec; - } u; -}; -typedef struct NSSLOWKEYPrivateKeyStr NSSLOWKEYPrivateKey; - -#endif /* _LOWKEYTI_H_ */ diff --git a/security/nss/lib/softoken/lowpbe.c b/security/nss/lib/softoken/lowpbe.c deleted file mode 100644 index be7e06e89..000000000 --- a/security/nss/lib/softoken/lowpbe.c +++ /dev/null @@ -1,1182 +0,0 @@ -/* - * 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. - */ - -#include "plarena.h" - -#include "seccomon.h" -#include "secitem.h" -#include "secport.h" -#include "hasht.h" -#include "pkcs11t.h" -#include "blapi.h" -#include "hasht.h" -#include "secasn1.h" -#include "secder.h" -#include "lowpbe.h" -#include "secoid.h" -#include "alghmac.h" -#include "softoken.h" -#include "secerr.h" - -/* template for PKCS 5 PBE Parameter. This template has been expanded - * based upon the additions in PKCS 12. This should eventually be moved - * if RSA updates PKCS 5. - */ -static const SEC_ASN1Template NSSPKCS5PBEParameterTemplate[] = -{ - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSPKCS5PBEParameter) }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSSPKCS5PBEParameter, salt) }, - { SEC_ASN1_INTEGER, - offsetof(NSSPKCS5PBEParameter, iteration) }, - { 0 } -}; - -static const SEC_ASN1Template NSSPKCS5PKCS12V2PBEParameterTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSPKCS5PBEParameter) }, - { SEC_ASN1_OCTET_STRING, offsetof(NSSPKCS5PBEParameter, salt) }, - { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, iteration) }, - { 0 } -}; - -SECStatus -nsspkcs5_HashBuf(const SECHashObject *hashObj, unsigned char *dest, - unsigned char *src, int len) -{ - void *ctx; - unsigned int retLen; - - ctx = hashObj->create(); - if(ctx == NULL) { - return SECFailure; - } - hashObj->begin(ctx); - hashObj->update(ctx, src, len); - hashObj->end(ctx, dest, &retLen, hashObj->length); - hashObj->destroy(ctx, PR_TRUE); - return SECSuccess; -} - -/* generate bits using any hash - */ -static SECItem * -nsspkcs5_PBKDF1(const SECHashObject *hashObj, SECItem *salt, SECItem *pwd, - int iter, PRBool faulty3DES) -{ - SECItem *hash = NULL, *pre_hash = NULL; - SECStatus rv = SECFailure; - - if((salt == NULL) || (pwd == NULL) || (iter < 0)) { - return NULL; - } - - hash = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - pre_hash = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - - if((hash != NULL) && (pre_hash != NULL)) { - int i, ph_len; - - ph_len = hashObj->length; - if((salt->len + pwd->len) > hashObj->length) { - ph_len = salt->len + pwd->len; - } - - rv = SECFailure; - - /* allocate buffers */ - hash->len = hashObj->length; - hash->data = (unsigned char *)PORT_ZAlloc(hash->len); - pre_hash->data = (unsigned char *)PORT_ZAlloc(ph_len); - - /* in pbeSHA1TripleDESCBC there was an allocation error that made - * it into the caller. We do not want to propagate those errors - * further, so we are doing it correctly, but reading the old method. - */ - if (faulty3DES) { - pre_hash->len = ph_len; - } else { - pre_hash->len = salt->len + pwd->len; - } - - /* preform hash */ - if ((hash->data != NULL) && (pre_hash->data != NULL)) { - rv = SECSuccess; - /* check for 0 length password */ - if(pwd->len > 0) { - PORT_Memcpy(pre_hash->data, pwd->data, pwd->len); - } - if(salt->len > 0) { - PORT_Memcpy((pre_hash->data+pwd->len), salt->data, salt->len); - } - for(i = 0; ((i < iter) && (rv == SECSuccess)); i++) { - rv = nsspkcs5_HashBuf(hashObj, hash->data, - pre_hash->data, pre_hash->len); - if(rv != SECFailure) { - pre_hash->len = hashObj->length; - PORT_Memcpy(pre_hash->data, hash->data, hashObj->length); - } - } - } - } - - if(pre_hash != NULL) { - SECITEM_FreeItem(pre_hash, PR_TRUE); - } - - if((rv != SECSuccess) && (hash != NULL)) { - SECITEM_FreeItem(hash, PR_TRUE); - hash = NULL; - } - - return hash; -} - -/* this bit generation routine is described in PKCS 12 and the proposed - * extensions to PKCS 5. an initial hash is generated following the - * instructions laid out in PKCS 5. If the number of bits generated is - * insufficient, then the method discussed in the proposed extensions to - * PKCS 5 in PKCS 12 are used. This extension makes use of the HMAC - * function. And the P_Hash function from the TLS standard. - */ -static SECItem * -nsspkcs5_PFXPBE(const SECHashObject *hashObj, NSSPKCS5PBEParameter *pbe_param, - SECItem *init_hash, unsigned int bytes_needed) -{ - SECItem *ret_bits = NULL; - int hash_size = 0; - unsigned int i; - unsigned int hash_iter; - unsigned int dig_len; - SECStatus rv = SECFailure; - unsigned char *state = NULL; - unsigned int state_len; - HMACContext *cx = NULL; - - hash_size = hashObj->length; - hash_iter = (bytes_needed + (unsigned int)hash_size - 1) / hash_size; - - /* allocate return buffer */ - ret_bits = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(ret_bits == NULL) - return NULL; - ret_bits->data = (unsigned char *)PORT_ZAlloc((hash_iter * hash_size) + 1); - ret_bits->len = (hash_iter * hash_size); - if(ret_bits->data == NULL) { - PORT_Free(ret_bits); - return NULL; - } - - /* allocate intermediate hash buffer. 8 is for the 8 bytes of - * data which are added based on iteration number - */ - - if ((unsigned int)hash_size > pbe_param->salt.len) { - state_len = hash_size; - } else { - state_len = pbe_param->salt.len; - } - state = (unsigned char *)PORT_ZAlloc(state_len); - if(state == NULL) { - rv = SECFailure; - goto loser; - } - if(pbe_param->salt.len > 0) { - PORT_Memcpy(state, pbe_param->salt.data, pbe_param->salt.len); - } - - cx = HMAC_Create(hashObj, init_hash->data, init_hash->len, PR_TRUE); - if (cx == NULL) { - rv = SECFailure; - goto loser; - } - - for(i = 0; i < hash_iter; i++) { - - /* generate output bits */ - HMAC_Begin(cx); - HMAC_Update(cx, state, state_len); - HMAC_Update(cx, pbe_param->salt.data, pbe_param->salt.len); - rv = HMAC_Finish(cx, ret_bits->data + (i * hash_size), - &dig_len, hash_size); - if (rv != SECSuccess) - goto loser; - PORT_Assert((unsigned int)hash_size == dig_len); - - /* generate new state */ - HMAC_Begin(cx); - HMAC_Update(cx, state, state_len); - rv = HMAC_Finish(cx, state, &state_len, state_len); - if (rv != SECSuccess) - goto loser; - PORT_Assert(state_len == dig_len); - } - -loser: - if (state != NULL) - PORT_ZFree(state, state_len); - HMAC_Destroy(cx); - - if(rv != SECSuccess) { - SECITEM_ZfreeItem(ret_bits, PR_TRUE); - ret_bits = NULL; - } - - return ret_bits; -} - -/* generate bits for the key and iv determination. if enough bits - * are not generated using PKCS 5, then we need to generate more bits - * based on the extension proposed in PKCS 12 - */ -static SECItem * -nsspkcs5_PBKDF1Extended(const SECHashObject *hashObj, - NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, PRBool faulty3DES) -{ - SECItem * hash = NULL; - SECItem * newHash = NULL; - int bytes_needed; - int bytes_available; - - bytes_needed = pbe_param->ivLen + pbe_param->keyLen; - bytes_available = hashObj->length; - - hash = nsspkcs5_PBKDF1(hashObj, &pbe_param->salt, pwitem, - pbe_param->iter, faulty3DES); - - if(hash == NULL) { - return NULL; - } - - if(bytes_needed <= bytes_available) { - return hash; - } - - newHash = nsspkcs5_PFXPBE(hashObj, pbe_param, hash, bytes_needed); - if (hash != newHash) - SECITEM_FreeItem(hash, PR_TRUE); - return newHash; -} - -#ifdef PBKDF2 - -/* - * PBDKDF2 is PKCS #5 v2.0 it's currently not used by NSS - */ -/* - * We This is safe because hLen for all our - * HMAC algorithms are multiples of 4. - */ -static void -xorbytes(unsigned char *dest, unsigned char *src, int len) -{ -#ifdef PARANOIA - while (len--) { - *dest = *dest ^ *src; - dest++; - src++; - } -#else - PRUInt32 dest32 = (PRUInt32 *)dest; - PRUInt32 src32 = (PRUInt32 *)dest; - while (len -= sizeof(PRUInt32)) { - *dest32 = *dest32 ^ *src32; - dest++; - src++; - } -#endif -} - -static SECStatus -nsspkcs5_PBKFD2_F(const SECHashObject *hashobj, SECItem *pwitem, SECItem *salt, - int iterations, unsigned int i, unsigned char *T) -{ - int j; - HMACContext *cx = NULL; - unsigned int hLen = hashObject->length - SECStatus rv = SECFailure; - unsigned char *last = NULL; - int lastLength = salt->len + 4; - - cx=HMAC_Create(hashobj,pwitem->data,pwitem->len,PR_TRUE); - if (cx == NULL) { - goto loser; - } - PORT_Memset(T,0,hLen); - realLastLength= MAX(lastLength,hLen); - last = PORT_Alloc(realLastLength); - if (last == NULL) { - goto loser; - } - PORT_Memcpy(last,salt.data,salt.len); - last[salt->len ] = (i >> 24) & 0xff; - last[salt->len+1] = (i >> 16) & 0xff; - last[salt->len+2] = (i >> 8) & 0xff; - last[salt->len+3] = i & 0xff; - - /* NOTE: we need at least one iteration to return success! */ - for (j=0; j < interations; j++) { - rv =HMAC_Begin(cx); - if (rv !=SECSuccess) { - break; - } - HMAC_Update(cx,last,lastLength); - rv =HMAC_Finish(cx,last,&lastLength,hLen); - if (rv !=SECSuccess) { - break; - } - do_xor(T,last,hLen); - } -loser: - if (cx) { - HMAC_DestroyContext(cx); - } - if (last) { - PORT_ZFree(last,reaLastLength); - } - return rv; -} - -static SECItem * -nsspkcs5_PBKFD2(const SECHashObject *hashObj, NSSPKCS5PBEParameter *pbe_param, - SECItem *pwitem) -{ - unsigned int dkLen = bytesNeeded; - unsigned int hLen = hashObject->length - unsigned int l = (dkLen+hLen-1) / hLen; - unsigned char *rp; - SECItem *result; - SECItem *salt = pbe_param->salt; - int interations = pbe_param->iter; - int bytesNeeded = pbe_param->keyLen; - - result = SECITEM_AllocItem(NULL,NULL,l*hLen); - if (result == NULL) { - return NULL; - } - - T = PORT_Alloc(hLen); - if (T == NULL) { - goto loser; - } - - for (i=0,rp=results->data; i < l ; i++, rp +=hLen) { - rv = nsspkcs5_PBKFD2_F(hashobj,pwitem,salt,iterations,i,T); - if (rv != SECSuccess) { - break; - } - PORT_Memcpy(rp,T,hLen); - } - -loser: - if (T) { - PORT_ZFree(T); - } - if (rv != SECSuccess) { - SECITEM_FreeITEM(result,PR_TRUE); - result = NULL; - } else { - result->len = dkLen; - } - - return result; -} -#endif - -#define HMAC_BUFFER 64 -#define NSSPBE_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y)) -#define NSSPBE_MIN(x,y) ((x) < (y) ? (x) : (y)) -/* - * This is the extended PBE function defined by the final PKCS #12 spec. - */ -static SECItem * -nsspkcs5_PKCS12PBE(const SECHashObject *hashObject, - NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, - PBEBitGenID bitGenPurpose, unsigned int bytesNeeded) -{ - PRArenaPool *arena = NULL; - unsigned int SLen,PLen; - unsigned int hashLength = hashObject->length; - unsigned char *S, *P; - SECItem *A = NULL, B, D, I; - SECItem *salt = &pbe_param->salt; - unsigned int c,i = 0; - unsigned int hashLen; - int iter; - unsigned char *iterBuf; - void *hash = NULL; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if(!arena) { - return NULL; - } - - /* how many hash object lengths are needed */ - c = (bytesNeeded + (hashLength-1))/hashLength; - - /* initialize our buffers */ - D.len = HMAC_BUFFER; - /* B and D are the same length, use one alloc go get both */ - D.data = (unsigned char*)PORT_ArenaZAlloc(arena, D.len*2); - B.len = D.len; - B.data = D.data + D.len; - - /* if all goes well, A will be returned, so don't use our temp arena */ - A = SECITEM_AllocItem(NULL,NULL,c*hashLength); - if (A == NULL) { - goto loser; - } - - SLen = NSSPBE_ROUNDUP(salt->len,HMAC_BUFFER); - PLen = NSSPBE_ROUNDUP(pwitem->len,HMAC_BUFFER); - I.len = SLen+PLen; - I.data = (unsigned char*)PORT_ArenaZAlloc(arena, I.len); - if (I.data == NULL) { - goto loser; - } - - /* S & P are only used to initialize I */ - S = I.data; - P = S + SLen; - - PORT_Memset(D.data, (char)bitGenPurpose, D.len); - if (SLen) { - for (i=0; i < SLen; i += salt->len) { - PORT_Memcpy(S+i, salt->data, NSSPBE_MIN(SLen-i,salt->len)); - } - } - if (PLen) { - for (i=0; i < PLen; i += pwitem->len) { - PORT_Memcpy(P+i, pwitem->data, NSSPBE_MIN(PLen-i,pwitem->len)); - } - } - - iterBuf = (unsigned char*)PORT_ArenaZAlloc(arena,hashLength); - if (iterBuf == NULL) { - goto loser; - } - - hash = hashObject->create(); - if(!hash) { - goto loser; - } - /* calculate the PBE now */ - for(i = 0; i < c; i++) { - int Bidx; /* must be signed or the for loop won't terminate */ - unsigned int k, j; - unsigned char *Ai = A->data+i*hashLength; - - - for(iter = 0; iter < pbe_param->iter; iter++) { - hashObject->begin(hash); - - if (iter) { - hashObject->update(hash, iterBuf, hashLen); - } else { - hashObject->update(hash, D.data, D.len); - hashObject->update(hash, I.data, I.len); - } - - hashObject->end(hash, iterBuf, &hashLen, hashObject->length); - if(hashLen != hashObject->length) { - break; - } - } - - PORT_Memcpy(Ai, iterBuf, hashLength); - for (Bidx = 0; Bidx < B.len; Bidx += hashLength) { - PORT_Memcpy(B.data+Bidx,iterBuf,NSSPBE_MIN(B.len-Bidx,hashLength)); - } - - k = I.len/B.len; - for(j = 0; j < k; j++) { - unsigned int q, carryBit; - unsigned char *Ij = I.data + j*B.len; - - /* (Ij = Ij+B+1) */ - for (Bidx = (B.len-1), q=1, carryBit=0; Bidx >= 0; Bidx--,q=0) { - q += (unsigned int)Ij[Bidx]; - q += (unsigned int)B.data[Bidx]; - q += carryBit; - - carryBit = (q > 0xff); - Ij[Bidx] = (unsigned char)(q & 0xff); - } - } - } -loser: - if (hash) { - hashObject->destroy(hash, PR_TRUE); - } - if(arena) { - PORT_FreeArena(arena, PR_TRUE); - } - - /* if i != c, then we didn't complete the loop above and must of failed - * somwhere along the way */ - if (i != c) { - SECITEM_ZfreeItem(A,PR_TRUE); - A = NULL; - } else { - A->len = bytesNeeded; - } - - return A; -} - -/* - * generate key as per PKCS 5 - */ -SECItem * -nsspkcs5_ComputeKeyAndIV(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, - SECItem *iv, PRBool faulty3DES) -{ - SECItem *hash = NULL, *key = NULL; - const SECHashObject *hashObj; - PRBool getIV = PR_FALSE; - - if((pbe_param == NULL) || (pwitem == NULL)) { - return NULL; - } - - key = SECITEM_AllocItem(NULL,NULL,pbe_param->keyLen); - if (key == NULL) { - return NULL; - } - - if ((pbe_param->ivLen) && (iv->data == NULL)) { - getIV = PR_TRUE; - iv->data = (unsigned char *)PORT_Alloc(pbe_param->ivLen); - if (iv->data == NULL) { - goto loser; - } - iv->len = pbe_param->ivLen; - } - - hashObj = &SECRawHashObjects[pbe_param->hashType]; - switch (pbe_param->pbeType) { - case NSSPKCS5_PBKDF1: - hash = nsspkcs5_PBKDF1Extended(hashObj,pbe_param,pwitem,faulty3DES); - if (hash == NULL) { - goto loser; - } - PORT_Assert(hash->len >= key->len+iv->len); - if (getIV) { - PORT_Memcpy(iv->data, hash->data+(hash->len - iv->len),iv->len); - } - break; -#ifdef PBKDF2 - case NSSPKCS5_PBKDF2: - hash = nsspkcs5_PBKDF2(hashObj,pbe_param,pwitem); - PORT_Assert(!getIV); - break; -#endif - case NSSPKCS5_PKCS12_V2: - if (getIV) { - hash = nsspkcs5_PKCS12PBE(hashObj,pbe_param,pwitem, - pbeBitGenCipherIV,iv->len); - if (hash == NULL) { - goto loser; - } - PORT_Memcpy(iv->data,hash->data,iv->len); - SECITEM_ZfreeItem(hash,PR_TRUE); - hash = NULL; - } - hash = nsspkcs5_PKCS12PBE(hashObj,pbe_param,pwitem, - pbe_param->keyID,key->len); - default: - break; - } - - if (hash == NULL) { - goto loser; - } - - if (pbe_param->is2KeyDES) { - PORT_Memcpy(key->data, hash->data, (key->len * 2) / 3); - PORT_Memcpy(&(key->data[(key->len * 2) / 3]), key->data, - key->len / 3); - } else { - PORT_Memcpy(key->data, hash->data, key->len); - } - - SECITEM_FreeItem(hash, PR_TRUE); - return key; - -loser: - if (getIV && iv->data) { - PORT_ZFree(iv->data,iv->len); - iv->data = NULL; - } - - SECITEM_ZfreeItem(key, PR_TRUE); - return NULL; -} - -static SECStatus -nsspkcs5_FillInParam(SECOidTag algorithm, NSSPKCS5PBEParameter *pbe_param) -{ - PRBool skipType = PR_FALSE; - - pbe_param->keyLen = 5; - pbe_param->ivLen = 8; - pbe_param->hashType = HASH_AlgSHA1; - pbe_param->pbeType = NSSPKCS5_PBKDF1; - pbe_param->encAlg = SEC_OID_RC2_CBC; - pbe_param->is2KeyDES = PR_FALSE; - switch(algorithm) { - /* DES3 Algorithms */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_2KEY_TRIPLE_DES_CBC: - pbe_param->is2KeyDES = PR_TRUE; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC: - pbe_param->pbeType = NSSPKCS5_PKCS12_V2; - /* fall through */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC: - pbe_param->keyLen = 24; - pbe_param->encAlg = SEC_OID_DES_EDE3_CBC; - break; - - /* DES Algorithms */ - case SEC_OID_PKCS5_PBE_WITH_MD2_AND_DES_CBC: - pbe_param->hashType = HASH_AlgMD2; - goto finish_des; - case SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC: - pbe_param->hashType = HASH_AlgMD5; - /* fall through */ - case SEC_OID_PKCS5_PBE_WITH_SHA1_AND_DES_CBC: -finish_des: - pbe_param->keyLen = 8; - pbe_param->encAlg = SEC_OID_DES_CBC; - break; - - /* RC2 Algorithms */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC: - pbe_param->keyLen = 16; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC: - pbe_param->pbeType = NSSPKCS5_PKCS12_V2; - break; - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC: - pbe_param->keyLen = 16; - /* fall through */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC: - break; - - /* RC4 algorithms */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC4: - skipType = PR_TRUE; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC4: - pbe_param->keyLen = 16; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC4: - if (!skipType) { - pbe_param->pbeType = NSSPKCS5_PKCS12_V2; - } - /* fall through */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC4: - pbe_param->ivLen = 0; - pbe_param->encAlg = SEC_OID_RC4; - break; - default: - return SECFailure; - } - - return SECSuccess; -} - -/* decode the algid and generate a PKCS 5 parameter from it - */ -NSSPKCS5PBEParameter * -nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator) -{ - PRArenaPool *arena = NULL; - NSSPKCS5PBEParameter *pbe_param = NULL; - SECStatus rv = SECFailure; - - arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if (arena == NULL) - return NULL; - - /* allocate memory for the parameter */ - pbe_param = (NSSPKCS5PBEParameter *)PORT_ArenaZAlloc(arena, - sizeof(NSSPKCS5PBEParameter)); - - if (pbe_param == NULL) { - goto loser; - } - - pbe_param->poolp = arena; - - rv = nsspkcs5_FillInParam(alg, pbe_param); - if (rv != SECSuccess) { - goto loser; - } - - pbe_param->iter = iterator; - if (salt) { - rv = SECITEM_CopyItem(arena,&pbe_param->salt,salt); - } - - /* default key gen */ - pbe_param->keyID = pbeBitGenCipherKey; - -loser: - if (rv != SECSuccess) { - PORT_FreeArena(arena, PR_TRUE); - pbe_param = NULL; - } - - return pbe_param; -} - -/* decode the algid and generate a PKCS 5 parameter from it - */ -NSSPKCS5PBEParameter * -nsspkcs5_AlgidToParam(SECAlgorithmID *algid) -{ - NSSPKCS5PBEParameter *pbe_param = NULL; - SECOidTag algorithm; - SECStatus rv = SECFailure; - - if (algid == NULL) { - return NULL; - } - - algorithm = SECOID_GetAlgorithmTag(algid); - if (algorithm == SEC_OID_UNKNOWN) { - goto loser; - } - - pbe_param = nsspkcs5_NewParam(algorithm, NULL, 1); - if (pbe_param == NULL) { - goto loser; - } - - /* decode parameter */ - rv = SECFailure; - switch (pbe_param->pbeType) { - case NSSPKCS5_PBKDF1: - rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, - NSSPKCS5PBEParameterTemplate, &algid->parameters); - break; - case NSSPKCS5_PKCS12_V2: - rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, - NSSPKCS5PKCS12V2PBEParameterTemplate, &algid->parameters); - break; - case NSSPKCS5_PBKDF2: - break; - } - -loser: - if (rv == SECSuccess) { - pbe_param->iter = DER_GetInteger(&pbe_param->iteration); - } else { - nsspkcs5_DestroyPBEParameter(pbe_param); - pbe_param = NULL; - } - - return pbe_param; -} - -/* destroy a pbe parameter. it assumes that the parameter was - * generated using the appropriate create function and therefor - * contains an arena pool. - */ -void -nsspkcs5_DestroyPBEParameter(NSSPKCS5PBEParameter *pbe_param) -{ - if (pbe_param != NULL) { - PORT_FreeArena(pbe_param->poolp, PR_TRUE); - } -} - - -/* crypto routines */ -/* perform DES encryption and decryption. these routines are called - * by nsspkcs5_CipherData. In the case of an error, NULL is returned. - */ -static SECItem * -sec_pkcs5_des(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, - PRBool encrypt) -{ - SECItem *dest; - SECItem *dup_src; - SECStatus rv = SECFailure; - int pad; - - if((src == NULL) || (key == NULL) || (iv == NULL)) - return NULL; - - dup_src = SECITEM_DupItem(src); - if(dup_src == NULL) { - return NULL; - } - - if(encrypt != PR_FALSE) { - void *dummy; - - dummy = DES_PadBuffer(NULL, dup_src->data, - dup_src->len, &dup_src->len); - if(dummy == NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); - return NULL; - } - dup_src->data = (unsigned char*)dummy; - } - - dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest != NULL) { - /* allocate with over flow */ - dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); - if(dest->data != NULL) { - DESContext *ctxt; - ctxt = DES_CreateContext(key->data, iv->data, - (triple_des ? NSS_DES_EDE3_CBC : NSS_DES_CBC), - encrypt); - - if(ctxt != NULL) { - rv = (encrypt ? DES_Encrypt : DES_Decrypt)( - ctxt, dest->data, &dest->len, - dup_src->len + 64, dup_src->data, dup_src->len); - - /* remove padding -- assumes 64 bit blocks */ - if((encrypt == PR_FALSE) && (rv == SECSuccess)) { - pad = dest->data[dest->len-1]; - if((pad > 0) && (pad <= 8)) { - if(dest->data[dest->len-pad] != pad) { - rv = SECFailure; - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - } else { - dest->len -= pad; - } - } else { - rv = SECFailure; - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - } - } - DES_DestroyContext(ctxt, PR_TRUE); - } - } - } - - if(rv == SECFailure) { - if(dest != NULL) { - SECITEM_FreeItem(dest, PR_TRUE); - } - dest = NULL; - } - - if(dup_src != NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); - } - - return dest; -} - -/* perform rc2 encryption/decryption if an error occurs, NULL is returned - */ -static SECItem * -sec_pkcs5_rc2(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy, - PRBool encrypt) -{ - SECItem *dest; - SECItem *dup_src; - SECStatus rv = SECFailure; - int pad; - - if((src == NULL) || (key == NULL) || (iv == NULL)) { - return NULL; - } - - dup_src = SECITEM_DupItem(src); - if(dup_src == NULL) { - return NULL; - } - - if(encrypt != PR_FALSE) { - void *dummy; - - dummy = DES_PadBuffer(NULL, dup_src->data, - dup_src->len, &dup_src->len); - if(dummy == NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); - return NULL; - } - dup_src->data = (unsigned char*)dummy; - } - - dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest != NULL) { - dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); - if(dest->data != NULL) { - RC2Context *ctxt; - - ctxt = RC2_CreateContext(key->data, key->len, iv->data, - NSS_RC2_CBC, key->len); - - if(ctxt != NULL) { - rv = (encrypt ? RC2_Encrypt: RC2_Decrypt)( - ctxt, dest->data, &dest->len, - dup_src->len + 64, dup_src->data, dup_src->len); - - /* assumes 8 byte blocks -- remove padding */ - if((rv == SECSuccess) && (encrypt != PR_TRUE)) { - pad = dest->data[dest->len-1]; - if((pad > 0) && (pad <= 8)) { - if(dest->data[dest->len-pad] != pad) { - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - rv = SECFailure; - } else { - dest->len -= pad; - } - } else { - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - rv = SECFailure; - } - } - - } - } - } - - if((rv != SECSuccess) && (dest != NULL)) { - SECITEM_FreeItem(dest, PR_TRUE); - dest = NULL; - } - - if(dup_src != NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); - } - - return dest; -} - -/* perform rc4 encryption and decryption */ -static SECItem * -sec_pkcs5_rc4(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy_op, - PRBool encrypt) -{ - SECItem *dest; - SECStatus rv = SECFailure; - - if((src == NULL) || (key == NULL) || (iv == NULL)) { - return NULL; - } - - dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest != NULL) { - dest->data = (unsigned char *)PORT_ZAlloc(sizeof(unsigned char) * - (src->len + 64)); - if(dest->data != NULL) { - RC4Context *ctxt; - - ctxt = RC4_CreateContext(key->data, key->len); - if(ctxt) { - rv = (encrypt ? RC4_Encrypt : RC4_Decrypt)( - ctxt, dest->data, &dest->len, - src->len + 64, src->data, src->len); - RC4_DestroyContext(ctxt, PR_TRUE); - } - } - } - - if((rv != SECSuccess) && (dest)) { - SECITEM_FreeItem(dest, PR_TRUE); - dest = NULL; - } - - return dest; -} -/* function pointer template for crypto functions */ -typedef SECItem *(* pkcs5_crypto_func)(SECItem *key, SECItem *iv, - SECItem *src, PRBool op1, PRBool op2); - -/* performs the cipher operation on the src and returns the result. - * if an error occurs, NULL is returned. - * - * a null length password is allowed. this corresponds to encrypting - * the data with ust the salt. - */ -/* change this to use PKCS 11? */ -SECItem * -nsspkcs5_CipherData(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, - SECItem *src, PRBool encrypt, PRBool *update) -{ - SECItem *key = NULL, iv; - SECItem *dest = NULL; - PRBool tripleDES = PR_TRUE; - pkcs5_crypto_func cryptof; - - iv.data = NULL; - - if (update) { - *update = PR_FALSE; - } - - if ((pwitem == NULL) || (src == NULL)) { - return NULL; - } - - /* get key, and iv */ - key = nsspkcs5_ComputeKeyAndIV(pbe_param, pwitem, &iv, PR_FALSE); - if(key == NULL) { - return NULL; - } - - switch(pbe_param->encAlg) { - case SEC_OID_DES_EDE3_CBC: - cryptof = sec_pkcs5_des; - tripleDES = PR_TRUE; - break; - case SEC_OID_DES_CBC: - cryptof = sec_pkcs5_des; - tripleDES = PR_FALSE; - break; - case SEC_OID_RC2_CBC: - cryptof = sec_pkcs5_rc2; - break; - case SEC_OID_RC4: - cryptof = sec_pkcs5_rc4; - break; - default: - cryptof = NULL; - break; - } - - if (cryptof == NULL) { - goto loser; - } - - dest = (*cryptof)(key, &iv, src, tripleDES, encrypt); - /* - * it's possible for some keys and keydb's to claim to - * be triple des when they're really des. In this case - * we simply try des. If des works we set the update flag - * so the key db knows it needs to update all it's entries. - * The case can only happen on decrypted of a - * SEC_OID_DES_EDE3_CBD. - */ - if ((dest == NULL) && (encrypt == PR_FALSE) && - (pbe_param->encAlg == SEC_OID_DES_EDE3_CBC)) { - dest = (*cryptof)(key, &iv, src, PR_FALSE, encrypt); - if (update && (dest != NULL)) *update = PR_TRUE; - } - -loser: - if (key != NULL) { - SECITEM_ZfreeItem(key, PR_TRUE); - } - if (iv.data != NULL) { - SECITEM_ZfreeItem(&iv, PR_FALSE); - } - - return dest; -} - -/* creates a algorithm ID containing the PBE algorithm and appropriate - * parameters. the required parameter is the algorithm. if salt is - * not specified, it is generated randomly. if IV is specified, it overrides - * the PKCS 5 generation of the IV. - * - * the returned SECAlgorithmID should be destroyed using - * SECOID_DestroyAlgorithmID - */ -SECAlgorithmID * -nsspkcs5_CreateAlgorithmID(PRArenaPool *arena, SECOidTag algorithm, - NSSPKCS5PBEParameter *pbe_param) -{ - SECAlgorithmID *algid, *ret_algid = NULL; - SECItem der_param; - SECStatus rv = SECFailure; - void *dummy = NULL; - - if (arena == NULL) { - return NULL; - } - - der_param.data = NULL; - der_param.len = 0; - - /* generate the algorithm id */ - algid = (SECAlgorithmID *)PORT_ArenaZAlloc(arena, sizeof(SECAlgorithmID)); - if (algid == NULL) { - goto loser; - } - - if (pbe_param->iteration.data == NULL) { - dummy = SEC_ASN1EncodeInteger(pbe_param->poolp,&pbe_param->iteration, - pbe_param->iter); - if (dummy == NULL) { - goto loser; - } - } - switch (pbe_param->pbeType) { - case NSSPKCS5_PBKDF1: - dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, - NSSPKCS5PBEParameterTemplate); - break; - case NSSPKCS5_PKCS12_V2: - dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, - NSSPKCS5PKCS12V2PBEParameterTemplate); - break; - default: - break; - } - - if (dummy == NULL) { - goto loser; - } - - rv = SECOID_SetAlgorithmID(arena, algid, algorithm, &der_param); - if (rv != SECSuccess) { - goto loser; - } - - ret_algid = (SECAlgorithmID *)PORT_ZAlloc(sizeof(SECAlgorithmID)); - if (ret_algid == NULL) { - goto loser; - } - - rv = SECOID_CopyAlgorithmID(NULL, ret_algid, algid); - if (rv != SECSuccess) { - SECOID_DestroyAlgorithmID(ret_algid, PR_TRUE); - ret_algid = NULL; - } - -loser: - - return ret_algid; -} diff --git a/security/nss/lib/softoken/lowpbe.h b/security/nss/lib/softoken/lowpbe.h deleted file mode 100644 index 8ddee11a6..000000000 --- a/security/nss/lib/softoken/lowpbe.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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 _SECPKCS5_H_ -#define _SECPKCS5_H_ - -#include "plarena.h" -#include "secitem.h" -#include "seccomon.h" -#include "secoidt.h" -#include "hasht.h" - -typedef SECItem * (* SEC_PKCS5GetPBEPassword)(void *arg); - -/* used for V2 PKCS 12 Draft Spec */ -typedef enum { - pbeBitGenIDNull = 0, - pbeBitGenCipherKey = 0x01, - pbeBitGenCipherIV = 0x02, - pbeBitGenIntegrityKey = 0x03 -} PBEBitGenID; - -typedef enum { - NSSPKCS5_PBKDF1 = 0, - NSSPKCS5_PBKDF2 = 1, - NSSPKCS5_PKCS12_V2 = 2 -} NSSPKCS5PBEType; - -typedef struct NSSPKCS5PBEParameterStr NSSPKCS5PBEParameter; - -struct NSSPKCS5PBEParameterStr { - PRArenaPool *poolp; - SECItem salt; /* octet string */ - SECItem iteration; /* integer */ - - /* used locally */ - int iter; - int keyLen; - int ivLen; - HASH_HashType hashType; - NSSPKCS5PBEType pbeType; - PBEBitGenID keyID; - SECOidTag encAlg; - PRBool is2KeyDES; -}; - - -SEC_BEGIN_PROTOS -/* Create a PKCS5 Algorithm ID - * The algorithm ID is set up using the PKCS #5 parameter structure - * algorithm is the PBE algorithm ID for the desired algorithm - * pbe is a pbe param block with all the info needed to create the - * algorithm id. - * If an error occurs or the algorithm specified is not supported - * or is not a password based encryption algorithm, NULL is returned. - * Otherwise, a pointer to the algorithm id is returned. - */ -extern SECAlgorithmID * -nsspkcs5_CreateAlgorithmID(PRArenaPool *arena, SECOidTag algorithm, - NSSPKCS5PBEParameter *pbe); - -/* - * Convert an Algorithm ID to a PBE Param. - * NOTE: this does not suppport PKCS 5 v2 because it's only used for the - * keyDB which only support PKCS 5 v1, PFX, and PKCS 12. - */ -NSSPKCS5PBEParameter * -nsspkcs5_AlgidToParam(SECAlgorithmID *algid); - -/* - * Convert an Algorithm ID to a PBE Param. - * NOTE: this does not suppport PKCS 5 v2 because it's only used for the - * keyDB which only support PKCS 5 v1, PFX, and PKCS 12. - */ -NSSPKCS5PBEParameter * -nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator); - - -/* Encrypt/Decrypt data using password based encryption. - * algid is the PBE algorithm identifier, - * pwitem is the password, - * src is the source for encryption/decryption, - * encrypt is PR_TRUE for encryption, PR_FALSE for decryption. - * The key and iv are generated based upon PKCS #5 then the src - * is either encrypted or decrypted. If an error occurs, NULL - * is returned, otherwise the ciphered contents is returned. - */ -extern SECItem * -nsspkcs5_CipherData(NSSPKCS5PBEParameter *, SECItem *pwitem, - SECItem *src, PRBool encrypt, PRBool *update); - -extern SECItem * -nsspkcs5_ComputeKeyAndIV(NSSPKCS5PBEParameter *, SECItem *pwitem, - SECItem *iv, PRBool faulty3DES); - -/* Destroys PBE parameter */ -extern void -nsspkcs5_DestroyPBEParameter(NSSPKCS5PBEParameter *param); - -SEC_END_PROTOS - -#endif diff --git a/security/nss/lib/softoken/manifest.mn b/security/nss/lib/softoken/manifest.mn deleted file mode 100644 index b73d4f8bf..000000000 --- a/security/nss/lib/softoken/manifest.mn +++ /dev/null @@ -1,87 +0,0 @@ -# -# 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. -# -CORE_DEPTH = ../../.. - -MODULE = nss - -REQUIRES = dbm - -LIBRARY_NAME = softokn -LIBRARY_VERSION = 3 -MAPFILE = $(OBJDIR)/softokn.def - -DEFINES += -DSHLIB_SUFFIX=\"$(DLL_SUFFIX)\" -DSHLIB_PREFIX=\"$(DLL_PREFIX)\" -DSOFTOKEN_LIB_NAME=\"$(notdir $(SHARED_LIBRARY))\" - - -EXPORTS = \ - pkcs11.h \ - pkcs11f.h \ - pkcs11p.h \ - pkcs11t.h \ - pkcs11n.h \ - pkcs11u.h \ - $(NULL) - -PRIVATE_EXPORTS = \ - alghmac.h \ - pk11pars.h \ - pkcs11i.h \ - $(NULL) - -CSRCS = \ - alghmac.c \ - dbinit.c \ - dbmshim.c \ - ecdecode.c \ - fipstest.c \ - fipstokn.c \ - keydb.c \ - lowcert.c \ - lowkey.c \ - lowpbe.c \ - padbuf.c \ - pcertdb.c \ - pk11db.c \ - pkcs11.c \ - pkcs11c.c \ - pkcs11u.c \ - rawhash.c \ - rsawrapr.c \ - softkver.c \ - tlsprf.c \ - $(NULL) - -ifdef NSS_ENABLE_ECC -DEFINES += -DNSS_ENABLE_ECC -endif - diff --git a/security/nss/lib/softoken/padbuf.c b/security/nss/lib/softoken/padbuf.c deleted file mode 100644 index a4e28947a..000000000 --- a/security/nss/lib/softoken/padbuf.c +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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. - */ -#include "blapit.h" -#include "secport.h" -#include "secerr.h" - -/* - * Prepare a buffer for DES encryption, growing to the appropriate boundary, - * filling with the appropriate padding. - * - * NOTE: If arena is non-NULL, we re-allocate from there, otherwise - * we assume (and use) XP memory (re)allocation. - */ -unsigned char * -DES_PadBuffer(PRArenaPool *arena, unsigned char *inbuf, unsigned int inlen, - unsigned int *outlen) -{ - unsigned char *outbuf; - unsigned int des_len; - unsigned int i; - unsigned char des_pad_len; - - /* - * We need from 1 to DES_KEY_LENGTH bytes -- we *always* grow. - * The extra bytes contain the value of the length of the padding: - * if we have 2 bytes of padding, then the padding is "0x02, 0x02". - */ - des_len = (inlen + DES_KEY_LENGTH) & ~(DES_KEY_LENGTH - 1); - - if (arena != NULL) { - outbuf = (unsigned char*)PORT_ArenaGrow (arena, inbuf, inlen, des_len); - } else { - outbuf = (unsigned char*)PORT_Realloc (inbuf, des_len); - } - - if (outbuf == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; - } - - des_pad_len = des_len - inlen; - for (i = inlen; i < des_len; i++) - outbuf[i] = des_pad_len; - - *outlen = des_len; - return outbuf; -} diff --git a/security/nss/lib/softoken/pcert.h b/security/nss/lib/softoken/pcert.h deleted file mode 100644 index 9743a8619..000000000 --- a/security/nss/lib/softoken/pcert.h +++ /dev/null @@ -1,240 +0,0 @@ -/* - * 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 _PCERTDB_H_ -#define _PCERTDB_H_ - -#include "plarena.h" -#include "prlong.h" -#include "pcertt.h" - -SEC_BEGIN_PROTOS - -/* -** Add a DER encoded certificate to the permanent database. -** "derCert" is the DER encoded certificate. -** "nickname" is the nickname to use for the cert -** "trust" is the trust parameters for the cert -*/ -SECStatus nsslowcert_AddPermCert(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTCertificate *cert, - char *nickname, NSSLOWCERTCertTrust *trust); -SECStatus nsslowcert_AddPermNickname(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname); - -SECStatus nsslowcert_DeletePermCertificate(NSSLOWCERTCertificate *cert); - -typedef SECStatus (PR_CALLBACK * PermCertCallback)(NSSLOWCERTCertificate *cert, - SECItem *k, void *pdata); -/* -** Traverse the entire permanent database, and pass the certs off to a -** user supplied function. -** "certfunc" is the user function to call for each certificate -** "udata" is the user's data, which is passed through to "certfunc" -*/ -SECStatus -nsslowcert_TraversePermCerts(NSSLOWCERTCertDBHandle *handle, - PermCertCallback certfunc, - void *udata ); - -PRBool -nsslowcert_CertDBKeyConflict(SECItem *derCert, NSSLOWCERTCertDBHandle *handle); - -certDBEntryRevocation * -nsslowcert_FindCrlByKey(NSSLOWCERTCertDBHandle *handle, - SECItem *crlKey, PRBool isKRL); - -SECStatus -nsslowcert_DeletePermCRL(NSSLOWCERTCertDBHandle *handle,SECItem *derName, - PRBool isKRL); -SECStatus -nsslowcert_AddCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl , - SECItem *derKey, char *url, PRBool isKRL); - -NSSLOWCERTCertDBHandle *nsslowcert_GetDefaultCertDB(); -NSSLOWKEYPublicKey *nsslowcert_ExtractPublicKey(NSSLOWCERTCertificate *); - -NSSLOWCERTCertificate * -nsslowcert_NewTempCertificate(NSSLOWCERTCertDBHandle *handle, SECItem *derCert, - char *nickname, PRBool isperm, PRBool copyDER); -NSSLOWCERTCertificate * -nsslowcert_DupCertificate(NSSLOWCERTCertificate *cert); -void nsslowcert_DestroyCertificate(NSSLOWCERTCertificate *cert); -void nsslowcert_DestroyTrust(NSSLOWCERTTrust *Trust); - -/* - * Lookup a certificate in the databases without locking - * "certKey" is the database key to look for - * - * XXX - this should be internal, but pkcs 11 needs to call it during a - * traversal. - */ -NSSLOWCERTCertificate * -nsslowcert_FindCertByKey(NSSLOWCERTCertDBHandle *handle, SECItem *certKey); - -/* - * Lookup trust for a certificate in the databases without locking - * "certKey" is the database key to look for - * - * XXX - this should be internal, but pkcs 11 needs to call it during a - * traversal. - */ -NSSLOWCERTTrust * -nsslowcert_FindTrustByKey(NSSLOWCERTCertDBHandle *handle, SECItem *certKey); - -/* -** Generate a certificate key from the issuer and serialnumber, then look it -** up in the database. Return the cert if found. -** "issuerAndSN" is the issuer and serial number to look for -*/ -extern NSSLOWCERTCertificate * -nsslowcert_FindCertByIssuerAndSN (NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssuerAndSN *issuerAndSN); - -/* -** Generate a certificate key from the issuer and serialnumber, then look it -** up in the database. Return the cert if found. -** "issuerAndSN" is the issuer and serial number to look for -*/ -extern NSSLOWCERTTrust * -nsslowcert_FindTrustByIssuerAndSN (NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssuerAndSN *issuerAndSN); - -/* -** Find a certificate in the database by a DER encoded certificate -** "derCert" is the DER encoded certificate -*/ -extern NSSLOWCERTCertificate * -nsslowcert_FindCertByDERCert(NSSLOWCERTCertDBHandle *handle, SECItem *derCert); - -/* convert an email address to lower case */ -char *nsslowcert_FixupEmailAddr(char *emailAddr); - -/* -** Decode a DER encoded certificate into an NSSLOWCERTCertificate structure -** "derSignedCert" is the DER encoded signed certificate -** "copyDER" is true if the DER should be copied, false if the -** existing copy should be referenced -** "nickname" is the nickname to use in the database. If it is NULL -** then a temporary nickname is generated. -*/ -extern NSSLOWCERTCertificate * -nsslowcert_DecodeDERCertificate (SECItem *derSignedCert, char *nickname); - -SECStatus -nsslowcert_KeyFromDERCert(PRArenaPool *arena, SECItem *derCert, SECItem *key); - -certDBEntrySMime * -nsslowcert_ReadDBSMimeEntry(NSSLOWCERTCertDBHandle *certHandle, - char *emailAddr); -void -nsslowcert_DestroyDBEntry(certDBEntry *entry); - -SECStatus -nsslowcert_OpenCertDB(NSSLOWCERTCertDBHandle *handle, PRBool readOnly, - const char *domain, const char *prefix, - NSSLOWCERTDBNameFunc namecb, void *cbarg, PRBool openVolatile); - -void -nsslowcert_ClosePermCertDB(NSSLOWCERTCertDBHandle *handle); - -/* - * is certa newer than certb? If one is expired, pick the other one. - */ -PRBool -nsslowcert_IsNewer(NSSLOWCERTCertificate *certa, NSSLOWCERTCertificate *certb); - - -SECStatus -nsslowcert_TraverseDBEntries(NSSLOWCERTCertDBHandle *handle, - certDBEntryType type, - SECStatus (* callback)(SECItem *data, SECItem *key, - certDBEntryType type, void *pdata), - void *udata ); -SECStatus -nsslowcert_TraversePermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject, - NSSLOWCERTCertCallback cb, void *cbarg); -int -nsslowcert_NumPermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject); -SECStatus -nsslowcert_TraversePermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname, NSSLOWCERTCertCallback cb, void *cbarg); - -int -nsslowcert_NumPermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname); -SECStatus -nsslowcert_GetCertTrust(NSSLOWCERTCertificate *cert, - NSSLOWCERTCertTrust *trust); - -SECStatus -nsslowcert_SaveSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, char *emailAddr, - SECItem *derSubject, SECItem *emailProfile, SECItem *profileTime); - -/* - * Change the trust attributes of a certificate and make them permanent - * in the database. - */ -SECStatus -nsslowcert_ChangeCertTrust(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust); - -PRBool -nsslowcert_needDBVerify(NSSLOWCERTCertDBHandle *handle); - -void -nsslowcert_setDBVerify(NSSLOWCERTCertDBHandle *handle, PRBool value); - -PRBool -nsslowcert_hasTrust(NSSLOWCERTCertTrust *trust); - -void -nsslowcert_DestroyGlobalLocks(void); - -void -pkcs11_freeNickname(char *nickname, char *space); - -char * -pkcs11_copyNickname(char *nickname, char *space, int spaceLen); - -void -pkcs11_freeStaticData(unsigned char *data, unsigned char *space); - -unsigned char * -pkcs11_copyStaticData(unsigned char *data, int datalen, unsigned char *space, - int spaceLen); -NSSLOWCERTCertificate * -nsslowcert_CreateCert(void); -SEC_END_PROTOS - - #endif /* _PCERTDB_H_ */ diff --git a/security/nss/lib/softoken/pcertdb.c b/security/nss/lib/softoken/pcertdb.c deleted file mode 100644 index fb7ff6b87..000000000 --- a/security/nss/lib/softoken/pcertdb.c +++ /dev/null @@ -1,5267 +0,0 @@ -/* - * 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. - */ - -/* - * Permanent Certificate database handling code - * - * $Id$ - */ -#include "prtime.h" - -#include "lowkeyti.h" -#include "pcert.h" -#include "mcom_db.h" -#include "pcert.h" -#include "secitem.h" -#include "secder.h" - -/* Call to PK11_FreeSlot below */ - -#include "secasn1.h" -#include "secerr.h" -#include "nssilock.h" -#include "prmon.h" -#include "nsslocks.h" -#include "base64.h" -#include "sechash.h" -#include "plhash.h" - -#include "cdbhdl.h" - -/* forward declaration */ -NSSLOWCERTCertificate * -nsslowcert_FindCertByDERCertNoLocking(NSSLOWCERTCertDBHandle *handle, SECItem *derCert); -static SECStatus -nsslowcert_UpdateSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, - char *emailAddr, SECItem *derSubject, SECItem *emailProfile, - SECItem *profileTime); -static SECStatus -nsslowcert_UpdatePermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust); -static SECStatus -nsslowcert_UpdateCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, - SECItem *crlKey, char *url, PRBool isKRL); - -static NSSLOWCERTCertificate *certListHead = NULL; -static NSSLOWCERTTrust *trustListHead = NULL; -static certDBEntryCert *entryListHead = NULL; -static int certListCount = 0; -static int trustListCount = 0; -static int entryListCount = 0; -#define MAX_CERT_LIST_COUNT 10 -#define MAX_TRUST_LIST_COUNT 10 -#define MAX_ENTRY_LIST_COUNT 10 - -/* - * the following functions are wrappers for the db library that implement - * a global lock to make the database thread safe. - */ -static PZLock *dbLock = NULL; - -void -certdb_InitDBLock(NSSLOWCERTCertDBHandle *handle) -{ - if (dbLock == NULL) { - nss_InitLock(&dbLock, nssILockCertDB); - PORT_Assert(dbLock != NULL); - } - - return; -} - -/* - * Acquire the global lock on the cert database. - * This lock is currently used for the following operations: - * adding or deleting a cert to either the temp or perm databases - * converting a temp to perm or perm to temp - * changing (maybe just adding!?) the trust of a cert - * chaning the DB status checking Configuration - */ -static void -nsslowcert_LockDB(NSSLOWCERTCertDBHandle *handle) -{ - PZ_EnterMonitor(handle->dbMon); - return; -} - -/* - * Free the global cert database lock. - */ -static void -nsslowcert_UnlockDB(NSSLOWCERTCertDBHandle *handle) -{ - PRStatus prstat; - - prstat = PZ_ExitMonitor(handle->dbMon); - - PORT_Assert(prstat == PR_SUCCESS); - - return; -} - -static PZLock *certRefCountLock = NULL; - -/* - * Acquire the cert reference count lock - * There is currently one global lock for all certs, but I'm putting a cert - * arg here so that it will be easy to make it per-cert in the future if - * that turns out to be necessary. - */ -static void -nsslowcert_LockCertRefCount(NSSLOWCERTCertificate *cert) -{ - if ( certRefCountLock == NULL ) { - nss_InitLock(&certRefCountLock, nssILockRefLock); - PORT_Assert(certRefCountLock != NULL); - } - - PZ_Lock(certRefCountLock); - return; -} - -/* - * Free the cert reference count lock - */ -static void -nsslowcert_UnlockCertRefCount(NSSLOWCERTCertificate *cert) -{ - PRStatus prstat; - - PORT_Assert(certRefCountLock != NULL); - - prstat = PZ_Unlock(certRefCountLock); - - PORT_Assert(prstat == PR_SUCCESS); - - return; -} - -static PZLock *certTrustLock = NULL; - -/* - * Acquire the cert trust lock - * There is currently one global lock for all certs, but I'm putting a cert - * arg here so that it will be easy to make it per-cert in the future if - * that turns out to be necessary. - */ -void -nsslowcert_LockCertTrust(NSSLOWCERTCertificate *cert) -{ - if ( certTrustLock == NULL ) { - nss_InitLock(&certTrustLock, nssILockCertDB); - PORT_Assert(certTrustLock != NULL); - } - - PZ_Lock(certTrustLock); - return; -} - -/* - * Free the cert trust lock - */ -void -nsslowcert_UnlockCertTrust(NSSLOWCERTCertificate *cert) -{ - PRStatus prstat; - - PORT_Assert(certTrustLock != NULL); - - prstat = PZ_Unlock(certTrustLock); - - PORT_Assert(prstat == PR_SUCCESS); - - return; -} - -static PZLock *freeListLock = NULL; - -/* - * Acquire the cert reference count lock - * There is currently one global lock for all certs, but I'm putting a cert - * arg here so that it will be easy to make it per-cert in the future if - * that turns out to be necessary. - */ -static void -nsslowcert_LockFreeList(void) -{ - if ( freeListLock == NULL ) { - nss_InitLock(&freeListLock, nssILockRefLock); - PORT_Assert(freeListLock != NULL); - } - - PZ_Lock(freeListLock); - return; -} - -/* - * Free the cert reference count lock - */ -static void -nsslowcert_UnlockFreeList(void) -{ - PRStatus prstat; - - PORT_Assert(freeListLock != NULL); - - prstat = PZ_Unlock(freeListLock); - - PORT_Assert(prstat == PR_SUCCESS); - - return; -} - -NSSLOWCERTCertificate * -nsslowcert_DupCertificate(NSSLOWCERTCertificate *c) -{ - if (c) { - nsslowcert_LockCertRefCount(c); - ++c->referenceCount; - nsslowcert_UnlockCertRefCount(c); - } - return c; -} - -static int -certdb_Get(DB *db, DBT *key, DBT *data, unsigned int flags) -{ - PRStatus prstat; - int ret; - - PORT_Assert(dbLock != NULL); - PZ_Lock(dbLock); - - ret = (* db->get)(db, key, data, flags); - - prstat = PZ_Unlock(dbLock); - - return(ret); -} - -static int -certdb_Put(DB *db, DBT *key, DBT *data, unsigned int flags) -{ - PRStatus prstat; - int ret = 0; - - PORT_Assert(dbLock != NULL); - PZ_Lock(dbLock); - - ret = (* db->put)(db, key, data, flags); - - prstat = PZ_Unlock(dbLock); - - return(ret); -} - -static int -certdb_Sync(DB *db, unsigned int flags) -{ - PRStatus prstat; - int ret; - - PORT_Assert(dbLock != NULL); - PZ_Lock(dbLock); - - ret = (* db->sync)(db, flags); - - prstat = PZ_Unlock(dbLock); - - return(ret); -} - -#define DB_NOT_FOUND -30991 /* from DBM 3.2 */ -static int -certdb_Del(DB *db, DBT *key, unsigned int flags) -{ - PRStatus prstat; - int ret; - - PORT_Assert(dbLock != NULL); - PZ_Lock(dbLock); - - ret = (* db->del)(db, key, flags); - - prstat = PZ_Unlock(dbLock); - - /* don't fail if the record is already deleted */ - if (ret == DB_NOT_FOUND) { - ret = 0; - } - - return(ret); -} - -static int -certdb_Seq(DB *db, DBT *key, DBT *data, unsigned int flags) -{ - PRStatus prstat; - int ret; - - PORT_Assert(dbLock != NULL); - PZ_Lock(dbLock); - - ret = (* db->seq)(db, key, data, flags); - - prstat = PZ_Unlock(dbLock); - - return(ret); -} - -static void -certdb_Close(DB *db) -{ - PRStatus prstat; - - PORT_Assert(dbLock != NULL); - PZ_Lock(dbLock); - - (* db->close)(db); - - prstat = PZ_Unlock(dbLock); - - return; -} - -void -pkcs11_freeNickname(char *nickname, char *space) -{ - if (nickname && nickname != space) { - PORT_Free(nickname); - } -} - -char * -pkcs11_copyNickname(char *nickname,char *space, int spaceLen) -{ - int len; - char *copy = NULL; - - len = PORT_Strlen(nickname)+1; - if (len <= spaceLen) { - copy = space; - PORT_Memcpy(copy,nickname,len); - } else { - copy = PORT_Strdup(nickname); - } - - return copy; -} - -void -pkcs11_freeStaticData (unsigned char *data, unsigned char *space) -{ - if (data && data != space) { - PORT_Free(data); - } -} - -unsigned char * -pkcs11_copyStaticData(unsigned char *data, int len, - unsigned char *space, int spaceLen) -{ - unsigned char *copy = NULL; - - if (len <= spaceLen) { - copy = space; - } else { - copy = (unsigned char *) PORT_Alloc(len); - } - if (copy) { - PORT_Memcpy(copy,data,len); - } - - return copy; -} - -/* - * destroy a database entry - */ -static void -DestroyDBEntry(certDBEntry *entry) -{ - PRArenaPool *arena = entry->common.arena; - - /* must be one of our certDBEntry from the free list */ - if (arena == NULL) { - certDBEntryCert *certEntry; - if ( entry->common.type != certDBEntryTypeCert) { - return; - } - certEntry = (certDBEntryCert *)entry; - - pkcs11_freeStaticData(certEntry->derCert.data, certEntry->derCertSpace); - pkcs11_freeNickname(certEntry->nickname, certEntry->nicknameSpace); - - nsslowcert_LockFreeList(); - if (entryListCount > MAX_ENTRY_LIST_COUNT) { - PORT_Free(certEntry); - } else { - entryListCount++; - PORT_Memset(certEntry, 0, sizeof( *certEntry)); - certEntry->next = entryListHead; - entryListHead = certEntry; - } - nsslowcert_UnlockFreeList(); - return; - } - - - /* Zero out the entry struct, so that any further attempts to use it - * will cause an exception (e.g. null pointer reference). */ - PORT_Memset(&entry->common, 0, sizeof entry->common); - PORT_FreeArena(arena, PR_FALSE); - - return; -} - -/* forward references */ -static void nsslowcert_DestroyCertificateNoLocking(NSSLOWCERTCertificate *cert); - -static SECStatus -DeleteDBEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryType type, SECItem *dbkey) -{ - DBT key; - int ret; - - /* init the database key */ - key.data = dbkey->data; - key.size = dbkey->len; - - dbkey->data[0] = (unsigned char)type; - - /* delete entry from database */ - ret = certdb_Del(handle->permCertDB, &key, 0 ); - if ( ret != 0 ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - ret = certdb_Sync(handle->permCertDB, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -static SECStatus -ReadDBEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCommon *entry, - SECItem *dbkey, SECItem *dbentry, PRArenaPool *arena) -{ - DBT data, key; - int ret; - unsigned char *buf; - - /* init the database key */ - key.data = dbkey->data; - key.size = dbkey->len; - - dbkey->data[0] = (unsigned char)entry->type; - - /* read entry from database */ - ret = certdb_Get(handle->permCertDB, &key, &data, 0 ); - if ( ret != 0 ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* validate the entry */ - if ( data.size < SEC_DB_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - buf = (unsigned char *)data.data; - /* version 7 has the same schema, we may be using a v7 db if we openned - * the databases readonly. */ - if (!((buf[0] == (unsigned char)CERT_DB_FILE_VERSION) - || (buf[0] == (unsigned char) CERT_DB_V7_FILE_VERSION))) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - if ( buf[1] != (unsigned char)entry->type ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* copy out header information */ - entry->version = (unsigned int)buf[0]; - entry->type = (certDBEntryType)buf[1]; - entry->flags = (unsigned int)buf[2]; - - /* format body of entry for return to caller */ - dbentry->len = data.size - SEC_DB_ENTRY_HEADER_LEN; - if ( dbentry->len ) { - if (arena) { - dbentry->data = (unsigned char *) - PORT_ArenaAlloc(arena, dbentry->len); - if ( dbentry->data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - PORT_Memcpy(dbentry->data, &buf[SEC_DB_ENTRY_HEADER_LEN], - dbentry->len); - } else { - dbentry->data = &buf[SEC_DB_ENTRY_HEADER_LEN]; - } - } else { - dbentry->data = NULL; - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/** - ** Implement low level database access - **/ -static SECStatus -WriteDBEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCommon *entry, - SECItem *dbkey, SECItem *dbentry) -{ - int ret; - DBT data, key; - unsigned char *buf; - - data.data = dbentry->data; - data.size = dbentry->len; - - buf = (unsigned char*)data.data; - - buf[0] = (unsigned char)entry->version; - buf[1] = (unsigned char)entry->type; - buf[2] = (unsigned char)entry->flags; - - key.data = dbkey->data; - key.size = dbkey->len; - - dbkey->data[0] = (unsigned char)entry->type; - - /* put the record into the database now */ - ret = certdb_Put(handle->permCertDB, &key, &data, 0); - - if ( ret != 0 ) { - goto loser; - } - - ret = certdb_Sync( handle->permCertDB, 0 ); - - if ( ret ) { - goto loser; - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * encode a database cert record - */ -static SECStatus -EncodeDBCertEntry(certDBEntryCert *entry, PRArenaPool *arena, SECItem *dbitem) -{ - unsigned int nnlen; - unsigned char *buf; - char *nn; - char zbuf = 0; - - if ( entry->nickname ) { - nn = entry->nickname; - } else { - nn = &zbuf; - } - nnlen = PORT_Strlen(nn) + 1; - - /* allocate space for encoded database record, including space - * for low level header - */ - dbitem->len = entry->derCert.len + nnlen + DB_CERT_ENTRY_HEADER_LEN + - SEC_DB_ENTRY_HEADER_LEN; - - dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* fill in database record */ - buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = ( entry->trust.sslFlags >> 8 ) & 0xff; - buf[1] = entry->trust.sslFlags & 0xff; - buf[2] = ( entry->trust.emailFlags >> 8 ) & 0xff; - buf[3] = entry->trust.emailFlags & 0xff; - buf[4] = ( entry->trust.objectSigningFlags >> 8 ) & 0xff; - buf[5] = entry->trust.objectSigningFlags & 0xff; - buf[6] = ( entry->derCert.len >> 8 ) & 0xff; - buf[7] = entry->derCert.len & 0xff; - buf[8] = ( nnlen >> 8 ) & 0xff; - buf[9] = nnlen & 0xff; - - PORT_Memcpy(&buf[DB_CERT_ENTRY_HEADER_LEN], entry->derCert.data, - entry->derCert.len); - - PORT_Memcpy(&buf[DB_CERT_ENTRY_HEADER_LEN + entry->derCert.len], - nn, nnlen); - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * encode a database key for a cert record - */ -static SECStatus -EncodeDBCertKey(SECItem *certKey, PRArenaPool *arena, SECItem *dbkey) -{ - unsigned int len = certKey->len + SEC_DB_KEY_HEADER_LEN; - if (arena) { - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, len); - } else { - if (dbkey->len < len) { - dbkey->data = (unsigned char *)PORT_Alloc(len); - } - } - dbkey->len = len; - if ( dbkey->data == NULL ) { - goto loser; - } - PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], - certKey->data, certKey->len); - dbkey->data[0] = certDBEntryTypeCert; - - return(SECSuccess); -loser: - return(SECFailure); -} - -static SECStatus -EncodeDBGenericKey(SECItem *certKey, PRArenaPool *arena, SECItem *dbkey, - certDBEntryType entryType) -{ - /* - * we only allow _one_ KRL key! - */ - if (entryType == certDBEntryTypeKeyRevocation) { - dbkey->len = SEC_DB_KEY_HEADER_LEN; - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; - } - dbkey->data[0] = (unsigned char) entryType; - return(SECSuccess); - } - - - dbkey->len = certKey->len + SEC_DB_KEY_HEADER_LEN; - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; - } - PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], - certKey->data, certKey->len); - dbkey->data[0] = (unsigned char) entryType; - - return(SECSuccess); -loser: - return(SECFailure); -} - -static SECStatus -DecodeDBCertEntry(certDBEntryCert *entry, SECItem *dbentry) -{ - unsigned int nnlen; - unsigned int headerlen; - int lenoff; - - /* allow updates of old versions of the database */ - switch ( entry->common.version ) { - case 5: - headerlen = DB_CERT_V5_ENTRY_HEADER_LEN; - lenoff = 3; - break; - case 6: - /* should not get here */ - PORT_Assert(0); - headerlen = DB_CERT_V6_ENTRY_HEADER_LEN; - lenoff = 3; - break; - case 7: - case 8: - headerlen = DB_CERT_ENTRY_HEADER_LEN; - lenoff = 6; - break; - default: - /* better not get here */ - PORT_Assert(0); - headerlen = DB_CERT_V5_ENTRY_HEADER_LEN; - lenoff = 3; - break; - } - - /* is record long enough for header? */ - if ( dbentry->len < headerlen ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* is database entry correct length? */ - entry->derCert.len = ( ( dbentry->data[lenoff] << 8 ) | - dbentry->data[lenoff+1] ); - nnlen = ( ( dbentry->data[lenoff+2] << 8 ) | dbentry->data[lenoff+3] ); - if ( ( entry->derCert.len + nnlen + headerlen ) - != dbentry->len) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* copy the dercert */ - - entry->derCert.data = pkcs11_copyStaticData(&dbentry->data[headerlen], - entry->derCert.len,entry->derCertSpace,sizeof(entry->derCertSpace)); - if ( entry->derCert.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* copy the nickname */ - if ( nnlen > 1 ) { - entry->nickname = (char *)pkcs11_copyStaticData( - &dbentry->data[headerlen+entry->derCert.len], nnlen, - (unsigned char *)entry->nicknameSpace, - sizeof(entry->nicknameSpace)); - if ( entry->nickname == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - } else { - entry->nickname = NULL; - } - - if ( entry->common.version < 7 ) { - /* allow updates of v5 db */ - entry->trust.sslFlags = dbentry->data[0]; - entry->trust.emailFlags = dbentry->data[1]; - entry->trust.objectSigningFlags = dbentry->data[2]; - } else { - entry->trust.sslFlags = ( dbentry->data[0] << 8 ) | dbentry->data[1]; - entry->trust.emailFlags = ( dbentry->data[2] << 8 ) | dbentry->data[3]; - entry->trust.objectSigningFlags = - ( dbentry->data[4] << 8 ) | dbentry->data[5]; - } - - return(SECSuccess); -loser: - return(SECFailure); -} - - -/* - * Create a new certDBEntryCert from existing data - */ -static certDBEntryCert * -NewDBCertEntry(SECItem *derCert, char *nickname, - NSSLOWCERTCertTrust *trust, int flags) -{ - certDBEntryCert *entry; - PRArenaPool *arena = NULL; - int nnlen; - - arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE ); - - if ( !arena ) { - goto loser; - } - - entry = (certDBEntryCert *)PORT_ArenaZAlloc(arena, sizeof(certDBEntryCert)); - - if ( entry == NULL ) { - goto loser; - } - - /* fill in the dbCert */ - entry->common.arena = arena; - entry->common.type = certDBEntryTypeCert; - entry->common.version = CERT_DB_FILE_VERSION; - entry->common.flags = flags; - - if ( trust ) { - entry->trust = *trust; - } - - entry->derCert.data = (unsigned char *)PORT_ArenaAlloc(arena, derCert->len); - if ( !entry->derCert.data ) { - goto loser; - } - entry->derCert.len = derCert->len; - PORT_Memcpy(entry->derCert.data, derCert->data, derCert->len); - - nnlen = ( nickname ? strlen(nickname) + 1 : 0 ); - - if ( nnlen ) { - entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( !entry->nickname ) { - goto loser; - } - PORT_Memcpy(entry->nickname, nickname, nnlen); - - } else { - entry->nickname = 0; - } - - return(entry); - -loser: - - /* allocation error, free arena and return */ - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); -} - -/* - * Decode a version 4 DBCert from the byte stream database format - * and construct a current database entry struct - */ -static certDBEntryCert * -DecodeV4DBCertEntry(unsigned char *buf, int len) -{ - certDBEntryCert *entry; - int certlen; - int nnlen; - PRArenaPool *arena; - - /* make sure length is at least long enough for the header */ - if ( len < DBCERT_V4_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(0); - } - - /* get other lengths */ - certlen = buf[3] << 8 | buf[4]; - nnlen = buf[5] << 8 | buf[6]; - - /* make sure DB entry is the right size */ - if ( ( certlen + nnlen + DBCERT_V4_HEADER_LEN ) != len ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(0); - } - - /* allocate arena */ - arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE ); - - if ( !arena ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); - } - - /* allocate structure and members */ - entry = (certDBEntryCert *) PORT_ArenaAlloc(arena, sizeof(certDBEntryCert)); - - if ( !entry ) { - goto loser; - } - - entry->derCert.data = (unsigned char *)PORT_ArenaAlloc(arena, certlen); - if ( !entry->derCert.data ) { - goto loser; - } - entry->derCert.len = certlen; - - if ( nnlen ) { - entry->nickname = (char *) PORT_ArenaAlloc(arena, nnlen); - if ( !entry->nickname ) { - goto loser; - } - } else { - entry->nickname = 0; - } - - entry->common.arena = arena; - entry->common.version = CERT_DB_FILE_VERSION; - entry->common.type = certDBEntryTypeCert; - entry->common.flags = 0; - entry->trust.sslFlags = buf[0]; - entry->trust.emailFlags = buf[1]; - entry->trust.objectSigningFlags = buf[2]; - - PORT_Memcpy(entry->derCert.data, &buf[DBCERT_V4_HEADER_LEN], certlen); - PORT_Memcpy(entry->nickname, &buf[DBCERT_V4_HEADER_LEN + certlen], nnlen); - - if (PORT_Strcmp(entry->nickname,"Server-Cert") == 0) { - entry->trust.sslFlags |= CERTDB_USER; - } - - return(entry); - -loser: - PORT_FreeArena(arena, PR_FALSE); - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); -} - -/* - * Encode a Certificate database entry into byte stream suitable for - * the database - */ -static SECStatus -WriteDBCertEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCert *entry) -{ - SECItem dbitem, dbkey; - PRArenaPool *tmparena = NULL; - SECItem tmpitem; - SECStatus rv; - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; - } - - rv = EncodeDBCertEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - /* get the database key and format it */ - rv = nsslowcert_KeyFromDERCert(tmparena, &entry->derCert, &tmpitem); - if ( rv == SECFailure ) { - goto loser; - } - - rv = EncodeDBCertKey(&tmpitem, tmparena, &dbkey); - if ( rv == SECFailure ) { - goto loser; - } - - /* now write it to the database */ - rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - return(SECFailure); -} - - -/* - * delete a certificate entry - */ -static SECStatus -DeleteDBCertEntry(NSSLOWCERTCertDBHandle *handle, SECItem *certKey) -{ - SECItem dbkey; - SECStatus rv; - - dbkey.data= NULL; - dbkey.len = 0; - - rv = EncodeDBCertKey(certKey, NULL, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = DeleteDBEntry(handle, certDBEntryTypeCert, &dbkey); - if ( rv == SECFailure ) { - goto loser; - } - - if (dbkey.data) { - PORT_Free(dbkey.data); - } - return(SECSuccess); - -loser: - if (dbkey.data) { - PORT_Free(dbkey.data); - } - return(SECFailure); -} - -static certDBEntryCert * -CreateCertEntry(void) -{ - certDBEntryCert *entry; - - nsslowcert_LockFreeList(); - entry = entryListHead; - if (entry) { - entryListCount--; - entryListHead = entry->next; - } - nsslowcert_UnlockFreeList(); - if (entry) { - return entry; - } - - return PORT_ZAlloc(sizeof(certDBEntryCert)); -} - -/* - * Read a certificate entry - */ -static certDBEntryCert * -ReadDBCertEntry(NSSLOWCERTCertDBHandle *handle, SECItem *certKey) -{ - certDBEntryCert *entry; - SECItem dbkey; - SECItem dbentry; - SECStatus rv; - unsigned char buf[512]; - - dbkey.data = buf; - dbkey.len = sizeof(buf); - - entry = CreateCertEntry(); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->common.arena = NULL; - entry->common.type = certDBEntryTypeCert; - - rv = EncodeDBCertKey(certKey, NULL, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, NULL); - if ( rv == SECFailure ) { - goto loser; - } - - rv = DecodeDBCertEntry(entry, &dbentry); - if ( rv != SECSuccess ) { - goto loser; - } - - pkcs11_freeStaticData(dbkey.data,buf); - dbkey.data = NULL; - return(entry); - -loser: - pkcs11_freeStaticData(dbkey.data,buf); - dbkey.data = NULL; - if ( entry ) { - - } - DestroyDBEntry((certDBEntry *)entry); - - return(NULL); -} - -/* - * encode a database cert record - */ -static SECStatus -EncodeDBCrlEntry(certDBEntryRevocation *entry, PRArenaPool *arena, SECItem *dbitem) -{ - unsigned int nnlen = 0; - unsigned char *buf; - - if (entry->url) { - nnlen = PORT_Strlen(entry->url) + 1; - } - - /* allocate space for encoded database record, including space - * for low level header - */ - dbitem->len = entry->derCrl.len + nnlen - + SEC_DB_ENTRY_HEADER_LEN + DB_CRL_ENTRY_HEADER_LEN; - - dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* fill in database record */ - buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = ( entry->derCrl.len >> 8 ) & 0xff; - buf[1] = entry->derCrl.len & 0xff; - buf[2] = ( nnlen >> 8 ) & 0xff; - buf[3] = nnlen & 0xff; - - PORT_Memcpy(&buf[DB_CRL_ENTRY_HEADER_LEN], entry->derCrl.data, - entry->derCrl.len); - - if (nnlen != 0) { - PORT_Memcpy(&buf[DB_CRL_ENTRY_HEADER_LEN + entry->derCrl.len], - entry->url, nnlen); - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -static SECStatus -DecodeDBCrlEntry(certDBEntryRevocation *entry, SECItem *dbentry) -{ - unsigned int nnlen; - - /* is record long enough for header? */ - if ( dbentry->len < DB_CRL_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* is database entry correct length? */ - entry->derCrl.len = ( ( dbentry->data[0] << 8 ) | dbentry->data[1] ); - nnlen = ( ( dbentry->data[2] << 8 ) | dbentry->data[3] ); - if ( ( entry->derCrl.len + nnlen + DB_CRL_ENTRY_HEADER_LEN ) - != dbentry->len) { - /* CRL entry is greater than 64 K. Hack to make this continue to work */ - if (dbentry->len >= (0xffff - DB_CRL_ENTRY_HEADER_LEN) - nnlen) { - entry->derCrl.len = - (dbentry->len - DB_CRL_ENTRY_HEADER_LEN) - nnlen; - } else { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - } - - /* copy the dercert */ - entry->derCrl.data = (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->derCrl.len); - if ( entry->derCrl.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->derCrl.data, &dbentry->data[DB_CRL_ENTRY_HEADER_LEN], - entry->derCrl.len); - - /* copy the url */ - entry->url = NULL; - if (nnlen != 0) { - entry->url = (char *)PORT_ArenaAlloc(entry->common.arena, nnlen); - if ( entry->url == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->url, - &dbentry->data[DB_CRL_ENTRY_HEADER_LEN + entry->derCrl.len], - nnlen); - } - - return(SECSuccess); -loser: - return(SECFailure); -} - -/* - * Create a new certDBEntryRevocation from existing data - */ -static certDBEntryRevocation * -NewDBCrlEntry(SECItem *derCrl, char * url, certDBEntryType crlType, int flags) -{ - certDBEntryRevocation *entry; - PRArenaPool *arena = NULL; - int nnlen; - - arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE ); - - if ( !arena ) { - goto loser; - } - - entry = (certDBEntryRevocation*) - PORT_ArenaZAlloc(arena, sizeof(certDBEntryRevocation)); - - if ( entry == NULL ) { - goto loser; - } - - /* fill in the dbRevolcation */ - entry->common.arena = arena; - entry->common.type = crlType; - entry->common.version = CERT_DB_FILE_VERSION; - entry->common.flags = flags; - - - entry->derCrl.data = (unsigned char *)PORT_ArenaAlloc(arena, derCrl->len); - if ( !entry->derCrl.data ) { - goto loser; - } - - if (url) { - nnlen = PORT_Strlen(url) + 1; - entry->url = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( !entry->url ) { - goto loser; - } - PORT_Memcpy(entry->url, url, nnlen); - } else { - entry->url = NULL; - } - - - entry->derCrl.len = derCrl->len; - PORT_Memcpy(entry->derCrl.data, derCrl->data, derCrl->len); - - return(entry); - -loser: - - /* allocation error, free arena and return */ - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); -} - - -static SECStatus -WriteDBCrlEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryRevocation *entry, - SECItem *crlKey ) -{ - SECItem dbkey; - PRArenaPool *tmparena = NULL; - SECItem encodedEntry; - SECStatus rv; - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; - } - - rv = EncodeDBCrlEntry(entry, tmparena, &encodedEntry); - if ( rv == SECFailure ) { - goto loser; - } - - rv = EncodeDBGenericKey(crlKey, tmparena, &dbkey, entry->common.type); - if ( rv == SECFailure ) { - goto loser; - } - - /* now write it to the database */ - rv = WriteDBEntry(handle, &entry->common, &dbkey, &encodedEntry); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - return(SECFailure); -} -/* - * delete a crl entry - */ -static SECStatus -DeleteDBCrlEntry(NSSLOWCERTCertDBHandle *handle, SECItem *crlKey, - certDBEntryType crlType) -{ - SECItem dbkey; - PRArenaPool *arena = NULL; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - rv = EncodeDBGenericKey(crlKey, arena, &dbkey, crlType); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = DeleteDBEntry(handle, crlType, &dbkey); - if ( rv == SECFailure ) { - goto loser; - } - - PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); - -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(SECFailure); -} - -/* - * Read a certificate entry - */ -static certDBEntryRevocation * -ReadDBCrlEntry(NSSLOWCERTCertDBHandle *handle, SECItem *certKey, - certDBEntryType crlType) -{ - PRArenaPool *arena = NULL; - PRArenaPool *tmparena = NULL; - certDBEntryRevocation *entry; - SECItem dbkey; - SECItem dbentry; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntryRevocation *) - PORT_ArenaAlloc(arena, sizeof(certDBEntryRevocation)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->common.arena = arena; - entry->common.type = crlType; - - rv = EncodeDBGenericKey(certKey, tmparena, &dbkey, crlType); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, NULL); - if ( rv == SECFailure ) { - goto loser; - } - - rv = DecodeDBCrlEntry(entry, &dbentry); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -void -nsslowcert_DestroyDBEntry(certDBEntry *entry) -{ - DestroyDBEntry(entry); - return; -} - -/* - * Encode a database nickname record - */ -static SECStatus -EncodeDBNicknameEntry(certDBEntryNickname *entry, PRArenaPool *arena, - SECItem *dbitem) -{ - unsigned char *buf; - - /* allocate space for encoded database record, including space - * for low level header - */ - dbitem->len = entry->subjectName.len + DB_NICKNAME_ENTRY_HEADER_LEN + - SEC_DB_ENTRY_HEADER_LEN; - - dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* fill in database record */ - buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = ( entry->subjectName.len >> 8 ) & 0xff; - buf[1] = entry->subjectName.len & 0xff; - - PORT_Memcpy(&buf[DB_NICKNAME_ENTRY_HEADER_LEN], entry->subjectName.data, - entry->subjectName.len); - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * Encode a database key for a nickname record - */ -static SECStatus -EncodeDBNicknameKey(char *nickname, PRArenaPool *arena, - SECItem *dbkey) -{ - unsigned int nnlen; - - nnlen = PORT_Strlen(nickname) + 1; /* includes null */ - - /* now get the database key and format it */ - dbkey->len = nnlen + SEC_DB_KEY_HEADER_LEN; - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; - } - PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], nickname, nnlen); - dbkey->data[0] = certDBEntryTypeNickname; - - return(SECSuccess); - -loser: - return(SECFailure); -} - -static SECStatus -DecodeDBNicknameEntry(certDBEntryNickname *entry, SECItem *dbentry, - char *nickname) -{ - /* is record long enough for header? */ - if ( dbentry->len < DB_NICKNAME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* is database entry correct length? */ - entry->subjectName.len = ( ( dbentry->data[0] << 8 ) | dbentry->data[1] ); - if (( entry->subjectName.len + DB_NICKNAME_ENTRY_HEADER_LEN ) != - dbentry->len ){ - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* copy the certkey */ - entry->subjectName.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->subjectName.len); - if ( entry->subjectName.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->subjectName.data, - &dbentry->data[DB_NICKNAME_ENTRY_HEADER_LEN], - entry->subjectName.len); - entry->subjectName.type = siBuffer; - - entry->nickname = (char *)PORT_ArenaAlloc(entry->common.arena, - PORT_Strlen(nickname)+1); - if ( entry->nickname ) { - PORT_Strcpy(entry->nickname, nickname); - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * create a new nickname entry - */ -static certDBEntryNickname * -NewDBNicknameEntry(char *nickname, SECItem *subjectName, unsigned int flags) -{ - PRArenaPool *arena = NULL; - certDBEntryNickname *entry; - int nnlen; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntryNickname *)PORT_ArenaAlloc(arena, - sizeof(certDBEntryNickname)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* init common fields */ - entry->common.arena = arena; - entry->common.type = certDBEntryTypeNickname; - entry->common.version = CERT_DB_FILE_VERSION; - entry->common.flags = flags; - - /* copy the nickname */ - nnlen = PORT_Strlen(nickname) + 1; - - entry->nickname = (char*)PORT_ArenaAlloc(arena, nnlen); - if ( entry->nickname == NULL ) { - goto loser; - } - - PORT_Memcpy(entry->nickname, nickname, nnlen); - - rv = SECITEM_CopyItem(arena, &entry->subjectName, subjectName); - if ( rv != SECSuccess ) { - goto loser; - } - - return(entry); -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -/* - * delete a nickname entry - */ -static SECStatus -DeleteDBNicknameEntry(NSSLOWCERTCertDBHandle *handle, char *nickname) -{ - PRArenaPool *arena = NULL; - SECStatus rv; - SECItem dbkey; - - if ( nickname == NULL ) { - return(SECSuccess); - } - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - rv = EncodeDBNicknameKey(nickname, arena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = DeleteDBEntry(handle, certDBEntryTypeNickname, &dbkey); - if ( rv == SECFailure ) { - goto loser; - } - - PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); - -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(SECFailure); -} - -/* - * Read a nickname entry - */ -static certDBEntryNickname * -ReadDBNicknameEntry(NSSLOWCERTCertDBHandle *handle, char *nickname) -{ - PRArenaPool *arena = NULL; - PRArenaPool *tmparena = NULL; - certDBEntryNickname *entry; - SECItem dbkey; - SECItem dbentry; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntryNickname *)PORT_ArenaAlloc(arena, - sizeof(certDBEntryNickname)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->common.arena = arena; - entry->common.type = certDBEntryTypeNickname; - - rv = EncodeDBNicknameKey(nickname, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); - if ( rv == SECFailure ) { - goto loser; - } - - /* is record long enough for header? */ - if ( dbentry.len < DB_NICKNAME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - rv = DecodeDBNicknameEntry(entry, &dbentry, nickname); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -/* - * Encode a nickname entry into byte stream suitable for - * the database - */ -static SECStatus -WriteDBNicknameEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryNickname *entry) -{ - SECItem dbitem, dbkey; - PRArenaPool *tmparena = NULL; - SECStatus rv; - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; - } - - rv = EncodeDBNicknameEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = EncodeDBNicknameKey(entry->nickname, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - /* now write it to the database */ - rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - return(SECFailure); - -} - -SECStatus -EncodeDBSMimeEntry(certDBEntrySMime *entry, PRArenaPool *arena, - SECItem *dbitem) -{ - unsigned char *buf; - - /* allocate space for encoded database record, including space - * for low level header - */ - dbitem->len = entry->subjectName.len + entry->smimeOptions.len + - entry->optionsDate.len + - DB_SMIME_ENTRY_HEADER_LEN + SEC_DB_ENTRY_HEADER_LEN; - - dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* fill in database record */ - buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = ( entry->subjectName.len >> 8 ) & 0xff; - buf[1] = entry->subjectName.len & 0xff; - buf[2] = ( entry->smimeOptions.len >> 8 ) & 0xff; - buf[3] = entry->smimeOptions.len & 0xff; - buf[4] = ( entry->optionsDate.len >> 8 ) & 0xff; - buf[5] = entry->optionsDate.len & 0xff; - - /* if no smime options, then there should not be an options date either */ - PORT_Assert( ! ( ( entry->smimeOptions.len == 0 ) && - ( entry->optionsDate.len != 0 ) ) ); - - PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN], entry->subjectName.data, - entry->subjectName.len); - if ( entry->smimeOptions.len ) { - PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN+entry->subjectName.len], - entry->smimeOptions.data, - entry->smimeOptions.len); - PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN + entry->subjectName.len + - entry->smimeOptions.len], - entry->optionsDate.data, - entry->optionsDate.len); - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * Encode a database key for a SMIME record - */ -static SECStatus -EncodeDBSMimeKey(char *emailAddr, PRArenaPool *arena, - SECItem *dbkey) -{ - unsigned int addrlen; - - addrlen = PORT_Strlen(emailAddr) + 1; /* includes null */ - - /* now get the database key and format it */ - dbkey->len = addrlen + SEC_DB_KEY_HEADER_LEN; - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; - } - PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], emailAddr, addrlen); - dbkey->data[0] = certDBEntryTypeSMimeProfile; - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * Decode a database SMIME record - */ -static SECStatus -DecodeDBSMimeEntry(certDBEntrySMime *entry, SECItem *dbentry, char *emailAddr) -{ - /* is record long enough for header? */ - if ( dbentry->len < DB_SMIME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* is database entry correct length? */ - entry->subjectName.len = ( ( dbentry->data[0] << 8 ) | dbentry->data[1] ); - entry->smimeOptions.len = ( ( dbentry->data[2] << 8 ) | dbentry->data[3] ); - entry->optionsDate.len = ( ( dbentry->data[4] << 8 ) | dbentry->data[5] ); - if (( entry->subjectName.len + entry->smimeOptions.len + - entry->optionsDate.len + DB_SMIME_ENTRY_HEADER_LEN ) != dbentry->len){ - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - /* copy the subject name */ - entry->subjectName.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->subjectName.len); - if ( entry->subjectName.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->subjectName.data, - &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN], - entry->subjectName.len); - - /* copy the smime options */ - if ( entry->smimeOptions.len ) { - entry->smimeOptions.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->smimeOptions.len); - if ( entry->smimeOptions.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->smimeOptions.data, - &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN + - entry->subjectName.len], - entry->smimeOptions.len); - } - if ( entry->optionsDate.len ) { - entry->optionsDate.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->optionsDate.len); - if ( entry->optionsDate.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->optionsDate.data, - &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN + - entry->subjectName.len + - entry->smimeOptions.len], - entry->optionsDate.len); - } - - /* both options and options date must either exist or not exist */ - if ( ( ( entry->optionsDate.len == 0 ) || - ( entry->smimeOptions.len == 0 ) ) && - entry->smimeOptions.len != entry->optionsDate.len ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - entry->emailAddr = (char *)PORT_ArenaAlloc(entry->common.arena, - PORT_Strlen(emailAddr)+1); - if ( entry->emailAddr ) { - PORT_Strcpy(entry->emailAddr, emailAddr); - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * create a new SMIME entry - */ -static certDBEntrySMime * -NewDBSMimeEntry(char *emailAddr, SECItem *subjectName, SECItem *smimeOptions, - SECItem *optionsDate, unsigned int flags) -{ - PRArenaPool *arena = NULL; - certDBEntrySMime *entry; - int addrlen; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntrySMime *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySMime)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* init common fields */ - entry->common.arena = arena; - entry->common.type = certDBEntryTypeSMimeProfile; - entry->common.version = CERT_DB_FILE_VERSION; - entry->common.flags = flags; - - /* copy the email addr */ - addrlen = PORT_Strlen(emailAddr) + 1; - - entry->emailAddr = (char*)PORT_ArenaAlloc(arena, addrlen); - if ( entry->emailAddr == NULL ) { - goto loser; - } - - PORT_Memcpy(entry->emailAddr, emailAddr, addrlen); - - /* copy the subject name */ - rv = SECITEM_CopyItem(arena, &entry->subjectName, subjectName); - if ( rv != SECSuccess ) { - goto loser; - } - - /* copy the smime options */ - if ( smimeOptions ) { - rv = SECITEM_CopyItem(arena, &entry->smimeOptions, smimeOptions); - if ( rv != SECSuccess ) { - goto loser; - } - } else { - PORT_Assert(optionsDate == NULL); - entry->smimeOptions.data = NULL; - entry->smimeOptions.len = 0; - } - - /* copy the options date */ - if ( optionsDate ) { - rv = SECITEM_CopyItem(arena, &entry->optionsDate, optionsDate); - if ( rv != SECSuccess ) { - goto loser; - } - } else { - PORT_Assert(smimeOptions == NULL); - entry->optionsDate.data = NULL; - entry->optionsDate.len = 0; - } - - return(entry); -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -/* - * delete a SMIME entry - */ -static SECStatus -DeleteDBSMimeEntry(NSSLOWCERTCertDBHandle *handle, char *emailAddr) -{ - PRArenaPool *arena = NULL; - SECStatus rv; - SECItem dbkey; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - rv = EncodeDBSMimeKey(emailAddr, arena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = DeleteDBEntry(handle, certDBEntryTypeSMimeProfile, &dbkey); - if ( rv == SECFailure ) { - goto loser; - } - - PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); - -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(SECFailure); -} - -/* - * Read a SMIME entry - */ -certDBEntrySMime * -nsslowcert_ReadDBSMimeEntry(NSSLOWCERTCertDBHandle *handle, char *emailAddr) -{ - PRArenaPool *arena = NULL; - PRArenaPool *tmparena = NULL; - certDBEntrySMime *entry; - SECItem dbkey; - SECItem dbentry; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntrySMime *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySMime)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->common.arena = arena; - entry->common.type = certDBEntryTypeSMimeProfile; - - rv = EncodeDBSMimeKey(emailAddr, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); - if ( rv == SECFailure ) { - goto loser; - } - - /* is record long enough for header? */ - if ( dbentry.len < DB_SMIME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - rv = DecodeDBSMimeEntry(entry, &dbentry, emailAddr); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -/* - * Encode a SMIME entry into byte stream suitable for - * the database - */ -static SECStatus -WriteDBSMimeEntry(NSSLOWCERTCertDBHandle *handle, certDBEntrySMime *entry) -{ - SECItem dbitem, dbkey; - PRArenaPool *tmparena = NULL; - SECStatus rv; - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; - } - - rv = EncodeDBSMimeEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = EncodeDBSMimeKey(entry->emailAddr, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - /* now write it to the database */ - rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - return(SECFailure); - -} - -/* - * Encode a database subject record - */ -static SECStatus -EncodeDBSubjectEntry(certDBEntrySubject *entry, PRArenaPool *arena, - SECItem *dbitem) -{ - unsigned char *buf; - int len; - unsigned int ncerts; - unsigned int i; - unsigned char *tmpbuf; - unsigned int nnlen = 0; - unsigned int eaddrslen = 0; - int keyidoff; - SECItem *certKeys; - SECItem *keyIDs; - - if ( entry->nickname ) { - nnlen = PORT_Strlen(entry->nickname) + 1; - } - if ( entry->emailAddrs ) { - eaddrslen = 2; - for (i=0; i < entry->nemailAddrs; i++) { - eaddrslen += PORT_Strlen(entry->emailAddrs[i]) + 1 + 2; - } - } - - ncerts = entry->ncerts; - - /* compute the length of the entry */ - keyidoff = DB_SUBJECT_ENTRY_HEADER_LEN + nnlen ; - len = keyidoff + 4 * ncerts + eaddrslen; - for ( i = 0; i < ncerts; i++ ) { - len += entry->certKeys[i].len; - len += entry->keyIDs[i].len; - } - - /* allocate space for encoded database record, including space - * for low level header - */ - dbitem->len = len + SEC_DB_ENTRY_HEADER_LEN; - - dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* fill in database record */ - buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = ( ncerts >> 8 ) & 0xff; - buf[1] = ncerts & 0xff; - buf[2] = ( nnlen >> 8 ) & 0xff; - buf[3] = nnlen & 0xff; - /* v7 email field is NULL in v8 */ - buf[4] = 0; - buf[5] = 0; - - PORT_Memcpy(&buf[DB_SUBJECT_ENTRY_HEADER_LEN], entry->nickname, nnlen); - - for ( i = 0; i < ncerts; i++ ) { - - certKeys = entry->certKeys; - keyIDs = entry->keyIDs; - - buf[keyidoff+i*2] = ( certKeys[i].len >> 8 ) & 0xff; - buf[keyidoff+1+i*2] = certKeys[i].len & 0xff; - buf[keyidoff+ncerts*2+i*2] = ( keyIDs[i].len >> 8 ) & 0xff; - buf[keyidoff+1+ncerts*2+i*2] = keyIDs[i].len & 0xff; - } - - /* temp pointer used to stuff certkeys and keyids into the buffer */ - tmpbuf = &buf[keyidoff+ncerts*4]; - - for ( i = 0; i < ncerts; i++ ) { - certKeys = entry->certKeys; - PORT_Memcpy(tmpbuf, certKeys[i].data, certKeys[i].len); - tmpbuf = tmpbuf + certKeys[i].len; - } - - for ( i = 0; i < ncerts; i++ ) { - keyIDs = entry->keyIDs; - PORT_Memcpy(tmpbuf, keyIDs[i].data, keyIDs[i].len); - tmpbuf = tmpbuf + keyIDs[i].len; - } - - if (entry->emailAddrs) { - tmpbuf[0] = (entry->nemailAddrs >> 8) & 0xff; - tmpbuf[1] = entry->nemailAddrs & 0xff; - tmpbuf += 2; - for (i=0; i < entry->nemailAddrs; i++) { - int nameLen = PORT_Strlen(entry->emailAddrs[i]) + 1; - tmpbuf[0] = (nameLen >> 8) & 0xff; - tmpbuf[1] = nameLen & 0xff; - tmpbuf += 2; - PORT_Memcpy(tmpbuf,entry->emailAddrs[i],nameLen); - tmpbuf +=nameLen; - } - } - - PORT_Assert(tmpbuf == &buf[len]); - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * Encode a database key for a subject record - */ -static SECStatus -EncodeDBSubjectKey(SECItem *derSubject, PRArenaPool *arena, - SECItem *dbkey) -{ - dbkey->len = derSubject->len + SEC_DB_KEY_HEADER_LEN; - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; - } - PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], derSubject->data, - derSubject->len); - dbkey->data[0] = certDBEntryTypeSubject; - - return(SECSuccess); - -loser: - return(SECFailure); -} - -static SECStatus -DecodeDBSubjectEntry(certDBEntrySubject *entry, SECItem *dbentry, - SECItem *derSubject) -{ - unsigned int ncerts; - PRArenaPool *arena; - unsigned int len, itemlen; - unsigned char *tmpbuf; - unsigned char *end; - unsigned int i; - SECStatus rv; - unsigned int keyidoff; - unsigned int nnlen, eaddrlen; - unsigned int stdlen; - - arena = entry->common.arena; - - rv = SECITEM_CopyItem(arena, &entry->derSubject, derSubject); - if ( rv != SECSuccess ) { - goto loser; - } - - /* is record long enough for header? */ - if ( dbentry->len < DB_SUBJECT_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - entry->ncerts = ncerts = ( ( dbentry->data[0] << 8 ) | dbentry->data[1] ); - nnlen = ( ( dbentry->data[2] << 8 ) | dbentry->data[3] ); - eaddrlen = ( ( dbentry->data[4] << 8 ) | dbentry->data[5] ); - stdlen = ncerts * 4 + DB_SUBJECT_ENTRY_HEADER_LEN + nnlen + eaddrlen; - if ( dbentry->len < stdlen) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - entry->certKeys = (SECItem *)PORT_ArenaAlloc(arena, - sizeof(SECItem) * ncerts); - entry->keyIDs = (SECItem *)PORT_ArenaAlloc(arena, - sizeof(SECItem) * ncerts); - - if ( ( entry->certKeys == NULL ) || ( entry->keyIDs == NULL ) ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - if ( nnlen > 1 ) { /* null terminator is stored */ - entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( entry->nickname == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->nickname, - &dbentry->data[DB_SUBJECT_ENTRY_HEADER_LEN], - nnlen); - } else { - entry->nickname = NULL; - } - - /* if we have an old style email entry, there is only one */ - entry->nemailAddrs = 0; - if ( eaddrlen > 1 ) { /* null terminator is stored */ - entry->emailAddrs = (char **)PORT_ArenaAlloc(arena, sizeof(char *)); - if ( entry->emailAddrs == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->emailAddrs[0] = (char *)PORT_ArenaAlloc(arena, eaddrlen); - if ( entry->emailAddrs[0] == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->emailAddrs[0], - &dbentry->data[DB_SUBJECT_ENTRY_HEADER_LEN+nnlen], - eaddrlen); - entry->nemailAddrs = 1; - } else { - entry->emailAddrs = NULL; - } - - /* collect the lengths of the certKeys and keyIDs, and total the - * overall length. - */ - keyidoff = DB_SUBJECT_ENTRY_HEADER_LEN + nnlen + eaddrlen; - len = keyidoff + 4 * ncerts; - - tmpbuf = &dbentry->data[0]; - - for ( i = 0; i < ncerts; i++ ) { - - itemlen = ( tmpbuf[keyidoff + 2*i] << 8 ) | tmpbuf[keyidoff + 1 + 2*i] ; - len += itemlen; - entry->certKeys[i].len = itemlen; - - itemlen = ( tmpbuf[keyidoff + 2*ncerts + 2*i] << 8 ) | - tmpbuf[keyidoff + 1 + 2*ncerts + 2*i] ; - len += itemlen; - entry->keyIDs[i].len = itemlen; - } - - /* is database entry correct length? */ - if ( len > dbentry->len ){ - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - tmpbuf = &tmpbuf[keyidoff + 4*ncerts]; - for ( i = 0; i < ncerts; i++ ) { - entry->certKeys[i].data = - (unsigned char *)PORT_ArenaAlloc(arena, entry->certKeys[i].len); - if ( entry->certKeys[i].data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->certKeys[i].data, tmpbuf, entry->certKeys[i].len); - tmpbuf = &tmpbuf[entry->certKeys[i].len]; - } - - for ( i = 0; i < ncerts; i++ ) { - entry->keyIDs[i].data = - (unsigned char *)PORT_ArenaAlloc(arena, entry->keyIDs[i].len); - if ( entry->keyIDs[i].data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->keyIDs[i].data, tmpbuf, entry->keyIDs[i].len); - tmpbuf = &tmpbuf[entry->keyIDs[i].len]; - } - - end = &dbentry->data[dbentry->len]; - if ((eaddrlen == 0) && (tmpbuf+1 < end)) { - /* read in the additional email addresses */ - entry->nemailAddrs = tmpbuf[0] << 8 | tmpbuf[1]; - tmpbuf += 2; - entry->emailAddrs = (char **) - PORT_ArenaAlloc(arena, entry->nemailAddrs * sizeof(char *)); - if (entry->emailAddrs == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - for (i=0; i < entry->nemailAddrs; i++) { - int nameLen; - if (tmpbuf + 2 > end) { - goto loser; - } - - nameLen = tmpbuf[0] << 8 | tmpbuf[1]; - entry->emailAddrs[i] = PORT_ArenaAlloc(arena,nameLen); - if (entry->emailAddrs == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - if (tmpbuf + (nameLen+2) > end) { - goto loser; - } - PORT_Memcpy(entry->emailAddrs[i],&tmpbuf[2],nameLen); - tmpbuf += 2 + nameLen; - } - } - - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * create a new subject entry with a single cert - */ -static certDBEntrySubject * -NewDBSubjectEntry(SECItem *derSubject, SECItem *certKey, - SECItem *keyID, char *nickname, char *emailAddr, - unsigned int flags) -{ - PRArenaPool *arena = NULL; - certDBEntrySubject *entry; - SECStatus rv; - unsigned int nnlen; - unsigned int eaddrlen; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntrySubject *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySubject)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* init common fields */ - entry->common.arena = arena; - entry->common.type = certDBEntryTypeSubject; - entry->common.version = CERT_DB_FILE_VERSION; - entry->common.flags = flags; - - /* copy the subject */ - rv = SECITEM_CopyItem(arena, &entry->derSubject, derSubject); - if ( rv != SECSuccess ) { - goto loser; - } - - entry->ncerts = 1; - entry->nemailAddrs = 0; - /* copy nickname */ - if ( nickname && ( *nickname != '\0' ) ) { - nnlen = PORT_Strlen(nickname) + 1; - entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( entry->nickname == NULL ) { - goto loser; - } - - PORT_Memcpy(entry->nickname, nickname, nnlen); - } else { - entry->nickname = NULL; - } - - /* copy email addr */ - if ( emailAddr && ( *emailAddr != '\0' ) ) { - emailAddr = nsslowcert_FixupEmailAddr(emailAddr); - if ( emailAddr == NULL ) { - entry->emailAddrs = NULL; - goto loser; - } - - eaddrlen = PORT_Strlen(emailAddr) + 1; - entry->emailAddrs = (char **)PORT_ArenaAlloc(arena, sizeof(char *)); - if ( entry->emailAddrs == NULL ) { - PORT_Free(emailAddr); - goto loser; - } - entry->emailAddrs[0] = PORT_ArenaStrdup(arena,emailAddr); - if (entry->emailAddrs[0]) { - entry->nemailAddrs = 1; - } - - PORT_Free(emailAddr); - } else { - entry->emailAddrs = NULL; - } - - /* allocate space for certKeys and keyIDs */ - entry->certKeys = (SECItem *)PORT_ArenaAlloc(arena, sizeof(SECItem)); - entry->keyIDs = (SECItem *)PORT_ArenaAlloc(arena, sizeof(SECItem)); - if ( ( entry->certKeys == NULL ) || ( entry->keyIDs == NULL ) ) { - goto loser; - } - - /* copy the certKey and keyID */ - rv = SECITEM_CopyItem(arena, &entry->certKeys[0], certKey); - if ( rv != SECSuccess ) { - goto loser; - } - rv = SECITEM_CopyItem(arena, &entry->keyIDs[0], keyID); - if ( rv != SECSuccess ) { - goto loser; - } - - return(entry); -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -/* - * delete a subject entry - */ -static SECStatus -DeleteDBSubjectEntry(NSSLOWCERTCertDBHandle *handle, SECItem *derSubject) -{ - SECItem dbkey; - PRArenaPool *arena = NULL; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - rv = EncodeDBSubjectKey(derSubject, arena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = DeleteDBEntry(handle, certDBEntryTypeSubject, &dbkey); - if ( rv == SECFailure ) { - goto loser; - } - - PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); - -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(SECFailure); -} - -/* - * Read the subject entry - */ -static certDBEntrySubject * -ReadDBSubjectEntry(NSSLOWCERTCertDBHandle *handle, SECItem *derSubject) -{ - PRArenaPool *arena = NULL; - PRArenaPool *tmparena = NULL; - certDBEntrySubject *entry; - SECItem dbkey; - SECItem dbentry; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntrySubject *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySubject)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->common.arena = arena; - entry->common.type = certDBEntryTypeSubject; - - rv = EncodeDBSubjectKey(derSubject, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); - if ( rv == SECFailure ) { - goto loser; - } - - rv = DecodeDBSubjectEntry(entry, &dbentry, derSubject); - if ( rv == SECFailure ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -/* - * Encode a subject name entry into byte stream suitable for - * the database - */ -static SECStatus -WriteDBSubjectEntry(NSSLOWCERTCertDBHandle *handle, certDBEntrySubject *entry) -{ - SECItem dbitem, dbkey; - PRArenaPool *tmparena = NULL; - SECStatus rv; - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; - } - - rv = EncodeDBSubjectEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = EncodeDBSubjectKey(&entry->derSubject, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; - } - - /* now write it to the database */ - rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - return(SECFailure); - -} - -typedef enum { nsslowcert_remove, nsslowcert_add } nsslowcertUpdateType; - -static SECStatus -nsslowcert_UpdateSubjectEmailAddr(NSSLOWCERTCertDBHandle *dbhandle, - SECItem *derSubject, char *emailAddr, nsslowcertUpdateType updateType) -{ - certDBEntrySubject *entry = NULL; - int index = -1, i; - SECStatus rv; - - if (emailAddr) { - emailAddr = nsslowcert_FixupEmailAddr(emailAddr); - if (emailAddr == NULL) { - return SECFailure; - } - } else { - return SECSuccess; - } - - entry = ReadDBSubjectEntry(dbhandle,derSubject); - if (entry == NULL) { - goto loser; - } - - if ( entry->emailAddrs ) { - for (i=0; i < entry->nemailAddrs; i++) { - if (PORT_Strcmp(entry->emailAddrs[i],emailAddr) == 0) { - index = i; - } - } - } - - - if (updateType == nsslowcert_remove) { - if (index == -1) { - return SECSuccess; - } - - entry->nemailAddrs--; - for (i=index; i < entry->nemailAddrs; i++) { - entry->emailAddrs[i] = entry->emailAddrs[i+1]; - } - } else { - char **newAddrs = NULL; - if (index != -1) { - return SECSuccess; - } - newAddrs = (char **)PORT_ArenaAlloc(entry->common.arena, - (entry->nemailAddrs+1)* sizeof(char *)); - if (!newAddrs) { - goto loser; - } - for (i=0; i < entry->nemailAddrs; i++) { - newAddrs[i] = entry->emailAddrs[i]; - } - newAddrs[entry->nemailAddrs] = - PORT_ArenaStrdup(entry->common.arena,emailAddr); - if (!newAddrs[entry->nemailAddrs]) { - goto loser; - } - entry->emailAddrs = newAddrs; - entry->nemailAddrs++; - } - - /* delete the subject entry */ - DeleteDBSubjectEntry(dbhandle, derSubject); - - /* write the new one */ - rv = WriteDBSubjectEntry(dbhandle, entry); - if ( rv != SECSuccess ) { - goto loser; - } - - DestroyDBEntry((certDBEntry *)entry); - if (emailAddr) PORT_Free(emailAddr); - return(SECSuccess); - -loser: - if (entry) DestroyDBEntry((certDBEntry *)entry); - if (emailAddr) PORT_Free(emailAddr); - return(SECFailure); -} - -/* - * writes a nickname to an existing subject entry that does not currently - * have one - */ -static SECStatus -AddNicknameToSubject(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname) -{ - certDBEntrySubject *entry; - SECStatus rv; - - if ( nickname == NULL ) { - return(SECFailure); - } - - entry = ReadDBSubjectEntry(dbhandle,&cert->derSubject); - PORT_Assert(entry != NULL); - if ( entry == NULL ) { - goto loser; - } - - PORT_Assert(entry->nickname == NULL); - if ( entry->nickname != NULL ) { - goto loser; - } - - entry->nickname = (nickname) ? - PORT_ArenaStrdup(entry->common.arena, nickname) : NULL; - - if ( entry->nickname == NULL ) { - goto loser; - } - - /* delete the subject entry */ - DeleteDBSubjectEntry(dbhandle, &cert->derSubject); - - /* write the new one */ - rv = WriteDBSubjectEntry(dbhandle, entry); - if ( rv != SECSuccess ) { - goto loser; - } - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * create a new version entry - */ -static certDBEntryVersion * -NewDBVersionEntry(unsigned int flags) -{ - PRArenaPool *arena = NULL; - certDBEntryVersion *entry; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntryVersion *)PORT_ArenaAlloc(arena, - sizeof(certDBEntryVersion)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->common.arena = arena; - entry->common.type = certDBEntryTypeVersion; - entry->common.version = CERT_DB_FILE_VERSION; - entry->common.flags = flags; - - return(entry); -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - -/* - * Read the version entry - */ -static certDBEntryVersion * -ReadDBVersionEntry(NSSLOWCERTCertDBHandle *handle) -{ - PRArenaPool *arena = NULL; - PRArenaPool *tmparena = NULL; - certDBEntryVersion *entry; - SECItem dbkey; - SECItem dbentry; - SECStatus rv; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - entry = (certDBEntryVersion *)PORT_ArenaAlloc(arena, - sizeof(certDBEntryVersion)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->common.arena = arena; - entry->common.type = certDBEntryTypeVersion; - - /* now get the database key and format it */ - dbkey.len = SEC_DB_VERSION_KEY_LEN + SEC_DB_KEY_HEADER_LEN; - dbkey.data = (unsigned char *)PORT_ArenaAlloc(tmparena, dbkey.len); - if ( dbkey.data == NULL ) { - goto loser; - } - PORT_Memcpy(&dbkey.data[SEC_DB_KEY_HEADER_LEN], SEC_DB_VERSION_KEY, - SEC_DB_VERSION_KEY_LEN); - - rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); - if (rv != SECSuccess) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(NULL); -} - - -/* - * Encode a version entry into byte stream suitable for - * the database - */ -static SECStatus -WriteDBVersionEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryVersion *entry) -{ - SECItem dbitem, dbkey; - PRArenaPool *tmparena = NULL; - SECStatus rv; - - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; - } - - /* allocate space for encoded database record, including space - * for low level header - */ - dbitem.len = SEC_DB_ENTRY_HEADER_LEN; - - dbitem.data = (unsigned char *)PORT_ArenaAlloc(tmparena, dbitem.len); - if ( dbitem.data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - /* now get the database key and format it */ - dbkey.len = SEC_DB_VERSION_KEY_LEN + SEC_DB_KEY_HEADER_LEN; - dbkey.data = (unsigned char *)PORT_ArenaAlloc(tmparena, dbkey.len); - if ( dbkey.data == NULL ) { - goto loser; - } - PORT_Memcpy(&dbkey.data[SEC_DB_KEY_HEADER_LEN], SEC_DB_VERSION_KEY, - SEC_DB_VERSION_KEY_LEN); - - /* now write it to the database */ - rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; - } - - PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); - -loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - return(SECFailure); -} - -/* - * cert is no longer a perm cert, but will remain a temp cert - */ -static SECStatus -RemovePermSubjectNode(NSSLOWCERTCertificate *cert) -{ - certDBEntrySubject *entry; - unsigned int i; - SECStatus rv; - - entry = ReadDBSubjectEntry(cert->dbhandle,&cert->derSubject); - if ( entry == NULL ) { - return(SECFailure); - } - - PORT_Assert(entry->ncerts); - rv = SECFailure; - - if ( entry->ncerts > 1 ) { - for ( i = 0; i < entry->ncerts; i++ ) { - if ( SECITEM_CompareItem(&entry->certKeys[i], &cert->certKey) == - SECEqual ) { - /* copy rest of list forward one entry */ - for ( i = i + 1; i < entry->ncerts; i++ ) { - entry->certKeys[i-1] = entry->certKeys[i]; - entry->keyIDs[i-1] = entry->keyIDs[i]; - } - entry->ncerts--; - DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); - rv = WriteDBSubjectEntry(cert->dbhandle, entry); - break; - } - } - } else { - /* no entries left, delete the perm entry in the DB */ - if ( entry->emailAddrs ) { - /* if the subject had an email record, then delete it too */ - for (i=0; i < entry->nemailAddrs; i++) { - DeleteDBSMimeEntry(cert->dbhandle, entry->emailAddrs[i]); - } - } - if ( entry->nickname ) { - DeleteDBNicknameEntry(cert->dbhandle, entry->nickname); - } - - DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); - } - DestroyDBEntry((certDBEntry *)entry); - - return(rv); -} - -/* - * add a cert to the perm subject list - */ -static SECStatus -AddPermSubjectNode(certDBEntrySubject *entry, NSSLOWCERTCertificate *cert, - char *nickname) -{ - SECItem *newCertKeys, *newKeyIDs; - unsigned int i, new_i; - SECStatus rv; - NSSLOWCERTCertificate *cmpcert; - unsigned int nnlen; - unsigned int ncerts; - PRBool added = PR_FALSE; - - PORT_Assert(entry); - ncerts = entry->ncerts; - - if ( nickname && entry->nickname ) { - /* nicknames must be the same */ - PORT_Assert(PORT_Strcmp(nickname, entry->nickname) == 0); - } - - if ( ( entry->nickname == NULL ) && ( nickname != NULL ) ) { - /* copy nickname into the entry */ - nnlen = PORT_Strlen(nickname) + 1; - entry->nickname = (char *)PORT_ArenaAlloc(entry->common.arena,nnlen); - if ( entry->nickname == NULL ) { - return(SECFailure); - } - PORT_Memcpy(entry->nickname, nickname, nnlen); - } - - /* a DB entry already exists, so add this cert */ - newCertKeys = (SECItem *)PORT_ArenaAlloc(entry->common.arena, - sizeof(SECItem) * ( ncerts + 1 ) ); - newKeyIDs = (SECItem *)PORT_ArenaAlloc(entry->common.arena, - sizeof(SECItem) * ( ncerts + 1 ) ); - - if ( ( newCertKeys == NULL ) || ( newKeyIDs == NULL ) ) { - return(SECFailure); - } - - for ( i = 0, new_i=0; i < ncerts; i++ ) { - cmpcert = nsslowcert_FindCertByKey(cert->dbhandle, - &entry->certKeys[i]); - /* The entry has been corrupted, remove it from the list */ - if (!cmpcert) { - continue; - } - - if ( nsslowcert_IsNewer(cert, cmpcert) ) { - /* insert before cmpcert */ - rv = SECITEM_CopyItem(entry->common.arena, &newCertKeys[new_i], - &cert->certKey); - if ( rv != SECSuccess ) { - return(SECFailure); - } - rv = SECITEM_CopyItem(entry->common.arena, &newKeyIDs[new_i], - &cert->subjectKeyID); - if ( rv != SECSuccess ) { - return(SECFailure); - } - new_i++; - /* copy the rest of the entry */ - for ( ; i < ncerts; i++ ,new_i++) { - newCertKeys[new_i] = entry->certKeys[i]; - newKeyIDs[new_i] = entry->keyIDs[i]; - } - - /* update certKeys and keyIDs */ - entry->certKeys = newCertKeys; - entry->keyIDs = newKeyIDs; - - /* set new count value */ - entry->ncerts = new_i; - added = PR_TRUE; - break; - } - /* copy this cert entry */ - newCertKeys[new_i] = entry->certKeys[i]; - newKeyIDs[new_i] = entry->keyIDs[i]; - new_i++; /* only increment if we copied the entries */ - } - - if ( !added ) { - /* insert new one at end */ - rv = SECITEM_CopyItem(entry->common.arena, &newCertKeys[new_i], - &cert->certKey); - if ( rv != SECSuccess ) { - return(SECFailure); - } - rv = SECITEM_CopyItem(entry->common.arena, &newKeyIDs[new_i], - &cert->subjectKeyID); - if ( rv != SECSuccess ) { - return(SECFailure); - } - new_i++; - - /* update certKeys and keyIDs */ - entry->certKeys = newCertKeys; - entry->keyIDs = newKeyIDs; - - /* increment count */ - entry->ncerts = new_i; - } - DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); - rv = WriteDBSubjectEntry(cert->dbhandle, entry); - return(rv); -} - - -SECStatus -nsslowcert_TraversePermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject, - NSSLOWCERTCertCallback cb, void *cbarg) -{ - certDBEntrySubject *entry; - unsigned int i; - NSSLOWCERTCertificate *cert; - SECStatus rv = SECSuccess; - - entry = ReadDBSubjectEntry(handle, derSubject); - - if ( entry == NULL ) { - return(SECFailure); - } - - for( i = 0; i < entry->ncerts; i++ ) { - cert = nsslowcert_FindCertByKey(handle, &entry->certKeys[i]); - if (!cert) { - continue; - } - rv = (* cb)(cert, cbarg); - nsslowcert_DestroyCertificate(cert); - if ( rv == SECFailure ) { - break; - } - } - - DestroyDBEntry((certDBEntry *)entry); - - return(rv); -} - -int -nsslowcert_NumPermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject) -{ - certDBEntrySubject *entry; - int ret; - - entry = ReadDBSubjectEntry(handle, derSubject); - - if ( entry == NULL ) { - return(SECFailure); - } - - ret = entry->ncerts; - - DestroyDBEntry((certDBEntry *)entry); - - return(ret); -} - -SECStatus -nsslowcert_TraversePermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname, NSSLOWCERTCertCallback cb, void *cbarg) -{ - certDBEntryNickname *nnentry = NULL; - certDBEntrySMime *smentry = NULL; - SECStatus rv; - SECItem *derSubject = NULL; - - nnentry = ReadDBNicknameEntry(handle, nickname); - if ( nnentry ) { - derSubject = &nnentry->subjectName; - } else { - smentry = nsslowcert_ReadDBSMimeEntry(handle, nickname); - if ( smentry ) { - derSubject = &smentry->subjectName; - } - } - - if ( derSubject ) { - rv = nsslowcert_TraversePermCertsForSubject(handle, derSubject, - cb, cbarg); - } else { - rv = SECFailure; - } - - if ( nnentry ) { - DestroyDBEntry((certDBEntry *)nnentry); - } - if ( smentry ) { - DestroyDBEntry((certDBEntry *)smentry); - } - - return(rv); -} - -int -nsslowcert_NumPermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname) -{ - certDBEntryNickname *entry; - int ret; - - entry = ReadDBNicknameEntry(handle, nickname); - - if ( entry ) { - ret = nsslowcert_NumPermCertsForSubject(handle, &entry->subjectName); - DestroyDBEntry((certDBEntry *)entry); - } else { - ret = 0; - } - return(ret); -} - -/* - * add a nickname to a cert that doesn't have one - */ -static SECStatus -AddNicknameToPermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname) -{ - certDBEntryCert *entry; - int rv; - - entry = cert->dbEntry; - PORT_Assert(entry != NULL); - if ( entry == NULL ) { - goto loser; - } - - pkcs11_freeNickname(entry->nickname,entry->nicknameSpace); - entry->nickname = NULL; - entry->nickname = pkcs11_copyNickname(nickname,entry->nicknameSpace, - sizeof(entry->nicknameSpace)); - - rv = WriteDBCertEntry(dbhandle, entry); - if ( rv ) { - goto loser; - } - - pkcs11_freeNickname(cert->nickname,cert->nicknameSpace); - cert->nickname = NULL; - cert->nickname = pkcs11_copyNickname(nickname,cert->nicknameSpace, - sizeof(cert->nicknameSpace)); - - return(SECSuccess); - -loser: - return(SECFailure); -} - -/* - * add a nickname to a cert that is already in the perm database, but doesn't - * have one yet (it is probably an e-mail cert). - */ -SECStatus -nsslowcert_AddPermNickname(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname) -{ - SECStatus rv = SECFailure; - certDBEntrySubject *entry = NULL; - certDBEntryNickname *nicknameEntry = NULL; - - nsslowcert_LockDB(dbhandle); - - entry = ReadDBSubjectEntry(dbhandle, &cert->derSubject); - if (entry == NULL) goto loser; - - if ( entry->nickname == NULL ) { - - /* no nickname for subject */ - rv = AddNicknameToSubject(dbhandle, cert, nickname); - if ( rv != SECSuccess ) { - goto loser; - } - rv = AddNicknameToPermCert(dbhandle, cert, nickname); - if ( rv != SECSuccess ) { - goto loser; - } - nicknameEntry = NewDBNicknameEntry(nickname, &cert->derSubject, 0); - if ( nicknameEntry == NULL ) { - goto loser; - } - - rv = WriteDBNicknameEntry(dbhandle, nicknameEntry); - if ( rv != SECSuccess ) { - goto loser; - } - } else { - /* subject already has a nickname */ - rv = AddNicknameToPermCert(dbhandle, cert, entry->nickname); - if ( rv != SECSuccess ) { - goto loser; - } - /* make sure nickname entry exists. If the database was corrupted, - * we may have lost the nickname entry. Add it back now */ - nicknameEntry = ReadDBNicknameEntry(dbhandle, entry->nickname); - if (nicknameEntry == NULL ) { - nicknameEntry = NewDBNicknameEntry(entry->nickname, - &cert->derSubject, 0); - if ( nicknameEntry == NULL ) { - goto loser; - } - - rv = WriteDBNicknameEntry(dbhandle, nicknameEntry); - if ( rv != SECSuccess ) { - goto loser; - } - } - } - rv = SECSuccess; - -loser: - if (entry) { - DestroyDBEntry((certDBEntry *)entry); - } - if (nicknameEntry) { - DestroyDBEntry((certDBEntry *)nicknameEntry); - } - nsslowcert_UnlockDB(dbhandle); - return(rv); -} - -static certDBEntryCert * -AddCertToPermDB(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTCertificate *cert, - char *nickname, NSSLOWCERTCertTrust *trust) -{ - certDBEntryCert *certEntry = NULL; - certDBEntryNickname *nicknameEntry = NULL; - certDBEntrySubject *subjectEntry = NULL; - int state = 0; - SECStatus rv; - PRBool donnentry = PR_FALSE; - - if ( nickname ) { - donnentry = PR_TRUE; - } - - subjectEntry = ReadDBSubjectEntry(handle, &cert->derSubject); - - if ( subjectEntry && subjectEntry->nickname ) { - donnentry = PR_FALSE; - nickname = subjectEntry->nickname; - } - - certEntry = NewDBCertEntry(&cert->derCert, nickname, trust, 0); - if ( certEntry == NULL ) { - goto loser; - } - - if ( donnentry ) { - nicknameEntry = NewDBNicknameEntry(nickname, &cert->derSubject, 0); - if ( nicknameEntry == NULL ) { - goto loser; - } - } - - rv = WriteDBCertEntry(handle, certEntry); - if ( rv != SECSuccess ) { - goto loser; - } - state = 1; - - if ( nicknameEntry ) { - rv = WriteDBNicknameEntry(handle, nicknameEntry); - if ( rv != SECSuccess ) { - goto loser; - } - } - - state = 2; - - cert->dbhandle = handle; - - /* add to or create new subject entry */ - if ( subjectEntry ) { - /* REWRITE BASED ON SUBJECT ENTRY */ - cert->dbhandle = handle; - rv = AddPermSubjectNode(subjectEntry, cert, nickname); - if ( rv != SECSuccess ) { - goto loser; - } - } else { - /* make a new subject entry - this case is only used when updating - * an old version of the database. This is OK because the oldnickname - * db format didn't allow multiple certs with the same subject. - */ - /* where does subjectKeyID and certKey come from? */ - subjectEntry = NewDBSubjectEntry(&cert->derSubject, &cert->certKey, - &cert->subjectKeyID, nickname, - NULL, 0); - if ( subjectEntry == NULL ) { - goto loser; - } - rv = WriteDBSubjectEntry(handle, subjectEntry); - if ( rv != SECSuccess ) { - goto loser; - } - } - - state = 3; - - if ( nicknameEntry ) { - DestroyDBEntry((certDBEntry *)nicknameEntry); - } - - if ( subjectEntry ) { - DestroyDBEntry((certDBEntry *)subjectEntry); - } - - return(certEntry); - -loser: - /* don't leave partial entry in the database */ - if ( state > 0 ) { - rv = DeleteDBCertEntry(handle, &cert->certKey); - } - if ( ( state > 1 ) && donnentry ) { - rv = DeleteDBNicknameEntry(handle, nickname); - } - if ( state > 2 ) { - rv = DeleteDBSubjectEntry(handle, &cert->derSubject); - } - if ( certEntry ) { - DestroyDBEntry((certDBEntry *)certEntry); - } - if ( nicknameEntry ) { - DestroyDBEntry((certDBEntry *)nicknameEntry); - } - if ( subjectEntry ) { - DestroyDBEntry((certDBEntry *)subjectEntry); - } - - return(NULL); -} - -/* forward declaration */ -static SECStatus -UpdateV7DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb); - -/* - * version 8 uses the same schema as version 7. The only differences are - * 1) version 8 db uses the blob shim to store data entries > 32k. - * 2) version 8 db sets the db block size to 32k. - * both of these are dealt with by the handle. - */ - -static SECStatus -UpdateV8DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) -{ - return UpdateV7DB(handle,updatedb); -} - - -/* - * we could just blindly sequence through reading key data pairs and writing - * them back out, but some cert.db's have gotten quite large and may have some - * subtle corruption problems, so instead we cycle through the certs and - * CRL's and S/MIME profiles and rebuild our subject lists from those records. - */ -static SECStatus -UpdateV7DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) -{ - DBT key, data; - int ret; - NSSLOWCERTCertificate *cert; - PRBool isKRL = PR_FALSE; - certDBEntryType entryType; - SECItem dbEntry, dbKey; - certDBEntryRevocation crlEntry; - certDBEntryCert certEntry; - certDBEntrySMime smimeEntry; - SECStatus rv; - - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); - - if ( ret ) { - return(SECFailure); - } - - do { - unsigned char *dataBuf = (unsigned char *)data.data; - unsigned char *keyBuf = (unsigned char *)key.data; - dbEntry.data = &dataBuf[SEC_DB_ENTRY_HEADER_LEN]; - dbEntry.len = data.size - SEC_DB_ENTRY_HEADER_LEN; - entryType = (certDBEntryType) keyBuf[0]; - dbKey.data = &keyBuf[SEC_DB_KEY_HEADER_LEN]; - dbKey.len = key.size - SEC_DB_KEY_HEADER_LEN; - if ((dbEntry.len <= 0) || (dbKey.len <= 0)) { - continue; - } - - switch (entryType) { - /* these entries will get regenerated as we read the - * rest of the data from the database */ - case certDBEntryTypeVersion: - case certDBEntryTypeSubject: - case certDBEntryTypeContentVersion: - case certDBEntryTypeNickname: - break; - - case certDBEntryTypeCert: - /* decode Entry */ - certEntry.common.version = (unsigned int)dataBuf[0]; - certEntry.common.type = entryType; - certEntry.common.flags = (unsigned int)dataBuf[2]; - rv = DecodeDBCertEntry(&certEntry,&dbEntry); - if (rv != SECSuccess) { - break; - } - /* should we check for existing duplicates? */ - cert = nsslowcert_DecodeDERCertificate(&certEntry.derCert, - certEntry.nickname); - if (cert) { - nsslowcert_UpdatePermCert(handle, cert, certEntry.nickname, - &certEntry.trust); - nsslowcert_DestroyCertificate(cert); - } - /* free any data the decode may have allocated. */ - pkcs11_freeStaticData(certEntry.derCert.data, - certEntry.derCertSpace); - pkcs11_freeNickname(certEntry.nickname, certEntry.nicknameSpace); - break; - - case certDBEntryTypeKeyRevocation: - isKRL = PR_TRUE; - /* fall through */ - case certDBEntryTypeRevocation: - crlEntry.common.version = (unsigned int)dataBuf[0]; - crlEntry.common.type = entryType; - crlEntry.common.flags = (unsigned int)dataBuf[2]; - crlEntry.common.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (crlEntry.common.arena == NULL) { - break; - } - rv = DecodeDBCrlEntry(&crlEntry,&dbEntry); - if (rv != SECSuccess) { - break; - } - nsslowcert_UpdateCrl(handle, &crlEntry.derCrl, &dbKey, - crlEntry.url, isKRL); - /* free data allocated by the decode */ - PORT_FreeArena(crlEntry.common.arena, PR_FALSE); - crlEntry.common.arena = NULL; - break; - - case certDBEntryTypeSMimeProfile: - smimeEntry.common.version = (unsigned int)dataBuf[0]; - smimeEntry.common.type = entryType; - smimeEntry.common.flags = (unsigned int)dataBuf[2]; - smimeEntry.common.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - rv = DecodeDBSMimeEntry(&smimeEntry,&dbEntry,(char *)dbKey.data); - /* decode entry */ - nsslowcert_UpdateSMimeProfile(handle, smimeEntry.emailAddr, - &smimeEntry.subjectName, &smimeEntry.smimeOptions, - &smimeEntry.optionsDate); - PORT_FreeArena(smimeEntry.common.arena, PR_FALSE); - smimeEntry.common.arena = NULL; - break; - default: - break; - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); - - (* updatedb->close)(updatedb); - - /* a database update is a good time to go back and verify the integrity of - * the keys and certs */ - handle->dbVerify = PR_TRUE; - return(SECSuccess); -} - -/* - * NOTE - Version 6 DB did not go out to the real world in a release, - * so we can remove this function in a later release. - */ -static SECStatus -UpdateV6DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) -{ - int ret; - DBT key, data; - unsigned char *buf, *tmpbuf = NULL; - certDBEntryType type; - certDBEntryNickname *nnEntry = NULL; - certDBEntrySubject *subjectEntry = NULL; - certDBEntrySMime *emailEntry = NULL; - char *nickname; - char *emailAddr; - SECStatus rv; - - /* - * Sequence through the old database and copy all of the entries - * to the new database. Subject name entries will have the new - * fields inserted into them (with zero length). - */ - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); - } - - do { - buf = (unsigned char *)data.data; - - if ( data.size >= 3 ) { - if ( buf[0] == 6 ) { /* version number */ - type = (certDBEntryType)buf[1]; - if ( type == certDBEntryTypeSubject ) { - /* expando subjecto entrieo */ - tmpbuf = (unsigned char *)PORT_Alloc(data.size + 4); - if ( tmpbuf ) { - /* copy header stuff */ - PORT_Memcpy(tmpbuf, buf, SEC_DB_ENTRY_HEADER_LEN + 2); - /* insert 4 more bytes of zero'd header */ - PORT_Memset(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 2], - 0, 4); - /* copy rest of the data */ - PORT_Memcpy(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 6], - &buf[SEC_DB_ENTRY_HEADER_LEN + 2], - data.size - (SEC_DB_ENTRY_HEADER_LEN + 2)); - - data.data = (void *)tmpbuf; - data.size += 4; - buf = tmpbuf; - } - } else if ( type == certDBEntryTypeCert ) { - /* expando certo entrieo */ - tmpbuf = (unsigned char *)PORT_Alloc(data.size + 3); - if ( tmpbuf ) { - /* copy header stuff */ - PORT_Memcpy(tmpbuf, buf, SEC_DB_ENTRY_HEADER_LEN); - - /* copy trust flage, setting msb's to 0 */ - tmpbuf[SEC_DB_ENTRY_HEADER_LEN] = 0; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+1] = - buf[SEC_DB_ENTRY_HEADER_LEN]; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+2] = 0; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+3] = - buf[SEC_DB_ENTRY_HEADER_LEN+1]; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+4] = 0; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+5] = - buf[SEC_DB_ENTRY_HEADER_LEN+2]; - - /* copy rest of the data */ - PORT_Memcpy(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 6], - &buf[SEC_DB_ENTRY_HEADER_LEN + 3], - data.size - (SEC_DB_ENTRY_HEADER_LEN + 3)); - - data.data = (void *)tmpbuf; - data.size += 3; - buf = tmpbuf; - } - - } - - /* update the record version number */ - buf[0] = CERT_DB_FILE_VERSION; - - /* copy to the new database */ - ret = certdb_Put(handle->permCertDB, &key, &data, 0); - if ( tmpbuf ) { - PORT_Free(tmpbuf); - tmpbuf = NULL; - } - } - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); - - ret = certdb_Sync(handle->permCertDB, 0); - - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); - } - - do { - buf = (unsigned char *)data.data; - - if ( data.size >= 3 ) { - if ( buf[0] == CERT_DB_FILE_VERSION ) { /* version number */ - type = (certDBEntryType)buf[1]; - if ( type == certDBEntryTypeNickname ) { - nickname = &((char *)key.data)[1]; - - /* get the matching nickname entry in the new DB */ - nnEntry = ReadDBNicknameEntry(handle, nickname); - if ( nnEntry == NULL ) { - goto endloop; - } - - /* find the subject entry pointed to by nickname */ - subjectEntry = ReadDBSubjectEntry(handle, - &nnEntry->subjectName); - if ( subjectEntry == NULL ) { - goto endloop; - } - - subjectEntry->nickname = - (char *)PORT_ArenaAlloc(subjectEntry->common.arena, - key.size - 1); - if ( subjectEntry->nickname ) { - PORT_Memcpy(subjectEntry->nickname, nickname, - key.size - 1); - rv = WriteDBSubjectEntry(handle, subjectEntry); - } - } else if ( type == certDBEntryTypeSMimeProfile ) { - emailAddr = &((char *)key.data)[1]; - - /* get the matching smime entry in the new DB */ - emailEntry = nsslowcert_ReadDBSMimeEntry(handle, emailAddr); - if ( emailEntry == NULL ) { - goto endloop; - } - - /* find the subject entry pointed to by nickname */ - subjectEntry = ReadDBSubjectEntry(handle, - &emailEntry->subjectName); - if ( subjectEntry == NULL ) { - goto endloop; - } - - subjectEntry->emailAddrs = (char **) - PORT_ArenaAlloc(subjectEntry->common.arena, - sizeof(char *)); - if ( subjectEntry->emailAddrs ) { - subjectEntry->emailAddrs[0] = - (char *)PORT_ArenaAlloc(subjectEntry->common.arena, - key.size - 1); - if ( subjectEntry->emailAddrs[0] ) { - PORT_Memcpy(subjectEntry->emailAddrs[0], emailAddr, - key.size - 1); - subjectEntry->nemailAddrs = 1; - rv = WriteDBSubjectEntry(handle, subjectEntry); - } - } - } - -endloop: - if ( subjectEntry ) { - DestroyDBEntry((certDBEntry *)subjectEntry); - subjectEntry = NULL; - } - if ( nnEntry ) { - DestroyDBEntry((certDBEntry *)nnEntry); - nnEntry = NULL; - } - if ( emailEntry ) { - DestroyDBEntry((certDBEntry *)emailEntry); - emailEntry = NULL; - } - } - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); - - ret = certdb_Sync(handle->permCertDB, 0); - - (* updatedb->close)(updatedb); - return(SECSuccess); -} - - -static SECStatus -updateV5Callback(NSSLOWCERTCertificate *cert, SECItem *k, void *pdata) -{ - NSSLOWCERTCertDBHandle *handle; - certDBEntryCert *entry; - NSSLOWCERTCertTrust *trust; - - handle = (NSSLOWCERTCertDBHandle *)pdata; - trust = &cert->dbEntry->trust; - - /* SSL user certs can be used for email if they have an email addr */ - if ( cert->emailAddr && ( trust->sslFlags & CERTDB_USER ) && - ( trust->emailFlags == 0 ) ) { - trust->emailFlags = CERTDB_USER; - } - /* servers didn't set the user flags on the server cert.. */ - if (PORT_Strcmp(cert->dbEntry->nickname,"Server-Cert") == 0) { - trust->sslFlags |= CERTDB_USER; - } - - entry = AddCertToPermDB(handle, cert, cert->dbEntry->nickname, - &cert->dbEntry->trust); - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); - } - - return(SECSuccess); -} - -static SECStatus -UpdateV5DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) -{ - NSSLOWCERTCertDBHandle updatehandle; - SECStatus rv; - - updatehandle.permCertDB = updatedb; - updatehandle.dbMon = PZ_NewMonitor(nssILockCertDB); - - rv = nsslowcert_TraversePermCerts(&updatehandle, updateV5Callback, - (void *)handle); - - PZ_DestroyMonitor(updatehandle.dbMon); - - (* updatedb->close)(updatedb); - return(SECSuccess); -} - -static PRBool -isV4DB(DB *db) { - DBT key,data; - int ret; - - key.data = "Version"; - key.size = 7; - - ret = (*db->get)(db, &key, &data, 0); - if (ret) { - return PR_FALSE; - } - - if ((data.size == 1) && (*(unsigned char *)data.data <= 4)) { - return PR_TRUE; - } - - return PR_FALSE; -} - -static SECStatus -UpdateV4DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) -{ - DBT key, data; - certDBEntryCert *entry, *entry2; - int ret; - PRArenaPool *arena = NULL; - NSSLOWCERTCertificate *cert; - - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); - - if ( ret ) { - return(SECFailure); - } - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - return(SECFailure); - } - - do { - if ( data.size != 1 ) { /* skip version number */ - - /* decode the old DB entry */ - entry = (certDBEntryCert *) - DecodeV4DBCertEntry((unsigned char*)data.data, data.size); - - if ( entry ) { - cert = nsslowcert_DecodeDERCertificate(&entry->derCert, - entry->nickname); - - if ( cert != NULL ) { - /* add to new database */ - entry2 = AddCertToPermDB(handle, cert, entry->nickname, - &entry->trust); - - nsslowcert_DestroyCertificate(cert); - if ( entry2 ) { - DestroyDBEntry((certDBEntry *)entry2); - } - } - DestroyDBEntry((certDBEntry *)entry); - } - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); - - PORT_FreeArena(arena, PR_FALSE); - (* updatedb->close)(updatedb); - return(SECSuccess); -} - - -/* - * return true if a database key conflict exists - */ -PRBool -nsslowcert_CertDBKeyConflict(SECItem *derCert, NSSLOWCERTCertDBHandle *handle) -{ - SECStatus rv; - DBT tmpdata; - DBT namekey; - int ret; - SECItem keyitem; - PRArenaPool *arena = NULL; - SECItem derKey; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - /* get the db key of the cert */ - rv = nsslowcert_KeyFromDERCert(arena, derCert, &derKey); - if ( rv != SECSuccess ) { - goto loser; - } - - rv = EncodeDBCertKey(&derKey, arena, &keyitem); - if ( rv != SECSuccess ) { - goto loser; - } - - namekey.data = keyitem.data; - namekey.size = keyitem.len; - - ret = certdb_Get(handle->permCertDB, &namekey, &tmpdata, 0); - if ( ret == 0 ) { - goto loser; - } - - PORT_FreeArena(arena, PR_FALSE); - - return(PR_FALSE); -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return(PR_TRUE); -} - -/* - * return true if a nickname conflict exists - * NOTE: caller must have already made sure that this exact cert - * doesn't exist in the DB - */ -static PRBool -nsslowcert_CertNicknameConflict(char *nickname, SECItem *derSubject, - NSSLOWCERTCertDBHandle *handle) -{ - PRBool rv; - certDBEntryNickname *entry; - - if ( nickname == NULL ) { - return(PR_FALSE); - } - - entry = ReadDBNicknameEntry(handle, nickname); - - if ( entry == NULL ) { - /* no entry for this nickname, so no conflict */ - return(PR_FALSE); - } - - rv = PR_TRUE; - if ( SECITEM_CompareItem(derSubject, &entry->subjectName) == SECEqual ) { - /* if subject names are the same, then no conflict */ - rv = PR_FALSE; - } - - DestroyDBEntry((certDBEntry *)entry); - return(rv); -} - -#ifdef DBM_USING_NSPR -#define NO_RDONLY PR_RDONLY -#define NO_RDWR PR_RDWR -#define NO_CREATE (PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE) -#else -#define NO_RDONLY O_RDONLY -#define NO_RDWR O_RDWR -#define NO_CREATE (O_RDWR | O_CREAT | O_TRUNC) -#endif - -/* - * open an old database that needs to be updated - */ -static DB * -nsslowcert_openolddb(NSSLOWCERTDBNameFunc namecb, void *cbarg, int version) -{ - char * tmpname; - DB *updatedb = NULL; - - tmpname = (* namecb)(cbarg, version); /* get v6 db name */ - if ( tmpname ) { - updatedb = dbopen( tmpname, NO_RDONLY, 0600, DB_HASH, 0 ); - PORT_Free(tmpname); - } - return updatedb; -} - -static SECStatus -openNewCertDB(const char *appName, const char *prefix, const char *certdbname, - NSSLOWCERTCertDBHandle *handle, NSSLOWCERTDBNameFunc namecb, void *cbarg) -{ - SECStatus rv; - certDBEntryVersion *versionEntry = NULL; - DB *updatedb = NULL; - int status = RDB_FAIL; - - if (appName) { - handle->permCertDB=rdbopen( appName, prefix, "cert", NO_CREATE, &status); - } else { - handle->permCertDB=dbsopen(certdbname, NO_CREATE, 0600, DB_HASH, 0); - } - - /* if create fails then we lose */ - if ( handle->permCertDB == 0 ) { - return status == RDB_RETRY ? SECWouldBlock : SECFailure; - } - - rv = db_BeginTransaction(handle->permCertDB); - if (rv != SECSuccess) { - db_InitComplete(handle->permCertDB); - return SECFailure; - } - - /* Verify version number; */ - - if (appName) { - updatedb = dbsopen(certdbname, NO_RDONLY, 0600, DB_HASH, 0); - if (updatedb) { - rv = UpdateV8DB(handle, updatedb); - db_FinishTransaction(handle->permCertDB,PR_FALSE); - db_InitComplete(handle->permCertDB); - return(rv); - } - } - - versionEntry = NewDBVersionEntry(0); - if ( versionEntry == NULL ) { - rv = SECFailure; - goto loser; - } - - rv = WriteDBVersionEntry(handle, versionEntry); - - DestroyDBEntry((certDBEntry *)versionEntry); - - if ( rv != SECSuccess ) { - goto loser; - } - - /* rv must already be Success here because of previous if statement */ - /* try to upgrade old db here */ - if ((updatedb = nsslowcert_openolddb(namecb,cbarg,7)) != NULL) { - rv = UpdateV7DB(handle, updatedb); - } else if ((updatedb = nsslowcert_openolddb(namecb,cbarg,6)) != NULL) { - rv = UpdateV6DB(handle, updatedb); - } else if ((updatedb = nsslowcert_openolddb(namecb,cbarg,5)) != NULL) { - rv = UpdateV5DB(handle, updatedb); - } else if ((updatedb = nsslowcert_openolddb(namecb,cbarg,4)) != NULL) { - /* NES has v5 format db's with v4 db names! */ - if (isV4DB(updatedb)) { - rv = UpdateV4DB(handle,updatedb); - } else { - rv = UpdateV5DB(handle,updatedb); - } - } - - -loser: - db_FinishTransaction(handle->permCertDB,rv != SECSuccess); - db_InitComplete(handle->permCertDB); - return rv; -} - -static int -nsslowcert_GetVersionNumber( NSSLOWCERTCertDBHandle *handle) -{ - certDBEntryVersion *versionEntry = NULL; - int version = 0; - - versionEntry = ReadDBVersionEntry(handle); - if ( versionEntry == NULL ) { - return 0; - } - version = versionEntry->common.version; - DestroyDBEntry((certDBEntry *)versionEntry); - return version; -} - -/* - * Open the certificate database and index databases. Create them if - * they are not there or bad. - */ -static SECStatus -nsslowcert_OpenPermCertDB(NSSLOWCERTCertDBHandle *handle, PRBool readOnly, - const char *appName, const char *prefix, - NSSLOWCERTDBNameFunc namecb, void *cbarg) -{ - SECStatus rv; - int openflags; - char *certdbname; - int version = 0; - - certdbname = (* namecb)(cbarg, CERT_DB_FILE_VERSION); - if ( certdbname == NULL ) { - return(SECFailure); - } - - openflags = readOnly ? NO_RDONLY : NO_RDWR; - - /* - * first open the permanent file based database. - */ - if (appName) { - handle->permCertDB = rdbopen( appName, prefix, "cert", openflags, NULL); - } else { - handle->permCertDB = dbsopen( certdbname, openflags, 0600, DB_HASH, 0 ); - } - - /* check for correct version number */ - if ( handle->permCertDB ) { - version = nsslowcert_GetVersionNumber(handle); - if ((version != CERT_DB_FILE_VERSION) && - !(appName && version == CERT_DB_V7_FILE_VERSION)) { - goto loser; - } - } else if ( readOnly ) { - /* don't create if readonly */ - /* Try openning a version 7 database */ - handle->permCertDB = nsslowcert_openolddb(namecb,cbarg, 7); - if (!handle->permCertDB) { - goto loser; - } - if (nsslowcert_GetVersionNumber(handle) != 7) { - goto loser; - } - } else { - /* if first open fails, try to create a new DB */ - rv = openNewCertDB(appName,prefix,certdbname,handle,namecb,cbarg); - if (rv == SECWouldBlock) { - /* only the rdb version can fail with wouldblock */ - handle->permCertDB = - rdbopen( appName, prefix, "cert", openflags, NULL); - - /* check for correct version number */ - if ( !handle->permCertDB ) { - goto loser; - } - version = nsslowcert_GetVersionNumber(handle); - if ((version != CERT_DB_FILE_VERSION) && - !(appName && version == CERT_DB_V7_FILE_VERSION)) { - goto loser; - } - } else if (rv != SECSuccess) { - goto loser; - } - } - - PORT_Free(certdbname); - - return (SECSuccess); - -loser: - - PORT_SetError(SEC_ERROR_BAD_DATABASE); - - if ( handle->permCertDB ) { - certdb_Close(handle->permCertDB); - handle->permCertDB = 0; - } - - PORT_Free(certdbname); - - return(SECFailure); -} - -/* - * delete all DB records associated with a particular certificate - */ -static SECStatus -DeletePermCert(NSSLOWCERTCertificate *cert) -{ - SECStatus rv; - SECStatus ret; - - ret = SECSuccess; - - rv = DeleteDBCertEntry(cert->dbhandle, &cert->certKey); - if ( rv != SECSuccess ) { - ret = SECFailure; - } - - rv = RemovePermSubjectNode(cert); - - - return(ret); -} - -/* - * Delete a certificate from the permanent database. - */ -SECStatus -nsslowcert_DeletePermCertificate(NSSLOWCERTCertificate *cert) -{ - SECStatus rv; - - nsslowcert_LockDB(cert->dbhandle); - - rv = db_BeginTransaction(cert->dbhandle->permCertDB); - if ( rv != SECSuccess ) { - goto loser; - } - /* delete the records from the permanent database */ - rv = DeletePermCert(cert); - - /* get rid of dbcert and stuff pointing to it */ - DestroyDBEntry((certDBEntry *)cert->dbEntry); - cert->dbEntry = NULL; - cert->trust = NULL; - - db_FinishTransaction(cert->dbhandle->permCertDB,rv != SECSuccess); -loser: - - nsslowcert_UnlockDB(cert->dbhandle); - return(rv); -} - -/* - * Traverse all of the entries in the database of a particular type - * call the given function for each one. - */ -SECStatus -nsslowcert_TraverseDBEntries(NSSLOWCERTCertDBHandle *handle, - certDBEntryType type, - SECStatus (* callback)(SECItem *data, SECItem *key, - certDBEntryType type, void *pdata), - void *udata ) -{ - DBT data; - DBT key; - SECStatus rv; - int ret; - SECItem dataitem; - SECItem keyitem; - unsigned char *buf; - unsigned char *keybuf; - - ret = certdb_Seq(handle->permCertDB, &key, &data, R_FIRST); - - if ( ret ) { - return(SECFailure); - } - - do { - buf = (unsigned char *)data.data; - - if ( buf[1] == (unsigned char)type ) { - dataitem.len = data.size; - dataitem.data = buf; - dataitem.type = siBuffer; - keyitem.len = key.size - SEC_DB_KEY_HEADER_LEN; - keybuf = (unsigned char *)key.data; - keyitem.data = &keybuf[SEC_DB_KEY_HEADER_LEN]; - keyitem.type = siBuffer; - - rv = (* callback)(&dataitem, &keyitem, type, udata); - if ( rv != SECSuccess ) { - return(rv); - } - } - } while ( certdb_Seq(handle->permCertDB, &key, &data, R_NEXT) == 0 ); - - return(SECSuccess); -} -/* - * Decode a certificate and enter it into the temporary certificate database. - * Deal with nicknames correctly - * - * This is the private entry point. - */ -static NSSLOWCERTCertificate * -DecodeACert(NSSLOWCERTCertDBHandle *handle, certDBEntryCert *entry) -{ - NSSLOWCERTCertificate *cert = NULL; - - cert = nsslowcert_DecodeDERCertificate(&entry->derCert, entry->nickname ); - - if ( cert == NULL ) { - goto loser; - } - - cert->dbhandle = handle; - cert->dbEntry = entry; - cert->trust = &entry->trust; - - return(cert); - -loser: - return(0); -} - -static NSSLOWCERTTrust * -CreateTrust(void) -{ - NSSLOWCERTTrust *trust = NULL; - - nsslowcert_LockFreeList(); - trust = trustListHead; - if (trust) { - trustListCount--; - trustListHead = trust->next; - } - nsslowcert_UnlockFreeList(); - if (trust) { - return trust; - } - - return PORT_ZAlloc(sizeof(NSSLOWCERTTrust)); -} - - -static NSSLOWCERTTrust * -DecodeTrustEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCert *entry, SECItem *dbKey) -{ - NSSLOWCERTTrust *trust = CreateTrust(); - if (trust == NULL) { - return trust; - } - trust->dbhandle = handle; - trust->dbEntry = entry; - trust->dbKey.data = pkcs11_copyStaticData(dbKey->data,dbKey->len, - trust->dbKeySpace, sizeof(trust->dbKeySpace)); - if (!trust->dbKey.data) { - PORT_Free(trust); - return NULL; - } - trust->dbKey.len = dbKey->len; - - trust->trust = &entry->trust; - trust->derCert = &entry->derCert; - - return(trust); -} - -typedef struct { - PermCertCallback certfunc; - NSSLOWCERTCertDBHandle *handle; - void *data; -} PermCertCallbackState; - -/* - * traversal callback to decode certs and call callers callback - */ -static SECStatus -certcallback(SECItem *dbdata, SECItem *dbkey, certDBEntryType type, void *data) -{ - PermCertCallbackState *mystate; - SECStatus rv; - certDBEntryCert *entry; - SECItem entryitem; - NSSLOWCERTCertificate *cert; - PRArenaPool *arena = NULL; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - entry = (certDBEntryCert *)PORT_ArenaAlloc(arena, sizeof(certDBEntryCert)); - mystate = (PermCertCallbackState *)data; - entry->common.version = (unsigned int)dbdata->data[0]; - entry->common.type = (certDBEntryType)dbdata->data[1]; - entry->common.flags = (unsigned int)dbdata->data[2]; - entry->common.arena = arena; - - entryitem.len = dbdata->len - SEC_DB_ENTRY_HEADER_LEN; - entryitem.data = &dbdata->data[SEC_DB_ENTRY_HEADER_LEN]; - - rv = DecodeDBCertEntry(entry, &entryitem); - if (rv != SECSuccess ) { - goto loser; - } - entry->derCert.type = siBuffer; - - /* note: Entry is 'inheritted'. */ - cert = DecodeACert(mystate->handle, entry); - - rv = (* mystate->certfunc)(cert, dbkey, mystate->data); - - /* arena stored in entry destroyed by nsslowcert_DestroyCertificate */ - nsslowcert_DestroyCertificateNoLocking(cert); - - return(rv); - -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - return(SECFailure); -} - -/* - * Traverse all of the certificates in the permanent database and - * call the given function for each one; expect the caller to have lock. - */ -static SECStatus -TraversePermCertsNoLocking(NSSLOWCERTCertDBHandle *handle, - SECStatus (* certfunc)(NSSLOWCERTCertificate *cert, - SECItem *k, - void *pdata), - void *udata ) -{ - SECStatus rv; - PermCertCallbackState mystate; - - mystate.certfunc = certfunc; - mystate.handle = handle; - mystate.data = udata; - rv = nsslowcert_TraverseDBEntries(handle, certDBEntryTypeCert, certcallback, - (void *)&mystate); - - return(rv); -} - -/* - * Traverse all of the certificates in the permanent database and - * call the given function for each one. - */ -SECStatus -nsslowcert_TraversePermCerts(NSSLOWCERTCertDBHandle *handle, - SECStatus (* certfunc)(NSSLOWCERTCertificate *cert, SECItem *k, - void *pdata), - void *udata ) -{ - SECStatus rv; - - nsslowcert_LockDB(handle); - rv = TraversePermCertsNoLocking(handle, certfunc, udata); - nsslowcert_UnlockDB(handle); - - return(rv); -} - - - -/* - * Close the database - */ -void -nsslowcert_ClosePermCertDB(NSSLOWCERTCertDBHandle *handle) -{ - if ( handle ) { - if ( handle->permCertDB ) { - certdb_Close( handle->permCertDB ); - handle->permCertDB = NULL; - } - if (handle->dbMon) { - PZ_DestroyMonitor(handle->dbMon); - handle->dbMon = NULL; - } - } - return; -} - -/* - * Get the trust attributes from a certificate - */ -SECStatus -nsslowcert_GetCertTrust(NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust) -{ - SECStatus rv; - - nsslowcert_LockCertTrust(cert); - - if ( cert->trust == NULL ) { - rv = SECFailure; - } else { - *trust = *cert->trust; - rv = SECSuccess; - } - - nsslowcert_UnlockCertTrust(cert); - return(rv); -} - -/* - * Change the trust attributes of a certificate and make them permanent - * in the database. - */ -SECStatus -nsslowcert_ChangeCertTrust(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust) -{ - certDBEntryCert *entry; - int rv; - SECStatus ret; - - nsslowcert_LockDB(handle); - nsslowcert_LockCertTrust(cert); - /* only set the trust on permanent certs */ - if ( cert->trust == NULL ) { - ret = SECFailure; - goto done; - } - - *cert->trust = *trust; - if ( cert->dbEntry == NULL ) { - ret = SECSuccess; /* not in permanent database */ - goto done; - } - - entry = cert->dbEntry; - entry->trust = *trust; - - rv = WriteDBCertEntry(handle, entry); - if ( rv ) { - ret = SECFailure; - goto done; - } - - ret = SECSuccess; - -done: - nsslowcert_UnlockCertTrust(cert); - nsslowcert_UnlockDB(handle); - return(ret); -} - - -static SECStatus -nsslowcert_UpdatePermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust) -{ - char *oldnn; - certDBEntryCert *entry; - PRBool conflict; - SECStatus ret; - - PORT_Assert(!cert->dbEntry); - - /* don't add a conflicting nickname */ - conflict = nsslowcert_CertNicknameConflict(nickname, &cert->derSubject, - dbhandle); - if ( conflict ) { - ret = SECFailure; - goto done; - } - - /* save old nickname so that we can delete it */ - oldnn = cert->nickname; - - entry = AddCertToPermDB(dbhandle, cert, nickname, trust); - - if ( entry == NULL ) { - ret = SECFailure; - goto done; - } - - pkcs11_freeNickname(oldnn,cert->nicknameSpace); - - cert->nickname = (entry->nickname) ? pkcs11_copyNickname(entry->nickname, - cert->nicknameSpace, sizeof(cert->nicknameSpace)) : NULL; - cert->trust = &entry->trust; - cert->dbEntry = entry; - - ret = SECSuccess; -done: - return(ret); -} - -SECStatus -nsslowcert_AddPermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust) -{ - SECStatus ret; - SECStatus rv; - - nsslowcert_LockDB(dbhandle); - rv = db_BeginTransaction(dbhandle->permCertDB); - if (rv != SECSuccess) { - nsslowcert_UnlockDB(dbhandle); - return SECFailure; - } - - ret = nsslowcert_UpdatePermCert(dbhandle, cert, nickname, trust); - - db_FinishTransaction(dbhandle->permCertDB, ret != SECSuccess); - nsslowcert_UnlockDB(dbhandle); - return(ret); -} - -/* - * Open the certificate database and index databases. Create them if - * they are not there or bad. - */ -SECStatus -nsslowcert_OpenCertDB(NSSLOWCERTCertDBHandle *handle, PRBool readOnly, - const char *appName, const char *prefix, - NSSLOWCERTDBNameFunc namecb, void *cbarg, PRBool openVolatile) -{ - int rv; - - certdb_InitDBLock(handle); - - handle->dbMon = PZ_NewMonitor(nssILockCertDB); - PORT_Assert(handle->dbMon != NULL); - handle->dbVerify = PR_FALSE; - - rv = nsslowcert_OpenPermCertDB(handle, readOnly, appName, prefix, - namecb, cbarg); - if ( rv ) { - goto loser; - } - - return (SECSuccess); - -loser: - - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); -} - -PRBool -nsslowcert_needDBVerify(NSSLOWCERTCertDBHandle *handle) -{ - if (!handle) return PR_FALSE; - return handle->dbVerify; -} - -void -nsslowcert_setDBVerify(NSSLOWCERTCertDBHandle *handle, PRBool value) -{ - handle->dbVerify = value; -} - - -/* - * Lookup a certificate in the databases. - */ -static NSSLOWCERTCertificate * -FindCertByKey(NSSLOWCERTCertDBHandle *handle, SECItem *certKey, PRBool lockdb) -{ - NSSLOWCERTCertificate *cert = NULL; - certDBEntryCert *entry; - PRBool locked = PR_FALSE; - - if ( lockdb ) { - locked = PR_TRUE; - nsslowcert_LockDB(handle); - } - - /* find in perm database */ - entry = ReadDBCertEntry(handle, certKey); - - if ( entry == NULL ) { - goto loser; - } - - /* inherit entry */ - cert = DecodeACert(handle, entry); - -loser: - if (cert == NULL) { - if (entry) { - DestroyDBEntry((certDBEntry *)entry); - } - } - - if ( locked ) { - nsslowcert_UnlockDB(handle); - } - - return(cert); -} - -/* - * Lookup a certificate in the databases. - */ -static NSSLOWCERTTrust * -FindTrustByKey(NSSLOWCERTCertDBHandle *handle, SECItem *certKey, PRBool lockdb) -{ - NSSLOWCERTTrust *trust = NULL; - certDBEntryCert *entry; - PRBool locked = PR_FALSE; - - if ( lockdb ) { - locked = PR_TRUE; - nsslowcert_LockDB(handle); - } - - /* find in perm database */ - entry = ReadDBCertEntry(handle, certKey); - - if ( entry == NULL ) { - goto loser; - } - - if (!nsslowcert_hasTrust(&entry->trust)) { - goto loser; - } - - /* inherit entry */ - trust = DecodeTrustEntry(handle, entry, certKey); - -loser: - if (trust == NULL) { - if (entry) { - DestroyDBEntry((certDBEntry *)entry); - } - } - - if ( locked ) { - nsslowcert_UnlockDB(handle); - } - - return(trust); -} - -/* - * Lookup a certificate in the databases without locking - */ -NSSLOWCERTCertificate * -nsslowcert_FindCertByKey(NSSLOWCERTCertDBHandle *handle, SECItem *certKey) -{ - return(FindCertByKey(handle, certKey, PR_FALSE)); -} - -/* - * Lookup a trust object in the databases without locking - */ -NSSLOWCERTTrust * -nsslowcert_FindTrustByKey(NSSLOWCERTCertDBHandle *handle, SECItem *certKey) -{ - return(FindTrustByKey(handle, certKey, PR_FALSE)); -} - -/* - * Generate a key from an issuerAndSerialNumber, and find the - * associated cert in the database. - */ -NSSLOWCERTCertificate * -nsslowcert_FindCertByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssuerAndSN *issuerAndSN) -{ - SECItem certKey; - SECItem *sn = &issuerAndSN->serialNumber; - SECItem *issuer = &issuerAndSN->derIssuer; - NSSLOWCERTCertificate *cert; - int data_left = sn->len-1; - int data_len = sn->len; - int index = 0; - - /* automatically detect DER encoded serial numbers and remove the der - * encoding since the database expects unencoded data. - * if it's DER encoded, there must be at least 3 bytes, tag, len, data */ - if ((sn->len >= 3) && (sn->data[0] == 0x2)) { - /* remove the der encoding of the serial number before generating the - * key.. */ - data_left = sn->len-2; - data_len = sn->data[1]; - index = 2; - - /* extended length ? (not very likely for a serial number) */ - if (data_len & 0x80) { - int len_count = data_len & 0x7f; - - data_len = 0; - data_left -= len_count; - if (data_left > 0) { - while (len_count --) { - data_len = (data_len << 8) | sn->data[index++]; - } - } - } - /* XXX leaving any leading zeros on the serial number for backwards - * compatibility - */ - /* not a valid der, must be just an unlucky serial number value */ - if (data_len != data_left) { - data_len = sn->len; - index = 0; - } - } - - certKey.type = 0; - certKey.data = (unsigned char*)PORT_Alloc(sn->len + issuer->len); - certKey.len = data_len + issuer->len; - - if ( certKey.data == NULL ) { - return(0); - } - - /* first try the serial number as hand-decoded above*/ - /* copy the serialNumber */ - PORT_Memcpy(certKey.data, &sn->data[index], data_len); - - /* copy the issuer */ - PORT_Memcpy( &certKey.data[data_len],issuer->data,issuer->len); - - cert = nsslowcert_FindCertByKey(handle, &certKey); - if (cert) { - PORT_Free(certKey.data); - return (cert); - } - - /* didn't find it, try by der encoded serial number */ - /* copy the serialNumber */ - PORT_Memcpy(certKey.data, sn->data, sn->len); - - /* copy the issuer */ - PORT_Memcpy( &certKey.data[sn->len], issuer->data, issuer->len); - certKey.len = sn->len + issuer->len; - - cert = nsslowcert_FindCertByKey(handle, &certKey); - - PORT_Free(certKey.data); - - return(cert); -} - -/* - * Generate a key from an issuerAndSerialNumber, and find the - * associated cert in the database. - */ -NSSLOWCERTTrust * -nsslowcert_FindTrustByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTIssuerAndSN *issuerAndSN) -{ - SECItem certKey; - SECItem *sn = &issuerAndSN->serialNumber; - SECItem *issuer = &issuerAndSN->derIssuer; - NSSLOWCERTTrust *trust; - unsigned char keyBuf[512]; - int data_left = sn->len-1; - int data_len = sn->len; - int index = 0; - int len; - - /* automatically detect DER encoded serial numbers and remove the der - * encoding since the database expects unencoded data. - * if it's DER encoded, there must be at least 3 bytes, tag, len, data */ - if ((sn->len >= 3) && (sn->data[0] == 0x2)) { - /* remove the der encoding of the serial number before generating the - * key.. */ - data_left = sn->len-2; - data_len = sn->data[1]; - index = 2; - - /* extended length ? (not very likely for a serial number) */ - if (data_len & 0x80) { - int len_count = data_len & 0x7f; - - data_len = 0; - data_left -= len_count; - if (data_left > 0) { - while (len_count --) { - data_len = (data_len << 8) | sn->data[index++]; - } - } - } - /* XXX leaving any leading zeros on the serial number for backwards - * compatibility - */ - /* not a valid der, must be just an unlucky serial number value */ - if (data_len != data_left) { - data_len = sn->len; - index = 0; - } - } - - certKey.type = 0; - certKey.len = data_len + issuer->len; - len = sn->len + issuer->len; - if (len > sizeof (keyBuf)) { - certKey.data = (unsigned char*)PORT_Alloc(len); - } else { - certKey.data = keyBuf; - } - - if ( certKey.data == NULL ) { - return(0); - } - - /* first try the serial number as hand-decoded above*/ - /* copy the serialNumber */ - PORT_Memcpy(certKey.data, &sn->data[index], data_len); - - /* copy the issuer */ - PORT_Memcpy( &certKey.data[data_len],issuer->data,issuer->len); - - trust = nsslowcert_FindTrustByKey(handle, &certKey); - if (trust) { - pkcs11_freeStaticData(certKey.data, keyBuf); - return (trust); - } - - if (index == 0) { - pkcs11_freeStaticData(certKey.data, keyBuf); - return NULL; - } - - /* didn't find it, try by der encoded serial number */ - /* copy the serialNumber */ - PORT_Memcpy(certKey.data, sn->data, sn->len); - - /* copy the issuer */ - PORT_Memcpy( &certKey.data[sn->len], issuer->data, issuer->len); - certKey.len = sn->len + issuer->len; - - trust = nsslowcert_FindTrustByKey(handle, &certKey); - - pkcs11_freeStaticData(certKey.data, keyBuf); - - return(trust); -} - -/* - * look for the given DER certificate in the database - */ -NSSLOWCERTCertificate * -nsslowcert_FindCertByDERCert(NSSLOWCERTCertDBHandle *handle, SECItem *derCert) -{ - PRArenaPool *arena; - SECItem certKey; - SECStatus rv; - NSSLOWCERTCertificate *cert = NULL; - - /* create a scratch arena */ - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - return(NULL); - } - - /* extract the database key from the cert */ - rv = nsslowcert_KeyFromDERCert(arena, derCert, &certKey); - if ( rv != SECSuccess ) { - goto loser; - } - - /* find the certificate */ - cert = nsslowcert_FindCertByKey(handle, &certKey); - -loser: - PORT_FreeArena(arena, PR_FALSE); - return(cert); -} - -static void -DestroyCertificate(NSSLOWCERTCertificate *cert, PRBool lockdb) -{ - int refCount; - NSSLOWCERTCertDBHandle *handle; - - if ( cert ) { - - handle = cert->dbhandle; - - /* - * handle may be NULL, for example if the cert was created with - * nsslowcert_DecodeDERCertificate. - */ - if ( lockdb && handle ) { - nsslowcert_LockDB(handle); - } - - nsslowcert_LockCertRefCount(cert); - PORT_Assert(cert->referenceCount > 0); - refCount = --cert->referenceCount; - nsslowcert_UnlockCertRefCount(cert); - - if ( ( refCount == 0 ) ) { - certDBEntryCert *entry = cert->dbEntry; - - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); - } - - pkcs11_freeNickname(cert->nickname,cert->nicknameSpace); - pkcs11_freeStaticData(cert->certKey.data,cert->certKeySpace); - cert->certKey.data = NULL; - cert->nickname = NULL; - - /* zero cert before freeing. Any stale references to this cert - * after this point will probably cause an exception. */ - PORT_Memset(cert, 0, sizeof *cert); - - /* use reflock to protect the free list */ - nsslowcert_LockFreeList(); - if (certListCount > MAX_CERT_LIST_COUNT) { - PORT_Free(cert); - } else { - certListCount++; - cert->next = certListHead; - certListHead = cert; - } - nsslowcert_UnlockFreeList(); - - cert = NULL; - } - if ( lockdb && handle ) { - nsslowcert_UnlockDB(handle); - } - } - - return; -} - -NSSLOWCERTCertificate * -nsslowcert_CreateCert(void) -{ - NSSLOWCERTCertificate *cert; - nsslowcert_LockFreeList(); - cert = certListHead; - if (cert) { - certListHead = cert->next; - certListCount--; - } - nsslowcert_UnlockFreeList(); - - if (cert) { - return cert; - } - return (NSSLOWCERTCertificate *) PORT_ZAlloc(sizeof(NSSLOWCERTCertificate)); -} - -void -nsslowcert_DestroyTrust(NSSLOWCERTTrust *trust) -{ - certDBEntryCert *entry = trust->dbEntry; - - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); - } - pkcs11_freeStaticData(trust->dbKey.data,trust->dbKeySpace); - PORT_Memset(trust, 0, sizeof(*trust)); - - nsslowcert_LockFreeList(); - if (trustListCount > MAX_TRUST_LIST_COUNT) { - PORT_Free(trust); - } else { - trustListCount++; - trust->next = trustListHead; - trustListHead = trust; - } - nsslowcert_UnlockFreeList(); - - return; -} - -void -nsslowcert_DestroyCertificate(NSSLOWCERTCertificate *cert) -{ - DestroyCertificate(cert, PR_TRUE); - return; -} - -static void -nsslowcert_DestroyCertificateNoLocking(NSSLOWCERTCertificate *cert) -{ - DestroyCertificate(cert, PR_FALSE); - return; -} - -/* - * Lookup a CRL in the databases. We mirror the same fast caching data base - * caching stuff used by certificates....? - */ -certDBEntryRevocation * -nsslowcert_FindCrlByKey(NSSLOWCERTCertDBHandle *handle, - SECItem *crlKey, PRBool isKRL) -{ - SECItem keyitem; - DBT key; - SECStatus rv; - PRArenaPool *arena = NULL; - certDBEntryRevocation *entry = NULL; - certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation - : certDBEntryTypeRevocation; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; - } - - rv = EncodeDBGenericKey(crlKey, arena, &keyitem, crlType); - if ( rv != SECSuccess ) { - goto loser; - } - - key.data = keyitem.data; - key.size = keyitem.len; - - /* find in perm database */ - entry = ReadDBCrlEntry(handle, crlKey, crlType); - - if ( entry == NULL ) { - goto loser; - } - -loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - return entry; -} - -/* - * replace the existing URL in the data base with a new one - */ -static SECStatus -nsslowcert_UpdateCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, - SECItem *crlKey, char *url, PRBool isKRL) -{ - SECStatus rv = SECFailure; - certDBEntryRevocation *entry = NULL; - certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation - : certDBEntryTypeRevocation; - DeleteDBCrlEntry(handle, crlKey, crlType); - - /* Write the new entry into the data base */ - entry = NewDBCrlEntry(derCrl, url, crlType, 0); - if (entry == NULL) goto done; - - rv = WriteDBCrlEntry(handle, entry, crlKey); - if (rv != SECSuccess) goto done; - -done: - if (entry) { - DestroyDBEntry((certDBEntry *)entry); - } - return rv; -} - -SECStatus -nsslowcert_AddCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, - SECItem *crlKey, char *url, PRBool isKRL) -{ - SECStatus rv; - - rv = db_BeginTransaction(handle->permCertDB); - if (rv != SECSuccess) { - return SECFailure; - } - rv = nsslowcert_UpdateCrl(handle, derCrl, crlKey, url, isKRL); - - db_FinishTransaction(handle->permCertDB, rv != SECSuccess); - return rv; -} - -SECStatus -nsslowcert_DeletePermCRL(NSSLOWCERTCertDBHandle *handle, SECItem *derName, - PRBool isKRL) -{ - SECStatus rv; - certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation - : certDBEntryTypeRevocation; - rv = db_BeginTransaction(handle->permCertDB); - if (rv != SECSuccess) { - return SECFailure; - } - - rv = DeleteDBCrlEntry(handle, derName, crlType); - if (rv != SECSuccess) goto done; - -done: - db_FinishTransaction(handle->permCertDB, rv != SECSuccess); - return rv; -} - - -PRBool -nsslowcert_hasTrust(NSSLOWCERTCertTrust *trust) -{ - if (trust == NULL) { - return PR_FALSE; - } - return !((trust->sslFlags & CERTDB_TRUSTED_UNKNOWN) && - (trust->emailFlags & CERTDB_TRUSTED_UNKNOWN) && - (trust->objectSigningFlags & CERTDB_TRUSTED_UNKNOWN)); -} - -/* - * This function has the logic that decides if another person's cert and - * email profile from an S/MIME message should be saved. It can deal with - * the case when there is no profile. - */ -static SECStatus -nsslowcert_UpdateSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, - char *emailAddr, SECItem *derSubject, SECItem *emailProfile, - SECItem *profileTime) -{ - certDBEntrySMime *entry = NULL; - SECStatus rv = SECFailure;; - - - /* find our existing entry */ - entry = nsslowcert_ReadDBSMimeEntry(dbhandle, emailAddr); - - if ( entry ) { - /* keep our old db entry consistant for old applications. */ - if (!SECITEM_ItemsAreEqual(derSubject, &entry->subjectName)) { - nsslowcert_UpdateSubjectEmailAddr(dbhandle, &entry->subjectName, - emailAddr, nsslowcert_remove); - } - DestroyDBEntry((certDBEntry *)entry); - entry = NULL; - } - - /* now save the entry */ - entry = NewDBSMimeEntry(emailAddr, derSubject, emailProfile, - profileTime, 0); - if ( entry == NULL ) { - rv = SECFailure; - goto loser; - } - - nsslowcert_LockDB(dbhandle); - - rv = DeleteDBSMimeEntry(dbhandle, emailAddr); - /* if delete fails, try to write new entry anyway... */ - - /* link subject entry back here */ - rv = nsslowcert_UpdateSubjectEmailAddr(dbhandle, derSubject, emailAddr, - nsslowcert_add); - if ( rv != SECSuccess ) { - nsslowcert_UnlockDB(dbhandle); - goto loser; - } - - rv = WriteDBSMimeEntry(dbhandle, entry); - if ( rv != SECSuccess ) { - nsslowcert_UnlockDB(dbhandle); - goto loser; - } - - nsslowcert_UnlockDB(dbhandle); - - rv = SECSuccess; - -loser: - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); - } - return(rv); -} - -SECStatus -nsslowcert_SaveSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, char *emailAddr, - SECItem *derSubject, SECItem *emailProfile, SECItem *profileTime) -{ - SECStatus rv = SECFailure;; - - rv = db_BeginTransaction(dbhandle->permCertDB); - if (rv != SECSuccess) { - return SECFailure; - } - - rv = nsslowcert_UpdateSMimeProfile(dbhandle, emailAddr, - derSubject, emailProfile, profileTime); - - db_FinishTransaction(dbhandle->permCertDB, rv != SECSuccess); - return(rv); -} - -void -nsslowcert_DestroyGlobalLocks() -{ - if (dbLock) { - PZ_DestroyLock(dbLock); - dbLock = NULL; - } - if (certRefCountLock) { - PZ_DestroyLock(certRefCountLock); - certRefCountLock = NULL; - } - if (certTrustLock) { - PZ_DestroyLock(certTrustLock); - certTrustLock = NULL; - } -} - diff --git a/security/nss/lib/softoken/pcertt.h b/security/nss/lib/softoken/pcertt.h deleted file mode 100644 index 13a155b1e..000000000 --- a/security/nss/lib/softoken/pcertt.h +++ /dev/null @@ -1,443 +0,0 @@ -/* - * 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. - */ -/* - * certt.h - public data structures for the certificate library - * - * $Id$ - */ -#ifndef _PCERTT_H_ -#define _PCERTT_H_ - -#include "prclist.h" -#include "pkcs11t.h" -#include "seccomon.h" -#include "secoidt.h" -#include "plarena.h" -#include "prcvar.h" -#include "nssilock.h" -#include "prio.h" -#include "prmon.h" - -/* Non-opaque objects */ -typedef struct NSSLOWCERTCertDBHandleStr NSSLOWCERTCertDBHandle; -typedef struct NSSLOWCERTCertKeyStr NSSLOWCERTCertKey; - -typedef struct NSSLOWCERTTrustStr NSSLOWCERTTrust; -typedef struct NSSLOWCERTCertTrustStr NSSLOWCERTCertTrust; -typedef struct NSSLOWCERTCertificateStr NSSLOWCERTCertificate; -typedef struct NSSLOWCERTCertificateListStr NSSLOWCERTCertificateList; -typedef struct NSSLOWCERTIssuerAndSNStr NSSLOWCERTIssuerAndSN; -typedef struct NSSLOWCERTSignedDataStr NSSLOWCERTSignedData; -typedef struct NSSLOWCERTSubjectPublicKeyInfoStr NSSLOWCERTSubjectPublicKeyInfo; -typedef struct NSSLOWCERTValidityStr NSSLOWCERTValidity; - -/* -** An X.509 validity object -*/ -struct NSSLOWCERTValidityStr { - PRArenaPool *arena; - SECItem notBefore; - SECItem notAfter; -}; - -/* - * A serial number and issuer name, which is used as a database key - */ -struct NSSLOWCERTCertKeyStr { - SECItem serialNumber; - SECItem derIssuer; -}; - -/* -** A signed data object. Used to implement the "signed" macro used -** in the X.500 specs. -*/ -struct NSSLOWCERTSignedDataStr { - SECItem data; - SECAlgorithmID signatureAlgorithm; - SECItem signature; -}; - -/* -** An X.509 subject-public-key-info object -*/ -struct NSSLOWCERTSubjectPublicKeyInfoStr { - PRArenaPool *arena; - SECAlgorithmID algorithm; - SECItem subjectPublicKey; -}; - -typedef struct _certDBEntryCert certDBEntryCert; -typedef struct _certDBEntryRevocation certDBEntryRevocation; - -struct NSSLOWCERTCertTrustStr { - unsigned int sslFlags; - unsigned int emailFlags; - unsigned int objectSigningFlags; -}; - -/* -** PKCS11 Trust representation -*/ -struct NSSLOWCERTTrustStr { - NSSLOWCERTTrust *next; - NSSLOWCERTCertDBHandle *dbhandle; - SECItem dbKey; /* database key for this cert */ - certDBEntryCert *dbEntry; /* database entry struct */ - NSSLOWCERTCertTrust *trust; - SECItem *derCert; /* original DER for the cert */ - unsigned char dbKeySpace[512]; -}; - -/* -** An X.509 certificate object (the unsigned form) -*/ -struct NSSLOWCERTCertificateStr { - /* the arena is used to allocate any data structures that have the same - * lifetime as the cert. This is all stuff that hangs off of the cert - * structure, and is all freed at the same time. I is used when the - * cert is decoded, destroyed, and at some times when it changes - * state - */ - NSSLOWCERTCertificate *next; - NSSLOWCERTCertDBHandle *dbhandle; - - SECItem derCert; /* original DER for the cert */ - SECItem derIssuer; /* DER for issuer name */ - SECItem derSN; - SECItem serialNumber; - SECItem derSubject; /* DER for subject name */ - SECItem derSubjKeyInfo; - NSSLOWCERTSubjectPublicKeyInfo *subjectPublicKeyInfo; - SECItem certKey; /* database key for this cert */ - SECItem validity; - certDBEntryCert *dbEntry; /* database entry struct */ - SECItem subjectKeyID; /* x509v3 subject key identifier */ - char *nickname; - char *emailAddr; - NSSLOWCERTCertTrust *trust; - - /* the reference count is modified whenever someone looks up, dups - * or destroys a certificate - */ - int referenceCount; - - char nicknameSpace[200]; - unsigned char certKeySpace[512]; -}; - -#define SEC_CERTIFICATE_VERSION_1 0 /* default created */ -#define SEC_CERTIFICATE_VERSION_2 1 /* v2 */ -#define SEC_CERTIFICATE_VERSION_3 2 /* v3 extensions */ - -#define SEC_CRL_VERSION_1 0 /* default */ -#define SEC_CRL_VERSION_2 1 /* v2 extensions */ - -struct NSSLOWCERTIssuerAndSNStr { - SECItem derIssuer; - SECItem serialNumber; -}; - -typedef SECStatus (* NSSLOWCERTCertCallback)(NSSLOWCERTCertificate *cert, void *arg); - -/* This is the typedef for the callback passed to nsslowcert_OpenCertDB() */ -/* callback to return database name based on version number */ -typedef char * (*NSSLOWCERTDBNameFunc)(void *arg, int dbVersion); - -/* XXX Lisa thinks the template declarations belong in cert.h, not here? */ - -#include "secasn1t.h" /* way down here because I expect template stuff to - * move out of here anyway */ - -/* - * Certificate Database related definitions and data structures - */ - -/* version number of certificate database */ -#define CERT_DB_FILE_VERSION 8 -#define CERT_DB_V7_FILE_VERSION 7 -#define CERT_DB_CONTENT_VERSION 2 - -#define SEC_DB_ENTRY_HEADER_LEN 3 -#define SEC_DB_KEY_HEADER_LEN 1 - -/* All database entries have this form: - * - * byte offset field - * ----------- ----- - * 0 version - * 1 type - * 2 flags - */ - -/* database entry types */ -typedef enum { - certDBEntryTypeVersion = 0, - certDBEntryTypeCert = 1, - certDBEntryTypeNickname = 2, - certDBEntryTypeSubject = 3, - certDBEntryTypeRevocation = 4, - certDBEntryTypeKeyRevocation = 5, - certDBEntryTypeSMimeProfile = 6, - certDBEntryTypeContentVersion = 7, - certDBEntryTypeBlob = 8 -} certDBEntryType; - -typedef struct { - certDBEntryType type; - unsigned int version; - unsigned int flags; - PRArenaPool *arena; -} certDBEntryCommon; - -/* - * Certificate entry: - * - * byte offset field - * ----------- ----- - * 0 sslFlags-msb - * 1 sslFlags-lsb - * 2 emailFlags-msb - * 3 emailFlags-lsb - * 4 objectSigningFlags-msb - * 5 objectSigningFlags-lsb - * 6 derCert-len-msb - * 7 derCert-len-lsb - * 8 nickname-len-msb - * 9 nickname-len-lsb - * ... derCert - * ... nickname - * - * NOTE: the nickname string as stored in the database is null terminated, - * in other words, the last byte of the db entry is always 0 - * if a nickname is present. - * NOTE: if nickname is not present, then nickname-len-msb and - * nickname-len-lsb will both be zero. - */ -struct _certDBEntryCert { - certDBEntryCommon common; - certDBEntryCert *next; - NSSLOWCERTCertTrust trust; - SECItem derCert; - char *nickname; - char nicknameSpace[200]; - unsigned char derCertSpace[2048]; -}; - -/* - * Certificate Nickname entry: - * - * byte offset field - * ----------- ----- - * 0 subjectname-len-msb - * 1 subjectname-len-lsb - * 2... subjectname - * - * The database key for this type of entry is a nickname string - * The "subjectname" value is the DER encoded DN of the identity - * that matches this nickname. - */ -typedef struct { - certDBEntryCommon common; - char *nickname; - SECItem subjectName; -} certDBEntryNickname; - -#define DB_NICKNAME_ENTRY_HEADER_LEN 2 - -/* - * Certificate Subject entry: - * - * byte offset field - * ----------- ----- - * 0 ncerts-msb - * 1 ncerts-lsb - * 2 nickname-msb - * 3 nickname-lsb - * 4 emailAddr-msb - * 5 emailAddr-lsb - * ... nickname - * ... emailAddr - * ...+2*i certkey-len-msb - * ...+1+2*i certkey-len-lsb - * ...+2*ncerts+2*i keyid-len-msb - * ...+1+2*ncerts+2*i keyid-len-lsb - * ... certkeys - * ... keyids - * - * The database key for this type of entry is the DER encoded subject name - * The "certkey" value is an array of certificate database lookup keys that - * points to the database entries for the certificates that matche - * this subject. - * - */ -typedef struct _certDBEntrySubject { - certDBEntryCommon common; - SECItem derSubject; - unsigned int ncerts; - char *nickname; - SECItem *certKeys; - SECItem *keyIDs; - char **emailAddrs; - unsigned int nemailAddrs; -} certDBEntrySubject; - -#define DB_SUBJECT_ENTRY_HEADER_LEN 6 - -/* - * Certificate SMIME profile entry: - * - * byte offset field - * ----------- ----- - * 0 subjectname-len-msb - * 1 subjectname-len-lsb - * 2 smimeoptions-len-msb - * 3 smimeoptions-len-lsb - * 4 options-date-len-msb - * 5 options-date-len-lsb - * 6... subjectname - * ... smimeoptions - * ... options-date - * - * The database key for this type of entry is the email address string - * The "subjectname" value is the DER encoded DN of the identity - * that matches this nickname. - * The "smimeoptions" value is a string that represents the algorithm - * capabilities on the remote user. - * The "options-date" is the date that the smime options value was created. - * This is generally the signing time of the signed message that contained - * the options. It is a UTCTime value. - */ -typedef struct { - certDBEntryCommon common; - char *emailAddr; - SECItem subjectName; - SECItem smimeOptions; - SECItem optionsDate; -} certDBEntrySMime; - -#define DB_SMIME_ENTRY_HEADER_LEN 6 - -/* - * Crl/krl entry: - * - * byte offset field - * ----------- ----- - * 0 derCert-len-msb - * 1 derCert-len-lsb - * 2 url-len-msb - * 3 url-len-lsb - * ... derCert - * ... url - * - * NOTE: the url string as stored in the database is null terminated, - * in other words, the last byte of the db entry is always 0 - * if a nickname is present. - * NOTE: if url is not present, then url-len-msb and - * url-len-lsb will both be zero. - */ -#define DB_CRL_ENTRY_HEADER_LEN 4 -struct _certDBEntryRevocation { - certDBEntryCommon common; - SECItem derCrl; - char *url; /* where to load the crl from */ -}; - -/* - * Database Version Entry: - * - * byte offset field - * ----------- ----- - * only the low level header... - * - * The database key for this type of entry is the string "Version" - */ -typedef struct { - certDBEntryCommon common; -} certDBEntryVersion; - -#define SEC_DB_VERSION_KEY "Version" -#define SEC_DB_VERSION_KEY_LEN sizeof(SEC_DB_VERSION_KEY) - -/* - * Database Content Version Entry: - * - * byte offset field - * ----------- ----- - * 0 contentVersion - * - * The database key for this type of entry is the string "ContentVersion" - */ -typedef struct { - certDBEntryCommon common; - char contentVersion; -} certDBEntryContentVersion; - -#define SEC_DB_CONTENT_VERSION_KEY "ContentVersion" -#define SEC_DB_CONTENT_VERSION_KEY_LEN sizeof(SEC_DB_CONTENT_VERSION_KEY) - -typedef union { - certDBEntryCommon common; - certDBEntryVersion version; - certDBEntryCert cert; - certDBEntryNickname nickname; - certDBEntrySubject subject; - certDBEntryRevocation revocation; -} certDBEntry; - -/* length of the fixed part of a database entry */ -#define DBCERT_V4_HEADER_LEN 7 -#define DB_CERT_V5_ENTRY_HEADER_LEN 7 -#define DB_CERT_V6_ENTRY_HEADER_LEN 7 -#define DB_CERT_ENTRY_HEADER_LEN 10 - -/* common flags for all types of certificates */ -#define CERTDB_VALID_PEER (1<<0) -#define CERTDB_TRUSTED (1<<1) -#define CERTDB_SEND_WARN (1<<2) -#define CERTDB_VALID_CA (1<<3) -#define CERTDB_TRUSTED_CA (1<<4) /* trusted for issuing server certs */ -#define CERTDB_NS_TRUSTED_CA (1<<5) -#define CERTDB_USER (1<<6) -#define CERTDB_TRUSTED_CLIENT_CA (1<<7) /* trusted for issuing client certs */ -#define CERTDB_INVISIBLE_CA (1<<8) /* don't show in UI */ -#define CERTDB_GOVT_APPROVED_CA (1<<9) /* can do strong crypto in export ver */ -#define CERTDB_NOT_TRUSTED (1<<10) /* explicitly don't trust this cert */ -#define CERTDB_TRUSTED_UNKNOWN (1<<11) /* accept trust from another source */ - -/* bits not affected by the CKO_NETSCAPE_TRUST object */ -#define CERTDB_PRESERVE_TRUST_BITS (CERTDB_USER | CERTDB_VALID_PEER | \ - CERTDB_NS_TRUSTED_CA | CERTDB_VALID_CA | CERTDB_INVISIBLE_CA | \ - CERTDB_GOVT_APPROVED_CA) - -#endif /* _PCERTT_H_ */ diff --git a/security/nss/lib/softoken/pk11db.c b/security/nss/lib/softoken/pk11db.c deleted file mode 100644 index 220e897ba..000000000 --- a/security/nss/lib/softoken/pk11db.c +++ /dev/null @@ -1,899 +0,0 @@ -/* - * 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. - */ -/* - * The following code handles the storage of PKCS 11 modules used by the - * NSS. This file is written to abstract away how the modules are - * stored so we can deside that later. - */ - -#include "pk11pars.h" -#include "pkcs11i.h" -#include "mcom_db.h" -#include "cdbhdl.h" - -#define FREE_CLEAR(p) if (p) { PORT_Free(p); p = NULL; } - -static void -secmod_parseTokenFlags(char *tmp, pk11_token_parameters *parsed) { - parsed->readOnly = pk11_argHasFlag("flags","readOnly",tmp); - parsed->noCertDB = pk11_argHasFlag("flags","noCertDB",tmp); - parsed->noKeyDB = pk11_argHasFlag("flags","noKeyDB",tmp); - parsed->forceOpen = pk11_argHasFlag("flags","forceOpen",tmp); - parsed->pwRequired = pk11_argHasFlag("flags","passwordRequired",tmp); - parsed->optimizeSpace = pk11_argHasFlag("flags","optimizeSpace",tmp); - return; -} - -static void -secmod_parseFlags(char *tmp, pk11_parameters *parsed) { - parsed->noModDB = pk11_argHasFlag("flags","noModDB",tmp); - parsed->readOnly = pk11_argHasFlag("flags","readOnly",tmp); - /* keep legacy interface working */ - parsed->noCertDB = pk11_argHasFlag("flags","noCertDB",tmp); - parsed->forceOpen = pk11_argHasFlag("flags","forceOpen",tmp); - parsed->pwRequired = pk11_argHasFlag("flags","passwordRequired",tmp); - parsed->optimizeSpace = pk11_argHasFlag("flags","optimizeSpace",tmp); - return; -} - -CK_RV -secmod_parseTokenParameters(char *param, pk11_token_parameters *parsed) -{ - int next; - char *tmp; - char *index; - index = pk11_argStrip(param); - - while (*index) { - PK11_HANDLE_STRING_ARG(index,parsed->configdir,"configDir=",;) - PK11_HANDLE_STRING_ARG(index,parsed->certPrefix,"certPrefix=",;) - PK11_HANDLE_STRING_ARG(index,parsed->keyPrefix,"keyPrefix=",;) - PK11_HANDLE_STRING_ARG(index,parsed->tokdes,"tokenDescription=",;) - PK11_HANDLE_STRING_ARG(index,parsed->slotdes,"slotDescription=",;) - PK11_HANDLE_STRING_ARG(index,tmp,"minPWLen=", - if(tmp) { parsed->minPW=atoi(tmp); PORT_Free(tmp); }) - PK11_HANDLE_STRING_ARG(index,tmp,"flags=", - if(tmp) { secmod_parseTokenFlags(param,parsed); PORT_Free(tmp); }) - PK11_HANDLE_FINAL_ARG(index) - } - return CKR_OK; -} - -static void -secmod_parseTokens(char *tokenParams, pk11_parameters *parsed) -{ - char *tokenIndex; - pk11_token_parameters *tokens = NULL; - int i=0,count = 0,next; - - if ((tokenParams == NULL) || (*tokenParams == 0)) return; - - /* first count the number of slots */ - for (tokenIndex = pk11_argStrip(tokenParams); *tokenIndex; - tokenIndex = pk11_argStrip(pk11_argSkipParameter(tokenIndex))) { - count++; - } - - /* get the data structures */ - tokens = (pk11_token_parameters *) - PORT_ZAlloc(count*sizeof(pk11_token_parameters)); - if (tokens == NULL) return; - - for (tokenIndex = pk11_argStrip(tokenParams), i = 0; - *tokenIndex && i < count ; i++ ) { - char *name; - name = pk11_argGetName(tokenIndex,&next); - tokenIndex += next; - - tokens[i].slotID = pk11_argDecodeNumber(name); - tokens[i].readOnly = PR_TRUE; - tokens[i].noCertDB = PR_TRUE; - tokens[i].noKeyDB = PR_TRUE; - if (!pk11_argIsBlank(*tokenIndex)) { - char *args = pk11_argFetchValue(tokenIndex,&next); - tokenIndex += next; - if (args) { - secmod_parseTokenParameters(args,&tokens[i]); - PORT_Free(args); - } - } - if (name) PORT_Free(name); - tokenIndex = pk11_argStrip(tokenIndex); - } - parsed->token_count = i; - parsed->tokens = tokens; - return; -} - -CK_RV -secmod_parseParameters(char *param, pk11_parameters *parsed, PRBool isFIPS) -{ - int next; - char *tmp; - char *index; - char *certPrefix = NULL, *keyPrefix = NULL; - char *tokdes = NULL, *ptokdes = NULL; - char *slotdes = NULL, *pslotdes = NULL; - char *fslotdes = NULL, *fpslotdes = NULL; - char *minPW = NULL; - index = pk11_argStrip(param); - - PORT_Memset(parsed, 0, sizeof(pk11_parameters)); - - while (*index) { - PK11_HANDLE_STRING_ARG(index,parsed->configdir,"configDir=",;) - PK11_HANDLE_STRING_ARG(index,parsed->secmodName,"secmod=",;) - PK11_HANDLE_STRING_ARG(index,parsed->man,"manufacturerID=",;) - PK11_HANDLE_STRING_ARG(index,parsed->libdes,"libraryDescription=",;) - /* constructed values, used so legacy interfaces still work */ - PK11_HANDLE_STRING_ARG(index,certPrefix,"certPrefix=",;) - PK11_HANDLE_STRING_ARG(index,keyPrefix,"keyPrefix=",;) - PK11_HANDLE_STRING_ARG(index,tokdes,"cryptoTokenDescription=",;) - PK11_HANDLE_STRING_ARG(index,ptokdes,"dbTokenDescription=",;) - PK11_HANDLE_STRING_ARG(index,slotdes,"cryptoSlotDescription=",;) - PK11_HANDLE_STRING_ARG(index,pslotdes,"dbSlotDescription=",;) - PK11_HANDLE_STRING_ARG(index,fslotdes,"FIPSSlotDescription=",;) - PK11_HANDLE_STRING_ARG(index,minPW,"FIPSTokenDescription=",;) - PK11_HANDLE_STRING_ARG(index,tmp,"minPWLen=",;) - - PK11_HANDLE_STRING_ARG(index,tmp,"flags=", - if(tmp) { secmod_parseFlags(param,parsed); PORT_Free(tmp); }) - PK11_HANDLE_STRING_ARG(index,tmp,"tokens=", - if(tmp) { secmod_parseTokens(tmp,parsed); PORT_Free(tmp); }) - PK11_HANDLE_FINAL_ARG(index) - } - if (parsed->tokens == NULL) { - int count = isFIPS ? 1 : 2; - int index = count-1; - pk11_token_parameters *tokens = NULL; - - tokens = (pk11_token_parameters *) - PORT_ZAlloc(count*sizeof(pk11_token_parameters)); - if (tokens == NULL) { - goto loser; - } - parsed->tokens = tokens; - parsed->token_count = count; - tokens[index].slotID = isFIPS ? FIPS_SLOT_ID : PRIVATE_KEY_SLOT_ID; - tokens[index].certPrefix = certPrefix; - tokens[index].keyPrefix = keyPrefix; - tokens[index].minPW = minPW ? atoi(minPW) : 0; - tokens[index].readOnly = parsed->readOnly; - tokens[index].noCertDB = parsed->noCertDB; - tokens[index].noKeyDB = parsed->noCertDB; - tokens[index].forceOpen = parsed->forceOpen; - tokens[index].pwRequired = parsed->pwRequired; - tokens[index].optimizeSpace = parsed->optimizeSpace; - tokens[0].optimizeSpace = parsed->optimizeSpace; - certPrefix = NULL; - keyPrefix = NULL; - if (isFIPS) { - tokens[index].tokdes = fslotdes; - tokens[index].slotdes = fpslotdes; - fslotdes = NULL; - fpslotdes = NULL; - } else { - tokens[index].tokdes = ptokdes; - tokens[index].slotdes = pslotdes; - tokens[0].slotID = NETSCAPE_SLOT_ID; - tokens[0].tokdes = tokdes; - tokens[0].slotdes = slotdes; - tokens[0].noCertDB = PR_TRUE; - tokens[0].noKeyDB = PR_TRUE; - ptokdes = NULL; - pslotdes = NULL; - tokdes = NULL; - slotdes = NULL; - } - } - -loser: - FREE_CLEAR(certPrefix); - FREE_CLEAR(keyPrefix); - FREE_CLEAR(tokdes); - FREE_CLEAR(ptokdes); - FREE_CLEAR(slotdes); - FREE_CLEAR(pslotdes); - FREE_CLEAR(fslotdes); - FREE_CLEAR(fpslotdes); - FREE_CLEAR(minPW); - return CKR_OK; -} - -void -secmod_freeParams(pk11_parameters *params) -{ - int i; - - for (i=0; i < params->token_count; i++) { - FREE_CLEAR(params->tokens[i].configdir); - FREE_CLEAR(params->tokens[i].certPrefix); - FREE_CLEAR(params->tokens[i].keyPrefix); - FREE_CLEAR(params->tokens[i].tokdes); - FREE_CLEAR(params->tokens[i].slotdes); - } - - FREE_CLEAR(params->configdir); - FREE_CLEAR(params->secmodName); - FREE_CLEAR(params->man); - FREE_CLEAR(params->libdes); - FREE_CLEAR(params->tokens); -} - - -char * -secmod_getSecmodName(char *param, char **appName, char **filename,PRBool *rw) -{ - int next; - char *configdir = NULL; - char *secmodName = NULL; - char *value = NULL; - char *save_params = param; - const char *lconfigdir; - param = pk11_argStrip(param); - - - while (*param) { - PK11_HANDLE_STRING_ARG(param,configdir,"configDir=",;) - PK11_HANDLE_STRING_ARG(param,secmodName,"secmod=",;) - PK11_HANDLE_FINAL_ARG(param) - } - - *rw = PR_TRUE; - if (pk11_argHasFlag("flags","readOnly",save_params) || - pk11_argHasFlag("flags","noModDB",save_params)) *rw = PR_FALSE; - - if (!secmodName || *secmodName == '\0') { - if (secmodName) PORT_Free(secmodName); - secmodName = PORT_Strdup(SECMOD_DB); - } - *filename = secmodName; - - lconfigdir = pk11_EvaluateConfigDir(configdir, appName); - - if (lconfigdir) { - value = PR_smprintf("%s" PATH_SEPARATOR "%s",lconfigdir,secmodName); - } else { - value = PR_smprintf("%s",secmodName); - } - if (configdir) PORT_Free(configdir); - return value; -} - -/* Construct a database key for a given module */ -static SECStatus secmod_MakeKey(DBT *key, char * module) { - int len = 0; - char *commonName; - - commonName = pk11_argGetParamValue("name",module); - if (commonName == NULL) { - commonName = pk11_argGetParamValue("library",module); - } - if (commonName == NULL) return SECFailure; - len = PORT_Strlen(commonName); - key->data = commonName; - key->size = len; - return SECSuccess; -} - -/* free out constructed database key */ -static void -secmod_FreeKey(DBT *key) -{ - if (key->data) { - PORT_Free(key->data); - } - key->data = NULL; - key->size = 0; -} - -typedef struct secmodDataStr secmodData; -typedef struct secmodSlotDataStr secmodSlotData; -struct secmodDataStr { - unsigned char major; - unsigned char minor; - unsigned char nameStart[2]; - unsigned char slotOffset[2]; - unsigned char internal; - unsigned char fips; - unsigned char ssl[8]; - unsigned char trustOrder[4]; - unsigned char cipherOrder[4]; - unsigned char reserved1; - unsigned char isModuleDB; - unsigned char isModuleDBOnly; - unsigned char isCritical; - unsigned char reserved[4]; - unsigned char names[6]; /* enough space for the length fields */ -}; - -struct secmodSlotDataStr { - unsigned char slotID[4]; - unsigned char defaultFlags[4]; - unsigned char timeout[4]; - unsigned char askpw; - unsigned char hasRootCerts; - unsigned char reserved[18]; /* this makes it a round 32 bytes */ -}; - -#define SECMOD_DB_VERSION_MAJOR 0 -#define SECMOD_DB_VERSION_MINOR 6 -#define SECMOD_DB_EXT1_VERSION_MAJOR 0 -#define SECMOD_DB_EXT1_VERSION_MINOR 6 -#define SECMOD_DB_NOUI_VERSION_MAJOR 0 -#define SECMOD_DB_NOUI_VERSION_MINOR 4 - -#define SECMOD_PUTSHORT(dest,src) \ - (dest)[1] = (unsigned char) ((src)&0xff); \ - (dest)[0] = (unsigned char) (((src) >> 8) & 0xff); -#define SECMOD_PUTLONG(dest,src) \ - (dest)[3] = (unsigned char) ((src)&0xff); \ - (dest)[2] = (unsigned char) (((src) >> 8) & 0xff); \ - (dest)[1] = (unsigned char) (((src) >> 16) & 0xff); \ - (dest)[0] = (unsigned char) (((src) >> 24) & 0xff); -#define SECMOD_GETSHORT(src) \ - ((unsigned short) (((src)[0] << 8) | (src)[1])) -#define SECMOD_GETLONG(src) \ - ((unsigned long) (( (unsigned long) (src)[0] << 24) | \ - ( (unsigned long) (src)[1] << 16) | \ - ( (unsigned long) (src)[2] << 8) | \ - (unsigned long) (src)[3])) - -/* - * build a data base entry from a module - */ -static SECStatus -secmod_EncodeData(DBT *data, char * module) -{ - secmodData *encoded = NULL; - secmodSlotData *slot; - unsigned char *dataPtr; - unsigned short len, len2 = 0, len3 = 0; - int count = 0; - unsigned short offset; - int dataLen, i; - unsigned long order; - unsigned long ssl[2]; - char *commonName = NULL , *dllName = NULL, *param = NULL, *nss = NULL; - char *slotParams, *ciphers; - PK11PreSlotInfo *slotInfo = NULL; - SECStatus rv = SECFailure; - - rv = pk11_argParseModuleSpec(module,&dllName,&commonName,¶m,&nss); - if (rv != SECSuccess) return rv; - rv = SECFailure; - - if (commonName == NULL) { - /* set error */ - goto loser; - } - - len = PORT_Strlen(commonName); - if (dllName) { - len2 = PORT_Strlen(dllName); - } - if (param) { - len3 = PORT_Strlen(param); - } - - slotParams = pk11_argGetParamValue("slotParams",nss); - slotInfo = pk11_argParseSlotInfo(NULL,slotParams,&count); - if (slotParams) PORT_Free(slotParams); - - if (count && slotInfo == NULL) { - /* set error */ - goto loser; - } - - dataLen = sizeof(secmodData) + len + len2 + len3 + sizeof(unsigned short) + - count*sizeof(secmodSlotData); - - data->data = (unsigned char *) PORT_ZAlloc(dataLen); - encoded = (secmodData *)data->data; - dataPtr = (unsigned char *) data->data; - data->size = dataLen; - - if (encoded == NULL) { - /* set error */ - goto loser; - } - - encoded->major = SECMOD_DB_VERSION_MAJOR; - encoded->minor = SECMOD_DB_VERSION_MINOR; - encoded->internal = (unsigned char) - (pk11_argHasFlag("flags","internal",nss) ? 1 : 0); - encoded->fips = (unsigned char) - (pk11_argHasFlag("flags","FIPS",nss) ? 1 : 0); - encoded->isModuleDB = (unsigned char) - (pk11_argHasFlag("flags","isModuleDB",nss) ? 1 : 0); - encoded->isModuleDBOnly = (unsigned char) - (pk11_argHasFlag("flags","isModuleDBOnly",nss) ? 1 : 0); - encoded->isCritical = (unsigned char) - (pk11_argHasFlag("flags","critical",nss) ? 1 : 0); - - order = pk11_argReadLong("trustOrder",nss, PK11_DEFAULT_TRUST_ORDER, NULL); - SECMOD_PUTLONG(encoded->trustOrder,order); - order = pk11_argReadLong("cipherOrder",nss,PK11_DEFAULT_CIPHER_ORDER,NULL); - SECMOD_PUTLONG(encoded->cipherOrder,order); - - - ciphers = pk11_argGetParamValue("ciphers",nss); - pk11_argSetNewCipherFlags(&ssl[0], ciphers); - SECMOD_PUTLONG(encoded->ssl,ssl[0]); - SECMOD_PUTLONG(&encoded->ssl[4],ssl[1]); - if (ciphers) PORT_Free(ciphers); - - offset = (unsigned short) &(((secmodData *)0)->names[0]); - SECMOD_PUTSHORT(encoded->nameStart,offset); - offset = offset + len + len2 + len3 + 3*sizeof(unsigned short); - SECMOD_PUTSHORT(encoded->slotOffset,offset); - - - SECMOD_PUTSHORT(&dataPtr[offset],((unsigned short)count)); - slot = (secmodSlotData *)(dataPtr+offset+sizeof(unsigned short)); - - offset = 0; - SECMOD_PUTSHORT(encoded->names,len); - offset += sizeof(unsigned short); - PORT_Memcpy(&encoded->names[offset],commonName,len); - offset += len; - - - SECMOD_PUTSHORT(&encoded->names[offset],len2); - offset += sizeof(unsigned short); - if (len2) PORT_Memcpy(&encoded->names[offset],dllName,len2); - offset += len2; - - SECMOD_PUTSHORT(&encoded->names[offset],len3); - offset += sizeof(unsigned short); - if (len3) PORT_Memcpy(&encoded->names[offset],param,len3); - offset += len3; - - if (count) { - for (i=0; i < count; i++) { - SECMOD_PUTLONG(slot[i].slotID, slotInfo[i].slotID); - SECMOD_PUTLONG(slot[i].defaultFlags, - slotInfo[i].defaultFlags); - SECMOD_PUTLONG(slot[i].timeout,slotInfo[i].timeout); - slot[i].askpw = slotInfo[i].askpw; - slot[i].hasRootCerts = slotInfo[i].hasRootCerts; - PORT_Memset(slot[i].reserved, 0, sizeof(slot[i].reserved)); - } - } - rv = SECSuccess; - -loser: - if (commonName) PORT_Free(commonName); - if (dllName) PORT_Free(dllName); - if (param) PORT_Free(param); - if (slotInfo) PORT_Free(slotInfo); - if (nss) PORT_Free(nss); - return rv; - -} - -static void -secmod_FreeData(DBT *data) -{ - if (data->data) { - PORT_Free(data->data); - } -} - -/* - * build a module from the data base entry. - */ -static char * -secmod_DecodeData(char *defParams, DBT *data, PRBool *retInternal) -{ - secmodData *encoded; - secmodSlotData *slots; - char *commonName = NULL,*dllName = NULL,*parameters = NULL; - unsigned char *names; - unsigned short len; - unsigned long slotCount; - unsigned short offset; - PRBool isOldVersion = PR_FALSE; - PRBool internal, isFIPS, isModuleDB=PR_FALSE, isModuleDBOnly=PR_FALSE; - PRBool extended=PR_FALSE; - PRBool hasRootCerts=PR_FALSE,hasRootTrust=PR_FALSE; - unsigned long trustOrder=PK11_DEFAULT_TRUST_ORDER, - cipherOrder=PK11_DEFAULT_CIPHER_ORDER; - unsigned long ssl0=0, ssl1=0; - char **slotStrings = NULL; - unsigned long slotID,defaultFlags,timeout; - char *nss,*moduleSpec; - int i; - - PLArenaPool *arena; - - arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if (arena == NULL) return NULL; - - encoded = (secmodData *)data->data; - names = (unsigned char *)data->data; - offset = SECMOD_GETSHORT(encoded->slotOffset); - slots = (secmodSlotData *) (names + offset + 2); - slotCount = SECMOD_GETSHORT(names + offset); - names += SECMOD_GETSHORT(encoded->nameStart); - - * retInternal = internal = (encoded->internal != 0) ? PR_TRUE: PR_FALSE; - isFIPS = (encoded->fips != 0) ? PR_TRUE: PR_FALSE; - len = SECMOD_GETSHORT(names); - - if (internal && (encoded->major == SECMOD_DB_NOUI_VERSION_MAJOR) && - (encoded->minor <= SECMOD_DB_NOUI_VERSION_MINOR)) { - isOldVersion = PR_TRUE; - } - - if ((encoded->major == SECMOD_DB_EXT1_VERSION_MAJOR) && - (encoded->minor >= SECMOD_DB_EXT1_VERSION_MINOR)) { - trustOrder = SECMOD_GETLONG(encoded->trustOrder); - cipherOrder = SECMOD_GETLONG(encoded->cipherOrder); - isModuleDB = (encoded->isModuleDB != 0) ? PR_TRUE: PR_FALSE; - isModuleDBOnly = (encoded->isModuleDBOnly != 0) ? PR_TRUE: PR_FALSE; - extended = PR_TRUE; - } - - if (internal && !extended) { - trustOrder = 0; - cipherOrder = 100; - } - - /* decode the common name */ - commonName = (char*)PORT_ArenaAlloc(arena,len+1); - if (commonName == NULL) { - PORT_FreeArena(arena,PR_TRUE); - return NULL; - } - PORT_Memcpy(commonName,&names[2],len); - commonName[len] = 0; - - /* decode the DLL name */ - names += len+2; - len = SECMOD_GETSHORT(names); - if (len) { - dllName = (char*)PORT_ArenaAlloc(arena,len + 1); - if (dllName == NULL) { - PORT_FreeArena(arena,PR_TRUE); - return NULL; - } - PORT_Memcpy(dllName,&names[2],len); - dllName[len] = 0; - } - if (!internal && extended) { - names += len+2; - len = SECMOD_GETSHORT(names); - if (len) { - parameters = (char*)PORT_ArenaAlloc(arena,len + 1); - if (parameters == NULL) { - PORT_FreeArena(arena,PR_TRUE); - return NULL; - } - PORT_Memcpy(parameters,&names[2],len); - parameters[len] = 0; - } - } - if (internal) { - parameters = PORT_ArenaStrdup(arena,defParams); - } - - /* decode SSL cipher enable flags */ - ssl0 = SECMOD_GETLONG(encoded->ssl); - ssl1 = SECMOD_GETLONG(&encoded->ssl[4]); - - /* slotCount; */ - slotStrings = (char **)PORT_ArenaAlloc(arena, slotCount * sizeof(char *)); - for (i=0; i < (int) slotCount; i++) { - slotID = SECMOD_GETLONG(slots[i].slotID); - defaultFlags = SECMOD_GETLONG(slots[i].defaultFlags); - if (isOldVersion && internal && (slotID != 2)) { - unsigned long internalFlags= - pk11_argSlotFlags("slotFlags",SECMOD_SLOT_FLAGS); - defaultFlags |= internalFlags; - } - timeout = SECMOD_GETLONG(slots[i].timeout); - hasRootCerts = slots[i].hasRootCerts; - if (hasRootCerts && !extended) { - trustOrder = 100; - } - - slotStrings[i] = pk11_mkSlotString(slotID, defaultFlags, timeout, - (unsigned char)slots[i].askpw, - hasRootCerts, hasRootTrust); - } - - nss = pk11_mkNSS(slotStrings, slotCount, internal, isFIPS, isModuleDB, - isModuleDBOnly, internal, trustOrder, cipherOrder, ssl0, ssl1); - moduleSpec = pk11_mkNewModuleSpec(dllName,commonName,parameters,nss); - PR_smprintf_free(nss); - PORT_FreeArena(arena,PR_TRUE); - - return (moduleSpec); -} - - - -static DB * -secmod_OpenDB(const char *appName, const char *filename, const char *dbName, - PRBool readOnly, PRBool update) -{ - DB *pkcs11db = NULL; - - - if (appName) { - char *secname = PORT_Strdup(filename); - int len = strlen(secname); - int status = RDB_FAIL; - - if (len >= 3 && PORT_Strcmp(&secname[len-3],".db") == 0) { - secname[len-3] = 0; - } - pkcs11db= - rdbopen(appName, "", secname, readOnly ? NO_RDONLY:NO_RDWR, NULL); - if (update && !pkcs11db) { - DB *updatedb; - - pkcs11db = rdbopen(appName, "", secname, NO_CREATE, &status); - if (!pkcs11db) { - if (status == RDB_RETRY) { - pkcs11db= rdbopen(appName, "", secname, - readOnly ? NO_RDONLY:NO_RDWR, NULL); - } - PORT_Free(secname); - return pkcs11db; - } - updatedb = dbopen(dbName, NO_RDONLY, 0600, DB_HASH, 0); - if (updatedb) { - db_Copy(pkcs11db,updatedb); - (*updatedb->close)(updatedb); - } else { - (*pkcs11db->close)(pkcs11db); - PORT_Free(secname); - return NULL; - } - } - PORT_Free(secname); - return pkcs11db; - } - - /* I'm sure we should do more checks here sometime... */ - pkcs11db = dbopen(dbName, readOnly ? NO_RDONLY : NO_RDWR, 0600, DB_HASH, 0); - - /* didn't exist? create it */ - if (pkcs11db == NULL) { - if (readOnly) - return NULL; - - pkcs11db = dbopen( dbName, NO_CREATE, 0600, DB_HASH, 0 ); - if (pkcs11db) - (* pkcs11db->sync)(pkcs11db, 0); - } - return pkcs11db; -} - -static void -secmod_CloseDB(DB *pkcs11db) -{ - (*pkcs11db->close)(pkcs11db); -} - -static char * -secmod_addEscape(const char *string, char quote) -{ - char *newString = 0; - int escapes = 0, size = 0; - const char *src; - char *dest; - - for (src=string; *src ; src++) { - if ((*src == quote) || (*src == '\\')) escapes++; - size++; - } - - newString = PORT_ZAlloc(escapes+size+1); - if (newString == NULL) { - return NULL; - } - - for (src=string, dest=newString; *src; src++,dest++) { - if ((*src == '\\') || (*src == quote)) { - *dest++ = '\\'; - } - *dest = *src; - } - - return newString; -} - -#define SECMOD_STEP 10 -#define PK11_DEFAULT_INTERNAL_INIT "library= name=\"NSS Internal PKCS #11 Module\" parameters=\"%s\" NSS=\"Flags=internal,critical trustOrder=75 cipherOrder=100 slotParams=(1={%s askpw=any timeout=30})\"" -/* - * Read all the existing modules in - */ -char ** -secmod_ReadPermDB(const char *appName, const char *filename, - const char *dbname, char *params, PRBool rw) -{ - DBT key,data; - int ret; - DB *pkcs11db = NULL; - char **moduleList = NULL; - int moduleCount = 1; - int useCount = SECMOD_STEP; - - moduleList = (char **) PORT_ZAlloc(useCount*sizeof(char **)); - if (moduleList == NULL) return NULL; - - pkcs11db = secmod_OpenDB(appName,filename,dbname,PR_TRUE,rw); - if (pkcs11db == NULL) goto done; - - /* read and parse the file or data base */ - ret = (*pkcs11db->seq)(pkcs11db, &key, &data, R_FIRST); - if (ret) goto done; - - - do { - char *moduleString; - PRBool internal = PR_FALSE; - if ((moduleCount+1) >= useCount) { - useCount += SECMOD_STEP; - moduleList = - (char **)PORT_Realloc(moduleList,useCount*sizeof(char *)); - if (moduleList == NULL) goto done; - PORT_Memset(&moduleList[moduleCount+1],0, - sizeof(char *)*SECMOD_STEP); - } - moduleString = secmod_DecodeData(params,&data,&internal); - if (internal) { - moduleList[0] = moduleString; - } else { - moduleList[moduleCount] = moduleString; - moduleCount++; - } - } while ( (*pkcs11db->seq)(pkcs11db, &key, &data, R_NEXT) == 0); - -done: - if (!moduleList[0]) { - char * newparams = secmod_addEscape(params,'"'); - if (newparams) { - moduleList[0] = PR_smprintf(PK11_DEFAULT_INTERNAL_INIT,newparams, - SECMOD_SLOT_FLAGS); - PORT_Free(newparams); - } - } - /* deal with trust cert db here */ - - if (pkcs11db) { - secmod_CloseDB(pkcs11db); - } else if (moduleList[0] && rw) { - secmod_AddPermDB(appName,filename,dbname,moduleList[0], rw) ; - } - if (!moduleList[0]) { - PORT_Free(moduleList); - moduleList = NULL; - } - return moduleList; -} - -SECStatus -secmod_ReleasePermDBData(const char *appName, const char *filename, - const char *dbname, char **moduleSpecList, PRBool rw) -{ - if (moduleSpecList) { - char **index; - for(index = moduleSpecList; *index; index++) { - PR_smprintf_free(*index); - } - PORT_Free(moduleSpecList); - } - return SECSuccess; -} - -/* - * Delete a module from the Data Base - */ -SECStatus -secmod_DeletePermDB(const char *appName, const char *filename, - const char *dbname, char *args, PRBool rw) -{ - DBT key; - SECStatus rv = SECFailure; - DB *pkcs11db = NULL; - int ret; - - if (!rw) return SECFailure; - - /* make sure we have a db handle */ - pkcs11db = secmod_OpenDB(appName,filename,dbname,PR_FALSE,PR_FALSE); - if (pkcs11db == NULL) { - return SECFailure; - } - - rv = secmod_MakeKey(&key,args); - if (rv != SECSuccess) goto done; - rv = SECFailure; - ret = (*pkcs11db->del)(pkcs11db, &key, 0); - secmod_FreeKey(&key); - if (ret != 0) goto done; - - - ret = (*pkcs11db->sync)(pkcs11db, 0); - if (ret == 0) rv = SECSuccess; - -done: - secmod_CloseDB(pkcs11db); - return rv; -} - -/* - * Add a module to the Data base - */ -SECStatus -secmod_AddPermDB(const char *appName, const char *filename, - const char *dbname, char *module, PRBool rw) -{ - DBT key,data; - SECStatus rv = SECFailure; - DB *pkcs11db = NULL; - int ret; - - - if (!rw) return SECFailure; - - /* make sure we have a db handle */ - pkcs11db = secmod_OpenDB(appName,filename,dbname,PR_FALSE,PR_FALSE); - if (pkcs11db == NULL) { - return SECFailure; - } - - rv = secmod_MakeKey(&key,module); - if (rv != SECSuccess) goto done; - rv = secmod_EncodeData(&data,module); - if (rv != SECSuccess) { - secmod_FreeKey(&key); - goto done; - } - rv = SECFailure; - ret = (*pkcs11db->put)(pkcs11db, &key, &data, 0); - secmod_FreeKey(&key); - secmod_FreeData(&data); - if (ret != 0) goto done; - - ret = (*pkcs11db->sync)(pkcs11db, 0); - if (ret == 0) rv = SECSuccess; - -done: - secmod_CloseDB(pkcs11db); - return rv; -} diff --git a/security/nss/lib/softoken/pk11pars.h b/security/nss/lib/softoken/pk11pars.h deleted file mode 100644 index 5fc939f80..000000000 --- a/security/nss/lib/softoken/pk11pars.h +++ /dev/null @@ -1,852 +0,0 @@ -/* - * 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) 2001 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. - */ -/* - * The following handles the loading, unloading and management of - * various PCKS #11 modules - */ - - -/* - * this header file contains routines for parsing PKCS #11 module spec - * strings. It contains 'C' code and should only be included in one module. - * Currently it is included in both softoken and the wrapper. - */ -#include <ctype.h> -#include "pkcs11.h" -#include "seccomon.h" -#include "prprf.h" -#include "secmodt.h" -#include "pk11init.h" - -#define PK11_ARG_LIBRARY_PARAMETER "library=" -#define PK11_ARG_NAME_PARAMETER "name=" -#define PK11_ARG_MODULE_PARAMETER "parameters=" -#define PK11_ARG_NSS_PARAMETER "NSS=" -#define PK11_ARG_FORTEZZA_FLAG "FORTEZZA" -#define PK11_ARG_ESCAPE '\\' - -struct pk11argSlotFlagTable { - char *name; - int len; - unsigned long value; -}; - -#define PK11_DEFAULT_CIPHER_ORDER 0 -#define PK11_DEFAULT_TRUST_ORDER 50 - - -#define PK11_ARG_ENTRY(arg,flag) \ -{ #arg , sizeof(#arg)-1, flag } -static struct pk11argSlotFlagTable pk11_argSlotFlagTable[] = { - PK11_ARG_ENTRY(RSA,SECMOD_RSA_FLAG), - PK11_ARG_ENTRY(DSA,SECMOD_RSA_FLAG), - PK11_ARG_ENTRY(RC2,SECMOD_RC4_FLAG), - PK11_ARG_ENTRY(RC4,SECMOD_RC2_FLAG), - PK11_ARG_ENTRY(DES,SECMOD_DES_FLAG), - PK11_ARG_ENTRY(DH,SECMOD_DH_FLAG), - PK11_ARG_ENTRY(FORTEZZA,SECMOD_FORTEZZA_FLAG), - PK11_ARG_ENTRY(RC5,SECMOD_RC5_FLAG), - PK11_ARG_ENTRY(SHA1,SECMOD_SHA1_FLAG), - PK11_ARG_ENTRY(MD5,SECMOD_MD5_FLAG), - PK11_ARG_ENTRY(MD2,SECMOD_MD2_FLAG), - PK11_ARG_ENTRY(SSL,SECMOD_SSL_FLAG), - PK11_ARG_ENTRY(TLS,SECMOD_TLS_FLAG), - PK11_ARG_ENTRY(AES,SECMOD_AES_FLAG), - PK11_ARG_ENTRY(PublicCerts,SECMOD_FRIENDLY_FLAG), - PK11_ARG_ENTRY(RANDOM,SECMOD_RANDOM_FLAG), -}; - -#define PK11_HANDLE_STRING_ARG(param,target,value,command) \ - if (PORT_Strncasecmp(param,value,sizeof(value)-1) == 0) { \ - param += sizeof(value)-1; \ - target = pk11_argFetchValue(param,&next); \ - param += next; \ - command ;\ - } else - -#define PK11_HANDLE_FINAL_ARG(param) \ - { param = pk11_argSkipParameter(param); } param = pk11_argStrip(param); - - -static int pk11_argSlotFlagTableSize = - sizeof(pk11_argSlotFlagTable)/sizeof(pk11_argSlotFlagTable[0]); - - -static PRBool pk11_argGetPair(char c) { - switch (c) { - case '\'': return c; - case '\"': return c; - case '<': return '>'; - case '{': return '}'; - case '[': return ']'; - case '(': return ')'; - default: break; - } - return ' '; -} - -static PRBool pk11_argIsBlank(char c) { - return isspace(c); -} - -static PRBool pk11_argIsEscape(char c) { - return c == '\\'; -} - -static PRBool pk11_argIsQuote(char c) { - switch (c) { - case '\'': - case '\"': - case '<': - case '{': /* } end curly to keep vi bracket matching working */ - case '(': /* ) */ - case '[': /* ] */ return PR_TRUE; - default: break; - } - return PR_FALSE; -} - -static PRBool pk11_argHasChar(char *v, char c) -{ - for ( ;*v; v++) { - if (*v == c) return PR_TRUE; - } - return PR_FALSE; -} - -static PRBool pk11_argHasBlanks(char *v) -{ - for ( ;*v; v++) { - if (pk11_argIsBlank(*v)) return PR_TRUE; - } - return PR_FALSE; -} - -static char *pk11_argStrip(char *c) { - while (*c && pk11_argIsBlank(*c)) c++; - return c; -} - -static char * -pk11_argFindEnd(char *string) { - char endChar = ' '; - PRBool lastEscape = PR_FALSE; - - if (pk11_argIsQuote(*string)) { - endChar = pk11_argGetPair(*string); - string++; - } - - for (;*string; string++) { - if (lastEscape) { - lastEscape = PR_FALSE; - continue; - } - if (pk11_argIsEscape(*string) && !lastEscape) { - lastEscape = PR_TRUE; - continue; - } - if ((endChar == ' ') && pk11_argIsBlank(*string)) break; - if (*string == endChar) { - break; - } - } - - return string; -} - -static char * -pk11_argFetchValue(char *string, int *pcount) -{ - char *end = pk11_argFindEnd(string); - char *retString, *copyString; - PRBool lastEscape = PR_FALSE; - - *pcount = (end - string)+1; - - if (*pcount == 0) return NULL; - - copyString = retString = (char *)PORT_Alloc(*pcount); - if (retString == NULL) return NULL; - - if (pk11_argIsQuote(*string)) string++; - for (; string < end; string++) { - if (pk11_argIsEscape(*string) && !lastEscape) { - lastEscape = PR_TRUE; - continue; - } - lastEscape = PR_FALSE; - *copyString++ = *string; - } - *copyString = 0; - return retString; -} - -static char * -pk11_argSkipParameter(char *string) -{ - char *end; - /* look for the end of the <name>= */ - for (;*string; string++) { - if (*string == '=') { string++; break; } - if (pk11_argIsBlank(*string)) return(string); - } - - end = pk11_argFindEnd(string); - if (*end) end++; - return end; -} - - -static SECStatus -pk11_argParseModuleSpec(char *modulespec, char **lib, char **mod, - char **parameters, char **nss) -{ - int next; - modulespec = pk11_argStrip(modulespec); - - *lib = *mod = *parameters = *nss = 0; - - while (*modulespec) { - PK11_HANDLE_STRING_ARG(modulespec,*lib,PK11_ARG_LIBRARY_PARAMETER,;) - PK11_HANDLE_STRING_ARG(modulespec,*mod,PK11_ARG_NAME_PARAMETER,;) - PK11_HANDLE_STRING_ARG(modulespec,*parameters, - PK11_ARG_MODULE_PARAMETER,;) - PK11_HANDLE_STRING_ARG(modulespec,*nss,PK11_ARG_NSS_PARAMETER,;) - PK11_HANDLE_FINAL_ARG(modulespec) - } - return SECSuccess; -} - - -static char * -pk11_argGetParamValue(char *paramName,char *parameters) -{ - char searchValue[256]; - int paramLen = strlen(paramName); - char *returnValue = NULL; - int next; - - if ((parameters == NULL) || (*parameters == 0)) return NULL; - - PORT_Assert(paramLen+2 < sizeof(searchValue)); - - PORT_Strcpy(searchValue,paramName); - PORT_Strcat(searchValue,"="); - while (*parameters) { - if (PORT_Strncasecmp(parameters,searchValue,paramLen+1) == 0) { - parameters += paramLen+1; - returnValue = pk11_argFetchValue(parameters,&next); - break; - } else { - parameters = pk11_argSkipParameter(parameters); - } - parameters = pk11_argStrip(parameters); - } - return returnValue; -} - - -static char * -pk11_argNextFlag(char *flags) -{ - for (; *flags ; flags++) { - if (*flags == ',') { - flags++; - break; - } - } - return flags; -} - -static PRBool -pk11_argHasFlag(char *label, char *flag, char *parameters) -{ - char *flags,*index; - int len = strlen(flag); - PRBool found = PR_FALSE; - - flags = pk11_argGetParamValue(label,parameters); - if (flags == NULL) return PR_FALSE; - - for (index=flags; *index; index=pk11_argNextFlag(index)) { - if (PORT_Strncasecmp(index,flag,len) == 0) { - found=PR_TRUE; - break; - } - } - PORT_Free(flags); - return found; -} - -static void -pk11_argSetNewCipherFlags(unsigned long *newCiphers,char *cipherList) -{ - newCiphers[0] = newCiphers[1] = 0; - if ((cipherList == NULL) || (*cipherList == 0)) return; - - for (;*cipherList; cipherList=pk11_argNextFlag(cipherList)) { - if (PORT_Strncasecmp(cipherList,PK11_ARG_FORTEZZA_FLAG, - sizeof(PK11_ARG_FORTEZZA_FLAG)-1) == 0) { - newCiphers[0] |= SECMOD_FORTEZZA_FLAG; - } - - /* add additional flags here as necessary */ - /* direct bit mapping escape */ - if (*cipherList == 0) { - if (cipherList[1] == 'l') { - newCiphers[1] |= atoi(&cipherList[2]); - } else { - newCiphers[0] |= atoi(&cipherList[2]); - } - } - } -} - - -/* - * decode a number. handle octal (leading '0'), hex (leading '0x') or decimal - */ -static long -pk11_argDecodeNumber(char *num) -{ - int radix = 10; - unsigned long value = 0; - long retValue = 0; - int sign = 1; - int digit; - - if (num == NULL) return retValue; - - num = pk11_argStrip(num); - - if (*num == '-') { - sign = -1; - num++; - } - - if (*num == '0') { - radix = 8; - num++; - if ((*num == 'x') || (*num == 'X')) { - radix = 16; - num++; - } - } - - - for ( ;*num; num++ ) { - if (isdigit(*num)) { - digit = *num - '0'; - } else if ((*num >= 'a') && (*num <= 'f')) { - digit = *num - 'a' + 10; - } else if ((*num >= 'A') && (*num <= 'F')) { - digit = *num - 'A' + 10; - } else { - break; - } - if (digit >= radix) break; - value = value*radix + digit; - } - - retValue = ((int) value) * sign; - return retValue; -} - -static long -pk11_argReadLong(char *label,char *params, long defValue, PRBool *isdefault) -{ - char *value; - long retValue; - if (isdefault) *isdefault = PR_FALSE; - - value = pk11_argGetParamValue(label,params); - if (value == NULL) { - if (isdefault) *isdefault = PR_TRUE; - return defValue; - } - retValue = pk11_argDecodeNumber(value); - if (value) PORT_Free(value); - - return retValue; -} - - -static unsigned long -pk11_argSlotFlags(char *label,char *params) -{ - char *flags,*index; - unsigned long retValue = 0; - int i; - PRBool all = PR_FALSE; - - flags = pk11_argGetParamValue(label,params); - if (flags == NULL) return 0; - - if (PORT_Strcasecmp(flags,"all") == 0) all = PR_TRUE; - - for (index=flags; *index; index=pk11_argNextFlag(index)) { - for (i=0; i < pk11_argSlotFlagTableSize; i++) { - if (all || (PORT_Strncasecmp(index, pk11_argSlotFlagTable[i].name, - pk11_argSlotFlagTable[i].len) == 0)) { - retValue |= pk11_argSlotFlagTable[i].value; - } - } - } - PORT_Free(flags); - return retValue; -} - - -static void -pk11_argDecodeSingleSlotInfo(char *name,char *params,PK11PreSlotInfo *slotInfo) -{ - char *askpw; - - slotInfo->slotID=pk11_argDecodeNumber(name); - slotInfo->defaultFlags=pk11_argSlotFlags("slotFlags",params); - slotInfo->timeout=pk11_argReadLong("timeout",params, 0, NULL); - - askpw = pk11_argGetParamValue("askpw",params); - slotInfo->askpw = 0; - - if (askpw) { - if (PORT_Strcasecmp(askpw,"every") == 0) { - slotInfo->askpw = -1; - } else if (PORT_Strcasecmp(askpw,"timeout") == 0) { - slotInfo->askpw = 1; - } - PORT_Free(askpw); - slotInfo->defaultFlags |= PK11_OWN_PW_DEFAULTS; - } - slotInfo->hasRootCerts = pk11_argHasFlag("rootFlags","hasRootCerts",params); - slotInfo->hasRootTrust = pk11_argHasFlag("rootFlags","hasRootTrust",params); -} - -static char * -pk11_argGetName(char *inString, int *next) -{ - char *name=NULL; - char *string; - int len; - - /* look for the end of the <name>= */ - for (string = inString;*string; string++) { - if (*string == '=') { break; } - if (pk11_argIsBlank(*string)) break; - } - - len = string - inString; - - *next = len; - if (*string == '=') (*next) += 1; - if (len > 0) { - name = PORT_Alloc(len+1); - PORT_Strncpy(name,inString,len); - name[len] = 0; - } - return name; -} - -static PK11PreSlotInfo * -pk11_argParseSlotInfo(PRArenaPool *arena, char *slotParams, int *retCount) -{ - char *slotIndex; - PK11PreSlotInfo *slotInfo = NULL; - int i=0,count = 0,next; - - *retCount = 0; - if ((slotParams == NULL) || (*slotParams == 0)) return NULL; - - /* first count the number of slots */ - for (slotIndex = pk11_argStrip(slotParams); *slotIndex; - slotIndex = pk11_argStrip(pk11_argSkipParameter(slotIndex))) { - count++; - } - - /* get the data structures */ - if (arena) { - slotInfo = (PK11PreSlotInfo *) - PORT_ArenaAlloc(arena,count*sizeof(PK11PreSlotInfo)); - PORT_Memset(slotInfo,0,count*sizeof(PK11PreSlotInfo)); - } else { - slotInfo = (PK11PreSlotInfo *) - PORT_ZAlloc(count*sizeof(PK11PreSlotInfo)); - } - if (slotInfo == NULL) return NULL; - - for (slotIndex = pk11_argStrip(slotParams), i = 0; - *slotIndex && i < count ; ) { - char *name; - name = pk11_argGetName(slotIndex,&next); - slotIndex += next; - - if (!pk11_argIsBlank(*slotIndex)) { - char *args = pk11_argFetchValue(slotIndex,&next); - slotIndex += next; - if (args) { - pk11_argDecodeSingleSlotInfo(name,args,&slotInfo[i]); - i++; - PORT_Free(args); - } - } - if (name) PORT_Free(name); - slotIndex = pk11_argStrip(slotIndex); - } - *retCount = i; - return slotInfo; -} - -static char *pk11_nullString = ""; - -static char * -pk11_formatValue(PRArenaPool *arena, char *value, char quote) -{ - char *vp,*vp2,*retval; - int size = 0, escapes = 0; - - for (vp=value; *vp ;vp++) { - if ((*vp == quote) || (*vp == PK11_ARG_ESCAPE)) escapes++; - size++; - } - if (arena) { - retval = PORT_ArenaZAlloc(arena,size+escapes+1); - } else { - retval = PORT_ZAlloc(size+escapes+1); - } - if (retval == NULL) return NULL; - vp2 = retval; - for (vp=value; *vp; vp++) { - if ((*vp == quote) || (*vp == PK11_ARG_ESCAPE)) - *vp2++ = PK11_ARG_ESCAPE; - *vp2++ = *vp; - } - return retval; -} - -static char *pk11_formatPair(char *name,char *value, char quote) -{ - char openQuote = quote; - char closeQuote = pk11_argGetPair(quote); - char *newValue = NULL; - char *returnValue; - PRBool need_quote = PR_FALSE; - - if (!value || (*value == 0)) return pk11_nullString; - - if (pk11_argHasBlanks(value) || pk11_argIsQuote(value[0])) - need_quote=PR_TRUE; - - if ((need_quote && pk11_argHasChar(value,closeQuote)) - || pk11_argHasChar(value,PK11_ARG_ESCAPE)) { - value = newValue = pk11_formatValue(NULL, value,quote); - if (newValue == NULL) return pk11_nullString; - } - if (need_quote) { - returnValue = PR_smprintf("%s=%c%s%c",name,openQuote,value,closeQuote); - } else { - returnValue = PR_smprintf("%s=%s",name,value); - } - if (returnValue == NULL) returnValue = pk11_nullString; - - if (newValue) PORT_Free(newValue); - - return returnValue; -} - -static char *pk11_formatIntPair(char *name,unsigned long value, unsigned long def) -{ - char *returnValue; - - if (value == def) return pk11_nullString; - - returnValue = PR_smprintf("%s=%d",name,value); - - return returnValue; -} - -static void -pk11_freePair(char *pair) -{ - if (pair && pair != pk11_nullString) { - PR_smprintf_free(pair); - } -} - -#define MAX_FLAG_SIZE sizeof("internal")+sizeof("FIPS")+sizeof("moduleDB")+\ - sizeof("moduleDBOnly")+sizeof("critical") -static char * -pk11_mkNSSFlags(PRBool internal, PRBool isFIPS, - PRBool isModuleDB, PRBool isModuleDBOnly, PRBool isCritical) -{ - char *flags = (char *)PORT_ZAlloc(MAX_FLAG_SIZE); - PRBool first = PR_TRUE; - - PORT_Memset(flags,0,MAX_FLAG_SIZE); - if (internal) { - PORT_Strcat(flags,"internal"); - first = PR_FALSE; - } - if (isFIPS) { - if (!first) PORT_Strcat(flags,","); - PORT_Strcat(flags,"FIPS"); - first = PR_FALSE; - } - if (isModuleDB) { - if (!first) PORT_Strcat(flags,","); - PORT_Strcat(flags,"moduleDB"); - first = PR_FALSE; - } - if (isModuleDBOnly) { - if (!first) PORT_Strcat(flags,","); - PORT_Strcat(flags,"moduleDBOnly"); - first = PR_FALSE; - } - if (isCritical) { - if (!first) PORT_Strcat(flags,","); - PORT_Strcat(flags,"critical"); - first = PR_FALSE; - } - return flags; -} - -static char * -pk11_mkCipherFlags(unsigned long ssl0, unsigned long ssl1) -{ - char *cipher = NULL; - int i; - - for (i=0; i < sizeof(ssl0)*8; i++) { - if (ssl0 & (1<<i)) { - char *string; - if ((1<<i) == SECMOD_FORTEZZA_FLAG) { - string = PR_smprintf("%s","FORTEZZA"); - } else { - string = PR_smprintf("0h0x%08x",1<<i); - } - if (cipher) { - char *tmp; - tmp = PR_smprintf("%s,%s",cipher,string); - PR_smprintf_free(cipher); - PR_smprintf_free(string); - tmp = cipher; - } else { - cipher = string; - } - } - } - for (i=0; i < sizeof(ssl0)*8; i++) { - if (ssl1 & (1<<i)) { - if (cipher) { - char *tmp; - tmp = PR_smprintf("%s,0l0x%08",cipher,1<<i); - PR_smprintf_free(cipher); - tmp = cipher; - } else { - cipher = PR_smprintf("0l0x%08x",1<<i); - } - } - } - - return cipher; -} - -static char * -pk11_mkSlotFlags(unsigned long defaultFlags) -{ - char *flags=NULL; - int i,j; - - for (i=0; i < sizeof(defaultFlags)*8; i++) { - if (defaultFlags & (1<<i)) { - char *string = NULL; - - for (j=0; j < pk11_argSlotFlagTableSize; j++) { - if (pk11_argSlotFlagTable[j].value == (((unsigned long)1)<<i)) { - string = pk11_argSlotFlagTable[j].name; - break; - } - } - if (string) { - if (flags) { - char *tmp; - tmp = PR_smprintf("%s,%s",flags,string); - PR_smprintf_free(flags); - flags = tmp; - } else { - flags = PR_smprintf("%s",string); - } - } - } - } - - return flags; -} - -#define PK11_MAX_ROOT_FLAG_SIZE sizeof("hasRootCerts")+sizeof("hasRootTrust") - -static char * -pk11_mkRootFlags(PRBool hasRootCerts, PRBool hasRootTrust) -{ - char *flags= (char *)PORT_ZAlloc(PK11_MAX_ROOT_FLAG_SIZE); - PRBool first = PR_TRUE; - - PORT_Memset(flags,0,PK11_MAX_ROOT_FLAG_SIZE); - if (hasRootCerts) { - PORT_Strcat(flags,"hasRootCerts"); - first = PR_FALSE; - } - if (hasRootTrust) { - if (!first) PORT_Strcat(flags,","); - PORT_Strcat(flags,"hasRootTrust"); - first = PR_FALSE; - } - return flags; -} - -static char * -pk11_mkSlotString(unsigned long slotID, unsigned long defaultFlags, - unsigned long timeout, unsigned char askpw_in, - PRBool hasRootCerts, PRBool hasRootTrust) { - char *askpw,*flags,*rootFlags,*slotString; - char *flagPair,*rootFlagsPair; - - switch (askpw_in) { - case 0xff: - askpw = "every"; - break; - case 1: - askpw = "timeout"; - break; - default: - askpw = "any"; - break; - } - flags = pk11_mkSlotFlags(defaultFlags); - rootFlags = pk11_mkRootFlags(hasRootCerts,hasRootTrust); - flagPair=pk11_formatPair("slotFlags",flags,'\''); - rootFlagsPair=pk11_formatPair("rootFlags",rootFlags,'\''); - if (flags) PR_smprintf_free(flags); - if (rootFlags) PORT_Free(rootFlags); - if (defaultFlags & PK11_OWN_PW_DEFAULTS) { - slotString = PR_smprintf("0x%08x=[%s askpw=%s timeout=%d %s]",slotID,flagPair,askpw,timeout,rootFlagsPair); - } else { - slotString = PR_smprintf("0x%08x=[%s %s]",slotID,flagPair,rootFlagsPair); - } - pk11_freePair(flagPair); - pk11_freePair(rootFlagsPair); - return slotString; -} - -static char * -pk11_mkNSS(char **slotStrings, int slotCount, PRBool internal, PRBool isFIPS, - PRBool isModuleDB, PRBool isModuleDBOnly, PRBool isCritical, - unsigned long trustOrder, unsigned long cipherOrder, - unsigned long ssl0, unsigned long ssl1) { - int slotLen, i; - char *slotParams, *ciphers, *nss, *nssFlags, *tmp; - char *trustOrderPair,*cipherOrderPair,*slotPair,*cipherPair,*flagPair; - - - /* now let's build up the string - * first the slot infos - */ - slotLen=0; - for (i=0; i < (int)slotCount; i++) { - slotLen += PORT_Strlen(slotStrings[i])+1; - } - slotLen += 1; /* space for the final NULL */ - - slotParams = (char *)PORT_ZAlloc(slotLen); - PORT_Memset(slotParams,0,slotLen); - for (i=0; i < (int)slotCount; i++) { - PORT_Strcat(slotParams,slotStrings[i]); - PORT_Strcat(slotParams," "); - PR_smprintf_free(slotStrings[i]); - slotStrings[i]=NULL; - } - - /* - * now the NSS structure - */ - nssFlags = pk11_mkNSSFlags(internal,isFIPS,isModuleDB,isModuleDBOnly, - isCritical); - /* for now only the internal module is critical */ - ciphers = pk11_mkCipherFlags(ssl0, ssl1); - - trustOrderPair=pk11_formatIntPair("trustOrder",trustOrder, - PK11_DEFAULT_TRUST_ORDER); - cipherOrderPair=pk11_formatIntPair("cipherOrder",cipherOrder, - PK11_DEFAULT_CIPHER_ORDER); - slotPair=pk11_formatPair("slotParams",slotParams,'{'); /* } */ - if (slotParams) PORT_Free(slotParams); - cipherPair=pk11_formatPair("ciphers",ciphers,'\''); - if (ciphers) PR_smprintf_free(ciphers); - flagPair=pk11_formatPair("Flags",nssFlags,'\''); - if (nssFlags) PORT_Free(nssFlags); - nss = PR_smprintf("%s %s %s %s %s",trustOrderPair, - cipherOrderPair,slotPair,cipherPair,flagPair); - pk11_freePair(trustOrderPair); - pk11_freePair(cipherOrderPair); - pk11_freePair(slotPair); - pk11_freePair(cipherPair); - pk11_freePair(flagPair); - tmp = pk11_argStrip(nss); - if (*tmp == '\0') { - PR_smprintf_free(nss); - nss = NULL; - } - return nss; -} - -static char * -pk11_mkNewModuleSpec(char *dllName, char *commonName, char *parameters, - char *NSS) { - char *moduleSpec; - char *lib,*name,*param,*nss; - - /* - * now the final spec - */ - lib = pk11_formatPair("library",dllName,'\"'); - name = pk11_formatPair("name",commonName,'\"'); - param = pk11_formatPair("parameters",parameters,'\"'); - nss = pk11_formatPair("NSS",NSS,'\"'); - moduleSpec = PR_smprintf("%s %s %s %s", lib,name,param,nss); - pk11_freePair(lib); - pk11_freePair(name); - pk11_freePair(param); - pk11_freePair(nss); - return (moduleSpec); -} - diff --git a/security/nss/lib/softoken/pkcs11.c b/security/nss/lib/softoken/pkcs11.c deleted file mode 100644 index d0fe96637..000000000 --- a/security/nss/lib/softoken/pkcs11.c +++ /dev/null @@ -1,4786 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Stephen Henson <stephen.henson@gemplus.com> - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - */ -/* - * This file implements PKCS 11 on top of our existing security modules - * - * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. - * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login. - * It supports Public Key ops, and all they bulk ciphers and hashes. - * It can also support Private Key ops for imported Private keys. It does - * not have any token storage. - * slot 2 is our private key support. It requires a login before use. It - * can store Private Keys and Certs as token objects. Currently only private - * keys and their associated Certificates are saved on the token. - * - * In this implementation, session objects are only visible to the session - * that created or generated them. - */ -#include "seccomon.h" -#include "secitem.h" -#include "pkcs11.h" -#include "pkcs11i.h" -#include "softoken.h" -#include "lowkeyi.h" -#include "blapi.h" -#include "secder.h" -#include "secport.h" -#include "pcert.h" -#include "secrng.h" - -#include "keydbi.h" - -#ifdef NSS_ENABLE_ECC -extern SECStatus EC_FillParams(PRArenaPool *arena, - const SECItem *encodedParams, ECParams *params); -#endif - -/* - * ******************** Static data ******************************* - */ - -/* The next three strings must be exactly 32 characters long */ -static char *manufacturerID = "mozilla.org "; -static char manufacturerID_space[33]; -static char *libraryDescription = "NSS Internal Crypto Services "; -static char libraryDescription_space[33]; - -#define __PASTE(x,y) x##y - -/* - * we renamed all our internal functions, get the correct - * definitions for them... - */ -#undef CK_PKCS11_FUNCTION_INFO -#undef CK_NEED_ARG_LIST - -#define CK_EXTERN extern -#define CK_PKCS11_FUNCTION_INFO(func) \ - CK_RV __PASTE(NS,func) -#define CK_NEED_ARG_LIST 1 - -#include "pkcs11f.h" - - - -/* build the crypto module table */ -static const CK_FUNCTION_LIST pk11_funcList = { - { 1, 10 }, - -#undef CK_PKCS11_FUNCTION_INFO -#undef CK_NEED_ARG_LIST - -#define CK_PKCS11_FUNCTION_INFO(func) \ - __PASTE(NS,func), -#include "pkcs11f.h" - -}; - -#undef CK_PKCS11_FUNCTION_INFO -#undef CK_NEED_ARG_LIST - - -#undef __PASTE - -/* List of DES Weak Keys */ -typedef unsigned char desKey[8]; -static const desKey pk11_desWeakTable[] = { -#ifdef noParity - /* weak */ - { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, - { 0x1e, 0x1e, 0x1e, 0x1e, 0x0e, 0x0e, 0x0e, 0x0e }, - { 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0xf0, 0xf0, 0xf0 }, - { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe }, - /* semi-weak */ - { 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe }, - { 0xfe, 0x00, 0xfe, 0x00, 0x00, 0xfe, 0x00, 0xfe }, - - { 0x1e, 0xe0, 0x1e, 0xe0, 0x0e, 0xf0, 0x0e, 0xf0 }, - { 0xe0, 0x1e, 0xe0, 0x1e, 0xf0, 0x0e, 0xf0, 0x0e }, - - { 0x00, 0xe0, 0x00, 0xe0, 0x00, 0x0f, 0x00, 0x0f }, - { 0xe0, 0x00, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00 }, - - { 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe }, - { 0xfe, 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e }, - - { 0x00, 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e }, - { 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e, 0x00 }, - - { 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0, 0xfe }, - { 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0 }, -#else - /* weak */ - { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }, - { 0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e }, - { 0xe0, 0xe0, 0xe0, 0xe0, 0xf1, 0xf1, 0xf1, 0xf1 }, - { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe }, - - /* semi-weak */ - { 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe }, - { 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01 }, - - { 0x1f, 0xe0, 0x1f, 0xe0, 0x0e, 0xf1, 0x0e, 0xf1 }, - { 0xe0, 0x1f, 0xe0, 0x1f, 0xf1, 0x0e, 0xf1, 0x0e }, - - { 0x01, 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1 }, - { 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1, 0x01 }, - - { 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe }, - { 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e }, - - { 0x01, 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e }, - { 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e, 0x01 }, - - { 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe }, - { 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1 } -#endif -}; - - -static const int pk11_desWeakTableSize = sizeof(pk11_desWeakTable)/ - sizeof(pk11_desWeakTable[0]); - -/* DES KEY Parity conversion table. Takes each byte/2 as an index, returns - * that byte with the proper parity bit set */ -static const unsigned char parityTable[256] = { -/* Even...0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e */ -/* E */ 0x01,0x02,0x04,0x07,0x08,0x0b,0x0d,0x0e, -/* Odd....0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e */ -/* O */ 0x10,0x13,0x15,0x16,0x19,0x1a,0x1c,0x1f, -/* Odd....0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e */ -/* O */ 0x20,0x23,0x25,0x26,0x29,0x2a,0x2c,0x2f, -/* Even...0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e */ -/* E */ 0x31,0x32,0x34,0x37,0x38,0x3b,0x3d,0x3e, -/* Odd....0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e */ -/* O */ 0x40,0x43,0x45,0x46,0x49,0x4a,0x4c,0x4f, -/* Even...0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e */ -/* E */ 0x51,0x52,0x54,0x57,0x58,0x5b,0x5d,0x5e, -/* Even...0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e */ -/* E */ 0x61,0x62,0x64,0x67,0x68,0x6b,0x6d,0x6e, -/* Odd....0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e */ -/* O */ 0x70,0x73,0x75,0x76,0x79,0x7a,0x7c,0x7f, -/* Odd....0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e */ -/* O */ 0x80,0x83,0x85,0x86,0x89,0x8a,0x8c,0x8f, -/* Even...0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e */ -/* E */ 0x91,0x92,0x94,0x97,0x98,0x9b,0x9d,0x9e, -/* Even...0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae */ -/* E */ 0xa1,0xa2,0xa4,0xa7,0xa8,0xab,0xad,0xae, -/* Odd....0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe */ -/* O */ 0xb0,0xb3,0xb5,0xb6,0xb9,0xba,0xbc,0xbf, -/* Even...0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce */ -/* E */ 0xc1,0xc2,0xc4,0xc7,0xc8,0xcb,0xcd,0xce, -/* Odd....0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde */ -/* O */ 0xd0,0xd3,0xd5,0xd6,0xd9,0xda,0xdc,0xdf, -/* Odd....0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee */ -/* O */ 0xe0,0xe3,0xe5,0xe6,0xe9,0xea,0xec,0xef, -/* Even...0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe */ -/* E */ 0xf1,0xf2,0xf4,0xf7,0xf8,0xfb,0xfd,0xfe, -}; - -/* Mechanisms */ -struct mechanismList { - CK_MECHANISM_TYPE type; - CK_MECHANISM_INFO info; - PRBool privkey; -}; - -/* - * the following table includes a complete list of mechanism defined by - * PKCS #11 version 2.01. Those Mechanisms not supported by this PKCS #11 - * module are ifdef'ed out. - */ -#define CKF_EN_DE CKF_ENCRYPT | CKF_DECRYPT -#define CKF_WR_UN CKF_WRAP | CKF_UNWRAP -#define CKF_SN_VR CKF_SIGN | CKF_VERIFY -#define CKF_SN_RE CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER - -#define CKF_EN_DE_WR_UN CKF_EN_DE | CKF_WR_UN -#define CKF_SN_VR_RE CKF_SN_VR | CKF_SN_RE -#define CKF_DUZ_IT_ALL CKF_EN_DE_WR_UN | CKF_SN_VR_RE - -#define CKF_EC_PNU CKF_EC_FP | CKF_EC_NAMEDCURVE | CKF_EC_UNCOMPRESS - -#define CKF_EC_BPNU CKF_EC_F_2M | CKF_EC_PNU - -#define CK_MAX 0xffffffff - -static const struct mechanismList mechanisms[] = { - - /* - * PKCS #11 Mechanism List. - * - * The first argument is the PKCS #11 Mechanism we support. - * The second argument is Mechanism info structure. It includes: - * The minimum key size, - * in bits for RSA, DSA, DH, EC*, KEA, RC2 and RC4 * algs. - * in bytes for RC5, AES, and CAST* - * ignored for DES*, IDEA and FORTEZZA based - * The maximum key size, - * in bits for RSA, DSA, DH, EC*, KEA, RC2 and RC4 * algs. - * in bytes for RC5, AES, and CAST* - * ignored for DES*, IDEA and FORTEZZA based - * Flags - * What operations are supported by this mechanism. - * The third argument is a bool which tells if this mechanism is - * supported in the database token. - * - */ - - /* ------------------------- RSA Operations ---------------------------*/ - {CKM_RSA_PKCS_KEY_PAIR_GEN,{RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_GENERATE_KEY_PAIR},PR_TRUE}, - {CKM_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_DUZ_IT_ALL}, PR_TRUE}, -#ifdef PK11_RSA9796_SUPPORTED - {CKM_RSA_9796, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_DUZ_IT_ALL}, PR_TRUE}, -#endif - {CKM_RSA_X_509, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_DUZ_IT_ALL}, PR_TRUE}, - /* -------------- RSA Multipart Signing Operations -------------------- */ - {CKM_MD2_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_MD5_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA1_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA256_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA384_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA512_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - /* ------------------------- DSA Operations --------------------------- */ - {CKM_DSA_KEY_PAIR_GEN, {DSA_MIN_P_BITS, DSA_MAX_P_BITS, - CKF_GENERATE_KEY_PAIR}, PR_TRUE}, - {CKM_DSA, {DSA_MIN_P_BITS, DSA_MAX_P_BITS, - CKF_SN_VR}, PR_TRUE}, - {CKM_DSA_SHA1, {DSA_MIN_P_BITS, DSA_MAX_P_BITS, - CKF_SN_VR}, PR_TRUE}, - /* -------------------- Diffie Hellman Operations --------------------- */ - /* no diffie hellman yet */ - {CKM_DH_PKCS_KEY_PAIR_GEN, {DH_MIN_P_BITS, DH_MAX_P_BITS, - CKF_GENERATE_KEY_PAIR}, PR_TRUE}, - {CKM_DH_PKCS_DERIVE, {DH_MIN_P_BITS, DH_MAX_P_BITS, - CKF_DERIVE}, PR_TRUE}, -#ifdef NSS_ENABLE_ECC - /* -------------------- Elliptic Curve Operations --------------------- */ - {CKM_EC_KEY_PAIR_GEN, {112, 571, CKF_GENERATE_KEY_PAIR|CKF_EC_BPNU}, PR_TRUE}, - {CKM_ECDH1_DERIVE, {112, 571, CKF_DERIVE|CKF_EC_BPNU}, PR_TRUE}, - {CKM_ECDSA, {112, 571, CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE}, - {CKM_ECDSA_SHA1, {112, 571, CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE}, -#endif /* NSS_ENABLE_ECC */ - /* ------------------------- RC2 Operations --------------------------- */ - {CKM_RC2_KEY_GEN, {1, 128, CKF_GENERATE}, PR_TRUE}, - {CKM_RC2_ECB, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC2_CBC, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC2_MAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_RC2_MAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_RC2_CBC_PAD, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* ------------------------- RC4 Operations --------------------------- */ - {CKM_RC4_KEY_GEN, {1, 256, CKF_GENERATE}, PR_FALSE}, - {CKM_RC4, {1, 256, CKF_EN_DE_WR_UN}, PR_FALSE}, - /* ------------------------- DES Operations --------------------------- */ - {CKM_DES_KEY_GEN, { 8, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_DES_ECB, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_DES_CBC, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_DES_MAC, { 8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_DES_MAC_GENERAL, { 8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_DES_CBC_PAD, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_DES2_KEY_GEN, {24, 24, CKF_GENERATE}, PR_TRUE}, - {CKM_DES3_KEY_GEN, {24, 24, CKF_GENERATE}, PR_TRUE }, - {CKM_DES3_ECB, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE }, - {CKM_DES3_CBC, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE }, - {CKM_DES3_MAC, {24, 24, CKF_SN_VR}, PR_TRUE }, - {CKM_DES3_MAC_GENERAL, {24, 24, CKF_SN_VR}, PR_TRUE }, - {CKM_DES3_CBC_PAD, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE }, - /* ------------------------- CDMF Operations --------------------------- */ - {CKM_CDMF_KEY_GEN, {8, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_CDMF_ECB, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CDMF_CBC, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CDMF_MAC, {8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CDMF_MAC_GENERAL, {8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CDMF_CBC_PAD, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* ------------------------- AES Operations --------------------------- */ - {CKM_AES_KEY_GEN, {16, 32, CKF_GENERATE}, PR_TRUE}, - {CKM_AES_ECB, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_AES_CBC, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_AES_MAC, {16, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_AES_MAC_GENERAL, {16, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_AES_CBC_PAD, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* ------------------------- Hashing Operations ----------------------- */ - {CKM_MD2, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_MD2_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_MD2_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_MD5, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_MD5_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_MD5_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA_1, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA_1_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA_1_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA256, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA256_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA256_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA384, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA384_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA384_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA512, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA512_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA512_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_TLS_PRF_GENERAL, {0, 512, CKF_SN_VR}, PR_FALSE}, - /* ------------------------- CAST Operations --------------------------- */ -#ifdef NSS_SOFTOKEN_DOES_CAST - /* Cast operations are not supported ( yet? ) */ - {CKM_CAST_KEY_GEN, {1, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_CAST_ECB, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST_CBC, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST_MAC, {1, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST_MAC_GENERAL, {1, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST_CBC_PAD, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST3_KEY_GEN, {1, 16, CKF_GENERATE}, PR_TRUE}, - {CKM_CAST3_ECB, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST3_CBC, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST3_MAC, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST3_MAC_GENERAL, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST3_CBC_PAD, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST5_KEY_GEN, {1, 16, CKF_GENERATE}, PR_TRUE}, - {CKM_CAST5_ECB, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST5_CBC, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST5_MAC, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST5_MAC_GENERAL, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST5_CBC_PAD, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, -#endif -#if NSS_SOFTOKEN_DOES_RC5 - /* ------------------------- RC5 Operations --------------------------- */ - {CKM_RC5_KEY_GEN, {1, 32, CKF_GENERATE}, PR_TRUE}, - {CKM_RC5_ECB, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC5_CBC, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC5_MAC, {1, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_RC5_MAC_GENERAL, {1, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_RC5_CBC_PAD, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, -#endif -#ifdef NSS_SOFTOKEN_DOES_IDEA - /* ------------------------- IDEA Operations -------------------------- */ - {CKM_IDEA_KEY_GEN, {16, 16, CKF_GENERATE}, PR_TRUE}, - {CKM_IDEA_ECB, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_IDEA_CBC, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_IDEA_MAC, {16, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_IDEA_MAC_GENERAL, {16, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_IDEA_CBC_PAD, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, -#endif - /* --------------------- Secret Key Operations ------------------------ */ - {CKM_GENERIC_SECRET_KEY_GEN, {1, 32, CKF_GENERATE}, PR_TRUE}, - {CKM_CONCATENATE_BASE_AND_KEY, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_CONCATENATE_BASE_AND_DATA, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_CONCATENATE_DATA_AND_BASE, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_XOR_BASE_AND_DATA, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_EXTRACT_KEY_FROM_KEY, {1, 32, CKF_DERIVE}, PR_FALSE}, - /* ---------------------- SSL Key Derivations ------------------------- */ - {CKM_SSL3_PRE_MASTER_KEY_GEN, {48, 48, CKF_GENERATE}, PR_FALSE}, - {CKM_SSL3_MASTER_KEY_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_MASTER_KEY_DERIVE_DH, {8, 128, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_KEY_AND_MAC_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_MD5_MAC, { 0, 16, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_SHA1_MAC, { 0, 20, CKF_DERIVE}, PR_FALSE}, - {CKM_MD5_KEY_DERIVATION, { 0, 16, CKF_DERIVE}, PR_FALSE}, - {CKM_MD2_KEY_DERIVATION, { 0, 16, CKF_DERIVE}, PR_FALSE}, - {CKM_SHA1_KEY_DERIVATION, { 0, 20, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS_MASTER_KEY_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS_MASTER_KEY_DERIVE_DH, {8, 128, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS_KEY_AND_MAC_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - /* ---------------------- PBE Key Derivations ------------------------ */ - {CKM_PBE_MD2_DES_CBC, {8, 8, CKF_DERIVE}, PR_TRUE}, - {CKM_PBE_MD5_DES_CBC, {8, 8, CKF_DERIVE}, PR_TRUE}, - /* ------------------ NETSCAPE PBE Key Derivations ------------------- */ - {CKM_NETSCAPE_PBE_SHA1_DES_CBC, { 8, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC, {24,24, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_DES3_EDE_CBC, {24,24, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_DES2_EDE_CBC, {24,24, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC2_40_CBC, {40,40, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC2_128_CBC, {128,128, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC4_40, {40,40, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC4_128, {128,128, CKF_GENERATE}, PR_TRUE}, - {CKM_PBA_SHA1_WITH_SHA1_HMAC, {20,20, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN, {20,20, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN, {16,16, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN, {16,16, CKF_GENERATE}, PR_TRUE}, - /* ------------------ AES Key Wrap (also encrypt) ------------------- */ - {CKM_NETSCAPE_AES_KEY_WRAP, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_NETSCAPE_AES_KEY_WRAP_PAD, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, -}; -static const CK_ULONG mechanismCount = sizeof(mechanisms)/sizeof(mechanisms[0]); - -static char * -pk11_setStringName(const char *inString, char *buffer, int buffer_length) -{ - int full_length, string_length; - - full_length = buffer_length -1; - string_length = PORT_Strlen(inString); - /* - * shorten the string, respecting utf8 encoding - * to do so, we work backward from the end - * bytes looking from the end are either: - * - ascii [0x00,0x7f] - * - the [2-n]th byte of a multibyte sequence - * [0x3F,0xBF], i.e, most significant 2 bits are '10' - * - the first byte of a multibyte sequence [0xC0,0xFD], - * i.e, most significant 2 bits are '11' - * - * When the string is too long, we lop off any trailing '10' bytes, - * if any. When these are all eliminated we lop off - * one additional byte. Thus if we lopped any '10' - * we'll be lopping a '11' byte (the first byte of the multibyte sequence), - * otherwise we're lopping off an ascii character. - * - * To test for '10' bytes, we first AND it with - * 11000000 (0xc0) so that we get 10000000 (0x80) if and only if - * the byte starts with 10. We test for equality. - */ - while ( string_length > full_length ) { - /* need to shorten */ - while ( string_length > 0 && - ((inString[string_length-1]&(char)0xc0) == (char)0x80)) { - /* lop off '10' byte */ - string_length--; - } - /* - * test string_length in case bad data is received - * and string consisted of all '10' bytes, - * avoiding any infinite loop - */ - if ( string_length ) { - /* remove either '11' byte or an asci byte */ - string_length--; - } - } - PORT_Memset(buffer,' ',full_length); - buffer[full_length] = 0; - PORT_Memcpy(buffer,inString,string_length); - return buffer; -} -/* - * Configuration utils - */ -static CK_RV -pk11_configure(const char *man, const char *libdes) -{ - - /* make sure the internationalization was done correctly... */ - if (man) { - manufacturerID = pk11_setStringName(man,manufacturerID_space, - sizeof(manufacturerID_space)); - } - if (libdes) { - libraryDescription = pk11_setStringName(libdes, - libraryDescription_space, sizeof(libraryDescription_space)); - } - - return CKR_OK; -} - -/* - * ******************** Password Utilities ******************************* - */ - -/* - * see if the key DB password is enabled - */ -PRBool -pk11_hasNullPassword(NSSLOWKEYDBHandle *keydb,SECItem **pwitem) -{ - PRBool pwenabled; - - pwenabled = PR_FALSE; - *pwitem = NULL; - if (nsslowkey_HasKeyDBPassword (keydb) == SECSuccess) { - *pwitem = nsslowkey_HashPassword("", keydb->global_salt); - if ( *pwitem ) { - if (nsslowkey_CheckKeyDBPassword (keydb, *pwitem) == SECSuccess) { - pwenabled = PR_TRUE; - } else { - SECITEM_ZfreeItem(*pwitem, PR_TRUE); - *pwitem = NULL; - } - } - } - - return pwenabled; -} - -/* - * ******************** Object Creation Utilities *************************** - */ - - -/* Make sure a given attribute exists. If it doesn't, initialize it to - * value and len - */ -CK_RV -pk11_defaultAttribute(PK11Object *object,CK_ATTRIBUTE_TYPE type,void *value, - unsigned int len) -{ - if ( !pk11_hasAttribute(object, type)) { - return pk11_AddAttributeType(object,type,value,len); - } - return CKR_OK; -} - -/* - * check the consistancy and initialize a Data Object - */ -static CK_RV -pk11_handleDataObject(PK11Session *session,PK11Object *object) -{ - CK_RV crv; - - /* first reject private and token data objects */ - if (pk11_isTrue(object,CKA_PRIVATE) || pk11_isTrue(object,CKA_TOKEN)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - /* now just verify the required date fields */ - crv = pk11_defaultAttribute(object,CKA_APPLICATION,NULL,0); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_VALUE,NULL,0); - if (crv != CKR_OK) return crv; - - return CKR_OK; -} - -/* - * check the consistancy and initialize a Certificate Object - */ -static CK_RV -pk11_handleCertObject(PK11Session *session,PK11Object *object) -{ - CK_CERTIFICATE_TYPE type; - PK11Attribute *attribute; - CK_RV crv; - - /* certificates must have a type */ - if ( !pk11_hasAttribute(object,CKA_CERTIFICATE_TYPE) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* we can't store any certs private */ - if (pk11_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - /* We only support X.509 Certs for now */ - attribute = pk11_FindAttribute(object,CKA_CERTIFICATE_TYPE); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; - type = *(CK_CERTIFICATE_TYPE *)attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - - if (type != CKC_X_509) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - /* X.509 Certificate */ - - /* make sure we have a cert */ - if ( !pk11_hasAttribute(object,CKA_VALUE) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* in PKCS #11, Subject is a required field */ - if ( !pk11_hasAttribute(object,CKA_SUBJECT) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* in PKCS #11, Issuer is a required field */ - if ( !pk11_hasAttribute(object,CKA_ISSUER) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* in PKCS #11, Serial is a required field */ - if ( !pk11_hasAttribute(object,CKA_SERIAL_NUMBER) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* add it to the object */ - object->objectInfo = NULL; - object->infoFree = (PK11Free) NULL; - - /* now just verify the required date fields */ - crv = pk11_defaultAttribute(object, CKA_ID, NULL, 0); - if (crv != CKR_OK) { return crv; } - - if (pk11_isTrue(object,CKA_TOKEN)) { - PK11Slot *slot = session->slot; - SECItem derCert; - NSSLOWCERTCertificate *cert; - NSSLOWCERTCertTrust *trust = NULL; - NSSLOWCERTCertTrust userTrust = - { CERTDB_USER, CERTDB_USER, CERTDB_USER }; - NSSLOWCERTCertTrust defTrust = - { CERTDB_TRUSTED_UNKNOWN, - CERTDB_TRUSTED_UNKNOWN, CERTDB_TRUSTED_UNKNOWN }; - char *label = NULL; - char *email = NULL; - SECStatus rv; - PRBool inDB = PR_TRUE; - - if (slot->certDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - /* get the der cert */ - attribute = pk11_FindAttribute(object,CKA_VALUE); - PORT_Assert(attribute); - - derCert.type = 0; - derCert.data = (unsigned char *)attribute->attrib.pValue; - derCert.len = attribute->attrib.ulValueLen ; - - label = pk11_getString(object,CKA_LABEL); - - cert = nsslowcert_FindCertByDERCert(slot->certDB, &derCert); - if (cert == NULL) { - cert = nsslowcert_DecodeDERCertificate(&derCert, label); - inDB = PR_FALSE; - } - if (cert == NULL) { - if (label) PORT_Free(label); - pk11_FreeAttribute(attribute); - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - if (slot->keyDB && nsslowkey_KeyForCertExists(slot->keyDB,cert)) { - trust = &userTrust; - } - if (!inDB) { - if (!trust) trust = &defTrust; - rv = nsslowcert_AddPermCert(slot->certDB, cert, label, trust); - } else { - rv = trust ? nsslowcert_ChangeCertTrust(slot->certDB,cert,trust) : - SECSuccess; - } - - if (label) PORT_Free(label); - pk11_FreeAttribute(attribute); - - if (rv != SECSuccess) { - nsslowcert_DestroyCertificate(cert); - return CKR_DEVICE_ERROR; - } - - /* - * Add a NULL S/MIME profile if necessary. - */ - email = pk11_getString(object,CKA_NETSCAPE_EMAIL); - if (email) { - certDBEntrySMime *entry; - - entry = nsslowcert_ReadDBSMimeEntry(slot->certDB,email); - if (!entry) { - nsslowcert_SaveSMimeProfile(slot->certDB, email, - &cert->derSubject, NULL, NULL); - } else { - nsslowcert_DestroyDBEntry((certDBEntry *)entry); - } - PORT_Free(email); - } - object->handle=pk11_mkHandle(slot,&cert->certKey,PK11_TOKEN_TYPE_CERT); - nsslowcert_DestroyCertificate(cert); - } - - return CKR_OK; -} - -unsigned int -pk11_MapTrust(CK_TRUST trust, PRBool clientAuth) -{ - unsigned int trustCA = clientAuth ? CERTDB_TRUSTED_CLIENT_CA : - CERTDB_TRUSTED_CA; - switch (trust) { - case CKT_NETSCAPE_TRUSTED: - return CERTDB_VALID_PEER|CERTDB_TRUSTED; - case CKT_NETSCAPE_TRUSTED_DELEGATOR: - return CERTDB_VALID_CA|trustCA; - case CKT_NETSCAPE_UNTRUSTED: - return CERTDB_NOT_TRUSTED; - case CKT_NETSCAPE_MUST_VERIFY: - return 0; - case CKT_NETSCAPE_VALID: /* implies must verify */ - return CERTDB_VALID_PEER; - case CKT_NETSCAPE_VALID_DELEGATOR: /* implies must verify */ - return CERTDB_VALID_CA; - default: - break; - } - return CERTDB_TRUSTED_UNKNOWN; -} - - -/* - * check the consistancy and initialize a Trust Object - */ -static CK_RV -pk11_handleTrustObject(PK11Session *session,PK11Object *object) -{ - NSSLOWCERTIssuerAndSN issuerSN; - - /* we can't store any certs private */ - if (pk11_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - /* certificates must have a type */ - if ( !pk11_hasAttribute(object,CKA_ISSUER) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object,CKA_SERIAL_NUMBER) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object,CKA_CERT_SHA1_HASH) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object,CKA_CERT_MD5_HASH) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - if (pk11_isTrue(object,CKA_TOKEN)) { - PK11Slot *slot = session->slot; - PK11Attribute *issuer = NULL; - PK11Attribute *serial = NULL; - NSSLOWCERTCertificate *cert = NULL; - PK11Attribute *trust; - CK_TRUST sslTrust = CKT_NETSCAPE_TRUST_UNKNOWN; - CK_TRUST clientTrust = CKT_NETSCAPE_TRUST_UNKNOWN; - CK_TRUST emailTrust = CKT_NETSCAPE_TRUST_UNKNOWN; - CK_TRUST signTrust = CKT_NETSCAPE_TRUST_UNKNOWN; - NSSLOWCERTCertTrust dbTrust = { 0 }; - SECStatus rv; - - - if (slot->certDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - issuer = pk11_FindAttribute(object,CKA_ISSUER); - PORT_Assert(issuer); - issuerSN.derIssuer.data = (unsigned char *)issuer->attrib.pValue; - issuerSN.derIssuer.len = issuer->attrib.ulValueLen ; - - serial = pk11_FindAttribute(object,CKA_SERIAL_NUMBER); - PORT_Assert(serial); - issuerSN.serialNumber.data = (unsigned char *)serial->attrib.pValue; - issuerSN.serialNumber.len = serial->attrib.ulValueLen ; - - cert = nsslowcert_FindCertByIssuerAndSN(slot->certDB,&issuerSN); - pk11_FreeAttribute(serial); - pk11_FreeAttribute(issuer); - - if (cert == NULL) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - trust = pk11_FindAttribute(object,CKA_TRUST_SERVER_AUTH); - if (trust) { - if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) { - PORT_Memcpy(&sslTrust,trust->attrib.pValue, sizeof(sslTrust)); - } - pk11_FreeAttribute(trust); - } - trust = pk11_FindAttribute(object,CKA_TRUST_CLIENT_AUTH); - if (trust) { - if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) { - PORT_Memcpy(&clientTrust,trust->attrib.pValue, - sizeof(clientTrust)); - } - pk11_FreeAttribute(trust); - } - trust = pk11_FindAttribute(object,CKA_TRUST_EMAIL_PROTECTION); - if (trust) { - if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) { - PORT_Memcpy(&emailTrust,trust->attrib.pValue, - sizeof(emailTrust)); - } - pk11_FreeAttribute(trust); - } - trust = pk11_FindAttribute(object,CKA_TRUST_CODE_SIGNING); - if (trust) { - if (trust->attrib.ulValueLen == sizeof(CK_TRUST)) { - PORT_Memcpy(&signTrust,trust->attrib.pValue, - sizeof(signTrust)); - } - pk11_FreeAttribute(trust); - } - - /* preserve certain old fields */ - if (cert->trust) { - dbTrust.sslFlags = - cert->trust->sslFlags & CERTDB_PRESERVE_TRUST_BITS; - dbTrust.emailFlags= - cert->trust->emailFlags & CERTDB_PRESERVE_TRUST_BITS; - dbTrust.objectSigningFlags = - cert->trust->objectSigningFlags & CERTDB_PRESERVE_TRUST_BITS; - } - - dbTrust.sslFlags |= pk11_MapTrust(sslTrust,PR_FALSE); - dbTrust.sslFlags |= pk11_MapTrust(clientTrust,PR_TRUE); - dbTrust.emailFlags |= pk11_MapTrust(emailTrust,PR_FALSE); - dbTrust.objectSigningFlags |= pk11_MapTrust(signTrust,PR_FALSE); - - rv = nsslowcert_ChangeCertTrust(slot->certDB,cert,&dbTrust); - object->handle=pk11_mkHandle(slot,&cert->certKey,PK11_TOKEN_TYPE_TRUST); - nsslowcert_DestroyCertificate(cert); - if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; - } - } - - return CKR_OK; -} - -/* - * check the consistancy and initialize a Trust Object - */ -static CK_RV -pk11_handleSMimeObject(PK11Session *session,PK11Object *object) -{ - - /* we can't store any certs private */ - if (pk11_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - /* certificates must have a type */ - if ( !pk11_hasAttribute(object,CKA_SUBJECT) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object,CKA_NETSCAPE_EMAIL) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - if (pk11_isTrue(object,CKA_TOKEN)) { - PK11Slot *slot = session->slot; - SECItem derSubj,rawProfile,rawTime,emailKey; - SECItem *pRawProfile = NULL; - SECItem *pRawTime = NULL; - char *email = NULL; - PK11Attribute *subject,*profile,*time; - SECStatus rv; - - PORT_Assert(slot); - if (slot->certDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - /* lookup SUBJECT */ - subject = pk11_FindAttribute(object,CKA_SUBJECT); - PORT_Assert(subject); - derSubj.data = (unsigned char *)subject->attrib.pValue; - derSubj.len = subject->attrib.ulValueLen ; - derSubj.type = 0; - - /* lookup VALUE */ - profile = pk11_FindAttribute(object,CKA_VALUE); - if (profile) { - rawProfile.data = (unsigned char *)profile->attrib.pValue; - rawProfile.len = profile->attrib.ulValueLen ; - rawProfile.type = siBuffer; - pRawProfile = &rawProfile; - } - - /* lookup Time */ - time = pk11_FindAttribute(object,CKA_NETSCAPE_SMIME_TIMESTAMP); - if (time) { - rawTime.data = (unsigned char *)time->attrib.pValue; - rawTime.len = time->attrib.ulValueLen ; - rawTime.type = siBuffer; - pRawTime = &rawTime; - } - - - email = pk11_getString(object,CKA_NETSCAPE_EMAIL); - - /* Store CRL by SUBJECT */ - rv = nsslowcert_SaveSMimeProfile(slot->certDB, email, &derSubj, - pRawProfile,pRawTime); - - pk11_FreeAttribute(subject); - if (profile) pk11_FreeAttribute(profile); - if (time) pk11_FreeAttribute(time); - if (rv != SECSuccess) { - PORT_Free(email); - return CKR_DEVICE_ERROR; - } - emailKey.data = (unsigned char *)email; - emailKey.len = PORT_Strlen(email)+1; - - object->handle = pk11_mkHandle(slot, &emailKey, PK11_TOKEN_TYPE_SMIME); - PORT_Free(email); - } - - return CKR_OK; -} - -/* - * check the consistancy and initialize a Trust Object - */ -static CK_RV -pk11_handleCrlObject(PK11Session *session,PK11Object *object) -{ - - /* we can't store any certs private */ - if (pk11_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - /* certificates must have a type */ - if ( !pk11_hasAttribute(object,CKA_SUBJECT) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object,CKA_VALUE) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - if (pk11_isTrue(object,CKA_TOKEN)) { - PK11Slot *slot = session->slot; - PRBool isKRL = PR_FALSE; - SECItem derSubj,derCrl; - char *url = NULL; - PK11Attribute *subject,*crl; - SECStatus rv; - - PORT_Assert(slot); - if (slot->certDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - /* lookup SUBJECT */ - subject = pk11_FindAttribute(object,CKA_SUBJECT); - PORT_Assert(subject); - derSubj.data = (unsigned char *)subject->attrib.pValue; - derSubj.len = subject->attrib.ulValueLen ; - - /* lookup VALUE */ - crl = pk11_FindAttribute(object,CKA_VALUE); - PORT_Assert(crl); - derCrl.data = (unsigned char *)crl->attrib.pValue; - derCrl.len = crl->attrib.ulValueLen ; - - - url = pk11_getString(object,CKA_NETSCAPE_URL); - isKRL = pk11_isTrue(object,CKA_NETSCAPE_KRL); - - /* Store CRL by SUBJECT */ - rv = nsslowcert_AddCrl(slot->certDB, &derCrl, &derSubj, url, isKRL); - - if (url) { - PORT_Free(url); - } - pk11_FreeAttribute(crl); - if (rv != SECSuccess) { - pk11_FreeAttribute(subject); - return CKR_DEVICE_ERROR; - } - - /* if we overwrote the existing CRL, poison the handle entry so we get - * a new object handle */ - (void) pk11_poisonHandle(slot, &derSubj, - isKRL ? PK11_TOKEN_KRL_HANDLE : PK11_TOKEN_TYPE_CRL); - object->handle = pk11_mkHandle(slot, &derSubj, - isKRL ? PK11_TOKEN_KRL_HANDLE : PK11_TOKEN_TYPE_CRL); - pk11_FreeAttribute(subject); - } - - return CKR_OK; -} - -/* - * check the consistancy and initialize a Public Key Object - */ -static CK_RV -pk11_handlePublicKeyObject(PK11Session *session, PK11Object *object, - CK_KEY_TYPE key_type) -{ - CK_BBOOL encrypt = CK_TRUE; - CK_BBOOL recover = CK_TRUE; - CK_BBOOL wrap = CK_TRUE; - CK_BBOOL derive = CK_FALSE; - CK_BBOOL verify = CK_TRUE; - CK_ATTRIBUTE_TYPE pubKeyAttr = CKA_VALUE; - PK11Attribute *attribute; - CK_RV crv; - - switch (key_type) { - case CKK_RSA: - crv = pk11_ConstrainAttribute(object, CKA_MODULUS, - RSA_MIN_MODULUS_BITS, 0, 0); - if (crv != CKR_OK) { - return crv; - } - crv = pk11_ConstrainAttribute(object, CKA_PUBLIC_EXPONENT, 2, 0, 0); - if (crv != CKR_OK) { - return crv; - } - pubKeyAttr = CKA_MODULUS; - break; - case CKK_DSA: - crv = pk11_ConstrainAttribute(object, CKA_SUBPRIME, - DSA_Q_BITS, DSA_Q_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = pk11_ConstrainAttribute(object, CKA_PRIME, - DSA_MIN_P_BITS, DSA_MAX_P_BITS, 64); - if (crv != CKR_OK) { - return crv; - } - crv = pk11_ConstrainAttribute(object, CKA_BASE, 1, DSA_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = pk11_ConstrainAttribute(object, CKA_VALUE, 1, DSA_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; - case CKK_DH: - crv = pk11_ConstrainAttribute(object, CKA_PRIME, - DH_MIN_P_BITS, DH_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = pk11_ConstrainAttribute(object, CKA_BASE, 1, DH_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = pk11_ConstrainAttribute(object, CKA_VALUE, 1, DH_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - verify = CK_FALSE; - derive = CK_TRUE; - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; -#ifdef NSS_ENABLE_ECC - case CKK_EC: - if ( !pk11_hasAttribute(object, CKA_EC_PARAMS)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_EC_POINT)) { - return CKR_TEMPLATE_INCOMPLETE; - } - pubKeyAttr = CKA_EC_POINT; - derive = CK_TRUE; /* for ECDH */ - verify = CK_TRUE; /* for ECDSA */ - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; -#endif /* NSS_ENABLE_ECC */ - default: - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - /* make sure the required fields exist */ - crv = pk11_defaultAttribute(object,CKA_SUBJECT,NULL,0); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_ENCRYPT,&encrypt,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_VERIFY,&verify,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_VERIFY_RECOVER, - &recover,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_WRAP,&wrap,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_DERIVE,&derive,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - object->objectInfo = pk11_GetPubKey(object,key_type, &crv); - if (object->objectInfo == NULL) { - return crv; - } - object->infoFree = (PK11Free) nsslowkey_DestroyPublicKey; - - if (pk11_isTrue(object,CKA_TOKEN)) { - PK11Slot *slot = session->slot; - NSSLOWKEYPrivateKey *priv; - SECItem pubKey; - - crv = pk11_Attribute2SSecItem(NULL,&pubKey,object,pubKeyAttr); - if (crv != CKR_OK) return crv; - - PORT_Assert(pubKey.data); - if (slot->keyDB == NULL) { - PORT_Free(pubKey.data); - return CKR_TOKEN_WRITE_PROTECTED; - } - if (slot->keyDB->version != 3) { - unsigned char buf[SHA1_LENGTH]; - SHA1_HashBuf(buf,pubKey.data,pubKey.len); - PORT_Memcpy(pubKey.data,buf,sizeof(buf)); - pubKey.len = sizeof(buf); - } - /* make sure the associated private key already exists */ - /* only works if we are logged in */ - priv = nsslowkey_FindKeyByPublicKey(slot->keyDB, &pubKey, - slot->password); - if (priv == NULL) { - PORT_Free(pubKey.data); - return CKR_ATTRIBUTE_VALUE_INVALID; - } - nsslowkey_DestroyPrivateKey(priv); - - object->handle = pk11_mkHandle(slot, &pubKey, PK11_TOKEN_TYPE_PUB); - PORT_Free(pubKey.data); - } - - return CKR_OK; -} - -static NSSLOWKEYPrivateKey * -pk11_mkPrivKey(PK11Object *object,CK_KEY_TYPE key, CK_RV *rvp); - -/* - * check the consistancy and initialize a Private Key Object - */ -static CK_RV -pk11_handlePrivateKeyObject(PK11Session *session,PK11Object *object,CK_KEY_TYPE key_type) -{ - CK_BBOOL cktrue = CK_TRUE; - CK_BBOOL encrypt = CK_TRUE; - CK_BBOOL recover = CK_TRUE; - CK_BBOOL wrap = CK_TRUE; - CK_BBOOL derive = CK_FALSE; - CK_BBOOL ckfalse = CK_FALSE; - SECItem mod; - CK_RV crv; - - switch (key_type) { - case CKK_RSA: - if ( !pk11_hasAttribute(object, CKA_MODULUS)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_PUBLIC_EXPONENT)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_PRIVATE_EXPONENT)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_PRIME_1)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_PRIME_2)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_EXPONENT_1)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_EXPONENT_2)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_COEFFICIENT)) { - return CKR_TEMPLATE_INCOMPLETE; - } - /* make sure Netscape DB attribute is set correctly */ - crv = pk11_Attribute2SSecItem(NULL, &mod, object, CKA_MODULUS); - if (crv != CKR_OK) return crv; - crv = pk11_forceAttribute(object, CKA_NETSCAPE_DB, - pk11_item_expand(&mod)); - if (mod.data) PORT_Free(mod.data); - if (crv != CKR_OK) return crv; - - break; - case CKK_DSA: - if ( !pk11_hasAttribute(object, CKA_SUBPRIME)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_NETSCAPE_DB)) { - return CKR_TEMPLATE_INCOMPLETE; - } - /* fall through */ - case CKK_DH: - if ( !pk11_hasAttribute(object, CKA_PRIME)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_BASE)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_VALUE)) { - return CKR_TEMPLATE_INCOMPLETE; - } - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; -#ifdef NSS_ENABLE_ECC - case CKK_EC: - if ( !pk11_hasAttribute(object, CKA_EC_PARAMS)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_VALUE)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !pk11_hasAttribute(object, CKA_NETSCAPE_DB)) { - return CKR_TEMPLATE_INCOMPLETE; - } - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - derive = CK_TRUE; - break; -#endif /* NSS_ENABLE_ECC */ - default: - return CKR_ATTRIBUTE_VALUE_INVALID; - } - crv = pk11_defaultAttribute(object,CKA_SUBJECT,NULL,0); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_SENSITIVE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_EXTRACTABLE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_DECRYPT,&encrypt,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_SIGN,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_SIGN_RECOVER,&recover, - sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_UNWRAP,&wrap,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_DERIVE,&derive,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - /* the next two bits get modified only in the key gen and token cases */ - crv = pk11_forceAttribute(object,CKA_ALWAYS_SENSITIVE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_forceAttribute(object,CKA_NEVER_EXTRACTABLE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - /* should we check the non-token RSA private keys? */ - - if (pk11_isTrue(object,CKA_TOKEN)) { - PK11Slot *slot = session->slot; - NSSLOWKEYPrivateKey *privKey; - char *label; - SECStatus rv = SECSuccess; - SECItem pubKey; - - if (slot->keyDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - privKey=pk11_mkPrivKey(object,key_type,&crv); - if (privKey == NULL) return crv; - label = pk11_getString(object,CKA_LABEL); - - crv = pk11_Attribute2SSecItem(NULL,&pubKey,object,CKA_NETSCAPE_DB); - if (crv != CKR_OK) { - if (label) PORT_Free(label); - nsslowkey_DestroyPrivateKey(privKey); - return CKR_TEMPLATE_INCOMPLETE; - } - if (slot->keyDB->version != 3) { - unsigned char buf[SHA1_LENGTH]; - SHA1_HashBuf(buf,pubKey.data,pubKey.len); - PORT_Memcpy(pubKey.data,buf,sizeof(buf)); - pubKey.len = sizeof(buf); - } - - if (key_type == CKK_RSA) { - rv = RSA_PrivateKeyCheck(&privKey->u.rsa); - if (rv == SECFailure) { - goto fail; - } - } - rv = nsslowkey_StoreKeyByPublicKey(object->slot->keyDB, - privKey, &pubKey, label, object->slot->password); - -fail: - if (label) PORT_Free(label); - object->handle = pk11_mkHandle(slot,&pubKey,PK11_TOKEN_TYPE_PRIV); - if (pubKey.data) PORT_Free(pubKey.data); - nsslowkey_DestroyPrivateKey(privKey); - if (rv != SECSuccess) return CKR_DEVICE_ERROR; - } else { - object->objectInfo = pk11_mkPrivKey(object,key_type,&crv); - if (object->objectInfo == NULL) return crv; - object->infoFree = (PK11Free) nsslowkey_DestroyPrivateKey; - /* now NULL out the sensitive attributes */ - if (pk11_isTrue(object,CKA_SENSITIVE)) { - pk11_nullAttribute(object,CKA_PRIVATE_EXPONENT); - pk11_nullAttribute(object,CKA_PRIME_1); - pk11_nullAttribute(object,CKA_PRIME_2); - pk11_nullAttribute(object,CKA_EXPONENT_1); - pk11_nullAttribute(object,CKA_EXPONENT_2); - pk11_nullAttribute(object,CKA_COEFFICIENT); - } - } - return CKR_OK; -} - -/* forward delcare the DES formating function for handleSecretKey */ -void pk11_FormatDESKey(unsigned char *key, int length); -static NSSLOWKEYPrivateKey *pk11_mkSecretKeyRep(PK11Object *object); - -/* Validate secret key data, and set defaults */ -static CK_RV -validateSecretKey(PK11Session *session, PK11Object *object, - CK_KEY_TYPE key_type, PRBool isFIPS) -{ - CK_RV crv; - CK_BBOOL cktrue = CK_TRUE; - CK_BBOOL ckfalse = CK_FALSE; - PK11Attribute *attribute = NULL; - unsigned long requiredLen; - - crv = pk11_defaultAttribute(object,CKA_SENSITIVE, - isFIPS?&cktrue:&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_EXTRACTABLE, - &cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_ENCRYPT,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_DECRYPT,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_SIGN,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_VERIFY,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_WRAP,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_UNWRAP,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - if ( !pk11_hasAttribute(object, CKA_VALUE)) { - return CKR_TEMPLATE_INCOMPLETE; - } - /* the next two bits get modified only in the key gen and token cases */ - crv = pk11_forceAttribute(object,CKA_ALWAYS_SENSITIVE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_forceAttribute(object,CKA_NEVER_EXTRACTABLE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - /* some types of keys have a value length */ - crv = CKR_OK; - switch (key_type) { - /* force CKA_VALUE_LEN to be set */ - case CKK_GENERIC_SECRET: - case CKK_RC2: - case CKK_RC4: -#if NSS_SOFTOKEN_DOES_RC5 - case CKK_RC5: -#endif -#ifdef NSS_SOFTOKEN_DOES_CAST - case CKK_CAST: - case CKK_CAST3: - case CKK_CAST5: -#endif -#if NSS_SOFTOKEN_DOES_IDEA - case CKK_IDEA: -#endif - attribute = pk11_FindAttribute(object,CKA_VALUE); - /* shouldn't happen */ - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; - crv = pk11_forceAttribute(object, CKA_VALUE_LEN, - &attribute->attrib.ulValueLen, sizeof(CK_ULONG)); - pk11_FreeAttribute(attribute); - break; - /* force the value to have the correct parity */ - case CKK_DES: - case CKK_DES2: - case CKK_DES3: - case CKK_CDMF: - attribute = pk11_FindAttribute(object,CKA_VALUE); - /* shouldn't happen */ - if (attribute == NULL) - return CKR_TEMPLATE_INCOMPLETE; - requiredLen = pk11_MapKeySize(key_type); - if (attribute->attrib.ulValueLen != requiredLen) { - pk11_FreeAttribute(attribute); - return CKR_KEY_SIZE_RANGE; - } - pk11_FormatDESKey((unsigned char*)attribute->attrib.pValue, - attribute->attrib.ulValueLen); - pk11_FreeAttribute(attribute); - break; - default: - break; - } - - return crv; -} - -#define PK11_KEY_MAX_RETRIES 10 /* don't hang if we are having problems with the rng */ -#define PK11_KEY_ID_SIZE 18 /* don't use either SHA1 or MD5 sizes */ -/* - * Secret keys must have a CKA_ID value to be stored in the database. This code - * will generate one if there wasn't one already. - */ -static CK_RV -pk11_GenerateSecretCKA_ID(NSSLOWKEYDBHandle *handle, SECItem *id, char *label) -{ - unsigned int retries; - SECStatus rv = SECSuccess; - CK_RV crv = CKR_OK; - - id->data = NULL; - if (label) { - id->data = (unsigned char *)PORT_Strdup(label); - if (id->data == NULL) { - return CKR_HOST_MEMORY; - } - id->len = PORT_Strlen(label)+1; - if (!nsslowkey_KeyForIDExists(handle,id)) { - return CKR_OK; - } - PORT_Free(id->data); - id->data = NULL; - id->len = 0; - } - id->data = (unsigned char *)PORT_Alloc(PK11_KEY_ID_SIZE); - if (id->data == NULL) { - return CKR_HOST_MEMORY; - } - id->len = PK11_KEY_ID_SIZE; - - retries = 0; - do { - rv = RNG_GenerateGlobalRandomBytes(id->data,id->len); - } while (rv == SECSuccess && nsslowkey_KeyForIDExists(handle,id) && - (++retries <= PK11_KEY_MAX_RETRIES)); - - if ((rv != SECSuccess) || (retries > PK11_KEY_MAX_RETRIES)) { - crv = CKR_DEVICE_ERROR; /* random number generator is bad */ - PORT_Free(id->data); - id->data = NULL; - id->len = 0; - } - return crv; -} - -/* - * check the consistancy and initialize a Secret Key Object - */ -static CK_RV -pk11_handleSecretKeyObject(PK11Session *session,PK11Object *object, - CK_KEY_TYPE key_type, PRBool isFIPS) -{ - CK_RV crv; - NSSLOWKEYPrivateKey *privKey = NULL; - SECItem pubKey; - char *label = NULL; - - pubKey.data = 0; - - /* First validate and set defaults */ - crv = validateSecretKey(session, object, key_type, isFIPS); - if (crv != CKR_OK) goto loser; - - /* If the object is a TOKEN object, store in the database */ - if (pk11_isTrue(object,CKA_TOKEN)) { - PK11Slot *slot = session->slot; - SECStatus rv = SECSuccess; - - if (slot->keyDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - label = pk11_getString(object,CKA_LABEL); - - crv = pk11_Attribute2SecItem(NULL, &pubKey, object, CKA_ID); - /* Should this be ID? */ - if (crv != CKR_OK) goto loser; - - /* if we don't have an ID, generate one */ - if (pubKey.len == 0) { - if (pubKey.data) { - PORT_Free(pubKey.data); - pubKey.data = NULL; - } - crv = pk11_GenerateSecretCKA_ID(slot->keyDB, &pubKey, label); - if (crv != CKR_OK) goto loser; - - crv = pk11_forceAttribute(object, CKA_ID, pubKey.data, pubKey.len); - if (crv != CKR_OK) goto loser; - } - - privKey=pk11_mkSecretKeyRep(object); - if (privKey == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; - } - - PORT_Assert(slot->keyDB); - rv = nsslowkey_StoreKeyByPublicKey(slot->keyDB, - privKey, &pubKey, label, slot->password); - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - goto loser; - } - - object->handle = pk11_mkHandle(slot,&pubKey,PK11_TOKEN_TYPE_KEY); - } - -loser: - if (label) PORT_Free(label); - if (privKey) nsslowkey_DestroyPrivateKey(privKey); - if (pubKey.data) PORT_Free(pubKey.data); - - return crv; -} - -/* - * check the consistancy and initialize a Key Object - */ -static CK_RV -pk11_handleKeyObject(PK11Session *session, PK11Object *object) -{ - PK11Attribute *attribute; - CK_KEY_TYPE key_type; - CK_BBOOL cktrue = CK_TRUE; - CK_BBOOL ckfalse = CK_FALSE; - CK_RV crv; - - /* verify the required fields */ - if ( !pk11_hasAttribute(object,CKA_KEY_TYPE) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* now verify the common fields */ - crv = pk11_defaultAttribute(object,CKA_ID,NULL,0); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_START_DATE,NULL,0); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_END_DATE,NULL,0); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_DERIVE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_LOCAL,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - /* get the key type */ - attribute = pk11_FindAttribute(object,CKA_KEY_TYPE); - key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - - switch (object->objclass) { - case CKO_PUBLIC_KEY: - return pk11_handlePublicKeyObject(session,object,key_type); - case CKO_PRIVATE_KEY: - return pk11_handlePrivateKeyObject(session,object,key_type); - case CKO_SECRET_KEY: - /* make sure the required fields exist */ - return pk11_handleSecretKeyObject(session,object,key_type, - (PRBool)(session->slot->slotID == FIPS_SLOT_ID)); - default: - break; - } - return CKR_ATTRIBUTE_VALUE_INVALID; -} - -/* - * check the consistancy and Verify a DSA Parameter Object - */ -static CK_RV -pk11_handleDSAParameterObject(PK11Session *session, PK11Object *object) -{ - PK11Attribute *primeAttr = NULL; - PK11Attribute *subPrimeAttr = NULL; - PK11Attribute *baseAttr = NULL; - PK11Attribute *seedAttr = NULL; - PK11Attribute *hAttr = NULL; - PK11Attribute *attribute; - CK_RV crv = CKR_TEMPLATE_INCOMPLETE; - PQGParams params; - PQGVerify vfy, *verify = NULL; - SECStatus result,rv; - - primeAttr = pk11_FindAttribute(object,CKA_PRIME); - if (primeAttr == NULL) goto loser; - params.prime.data = primeAttr->attrib.pValue; - params.prime.len = primeAttr->attrib.ulValueLen; - - subPrimeAttr = pk11_FindAttribute(object,CKA_SUBPRIME); - if (subPrimeAttr == NULL) goto loser; - params.subPrime.data = subPrimeAttr->attrib.pValue; - params.subPrime.len = subPrimeAttr->attrib.ulValueLen; - - baseAttr = pk11_FindAttribute(object,CKA_BASE); - if (baseAttr == NULL) goto loser; - params.base.data = baseAttr->attrib.pValue; - params.base.len = baseAttr->attrib.ulValueLen; - - attribute = pk11_FindAttribute(object, CKA_NETSCAPE_PQG_COUNTER); - if (attribute != NULL) { - vfy.counter = *(CK_ULONG *) attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - - seedAttr = pk11_FindAttribute(object, CKA_NETSCAPE_PQG_SEED); - if (seedAttr == NULL) goto loser; - vfy.seed.data = seedAttr->attrib.pValue; - vfy.seed.len = seedAttr->attrib.ulValueLen; - - hAttr = pk11_FindAttribute(object, CKA_NETSCAPE_PQG_H); - if (hAttr == NULL) goto loser; - vfy.h.data = hAttr->attrib.pValue; - vfy.h.len = hAttr->attrib.ulValueLen; - - verify = &vfy; - } - - crv = CKR_FUNCTION_FAILED; - rv = PQG_VerifyParams(¶ms,verify,&result); - if (rv == SECSuccess) { - crv = (result== SECSuccess) ? CKR_OK : CKR_ATTRIBUTE_VALUE_INVALID; - } - -loser: - if (hAttr) pk11_FreeAttribute(hAttr); - if (seedAttr) pk11_FreeAttribute(seedAttr); - if (baseAttr) pk11_FreeAttribute(baseAttr); - if (subPrimeAttr) pk11_FreeAttribute(subPrimeAttr); - if (primeAttr) pk11_FreeAttribute(primeAttr); - - return crv; -} - -/* - * check the consistancy and initialize a Key Parameter Object - */ -static CK_RV -pk11_handleKeyParameterObject(PK11Session *session, PK11Object *object) -{ - PK11Attribute *attribute; - CK_KEY_TYPE key_type; - CK_BBOOL ckfalse = CK_FALSE; - CK_RV crv; - - /* verify the required fields */ - if ( !pk11_hasAttribute(object,CKA_KEY_TYPE) ) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* now verify the common fields */ - crv = pk11_defaultAttribute(object,CKA_LOCAL,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - /* get the key type */ - attribute = pk11_FindAttribute(object,CKA_KEY_TYPE); - key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - - switch (key_type) { - case CKK_DSA: - return pk11_handleDSAParameterObject(session,object); - - default: - break; - } - return CKR_KEY_TYPE_INCONSISTENT; -} - -/* - * Handle Object does all the object consistancy checks, automatic attribute - * generation, attribute defaulting, etc. If handleObject succeeds, the object - * will be assigned an object handle, and the object installed in the session - * or stored in the DB. - */ -CK_RV -pk11_handleObject(PK11Object *object, PK11Session *session) -{ - PK11Slot *slot = session->slot; - CK_BBOOL ckfalse = CK_FALSE; - CK_BBOOL cktrue = CK_TRUE; - PK11Attribute *attribute; - CK_RV crv; - - /* make sure all the base object types are defined. If not set the - * defaults */ - crv = pk11_defaultAttribute(object,CKA_TOKEN,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_PRIVATE,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_LABEL,NULL,0); - if (crv != CKR_OK) return crv; - crv = pk11_defaultAttribute(object,CKA_MODIFIABLE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - /* don't create a private object if we aren't logged in */ - if ((!slot->isLoggedIn) && (slot->needLogin) && - (pk11_isTrue(object,CKA_PRIVATE))) { - return CKR_USER_NOT_LOGGED_IN; - } - - - if (((session->info.flags & CKF_RW_SESSION) == 0) && - (pk11_isTrue(object,CKA_TOKEN))) { - return CKR_SESSION_READ_ONLY; - } - - /* PKCS #11 object ID's are unique for all objects on a - * token */ - PK11_USE_THREADS(PZ_Lock(slot->objectLock);) - object->handle = slot->tokenIDCount++; - PK11_USE_THREADS(PZ_Unlock(slot->objectLock);) - - /* get the object class */ - attribute = pk11_FindAttribute(object,CKA_CLASS); - if (attribute == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - object->objclass = *(CK_OBJECT_CLASS *)attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - - /* now handle the specific. Get a session handle for these functions - * to use */ - switch (object->objclass) { - case CKO_DATA: - crv = pk11_handleDataObject(session,object); - break; - case CKO_CERTIFICATE: - crv = pk11_handleCertObject(session,object); - break; - case CKO_NETSCAPE_TRUST: - crv = pk11_handleTrustObject(session,object); - break; - case CKO_NETSCAPE_CRL: - crv = pk11_handleCrlObject(session,object); - break; - case CKO_NETSCAPE_SMIME: - crv = pk11_handleSMimeObject(session,object); - break; - case CKO_PRIVATE_KEY: - case CKO_PUBLIC_KEY: - case CKO_SECRET_KEY: - crv = pk11_handleKeyObject(session,object); - break; - case CKO_KG_PARAMETERS: - crv = pk11_handleKeyParameterObject(session,object); - break; - default: - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - - /* can't fail from here on out unless the pk_handlXXX functions have - * failed the request */ - if (crv != CKR_OK) { - return crv; - } - - /* now link the object into the slot and session structures */ - if (pk11_isToken(object->handle)) { - pk11_convertSessionToToken(object); - } else { - object->slot = slot; - pk11_AddObject(session,object); - } - - return CKR_OK; -} - -/* - * ******************** Public Key Utilities *************************** - */ -/* Generate a low public key structure from an object */ -NSSLOWKEYPublicKey *pk11_GetPubKey(PK11Object *object,CK_KEY_TYPE key_type, - CK_RV *crvp) -{ - NSSLOWKEYPublicKey *pubKey; - PLArenaPool *arena; - CK_RV crv; - - if (object->objclass != CKO_PUBLIC_KEY) { - *crvp = CKR_KEY_TYPE_INCONSISTENT; - return NULL; - } - - if (pk11_isToken(object->handle)) { -/* ferret out the token object handle */ - } - - /* If we already have a key, use it */ - if (object->objectInfo) { - *crvp = CKR_OK; - return (NSSLOWKEYPublicKey *)object->objectInfo; - } - - /* allocate the structure */ - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - *crvp = CKR_HOST_MEMORY; - return NULL; - } - - pubKey = (NSSLOWKEYPublicKey *) - PORT_ArenaAlloc(arena,sizeof(NSSLOWKEYPublicKey)); - if (pubKey == NULL) { - PORT_FreeArena(arena,PR_FALSE); - *crvp = CKR_HOST_MEMORY; - return NULL; - } - - /* fill in the structure */ - pubKey->arena = arena; - switch (key_type) { - case CKK_RSA: - pubKey->keyType = NSSLOWKEYRSAKey; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.rsa.modulus, - object,CKA_MODULUS); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.rsa.publicExponent, - object,CKA_PUBLIC_EXPONENT); - break; - case CKK_DSA: - pubKey->keyType = NSSLOWKEYDSAKey; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.dsa.params.prime, - object,CKA_PRIME); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.dsa.params.subPrime, - object,CKA_SUBPRIME); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.dsa.params.base, - object,CKA_BASE); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.dsa.publicValue, - object,CKA_VALUE); - break; - case CKK_DH: - pubKey->keyType = NSSLOWKEYDHKey; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.dh.prime, - object,CKA_PRIME); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.dh.base, - object,CKA_BASE); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.dh.publicValue, - object,CKA_VALUE); - break; -#ifdef NSS_ENABLE_ECC - case CKK_EC: - pubKey->keyType = NSSLOWKEYECKey; - crv = pk11_Attribute2SSecItem(arena, - &pubKey->u.ec.ecParams.DEREncoding, - object,CKA_EC_PARAMS); - if (crv != CKR_OK) break; - - /* Fill out the rest of the ecParams structure - * based on the encoded params - */ - if (EC_FillParams(arena, &pubKey->u.ec.ecParams.DEREncoding, - &pubKey->u.ec.ecParams) != SECSuccess) break; - - crv = pk11_Attribute2SSecItem(arena,&pubKey->u.ec.publicValue, - object,CKA_EC_POINT); - break; -#endif /* NSS_ENABLE_ECC */ - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - *crvp = crv; - if (crv != CKR_OK) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; - } - - object->objectInfo = pubKey; - object->infoFree = (PK11Free) nsslowkey_DestroyPublicKey; - return pubKey; -} - -/* make a private key from a verified object */ -static NSSLOWKEYPrivateKey * -pk11_mkPrivKey(PK11Object *object, CK_KEY_TYPE key_type, CK_RV *crvp) -{ - NSSLOWKEYPrivateKey *privKey; - PLArenaPool *arena; - CK_RV crv = CKR_OK; - SECStatus rv; - - PORT_Assert(!pk11_isToken(object->handle)); - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - *crvp = CKR_HOST_MEMORY; - return NULL; - } - - privKey = (NSSLOWKEYPrivateKey *) - PORT_ArenaZAlloc(arena,sizeof(NSSLOWKEYPrivateKey)); - if (privKey == NULL) { - PORT_FreeArena(arena,PR_FALSE); - *crvp = CKR_HOST_MEMORY; - return NULL; - } - - /* in future this would be a switch on key_type */ - privKey->arena = arena; - switch (key_type) { - case CKK_RSA: - privKey->keyType = NSSLOWKEYRSAKey; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.modulus, - object,CKA_MODULUS); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.publicExponent,object, - CKA_PUBLIC_EXPONENT); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.privateExponent,object, - CKA_PRIVATE_EXPONENT); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.prime1,object, - CKA_PRIME_1); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.prime2,object, - CKA_PRIME_2); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.exponent1, - object, CKA_EXPONENT_1); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.exponent2, - object, CKA_EXPONENT_2); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(arena,&privKey->u.rsa.coefficient,object, - CKA_COEFFICIENT); - if (crv != CKR_OK) break; - rv = DER_SetUInteger(privKey->arena, &privKey->u.rsa.version, - NSSLOWKEY_VERSION); - if (rv != SECSuccess) crv = CKR_HOST_MEMORY; - break; - - case CKK_DSA: - privKey->keyType = NSSLOWKEYDSAKey; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dsa.params.prime, - object,CKA_PRIME); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dsa.params.subPrime, - object,CKA_SUBPRIME); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dsa.params.base, - object,CKA_BASE); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dsa.privateValue, - object,CKA_VALUE); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dsa.publicValue, - object,CKA_NETSCAPE_DB); - /* can't set the public value.... */ - break; - - case CKK_DH: - privKey->keyType = NSSLOWKEYDHKey; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dh.prime, - object,CKA_PRIME); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dh.base, - object,CKA_BASE); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dh.privateValue, - object,CKA_VALUE); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.dh.publicValue, - object,CKA_NETSCAPE_DB); - break; - -#ifdef NSS_ENABLE_ECC - case CKK_EC: - privKey->keyType = NSSLOWKEYECKey; - crv = pk11_Attribute2SSecItem(arena, - &privKey->u.ec.ecParams.DEREncoding, - object,CKA_EC_PARAMS); - if (crv != CKR_OK) break; - - /* Fill out the rest of the ecParams structure - * based on the encoded params - */ - if (EC_FillParams(arena, &privKey->u.ec.ecParams.DEREncoding, - &privKey->u.ec.ecParams) != SECSuccess) break; - crv = pk11_Attribute2SSecItem(arena,&privKey->u.ec.privateValue, - object,CKA_VALUE); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(arena, &privKey->u.ec.publicValue, - object,CKA_NETSCAPE_DB); - if (crv != CKR_OK) break; - rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version, - NSSLOWKEY_EC_PRIVATE_KEY_VERSION); - if (rv != SECSuccess) crv = CKR_HOST_MEMORY; - break; -#endif /* NSS_ENABLE_ECC */ - - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - *crvp = crv; - if (crv != CKR_OK) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; - } - return privKey; -} - - -/* Generate a low private key structure from an object */ -NSSLOWKEYPrivateKey * -pk11_GetPrivKey(PK11Object *object,CK_KEY_TYPE key_type, CK_RV *crvp) -{ - NSSLOWKEYPrivateKey *priv = NULL; - - if (object->objclass != CKO_PRIVATE_KEY) { - *crvp = CKR_KEY_TYPE_INCONSISTENT; - return NULL; - } - if (object->objectInfo) { - *crvp = CKR_OK; - return (NSSLOWKEYPrivateKey *)object->objectInfo; - } - - if (pk11_isToken(object->handle)) { - /* grab it from the data base */ - PK11TokenObject *to = pk11_narrowToTokenObject(object); - - PORT_Assert(to); - PORT_Assert(object->slot->keyDB); - priv = nsslowkey_FindKeyByPublicKey(object->slot->keyDB, &to->dbKey, - object->slot->password); - *crvp = priv ? CKR_OK : CKR_DEVICE_ERROR; - } else { - priv = pk11_mkPrivKey(object, key_type, crvp); - } - object->objectInfo = priv; - object->infoFree = (PK11Free) nsslowkey_DestroyPrivateKey; - return priv; -} - -/* - **************************** Symetric Key utils ************************ - */ -/* - * set the DES key with parity bits correctly - */ -void -pk11_FormatDESKey(unsigned char *key, int length) -{ - int i; - - /* format the des key */ - for (i=0; i < length; i++) { - key[i] = parityTable[key[i]>>1]; - } -} - -/* - * check a des key (des2 or des3 subkey) for weak keys. - */ -PRBool -pk11_CheckDESKey(unsigned char *key) -{ - int i; - - /* format the des key with parity */ - pk11_FormatDESKey(key, 8); - - for (i=0; i < pk11_desWeakTableSize; i++) { - if (PORT_Memcmp(key,pk11_desWeakTable[i],8) == 0) { - return PR_TRUE; - } - } - return PR_FALSE; -} - -/* - * check if a des or triple des key is weak. - */ -PRBool -pk11_IsWeakKey(unsigned char *key,CK_KEY_TYPE key_type) -{ - - switch(key_type) { - case CKK_DES: - return pk11_CheckDESKey(key); - case CKM_DES2_KEY_GEN: - if (pk11_CheckDESKey(key)) return PR_TRUE; - return pk11_CheckDESKey(&key[8]); - case CKM_DES3_KEY_GEN: - if (pk11_CheckDESKey(key)) return PR_TRUE; - if (pk11_CheckDESKey(&key[8])) return PR_TRUE; - return pk11_CheckDESKey(&key[16]); - default: - break; - } - return PR_FALSE; -} - - -/* make a fake private key representing a symmetric key */ -static NSSLOWKEYPrivateKey * -pk11_mkSecretKeyRep(PK11Object *object) -{ - NSSLOWKEYPrivateKey *privKey = 0; - PLArenaPool *arena = 0; - CK_KEY_TYPE keyType; - SECItem keyTypeItem; - CK_RV crv; - SECStatus rv; - static unsigned char derZero[1] = { 0 }; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { crv = CKR_HOST_MEMORY; goto loser; } - - privKey = (NSSLOWKEYPrivateKey *) - PORT_ArenaZAlloc(arena,sizeof(NSSLOWKEYPrivateKey)); - if (privKey == NULL) { crv = CKR_HOST_MEMORY; goto loser; } - - privKey->arena = arena; - - /* Secret keys are represented in the database as "fake" RSA keys. The RSA key - * is marked as a secret key representation by setting the public exponent field - * to 0, which is an invalid RSA exponent. The other fields are set as follows: - * modulus - CKA_ID value for the secret key - * private exponent - CKA_VALUE (the key itself) - * coefficient - CKA_KEY_TYPE, which indicates what encryption algorithm - * is used for the key. - * all others - set to integer 0 - */ - privKey->keyType = NSSLOWKEYRSAKey; - - /* The modulus is set to the key id of the symmetric key */ - crv=pk11_Attribute2SecItem(arena,&privKey->u.rsa.modulus,object,CKA_ID); - if (crv != CKR_OK) goto loser; - - /* The public exponent is set to 0 length to indicate a special key */ - privKey->u.rsa.publicExponent.len = sizeof derZero; - privKey->u.rsa.publicExponent.data = derZero; - - /* The private exponent is the actual key value */ - crv=pk11_Attribute2SecItem(arena,&privKey->u.rsa.privateExponent,object,CKA_VALUE); - if (crv != CKR_OK) goto loser; - - /* All other fields empty - needs testing */ - privKey->u.rsa.prime1.len = sizeof derZero; - privKey->u.rsa.prime1.data = derZero; - - privKey->u.rsa.prime2.len = sizeof derZero; - privKey->u.rsa.prime2.data = derZero; - - privKey->u.rsa.exponent1.len = sizeof derZero; - privKey->u.rsa.exponent1.data = derZero; - - privKey->u.rsa.exponent2.len = sizeof derZero; - privKey->u.rsa.exponent2.data = derZero; - - /* Coeficient set to KEY_TYPE */ - crv = pk11_GetULongAttribute(object, CKA_KEY_TYPE, &keyType); - if (crv != CKR_OK) goto loser; - keyType = PR_htonl(keyType); - keyTypeItem.data = (unsigned char *)&keyType; - keyTypeItem.len = sizeof (keyType); - rv = SECITEM_CopyItem(arena, &privKey->u.rsa.coefficient, &keyTypeItem); - if (rv != SECSuccess) { - crv = CKR_HOST_MEMORY; - goto loser; - } - - /* Private key version field set normally for compatibility */ - rv = DER_SetUInteger(privKey->arena, - &privKey->u.rsa.version, NSSLOWKEY_VERSION); - if (rv != SECSuccess) { crv = CKR_HOST_MEMORY; goto loser; } - -loser: - if (crv != CKR_OK) { - PORT_FreeArena(arena,PR_FALSE); - privKey = 0; - } - - return privKey; -} - -static PRBool -isSecretKey(NSSLOWKEYPrivateKey *privKey) -{ - if (privKey->keyType == NSSLOWKEYRSAKey && - privKey->u.rsa.publicExponent.len == 1 && - privKey->u.rsa.publicExponent.data[0] == 0) - return PR_TRUE; - - return PR_FALSE; -} - -/********************************************************************** - * - * Start of PKCS 11 functions - * - **********************************************************************/ - - -/* return the function list */ -CK_RV NSC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) -{ - *pFunctionList = (CK_FUNCTION_LIST_PTR) &pk11_funcList; - return CKR_OK; -} - -/* return the function list */ -CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) -{ - return NSC_GetFunctionList(pFunctionList); -} - -static PLHashNumber -pk11_HashNumber(const void *key) -{ - return (PLHashNumber) key; -} - -/* - * eventually I'd like to expunge all occurances of XXX_SLOT_ID and - * just go with the info in the slot. This is one place, however, - * where it might be a little difficult. - */ -const char * -pk11_getDefTokName(CK_SLOT_ID slotID) -{ - static char buf[33]; - - switch (slotID) { - case NETSCAPE_SLOT_ID: - return "NSS Generic Crypto Services "; - case PRIVATE_KEY_SLOT_ID: - return "NSS Certificate DB "; - case FIPS_SLOT_ID: - return "NSS FIPS-140-1 Certificate DB "; - default: - break; - } - sprintf(buf,"NSS Application Token %08x ",(unsigned int) slotID); - return buf; -} - -const char * -pk11_getDefSlotName(CK_SLOT_ID slotID) -{ - static char buf[65]; - - switch (slotID) { - case NETSCAPE_SLOT_ID: - return - "NSS Internal Cryptographic Services "; - case PRIVATE_KEY_SLOT_ID: - return - "NSS User Private Key and Certificate Services "; - case FIPS_SLOT_ID: - return - "Netscape FIPS-140-1 User Private Key Services "; - default: - break; - } - sprintf(buf, - "NSS Application Slot %08x ", - (unsigned int) slotID); - return buf; -} - -static CK_ULONG nscSlotCount[2] = {0 , 0}; -static CK_SLOT_ID_PTR nscSlotList[2] = {NULL, NULL}; -static CK_ULONG nscSlotListSize[2] = {0, 0}; -static PLHashTable *nscSlotHashTable[2] = {NULL, NULL}; - -static int -pk11_GetModuleIndex(CK_SLOT_ID slotID) -{ - if ((slotID == FIPS_SLOT_ID) || (slotID > 100)) { - return NSC_FIPS_MODULE; - } - return NSC_NON_FIPS_MODULE; -} - -/* look up a slot structure from the ID (used to be a macro when we only - * had two slots) */ -PK11Slot * -pk11_SlotFromID(CK_SLOT_ID slotID) -{ - int index = pk11_GetModuleIndex(slotID); - return (PK11Slot *)PL_HashTableLookupConst(nscSlotHashTable[index], - (void *)slotID); -} - -PK11Slot * -pk11_SlotFromSessionHandle(CK_SESSION_HANDLE handle) -{ - CK_ULONG slotIDIndex = (handle >> 24) & 0x7f; - CK_ULONG moduleIndex = (handle >> 31) & 1; - - if (slotIDIndex >= nscSlotCount[moduleIndex]) { - return NULL; - } - - return pk11_SlotFromID(nscSlotList[moduleIndex][slotIDIndex]); -} - -PK11Slot * pk11_NewSlotFromID(CK_SLOT_ID slotID, int moduleIndex) -{ - PK11Slot *slot = NULL; - PLHashEntry *entry; - int index; - - index = pk11_GetModuleIndex(slotID); - - /* make sure the slotID for this module is valid */ - if (moduleIndex != index) { - return NULL; - } - - if (nscSlotList[index] == NULL) { - nscSlotListSize[index] = NSC_SLOT_LIST_BLOCK_SIZE; - nscSlotList[index] = (CK_SLOT_ID *) - PORT_ZAlloc(nscSlotListSize[index]*sizeof(CK_SLOT_ID)); - if (nscSlotList[index] == NULL) { - return NULL; - } - } - if (nscSlotCount[index] >= nscSlotListSize[index]) { - CK_SLOT_ID* oldNscSlotList = nscSlotList[index]; - CK_ULONG oldNscSlotListSize = nscSlotListSize[index]; - nscSlotListSize[index] += NSC_SLOT_LIST_BLOCK_SIZE; - nscSlotList[index] = (CK_SLOT_ID *) PORT_Realloc(oldNscSlotList, - nscSlotListSize[index]*sizeof(CK_SLOT_ID)); - if (nscSlotList[index] == NULL) { - nscSlotList[index] = oldNscSlotList; - nscSlotListSize[index] = oldNscSlotListSize; - return NULL; - } - } - - if (nscSlotHashTable[index] == NULL) { - nscSlotHashTable[index] = PL_NewHashTable(64,pk11_HashNumber, - PL_CompareValues, PL_CompareValues, NULL, 0); - if (nscSlotHashTable[index] == NULL) { - return NULL; - } - } - - slot = (PK11Slot *) PORT_ZAlloc(sizeof(PK11Slot)); - if (slot == NULL) { - return NULL; - } - - entry = PL_HashTableAdd(nscSlotHashTable[index],(void *)slotID,slot); - if (entry == NULL) { - PORT_Free(slot); - return NULL; - } - slot->index = (nscSlotCount[index] & 0x7f) | ((index << 7) & 0x80); - nscSlotList[index][nscSlotCount[index]++] = slotID; - - return slot; -} - -static SECStatus -pk11_set_user(NSSLOWCERTCertificate *cert, SECItem *dummy, void *arg) -{ - PK11Slot *slot = (PK11Slot *)arg; - NSSLOWCERTCertTrust trust = *cert->trust; - - if (nsslowkey_KeyForCertExists(slot->keyDB,cert)) { - trust.sslFlags |= CERTDB_USER; - trust.emailFlags |= CERTDB_USER; - trust.objectSigningFlags |= CERTDB_USER; - } else { - trust.sslFlags &= ~CERTDB_USER; - trust.emailFlags &= ~CERTDB_USER; - trust.objectSigningFlags &= ~CERTDB_USER; - } - - if (PORT_Memcmp(&trust,cert->trust, sizeof (trust)) != 0) { - nsslowcert_ChangeCertTrust(slot->certDB,cert, &trust); - } - - /* should check for email address and make sure we have an s/mime profile */ - return SECSuccess; -} - -static void -pk11_DBVerify(PK11Slot *slot) -{ - /* walk through all the certs and check to see if there are any - * user certs, and make sure there are s/mime profiles for all certs with - * email addresses */ - nsslowcert_TraversePermCerts(slot->certDB,pk11_set_user,slot); - - return; -} - -/* - * initialize one of the slot structures. figure out which by the ID - */ -CK_RV -PK11_SlotInit(char *configdir,pk11_token_parameters *params, int moduleIndex) -{ - unsigned int i; - CK_SLOT_ID slotID = params->slotID; - PK11Slot *slot = pk11_NewSlotFromID(slotID, moduleIndex); - PRBool needLogin = !params->noKeyDB; - CK_RV crv; - - if (slot == NULL) { - return CKR_HOST_MEMORY; - } - - slot->optimizeSpace = params->optimizeSpace; - if (slot->optimizeSpace) { - slot->tokObjHashSize = SPACE_TOKEN_OBJECT_HASH_SIZE; - slot->sessHashSize = SPACE_SESSION_HASH_SIZE; - slot->numSessionLocks = 1; - } else { - slot->tokObjHashSize = TIME_TOKEN_OBJECT_HASH_SIZE; - slot->sessHashSize = TIME_SESSION_HASH_SIZE; - slot->numSessionLocks = slot->sessHashSize/BUCKETS_PER_SESSION_LOCK; - } - slot->sessionLockMask = slot->numSessionLocks-1; - -#ifdef PKCS11_USE_THREADS - slot->slotLock = PZ_NewLock(nssILockSession); - if (slot->slotLock == NULL) { - return CKR_HOST_MEMORY; - } - slot->sessionLock = (PZLock **) - PORT_ZAlloc(slot->numSessionLocks * sizeof(PZLock *)); - if (slot->sessionLock == NULL) { - return CKR_HOST_MEMORY; - } - for (i=0; i < slot->numSessionLocks; i++) { - slot->sessionLock[i] = PZ_NewLock(nssILockSession); - if (slot->sessionLock[i] == NULL) return CKR_HOST_MEMORY; - } - slot->objectLock = PZ_NewLock(nssILockObject); - if (slot->objectLock == NULL) return CKR_HOST_MEMORY; -#else - slot->slotLock = NULL; - slot->sessionLock = (PZLock **) - PORT_ZAlloc(slot->numSessionLocks * sizeof(PZLock *)); - if (slot->sessionLock == NULL) { - return CKR_HOST_MEMORY; - } - for (i=0; i < slot->numSessionLocks; i++) { - slot->sessionLock[i] = NULL; - } - slot->objectLock = NULL; -#endif - slot->head = (PK11Session **) - PORT_ZAlloc(slot->sessHashSize*sizeof(PK11Session *)); - if (slot->head == NULL) { - return CKR_HOST_MEMORY; - } - slot->tokObjects = (PK11Object **) - PORT_ZAlloc(slot->tokObjHashSize*sizeof(PK11Object *)); - if (slot->tokObjects == NULL) { - return CKR_HOST_MEMORY; - } - slot->tokenHashTable = PL_NewHashTable(64,pk11_HashNumber,PL_CompareValues, - SECITEM_HashCompare, NULL, 0); - if (slot->tokenHashTable == NULL) { - return CKR_HOST_MEMORY; - } - slot->password = NULL; - slot->hasTokens = PR_FALSE; - slot->sessionIDCount = 0; - slot->sessionIDConflict = 0; - slot->sessionCount = 0; - slot->rwSessionCount = 0; - slot->tokenIDCount = 1; - slot->needLogin = PR_FALSE; - slot->isLoggedIn = PR_FALSE; - slot->ssoLoggedIn = PR_FALSE; - slot->DB_loaded = PR_FALSE; - slot->slotID = slotID; - slot->certDB = NULL; - slot->keyDB = NULL; - slot->minimumPinLen = 0; - slot->readOnly = params->readOnly; - pk11_setStringName(params->tokdes ? params->tokdes : - pk11_getDefTokName(slotID), slot->tokDescription, - sizeof(slot->tokDescription)); - pk11_setStringName(params->slotdes ? params->slotdes : - pk11_getDefSlotName(slotID), slot->slotDescription, - sizeof(slot->slotDescription)); - - if ((!params->noCertDB) || (!params->noKeyDB)) { - crv = pk11_DBInit(params->configdir ? params->configdir : configdir, - params->certPrefix, params->keyPrefix, params->readOnly, - params->noCertDB, params->noKeyDB, params->forceOpen, - &slot->certDB, &slot->keyDB); - if (crv != CKR_OK) { - /* shoutdown slot? */ - return crv; - } - - if (nsslowcert_needDBVerify(slot->certDB)) { - pk11_DBVerify(slot); - } - } - if (needLogin) { - /* if the data base is initialized with a null password,remember that */ - slot->needLogin = - (PRBool)!pk11_hasNullPassword(slot->keyDB,&slot->password); - if (params->minPW <= PK11_MAX_PIN) { - slot->minimumPinLen = params->minPW; - } - if ((slot->minimumPinLen == 0) && (params->pwRequired) && - (slot->minimumPinLen <= PK11_MAX_PIN)) { - slot->minimumPinLen = 1; - } - } - return CKR_OK; -} - -static PRIntn -pk11_freeHashItem(PLHashEntry* entry, PRIntn index, void *arg) -{ - SECItem *item = (SECItem *)entry->value; - - SECITEM_FreeItem(item, PR_TRUE); - return HT_ENUMERATE_NEXT; -} - -/* - * initialize one of the slot structures. figure out which by the ID - */ -static CK_RV -pk11_DestroySlotData(PK11Slot *slot) -{ - unsigned int i; - -#ifdef PKCS11_USE_THREADS - if (slot->slotLock) { - PZ_DestroyLock(slot->slotLock); - slot->slotLock = NULL; - } - if (slot->sessionLock) { - for (i=0; i < slot->numSessionLocks; i++) { - if (slot->sessionLock[i]) { - PZ_DestroyLock(slot->sessionLock[i]); - slot->sessionLock[i] = NULL; - } - } - } - if (slot->objectLock) { - PZ_DestroyLock(slot->objectLock); - slot->objectLock = NULL; - } -#endif - if (slot->sessionLock) { - PORT_Free(slot->sessionLock); - slot->sessionLock = NULL; - } - - if (slot->tokenHashTable) { - PL_HashTableEnumerateEntries(slot->tokenHashTable, - pk11_freeHashItem,NULL); - PL_HashTableDestroy(slot->tokenHashTable); - slot->tokenHashTable = NULL; - } - - if (slot->tokObjects) { - for(i=0; i < slot->tokObjHashSize; i++) { - PK11Object *object = slot->tokObjects[i]; - slot->tokObjects[i] = NULL; - if (object) pk11_FreeObject(object); - } - PORT_Free(slot->tokObjects); - slot->tokObjects = NULL; - } - slot->tokObjHashSize = 0; - if (slot->head) { - for(i=0; i < slot->sessHashSize; i++) { - PK11Session *session = slot->head[i]; - slot->head[i] = NULL; - if (session) pk11_FreeSession(session); - } - PORT_Free(slot->head); - slot->head = NULL; - } - slot->sessHashSize = 0; - pk11_DBShutdown(slot->certDB,slot->keyDB); - - PORT_Free(slot); - return CKR_OK; -} - -/* - * handle the SECMOD.db - */ -char ** -NSC_ModuleDBFunc(unsigned long function,char *parameters, void *args) -{ - char *secmod = NULL; - char *appName = NULL; - char *filename = NULL; - PRBool rw; - static char *success="Success"; - char **rvstr = NULL; - - secmod = secmod_getSecmodName(parameters,&appName,&filename, &rw); - - switch (function) { - case SECMOD_MODULE_DB_FUNCTION_FIND: - rvstr = secmod_ReadPermDB(appName,filename,secmod,(char *)parameters,rw); - break; - case SECMOD_MODULE_DB_FUNCTION_ADD: - rvstr = (secmod_AddPermDB(appName,filename,secmod,(char *)args,rw) - == SECSuccess) ? &success: NULL; - break; - case SECMOD_MODULE_DB_FUNCTION_DEL: - rvstr = (secmod_DeletePermDB(appName,filename,secmod,(char *)args,rw) - == SECSuccess) ? &success: NULL; - break; - case SECMOD_MODULE_DB_FUNCTION_RELEASE: - rvstr = (secmod_ReleasePermDBData(appName,filename,secmod, - (char **)args,rw) == SECSuccess) ? &success: NULL; - break; - } - if (secmod) PR_smprintf_free(secmod); - if (appName) PORT_Free(appName); - if (filename) PORT_Free(filename); - return rvstr; -} - -static void nscFreeAllSlots(int moduleIndex) -{ - /* free all the slots */ - PK11Slot *slot = NULL; - CK_SLOT_ID slotID; - int i; - - if (nscSlotList[moduleIndex]) { - CK_ULONG tmpSlotCount = nscSlotCount[moduleIndex]; - CK_SLOT_ID_PTR tmpSlotList = nscSlotList[moduleIndex]; - PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex]; - - /* first close all the session */ - for (i=0; i < (int) tmpSlotCount; i++) { - slotID = tmpSlotList[i]; - (void) NSC_CloseAllSessions(slotID); - } - - /* now clear out the statics */ - nscSlotList[moduleIndex] = NULL; - nscSlotCount[moduleIndex] = 0; - nscSlotHashTable[moduleIndex] = NULL; - nscSlotListSize[moduleIndex] = 0; - - for (i=0; i < (int) tmpSlotCount; i++) { - slotID = tmpSlotList[i]; - slot = (PK11Slot *) - PL_HashTableLookup(tmpSlotHashTable, (void *)slotID); - PORT_Assert(slot); - if (!slot) continue; - pk11_DestroySlotData(slot); - PL_HashTableRemove(tmpSlotHashTable, (void *)slotID); - } - PORT_Free(tmpSlotList); - PL_HashTableDestroy(tmpSlotHashTable); - } -} - -static void -pk11_closePeer(PRBool isFIPS) -{ - CK_SLOT_ID slotID = isFIPS ? PRIVATE_KEY_SLOT_ID: FIPS_SLOT_ID; - PK11Slot *slot; - int moduleIndex = isFIPS? NSC_NON_FIPS_MODULE : NSC_FIPS_MODULE; - PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex]; - - slot = (PK11Slot *) PL_HashTableLookup(tmpSlotHashTable, (void *)slotID); - if (slot == NULL) { - return; - } - pk11_DBShutdown(slot->certDB,slot->keyDB); - slot->certDB = NULL; - slot->keyDB = NULL; - return; -} - -static PRBool nsc_init = PR_FALSE; -extern SECStatus secoid_Init(void); - -/* NSC_Initialize initializes the Cryptoki library. */ -CK_RV nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS) -{ - CK_RV crv = CKR_OK; - SECStatus rv; - CK_C_INITIALIZE_ARGS *init_args = (CK_C_INITIALIZE_ARGS *) pReserved; - int i; - int moduleIndex = isFIPS? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE; - - - if (isFIPS) { - /* make sure that our check file signatures are OK */ - if (!BLAPI_VerifySelf(NULL) || - !BLAPI_SHVerify(SOFTOKEN_LIB_NAME, (PRFuncPtr) pk11_closePeer)) { - crv = CKR_DEVICE_ERROR; /* better error code? checksum error? */ - return crv; - } - } - - rv = secoid_Init(); - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - return crv; - } - - rv = RNG_RNGInit(); /* initialize random number generator */ - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - return crv; - } - RNG_SystemInfoForRNG(); - - - /* NOTE: - * we should be getting out mutexes from this list, not statically binding - * them from NSPR. This should happen before we allow the internal to split - * off from the rest on NSS. - */ - - /* initialize the key and cert db's */ - nsslowkey_SetDefaultKeyDBAlg - (SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC); - crv = CKR_ARGUMENTS_BAD; - if ((init_args && init_args->LibraryParameters)) { - pk11_parameters paramStrings; - - crv = secmod_parseParameters - ((char *)init_args->LibraryParameters, ¶mStrings, isFIPS); - if (crv != CKR_OK) { - return crv; - } - crv = pk11_configure(paramStrings.man, paramStrings.libdes); - if (crv != CKR_OK) { - goto loser; - } - - /* if we have a peer already open, have him close his DB's so we - * don't clobber each other. */ - if ((isFIPS && nsc_init) || (!isFIPS && nsf_init)) { - pk11_closePeer(isFIPS); - } - - for (i=0; i < paramStrings.token_count; i++) { - crv = - PK11_SlotInit(paramStrings.configdir, ¶mStrings.tokens[i], - moduleIndex); - if (crv != CKR_OK) { - nscFreeAllSlots(moduleIndex); - break; - } - } -loser: - secmod_freeParams(¶mStrings); - } - - return crv; -} - -CK_RV NSC_Initialize(CK_VOID_PTR pReserved) -{ - CK_RV crv; - if (nsc_init) { - return CKR_CRYPTOKI_ALREADY_INITIALIZED; - } - crv = nsc_CommonInitialize(pReserved,PR_FALSE); - nsc_init = (PRBool) (crv == CKR_OK); - return crv; -} - -extern SECStatus SECOID_Shutdown(void); - -/* NSC_Finalize indicates that an application is done with the - * Cryptoki library.*/ -CK_RV nsc_CommonFinalize (CK_VOID_PTR pReserved, PRBool isFIPS) -{ - - - nscFreeAllSlots(isFIPS ? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE); - - /* don't muck with the globals is our peer is still initialized */ - if (isFIPS && nsc_init) { - return CKR_OK; - } - if (!isFIPS && nsf_init) { - return CKR_OK; - } - - nsslowcert_DestroyGlobalLocks(); - -#ifdef LEAK_TEST - /* - * do we really want to throw away all our hard earned entropy here!!? - * No we don't! Not calling RNG_RNGShutdown only 'leaks' data on the - * initial call to RNG_Init(). So the only reason to call this is to clean - * up leak detection warnings on shutdown. In many cases we *don't* want - * to free up the global RNG context because the application has Finalized - * simply to swap profiles. We don't want to loose the entropy we've - * already collected. - */ - RNG_RNGShutdown(); -#endif - - pk11_CleanupFreeLists(); - /* tell freeBL to clean up after itself */ - BL_Cleanup(); - /* clean up the default OID table */ - SECOID_Shutdown(); - nsc_init = PR_FALSE; - - return CKR_OK; -} - -/* NSC_Finalize indicates that an application is done with the - * Cryptoki library.*/ -CK_RV NSC_Finalize (CK_VOID_PTR pReserved) -{ - CK_RV crv; - - if (!nsc_init) { - return CKR_OK; - } - - crv = nsc_CommonFinalize (pReserved, PR_FALSE); - - nsc_init = (PRBool) !(crv == CKR_OK); - - return crv; -} - -extern const char __nss_softokn_rcsid[]; -extern const char __nss_softokn_sccsid[]; - -/* NSC_GetInfo returns general information about Cryptoki. */ -CK_RV NSC_GetInfo(CK_INFO_PTR pInfo) -{ - volatile char c; /* force a reference that won't get optimized away */ - - c = __nss_softokn_rcsid[0] + __nss_softokn_sccsid[0]; - pInfo->cryptokiVersion.major = 2; - pInfo->cryptokiVersion.minor = 11; - PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32); - pInfo->libraryVersion.major = 3; - pInfo->libraryVersion.minor = 8; - PORT_Memcpy(pInfo->libraryDescription,libraryDescription,32); - pInfo->flags = 0; - return CKR_OK; -} - - -/* NSC_GetSlotList obtains a list of slots in the system. */ -CK_RV nsc_CommonGetSlotList(CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount, int moduleIndex) -{ - *pulCount = nscSlotCount[moduleIndex]; - if (pSlotList != NULL) { - PORT_Memcpy(pSlotList,nscSlotList[moduleIndex], - nscSlotCount[moduleIndex]*sizeof(CK_SLOT_ID)); - } - return CKR_OK; -} - -/* NSC_GetSlotList obtains a list of slots in the system. */ -CK_RV NSC_GetSlotList(CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) -{ - return nsc_CommonGetSlotList(tokenPresent, pSlotList, pulCount, - NSC_NON_FIPS_MODULE); -} - -/* NSC_GetSlotInfo obtains information about a particular slot in the system. */ -CK_RV NSC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) -{ - PK11Slot *slot = pk11_SlotFromID(slotID); - if (slot == NULL) return CKR_SLOT_ID_INVALID; - - pInfo->firmwareVersion.major = 0; - pInfo->firmwareVersion.minor = 0; - - PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32); - PORT_Memcpy(pInfo->slotDescription,slot->slotDescription,64); - pInfo->flags = CKF_TOKEN_PRESENT; - /* ok we really should read it out of the keydb file. */ - /* pInfo->hardwareVersion.major = NSSLOWKEY_DB_FILE_VERSION; */ - pInfo->hardwareVersion.major = 3; - pInfo->hardwareVersion.minor = 8; - return CKR_OK; -} - -#define CKF_THREAD_SAFE 0x8000 /* for now */ -/* - * check the current state of the 'needLogin' flag in case the database has - * been changed underneath us. - */ -static PRBool -pk11_checkNeedLogin(PK11Slot *slot) -{ - if (slot->password) { - if (nsslowkey_CheckKeyDBPassword(slot->keyDB,slot->password) - == SECSuccess) { - return slot->needLogin; - } else { - SECITEM_FreeItem(slot->password, PR_TRUE); - slot->password = NULL; - slot->isLoggedIn = PR_FALSE; - } - } - slot->needLogin = - (PRBool)!pk11_hasNullPassword(slot->keyDB,&slot->password); - return (slot->needLogin); -} - -/* NSC_GetTokenInfo obtains information about a particular token in - * the system. */ -CK_RV NSC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo) -{ - PK11Slot *slot = pk11_SlotFromID(slotID); - NSSLOWKEYDBHandle *handle; - - if (slot == NULL) return CKR_SLOT_ID_INVALID; - - PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32); - PORT_Memcpy(pInfo->model,"NSS 3 ",16); - PORT_Memcpy(pInfo->serialNumber,"0000000000000000",16); - pInfo->ulMaxSessionCount = 0; /* arbitrarily large */ - pInfo->ulSessionCount = slot->sessionCount; - pInfo->ulMaxRwSessionCount = 0; /* arbitarily large */ - pInfo->ulRwSessionCount = slot->rwSessionCount; - pInfo->firmwareVersion.major = 0; - pInfo->firmwareVersion.minor = 0; - PORT_Memcpy(pInfo->label,slot->tokDescription,32); - handle = slot->keyDB; - if (handle == NULL) { - pInfo->flags= CKF_RNG | CKF_WRITE_PROTECTED | CKF_THREAD_SAFE; - pInfo->ulMaxPinLen = 0; - pInfo->ulMinPinLen = 0; - pInfo->ulTotalPublicMemory = 0; - pInfo->ulFreePublicMemory = 0; - pInfo->ulTotalPrivateMemory = 0; - pInfo->ulFreePrivateMemory = 0; - pInfo->hardwareVersion.major = 4; - pInfo->hardwareVersion.minor = 0; - } else { - /* - * we have three possible states which we may be in: - * (1) No DB password has been initialized. This also means we - * have no keys in the key db. - * (2) Password initialized to NULL. This means we have keys, but - * the user has chosen not use a password. - * (3) Finally we have an initialized password whicn is not NULL, and - * we will need to prompt for it. - */ - if (nsslowkey_HasKeyDBPassword(handle) == SECFailure) { - pInfo->flags = CKF_THREAD_SAFE | CKF_LOGIN_REQUIRED; - } else if (!pk11_checkNeedLogin(slot)) { - pInfo->flags = CKF_THREAD_SAFE | CKF_USER_PIN_INITIALIZED; - } else { - pInfo->flags = CKF_THREAD_SAFE | - CKF_LOGIN_REQUIRED | CKF_USER_PIN_INITIALIZED; - } - pInfo->ulMaxPinLen = PK11_MAX_PIN; - pInfo->ulMinPinLen = 0; - if (slot->minimumPinLen > 0) { - pInfo->ulMinPinLen = (CK_ULONG)slot->minimumPinLen; - } - pInfo->ulTotalPublicMemory = 1; - pInfo->ulFreePublicMemory = 1; - pInfo->ulTotalPrivateMemory = 1; - pInfo->ulFreePrivateMemory = 1; - pInfo->hardwareVersion.major = CERT_DB_FILE_VERSION; - pInfo->hardwareVersion.minor = handle->version; - } - return CKR_OK; -} - -/* NSC_GetMechanismList obtains a list of mechanism types - * supported by a token. */ -CK_RV NSC_GetMechanismList(CK_SLOT_ID slotID, - CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) -{ - CK_ULONG i; - - switch (slotID) { - case NETSCAPE_SLOT_ID: - *pulCount = mechanismCount; - if (pMechanismList != NULL) { - for (i=0; i < mechanismCount; i++) { - pMechanismList[i] = mechanisms[i].type; - } - } - break; - default: - *pulCount = 0; - for (i=0; i < mechanismCount; i++) { - if (mechanisms[i].privkey) { - (*pulCount)++; - if (pMechanismList != NULL) { - *pMechanismList++ = mechanisms[i].type; - } - } - } - break; - } - return CKR_OK; -} - - -/* NSC_GetMechanismInfo obtains information about a particular mechanism - * possibly supported by a token. */ -CK_RV NSC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, - CK_MECHANISM_INFO_PTR pInfo) -{ - PRBool isPrivateKey; - CK_ULONG i; - - switch (slotID) { - case NETSCAPE_SLOT_ID: - isPrivateKey = PR_FALSE; - break; - default: - isPrivateKey = PR_TRUE; - break; - } - for (i=0; i < mechanismCount; i++) { - if (type == mechanisms[i].type) { - if (isPrivateKey && !mechanisms[i].privkey) { - return CKR_MECHANISM_INVALID; - } - PORT_Memcpy(pInfo,&mechanisms[i].info, sizeof(CK_MECHANISM_INFO)); - return CKR_OK; - } - } - return CKR_MECHANISM_INVALID; -} - -CK_RV pk11_MechAllowsOperation(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE op) -{ - CK_ULONG i; - CK_FLAGS flags; - - switch (op) { - case CKA_ENCRYPT: flags = CKF_ENCRYPT; break; - case CKA_DECRYPT: flags = CKF_DECRYPT; break; - case CKA_WRAP: flags = CKF_WRAP; break; - case CKA_UNWRAP: flags = CKF_UNWRAP; break; - case CKA_SIGN: flags = CKF_SIGN; break; - case CKA_SIGN_RECOVER: flags = CKF_SIGN_RECOVER; break; - case CKA_VERIFY: flags = CKF_VERIFY; break; - case CKA_VERIFY_RECOVER: flags = CKF_VERIFY_RECOVER; break; - case CKA_DERIVE: flags = CKF_DERIVE; break; - default: - return CKR_ARGUMENTS_BAD; - } - for (i=0; i < mechanismCount; i++) { - if (type == mechanisms[i].type) { - return (flags & mechanisms[i].info.flags) ? CKR_OK - : CKR_MECHANISM_INVALID; - } - } - return CKR_MECHANISM_INVALID; -} - - -static SECStatus -pk11_TurnOffUser(NSSLOWCERTCertificate *cert, SECItem *k, void *arg) -{ - NSSLOWCERTCertTrust trust; - SECStatus rv; - - rv = nsslowcert_GetCertTrust(cert,&trust); - if (rv == SECSuccess && ((trust.emailFlags & CERTDB_USER) || - (trust.sslFlags & CERTDB_USER) || - (trust.objectSigningFlags & CERTDB_USER))) { - trust.emailFlags &= ~CERTDB_USER; - trust.sslFlags &= ~CERTDB_USER; - trust.objectSigningFlags &= ~CERTDB_USER; - nsslowcert_ChangeCertTrust(cert->dbhandle,cert,&trust); - } - return SECSuccess; -} - -/* NSC_InitToken initializes a token. */ -CK_RV NSC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin, - CK_ULONG ulPinLen,CK_CHAR_PTR pLabel) { - PK11Slot *slot = pk11_SlotFromID(slotID); - NSSLOWKEYDBHandle *handle; - NSSLOWCERTCertDBHandle *certHandle; - SECStatus rv; - unsigned int i; - PK11Object *object; - - if (slot == NULL) return CKR_SLOT_ID_INVALID; - - /* don't initialize the database if we aren't talking to a token - * that uses the key database. - */ - if (slotID == NETSCAPE_SLOT_ID) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - /* first, delete all our loaded key and cert objects from our - * internal list. */ - PK11_USE_THREADS(PZ_Lock(slot->objectLock);) - for (i=0; i < slot->tokObjHashSize; i++) { - do { - object = slot->tokObjects[i]; - /* hand deque */ - /* this duplicates function of NSC_close session functions, but - * because we know that we are freeing all the sessions, we can - * do more efficient processing */ - if (object) { - slot->tokObjects[i] = object->next; - - if (object->next) object->next->prev = NULL; - object->next = object->prev = NULL; - } - if (object) pk11_FreeObject(object); - } while (object != NULL); - } - slot->DB_loaded = PR_FALSE; - PK11_USE_THREADS(PZ_Unlock(slot->objectLock);) - - /* then clear out the key database */ - handle = slot->keyDB; - if (handle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - /* what to do on an error here? */ - rv = nsslowkey_ResetKeyDB(handle); - - /* finally mark all the user certs as non-user certs */ - certHandle = slot->certDB; - if (certHandle == NULL) return CKR_OK; - - nsslowcert_TraversePermCerts(certHandle,pk11_TurnOffUser, NULL); - - return CKR_OK; /*is this the right function for not implemented*/ -} - - -/* NSC_InitPIN initializes the normal user's PIN. */ -CK_RV NSC_InitPIN(CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pPin, CK_ULONG ulPinLen) -{ - PK11Session *sp; - PK11Slot *slot; - NSSLOWKEYDBHandle *handle; - SECItem *newPin; - char newPinStr[PK11_MAX_PIN+1]; - SECStatus rv; - - - sp = pk11_SessionFromHandle(hSession); - if (sp == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } - - slot = pk11_SlotFromSession(sp); - if (slot == NULL) { - pk11_FreeSession(sp); - return CKR_SESSION_HANDLE_INVALID;; - } - - handle = slot->keyDB; - if (handle == NULL) { - pk11_FreeSession(sp); - return CKR_PIN_LEN_RANGE; - } - - - if (sp->info.state != CKS_RW_SO_FUNCTIONS) { - pk11_FreeSession(sp); - return CKR_USER_NOT_LOGGED_IN; - } - - pk11_FreeSession(sp); - - /* make sure the pins aren't too long */ - if (ulPinLen > PK11_MAX_PIN) { - return CKR_PIN_LEN_RANGE; - } - if (ulPinLen < (CK_ULONG)slot->minimumPinLen) { - return CKR_PIN_LEN_RANGE; - } - - if (nsslowkey_HasKeyDBPassword(handle) != SECFailure) { - return CKR_DEVICE_ERROR; - } - - /* convert to null terminated string */ - PORT_Memcpy(newPinStr,pPin,ulPinLen); - newPinStr[ulPinLen] = 0; - - /* build the hashed pins which we pass around */ - newPin = nsslowkey_HashPassword(newPinStr,handle->global_salt); - PORT_Memset(newPinStr,0,sizeof(newPinStr)); - - /* change the data base */ - rv = nsslowkey_SetKeyDBPassword(handle,newPin); - - /* Now update our local copy of the pin */ - if (rv == SECSuccess) { - if (slot->password) { - SECITEM_ZfreeItem(slot->password, PR_TRUE); - } - slot->password = newPin; - if (ulPinLen == 0) slot->needLogin = PR_FALSE; - return CKR_OK; - } - SECITEM_ZfreeItem(newPin, PR_TRUE); - return CKR_PIN_INCORRECT; -} - - -/* NSC_SetPIN modifies the PIN of user that is currently logged in. */ -/* NOTE: This is only valid for the PRIVATE_KEY_SLOT */ -CK_RV NSC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, - CK_ULONG ulOldLen, CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen) -{ - PK11Session *sp; - PK11Slot *slot; - NSSLOWKEYDBHandle *handle; - SECItem *newPin; - SECItem *oldPin; - char newPinStr[PK11_MAX_PIN+1],oldPinStr[PK11_MAX_PIN+1]; - SECStatus rv; - - - sp = pk11_SessionFromHandle(hSession); - if (sp == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } - - slot = pk11_SlotFromSession(sp); - if (!slot) { - pk11_FreeSession(sp); - return CKR_SESSION_HANDLE_INVALID;; - } - - handle = slot->keyDB; - if (handle == NULL) { - pk11_FreeSession(sp); - return CKR_PIN_LEN_RANGE; - } - - if (slot->needLogin && sp->info.state != CKS_RW_USER_FUNCTIONS) { - pk11_FreeSession(sp); - return CKR_USER_NOT_LOGGED_IN; - } - - pk11_FreeSession(sp); - - /* make sure the pins aren't too long */ - if ((ulNewLen > PK11_MAX_PIN) || (ulOldLen > PK11_MAX_PIN)) { - return CKR_PIN_LEN_RANGE; - } - if (ulNewLen < (CK_ULONG)slot->minimumPinLen) { - return CKR_PIN_LEN_RANGE; - } - - - /* convert to null terminated string */ - PORT_Memcpy(newPinStr,pNewPin,ulNewLen); - newPinStr[ulNewLen] = 0; - PORT_Memcpy(oldPinStr,pOldPin,ulOldLen); - oldPinStr[ulOldLen] = 0; - - /* build the hashed pins which we pass around */ - newPin = nsslowkey_HashPassword(newPinStr,handle->global_salt); - oldPin = nsslowkey_HashPassword(oldPinStr,handle->global_salt); - PORT_Memset(newPinStr,0,sizeof(newPinStr)); - PORT_Memset(oldPinStr,0,sizeof(oldPinStr)); - - /* change the data base */ - rv = nsslowkey_ChangeKeyDBPassword(handle,oldPin,newPin); - - /* Now update our local copy of the pin */ - SECITEM_ZfreeItem(oldPin, PR_TRUE); - if (rv == SECSuccess) { - if (slot->password) { - SECITEM_ZfreeItem(slot->password, PR_TRUE); - } - slot->password = newPin; - slot->needLogin = (PRBool)(ulNewLen != 0); - return CKR_OK; - } - SECITEM_ZfreeItem(newPin, PR_TRUE); - return CKR_PIN_INCORRECT; -} - -/* NSC_OpenSession opens a session between an application and a token. */ -CK_RV NSC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, - CK_VOID_PTR pApplication,CK_NOTIFY Notify,CK_SESSION_HANDLE_PTR phSession) -{ - PK11Slot *slot; - CK_SESSION_HANDLE sessionID; - PK11Session *session; - PK11Session *sameID; - - slot = pk11_SlotFromID(slotID); - if (slot == NULL) return CKR_SLOT_ID_INVALID; - - /* new session (we only have serial sessions) */ - session = pk11_NewSession(slotID, Notify, pApplication, - flags | CKF_SERIAL_SESSION); - if (session == NULL) return CKR_HOST_MEMORY; - - if (slot->readOnly && (flags & CKF_RW_SESSION)) { - /* NETSCAPE_SLOT_ID is Read ONLY */ - session->info.flags &= ~CKF_RW_SESSION; - } - PK11_USE_THREADS(PZ_Lock(slot->slotLock);) - ++slot->sessionCount; - PK11_USE_THREADS(PZ_Unlock(slot->slotLock);) - if (session->info.flags & CKF_RW_SESSION) { - PR_AtomicIncrement(&slot->rwSessionCount); - } - - do { - do { - sessionID = (PR_AtomicIncrement(&slot->sessionIDCount) & 0xffffff) - | (slot->index << 24); - } while (sessionID == CK_INVALID_HANDLE); - PK11_USE_THREADS(PZ_Lock(PK11_SESSION_LOCK(slot,sessionID));) - pk11queue_find(sameID, sessionID, slot->head, slot->sessHashSize); - if (sameID == NULL) { - session->handle = sessionID; - pk11_update_state(slot, session); - pk11queue_add(session, sessionID, slot->head,slot->sessHashSize); - } else { - slot->sessionIDConflict++; /* for debugging */ - } - PK11_USE_THREADS(PZ_Unlock(PK11_SESSION_LOCK(slot,sessionID));) - } while (sameID != NULL); - - *phSession = sessionID; - return CKR_OK; -} - - -/* NSC_CloseSession closes a session between an application and a token. */ -CK_RV NSC_CloseSession(CK_SESSION_HANDLE hSession) -{ - PK11Slot *slot; - PK11Session *session; - SECItem *pw = NULL; - PRBool sessionFound; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - slot = pk11_SlotFromSession(session); - sessionFound = PR_FALSE; - - /* lock */ - PK11_USE_THREADS(PZ_Lock(PK11_SESSION_LOCK(slot,hSession));) - if (pk11queue_is_queued(session,hSession,slot->head,slot->sessHashSize)) { - sessionFound = PR_TRUE; - pk11queue_delete(session,hSession,slot->head,slot->sessHashSize); - session->refCount--; /* can't go to zero while we hold the reference */ - PORT_Assert(session->refCount > 0); - } - PK11_USE_THREADS(PZ_Unlock(PK11_SESSION_LOCK(slot,hSession));) - - if (sessionFound) { - PK11_USE_THREADS(PZ_Lock(slot->slotLock);) - if (--slot->sessionCount == 0) { - pw = slot->password; - slot->isLoggedIn = PR_FALSE; - slot->password = NULL; - } - PK11_USE_THREADS(PZ_Unlock(slot->slotLock);) - if (session->info.flags & CKF_RW_SESSION) { - PR_AtomicDecrement(&slot->rwSessionCount); - } - } - - pk11_FreeSession(session); - if (pw) SECITEM_ZfreeItem(pw, PR_TRUE); - return CKR_OK; -} - - -/* NSC_CloseAllSessions closes all sessions with a token. */ -CK_RV NSC_CloseAllSessions (CK_SLOT_ID slotID) -{ - PK11Slot *slot; - SECItem *pw = NULL; - PK11Session *session; - unsigned int i; - - slot = pk11_SlotFromID(slotID); - if (slot == NULL) return CKR_SLOT_ID_INVALID; - - /* first log out the card */ - PK11_USE_THREADS(PZ_Lock(slot->slotLock);) - pw = slot->password; - slot->isLoggedIn = PR_FALSE; - slot->password = NULL; - PK11_USE_THREADS(PZ_Unlock(slot->slotLock);) - if (pw) SECITEM_ZfreeItem(pw, PR_TRUE); - - /* now close all the current sessions */ - /* NOTE: If you try to open new sessions before NSC_CloseAllSessions - * completes, some of those new sessions may or may not be closed by - * NSC_CloseAllSessions... but any session running when this code starts - * will guarrenteed be close, and no session will be partially closed */ - for (i=0; i < slot->sessHashSize; i++) { - do { - PK11_USE_THREADS(PZ_Lock(PK11_SESSION_LOCK(slot,i));) - session = slot->head[i]; - /* hand deque */ - /* this duplicates function of NSC_close session functions, but - * because we know that we are freeing all the sessions, we can - * do more efficient processing */ - if (session) { - slot->head[i] = session->next; - if (session->next) session->next->prev = NULL; - session->next = session->prev = NULL; - PK11_USE_THREADS(PZ_Unlock(PK11_SESSION_LOCK(slot,i));) - PK11_USE_THREADS(PZ_Lock(slot->slotLock);) - --slot->sessionCount; - PK11_USE_THREADS(PZ_Unlock(slot->slotLock);) - if (session->info.flags & CKF_RW_SESSION) { - PR_AtomicDecrement(&slot->rwSessionCount); - } - } else { - PK11_USE_THREADS(PZ_Unlock(PK11_SESSION_LOCK(slot,i));) - } - if (session) pk11_FreeSession(session); - } while (session != NULL); - } - return CKR_OK; -} - - -/* NSC_GetSessionInfo obtains information about the session. */ -CK_RV NSC_GetSessionInfo(CK_SESSION_HANDLE hSession, - CK_SESSION_INFO_PTR pInfo) -{ - PK11Session *session; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - - PORT_Memcpy(pInfo,&session->info,sizeof(CK_SESSION_INFO)); - pk11_FreeSession(session); - return CKR_OK; -} - -/* NSC_Login logs a user into a token. */ -CK_RV NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, - CK_CHAR_PTR pPin, CK_ULONG ulPinLen) -{ - PK11Slot *slot; - PK11Session *session; - NSSLOWKEYDBHandle *handle; - CK_FLAGS sessionFlags; - SECItem *pin; - char pinStr[PK11_MAX_PIN+1]; - - - /* get the slot */ - slot = pk11_SlotFromSessionHandle(hSession); - - /* make sure the session is valid */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - sessionFlags = session->info.flags; - pk11_FreeSession(session); - session = NULL; - - /* can't log into the Netscape Slot */ - if (slot->slotID == NETSCAPE_SLOT_ID) - return CKR_USER_TYPE_INVALID; - - if (slot->isLoggedIn) return CKR_USER_ALREADY_LOGGED_IN; - slot->ssoLoggedIn = PR_FALSE; - - if (ulPinLen > PK11_MAX_PIN) return CKR_PIN_LEN_RANGE; - - /* convert to null terminated string */ - PORT_Memcpy(pinStr,pPin,ulPinLen); - pinStr[ulPinLen] = 0; - - handle = slot->keyDB; - if (handle == NULL) { - return CKR_USER_TYPE_INVALID; - } - - /* - * Deal with bootstrap. We allow the SSO to login in with a NULL - * password if and only if we haven't initialized the KEY DB yet. - * We only allow this on a RW session. - */ - if (nsslowkey_HasKeyDBPassword(handle) == SECFailure) { - /* allow SSO's to log in only if there is not password on the - * key database */ - if (((userType == CKU_SO) && (sessionFlags & CKF_RW_SESSION)) - /* fips always needs to authenticate, even if there isn't a db */ - || (slot->slotID == FIPS_SLOT_ID)) { - /* should this be a fixed password? */ - if (ulPinLen == 0) { - SECItem *pw; - PK11_USE_THREADS(PZ_Lock(slot->slotLock);) - pw = slot->password; - slot->password = NULL; - slot->isLoggedIn = PR_TRUE; - slot->ssoLoggedIn = (PRBool)(userType == CKU_SO); - PK11_USE_THREADS(PZ_Unlock(slot->slotLock);) - pk11_update_all_states(slot); - SECITEM_ZfreeItem(pw,PR_TRUE); - return CKR_OK; - } - return CKR_PIN_INCORRECT; - } - return CKR_USER_TYPE_INVALID; - } - - /* don't allow the SSO to log in if the user is already initialized */ - if (userType != CKU_USER) { return CKR_USER_TYPE_INVALID; } - - - /* build the hashed pins which we pass around */ - pin = nsslowkey_HashPassword(pinStr,handle->global_salt); - if (pin == NULL) return CKR_HOST_MEMORY; - - if (nsslowkey_CheckKeyDBPassword(handle,pin) == SECSuccess) { - SECItem *tmp; - PK11_USE_THREADS(PZ_Lock(slot->slotLock);) - tmp = slot->password; - slot->isLoggedIn = PR_TRUE; - slot->password = pin; - PK11_USE_THREADS(PZ_Unlock(slot->slotLock);) - if (tmp) SECITEM_ZfreeItem(tmp, PR_TRUE); - - /* update all sessions */ - pk11_update_all_states(slot); - return CKR_OK; - } - - SECITEM_ZfreeItem(pin, PR_TRUE); - return CKR_PIN_INCORRECT; -} - -/* NSC_Logout logs a user out from a token. */ -CK_RV NSC_Logout(CK_SESSION_HANDLE hSession) -{ - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - PK11Session *session; - SECItem *pw = NULL; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - pk11_FreeSession(session); - session = NULL; - - if (!slot->isLoggedIn) return CKR_USER_NOT_LOGGED_IN; - - PK11_USE_THREADS(PZ_Lock(slot->slotLock);) - pw = slot->password; - slot->isLoggedIn = PR_FALSE; - slot->ssoLoggedIn = PR_FALSE; - slot->password = NULL; - PK11_USE_THREADS(PZ_Unlock(slot->slotLock);) - if (pw) SECITEM_ZfreeItem(pw, PR_TRUE); - - pk11_update_all_states(slot); - return CKR_OK; -} - - -/* NSC_CreateObject creates a new object. */ -CK_RV NSC_CreateObject(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject) -{ - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - PK11Session *session; - PK11Object *object; - CK_RV crv; - int i; - - - /* - * now lets create an object to hang the attributes off of - */ - object = pk11_NewObject(slot); /* fill in the handle later */ - if (object == NULL) { - return CKR_HOST_MEMORY; - } - - /* - * load the template values into the object - */ - for (i=0; i < (int) ulCount; i++) { - crv = pk11_AddAttributeType(object,pk11_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) { - pk11_FreeObject(object); - return crv; - } - } - - /* get the session */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - pk11_FreeObject(object); - return CKR_SESSION_HANDLE_INVALID; - } - - /* - * handle the base object stuff - */ - crv = pk11_handleObject(object,session); - *phObject = object->handle; - pk11_FreeSession(session); - pk11_FreeObject(object); - - return crv; -} - - -/* NSC_CopyObject copies an object, creating a new object for the copy. */ -CK_RV NSC_CopyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phNewObject) -{ - PK11Object *destObject,*srcObject; - PK11Session *session; - CK_RV crv = CKR_OK; - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - int i; - - /* Get srcObject so we can find the class */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } - srcObject = pk11_ObjectFromHandle(hObject,session); - if (srcObject == NULL) { - pk11_FreeSession(session); - return CKR_OBJECT_HANDLE_INVALID; - } - /* - * create an object to hang the attributes off of - */ - destObject = pk11_NewObject(slot); /* fill in the handle later */ - if (destObject == NULL) { - pk11_FreeSession(session); - pk11_FreeObject(srcObject); - return CKR_HOST_MEMORY; - } - - /* - * load the template values into the object - */ - for (i=0; i < (int) ulCount; i++) { - if (pk11_modifyType(pTemplate[i].type,srcObject->objclass) == PK11_NEVER) { - crv = CKR_ATTRIBUTE_READ_ONLY; - break; - } - crv = pk11_AddAttributeType(destObject,pk11_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) { break; } - } - if (crv != CKR_OK) { - pk11_FreeSession(session); - pk11_FreeObject(srcObject); - pk11_FreeObject(destObject); - return crv; - } - - /* sensitive can only be changed to CK_TRUE */ - if (pk11_hasAttribute(destObject,CKA_SENSITIVE)) { - if (!pk11_isTrue(destObject,CKA_SENSITIVE)) { - pk11_FreeSession(session); - pk11_FreeObject(srcObject); - pk11_FreeObject(destObject); - return CKR_ATTRIBUTE_READ_ONLY; - } - } - - /* - * now copy the old attributes from the new attributes - */ - /* don't create a token object if we aren't in a rw session */ - /* we need to hold the lock to copy a consistant version of - * the object. */ - crv = pk11_CopyObject(destObject,srcObject); - - destObject->objclass = srcObject->objclass; - pk11_FreeObject(srcObject); - if (crv != CKR_OK) { - pk11_FreeObject(destObject); - pk11_FreeSession(session); - } - - crv = pk11_handleObject(destObject,session); - *phNewObject = destObject->handle; - pk11_FreeSession(session); - pk11_FreeObject(destObject); - - return crv; -} - - -/* NSC_GetObjectSize gets the size of an object in bytes. */ -CK_RV NSC_GetObjectSize(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) { - *pulSize = 0; - return CKR_OK; -} - - -/* NSC_GetAttributeValue obtains the value of one or more object attributes. */ -CK_RV NSC_GetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) { - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - PK11Session *session; - PK11Object *object; - PK11Attribute *attribute; - PRBool sensitive; - CK_RV crv; - int i; - - /* - * make sure we're allowed - */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } - - object = pk11_ObjectFromHandle(hObject,session); - pk11_FreeSession(session); - if (object == NULL) { - return CKR_OBJECT_HANDLE_INVALID; - } - - /* don't read a private object if we aren't logged in */ - if ((!slot->isLoggedIn) && (slot->needLogin) && - (pk11_isTrue(object,CKA_PRIVATE))) { - pk11_FreeObject(object); - return CKR_USER_NOT_LOGGED_IN; - } - - crv = CKR_OK; - sensitive = pk11_isTrue(object,CKA_SENSITIVE); - for (i=0; i < (int) ulCount; i++) { - /* Make sure that this attribute is retrievable */ - if (sensitive && pk11_isSensitive(pTemplate[i].type,object->objclass)) { - crv = CKR_ATTRIBUTE_SENSITIVE; - pTemplate[i].ulValueLen = -1; - continue; - } - attribute = pk11_FindAttribute(object,pTemplate[i].type); - if (attribute == NULL) { - crv = CKR_ATTRIBUTE_TYPE_INVALID; - pTemplate[i].ulValueLen = -1; - continue; - } - if (pTemplate[i].pValue != NULL) { - PORT_Memcpy(pTemplate[i].pValue,attribute->attrib.pValue, - attribute->attrib.ulValueLen); - } - pTemplate[i].ulValueLen = attribute->attrib.ulValueLen; - pk11_FreeAttribute(attribute); - } - - pk11_FreeObject(object); - return crv; -} - -/* NSC_SetAttributeValue modifies the value of one or more object attributes */ -CK_RV NSC_SetAttributeValue (CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) { - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - PK11Session *session; - PK11Attribute *attribute; - PK11Object *object; - PRBool isToken; - CK_RV crv = CKR_OK; - CK_BBOOL legal; - int i; - - /* - * make sure we're allowed - */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } - - object = pk11_ObjectFromHandle(hObject,session); - if (object == NULL) { - pk11_FreeSession(session); - return CKR_OBJECT_HANDLE_INVALID; - } - - /* don't modify a private object if we aren't logged in */ - if ((!slot->isLoggedIn) && (slot->needLogin) && - (pk11_isTrue(object,CKA_PRIVATE))) { - pk11_FreeSession(session); - pk11_FreeObject(object); - return CKR_USER_NOT_LOGGED_IN; - } - - /* don't modify a token object if we aren't in a rw session */ - isToken = pk11_isTrue(object,CKA_TOKEN); - if (((session->info.flags & CKF_RW_SESSION) == 0) && isToken) { - pk11_FreeSession(session); - pk11_FreeObject(object); - return CKR_SESSION_READ_ONLY; - } - pk11_FreeSession(session); - - /* only change modifiable objects */ - if (!pk11_isTrue(object,CKA_MODIFIABLE)) { - pk11_FreeObject(object); - return CKR_ATTRIBUTE_READ_ONLY; - } - - for (i=0; i < (int) ulCount; i++) { - /* Make sure that this attribute is changeable */ - switch (pk11_modifyType(pTemplate[i].type,object->objclass)) { - case PK11_NEVER: - case PK11_ONCOPY: - default: - crv = CKR_ATTRIBUTE_READ_ONLY; - break; - - case PK11_SENSITIVE: - legal = (pTemplate[i].type == CKA_EXTRACTABLE) ? CK_FALSE : CK_TRUE; - if ((*(CK_BBOOL *)pTemplate[i].pValue) != legal) { - crv = CKR_ATTRIBUTE_READ_ONLY; - } - break; - case PK11_ALWAYS: - break; - } - if (crv != CKR_OK) break; - - /* find the old attribute */ - attribute = pk11_FindAttribute(object,pTemplate[i].type); - if (attribute == NULL) { - crv =CKR_ATTRIBUTE_TYPE_INVALID; - break; - } - pk11_FreeAttribute(attribute); - crv = pk11_forceAttribute(object,pk11_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; - - } - - pk11_FreeObject(object); - return crv; -} - -/* - * find any certs that may match the template and load them. - */ -#define NSC_CERT 0x00000001 -#define NSC_TRUST 0x00000002 -#define NSC_CRL 0x00000004 -#define NSC_SMIME 0x00000008 -#define NSC_PRIVATE 0x00000010 -#define NSC_PUBLIC 0x00000020 -#define NSC_KEY 0x00000040 - -/* - * structure to collect key handles. - */ -typedef struct pk11CrlDataStr { - PK11Slot *slot; - PK11SearchResults *searchHandles; - CK_ATTRIBUTE *template; - CK_ULONG templ_count; -} pk11CrlData; - - -static SECStatus -pk11_crl_collect(SECItem *data, SECItem *key, certDBEntryType type, void *arg) -{ - pk11CrlData *crlData; - CK_OBJECT_HANDLE class_handle; - PK11Slot *slot; - - crlData = (pk11CrlData *)arg; - slot = crlData->slot; - - class_handle = (type == certDBEntryTypeRevocation) ? PK11_TOKEN_TYPE_CRL : - PK11_TOKEN_KRL_HANDLE; - if (pk11_tokenMatch(slot, key, class_handle, - crlData->template, crlData->templ_count)) { - pk11_addHandle(crlData->searchHandles, - pk11_mkHandle(slot,key,class_handle)); - } - return(SECSuccess); -} - -static void -pk11_searchCrls(PK11Slot *slot, SECItem *derSubject, PRBool isKrl, - unsigned long classFlags, PK11SearchResults *search, - CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) -{ - NSSLOWCERTCertDBHandle *certHandle = NULL; - - certHandle = slot->certDB; - if (certHandle == NULL) { - return; - } - if (derSubject->data != NULL) { - certDBEntryRevocation *crl = - nsslowcert_FindCrlByKey(certHandle, derSubject, isKrl); - - if (crl != NULL) { - pk11_addHandle(search, pk11_mkHandle(slot, derSubject, - isKrl ? PK11_TOKEN_KRL_HANDLE : PK11_TOKEN_TYPE_CRL)); - nsslowcert_DestroyDBEntry((certDBEntry *)crl); - } - } else { - pk11CrlData crlData; - - /* traverse */ - crlData.slot = slot; - crlData.searchHandles = search; - crlData.template = pTemplate; - crlData.templ_count = ulCount; - nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeRevocation, - pk11_crl_collect, (void *)&crlData); - nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeKeyRevocation, - pk11_crl_collect, (void *)&crlData); - } -} - -/* - * structure to collect key handles. - */ -typedef struct pk11KeyDataStr { - PK11Slot *slot; - PK11SearchResults *searchHandles; - SECItem *id; - CK_ATTRIBUTE *template; - CK_ULONG templ_count; - unsigned long classFlags; - PRBool isLoggedIn; - PRBool strict; -} pk11KeyData; - - -static SECStatus -pk11_key_collect(DBT *key, DBT *data, void *arg) -{ - pk11KeyData *keyData; - NSSLOWKEYPrivateKey *privKey = NULL; - SECItem tmpDBKey; - PK11Slot *slot; - - keyData = (pk11KeyData *)arg; - slot = keyData->slot; - - tmpDBKey.data = key->data; - tmpDBKey.len = key->size; - tmpDBKey.type = siBuffer; - - PORT_Assert(slot->keyDB); - if (!keyData->strict && keyData->id) { - SECItem result; - PRBool haveMatch= PR_FALSE; - unsigned char hashKey[SHA1_LENGTH]; - result.data = hashKey; - result.len = sizeof(hashKey); - - if (keyData->id->len == 0) { - /* Make sure this isn't a NSC_KEY */ - privKey = nsslowkey_FindKeyByPublicKey(keyData->slot->keyDB, - &tmpDBKey, keyData->slot->password); - if (privKey) { - haveMatch = isSecretKey(privKey) ? - (PRBool)(keyData->classFlags & NSC_KEY) != 0: - (PRBool)(keyData->classFlags & - (NSC_PRIVATE|NSC_PUBLIC)) != 0; - nsslowkey_DestroyPrivateKey(privKey); - } - } else { - SHA1_HashBuf( hashKey, key->data, key->size ); /* match id */ - haveMatch = SECITEM_ItemsAreEqual(keyData->id,&result); - if (!haveMatch && ((unsigned char *)key->data)[0] == 0) { - /* This is a fix for backwards compatibility. The key - * database indexes private keys by the public key, and - * versions of NSS prior to 3.4 stored the public key as - * a signed integer. The public key is now treated as an - * unsigned integer, with no leading zero. In order to - * correctly compute the hash of an old key, it is necessary - * to fallback and detect the leading zero. - */ - SHA1_HashBuf(hashKey, - (unsigned char *)key->data + 1, key->size - 1); - haveMatch = SECITEM_ItemsAreEqual(keyData->id,&result); - } - } - if (haveMatch) { - if (keyData->classFlags & NSC_PRIVATE) { - pk11_addHandle(keyData->searchHandles, - pk11_mkHandle(slot,&tmpDBKey,PK11_TOKEN_TYPE_PRIV)); - } - if (keyData->classFlags & NSC_PUBLIC) { - pk11_addHandle(keyData->searchHandles, - pk11_mkHandle(slot,&tmpDBKey,PK11_TOKEN_TYPE_PUB)); - } - if (keyData->classFlags & NSC_KEY) { - pk11_addHandle(keyData->searchHandles, - pk11_mkHandle(slot,&tmpDBKey,PK11_TOKEN_TYPE_KEY)); - } - } - return SECSuccess; - } - - privKey = nsslowkey_FindKeyByPublicKey(keyData->slot->keyDB, &tmpDBKey, - keyData->slot->password); - if ( privKey == NULL ) { - goto loser; - } - - if (isSecretKey(privKey)) { - if ((keyData->classFlags & NSC_KEY) && - pk11_tokenMatch(keyData->slot, &tmpDBKey, PK11_TOKEN_TYPE_KEY, - keyData->template, keyData->templ_count)) { - pk11_addHandle(keyData->searchHandles, - pk11_mkHandle(keyData->slot, &tmpDBKey, PK11_TOKEN_TYPE_KEY)); - } - } else { - if ((keyData->classFlags & NSC_PRIVATE) && - pk11_tokenMatch(keyData->slot, &tmpDBKey, PK11_TOKEN_TYPE_PRIV, - keyData->template, keyData->templ_count)) { - pk11_addHandle(keyData->searchHandles, - pk11_mkHandle(keyData->slot,&tmpDBKey,PK11_TOKEN_TYPE_PRIV)); - } - if ((keyData->classFlags & NSC_PUBLIC) && - pk11_tokenMatch(keyData->slot, &tmpDBKey, PK11_TOKEN_TYPE_PUB, - keyData->template, keyData->templ_count)) { - pk11_addHandle(keyData->searchHandles, - pk11_mkHandle(keyData->slot, &tmpDBKey,PK11_TOKEN_TYPE_PUB)); - } - } - -loser: - if ( privKey ) { - nsslowkey_DestroyPrivateKey(privKey); - } - return(SECSuccess); -} - -static void -pk11_searchKeys(PK11Slot *slot, SECItem *key_id, PRBool isLoggedIn, - unsigned long classFlags, PK11SearchResults *search, PRBool mustStrict, - CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) -{ - NSSLOWKEYDBHandle *keyHandle = NULL; - NSSLOWKEYPrivateKey *privKey; - pk11KeyData keyData; - PRBool found = PR_FALSE; - - keyHandle = slot->keyDB; - if (keyHandle == NULL) { - return; - } - - if (key_id->data) { - privKey = nsslowkey_FindKeyByPublicKey(keyHandle, key_id, slot->password); - if (privKey) { - if ((classFlags & NSC_KEY) && isSecretKey(privKey)) { - pk11_addHandle(search, - pk11_mkHandle(slot,key_id,PK11_TOKEN_TYPE_KEY)); - found = PR_TRUE; - } - if ((classFlags & NSC_PRIVATE) && !isSecretKey(privKey)) { - pk11_addHandle(search, - pk11_mkHandle(slot,key_id,PK11_TOKEN_TYPE_PRIV)); - found = PR_TRUE; - } - if ((classFlags & NSC_PUBLIC) && !isSecretKey(privKey)) { - pk11_addHandle(search, - pk11_mkHandle(slot,key_id,PK11_TOKEN_TYPE_PUB)); - found = PR_TRUE; - } - nsslowkey_DestroyPrivateKey(privKey); - } - /* don't do the traversal if we have an up to date db */ - if (keyHandle->version != 3) { - return; - } - /* don't do the traversal if it can't possibly be the correct id */ - /* all soft token id's are SHA1_HASH_LEN's */ - if (key_id->len != SHA1_LENGTH) { - return; - } - if (found) { - /* if we already found some keys, don't do the traversal */ - return; - } - } - keyData.slot = slot; - keyData.searchHandles = search; - keyData.id = key_id; - keyData.template = pTemplate; - keyData.templ_count = ulCount; - keyData.isLoggedIn = isLoggedIn; - keyData.classFlags = classFlags; - keyData.strict = mustStrict ? mustStrict : NSC_STRICT; - - nsslowkey_TraverseKeys(keyHandle, pk11_key_collect, &keyData); -} - -/* - * structure to collect certs into - */ -typedef struct pk11CertDataStr { - PK11Slot *slot; - int cert_count; - int max_cert_count; - NSSLOWCERTCertificate **certs; - CK_ATTRIBUTE *template; - CK_ULONG templ_count; - unsigned long classFlags; - PRBool strict; -} pk11CertData; - -/* - * collect all the certs from the traverse call. - */ -static SECStatus -pk11_cert_collect(NSSLOWCERTCertificate *cert,void *arg) -{ - pk11CertData *cd = (pk11CertData *)arg; - - if (cert == NULL) { - return SECSuccess; - } - - if (cd->certs == NULL) { - return SECFailure; - } - - if (cd->strict) { - if ((cd->classFlags & NSC_CERT) && !pk11_tokenMatch(cd->slot, - &cert->certKey, PK11_TOKEN_TYPE_CERT, cd->template,cd->templ_count)) { - return SECSuccess; - } - if ((cd->classFlags & NSC_TRUST) && !pk11_tokenMatch(cd->slot, - &cert->certKey, PK11_TOKEN_TYPE_TRUST, - cd->template, cd->templ_count)) { - return SECSuccess; - } - } - - /* allocate more space if we need it. This should only happen in - * the general traversal case */ - if (cd->cert_count >= cd->max_cert_count) { - int size; - cd->max_cert_count += NSC_CERT_BLOCK_SIZE; - size = cd->max_cert_count * sizeof (NSSLOWCERTCertificate *); - cd->certs = (NSSLOWCERTCertificate **)PORT_Realloc(cd->certs,size); - if (cd->certs == NULL) { - return SECFailure; - } - } - - cd->certs[cd->cert_count++] = nsslowcert_DupCertificate(cert); - return SECSuccess; -} - -/* provide impedence matching ... */ -static SECStatus -pk11_cert_collect2(NSSLOWCERTCertificate *cert, SECItem *dymmy, void *arg) -{ - return pk11_cert_collect(cert, arg); -} - -static void -pk11_searchSingleCert(pk11CertData *certData,NSSLOWCERTCertificate *cert) -{ - if (cert == NULL) { - return; - } - if (certData->strict && - !pk11_tokenMatch(certData->slot, &cert->certKey, PK11_TOKEN_TYPE_CERT, - certData->template,certData->templ_count)) { - nsslowcert_DestroyCertificate(cert); - return; - } - certData->certs = (NSSLOWCERTCertificate **) - PORT_Alloc(sizeof (NSSLOWCERTCertificate *)); - if (certData->certs == NULL) { - nsslowcert_DestroyCertificate(cert); - return; - } - certData->certs[0] = cert; - certData->cert_count = 1; -} - -static void -pk11_CertSetupData(pk11CertData *certData,int count) -{ - certData->max_cert_count = count; - - if (certData->max_cert_count <= 0) { - return; - } - certData->certs = (NSSLOWCERTCertificate **) - PORT_Alloc( count * sizeof(NSSLOWCERTCertificate *)); - return; -} - -static void -pk11_searchCertsAndTrust(PK11Slot *slot, SECItem *derCert, SECItem *name, - SECItem *derSubject, NSSLOWCERTIssuerAndSN *issuerSN, - SECItem *email, - unsigned long classFlags, PK11SearchResults *handles, - CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) -{ - NSSLOWCERTCertDBHandle *certHandle = NULL; - pk11CertData certData; - int i; - - certHandle = slot->certDB; - if (certHandle == NULL) return; - - certData.slot = slot; - certData.max_cert_count = 0; - certData.certs = NULL; - certData.cert_count = 0; - certData.template = pTemplate; - certData.templ_count = ulCount; - certData.classFlags = classFlags; - certData.strict = NSC_STRICT; - - - /* - * Find the Cert. - */ - if (derCert->data != NULL) { - NSSLOWCERTCertificate *cert = - nsslowcert_FindCertByDERCert(certHandle,derCert); - pk11_searchSingleCert(&certData,cert); - } else if (name->data != NULL) { - char *tmp_name = (char*)PORT_Alloc(name->len+1); - int count; - - if (tmp_name == NULL) { - return; - } - PORT_Memcpy(tmp_name,name->data,name->len); - tmp_name[name->len] = 0; - - count= nsslowcert_NumPermCertsForNickname(certHandle,tmp_name); - pk11_CertSetupData(&certData,count); - nsslowcert_TraversePermCertsForNickname(certHandle,tmp_name, - pk11_cert_collect, &certData); - PORT_Free(tmp_name); - } else if (derSubject->data != NULL) { - int count; - - count = nsslowcert_NumPermCertsForSubject(certHandle,derSubject); - pk11_CertSetupData(&certData,count); - nsslowcert_TraversePermCertsForSubject(certHandle,derSubject, - pk11_cert_collect, &certData); - } else if ((issuerSN->derIssuer.data != NULL) && - (issuerSN->serialNumber.data != NULL)) { - if (classFlags & NSC_CERT) { - NSSLOWCERTCertificate *cert = - nsslowcert_FindCertByIssuerAndSN(certHandle,issuerSN); - - pk11_searchSingleCert(&certData,cert); - } - if (classFlags & NSC_TRUST) { - NSSLOWCERTTrust *trust = - nsslowcert_FindTrustByIssuerAndSN(certHandle, issuerSN); - - if (trust) { - pk11_addHandle(handles, - pk11_mkHandle(slot,&trust->dbKey,PK11_TOKEN_TYPE_TRUST)); - nsslowcert_DestroyTrust(trust); - } - } - } else if (email->data != NULL) { - char *tmp_name = (char*)PORT_Alloc(email->len+1); - certDBEntrySMime *entry = NULL; - - if (tmp_name == NULL) { - return; - } - PORT_Memcpy(tmp_name,email->data,email->len); - tmp_name[email->len] = 0; - - entry = nsslowcert_ReadDBSMimeEntry(certHandle,tmp_name); - if (entry) { - int count; - SECItem *subjectName = &entry->subjectName; - - count = nsslowcert_NumPermCertsForSubject(certHandle, subjectName); - pk11_CertSetupData(&certData,count); - nsslowcert_TraversePermCertsForSubject(certHandle, subjectName, - pk11_cert_collect, &certData); - - nsslowcert_DestroyDBEntry((certDBEntry *)entry); - } - PORT_Free(tmp_name); - } else { - /* we aren't filtering the certs, we are working on all, so turn - * on the strict filters. */ - certData.strict = PR_TRUE; - pk11_CertSetupData(&certData,NSC_CERT_BLOCK_SIZE); - nsslowcert_TraversePermCerts(certHandle, pk11_cert_collect2, &certData); - } - - /* - * build the handles - */ - for (i=0 ; i < certData.cert_count ; i++) { - NSSLOWCERTCertificate *cert = certData.certs[i]; - - /* if we filtered it would have been on the stuff above */ - if (classFlags & NSC_CERT) { - pk11_addHandle(handles, - pk11_mkHandle(slot,&cert->certKey,PK11_TOKEN_TYPE_CERT)); - } - if ((classFlags & NSC_TRUST) && nsslowcert_hasTrust(cert->trust)) { - pk11_addHandle(handles, - pk11_mkHandle(slot,&cert->certKey,PK11_TOKEN_TYPE_TRUST)); - } - nsslowcert_DestroyCertificate(cert); - } - - if (certData.certs) PORT_Free(certData.certs); - return; -} - -static void -pk11_searchSMime(PK11Slot *slot, SECItem *email, PK11SearchResults *handles, - CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) -{ - NSSLOWCERTCertDBHandle *certHandle = NULL; - certDBEntrySMime *entry; - - certHandle = slot->certDB; - if (certHandle == NULL) return; - - if (email->data != NULL) { - char *tmp_name = (char*)PORT_Alloc(email->len+1); - - if (tmp_name == NULL) { - return; - } - PORT_Memcpy(tmp_name,email->data,email->len); - tmp_name[email->len] = 0; - - entry = nsslowcert_ReadDBSMimeEntry(certHandle,tmp_name); - if (entry) { - SECItem emailKey; - - emailKey.data = (unsigned char *)tmp_name; - emailKey.len = PORT_Strlen(tmp_name)+1; - emailKey.type = 0; - pk11_addHandle(handles, - pk11_mkHandle(slot,&emailKey,PK11_TOKEN_TYPE_SMIME)); - nsslowcert_DestroyDBEntry((certDBEntry *)entry); - } - PORT_Free(tmp_name); - } - return; -} - -static CK_RV -pk11_searchTokenList(PK11Slot *slot, PK11SearchResults *search, - CK_ATTRIBUTE *pTemplate, CK_LONG ulCount, - PRBool *tokenOnly, PRBool isLoggedIn) -{ - int i; - PRBool isKrl = PR_FALSE; - SECItem derCert = { siBuffer, NULL, 0 }; - SECItem derSubject = { siBuffer, NULL, 0 }; - SECItem name = { siBuffer, NULL, 0 }; - SECItem email = { siBuffer, NULL, 0 }; - SECItem key_id = { siBuffer, NULL, 0 }; - SECItem cert_sha1_hash = { siBuffer, NULL, 0 }; - SECItem cert_md5_hash = { siBuffer, NULL, 0 }; - NSSLOWCERTIssuerAndSN issuerSN = { - { siBuffer, NULL, 0 }, - { siBuffer, NULL, 0 } - }; - SECItem *copy = NULL; - unsigned long classFlags = - NSC_CERT|NSC_TRUST|NSC_PRIVATE|NSC_PUBLIC|NSC_KEY|NSC_SMIME|NSC_CRL; - - /* if we aren't logged in, don't look for private or secret keys */ - if (!isLoggedIn) { - classFlags &= ~(NSC_PRIVATE|NSC_KEY); - } - - /* - * look for things to search on token objects for. If the right options - * are specified, we can use them as direct indeces into the database - * (rather than using linear searches. We can also use the attributes to - * limit the kinds of objects we are searching for. Later we can use this - * array to filter the remaining objects more finely. - */ - for (i=0 ;classFlags && i < (int)ulCount; i++) { - - switch (pTemplate[i].type) { - case CKA_SUBJECT: - copy = &derSubject; - classFlags &= (NSC_CERT|NSC_PRIVATE|NSC_PUBLIC|NSC_SMIME|NSC_CRL); - break; - case CKA_ISSUER: - copy = &issuerSN.derIssuer; - classFlags &= (NSC_CERT|NSC_TRUST); - break; - case CKA_SERIAL_NUMBER: - copy = &issuerSN.serialNumber; - classFlags &= (NSC_CERT|NSC_TRUST); - break; - case CKA_VALUE: - copy = &derCert; - classFlags &= (NSC_CERT|NSC_CRL|NSC_SMIME); - break; - case CKA_LABEL: - copy = &name; - break; - case CKA_NETSCAPE_EMAIL: - copy = &email; - classFlags &= NSC_SMIME|NSC_CERT; - break; - case CKA_NETSCAPE_SMIME_TIMESTAMP: - classFlags &= NSC_SMIME; - break; - case CKA_CLASS: - if (pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS)) { - classFlags = 0; - break;; - } - switch (*((CK_OBJECT_CLASS *)pTemplate[i].pValue)) { - case CKO_CERTIFICATE: - classFlags &= NSC_CERT; - break; - case CKO_NETSCAPE_TRUST: - classFlags &= NSC_TRUST; - break; - case CKO_NETSCAPE_CRL: - classFlags &= NSC_CRL; - break; - case CKO_NETSCAPE_SMIME: - classFlags &= NSC_SMIME; - break; - case CKO_PRIVATE_KEY: - classFlags &= NSC_PRIVATE; - break; - case CKO_PUBLIC_KEY: - classFlags &= NSC_PUBLIC; - break; - case CKO_SECRET_KEY: - classFlags &= NSC_KEY; - break; - default: - classFlags = 0; - break; - } - break; - case CKA_PRIVATE: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - } - if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) { - classFlags &= (NSC_PRIVATE|NSC_KEY); - } else { - classFlags &= ~(NSC_PRIVATE|NSC_KEY); - } - break; - case CKA_SENSITIVE: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - } - if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) { - classFlags &= (NSC_PRIVATE|NSC_KEY); - } else { - classFlags = 0; - } - break; - case CKA_TOKEN: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - } - if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) { - *tokenOnly = PR_TRUE; - } else { - classFlags = 0; - } - break; - case CKA_CERT_SHA1_HASH: - classFlags &= NSC_TRUST; - copy = &cert_sha1_hash; break; - case CKA_CERT_MD5_HASH: - classFlags &= NSC_TRUST; - copy = &cert_md5_hash; break; - case CKA_CERTIFICATE_TYPE: - if (pTemplate[i].ulValueLen != sizeof(CK_CERTIFICATE_TYPE)) { - classFlags = 0; - } - classFlags &= NSC_CERT; - if (*((CK_CERTIFICATE_TYPE *)pTemplate[i].pValue) != CKC_X_509) { - classFlags = 0; - } - break; - case CKA_ID: - copy = &key_id; - classFlags &= (NSC_CERT|NSC_PRIVATE|NSC_KEY|NSC_PUBLIC); - break; - case CKA_NETSCAPE_KRL: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - } - classFlags &= NSC_CRL; - isKrl = (PRBool)(*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE); - break; - case CKA_MODIFIABLE: - break; - case CKA_KEY_TYPE: - case CKA_DERIVE: - classFlags &= NSC_PUBLIC|NSC_PRIVATE|NSC_KEY; - break; - case CKA_VERIFY_RECOVER: - classFlags &= NSC_PUBLIC; - break; - case CKA_SIGN_RECOVER: - classFlags &= NSC_PRIVATE; - break; - case CKA_ENCRYPT: - case CKA_VERIFY: - case CKA_WRAP: - classFlags &= NSC_PUBLIC|NSC_KEY; - break; - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_UNWRAP: - case CKA_ALWAYS_SENSITIVE: - case CKA_EXTRACTABLE: - case CKA_NEVER_EXTRACTABLE: - classFlags &= NSC_PRIVATE|NSC_KEY; - break; - /* can't be a certificate if it doesn't match one of the above - * attributes */ - default: - classFlags = 0; - break; - } - if (copy) { - copy->data = (unsigned char*)pTemplate[i].pValue; - copy->len = pTemplate[i].ulValueLen; - } - copy = NULL; - } - - - /* certs */ - if (classFlags & (NSC_CERT|NSC_TRUST)) { - pk11_searchCertsAndTrust(slot,&derCert,&name,&derSubject, - &issuerSN, &email,classFlags,search, - pTemplate, ulCount); - } - - /* keys */ - if (classFlags & (NSC_PRIVATE|NSC_PUBLIC|NSC_KEY)) { - PRBool mustStrict = ((classFlags & NSC_KEY) != 0) && (name.len != 0); - pk11_searchKeys(slot, &key_id, isLoggedIn, classFlags, search, - mustStrict, pTemplate, ulCount); - } - - /* crl's */ - if (classFlags & NSC_CRL) { - pk11_searchCrls(slot, &derSubject, isKrl, classFlags, search, - pTemplate, ulCount); - } - /* Add S/MIME entry stuff */ - if (classFlags & NSC_SMIME) { - pk11_searchSMime(slot, &email, search, pTemplate, ulCount); - } - return CKR_OK; -} - - -/* NSC_FindObjectsInit initializes a search for token and session objects - * that match a template. */ -CK_RV NSC_FindObjectsInit(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) -{ - PK11SearchResults *search = NULL, *freeSearch = NULL; - PK11Session *session = NULL; - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - PRBool tokenOnly = PR_FALSE; - CK_RV crv = CKR_OK; - PRBool isLoggedIn; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - crv = CKR_SESSION_HANDLE_INVALID; - goto loser; - } - - search = (PK11SearchResults *)PORT_Alloc(sizeof(PK11SearchResults)); - if (search == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; - } - search->handles = (CK_OBJECT_HANDLE *) - PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE); - if (search->handles == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; - } - search->index = 0; - search->size = 0; - search->array_size = NSC_SEARCH_BLOCK_SIZE; - isLoggedIn = (PRBool)((!slot->needLogin) || slot->isLoggedIn); - - crv = pk11_searchTokenList(slot, search, pTemplate, ulCount, &tokenOnly, - isLoggedIn); - if (crv != CKR_OK) { - goto loser; - } - - /* build list of found objects in the session */ - if (!tokenOnly) { - crv = pk11_searchObjectList(search, slot->tokObjects, - slot->tokObjHashSize, slot->objectLock, - pTemplate, ulCount, isLoggedIn); - } - if (crv != CKR_OK) { - goto loser; - } - - if ((freeSearch = session->search) != NULL) { - session->search = NULL; - pk11_FreeSearch(freeSearch); - } - session->search = search; - pk11_FreeSession(session); - return CKR_OK; - -loser: - if (search) { - pk11_FreeSearch(search); - } - if (session) { - pk11_FreeSession(session); - } - return crv; -} - - -/* NSC_FindObjects continues a search for token and session objects - * that match a template, obtaining additional object handles. */ -CK_RV NSC_FindObjects(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE_PTR phObject,CK_ULONG ulMaxObjectCount, - CK_ULONG_PTR pulObjectCount) -{ - PK11Session *session; - PK11SearchResults *search; - int transfer; - int left; - - *pulObjectCount = 0; - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - if (session->search == NULL) { - pk11_FreeSession(session); - return CKR_OK; - } - search = session->search; - left = session->search->size - session->search->index; - transfer = ((int)ulMaxObjectCount > left) ? left : ulMaxObjectCount; - if (transfer > 0) { - PORT_Memcpy(phObject,&search->handles[search->index], - transfer*sizeof(CK_OBJECT_HANDLE_PTR)); - } else { - *phObject = CK_INVALID_HANDLE; - } - - search->index += transfer; - if (search->index == search->size) { - session->search = NULL; - pk11_FreeSearch(search); - } - *pulObjectCount = transfer; - pk11_FreeSession(session); - return CKR_OK; -} - -/* NSC_FindObjectsFinal finishes a search for token and session objects. */ -CK_RV NSC_FindObjectsFinal(CK_SESSION_HANDLE hSession) -{ - PK11Session *session; - PK11SearchResults *search; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - search = session->search; - session->search = NULL; - pk11_FreeSession(session); - if (search != NULL) { - pk11_FreeSearch(search); - } - return CKR_OK; -} - - - -CK_RV NSC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, - CK_VOID_PTR pReserved) -{ - return CKR_FUNCTION_NOT_SUPPORTED; -} diff --git a/security/nss/lib/softoken/pkcs11.h b/security/nss/lib/softoken/pkcs11.h deleted file mode 100644 index 9b54421e7..000000000 --- a/security/nss/lib/softoken/pkcs11.h +++ /dev/null @@ -1,319 +0,0 @@ -/* - * 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): RSA Labs - * - * 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. - */ -/* - * Copyright (C) 1994-1999 RSA Security Inc. Licence to copy this document - * is granted provided that it is identified as "RSA Security In.c Public-Key - * Cryptography Standards (PKCS)" in all material mentioning or referencing - * this document. - * - * The latest version of this header can be found at: - * http://www.rsalabs.com/pkcs/pkcs-11/index.html - */ -#ifndef _PKCS11_H_ -#define _PKCS11_H_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -/* Before including this file (pkcs11.h) (or pkcs11t.h by - * itself), 6 platform-specific macros must be defined. These - * macros are described below, and typical definitions for them - * are also given. Be advised that these definitions can depend - * on both the platform and the compiler used (and possibly also - * on whether a PKCS #11 library is linked statically or - * dynamically). - * - * In addition to defining these 6 macros, the packing convention - * for PKCS #11 structures should be set. The PKCS #11 - * convention on packing is that structures should be 1-byte - * aligned. - * - * In a Win32 environment, this might be done by using the - * following preprocessor directive before including pkcs11.h - * or pkcs11t.h: - * - * #pragma pack(push, cryptoki, 1) - * - * and using the following preprocessor directive after including - * pkcs11.h or pkcs11t.h: - * - * #pragma pack(pop, cryptoki) - * - * In a Win16 environment, this might be done by using the - * following preprocessor directive before including pkcs11.h - * or pkcs11t.h: - * - * #pragma pack(1) - * - * In a UNIX environment, you're on your own here. You might - * not need to do anything. - * - * - * Now for the macros: - * - * - * 1. CK_PTR: The indirection string for making a pointer to an - * object. It can be used like this: - * - * typedef CK_BYTE CK_PTR CK_BYTE_PTR; - * - * In a Win32 environment, it might be defined by - * - * #define CK_PTR * - * - * In a Win16 environment, it might be defined by - * - * #define CK_PTR far * - * - * In a UNIX environment, it might be defined by - * - * #define CK_PTR * - * - * - * 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes - * an exportable PKCS #11 library function definition out of a - * return type and a function name. It should be used in the - * following fashion to define the exposed PKCS #11 functions in - * a PKCS #11 library: - * - * CK_DEFINE_FUNCTION(CK_RV, C_Initialize)( - * CK_VOID_PTR pReserved - * ) - * { - * ... - * } - * - * For defining a function in a Win32 PKCS #11 .dll, it might be - * defined by - * - * #define CK_DEFINE_FUNCTION(returnType, name) \ - * returnType __declspec(dllexport) name - * - * For defining a function in a Win16 PKCS #11 .dll, it might be - * defined by - * - * #define CK_DEFINE_FUNCTION(returnType, name) \ - * returnType __export _far _pascal name - * - * In a UNIX environment, it might be defined by - * - * #define CK_DEFINE_FUNCTION(returnType, name) \ - * returnType name - * - * - * 3. CK_DECLARE_FUNCTION(returnType, name): A macro which makes - * an importable PKCS #11 library function declaration out of a - * return type and a function name. It should be used in the - * following fashion: - * - * extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)( - * CK_VOID_PTR pReserved - * ); - * - * For declaring a function in a Win32 PKCS #11 .dll, it might - * be defined by - * - * #define CK_DECLARE_FUNCTION(returnType, name) \ - * returnType __declspec(dllimport) name - * - * For declaring a function in a Win16 PKCS #11 .dll, it might - * be defined by - * - * #define CK_DECLARE_FUNCTION(returnType, name) \ - * returnType __export _far _pascal name - * - * In a UNIX environment, it might be defined by - * - * #define CK_DECLARE_FUNCTION(returnType, name) \ - * returnType name - * - * - * 4. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro - * which makes a PKCS #11 API function pointer declaration or - * function pointer type declaration out of a return type and a - * function name. It should be used in the following fashion: - * - * // Define funcPtr to be a pointer to a PKCS #11 API function - * // taking arguments args and returning CK_RV. - * CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args); - * - * or - * - * // Define funcPtrType to be the type of a pointer to a - * // PKCS #11 API function taking arguments args and returning - * // CK_RV, and then define funcPtr to be a variable of type - * // funcPtrType. - * typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args); - * funcPtrType funcPtr; - * - * For accessing functions in a Win32 PKCS #11 .dll, in might be - * defined by - * - * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ - * returnType __declspec(dllimport) (* name) - * - * For accessing functions in a Win16 PKCS #11 .dll, it might be - * defined by - * - * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ - * returnType __export _far _pascal (* name) - * - * In a UNIX environment, it might be defined by - * - * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ - * returnType (* name) - * - * - * 5. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes - * a function pointer type for an application callback out of - * a return type for the callback and a name for the callback. - * It should be used in the following fashion: - * - * CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args); - * - * to declare a function pointer, myCallback, to a callback - * which takes arguments args and returns a CK_RV. It can also - * be used like this: - * - * typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args); - * myCallbackType myCallback; - * - * In a Win32 environment, it might be defined by - * - * #define CK_CALLBACK_FUNCTION(returnType, name) \ - * returnType (* name) - * - * In a Win16 environment, it might be defined by - * - * #define CK_CALLBACK_FUNCTION(returnType, name) \ - * returnType _far _pascal (* name) - * - * In a UNIX environment, it might be defined by - * - * #define CK_CALLBACK_FUNCTION(returnType, name) \ - * returnType (* name) - * - * - * 6. NULL_PTR: This macro is the value of a NULL pointer. - * - * In any ANSI/ISO C environment (and in many others as well), - * this should be defined by - * - * #ifndef NULL_PTR - * #define NULL_PTR 0 - * #endif - */ - - -/* All the various PKCS #11 types and #define'd values are in the - * file pkcs11t.h. */ -#include "pkcs11t.h" - -#define __PASTE(x,y) x##y - - -/* packing defines */ -#include "pkcs11p.h" -/* ============================================================== - * Define the "extern" form of all the entry points. - * ============================================================== - */ - -#define CK_NEED_ARG_LIST 1 -#define CK_PKCS11_FUNCTION_INFO(name) \ - CK_DECLARE_FUNCTION(CK_RV, name) - -/* pkcs11f.h has all the information about the PKCS #11 - * function prototypes. */ -#include "pkcs11f.h" - -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - - -/* ============================================================== - * Define the typedef form of all the entry points. That is, for - * each PKCS #11 function C_XXX, define a type CK_C_XXX which is - * a pointer to that kind of function. - * ============================================================== - */ - -#define CK_NEED_ARG_LIST 1 -#define CK_PKCS11_FUNCTION_INFO(name) \ - typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name)) - -/* pkcs11f.h has all the information about the PKCS #11 - * function prototypes. */ -#include "pkcs11f.h" - -#undef CK_NEED_ARG_LIST -#undef CK_PKCS11_FUNCTION_INFO - - -/* ============================================================== - * Define structed vector of entry points. A CK_FUNCTION_LIST - * contains a CK_VERSION indicating a library's PKCS #11 version - * and then a whole slew of function pointers to the routines in - * the library. This type was declared, but not defined, in - * pkcs11t.h. - * ============================================================== - */ - -#define CK_PKCS11_FUNCTION_INFO(name) \ - __PASTE(CK_,name) name; - -struct CK_FUNCTION_LIST { - - CK_VERSION version; /* PKCS #11 version */ - -/* Pile all the function pointers into the CK_FUNCTION_LIST. */ -/* pkcs11f.h has all the information about the PKCS #11 - * function prototypes. */ -#include "pkcs11f.h" - -}; - -#undef CK_PKCS11_FUNCTION_INFO - - -#undef __PASTE - -/* unpack */ -#include "pkcs11u.h" - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/security/nss/lib/softoken/pkcs11c.c b/security/nss/lib/softoken/pkcs11c.c deleted file mode 100644 index 50788e5c6..000000000 --- a/security/nss/lib/softoken/pkcs11c.c +++ /dev/null @@ -1,5433 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Stephen Henson <stephen.henson@gemplus.com> - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - */ -/* - * This file implements PKCS 11 on top of our existing security modules - * - * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. - * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login. - * It supports Public Key ops, and all they bulk ciphers and hashes. - * It can also support Private Key ops for imported Private keys. It does - * not have any token storage. - * slot 2 is our private key support. It requires a login before use. It - * can store Private Keys and Certs as token objects. Currently only private - * keys and their associated Certificates are saved on the token. - * - * In this implementation, session objects are only visible to the session - * that created or generated them. - */ -#include "seccomon.h" -#include "secitem.h" -#include "secport.h" -#include "blapi.h" -#include "pqgutil.h" -#include "pkcs11.h" -#include "pkcs11i.h" -#include "lowkeyi.h" -#include "pcert.h" -#include "sechash.h" -#include "secder.h" -#include "secdig.h" -#include "lowpbe.h" /* We do PBE below */ -#include "pkcs11t.h" -#include "secoid.h" -#include "alghmac.h" -#include "softoken.h" -#include "secasn1.h" -#include "secerr.h" - -#include "pcert.h" -#include "ssl3prot.h" /* for SSL3_RANDOM_LENGTH */ - -#define __PASTE(x,y) x##y - -/* - * we renamed all our internal functions, get the correct - * definitions for them... - */ -#undef CK_PKCS11_FUNCTION_INFO -#undef CK_NEED_ARG_LIST - -#define CK_EXTERN extern -#define CK_PKCS11_FUNCTION_INFO(func) \ - CK_RV __PASTE(NS,func) -#define CK_NEED_ARG_LIST 1 - -#include "pkcs11f.h" - -static void pk11_Null(void *data, PRBool freeit) -{ - return; -} - -#ifdef NSS_ENABLE_ECC -extern SECStatus EC_DecodeParams(const SECItem *encodedParams, - ECParams **ecparams); -#ifdef EC_DEBUG -#define SEC_PRINT(str1, str2, num, sitem) \ - printf("pkcs11c.c:%s:%s (keytype=%d) [len=%d]\n", \ - str1, str2, num, sitem->len); \ - for (i = 0; i < sitem->len; i++) { \ - printf("%02x:", sitem->data[i]); \ - } \ - printf("\n") -#else -#define SEC_PRINT(a, b, c, d) -#endif -#endif /* NSS_ENABLE_ECC */ - -/* - * free routines.... Free local type allocated data, and convert - * other free routines to the destroy signature. - */ -static void -pk11_FreePrivKey(NSSLOWKEYPrivateKey *key, PRBool freeit) -{ - nsslowkey_DestroyPrivateKey(key); -} - -static void -pk11_HMAC_Destroy(HMACContext *context, PRBool freeit) -{ - HMAC_Destroy(context); -} - -static void -pk11_Space(void *data, PRBool freeit) -{ - PORT_Free(data); -} - - -/* - * turn a CDMF key into a des key. CDMF is an old IBM scheme to export DES by - * Deprecating a full des key to 40 bit key strenth. - */ -static CK_RV -pk11_cdmf2des(unsigned char *cdmfkey, unsigned char *deskey) -{ - unsigned char key1[8] = { 0xc4, 0x08, 0xb0, 0x54, 0x0b, 0xa1, 0xe0, 0xae }; - unsigned char key2[8] = { 0xef, 0x2c, 0x04, 0x1c, 0xe6, 0x38, 0x2f, 0xe6 }; - unsigned char enc_src[8]; - unsigned char enc_dest[8]; - unsigned int leng,i; - DESContext *descx; - SECStatus rv; - - - /* zero the parity bits */ - for (i=0; i < 8; i++) { - enc_src[i] = cdmfkey[i] & 0xfe; - } - - /* encrypt with key 1 */ - descx = DES_CreateContext(key1, NULL, NSS_DES, PR_TRUE); - if (descx == NULL) return CKR_HOST_MEMORY; - rv = DES_Encrypt(descx, enc_dest, &leng, 8, enc_src, 8); - DES_DestroyContext(descx,PR_TRUE); - if (rv != SECSuccess) return CKR_DEVICE_ERROR; - - /* xor source with des, zero the parity bits and depricate the key*/ - for (i=0; i < 8; i++) { - if (i & 1) { - enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0xfe; - } else { - enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0x0e; - } - } - - /* encrypt with key 2 */ - descx = DES_CreateContext(key2, NULL, NSS_DES, PR_TRUE); - if (descx == NULL) return CKR_HOST_MEMORY; - rv = DES_Encrypt(descx, deskey, &leng, 8, enc_src, 8); - DES_DestroyContext(descx,PR_TRUE); - if (rv != SECSuccess) return CKR_DEVICE_ERROR; - - /* set the corret parity on our new des key */ - pk11_FormatDESKey(deskey, 8); - return CKR_OK; -} - - -/* NSC_DestroyObject destroys an object. */ -CK_RV -NSC_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) -{ - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - PK11Session *session; - PK11Object *object; - PK11FreeStatus status; - - /* - * This whole block just makes sure we really can destroy the - * requested object. - */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } - - object = pk11_ObjectFromHandle(hObject,session); - if (object == NULL) { - pk11_FreeSession(session); - return CKR_OBJECT_HANDLE_INVALID; - } - - /* don't destroy a private object if we aren't logged in */ - if ((!slot->isLoggedIn) && (slot->needLogin) && - (pk11_isTrue(object,CKA_PRIVATE))) { - pk11_FreeSession(session); - pk11_FreeObject(object); - return CKR_USER_NOT_LOGGED_IN; - } - - /* don't destroy a token object if we aren't in a rw session */ - - if (((session->info.flags & CKF_RW_SESSION) == 0) && - (pk11_isTrue(object,CKA_TOKEN))) { - pk11_FreeSession(session); - pk11_FreeObject(object); - return CKR_SESSION_READ_ONLY; - } - - pk11_DeleteObject(session,object); - - pk11_FreeSession(session); - - /* - * get some indication if the object is destroyed. Note: this is not - * 100%. Someone may have an object reference outstanding (though that - * should not be the case by here. Also note that the object is "half" - * destroyed. Our internal representation is destroyed, but it may still - * be in the data base. - */ - status = pk11_FreeObject(object); - - return (status != PK11_DestroyFailure) ? CKR_OK : CKR_DEVICE_ERROR; -} - - -/* - ************** Crypto Functions: Utilities ************************ - */ - - -/* - * return a context based on the PK11Context type. - */ -PK11SessionContext * -pk11_ReturnContextByType(PK11Session *session, PK11ContextType type) -{ - switch (type) { - case PK11_ENCRYPT: - case PK11_DECRYPT: - return session->enc_context; - case PK11_HASH: - return session->hash_context; - case PK11_SIGN: - case PK11_SIGN_RECOVER: - case PK11_VERIFY: - case PK11_VERIFY_RECOVER: - return session->hash_context; - } - return NULL; -} - -/* - * change a context based on the PK11Context type. - */ -void -pk11_SetContextByType(PK11Session *session, PK11ContextType type, - PK11SessionContext *context) -{ - switch (type) { - case PK11_ENCRYPT: - case PK11_DECRYPT: - session->enc_context = context; - break; - case PK11_HASH: - session->hash_context = context; - break; - case PK11_SIGN: - case PK11_SIGN_RECOVER: - case PK11_VERIFY: - case PK11_VERIFY_RECOVER: - session->hash_context = context; - break; - } - return; -} - -/* - * code to grab the context. Needed by every C_XXXUpdate, C_XXXFinal, - * and C_XXX function. The function takes a session handle, the context type, - * and wether or not the session needs to be multipart. It returns the context, - * and optionally returns the session pointer (if sessionPtr != NULL) if session - * pointer is returned, the caller is responsible for freeing it. - */ -static CK_RV -pk11_GetContext(CK_SESSION_HANDLE handle,PK11SessionContext **contextPtr, - PK11ContextType type, PRBool needMulti, PK11Session **sessionPtr) -{ - PK11Session *session; - PK11SessionContext *context; - - session = pk11_SessionFromHandle(handle); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - context = pk11_ReturnContextByType(session,type); - /* make sure the context is valid */ - if((context==NULL)||(context->type!=type)||(needMulti&&!(context->multi))){ - pk11_FreeSession(session); - return CKR_OPERATION_NOT_INITIALIZED; - } - *contextPtr = context; - if (sessionPtr != NULL) { - *sessionPtr = session; - } else { - pk11_FreeSession(session); - } - return CKR_OK; -} - -/* - ************** Crypto Functions: Encrypt ************************ - */ - -/* - * All the NSC_InitXXX functions have a set of common checks and processing they - * all need to do at the beginning. This is done here. - */ -static CK_RV -pk11_InitGeneric(PK11Session *session,PK11SessionContext **contextPtr, - PK11ContextType ctype,PK11Object **keyPtr, - CK_OBJECT_HANDLE hKey, CK_KEY_TYPE *keyTypePtr, - CK_OBJECT_CLASS pubKeyType, CK_ATTRIBUTE_TYPE operation) -{ - PK11Object *key = NULL; - PK11Attribute *att; - PK11SessionContext *context; - - /* We can only init if there is not current context active */ - if (pk11_ReturnContextByType(session,ctype) != NULL) { - return CKR_OPERATION_ACTIVE; - } - - /* find the key */ - if (keyPtr) { - unsigned int size; - key = pk11_ObjectFromHandle(hKey,session); - if (key == NULL) { - return CKR_KEY_HANDLE_INVALID; - } - - /* make sure it's a valid key for this operation */ - if (((key->objclass != CKO_SECRET_KEY) && (key->objclass != pubKeyType)) - || !pk11_isTrue(key,operation)) { - pk11_FreeObject(key); - return CKR_KEY_TYPE_INCONSISTENT; - } - /* get the key type */ - att = pk11_FindAttribute(key,CKA_KEY_TYPE); - PORT_Assert(att != NULL); - size = sizeof(CK_KEY_TYPE); - if (att->attrib.ulValueLen < size) { - CK_KEY_TYPE kt; - int i; - int shift; -#ifdef IS_LITTLE_ENDIAN - shift = 0; -#else - shift = (att->attrib.ulValueLen - 1) * 8; -#endif - kt = 0; - for (i=att->attrib.ulValueLen - 1; i>=0; i--) { - kt |= ((unsigned char *)att->attrib.pValue)[i] << shift; -#ifdef IS_LITTLE_ENDIAN - shift += 8; -#else - shift -= 8; -#endif - } - *keyTypePtr = kt; - } else { - *keyTypePtr = *((CK_KEY_TYPE *)att->attrib.pValue); - } - pk11_FreeAttribute(att); - *keyPtr = key; - } - - /* allocate the context structure */ - context = (PK11SessionContext *)PORT_Alloc(sizeof(PK11SessionContext)); - if (context == NULL) { - if (key) pk11_FreeObject(key); - return CKR_HOST_MEMORY; - } - context->type = ctype; - context->multi = PR_TRUE; - context->cipherInfo = NULL; - context->hashInfo = NULL; - context->doPad = PR_FALSE; - context->padDataLength = 0; - context->key = key; - context->blockSize = 0; - - *contextPtr = context; - return CKR_OK; -} - -/* NSC_CryptInit initializes an encryption/Decryption operation. */ -/* This function is used by NSC_EncryptInit, NSC_DecryptInit, - * NSC_WrapKey, NSC_UnwrapKey, - * NSC_SignInit, NSC_VerifyInit (via pk11_InitCBCMac), - * The only difference in their uses is the value of etype. - */ -static CK_RV -pk11_CryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey, CK_ATTRIBUTE_TYPE etype, - PK11ContextType contextType, PRBool isEncrypt) -{ - PK11Session *session; - PK11Object *key; - PK11SessionContext *context; - PK11Attribute *att; - CK_RC2_CBC_PARAMS *rc2_param; -#if NSS_SOFTOKEN_DOES_RC5 - CK_RC5_CBC_PARAMS *rc5_param; - SECItem rc5Key; -#endif - CK_KEY_TYPE key_type; - CK_RV crv = CKR_OK; - unsigned effectiveKeyLength; - unsigned char newdeskey[24]; - PRBool useNewKey=PR_FALSE; - int t; - - crv = pk11_MechAllowsOperation(pMechanism->mechanism, etype); - if (crv != CKR_OK) - return crv; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - - crv = pk11_InitGeneric(session,&context,contextType,&key,hKey,&key_type, - isEncrypt ?CKO_PUBLIC_KEY:CKO_PRIVATE_KEY, etype); - - if (crv != CKR_OK) { - pk11_FreeSession(session); - return crv; - } - - context->doPad = PR_FALSE; - switch(pMechanism->mechanism) { - case CKM_RSA_PKCS: - case CKM_RSA_X_509: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->multi = PR_FALSE; - context->cipherInfo = isEncrypt ? - (void *)pk11_GetPubKey(key,CKK_RSA,&crv) : - (void *)pk11_GetPrivKey(key,CKK_RSA,&crv); - if (context->cipherInfo == NULL) { - break; - } - if (isEncrypt) { - context->update = (PK11Cipher) - (pMechanism->mechanism == CKM_RSA_X_509 - ? RSA_EncryptRaw : RSA_EncryptBlock); - } else { - context->update = (PK11Cipher) - (pMechanism->mechanism == CKM_RSA_X_509 - ? RSA_DecryptRaw : RSA_DecryptBlock); - } - context->destroy = pk11_Null; - break; - case CKM_RC2_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_RC2_ECB: - case CKM_RC2_CBC: - context->blockSize = 8; - if (key_type != CKK_RC2) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = pk11_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - rc2_param = (CK_RC2_CBC_PARAMS *)pMechanism->pParameter; - effectiveKeyLength = (rc2_param->ulEffectiveBits+7)/8; - context->cipherInfo = - RC2_CreateContext((unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen, rc2_param->iv, - pMechanism->mechanism == CKM_RC2_ECB ? NSS_RC2 : - NSS_RC2_CBC,effectiveKeyLength); - pk11_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (PK11Cipher) (isEncrypt ? RC2_Encrypt : RC2_Decrypt); - context->destroy = (PK11Destroy) RC2_DestroyContext; - break; -#if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_RC5_ECB: - case CKM_RC5_CBC: - if (key_type != CKK_RC5) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = pk11_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - rc5_param = (CK_RC5_CBC_PARAMS *)pMechanism->pParameter; - context->blockSize = rc5_param->ulWordsize*2; - rc5Key.data = (unsigned char*)att->attrib.pValue; - rc5Key.len = att->attrib.ulValueLen; - context->cipherInfo = RC5_CreateContext(&rc5Key,rc5_param->ulRounds, - rc5_param->ulWordsize,rc5_param->pIv, - pMechanism->mechanism == CKM_RC5_ECB ? NSS_RC5 : NSS_RC5_CBC); - pk11_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (PK11Cipher) (isEncrypt ? RC5_Encrypt : RC5_Decrypt); - context->destroy = (PK11Destroy) RC5_DestroyContext; - break; -#endif - case CKM_RC4: - if (key_type != CKK_RC4) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = pk11_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = - RC4_CreateContext((unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - pk11_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; /* WRONG !!! */ - break; - } - context->update = (PK11Cipher) (isEncrypt ? RC4_Encrypt : RC4_Decrypt); - context->destroy = (PK11Destroy) RC4_DestroyContext; - break; - case CKM_CDMF_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_CDMF_ECB: - case CKM_CDMF_CBC: - if (key_type != CKK_CDMF) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = (pMechanism->mechanism == CKM_CDMF_ECB) ? NSS_DES : NSS_DES_CBC; - if (crv != CKR_OK) break; - goto finish_des; - case CKM_DES_ECB: - if (key_type != CKK_DES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES; - goto finish_des; - case CKM_DES_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_DES_CBC: - if (key_type != CKK_DES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES_CBC; - goto finish_des; - case CKM_DES3_ECB: - if ((key_type != CKK_DES2) && (key_type != CKK_DES3)) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES_EDE3; - goto finish_des; - case CKM_DES3_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_DES3_CBC: - if ((key_type != CKK_DES2) && (key_type != CKK_DES3)) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES_EDE3_CBC; -finish_des: - context->blockSize = 8; - att = pk11_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - if (key_type == CKK_DES2 && - (t == NSS_DES_EDE3_CBC || t == NSS_DES_EDE3)) { - /* extend DES2 key to DES3 key. */ - memcpy(newdeskey, att->attrib.pValue, 16); - memcpy(newdeskey + 16, newdeskey, 8); - useNewKey=PR_TRUE; - } else if (key_type == CKK_CDMF) { - crv = pk11_cdmf2des((unsigned char*)att->attrib.pValue,newdeskey); - if (crv != CKR_OK) { - pk11_FreeAttribute(att); - break; - } - useNewKey=PR_TRUE; - } - context->cipherInfo = DES_CreateContext( - useNewKey ? newdeskey : (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter,t, isEncrypt); - if (useNewKey) - memset(newdeskey, 0, sizeof newdeskey); - pk11_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (PK11Cipher) (isEncrypt ? DES_Encrypt : DES_Decrypt); - context->destroy = (PK11Destroy) DES_DestroyContext; - break; - - case CKM_AES_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_AES_ECB: - case CKM_AES_CBC: - context->blockSize = 16; - if (key_type != CKK_AES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = pk11_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = AES_CreateContext( - (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter, - pMechanism->mechanism == CKM_AES_ECB ? NSS_AES : NSS_AES_CBC, - isEncrypt, att->attrib.ulValueLen, 16); - pk11_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (PK11Cipher) (isEncrypt ? AES_Encrypt : AES_Decrypt); - context->destroy = (PK11Destroy) AES_DestroyContext; - break; - - case CKM_NETSCAPE_AES_KEY_WRAP_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_NETSCAPE_AES_KEY_WRAP: - context->multi = PR_FALSE; - context->blockSize = 8; - if (key_type != CKK_AES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = pk11_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = AESKeyWrap_CreateContext( - (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter, - isEncrypt, att->attrib.ulValueLen); - pk11_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (PK11Cipher) (isEncrypt ? AESKeyWrap_Encrypt - : AESKeyWrap_Decrypt); - context->destroy = (PK11Destroy) AESKeyWrap_DestroyContext; - break; - - default: - crv = CKR_MECHANISM_INVALID; - break; - } - - if (crv != CKR_OK) { - pk11_FreeContext(context); - pk11_FreeSession(session); - return crv; - } - pk11_SetContextByType(session, contextType, context); - pk11_FreeSession(session); - return CKR_OK; -} - -/* NSC_EncryptInit initializes an encryption operation. */ -CK_RV NSC_EncryptInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) -{ - return pk11_CryptInit(hSession, pMechanism, hKey, CKA_ENCRYPT, - PK11_ENCRYPT, PR_TRUE); -} - -/* NSC_EncryptUpdate continues a multiple-part encryption operation. */ -CK_RV NSC_EncryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) -{ - PK11SessionContext *context; - unsigned int outlen,i; - unsigned int padoutlen = 0; - unsigned int maxout = *pulEncryptedPartLen; - CK_RV crv; - SECStatus rv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_ENCRYPT,PR_TRUE,NULL); - if (crv != CKR_OK) return crv; - - /* do padding */ - if (context->doPad) { - /* deal with previous buffered data */ - if (context->padDataLength != 0) { - /* fill in the padded to a full block size */ - for (i=context->padDataLength; - (ulPartLen != 0) && i < context->blockSize; i++) { - context->padBuf[i] = *pPart++; - ulPartLen--; - context->padDataLength++; - } - - /* not enough data to encrypt yet? then return */ - if (context->padDataLength != context->blockSize) { - *pulEncryptedPartLen = 0; - return CKR_OK; - } - /* encrypt the current padded data */ - rv = (*context->update)(context->cipherInfo, pEncryptedPart, - &padoutlen, context->blockSize, context->padBuf, - context->blockSize); - if (rv != SECSuccess) return CKR_DEVICE_ERROR; - pEncryptedPart += padoutlen; - maxout -= padoutlen; - } - /* save the residual */ - context->padDataLength = ulPartLen % context->blockSize; - if (context->padDataLength) { - PORT_Memcpy(context->padBuf, - &pPart[ulPartLen-context->padDataLength], - context->padDataLength); - ulPartLen -= context->padDataLength; - } - /* if we've exhausted our new buffer, we're done */ - if (ulPartLen == 0) { - *pulEncryptedPartLen = padoutlen; - return CKR_OK; - } - } - - - /* do it: NOTE: this assumes buf size in is >= buf size out! */ - rv = (*context->update)(context->cipherInfo,pEncryptedPart, - &outlen, maxout, pPart, ulPartLen); - *pulEncryptedPartLen = (CK_ULONG) (outlen + padoutlen); - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - - -/* NSC_EncryptFinal finishes a multiple-part encryption operation. */ -CK_RV NSC_EncryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pulLastEncryptedPartLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen,i; - unsigned int maxout = *pulLastEncryptedPartLen; - CK_RV crv; - SECStatus rv = SECSuccess; - PRBool contextFinished = PR_TRUE; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_ENCRYPT,PR_TRUE,&session); - if (crv != CKR_OK) return crv; - - *pulLastEncryptedPartLen = 0; - if (!pLastEncryptedPart) { - /* caller is checking the amount of remaining data */ - if (context->blockSize > 0 && context->doPad) { - *pulLastEncryptedPartLen = context->blockSize; - contextFinished = PR_FALSE; /* still have padding to go */ - } - goto finish; - } - - /* do padding */ - if (context->doPad) { - unsigned char padbyte = (unsigned char) - (context->blockSize - context->padDataLength); - /* fill out rest of pad buffer with pad magic*/ - for (i=context->padDataLength; i < context->blockSize; i++) { - context->padBuf[i] = padbyte; - } - rv = (*context->update)(context->cipherInfo,pLastEncryptedPart, - &outlen, maxout, context->padBuf, context->blockSize); - if (rv == SECSuccess) *pulLastEncryptedPartLen = (CK_ULONG) outlen; - } - -finish: - if (contextFinished) { - pk11_SetContextByType(session, PK11_ENCRYPT, NULL); - pk11_FreeContext(context); - } - pk11_FreeSession(session); - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - -/* NSC_Encrypt encrypts single-part data. */ -CK_RV NSC_Encrypt (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, - CK_ULONG_PTR pulEncryptedDataLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen; - unsigned int maxoutlen = *pulEncryptedDataLen; - CK_RV crv; - CK_RV crv2; - SECStatus rv = SECSuccess; - SECItem pText; - - pText.type = siBuffer; - pText.data = pData; - pText.len = ulDataLen; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_ENCRYPT,PR_FALSE,&session); - if (crv != CKR_OK) return crv; - - if (!pEncryptedData) { - *pulEncryptedDataLen = ulDataLen + 2 * context->blockSize; - goto finish; - } - - if (context->doPad) { - if (context->multi) { - CK_ULONG finalLen; - /* padding is fairly complicated, have the update and final - * code deal with it */ - pk11_FreeSession(session); - crv = NSC_EncryptUpdate(hSession, pData, ulDataLen, pEncryptedData, - pulEncryptedDataLen); - if (crv != CKR_OK) - *pulEncryptedDataLen = 0; - maxoutlen -= *pulEncryptedDataLen; - pEncryptedData += *pulEncryptedDataLen; - finalLen = maxoutlen; - crv2 = NSC_EncryptFinal(hSession, pEncryptedData, &finalLen); - if (crv2 == CKR_OK) - *pulEncryptedDataLen += finalLen; - return crv == CKR_OK ? crv2 : crv; - } - /* doPad without multi means that padding must be done on the first - ** and only update. There will be no final. - */ - PORT_Assert(context->blockSize > 1); - if (context->blockSize > 1) { - CK_ULONG remainder = ulDataLen % context->blockSize; - CK_ULONG padding = context->blockSize - remainder; - pText.len += padding; - pText.data = PORT_ZAlloc(pText.len); - if (pText.data) { - memcpy(pText.data, pData, ulDataLen); - memset(pText.data + ulDataLen, padding, padding); - } else { - crv = CKR_HOST_MEMORY; - goto fail; - } - } - } - - /* do it: NOTE: this assumes buf size is big enough. */ - rv = (*context->update)(context->cipherInfo, pEncryptedData, - &outlen, maxoutlen, pText.data, pText.len); - crv = (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; - *pulEncryptedDataLen = (CK_ULONG) outlen; - if (pText.data != pData) - PORT_ZFree(pText.data, pText.len); -fail: - pk11_SetContextByType(session, PK11_ENCRYPT, NULL); - pk11_FreeContext(context); -finish: - pk11_FreeSession(session); - - return crv; -} - - -/* - ************** Crypto Functions: Decrypt ************************ - */ - -/* NSC_DecryptInit initializes a decryption operation. */ -CK_RV NSC_DecryptInit( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) -{ - return pk11_CryptInit(hSession, pMechanism, hKey, CKA_DECRYPT, - PK11_DECRYPT, PR_FALSE); -} - -/* NSC_DecryptUpdate continues a multiple-part decryption operation. */ -CK_RV NSC_DecryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) -{ - PK11SessionContext *context; - unsigned int padoutlen = 0; - unsigned int outlen; - unsigned int maxout = *pulPartLen; - CK_RV crv; - SECStatus rv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_DECRYPT,PR_TRUE,NULL); - if (crv != CKR_OK) return crv; - - if (context->doPad) { - /* first decrypt our saved buffer */ - if (context->padDataLength != 0) { - rv = (*context->update)(context->cipherInfo, pPart, &padoutlen, - maxout, context->padBuf, context->blockSize); - if (rv != SECSuccess) return CKR_DEVICE_ERROR; - pPart += padoutlen; - maxout -= padoutlen; - } - /* now save the final block for the next decrypt or the final */ - PORT_Memcpy(context->padBuf,&pEncryptedPart[ulEncryptedPartLen - - context->blockSize], context->blockSize); - context->padDataLength = context->blockSize; - ulEncryptedPartLen -= context->padDataLength; - } - - /* do it: NOTE: this assumes buf size in is >= buf size out! */ - rv = (*context->update)(context->cipherInfo,pPart, &outlen, - maxout, pEncryptedPart, ulEncryptedPartLen); - *pulPartLen = (CK_ULONG) (outlen + padoutlen); - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - - -/* NSC_DecryptFinal finishes a multiple-part decryption operation. */ -CK_RV NSC_DecryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastPart, CK_ULONG_PTR pulLastPartLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen; - unsigned int maxout = *pulLastPartLen; - CK_RV crv; - SECStatus rv = SECSuccess; - PRBool contextFinished = PR_TRUE; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_DECRYPT,PR_TRUE,&session); - if (crv != CKR_OK) return crv; - - *pulLastPartLen = 0; - if (!pLastPart) { - /* caller is checking the amount of remaining data */ - if (context->padDataLength > 0) { - *pulLastPartLen = 2 * context->blockSize; - contextFinished = PR_FALSE; /* still have padding to go */ - } - goto finish; - } - - if (context->doPad) { - /* decrypt our saved buffer */ - if (context->padDataLength != 0) { - /* this assumes that pLastPart is big enough to hold the *whole* - * buffer!!! */ - rv = (*context->update)(context->cipherInfo, pLastPart, &outlen, - maxout, context->padBuf, context->blockSize); - if (rv == SECSuccess) { - unsigned int padSize = - (unsigned int) pLastPart[context->blockSize-1]; - if ((padSize > context->blockSize) || (padSize == 0)) { - rv = SECFailure; - } else { - *pulLastPartLen = outlen - padSize; - } - } - } - } - -finish: - if (contextFinished) { - pk11_SetContextByType(session, PK11_DECRYPT, NULL); - pk11_FreeContext(context); - } - pk11_FreeSession(session); - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - -/* NSC_Decrypt decrypts encrypted data in a single part. */ -CK_RV NSC_Decrypt(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData,CK_ULONG ulEncryptedDataLen,CK_BYTE_PTR pData, - CK_ULONG_PTR pulDataLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen; - unsigned int maxoutlen = *pulDataLen; - CK_RV crv; - CK_RV crv2; - SECStatus rv = SECSuccess; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_DECRYPT,PR_FALSE,&session); - if (crv != CKR_OK) return crv; - - if (!pData) { - *pulDataLen = ulEncryptedDataLen + context->blockSize; - goto finish; - } - - if (context->doPad && context->multi) { - CK_ULONG finalLen; - /* padding is fairly complicated, have the update and final - * code deal with it */ - pk11_FreeSession(session); - crv = NSC_DecryptUpdate(hSession,pEncryptedData,ulEncryptedDataLen, - pData, pulDataLen); - if (crv != CKR_OK) - *pulDataLen = 0; - maxoutlen -= *pulDataLen; - pData += *pulDataLen; - finalLen = maxoutlen; - crv2 = NSC_DecryptFinal(hSession, pData, &finalLen); - if (crv2 == CKR_OK) - *pulDataLen += finalLen; - return crv == CKR_OK ? crv2 : crv; - } - - rv = (*context->update)(context->cipherInfo, pData, &outlen, maxoutlen, - pEncryptedData, ulEncryptedDataLen); - /* XXX need to do MUCH better error mapping than this. */ - crv = (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; - if (rv == SECSuccess && context->doPad) { - CK_ULONG padding = pData[outlen - 1]; - if (padding > context->blockSize || !padding) { - crv = CKR_ENCRYPTED_DATA_INVALID; - } else - outlen -= padding; - } - *pulDataLen = (CK_ULONG) outlen; - pk11_SetContextByType(session, PK11_DECRYPT, NULL); - pk11_FreeContext(context); -finish: - pk11_FreeSession(session); - return crv; -} - - - -/* - ************** Crypto Functions: Digest (HASH) ************************ - */ - -/* NSC_DigestInit initializes a message-digesting operation. */ -CK_RV NSC_DigestInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism) -{ - PK11Session *session; - PK11SessionContext *context; - CK_RV crv = CKR_OK; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) - return CKR_SESSION_HANDLE_INVALID; - crv = pk11_InitGeneric(session,&context,PK11_HASH,NULL,0,NULL, 0, 0); - if (crv != CKR_OK) { - pk11_FreeSession(session); - return crv; - } - - -#define INIT_MECH(mech,mmm) \ - case mech: { \ - mmm ## Context * mmm ## _ctx = mmm ## _NewContext(); \ - context->cipherInfo = (void *)mmm ## _ctx; \ - context->cipherInfoLen = mmm ## _FlattenSize(mmm ## _ctx); \ - context->currentMech = mech; \ - context->hashUpdate = (PK11Hash) mmm ## _Update; \ - context->end = (PK11End) mmm ## _End; \ - context->destroy = (PK11Destroy) mmm ## _DestroyContext; \ - context->maxLen = mmm ## _LENGTH; \ - if (mmm ## _ctx) \ - mmm ## _Begin(mmm ## _ctx); \ - else \ - crv = CKR_HOST_MEMORY; \ - break; \ - } - - switch(pMechanism->mechanism) { - INIT_MECH(CKM_MD2, MD2) - INIT_MECH(CKM_MD5, MD5) - INIT_MECH(CKM_SHA_1, SHA1) - INIT_MECH(CKM_SHA256, SHA256) - INIT_MECH(CKM_SHA384, SHA384) - INIT_MECH(CKM_SHA512, SHA512) - - default: - crv = CKR_MECHANISM_INVALID; - break; - } - - if (crv != CKR_OK) { - pk11_FreeContext(context); - pk11_FreeSession(session); - return crv; - } - pk11_SetContextByType(session, PK11_HASH, context); - pk11_FreeSession(session); - return CKR_OK; -} - - -/* NSC_Digest digests data in a single part. */ -CK_RV NSC_Digest(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int digestLen; - unsigned int maxout = *pulDigestLen; - CK_RV crv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_HASH,PR_FALSE,&session); - if (crv != CKR_OK) return crv; - - if (pDigest == NULL) { - *pulDigestLen = context->maxLen; - goto finish; - } - - /* do it: */ - (*context->hashUpdate)(context->cipherInfo, pData, ulDataLen); - /* NOTE: this assumes buf size is bigenough for the algorithm */ - (*context->end)(context->cipherInfo, pDigest, &digestLen,maxout); - *pulDigestLen = digestLen; - - pk11_SetContextByType(session, PK11_HASH, NULL); - pk11_FreeContext(context); -finish: - pk11_FreeSession(session); - return CKR_OK; -} - - -/* NSC_DigestUpdate continues a multiple-part message-digesting operation. */ -CK_RV NSC_DigestUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG ulPartLen) -{ - PK11SessionContext *context; - CK_RV crv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_HASH,PR_TRUE,NULL); - if (crv != CKR_OK) return crv; - /* do it: */ - (*context->hashUpdate)(context->cipherInfo, pPart, ulPartLen); - return CKR_OK; -} - - -/* NSC_DigestFinal finishes a multiple-part message-digesting operation. */ -CK_RV NSC_DigestFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int maxout = *pulDigestLen; - unsigned int digestLen; - CK_RV crv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession, &context, PK11_HASH, PR_TRUE, &session); - if (crv != CKR_OK) return crv; - - if (pDigest != NULL) { - (*context->end)(context->cipherInfo, pDigest, &digestLen, maxout); - *pulDigestLen = digestLen; - pk11_SetContextByType(session, PK11_HASH, NULL); - pk11_FreeContext(context); - } else { - *pulDigestLen = context->maxLen; - } - - pk11_FreeSession(session); - return CKR_OK; -} - -/* - * these helper functions are used by Generic Macing and Signing functions - * that use hashes as part of their operations. - */ -#define DOSUB(mmm) \ -static CK_RV \ -pk11_doSub ## mmm(PK11SessionContext *context) { \ - mmm ## Context * mmm ## _ctx = mmm ## _NewContext(); \ - context->hashInfo = (void *) mmm ## _ctx; \ - context->hashUpdate = (PK11Hash) mmm ## _Update; \ - context->end = (PK11End) mmm ## _End; \ - context->hashdestroy = (PK11Destroy) mmm ## _DestroyContext; \ - if (!context->hashInfo) { \ - return CKR_HOST_MEMORY; \ - } \ - mmm ## _Begin( mmm ## _ctx ); \ - return CKR_OK; \ -} - -DOSUB(MD2) -DOSUB(MD5) -DOSUB(SHA1) -DOSUB(SHA256) -DOSUB(SHA384) -DOSUB(SHA512) - -/* - * HMAC General copies only a portion of the result. This update routine likes - * the final HMAC output with the signature. - */ -static SECStatus -pk11_HMACCopy(CK_ULONG *copyLen,unsigned char *sig,unsigned int *sigLen, - unsigned int maxLen,unsigned char *hash, unsigned int hashLen) -{ - if (maxLen < *copyLen) return SECFailure; - PORT_Memcpy(sig,hash,*copyLen); - *sigLen = *copyLen; - return SECSuccess; -} - -/* Verify is just a compare for HMAC */ -static SECStatus -pk11_HMACCmp(CK_ULONG *copyLen,unsigned char *sig,unsigned int sigLen, - unsigned char *hash, unsigned int hashLen) -{ - return PORT_Memcmp(sig,hash,*copyLen) ? SECSuccess : SECFailure ; -} - -/* - * common HMAC initalization routine - */ -static CK_RV -pk11_doHMACInit(PK11SessionContext *context,HASH_HashType hash, - PK11Object *key, CK_ULONG mac_size) -{ - PK11Attribute *keyval; - HMACContext *HMACcontext; - CK_ULONG *intpointer; - const SECHashObject *hashObj = &SECRawHashObjects[hash]; - PRBool isFIPS = (key->slot->slotID == FIPS_SLOT_ID); - - /* required by FIPS 198 Section 4 */ - if (isFIPS && (mac_size < 4 || mac_size < hashObj->length/2)) { - return CKR_BUFFER_TOO_SMALL; - } - - keyval = pk11_FindAttribute(key,CKA_VALUE); - if (keyval == NULL) return CKR_KEY_SIZE_RANGE; - - HMACcontext = HMAC_Create(hashObj, - (const unsigned char*)keyval->attrib.pValue, - keyval->attrib.ulValueLen, isFIPS); - context->hashInfo = HMACcontext; - context->multi = PR_TRUE; - pk11_FreeAttribute(keyval); - if (context->hashInfo == NULL) { - if (PORT_GetError() == SEC_ERROR_INVALID_ARGS) { - return CKR_KEY_SIZE_RANGE; - } - return CKR_HOST_MEMORY; - } - context->hashUpdate = (PK11Hash) HMAC_Update; - context->end = (PK11End) HMAC_Finish; - - context->hashdestroy = (PK11Destroy) pk11_HMAC_Destroy; - intpointer = (CK_ULONG *) PORT_Alloc(sizeof(CK_ULONG)); - if (intpointer == NULL) { - return CKR_HOST_MEMORY; - } - *intpointer = mac_size; - context->cipherInfo = (void *) intpointer; - context->destroy = (PK11Destroy) pk11_Space; - context->update = (PK11Cipher) pk11_HMACCopy; - context->verify = (PK11Verify) pk11_HMACCmp; - context->maxLen = hashObj->length; - HMAC_Begin(HMACcontext); - return CKR_OK; -} - -/* - * SSL Macing support. SSL Macs are inited, then update with the base - * hashing algorithm, then finalized in sign and verify - */ - -/* - * FROM SSL: - * 60 bytes is 3 times the maximum length MAC size that is supported. - * We probably should have one copy of this table. We still need this table - * in ssl to 'sign' the handshake hashes. - */ -static unsigned char ssl_pad_1 [60] = { - 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, - 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, - 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, - 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, - 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, - 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, - 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, - 0x36, 0x36, 0x36, 0x36 -}; -static unsigned char ssl_pad_2 [60] = { - 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, - 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, - 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, - 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, - 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, - 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, - 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, - 0x5c, 0x5c, 0x5c, 0x5c -}; - -static SECStatus -pk11_SSLMACSign(PK11SSLMACInfo *info,unsigned char *sig,unsigned int *sigLen, - unsigned int maxLen,unsigned char *hash, unsigned int hashLen) -{ - unsigned char tmpBuf[PK11_MAX_MAC_LENGTH]; - unsigned int out; - - info->begin(info->hashContext); - info->update(info->hashContext,info->key,info->keySize); - info->update(info->hashContext,ssl_pad_2,info->padSize); - info->update(info->hashContext,hash,hashLen); - info->end(info->hashContext,tmpBuf,&out,PK11_MAX_MAC_LENGTH); - PORT_Memcpy(sig,tmpBuf,info->macSize); - *sigLen = info->macSize; - return SECSuccess; -} - -static SECStatus -pk11_SSLMACVerify(PK11SSLMACInfo *info,unsigned char *sig,unsigned int sigLen, - unsigned char *hash, unsigned int hashLen) -{ - unsigned char tmpBuf[PK11_MAX_MAC_LENGTH]; - unsigned int out; - - info->begin(info->hashContext); - info->update(info->hashContext,info->key,info->keySize); - info->update(info->hashContext,ssl_pad_2,info->padSize); - info->update(info->hashContext,hash,hashLen); - info->end(info->hashContext,tmpBuf,&out,PK11_MAX_MAC_LENGTH); - return (PORT_Memcmp(sig,tmpBuf,info->macSize) == 0) ? - SECSuccess : SECFailure; -} - -/* - * common HMAC initalization routine - */ -static CK_RV -pk11_doSSLMACInit(PK11SessionContext *context,SECOidTag oid, - PK11Object *key, CK_ULONG mac_size) -{ - PK11Attribute *keyval; - PK11Begin begin; - int padSize; - PK11SSLMACInfo *sslmacinfo; - CK_RV crv = CKR_MECHANISM_INVALID; - - if (oid == SEC_OID_SHA1) { - crv = pk11_doSubSHA1(context); - if (crv != CKR_OK) return crv; - begin = (PK11Begin) SHA1_Begin; - padSize = 40; - } else { - crv = pk11_doSubMD5(context); - if (crv != CKR_OK) return crv; - begin = (PK11Begin) MD5_Begin; - padSize = 48; - } - context->multi = PR_TRUE; - - keyval = pk11_FindAttribute(key,CKA_VALUE); - if (keyval == NULL) return CKR_KEY_SIZE_RANGE; - - context->hashUpdate(context->hashInfo,keyval->attrib.pValue, - keyval->attrib.ulValueLen); - context->hashUpdate(context->hashInfo,ssl_pad_1,padSize); - sslmacinfo = (PK11SSLMACInfo *) PORT_Alloc(sizeof(PK11SSLMACInfo)); - if (sslmacinfo == NULL) { - pk11_FreeAttribute(keyval); - return CKR_HOST_MEMORY; - } - sslmacinfo->macSize = mac_size; - sslmacinfo->hashContext = context->hashInfo; - PORT_Memcpy(sslmacinfo->key,keyval->attrib.pValue, - keyval->attrib.ulValueLen); - sslmacinfo->keySize = keyval->attrib.ulValueLen; - sslmacinfo->begin = begin; - sslmacinfo->end = context->end; - sslmacinfo->update = context->hashUpdate; - sslmacinfo->padSize = padSize; - pk11_FreeAttribute(keyval); - context->cipherInfo = (void *) sslmacinfo; - context->destroy = (PK11Destroy) pk11_Space; - context->update = (PK11Cipher) pk11_SSLMACSign; - context->verify = (PK11Verify) pk11_SSLMACVerify; - context->maxLen = mac_size; - return CKR_OK; -} - -/* - ************** Crypto Functions: Sign ************************ - */ - -/* - * Check if We're using CBCMacing and initialize the session context if we are. - */ -static CK_RV -pk11_InitCBCMac(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey, CK_ATTRIBUTE_TYPE keyUsage, - PK11ContextType contextType) - -{ - CK_MECHANISM cbc_mechanism; - CK_ULONG mac_bytes = PK11_INVALID_MAC_SIZE; - CK_RC2_CBC_PARAMS rc2_params; -#if NSS_SOFTOKEN_DOES_RC5 - CK_RC5_CBC_PARAMS rc5_params; - CK_RC5_MAC_GENERAL_PARAMS *rc5_mac; -#endif - unsigned char ivBlock[PK11_MAX_BLOCK_SIZE]; - PK11SessionContext *context; - CK_RV crv; - int blockSize; - - switch (pMechanism->mechanism) { - case CKM_RC2_MAC_GENERAL: - mac_bytes = - ((CK_RC2_MAC_GENERAL_PARAMS *)pMechanism->pParameter)->ulMacLength; - /* fall through */ - case CKM_RC2_MAC: - /* this works because ulEffectiveBits is in the same place in both the - * CK_RC2_MAC_GENERAL_PARAMS and CK_RC2_CBC_PARAMS */ - rc2_params.ulEffectiveBits = ((CK_RC2_MAC_GENERAL_PARAMS *) - pMechanism->pParameter)->ulEffectiveBits; - PORT_Memset(rc2_params.iv,0,sizeof(rc2_params.iv)); - cbc_mechanism.mechanism = CKM_RC2_CBC; - cbc_mechanism.pParameter = &rc2_params; - cbc_mechanism.ulParameterLen = sizeof(rc2_params); - blockSize = 8; - break; -#if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_MAC_GENERAL: - mac_bytes = - ((CK_RC5_MAC_GENERAL_PARAMS *)pMechanism->pParameter)->ulMacLength; - /* fall through */ - case CKM_RC5_MAC: - /* this works because ulEffectiveBits is in the same place in both the - * CK_RC5_MAC_GENERAL_PARAMS and CK_RC5_CBC_PARAMS */ - rc5_mac = (CK_RC5_MAC_GENERAL_PARAMS *)pMechanism->pParameter; - rc5_params.ulWordsize = rc5_mac->ulWordsize; - rc5_params.ulRounds = rc5_mac->ulRounds; - rc5_params.pIv = ivBlock; - blockSize = rc5_mac->ulWordsize*2; - rc5_params.ulIvLen = blockSize; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_RC5_CBC; - cbc_mechanism.pParameter = &rc5_params; - cbc_mechanism.ulParameterLen = sizeof(rc5_params); - break; -#endif - /* add cast and idea later */ - case CKM_DES_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_DES_MAC: - blockSize = 8; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_DES_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_DES3_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_DES3_MAC: - blockSize = 8; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_DES3_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_CDMF_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_CDMF_MAC: - blockSize = 8; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_CDMF_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_AES_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_AES_MAC: - blockSize = 16; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_AES_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - default: - return CKR_FUNCTION_NOT_SUPPORTED; - } - - crv = pk11_CryptInit(hSession, &cbc_mechanism, hKey, keyUsage, - contextType, PR_TRUE); - if (crv != CKR_OK) return crv; - crv = pk11_GetContext(hSession,&context,contextType,PR_TRUE,NULL); - - /* this shouldn't happen! */ - PORT_Assert(crv == CKR_OK); - if (crv != CKR_OK) return crv; - context->blockSize = blockSize; - if (mac_bytes == PK11_INVALID_MAC_SIZE) mac_bytes = blockSize/2; - context->macSize = mac_bytes; - return CKR_OK; -} - -/* - * encode RSA PKCS #1 Signature data before signing... - */ -static SECStatus -pk11_HashSign(PK11HashSignInfo *info,unsigned char *sig,unsigned int *sigLen, - unsigned int maxLen,unsigned char *hash, unsigned int hashLen) -{ - - SECStatus rv = SECFailure; - SECItem digder; - PLArenaPool *arena = NULL; - SGNDigestInfo *di = NULL; - - digder.data = NULL; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { goto loser; } - - /* Construct digest info */ - di = SGN_CreateDigestInfo(info->hashOid, hash, hashLen); - if (!di) { goto loser; } - - /* Der encode the digest as a DigestInfo */ - rv = DER_Encode(arena, &digder, SGNDigestInfoTemplate, di); - if (rv != SECSuccess) { - goto loser; - } - - /* - ** Encrypt signature after constructing appropriate PKCS#1 signature - ** block - */ - rv = RSA_Sign(info->key,sig,sigLen,maxLen,digder.data,digder.len); - - loser: - SGN_DestroyDigestInfo(di); - if (arena != NULL) { - PORT_FreeArena(arena, PR_FALSE); - } - return rv; -} - -static SECStatus -nsc_DSA_Verify_Stub(void *ctx, void *sigBuf, unsigned int sigLen, - void *dataBuf, unsigned int dataLen) -{ - SECItem signature, digest; - NSSLOWKEYPublicKey *key = (NSSLOWKEYPublicKey *)ctx; - - signature.data = (unsigned char *)sigBuf; - signature.len = sigLen; - digest.data = (unsigned char *)dataBuf; - digest.len = dataLen; - return DSA_VerifyDigest(&(key->u.dsa), &signature, &digest); -} - -static SECStatus -nsc_DSA_Sign_Stub(void *ctx, void *sigBuf, - unsigned int *sigLen, unsigned int maxSigLen, - void *dataBuf, unsigned int dataLen) -{ - SECItem signature = { 0 }, digest; - SECStatus rv; - NSSLOWKEYPrivateKey *key = (NSSLOWKEYPrivateKey *)ctx; - - (void)SECITEM_AllocItem(NULL, &signature, maxSigLen); - digest.data = (unsigned char *)dataBuf; - digest.len = dataLen; - rv = DSA_SignDigest(&(key->u.dsa), &signature, &digest); - *sigLen = signature.len; - PORT_Memcpy(sigBuf, signature.data, signature.len); - SECITEM_FreeItem(&signature, PR_FALSE); - return rv; -} - -#ifdef NSS_ENABLE_ECC -static SECStatus -nsc_ECDSAVerifyStub(void *ctx, void *sigBuf, unsigned int sigLen, - void *dataBuf, unsigned int dataLen) -{ - SECItem signature, digest; - NSSLOWKEYPublicKey *key = (NSSLOWKEYPublicKey *)ctx; - - signature.data = (unsigned char *)sigBuf; - signature.len = sigLen; - digest.data = (unsigned char *)dataBuf; - digest.len = dataLen; - return ECDSA_VerifyDigest(&(key->u.ec), &signature, &digest); -} - -static SECStatus -nsc_ECDSASignStub(void *ctx, void *sigBuf, - unsigned int *sigLen, unsigned int maxSigLen, - void *dataBuf, unsigned int dataLen) -{ - SECItem signature = { 0 }, digest; - SECStatus rv; - NSSLOWKEYPrivateKey *key = (NSSLOWKEYPrivateKey *)ctx; - - (void)SECITEM_AllocItem(NULL, &signature, maxSigLen); - digest.data = (unsigned char *)dataBuf; - digest.len = dataLen; - rv = ECDSA_SignDigest(&(key->u.ec), &signature, &digest); - *sigLen = signature.len; - PORT_Memcpy(sigBuf, signature.data, signature.len); - SECITEM_FreeItem(&signature, PR_FALSE); - return rv; -} -#endif /* NSS_ENABLE_ECC */ - -/* NSC_SignInit setups up the signing operations. There are three basic - * types of signing: - * (1) the tradition single part, where "Raw RSA" or "Raw DSA" is applied - * to data in a single Sign operation (which often looks a lot like an - * encrypt, with data coming in and data going out). - * (2) Hash based signing, where we continually hash the data, then apply - * some sort of signature to the end. - * (3) Block Encryption CBC MAC's, where the Data is encrypted with a key, - * and only the final block is part of the mac. - * - * For case number 3, we initialize a context much like the Encryption Context - * (in fact we share code). We detect case 3 in C_SignUpdate, C_Sign, and - * C_Final by the following method... if it's not multi-part, and it's doesn't - * have a hash context, it must be a block Encryption CBC MAC. - * - * For case number 2, we initialize a hash structure, as well as make it - * multi-part. Updates are simple calls to the hash update function. Final - * calls the hashend, then passes the result to the 'update' function (which - * operates as a final signature function). In some hash based MAC'ing (as - * opposed to hash base signatures), the update function is can be simply a - * copy (as is the case with HMAC). - */ -CK_RV NSC_SignInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) -{ - PK11Session *session; - PK11Object *key; - PK11SessionContext *context; - CK_KEY_TYPE key_type; - CK_RV crv = CKR_OK; - NSSLOWKEYPrivateKey *privKey; - PK11HashSignInfo *info = NULL; - - /* Block Cipher MACing Algorithms use a different Context init method..*/ - crv = pk11_InitCBCMac(hSession, pMechanism, hKey, CKA_SIGN, PK11_SIGN); - if (crv != CKR_FUNCTION_NOT_SUPPORTED) return crv; - - /* we're not using a block cipher mac */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - crv = pk11_InitGeneric(session,&context,PK11_SIGN,&key,hKey,&key_type, - CKO_PRIVATE_KEY,CKA_SIGN); - if (crv != CKR_OK) { - pk11_FreeSession(session); - return crv; - } - - context->multi = PR_FALSE; - -#define INIT_RSA_SIGN_MECH(mmm) \ - case CKM_ ## mmm ## _RSA_PKCS: \ - context->multi = PR_TRUE; \ - crv = pk11_doSub ## mmm (context); \ - if (crv != CKR_OK) break; \ - context->update = (PK11Cipher) pk11_HashSign; \ - info = PORT_New(PK11HashSignInfo); \ - if (info == NULL) { crv = CKR_HOST_MEMORY; break; } \ - info->hashOid = SEC_OID_ ## mmm ; \ - goto finish_rsa; - - switch(pMechanism->mechanism) { - INIT_RSA_SIGN_MECH(MD5) - INIT_RSA_SIGN_MECH(MD2) - INIT_RSA_SIGN_MECH(SHA1) - INIT_RSA_SIGN_MECH(SHA256) - INIT_RSA_SIGN_MECH(SHA384) - INIT_RSA_SIGN_MECH(SHA512) - - case CKM_RSA_PKCS: - context->update = (PK11Cipher) RSA_Sign; - goto finish_rsa; - case CKM_RSA_X_509: - context->update = (PK11Cipher) RSA_SignRaw; -finish_rsa: - if (key_type != CKK_RSA) { - if (info) PORT_Free(info); - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - privKey = pk11_GetPrivKey(key,CKK_RSA,&crv); - if (privKey == NULL) { - if (info) PORT_Free(info); - break; - } - /* OK, info is allocated only if we're doing hash and sign mechanism. - * It's necessary to be able to set the correct OID in the final - * signature. - */ - if (info) { - info->key = privKey; - context->cipherInfo = info; - context->destroy = (PK11Destroy)pk11_Space; - } else { - context->cipherInfo = privKey; - context->destroy = (PK11Destroy)pk11_Null; - } - context->maxLen = nsslowkey_PrivateModulusLen(privKey); - break; - - case CKM_DSA_SHA1: - context->multi = PR_TRUE; - crv = pk11_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_DSA: - if (key_type != CKK_DSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - privKey = pk11_GetPrivKey(key,CKK_DSA,&crv); - if (privKey == NULL) { - break; - } - context->cipherInfo = privKey; - context->update = (PK11Cipher) nsc_DSA_Sign_Stub; - context->destroy = (privKey == key->objectInfo) ? - (PK11Destroy) pk11_Null:(PK11Destroy)pk11_FreePrivKey; - context->maxLen = DSA_SIGNATURE_LEN; - - break; - -#ifdef NSS_ENABLE_ECC - case CKM_ECDSA_SHA1: - context->multi = PR_TRUE; - crv = pk11_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_ECDSA: - if (key_type != CKK_EC) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - privKey = pk11_GetPrivKey(key,CKK_EC,&crv); - if (privKey == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->cipherInfo = privKey; - context->update = (PK11Cipher) nsc_ECDSASignStub; - context->destroy = (privKey == key->objectInfo) ? - (PK11Destroy) pk11_Null:(PK11Destroy)pk11_FreePrivKey; - context->maxLen = MAX_ECKEY_LEN * 2; - - break; -#endif /* NSS_ENABLE_ECC */ - -#define INIT_HMAC_MECH(mmm) \ - case CKM_ ## mmm ## _HMAC_GENERAL: \ - crv = pk11_doHMACInit(context, HASH_Alg ## mmm ,key, \ - *(CK_ULONG *)pMechanism->pParameter); \ - break; \ - case CKM_ ## mmm ## _HMAC: \ - crv = pk11_doHMACInit(context, HASH_Alg ## mmm ,key, mmm ## _LENGTH); \ - break; - - INIT_HMAC_MECH(MD2) - INIT_HMAC_MECH(MD5) - INIT_HMAC_MECH(SHA256) - INIT_HMAC_MECH(SHA384) - INIT_HMAC_MECH(SHA512) - - case CKM_SHA_1_HMAC_GENERAL: - crv = pk11_doHMACInit(context,HASH_AlgSHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SHA_1_HMAC: - crv = pk11_doHMACInit(context,HASH_AlgSHA1,key,SHA1_LENGTH); - break; - - case CKM_SSL3_MD5_MAC: - crv = pk11_doSSLMACInit(context,SEC_OID_MD5,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SSL3_SHA1_MAC: - crv = pk11_doSSLMACInit(context,SEC_OID_SHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_TLS_PRF_GENERAL: - crv = pk11_TLSPRFInit(context, key, key_type); - break; - default: - crv = CKR_MECHANISM_INVALID; - break; - } - - if (crv != CKR_OK) { - pk11_FreeContext(context); - pk11_FreeSession(session); - return crv; - } - pk11_SetContextByType(session, PK11_SIGN, context); - pk11_FreeSession(session); - return CKR_OK; -} - - -/* MACUpdate is the common implementation for SignUpdate and VerifyUpdate. - * (sign and verify only very in their setup and final operations) */ -static CK_RV -pk11_MACUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG ulPartLen,PK11ContextType type) -{ - unsigned int outlen; - PK11SessionContext *context; - CK_RV crv; - SECStatus rv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,type,PR_FALSE,NULL); - if (crv != CKR_OK) return crv; - - if (context->hashInfo) { - (*context->hashUpdate)(context->hashInfo, pPart, ulPartLen); - return CKR_OK; - } - - /* must be block cipher macing */ - - /* deal with previous buffered data */ - if (context->padDataLength != 0) { - int i; - /* fill in the padded to a full block size */ - for (i=context->padDataLength; (ulPartLen != 0) && - i < (int)context->blockSize; i++) { - context->padBuf[i] = *pPart++; - ulPartLen--; - context->padDataLength++; - } - - /* not enough data to encrypt yet? then return */ - if (context->padDataLength != context->blockSize) return CKR_OK; - /* encrypt the current padded data */ - rv = (*context->update)(context->cipherInfo,context->macBuf,&outlen, - PK11_MAX_BLOCK_SIZE,context->padBuf,context->blockSize); - if (rv != SECSuccess) return CKR_DEVICE_ERROR; - } - - /* save the residual */ - context->padDataLength = ulPartLen % context->blockSize; - if (context->padDataLength) { - PORT_Memcpy(context->padBuf, - &pPart[ulPartLen-context->padDataLength], - context->padDataLength); - ulPartLen -= context->padDataLength; - } - - /* if we've exhausted our new buffer, we're done */ - if (ulPartLen == 0) { return CKR_OK; } - - /* run the data through out encrypter */ - while (ulPartLen) { - rv = (*context->update)(context->cipherInfo, context->padBuf, &outlen, - PK11_MAX_BLOCK_SIZE, pPart, context->blockSize); - if (rv != SECSuccess) return CKR_DEVICE_ERROR; - /* paranoia.. make sure we exit the loop */ - PORT_Assert(ulPartLen >= context->blockSize); - if (ulPartLen < context->blockSize) break; - ulPartLen -= context->blockSize; - } - - return CKR_OK; - -} - -/* NSC_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature */ -CK_RV NSC_SignUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG ulPartLen) -{ - return pk11_MACUpdate(hSession, pPart, ulPartLen, PK11_SIGN); -} - - -/* NSC_SignFinal finishes a multiple-part signature operation, - * returning the signature. */ -CK_RV NSC_SignFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen; - unsigned int digestLen; - unsigned int maxoutlen = *pulSignatureLen; - unsigned char tmpbuf[PK11_MAX_MAC_LENGTH]; - CK_RV crv; - SECStatus rv = SECSuccess; - - /* make sure we're legal */ - *pulSignatureLen = 0; - crv = pk11_GetContext(hSession,&context,PK11_SIGN,PR_TRUE,&session); - if (crv != CKR_OK) return crv; - - if (!pSignature) { - *pulSignatureLen = context->maxLen; - goto finish; - } else if (context->hashInfo) { - (*context->end)(context->hashInfo, tmpbuf, &digestLen, sizeof(tmpbuf)); - rv = (*context->update)(context->cipherInfo, pSignature, - &outlen, maxoutlen, tmpbuf, digestLen); - *pulSignatureLen = (CK_ULONG) outlen; - } else { - /* deal with the last block if any residual */ - if (context->padDataLength) { - /* fill out rest of pad buffer with pad magic*/ - int i; - for (i=context->padDataLength; i < (int)context->blockSize; i++) { - context->padBuf[i] = 0; - } - rv = (*context->update)(context->cipherInfo,context->macBuf, - &outlen,PK11_MAX_BLOCK_SIZE,context->padBuf,context->blockSize); - } - if (rv == SECSuccess) { - PORT_Memcpy(pSignature,context->macBuf,context->macSize); - *pulSignatureLen = context->macSize; - } - } - - pk11_FreeContext(context); - pk11_SetContextByType(session, PK11_SIGN, NULL); - -finish: - pk11_FreeSession(session); - - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - -/* NSC_Sign signs (encrypts with private key) data in a single part, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature */ -CK_RV NSC_Sign(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData,CK_ULONG ulDataLen,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen; - unsigned int maxoutlen = *pulSignatureLen; - CK_RV crv,crv2; - SECStatus rv = SECSuccess; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_SIGN,PR_FALSE,&session); - if (crv != CKR_OK) return crv; - - if (!pSignature) { - *pulSignatureLen = context->maxLen; - goto finish; - } - - /* multi part Signing are completely implemented by SignUpdate and - * sign Final */ - if (context->multi) { - pk11_FreeSession(session); - crv = NSC_SignUpdate(hSession,pData,ulDataLen); - if (crv != CKR_OK) *pulSignatureLen = 0; - crv2 = NSC_SignFinal(hSession, pSignature, pulSignatureLen); - return crv == CKR_OK ? crv2 :crv; - } - - rv = (*context->update)(context->cipherInfo, pSignature, - &outlen, maxoutlen, pData, ulDataLen); - *pulSignatureLen = (CK_ULONG) outlen; - pk11_FreeContext(context); - pk11_SetContextByType(session, PK11_SIGN, NULL); - -finish: - pk11_FreeSession(session); - - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - - -/* - ************** Crypto Functions: Sign Recover ************************ - */ -/* NSC_SignRecoverInit initializes a signature operation, - * where the (digest) data can be recovered from the signature. - * E.g. encryption with the user's private key */ -CK_RV NSC_SignRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) -{ - switch (pMechanism->mechanism) { - case CKM_RSA_PKCS: - case CKM_RSA_X_509: - return NSC_SignInit(hSession,pMechanism,hKey); - default: - break; - } - return CKR_MECHANISM_INVALID; -} - - -/* NSC_SignRecover signs data in a single operation - * where the (digest) data can be recovered from the signature. - * E.g. encryption with the user's private key */ -CK_RV NSC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) -{ - return NSC_Sign(hSession,pData,ulDataLen,pSignature,pulSignatureLen); -} - -/* - ************** Crypto Functions: verify ************************ - */ - -/* Handle RSA Signature formating */ -static SECStatus -pk11_hashCheckSign(PK11HashVerifyInfo *info, unsigned char *sig, - unsigned int sigLen, unsigned char *digest, unsigned int digestLen) -{ - - SECItem it; - SGNDigestInfo *di = NULL; - SECStatus rv = SECSuccess; - - it.data = NULL; - - if (info->key == NULL) goto loser; - - it.len = nsslowkey_PublicModulusLen(info->key); - if (!it.len) goto loser; - - it.data = (unsigned char *) PORT_Alloc(it.len); - if (it.data == NULL) goto loser; - - /* decrypt the block */ - rv = RSA_CheckSignRecover(info->key, it.data, &it.len, it.len, sig, sigLen); - if (rv != SECSuccess) goto loser; - - di = SGN_DecodeDigestInfo(&it); - if (di == NULL) goto loser; - if (di->digest.len != digestLen) goto loser; - - /* make sure the tag is OK */ - if (SECOID_GetAlgorithmTag(&di->digestAlgorithm) != info->hashOid) { - goto loser; - } - /* Now check the signature */ - if (PORT_Memcmp(digest, di->digest.data, di->digest.len) == 0) { - goto done; - } - - loser: - rv = SECFailure; - - done: - if (it.data != NULL) PORT_Free(it.data); - if (di != NULL) SGN_DestroyDigestInfo(di); - - return rv; -} - -/* NSC_VerifyInit initializes a verification operation, - * where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature (e.g. DSA) */ -CK_RV NSC_VerifyInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) -{ - PK11Session *session; - PK11Object *key; - PK11SessionContext *context; - CK_KEY_TYPE key_type; - CK_RV crv = CKR_OK; - NSSLOWKEYPublicKey *pubKey; - PK11HashVerifyInfo *info = NULL; - - /* Block Cipher MACing Algorithms use a different Context init method..*/ - crv = pk11_InitCBCMac(hSession, pMechanism, hKey, CKA_VERIFY, PK11_VERIFY); - if (crv != CKR_FUNCTION_NOT_SUPPORTED) return crv; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - crv = pk11_InitGeneric(session,&context,PK11_VERIFY,&key,hKey,&key_type, - CKO_PUBLIC_KEY,CKA_VERIFY); - if (crv != CKR_OK) { - pk11_FreeSession(session); - return crv; - } - - context->multi = PR_FALSE; - -#define INIT_RSA_VFY_MECH(mmm) \ - case CKM_ ## mmm ## _RSA_PKCS: \ - context->multi = PR_TRUE; \ - crv = pk11_doSub ## mmm (context); \ - if (crv != CKR_OK) break; \ - context->verify = (PK11Verify) pk11_hashCheckSign; \ - info = PORT_New(PK11HashVerifyInfo); \ - if (info == NULL) { crv = CKR_HOST_MEMORY; break; } \ - info->hashOid = SEC_OID_ ## mmm ; \ - goto finish_rsa; - - switch(pMechanism->mechanism) { - INIT_RSA_VFY_MECH(MD5) - INIT_RSA_VFY_MECH(MD2) - INIT_RSA_VFY_MECH(SHA1) - INIT_RSA_VFY_MECH(SHA256) - INIT_RSA_VFY_MECH(SHA384) - INIT_RSA_VFY_MECH(SHA512) - - case CKM_RSA_PKCS: - context->verify = (PK11Verify) RSA_CheckSign; - goto finish_rsa; - case CKM_RSA_X_509: - context->verify = (PK11Verify) RSA_CheckSignRaw; -finish_rsa: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - pubKey = pk11_GetPubKey(key,CKK_RSA,&crv); - if (pubKey == NULL) { - break; - } - if (info) { - info->key = pubKey; - context->cipherInfo = info; - context->destroy = pk11_Space; - } else { - context->cipherInfo = pubKey; - context->destroy = pk11_Null; - } - break; - case CKM_DSA_SHA1: - context->multi = PR_TRUE; - crv = pk11_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_DSA: - if (key_type != CKK_DSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - pubKey = pk11_GetPubKey(key,CKK_DSA,&crv); - if (pubKey == NULL) { - break; - } - context->cipherInfo = pubKey; - context->verify = (PK11Verify) nsc_DSA_Verify_Stub; - context->destroy = pk11_Null; - break; -#ifdef NSS_ENABLE_ECC - case CKM_ECDSA_SHA1: - context->multi = PR_TRUE; - crv = pk11_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_ECDSA: - if (key_type != CKK_EC) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->multi = PR_FALSE; - pubKey = pk11_GetPubKey(key,CKK_EC,&crv); - if (pubKey == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->cipherInfo = pubKey; - context->verify = (PK11Verify) nsc_ECDSAVerifyStub; - context->destroy = pk11_Null; - break; -#endif /* NSS_ENABLE_ECC */ - - INIT_HMAC_MECH(MD2) - INIT_HMAC_MECH(MD5) - INIT_HMAC_MECH(SHA256) - INIT_HMAC_MECH(SHA384) - INIT_HMAC_MECH(SHA512) - - case CKM_SHA_1_HMAC_GENERAL: - crv = pk11_doHMACInit(context,HASH_AlgSHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SHA_1_HMAC: - crv = pk11_doHMACInit(context,HASH_AlgSHA1,key,SHA1_LENGTH); - break; - - case CKM_SSL3_MD5_MAC: - crv = pk11_doSSLMACInit(context,SEC_OID_MD5,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SSL3_SHA1_MAC: - crv = pk11_doSSLMACInit(context,SEC_OID_SHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_TLS_PRF_GENERAL: - crv = pk11_TLSPRFInit(context, key, key_type); - break; - - default: - crv = CKR_MECHANISM_INVALID; - break; - } - - if (crv != CKR_OK) { - PORT_Free(context); - pk11_FreeSession(session); - return crv; - } - pk11_SetContextByType(session, PK11_VERIFY, context); - pk11_FreeSession(session); - return CKR_OK; -} - -/* NSC_Verify verifies a signature in a single-part operation, - * where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature */ -CK_RV NSC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) -{ - PK11Session *session; - PK11SessionContext *context; - CK_RV crv; - SECStatus rv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_VERIFY,PR_FALSE,&session); - if (crv != CKR_OK) return crv; - - rv = (*context->verify)(context->cipherInfo,pSignature, ulSignatureLen, - pData, ulDataLen); - pk11_FreeContext(context); - pk11_SetContextByType(session, PK11_VERIFY, NULL); - pk11_FreeSession(session); - - return (rv == SECSuccess) ? CKR_OK : CKR_SIGNATURE_INVALID; - -} - - -/* NSC_VerifyUpdate continues a multiple-part verification operation, - * where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature */ -CK_RV NSC_VerifyUpdate( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen) -{ - return pk11_MACUpdate(hSession, pPart, ulPartLen, PK11_VERIFY); -} - - -/* NSC_VerifyFinal finishes a multiple-part verification operation, - * checking the signature. */ -CK_RV NSC_VerifyFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG ulSignatureLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen; - unsigned int digestLen; - unsigned char tmpbuf[PK11_MAX_MAC_LENGTH]; - CK_RV crv; - SECStatus rv = SECSuccess; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_VERIFY,PR_TRUE,&session); - if (crv != CKR_OK) return crv; - - if (context->hashInfo) { - (*context->end)(context->hashInfo, tmpbuf, &digestLen, sizeof(tmpbuf)); - rv = (*context->verify)(context->cipherInfo, pSignature, - ulSignatureLen, tmpbuf, digestLen); - } else { - if (context->padDataLength) { - /* fill out rest of pad buffer with pad magic*/ - int i; - for (i=context->padDataLength; i < (int)context->blockSize; i++) { - context->padBuf[i] = 0; - } - rv = (*context->update)(context->cipherInfo,context->macBuf, - &outlen,PK11_MAX_BLOCK_SIZE,context->padBuf,context->blockSize); - } - if (rv == SECSuccess) { - rv =(PORT_Memcmp(pSignature,context->macBuf,context->macSize) == 0) - ? SECSuccess : SECFailure; - } - } - - pk11_FreeContext(context); - pk11_SetContextByType(session, PK11_VERIFY, NULL); - pk11_FreeSession(session); - return (rv == SECSuccess) ? CKR_OK : CKR_SIGNATURE_INVALID; - -} - -/* - ************** Crypto Functions: Verify Recover ************************ - */ - -/* NSC_VerifyRecoverInit initializes a signature verification operation, - * where the data is recovered from the signature. - * E.g. Decryption with the user's public key */ -CK_RV NSC_VerifyRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) -{ - PK11Session *session; - PK11Object *key; - PK11SessionContext *context; - CK_KEY_TYPE key_type; - CK_RV crv = CKR_OK; - NSSLOWKEYPublicKey *pubKey; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - crv = pk11_InitGeneric(session,&context,PK11_VERIFY_RECOVER, - &key,hKey,&key_type,CKO_PUBLIC_KEY,CKA_VERIFY_RECOVER); - if (crv != CKR_OK) { - pk11_FreeSession(session); - return crv; - } - - context->multi = PR_TRUE; - - switch(pMechanism->mechanism) { - case CKM_RSA_PKCS: - case CKM_RSA_X_509: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->multi = PR_FALSE; - pubKey = pk11_GetPubKey(key,CKK_RSA,&crv); - if (pubKey == NULL) { - break; - } - context->cipherInfo = pubKey; - context->update = (PK11Cipher) (pMechanism->mechanism == CKM_RSA_X_509 - ? RSA_CheckSignRecoverRaw : RSA_CheckSignRecover); - context->destroy = pk11_Null; - break; - default: - crv = CKR_MECHANISM_INVALID; - break; - } - - if (crv != CKR_OK) { - PORT_Free(context); - pk11_FreeSession(session); - return crv; - } - pk11_SetContextByType(session, PK11_VERIFY_RECOVER, context); - pk11_FreeSession(session); - return CKR_OK; -} - - -/* NSC_VerifyRecover verifies a signature in a single-part operation, - * where the data is recovered from the signature. - * E.g. Decryption with the user's public key */ -CK_RV NSC_VerifyRecover(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG ulSignatureLen, - CK_BYTE_PTR pData,CK_ULONG_PTR pulDataLen) -{ - PK11Session *session; - PK11SessionContext *context; - unsigned int outlen; - unsigned int maxoutlen = *pulDataLen; - CK_RV crv; - SECStatus rv; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession,&context,PK11_VERIFY_RECOVER, - PR_FALSE,&session); - if (crv != CKR_OK) return crv; - - rv = (*context->update)(context->cipherInfo, pData, &outlen, maxoutlen, - pSignature, ulSignatureLen); - *pulDataLen = (CK_ULONG) outlen; - pk11_FreeContext(context); - pk11_SetContextByType(session, PK11_VERIFY_RECOVER, NULL); - pk11_FreeSession(session); - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - -/* - **************************** Random Functions: ************************ - */ - -/* NSC_SeedRandom mixes additional seed material into the token's random number - * generator. */ -CK_RV NSC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, - CK_ULONG ulSeedLen) -{ - SECStatus rv; - - rv = RNG_RandomUpdate(pSeed, ulSeedLen); - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - -/* NSC_GenerateRandom generates random data. */ -CK_RV NSC_GenerateRandom(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) -{ - SECStatus rv; - - rv = RNG_GenerateGlobalRandomBytes(pRandomData, ulRandomLen); - return (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; -} - -/* - **************************** Key Functions: ************************ - */ - - -/* - * generate a password based encryption key. This code uses - * PKCS5 to do the work. - */ -static CK_RV -nsc_pbe_key_gen(NSSPKCS5PBEParameter *pkcs5_pbe, CK_MECHANISM_PTR pMechanism, - char *buf, CK_ULONG *key_length, PRBool faulty3DES) -{ - SECItem *pbe_key = NULL, iv, pwitem; - CK_PBE_PARAMS *pbe_params = NULL; - - *key_length = 0; - iv.data = NULL; iv.len = 0; - - pbe_params = (CK_PBE_PARAMS *)pMechanism->pParameter; - - pwitem.data = (unsigned char *)pbe_params->pPassword; - pwitem.len = (unsigned int)pbe_params->ulPasswordLen; - pbe_key = nsspkcs5_ComputeKeyAndIV(pkcs5_pbe, &pwitem, &iv, faulty3DES); - if (pbe_key == NULL) { - return CKR_HOST_MEMORY; - } - - PORT_Memcpy(buf, pbe_key->data, pbe_key->len); - *key_length = pbe_key->len; - SECITEM_ZfreeItem(pbe_key, PR_TRUE); - pbe_key = NULL; - - if (iv.data && pbe_params->pInitVector != NULL) { - PORT_Memcpy(pbe_params->pInitVector, iv.data, iv.len); - } - return CKR_OK; -} -static CK_RV -nsc_parameter_gen(CK_KEY_TYPE key_type, PK11Object *key) -{ - PK11Attribute *attribute; - CK_ULONG counter; - unsigned int seedBits = 0; - unsigned int primeBits; - CK_RV crv = CKR_OK; - PQGParams *params = NULL; - PQGVerify *vfy = NULL; - SECStatus rv; - - attribute = pk11_FindAttribute(key, CKA_PRIME_BITS); - if (attribute == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - primeBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - - attribute = pk11_FindAttribute(key, CKA_NETSCAPE_PQG_SEED_BITS); - if (attribute != NULL) { - seedBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - } - - pk11_DeleteAttributeType(key,CKA_PRIME_BITS); - pk11_DeleteAttributeType(key,CKA_NETSCAPE_PQG_SEED_BITS); - - if (seedBits == 0) { - rv = PQG_ParamGen(primeBits, ¶ms, &vfy); - } else { - rv = PQG_ParamGenSeedLen(primeBits,seedBits/8, ¶ms, &vfy); - } - - if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; - } - crv = pk11_AddAttributeType(key,CKA_PRIME, - params->prime.data, params->prime.len); - if (crv != CKR_OK) goto loser; - crv = pk11_AddAttributeType(key,CKA_SUBPRIME, - params->subPrime.data, params->subPrime.len); - if (crv != CKR_OK) goto loser; - crv = pk11_AddAttributeType(key,CKA_BASE, - params->base.data, params->base.len); - if (crv != CKR_OK) goto loser; - counter = vfy->counter; - crv = pk11_AddAttributeType(key,CKA_NETSCAPE_PQG_COUNTER, - &counter, sizeof(counter)); - crv = pk11_AddAttributeType(key,CKA_NETSCAPE_PQG_SEED, - vfy->seed.data, vfy->seed.len); - if (crv != CKR_OK) goto loser; - crv = pk11_AddAttributeType(key,CKA_NETSCAPE_PQG_H, - vfy->h.data, vfy->h.len); - if (crv != CKR_OK) goto loser; - -loser: - if (params) { - PQG_DestroyParams(params); - } - if (vfy) { - PQG_DestroyVerify(vfy); - } - return crv; -} - - - - - - - -static CK_RV -nsc_SetupBulkKeyGen(CK_MECHANISM_TYPE mechanism, CK_KEY_TYPE *key_type, - CK_ULONG *key_length) -{ - CK_RV crv = CKR_OK; - - switch (mechanism) { - case CKM_RC2_KEY_GEN: - *key_type = CKK_RC2; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; -#if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_KEY_GEN: - *key_type = CKK_RC5; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; -#endif - case CKM_RC4_KEY_GEN: - *key_type = CKK_RC4; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; - case CKM_GENERIC_SECRET_KEY_GEN: - *key_type = CKK_GENERIC_SECRET; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; - case CKM_CDMF_KEY_GEN: - *key_type = CKK_CDMF; - *key_length = 8; - break; - case CKM_DES_KEY_GEN: - *key_type = CKK_DES; - *key_length = 8; - break; - case CKM_DES2_KEY_GEN: - *key_type = CKK_DES2; - *key_length = 16; - break; - case CKM_DES3_KEY_GEN: - *key_type = CKK_DES3; - *key_length = 24; - break; - case CKM_AES_KEY_GEN: - *key_type = CKK_AES; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; - default: - PORT_Assert(0); - crv = CKR_MECHANISM_INVALID; - break; - } - - return crv; -} - -CK_RV -nsc_SetupHMACKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe) -{ - SECItem salt; - CK_PBE_PARAMS *pbe_params = NULL; - NSSPKCS5PBEParameter *params; - PRArenaPool *arena = NULL; - SECStatus rv; - - *pbe = NULL; - - arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if (arena == NULL) { - return CKR_HOST_MEMORY; - } - - params = (NSSPKCS5PBEParameter *) PORT_ArenaZAlloc(arena, - sizeof(NSSPKCS5PBEParameter)); - if (params == NULL) { - PORT_FreeArena(arena,PR_TRUE); - return CKR_HOST_MEMORY; - } - - params->poolp = arena; - params->ivLen = 0; - params->pbeType = NSSPKCS5_PKCS12_V2; - params->hashType = HASH_AlgSHA1; - params->encAlg = SEC_OID_SHA1; /* any invalid value */ - params->is2KeyDES = PR_FALSE; - params->keyID = pbeBitGenIntegrityKey; - pbe_params = (CK_PBE_PARAMS *)pMechanism->pParameter; - params->iter = pbe_params->ulIteration; - - salt.data = (unsigned char *)pbe_params->pSalt; - salt.len = (unsigned int)pbe_params->ulSaltLen; - rv = SECITEM_CopyItem(arena,¶ms->salt,&salt); - if (rv != SECSuccess) { - PORT_FreeArena(arena,PR_TRUE); - return CKR_HOST_MEMORY; - } - switch (pMechanism->mechanism) { - case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN: - case CKM_PBA_SHA1_WITH_SHA1_HMAC: - params->hashType = HASH_AlgSHA1; - params->keyLen = 20; - break; - case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN: - params->hashType = HASH_AlgMD5; - params->keyLen = 16; - break; - case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN: - params->hashType = HASH_AlgMD2; - params->keyLen = 16; - break; - default: - PORT_FreeArena(arena,PR_TRUE); - return CKR_MECHANISM_INVALID; - } - *pbe = params; - return CKR_OK; -} -/* maybe this should be table driven? */ -static CK_RV -nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, - CK_KEY_TYPE *key_type) -{ - CK_RV crv = CKR_OK; - SECOidData *oid; - CK_PBE_PARAMS *pbe_params; - NSSPKCS5PBEParameter *params; - SECItem salt; - - *pbe = NULL; - - oid = SECOID_FindOIDByMechanism(pMechanism->mechanism); - if (oid == NULL) { - return CKR_MECHANISM_INVALID; - } - - pbe_params = (CK_PBE_PARAMS *)pMechanism->pParameter; - salt.data = (unsigned char *)pbe_params->pSalt; - salt.len = (unsigned int)pbe_params->ulSaltLen; - - params=nsspkcs5_NewParam(oid->offset, &salt, pbe_params->ulIteration); - if (params == NULL) { - return CKR_MECHANISM_INVALID; - } - - - switch (params->encAlg) { - case SEC_OID_DES_CBC: - *key_type = CKK_DES; - break; - case SEC_OID_DES_EDE3_CBC: - *key_type = params->is2KeyDES ? CKK_DES2 : CKK_DES3; - break; - case SEC_OID_RC2_CBC: - *key_type = CKK_RC2; - break; - case SEC_OID_RC4: - *key_type = CKK_RC4; - break; - default: - crv = CKR_MECHANISM_INVALID; - nsspkcs5_DestroyPBEParameter(params); - break; - } - if (crv == CKR_OK) { - *pbe = params; - } - return crv; -} - -/* NSC_GenerateKey generates a secret key, creating a new key object. */ -CK_RV NSC_GenerateKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phKey) -{ - PK11Object *key; - PK11Session *session; - PRBool checkWeak = PR_FALSE; - CK_ULONG key_length = 0; - CK_KEY_TYPE key_type = CKK_INVALID_KEY_TYPE; - CK_OBJECT_CLASS objclass = CKO_SECRET_KEY; - CK_RV crv = CKR_OK; - CK_BBOOL cktrue = CK_TRUE; - int i; - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - char buf[MAX_KEY_LEN]; - enum {nsc_pbe, nsc_ssl, nsc_bulk, nsc_param} key_gen_type; - NSSPKCS5PBEParameter *pbe_param; - SSL3RSAPreMasterSecret *rsa_pms; - CK_VERSION *version; - /* in very old versions of NSS, there were implementation errors with key - * generation methods. We want to beable to read these, but not - * produce them any more. The affected algorithm was 3DES. - */ - PRBool faultyPBE3DES = PR_FALSE; - - - /* - * now lets create an object to hang the attributes off of - */ - key = pk11_NewObject(slot); /* fill in the handle later */ - if (key == NULL) { - return CKR_HOST_MEMORY; - } - - /* - * load the template values into the object - */ - for (i=0; i < (int) ulCount; i++) { - if (pTemplate[i].type == CKA_VALUE_LEN) { - key_length = *(CK_ULONG *)pTemplate[i].pValue; - continue; - } - - crv = pk11_AddAttributeType(key,pk11_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; - } - if (crv != CKR_OK) { - pk11_FreeObject(key); - return crv; - } - - /* make sure we don't have any class, key_type, or value fields */ - pk11_DeleteAttributeType(key,CKA_CLASS); - pk11_DeleteAttributeType(key,CKA_KEY_TYPE); - pk11_DeleteAttributeType(key,CKA_VALUE); - - /* Now Set up the parameters to generate the key (based on mechanism) */ - key_gen_type = nsc_bulk; /* bulk key by default */ - switch (pMechanism->mechanism) { - case CKM_CDMF_KEY_GEN: - case CKM_DES_KEY_GEN: - case CKM_DES2_KEY_GEN: - case CKM_DES3_KEY_GEN: - checkWeak = PR_TRUE; - case CKM_RC2_KEY_GEN: - case CKM_RC4_KEY_GEN: - case CKM_GENERIC_SECRET_KEY_GEN: - case CKM_AES_KEY_GEN: -#if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_KEY_GEN: -#endif - crv = nsc_SetupBulkKeyGen(pMechanism->mechanism,&key_type,&key_length); - break; - case CKM_SSL3_PRE_MASTER_KEY_GEN: - key_type = CKK_GENERIC_SECRET; - key_length = 48; - key_gen_type = nsc_ssl; - break; - case CKM_PBA_SHA1_WITH_SHA1_HMAC: - case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN: - case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN: - case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN: - key_gen_type = nsc_pbe; - key_type = CKK_GENERIC_SECRET; - crv = nsc_SetupHMACKeyGen(pMechanism, &pbe_param); - break; - case CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC: - faultyPBE3DES = PR_TRUE; - case CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC: - case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC2_CBC: - case CKM_NETSCAPE_PBE_SHA1_DES_CBC: - case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC2_CBC: - case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC4: - case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC4: - case CKM_PBE_SHA1_DES3_EDE_CBC: - case CKM_PBE_SHA1_DES2_EDE_CBC: - case CKM_PBE_SHA1_RC2_128_CBC: - case CKM_PBE_SHA1_RC2_40_CBC: - case CKM_PBE_SHA1_RC4_128: - case CKM_PBE_SHA1_RC4_40: - case CKM_PBE_MD5_DES_CBC: - case CKM_PBE_MD2_DES_CBC: - key_gen_type = nsc_pbe; - crv = nsc_SetupPBEKeyGen(pMechanism,&pbe_param, &key_type); - break; - case CKM_DSA_PARAMETER_GEN: - key_gen_type = nsc_param; - key_type = CKK_DSA; - objclass = CKO_KG_PARAMETERS; - crv = CKR_OK; - break; - default: - crv = CKR_MECHANISM_INVALID; - break; - } - - /* make sure we aren't going to overflow the buffer */ - if (sizeof(buf) < key_length) { - /* someone is getting pretty optimistic about how big their key can - * be... */ - crv = CKR_TEMPLATE_INCONSISTENT; - } - - if (crv != CKR_OK) { pk11_FreeObject(key); return crv; } - - /* if there was no error, - * key_type *MUST* be set in the switch statement above */ - PORT_Assert( key_type != CKK_INVALID_KEY_TYPE ); - - /* - * now to the actual key gen. - */ - switch (key_gen_type) { - case nsc_pbe: - crv = nsc_pbe_key_gen(pbe_param, pMechanism, buf, &key_length, - faultyPBE3DES); - nsspkcs5_DestroyPBEParameter(pbe_param); - break; - case nsc_ssl: - rsa_pms = (SSL3RSAPreMasterSecret *)buf; - version = (CK_VERSION *)pMechanism->pParameter; - rsa_pms->client_version[0] = version->major; - rsa_pms->client_version[1] = version->minor; - crv = - NSC_GenerateRandom(0,&rsa_pms->random[0], sizeof(rsa_pms->random)); - break; - case nsc_bulk: - /* get the key, check for weak keys and repeat if found */ - do { - crv = NSC_GenerateRandom(0, (unsigned char *)buf, key_length); - } while (crv == CKR_OK && checkWeak && - pk11_IsWeakKey((unsigned char *)buf,key_type)); - break; - case nsc_param: - /* generate parameters */ - *buf = 0; - crv = nsc_parameter_gen(key_type,key); - break; - } - - if (crv != CKR_OK) { pk11_FreeObject(key); return crv; } - - /* Add the class, key_type, and value */ - crv = pk11_AddAttributeType(key,CKA_CLASS,&objclass,sizeof(CK_OBJECT_CLASS)); - if (crv != CKR_OK) { pk11_FreeObject(key); return crv; } - crv = pk11_AddAttributeType(key,CKA_KEY_TYPE,&key_type,sizeof(CK_KEY_TYPE)); - if (crv != CKR_OK) { pk11_FreeObject(key); return crv; } - if (key_length != 0) { - crv = pk11_AddAttributeType(key,CKA_VALUE,buf,key_length); - if (crv != CKR_OK) { pk11_FreeObject(key); return crv; } - } - - /* get the session */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - pk11_FreeObject(key); - return CKR_SESSION_HANDLE_INVALID; - } - - /* - * handle the base object stuff - */ - crv = pk11_handleObject(key,session); - pk11_FreeSession(session); - if (pk11_isTrue(key,CKA_SENSITIVE)) { - pk11_forceAttribute(key,CKA_ALWAYS_SENSITIVE,&cktrue,sizeof(CK_BBOOL)); - } - if (!pk11_isTrue(key,CKA_EXTRACTABLE)) { - pk11_forceAttribute(key,CKA_NEVER_EXTRACTABLE,&cktrue,sizeof(CK_BBOOL)); - } - - *phKey = key->handle; - pk11_FreeObject(key); - return crv; -} - - -/* NSC_GenerateKeyPair generates a public-key/private-key pair, - * creating new key objects. */ -CK_RV NSC_GenerateKeyPair (CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, - CK_OBJECT_HANDLE_PTR phPrivateKey) -{ - PK11Object * publicKey,*privateKey; - PK11Session * session; - CK_KEY_TYPE key_type; - CK_RV crv = CKR_OK; - CK_BBOOL cktrue = CK_TRUE; - SECStatus rv; - CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY; - CK_OBJECT_CLASS privClass = CKO_PRIVATE_KEY; - int i; - PK11Slot * slot = pk11_SlotFromSessionHandle(hSession); - unsigned int bitSize; - - /* RSA */ - int public_modulus_bits = 0; - SECItem pubExp; - RSAPrivateKey * rsaPriv; - - /* DSA */ - PQGParams pqgParam; - DHParams dhParam; - DSAPrivateKey * dsaPriv; - - /* Diffie Hellman */ - int private_value_bits = 0; - DHPrivateKey * dhPriv; - -#ifdef NSS_ENABLE_ECC - /* Elliptic Curve Cryptography */ - SECItem ecEncodedParams; /* DER Encoded parameters */ - ECPrivateKey * ecPriv; - ECParams * ecParams; -#endif /* NSS_ENABLE_ECC */ - - /* - * now lets create an object to hang the attributes off of - */ - publicKey = pk11_NewObject(slot); /* fill in the handle later */ - if (publicKey == NULL) { - return CKR_HOST_MEMORY; - } - - /* - * load the template values into the publicKey - */ - for (i=0; i < (int) ulPublicKeyAttributeCount; i++) { - if (pPublicKeyTemplate[i].type == CKA_MODULUS_BITS) { - public_modulus_bits = *(CK_ULONG *)pPublicKeyTemplate[i].pValue; - continue; - } - - crv = pk11_AddAttributeType(publicKey, - pk11_attr_expand(&pPublicKeyTemplate[i])); - if (crv != CKR_OK) break; - } - - if (crv != CKR_OK) { - pk11_FreeObject(publicKey); - return CKR_HOST_MEMORY; - } - - privateKey = pk11_NewObject(slot); /* fill in the handle later */ - if (privateKey == NULL) { - pk11_FreeObject(publicKey); - return CKR_HOST_MEMORY; - } - /* - * now load the private key template - */ - for (i=0; i < (int) ulPrivateKeyAttributeCount; i++) { - if (pPrivateKeyTemplate[i].type == CKA_VALUE_BITS) { - private_value_bits = *(CK_ULONG *)pPrivateKeyTemplate[i].pValue; - continue; - } - - crv = pk11_AddAttributeType(privateKey, - pk11_attr_expand(&pPrivateKeyTemplate[i])); - if (crv != CKR_OK) break; - } - - if (crv != CKR_OK) { - pk11_FreeObject(publicKey); - pk11_FreeObject(privateKey); - return CKR_HOST_MEMORY; - } - pk11_DeleteAttributeType(privateKey,CKA_CLASS); - pk11_DeleteAttributeType(privateKey,CKA_KEY_TYPE); - pk11_DeleteAttributeType(privateKey,CKA_VALUE); - pk11_DeleteAttributeType(publicKey,CKA_CLASS); - pk11_DeleteAttributeType(publicKey,CKA_KEY_TYPE); - pk11_DeleteAttributeType(publicKey,CKA_VALUE); - - /* Now Set up the parameters to generate the key (based on mechanism) */ - switch (pMechanism->mechanism) { - case CKM_RSA_PKCS_KEY_PAIR_GEN: - /* format the keys */ - pk11_DeleteAttributeType(publicKey,CKA_MODULUS); - pk11_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - pk11_DeleteAttributeType(privateKey,CKA_MODULUS); - pk11_DeleteAttributeType(privateKey,CKA_PRIVATE_EXPONENT); - pk11_DeleteAttributeType(privateKey,CKA_PUBLIC_EXPONENT); - pk11_DeleteAttributeType(privateKey,CKA_PRIME_1); - pk11_DeleteAttributeType(privateKey,CKA_PRIME_2); - pk11_DeleteAttributeType(privateKey,CKA_EXPONENT_1); - pk11_DeleteAttributeType(privateKey,CKA_EXPONENT_2); - pk11_DeleteAttributeType(privateKey,CKA_COEFFICIENT); - key_type = CKK_RSA; - if (public_modulus_bits == 0) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - if (public_modulus_bits < RSA_MIN_MODULUS_BITS) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - if (public_modulus_bits % 2 != 0) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - - /* extract the exponent */ - crv=pk11_Attribute2SSecItem(NULL,&pubExp,publicKey,CKA_PUBLIC_EXPONENT); - if (crv != CKR_OK) break; - bitSize = pk11_GetLengthInBits(pubExp.data, pubExp.len); - if (bitSize < 2) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - crv = pk11_AddAttributeType(privateKey,CKA_PUBLIC_EXPONENT, - pk11_item_expand(&pubExp)); - if (crv != CKR_OK) { - PORT_Free(pubExp.data); - break; - } - - rsaPriv = RSA_NewKey(public_modulus_bits, &pubExp); - PORT_Free(pubExp.data); - if (rsaPriv == NULL) { - crv = CKR_DEVICE_ERROR; - break; - } - /* now fill in the RSA dependent paramenters in the public key */ - crv = pk11_AddAttributeType(publicKey,CKA_MODULUS, - pk11_item_expand(&rsaPriv->modulus)); - if (crv != CKR_OK) goto kpg_done; - /* now fill in the RSA dependent paramenters in the private key */ - crv = pk11_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - pk11_item_expand(&rsaPriv->modulus)); - if (crv != CKR_OK) goto kpg_done; - crv = pk11_AddAttributeType(privateKey,CKA_MODULUS, - pk11_item_expand(&rsaPriv->modulus)); - if (crv != CKR_OK) goto kpg_done; - crv = pk11_AddAttributeType(privateKey,CKA_PRIVATE_EXPONENT, - pk11_item_expand(&rsaPriv->privateExponent)); - if (crv != CKR_OK) goto kpg_done; - crv = pk11_AddAttributeType(privateKey,CKA_PRIME_1, - pk11_item_expand(&rsaPriv->prime1)); - if (crv != CKR_OK) goto kpg_done; - crv = pk11_AddAttributeType(privateKey,CKA_PRIME_2, - pk11_item_expand(&rsaPriv->prime2)); - if (crv != CKR_OK) goto kpg_done; - crv = pk11_AddAttributeType(privateKey,CKA_EXPONENT_1, - pk11_item_expand(&rsaPriv->exponent1)); - if (crv != CKR_OK) goto kpg_done; - crv = pk11_AddAttributeType(privateKey,CKA_EXPONENT_2, - pk11_item_expand(&rsaPriv->exponent2)); - if (crv != CKR_OK) goto kpg_done; - crv = pk11_AddAttributeType(privateKey,CKA_COEFFICIENT, - pk11_item_expand(&rsaPriv->coefficient)); -kpg_done: - /* Should zeroize the contents first, since this func doesn't. */ - PORT_FreeArena(rsaPriv->arena, PR_TRUE); - break; - case CKM_DSA_KEY_PAIR_GEN: - pk11_DeleteAttributeType(publicKey,CKA_VALUE); - pk11_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - pk11_DeleteAttributeType(privateKey,CKA_PRIME); - pk11_DeleteAttributeType(privateKey,CKA_SUBPRIME); - pk11_DeleteAttributeType(privateKey,CKA_BASE); - key_type = CKK_DSA; - - /* extract the necessary paramters and copy them to the private key */ - crv=pk11_Attribute2SSecItem(NULL,&pqgParam.prime,publicKey,CKA_PRIME); - if (crv != CKR_OK) break; - crv=pk11_Attribute2SSecItem(NULL,&pqgParam.subPrime,publicKey, - CKA_SUBPRIME); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - break; - } - crv=pk11_Attribute2SSecItem(NULL,&pqgParam.base,publicKey,CKA_BASE); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - break; - } - crv = pk11_AddAttributeType(privateKey,CKA_PRIME, - pk11_item_expand(&pqgParam.prime)); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - crv = pk11_AddAttributeType(privateKey,CKA_SUBPRIME, - pk11_item_expand(&pqgParam.subPrime)); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - crv = pk11_AddAttributeType(privateKey,CKA_BASE, - pk11_item_expand(&pqgParam.base)); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - - bitSize = pk11_GetLengthInBits(pqgParam.subPrime.data, - pqgParam.subPrime.len); - if (bitSize != DSA_Q_BITS) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - bitSize = pk11_GetLengthInBits(pqgParam.prime.data,pqgParam.prime.len); - if ((bitSize < DSA_MIN_P_BITS) || (bitSize > DSA_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - bitSize = pk11_GetLengthInBits(pqgParam.base.data,pqgParam.base.len); - if ((bitSize < 1) || (bitSize > DSA_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - - /* Generate the key */ - rv = DSA_NewKey(&pqgParam, &dsaPriv); - - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - - if (rv != SECSuccess) { crv = CKR_DEVICE_ERROR; break; } - - /* store the generated key into the attributes */ - crv = pk11_AddAttributeType(publicKey,CKA_VALUE, - pk11_item_expand(&dsaPriv->publicValue)); - if (crv != CKR_OK) goto dsagn_done; - - /* now fill in the RSA dependent paramenters in the private key */ - crv = pk11_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - pk11_item_expand(&dsaPriv->publicValue)); - if (crv != CKR_OK) goto dsagn_done; - crv = pk11_AddAttributeType(privateKey,CKA_VALUE, - pk11_item_expand(&dsaPriv->privateValue)); - -dsagn_done: - /* should zeroize, since this function doesn't. */ - PORT_FreeArena(dsaPriv->params.arena, PR_TRUE); - break; - - case CKM_DH_PKCS_KEY_PAIR_GEN: - pk11_DeleteAttributeType(privateKey,CKA_PRIME); - pk11_DeleteAttributeType(privateKey,CKA_BASE); - pk11_DeleteAttributeType(privateKey,CKA_VALUE); - pk11_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - key_type = CKK_DH; - - /* extract the necessary parameters and copy them to private keys */ - crv = pk11_Attribute2SSecItem(NULL, &dhParam.prime, publicKey, - CKA_PRIME); - if (crv != CKR_OK) break; - crv = pk11_Attribute2SSecItem(NULL, &dhParam.base, publicKey, CKA_BASE); - if (crv != CKR_OK) { - PORT_Free(dhParam.prime.data); - break; - } - crv = pk11_AddAttributeType(privateKey, CKA_PRIME, - pk11_item_expand(&dhParam.prime)); - if (crv != CKR_OK) { - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - crv = pk11_AddAttributeType(privateKey, CKA_BASE, - pk11_item_expand(&dhParam.base)); - if (crv != CKR_OK) { - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - bitSize = pk11_GetLengthInBits(dhParam.prime.data,dhParam.prime.len); - if ((bitSize < DH_MIN_P_BITS) || (bitSize > DH_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - bitSize = pk11_GetLengthInBits(dhParam.base.data,dhParam.base.len); - if ((bitSize < 1) || (bitSize > DH_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - - rv = DH_NewKey(&dhParam, &dhPriv); - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - break; - } - - crv=pk11_AddAttributeType(publicKey, CKA_VALUE, - pk11_item_expand(&dhPriv->publicValue)); - if (crv != CKR_OK) goto dhgn_done; - - crv = pk11_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - pk11_item_expand(&dhPriv->publicValue)); - if (crv != CKR_OK) goto dhgn_done; - - crv=pk11_AddAttributeType(privateKey, CKA_VALUE, - pk11_item_expand(&dhPriv->privateValue)); - -dhgn_done: - /* should zeroize, since this function doesn't. */ - PORT_FreeArena(dhPriv->arena, PR_TRUE); - break; - -#ifdef NSS_ENABLE_ECC - case CKM_EC_KEY_PAIR_GEN: - pk11_DeleteAttributeType(privateKey,CKA_EC_PARAMS); - pk11_DeleteAttributeType(privateKey,CKA_VALUE); - pk11_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - key_type = CKK_EC; - - /* extract the necessary parameters and copy them to private keys */ - crv = pk11_Attribute2SSecItem(NULL, &ecEncodedParams, publicKey, - CKA_EC_PARAMS); - if (crv != CKR_OK) break; - - crv = pk11_AddAttributeType(privateKey, CKA_EC_PARAMS, - pk11_item_expand(&ecEncodedParams)); - if (crv != CKR_OK) { - PORT_Free(ecEncodedParams.data); - break; - } - - /* Decode ec params before calling EC_NewKey */ - rv = EC_DecodeParams(&ecEncodedParams, &ecParams); - PORT_Free(ecEncodedParams.data); - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - break; - } - rv = EC_NewKey(ecParams, &ecPriv); - PORT_FreeArena(ecParams->arena, PR_TRUE); - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - break; - } - - crv = pk11_AddAttributeType(publicKey, CKA_EC_POINT, - pk11_item_expand(&ecPriv->publicValue)); - if (crv != CKR_OK) goto ecgn_done; - - crv = pk11_AddAttributeType(privateKey, CKA_VALUE, - pk11_item_expand(&ecPriv->privateValue)); - if (crv != CKR_OK) goto ecgn_done; - - crv = pk11_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - pk11_item_expand(&ecPriv->publicValue)); -ecgn_done: - /* should zeroize, since this function doesn't. */ - PORT_FreeArena(ecPriv->ecParams.arena, PR_TRUE); - break; -#endif /* NSS_ENABLE_ECC */ - - default: - crv = CKR_MECHANISM_INVALID; - } - - if (crv != CKR_OK) { - pk11_FreeObject(privateKey); - pk11_FreeObject(publicKey); - return crv; - } - - - /* Add the class, key_type The loop lets us check errors blow out - * on errors and clean up at the bottom */ - session = NULL; /* make pedtantic happy... session cannot leave the*/ - /* loop below NULL unless an error is set... */ - do { - crv = pk11_AddAttributeType(privateKey,CKA_CLASS,&privClass, - sizeof(CK_OBJECT_CLASS)); - if (crv != CKR_OK) break; - crv = pk11_AddAttributeType(publicKey,CKA_CLASS,&pubClass, - sizeof(CK_OBJECT_CLASS)); - if (crv != CKR_OK) break; - crv = pk11_AddAttributeType(privateKey,CKA_KEY_TYPE,&key_type, - sizeof(CK_KEY_TYPE)); - if (crv != CKR_OK) break; - crv = pk11_AddAttributeType(publicKey,CKA_KEY_TYPE,&key_type, - sizeof(CK_KEY_TYPE)); - if (crv != CKR_OK) break; - session = pk11_SessionFromHandle(hSession); - if (session == NULL) crv = CKR_SESSION_HANDLE_INVALID; - } while (0); - - if (crv != CKR_OK) { - pk11_FreeObject(privateKey); - pk11_FreeObject(publicKey); - return crv; - } - - /* - * handle the base object cleanup for the public Key - */ - crv = pk11_handleObject(privateKey,session); - if (crv != CKR_OK) { - pk11_FreeSession(session); - pk11_FreeObject(privateKey); - pk11_FreeObject(publicKey); - return crv; - } - - /* - * handle the base object cleanup for the private Key - * If we have any problems, we destroy the public Key we've - * created and linked. - */ - crv = pk11_handleObject(publicKey,session); - pk11_FreeSession(session); - if (crv != CKR_OK) { - pk11_FreeObject(publicKey); - NSC_DestroyObject(hSession,privateKey->handle); - pk11_FreeObject(privateKey); - return crv; - } - if (pk11_isTrue(privateKey,CKA_SENSITIVE)) { - pk11_forceAttribute(privateKey,CKA_ALWAYS_SENSITIVE, - &cktrue,sizeof(CK_BBOOL)); - } - if (pk11_isTrue(publicKey,CKA_SENSITIVE)) { - pk11_forceAttribute(publicKey,CKA_ALWAYS_SENSITIVE, - &cktrue,sizeof(CK_BBOOL)); - } - if (!pk11_isTrue(privateKey,CKA_EXTRACTABLE)) { - pk11_forceAttribute(privateKey,CKA_NEVER_EXTRACTABLE, - &cktrue,sizeof(CK_BBOOL)); - } - if (!pk11_isTrue(publicKey,CKA_EXTRACTABLE)) { - pk11_forceAttribute(publicKey,CKA_NEVER_EXTRACTABLE, - &cktrue,sizeof(CK_BBOOL)); - } - *phPrivateKey = privateKey->handle; - *phPublicKey = publicKey->handle; - pk11_FreeObject(publicKey); - pk11_FreeObject(privateKey); - - return CKR_OK; -} - -static SECItem *pk11_PackagePrivateKey(PK11Object *key, CK_RV *crvp) -{ - NSSLOWKEYPrivateKey *lk = NULL; - NSSLOWKEYPrivateKeyInfo *pki = NULL; - PK11Attribute *attribute = NULL; - PLArenaPool *arena = NULL; - SECOidTag algorithm = SEC_OID_UNKNOWN; - void *dummy, *param = NULL; - SECStatus rv = SECSuccess; - SECItem *encodedKey = NULL; -#ifdef NSS_ENABLE_ECC - SECItem *fordebug; - int savelen; - int i; -#endif - - if(!key) { - *crvp = CKR_KEY_HANDLE_INVALID; /* really can't happen */ - return NULL; - } - - attribute = pk11_FindAttribute(key, CKA_KEY_TYPE); - if(!attribute) { - *crvp = CKR_KEY_TYPE_INCONSISTENT; - return NULL; - } - - lk = pk11_GetPrivKey(key, *(CK_KEY_TYPE *)attribute->attrib.pValue, crvp); - pk11_FreeAttribute(attribute); - if(!lk) { - return NULL; - } - - arena = PORT_NewArena(2048); /* XXX different size? */ - if(!arena) { - *crvp = CKR_HOST_MEMORY; - rv = SECFailure; - goto loser; - } - - pki = (NSSLOWKEYPrivateKeyInfo*)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPrivateKeyInfo)); - if(!pki) { - *crvp = CKR_HOST_MEMORY; - rv = SECFailure; - goto loser; - } - pki->arena = arena; - - param = NULL; - switch(lk->keyType) { - case NSSLOWKEYRSAKey: - prepare_low_rsa_priv_key_for_asn1(lk); - dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, - nsslowkey_RSAPrivateKeyTemplate); - algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION; - break; - case NSSLOWKEYDSAKey: - prepare_low_dsa_priv_key_export_for_asn1(lk); - dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, - nsslowkey_DSAPrivateKeyExportTemplate); - prepare_low_pqg_params_for_asn1(&lk->u.dsa.params); - param = SEC_ASN1EncodeItem(NULL, NULL, &(lk->u.dsa.params), - nsslowkey_PQGParamsTemplate); - algorithm = SEC_OID_ANSIX9_DSA_SIGNATURE; - break; -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - prepare_low_ec_priv_key_for_asn1(lk); - /* Public value is encoded as a bit string so adjust length - * to be in bits before ASN encoding and readjust - * immediately after. - * - * Since the SECG specification recommends not including the - * parameters as part of ECPrivateKey, we zero out the curveOID - * length before encoding and restore it later. - */ - lk->u.ec.publicValue.len <<= 3; - savelen = lk->u.ec.ecParams.curveOID.len; - lk->u.ec.ecParams.curveOID.len = 0; - dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, - nsslowkey_ECPrivateKeyTemplate); - lk->u.ec.ecParams.curveOID.len = savelen; - lk->u.ec.publicValue.len >>= 3; - - fordebug = &pki->privateKey; - SEC_PRINT("pk11_PackagePrivateKey()", "PrivateKey", lk->keyType, - fordebug); - - param = SECITEM_DupItem(&lk->u.ec.ecParams.DEREncoding); - - algorithm = SEC_OID_ANSIX962_EC_PUBLIC_KEY; - break; -#endif /* NSS_ENABLE_ECC */ - case NSSLOWKEYDHKey: - default: - dummy = NULL; - break; - } - - if(!dummy || ((lk->keyType == NSSLOWKEYDSAKey) && !param)) { - *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(arena, &pki->algorithm, algorithm, - (SECItem*)param); - if(rv != SECSuccess) { - *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ - rv = SECFailure; - goto loser; - } - - dummy = SEC_ASN1EncodeInteger(arena, &pki->version, - NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); - if(!dummy) { - *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ - rv = SECFailure; - goto loser; - } - - encodedKey = SEC_ASN1EncodeItem(NULL, NULL, pki, - nsslowkey_PrivateKeyInfoTemplate); - *crvp = encodedKey ? CKR_OK : CKR_DEVICE_ERROR; - -#ifdef NSS_ENABLE_ECC - fordebug = encodedKey; - SEC_PRINT("pk11_PackagePrivateKey()", "PrivateKeyInfo", lk->keyType, - fordebug); -#endif -loser: - if(arena) { - PORT_FreeArena(arena, PR_TRUE); - } - - if(lk && (lk != key->objectInfo)) { - nsslowkey_DestroyPrivateKey(lk); - } - - if(param) { - SECITEM_ZfreeItem((SECItem*)param, PR_TRUE); - } - - if(rv != SECSuccess) { - return NULL; - } - - return encodedKey; -} - -/* it doesn't matter yet, since we colapse error conditions in the - * level above, but we really should map those few key error differences */ -static CK_RV -pk11_mapWrap(CK_RV crv) -{ - switch (crv) { - case CKR_ENCRYPTED_DATA_INVALID: crv = CKR_WRAPPED_KEY_INVALID; break; - } - return crv; -} - -/* NSC_WrapKey wraps (i.e., encrypts) a key. */ -CK_RV NSC_WrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, - CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pulWrappedKeyLen) -{ - PK11Session *session; - PK11Attribute *attribute; - PK11Object *key; - CK_RV crv; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } - - key = pk11_ObjectFromHandle(hKey,session); - pk11_FreeSession(session); - if (key == NULL) { - return CKR_KEY_HANDLE_INVALID; - } - - switch(key->objclass) { - case CKO_SECRET_KEY: - { - PK11SessionContext *context = NULL; - SECItem pText; - - attribute = pk11_FindAttribute(key,CKA_VALUE); - - if (attribute == NULL) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - crv = pk11_CryptInit(hSession, pMechanism, hWrappingKey, - CKA_WRAP, PK11_ENCRYPT, PR_TRUE); - if (crv != CKR_OK) { - pk11_FreeAttribute(attribute); - break; - } - - pText.type = siBuffer; - pText.data = (unsigned char *)attribute->attrib.pValue; - pText.len = attribute->attrib.ulValueLen; - - /* Find out if this is a block cipher. */ - crv = pk11_GetContext(hSession,&context,PK11_ENCRYPT,PR_FALSE,NULL); - if (crv != CKR_OK || !context) - break; - if (context->blockSize > 1) { - unsigned int remainder = pText.len % context->blockSize; - if (!context->doPad && remainder) { - /* When wrapping secret keys with unpadded block ciphers, - ** the keys are zero padded, if necessary, to fill out - ** a full block. - */ - pText.len += context->blockSize - remainder; - pText.data = PORT_ZAlloc(pText.len); - if (pText.data) - memcpy(pText.data, attribute->attrib.pValue, - attribute->attrib.ulValueLen); - else { - crv = CKR_HOST_MEMORY; - break; - } - } - } - - crv = NSC_Encrypt(hSession, (CK_BYTE_PTR)pText.data, - pText.len, pWrappedKey, pulWrappedKeyLen); - - if (pText.data != (unsigned char *)attribute->attrib.pValue) - PORT_ZFree(pText.data, pText.len); - pk11_FreeAttribute(attribute); - break; - } - - case CKO_PRIVATE_KEY: - { - SECItem *bpki = pk11_PackagePrivateKey(key, &crv); - - if(!bpki) { - break; - } - - crv = pk11_CryptInit(hSession, pMechanism, hWrappingKey, - CKA_WRAP, PK11_ENCRYPT, PR_TRUE); - if(crv != CKR_OK) { - SECITEM_ZfreeItem(bpki, PR_TRUE); - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - - crv = NSC_Encrypt(hSession, bpki->data, bpki->len, - pWrappedKey, pulWrappedKeyLen); - SECITEM_ZfreeItem(bpki, PR_TRUE); - break; - } - - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - pk11_FreeObject(key); - - return pk11_mapWrap(crv); -} - -/* - * import a pprivate key info into the desired slot - */ -static SECStatus -pk11_unwrapPrivateKey(PK11Object *key, SECItem *bpki) -{ - CK_BBOOL cktrue = CK_TRUE; - CK_KEY_TYPE keyType = CKK_RSA; - SECStatus rv = SECFailure; - const SEC_ASN1Template *keyTemplate, *paramTemplate; - void *paramDest = NULL; - PLArenaPool *arena; - NSSLOWKEYPrivateKey *lpk = NULL; - NSSLOWKEYPrivateKeyInfo *pki = NULL; - SECItem *ck_id = NULL; - CK_RV crv = CKR_KEY_TYPE_INCONSISTENT; - - arena = PORT_NewArena(2048); - if(!arena) { - return SECFailure; - } - - pki = (NSSLOWKEYPrivateKeyInfo*)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPrivateKeyInfo)); - if(!pki) { - PORT_FreeArena(arena, PR_TRUE); - return SECFailure; - } - - if(SEC_ASN1DecodeItem(arena, pki, nsslowkey_PrivateKeyInfoTemplate, bpki) - != SECSuccess) { - PORT_FreeArena(arena, PR_FALSE); - return SECFailure; - } - - lpk = (NSSLOWKEYPrivateKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPrivateKey)); - if(lpk == NULL) { - goto loser; - } - lpk->arena = arena; - - switch(SECOID_GetAlgorithmTag(&pki->algorithm)) { - case SEC_OID_PKCS1_RSA_ENCRYPTION: - keyTemplate = nsslowkey_RSAPrivateKeyTemplate; - paramTemplate = NULL; - paramDest = NULL; - lpk->keyType = NSSLOWKEYRSAKey; - prepare_low_rsa_priv_key_for_asn1(lpk); - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - keyTemplate = nsslowkey_DSAPrivateKeyExportTemplate; - paramTemplate = nsslowkey_PQGParamsTemplate; - paramDest = &(lpk->u.dsa.params); - lpk->keyType = NSSLOWKEYDSAKey; - prepare_low_dsa_priv_key_export_for_asn1(lpk); - prepare_low_pqg_params_for_asn1(&lpk->u.dsa.params); - break; - /* case NSSLOWKEYDHKey: */ -#ifdef NSS_ENABLE_ECC - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - keyTemplate = nsslowkey_ECPrivateKeyTemplate; - paramTemplate = NULL; - paramDest = &(lpk->u.ec.ecParams.DEREncoding); - lpk->keyType = NSSLOWKEYECKey; - prepare_low_ec_priv_key_for_asn1(lpk); - prepare_low_ecparams_for_asn1(&lpk->u.ec.ecParams); - break; -#endif /* NSS_ENABLE_ECC */ - default: - keyTemplate = NULL; - paramTemplate = NULL; - paramDest = NULL; - break; - } - - if(!keyTemplate) { - goto loser; - } - - /* decode the private key and any algorithm parameters */ - rv = SEC_QuickDERDecodeItem(arena, lpk, keyTemplate, &pki->privateKey); - -#ifdef NSS_ENABLE_ECC - if (lpk->keyType == NSSLOWKEYECKey) { - /* convert length in bits to length in bytes */ - lpk->u.ec.publicValue.len >>= 3; - rv = SECITEM_CopyItem(arena, - &(lpk->u.ec.ecParams.DEREncoding), - &(pki->algorithm.parameters)); - if(rv != SECSuccess) { - goto loser; - } - } -#endif /* NSS_ENABLE_ECC */ - - if(rv != SECSuccess) { - goto loser; - } - if(paramDest && paramTemplate) { - rv = SEC_QuickDERDecodeItem(arena, paramDest, paramTemplate, - &(pki->algorithm.parameters)); - if(rv != SECSuccess) { - goto loser; - } - } - - rv = SECFailure; - - switch (lpk->keyType) { - case NSSLOWKEYRSAKey: - keyType = CKK_RSA; - if(pk11_hasAttribute(key, CKA_NETSCAPE_DB)) { - pk11_DeleteAttributeType(key, CKA_NETSCAPE_DB); - } - crv = pk11_AddAttributeType(key, CKA_KEY_TYPE, &keyType, - sizeof(keyType)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_UNWRAP, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_DECRYPT, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_SIGN, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_MODULUS, - pk11_item_expand(&lpk->u.rsa.modulus)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_PUBLIC_EXPONENT, - pk11_item_expand(&lpk->u.rsa.publicExponent)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_PRIVATE_EXPONENT, - pk11_item_expand(&lpk->u.rsa.privateExponent)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_PRIME_1, - pk11_item_expand(&lpk->u.rsa.prime1)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_PRIME_2, - pk11_item_expand(&lpk->u.rsa.prime2)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_EXPONENT_1, - pk11_item_expand(&lpk->u.rsa.exponent1)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_EXPONENT_2, - pk11_item_expand(&lpk->u.rsa.exponent2)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_COEFFICIENT, - pk11_item_expand(&lpk->u.rsa.coefficient)); - break; - case NSSLOWKEYDSAKey: - keyType = CKK_DSA; - crv = (pk11_hasAttribute(key, CKA_NETSCAPE_DB)) ? CKR_OK : - CKR_KEY_TYPE_INCONSISTENT; - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_KEY_TYPE, &keyType, - sizeof(keyType)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_SIGN, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_PRIME, - pk11_item_expand(&lpk->u.dsa.params.prime)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_SUBPRIME, - pk11_item_expand(&lpk->u.dsa.params.subPrime)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_BASE, - pk11_item_expand(&lpk->u.dsa.params.base)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_VALUE, - pk11_item_expand(&lpk->u.dsa.privateValue)); - if(crv != CKR_OK) break; - break; -#ifdef notdef - case NSSLOWKEYDHKey: - template = dhTemplate; - templateCount = sizeof(dhTemplate)/sizeof(CK_ATTRIBUTE); - keyType = CKK_DH; - break; -#endif - /* what about fortezza??? */ -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - keyType = CKK_EC; - crv = (pk11_hasAttribute(key, CKA_NETSCAPE_DB)) ? CKR_OK : - CKR_KEY_TYPE_INCONSISTENT; - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_KEY_TYPE, &keyType, - sizeof(keyType)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_SIGN, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_DERIVE, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_EC_PARAMS, - pk11_item_expand(&lpk->u.ec.ecParams.DEREncoding)); - if(crv != CKR_OK) break; - crv = pk11_AddAttributeType(key, CKA_VALUE, - pk11_item_expand(&lpk->u.ec.privateValue)); - if(crv != CKR_OK) break; - /* XXX Do we need to decode the EC Params here ?? */ - break; -#endif /* NSS_ENABLE_ECC */ - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - -loser: - if(ck_id) { - SECITEM_ZfreeItem(ck_id, PR_TRUE); - } - - if(lpk) { - nsslowkey_DestroyPrivateKey(lpk); - } - - if(crv != CKR_OK) { - return SECFailure; - } - - return SECSuccess; -} - - -/* NSC_UnwrapKey unwraps (decrypts) a wrapped key, creating a new key object. */ -CK_RV NSC_UnwrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, - CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) -{ - PK11Object *key = NULL; - PK11Session *session; - CK_ULONG key_length = 0; - unsigned char * buf = NULL; - CK_RV crv = CKR_OK; - int i; - CK_ULONG bsize = ulWrappedKeyLen; - PK11Slot *slot = pk11_SlotFromSessionHandle(hSession); - SECItem bpki; - CK_OBJECT_CLASS target_type = CKO_SECRET_KEY; - - /* - * now lets create an object to hang the attributes off of - */ - key = pk11_NewObject(slot); /* fill in the handle later */ - if (key == NULL) { - return CKR_HOST_MEMORY; - } - - /* - * load the template values into the object - */ - for (i=0; i < (int) ulAttributeCount; i++) { - if (pTemplate[i].type == CKA_VALUE_LEN) { - key_length = *(CK_ULONG *)pTemplate[i].pValue; - continue; - } - if (pTemplate[i].type == CKA_CLASS) { - target_type = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; - } - crv = pk11_AddAttributeType(key,pk11_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; - } - if (crv != CKR_OK) { - pk11_FreeObject(key); - return crv; - } - - crv = pk11_CryptInit(hSession,pMechanism,hUnwrappingKey,CKA_UNWRAP, - PK11_DECRYPT, PR_FALSE); - if (crv != CKR_OK) { - pk11_FreeObject(key); - return pk11_mapWrap(crv); - } - - /* allocate the buffer to decrypt into - * this assumes the unwrapped key is never larger than the - * wrapped key. For all the mechanisms we support this is true */ - buf = (unsigned char *)PORT_Alloc( ulWrappedKeyLen); - bsize = ulWrappedKeyLen; - - crv = NSC_Decrypt(hSession, pWrappedKey, ulWrappedKeyLen, buf, &bsize); - if (crv != CKR_OK) { - pk11_FreeObject(key); - PORT_Free(buf); - return pk11_mapWrap(crv); - } - - switch(target_type) { - case CKO_SECRET_KEY: - if (!pk11_hasAttribute(key,CKA_KEY_TYPE)) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - - if (key_length == 0 || key_length > bsize) { - key_length = bsize; - } - if (key_length > MAX_KEY_LEN) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - - /* add the value */ - crv = pk11_AddAttributeType(key,CKA_VALUE,buf,key_length); - break; - case CKO_PRIVATE_KEY: - bpki.data = (unsigned char *)buf; - bpki.len = bsize; - crv = CKR_OK; - if(pk11_unwrapPrivateKey(key, &bpki) != SECSuccess) { - crv = CKR_TEMPLATE_INCOMPLETE; - } - break; - default: - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - - PORT_ZFree(buf, bsize); - if (crv != CKR_OK) { pk11_FreeObject(key); return crv; } - - /* get the session */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - pk11_FreeObject(key); - return CKR_SESSION_HANDLE_INVALID; - } - - /* - * handle the base object stuff - */ - crv = pk11_handleObject(key,session); - *phKey = key->handle; - pk11_FreeSession(session); - pk11_FreeObject(key); - - return crv; - -} - -/* - * The SSL key gen mechanism create's lots of keys. This function handles the - * details of each of these key creation. - */ -static CK_RV -pk11_buildSSLKey(CK_SESSION_HANDLE hSession, PK11Object *baseKey, - PRBool isMacKey, unsigned char *keyBlock, unsigned int keySize, - CK_OBJECT_HANDLE *keyHandle) -{ - PK11Object *key; - PK11Session *session; - CK_KEY_TYPE keyType = CKK_GENERIC_SECRET; - CK_BBOOL cktrue = CK_TRUE; - CK_BBOOL ckfalse = CK_FALSE; - CK_RV crv = CKR_HOST_MEMORY; - - /* - * now lets create an object to hang the attributes off of - */ - *keyHandle = CK_INVALID_HANDLE; - key = pk11_NewObject(baseKey->slot); - if (key == NULL) return CKR_HOST_MEMORY; - pk11_narrowToSessionObject(key)->wasDerived = PR_TRUE; - - crv = pk11_CopyObject(key,baseKey); - if (crv != CKR_OK) goto loser; - if (isMacKey) { - crv = pk11_forceAttribute(key,CKA_KEY_TYPE,&keyType,sizeof(keyType)); - if (crv != CKR_OK) goto loser; - crv = pk11_forceAttribute(key,CKA_DERIVE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = pk11_forceAttribute(key,CKA_ENCRYPT,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = pk11_forceAttribute(key,CKA_DECRYPT,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = pk11_forceAttribute(key,CKA_SIGN,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = pk11_forceAttribute(key,CKA_VERIFY,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = pk11_forceAttribute(key,CKA_WRAP,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = pk11_forceAttribute(key,CKA_UNWRAP,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - } - crv = pk11_forceAttribute(key,CKA_VALUE,keyBlock,keySize); - if (crv != CKR_OK) goto loser; - - /* get the session */ - crv = CKR_HOST_MEMORY; - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { goto loser; } - - crv = pk11_handleObject(key,session); - pk11_FreeSession(session); - *keyHandle = key->handle; -loser: - if (key) pk11_FreeObject(key); - return crv; -} - -/* - * if there is an error, we need to free the keys we already created in SSL - * This is the routine that will do it.. - */ -static void -pk11_freeSSLKeys(CK_SESSION_HANDLE session, - CK_SSL3_KEY_MAT_OUT *returnedMaterial ) -{ - if (returnedMaterial->hClientMacSecret != CK_INVALID_HANDLE) { - NSC_DestroyObject(session,returnedMaterial->hClientMacSecret); - } - if (returnedMaterial->hServerMacSecret != CK_INVALID_HANDLE) { - NSC_DestroyObject(session, returnedMaterial->hServerMacSecret); - } - if (returnedMaterial->hClientKey != CK_INVALID_HANDLE) { - NSC_DestroyObject(session, returnedMaterial->hClientKey); - } - if (returnedMaterial->hServerKey != CK_INVALID_HANDLE) { - NSC_DestroyObject(session, returnedMaterial->hServerKey); - } -} - -/* - * when deriving from sensitive and extractable keys, we need to preserve some - * of the semantics in the derived key. This helper routine maintains these - * semantics. - */ -static CK_RV -pk11_DeriveSensitiveCheck(PK11Object *baseKey,PK11Object *destKey) -{ - PRBool hasSensitive; - PRBool sensitive = PR_FALSE; - PRBool hasExtractable; - PRBool extractable = PR_TRUE; - CK_RV crv = CKR_OK; - PK11Attribute *att; - - hasSensitive = PR_FALSE; - att = pk11_FindAttribute(destKey,CKA_SENSITIVE); - if (att) { - hasSensitive = PR_TRUE; - sensitive = (PRBool) *(CK_BBOOL *)att->attrib.pValue; - pk11_FreeAttribute(att); - } - - hasExtractable = PR_FALSE; - att = pk11_FindAttribute(destKey,CKA_EXTRACTABLE); - if (att) { - hasExtractable = PR_TRUE; - extractable = (PRBool) *(CK_BBOOL *)att->attrib.pValue; - pk11_FreeAttribute(att); - } - - - /* don't make a key more accessible */ - if (pk11_isTrue(baseKey,CKA_SENSITIVE) && hasSensitive && - (sensitive == PR_FALSE)) { - return CKR_KEY_FUNCTION_NOT_PERMITTED; - } - if (!pk11_isTrue(baseKey,CKA_EXTRACTABLE) && hasExtractable && - (extractable == PR_TRUE)) { - return CKR_KEY_FUNCTION_NOT_PERMITTED; - } - - /* inherit parent's sensitivity */ - if (!hasSensitive) { - att = pk11_FindAttribute(baseKey,CKA_SENSITIVE); - if (att == NULL) return CKR_KEY_TYPE_INCONSISTENT; - crv = pk11_defaultAttribute(destKey,pk11_attr_expand(&att->attrib)); - pk11_FreeAttribute(att); - if (crv != CKR_OK) return crv; - } - if (!hasExtractable) { - att = pk11_FindAttribute(baseKey,CKA_EXTRACTABLE); - if (att == NULL) return CKR_KEY_TYPE_INCONSISTENT; - crv = pk11_defaultAttribute(destKey,pk11_attr_expand(&att->attrib)); - pk11_FreeAttribute(att); - if (crv != CKR_OK) return crv; - } - - /* we should inherit the parent's always extractable/ never sensitive info, - * but handleObject always forces this attributes, so we would need to do - * something special. */ - return CKR_OK; -} - -/* - * make known fixed PKCS #11 key types to their sizes in bytes - */ -unsigned long -pk11_MapKeySize(CK_KEY_TYPE keyType) -{ - switch (keyType) { - case CKK_CDMF: - return 8; - case CKK_DES: - return 8; - case CKK_DES2: - return 16; - case CKK_DES3: - return 24; - /* IDEA and CAST need to be added */ - default: - break; - } - return 0; -} - -/* - * SSL Key generation given pre master secret - */ -#define NUM_MIXERS 9 -static const char * const mixers[NUM_MIXERS] = { - "A", - "BB", - "CCC", - "DDDD", - "EEEEE", - "FFFFFF", - "GGGGGGG", - "HHHHHHHH", - "IIIIIIIII" }; -#define SSL3_PMS_LENGTH 48 -#define SSL3_MASTER_SECRET_LENGTH 48 - - -/* NSC_DeriveKey derives a key from a base key, creating a new key object. */ -CK_RV NSC_DeriveKey( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) -{ - PK11Session * session; - PK11Slot * slot = pk11_SlotFromSessionHandle(hSession); - PK11Object * key; - PK11Object * sourceKey; - PK11Attribute * att; - PK11Attribute * att2; - unsigned char * buf; - SHA1Context * sha; - MD5Context * md5; - MD2Context * md2; - CK_ULONG macSize; - CK_ULONG tmpKeySize; - CK_ULONG IVSize; - CK_ULONG keySize = 0; - CK_RV crv = CKR_OK; - CK_BBOOL cktrue = CK_TRUE; - CK_KEY_TYPE keyType = CKK_GENERIC_SECRET; - CK_OBJECT_CLASS classType = CKO_SECRET_KEY; - CK_KEY_DERIVATION_STRING_DATA *stringPtr; - PRBool isTLS = PR_FALSE; - PRBool isDH = PR_FALSE; - SECStatus rv; - int i; - unsigned int outLen; - unsigned char sha_out[SHA1_LENGTH]; - unsigned char key_block[NUM_MIXERS * MD5_LENGTH]; - unsigned char key_block2[MD5_LENGTH]; - PRBool isFIPS; - - /* - * now lets create an object to hang the attributes off of - */ - if (phKey) *phKey = CK_INVALID_HANDLE; - - key = pk11_NewObject(slot); /* fill in the handle later */ - if (key == NULL) { - return CKR_HOST_MEMORY; - } - isFIPS = (slot->slotID == FIPS_SLOT_ID); - - /* - * load the template values into the object - */ - for (i=0; i < (int) ulAttributeCount; i++) { - crv = pk11_AddAttributeType(key,pk11_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; - - if (pTemplate[i].type == CKA_KEY_TYPE) { - keyType = *(CK_KEY_TYPE *)pTemplate[i].pValue; - } - if (pTemplate[i].type == CKA_VALUE_LEN) { - keySize = *(CK_ULONG *)pTemplate[i].pValue; - } - } - if (crv != CKR_OK) { pk11_FreeObject(key); return crv; } - - if (keySize == 0) { - keySize = pk11_MapKeySize(keyType); - } - - /* Derive can only create SECRET KEY's currently... */ - classType = CKO_SECRET_KEY; - crv = pk11_forceAttribute (key,CKA_CLASS,&classType,sizeof(classType)); - if (crv != CKR_OK) { - pk11_FreeObject(key); - return crv; - } - - /* look up the base key we're deriving with */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - pk11_FreeObject(key); - return CKR_SESSION_HANDLE_INVALID; - } - - sourceKey = pk11_ObjectFromHandle(hBaseKey,session); - pk11_FreeSession(session); - if (sourceKey == NULL) { - pk11_FreeObject(key); - return CKR_KEY_HANDLE_INVALID; - } - - /* don't use key derive to expose sensitive keys */ - crv = pk11_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) { - pk11_FreeObject(key); - pk11_FreeObject(sourceKey); - return crv; - } - - /* get the value of the base key */ - att = pk11_FindAttribute(sourceKey,CKA_VALUE); - if (att == NULL) { - pk11_FreeObject(key); - pk11_FreeObject(sourceKey); - return CKR_KEY_HANDLE_INVALID; - } - - switch (pMechanism->mechanism) { - /* - * generate the master secret - */ - case CKM_TLS_MASTER_KEY_DERIVE: - case CKM_TLS_MASTER_KEY_DERIVE_DH: - isTLS = PR_TRUE; - /* fall thru */ - case CKM_SSL3_MASTER_KEY_DERIVE: - case CKM_SSL3_MASTER_KEY_DERIVE_DH: - { - CK_SSL3_MASTER_KEY_DERIVE_PARAMS *ssl3_master; - SSL3RSAPreMasterSecret *rsa_pms; - if ((pMechanism->mechanism == CKM_SSL3_MASTER_KEY_DERIVE_DH) || - (pMechanism->mechanism == CKM_TLS_MASTER_KEY_DERIVE_DH)) - isDH = PR_TRUE; - - /* first do the consistancy checks */ - if (!isDH && (att->attrib.ulValueLen != SSL3_PMS_LENGTH)) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att2 = pk11_FindAttribute(sourceKey,CKA_KEY_TYPE); - if ((att2 == NULL) || (*(CK_KEY_TYPE *)att2->attrib.pValue != - CKK_GENERIC_SECRET)) { - if (att2) pk11_FreeAttribute(att2); - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - pk11_FreeAttribute(att2); - if (keyType != CKK_GENERIC_SECRET) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - if ((keySize != 0) && (keySize != SSL3_MASTER_SECRET_LENGTH)) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - - - /* finally do the key gen */ - ssl3_master = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *) - pMechanism->pParameter; - if (ssl3_master->pVersion) { - PK11SessionObject *sessKey = pk11_narrowToSessionObject(key); - rsa_pms = (SSL3RSAPreMasterSecret *) att->attrib.pValue; - /* don't leak more key material then necessary for SSL to work */ - if ((sessKey == NULL) || sessKey->wasDerived) { - ssl3_master->pVersion->major = 0xff; - ssl3_master->pVersion->minor = 0xff; - } else { - ssl3_master->pVersion->major = rsa_pms->client_version[0]; - ssl3_master->pVersion->minor = rsa_pms->client_version[1]; - } - } - if (ssl3_master->RandomInfo.ulClientRandomLen != SSL3_RANDOM_LENGTH) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - if (ssl3_master->RandomInfo.ulServerRandomLen != SSL3_RANDOM_LENGTH) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - - if (isTLS) { - unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; - SECItem crsr = { siBuffer, NULL, 0 }; - SECItem master = { siBuffer, NULL, 0 }; - SECItem pms = { siBuffer, NULL, 0 }; - SECStatus status; - - pms.data = (unsigned char*)att->attrib.pValue; - pms.len = att->attrib.ulValueLen; - master.data = key_block; - master.len = SSL3_MASTER_SECRET_LENGTH; - crsr.data = crsrdata; - crsr.len = sizeof(crsrdata); - - PORT_Memcpy(crsrdata, ssl3_master->RandomInfo.pClientRandom, - SSL3_RANDOM_LENGTH); - PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, - ssl3_master->RandomInfo.pServerRandom, SSL3_RANDOM_LENGTH); - - status = pk11_PRF(&pms, "master secret", &crsr, &master, isFIPS); - if (status != SECSuccess) { - crv = CKR_FUNCTION_FAILED; - break; - } - } else { - /* now allocate the hash contexts */ - md5 = MD5_NewContext(); - if (md5 == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - sha = SHA1_NewContext(); - if (sha == NULL) { - PORT_Free(md5); - crv = CKR_HOST_MEMORY; - break; - } - for (i = 0; i < 3; i++) { - SHA1_Begin(sha); - SHA1_Update(sha, (unsigned char*) mixers[i], strlen(mixers[i])); - SHA1_Update(sha, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - SHA1_Update(sha, ssl3_master->RandomInfo.pClientRandom, - ssl3_master->RandomInfo.ulClientRandomLen); - SHA1_Update(sha, ssl3_master->RandomInfo.pServerRandom, - ssl3_master->RandomInfo.ulServerRandomLen); - SHA1_End(sha, sha_out, &outLen, SHA1_LENGTH); - PORT_Assert(outLen == SHA1_LENGTH); - MD5_Begin(md5); - MD5_Update(md5, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - MD5_Update(md5, sha_out, outLen); - MD5_End(md5, &key_block[i*MD5_LENGTH], &outLen, MD5_LENGTH); - PORT_Assert(outLen == MD5_LENGTH); - } - PORT_Free(md5); - PORT_Free(sha); - } - - /* store the results */ - crv = pk11_forceAttribute - (key,CKA_VALUE,key_block,SSL3_MASTER_SECRET_LENGTH); - if (crv != CKR_OK) break; - keyType = CKK_GENERIC_SECRET; - crv = pk11_forceAttribute (key,CKA_KEY_TYPE,&keyType,sizeof(keyType)); - if (isTLS) { - /* TLS's master secret is used to "sign" finished msgs with PRF. */ - /* XXX This seems like a hack. But PK11_Derive only accepts - * one "operation" argument. */ - crv = pk11_forceAttribute(key,CKA_SIGN, &cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) break; - crv = pk11_forceAttribute(key,CKA_VERIFY,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) break; - /* While we're here, we might as well force this, too. */ - crv = pk11_forceAttribute(key,CKA_DERIVE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) break; - } - break; - } - - case CKM_TLS_KEY_AND_MAC_DERIVE: - isTLS = PR_TRUE; - /* fall thru */ - case CKM_SSL3_KEY_AND_MAC_DERIVE: - { - CK_SSL3_KEY_MAT_PARAMS *ssl3_keys; - CK_SSL3_KEY_MAT_OUT * ssl3_keys_out; - CK_ULONG effKeySize; - - crv = pk11_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - if (att->attrib.ulValueLen != SSL3_MASTER_SECRET_LENGTH) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - att2 = pk11_FindAttribute(sourceKey,CKA_KEY_TYPE); - if ((att2 == NULL) || (*(CK_KEY_TYPE *)att2->attrib.pValue != - CKK_GENERIC_SECRET)) { - if (att2) pk11_FreeAttribute(att2); - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - pk11_FreeAttribute(att2); - md5 = MD5_NewContext(); - if (md5 == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - sha = SHA1_NewContext(); - if (sha == NULL) { - PORT_Free(md5); - crv = CKR_HOST_MEMORY; - break; - } - ssl3_keys = (CK_SSL3_KEY_MAT_PARAMS *) pMechanism->pParameter; - /* - * clear out our returned keys so we can recover on failure - */ - ssl3_keys_out = ssl3_keys->pReturnedKeyMaterial; - ssl3_keys_out->hClientMacSecret = CK_INVALID_HANDLE; - ssl3_keys_out->hServerMacSecret = CK_INVALID_HANDLE; - ssl3_keys_out->hClientKey = CK_INVALID_HANDLE; - ssl3_keys_out->hServerKey = CK_INVALID_HANDLE; - - /* - * generate the key material: This looks amazingly similar to the - * PMS code, and is clearly crying out for a function to provide it. - */ - if (isTLS) { - SECStatus status; - SECItem master = { siBuffer, NULL, 0 }; - SECItem srcr = { siBuffer, NULL, 0 }; - SECItem keyblk = { siBuffer, NULL, 0 }; - unsigned char srcrdata[SSL3_RANDOM_LENGTH * 2]; - - master.data = (unsigned char*)att->attrib.pValue; - master.len = att->attrib.ulValueLen; - srcr.data = srcrdata; - srcr.len = sizeof srcrdata; - keyblk.data = key_block; - keyblk.len = sizeof key_block; - - PORT_Memcpy(srcrdata, - ssl3_keys->RandomInfo.pServerRandom, - SSL3_RANDOM_LENGTH); - PORT_Memcpy(srcrdata + SSL3_RANDOM_LENGTH, - ssl3_keys->RandomInfo.pClientRandom, - SSL3_RANDOM_LENGTH); - - status = pk11_PRF(&master, "key expansion", &srcr, &keyblk, - isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - } else { - /* key_block = - * MD5(master_secret + SHA('A' + master_secret + - * ServerHello.random + ClientHello.random)) + - * MD5(master_secret + SHA('BB' + master_secret + - * ServerHello.random + ClientHello.random)) + - * MD5(master_secret + SHA('CCC' + master_secret + - * ServerHello.random + ClientHello.random)) + - * [...]; - */ - for (i = 0; i < NUM_MIXERS; i++) { - SHA1_Begin(sha); - SHA1_Update(sha, (unsigned char*) mixers[i], strlen(mixers[i])); - SHA1_Update(sha, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - SHA1_Update(sha, ssl3_keys->RandomInfo.pServerRandom, - ssl3_keys->RandomInfo.ulServerRandomLen); - SHA1_Update(sha, ssl3_keys->RandomInfo.pClientRandom, - ssl3_keys->RandomInfo.ulClientRandomLen); - SHA1_End(sha, sha_out, &outLen, SHA1_LENGTH); - PORT_Assert(outLen == SHA1_LENGTH); - MD5_Begin(md5); - MD5_Update(md5, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - MD5_Update(md5, sha_out, outLen); - MD5_End(md5, &key_block[i*MD5_LENGTH], &outLen, MD5_LENGTH); - PORT_Assert(outLen == MD5_LENGTH); - } - } - - /* - * Put the key material where it goes. - */ - i = 0; /* now shows how much consumed */ - macSize = ssl3_keys->ulMacSizeInBits/8; - effKeySize = ssl3_keys->ulKeySizeInBits/8; - IVSize = ssl3_keys->ulIVSizeInBits/8; - if (keySize == 0) { - effKeySize = keySize; - } - - /* - * The key_block is partitioned as follows: - * client_write_MAC_secret[CipherSpec.hash_size] - */ - crv = pk11_buildSSLKey(hSession,key,PR_TRUE,&key_block[i],macSize, - &ssl3_keys_out->hClientMacSecret); - if (crv != CKR_OK) - goto key_and_mac_derive_fail; - - i += macSize; - - /* - * server_write_MAC_secret[CipherSpec.hash_size] - */ - crv = pk11_buildSSLKey(hSession,key,PR_TRUE,&key_block[i],macSize, - &ssl3_keys_out->hServerMacSecret); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - i += macSize; - - if (keySize) { - if (!ssl3_keys->bIsExport) { - /* - ** Generate Domestic write keys and IVs. - ** client_write_key[CipherSpec.key_material] - */ - crv = pk11_buildSSLKey(hSession,key,PR_FALSE,&key_block[i], - keySize, &ssl3_keys_out->hClientKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - i += keySize; - - /* - ** server_write_key[CipherSpec.key_material] - */ - crv = pk11_buildSSLKey(hSession,key,PR_FALSE,&key_block[i], - keySize, &ssl3_keys_out->hServerKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - i += keySize; - - /* - ** client_write_IV[CipherSpec.IV_size] - */ - if (IVSize > 0) { - PORT_Memcpy(ssl3_keys_out->pIVClient, - &key_block[i], IVSize); - i += IVSize; - } - - /* - ** server_write_IV[CipherSpec.IV_size] - */ - if (IVSize > 0) { - PORT_Memcpy(ssl3_keys_out->pIVServer, - &key_block[i], IVSize); - i += IVSize; - } - PORT_Assert(i <= sizeof key_block); - - } else if (!isTLS) { - - /* - ** Generate SSL3 Export write keys and IVs. - ** client_write_key[CipherSpec.key_material] - ** final_client_write_key = MD5(client_write_key + - ** ClientHello.random + ServerHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, &key_block[i], effKeySize); - MD5_Update(md5, ssl3_keys->RandomInfo.pClientRandom, - ssl3_keys->RandomInfo.ulClientRandomLen); - MD5_Update(md5, ssl3_keys->RandomInfo.pServerRandom, - ssl3_keys->RandomInfo.ulServerRandomLen); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - i += effKeySize; - crv = pk11_buildSSLKey(hSession,key,PR_FALSE,key_block2, - keySize,&ssl3_keys_out->hClientKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** server_write_key[CipherSpec.key_material] - ** final_server_write_key = MD5(server_write_key + - ** ServerHello.random + ClientHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, &key_block[i], effKeySize); - MD5_Update(md5, ssl3_keys->RandomInfo.pServerRandom, - ssl3_keys->RandomInfo.ulServerRandomLen); - MD5_Update(md5, ssl3_keys->RandomInfo.pClientRandom, - ssl3_keys->RandomInfo.ulClientRandomLen); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - i += effKeySize; - crv = pk11_buildSSLKey(hSession,key,PR_FALSE,key_block2, - keySize,&ssl3_keys_out->hServerKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** client_write_IV = - ** MD5(ClientHello.random + ServerHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, ssl3_keys->RandomInfo.pClientRandom, - ssl3_keys->RandomInfo.ulClientRandomLen); - MD5_Update(md5, ssl3_keys->RandomInfo.pServerRandom, - ssl3_keys->RandomInfo.ulServerRandomLen); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - PORT_Memcpy(ssl3_keys_out->pIVClient, key_block2, IVSize); - - /* - ** server_write_IV = - ** MD5(ServerHello.random + ClientHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, ssl3_keys->RandomInfo.pServerRandom, - ssl3_keys->RandomInfo.ulServerRandomLen); - MD5_Update(md5, ssl3_keys->RandomInfo.pClientRandom, - ssl3_keys->RandomInfo.ulClientRandomLen); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - PORT_Memcpy(ssl3_keys_out->pIVServer, key_block2, IVSize); - - } else { - - /* - ** Generate TLS Export write keys and IVs. - */ - SECStatus status; - SECItem secret = { siBuffer, NULL, 0 }; - SECItem crsr = { siBuffer, NULL, 0 }; - SECItem keyblk = { siBuffer, NULL, 0 }; - unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; - - crsr.data = crsrdata; - crsr.len = sizeof crsrdata; - - PORT_Memcpy(crsrdata, - ssl3_keys->RandomInfo.pClientRandom, - SSL3_RANDOM_LENGTH); - PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, - ssl3_keys->RandomInfo.pServerRandom, - SSL3_RANDOM_LENGTH); - - - /* - ** client_write_key[CipherSpec.key_material] - ** final_client_write_key = PRF(client_write_key, - ** "client write key", - ** client_random + server_random); - */ - secret.data = &key_block[i]; - secret.len = effKeySize; - i += effKeySize; - keyblk.data = key_block2; - keyblk.len = sizeof key_block2; - status = pk11_PRF(&secret, "client write key", &crsr, &keyblk, - isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - crv = pk11_buildSSLKey(hSession, key, PR_FALSE, key_block2, - keySize, &ssl3_keys_out->hClientKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** server_write_key[CipherSpec.key_material] - ** final_server_write_key = PRF(server_write_key, - ** "server write key", - ** client_random + server_random); - */ - secret.data = &key_block[i]; - secret.len = effKeySize; - i += effKeySize; - keyblk.data = key_block2; - keyblk.len = sizeof key_block2; - status = pk11_PRF(&secret, "server write key", &crsr, &keyblk, - isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - crv = pk11_buildSSLKey(hSession, key, PR_FALSE, key_block2, - keySize, &ssl3_keys_out->hServerKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** iv_block = PRF("", "IV block", - ** client_random + server_random); - ** client_write_IV[SecurityParameters.IV_size] - ** server_write_IV[SecurityParameters.IV_size] - */ - if (IVSize) { - secret.data = NULL; - secret.len = 0; - keyblk.data = &key_block[i]; - keyblk.len = 2 * IVSize; - status = pk11_PRF(&secret, "IV block", &crsr, &keyblk, - isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - PORT_Memcpy(ssl3_keys_out->pIVClient, keyblk.data, IVSize); - PORT_Memcpy(ssl3_keys_out->pIVServer, keyblk.data + IVSize, - IVSize); - } - } - } - - crv = CKR_OK; - - if (0) { -key_and_mac_derive_fail: - if (crv == CKR_OK) - crv = CKR_FUNCTION_FAILED; - pk11_freeSSLKeys(hSession, ssl3_keys_out); - } - MD5_DestroyContext(md5, PR_TRUE); - SHA1_DestroyContext(sha, PR_TRUE); - pk11_FreeObject(key); - key = NULL; - break; - } - - case CKM_CONCATENATE_BASE_AND_KEY: - { - PK11Object *newKey; - - crv = pk11_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - crv = CKR_SESSION_HANDLE_INVALID; - break; - } - - newKey = pk11_ObjectFromHandle(*(CK_OBJECT_HANDLE *) - pMechanism->pParameter,session); - pk11_FreeSession(session); - if ( newKey == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - - if (pk11_isTrue(newKey,CKA_SENSITIVE)) { - crv = pk11_forceAttribute(newKey,CKA_SENSITIVE,&cktrue, - sizeof(CK_BBOOL)); - if (crv != CKR_OK) { - pk11_FreeObject(newKey); - break; - } - } - - att2 = pk11_FindAttribute(newKey,CKA_VALUE); - if (att2 == NULL) { - pk11_FreeObject(newKey); - crv = CKR_KEY_HANDLE_INVALID; - break; - } - tmpKeySize = att->attrib.ulValueLen+att2->attrib.ulValueLen; - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - pk11_FreeObject(newKey); - pk11_FreeAttribute(att2); - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(tmpKeySize); - if (buf == NULL) { - pk11_FreeAttribute(att2); - pk11_FreeObject(newKey); - crv = CKR_HOST_MEMORY; - break; - } - - PORT_Memcpy(buf,att->attrib.pValue,att->attrib.ulValueLen); - PORT_Memcpy(buf+att->attrib.ulValueLen, - att2->attrib.pValue,att2->attrib.ulValueLen); - - crv = pk11_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,tmpKeySize); - pk11_FreeAttribute(att2); - pk11_FreeObject(newKey); - break; - } - - case CKM_CONCATENATE_BASE_AND_DATA: - stringPtr = (CK_KEY_DERIVATION_STRING_DATA *) pMechanism->pParameter; - tmpKeySize = att->attrib.ulValueLen+stringPtr->ulLen; - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(tmpKeySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - PORT_Memcpy(buf,att->attrib.pValue,att->attrib.ulValueLen); - PORT_Memcpy(buf+att->attrib.ulValueLen,stringPtr->pData, - stringPtr->ulLen); - - crv = pk11_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,tmpKeySize); - break; - case CKM_CONCATENATE_DATA_AND_BASE: - stringPtr = (CK_KEY_DERIVATION_STRING_DATA *)pMechanism->pParameter; - tmpKeySize = att->attrib.ulValueLen+stringPtr->ulLen; - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(tmpKeySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - PORT_Memcpy(buf,stringPtr->pData,stringPtr->ulLen); - PORT_Memcpy(buf+stringPtr->ulLen,att->attrib.pValue, - att->attrib.ulValueLen); - - crv = pk11_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,tmpKeySize); - break; - case CKM_XOR_BASE_AND_DATA: - stringPtr = (CK_KEY_DERIVATION_STRING_DATA *)pMechanism->pParameter; - tmpKeySize = PR_MIN(att->attrib.ulValueLen,stringPtr->ulLen); - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(keySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - - PORT_Memcpy(buf,att->attrib.pValue,keySize); - for (i=0; i < (int)keySize; i++) { - buf[i] ^= stringPtr->pData[i]; - } - - crv = pk11_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,keySize); - break; - - case CKM_EXTRACT_KEY_FROM_KEY: - { - /* the following assumes 8 bits per byte */ - CK_ULONG extract = *(CK_EXTRACT_PARAMS *)pMechanism->pParameter; - CK_ULONG shift = extract & 0x7; /* extract mod 8 the fast way */ - CK_ULONG offset = extract >> 3; /* extract div 8 the fast way */ - - if (keySize == 0) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - /* make sure we have enough bits in the original key */ - if (att->attrib.ulValueLen < - (offset + keySize + ((shift != 0)? 1 :0)) ) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - buf = (unsigned char*)PORT_Alloc(keySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - /* copy the bits we need into the new key */ - for (i=0; i < (int)keySize; i++) { - unsigned char *value = - ((unsigned char *)att->attrib.pValue)+offset+i; - if (shift) { - buf[i] = (value[0] << (shift)) | (value[1] >> (8 - shift)); - } else { - buf[i] = value[0]; - } - } - - crv = pk11_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,keySize); - break; - } - case CKM_MD2_KEY_DERIVATION: - if (keySize == 0) keySize = MD2_LENGTH; - if (keySize > MD2_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - /* now allocate the hash contexts */ - md2 = MD2_NewContext(); - if (md2 == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - MD2_Begin(md2); - MD2_Update(md2,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - MD2_End(md2,key_block,&outLen,MD2_LENGTH); - MD2_DestroyContext(md2, PR_TRUE); - - crv = pk11_forceAttribute (key,CKA_VALUE,key_block,keySize); - break; - case CKM_MD5_KEY_DERIVATION: - if (keySize == 0) keySize = MD5_LENGTH; - if (keySize > MD5_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - /* now allocate the hash contexts */ - md5 = MD5_NewContext(); - if (md5 == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - MD5_Begin(md5); - MD5_Update(md5,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - MD5_End(md5,key_block,&outLen,MD5_LENGTH); - MD5_DestroyContext(md5, PR_TRUE); - - crv = pk11_forceAttribute (key,CKA_VALUE,key_block,keySize); - break; - case CKM_SHA1_KEY_DERIVATION: - if (keySize == 0) keySize = SHA1_LENGTH; - if (keySize > SHA1_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - /* now allocate the hash contexts */ - sha = SHA1_NewContext(); - if (sha == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - SHA1_Begin(sha); - SHA1_Update(sha,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - SHA1_End(sha,key_block,&outLen,SHA1_LENGTH); - SHA1_DestroyContext(sha, PR_TRUE); - - crv = pk11_forceAttribute(key,CKA_VALUE,key_block,keySize); - break; - - case CKM_DH_PKCS_DERIVE: - { - SECItem derived, dhPublic; - SECItem dhPrime, dhValue; - /* sourceKey - values for the local existing low key */ - /* get prime and value attributes */ - crv = pk11_Attribute2SecItem(NULL, &dhPrime, sourceKey, CKA_PRIME); - if (crv != SECSuccess) break; - crv = pk11_Attribute2SecItem(NULL, &dhValue, sourceKey, CKA_VALUE); - if (crv != SECSuccess) { - PORT_Free(dhPrime.data); - break; - } - - dhPublic.data = pMechanism->pParameter; - dhPublic.len = pMechanism->ulParameterLen; - - /* calculate private value - oct */ - rv = DH_Derive(&dhPublic, &dhPrime, &dhValue, &derived, keySize); - - PORT_Free(dhPrime.data); - PORT_Free(dhValue.data); - - if (rv == SECSuccess) { - pk11_forceAttribute(key, CKA_VALUE, derived.data, derived.len); - PORT_ZFree(derived.data, derived.len); - } else - crv = CKR_HOST_MEMORY; - - break; - } - -#ifdef NSS_ENABLE_ECC - case CKM_ECDH1_DERIVE: - case CKM_ECDH1_COFACTOR_DERIVE: - { - SECItem ecScalar, ecPoint; - SECItem tmp; - PRBool withCofactor = PR_FALSE; - unsigned char secret_hash[20]; - unsigned char *secret; - int secretlen; - CK_ECDH1_DERIVE_PARAMS *mechParams; - NSSLOWKEYPrivateKey *privKey; - - /* Check mechanism parameters */ - mechParams = (CK_ECDH1_DERIVE_PARAMS *) pMechanism->pParameter; - if ((pMechanism->ulParameterLen != sizeof(CK_ECDH1_DERIVE_PARAMS)) || - ((mechParams->kdf == CKD_NULL) && - ((mechParams->ulSharedDataLen != 0) || - (mechParams->pSharedData != NULL)))) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - - privKey = pk11_GetPrivKey(sourceKey, CKK_EC, &crv); - if (privKey == NULL) { - break; - } - - /* Now we are working with a non-NULL private key */ - SECITEM_CopyItem(NULL, &ecScalar, &privKey->u.ec.privateValue); - - ecPoint.data = mechParams->pPublicData; - ecPoint.len = mechParams->ulPublicDataLen; - - if (pMechanism->mechanism == CKM_ECDH1_COFACTOR_DERIVE) { - withCofactor = PR_TRUE; - } else { - /* When not using cofactor derivation, one should - * validate the public key to avoid small subgroup - * attacks. - */ - if (EC_ValidatePublicKey(&privKey->u.ec.ecParams, &ecPoint) - != SECSuccess) { - crv = CKR_ARGUMENTS_BAD; - PORT_Free(ecScalar.data); - if (privKey != sourceKey->objectInfo) - nsslowkey_DestroyPrivateKey(privKey); - break; - } - } - - rv = ECDH_Derive(&ecPoint, &privKey->u.ec.ecParams, &ecScalar, - withCofactor, &tmp); - PORT_Free(ecScalar.data); - if (privKey != sourceKey->objectInfo) - nsslowkey_DestroyPrivateKey(privKey); - - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - break; - } - - secret = tmp.data; - secretlen = tmp.len; - if (mechParams->kdf == CKD_SHA1_KDF) { - /* Compute SHA1 hash */ - memset(secret_hash, 0, 20); - rv = SHA1_HashBuf(secret_hash, tmp.data, tmp.len); - if (rv != SECSuccess) { - PORT_ZFree(tmp.data, tmp.len); - } else { - secret = secret_hash; - secretlen = 20; - } - } - - if (rv == SECSuccess) { - pk11_forceAttribute(key, CKA_VALUE, secret, secretlen); - PORT_ZFree(tmp.data, tmp.len); - memset(secret_hash, 0, 20); - } else - crv = CKR_HOST_MEMORY; - - break; - } -#endif /* NSS_ENABLE_ECC */ - - default: - crv = CKR_MECHANISM_INVALID; - } - pk11_FreeAttribute(att); - pk11_FreeObject(sourceKey); - if (crv != CKR_OK) { - if (key) pk11_FreeObject(key); - return crv; - } - - /* link the key object into the list */ - if (key) { - PK11SessionObject *sessKey = pk11_narrowToSessionObject(key); - PORT_Assert(sessKey); - /* get the session */ - sessKey->wasDerived = PR_TRUE; - session = pk11_SessionFromHandle(hSession); - if (session == NULL) { - pk11_FreeObject(key); - return CKR_HOST_MEMORY; - } - - crv = pk11_handleObject(key,session); - pk11_FreeSession(session); - *phKey = key->handle; - pk11_FreeObject(key); - } - return crv; -} - - -/* NSC_GetFunctionStatus obtains an updated status of a function running - * in parallel with an application. */ -CK_RV NSC_GetFunctionStatus(CK_SESSION_HANDLE hSession) -{ - return CKR_FUNCTION_NOT_PARALLEL; -} - -/* NSC_CancelFunction cancels a function running in parallel */ -CK_RV NSC_CancelFunction(CK_SESSION_HANDLE hSession) -{ - return CKR_FUNCTION_NOT_PARALLEL; -} - -/* NSC_GetOperationState saves the state of the cryptographic - *operation in a session. - * NOTE: This code only works for digest functions for now. eventually need - * to add full flatten/resurect to our state stuff so that all types of state - * can be saved */ -CK_RV NSC_GetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) -{ - PK11SessionContext *context; - PK11Session *session; - CK_RV crv; - CK_ULONG pOSLen = *pulOperationStateLen; - - /* make sure we're legal */ - crv = pk11_GetContext(hSession, &context, PK11_HASH, PR_TRUE, &session); - if (crv != CKR_OK) return crv; - - *pulOperationStateLen = context->cipherInfoLen + sizeof(CK_MECHANISM_TYPE) - + sizeof(PK11ContextType); - if (pOperationState == NULL) { - pk11_FreeSession(session); - return CKR_OK; - } else { - if (pOSLen < *pulOperationStateLen) { - return CKR_BUFFER_TOO_SMALL; - } - } - PORT_Memcpy(pOperationState,&context->type,sizeof(PK11ContextType)); - pOperationState += sizeof(PK11ContextType); - PORT_Memcpy(pOperationState,&context->currentMech, - sizeof(CK_MECHANISM_TYPE)); - pOperationState += sizeof(CK_MECHANISM_TYPE); - PORT_Memcpy(pOperationState,context->cipherInfo,context->cipherInfoLen); - pk11_FreeSession(session); - return CKR_OK; -} - - -#define pk11_Decrement(stateSize,len) \ - stateSize = ((stateSize) > (CK_ULONG)(len)) ? \ - ((stateSize) - (CK_ULONG)(len)) : 0; - -/* NSC_SetOperationState restores the state of the cryptographic - * operation in a session. This is coded like it can restore lots of - * states, but it only works for truly flat cipher structures. */ -CK_RV NSC_SetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, - CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) -{ - PK11SessionContext *context; - PK11Session *session; - PK11ContextType type; - CK_MECHANISM mech; - CK_RV crv = CKR_OK; - - while (ulOperationStateLen != 0) { - /* get what type of state we're dealing with... */ - PORT_Memcpy(&type,pOperationState, sizeof(PK11ContextType)); - - /* fix up session contexts based on type */ - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - context = pk11_ReturnContextByType(session, type); - pk11_SetContextByType(session, type, NULL); - if (context) { - pk11_FreeContext(context); - } - pOperationState += sizeof(PK11ContextType); - pk11_Decrement(ulOperationStateLen,sizeof(PK11ContextType)); - - - /* get the mechanism structure */ - PORT_Memcpy(&mech.mechanism,pOperationState,sizeof(CK_MECHANISM_TYPE)); - pOperationState += sizeof(CK_MECHANISM_TYPE); - pk11_Decrement(ulOperationStateLen, sizeof(CK_MECHANISM_TYPE)); - /* should be filled in... but not necessary for hash */ - mech.pParameter = NULL; - mech.ulParameterLen = 0; - switch (type) { - case PK11_HASH: - crv = NSC_DigestInit(hSession,&mech); - if (crv != CKR_OK) break; - crv = pk11_GetContext(hSession, &context, PK11_HASH, PR_TRUE, - NULL); - if (crv != CKR_OK) break; - PORT_Memcpy(context->cipherInfo,pOperationState, - context->cipherInfoLen); - pOperationState += context->cipherInfoLen; - pk11_Decrement(ulOperationStateLen,context->cipherInfoLen); - break; - default: - /* do sign/encrypt/decrypt later */ - crv = CKR_SAVED_STATE_INVALID; - } - pk11_FreeSession(session); - if (crv != CKR_OK) break; - } - return crv; -} - -/* Dual-function cryptographic operations */ - -/* NSC_DigestEncryptUpdate continues a multiple-part digesting and encryption - * operation. */ -CK_RV NSC_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) -{ - CK_RV crv; - - crv = NSC_EncryptUpdate(hSession,pPart,ulPartLen, pEncryptedPart, - pulEncryptedPartLen); - if (crv != CKR_OK) return crv; - crv = NSC_DigestUpdate(hSession,pPart,ulPartLen); - - return crv; -} - - -/* NSC_DecryptDigestUpdate continues a multiple-part decryption and - * digesting operation. */ -CK_RV NSC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) -{ - CK_RV crv; - - crv = NSC_DecryptUpdate(hSession,pEncryptedPart, ulEncryptedPartLen, - pPart, pulPartLen); - if (crv != CKR_OK) return crv; - crv = NSC_DigestUpdate(hSession,pPart,*pulPartLen); - - return crv; -} - - -/* NSC_SignEncryptUpdate continues a multiple-part signing and - * encryption operation. */ -CK_RV NSC_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) -{ - CK_RV crv; - - crv = NSC_EncryptUpdate(hSession,pPart,ulPartLen, pEncryptedPart, - pulEncryptedPartLen); - if (crv != CKR_OK) return crv; - crv = NSC_SignUpdate(hSession,pPart,ulPartLen); - - return crv; -} - - -/* NSC_DecryptVerifyUpdate continues a multiple-part decryption - * and verify operation. */ -CK_RV NSC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, - CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) -{ - CK_RV crv; - - crv = NSC_DecryptUpdate(hSession,pEncryptedData, ulEncryptedDataLen, - pData, pulDataLen); - if (crv != CKR_OK) return crv; - crv = NSC_VerifyUpdate(hSession, pData, *pulDataLen); - - return crv; -} - -/* NSC_DigestKey continues a multi-part message-digesting operation, - * by digesting the value of a secret key as part of the data already digested. - */ -CK_RV NSC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) -{ - PK11Session *session = NULL; - PK11Object *key = NULL; - PK11Attribute *att; - CK_RV crv; - - session = pk11_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - - key = pk11_ObjectFromHandle(hKey,session); - pk11_FreeSession(session); - if (key == NULL) return CKR_KEY_HANDLE_INVALID; - - /* PUT ANY DIGEST KEY RESTRICTION CHECKS HERE */ - - /* make sure it's a valid key for this operation */ - if (key->objclass != CKO_SECRET_KEY) { - pk11_FreeObject(key); - return CKR_KEY_TYPE_INCONSISTENT; - } - /* get the key value */ - att = pk11_FindAttribute(key,CKA_VALUE); - pk11_FreeObject(key); - - crv = NSC_DigestUpdate(hSession,(CK_BYTE_PTR)att->attrib.pValue, - att->attrib.ulValueLen); - pk11_FreeAttribute(att); - return crv; -} diff --git a/security/nss/lib/softoken/pkcs11f.h b/security/nss/lib/softoken/pkcs11f.h deleted file mode 100644 index 70d34da5e..000000000 --- a/security/nss/lib/softoken/pkcs11f.h +++ /dev/null @@ -1,934 +0,0 @@ -/* - * 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. - */ -/* - * Copyright (C) 1994-1999 RSA Security Inc. Licence to copy this document - * is granted provided that it is identified as "RSA Security In.c Public-Key - * Cryptography Standards (PKCS)" in all material mentioning or referencing - * this document. - */ -/* This function contains pretty much everything about all the */ -/* PKCS #11 function prototypes. Because this information is */ -/* used for more than just declaring function prototypes, the */ -/* order of the functions appearing herein is important, and */ -/* should not be altered. */ - - - -/* General-purpose */ - -/* C_Initialize initializes the PKCS #11 library. */ -CK_PKCS11_FUNCTION_INFO(C_Initialize) -#ifdef CK_NEED_ARG_LIST -( - CK_VOID_PTR pInitArgs /* if this is not NULL_PTR, it gets - * cast to CK_C_INITIALIZE_ARGS_PTR - * and dereferenced */ -); -#endif - - -/* C_Finalize indicates that an application is done with the - * PKCS #11 library. */ -CK_PKCS11_FUNCTION_INFO(C_Finalize) -#ifdef CK_NEED_ARG_LIST -( - CK_VOID_PTR pReserved /* reserved. Should be NULL_PTR */ -); -#endif - - -/* C_GetInfo returns general information about PKCS #11. */ -CK_PKCS11_FUNCTION_INFO(C_GetInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_INFO_PTR pInfo /* location that receives information */ -); -#endif - - -/* C_GetFunctionList returns the function list. */ -CK_PKCS11_FUNCTION_INFO(C_GetFunctionList) -#ifdef CK_NEED_ARG_LIST -( - CK_FUNCTION_LIST_PTR_PTR ppFunctionList /* receives pointer to - * function list */ -); -#endif - - - -/* Slot and token management */ - -/* C_GetSlotList obtains a list of slots in the system. */ -CK_PKCS11_FUNCTION_INFO(C_GetSlotList) -#ifdef CK_NEED_ARG_LIST -( - CK_BBOOL tokenPresent, /* only slots with tokens? */ - CK_SLOT_ID_PTR pSlotList, /* receives array of slot IDs */ - CK_ULONG_PTR pulCount /* receives number of slots */ -); -#endif - - -/* C_GetSlotInfo obtains information about a particular slot in - * the system. */ -CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* the ID of the slot */ - CK_SLOT_INFO_PTR pInfo /* receives the slot information */ -); -#endif - - -/* C_GetTokenInfo obtains information about a particular token - * in the system. */ -CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* ID of the token's slot */ - CK_TOKEN_INFO_PTR pInfo /* receives the token information */ -); -#endif - - -/* C_GetMechanismList obtains a list of mechanism types - * supported by a token. */ -CK_PKCS11_FUNCTION_INFO(C_GetMechanismList) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* ID of token's slot */ - CK_MECHANISM_TYPE_PTR pMechanismList, /* gets mech. array */ - CK_ULONG_PTR pulCount /* gets # of mechs. */ -); -#endif - - -/* C_GetMechanismInfo obtains information about a particular - * mechanism possibly supported by a token. */ -CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* ID of the token's slot */ - CK_MECHANISM_TYPE type, /* type of mechanism */ - CK_MECHANISM_INFO_PTR pInfo /* receives mechanism info */ -); -#endif - - -/* C_InitToken initializes a token. */ -CK_PKCS11_FUNCTION_INFO(C_InitToken) -#ifdef CK_NEED_ARG_LIST -( -/* pLabel changed from CK_CHAR_PTR to CK_UTF8CHAR_PTR for v2.10 */ - CK_SLOT_ID slotID, /* ID of the token's slot */ - CK_CHAR_PTR pPin, /* the SO's initial PIN */ - CK_ULONG ulPinLen, /* length in bytes of the PIN */ - CK_UTF8CHAR_PTR pLabel /* 32-byte token label (blank padded) */ -); -#endif - - -/* C_InitPIN initializes the normal user's PIN. */ -CK_PKCS11_FUNCTION_INFO(C_InitPIN) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_CHAR_PTR pPin, /* the normal user's PIN */ - CK_ULONG ulPinLen /* length in bytes of the PIN */ -); -#endif - - -/* C_SetPIN modifies the PIN of the user who is logged in. */ -CK_PKCS11_FUNCTION_INFO(C_SetPIN) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_CHAR_PTR pOldPin, /* the old PIN */ - CK_ULONG ulOldLen, /* length of the old PIN */ - CK_CHAR_PTR pNewPin, /* the new PIN */ - CK_ULONG ulNewLen /* length of the new PIN */ -); -#endif - - - -/* Session management */ - -/* C_OpenSession opens a session between an application and a - * token. */ -CK_PKCS11_FUNCTION_INFO(C_OpenSession) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID, /* the slot's ID */ - CK_FLAGS flags, /* from CK_SESSION_INFO */ - CK_VOID_PTR pApplication, /* passed to callback */ - CK_NOTIFY Notify, /* callback function */ - CK_SESSION_HANDLE_PTR phSession /* gets session handle */ -); -#endif - - -/* C_CloseSession closes a session between an application and a - * token. */ -CK_PKCS11_FUNCTION_INFO(C_CloseSession) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - -/* C_CloseAllSessions closes all sessions with a token. */ -CK_PKCS11_FUNCTION_INFO(C_CloseAllSessions) -#ifdef CK_NEED_ARG_LIST -( - CK_SLOT_ID slotID /* the token's slot */ -); -#endif - - -/* C_GetSessionInfo obtains information about the session. */ -CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_SESSION_INFO_PTR pInfo /* receives session info */ -); -#endif - - -/* C_GetOperationState obtains the state of the cryptographic operation - * in a session. */ -CK_PKCS11_FUNCTION_INFO(C_GetOperationState) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pOperationState, /* gets state */ - CK_ULONG_PTR pulOperationStateLen /* gets state length */ -); -#endif - - -/* C_SetOperationState restores the state of the cryptographic - * operation in a session. */ -CK_PKCS11_FUNCTION_INFO(C_SetOperationState) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pOperationState, /* holds state */ - CK_ULONG ulOperationStateLen, /* holds state length */ - CK_OBJECT_HANDLE hEncryptionKey, /* en/decryption key */ - CK_OBJECT_HANDLE hAuthenticationKey /* sign/verify key */ -); -#endif - - -/* C_Login logs a user into a token. */ -CK_PKCS11_FUNCTION_INFO(C_Login) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_USER_TYPE userType, /* the user type */ - CK_CHAR_PTR pPin, /* the user's PIN */ - CK_ULONG ulPinLen /* the length of the PIN */ -); -#endif - - -/* C_Logout logs a user out from a token. */ -CK_PKCS11_FUNCTION_INFO(C_Logout) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - - -/* Object management */ - -/* C_CreateObject creates a new object. */ -CK_PKCS11_FUNCTION_INFO(C_CreateObject) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* the object's template */ - CK_ULONG ulCount, /* attributes in template */ - CK_OBJECT_HANDLE_PTR phObject /* gets new object's handle. */ -); -#endif - - -/* C_CopyObject copies an object, creating a new object for the - * copy. */ -CK_PKCS11_FUNCTION_INFO(C_CopyObject) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* template for new object */ - CK_ULONG ulCount, /* attributes in template */ - CK_OBJECT_HANDLE_PTR phNewObject /* receives handle of copy */ -); -#endif - - -/* C_DestroyObject destroys an object. */ -CK_PKCS11_FUNCTION_INFO(C_DestroyObject) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject /* the object's handle */ -); -#endif - - -/* C_GetObjectSize gets the size of an object in bytes. */ -CK_PKCS11_FUNCTION_INFO(C_GetObjectSize) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ULONG_PTR pulSize /* receives size of object */ -); -#endif - - -/* C_GetAttributeValue obtains the value of one or more object - * attributes. */ -CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs; gets vals */ - CK_ULONG ulCount /* attributes in template */ -); -#endif - - -/* C_SetAttributeValue modifies the value of one or more object - * attributes */ -CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hObject, /* the object's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs and values */ - CK_ULONG ulCount /* attributes in template */ -); -#endif - - -/* C_FindObjectsInit initializes a search for token and session - * objects that match a template. */ -CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_ATTRIBUTE_PTR pTemplate, /* attribute values to match */ - CK_ULONG ulCount /* attrs in search template */ -); -#endif - - -/* C_FindObjects continues a search for token and session - * objects that match a template, obtaining additional object - * handles. */ -CK_PKCS11_FUNCTION_INFO(C_FindObjects) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_OBJECT_HANDLE_PTR phObject, /* gets obj. handles */ - CK_ULONG ulMaxObjectCount, /* max handles to get */ - CK_ULONG_PTR pulObjectCount /* actual # returned */ -); -#endif - - -/* C_FindObjectsFinal finishes a search for token and session - * objects. */ -CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - - -/* Encryption and decryption */ - -/* C_EncryptInit initializes an encryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_EncryptInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the encryption mechanism */ - CK_OBJECT_HANDLE hKey /* handle of encryption key */ -); -#endif - - -/* C_Encrypt encrypts single-part data. */ -CK_PKCS11_FUNCTION_INFO(C_Encrypt) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pData, /* the plaintext data */ - CK_ULONG ulDataLen, /* bytes of plaintext */ - CK_BYTE_PTR pEncryptedData, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedDataLen /* gets c-text size */ -); -#endif - - -/* C_EncryptUpdate continues a multiple-part encryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pPart, /* the plaintext data */ - CK_ULONG ulPartLen, /* plaintext data len */ - CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedPartLen /* gets c-text size */ -); -#endif - - -/* C_EncryptFinal finishes a multiple-part encryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_EncryptFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session handle */ - CK_BYTE_PTR pLastEncryptedPart, /* last c-text */ - CK_ULONG_PTR pulLastEncryptedPartLen /* gets last size */ -); -#endif - - -/* C_DecryptInit initializes a decryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the decryption mechanism */ - CK_OBJECT_HANDLE hKey /* handle of decryption key */ -); -#endif - - -/* C_Decrypt decrypts encrypted data in a single part. */ -CK_PKCS11_FUNCTION_INFO(C_Decrypt) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedData, /* ciphertext */ - CK_ULONG ulEncryptedDataLen, /* ciphertext length */ - CK_BYTE_PTR pData, /* gets plaintext */ - CK_ULONG_PTR pulDataLen /* gets p-text size */ -); -#endif - - -/* C_DecryptUpdate continues a multiple-part decryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedPart, /* encrypted data */ - CK_ULONG ulEncryptedPartLen, /* input length */ - CK_BYTE_PTR pPart, /* gets plaintext */ - CK_ULONG_PTR pulPartLen /* p-text size */ -); -#endif - - -/* C_DecryptFinal finishes a multiple-part decryption - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pLastPart, /* gets plaintext */ - CK_ULONG_PTR pulLastPartLen /* p-text size */ -); -#endif - - - -/* Message digesting */ - -/* C_DigestInit initializes a message-digesting operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism /* the digesting mechanism */ -); -#endif - - -/* C_Digest digests data in a single part. */ -CK_PKCS11_FUNCTION_INFO(C_Digest) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* data to be digested */ - CK_ULONG ulDataLen, /* bytes of data to digest */ - CK_BYTE_PTR pDigest, /* gets the message digest */ - CK_ULONG_PTR pulDigestLen /* gets digest length */ -); -#endif - - -/* C_DigestUpdate continues a multiple-part message-digesting - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pPart, /* data to be digested */ - CK_ULONG ulPartLen /* bytes of data to be digested */ -); -#endif - - -/* C_DigestKey continues a multi-part message-digesting - * operation, by digesting the value of a secret key as part of - * the data already digested. */ -CK_PKCS11_FUNCTION_INFO(C_DigestKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_OBJECT_HANDLE hKey /* secret key to digest */ -); -#endif - - -/* C_DigestFinal finishes a multiple-part message-digesting - * operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pDigest, /* gets the message digest */ - CK_ULONG_PTR pulDigestLen /* gets byte count of digest */ -); -#endif - - - -/* Signing and MACing */ - -/* C_SignInit initializes a signature (private key encryption) - * operation, where the signature is (will be) an appendix to - * the data, and plaintext cannot be recovered from the - *signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ - CK_OBJECT_HANDLE hKey /* handle of signature key */ -); -#endif - - -/* C_Sign signs (encrypts with private key) data in a single - * part, where the signature is (will be) an appendix to the - * data, and plaintext cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_Sign) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* the data to sign */ - CK_ULONG ulDataLen, /* count of bytes to sign */ - CK_BYTE_PTR pSignature, /* gets the signature */ - CK_ULONG_PTR pulSignatureLen /* gets signature length */ -); -#endif - - -/* C_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pPart, /* the data to sign */ - CK_ULONG ulPartLen /* count of bytes to sign */ -); -#endif - - -/* C_SignFinal finishes a multiple-part signature operation, - * returning the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSignature, /* gets the signature */ - CK_ULONG_PTR pulSignatureLen /* gets signature length */ -); -#endif - - -/* C_SignRecoverInit initializes a signature operation, where - * the data can be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ - CK_OBJECT_HANDLE hKey /* handle of the signature key */ -); -#endif - - -/* C_SignRecover signs data in a single operation, where the - * data can be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_SignRecover) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* the data to sign */ - CK_ULONG ulDataLen, /* count of bytes to sign */ - CK_BYTE_PTR pSignature, /* gets the signature */ - CK_ULONG_PTR pulSignatureLen /* gets signature length */ -); -#endif - - - -/* Verifying signatures and MACs */ - -/* C_VerifyInit initializes a verification operation, where the - * signature is an appendix to the data, and plaintext cannot - * cannot be recovered from the signature (e.g. DSA). */ -CK_PKCS11_FUNCTION_INFO(C_VerifyInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ - CK_OBJECT_HANDLE hKey /* verification key */ -); -#endif - - -/* C_Verify verifies a signature in a single-part operation, - * where the signature is an appendix to the data, and plaintext - * cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_Verify) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pData, /* signed data */ - CK_ULONG ulDataLen, /* length of signed data */ - CK_BYTE_PTR pSignature, /* signature */ - CK_ULONG ulSignatureLen /* signature length*/ -); -#endif - - -/* C_VerifyUpdate continues a multiple-part verification - * operation, where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pPart, /* signed data */ - CK_ULONG ulPartLen /* length of signed data */ -); -#endif - - -/* C_VerifyFinal finishes a multiple-part verification - * operation, checking the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyFinal) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSignature, /* signature to verify */ - CK_ULONG ulSignatureLen /* signature length */ -); -#endif - - -/* C_VerifyRecoverInit initializes a signature verification - * operation, where the data is recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ - CK_OBJECT_HANDLE hKey /* verification key */ -); -#endif - - -/* C_VerifyRecover verifies a signature in a single-part - * operation, where the data is recovered from the signature. */ -CK_PKCS11_FUNCTION_INFO(C_VerifyRecover) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSignature, /* signature to verify */ - CK_ULONG ulSignatureLen, /* signature length */ - CK_BYTE_PTR pData, /* gets signed data */ - CK_ULONG_PTR pulDataLen /* gets signed data len */ -); -#endif - - - -/* Dual-function cryptographic operations */ - -/* C_DigestEncryptUpdate continues a multiple-part digesting - * and encryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pPart, /* the plaintext data */ - CK_ULONG ulPartLen, /* plaintext length */ - CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ -); -#endif - - -/* C_DecryptDigestUpdate continues a multiple-part decryption and - * digesting operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedPart, /* ciphertext */ - CK_ULONG ulEncryptedPartLen, /* ciphertext length */ - CK_BYTE_PTR pPart, /* gets plaintext */ - CK_ULONG_PTR pulPartLen /* gets plaintext len */ -); -#endif - - -/* C_SignEncryptUpdate continues a multiple-part signing and - * encryption operation. */ -CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pPart, /* the plaintext data */ - CK_ULONG ulPartLen, /* plaintext length */ - CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ - CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ -); -#endif - - -/* C_DecryptVerifyUpdate continues a multiple-part decryption and - * verify operation. */ -CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_BYTE_PTR pEncryptedPart, /* ciphertext */ - CK_ULONG ulEncryptedPartLen, /* ciphertext length */ - CK_BYTE_PTR pPart, /* gets plaintext */ - CK_ULONG_PTR pulPartLen /* gets p-text length */ -); -#endif - - - -/* Key management */ - -/* C_GenerateKey generates a secret key, creating a new key - * object. */ -CK_PKCS11_FUNCTION_INFO(C_GenerateKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* key generation mech. */ - CK_ATTRIBUTE_PTR pTemplate, /* template for new key */ - CK_ULONG ulCount, /* # of attrs in template */ - CK_OBJECT_HANDLE_PTR phKey /* gets handle of new key */ -); -#endif - - -/* C_GenerateKeyPair generates a public-key/private-key pair, - * creating new key objects. */ -CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session - * handle */ - CK_MECHANISM_PTR pMechanism, /* key-gen - * mech. */ - CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template - * for pub. - * key */ - CK_ULONG ulPublicKeyAttributeCount, /* # pub. - * attrs. */ - CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template - * for priv. - * key */ - CK_ULONG ulPrivateKeyAttributeCount, /* # priv. - * attrs. */ - CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub. - * key - * handle */ - CK_OBJECT_HANDLE_PTR phPrivateKey /* gets - * priv. key - * handle */ -); -#endif - - -/* C_WrapKey wraps (i.e., encrypts) a key. */ -CK_PKCS11_FUNCTION_INFO(C_WrapKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_MECHANISM_PTR pMechanism, /* the wrapping mechanism */ - CK_OBJECT_HANDLE hWrappingKey, /* wrapping key */ - CK_OBJECT_HANDLE hKey, /* key to be wrapped */ - CK_BYTE_PTR pWrappedKey, /* gets wrapped key */ - CK_ULONG_PTR pulWrappedKeyLen /* gets wrapped key size */ -); -#endif - - -/* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new - * key object. */ -CK_PKCS11_FUNCTION_INFO(C_UnwrapKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_MECHANISM_PTR pMechanism, /* unwrapping mech. */ - CK_OBJECT_HANDLE hUnwrappingKey, /* unwrapping key */ - CK_BYTE_PTR pWrappedKey, /* the wrapped key */ - CK_ULONG ulWrappedKeyLen, /* wrapped key len */ - CK_ATTRIBUTE_PTR pTemplate, /* new key template */ - CK_ULONG ulAttributeCount, /* template length */ - CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ -); -#endif - - -/* C_DeriveKey derives a key from a base key, creating a new key - * object. */ -CK_PKCS11_FUNCTION_INFO(C_DeriveKey) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* session's handle */ - CK_MECHANISM_PTR pMechanism, /* key deriv. mech. */ - CK_OBJECT_HANDLE hBaseKey, /* base key */ - CK_ATTRIBUTE_PTR pTemplate, /* new key template */ - CK_ULONG ulAttributeCount, /* template length */ - CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ -); -#endif - - - -/* Random number generation */ - -/* C_SeedRandom mixes additional seed material into the token's - * random number generator. */ -CK_PKCS11_FUNCTION_INFO(C_SeedRandom) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR pSeed, /* the seed material */ - CK_ULONG ulSeedLen /* length of seed material */ -); -#endif - - -/* C_GenerateRandom generates random data. */ -CK_PKCS11_FUNCTION_INFO(C_GenerateRandom) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_BYTE_PTR RandomData, /* receives the random data */ - CK_ULONG ulRandomLen /* # of bytes to generate */ -); -#endif - - - -/* Parallel function management */ - -/* C_GetFunctionStatus is a legacy function; it obtains an - * updated status of a function running in parallel with an - * application. */ -CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - -/* C_CancelFunction is a legacy function; it cancels a function - * running in parallel. */ -CK_PKCS11_FUNCTION_INFO(C_CancelFunction) -#ifdef CK_NEED_ARG_LIST -( - CK_SESSION_HANDLE hSession /* the session's handle */ -); -#endif - - - -/* Functions added in for PKCS #11 Version 2.01 or later */ - -/* C_WaitForSlotEvent waits for a slot event (token insertion, - * removal, etc.) to occur. */ -CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent) -#ifdef CK_NEED_ARG_LIST -( - CK_FLAGS flags, /* blocking/nonblocking flag */ - CK_SLOT_ID_PTR pSlot, /* location that receives the slot ID */ - CK_VOID_PTR pRserved /* reserved. Should be NULL_PTR */ -); -#endif diff --git a/security/nss/lib/softoken/pkcs11i.h b/security/nss/lib/softoken/pkcs11i.h deleted file mode 100644 index 0f382f8ba..000000000 --- a/security/nss/lib/softoken/pkcs11i.h +++ /dev/null @@ -1,727 +0,0 @@ -/* - * 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. - */ -/* - * Internal data structures and functions used by pkcs11.c - */ -#ifndef _PKCS11I_H_ -#define _PKCS11I_H_ 1 - -#include "nssilock.h" -#include "seccomon.h" -#include "secoidt.h" -#include "lowkeyti.h" -#include "pkcs11t.h" -#include "pcertt.h" - - -/* - * Configuration Defines - * - * The following defines affect the space verse speed trade offs of - * the PKCS #11 module. For the most part the current settings are optimized - * for web servers, where we want faster speed and lower lock contention at - * the expense of space. - */ - -#define PKCS11_USE_THREADS /* set to true of you are need threads */ -/* - * Attribute Allocation strategy: - * - * 1) static allocation (PKCS11_STATIC_ATTRIBUTES set - * PKCS11_REF_COUNT_ATTRIBUTES not set) - * Attributes are pre-allocated as part of the session object and used from - * the object array. - * - * 2) heap allocation with ref counting (PKCS11_STATIC_ATTRIBUTES not set - * PKCS11_REF_COUNT_ATTRIBUTES set) - * Attributes are allocated from the heap when needed and freed when their - * reference count goes to zero. - * - * 3) arena allocation (PKCS11_STATIC_ATTRIBUTES not set - * PKCS11_REF_COUNT_ATTRIBUTE not set) - * Attributes are allocated from the arena when needed and freed only when - * the object goes away. - */ -#define PKCS11_STATIC_ATTRIBUTES -/*#define PKCS11_REF_COUNT_ATTRIBUTES */ -/* the next two are only active if PKCS11_STATIC_ATTRIBUTES is set */ -#define MAX_OBJS_ATTRS 45 /* number of attributes to preallocate in - * the object (must me the absolute max) */ -#define ATTR_SPACE 50 /* Maximum size of attribute data before extra - * data needs to be allocated. This is set to - * enough space to hold an SSL MASTER secret */ - -#define NSC_STRICT PR_FALSE /* forces the code to do strict template - * matching when doing C_FindObject on token - * objects. This will slow down search in - * NSS. */ -/* default search block allocations and increments */ -#define NSC_CERT_BLOCK_SIZE 50 -#define NSC_SEARCH_BLOCK_SIZE 5 -#define NSC_SLOT_LIST_BLOCK_SIZE 10 - -#define NSC_FIPS_MODULE 1 -#define NSC_NON_FIPS_MODULE 0 - -/* these are data base storage hashes, not cryptographic hashes.. The define - * the effective size of the various object hash tables */ -/* clients care more about memory usage than lookup performance on - * cyrptographic objects. Clients also have less objects around to play with - * - * we eventually should make this configurable at runtime! Especially now that - * NSS is a shared library. - */ -#define SPACE_ATTRIBUTE_HASH_SIZE 32 -#define SPACE_TOKEN_OBJECT_HASH_SIZE 32 -#define SPACE_SESSION_HASH_SIZE 32 -#define TIME_ATTRIBUTE_HASH_SIZE 32 -#define TIME_TOKEN_OBJECT_HASH_SIZE 1024 -#define TIME_SESSION_HASH_SIZE 1024 -#define MAX_OBJECT_LIST_SIZE 800 - /* how many objects to keep on the free list - * before we start freeing them */ -#define MAX_KEY_LEN 256 - -#define MULTIACCESS "multiaccess:" - -/* - * LOG2_BUCKETS_PER_SESSION_LOCK must be a prime number. - * With SESSION_HASH_SIZE=1024, LOG2 can be 9, 5, 1, or 0. - * With SESSION_HASH_SIZE=4096, LOG2 can be 11, 9, 5, 1, or 0. - * - * HASH_SIZE LOG2_BUCKETS_PER BUCKETS_PER_LOCK NUMBER_OF_BUCKETS - * 1024 9 512 2 - * 1024 5 32 32 - * 1024 1 2 512 - * 1024 0 1 1024 - * 4096 11 2048 2 - * 4096 9 512 8 - * 4096 5 32 128 - * 4096 1 2 2048 - * 4096 0 1 4096 - */ -#define LOG2_BUCKETS_PER_SESSION_LOCK 1 -#define BUCKETS_PER_SESSION_LOCK (1 << (LOG2_BUCKETS_PER_SESSION_LOCK)) -/* NOSPREAD sessionID to hash table index macro has been slower. */ - -#ifdef PKCS11_USE_THREADS -#define PK11_USE_THREADS(x) x -#else -#define PK11_USE_THREADS(x) -#endif - -/* define typedefs, double as forward declarations as well */ -typedef struct PK11AttributeStr PK11Attribute; -typedef struct PK11ObjectListStr PK11ObjectList; -typedef struct PK11ObjectFreeListStr PK11ObjectFreeList; -typedef struct PK11ObjectListElementStr PK11ObjectListElement; -typedef struct PK11ObjectStr PK11Object; -typedef struct PK11SessionObjectStr PK11SessionObject; -typedef struct PK11TokenObjectStr PK11TokenObject; -typedef struct PK11SessionStr PK11Session; -typedef struct PK11SlotStr PK11Slot; -typedef struct PK11SessionContextStr PK11SessionContext; -typedef struct PK11SearchResultsStr PK11SearchResults; -typedef struct PK11HashVerifyInfoStr PK11HashVerifyInfo; -typedef struct PK11HashSignInfoStr PK11HashSignInfo; -typedef struct PK11SSLMACInfoStr PK11SSLMACInfo; - -/* define function pointer typdefs for pointer tables */ -typedef void (*PK11Destroy)(void *, PRBool); -typedef void (*PK11Begin)(void *); -typedef SECStatus (*PK11Cipher)(void *,void *,unsigned int *,unsigned int, - void *, unsigned int); -typedef SECStatus (*PK11Verify)(void *,void *,unsigned int,void *,unsigned int); -typedef void (*PK11Hash)(void *,void *,unsigned int); -typedef void (*PK11End)(void *,void *,unsigned int *,unsigned int); -typedef void (*PK11Free)(void *); - -/* Value to tell if an attribute is modifiable or not. - * NEVER: attribute is only set on creation. - * ONCOPY: attribute is set on creation and can only be changed on copy. - * SENSITIVE: attribute can only be changed to TRUE. - * ALWAYS: attribute can always be changed. - */ -typedef enum { - PK11_NEVER = 0, - PK11_ONCOPY = 1, - PK11_SENSITIVE = 2, - PK11_ALWAYS = 3 -} PK11ModifyType; - -/* - * Free Status Enum... tell us more information when we think we're - * deleting an object. - */ -typedef enum { - PK11_DestroyFailure, - PK11_Destroyed, - PK11_Busy -} PK11FreeStatus; - -/* - * attribute values of an object. - */ -struct PK11AttributeStr { - PK11Attribute *next; - PK11Attribute *prev; - PRBool freeAttr; - PRBool freeData; -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - int refCount; - PZLock *refLock; -#endif - /*must be called handle to make pk11queue_find work */ - CK_ATTRIBUTE_TYPE handle; - CK_ATTRIBUTE attrib; -#ifdef PKCS11_STATIC_ATTRIBUTES - unsigned char space[ATTR_SPACE]; -#endif -}; - - -/* - * doubly link list of objects - */ -struct PK11ObjectListStr { - PK11ObjectList *next; - PK11ObjectList *prev; - PK11Object *parent; -}; - -struct PK11ObjectFreeListStr { - PK11Object *head; - PZLock *lock; - int count; -}; - -/* - * PKCS 11 crypto object structure - */ -struct PK11ObjectStr { - PK11Object *next; - PK11Object *prev; - CK_OBJECT_CLASS objclass; - CK_OBJECT_HANDLE handle; - int refCount; - PZLock *refLock; - PK11Slot *slot; - void *objectInfo; - PK11Free infoFree; -#ifndef PKCS11_STATIC_ATTRIBUTES - PLArenaPool *arena; -#endif -}; - -struct PK11TokenObjectStr { - PK11Object obj; - SECItem dbKey; -}; - -struct PK11SessionObjectStr { - PK11Object obj; - PK11ObjectList sessionList; - PZLock *attributeLock; - PK11Session *session; - PRBool wasDerived; -#ifdef PKCS11_STATIC_ATTRIBUTES - int nextAttr; - PK11Attribute attrList[MAX_OBJS_ATTRS]; -#endif - PRBool optimizeSpace; - unsigned int hashSize; - PK11Attribute *head[1]; -}; - -/* - * struct to deal with a temparary list of objects - */ -struct PK11ObjectListElementStr { - PK11ObjectListElement *next; - PK11Object *object; -}; - -/* - * Area to hold Search results - */ -struct PK11SearchResultsStr { - CK_OBJECT_HANDLE *handles; - int size; - int index; - int array_size; -}; - - -/* - * the universal crypto/hash/sign/verify context structure - */ -typedef enum { - PK11_ENCRYPT, - PK11_DECRYPT, - PK11_HASH, - PK11_SIGN, - PK11_SIGN_RECOVER, - PK11_VERIFY, - PK11_VERIFY_RECOVER -} PK11ContextType; - - -#define PK11_MAX_BLOCK_SIZE 16 -/* currently SHA512 is the biggest hash length */ -#define PK11_MAX_MAC_LENGTH 64 -#define PK11_INVALID_MAC_SIZE 0xffffffff - -struct PK11SessionContextStr { - PK11ContextType type; - PRBool multi; /* is multipart */ - PRBool doPad; /* use PKCS padding for block ciphers */ - unsigned int blockSize; /* blocksize for padding */ - unsigned int padDataLength; /* length of the valid data in padbuf */ - unsigned char padBuf[PK11_MAX_BLOCK_SIZE]; - unsigned char macBuf[PK11_MAX_BLOCK_SIZE]; - CK_ULONG macSize; /* size of a general block cipher mac*/ - void *cipherInfo; - void *hashInfo; - unsigned int cipherInfoLen; - CK_MECHANISM_TYPE currentMech; - PK11Cipher update; - PK11Hash hashUpdate; - PK11End end; - PK11Destroy destroy; - PK11Destroy hashdestroy; - PK11Verify verify; - unsigned int maxLen; - PK11Object *key; -}; - -/* - * Sessions (have objects) - */ -struct PK11SessionStr { - PK11Session *next; - PK11Session *prev; - CK_SESSION_HANDLE handle; - int refCount; - PZLock *objectLock; - int objectIDCount; - CK_SESSION_INFO info; - CK_NOTIFY notify; - CK_VOID_PTR appData; - PK11Slot *slot; - PK11SearchResults *search; - PK11SessionContext *enc_context; - PK11SessionContext *hash_context; - PK11SessionContext *sign_context; - PK11ObjectList *objects[1]; -}; - -/* - * slots (have sessions and objects) - * - * The array of sessionLock's protect the session hash table (head[]) - * as well as the reference count of session objects in that bucket - * (head[]->refCount), objectLock protects all elements of the token - * object hash table (tokObjects[], tokenIDCount, and tokenHashTable), - * and slotLock protects the remaining protected elements: - * password, isLoggedIn, ssoLoggedIn, and sessionCount - */ -struct PK11SlotStr { - CK_SLOT_ID slotID; - PZLock *slotLock; - PZLock **sessionLock; - unsigned int numSessionLocks; - unsigned long sessionLockMask; - PZLock *objectLock; - SECItem *password; - PRBool hasTokens; - PRBool isLoggedIn; - PRBool ssoLoggedIn; - PRBool needLogin; - PRBool DB_loaded; - PRBool readOnly; - PRBool optimizeSpace; - NSSLOWCERTCertDBHandle *certDB; - NSSLOWKEYDBHandle *keyDB; - int minimumPinLen; - PRInt32 sessionIDCount; /* atomically incremented */ - int sessionIDConflict; /* not protected by a lock */ - int sessionCount; - PRInt32 rwSessionCount; /* set by atomic operations */ - int tokenIDCount; - int index; - PLHashTable *tokenHashTable; - PK11Object **tokObjects; - unsigned int tokObjHashSize; - PK11Session **head; - unsigned int sessHashSize; - char tokDescription[33]; - char slotDescription[64]; -}; - -/* - * special joint operations Contexts - */ -struct PK11HashVerifyInfoStr { - SECOidTag hashOid; - NSSLOWKEYPublicKey *key; -}; - -struct PK11HashSignInfoStr { - SECOidTag hashOid; - NSSLOWKEYPrivateKey *key; -}; - -/* context for the Final SSLMAC message */ -struct PK11SSLMACInfoStr { - void *hashContext; - PK11Begin begin; - PK11Hash update; - PK11End end; - CK_ULONG macSize; - int padSize; - unsigned char key[MAX_KEY_LEN]; - unsigned int keySize; -}; - -/* - * session handle modifiers - */ -#define PK11_SESSION_SLOT_MASK 0xff000000L - -/* - * object handle modifiers - */ -#define PK11_TOKEN_MASK 0x80000000L -#define PK11_TOKEN_MAGIC 0x80000000L -#define PK11_TOKEN_TYPE_MASK 0x70000000L -/* keydb (high bit == 0) */ -#define PK11_TOKEN_TYPE_PRIV 0x10000000L -#define PK11_TOKEN_TYPE_PUB 0x20000000L -#define PK11_TOKEN_TYPE_KEY 0x30000000L -/* certdb (high bit == 1) */ -#define PK11_TOKEN_TYPE_TRUST 0x40000000L -#define PK11_TOKEN_TYPE_CRL 0x50000000L -#define PK11_TOKEN_TYPE_SMIME 0x60000000L -#define PK11_TOKEN_TYPE_CERT 0x70000000L - -#define PK11_TOKEN_KRL_HANDLE (PK11_TOKEN_MAGIC|PK11_TOKEN_TYPE_CRL|1) -/* how big a password/pin we can deal with */ -#define PK11_MAX_PIN 255 - -/* slot ID's */ -#define NETSCAPE_SLOT_ID 1 -#define PRIVATE_KEY_SLOT_ID 2 -#define FIPS_SLOT_ID 3 - -/* slot helper macros */ -#define pk11_SlotFromSession(sp) ((sp)->slot) -#define pk11_isToken(id) (((id) & PK11_TOKEN_MASK) == PK11_TOKEN_MAGIC) - -/* the session hash multiplier (see bug 201081) */ -#define SHMULTIPLIER 1791398085 - -/* queueing helper macros */ -#define pk11_hash(value,size) \ - ((PRUint32)((value) * SHMULTIPLIER) & (size-1)) -#define pk11queue_add(element,id,head,hash_size) \ - { int tmp = pk11_hash(id,hash_size); \ - (element)->next = (head)[tmp]; \ - (element)->prev = NULL; \ - if ((head)[tmp]) (head)[tmp]->prev = (element); \ - (head)[tmp] = (element); } -#define pk11queue_find(element,id,head,hash_size) \ - for( (element) = (head)[pk11_hash(id,hash_size)]; (element) != NULL; \ - (element) = (element)->next) { \ - if ((element)->handle == (id)) { break; } } -#define pk11queue_is_queued(element,id,head,hash_size) \ - ( ((element)->next) || ((element)->prev) || \ - ((head)[pk11_hash(id,hash_size)] == (element)) ) -#define pk11queue_delete(element,id,head,hash_size) \ - if ((element)->next) (element)->next->prev = (element)->prev; \ - if ((element)->prev) (element)->prev->next = (element)->next; \ - else (head)[pk11_hash(id,hash_size)] = ((element)->next); \ - (element)->next = NULL; \ - (element)->prev = NULL; \ - -#define pk11queue_init_element(element) \ - (element)->prev = NULL; - -#define pk11queue_add2(element, id, index, head) \ - { \ - (element)->next = (head)[index]; \ - if ((head)[index]) \ - (head)[index]->prev = (element); \ - (head)[index] = (element); \ - } - -#define pk11queue_find2(element, id, index, head) \ - for ( (element) = (head)[index]; \ - (element) != NULL; \ - (element) = (element)->next) { \ - if ((element)->handle == (id)) { break; } \ - } - -#define pk11queue_delete2(element, id, index, head) \ - if ((element)->next) (element)->next->prev = (element)->prev; \ - if ((element)->prev) (element)->prev->next = (element)->next; \ - else (head)[index] = ((element)->next); - -#define pk11queue_clear_deleted_element(element) \ - (element)->next = NULL; \ - (element)->prev = NULL; \ - - -/* sessionID (handle) is used to determine session lock bucket */ -#ifdef NOSPREAD -/* NOSPREAD: (ID>>L2LPB) & (perbucket-1) */ -#define PK11_SESSION_LOCK(slot,handle) \ - ((slot)->sessionLock[((handle) >> LOG2_BUCKETS_PER_SESSION_LOCK) \ - & (slot)->sessionLockMask]) -#else -/* SPREAD: ID & (perbucket-1) */ -#define PK11_SESSION_LOCK(slot,handle) \ - ((slot)->sessionLock[(handle) & (slot)->sessionLockMask]) -#endif - -/* expand an attribute & secitem structures out */ -#define pk11_attr_expand(ap) (ap)->type,(ap)->pValue,(ap)->ulValueLen -#define pk11_item_expand(ip) (ip)->data,(ip)->len - -typedef struct pk11_token_parametersStr { - CK_SLOT_ID slotID; - char *configdir; - char *certPrefix; - char *keyPrefix; - char *tokdes; - char *slotdes; - int minPW; - PRBool readOnly; - PRBool noCertDB; - PRBool noKeyDB; - PRBool forceOpen; - PRBool pwRequired; - PRBool optimizeSpace; -} pk11_token_parameters; - -typedef struct pk11_parametersStr { - char *configdir; - char *secmodName; - char *man; - char *libdes; - PRBool readOnly; - PRBool noModDB; - PRBool noCertDB; - PRBool forceOpen; - PRBool pwRequired; - PRBool optimizeSpace; - pk11_token_parameters *tokens; - int token_count; -} pk11_parameters; - - -/* machine dependent path stuff used by dbinit.c and pk11db.c */ -#ifdef macintosh -#define PATH_SEPARATOR ":" -#define SECMOD_DB "Security Modules" -#define CERT_DB_FMT "%sCertificates%s" -#define KEY_DB_FMT "%sKey Database%s" -#else -#define PATH_SEPARATOR "/" -#define SECMOD_DB "secmod.db" -#define CERT_DB_FMT "%scert%s.db" -#define KEY_DB_FMT "%skey%s.db" -#endif - -SEC_BEGIN_PROTOS - -extern int nsf_init; -extern CK_RV nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS); -extern CK_RV nsc_CommonFinalize(CK_VOID_PTR pReserved, PRBool isFIPS); -extern CK_RV nsc_CommonGetSlotList(CK_BBOOL tokPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount, int moduleIndex); -/* shared functions between PKCS11.c and PK11FIPS.c */ -extern CK_RV PK11_SlotInit(char *configdir,pk11_token_parameters *params, - int moduleIndex); - -/* internal utility functions used by pkcs11.c */ -extern PK11Attribute *pk11_FindAttribute(PK11Object *object, - CK_ATTRIBUTE_TYPE type); -extern void pk11_FreeAttribute(PK11Attribute *attribute); -extern CK_RV pk11_AddAttributeType(PK11Object *object, CK_ATTRIBUTE_TYPE type, - void *valPtr, - CK_ULONG length); -extern CK_RV pk11_Attribute2SecItem(PLArenaPool *arena, SECItem *item, - PK11Object *object, CK_ATTRIBUTE_TYPE type); -extern unsigned int pk11_GetLengthInBits(unsigned char *buf, - unsigned int bufLen); -extern CK_RV pk11_ConstrainAttribute(PK11Object *object, - CK_ATTRIBUTE_TYPE type, int minLength, int maxLength, int minMultiple); -extern PRBool pk11_hasAttribute(PK11Object *object, CK_ATTRIBUTE_TYPE type); -extern PRBool pk11_isTrue(PK11Object *object, CK_ATTRIBUTE_TYPE type); -extern void pk11_DeleteAttributeType(PK11Object *object, - CK_ATTRIBUTE_TYPE type); -extern CK_RV pk11_Attribute2SecItem(PLArenaPool *arena, SECItem *item, - PK11Object *object, CK_ATTRIBUTE_TYPE type); -extern CK_RV pk11_Attribute2SSecItem(PLArenaPool *arena, SECItem *item, - PK11Object *object, - CK_ATTRIBUTE_TYPE type); -extern PK11ModifyType pk11_modifyType(CK_ATTRIBUTE_TYPE type, - CK_OBJECT_CLASS inClass); -extern PRBool pk11_isSensitive(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass); -extern char *pk11_getString(PK11Object *object, CK_ATTRIBUTE_TYPE type); -extern void pk11_nullAttribute(PK11Object *object,CK_ATTRIBUTE_TYPE type); -extern CK_RV pk11_GetULongAttribute(PK11Object *object, CK_ATTRIBUTE_TYPE type, - CK_ULONG *longData); -extern CK_RV pk11_forceAttribute(PK11Object *object, CK_ATTRIBUTE_TYPE type, - void *value, unsigned int len); -extern CK_RV pk11_defaultAttribute(PK11Object *object, CK_ATTRIBUTE_TYPE type, - void *value, unsigned int len); -extern unsigned int pk11_MapTrust(CK_TRUST trust, PRBool clientAuth); - -extern PK11Object *pk11_NewObject(PK11Slot *slot); -extern CK_RV pk11_CopyObject(PK11Object *destObject, PK11Object *srcObject); -extern PK11FreeStatus pk11_FreeObject(PK11Object *object); -extern CK_RV pk11_DeleteObject(PK11Session *session, PK11Object *object); -extern void pk11_ReferenceObject(PK11Object *object); -extern PK11Object *pk11_ObjectFromHandle(CK_OBJECT_HANDLE handle, - PK11Session *session); -extern void pk11_AddSlotObject(PK11Slot *slot, PK11Object *object); -extern void pk11_AddObject(PK11Session *session, PK11Object *object); - -extern CK_RV pk11_searchObjectList(PK11SearchResults *search, - PK11Object **head, unsigned int size, - PZLock *lock, CK_ATTRIBUTE_PTR inTemplate, - int count, PRBool isLoggedIn); -extern PK11ObjectListElement *pk11_FreeObjectListElement( - PK11ObjectListElement *objectList); -extern void pk11_FreeObjectList(PK11ObjectListElement *objectList); -extern void pk11_FreeSearch(PK11SearchResults *search); -extern CK_RV pk11_handleObject(PK11Object *object, PK11Session *session); - -extern PK11Slot *pk11_SlotFromID(CK_SLOT_ID slotID); -extern PK11Slot *pk11_SlotFromSessionHandle(CK_SESSION_HANDLE handle); -extern PK11Session *pk11_SessionFromHandle(CK_SESSION_HANDLE handle); -extern void pk11_FreeSession(PK11Session *session); -extern PK11Session *pk11_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, - CK_VOID_PTR pApplication, CK_FLAGS flags); -extern void pk11_update_state(PK11Slot *slot,PK11Session *session); -extern void pk11_update_all_states(PK11Slot *slot); -extern void pk11_FreeContext(PK11SessionContext *context); -extern void pk11_CleanupFreeLists(void); - -extern NSSLOWKEYPublicKey *pk11_GetPubKey(PK11Object *object, - CK_KEY_TYPE key_type, CK_RV *crvp); -extern NSSLOWKEYPrivateKey *pk11_GetPrivKey(PK11Object *object, - CK_KEY_TYPE key_type, CK_RV *crvp); -extern void pk11_FormatDESKey(unsigned char *key, int length); -extern PRBool pk11_CheckDESKey(unsigned char *key); -extern PRBool pk11_IsWeakKey(unsigned char *key,CK_KEY_TYPE key_type); - -extern CK_RV secmod_parseParameters(char *param, pk11_parameters *parsed, - PRBool isFIPS); -extern void secmod_freeParams(pk11_parameters *params); -extern char *secmod_getSecmodName(char *params, char **domain, - char **filename, PRBool *rw); -extern char ** secmod_ReadPermDB(const char *domain, const char *filename, - const char *dbname, char *params, PRBool rw); -extern SECStatus secmod_DeletePermDB(const char *domain, const char *filename, - const char *dbname, char *args, PRBool rw); -extern SECStatus secmod_AddPermDB(const char *domain, const char *filename, - const char *dbname, char *module, PRBool rw); -extern SECStatus secmod_ReleasePermDBData(const char *domain, - const char *filename, const char *dbname, char **specList, PRBool rw); -/* mechanism allows this operation */ -extern CK_RV pk11_MechAllowsOperation(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE op); -/* - * OK there are now lots of options here, lets go through them all: - * - * configdir - base directory where all the cert, key, and module datbases live. - * certPrefix - prefix added to the beginning of the cert database example: " - * "https-server1-" - * keyPrefix - prefix added to the beginning of the key database example: " - * "https-server1-" - * secmodName - name of the security module database (usually "secmod.db"). - * readOnly - Boolean: true if the databases are to be openned read only. - * nocertdb - Don't open the cert DB and key DB's, just initialize the - * Volatile certdb. - * nomoddb - Don't open the security module DB, just initialize the - * PKCS #11 module. - * forceOpen - Continue to force initializations even if the databases cannot - * be opened. - */ -CK_RV pk11_DBInit(const char *configdir, const char *certPrefix, - const char *keyPrefix, PRBool readOnly, PRBool noCertDB, - PRBool noKeyDB, PRBool forceOpen, - NSSLOWCERTCertDBHandle **certDB, NSSLOWKEYDBHandle **keyDB); - -void pk11_DBShutdown(NSSLOWCERTCertDBHandle *certHandle, - NSSLOWKEYDBHandle *keyHandle); - -const char *pk11_EvaluateConfigDir(const char *configdir, char **domain); - -/* - * narrow objects - */ -PK11SessionObject * pk11_narrowToSessionObject(PK11Object *); -PK11TokenObject * pk11_narrowToTokenObject(PK11Object *); - -/* - * token object utilities - */ -void pk11_addHandle(PK11SearchResults *search, CK_OBJECT_HANDLE handle); -PRBool pk11_poisonHandle(PK11Slot *slot, SECItem *dbkey, - CK_OBJECT_HANDLE handle); -PRBool pk11_tokenMatch(PK11Slot *slot, SECItem *dbKey, CK_OBJECT_HANDLE class, - CK_ATTRIBUTE_PTR theTemplate,int count); -CK_OBJECT_HANDLE pk11_mkHandle(PK11Slot *slot, - SECItem *dbKey, CK_OBJECT_HANDLE class); -PK11Object * pk11_NewTokenObject(PK11Slot *slot, SECItem *dbKey, - CK_OBJECT_HANDLE handle); -PK11TokenObject *pk11_convertSessionToToken(PK11Object *so); - -/**************************************** - * implement TLS Pseudo Random Function (PRF) - */ - -extern SECStatus -pk11_PRF(const SECItem *secret, const char *label, SECItem *seed, - SECItem *result, PRBool isFIPS); - -extern CK_RV -pk11_TLSPRFInit(PK11SessionContext *context, - PK11Object * key, - CK_KEY_TYPE key_type); - -SEC_END_PROTOS - -#endif /* _PKCS11I_H_ */ diff --git a/security/nss/lib/softoken/pkcs11n.h b/security/nss/lib/softoken/pkcs11n.h deleted file mode 100644 index 4aaa8a8fb..000000000 --- a/security/nss/lib/softoken/pkcs11n.h +++ /dev/null @@ -1,228 +0,0 @@ -/* - * 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): - * Dr Stephen Henson <stephen.henson@gemplus.com> - * - * 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 _PKCS11N_H_ -#define _PKCS11N_H_ - -#ifdef DEBUG -static const char CKT_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; -#endif /* DEBUG */ - -/* - * pkcs11n.h - * - * This file contains the NSS-specific type definitions for Cryptoki - * (PKCS#11). - */ - -/* - * NSSCK_VENDOR_NETSCAPE - * - * Cryptoki reserves the high half of all the number spaces for - * vendor-defined use. I'd like to keep all of our Netscape- - * specific values together, but not in the oh-so-obvious - * 0x80000001, 0x80000002, etc. area. So I've picked an offset, - * and constructed values for the beginnings of our spaces. - * - * Note that some "historical" Netscape values don't fall within - * this range. - */ -#define NSSCK_VENDOR_NETSCAPE 0x4E534350 /* NSCP */ - -/* - * Netscape-defined object classes - * - */ -#define CKO_NETSCAPE (CKO_VENDOR_DEFINED|NSSCK_VENDOR_NETSCAPE) - -#define CKO_NETSCAPE_CRL (CKO_NETSCAPE + 1) -#define CKO_NETSCAPE_SMIME (CKO_NETSCAPE + 2) -#define CKO_NETSCAPE_TRUST (CKO_NETSCAPE + 3) -#define CKO_NETSCAPE_BUILTIN_ROOT_LIST (CKO_NETSCAPE + 4) - -/* - * Netscape-defined key types - * - */ -#define CKK_NETSCAPE (CKK_VENDOR_DEFINED|NSSCK_VENDOR_NETSCAPE) - -#define CKK_NETSCAPE_PKCS8 (CKK_NETSCAPE + 1) -/* - * Netscape-defined certificate types - * - */ -#define CKC_NETSCAPE (CKC_VENDOR_DEFINED|NSSCK_VENDOR_NETSCAPE) - -/* - * Netscape-defined object attributes - * - */ -#define CKA_NETSCAPE (CKA_VENDOR_DEFINED|NSSCK_VENDOR_NETSCAPE) - -#define CKA_NETSCAPE_URL (CKA_NETSCAPE + 1) -#define CKA_NETSCAPE_EMAIL (CKA_NETSCAPE + 2) -#define CKA_NETSCAPE_SMIME_INFO (CKA_NETSCAPE + 3) -#define CKA_NETSCAPE_SMIME_TIMESTAMP (CKA_NETSCAPE + 4) -#define CKA_NETSCAPE_PKCS8_SALT (CKA_NETSCAPE + 5) -#define CKA_NETSCAPE_PASSWORD_CHECK (CKA_NETSCAPE + 6) -#define CKA_NETSCAPE_EXPIRES (CKA_NETSCAPE + 7) -#define CKA_NETSCAPE_KRL (CKA_NETSCAPE + 8) - -#define CKA_NETSCAPE_PQG_COUNTER (CKA_NETSCAPE + 20) -#define CKA_NETSCAPE_PQG_SEED (CKA_NETSCAPE + 21) -#define CKA_NETSCAPE_PQG_H (CKA_NETSCAPE + 22) -#define CKA_NETSCAPE_PQG_SEED_BITS (CKA_NETSCAPE + 23) - -/* - * Trust attributes: - * - * If trust goes standard, these probably will too. So I'll - * put them all in one place. - */ - -#define CKA_TRUST (CKA_NETSCAPE + 0x2000) - -/* "Usage" key information */ -#define CKA_TRUST_DIGITAL_SIGNATURE (CKA_TRUST + 1) -#define CKA_TRUST_NON_REPUDIATION (CKA_TRUST + 2) -#define CKA_TRUST_KEY_ENCIPHERMENT (CKA_TRUST + 3) -#define CKA_TRUST_DATA_ENCIPHERMENT (CKA_TRUST + 4) -#define CKA_TRUST_KEY_AGREEMENT (CKA_TRUST + 5) -#define CKA_TRUST_KEY_CERT_SIGN (CKA_TRUST + 6) -#define CKA_TRUST_CRL_SIGN (CKA_TRUST + 7) - -/* "Purpose" trust information */ -#define CKA_TRUST_SERVER_AUTH (CKA_TRUST + 8) -#define CKA_TRUST_CLIENT_AUTH (CKA_TRUST + 9) -#define CKA_TRUST_CODE_SIGNING (CKA_TRUST + 10) -#define CKA_TRUST_EMAIL_PROTECTION (CKA_TRUST + 11) -#define CKA_TRUST_IPSEC_END_SYSTEM (CKA_TRUST + 12) -#define CKA_TRUST_IPSEC_TUNNEL (CKA_TRUST + 13) -#define CKA_TRUST_IPSEC_USER (CKA_TRUST + 14) -#define CKA_TRUST_TIME_STAMPING (CKA_TRUST + 15) -#define CKA_CERT_SHA1_HASH (CKA_TRUST + 100) -#define CKA_CERT_MD5_HASH (CKA_TRUST + 101) - -/* Netscape trust stuff */ -/* XXX fgmr new ones here-- step-up, etc. */ - -/* HISTORICAL: define used to pass in the database key for DSA private keys */ -#define CKA_NETSCAPE_DB 0xD5A0DB00L -#define CKA_NETSCAPE_TRUST 0x80000001L - -/* - * Netscape-defined crypto mechanisms - * - */ -#define CKM_NETSCAPE (CKM_VENDOR_DEFINED|NSSCK_VENDOR_NETSCAPE) - -#define CKM_NETSCAPE_AES_KEY_WRAP (CKM_NETSCAPE + 1) -#define CKM_NETSCAPE_AES_KEY_WRAP_PAD (CKM_NETSCAPE + 2) - -/* - * HISTORICAL: - * Do not attempt to use these. They are only used by NETSCAPE's internal - * PKCS #11 interface. Most of these are place holders for other mechanism - * and will change in the future. - */ -#define CKM_NETSCAPE_PBE_SHA1_DES_CBC 0x80000002L -#define CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC 0x80000003L -#define CKM_NETSCAPE_PBE_SHA1_40_BIT_RC2_CBC 0x80000004L -#define CKM_NETSCAPE_PBE_SHA1_128_BIT_RC2_CBC 0x80000005L -#define CKM_NETSCAPE_PBE_SHA1_40_BIT_RC4 0x80000006L -#define CKM_NETSCAPE_PBE_SHA1_128_BIT_RC4 0x80000007L -#define CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC 0x80000008L -#define CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN 0x80000009L -#define CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN 0x8000000aL -#define CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN 0x8000000bL - -#define CKM_TLS_PRF_GENERAL 0x80000373L - -/* - * Netscape-defined return values - * - */ -#define CKR_NETSCAPE (CKM_VENDOR_DEFINED|NSSCK_VENDOR_NETSCAPE) - -/* - * Trust info - * - * This isn't part of the Cryptoki standard (yet), so I'm putting - * all the definitions here. Some of this would move to nssckt.h - * if trust info were made part of the standard. In view of this - * possibility, I'm putting my (Netscape) values in the netscape - * vendor space, like everything else. - */ - -typedef CK_ULONG CK_TRUST; - -/* The following trust types are defined: */ -#define CKT_VENDOR_DEFINED 0x80000000 - -#define CKT_NETSCAPE (CKT_VENDOR_DEFINED|NSSCK_VENDOR_NETSCAPE) - -/* If trust goes standard, these'll probably drop out of vendor space. */ -#define CKT_NETSCAPE_TRUSTED (CKT_NETSCAPE + 1) -#define CKT_NETSCAPE_TRUSTED_DELEGATOR (CKT_NETSCAPE + 2) -#define CKT_NETSCAPE_UNTRUSTED (CKT_NETSCAPE + 3) -#define CKT_NETSCAPE_MUST_VERIFY (CKT_NETSCAPE + 4) -#define CKT_NETSCAPE_TRUST_UNKNOWN (CKT_NETSCAPE + 5) /* default */ - -/* - * These may well remain Netscape-specific; I'm only using them - * to cache resolution data. - */ -#define CKT_NETSCAPE_VALID (CKT_NETSCAPE + 10) -#define CKT_NETSCAPE_VALID_DELEGATOR (CKT_NETSCAPE + 11) - - -/* - * These are not really PKCS #11 values specifically. They are the 'loadable' - * module spec NSS uses. The are available for others to use as well, but not - * part of the formal PKCS #11 spec. - * - * The function 'FIND' returns an array of PKCS #11 initialization strings - * The function 'ADD' takes a PKCS #11 initialization string and stores it. - * The function 'DEL' takes a 'name= library=' value and deletes the associated - * string. - * The function 'RELEASE' frees the array returned by 'FIND' - */ -#define SECMOD_MODULE_DB_FUNCTION_FIND 0 -#define SECMOD_MODULE_DB_FUNCTION_ADD 1 -#define SECMOD_MODULE_DB_FUNCTION_DEL 2 -#define SECMOD_MODULE_DB_FUNCTION_RELEASE 3 -typedef char ** (PR_CALLBACK *SECMODModuleDBFunc)(unsigned long function, - char *parameters, void *moduleSpec); - -#endif /* _PKCS11N_H_ */ diff --git a/security/nss/lib/softoken/pkcs11p.h b/security/nss/lib/softoken/pkcs11p.h deleted file mode 100644 index 1361991c5..000000000 --- a/security/nss/lib/softoken/pkcs11p.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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. - */ -/* - * Copyright (C) 1994-1999 RSA Security Inc. Licence to copy this document - * is granted provided that it is identified as "RSA Security Inc. Public-Key - * Cryptography Standards (PKCS)" in all material mentioning or referencing - * this document. - */ -/* these data types are platform/implementation dependent. */ -/* - * Packing was removed from the shipped RSA header files, even - * though it's still needed. put in a central file to help merging.. - */ - -#if defined(_WIN32) -#ifdef _MSC_VER -#pragma warning(disable:4103) -#endif -#pragma pack(push, cryptoki, 1) -#endif - diff --git a/security/nss/lib/softoken/pkcs11t.h b/security/nss/lib/softoken/pkcs11t.h deleted file mode 100644 index 4b16e873d..000000000 --- a/security/nss/lib/softoken/pkcs11t.h +++ /dev/null @@ -1,1409 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - */ -/* - * Copyright (C) 1994-1999 RSA Security Inc. Licence to copy this document - * is granted provided that it is identified as "RSA Security In.c Public-Key - * Cryptography Standards (PKCS)" in all material mentioning or referencing - * this document. - */ -/* See top of pkcs11.h for information about the macros that - * must be defined and the structure-packing conventions that - * must be set before including this file. - */ - -#ifndef _PKCS11T_H_ -#define _PKCS11T_H_ 1 - -#ifndef CK_FALSE -#define CK_FALSE 0 -#endif - -#ifndef CK_TRUE -#define CK_TRUE (!CK_FALSE) -#endif - -#include "prtypes.h" - -#define CK_PTR * -#define CK_NULL_PTR 0 -#define CK_CALLBACK_FUNCTION(rv,func) rv (PR_CALLBACK * func) -#define CK_DECLARE_FUNCTION(rv,func) PR_EXTERN(rv) func -#define CK_DECLARE_FUNCTION_POINTER(rv,func) rv (PR_CALLBACK * func) - -#define CK_INVALID_SESSION 0 - -/* an unsigned 8-bit value */ -typedef unsigned char CK_BYTE; - -/* an unsigned 8-bit character */ -typedef CK_BYTE CK_CHAR; - -/* an unsigned 8-bit character */ -typedef CK_BYTE CK_UTF8CHAR; - -/* a BYTE-sized Boolean flag */ -typedef CK_BYTE CK_BBOOL; - -/* an unsigned value, at least 32 bits long */ -typedef unsigned long int CK_ULONG; - -/* a signed value, the same size as a CK_ULONG */ -/* CK_LONG is new for v2.0 */ -typedef long int CK_LONG; - -/* at least 32 bits; each bit is a Boolean flag */ -typedef CK_ULONG CK_FLAGS; - - -/* some special values for certain CK_ULONG variables */ -#define CK_UNAVAILABLE_INFORMATION (~0UL) -#define CK_EFFECTIVELY_INFINITE 0 - - -typedef CK_BYTE CK_PTR CK_BYTE_PTR; -typedef CK_CHAR CK_PTR CK_CHAR_PTR; -typedef CK_UTF8CHAR CK_PTR CK_UTF8CHAR_PTR; -typedef CK_ULONG CK_PTR CK_ULONG_PTR; -typedef void CK_PTR CK_VOID_PTR; - -/* Pointer to a CK_VOID_PTR-- i.e., pointer to pointer to void */ -typedef CK_VOID_PTR CK_PTR CK_VOID_PTR_PTR; - - -/* The following value is always invalid if used as a session */ -/* handle or object handle */ -#define CK_INVALID_HANDLE 0 - - -/* pack */ -#include "pkcs11p.h" - -typedef struct CK_VERSION { - CK_BYTE major; /* integer portion of version number */ - CK_BYTE minor; /* 1/100ths portion of version number */ -} CK_VERSION; - -typedef CK_VERSION CK_PTR CK_VERSION_PTR; - - -typedef struct CK_INFO { - /* manufacturerID and libraryDecription have been changed from - * CK_CHAR to CK_UTF8CHAR for v2.10 */ - CK_VERSION cryptokiVersion; /* PKCS #11 interface ver */ - CK_UTF8CHAR manufacturerID[32]; /* blank padded */ - CK_FLAGS flags; /* must be zero */ - - /* libraryDescription and libraryVersion are new for v2.0 */ - CK_UTF8CHAR libraryDescription[32]; /* blank padded */ - CK_VERSION libraryVersion; /* version of library */ -} CK_INFO; - -typedef CK_INFO CK_PTR CK_INFO_PTR; - - -/* CK_NOTIFICATION enumerates the types of notifications that - * PKCS #11 provides to an application */ -/* CK_NOTIFICATION has been changed from an enum to a CK_ULONG - * for v2.0 */ -typedef CK_ULONG CK_NOTIFICATION; -#define CKN_SURRENDER 0 - - -typedef CK_ULONG CK_SLOT_ID; - -typedef CK_SLOT_ID CK_PTR CK_SLOT_ID_PTR; - - -/* CK_SLOT_INFO provides information about a slot */ -typedef struct CK_SLOT_INFO { - /* slotDescription and manufacturerID have been changed from - * CK_CHAR to CK_UTF8CHAR for v2.10 */ - CK_UTF8CHAR slotDescription[64]; /* blank padded */ - CK_UTF8CHAR manufacturerID[32]; /* blank padded */ - CK_FLAGS flags; - - /* hardwareVersion and firmwareVersion are new for v2.0 */ - CK_VERSION hardwareVersion; /* version of hardware */ - CK_VERSION firmwareVersion; /* version of firmware */ -} CK_SLOT_INFO; - -/* flags: bit flags that provide capabilities of the slot - * Bit Flag Mask Meaning - */ -#define CKF_TOKEN_PRESENT 0x00000001 /* a token is there */ -#define CKF_REMOVABLE_DEVICE 0x00000002 /* removable devices*/ -#define CKF_HW_SLOT 0x00000004 /* hardware slot */ - -typedef CK_SLOT_INFO CK_PTR CK_SLOT_INFO_PTR; - - -/* CK_TOKEN_INFO provides information about a token */ -typedef struct CK_TOKEN_INFO { - /* label, manufacturerID, and model have been changed from - * CK_CHAR to CK_UTF8CHAR for v2.10 */ - CK_UTF8CHAR label[32]; /* blank padded */ - CK_UTF8CHAR manufacturerID[32]; /* blank padded */ - CK_UTF8CHAR model[16]; /* blank padded */ - CK_CHAR serialNumber[16]; /* blank padded */ - CK_FLAGS flags; /* see below */ - - /* ulMaxSessionCount, ulSessionCount, ulMaxRwSessionCount, - * ulRwSessionCount, ulMaxPinLen, and ulMinPinLen have all been - * changed from CK_USHORT to CK_ULONG for v2.0 */ - CK_ULONG ulMaxSessionCount; /* max open sessions */ - CK_ULONG ulSessionCount; /* sess. now open */ - CK_ULONG ulMaxRwSessionCount; /* max R/W sessions */ - CK_ULONG ulRwSessionCount; /* R/W sess. now open */ - CK_ULONG ulMaxPinLen; /* in bytes */ - CK_ULONG ulMinPinLen; /* in bytes */ - CK_ULONG ulTotalPublicMemory; /* in bytes */ - CK_ULONG ulFreePublicMemory; /* in bytes */ - CK_ULONG ulTotalPrivateMemory; /* in bytes */ - CK_ULONG ulFreePrivateMemory; /* in bytes */ - - /* hardwareVersion, firmwareVersion, and time are new for - * v2.0 */ - CK_VERSION hardwareVersion; /* version of hardware */ - CK_VERSION firmwareVersion; /* version of firmware */ - CK_CHAR utcTime[16]; /* time */ -} CK_TOKEN_INFO; - -/* The flags parameter is defined as follows: - * Bit Flag Mask Meaning - */ -#define CKF_RNG 0x00000001 /* has random # - * generator */ -#define CKF_WRITE_PROTECTED 0x00000002 /* token is - * write- - * protected */ -#define CKF_LOGIN_REQUIRED 0x00000004 /* user must - * login */ -#define CKF_USER_PIN_INITIALIZED 0x00000008 /* normal user's - * PIN is set */ - -/* CKF_RESTORE_KEY_NOT_NEEDED is new for v2.0. If it is set, - * that means that *every* time the state of cryptographic - * operations of a session is successfully saved, all keys - * needed to continue those operations are stored in the state */ -#define CKF_RESTORE_KEY_NOT_NEEDED 0x00000020 - -/* CKF_CLOCK_ON_TOKEN is new for v2.0. If it is set, that means - * that the token has some sort of clock. The time on that - * clock is returned in the token info structure */ -#define CKF_CLOCK_ON_TOKEN 0x00000040 - -/* CKF_PROTECTED_AUTHENTICATION_PATH is new for v2.0. If it is - * set, that means that there is some way for the user to login - * without sending a PIN through the PKCS #11 library itself */ -#define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100 - -/* CKF_DUAL_CRYPTO_OPERATIONS is new for v2.0. If it is true, - * that means that a single session with the token can perform - * dual simultaneous cryptographic operations (digest and - * encrypt; decrypt and digest; sign and encrypt; and decrypt - * and sign) */ -#define CKF_DUAL_CRYPTO_OPERATIONS 0x00000200 - -/* CKF_TOKEN_INITIALIZED if new for v2.10. If it is true, the - * token has been initialized using C_InitializeToken or an - * equivalent mechanism outside the scope of PKCS #11. - * Calling C_InitializeToken when this flag is set will cause - * the token to be reinitialized. */ -#define CKF_TOKEN_INITIALIZED 0x00000400 - -/* CKF_SECONDARY_AUTHENTICATION if new for v2.10. If it is - * true, the token supports secondary authentication for - * private key objects. */ -/* DEPRICATED in v2.11 */ -#define CKF_SECONDARY_AUTHENTICATION 0x00000800 - -/* CKF_USER_PIN_COUNT_LOW if new for v2.10. If it is true, an - * incorrect user login PIN has been entered at least once - * since the last successful authentication. */ -#define CKF_USER_PIN_COUNT_LOW 0x00010000 - -/* CKF_USER_PIN_FINAL_TRY if new for v2.10. If it is true, - * supplying an incorrect user PIN will it to become locked. */ -#define CKF_USER_PIN_FINAL_TRY 0x00020000 - -/* CKF_USER_PIN_LOCKED if new for v2.10. If it is true, the - * user PIN has been locked. User login to the token is not - * possible. */ -#define CKF_USER_PIN_LOCKED 0x00040000 - -/* CKF_USER_PIN_TO_BE_CHANGED if new for v2.10. If it is true, - * the user PIN value is the default value set by token - * initialization or manufacturing. */ -#define CKF_USER_PIN_TO_BE_CHANGED 0x00080000 - -/* CKF_SO_PIN_COUNT_LOW if new for v2.10. If it is true, an - * incorrect SO login PIN has been entered at least once since - * the last successful authentication. */ -#define CKF_SO_PIN_COUNT_LOW 0x00100000 - -/* CKF_SO_PIN_FINAL_TRY if new for v2.10. If it is true, - * supplying an incorrect SO PIN will it to become locked. */ -#define CKF_SO_PIN_FINAL_TRY 0x00200000 - -/* CKF_SO_PIN_LOCKED if new for v2.10. If it is true, the SO - * PIN has been locked. SO login to the token is not possible. - */ -#define CKF_SO_PIN_LOCKED 0x00400000 - -/* CKF_SO_PIN_TO_BE_CHANGED if new for v2.10. If it is true, - * the SO PIN value is the default value set by token - * initialization or manufacturing. */ -#define CKF_SO_PIN_TO_BE_CHANGED 0x00800000 - -typedef CK_TOKEN_INFO CK_PTR CK_TOKEN_INFO_PTR; - - -/* CK_SESSION_HANDLE is a PKCS #11-assigned value that - * identifies a session */ -typedef CK_ULONG CK_SESSION_HANDLE; - -typedef CK_SESSION_HANDLE CK_PTR CK_SESSION_HANDLE_PTR; - - -/* CK_USER_TYPE enumerates the types of PKCS #11 users */ -/* CK_USER_TYPE has been changed from an enum to a CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_USER_TYPE; -/* Security Officer */ -#define CKU_SO 0 -/* Normal user */ -#define CKU_USER 1 - - -/* CK_STATE enumerates the session states */ -/* CK_STATE has been changed from an enum to a CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_STATE; -#define CKS_RO_PUBLIC_SESSION 0 -#define CKS_RO_USER_FUNCTIONS 1 -#define CKS_RW_PUBLIC_SESSION 2 -#define CKS_RW_USER_FUNCTIONS 3 -#define CKS_RW_SO_FUNCTIONS 4 - - -/* CK_SESSION_INFO provides information about a session */ -typedef struct CK_SESSION_INFO { - CK_SLOT_ID slotID; - CK_STATE state; - CK_FLAGS flags; /* see below */ - - /* ulDeviceError was changed from CK_USHORT to CK_ULONG for - * v2.0 */ - CK_ULONG ulDeviceError; /* device-dependent error code */ -} CK_SESSION_INFO; - -/* The flags are defined in the following table: - * Bit Flag Mask Meaning - */ -#define CKF_RW_SESSION 0x00000002 /* session is r/w */ -#define CKF_SERIAL_SESSION 0x00000004 /* no parallel */ - -typedef CK_SESSION_INFO CK_PTR CK_SESSION_INFO_PTR; - - -/* CK_OBJECT_HANDLE is a token-specific identifier for an - * object */ -typedef CK_ULONG CK_OBJECT_HANDLE; - -typedef CK_OBJECT_HANDLE CK_PTR CK_OBJECT_HANDLE_PTR; - - -/* CK_OBJECT_CLASS is a value that identifies the classes (or - * types) of objects that PKCS #11 recognizes. It is defined - * as follows: */ -/* CK_OBJECT_CLASS was changed from CK_USHORT to CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_OBJECT_CLASS; - -/* The following classes of objects are defined: */ -/* CKO_HW_FEATURE is new for v2.10 */ -/* CKO_DOMAIN_PARAMETERS is new for v2.11 */ -#define CKO_DATA 0x00000000 -#define CKO_CERTIFICATE 0x00000001 -#define CKO_PUBLIC_KEY 0x00000002 -#define CKO_PRIVATE_KEY 0x00000003 -#define CKO_SECRET_KEY 0x00000004 -#define CKO_HW_FEATURE 0x00000005 -#define CKO_DOMAIN_PARAMETERS 0x00000006 -#define CKO_KG_PARAMETERS 0x00000006 -#define CKO_VENDOR_DEFINED 0x80000000 - -typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR; - -/* CK_HW_FEATURE_TYPE is new for v2.10. CK_HW_FEATURE_TYPE is a - * value that identifies the hardware feature type of an object - * with CK_OBJECT_CLASS equal to CKO_HW_FEATURE. */ -typedef CK_ULONG CK_HW_FEATURE_TYPE; - -/* The following hardware feature types are defined */ -#define CKH_MONOTONIC_COUNTER 0x00000001 -#define CKH_CLOCK 0x00000002 -#define CKH_VENDOR_DEFINED 0x80000000 - -/* CK_KEY_TYPE is a value that identifies a key type */ -/* CK_KEY_TYPE was changed from CK_USHORT to CK_ULONG for v2.0 */ -typedef CK_ULONG CK_KEY_TYPE; - -/* the following key types are defined: */ -#define CKK_RSA 0x00000000 -#define CKK_DSA 0x00000001 -#define CKK_DH 0x00000002 - -/* CKK_ECDSA and CKK_KEA are new for v2.0 */ -/* CKK_X9_42_DH is new for v2.11 */ -#define CKK_ECDSA 0x00000003 /* deprecated in v2.11 */ -#define CKK_EC 0x00000003 -#define CKK_X9_42_DH 0x00000004 -#define CKK_KEA 0x00000005 - -#define CKK_GENERIC_SECRET 0x00000010 -#define CKK_RC2 0x00000011 -#define CKK_RC4 0x00000012 -#define CKK_DES 0x00000013 -#define CKK_DES2 0x00000014 -#define CKK_DES3 0x00000015 - -/* all these key types are new for v2.0 */ -#define CKK_CAST 0x00000016 -#define CKK_CAST3 0x00000017 -#define CKK_CAST5 0x00000018 /* deprecated in v2.11 */ -#define CKK_CAST128 0x00000018 -#define CKK_RC5 0x00000019 -#define CKK_IDEA 0x0000001A -#define CKK_SKIPJACK 0x0000001B -#define CKK_BATON 0x0000001C -#define CKK_JUNIPER 0x0000001D -#define CKK_CDMF 0x0000001E - -/* all these key types are new for v2.11 */ -#define CKK_AES 0x0000001F - -#define CKK_VENDOR_DEFINED 0x80000000 -#define CKK_INVALID_KEY_TYPE 0xffffffff - - -/* CK_CERTIFICATE_TYPE is a value that identifies a certificate - * type */ -/* CK_CERTIFICATE_TYPE was changed from CK_USHORT to CK_ULONG - * for v2.0 */ -typedef CK_ULONG CK_CERTIFICATE_TYPE; - -/* The following certificate types are defined: */ -/* CKC_X_509_ATTR_CERT is new for v2.10 */ -#define CKC_X_509 0x00000000 -#define CKC_X_509_ATTR_CERT 0x00000001 -#define CKC_VENDOR_DEFINED 0x80000000 - - -/* CK_ATTRIBUTE_TYPE is a value that identifies an attribute - * type */ -/* CK_ATTRIBUTE_TYPE was changed from CK_USHORT to CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_ATTRIBUTE_TYPE; - -/* The following attribute types are defined: */ -#define CKA_CLASS 0x00000000 -#define CKA_TOKEN 0x00000001 -#define CKA_PRIVATE 0x00000002 -#define CKA_LABEL 0x00000003 -#define CKA_APPLICATION 0x00000010 -#define CKA_VALUE 0x00000011 - -/* CKA_OBJECT_ID is new for v2.10 */ -#define CKA_OBJECT_ID 0x00000012 - -#define CKA_CERTIFICATE_TYPE 0x00000080 -#define CKA_ISSUER 0x00000081 -#define CKA_SERIAL_NUMBER 0x00000082 - -/* CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new - * for v2.10 */ -#define CKA_AC_ISSUER 0x00000083 -#define CKA_OWNER 0x00000084 -#define CKA_ATTR_TYPES 0x00000085 -/* CKA_TRUSTED is new for v2.11 */ -#define CKA_TRUSTED 0x00000086 - -#define CKA_KEY_TYPE 0x00000100 -#define CKA_SUBJECT 0x00000101 -#define CKA_ID 0x00000102 -#define CKA_SENSITIVE 0x00000103 -#define CKA_ENCRYPT 0x00000104 -#define CKA_DECRYPT 0x00000105 -#define CKA_WRAP 0x00000106 -#define CKA_UNWRAP 0x00000107 -#define CKA_SIGN 0x00000108 -#define CKA_SIGN_RECOVER 0x00000109 -#define CKA_VERIFY 0x0000010A -#define CKA_VERIFY_RECOVER 0x0000010B -#define CKA_DERIVE 0x0000010C -#define CKA_START_DATE 0x00000110 -#define CKA_END_DATE 0x00000111 -#define CKA_MODULUS 0x00000120 -#define CKA_MODULUS_BITS 0x00000121 -#define CKA_PUBLIC_EXPONENT 0x00000122 -#define CKA_PRIVATE_EXPONENT 0x00000123 -#define CKA_PRIME_1 0x00000124 -#define CKA_PRIME_2 0x00000125 -#define CKA_EXPONENT_1 0x00000126 -#define CKA_EXPONENT_2 0x00000127 -#define CKA_COEFFICIENT 0x00000128 -#define CKA_PRIME 0x00000130 -#define CKA_SUBPRIME 0x00000131 -#define CKA_BASE 0x00000132 -/* CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11 */ -#define CKA_PRIME_BITS 0x00000133 -#define CKA_SUB_PRIME_BITS 0x00000134 -#define CKA_VALUE_BITS 0x00000160 -#define CKA_VALUE_LEN 0x00000161 - -/* CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE, - * CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS, - * and CKA_EC_POINT are new for v2.0 */ -#define CKA_EXTRACTABLE 0x00000162 -#define CKA_LOCAL 0x00000163 -#define CKA_NEVER_EXTRACTABLE 0x00000164 -#define CKA_ALWAYS_SENSITIVE 0x00000165 -/* CKA_KEY_GEN_MECHANISM is new for v2.11 */ -#define CKA_KEY_GEN_MECHANISM 0x00000166 -#define CKA_MODIFIABLE 0x00000170 -#define CKA_ECDSA_PARAMS 0x00000180 /* depricated v2.11 */ -#define CKA_EC_PARAMS 0x00000180 -#define CKA_EC_POINT 0x00000181 - -/* CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS, - * CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET - * are new for v2.10 */ -#define CKA_SECONDARY_AUTH 0x00000200 /* depricated v2.11 */ -#define CKA_AUTH_PIN_FLAGS 0x00000201 /* depricated v2.11 */ -#define CKA_HW_FEATURE_TYPE 0x00000300 -#define CKA_RESET_ON_INIT 0x00000301 -#define CKA_HAS_RESET 0x00000302 - -#define CKA_VENDOR_DEFINED 0x80000000 - - -/* CK_ATTRIBUTE is a structure that includes the type, length - * and value of an attribute */ -typedef struct CK_ATTRIBUTE { - CK_ATTRIBUTE_TYPE type; - CK_VOID_PTR pValue; - - /* ulValueLen went from CK_USHORT to CK_ULONG for v2.0 */ - CK_ULONG ulValueLen; /* in bytes */ -} CK_ATTRIBUTE; - -typedef CK_ATTRIBUTE CK_PTR CK_ATTRIBUTE_PTR; - - -/* CK_DATE is a structure that defines a date */ -typedef struct CK_DATE{ - CK_CHAR year[4]; /* the year ("1900" - "9999") */ - CK_CHAR month[2]; /* the month ("01" - "12") */ - CK_CHAR day[2]; /* the day ("01" - "31") */ -} CK_DATE; - - -/* CK_MECHANISM_TYPE is a value that identifies a mechanism - * type */ -/* CK_MECHANISM_TYPE was changed from CK_USHORT to CK_ULONG for - * v2.0 */ -typedef CK_ULONG CK_MECHANISM_TYPE; - -/* the following mechanism types are defined: */ -#define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000 -#define CKM_RSA_PKCS 0x00000001 -#define CKM_RSA_9796 0x00000002 -#define CKM_RSA_X_509 0x00000003 - -/* CKM_MD2_RSA_PKCS, CKM_MD5_RSA_PKCS, and CKM_SHA1_RSA_PKCS - * are new for v2.0. They are mechanisms which hash and sign */ -#define CKM_MD2_RSA_PKCS 0x00000004 -#define CKM_MD5_RSA_PKCS 0x00000005 -#define CKM_SHA1_RSA_PKCS 0x00000006 - -/* CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160_RSA_PKCS & CKM_RSA_OAEP - * are new for 2.10 */ -#define CKM_RIPEMD128_RSA_PKCS 0x00000007 -#define CKM_RIPEMD160_RSA_PKCS 0x00000008 -#define CKM_RSA_PKCS_OAEP 0x00000009 - -/* CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31 & CKM_RSA_X9_31_KEY_PAIR_GEN - * are new for 2.11 */ -#define CKM_RSA_X9_31_KEY_PAIR_GEN 0x0000000A -#define CKM_RSA_X9_31 0x0000000B -#define CKM_SHA1_RSA_X9_31 0x0000000C - -#define CKM_DSA_KEY_PAIR_GEN 0x00000010 -#define CKM_DSA 0x00000011 -#define CKM_DSA_SHA1 0x00000012 -#define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020 -#define CKM_DH_PKCS_DERIVE 0x00000021 - -/* CKM_X9_42_DH_PKCS_KEY_PAIR_GEN, CKM_X9_42_DH_DERIVE, - * CKM_X9_42_DH_HYBRID_DERIVE, & CKM_X9_42_MQV_DERIVE - * are new for v2.11 */ -#define CKM_X9_42_DH_PKCS_KEY_PAIR_GEN 0x00000030 -#define CKM_X9_42_DH_DERIVE 0x00000031 -#define CKM_X9_42_DH_HYBRID_DERIVE 0x00000032 -#define CKM_X9_42_MQV_DERIVE 0x00000033 - -#define CKM_SHA256_RSA_PKCS 0x00000040 /* v2.20 */ -#define CKM_SHA384_RSA_PKCS 0x00000041 /* v2.20 */ -#define CKM_SHA512_RSA_PKCS 0x00000042 /* v2.20 */ - -#define CKM_RC2_KEY_GEN 0x00000100 -#define CKM_RC2_ECB 0x00000101 -#define CKM_RC2_CBC 0x00000102 -#define CKM_RC2_MAC 0x00000103 - -/* CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0 */ -#define CKM_RC2_MAC_GENERAL 0x00000104 -#define CKM_RC2_CBC_PAD 0x00000105 - -#define CKM_RC4_KEY_GEN 0x00000110 -#define CKM_RC4 0x00000111 -#define CKM_DES_KEY_GEN 0x00000120 -#define CKM_DES_ECB 0x00000121 -#define CKM_DES_CBC 0x00000122 -#define CKM_DES_MAC 0x00000123 - -/* CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0 */ -#define CKM_DES_MAC_GENERAL 0x00000124 -#define CKM_DES_CBC_PAD 0x00000125 - -#define CKM_DES2_KEY_GEN 0x00000130 -#define CKM_DES3_KEY_GEN 0x00000131 -#define CKM_DES3_ECB 0x00000132 -#define CKM_DES3_CBC 0x00000133 -#define CKM_DES3_MAC 0x00000134 - -/* CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN, - * CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC, - * CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0 */ -#define CKM_DES3_MAC_GENERAL 0x00000135 -#define CKM_DES3_CBC_PAD 0x00000136 -#define CKM_CDMF_KEY_GEN 0x00000140 -#define CKM_CDMF_ECB 0x00000141 -#define CKM_CDMF_CBC 0x00000142 -#define CKM_CDMF_MAC 0x00000143 -#define CKM_CDMF_MAC_GENERAL 0x00000144 -#define CKM_CDMF_CBC_PAD 0x00000145 - -#define CKM_MD2 0x00000200 - -/* CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0 */ -#define CKM_MD2_HMAC 0x00000201 -#define CKM_MD2_HMAC_GENERAL 0x00000202 - -#define CKM_MD5 0x00000210 - -/* CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0 */ -#define CKM_MD5_HMAC 0x00000211 -#define CKM_MD5_HMAC_GENERAL 0x00000212 - -#define CKM_SHA_1 0x00000220 - -/* CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0 */ -#define CKM_SHA_1_HMAC 0x00000221 -#define CKM_SHA_1_HMAC_GENERAL 0x00000222 - -/* CKM_RIPEMD128, CKM_RIPEMD128_HMAC, - * CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC, - * and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10 */ -#define CKM_RIPEMD128 0x00000230 -#define CKM_RIPEMD128_HMAC 0x00000231 -#define CKM_RIPEMD128_HMAC_GENERAL 0x00000232 -#define CKM_RIPEMD160 0x00000240 -#define CKM_RIPEMD160_HMAC 0x00000241 -#define CKM_RIPEMD160_HMAC_GENERAL 0x00000242 - -#define CKM_SHA256 0x00000250 /* v2.20 */ -#define CKM_SHA256_HMAC_GENERAL 0x00000251 /* v2.20 */ -#define CKM_SHA256_HMAC 0x00000252 /* v2.20 */ - -#define CKM_SHA384 0x00000260 /* v2.20 */ -#define CKM_SHA384_HMAC_GENERAL 0x00000261 /* v2.20 */ -#define CKM_SHA384_HMAC 0x00000262 /* v2.20 */ - -#define CKM_SHA512 0x00000270 /* v2.20 */ -#define CKM_SHA512_HMAC_GENERAL 0x00000271 /* v2.20 */ -#define CKM_SHA512_HMAC 0x00000272 /* v2.20 */ - -/* All of the following mechanisms are new for v2.0 */ -/* Note that CAST128 and CAST5 are the same algorithm */ -#define CKM_CAST_KEY_GEN 0x00000300 -#define CKM_CAST_ECB 0x00000301 -#define CKM_CAST_CBC 0x00000302 -#define CKM_CAST_MAC 0x00000303 -#define CKM_CAST_MAC_GENERAL 0x00000304 -#define CKM_CAST_CBC_PAD 0x00000305 -#define CKM_CAST3_KEY_GEN 0x00000310 -#define CKM_CAST3_ECB 0x00000311 -#define CKM_CAST3_CBC 0x00000312 -#define CKM_CAST3_MAC 0x00000313 -#define CKM_CAST3_MAC_GENERAL 0x00000314 -#define CKM_CAST3_CBC_PAD 0x00000315 -#define CKM_CAST5_KEY_GEN 0x00000320 -#define CKM_CAST128_KEY_GEN 0x00000320 -#define CKM_CAST5_ECB 0x00000321 -#define CKM_CAST128_ECB 0x00000321 -#define CKM_CAST5_CBC 0x00000322 -#define CKM_CAST128_CBC 0x00000322 -#define CKM_CAST5_MAC 0x00000323 -#define CKM_CAST128_MAC 0x00000323 -#define CKM_CAST5_MAC_GENERAL 0x00000324 -#define CKM_CAST128_MAC_GENERAL 0x00000324 -#define CKM_CAST5_CBC_PAD 0x00000325 -#define CKM_CAST128_CBC_PAD 0x00000325 -#define CKM_RC5_KEY_GEN 0x00000330 -#define CKM_RC5_ECB 0x00000331 -#define CKM_RC5_CBC 0x00000332 -#define CKM_RC5_MAC 0x00000333 -#define CKM_RC5_MAC_GENERAL 0x00000334 -#define CKM_RC5_CBC_PAD 0x00000335 -#define CKM_IDEA_KEY_GEN 0x00000340 -#define CKM_IDEA_ECB 0x00000341 -#define CKM_IDEA_CBC 0x00000342 -#define CKM_IDEA_MAC 0x00000343 -#define CKM_IDEA_MAC_GENERAL 0x00000344 -#define CKM_IDEA_CBC_PAD 0x00000345 -#define CKM_GENERIC_SECRET_KEY_GEN 0x00000350 -#define CKM_CONCATENATE_BASE_AND_KEY 0x00000360 -#define CKM_CONCATENATE_BASE_AND_DATA 0x00000362 -#define CKM_CONCATENATE_DATA_AND_BASE 0x00000363 -#define CKM_XOR_BASE_AND_DATA 0x00000364 -#define CKM_EXTRACT_KEY_FROM_KEY 0x00000365 -#define CKM_SSL3_PRE_MASTER_KEY_GEN 0x00000370 -#define CKM_SSL3_MASTER_KEY_DERIVE 0x00000371 -#define CKM_SSL3_KEY_AND_MAC_DERIVE 0x00000372 - -/* CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN, - * CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, - * CKM_TLS_MASTER_KEY_DERIVE_DH, & CKM_SSL3_MASTER_KEY_DERIVE_DH - * are new for v2.11. */ -#define CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373 -#define CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374 -#define CKM_TLS_MASTER_KEY_DERIVE 0x00000375 -#define CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376 -#define CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377 - -#define CKM_SSL3_MD5_MAC 0x00000380 -#define CKM_SSL3_SHA1_MAC 0x00000381 -#define CKM_MD5_KEY_DERIVATION 0x00000390 -#define CKM_MD2_KEY_DERIVATION 0x00000391 -#define CKM_SHA1_KEY_DERIVATION 0x00000392 -#define CKM_SHA256_KEY_DERIVATION 0x00000393 /* v2.20 */ -#define CKM_SHA384_KEY_DERIVATION 0x00000394 /* v2.20 */ -#define CKM_SHA512_KEY_DERIVATION 0x00000395 /* v2.20 */ - -#define CKM_PBE_MD2_DES_CBC 0x000003A0 -#define CKM_PBE_MD5_DES_CBC 0x000003A1 -#define CKM_PBE_MD5_CAST_CBC 0x000003A2 -#define CKM_PBE_MD5_CAST3_CBC 0x000003A3 -#define CKM_PBE_MD5_CAST5_CBC 0x000003A4 -#define CKM_PBE_MD5_CAST128_CBC 0x000003A4 -#define CKM_PBE_SHA1_CAST5_CBC 0x000003A5 -#define CKM_PBE_SHA1_CAST128_CBC 0x000003A5 -#define CKM_PBE_SHA1_RC4_128 0x000003A6 -#define CKM_PBE_SHA1_RC4_40 0x000003A7 -#define CKM_PBE_SHA1_DES3_EDE_CBC 0x000003A8 -#define CKM_PBE_SHA1_DES2_EDE_CBC 0x000003A9 -#define CKM_PBE_SHA1_RC2_128_CBC 0x000003AA -#define CKM_PBE_SHA1_RC2_40_CBC 0x000003AB - -/* CKM_PKCS5_PBKD2 is new for v2.10 */ -#define CKM_PKCS5_PBKD2 0x000003B0 - -#define CKM_PBA_SHA1_WITH_SHA1_HMAC 0x000003C0 -#define CKM_KEY_WRAP_LYNKS 0x00000400 -#define CKM_KEY_WRAP_SET_OAEP 0x00000401 - -/* Fortezza mechanisms */ -#define CKM_SKIPJACK_KEY_GEN 0x00001000 -#define CKM_SKIPJACK_ECB64 0x00001001 -#define CKM_SKIPJACK_CBC64 0x00001002 -#define CKM_SKIPJACK_OFB64 0x00001003 -#define CKM_SKIPJACK_CFB64 0x00001004 -#define CKM_SKIPJACK_CFB32 0x00001005 -#define CKM_SKIPJACK_CFB16 0x00001006 -#define CKM_SKIPJACK_CFB8 0x00001007 -#define CKM_SKIPJACK_WRAP 0x00001008 -#define CKM_SKIPJACK_PRIVATE_WRAP 0x00001009 -#define CKM_SKIPJACK_RELAYX 0x0000100a -#define CKM_KEA_KEY_PAIR_GEN 0x00001010 -#define CKM_KEA_KEY_DERIVE 0x00001011 -#define CKM_FORTEZZA_TIMESTAMP 0x00001020 -#define CKM_BATON_KEY_GEN 0x00001030 -#define CKM_BATON_ECB128 0x00001031 -#define CKM_BATON_ECB96 0x00001032 -#define CKM_BATON_CBC128 0x00001033 -#define CKM_BATON_COUNTER 0x00001034 -#define CKM_BATON_SHUFFLE 0x00001035 -#define CKM_BATON_WRAP 0x00001036 -#define CKM_ECDSA_KEY_PAIR_GEN 0x00001040 /* depricated in v2.11 */ -#define CKM_EC_KEY_PAIR_GEN 0x00001040 -#define CKM_ECDSA 0x00001041 -#define CKM_ECDSA_SHA1 0x00001042 - -/* ECDH1 is new for 2.11 */ -#define CKM_ECDH1_DERIVE 0x00001043 -#define CKM_ECDH1_COFACTOR_DERIVE 0x00001044 -#define CKM_ECMQV_DERIVE 0x00001045 - -#define CKM_JUNIPER_KEY_GEN 0x00001060 -#define CKM_JUNIPER_ECB128 0x00001061 -#define CKM_JUNIPER_CBC128 0x00001062 -#define CKM_JUNIPER_COUNTER 0x00001063 -#define CKM_JUNIPER_SHUFFLE 0x00001064 -#define CKM_JUNIPER_WRAP 0x00001065 -#define CKM_FASTHASH 0x00001070 - -/* AES is new for 2.11 */ -#define CKM_AES_KEY_GEN 0x00001080 -#define CKM_AES_ECB 0x00001081 -#define CKM_AES_CBC 0x00001082 -#define CKM_AES_MAC 0x00001083 -#define CKM_AES_MAC_GENERAL 0x00001084 -#define CKM_AES_CBC_PAD 0x00001085 - -/* CKM_DSA_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN, - * and CKM_DH_X9_42_PARAMETER_GEN are new for 2.11 */ -#define CKM_DSA_PARAMETER_GEN 0x00002000 -#define CKM_DH_PKCS_PARAMETER_GEN 0x00002001 -#define CKM_DH_X9_42_PARAMETER_GEN 0x00002002 - -#define CKM_VENDOR_DEFINED 0x80000000 - -typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR; - - -/* CK_MECHANISM is a structure that specifies a particular - * mechanism */ -typedef struct CK_MECHANISM { - CK_MECHANISM_TYPE mechanism; - CK_VOID_PTR pParameter; - - /* ulParameterLen was changed from CK_USHORT to CK_ULONG for - * v2.0 */ - CK_ULONG ulParameterLen; /* in bytes */ -} CK_MECHANISM; - -typedef CK_MECHANISM CK_PTR CK_MECHANISM_PTR; - - -/* CK_MECHANISM_INFO provides information about a particular - * mechanism */ -typedef struct CK_MECHANISM_INFO { - CK_ULONG ulMinKeySize; - CK_ULONG ulMaxKeySize; - CK_FLAGS flags; -} CK_MECHANISM_INFO; - -/* The flags are defined as follows: - * Bit Flag Mask Meaning */ -#define CKF_HW 0x00000001 /* performed by HW */ - -/* The flags CKF_ENCRYPT, CKF_DECRYPT, CKF_DIGEST, CKF_SIGN, - * CKG_SIGN_RECOVER, CKF_VERIFY, CKF_VERIFY_RECOVER, - * CKF_GENERATE, CKF_GENERATE_KEY_PAIR, CKF_WRAP, CKF_UNWRAP, - * and CKF_DERIVE are new for v2.0. They specify whether or not - * a mechanism can be used for a particular task */ -/* The flags CKF_EC_FP, CKF_EC_F_2M, CKF_EC_ECPARAMETERS, CKF_EC_NAMEDCURVE, - * CKF_EC_UNCOMPRESS, and CKF_EC_COMPRESS are new for v2.11 */ -#define CKF_ENCRYPT 0x00000100 -#define CKF_DECRYPT 0x00000200 -#define CKF_DIGEST 0x00000400 -#define CKF_SIGN 0x00000800 -#define CKF_SIGN_RECOVER 0x00001000 -#define CKF_VERIFY 0x00002000 -#define CKF_VERIFY_RECOVER 0x00004000 -#define CKF_GENERATE 0x00008000 -#define CKF_GENERATE_KEY_PAIR 0x00010000 -#define CKF_WRAP 0x00020000 -#define CKF_UNWRAP 0x00040000 -#define CKF_DERIVE 0x00080000 -#define CKF_EC_FP 0x00100000 -#define CKF_EC_F_2M 0x00200000 -#define CKF_EC_ECPARAMETERS 0x00400000 -#define CKF_EC_NAMEDCURVE 0x00800000 -#define CKF_EC_UNCOMPRESS 0x01000000 -#define CKF_EC_COMPRESS 0x02000000 - -#define CKF_EXTENSION 0x80000000 /* FALSE for 2.01 */ - -typedef CK_MECHANISM_INFO CK_PTR CK_MECHANISM_INFO_PTR; - - -/* CK_RV is a value that identifies the return value of a - * PKCS #11 function */ -/* CK_RV was changed from CK_USHORT to CK_ULONG for v2.0 */ -typedef CK_ULONG CK_RV; - -#define CKR_OK 0x00000000 -#define CKR_CANCEL 0x00000001 -#define CKR_HOST_MEMORY 0x00000002 -#define CKR_SLOT_ID_INVALID 0x00000003 - -/* CKR_FLAGS_INVALID was removed for v2.0 */ - -/* CKR_GENERAL_ERROR and CKR_FUNCTION_FAILED are new for v2.0 */ -#define CKR_GENERAL_ERROR 0x00000005 -#define CKR_FUNCTION_FAILED 0x00000006 - -/* CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS, - * and CKR_CANT_LOCK are new for v2.01 */ -#define CKR_ARGUMENTS_BAD 0x00000007 -#define CKR_NO_EVENT 0x00000008 -#define CKR_NEED_TO_CREATE_THREADS 0x00000009 -#define CKR_CANT_LOCK 0x0000000A - -#define CKR_ATTRIBUTE_READ_ONLY 0x00000010 -#define CKR_ATTRIBUTE_SENSITIVE 0x00000011 -#define CKR_ATTRIBUTE_TYPE_INVALID 0x00000012 -#define CKR_ATTRIBUTE_VALUE_INVALID 0x00000013 -#define CKR_DATA_INVALID 0x00000020 -#define CKR_DATA_LEN_RANGE 0x00000021 -#define CKR_DEVICE_ERROR 0x00000030 -#define CKR_DEVICE_MEMORY 0x00000031 -#define CKR_DEVICE_REMOVED 0x00000032 -#define CKR_ENCRYPTED_DATA_INVALID 0x00000040 -#define CKR_ENCRYPTED_DATA_LEN_RANGE 0x00000041 -#define CKR_FUNCTION_CANCELED 0x00000050 -#define CKR_FUNCTION_NOT_PARALLEL 0x00000051 - -/* CKR_FUNCTION_NOT_SUPPORTED is new for v2.0 */ -#define CKR_FUNCTION_NOT_SUPPORTED 0x00000054 - -#define CKR_KEY_HANDLE_INVALID 0x00000060 - -/* CKR_KEY_SENSITIVE was removed for v2.0 */ - -#define CKR_KEY_SIZE_RANGE 0x00000062 -#define CKR_KEY_TYPE_INCONSISTENT 0x00000063 - -/* CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED, - * CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED, - * CKR_KEY_NOT_WRAPPABLE, and CKR_KEY_UNEXTRACTABLE are new for - * v2.0 */ -#define CKR_KEY_NOT_NEEDED 0x00000064 -#define CKR_KEY_CHANGED 0x00000065 -#define CKR_KEY_NEEDED 0x00000066 -#define CKR_KEY_INDIGESTIBLE 0x00000067 -#define CKR_KEY_FUNCTION_NOT_PERMITTED 0x00000068 -#define CKR_KEY_NOT_WRAPPABLE 0x00000069 -#define CKR_KEY_UNEXTRACTABLE 0x0000006A - -/* CKR_KEY_PARAMS_INVALID is new for v2.11 */ -#define CKR_KEY_PARAMS_INVALID 0x0000006B - -#define CKR_MECHANISM_INVALID 0x00000070 -#define CKR_MECHANISM_PARAM_INVALID 0x00000071 - -/* CKR_OBJECT_CLASS_INCONSISTENT and CKR_OBJECT_CLASS_INVALID - * were removed for v2.0 */ -#define CKR_OBJECT_HANDLE_INVALID 0x00000082 -#define CKR_OPERATION_ACTIVE 0x00000090 -#define CKR_OPERATION_NOT_INITIALIZED 0x00000091 -#define CKR_PIN_INCORRECT 0x000000A0 -#define CKR_PIN_INVALID 0x000000A1 -#define CKR_PIN_LEN_RANGE 0x000000A2 - -/* CKR_PIN_EXPIRED and CKR_PIN_LOCKED are new for v2.0 */ -#define CKR_PIN_EXPIRED 0x000000A3 -#define CKR_PIN_LOCKED 0x000000A4 - -#define CKR_SESSION_CLOSED 0x000000B0 -#define CKR_SESSION_COUNT 0x000000B1 -#define CKR_SESSION_HANDLE_INVALID 0x000000B3 -#define CKR_SESSION_PARALLEL_NOT_SUPPORTED 0x000000B4 -#define CKR_SESSION_READ_ONLY 0x000000B5 -#define CKR_SESSION_EXISTS 0x000000B6 - -/* CKR_SESSION_READ_ONLY_EXISTS and - * CKR_SESSION_READ_WRITE_SO_EXISTS are new for v2.0 */ -#define CKR_SESSION_READ_ONLY_EXISTS 0x000000B7 -#define CKR_SESSION_READ_WRITE_SO_EXISTS 0x000000B8 - -#define CKR_SIGNATURE_INVALID 0x000000C0 -#define CKR_SIGNATURE_LEN_RANGE 0x000000C1 -#define CKR_TEMPLATE_INCOMPLETE 0x000000D0 -#define CKR_TEMPLATE_INCONSISTENT 0x000000D1 -#define CKR_TOKEN_NOT_PRESENT 0x000000E0 -#define CKR_TOKEN_NOT_RECOGNIZED 0x000000E1 -#define CKR_TOKEN_WRITE_PROTECTED 0x000000E2 -#define CKR_UNWRAPPING_KEY_HANDLE_INVALID 0x000000F0 -#define CKR_UNWRAPPING_KEY_SIZE_RANGE 0x000000F1 -#define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT 0x000000F2 -#define CKR_USER_ALREADY_LOGGED_IN 0x00000100 -#define CKR_USER_NOT_LOGGED_IN 0x00000101 -#define CKR_USER_PIN_NOT_INITIALIZED 0x00000102 -#define CKR_USER_TYPE_INVALID 0x00000103 - -/* CKR_USER_ANOTHER_ALREADY_LOGGED_IN and CKR_USER_TOO_MANY_TYPES - * are new to v2.01 */ -#define CKR_USER_ANOTHER_ALREADY_LOGGED_IN 0x00000104 -#define CKR_USER_TOO_MANY_TYPES 0x00000105 - -#define CKR_WRAPPED_KEY_INVALID 0x00000110 -#define CKR_WRAPPED_KEY_LEN_RANGE 0x00000112 -#define CKR_WRAPPING_KEY_HANDLE_INVALID 0x00000113 -#define CKR_WRAPPING_KEY_SIZE_RANGE 0x00000114 -#define CKR_WRAPPING_KEY_TYPE_INCONSISTENT 0x00000115 -#define CKR_RANDOM_SEED_NOT_SUPPORTED 0x00000120 - -/* New for v2.0 */ -#define CKR_RANDOM_NO_RNG 0x00000121 - -/* New for v2.11 */ -#define CKR_DOMAIN_PARAMS_INVALID 0x00000130 - -/* These are new to v2.0 */ -#define CKR_BUFFER_TOO_SMALL 0x00000150 -#define CKR_SAVED_STATE_INVALID 0x00000160 -#define CKR_INFORMATION_SENSITIVE 0x00000170 -#define CKR_STATE_UNSAVEABLE 0x00000180 - -/* These are new to v2.01 */ -#define CKR_CRYPTOKI_NOT_INITIALIZED 0x00000190 -#define CKR_CRYPTOKI_ALREADY_INITIALIZED 0x00000191 -#define CKR_MUTEX_BAD 0x000001A0 -#define CKR_MUTEX_NOT_LOCKED 0x000001A1 - -#define CKR_VENDOR_DEFINED 0x80000000 - - -/* CK_NOTIFY is an application callback that processes events */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_NOTIFY)( - CK_SESSION_HANDLE hSession, /* the session's handle */ - CK_NOTIFICATION event, - CK_VOID_PTR pApplication /* passed to C_OpenSession */ -); - - -/* CK_FUNCTION_LIST is a structure holding a PKCS #11 spec - * version and pointers of appropriate types to all the - * PKCS #11 functions */ -/* CK_FUNCTION_LIST is new for v2.0 */ -typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST; - -typedef CK_FUNCTION_LIST CK_PTR CK_FUNCTION_LIST_PTR; - -typedef CK_FUNCTION_LIST_PTR CK_PTR CK_FUNCTION_LIST_PTR_PTR; - - -/* CK_CREATEMUTEX is an application callback for creating a - * mutex object */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_CREATEMUTEX)( - CK_VOID_PTR_PTR ppMutex /* location to receive ptr to mutex */ -); - - -/* CK_DESTROYMUTEX is an application callback for destroying a - * mutex object */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_DESTROYMUTEX)( - CK_VOID_PTR pMutex /* pointer to mutex */ -); - - -/* CK_LOCKMUTEX is an application callback for locking a mutex */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_LOCKMUTEX)( - CK_VOID_PTR pMutex /* pointer to mutex */ -); - - -/* CK_UNLOCKMUTEX is an application callback for unlocking a - * mutex */ -typedef CK_CALLBACK_FUNCTION(CK_RV, CK_UNLOCKMUTEX)( - CK_VOID_PTR pMutex /* pointer to mutex */ -); - - -/* CK_C_INITIALIZE_ARGS provides the optional arguments to - * C_Initialize */ -typedef struct CK_C_INITIALIZE_ARGS { - CK_CREATEMUTEX CreateMutex; - CK_DESTROYMUTEX DestroyMutex; - CK_LOCKMUTEX LockMutex; - CK_UNLOCKMUTEX UnlockMutex; - CK_FLAGS flags; - CK_CHAR_PTR *LibraryParameters; - CK_VOID_PTR pReserved; -} CK_C_INITIALIZE_ARGS; - -/* flags: bit flags that provide capabilities of the slot - * Bit Flag Mask Meaning - */ -#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001 -#define CKF_OS_LOCKING_OK 0x00000002 - -typedef CK_C_INITIALIZE_ARGS CK_PTR CK_C_INITIALIZE_ARGS_PTR; - - -/* additional flags for parameters to functions */ - -/* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */ -#define CKF_DONT_BLOCK 1 - -/* CK_RSA_PKCS_OAEP_MGF_TYPE is new for v2.10. - * CK_RSA_PKCS_OAEP_MGF_TYPE is used to indicate the Message - * Generation Function (MGF) applied to a message block when - * formatting a message block for the PKCS #1 OAEP encryption - * scheme. */ -typedef CK_ULONG CK_RSA_PKCS_OAEP_MGF_TYPE; - -typedef CK_RSA_PKCS_OAEP_MGF_TYPE CK_PTR CK_RSA_PKCS_OAEP_MGF_TYPE_PTR; - -/* The following MGFs are defined */ -#define CKG_MGF1_SHA1 0x00000001 - -/* CK_RSA_PKCS_OAEP_SOURCE_TYPE is new for v2.10. - * CK_RSA_PKCS_OAEP_SOURCE_TYPE is used to indicate the source - * of the encoding parameter when formatting a message block - * for the PKCS #1 OAEP encryption scheme. */ -typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE; - -typedef CK_RSA_PKCS_OAEP_SOURCE_TYPE CK_PTR CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR; - -/* The following encoding parameter sources are defined */ -#define CKZ_DATA_SPECIFIED 0x00000001 - -/* CK_RSA_PKCS_OAEP_PARAMS is new for v2.10. - * CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the - * CKM_RSA_PKCS_OAEP mechanism. */ -typedef struct CK_RSA_PKCS_OAEP_PARAMS { - CK_MECHANISM_TYPE hashAlg; - CK_RSA_PKCS_OAEP_MGF_TYPE mgf; - CK_RSA_PKCS_OAEP_SOURCE_TYPE source; - CK_VOID_PTR pSourceData; - CK_ULONG ulSourceDataLen; -} CK_RSA_PKCS_OAEP_PARAMS; - -typedef CK_RSA_PKCS_OAEP_PARAMS CK_PTR CK_RSA_PKCS_OAEP_PARAMS_PTR; - -/* CK_KEA_DERIVE_PARAMS provides the parameters to the - * CKM_KEA_DERIVE mechanism */ -/* CK_KEA_DERIVE_PARAMS is new for v2.0 */ -typedef struct CK_KEA_DERIVE_PARAMS { - CK_BBOOL isSender; - CK_ULONG ulRandomLen; - CK_BYTE_PTR pRandomA; - CK_BYTE_PTR pRandomB; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; -} CK_KEA_DERIVE_PARAMS; - -typedef CK_KEA_DERIVE_PARAMS CK_PTR CK_KEA_DERIVE_PARAMS_PTR; - - -/* CK_RC2_PARAMS provides the parameters to the CKM_RC2_ECB and - * CKM_RC2_MAC mechanisms. An instance of CK_RC2_PARAMS just - * holds the effective keysize */ -typedef CK_ULONG CK_RC2_PARAMS; - -typedef CK_RC2_PARAMS CK_PTR CK_RC2_PARAMS_PTR; - - -/* CK_RC2_CBC_PARAMS provides the parameters to the CKM_RC2_CBC - * mechanism */ -typedef struct CK_RC2_CBC_PARAMS { - /* ulEffectiveBits was changed from CK_USHORT to CK_ULONG for - * v2.0 */ - CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ - - CK_BYTE iv[8]; /* IV for CBC mode */ -} CK_RC2_CBC_PARAMS; - -typedef CK_RC2_CBC_PARAMS CK_PTR CK_RC2_CBC_PARAMS_PTR; - - -/* CK_RC2_MAC_GENERAL_PARAMS provides the parameters for the - * CKM_RC2_MAC_GENERAL mechanism */ -/* CK_RC2_MAC_GENERAL_PARAMS is new for v2.0 */ -typedef struct CK_RC2_MAC_GENERAL_PARAMS { - CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ - CK_ULONG ulMacLength; /* Length of MAC in bytes */ -} CK_RC2_MAC_GENERAL_PARAMS; - -typedef CK_RC2_MAC_GENERAL_PARAMS CK_PTR \ - CK_RC2_MAC_GENERAL_PARAMS_PTR; - - -/* CK_RC5_PARAMS provides the parameters to the CKM_RC5_ECB and - * CKM_RC5_MAC mechanisms */ -/* CK_RC5_PARAMS is new for v2.0 */ -typedef struct CK_RC5_PARAMS { - CK_ULONG ulWordsize; /* wordsize in bits */ - CK_ULONG ulRounds; /* number of rounds */ -} CK_RC5_PARAMS; - -typedef CK_RC5_PARAMS CK_PTR CK_RC5_PARAMS_PTR; - - -/* CK_RC5_CBC_PARAMS provides the parameters to the CKM_RC5_CBC - * mechanism */ -/* CK_RC5_CBC_PARAMS is new for v2.0 */ -typedef struct CK_RC5_CBC_PARAMS { - CK_ULONG ulWordsize; /* wordsize in bits */ - CK_ULONG ulRounds; /* number of rounds */ - CK_BYTE_PTR pIv; /* pointer to IV */ - CK_ULONG ulIvLen; /* length of IV in bytes */ -} CK_RC5_CBC_PARAMS; - -typedef CK_RC5_CBC_PARAMS CK_PTR CK_RC5_CBC_PARAMS_PTR; - - -/* CK_RC5_MAC_GENERAL_PARAMS provides the parameters for the - * CKM_RC5_MAC_GENERAL mechanism */ -/* CK_RC5_MAC_GENERAL_PARAMS is new for v2.0 */ -typedef struct CK_RC5_MAC_GENERAL_PARAMS { - CK_ULONG ulWordsize; /* wordsize in bits */ - CK_ULONG ulRounds; /* number of rounds */ - CK_ULONG ulMacLength; /* Length of MAC in bytes */ -} CK_RC5_MAC_GENERAL_PARAMS; - -typedef CK_RC5_MAC_GENERAL_PARAMS CK_PTR \ - CK_RC5_MAC_GENERAL_PARAMS_PTR; - - -/* CK_MAC_GENERAL_PARAMS provides the parameters to most block - * ciphers' MAC_GENERAL mechanisms. Its value is the length of - * the MAC */ -/* CK_MAC_GENERAL_PARAMS is new for v2.0 */ -typedef CK_ULONG CK_MAC_GENERAL_PARAMS; - -typedef CK_MAC_GENERAL_PARAMS CK_PTR CK_MAC_GENERAL_PARAMS_PTR; - - -/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the - * CKM_SKIPJACK_PRIVATE_WRAP mechanism */ -/* CK_SKIPJACK_PRIVATE_WRAP_PARAMS is new for v2.0 */ -typedef struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS { - CK_ULONG ulPasswordLen; - CK_BYTE_PTR pPassword; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; - CK_ULONG ulPAndGLen; - CK_ULONG ulQLen; - CK_ULONG ulRandomLen; - CK_BYTE_PTR pRandomA; - CK_BYTE_PTR pPrimeP; - CK_BYTE_PTR pBaseG; - CK_BYTE_PTR pSubprimeQ; -} CK_SKIPJACK_PRIVATE_WRAP_PARAMS; - -typedef CK_SKIPJACK_PRIVATE_WRAP_PARAMS CK_PTR \ - CK_SKIPJACK_PRIVATE_WRAP_PTR; - - -/* CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the - * CKM_SKIPJACK_RELAYX mechanism */ -/* CK_SKIPJACK_RELAYX_PARAMS is new for v2.0 */ -typedef struct CK_SKIPJACK_RELAYX_PARAMS { - CK_ULONG ulOldWrappedXLen; - CK_BYTE_PTR pOldWrappedX; - CK_ULONG ulOldPasswordLen; - CK_BYTE_PTR pOldPassword; - CK_ULONG ulOldPublicDataLen; - CK_BYTE_PTR pOldPublicData; - CK_ULONG ulOldRandomLen; - CK_BYTE_PTR pOldRandomA; - CK_ULONG ulNewPasswordLen; - CK_BYTE_PTR pNewPassword; - CK_ULONG ulNewPublicDataLen; - CK_BYTE_PTR pNewPublicData; - CK_ULONG ulNewRandomLen; - CK_BYTE_PTR pNewRandomA; -} CK_SKIPJACK_RELAYX_PARAMS; - -typedef CK_SKIPJACK_RELAYX_PARAMS CK_PTR \ - CK_SKIPJACK_RELAYX_PARAMS_PTR; - - -typedef struct CK_PBE_PARAMS { - CK_CHAR_PTR pInitVector; - CK_CHAR_PTR pPassword; - CK_ULONG ulPasswordLen; - CK_CHAR_PTR pSalt; - CK_ULONG ulSaltLen; - CK_ULONG ulIteration; -} CK_PBE_PARAMS; - -typedef CK_PBE_PARAMS CK_PTR CK_PBE_PARAMS_PTR; - - -/* CK_KEY_WRAP_SET_OAEP_PARAMS provides the parameters to the - * CKM_KEY_WRAP_SET_OAEP mechanism */ -/* CK_KEY_WRAP_SET_OAEP_PARAMS is new for v2.0 */ -typedef struct CK_KEY_WRAP_SET_OAEP_PARAMS { - CK_BYTE bBC; /* block contents byte */ - CK_BYTE_PTR pX; /* extra data */ - CK_ULONG ulXLen; /* length of extra data in bytes */ -} CK_KEY_WRAP_SET_OAEP_PARAMS; - -typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR \ - CK_KEY_WRAP_SET_OAEP_PARAMS_PTR; - - -typedef struct CK_SSL3_RANDOM_DATA { - CK_BYTE_PTR pClientRandom; - CK_ULONG ulClientRandomLen; - CK_BYTE_PTR pServerRandom; - CK_ULONG ulServerRandomLen; -} CK_SSL3_RANDOM_DATA; - - -typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS { - CK_SSL3_RANDOM_DATA RandomInfo; - CK_VERSION_PTR pVersion; -} CK_SSL3_MASTER_KEY_DERIVE_PARAMS; - -typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS CK_PTR \ - CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR; - - -typedef struct CK_SSL3_KEY_MAT_OUT { - CK_OBJECT_HANDLE hClientMacSecret; - CK_OBJECT_HANDLE hServerMacSecret; - CK_OBJECT_HANDLE hClientKey; - CK_OBJECT_HANDLE hServerKey; - CK_BYTE_PTR pIVClient; - CK_BYTE_PTR pIVServer; -} CK_SSL3_KEY_MAT_OUT; - -typedef CK_SSL3_KEY_MAT_OUT CK_PTR CK_SSL3_KEY_MAT_OUT_PTR; - - -typedef struct CK_SSL3_KEY_MAT_PARAMS { - CK_ULONG ulMacSizeInBits; - CK_ULONG ulKeySizeInBits; - CK_ULONG ulIVSizeInBits; - CK_BBOOL bIsExport; - CK_SSL3_RANDOM_DATA RandomInfo; - CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial; -} CK_SSL3_KEY_MAT_PARAMS; - -typedef CK_SSL3_KEY_MAT_PARAMS CK_PTR CK_SSL3_KEY_MAT_PARAMS_PTR; - - -typedef struct CK_KEY_DERIVATION_STRING_DATA { - CK_BYTE_PTR pData; - CK_ULONG ulLen; -} CK_KEY_DERIVATION_STRING_DATA; - -typedef CK_KEY_DERIVATION_STRING_DATA CK_PTR \ - CK_KEY_DERIVATION_STRING_DATA_PTR; - - -/* The CK_EXTRACT_PARAMS is used for the - * CKM_EXTRACT_KEY_FROM_KEY mechanism. It specifies which bit - * of the base key should be used as the first bit of the - * derived key */ -/* CK_EXTRACT_PARAMS is new for v2.0 */ -typedef CK_ULONG CK_EXTRACT_PARAMS; - -typedef CK_EXTRACT_PARAMS CK_PTR CK_EXTRACT_PARAMS_PTR; - -/* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is new for v2.10. - * CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to - * indicate the Pseudo-Random Function (PRF) used to generate - * key bits using PKCS #5 PBKDF2. */ -typedef CK_ULONG CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE; - -typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR; - -/* The following PRFs are defined in PKCS #5 v2.0. */ -#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001 - - -/* CK_PKCS5_PBKD2_SALT_SOURCE_TYPE is new for v2.10. - * CK_PKCS5_PBKD2_SALT_SOURCE_TYPE is used to indicate the - * source of the salt value when deriving a key using PKCS #5 - * PBKDF2. */ -typedef CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE; - -typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR; - -/* The following salt value sources are defined in PKCS #5 v2.0. */ -#define CKZ_SALT_SPECIFIED 0x00000001 - -/* CK_PKCS5_PBKD2_PARAMS is new for v2.10. - * CK_PKCS5_PBKD2_PARAMS is a structure that provides the - * parameters to the CKM_PKCS5_PBKD2 mechanism. */ -typedef struct CK_PKCS5_PBKD2_PARAMS { - CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource; - CK_VOID_PTR pSaltSourceData; - CK_ULONG ulSaltSourceDataLen; - CK_ULONG iterations; - CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf; - CK_VOID_PTR pPrfData; - CK_ULONG ulPrfDataLen; -} CK_PKCS5_PBKD2_PARAMS; - -typedef CK_PKCS5_PBKD2_PARAMS CK_PTR CK_PKCS5_PBKD2_PARAMS_PTR; - -/* CK_ECDH1_DERIVE_PARAMS is defined in Section 12.4.4 of - * PKCS#11v2.11. This structure provides parameters for - * the CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE key - * derivation mechanisms. - */ -typedef CK_ULONG CK_EC_KDF_TYPE; -#define CKD_NULL 0x00000001 -#define CKD_SHA1_KDF 0x00000002 - -typedef struct CK_ECDH1_DERIVE_PARAMS { - CK_EC_KDF_TYPE kdf; - CK_ULONG ulSharedDataLen; - CK_BYTE_PTR pSharedData; - CK_ULONG ulPublicDataLen; - CK_BYTE_PTR pPublicData; -} CK_ECDH1_DERIVE_PARAMS; - -typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR; - -/* Netscape Specific defines */ -#include "pkcs11n.h" - -/* undo packing */ -#include "pkcs11u.h" - -#endif diff --git a/security/nss/lib/softoken/pkcs11u.c b/security/nss/lib/softoken/pkcs11u.c deleted file mode 100644 index 046dcdde6..000000000 --- a/security/nss/lib/softoken/pkcs11u.c +++ /dev/null @@ -1,3040 +0,0 @@ -/* - * 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. - * - * Portions created by Sun Microsystems, Inc. are Copyright (C) 2003 - * Sun Microsystems, Inc. All Rights Reserved. - * - * Contributor(s): - * Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories - * - * 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. - */ -/* - * Internal PKCS #11 functions. Should only be called by pkcs11.c - */ -#include "pkcs11.h" -#include "pkcs11i.h" -#include "pcertt.h" -#include "lowkeyi.h" -#include "pcert.h" -#include "secasn1.h" -#include "blapi.h" -#include "secerr.h" - -/* - * ******************** Attribute Utilities ******************************* - */ - -/* - * create a new attribute with type, value, and length. Space is allocated - * to hold value. - */ -static PK11Attribute * -pk11_NewAttribute(PK11Object *object, - CK_ATTRIBUTE_TYPE type, CK_VOID_PTR value, CK_ULONG len) -{ - PK11Attribute *attribute; - -#ifdef PKCS11_STATIC_ATTRIBUTES - PK11SessionObject *so = pk11_narrowToSessionObject(object); - int index; - - if (so == NULL) { - /* allocate new attribute in a buffer */ - PORT_Assert(0); - } - /* - * PKCS11_STATIC_ATTRIBUTES attempts to keep down contention on Malloc and Arena locks - * by limiting the number of these calls on high traversed paths. this - * is done for attributes by 'allocating' them from a pool already allocated - * by the parent object. - */ - PK11_USE_THREADS(PZ_Lock(so->attributeLock);) - index = so->nextAttr++; - PK11_USE_THREADS(PZ_Unlock(so->attributeLock);) - PORT_Assert(index < MAX_OBJS_ATTRS); - if (index >= MAX_OBJS_ATTRS) return NULL; - - attribute = &so->attrList[index]; - attribute->attrib.type = type; - attribute->freeAttr = PR_FALSE; - attribute->freeData = PR_FALSE; - if (value) { - if (len <= ATTR_SPACE) { - attribute->attrib.pValue = attribute->space; - } else { - attribute->attrib.pValue = PORT_Alloc(len); - attribute->freeData = PR_TRUE; - } - if (attribute->attrib.pValue == NULL) { - return NULL; - } - PORT_Memcpy(attribute->attrib.pValue,value,len); - attribute->attrib.ulValueLen = len; - } else { - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; - } -#else -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - attribute = (PK11Attribute*)PORT_Alloc(sizeof(PK11Attribute)); - attribute->freeAttr = PR_TRUE; -#else - attribute = (PK11Attribute*)PORT_ArenaAlloc(object->arena,sizeof(PK11Attribute)); - attribute->freeAttr = PR_FALSE; -#endif /* PKCS11_REF_COUNT_ATTRIBUTES */ - if (attribute == NULL) return NULL; - attribute->freeData = PR_FALSE; - - if (value) { -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - attribute->attrib.pValue = PORT_Alloc(len); - attribute->freeData = PR_TRUE; -#else - attribute->attrib.pValue = PORT_ArenaAlloc(object->arena,len); -#endif /* PKCS11_REF_COUNT_ATTRIBUTES */ - if (attribute->attrib.pValue == NULL) { -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - PORT_Free(attribute); -#endif /* PKCS11_REF_COUNT_ATTRIBUTES */ - return NULL; - } - PORT_Memcpy(attribute->attrib.pValue,value,len); - attribute->attrib.ulValueLen = len; - } else { - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; - } -#endif /* PKCS11_STATIC_ATTRIBUTES */ - attribute->attrib.type = type; - attribute->handle = type; - attribute->next = attribute->prev = NULL; -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - attribute->refCount = 1; -#ifdef PKCS11_USE_THREADS - attribute->refLock = PZ_NewLock(nssILockRefLock); - if (attribute->refLock == NULL) { - if (attribute->attrib.pValue) PORT_Free(attribute->attrib.pValue); - PORT_Free(attribute); - return NULL; - } -#else - attribute->refLock = NULL; -#endif -#endif /* PKCS11_REF_COUNT_ATTRIBUTES */ - return attribute; -} - -static PK11Attribute * -pk11_NewTokenAttribute(CK_ATTRIBUTE_TYPE type, CK_VOID_PTR value, - CK_ULONG len, PRBool copy) -{ - PK11Attribute *attribute; - - attribute = (PK11Attribute*)PORT_Alloc(sizeof(PK11Attribute)); - - if (attribute == NULL) return NULL; - attribute->attrib.type = type; - attribute->handle = type; - attribute->next = attribute->prev = NULL; - attribute->freeAttr = PR_TRUE; - attribute->freeData = PR_FALSE; -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - attribute->refCount = 1; -#ifdef PKCS11_USE_THREADS - attribute->refLock = PZ_NewLock(nssILockRefLock); - if (attribute->refLock == NULL) { - PORT_Free(attribute); - return NULL; - } -#else - attribute->refLock = NULL; -#endif -#endif /* PKCS11_REF_COUNT_ATTRIBUTES */ - attribute->attrib.type = type; - if (!copy) { - attribute->attrib.pValue = value; - attribute->attrib.ulValueLen = len; - return attribute; - } - - if (value) { -#ifdef PKCS11_STATIC_ATTRIBUTES - if (len <= ATTR_SPACE) { - attribute->attrib.pValue = attribute->space; - } else { - attribute->attrib.pValue = PORT_Alloc(len); - attribute->freeData = PR_TRUE; - } -#else - attribute->attrib.pValue = PORT_Alloc(len); - attribute->freeData = PR_TRUE; -#endif - if (attribute->attrib.pValue == NULL) { -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - if (attribute->refLock) { - PK11_USE_THREADS(PZ_DestroyLock(attribute->refLock);) - } -#endif - PORT_Free(attribute); - return NULL; - } - PORT_Memcpy(attribute->attrib.pValue,value,len); - attribute->attrib.ulValueLen = len; - } else { - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; - } - return attribute; -} - -static PK11Attribute * -pk11_NewTokenAttributeSigned(CK_ATTRIBUTE_TYPE type, CK_VOID_PTR value, - CK_ULONG len, PRBool copy) -{ - unsigned char * dval = (unsigned char *)value; - if (*dval == 0) { - dval++; - len--; - } - return pk11_NewTokenAttribute(type,dval,len,copy); -} - -/* - * Free up all the memory associated with an attribute. Reference count - * must be zero to call this. - */ -static void -pk11_DestroyAttribute(PK11Attribute *attribute) -{ -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - PORT_Assert(attribute->refCount == 0); - PK11_USE_THREADS(PZ_DestroyLock(attribute->refLock);) -#endif - if (attribute->freeData) { - if (attribute->attrib.pValue) { - /* clear out the data in the attribute value... it may have been - * sensitive data */ - PORT_Memset(attribute->attrib.pValue, 0, - attribute->attrib.ulValueLen); - } - PORT_Free(attribute->attrib.pValue); - } - PORT_Free(attribute); -} - -/* - * release a reference to an attribute structure - */ -void -pk11_FreeAttribute(PK11Attribute *attribute) -{ -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - PRBool destroy = PR_FALSE; -#endif - - if (attribute->freeAttr) { - pk11_DestroyAttribute(attribute); - return; - } - -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - PK11_USE_THREADS(PZ_Lock(attribute->refLock);) - if (attribute->refCount == 1) destroy = PR_TRUE; - attribute->refCount--; - PK11_USE_THREADS(PZ_Unlock(attribute->refLock);) - - if (destroy) pk11_DestroyAttribute(attribute); -#endif -} - -#ifdef PKCS11_REF_COUNT_ATTRIBUTES -#define PK11_DEF_ATTRIBUTE(value,len) \ - { NULL, NULL, PR_FALSE, PR_FALSE, 1, NULL, 0, { 0, value, len } } - -#else -#define PK11_DEF_ATTRIBUTE(value,len) \ - { NULL, NULL, PR_FALSE, PR_FALSE, 0, { 0, value, len } } -#endif - -CK_BBOOL pk11_staticTrueValue = CK_TRUE; -CK_BBOOL pk11_staticFalseValue = CK_FALSE; -static const PK11Attribute pk11_StaticTrueAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticTrueValue,sizeof(pk11_staticTrueValue)); -static const PK11Attribute pk11_StaticFalseAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticFalseValue,sizeof(pk11_staticFalseValue)); -static const PK11Attribute pk11_StaticNullAttr = PK11_DEF_ATTRIBUTE(NULL,0); -char pk11_StaticOneValue = 1; -static const PK11Attribute pk11_StaticOneAttr = - PK11_DEF_ATTRIBUTE(&pk11_StaticOneValue,sizeof(pk11_StaticOneValue)); - -CK_CERTIFICATE_TYPE pk11_staticX509Value = CKC_X_509; -static const PK11Attribute pk11_StaticX509Attr = - PK11_DEF_ATTRIBUTE(&pk11_staticX509Value, sizeof(pk11_staticX509Value)); -CK_TRUST pk11_staticTrustedValue = CKT_NETSCAPE_TRUSTED; -CK_TRUST pk11_staticTrustedDelegatorValue = CKT_NETSCAPE_TRUSTED_DELEGATOR; -CK_TRUST pk11_staticValidDelegatorValue = CKT_NETSCAPE_VALID_DELEGATOR; -CK_TRUST pk11_staticUnTrustedValue = CKT_NETSCAPE_UNTRUSTED; -CK_TRUST pk11_staticTrustUnknownValue = CKT_NETSCAPE_TRUST_UNKNOWN; -CK_TRUST pk11_staticValidPeerValue = CKT_NETSCAPE_VALID; -CK_TRUST pk11_staticMustVerifyValue = CKT_NETSCAPE_MUST_VERIFY; -static const PK11Attribute pk11_StaticTrustedAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticTrustedValue, - sizeof(pk11_staticTrustedValue)); -static const PK11Attribute pk11_StaticTrustedDelegatorAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticTrustedDelegatorValue, - sizeof(pk11_staticTrustedDelegatorValue)); -static const PK11Attribute pk11_StaticValidDelegatorAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticValidDelegatorValue, - sizeof(pk11_staticValidDelegatorValue)); -static const PK11Attribute pk11_StaticUnTrustedAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticUnTrustedValue, - sizeof(pk11_staticUnTrustedValue)); -static const PK11Attribute pk11_StaticTrustUnknownAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticTrustUnknownValue, - sizeof(pk11_staticTrustUnknownValue)); -static const PK11Attribute pk11_StaticValidPeerAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticValidPeerValue, - sizeof(pk11_staticValidPeerValue)); -static const PK11Attribute pk11_StaticMustVerifyAttr = - PK11_DEF_ATTRIBUTE(&pk11_staticMustVerifyValue, - sizeof(pk11_staticMustVerifyValue)); - -static certDBEntrySMime * -pk11_getSMime(PK11TokenObject *object) -{ - certDBEntrySMime *entry; - - if (object->obj.objclass != CKO_NETSCAPE_SMIME) { - return NULL; - } - if (object->obj.objectInfo) { - return (certDBEntrySMime *)object->obj.objectInfo; - } - - entry = nsslowcert_ReadDBSMimeEntry(object->obj.slot->certDB, - (char *)object->dbKey.data); - object->obj.objectInfo = (void *)entry; - object->obj.infoFree = (PK11Free) nsslowcert_DestroyDBEntry; - return entry; -} - -static certDBEntryRevocation * -pk11_getCrl(PK11TokenObject *object) -{ - certDBEntryRevocation *crl; - PRBool isKrl; - - if (object->obj.objclass != CKO_NETSCAPE_CRL) { - return NULL; - } - if (object->obj.objectInfo) { - return (certDBEntryRevocation *)object->obj.objectInfo; - } - - isKrl = (PRBool) object->obj.handle == PK11_TOKEN_KRL_HANDLE; - crl = nsslowcert_FindCrlByKey(object->obj.slot->certDB, - &object->dbKey, isKrl); - object->obj.objectInfo = (void *)crl; - object->obj.infoFree = (PK11Free) nsslowcert_DestroyDBEntry; - return crl; -} - -static NSSLOWCERTCertificate * -pk11_getCert(PK11TokenObject *object) -{ - NSSLOWCERTCertificate *cert; - CK_OBJECT_CLASS objClass = object->obj.objclass; - - if ((objClass != CKO_CERTIFICATE) && (objClass != CKO_NETSCAPE_TRUST)) { - return NULL; - } - if (objClass == CKO_CERTIFICATE && object->obj.objectInfo) { - return (NSSLOWCERTCertificate *)object->obj.objectInfo; - } - cert = nsslowcert_FindCertByKey(object->obj.slot->certDB,&object->dbKey); - if (objClass == CKO_CERTIFICATE) { - object->obj.objectInfo = (void *)cert; - object->obj.infoFree = (PK11Free) nsslowcert_DestroyCertificate ; - } - return cert; -} - -static NSSLOWCERTTrust * -pk11_getTrust(PK11TokenObject *object) -{ - NSSLOWCERTTrust *trust; - - if (object->obj.objclass != CKO_NETSCAPE_TRUST) { - return NULL; - } - if (object->obj.objectInfo) { - return (NSSLOWCERTTrust *)object->obj.objectInfo; - } - trust = nsslowcert_FindTrustByKey(object->obj.slot->certDB,&object->dbKey); - object->obj.objectInfo = (void *)trust; - object->obj.infoFree = (PK11Free) nsslowcert_DestroyTrust ; - return trust; -} - -static NSSLOWKEYPublicKey * -pk11_GetPublicKey(PK11TokenObject *object) -{ - NSSLOWKEYPublicKey *pubKey; - NSSLOWKEYPrivateKey *privKey; - - if (object->obj.objclass != CKO_PUBLIC_KEY) { - return NULL; - } - if (object->obj.objectInfo) { - return (NSSLOWKEYPublicKey *)object->obj.objectInfo; - } - privKey = nsslowkey_FindKeyByPublicKey(object->obj.slot->keyDB, - &object->dbKey, object->obj.slot->password); - if (privKey == NULL) { - return NULL; - } - pubKey = nsslowkey_ConvertToPublicKey(privKey); - nsslowkey_DestroyPrivateKey(privKey); - object->obj.objectInfo = (void *) pubKey; - object->obj.infoFree = (PK11Free) nsslowkey_DestroyPublicKey ; - return pubKey; -} - -static NSSLOWKEYPrivateKey * -pk11_GetPrivateKey(PK11TokenObject *object) -{ - NSSLOWKEYPrivateKey *privKey; - - if ((object->obj.objclass != CKO_PRIVATE_KEY) && - (object->obj.objclass != CKO_SECRET_KEY)) { - return NULL; - } - if (object->obj.objectInfo) { - return (NSSLOWKEYPrivateKey *)object->obj.objectInfo; - } - privKey = nsslowkey_FindKeyByPublicKey(object->obj.slot->keyDB, - &object->dbKey, object->obj.slot->password); - if (privKey == NULL) { - return NULL; - } - object->obj.objectInfo = (void *) privKey; - object->obj.infoFree = (PK11Free) nsslowkey_DestroyPrivateKey ; - return privKey; -} - -/* pk11_GetPubItem returns data associated with the public key. - * one only needs to free the public key. This comment is here - * because this sematic would be non-obvious otherwise. All callers - * should include this comment. - */ -static SECItem * -pk11_GetPubItem(NSSLOWKEYPublicKey *pubKey) { - SECItem *pubItem = NULL; - /* get value to compare from the cert's public key */ - switch ( pubKey->keyType ) { - case NSSLOWKEYRSAKey: - pubItem = &pubKey->u.rsa.modulus; - break; - case NSSLOWKEYDSAKey: - pubItem = &pubKey->u.dsa.publicValue; - break; - case NSSLOWKEYDHKey: - pubItem = &pubKey->u.dh.publicValue; - break; -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - pubItem = &pubKey->u.ec.publicValue; - break; -#endif /* NSS_ENABLE_ECC */ - default: - break; - } - return pubItem; -} - -static const SEC_ASN1Template pk11_SerialTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWCERTCertificate,serialNumber) }, - { 0 } -}; - -static PK11Attribute * -pk11_FindRSAPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_RSA; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash,key->u.rsa.modulus.data,key->u.rsa.modulus.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_ENCRYPT: - case CKA_VERIFY: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_MODULUS: - return pk11_NewTokenAttributeSigned(type,key->u.rsa.modulus.data, - key->u.rsa.modulus.len, PR_FALSE); - case CKA_PUBLIC_EXPONENT: - return pk11_NewTokenAttributeSigned(type,key->u.rsa.publicExponent.data, - key->u.rsa.publicExponent.len, PR_FALSE); - default: - break; - } - return NULL; -} - -static PK11Attribute * -pk11_FindDSAPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_DSA; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dsa.publicValue.data, - key->u.dsa.publicValue.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - case CKA_ENCRYPT: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_VERIFY: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_VALUE: - return pk11_NewTokenAttributeSigned(type,key->u.dsa.publicValue.data, - key->u.dsa.publicValue.len, PR_FALSE); - case CKA_PRIME: - return pk11_NewTokenAttributeSigned(type,key->u.dsa.params.prime.data, - key->u.dsa.params.prime.len, PR_FALSE); - case CKA_SUBPRIME: - return pk11_NewTokenAttributeSigned(type, - key->u.dsa.params.subPrime.data, - key->u.dsa.params.subPrime.len, PR_FALSE); - case CKA_BASE: - return pk11_NewTokenAttributeSigned(type,key->u.dsa.params.base.data, - key->u.dsa.params.base.len, PR_FALSE); - default: - break; - } - return NULL; -} - -static PK11Attribute * -pk11_FindDHPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_DH; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dh.publicValue.data,key->u.dh.publicValue.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_ENCRYPT: - case CKA_VERIFY: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_VALUE: - return pk11_NewTokenAttributeSigned(type,key->u.dh.publicValue.data, - key->u.dh.publicValue.len, PR_FALSE); - case CKA_PRIME: - return pk11_NewTokenAttributeSigned(type,key->u.dh.prime.data, - key->u.dh.prime.len, PR_FALSE); - case CKA_BASE: - return pk11_NewTokenAttributeSigned(type,key->u.dh.base.data, - key->u.dh.base.len, PR_FALSE); - default: - break; - } - return NULL; -} - -#ifdef NSS_ENABLE_ECC -static PK11Attribute * -pk11_FindECPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_EC; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash, key->u.ec.publicValue.data, - key->u.ec.publicValue.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - case CKA_VERIFY: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_ENCRYPT: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_EC_PARAMS: - /* XXX Why is the last arg PR_FALSE? */ - return pk11_NewTokenAttributeSigned(type, - key->u.ec.ecParams.DEREncoding.data, - key->u.ec.ecParams.DEREncoding.len, - PR_FALSE); - case CKA_EC_POINT: - /* XXX Why is the last arg PR_FALSE? */ - return pk11_NewTokenAttributeSigned(type,key->u.ec.publicValue.data, - key->u.ec.publicValue.len, PR_FALSE); - default: - break; - } - return NULL; -} -#endif /* NSS_ENABLE_ECC */ - -static PK11Attribute * -pk11_FindPublicKeyAttribute(PK11TokenObject *object, CK_ATTRIBUTE_TYPE type) -{ - NSSLOWKEYPublicKey *key; - PK11Attribute *att = NULL; - char *label; - - switch (type) { - case CKA_PRIVATE: - case CKA_SENSITIVE: - case CKA_ALWAYS_SENSITIVE: - case CKA_NEVER_EXTRACTABLE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_MODIFIABLE: - case CKA_EXTRACTABLE: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_LABEL: - label = nsslowkey_FindKeyNicknameByPublicKey(object->obj.slot->keyDB, - &object->dbKey, object->obj.slot->password); - if (label == NULL) { - return (PK11Attribute *)&pk11_StaticOneAttr; - } - att = pk11_NewTokenAttribute(type,label,PORT_Strlen(label), PR_TRUE); - PORT_Free(label); - return att; - default: - break; - } - - key = pk11_GetPublicKey(object); - if (key == NULL) { - return NULL; - } - - switch (key->keyType) { - case NSSLOWKEYRSAKey: - return pk11_FindRSAPublicKeyAttribute(key,type); - case NSSLOWKEYDSAKey: - return pk11_FindDSAPublicKeyAttribute(key,type); - case NSSLOWKEYDHKey: - return pk11_FindDHPublicKeyAttribute(key,type); -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - return pk11_FindECPublicKeyAttribute(key,type); -#endif /* NSS_ENABLE_ECC */ - default: - break; - } - - return NULL; -} - -static PK11Attribute * -pk11_FindSecretKeyAttribute(PK11TokenObject *object, CK_ATTRIBUTE_TYPE type) -{ - NSSLOWKEYPrivateKey *key; - char *label; - unsigned char *keyString; - PK11Attribute *att; - int keyTypeLen; - CK_ULONG keyLen; - CK_KEY_TYPE keyType; - - switch (type) { - case CKA_PRIVATE: - case CKA_SENSITIVE: - case CKA_ALWAYS_SENSITIVE: - case CKA_EXTRACTABLE: - case CKA_DERIVE: - case CKA_ENCRYPT: - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_VERIFY: - case CKA_WRAP: - case CKA_UNWRAP: - case CKA_MODIFIABLE: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_NEVER_EXTRACTABLE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_LABEL: - label = nsslowkey_FindKeyNicknameByPublicKey(object->obj.slot->keyDB, - &object->dbKey, object->obj.slot->password); - if (label == NULL) { - return (PK11Attribute *)&pk11_StaticNullAttr; - } - att = pk11_NewTokenAttribute(type,label,PORT_Strlen(label), PR_TRUE); - PORT_Free(label); - return att; - case CKA_KEY_TYPE: - case CKA_VALUE_LEN: - case CKA_VALUE: - break; - default: - return NULL; - } - - key = pk11_GetPrivateKey(object); - if (key == NULL) { - return NULL; - } - switch (type) { - case CKA_KEY_TYPE: - /* handle legacy databases. In legacy databases key_type was stored - * in host order, with any leading zeros stripped off. Only key types - * under 0x1f (AES) were stored. We assume that any values which are - * either 1 byte long (big endian), or have byte[0] between 0 and - * 0x1f and bytes[1]-bytes[3] equal to '0' (little endian). All other - * values are assumed to be from the new database, which is always 4 - * bytes in host order */ - keyType=0; - keyString = key->u.rsa.coefficient.data; - keyTypeLen = key->u.rsa.coefficient.len; - /* only length of 1 or 4 are valid */ - if ((keyTypeLen != sizeof(keyType)) && (keyTypeLen != 1)) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return NULL; - } - if ((keyTypeLen == 1) || - ((keyString[0] <= 0x1f) && (keyString[1] == 0) && - (keyString[2] == 0) && (keyString[3] == 0))) { - keyType = (CK_KEY_TYPE) keyString[0] ; - } else { - keyType = *(CK_KEY_TYPE *) keyString; - keyType = PR_ntohl(keyType); - } - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType),PR_TRUE); - case CKA_VALUE: - return pk11_NewTokenAttribute(type,key->u.rsa.privateExponent.data, - key->u.rsa.privateExponent.len, PR_FALSE); - case CKA_VALUE_LEN: - keyLen=key->u.rsa.privateExponent.len; - return pk11_NewTokenAttribute(type, &keyLen, sizeof(CK_ULONG), PR_TRUE); - } - - return NULL; -} - -static PK11Attribute * -pk11_FindRSAPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, - CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_RSA; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash,key->u.rsa.modulus.data,key->u.rsa.modulus.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_MODULUS: - return pk11_NewTokenAttributeSigned(type,key->u.rsa.modulus.data, - key->u.rsa.modulus.len, PR_FALSE); - case CKA_PUBLIC_EXPONENT: - return pk11_NewTokenAttributeSigned(type,key->u.rsa.publicExponent.data, - key->u.rsa.publicExponent.len, PR_FALSE); - case CKA_PRIVATE_EXPONENT: - case CKA_PRIME_1: - case CKA_PRIME_2: - case CKA_EXPONENT_1: - case CKA_EXPONENT_2: - case CKA_COEFFICIENT: - return (PK11Attribute *) &pk11_StaticNullAttr; - default: - break; - } - return NULL; -} - -static PK11Attribute * -pk11_FindDSAPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, - CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_DSA; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dsa.publicValue.data, - key->u.dsa.publicValue.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - case CKA_DECRYPT: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_SIGN: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_VALUE: - return (PK11Attribute *) &pk11_StaticNullAttr; - case CKA_PRIME: - return pk11_NewTokenAttributeSigned(type,key->u.dsa.params.prime.data, - key->u.dsa.params.prime.len, PR_FALSE); - case CKA_SUBPRIME: - return pk11_NewTokenAttributeSigned(type, - key->u.dsa.params.subPrime.data, - key->u.dsa.params.subPrime.len, PR_FALSE); - case CKA_BASE: - return pk11_NewTokenAttributeSigned(type,key->u.dsa.params.base.data, - key->u.dsa.params.base.len, PR_FALSE); - default: - break; - } - return NULL; -} - -static PK11Attribute * -pk11_FindDHPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_DH; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dh.publicValue.data,key->u.dh.publicValue.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_VALUE: - return (PK11Attribute *) &pk11_StaticNullAttr; - case CKA_PRIME: - return pk11_NewTokenAttributeSigned(type,key->u.dh.prime.data, - key->u.dh.prime.len, PR_FALSE); - case CKA_BASE: - return pk11_NewTokenAttributeSigned(type,key->u.dh.base.data, - key->u.dh.base.len, PR_FALSE); - default: - break; - } - return NULL; -} - -#ifdef NSS_ENABLE_ECC -static PK11Attribute * -pk11_FindECPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type) -{ - unsigned char hash[SHA1_LENGTH]; - CK_KEY_TYPE keyType = CKK_EC; - - switch (type) { - case CKA_KEY_TYPE: - return pk11_NewTokenAttribute(type,&keyType,sizeof(keyType), PR_TRUE); - case CKA_ID: - SHA1_HashBuf(hash,key->u.ec.publicValue.data,key->u.ec.publicValue.len); - return pk11_NewTokenAttribute(type,hash,SHA1_LENGTH, PR_TRUE); - case CKA_DERIVE: - case CKA_SIGN: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_DECRYPT: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_VALUE: - return (PK11Attribute *) &pk11_StaticNullAttr; - case CKA_EC_PARAMS: - /* XXX Why is the last arg PR_FALSE? */ - return pk11_NewTokenAttributeSigned(type, - key->u.ec.ecParams.DEREncoding.data, - key->u.ec.ecParams.DEREncoding.len, - PR_FALSE); - default: - break; - } - return NULL; -} -#endif /* NSS_ENABLE_ECC */ - -static PK11Attribute * -pk11_FindPrivateKeyAttribute(PK11TokenObject *object, CK_ATTRIBUTE_TYPE type) -{ - NSSLOWKEYPrivateKey *key; - char *label; - PK11Attribute *att; - - switch (type) { - case CKA_PRIVATE: - case CKA_SENSITIVE: - case CKA_ALWAYS_SENSITIVE: - case CKA_EXTRACTABLE: - case CKA_MODIFIABLE: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_NEVER_EXTRACTABLE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_SUBJECT: - return (PK11Attribute *)&pk11_StaticNullAttr; - case CKA_LABEL: - label = nsslowkey_FindKeyNicknameByPublicKey(object->obj.slot->keyDB, - &object->dbKey, object->obj.slot->password); - if (label == NULL) { - return (PK11Attribute *)&pk11_StaticNullAttr; - } - att = pk11_NewTokenAttribute(type,label,PORT_Strlen(label), PR_TRUE); - PORT_Free(label); - return att; - default: - break; - } - key = pk11_GetPrivateKey(object); - if (key == NULL) { - return NULL; - } - switch (key->keyType) { - case NSSLOWKEYRSAKey: - return pk11_FindRSAPrivateKeyAttribute(key,type); - case NSSLOWKEYDSAKey: - return pk11_FindDSAPrivateKeyAttribute(key,type); - case NSSLOWKEYDHKey: - return pk11_FindDHPrivateKeyAttribute(key,type); -#ifdef NSS_ENABLE_ECC - case NSSLOWKEYECKey: - return pk11_FindECPrivateKeyAttribute(key,type); -#endif /* NSS_ENABLE_ECC */ - default: - break; - } - - return NULL; -} - -static PK11Attribute * -pk11_FindSMIMEAttribute(PK11TokenObject *object, CK_ATTRIBUTE_TYPE type) -{ - certDBEntrySMime *entry; - switch (type) { - case CKA_PRIVATE: - case CKA_MODIFIABLE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_NETSCAPE_EMAIL: - return pk11_NewTokenAttribute(type,object->dbKey.data, - object->dbKey.len-1, PR_FALSE); - case CKA_NETSCAPE_SMIME_TIMESTAMP: - case CKA_SUBJECT: - case CKA_VALUE: - break; - default: - return NULL; - } - entry = pk11_getSMime(object); - if (entry == NULL) { - return NULL; - } - switch (type) { - case CKA_NETSCAPE_SMIME_TIMESTAMP: - return pk11_NewTokenAttribute(type,entry->optionsDate.data, - entry->optionsDate.len, PR_FALSE); - case CKA_SUBJECT: - return pk11_NewTokenAttribute(type,entry->subjectName.data, - entry->subjectName.len, PR_FALSE); - case CKA_VALUE: - return pk11_NewTokenAttribute(type,entry->smimeOptions.data, - entry->smimeOptions.len, PR_FALSE); - default: - break; - } - return NULL; -} - -static PK11Attribute * -pk11_FindTrustAttribute(PK11TokenObject *object, CK_ATTRIBUTE_TYPE type) -{ - NSSLOWCERTTrust *trust; - unsigned char hash[SHA1_LENGTH]; - unsigned int trustFlags; - - switch (type) { - case CKA_PRIVATE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_MODIFIABLE: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_CERT_SHA1_HASH: - case CKA_CERT_MD5_HASH: - case CKA_TRUST_CLIENT_AUTH: - case CKA_TRUST_SERVER_AUTH: - case CKA_TRUST_EMAIL_PROTECTION: - case CKA_TRUST_CODE_SIGNING: - break; - default: - return NULL; - } - trust = pk11_getTrust(object); - if (trust == NULL) { - return NULL; - } - switch (type) { - case CKA_CERT_SHA1_HASH: - SHA1_HashBuf(hash,trust->derCert->data,trust->derCert->len); - return pk11_NewTokenAttribute(type, hash, SHA1_LENGTH, PR_TRUE); - case CKA_CERT_MD5_HASH: - MD5_HashBuf(hash,trust->derCert->data,trust->derCert->len); - return pk11_NewTokenAttribute(type, hash, MD5_LENGTH, PR_TRUE); - case CKA_TRUST_CLIENT_AUTH: - trustFlags = trust->trust->sslFlags & CERTDB_TRUSTED_CLIENT_CA ? - trust->trust->sslFlags | CERTDB_TRUSTED_CA : 0 ; - goto trust; - case CKA_TRUST_SERVER_AUTH: - trustFlags = trust->trust->sslFlags; - goto trust; - case CKA_TRUST_EMAIL_PROTECTION: - trustFlags = trust->trust->emailFlags; - goto trust; - case CKA_TRUST_CODE_SIGNING: - trustFlags = trust->trust->objectSigningFlags; -trust: - if (trustFlags & CERTDB_TRUSTED_CA ) { - return (PK11Attribute *)&pk11_StaticTrustedDelegatorAttr; - } - if (trustFlags & CERTDB_TRUSTED) { - return (PK11Attribute *)&pk11_StaticTrustedAttr; - } - if (trustFlags & CERTDB_NOT_TRUSTED) { - return (PK11Attribute *)&pk11_StaticUnTrustedAttr; - } - if (trustFlags & CERTDB_TRUSTED_UNKNOWN) { - return (PK11Attribute *)&pk11_StaticTrustUnknownAttr; - } - if (trustFlags & CERTDB_VALID_CA) { - return (PK11Attribute *)&pk11_StaticValidDelegatorAttr; - } - if (trustFlags & CERTDB_VALID_PEER) { - return (PK11Attribute *)&pk11_StaticValidPeerAttr; - } - return (PK11Attribute *)&pk11_StaticMustVerifyAttr; - default: - break; - } - -#ifdef notdef - switch (type) { - case CKA_ISSUER: - cert = pk11_getCertObject(object); - if (cert == NULL) break; - attr = pk11_NewTokenAttribute(type,cert->derIssuer.data, - cert->derIssuer.len, PR_FALSE); - - case CKA_SERIAL_NUMBER: - cert = pk11_getCertObject(object); - if (cert == NULL) break; - item = SEC_ASN1EncodeItem(NULL,NULL,cert,pk11_SerialTemplate); - if (item == NULL) break; - attr = pk11_NewTokenAttribute(type, item->data, item->len, PR_TRUE); - SECITEM_FreeItem(item,PR_TRUE); - } - if (cert) { - NSSLOWCERTDestroyCertificate(cert); - return attr; - } -#endif - return NULL; -} - -static PK11Attribute * -pk11_FindCrlAttribute(PK11TokenObject *object, CK_ATTRIBUTE_TYPE type) -{ - certDBEntryRevocation *crl; - - switch (type) { - case CKA_PRIVATE: - case CKA_MODIFIABLE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_NETSCAPE_KRL: - return (PK11Attribute *) ((object->obj.handle == PK11_TOKEN_KRL_HANDLE) - ? &pk11_StaticTrueAttr : &pk11_StaticFalseAttr); - case CKA_SUBJECT: - return pk11_NewTokenAttribute(type,object->dbKey.data, - object->dbKey.len, PR_FALSE); - case CKA_NETSCAPE_URL: - case CKA_VALUE: - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; - } - crl = pk11_getCrl(object); - if (!crl) { - return NULL; - } - switch (type) { - case CKA_NETSCAPE_URL: - if (crl->url == NULL) { - return (PK11Attribute *) &pk11_StaticNullAttr; - } - return pk11_NewTokenAttribute(type, crl->url, - PORT_Strlen(crl->url)+1, PR_TRUE); - case CKA_VALUE: - return pk11_NewTokenAttribute(type, crl->derCrl.data, - crl->derCrl.len, PR_FALSE); - default: - break; - } - return NULL; -} - -static PK11Attribute * -pk11_FindCertAttribute(PK11TokenObject *object, CK_ATTRIBUTE_TYPE type) -{ - NSSLOWCERTCertificate *cert; - NSSLOWKEYPublicKey *pubKey; - unsigned char hash[SHA1_LENGTH]; - SECItem *item; - - switch (type) { - case CKA_PRIVATE: - return (PK11Attribute *) &pk11_StaticFalseAttr; - case CKA_MODIFIABLE: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_CERTIFICATE_TYPE: - /* hardcoding X.509 into here */ - return (PK11Attribute *)&pk11_StaticX509Attr; - case CKA_VALUE: - case CKA_ID: - case CKA_LABEL: - case CKA_SUBJECT: - case CKA_ISSUER: - case CKA_SERIAL_NUMBER: - case CKA_NETSCAPE_EMAIL: - break; - default: - return NULL; - } - cert = pk11_getCert(object); - if (cert == NULL) { - return NULL; - } - switch (type) { - case CKA_VALUE: - return pk11_NewTokenAttribute(type,cert->derCert.data, - cert->derCert.len,PR_FALSE); - case CKA_ID: - if (((cert->trust->sslFlags & CERTDB_USER) == 0) && - ((cert->trust->emailFlags & CERTDB_USER) == 0) && - ((cert->trust->objectSigningFlags & CERTDB_USER) == 0)) { - return (PK11Attribute *) &pk11_StaticNullAttr; - } - pubKey = nsslowcert_ExtractPublicKey(cert); - if (pubKey == NULL) break; - item = pk11_GetPubItem(pubKey); - if (item == NULL) { - nsslowkey_DestroyPublicKey(pubKey); - break; - } - SHA1_HashBuf(hash,item->data,item->len); - /* item is imbedded in pubKey, just free the key */ - nsslowkey_DestroyPublicKey(pubKey); - return pk11_NewTokenAttribute(type, hash, SHA1_LENGTH, PR_TRUE); - case CKA_LABEL: - return cert->nickname ? pk11_NewTokenAttribute(type, cert->nickname, - PORT_Strlen(cert->nickname), PR_FALSE) : - (PK11Attribute *) &pk11_StaticNullAttr; - case CKA_SUBJECT: - return pk11_NewTokenAttribute(type,cert->derSubject.data, - cert->derSubject.len, PR_FALSE); - case CKA_ISSUER: - return pk11_NewTokenAttribute(type,cert->derIssuer.data, - cert->derIssuer.len, PR_FALSE); - case CKA_SERIAL_NUMBER: - return pk11_NewTokenAttribute(type,cert->derSN.data, - cert->derSN.len, PR_FALSE); - case CKA_NETSCAPE_EMAIL: - return (cert->emailAddr && cert->emailAddr[0]) - ? pk11_NewTokenAttribute(type, cert->emailAddr, - PORT_Strlen(cert->emailAddr), PR_FALSE) - : (PK11Attribute *) &pk11_StaticNullAttr; - default: - break; - } - return NULL; -} - -static PK11Attribute * -pk11_FindTokenAttribute(PK11TokenObject *object,CK_ATTRIBUTE_TYPE type) -{ - /* handle the common ones */ - switch (type) { - case CKA_CLASS: - return pk11_NewTokenAttribute(type,&object->obj.objclass, - sizeof(object->obj.objclass),PR_FALSE); - case CKA_TOKEN: - return (PK11Attribute *) &pk11_StaticTrueAttr; - case CKA_LABEL: - if ( (object->obj.objclass == CKO_CERTIFICATE) - || (object->obj.objclass == CKO_PRIVATE_KEY) - || (object->obj.objclass == CKO_PUBLIC_KEY) - || (object->obj.objclass == CKO_SECRET_KEY)) { - break; - } - return (PK11Attribute *) &pk11_StaticNullAttr; - default: - break; - } - switch (object->obj.objclass) { - case CKO_CERTIFICATE: - return pk11_FindCertAttribute(object,type); - case CKO_NETSCAPE_CRL: - return pk11_FindCrlAttribute(object,type); - case CKO_NETSCAPE_TRUST: - return pk11_FindTrustAttribute(object,type); - case CKO_NETSCAPE_SMIME: - return pk11_FindSMIMEAttribute(object,type); - case CKO_PUBLIC_KEY: - return pk11_FindPublicKeyAttribute(object,type); - case CKO_PRIVATE_KEY: - return pk11_FindPrivateKeyAttribute(object,type); - case CKO_SECRET_KEY: - return pk11_FindSecretKeyAttribute(object,type); - default: - break; - } - PORT_Assert(0); - return NULL; -} - -/* - * look up and attribute structure from a type and Object structure. - * The returned attribute is referenced and needs to be freed when - * it is no longer needed. - */ -PK11Attribute * -pk11_FindAttribute(PK11Object *object,CK_ATTRIBUTE_TYPE type) -{ - PK11Attribute *attribute; - PK11SessionObject *sessObject = pk11_narrowToSessionObject(object); - - if (sessObject == NULL) { - return pk11_FindTokenAttribute(pk11_narrowToTokenObject(object),type); - } - - PK11_USE_THREADS(PZ_Lock(sessObject->attributeLock);) - pk11queue_find(attribute,type,sessObject->head, sessObject->hashSize); -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - if (attribute) { - /* atomic increment would be nice here */ - PK11_USE_THREADS(PZ_Lock(attribute->refLock);) - attribute->refCount++; - PK11_USE_THREADS(PZ_Unlock(attribute->refLock);) - } -#endif - PK11_USE_THREADS(PZ_Unlock(sessObject->attributeLock);) - - return(attribute); -} - -/* - * Take a buffer and it's length and return it's true size in bits; - */ -unsigned int -pk11_GetLengthInBits(unsigned char *buf, unsigned int bufLen) -{ - unsigned int size = bufLen * 8; - int i; - /* Get the real length in bytes */ - for (i=0; i < bufLen; i++) { - unsigned char c = *buf++; - if (c != 0) { - unsigned char m; - for (m=0x80; m > 0 ; m = m >> 1) { - if ((c & m) != 0) { - break; - } - size--; - } - break; - } - size-=8; - } - return size; -} - -/* - * Constrain a big num attribute. to size and padding - * minLength means length of the object must be greater than equal to minLength - * maxLength means length of the object must be less than equal to maxLength - * minMultiple means that object length mod minMultiple must equal 0. - * all input sizes are in bits. - * if any constraint is '0' that constraint is not checked. - */ -CK_RV -pk11_ConstrainAttribute(PK11Object *object, CK_ATTRIBUTE_TYPE type, - int minLength, int maxLength, int minMultiple) -{ - PK11Attribute *attribute; - unsigned int size; - unsigned char *ptr; - int i,j; - - attribute = pk11_FindAttribute(object, type); - if (!attribute) { - return CKR_TEMPLATE_INCOMPLETE; - } - ptr = (unsigned char *) attribute->attrib.pValue; - if (ptr == NULL) { - pk11_FreeAttribute(attribute); - return CKR_ATTRIBUTE_VALUE_INVALID; - } - size = pk11_GetLengthInBits(ptr, attribute->attrib.ulValueLen); - pk11_FreeAttribute(attribute); - - if ((minLength != 0) && (size < minLength)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - if ((maxLength != 0) && (size > maxLength)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - if ((minMultiple != 0) && ((size % minMultiple) != 0)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - return CKR_OK; -} - -PRBool -pk11_hasAttributeToken(PK11TokenObject *object) -{ - return PR_FALSE; -} - -/* - * return true if object has attribute - */ -PRBool -pk11_hasAttribute(PK11Object *object,CK_ATTRIBUTE_TYPE type) -{ - PK11Attribute *attribute; - PK11SessionObject *sessObject = pk11_narrowToSessionObject(object); - - if (sessObject == NULL) { - return pk11_hasAttributeToken(pk11_narrowToTokenObject(object)); - } - - PK11_USE_THREADS(PZ_Lock(sessObject->attributeLock);) - pk11queue_find(attribute,type,sessObject->head, sessObject->hashSize); - PK11_USE_THREADS(PZ_Unlock(sessObject->attributeLock);) - - return (PRBool)(attribute != NULL); -} - -/* - * add an attribute to an object - */ -static void -pk11_AddAttribute(PK11Object *object,PK11Attribute *attribute) -{ - PK11SessionObject *sessObject = pk11_narrowToSessionObject(object); - - if (sessObject == NULL) return; - PK11_USE_THREADS(PZ_Lock(sessObject->attributeLock);) - pk11queue_add(attribute,attribute->handle, - sessObject->head, sessObject->hashSize); - PK11_USE_THREADS(PZ_Unlock(sessObject->attributeLock);) -} - -/* - * copy an unsigned attribute into a SECItem. Secitem is allocated in - * the specified arena. - */ -CK_RV -pk11_Attribute2SSecItem(PLArenaPool *arena,SECItem *item,PK11Object *object, - CK_ATTRIBUTE_TYPE type) -{ - PK11Attribute *attribute; - - item->data = NULL; - - attribute = pk11_FindAttribute(object, type); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; - - (void)SECITEM_AllocItem(arena, item, attribute->attrib.ulValueLen); - if (item->data == NULL) { - pk11_FreeAttribute(attribute); - return CKR_HOST_MEMORY; - } - PORT_Memcpy(item->data, attribute->attrib.pValue, item->len); - pk11_FreeAttribute(attribute); - return CKR_OK; -} - - -/* - * delete an attribute from an object - */ -static void -pk11_DeleteAttribute(PK11Object *object, PK11Attribute *attribute) -{ - PK11SessionObject *sessObject = pk11_narrowToSessionObject(object); - - if (sessObject == NULL) { - return ; - } - PK11_USE_THREADS(PZ_Lock(sessObject->attributeLock);) - if (pk11queue_is_queued(attribute,attribute->handle, - sessObject->head, sessObject->hashSize)) { - pk11queue_delete(attribute,attribute->handle, - sessObject->head, sessObject->hashSize); - } - PK11_USE_THREADS(PZ_Unlock(sessObject->attributeLock);) - pk11_FreeAttribute(attribute); -} - -/* - * this is only valid for CK_BBOOL type attributes. Return the state - * of that attribute. - */ -PRBool -pk11_isTrue(PK11Object *object,CK_ATTRIBUTE_TYPE type) -{ - PK11Attribute *attribute; - PRBool tok = PR_FALSE; - - attribute=pk11_FindAttribute(object,type); - if (attribute == NULL) { return PR_FALSE; } - tok = (PRBool)(*(CK_BBOOL *)attribute->attrib.pValue); - pk11_FreeAttribute(attribute); - - return tok; -} - -/* - * force an attribute to null. - * this is for sensitive keys which are stored in the database, we don't - * want to keep this info around in memory in the clear. - */ -void -pk11_nullAttribute(PK11Object *object,CK_ATTRIBUTE_TYPE type) -{ - PK11Attribute *attribute; - - attribute=pk11_FindAttribute(object,type); - if (attribute == NULL) return; - - if (attribute->attrib.pValue != NULL) { - PORT_Memset(attribute->attrib.pValue,0,attribute->attrib.ulValueLen); - if (attribute->freeData) { - PORT_Free(attribute->attrib.pValue); - } - attribute->freeData = PR_FALSE; - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; - } - pk11_FreeAttribute(attribute); -} - -static CK_RV -pk11_SetCertAttribute(PK11TokenObject *to, CK_ATTRIBUTE_TYPE type, - void *value, unsigned int len) -{ - NSSLOWCERTCertificate *cert; - char *nickname = NULL; - SECStatus rv; - - /* we can't change the EMAIL values, but let the - * upper layers feel better about the fact we tried to set these */ - if (type == CKA_NETSCAPE_EMAIL) { - return CKR_OK; - } - - if (to->obj.slot->certDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - - if ((type != CKA_LABEL) && (type != CKA_ID)) { - return CKR_ATTRIBUTE_READ_ONLY; - } - - cert = pk11_getCert(to); - if (cert == NULL) { - return CKR_OBJECT_HANDLE_INVALID; - } - - /* if the app is trying to set CKA_ID, it's probably because it just - * imported the key. Look to see if we need to set the CERTDB_USER bits. - */ - if (type == CKA_ID) { - if (((cert->trust->sslFlags & CERTDB_USER) == 0) && - ((cert->trust->emailFlags & CERTDB_USER) == 0) && - ((cert->trust->objectSigningFlags & CERTDB_USER) == 0)) { - PK11Slot *slot = to->obj.slot; - - if (slot->keyDB && nsslowkey_KeyForCertExists(slot->keyDB,cert)) { - NSSLOWCERTCertTrust trust = *cert->trust; - trust.sslFlags |= CERTDB_USER; - trust.emailFlags |= CERTDB_USER; - trust.objectSigningFlags |= CERTDB_USER; - nsslowcert_ChangeCertTrust(slot->certDB,cert,&trust); - } - } - return CKR_OK; - } - - /* must be CKA_LABEL */ - if (value != NULL) { - nickname = PORT_ZAlloc(len+1); - if (nickname == NULL) { - return CKR_HOST_MEMORY; - } - PORT_Memcpy(nickname,value,len); - nickname[len] = 0; - } - rv = nsslowcert_AddPermNickname(to->obj.slot->certDB, cert, nickname); - if (nickname) PORT_Free(nickname); - if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; - } - return CKR_OK; -} - -static CK_RV -pk11_SetPrivateKeyAttribute(PK11TokenObject *to, CK_ATTRIBUTE_TYPE type, - void *value, unsigned int len) -{ - NSSLOWKEYPrivateKey *privKey; - char *nickname = NULL; - SECStatus rv; - - /* we can't change the ID and we don't store the subject, but let the - * upper layers feel better about the fact we tried to set these */ - if ((type == CKA_ID) || (type == CKA_SUBJECT)) { - return CKR_OK; - } - - if (to->obj.slot->keyDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - if (type != CKA_LABEL) { - return CKR_ATTRIBUTE_READ_ONLY; - } - - privKey = pk11_GetPrivateKey(to); - if (privKey == NULL) { - return CKR_OBJECT_HANDLE_INVALID; - } - if (value != NULL) { - nickname = PORT_ZAlloc(len+1); - if (nickname == NULL) { - return CKR_HOST_MEMORY; - } - PORT_Memcpy(nickname,value,len); - nickname[len] = 0; - } - rv = nsslowkey_UpdateNickname(to->obj.slot->keyDB, privKey, &to->dbKey, - nickname, to->obj.slot->password); - if (nickname) PORT_Free(nickname); - if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; - } - return CKR_OK; -} - -static CK_RV -pk11_SetTrustAttribute(PK11TokenObject *to, CK_ATTRIBUTE_TYPE type, - void *value, unsigned int len) -{ - unsigned int flags; - CK_TRUST trust; - NSSLOWCERTCertificate *cert; - NSSLOWCERTCertTrust dbTrust; - SECStatus rv; - - if (to->obj.slot->certDB == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } - if (len != sizeof (CK_TRUST)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - trust = *(CK_TRUST *)value; - flags = pk11_MapTrust(trust, (PRBool) (type == CKA_TRUST_SERVER_AUTH)); - - cert = pk11_getCert(to); - if (cert == NULL) { - return CKR_OBJECT_HANDLE_INVALID; - } - dbTrust = *cert->trust; - - switch (type) { - case CKA_TRUST_EMAIL_PROTECTION: - dbTrust.emailFlags = flags | - (cert->trust->emailFlags & CERTDB_PRESERVE_TRUST_BITS); - break; - case CKA_TRUST_CODE_SIGNING: - dbTrust.objectSigningFlags = flags | - (cert->trust->objectSigningFlags & CERTDB_PRESERVE_TRUST_BITS); - break; - case CKA_TRUST_CLIENT_AUTH: - dbTrust.sslFlags = flags | (cert->trust->sslFlags & - (CERTDB_PRESERVE_TRUST_BITS|CERTDB_TRUSTED_CA)); - break; - case CKA_TRUST_SERVER_AUTH: - dbTrust.sslFlags = flags | (cert->trust->sslFlags & - (CERTDB_PRESERVE_TRUST_BITS|CERTDB_TRUSTED_CLIENT_CA)); - break; - default: - return CKR_ATTRIBUTE_READ_ONLY; - } - - rv = nsslowcert_ChangeCertTrust(to->obj.slot->certDB,cert,&dbTrust); - if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; - } - return CKR_OK; -} - -static CK_RV -pk11_forceTokenAttribute(PK11Object *object,CK_ATTRIBUTE_TYPE type, - void *value, unsigned int len) -{ - PK11Attribute *attribute; - PK11TokenObject *to = pk11_narrowToTokenObject(object); - CK_RV crv = CKR_ATTRIBUTE_READ_ONLY; - - PORT_Assert(to); - if (to == NULL) { - return CKR_DEVICE_ERROR; - } - - /* if we are just setting it to the value we already have, - * allow it to happen. Let label setting go through so - * we have the opportunity to repair any database corruption. */ - attribute=pk11_FindAttribute(object,type); - if ((type != CKA_LABEL) && (attribute->attrib.ulValueLen == len) && - PORT_Memcmp(attribute->attrib.pValue,value,len) == 0) { - pk11_FreeAttribute(attribute); - return CKR_OK; - } - - switch (object->objclass) { - case CKO_CERTIFICATE: - /* change NICKNAME, EMAIL, */ - crv = pk11_SetCertAttribute(to,type,value,len); - break; - case CKO_NETSCAPE_CRL: - /* change URL */ - break; - case CKO_NETSCAPE_TRUST: - crv = pk11_SetTrustAttribute(to,type,value,len); - break; - case CKO_PRIVATE_KEY: - case CKO_SECRET_KEY: - crv = pk11_SetPrivateKeyAttribute(to,type,value,len); - break; - } - pk11_FreeAttribute(attribute); - return crv; -} - -/* - * force an attribute to a spaecif value. - */ -CK_RV -pk11_forceAttribute(PK11Object *object,CK_ATTRIBUTE_TYPE type, void *value, - unsigned int len) -{ - PK11Attribute *attribute; - void *att_val = NULL; - PRBool freeData = PR_FALSE; - - if (pk11_isToken(object->handle)) { - return pk11_forceTokenAttribute(object,type,value,len); - } - attribute=pk11_FindAttribute(object,type); - if (attribute == NULL) return pk11_AddAttributeType(object,type,value,len); - - - if (value) { -#ifdef PKCS11_STATIC_ATTRIBUTES - if (len <= ATTR_SPACE) { - att_val = attribute->space; - } else { - att_val = PORT_Alloc(len); - freeData = PR_TRUE; - } -#else -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - att_val = PORT_Alloc(len); - freeData = PR_TRUE; -#else - att_val = PORT_ArenaAlloc(object->arena,len); -#endif /* PKCS11_REF_COUNT_ATTRIBUTES */ -#endif /* PKCS11_STATIC_ATTRIBUTES */ - if (att_val == NULL) { - return CKR_HOST_MEMORY; - } - if (attribute->attrib.pValue == att_val) { - PORT_Memset(attribute->attrib.pValue,0, - attribute->attrib.ulValueLen); - } - PORT_Memcpy(att_val,value,len); - } - if (attribute->attrib.pValue != NULL) { - if (attribute->attrib.pValue != att_val) { - PORT_Memset(attribute->attrib.pValue,0, - attribute->attrib.ulValueLen); - } - if (attribute->freeData) { - PORT_Free(attribute->attrib.pValue); - } - attribute->freeData = PR_FALSE; - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; - } - if (att_val) { - attribute->attrib.pValue = att_val; - attribute->attrib.ulValueLen = len; - attribute->freeData = freeData; - } - pk11_FreeAttribute(attribute); - return CKR_OK; -} - -/* - * return a null terminated string from attribute 'type'. This string - * is allocated and needs to be freed with PORT_Free() When complete. - */ -char * -pk11_getString(PK11Object *object,CK_ATTRIBUTE_TYPE type) -{ - PK11Attribute *attribute; - char *label = NULL; - - attribute=pk11_FindAttribute(object,type); - if (attribute == NULL) return NULL; - - if (attribute->attrib.pValue != NULL) { - label = (char *) PORT_Alloc(attribute->attrib.ulValueLen+1); - if (label == NULL) { - pk11_FreeAttribute(attribute); - return NULL; - } - - PORT_Memcpy(label,attribute->attrib.pValue, - attribute->attrib.ulValueLen); - label[attribute->attrib.ulValueLen] = 0; - } - pk11_FreeAttribute(attribute); - return label; -} - -/* - * decode when a particular attribute may be modified - * PK11_NEVER: This attribute must be set at object creation time and - * can never be modified. - * PK11_ONCOPY: This attribute may be modified only when you copy the - * object. - * PK11_SENSITIVE: The CKA_SENSITIVE attribute can only be changed from - * CK_FALSE to CK_TRUE. - * PK11_ALWAYS: This attribute can always be modified. - * Some attributes vary their modification type based on the class of the - * object. - */ -PK11ModifyType -pk11_modifyType(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass) -{ - /* if we don't know about it, user user defined, always allow modify */ - PK11ModifyType mtype = PK11_ALWAYS; - - switch(type) { - /* NEVER */ - case CKA_CLASS: - case CKA_CERTIFICATE_TYPE: - case CKA_KEY_TYPE: - case CKA_MODULUS: - case CKA_MODULUS_BITS: - case CKA_PUBLIC_EXPONENT: - case CKA_PRIVATE_EXPONENT: - case CKA_PRIME: - case CKA_SUBPRIME: - case CKA_BASE: - case CKA_PRIME_1: - case CKA_PRIME_2: - case CKA_EXPONENT_1: - case CKA_EXPONENT_2: - case CKA_COEFFICIENT: - case CKA_VALUE_LEN: - case CKA_ALWAYS_SENSITIVE: - case CKA_NEVER_EXTRACTABLE: - case CKA_NETSCAPE_DB: - mtype = PK11_NEVER; - break; - - /* ONCOPY */ - case CKA_TOKEN: - case CKA_PRIVATE: - case CKA_MODIFIABLE: - mtype = PK11_ONCOPY; - break; - - /* SENSITIVE */ - case CKA_SENSITIVE: - case CKA_EXTRACTABLE: - mtype = PK11_SENSITIVE; - break; - - /* ALWAYS */ - case CKA_LABEL: - case CKA_APPLICATION: - case CKA_ID: - case CKA_SERIAL_NUMBER: - case CKA_START_DATE: - case CKA_END_DATE: - case CKA_DERIVE: - case CKA_ENCRYPT: - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_VERIFY: - case CKA_SIGN_RECOVER: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - case CKA_UNWRAP: - mtype = PK11_ALWAYS; - break; - - /* DEPENDS ON CLASS */ - case CKA_VALUE: - mtype = (inClass == CKO_DATA) ? PK11_ALWAYS : PK11_NEVER; - break; - - case CKA_SUBJECT: - mtype = (inClass == CKO_CERTIFICATE) ? PK11_NEVER : PK11_ALWAYS; - break; - default: - break; - } - return mtype; -} - -/* decode if a particular attribute is sensitive (cannot be read - * back to the user of if the object is set to SENSITIVE) */ -PRBool -pk11_isSensitive(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass) -{ - switch(type) { - /* ALWAYS */ - case CKA_PRIVATE_EXPONENT: - case CKA_PRIME_1: - case CKA_PRIME_2: - case CKA_EXPONENT_1: - case CKA_EXPONENT_2: - case CKA_COEFFICIENT: - return PR_TRUE; - - /* DEPENDS ON CLASS */ - case CKA_VALUE: - /* PRIVATE and SECRET KEYS have SENSITIVE values */ - return (PRBool)((inClass == CKO_PRIVATE_KEY) || (inClass == CKO_SECRET_KEY)); - - default: - break; - } - return PR_FALSE; -} - -/* - * copy an attribute into a SECItem. Secitem is allocated in the specified - * arena. - */ -CK_RV -pk11_Attribute2SecItem(PLArenaPool *arena,SECItem *item,PK11Object *object, - CK_ATTRIBUTE_TYPE type) -{ - int len; - PK11Attribute *attribute; - - attribute = pk11_FindAttribute(object, type); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; - len = attribute->attrib.ulValueLen; - - if (arena) { - item->data = (unsigned char *) PORT_ArenaAlloc(arena,len); - } else { - item->data = (unsigned char *) PORT_Alloc(len); - } - if (item->data == NULL) { - pk11_FreeAttribute(attribute); - return CKR_HOST_MEMORY; - } - item->len = len; - PORT_Memcpy(item->data,attribute->attrib.pValue, len); - pk11_FreeAttribute(attribute); - return CKR_OK; -} - -CK_RV -pk11_GetULongAttribute(PK11Object *object, CK_ATTRIBUTE_TYPE type, - CK_ULONG *longData) -{ - int len; - PK11Attribute *attribute; - - attribute = pk11_FindAttribute(object, type); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; - - if (attribute->attrib.ulValueLen != sizeof(CK_ULONG)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } - - *longData = *(CK_ULONG *)attribute->attrib.pValue; - pk11_FreeAttribute(attribute); - return CKR_OK; -} - -void -pk11_DeleteAttributeType(PK11Object *object,CK_ATTRIBUTE_TYPE type) -{ - PK11Attribute *attribute; - attribute = pk11_FindAttribute(object, type); - if (attribute == NULL) return ; - pk11_DeleteAttribute(object,attribute); - pk11_FreeAttribute(attribute); -} - -CK_RV -pk11_AddAttributeType(PK11Object *object,CK_ATTRIBUTE_TYPE type,void *valPtr, - CK_ULONG length) -{ - PK11Attribute *attribute; - attribute = pk11_NewAttribute(object,type,valPtr,length); - if (attribute == NULL) { return CKR_HOST_MEMORY; } - pk11_AddAttribute(object,attribute); - return CKR_OK; -} - -/* - * ******************** Object Utilities ******************************* - */ - -static SECStatus -pk11_deleteTokenKeyByHandle(PK11Slot *slot, CK_OBJECT_HANDLE handle) -{ - SECItem *item; - PRBool rem; - - item = (SECItem *)PL_HashTableLookup(slot->tokenHashTable, (void *)handle); - rem = PL_HashTableRemove(slot->tokenHashTable,(void *)handle) ; - if (rem && item) { - SECITEM_FreeItem(item,PR_TRUE); - } - return rem ? SECSuccess : SECFailure; -} - -static SECStatus -pk11_addTokenKeyByHandle(PK11Slot *slot, CK_OBJECT_HANDLE handle, SECItem *key) -{ - PLHashEntry *entry; - SECItem *item; - - item = SECITEM_DupItem(key); - if (item == NULL) { - return SECFailure; - } - entry = PL_HashTableAdd(slot->tokenHashTable,(void *)handle,item); - if (entry == NULL) { - SECITEM_FreeItem(item,PR_TRUE); - return SECFailure; - } - return SECSuccess; -} - -static SECItem * -pk11_lookupTokenKeyByHandle(PK11Slot *slot, CK_OBJECT_HANDLE handle) -{ - return (SECItem *)PL_HashTableLookup(slot->tokenHashTable, (void *)handle); -} - -/* - * use the refLock. This operations should be very rare, so the added - * contention on the ref lock should be lower than the overhead of adding - * a new lock. We use separate functions for this just in case I'm wrong. - */ -static void -pk11_tokenKeyLock(PK11Slot *slot) { - PK11_USE_THREADS(PZ_Lock(slot->objectLock);) -} - -static void -pk11_tokenKeyUnlock(PK11Slot *slot) { - PK11_USE_THREADS(PZ_Unlock(slot->objectLock);) -} - - -/* allocation hooks that allow us to recycle old object structures */ -static PK11ObjectFreeList sessionObjectList = { NULL, NULL, 0 }; -static PK11ObjectFreeList tokenObjectList = { NULL, NULL, 0 }; - -PK11Object * -pk11_GetObjectFromList(PRBool *hasLocks, PRBool optimizeSpace, - PK11ObjectFreeList *list, unsigned int hashSize, PRBool isSessionObject) -{ - PK11Object *object; - int size = 0; - - if (!optimizeSpace) { - if (list->lock == NULL) { - list->lock = PZ_NewLock(nssILockObject); - } - - PK11_USE_THREADS(PZ_Lock(list->lock)); - object = list->head; - if (object) { - list->head = object->next; - list->count--; - } - PK11_USE_THREADS(PZ_Unlock(list->lock)); - if (object) { - object->next = object->prev = NULL; - *hasLocks = PR_TRUE; - return object; - } - } - size = isSessionObject ? sizeof(PK11SessionObject) - + hashSize *sizeof(PK11Attribute *) : sizeof(PK11TokenObject); - - object = (PK11Object*)PORT_ZAlloc(size); - if (isSessionObject) { - ((PK11SessionObject *)object)->hashSize = hashSize; - } - *hasLocks = PR_FALSE; - return object; -} - -static void -pk11_PutObjectToList(PK11Object *object, PK11ObjectFreeList *list, - PRBool isSessionObject) { - - /* the code below is equivalent to : - * optimizeSpace = isSessionObject ? object->optimizeSpace : PR_FALSE; - * just faster. - */ - PRBool optimizeSpace = isSessionObject && - ((PK11SessionObject *)object)->optimizeSpace; - if (!optimizeSpace && (list->count < MAX_OBJECT_LIST_SIZE)) { - if (list->lock == NULL) { - list->lock = PZ_NewLock(nssILockObject); - } - PK11_USE_THREADS(PZ_Lock(list->lock)); - object->next = list->head; - list->head = object; - list->count++; - PK11_USE_THREADS(PZ_Unlock(list->lock)); - return; - } - if (isSessionObject) { - PK11SessionObject *so = (PK11SessionObject *)object; - PK11_USE_THREADS(PZ_DestroyLock(so->attributeLock);) - so->attributeLock = NULL; - } - PK11_USE_THREADS(PZ_DestroyLock(object->refLock);) - object->refLock = NULL; - PORT_Free(object); -} - -static PK11Object * -pk11_freeObjectData(PK11Object *object) { - PK11Object *next = object->next; - - PORT_Free(object); - return next; -} - -static void -pk11_CleanupFreeList(PK11ObjectFreeList *list, PRBool isSessionList) -{ - PK11Object *object; - - if (!list->lock) { - return; - } - PK11_USE_THREADS(PZ_Lock(list->lock)); - for (object= list->head; object != NULL; - object = pk11_freeObjectData(object)) { -#ifdef PKCS11_USE_THREADS - PZ_DestroyLock(object->refLock); - if (isSessionList) { - PZ_DestroyLock(((PK11SessionObject *)object)->attributeLock); - } -#endif - } - list->count = 0; - list->head = NULL; - PK11_USE_THREADS(PZ_Unlock(list->lock)); - PK11_USE_THREADS(PZ_DestroyLock(list->lock)); - list->lock = NULL; -} - -void -pk11_CleanupFreeLists(void) -{ - pk11_CleanupFreeList(&sessionObjectList, PR_TRUE); - pk11_CleanupFreeList(&tokenObjectList, PR_FALSE); -} - - -/* - * Create a new object - */ -PK11Object * -pk11_NewObject(PK11Slot *slot) -{ - PK11Object *object; - PK11SessionObject *sessObject; - PRBool hasLocks = PR_FALSE; - unsigned int i; - unsigned int hashSize = 0; - - hashSize = (slot->optimizeSpace) ? SPACE_ATTRIBUTE_HASH_SIZE : - TIME_ATTRIBUTE_HASH_SIZE; - -#ifdef PKCS11_STATIC_ATTRIBUTES - object = pk11_GetObjectFromList(&hasLocks, slot->optimizeSpace, - &sessionObjectList, hashSize, PR_TRUE); - if (object == NULL) { - return NULL; - } - sessObject = (PK11SessionObject *)object; - sessObject->nextAttr = 0; - - for (i=0; i < MAX_OBJS_ATTRS; i++) { - sessObject->attrList[i].attrib.pValue = NULL; - sessObject->attrList[i].freeData = PR_FALSE; - } -#else - PRArenaPool *arena; - - arena = PORT_NewArena(2048); - if (arena == NULL) return NULL; - - object = (PK11Object*)PORT_ArenaAlloc(arena,sizeof(PK11SessionObject) - +hashSize * sizeof(PK11Attribute *)); - if (object == NULL) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; - } - object->arena = arena; - - sessObject = (PK11SessionObject *)object; - sessObject->hashSize = hashSize; -#endif - sessObject->optimizeSpace = slot->optimizeSpace; - - object->handle = 0; - object->next = object->prev = NULL; - object->slot = slot; - - object->refCount = 1; - sessObject->sessionList.next = NULL; - sessObject->sessionList.prev = NULL; - sessObject->sessionList.parent = object; - sessObject->session = NULL; - sessObject->wasDerived = PR_FALSE; -#ifdef PKCS11_USE_THREADS - if (!hasLocks) object->refLock = PZ_NewLock(nssILockRefLock); - if (object->refLock == NULL) { -#ifdef PKCS11_STATIC_ATTRIBUTES - PORT_Free(object); -#else - PORT_FreeArena(arena,PR_FALSE); -#endif - return NULL; - } - if (!hasLocks) sessObject->attributeLock = PZ_NewLock(nssILockAttribute); - if (sessObject->attributeLock == NULL) { - PK11_USE_THREADS(PZ_DestroyLock(object->refLock);) -#ifdef PKCS11_STATIC_ATTRIBUTES - PORT_Free(object); -#else - PORT_FreeArena(arena,PR_FALSE); -#endif - return NULL; - } -#else - sessObject->attributeLock = NULL; - object->refLock = NULL; -#endif - for (i=0; i < sessObject->hashSize; i++) { - sessObject->head[i] = NULL; - } - object->objectInfo = NULL; - object->infoFree = NULL; - return object; -} - -static CK_RV -pk11_DestroySessionObjectData(PK11SessionObject *so) -{ - int i; - -#ifdef PKCS11_STATIC_ATTRIBUTES - for (i=0; i < MAX_OBJS_ATTRS; i++) { - unsigned char *value = so->attrList[i].attrib.pValue; - if (value) { - PORT_Memset(value,0,so->attrList[i].attrib.ulValueLen); - if (so->attrList[i].freeData) { - PORT_Free(value); - } - so->attrList[i].attrib.pValue = NULL; - so->attrList[i].freeData = PR_FALSE; - } - } -#endif - -#ifdef PKCS11_REF_COUNT_ATTRIBUTES - /* clean out the attributes */ - /* since no one is referencing us, it's safe to walk the chain - * without a lock */ - for (i=0; i < so->hashSize; i++) { - PK11Attribute *ap,*next; - for (ap = so->head[i]; ap != NULL; ap = next) { - next = ap->next; - /* paranoia */ - ap->next = ap->prev = NULL; - pk11_FreeAttribute(ap); - } - so->head[i] = NULL; - } -#endif -/* PK11_USE_THREADS(PZ_DestroyLock(so->attributeLock));*/ - return CKR_OK; -} - -/* - * free all the data associated with an object. Object reference count must - * be 'zero'. - */ -static CK_RV -pk11_DestroyObject(PK11Object *object) -{ - CK_RV crv = CKR_OK; - PK11SessionObject *so = pk11_narrowToSessionObject(object); - PK11TokenObject *to = pk11_narrowToTokenObject(object); - - PORT_Assert(object->refCount == 0); - - /* delete the database value */ - if (to) { - if (to->dbKey.data) { - PORT_Free(to->dbKey.data); - to->dbKey.data = NULL; - } - } - if (so) { - pk11_DestroySessionObjectData(so); - } - if (object->objectInfo) { - (*object->infoFree)(object->objectInfo); - object->objectInfo = NULL; - object->infoFree = NULL; - } -#ifdef PKCS11_STATIC_ATTRIBUTES - if (so) { - pk11_PutObjectToList(object,&sessionObjectList,PR_TRUE); - } else { - pk11_PutObjectToList(object,&tokenObjectList,PR_FALSE); - } -#else - if (object->refLock) { - PK11_USE_THREADS(PZ_DestroyLock(object->refLock);) - } - arena = object->arena; - PORT_FreeArena(arena,PR_FALSE); -#endif - return crv; -} - -void -pk11_ReferenceObject(PK11Object *object) -{ - PK11_USE_THREADS(PZ_Lock(object->refLock);) - object->refCount++; - PK11_USE_THREADS(PZ_Unlock(object->refLock);) -} - -static PK11Object * -pk11_ObjectFromHandleOnSlot(CK_OBJECT_HANDLE handle, PK11Slot *slot) -{ - PK11Object *object; - PRUint32 index = pk11_hash(handle, slot->tokObjHashSize); - - if (pk11_isToken(handle)) { - return pk11_NewTokenObject(slot, NULL, handle); - } - - PK11_USE_THREADS(PZ_Lock(slot->objectLock);) - pk11queue_find2(object, handle, index, slot->tokObjects); - if (object) { - pk11_ReferenceObject(object); - } - PK11_USE_THREADS(PZ_Unlock(slot->objectLock);) - - return(object); -} -/* - * look up and object structure from a handle. OBJECT_Handles only make - * sense in terms of a given session. make a reference to that object - * structure returned. - */ -PK11Object * -pk11_ObjectFromHandle(CK_OBJECT_HANDLE handle, PK11Session *session) -{ - PK11Slot *slot = pk11_SlotFromSession(session); - - return pk11_ObjectFromHandleOnSlot(handle,slot); -} - - -/* - * release a reference to an object handle - */ -PK11FreeStatus -pk11_FreeObject(PK11Object *object) -{ - PRBool destroy = PR_FALSE; - CK_RV crv; - - PK11_USE_THREADS(PZ_Lock(object->refLock);) - if (object->refCount == 1) destroy = PR_TRUE; - object->refCount--; - PK11_USE_THREADS(PZ_Unlock(object->refLock);) - - if (destroy) { - crv = pk11_DestroyObject(object); - if (crv != CKR_OK) { - return PK11_DestroyFailure; - } - return PK11_Destroyed; - } - return PK11_Busy; -} - -/* - * add an object to a slot and session queue. These two functions - * adopt the object. - */ -void -pk11_AddSlotObject(PK11Slot *slot, PK11Object *object) -{ - PRUint32 index = pk11_hash(object->handle, slot->tokObjHashSize); - pk11queue_init_element(object); - PK11_USE_THREADS(PZ_Lock(slot->objectLock);) - pk11queue_add2(object, object->handle, index, slot->tokObjects); - PK11_USE_THREADS(PZ_Unlock(slot->objectLock);) -} - -void -pk11_AddObject(PK11Session *session, PK11Object *object) -{ - PK11Slot *slot = pk11_SlotFromSession(session); - PK11SessionObject *so = pk11_narrowToSessionObject(object); - - if (so) { - PK11_USE_THREADS(PZ_Lock(session->objectLock);) - pk11queue_add(&so->sessionList,0,session->objects,0); - so->session = session; - PK11_USE_THREADS(PZ_Unlock(session->objectLock);) - } - pk11_AddSlotObject(slot,object); - pk11_ReferenceObject(object); -} - -/* - * add an object to a slot andsession queue - */ -CK_RV -pk11_DeleteObject(PK11Session *session, PK11Object *object) -{ - PK11Slot *slot = pk11_SlotFromSession(session); - PK11SessionObject *so = pk11_narrowToSessionObject(object); - PK11TokenObject *to = pk11_narrowToTokenObject(object); - CK_RV crv = CKR_OK; - SECStatus rv; - NSSLOWCERTCertificate *cert; - NSSLOWCERTCertTrust tmptrust; - PRBool isKrl; - PRUint32 index = pk11_hash(object->handle, slot->tokObjHashSize); - - /* Handle Token case */ - if (so && so->session) { - PK11Session *session = so->session; - PK11_USE_THREADS(PZ_Lock(session->objectLock);) - pk11queue_delete(&so->sessionList,0,session->objects,0); - PK11_USE_THREADS(PZ_Unlock(session->objectLock);) - PK11_USE_THREADS(PZ_Lock(slot->objectLock);) - pk11queue_delete2(object, object->handle, index, slot->tokObjects); - PK11_USE_THREADS(PZ_Unlock(slot->objectLock);) - pk11queue_clear_deleted_element(object); - pk11_FreeObject(object); /* reduce it's reference count */ - } else { - PORT_Assert(to); - /* remove the objects from the real data base */ - switch (object->handle & PK11_TOKEN_TYPE_MASK) { - case PK11_TOKEN_TYPE_PRIV: - case PK11_TOKEN_TYPE_KEY: - /* KEYID is the public KEY for DSA and DH, and the MODULUS for - * RSA */ - PORT_Assert(slot->keyDB); - rv = nsslowkey_DeleteKey(slot->keyDB, &to->dbKey); - if (rv != SECSuccess) crv= CKR_DEVICE_ERROR; - break; - case PK11_TOKEN_TYPE_PUB: - break; /* public keys only exist at the behest of the priv key */ - case PK11_TOKEN_TYPE_CERT: - cert = nsslowcert_FindCertByKey(slot->certDB,&to->dbKey); - if (cert == NULL) { - crv = CKR_DEVICE_ERROR; - break; - } - rv = nsslowcert_DeletePermCertificate(cert); - if (rv != SECSuccess) crv = CKR_DEVICE_ERROR; - nsslowcert_DestroyCertificate(cert); - break; - case PK11_TOKEN_TYPE_CRL: - isKrl = (PRBool) (object->handle == PK11_TOKEN_KRL_HANDLE); - rv = nsslowcert_DeletePermCRL(slot->certDB,&to->dbKey,isKrl); - if (rv == SECFailure) crv = CKR_DEVICE_ERROR; - break; - case PK11_TOKEN_TYPE_TRUST: - cert = nsslowcert_FindCertByKey(slot->certDB,&to->dbKey); - if (cert == NULL) { - crv = CKR_DEVICE_ERROR; - break; - } - tmptrust = *cert->trust; - tmptrust.sslFlags &= CERTDB_PRESERVE_TRUST_BITS; - tmptrust.emailFlags &= CERTDB_PRESERVE_TRUST_BITS; - tmptrust.objectSigningFlags &= CERTDB_PRESERVE_TRUST_BITS; - tmptrust.sslFlags |= CERTDB_TRUSTED_UNKNOWN; - tmptrust.emailFlags |= CERTDB_TRUSTED_UNKNOWN; - tmptrust.objectSigningFlags |= CERTDB_TRUSTED_UNKNOWN; - rv = nsslowcert_ChangeCertTrust(slot->certDB,cert,&tmptrust); - if (rv != SECSuccess) crv = CKR_DEVICE_ERROR; - nsslowcert_DestroyCertificate(cert); - break; - default: - break; - } - pk11_tokenKeyLock(object->slot); - pk11_deleteTokenKeyByHandle(object->slot,object->handle); - pk11_tokenKeyUnlock(object->slot); - } - return crv; -} - -/* - * copy the attributes from one object to another. Don't overwrite existing - * attributes. NOTE: This is a pretty expensive operation since it - * grabs the attribute locks for the src object for a *long* time. - */ -CK_RV -pk11_CopyObject(PK11Object *destObject,PK11Object *srcObject) -{ - PK11Attribute *attribute; - PK11SessionObject *src_so = pk11_narrowToSessionObject(srcObject); - unsigned int i; - - if (src_so == NULL) { - return CKR_DEVICE_ERROR; /* can't copy token objects yet */ - } - - PK11_USE_THREADS(PZ_Lock(src_so->attributeLock);) - for(i=0; i < src_so->hashSize; i++) { - attribute = src_so->head[i]; - do { - if (attribute) { - if (!pk11_hasAttribute(destObject,attribute->handle)) { - /* we need to copy the attribute since each attribute - * only has one set of link list pointers */ - PK11Attribute *newAttribute = pk11_NewAttribute( - destObject,pk11_attr_expand(&attribute->attrib)); - if (newAttribute == NULL) { - PK11_USE_THREADS(PZ_Unlock(src_so->attributeLock);) - return CKR_HOST_MEMORY; - } - pk11_AddAttribute(destObject,newAttribute); - } - attribute=attribute->next; - } - } while (attribute != NULL); - } - PK11_USE_THREADS(PZ_Unlock(src_so->attributeLock);) - return CKR_OK; -} - -/* - * ******************** Search Utilities ******************************* - */ - -/* add an object to a search list */ -CK_RV -AddToList(PK11ObjectListElement **list,PK11Object *object) -{ - PK11ObjectListElement *newElem = - (PK11ObjectListElement *)PORT_Alloc(sizeof(PK11ObjectListElement)); - - if (newElem == NULL) return CKR_HOST_MEMORY; - - newElem->next = *list; - newElem->object = object; - pk11_ReferenceObject(object); - - *list = newElem; - return CKR_OK; -} - - -/* return true if the object matches the template */ -PRBool -pk11_objectMatch(PK11Object *object,CK_ATTRIBUTE_PTR theTemplate,int count) -{ - int i; - - for (i=0; i < count; i++) { - PK11Attribute *attribute = pk11_FindAttribute(object,theTemplate[i].type); - if (attribute == NULL) { - return PR_FALSE; - } - if (attribute->attrib.ulValueLen == theTemplate[i].ulValueLen) { - if (PORT_Memcmp(attribute->attrib.pValue,theTemplate[i].pValue, - theTemplate[i].ulValueLen) == 0) { - pk11_FreeAttribute(attribute); - continue; - } - } - pk11_FreeAttribute(attribute); - return PR_FALSE; - } - return PR_TRUE; -} - -/* search through all the objects in the queue and return the template matches - * in the object list. - */ -CK_RV -pk11_searchObjectList(PK11SearchResults *search,PK11Object **head, - unsigned int size, PZLock *lock, CK_ATTRIBUTE_PTR theTemplate, - int count, PRBool isLoggedIn) -{ - unsigned int i; - PK11Object *object; - CK_RV crv = CKR_OK; - - for(i=0; i < size; i++) { - /* We need to hold the lock to copy a consistant version of - * the linked list. */ - PK11_USE_THREADS(PZ_Lock(lock);) - for (object = head[i]; object != NULL; object= object->next) { - if (pk11_objectMatch(object,theTemplate,count)) { - /* don't return objects that aren't yet visible */ - if ((!isLoggedIn) && pk11_isTrue(object,CKA_PRIVATE)) continue; - pk11_addHandle(search,object->handle); - } - } - PK11_USE_THREADS(PZ_Unlock(lock);) - } - return crv; -} - -/* - * free a single list element. Return the Next object in the list. - */ -PK11ObjectListElement * -pk11_FreeObjectListElement(PK11ObjectListElement *objectList) -{ - PK11ObjectListElement *ol = objectList->next; - - pk11_FreeObject(objectList->object); - PORT_Free(objectList); - return ol; -} - -/* free an entire object list */ -void -pk11_FreeObjectList(PK11ObjectListElement *objectList) -{ - PK11ObjectListElement *ol; - - for (ol= objectList; ol != NULL; ol = pk11_FreeObjectListElement(ol)) {} -} - -/* - * free a search structure - */ -void -pk11_FreeSearch(PK11SearchResults *search) -{ - if (search->handles) { - PORT_Free(search->handles); - } - PORT_Free(search); -} - -/* - * ******************** Session Utilities ******************************* - */ - -/* update the sessions state based in it's flags and wether or not it's - * logged in */ -void -pk11_update_state(PK11Slot *slot,PK11Session *session) -{ - if (slot->isLoggedIn) { - if (slot->ssoLoggedIn) { - session->info.state = CKS_RW_SO_FUNCTIONS; - } else if (session->info.flags & CKF_RW_SESSION) { - session->info.state = CKS_RW_USER_FUNCTIONS; - } else { - session->info.state = CKS_RO_USER_FUNCTIONS; - } - } else { - if (session->info.flags & CKF_RW_SESSION) { - session->info.state = CKS_RW_PUBLIC_SESSION; - } else { - session->info.state = CKS_RO_PUBLIC_SESSION; - } - } -} - -/* update the state of all the sessions on a slot */ -void -pk11_update_all_states(PK11Slot *slot) -{ - unsigned int i; - PK11Session *session; - - for (i=0; i < slot->sessHashSize; i++) { - PK11_USE_THREADS(PZ_Lock(PK11_SESSION_LOCK(slot,i));) - for (session = slot->head[i]; session; session = session->next) { - pk11_update_state(slot,session); - } - PK11_USE_THREADS(PZ_Unlock(PK11_SESSION_LOCK(slot,i));) - } -} - -/* - * context are cipher and digest contexts that are associated with a session - */ -void -pk11_FreeContext(PK11SessionContext *context) -{ - if (context->cipherInfo) { - (*context->destroy)(context->cipherInfo,PR_TRUE); - } - if (context->hashInfo) { - (*context->hashdestroy)(context->hashInfo,PR_TRUE); - } - if (context->key) { - pk11_FreeObject(context->key); - context->key = NULL; - } - PORT_Free(context); -} - -/* - * create a new nession. NOTE: The session handle is not set, and the - * session is not added to the slot's session queue. - */ -PK11Session * -pk11_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, CK_VOID_PTR pApplication, - CK_FLAGS flags) -{ - PK11Session *session; - PK11Slot *slot = pk11_SlotFromID(slotID); - - if (slot == NULL) return NULL; - - session = (PK11Session*)PORT_Alloc(sizeof(PK11Session)); - if (session == NULL) return NULL; - - session->next = session->prev = NULL; - session->refCount = 1; - session->enc_context = NULL; - session->hash_context = NULL; - session->sign_context = NULL; - session->search = NULL; - session->objectIDCount = 1; -#ifdef PKCS11_USE_THREADS - session->objectLock = PZ_NewLock(nssILockObject); - if (session->objectLock == NULL) { - PORT_Free(session); - return NULL; - } -#else - session->objectLock = NULL; -#endif - session->objects[0] = NULL; - - session->slot = slot; - session->notify = notify; - session->appData = pApplication; - session->info.flags = flags; - session->info.slotID = slotID; - session->info.ulDeviceError = 0; - pk11_update_state(slot,session); - return session; -} - - -/* free all the data associated with a session. */ -static void -pk11_DestroySession(PK11Session *session) -{ - PK11ObjectList *op,*next; - PORT_Assert(session->refCount == 0); - - /* clean out the attributes */ - /* since no one is referencing us, it's safe to walk the chain - * without a lock */ - for (op = session->objects[0]; op != NULL; op = next) { - next = op->next; - /* paranoia */ - op->next = op->prev = NULL; - pk11_DeleteObject(session,op->parent); - } - PK11_USE_THREADS(PZ_DestroyLock(session->objectLock);) - if (session->enc_context) { - pk11_FreeContext(session->enc_context); - } - if (session->hash_context) { - pk11_FreeContext(session->hash_context); - } - if (session->sign_context) { - pk11_FreeContext(session->sign_context); - } - if (session->search) { - pk11_FreeSearch(session->search); - } - PORT_Free(session); -} - - -/* - * look up a session structure from a session handle - * generate a reference to it. - */ -PK11Session * -pk11_SessionFromHandle(CK_SESSION_HANDLE handle) -{ - PK11Slot *slot = pk11_SlotFromSessionHandle(handle); - PK11Session *session; - - PK11_USE_THREADS(PZ_Lock(PK11_SESSION_LOCK(slot,handle));) - pk11queue_find(session,handle,slot->head,slot->sessHashSize); - if (session) session->refCount++; - PK11_USE_THREADS(PZ_Unlock(PK11_SESSION_LOCK(slot,handle));) - - return (session); -} - -/* - * release a reference to a session handle - */ -void -pk11_FreeSession(PK11Session *session) -{ - PRBool destroy = PR_FALSE; - PK11_USE_THREADS(PK11Slot *slot = pk11_SlotFromSession(session);) - - PK11_USE_THREADS(PZ_Lock(PK11_SESSION_LOCK(slot,session->handle));) - if (session->refCount == 1) destroy = PR_TRUE; - session->refCount--; - PK11_USE_THREADS(PZ_Unlock(PK11_SESSION_LOCK(slot,session->handle));) - - if (destroy) pk11_DestroySession(session); -} -/* - * handle Token Object stuff - */ -static void -pk11_XORHash(unsigned char *key, unsigned char *dbkey, int len) -{ - int i; - - PORT_Memset(key, 0, 4); - - for (i=0; i < len-4; i += 4) { - key[0] ^= dbkey[i]; - key[1] ^= dbkey[i+1]; - key[2] ^= dbkey[i+2]; - key[3] ^= dbkey[i+3]; - } -} - -/* Make a token handle for an object and record it so we can find it again */ -CK_OBJECT_HANDLE -pk11_mkHandle(PK11Slot *slot, SECItem *dbKey, CK_OBJECT_HANDLE class) -{ - unsigned char hashBuf[4]; - CK_OBJECT_HANDLE handle; - SECItem *key; - - handle = class; - /* there is only one KRL, use a fixed handle for it */ - if (handle != PK11_TOKEN_KRL_HANDLE) { - pk11_XORHash(hashBuf,dbKey->data,dbKey->len); - handle = (hashBuf[0] << 24) | (hashBuf[1] << 16) | - (hashBuf[2] << 8) | hashBuf[3]; - handle = PK11_TOKEN_MAGIC | class | - (handle & ~(PK11_TOKEN_TYPE_MASK|PK11_TOKEN_MASK)); - /* we have a CRL who's handle has randomly matched the reserved KRL - * handle, increment it */ - if (handle == PK11_TOKEN_KRL_HANDLE) { - handle++; - } - } - - pk11_tokenKeyLock(slot); - while ((key = pk11_lookupTokenKeyByHandle(slot,handle)) != NULL) { - if (SECITEM_ItemsAreEqual(key,dbKey)) { - pk11_tokenKeyUnlock(slot); - return handle; - } - handle++; - } - pk11_addTokenKeyByHandle(slot,handle,dbKey); - pk11_tokenKeyUnlock(slot); - return handle; -} - -PRBool -pk11_poisonHandle(PK11Slot *slot, SECItem *dbKey, CK_OBJECT_HANDLE class) -{ - unsigned char hashBuf[4]; - CK_OBJECT_HANDLE handle; - SECItem *key; - - handle = class; - /* there is only one KRL, use a fixed handle for it */ - if (handle != PK11_TOKEN_KRL_HANDLE) { - pk11_XORHash(hashBuf,dbKey->data,dbKey->len); - handle = (hashBuf[0] << 24) | (hashBuf[1] << 16) | - (hashBuf[2] << 8) | hashBuf[3]; - handle = PK11_TOKEN_MAGIC | class | - (handle & ~(PK11_TOKEN_TYPE_MASK|PK11_TOKEN_MASK)); - /* we have a CRL who's handle has randomly matched the reserved KRL - * handle, increment it */ - if (handle == PK11_TOKEN_KRL_HANDLE) { - handle++; - } - } - pk11_tokenKeyLock(slot); - while ((key = pk11_lookupTokenKeyByHandle(slot,handle)) != NULL) { - if (SECITEM_ItemsAreEqual(key,dbKey)) { - key->data[0] ^= 0x80; - pk11_tokenKeyUnlock(slot); - return PR_TRUE; - } - handle++; - } - pk11_tokenKeyUnlock(slot); - return PR_FALSE; -} - -void -pk11_addHandle(PK11SearchResults *search, CK_OBJECT_HANDLE handle) -{ - if (search->handles == NULL) { - return; - } - if (search->size >= search->array_size) { - search->array_size += NSC_SEARCH_BLOCK_SIZE; - search->handles = (CK_OBJECT_HANDLE *) PORT_Realloc(search->handles, - sizeof(CK_OBJECT_HANDLE)* search->array_size); - if (search->handles == NULL) { - return; - } - } - search->handles[search->size] = handle; - search->size++; -} - -static const CK_OBJECT_HANDLE pk11_classArray[] = { - 0, CKO_PRIVATE_KEY, CKO_PUBLIC_KEY, CKO_SECRET_KEY, - CKO_NETSCAPE_TRUST, CKO_NETSCAPE_CRL, CKO_NETSCAPE_SMIME, - CKO_CERTIFICATE }; - -#define handleToClass(handle) \ - pk11_classArray[((handle & PK11_TOKEN_TYPE_MASK))>>28] - -PK11Object * -pk11_NewTokenObject(PK11Slot *slot, SECItem *dbKey, CK_OBJECT_HANDLE handle) -{ - PK11Object *object = NULL; - PK11TokenObject *tokObject = NULL; - PRBool hasLocks = PR_FALSE; - SECStatus rv; - -#ifdef PKCS11_STATIC_ATTRIBUTES - object = pk11_GetObjectFromList(&hasLocks, PR_FALSE, &tokenObjectList, 0, - PR_FALSE); - if (object == NULL) { - return NULL; - } -#else - PRArenaPool *arena; - - arena = PORT_NewArena(2048); - if (arena == NULL) return NULL; - - object = (PK11Object*)PORT_ArenaZAlloc(arena,sizeof(PK11TokenObject)); - if (object == NULL) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; - } - object->arena = arena; -#endif - tokObject = (PK11TokenObject *) object; - - object->objclass = handleToClass(handle); - object->handle = handle; - object->slot = slot; - object->objectInfo = NULL; - object->infoFree = NULL; - if (dbKey == NULL) { - pk11_tokenKeyLock(slot); - dbKey = pk11_lookupTokenKeyByHandle(slot,handle); - if (dbKey == NULL) { - pk11_tokenKeyUnlock(slot); - goto loser; - } - rv = SECITEM_CopyItem(NULL,&tokObject->dbKey,dbKey); - pk11_tokenKeyUnlock(slot); - } else { - rv = SECITEM_CopyItem(NULL,&tokObject->dbKey,dbKey); - } - if (rv != SECSuccess) { - goto loser; - } -#ifdef PKCS11_USE_THREADS - if (!hasLocks) { - object->refLock = PZ_NewLock(nssILockRefLock); - } - if (object->refLock == NULL) { - goto loser; - } -#endif - object->refCount = 1; - - return object; -loser: - if (object) { - (void) pk11_DestroyObject(object); - } - return NULL; - -} - -PRBool -pk11_tokenMatch(PK11Slot *slot, SECItem *dbKey, CK_OBJECT_HANDLE class, - CK_ATTRIBUTE_PTR theTemplate,int count) -{ - PK11Object *object; - PRBool ret; - - object = pk11_NewTokenObject(slot,dbKey,PK11_TOKEN_MASK|class); - if (object == NULL) { - return PR_FALSE; - } - - ret = pk11_objectMatch(object,theTemplate,count); - pk11_FreeObject(object); - return ret; -} - -PK11TokenObject * -pk11_convertSessionToToken(PK11Object *obj) -{ - SECItem *key; - PK11SessionObject *so = (PK11SessionObject *)obj; - PK11TokenObject *to = pk11_narrowToTokenObject(obj); - SECStatus rv; - - pk11_DestroySessionObjectData(so); - PK11_USE_THREADS(PZ_DestroyLock(so->attributeLock)); - if (to == NULL) { - return NULL; - } - pk11_tokenKeyLock(so->obj.slot); - key = pk11_lookupTokenKeyByHandle(so->obj.slot,so->obj.handle); - if (key == NULL) { - pk11_tokenKeyUnlock(so->obj.slot); - return NULL; - } - rv = SECITEM_CopyItem(NULL,&to->dbKey,key); - pk11_tokenKeyUnlock(so->obj.slot); - if (rv == SECFailure) { - return NULL; - } - - return to; - -} - -PK11SessionObject * -pk11_narrowToSessionObject(PK11Object *obj) -{ - return !pk11_isToken(obj->handle) ? (PK11SessionObject *)obj : NULL; -} - -PK11TokenObject * -pk11_narrowToTokenObject(PK11Object *obj) -{ - return pk11_isToken(obj->handle) ? (PK11TokenObject *)obj : NULL; -} - diff --git a/security/nss/lib/softoken/pkcs11u.h b/security/nss/lib/softoken/pkcs11u.h deleted file mode 100644 index 777eda4d4..000000000 --- a/security/nss/lib/softoken/pkcs11u.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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. - */ -/* - * Copyright (C) 1994-1999 RSA Security Inc. Licence to copy this document - * is granted provided that it is identified as "RSA Security Inc. Public-Key - * Cryptography Standards (PKCS)" in all material mentioning or referencing - * this document. - */ -/* - * reset any packing set by pkcs11p.h - */ - -#if defined (_WIN32) -#ifdef _MSC_VER -#pragma warning(disable:4103) -#endif -#pragma pack(pop, cryptoki) -#endif - diff --git a/security/nss/lib/softoken/rawhash.c b/security/nss/lib/softoken/rawhash.c deleted file mode 100644 index b32d3f31a..000000000 --- a/security/nss/lib/softoken/rawhash.c +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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. - */ - -#include "nspr.h" -#include "sechash.h" -#include "blapi.h" /* below the line */ - - -static void * -null_hash_new_context(void) -{ - return NULL; -} - -static void * -null_hash_clone_context(void *v) -{ - PORT_Assert(v == NULL); - return NULL; -} - -static void -null_hash_begin(void *v) -{ -} - -static void -null_hash_update(void *v, const unsigned char *input, unsigned int length) -{ -} - -static void -null_hash_end(void *v, unsigned char *output, unsigned int *outLen, - unsigned int maxOut) -{ - *outLen = 0; -} - -static void -null_hash_destroy_context(void *v, PRBool b) -{ - PORT_Assert(v == NULL); -} - - -const SECHashObject SECRawHashObjects[] = { - { 0, - (void * (*)(void)) null_hash_new_context, - (void * (*)(void *)) null_hash_clone_context, - (void (*)(void *, PRBool)) null_hash_destroy_context, - (void (*)(void *)) null_hash_begin, - (void (*)(void *, const unsigned char *, unsigned int)) null_hash_update, - (void (*)(void *, unsigned char *, unsigned int *, - unsigned int)) null_hash_end - }, - { MD2_LENGTH, - (void * (*)(void)) MD2_NewContext, - (void * (*)(void *)) null_hash_clone_context, - (void (*)(void *, PRBool)) MD2_DestroyContext, - (void (*)(void *)) MD2_Begin, - (void (*)(void *, const unsigned char *, unsigned int)) MD2_Update, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) MD2_End - }, - { MD5_LENGTH, - (void * (*)(void)) MD5_NewContext, - (void * (*)(void *)) null_hash_clone_context, - (void (*)(void *, PRBool)) MD5_DestroyContext, - (void (*)(void *)) MD5_Begin, - (void (*)(void *, const unsigned char *, unsigned int)) MD5_Update, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) MD5_End - }, - { SHA1_LENGTH, - (void * (*)(void)) SHA1_NewContext, - (void * (*)(void *)) null_hash_clone_context, - (void (*)(void *, PRBool)) SHA1_DestroyContext, - (void (*)(void *)) SHA1_Begin, - (void (*)(void *, const unsigned char *, unsigned int)) SHA1_Update, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) SHA1_End - }, - { SHA256_LENGTH, - (void * (*)(void)) SHA256_NewContext, - (void * (*)(void *)) null_hash_clone_context, - (void (*)(void *, PRBool)) SHA256_DestroyContext, - (void (*)(void *)) SHA256_Begin, - (void (*)(void *, const unsigned char *, unsigned int)) SHA256_Update, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) SHA256_End - }, - { SHA384_LENGTH, - (void * (*)(void)) SHA384_NewContext, - (void * (*)(void *)) null_hash_clone_context, - (void (*)(void *, PRBool)) SHA384_DestroyContext, - (void (*)(void *)) SHA384_Begin, - (void (*)(void *, const unsigned char *, unsigned int)) SHA384_Update, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) SHA384_End - }, - { SHA512_LENGTH, - (void * (*)(void)) SHA512_NewContext, - (void * (*)(void *)) null_hash_clone_context, - (void (*)(void *, PRBool)) SHA512_DestroyContext, - (void (*)(void *)) SHA512_Begin, - (void (*)(void *, const unsigned char *, unsigned int)) SHA512_Update, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) SHA512_End - }, -}; - diff --git a/security/nss/lib/softoken/rsawrapr.c b/security/nss/lib/softoken/rsawrapr.c deleted file mode 100644 index 53bbfc35d..000000000 --- a/security/nss/lib/softoken/rsawrapr.c +++ /dev/null @@ -1,873 +0,0 @@ -/* - * PKCS#1 encoding and decoding functions. - * This file is believed to contain no code licensed from other parties. - * - * 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. - * - * $Id$ - */ - -#include "blapi.h" -#include "softoken.h" -#include "sechash.h" - -#include "lowkeyi.h" -#include "secerr.h" - -#define RSA_BLOCK_MIN_PAD_LEN 8 -#define RSA_BLOCK_FIRST_OCTET 0x00 -#define RSA_BLOCK_PRIVATE0_PAD_OCTET 0x00 -#define RSA_BLOCK_PRIVATE_PAD_OCTET 0xff -#define RSA_BLOCK_AFTER_PAD_OCTET 0x00 - -#define OAEP_SALT_LEN 8 -#define OAEP_PAD_LEN 8 -#define OAEP_PAD_OCTET 0x00 - -#define FLAT_BUFSIZE 512 /* bytes to hold flattened SHA1Context. */ - -static SHA1Context * -SHA1_CloneContext(SHA1Context *original) -{ - SHA1Context * clone = NULL; - unsigned char *pBuf; - int sha1ContextSize = SHA1_FlattenSize(original); - SECStatus frv; - unsigned char buf[FLAT_BUFSIZE]; - - PORT_Assert(sizeof buf >= sha1ContextSize); - if (sizeof buf >= sha1ContextSize) { - pBuf = buf; - } else { - pBuf = PORT_Alloc(sha1ContextSize); - if (!pBuf) - goto done; - } - - frv = SHA1_Flatten(original, pBuf); - if (frv == SECSuccess) { - clone = SHA1_Resurrect(pBuf, NULL); - memset(pBuf, 0, sha1ContextSize); - } -done: - if (pBuf != buf) - PORT_Free(pBuf); - return clone; -} - -/* - * Modify data by XORing it with a special hash of salt. - */ -static SECStatus -oaep_xor_with_h1(unsigned char *data, unsigned int datalen, - unsigned char *salt, unsigned int saltlen) -{ - SHA1Context *sha1cx; - unsigned char *dp, *dataend; - unsigned char end_octet; - - sha1cx = SHA1_NewContext(); - if (sha1cx == NULL) { - return SECFailure; - } - - /* - * Get a hash of salt started; we will use it several times, - * adding in a different end octet (x00, x01, x02, ...). - */ - SHA1_Begin (sha1cx); - SHA1_Update (sha1cx, salt, saltlen); - end_octet = 0; - - dp = data; - dataend = data + datalen; - - while (dp < dataend) { - SHA1Context *sha1cx_h1; - unsigned int sha1len, sha1off; - unsigned char sha1[SHA1_LENGTH]; - - /* - * Create hash of (salt || end_octet) - */ - sha1cx_h1 = SHA1_CloneContext (sha1cx); - SHA1_Update (sha1cx_h1, &end_octet, 1); - SHA1_End (sha1cx_h1, sha1, &sha1len, sizeof(sha1)); - SHA1_DestroyContext (sha1cx_h1, PR_TRUE); - PORT_Assert (sha1len == SHA1_LENGTH); - - /* - * XOR that hash with the data. - * When we have fewer than SHA1_LENGTH octets of data - * left to xor, use just the low-order ones of the hash. - */ - sha1off = 0; - if ((dataend - dp) < SHA1_LENGTH) - sha1off = SHA1_LENGTH - (dataend - dp); - while (sha1off < SHA1_LENGTH) - *dp++ ^= sha1[sha1off++]; - - /* - * Bump for next hash chunk. - */ - end_octet++; - } - - return SECSuccess; -} - -/* - * Modify salt by XORing it with a special hash of data. - */ -static SECStatus -oaep_xor_with_h2(unsigned char *salt, unsigned int saltlen, - unsigned char *data, unsigned int datalen) -{ - unsigned char sha1[SHA1_LENGTH]; - unsigned char *psalt, *psha1, *saltend; - SECStatus rv; - - /* - * Create a hash of data. - */ - rv = SHA1_HashBuf (sha1, data, datalen); - if (rv != SECSuccess) { - return rv; - } - - /* - * XOR the low-order octets of that hash with salt. - */ - PORT_Assert (saltlen <= SHA1_LENGTH); - saltend = salt + saltlen; - psalt = salt; - psha1 = sha1 + SHA1_LENGTH - saltlen; - while (psalt < saltend) { - *psalt++ ^= *psha1++; - } - - return SECSuccess; -} - -/* - * Format one block of data for public/private key encryption using - * the rules defined in PKCS #1. - */ -static unsigned char * -rsa_FormatOneBlock(unsigned modulusLen, RSA_BlockType blockType, - SECItem *data) -{ - unsigned char *block; - unsigned char *bp; - int padLen; - int i; - - block = (unsigned char *) PORT_Alloc(modulusLen); - if (block == NULL) - return NULL; - - bp = block; - - /* - * All RSA blocks start with two octets: - * 0x00 || BlockType - */ - *bp++ = RSA_BLOCK_FIRST_OCTET; - *bp++ = (unsigned char) blockType; - - switch (blockType) { - - /* - * Blocks intended for private-key operation. - */ - case RSA_BlockPrivate0: /* essentially unused */ - case RSA_BlockPrivate: /* preferred method */ - /* - * 0x00 || BT || Pad || 0x00 || ActualData - * 1 1 padLen 1 data->len - * Pad is either all 0x00 or all 0xff bytes, depending on blockType. - */ - padLen = modulusLen - data->len - 3; - PORT_Assert (padLen >= RSA_BLOCK_MIN_PAD_LEN); - if (padLen < RSA_BLOCK_MIN_PAD_LEN) { - PORT_Free (block); - return NULL; - } - PORT_Memset (bp, - blockType == RSA_BlockPrivate0 - ? RSA_BLOCK_PRIVATE0_PAD_OCTET - : RSA_BLOCK_PRIVATE_PAD_OCTET, - padLen); - bp += padLen; - *bp++ = RSA_BLOCK_AFTER_PAD_OCTET; - PORT_Memcpy (bp, data->data, data->len); - break; - - /* - * Blocks intended for public-key operation. - */ - case RSA_BlockPublic: - - /* - * 0x00 || BT || Pad || 0x00 || ActualData - * 1 1 padLen 1 data->len - * Pad is all non-zero random bytes. - */ - padLen = modulusLen - data->len - 3; - PORT_Assert (padLen >= RSA_BLOCK_MIN_PAD_LEN); - if (padLen < RSA_BLOCK_MIN_PAD_LEN) { - PORT_Free (block); - return NULL; - } - for (i = 0; i < padLen; i++) { - /* Pad with non-zero random data. */ - do { - RNG_GenerateGlobalRandomBytes(bp + i, 1); - } while (bp[i] == RSA_BLOCK_AFTER_PAD_OCTET); - } - bp += padLen; - *bp++ = RSA_BLOCK_AFTER_PAD_OCTET; - PORT_Memcpy (bp, data->data, data->len); - - break; - - /* - * Blocks intended for public-key operation, using - * Optimal Asymmetric Encryption Padding (OAEP). - */ - case RSA_BlockOAEP: - /* - * 0x00 || BT || Modified2(Salt) || Modified1(PaddedData) - * 1 1 OAEP_SALT_LEN OAEP_PAD_LEN + data->len [+ N] - * - * where: - * PaddedData is "Pad1 || ActualData [|| Pad2]" - * Salt is random data. - * Pad1 is all zeros. - * Pad2, if present, is random data. - * (The "modified" fields are all the same length as the original - * unmodified values; they are just xor'd with other values.) - * - * Modified1 is an XOR of PaddedData with a special octet - * string constructed of iterated hashing of Salt (see below). - * Modified2 is an XOR of Salt with the low-order octets of - * the hash of Modified1 (see farther below ;-). - * - * Whew! - */ - - - /* - * Salt - */ - RNG_GenerateGlobalRandomBytes(bp, OAEP_SALT_LEN); - bp += OAEP_SALT_LEN; - - /* - * Pad1 - */ - PORT_Memset (bp, OAEP_PAD_OCTET, OAEP_PAD_LEN); - bp += OAEP_PAD_LEN; - - /* - * Data - */ - PORT_Memcpy (bp, data->data, data->len); - bp += data->len; - - /* - * Pad2 - */ - if (bp < (block + modulusLen)) - RNG_GenerateGlobalRandomBytes(bp, block - bp + modulusLen); - - /* - * Now we have the following: - * 0x00 || BT || Salt || PaddedData - * (From this point on, "Pad1 || Data [|| Pad2]" is treated - * as the one entity PaddedData.) - * - * We need to turn PaddedData into Modified1. - */ - if (oaep_xor_with_h1(block + 2 + OAEP_SALT_LEN, - modulusLen - 2 - OAEP_SALT_LEN, - block + 2, OAEP_SALT_LEN) != SECSuccess) { - PORT_Free (block); - return NULL; - } - - /* - * Now we have: - * 0x00 || BT || Salt || Modified1(PaddedData) - * - * The remaining task is to turn Salt into Modified2. - */ - if (oaep_xor_with_h2(block + 2, OAEP_SALT_LEN, - block + 2 + OAEP_SALT_LEN, - modulusLen - 2 - OAEP_SALT_LEN) != SECSuccess) { - PORT_Free (block); - return NULL; - } - - break; - - default: - PORT_Assert (0); - PORT_Free (block); - return NULL; - } - - return block; -} - -static SECStatus -rsa_FormatBlock(SECItem *result, unsigned modulusLen, - RSA_BlockType blockType, SECItem *data) -{ - /* - * XXX For now assume that the data length fits in a single - * XXX encryption block; the ASSERTs below force this. - * XXX To fix it, each case will have to loop over chunks whose - * XXX lengths satisfy the assertions, until all data is handled. - * XXX (Unless RSA has more to say about how to handle data - * XXX which does not fit in a single encryption block?) - * XXX And I do not know what the result is supposed to be, - * XXX so the interface to this function may need to change - * XXX to allow for returning multiple blocks, if they are - * XXX not wanted simply concatenated one after the other. - */ - - switch (blockType) { - case RSA_BlockPrivate0: - case RSA_BlockPrivate: - case RSA_BlockPublic: - /* - * 0x00 || BT || Pad || 0x00 || ActualData - * - * The "3" below is the first octet + the second octet + the 0x00 - * octet that always comes just before the ActualData. - */ - PORT_Assert (data->len <= (modulusLen - (3 + RSA_BLOCK_MIN_PAD_LEN))); - - result->data = rsa_FormatOneBlock(modulusLen, blockType, data); - if (result->data == NULL) { - result->len = 0; - return SECFailure; - } - result->len = modulusLen; - - break; - - case RSA_BlockOAEP: - /* - * 0x00 || BT || M1(Salt) || M2(Pad1||ActualData[||Pad2]) - * - * The "2" below is the first octet + the second octet. - * (The other fields do not contain the clear values, but are - * the same length as the clear values.) - */ - PORT_Assert (data->len <= (modulusLen - (2 + OAEP_SALT_LEN - + OAEP_PAD_LEN))); - - result->data = rsa_FormatOneBlock(modulusLen, blockType, data); - if (result->data == NULL) { - result->len = 0; - return SECFailure; - } - result->len = modulusLen; - - break; - - case RSA_BlockRaw: - /* - * Pad || ActualData - * Pad is zeros. The application is responsible for recovering - * the actual data. - */ - result->data = (unsigned char*)PORT_ZAlloc(modulusLen); - result->len = modulusLen; - PORT_Memcpy(result->data+(modulusLen-data->len),data->data,data->len); - break; - - default: - PORT_Assert (0); - result->data = NULL; - result->len = 0; - return SECFailure; - } - - return SECSuccess; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_Sign(NSSLOWKEYPrivateKey *key, - unsigned char * output, - unsigned int * output_len, - unsigned int maxOutputLen, - unsigned char * input, - unsigned int input_len) -{ - SECStatus rv = SECSuccess; - unsigned int modulus_len = nsslowkey_PrivateModulusLen(key); - SECItem formatted; - SECItem unformatted; - - if (maxOutputLen < modulus_len) - return SECFailure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - return SECFailure; - - unformatted.len = input_len; - unformatted.data = input; - formatted.data = NULL; - rv = rsa_FormatBlock(&formatted, modulus_len, RSA_BlockPrivate, - &unformatted); - if (rv != SECSuccess) - goto done; - - rv = RSA_PrivateKeyOpDoubleChecked(&key->u.rsa, output, formatted.data); - *output_len = modulus_len; - - goto done; - -done: - if (formatted.data != NULL) - PORT_ZFree(formatted.data, modulus_len); - return rv; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_CheckSign(NSSLOWKEYPublicKey *key, - unsigned char * sign, - unsigned int sign_len, - unsigned char * hash, - unsigned int hash_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PublicModulusLen(key); - unsigned int i; - unsigned char * buffer; - - modulus_len = nsslowkey_PublicModulusLen(key); - if (sign_len != modulus_len) - goto failure; - if (hash_len > modulus_len - 8) - goto failure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - - buffer = (unsigned char *)PORT_Alloc(modulus_len + 1); - if (!buffer) - goto failure; - - rv = RSA_PublicKeyOp(&key->u.rsa, buffer, sign); - if (rv != SECSuccess) - goto loser; - - /* - * check the padding that was used - */ - if (buffer[0] != 0 || buffer[1] != 1) - goto loser; - for (i = 2; i < modulus_len - hash_len - 1; i++) { - if (buffer[i] == 0) - break; - if (buffer[i] != 0xff) - goto loser; - } - - /* - * make sure we get the same results - */ - if (PORT_Memcmp(buffer + modulus_len - hash_len, hash, hash_len) != 0) - goto loser; - - PORT_Free(buffer); - return SECSuccess; - -loser: - PORT_Free(buffer); -failure: - return SECFailure; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_CheckSignRecover(NSSLOWKEYPublicKey *key, - unsigned char * data, - unsigned int * data_len, - unsigned int max_output_len, - unsigned char * sign, - unsigned int sign_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PublicModulusLen(key); - unsigned int i; - unsigned char * buffer; - - if (sign_len != modulus_len) - goto failure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - - buffer = (unsigned char *)PORT_Alloc(modulus_len + 1); - if (!buffer) - goto failure; - - rv = RSA_PublicKeyOp(&key->u.rsa, buffer, sign); - if (rv != SECSuccess) - goto loser; - *data_len = 0; - - /* - * check the padding that was used - */ - if (buffer[0] != 0 || buffer[1] != 1) - goto loser; - for (i = 2; i < modulus_len; i++) { - if (buffer[i] == 0) { - *data_len = modulus_len - i - 1; - break; - } - if (buffer[i] != 0xff) - goto loser; - } - if (*data_len == 0) - goto loser; - if (*data_len > max_output_len) - goto loser; - - /* - * make sure we get the same results - */ - PORT_Memcpy(data,buffer + modulus_len - *data_len, *data_len); - - PORT_Free(buffer); - return SECSuccess; - -loser: - PORT_Free(buffer); -failure: - return SECFailure; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_EncryptBlock(NSSLOWKEYPublicKey *key, - unsigned char * output, - unsigned int * output_len, - unsigned int max_output_len, - unsigned char * input, - unsigned int input_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PublicModulusLen(key); - SECItem formatted; - SECItem unformatted; - - formatted.data = NULL; - if (max_output_len < modulus_len) - goto failure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - - unformatted.len = input_len; - unformatted.data = input; - formatted.data = NULL; - rv = rsa_FormatBlock(&formatted, modulus_len, RSA_BlockPublic, - &unformatted); - if (rv != SECSuccess) - goto failure; - - rv = RSA_PublicKeyOp(&key->u.rsa, output, formatted.data); - if (rv != SECSuccess) - goto failure; - - PORT_ZFree(formatted.data, modulus_len); - *output_len = modulus_len; - return SECSuccess; - -failure: - if (formatted.data != NULL) - PORT_ZFree(formatted.data, modulus_len); - return SECFailure; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_DecryptBlock(NSSLOWKEYPrivateKey *key, - unsigned char * output, - unsigned int * output_len, - unsigned int max_output_len, - unsigned char * input, - unsigned int input_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PrivateModulusLen(key); - unsigned int i; - unsigned char * buffer; - - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - if (input_len != modulus_len) - goto failure; - - buffer = (unsigned char *)PORT_Alloc(modulus_len + 1); - if (!buffer) - goto failure; - - rv = RSA_PrivateKeyOp(&key->u.rsa, buffer, input); - if (rv != SECSuccess) - goto loser; - - if (buffer[0] != 0 || buffer[1] != 2) - goto loser; - *output_len = 0; - for (i = 2; i < modulus_len; i++) { - if (buffer[i] == 0) { - *output_len = modulus_len - i - 1; - break; - } - } - if (*output_len == 0) - goto loser; - if (*output_len > max_output_len) - goto loser; - - PORT_Memcpy(output, buffer + modulus_len - *output_len, *output_len); - - PORT_Free(buffer); - return SECSuccess; - -loser: - PORT_Free(buffer); -failure: - return SECFailure; -} - -/* XXX Doesn't set error code */ -/* - * added to make pkcs #11 happy - * RAW is RSA_X_509 - */ -SECStatus -RSA_SignRaw(NSSLOWKEYPrivateKey *key, - unsigned char * output, - unsigned int * output_len, - unsigned int maxOutputLen, - unsigned char * input, - unsigned int input_len) -{ - SECStatus rv = SECSuccess; - unsigned int modulus_len = nsslowkey_PrivateModulusLen(key); - SECItem formatted; - SECItem unformatted; - - if (maxOutputLen < modulus_len) - return SECFailure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - return SECFailure; - - unformatted.len = input_len; - unformatted.data = input; - formatted.data = NULL; - rv = rsa_FormatBlock(&formatted, modulus_len, RSA_BlockRaw, &unformatted); - if (rv != SECSuccess) - goto done; - - rv = RSA_PrivateKeyOpDoubleChecked(&key->u.rsa, output, formatted.data); - *output_len = modulus_len; - -done: - if (formatted.data != NULL) - PORT_ZFree(formatted.data, modulus_len); - return rv; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_CheckSignRaw(NSSLOWKEYPublicKey *key, - unsigned char * sign, - unsigned int sign_len, - unsigned char * hash, - unsigned int hash_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PublicModulusLen(key); - unsigned char * buffer; - - if (sign_len != modulus_len) - goto failure; - if (hash_len > modulus_len) - goto failure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - - buffer = (unsigned char *)PORT_Alloc(modulus_len + 1); - if (!buffer) - goto failure; - - rv = RSA_PublicKeyOp(&key->u.rsa, buffer, sign); - if (rv != SECSuccess) - goto loser; - - /* - * make sure we get the same results - */ - /* NOTE: should we verify the leading zeros? */ - if (PORT_Memcmp(buffer + (modulus_len-hash_len), hash, hash_len) != 0) - goto loser; - - PORT_Free(buffer); - return SECSuccess; - -loser: - PORT_Free(buffer); -failure: - return SECFailure; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_CheckSignRecoverRaw(NSSLOWKEYPublicKey *key, - unsigned char * data, - unsigned int * data_len, - unsigned int max_output_len, - unsigned char * sign, - unsigned int sign_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PublicModulusLen(key); - - if (sign_len != modulus_len) - goto failure; - if (max_output_len < modulus_len) - goto failure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - - rv = RSA_PublicKeyOp(&key->u.rsa, data, sign); - if (rv != SECSuccess) - goto failure; - - *data_len = modulus_len; - return SECSuccess; - -failure: - return SECFailure; -} - - -/* XXX Doesn't set error code */ -SECStatus -RSA_EncryptRaw(NSSLOWKEYPublicKey *key, - unsigned char * output, - unsigned int * output_len, - unsigned int max_output_len, - unsigned char * input, - unsigned int input_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PublicModulusLen(key); - SECItem formatted; - SECItem unformatted; - - formatted.data = NULL; - if (max_output_len < modulus_len) - goto failure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - - unformatted.len = input_len; - unformatted.data = input; - formatted.data = NULL; - rv = rsa_FormatBlock(&formatted, modulus_len, RSA_BlockRaw, &unformatted); - if (rv != SECSuccess) - goto failure; - - rv = RSA_PublicKeyOp(&key->u.rsa, output, formatted.data); - if (rv != SECSuccess) - goto failure; - - PORT_ZFree(formatted.data, modulus_len); - *output_len = modulus_len; - return SECSuccess; - -failure: - if (formatted.data != NULL) - PORT_ZFree(formatted.data, modulus_len); - return SECFailure; -} - -/* XXX Doesn't set error code */ -SECStatus -RSA_DecryptRaw(NSSLOWKEYPrivateKey *key, - unsigned char * output, - unsigned int * output_len, - unsigned int max_output_len, - unsigned char * input, - unsigned int input_len) -{ - SECStatus rv; - unsigned int modulus_len = nsslowkey_PrivateModulusLen(key); - - if (modulus_len <= 0) - goto failure; - if (modulus_len > max_output_len) - goto failure; - PORT_Assert(key->keyType == NSSLOWKEYRSAKey); - if (key->keyType != NSSLOWKEYRSAKey) - goto failure; - if (input_len != modulus_len) - goto failure; - - rv = RSA_PrivateKeyOp(&key->u.rsa, output, input); - if (rv != SECSuccess) - goto failure; - - *output_len = modulus_len; - return SECSuccess; - -failure: - return SECFailure; -} diff --git a/security/nss/lib/softoken/softkver.c b/security/nss/lib/softoken/softkver.c deleted file mode 100644 index e833664a1..000000000 --- a/security/nss/lib/softoken/softkver.c +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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) 2002 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. - */ - -/* Library identity and versioning */ - -#include "nss.h" - -#if defined(DEBUG) -#define _DEBUG_STRING " (debug)" -#else -#define _DEBUG_STRING "" -#endif - -/* - * Version information for the 'ident' and 'what commands - * - * NOTE: the first component of the concatenated rcsid string - * must not end in a '$' to prevent rcs keyword substitution. - */ -const char __nss_softokn_rcsid[] = "$Header: NSS " NSS_VERSION _DEBUG_STRING - " " __DATE__ " " __TIME__ " $"; -const char __nss_softokn_sccsid[] = "@(#)NSS " NSS_VERSION _DEBUG_STRING - " " __DATE__ " " __TIME__; diff --git a/security/nss/lib/softoken/softoken.h b/security/nss/lib/softoken/softoken.h deleted file mode 100644 index e399581c9..000000000 --- a/security/nss/lib/softoken/softoken.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * softoken.h - private data structures and prototypes for the softoken lib - * - * 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. - * - * $Id$ - */ - -#ifndef _SOFTOKEN_H_ -#define _SOFTOKEN_H_ - -#include "blapi.h" -#include "lowkeyti.h" -#include "softoknt.h" -#include "secoidt.h" - -#include "pkcs11t.h" /* CK_RV Required for pk11_fipsPowerUpSelfTest(). */ - -SEC_BEGIN_PROTOS - -/* -** RSA encryption/decryption. When encrypting/decrypting the output -** buffer must be at least the size of the public key modulus. -*/ - -/* -** Format some data into a PKCS#1 encryption block, preparing the -** data for RSA encryption. -** "result" where the formatted block is stored (memory is allocated) -** "modulusLen" the size of the formatted block -** "blockType" what block type to use (SEC_RSABlock*) -** "data" the data to format -*/ -extern SECStatus RSA_FormatBlock(SECItem *result, - unsigned int modulusLen, - RSA_BlockType blockType, - SECItem *data); -/* -** Similar, but just returns a pointer to the allocated memory, *and* -** will *only* format one block, even if we (in the future) modify -** RSA_FormatBlock() to loop over multiples of modulusLen. -*/ -extern unsigned char *RSA_FormatOneBlock(unsigned int modulusLen, - RSA_BlockType blockType, - SECItem *data); - - - -/* - * convenience wrappers for doing single RSA operations. They create the - * RSA context internally and take care of the formatting - * requirements. Blinding happens automagically within RSA_SignHash and - * RSA_DecryptBlock. - */ -extern -SECStatus RSA_Sign(NSSLOWKEYPrivateKey *key, unsigned char *output, - unsigned int *outputLen, unsigned int maxOutputLen, - unsigned char *input, unsigned int inputLen); -extern -SECStatus RSA_CheckSign(NSSLOWKEYPublicKey *key, unsigned char *sign, - unsigned int signLength, unsigned char *hash, - unsigned int hashLength); -extern -SECStatus RSA_CheckSignRecover(NSSLOWKEYPublicKey *key, unsigned char *data, - unsigned int *data_len,unsigned int max_output_len, - unsigned char *sign, unsigned int sign_len); -extern -SECStatus RSA_EncryptBlock(NSSLOWKEYPublicKey *key, unsigned char *output, - unsigned int *outputLen, unsigned int maxOutputLen, - unsigned char *input, unsigned int inputLen); -extern -SECStatus RSA_DecryptBlock(NSSLOWKEYPrivateKey *key, unsigned char *output, - unsigned int *outputLen, unsigned int maxOutputLen, - unsigned char *input, unsigned int inputLen); - -/* - * added to make pkcs #11 happy - * RAW is RSA_X_509 - */ -extern -SECStatus RSA_SignRaw( NSSLOWKEYPrivateKey *key, unsigned char *output, - unsigned int *output_len, unsigned int maxOutputLen, - unsigned char *input, unsigned int input_len); -extern -SECStatus RSA_CheckSignRaw( NSSLOWKEYPublicKey *key, unsigned char *sign, - unsigned int sign_len, unsigned char *hash, - unsigned int hash_len); -extern -SECStatus RSA_CheckSignRecoverRaw( NSSLOWKEYPublicKey *key, unsigned char *data, - unsigned int *data_len, unsigned int max_output_len, - unsigned char *sign, unsigned int sign_len); -extern -SECStatus RSA_EncryptRaw( NSSLOWKEYPublicKey *key, unsigned char *output, - unsigned int *output_len, - unsigned int max_output_len, - unsigned char *input, unsigned int input_len); -extern -SECStatus RSA_DecryptRaw(NSSLOWKEYPrivateKey *key, unsigned char *output, - unsigned int *output_len, - unsigned int max_output_len, - unsigned char *input, unsigned int input_len); - -/* -** Prepare a buffer for DES encryption, growing to the appropriate boundary, -** filling with the appropriate padding. -** We add from 1 to DES_KEY_LENGTH bytes -- we *always* grow. -** The extra bytes contain the value of the length of the padding: -** if we have 2 bytes of padding, then the padding is "0x02, 0x02". -** -** NOTE: If arena is non-NULL, we re-allocate from there, otherwise -** we assume (and use) PR memory (re)allocation. -** Maybe this belongs in util? -*/ -extern unsigned char * DES_PadBuffer(PRArenaPool *arena, unsigned char *inbuf, - unsigned int inlen, unsigned int *outlen); - - -/****************************************/ -/* -** Power-Up selftests required for FIPS and invoked only -** under PKCS #11 FIPS mode. -*/ -extern CK_RV pk11_fipsPowerUpSelfTest( void ); - -/* -** make known fixed PKCS #11 key types to their sizes in bytes -*/ -unsigned long pk11_MapKeySize(CK_KEY_TYPE keyType); - -SEC_END_PROTOS - -#endif /* _SOFTOKEN_H_ */ diff --git a/security/nss/lib/softoken/softokn.def b/security/nss/lib/softoken/softokn.def deleted file mode 100644 index d851aa34d..000000000 --- a/security/nss/lib/softoken/softokn.def +++ /dev/null @@ -1,57 +0,0 @@ -;+# -;+# 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) 2000 Netscape Communications Corporation. All -;+# Rights Reserved. -;+# -;+# Contributor(s): -;+# Dr Stephen Henson <stephen.henson@gemplus.com> -;+# -;+# 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. -;+# -;+# -;+# OK, this file is meant to support SUN, LINUX, AIX and WINDOWS -;+# 1. For all unix platforms, the string ";-" means "remove this line" -;+# 2. For all unix platforms, the string " DATA " will be removed from any -;+# line on which it occurs. -;+# 3. Lines containing ";+" will have ";+" removed on SUN and LINUX. -;+# On AIX, lines containing ";+" will be removed. -;+# 4. For all unix platforms, the string ";;" will thave the ";;" removed. -;+# 5. For all unix platforms, after the above processing has taken place, -;+# all characters after the first ";" on the line will be removed. -;+# And for AIX, the first ";" will also be removed. -;+# This file is passed directly to windows. Since ';' is a comment, all UNIX -;+# directives are hidden behind ";", ";+", and ";-" -;+NSS_3.4 { # NSS 3.4 release -;+ global: -LIBRARY softokn3 ;- -EXPORTS ;- -C_GetFunctionList; Make this function like a real PKCS #11 module as well -FC_GetFunctionList; -NSC_GetFunctionList; -NSC_ModuleDBFunc; -;+ local: -;+ *; -;+}; diff --git a/security/nss/lib/softoken/softokn.rc b/security/nss/lib/softoken/softokn.rc deleted file mode 100644 index 087a5d26b..000000000 --- a/security/nss/lib/softoken/softokn.rc +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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) 2001 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. - */ - -#include "nss.h" -#include <winver.h> - -#define MY_LIBNAME "softokn" -#define MY_FILEDESCRIPTION "NSS PKCS #11 Library" - -#define STRINGIZE(x) #x -#define STRINGIZE2(x) STRINGIZE(x) -#define NSS_VMAJOR_STR STRINGIZE2(NSS_VMAJOR) - -#ifdef _DEBUG -#define MY_DEBUG_STR " (debug)" -#define MY_FILEFLAGS_1 VS_FF_DEBUG -#else -#define MY_DEBUG_STR "" -#define MY_FILEFLAGS_1 0x0L -#endif -#if NSS_BETA -#define MY_FILEFLAGS_2 MY_FILEFLAGS_1|VS_FF_PRERELEASE -#else -#define MY_FILEFLAGS_2 MY_FILEFLAGS_1 -#endif - -#ifdef WINNT -#define MY_FILEOS VOS_NT_WINDOWS32 -#else -#define MY_FILEOS VOS__WINDOWS32 -#endif - -#define MY_INTERNAL_NAME MY_LIBNAME NSS_VMAJOR_STR - -///////////////////////////////////////////////////////////////////////////// -// -// Version-information resource -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION NSS_VMAJOR,NSS_VMINOR,NSS_VPATCH,0 - PRODUCTVERSION NSS_VMAJOR,NSS_VMINOR,NSS_VPATCH,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK - FILEFLAGS MY_FILEFLAGS_2 - FILEOS MY_FILEOS - FILETYPE VFT_DLL - FILESUBTYPE 0x0L // not used - -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" // Lang=US English, CharSet=Unicode - BEGIN - VALUE "CompanyName", "Netscape Communications Corporation\0" - VALUE "FileDescription", MY_FILEDESCRIPTION MY_DEBUG_STR "\0" - VALUE "FileVersion", NSS_VERSION "\0" - VALUE "InternalName", MY_INTERNAL_NAME "\0" - VALUE "LegalCopyright", "Copyright \251 1994-2001 Netscape Communications Corporation\0" - VALUE "OriginalFilename", MY_INTERNAL_NAME ".dll\0" - VALUE "ProductName", "Network Security Services\0" - VALUE "ProductVersion", NSS_VERSION "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END diff --git a/security/nss/lib/softoken/softoknt.h b/security/nss/lib/softoken/softoknt.h deleted file mode 100644 index da66c9042..000000000 --- a/security/nss/lib/softoken/softoknt.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * softoknt.h - public data structures for the software token library - * - * 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. - * - * $Id$ - */ - -#ifndef _SOFTOKNT_H_ -#define _SOFTOKNT_H_ - -/* - * RSA block types - * - * The actual values are important -- they are fixed, *not* arbitrary. - * The explicit value assignments are not needed (because C would give - * us those same values anyway) but are included as a reminder... - */ -typedef enum { - RSA_BlockPrivate0 = 0, /* unused, really */ - RSA_BlockPrivate = 1, /* pad for a private-key operation */ - RSA_BlockPublic = 2, /* pad for a public-key operation */ - RSA_BlockOAEP = 3, /* use OAEP padding */ - /* XXX is this only for a public-key - operation? If so, add "Public" */ - RSA_BlockRaw = 4, /* simply justify the block appropriately */ - RSA_BlockTotal -} RSA_BlockType; - -#define NSS_SOFTOKEN_DEFAULT_CHUNKSIZE 2048 - -#endif /* _SOFTOKNT_H_ */ diff --git a/security/nss/lib/softoken/tlsprf.c b/security/nss/lib/softoken/tlsprf.c deleted file mode 100644 index 9d1a6e677..000000000 --- a/security/nss/lib/softoken/tlsprf.c +++ /dev/null @@ -1,334 +0,0 @@ -/* tlsprf.c - TLS Pseudo Random Function (PRF) implementation - * - * 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. - * - * $Id$ - */ - -#include "pkcs11i.h" -#include "sechash.h" -#include "alghmac.h" - -#define PK11_OFFSETOF(str, memb) ((PRPtrdiff)(&(((str *)0)->memb))) - -#define PHASH_STATE_MAX_LEN 20 - -/* TLS P_hash function */ -static SECStatus -pk11_P_hash(HASH_HashType hashType, const SECItem *secret, const char *label, - SECItem *seed, SECItem *result, PRBool isFIPS) -{ - unsigned char state[PHASH_STATE_MAX_LEN]; - unsigned char outbuf[PHASH_STATE_MAX_LEN]; - unsigned int state_len = 0, label_len = 0, outbuf_len = 0, chunk_size; - unsigned int remaining; - unsigned char *res; - SECStatus status; - HMACContext *cx; - SECStatus rv = SECFailure; - const SECHashObject *hashObj = &SECRawHashObjects[hashType]; - - PORT_Assert((secret != NULL) && (secret->data != NULL || !secret->len)); - PORT_Assert((seed != NULL) && (seed->data != NULL)); - PORT_Assert((result != NULL) && (result->data != NULL)); - - remaining = result->len; - res = result->data; - - if (label != NULL) - label_len = PORT_Strlen(label); - - cx = HMAC_Create(hashObj, secret->data, secret->len, isFIPS); - if (cx == NULL) - goto loser; - - /* initialize the state = A(1) = HMAC_hash(secret, seed) */ - HMAC_Begin(cx); - HMAC_Update(cx, (unsigned char *)label, label_len); - HMAC_Update(cx, seed->data, seed->len); - status = HMAC_Finish(cx, state, &state_len, PHASH_STATE_MAX_LEN); - if (status != SECSuccess) - goto loser; - - /* generate a block at a time until we're done */ - while (remaining > 0) { - - HMAC_Begin(cx); - HMAC_Update(cx, state, state_len); - if (label_len) - HMAC_Update(cx, (unsigned char *)label, label_len); - HMAC_Update(cx, seed->data, seed->len); - status = HMAC_Finish(cx, outbuf, &outbuf_len, PHASH_STATE_MAX_LEN); - if (status != SECSuccess) - goto loser; - - /* Update the state = A(i) = HMAC_hash(secret, A(i-1)) */ - HMAC_Begin(cx); - HMAC_Update(cx, state, state_len); - status = HMAC_Finish(cx, state, &state_len, PHASH_STATE_MAX_LEN); - if (status != SECSuccess) - goto loser; - - chunk_size = PR_MIN(outbuf_len, remaining); - PORT_Memcpy(res, &outbuf, chunk_size); - res += chunk_size; - remaining -= chunk_size; - } - - rv = SECSuccess; - -loser: - /* if (cx) HMAC_Destroy(cx); */ - /* clear out state so it's not left on the stack */ - if (cx) HMAC_Destroy(cx); - PORT_Memset(state, 0, sizeof(state)); - PORT_Memset(outbuf, 0, sizeof(outbuf)); - return rv; -} - -SECStatus -pk11_PRF(const SECItem *secret, const char *label, SECItem *seed, - SECItem *result, PRBool isFIPS) -{ - SECStatus rv = SECFailure, status; - unsigned int i; - SECItem tmp = { siBuffer, NULL, 0}; - SECItem S1; - SECItem S2; - - PORT_Assert((secret != NULL) && (secret->data != NULL || !secret->len)); - PORT_Assert((seed != NULL) && (seed->data != NULL)); - PORT_Assert((result != NULL) && (result->data != NULL)); - - S1.type = siBuffer; - S1.len = (secret->len / 2) + (secret->len & 1); - S1.data = secret->data; - - S2.type = siBuffer; - S2.len = S1.len; - S2.data = secret->data + (secret->len - S2.len); - - tmp.data = (unsigned char*)PORT_Alloc(result->len); - if (tmp.data == NULL) - goto loser; - tmp.len = result->len; - - status = pk11_P_hash(HASH_AlgMD5, &S1, label, seed, result, isFIPS); - if (status != SECSuccess) - goto loser; - - status = pk11_P_hash(HASH_AlgSHA1, &S2, label, seed, &tmp, isFIPS); - if (status != SECSuccess) - goto loser; - - for (i = 0; i < result->len; i++) - result->data[i] ^= tmp.data[i]; - - rv = SECSuccess; - -loser: - if (tmp.data != NULL) - PORT_ZFree(tmp.data, tmp.len); - return rv; -} - -static void pk11_TLSPRFNull(void *data, PRBool freeit) -{ - return; -} - -typedef struct { - PRUint32 cxSize; /* size of allocated block, in bytes. */ - PRUint32 cxBufSize; /* sizeof buffer at cxBufPtr. */ - unsigned char *cxBufPtr; /* points to real buffer, may be cxBuf. */ - PRUint32 cxKeyLen; /* bytes of cxBufPtr containing key. */ - PRUint32 cxDataLen; /* bytes of cxBufPtr containing data. */ - SECStatus cxRv; /* records failure of void functions. */ - PRBool cxIsFIPS; /* true if conforming to FIPS 198. */ - unsigned char cxBuf[512]; /* actual size may be larger than 512. */ -} TLSPRFContext; - -static void -pk11_TLSPRFHashUpdate(TLSPRFContext *cx, const unsigned char *data, - unsigned int data_len) -{ - PRUint32 bytesUsed = cx->cxKeyLen + cx->cxDataLen; - - if (cx->cxRv != SECSuccess) /* function has previously failed. */ - return; - if (bytesUsed + data_len > cx->cxBufSize) { - /* We don't use realloc here because - ** (a) realloc doesn't zero out the old block, and - ** (b) if realloc fails, we lose the old block. - */ - PRUint32 newBufSize = bytesUsed + data_len + 512; - unsigned char * newBuf = (unsigned char *)PORT_Alloc(newBufSize); - if (!newBuf) { - cx->cxRv = SECFailure; - return; - } - PORT_Memcpy(newBuf, cx->cxBufPtr, bytesUsed); - if (cx->cxBufPtr != cx->cxBuf) { - PORT_ZFree(cx->cxBufPtr, bytesUsed); - } - cx->cxBufPtr = newBuf; - cx->cxBufSize = newBufSize; - } - PORT_Memcpy(cx->cxBufPtr + bytesUsed, data, data_len); - cx->cxDataLen += data_len; -} - -static void -pk11_TLSPRFEnd(TLSPRFContext *ctx, unsigned char *hashout, - unsigned int *pDigestLen, unsigned int maxDigestLen) -{ - *pDigestLen = 0; /* tells Verify that no data has been input yet. */ -} - -/* Compute the PRF values from the data previously input. */ -static SECStatus -pk11_TLSPRFUpdate(TLSPRFContext *cx, - unsigned char *sig, /* output goes here. */ - unsigned int * sigLen, /* how much output. */ - unsigned int maxLen, /* output buffer size */ - unsigned char *hash, /* unused. */ - unsigned int hashLen) /* unused. */ -{ - SECStatus rv; - SECItem sigItem; - SECItem seedItem; - SECItem secretItem; - - if (cx->cxRv != SECSuccess) - return cx->cxRv; - - secretItem.data = cx->cxBufPtr; - secretItem.len = cx->cxKeyLen; - - seedItem.data = cx->cxBufPtr + cx->cxKeyLen; - seedItem.len = cx->cxDataLen; - - sigItem.data = sig; - sigItem.len = maxLen; - - rv = pk11_PRF(&secretItem, NULL, &seedItem, &sigItem, cx->cxIsFIPS); - if (rv == SECSuccess && sigLen != NULL) - *sigLen = sigItem.len; - return rv; - -} - -static SECStatus -pk11_TLSPRFVerify(TLSPRFContext *cx, - unsigned char *sig, /* input, for comparison. */ - unsigned int sigLen, /* length of sig. */ - unsigned char *hash, /* data to be verified. */ - unsigned int hashLen) /* size of hash data. */ -{ - unsigned char * tmp = (unsigned char *)PORT_Alloc(sigLen); - unsigned int tmpLen = sigLen; - SECStatus rv; - - if (!tmp) - return SECFailure; - if (hashLen) { - /* hashLen is non-zero when the user does a one-step verify. - ** In this case, none of the data has been input yet. - */ - pk11_TLSPRFHashUpdate(cx, hash, hashLen); - } - rv = pk11_TLSPRFUpdate(cx, tmp, &tmpLen, sigLen, NULL, 0); - if (rv == SECSuccess) { - rv = (SECStatus)(1 - !PORT_Memcmp(tmp, sig, sigLen)); - } - PORT_ZFree(tmp, sigLen); - return rv; -} - -static void -pk11_TLSPRFHashDestroy(TLSPRFContext *cx, PRBool freeit) -{ - if (freeit) { - if (cx->cxBufPtr != cx->cxBuf) - PORT_ZFree(cx->cxBufPtr, cx->cxBufSize); - PORT_ZFree(cx, cx->cxSize); - } -} - -CK_RV -pk11_TLSPRFInit(PK11SessionContext *context, - PK11Object * key, - CK_KEY_TYPE key_type) -{ - PK11Attribute * keyVal; - TLSPRFContext * prf_cx; - CK_RV crv = CKR_HOST_MEMORY; - PRUint32 keySize; - PRUint32 blockSize; - - if (key_type != CKK_GENERIC_SECRET) - return CKR_KEY_TYPE_INCONSISTENT; /* CKR_KEY_FUNCTION_NOT_PERMITTED */ - - context->multi = PR_TRUE; - - keyVal = pk11_FindAttribute(key, CKA_VALUE); - keySize = (!keyVal) ? 0 : keyVal->attrib.ulValueLen; - blockSize = keySize + sizeof(TLSPRFContext); - prf_cx = (TLSPRFContext *)PORT_Alloc(blockSize); - if (!prf_cx) - goto done; - prf_cx->cxSize = blockSize; - prf_cx->cxKeyLen = keySize; - prf_cx->cxDataLen = 0; - prf_cx->cxBufSize = blockSize - PK11_OFFSETOF(TLSPRFContext, cxBuf); - prf_cx->cxRv = SECSuccess; - prf_cx->cxIsFIPS = (key->slot->slotID == FIPS_SLOT_ID); - prf_cx->cxBufPtr = prf_cx->cxBuf; - if (keySize) - PORT_Memcpy(prf_cx->cxBufPtr, keyVal->attrib.pValue, keySize); - - context->hashInfo = (void *) prf_cx; - context->cipherInfo = (void *) prf_cx; - context->hashUpdate = (PK11Hash) pk11_TLSPRFHashUpdate; - context->end = (PK11End) pk11_TLSPRFEnd; - context->update = (PK11Cipher) pk11_TLSPRFUpdate; - context->verify = (PK11Verify) pk11_TLSPRFVerify; - context->destroy = (PK11Destroy) pk11_TLSPRFNull; - context->hashdestroy = (PK11Destroy) pk11_TLSPRFHashDestroy; - crv = CKR_OK; - -done: - if (keyVal) - pk11_FreeAttribute(keyVal); - return crv; -} - |