diff --git a/.hgtags b/.hgtags index c6317565ac4e..a62ce26af598 100644 --- a/.hgtags +++ b/.hgtags @@ -123,3 +123,4 @@ b297a6727acfd21e757ddd38cd61894812666265 FIREFOX_AURORA_36_BASE fcef8ded82219c89298b4e376cfbdfba79a1d35a FIREFOX_AURORA_43_BASE 67a788db9f07822cfef52351bbbe3745dff8bd7f FIREFOX_AURORA_44_BASE 99137d6d4061f408ae0869122649d8bdf489cc30 FIREFOX_AURORA_45_BASE +67c66c2878aed17ae3096d7db483ddbb2293c503 FIREFOX_AURORA_46_BASE diff --git a/CLOBBER b/CLOBBER index d8162056e885..e30b6ea3fc51 100644 --- a/CLOBBER +++ b/CLOBBER @@ -22,5 +22,5 @@ # changes to stick? As of bug 928195, this shouldn't be necessary! Please # don't change CLOBBER for WebIDL changes any more. -Bug 1240627 - Enable AVX2 optimizations in ffvpx on Mac +Merge day clobber \ No newline at end of file diff --git a/browser/components/search/test/browser_contextmenu.js b/browser/components/search/test/browser_contextmenu.js index c34bbdcc254b..d33c111c9deb 100644 --- a/browser/components/search/test/browser_contextmenu.js +++ b/browser/components/search/test/browser_contextmenu.js @@ -9,6 +9,9 @@ add_task(function* () { const ENGINE_NAME = "Foo"; var contextMenu; + // We want select events to be fired. + yield new Promise(resolve => SpecialPowers.pushPrefEnv({"set": [["dom.select_events.enabled", true]]}, resolve)); + let envService = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); let originalValue = envService.get("XPCSHELL_TEST_PROFILE_DIR"); envService.set("XPCSHELL_TEST_PROFILE_DIR", "1"); diff --git a/browser/config/version.txt b/browser/config/version.txt index 5860193beb70..e6fc4bf53cdc 100644 --- a/browser/config/version.txt +++ b/browser/config/version.txt @@ -1 +1 @@ -46.0a1 +47.0a1 diff --git a/browser/config/version_display.txt b/browser/config/version_display.txt index 5860193beb70..e6fc4bf53cdc 100644 --- a/browser/config/version_display.txt +++ b/browser/config/version_display.txt @@ -1 +1 @@ -46.0a1 +47.0a1 diff --git a/config/milestone.txt b/config/milestone.txt index 35a9cb601971..4fa46156b811 100644 --- a/config/milestone.txt +++ b/config/milestone.txt @@ -10,4 +10,4 @@ # hardcoded milestones in the tree from these two files. #-------------------------------------------------------- -46.0a1 +47.0a1 diff --git a/dom/bindings/BindingUtils.h b/dom/bindings/BindingUtils.h index dd4de1afcc52..312c3cef3fbc 100644 --- a/dom/bindings/BindingUtils.h +++ b/dom/bindings/BindingUtils.h @@ -2309,7 +2309,7 @@ public: // Rooter class for MozMap; this is what we mostly use in the codegen. template -class MOZ_RAII MozMapRooter : private JS::CustomAutoRooter +class MOZ_RAII MozMapRooter final : private JS::CustomAutoRooter { public: MozMapRooter(JSContext *aCx, MozMap* aMozMap diff --git a/dom/bindings/TypedArray.h b/dom/bindings/TypedArray.h index 8305dff47646..89d6b087348b 100644 --- a/dom/bindings/TypedArray.h +++ b/dom/bindings/TypedArray.h @@ -412,8 +412,8 @@ private: // Class for easily setting up a rooted typed array object on the stack template -class MOZ_RAII RootedTypedArray : public ArrayType, - private TypedArrayRooter +class MOZ_RAII RootedTypedArray final : public ArrayType, + private TypedArrayRooter { public: explicit RootedTypedArray(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : diff --git a/gfx/layers/basic/BasicCompositor.cpp b/gfx/layers/basic/BasicCompositor.cpp index 5872bb64adb2..a3a12c3e92e6 100644 --- a/gfx/layers/basic/BasicCompositor.cpp +++ b/gfx/layers/basic/BasicCompositor.cpp @@ -549,6 +549,9 @@ BasicCompositor::BeginFrame(const nsIntRegion& aInvalidRegion, } else { // StartRemoteDrawingInRegion can mutate mInvalidRegion. mDrawTarget = mWidget->StartRemoteDrawingInRegion(mInvalidRegion); + if (!mDrawTarget) { + return; + } mInvalidRect = mInvalidRegion.GetBounds(); if (mInvalidRect.IsEmpty()) { mWidget->EndRemoteDrawingInRegion(mDrawTarget, mInvalidRegion); diff --git a/js/src/jit/RangeAnalysis.cpp b/js/src/jit/RangeAnalysis.cpp index 82c10b0f5076..060955becad9 100644 --- a/js/src/jit/RangeAnalysis.cpp +++ b/js/src/jit/RangeAnalysis.cpp @@ -2087,7 +2087,7 @@ RangeAnalysis::analyzeLoopPhi(MBasicBlock* header, LoopIterationBound* loopBound return; if (!phi->range()) - phi->setRange(new(alloc()) Range()); + phi->setRange(new(alloc()) Range(phi)); LinearSum initialSum(alloc()); if (!initialSum.add(initial, 1)) diff --git a/security/nss/.clang-format b/security/nss/.clang-format new file mode 100644 index 000000000000..f508bfe3425e --- /dev/null +++ b/security/nss/.clang-format @@ -0,0 +1,64 @@ +--- +Language: Cpp +# BasedOnStyle: Mozilla +AccessModifierOffset: -2 +AlignAfterOpenBracket: true +AlignEscapedNewlinesLeft: false +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AlwaysBreakAfterDefinitionReturnType: true +AlwaysBreakTemplateDeclarations: false +AlwaysBreakBeforeMultilineStrings: false +BreakBeforeBinaryOperators: None +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BinPackParameters: true +BinPackArguments: true +ColumnLimit: 0 +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +DerivePointerAlignment: true +ExperimentalAutoDetectBinPacking: false +IndentCaseLabels: true +IndentWrappedFunctionNames: false +IndentFunctionDeclarationAfterType: false +MaxEmptyLinesToKeep: 1 +KeepEmptyLinesAtTheStartOfBlocks: true +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: false +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakString: 1000 +PenaltyBreakFirstLessLess: 120 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Right +SpacesBeforeTrailingComments: 1 +Cpp11BracedListStyle: false +Standard: Cpp03 +IndentWidth: 4 +TabWidth: 8 +UseTab: Never +BreakBeforeBraces: Linux +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpacesInAngles: false +SpaceInEmptyParentheses: false +SpacesInCStyleCastParentheses: false +SpaceAfterCStyleCast: false +SpacesInContainerLiterals: true +SpaceBeforeAssignmentOperators: true +ContinuationIndentWidth: 4 +CommentPragmas: '^ IWYU pragma:' +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +SpaceBeforeParens: ControlStatements +DisableFormat: false +... diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO index 8882305ffb2c..90bd1570fec7 100644 --- a/security/nss/TAG-INFO +++ b/security/nss/TAG-INFO @@ -1 +1 @@ -NSS_3_21_RTM +NSS_3_22_BETA2 diff --git a/security/nss/cmd/certutil/certutil.c b/security/nss/cmd/certutil/certutil.c index ab22fbca18fe..07cfb1a810a2 100644 --- a/security/nss/cmd/certutil/certutil.c +++ b/security/nss/cmd/certutil/certutil.c @@ -3496,6 +3496,9 @@ shutdown: /* Allocated by a PL_strdup call in SECU_GetModulePassword. */ PL_strfree(pwdata.data); } + if (email) { + PL_strfree(email); + } /* Open the batch command file. * diff --git a/security/nss/cmd/certutil/keystuff.c b/security/nss/cmd/certutil/keystuff.c index c62e5637e1f5..1bc6cab4ad51 100644 --- a/security/nss/cmd/certutil/keystuff.c +++ b/security/nss/cmd/certutil/keystuff.c @@ -42,7 +42,7 @@ const SEC_ASN1Template SECKEY_PQGParamsTemplate[] = { { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,prime) }, { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,subPrime) }, { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,base) }, - { 0, } + { 0 } }; /* returns 0 for success, -1 for failure (EOF encountered) */ diff --git a/security/nss/cmd/checkcert/checkcert.c b/security/nss/cmd/checkcert/checkcert.c deleted file mode 100644 index 235451c39263..000000000000 --- a/security/nss/cmd/checkcert/checkcert.c +++ /dev/null @@ -1,575 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "secutil.h" -#include "plgetopt.h" -#include "cert.h" -#include "secoid.h" -#include "cryptohi.h" - -/* maximum supported modulus length in bits (indicate problem if over this) */ -#define MAX_MODULUS (1024) - - -static void Usage(char *progName) -{ - fprintf(stderr, "Usage: %s [aAvf] [certtocheck] [issuingcert]\n", - progName); - fprintf(stderr, "%-20s Cert to check is base64 encoded\n", - "-a"); - fprintf(stderr, "%-20s Issuer's cert is base64 encoded\n", - "-A"); - fprintf(stderr, "%-20s Verbose (indicate decoding progress etc.)\n", - "-v"); - fprintf(stderr, "%-20s Force sanity checks even if pretty print fails.\n", - "-f"); - fprintf(stderr, "%-20s Define an output file to use (default is stdout)\n", - "-o output"); - fprintf(stderr, "%-20s Specify the input type (no default)\n", - "-t type"); - exit(-1); -} - - -/* - * Check integer field named fieldName, printing out results and - * returning the length of the integer in bits - */ - -static -int checkInteger(SECItem *intItem, char *fieldName, int verbose) -{ - int len, bitlen; - if (verbose) { - printf("Checking %s\n", fieldName); - } - - len = intItem->len; - - if (len && (intItem->data[0] & 0x80)) { - printf("PROBLEM: %s is NEGATIVE 2's-complement integer.\n", - fieldName); - } - - - /* calculate bit length and check for unnecessary leading zeros */ - bitlen = len << 3; - if (len > 1 && intItem->data[0] == 0) { - /* leading zero byte(s) */ - if (!(intItem->data[1] & 0x80)) { - printf("PROBLEM: %s has unneeded leading zeros. Violates DER.\n", - fieldName); - } - /* strip leading zeros in length calculation */ - { - int i=0; - while (bitlen > 8 && intItem->data[i] == 0) { - bitlen -= 8; - i++; - } - } - } - return bitlen; -} - - - - -static -void checkName(CERTName *n, char *fieldName, int verbose) -{ - char *v=0; - if (verbose) { - printf("Checking %s\n", fieldName); - } - - v = CERT_GetCountryName(n); - if (!v) { - printf("PROBLEM: %s lacks Country Name (C)\n", - fieldName); - } - PORT_Free(v); - - v = CERT_GetOrgName(n); - if (!v) { - printf("PROBLEM: %s lacks Organization Name (O)\n", - fieldName); - } - PORT_Free(v); - - v = CERT_GetOrgUnitName(n); - if (!v) { - printf("WARNING: %s lacks Organization Unit Name (OU)\n", - fieldName); - } - PORT_Free(v); - - v = CERT_GetCommonName(n); - if (!v) { - printf("PROBLEM: %s lacks Common Name (CN)\n", - fieldName); - } - PORT_Free(v); -} - - -static -SECStatus -OurVerifyData(unsigned char *buf, int len, SECKEYPublicKey *key, - SECItem *sig, SECAlgorithmID *sigAlgorithm) -{ - SECStatus rv; - VFYContext *cx; - SECOidData *sigAlgOid, *oiddata; - SECOidTag hashAlgTag; - int showDigestOid=0; - - cx = VFY_CreateContextWithAlgorithmID(key, sig, sigAlgorithm, &hashAlgTag, - NULL); - if (cx == NULL) - return SECFailure; - - sigAlgOid = SECOID_FindOID(&sigAlgorithm->algorithm); - if (sigAlgOid == 0) - return SECFailure; - - if (showDigestOid) { - oiddata = SECOID_FindOIDByTag(hashAlgTag); - if ( oiddata ) { - printf("PROBLEM: (cont) Digest OID is %s\n", oiddata->desc); - } else { - SECU_PrintAsHex(stdout, - &oiddata->oid, "PROBLEM: UNKNOWN OID", 0); - } - } - - rv = VFY_Begin(cx); - if (rv == SECSuccess) { - rv = VFY_Update(cx, buf, len); - if (rv == SECSuccess) - rv = VFY_End(cx); - } - - VFY_DestroyContext(cx, PR_TRUE); - return rv; -} - - - -static -SECStatus -OurVerifySignedData(CERTSignedData *sd, CERTCertificate *cert) -{ - SECItem sig; - SECKEYPublicKey *pubKey = 0; - SECStatus rv; - - /* check the certificate's validity */ - rv = CERT_CertTimesValid(cert); - if ( rv ) { - return(SECFailure); - } - - /* get cert's public key */ - pubKey = CERT_ExtractPublicKey(cert); - if ( !pubKey ) { - return(SECFailure); - } - - /* check the signature */ - sig = sd->signature; - DER_ConvertBitString(&sig); - rv = OurVerifyData(sd->data.data, sd->data.len, pubKey, &sig, - &sd->signatureAlgorithm); - - SECKEY_DestroyPublicKey(pubKey); - - if ( rv ) { - return(SECFailure); - } - - return(SECSuccess); -} - - - - -static -CERTCertificate *createEmptyCertificate(void) -{ - PLArenaPool *arena = 0; - CERTCertificate *c = 0; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - return 0; - } - - - c = (CERTCertificate *) PORT_ArenaZAlloc(arena, sizeof(CERTCertificate)); - - if (c) { - c->referenceCount = 1; - c->arena = arena; - } else { - PORT_FreeArena(arena,PR_TRUE); - } - - return c; -} - - -int main(int argc, char **argv) -{ - int verbose=0, force=0; - int ascii=0, issuerAscii=0; - char *progName=0; - PRFileDesc *inFile=0, *issuerCertFile=0; - SECItem derCert, derIssuerCert; - PLArenaPool *arena=0; - CERTSignedData *signedData=0; - CERTCertificate *cert=0, *issuerCert=0; - SECKEYPublicKey *rsapubkey=0; - SECAlgorithmID md5WithRSAEncryption, md2WithRSAEncryption; - SECAlgorithmID sha1WithRSAEncryption, rsaEncryption; - SECItem spk; - int selfSigned=0; - int invalid=0; - char *inFileName = NULL, *issuerCertFileName = NULL; - PLOptState *optstate; - PLOptStatus status; - SECStatus rv; - - PORT_Memset(&md5WithRSAEncryption, 0, sizeof(md5WithRSAEncryption)); - PORT_Memset(&md2WithRSAEncryption, 0, sizeof(md2WithRSAEncryption)); - PORT_Memset(&sha1WithRSAEncryption, 0, sizeof(sha1WithRSAEncryption)); - PORT_Memset(&rsaEncryption, 0, sizeof(rsaEncryption)); - - progName = strrchr(argv[0], '/'); - progName = progName ? progName+1 : argv[0]; - - optstate = PL_CreateOptState(argc, argv, "aAvf"); - while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { - switch (optstate->option) { - case 'v': - verbose = 1; - break; - - case 'f': - force = 1; - break; - - case 'a': - ascii = 1; - break; - - case 'A': - issuerAscii = 1; - break; - - case '\0': - if (!inFileName) - inFileName = PL_strdup(optstate->value); - else if (!issuerCertFileName) - issuerCertFileName = PL_strdup(optstate->value); - else - Usage(progName); - break; - } - } - - if (!inFileName || !issuerCertFileName || status == PL_OPT_BAD) { - /* insufficient or excess args */ - Usage(progName); - } - - inFile = PR_Open(inFileName, PR_RDONLY, 0); - if (!inFile) { - fprintf(stderr, "%s: unable to open \"%s\" for reading\n", - progName, inFileName); - exit(1); - } - - issuerCertFile = PR_Open(issuerCertFileName, PR_RDONLY, 0); - if (!issuerCertFile) { - fprintf(stderr, "%s: unable to open \"%s\" for reading\n", - progName, issuerCertFileName); - exit(1); - } - - if (SECU_ReadDERFromFile(&derCert, inFile, ascii, PR_FALSE) != SECSuccess) { - printf("Couldn't read input certificate as DER binary or base64\n"); - exit(1); - } - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == 0) { - fprintf(stderr,"%s: can't allocate scratch arena!", progName); - exit(1); - } - - if (issuerCertFile) { - CERTSignedData *issuerCertSD=0; - if (SECU_ReadDERFromFile(&derIssuerCert, issuerCertFile, issuerAscii, - PR_FALSE) != SECSuccess) { - printf("Couldn't read issuer certificate as DER binary or base64.\n"); - exit(1); - } - issuerCertSD = PORT_ArenaZNew(arena, CERTSignedData); - if (!issuerCertSD) { - fprintf(stderr,"%s: can't allocate issuer signed data!", progName); - exit(1); - } - rv = SEC_ASN1DecodeItem(arena, issuerCertSD, - SEC_ASN1_GET(CERT_SignedDataTemplate), - &derIssuerCert); - if (rv) { - fprintf(stderr, "%s: Issuer cert isn't X509 SIGNED Data?\n", - progName); - exit(1); - } - issuerCert = createEmptyCertificate(); - if (!issuerCert) { - printf("%s: can't allocate space for issuer cert.", progName); - exit(1); - } - rv = SEC_ASN1DecodeItem(arena, issuerCert, - SEC_ASN1_GET(CERT_CertificateTemplate), - &issuerCertSD->data); - if (rv) { - printf("%s: Does not appear to be an X509 Certificate.\n", - progName); - exit(1); - } - } - - signedData = PORT_ArenaZNew(arena,CERTSignedData); - if (!signedData) { - fprintf(stderr,"%s: can't allocate signedData!", progName); - exit(1); - } - - rv = SEC_ASN1DecodeItem(arena, signedData, - SEC_ASN1_GET(CERT_SignedDataTemplate), - &derCert); - if (rv) { - fprintf(stderr, "%s: Does not appear to be X509 SIGNED Data.\n", - progName); - exit(1); - } - - if (verbose) { - printf("Decoded ok as X509 SIGNED data.\n"); - } - - cert = createEmptyCertificate(); - if (!cert) { - fprintf(stderr, "%s: can't allocate cert", progName); - exit(1); - } - - rv = SEC_ASN1DecodeItem(arena, cert, - SEC_ASN1_GET(CERT_CertificateTemplate), - &signedData->data); - if (rv) { - fprintf(stderr, "%s: Does not appear to be an X509 Certificate.\n", - progName); - exit(1); - } - - - if (verbose) { - printf("Decoded ok as an X509 certificate.\n"); - } - - SECU_RegisterDynamicOids(); - rv = SECU_PrintSignedData(stdout, &derCert, "Certificate", 0, - (SECU_PPFunc)SECU_PrintCertificate); - - if (rv) { - fprintf(stderr, "%s: Unable to pretty print cert. Error: %d\n", - progName, PORT_GetError()); - if (!force) { - exit(1); - } - } - - - /* Do various checks on the cert */ - - printf("\n"); - - /* Check algorithms */ - rv = SECOID_SetAlgorithmID(arena, &md5WithRSAEncryption, - SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, NULL); - if (rv) { - fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION.\n", - progName); - exit(1); - } - - rv = SECOID_SetAlgorithmID(arena, &md2WithRSAEncryption, - SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION, NULL); - if (rv) { - fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION.\n", - progName); - exit(1); - } - - rv = SECOID_SetAlgorithmID(arena, &sha1WithRSAEncryption, - SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION, NULL); - if (rv) { - fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION.\n", - progName); - exit(1); - } - - rv = SECOID_SetAlgorithmID(arena, &rsaEncryption, - SEC_OID_PKCS1_RSA_ENCRYPTION, NULL); - if (rv) { - fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_RSA_ENCRYPTION.\n", - progName); - exit(1); - } - - { - int isMD5RSA = (SECOID_CompareAlgorithmID(&cert->signature, - &md5WithRSAEncryption) == 0); - int isMD2RSA = (SECOID_CompareAlgorithmID(&cert->signature, - &md2WithRSAEncryption) == 0); - int isSHA1RSA = (SECOID_CompareAlgorithmID(&cert->signature, - &sha1WithRSAEncryption) == 0); - - if (verbose) { - printf("\nDoing algorithm checks.\n"); - } - - if (!(isMD5RSA || isMD2RSA || isSHA1RSA)) { - printf("PROBLEM: Signature not PKCS1 MD5, MD2, or SHA1 + RSA.\n"); - } else if (!isMD5RSA) { - printf("WARNING: Signature not PKCS1 MD5 with RSA Encryption\n"); - } - - if (SECOID_CompareAlgorithmID(&cert->signature, - &signedData->signatureAlgorithm)) { - printf("PROBLEM: Algorithm in sig and certInfo don't match.\n"); - } - } - - if (SECOID_CompareAlgorithmID(&cert->subjectPublicKeyInfo.algorithm, - &rsaEncryption)) { - printf("PROBLEM: Public key algorithm is not PKCS1 RSA Encryption.\n"); - } - - /* Check further public key properties */ - spk = cert->subjectPublicKeyInfo.subjectPublicKey; - DER_ConvertBitString(&spk); - - if (verbose) { - printf("\nsubjectPublicKey DER\n"); - rv = DER_PrettyPrint(stdout, &spk, PR_FALSE); - printf("\n"); - } - - rsapubkey = (SECKEYPublicKey *) - PORT_ArenaZAlloc(arena,sizeof(SECKEYPublicKey)); - if (!rsapubkey) { - fprintf(stderr, "%s: rsapubkey allocation failed.\n", progName); - exit(1); - } - - rv = SEC_ASN1DecodeItem(arena, rsapubkey, - SEC_ASN1_GET(SECKEY_RSAPublicKeyTemplate), &spk); - if (rv) { - printf("PROBLEM: subjectPublicKey is not a DER PKCS1 RSAPublicKey.\n"); - } else { - int mlen; - int pubexp; - if (verbose) { - printf("Decoded RSA Public Key ok. Doing key checks.\n"); - } - PORT_Assert(rsapubkey->keyType == rsaKey); /* XXX RSA */ - mlen = checkInteger(&rsapubkey->u.rsa.modulus, "Modulus", verbose); - printf("INFO: Public Key modulus length in bits: %d\n", mlen); - if (mlen > MAX_MODULUS) { - printf("PROBLEM: Modulus length exceeds %d bits.\n", - MAX_MODULUS); - } - if (mlen < 512) { - printf("WARNING: Short modulus.\n"); - } - if (mlen != (1 << (ffs(mlen)-1))) { - printf("WARNING: Unusual modulus length (not a power of two).\n"); - } - checkInteger(&rsapubkey->u.rsa.publicExponent, "Public Exponent", - verbose); - pubexp = DER_GetInteger(&rsapubkey->u.rsa.publicExponent); - if (pubexp != 17 && pubexp != 3 && pubexp != 65537) { - printf("WARNING: Public exponent not any of: 3, 17, 65537\n"); - } - } - - - /* Name checks */ - checkName(&cert->issuer, "Issuer Name", verbose); - checkName(&cert->subject, "Subject Name", verbose); - - if (issuerCert) { - SECComparison c = - CERT_CompareName(&cert->issuer, &issuerCert->subject); - if (c) { - printf("PROBLEM: Issuer Name and Subject in Issuing Cert differ\n"); - } - } - - /* Check if self-signed */ - selfSigned = (CERT_CompareName(&cert->issuer, &cert->subject) == 0); - if (selfSigned) { - printf("INFO: Certificate is self signed.\n"); - } else { - printf("INFO: Certificate is NOT self-signed.\n"); - } - - - /* Validity time check */ - if (CERT_CertTimesValid(cert) == SECSuccess) { - printf("INFO: Inside validity period of certificate.\n"); - } else { - printf("PROBLEM: Not in validity period of certificate.\n"); - invalid = 1; - } - - /* Signature check if self-signed */ - if (selfSigned && !invalid) { - if (rsapubkey->u.rsa.modulus.len) { - SECStatus ver; - if (verbose) { - printf("Checking self signature.\n"); - } - ver = OurVerifySignedData(signedData, cert); - if (ver != SECSuccess) { - printf("PROBLEM: Verification of self-signature failed!\n"); - } else { - printf("INFO: Self-signature verifies ok.\n"); - } - } else { - printf("INFO: Not checking signature due to key problems.\n"); - } - } else if (!selfSigned && !invalid && issuerCert) { - SECStatus ver; - ver = OurVerifySignedData(signedData, issuerCert); - if (ver != SECSuccess) { - printf("PROBLEM: Verification of issuer's signature failed!\n"); - } else { - printf("INFO: Issuer's signature verifies ok.\n"); - } - } else { - printf("INFO: Not checking signature.\n"); - } - - return 0; -} - - - diff --git a/security/nss/cmd/checkcert/manifest.mn b/security/nss/cmd/checkcert/manifest.mn deleted file mode 100644 index d796b64d8834..000000000000 --- a/security/nss/cmd/checkcert/manifest.mn +++ /dev/null @@ -1,19 +0,0 @@ -# -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -CORE_DEPTH = ../.. - -# MODULE public and private header directories are implicitly REQUIRED. -MODULE = nss - -# This next line is used by .mk files -# and gets translated into $LINCS in manifest.mnw -REQUIRES = seccmd dbm - -DEFINES = -DNSPR20 - -CSRCS = checkcert.c - -PROGRAM = checkcert diff --git a/security/nss/cmd/fipstest/fipstest.c b/security/nss/cmd/fipstest/fipstest.c index 6a2cf2cc6bba..b5a5644bb829 100644 --- a/security/nss/cmd/fipstest/fipstest.c +++ b/security/nss/cmd/fipstest/fipstest.c @@ -5344,9 +5344,9 @@ rsa_siggen_test(char *reqfn) NSSLOWKEYPublicKey * rsa_public_key; NSSLOWKEYPrivateKey * rsa_private_key; NSSLOWKEYPrivateKey low_RSA_private_key = { NULL, - NSSLOWKEYRSAKey, }; + NSSLOWKEYRSAKey }; NSSLOWKEYPublicKey low_RSA_public_key = { NULL, - NSSLOWKEYRSAKey, }; + NSSLOWKEYRSAKey }; low_RSA_private_key.u.rsa = *rsaBlapiPrivKey; low_RSA_public_key.u.rsa = *rsaBlapiPublicKey; @@ -5610,7 +5610,7 @@ rsa_sigver_test(char *reqfn) SECStatus rv = SECFailure; NSSLOWKEYPublicKey * rsa_public_key; NSSLOWKEYPublicKey low_RSA_public_key = { NULL, - NSSLOWKEYRSAKey, }; + NSSLOWKEYRSAKey }; /* convert to a low RSA public key */ low_RSA_public_key.u.rsa = rsaBlapiPublicKey; diff --git a/security/nss/cmd/lib/derprint.c b/security/nss/cmd/lib/derprint.c index 75811df3fb5d..28d14665ffa2 100644 --- a/security/nss/cmd/lib/derprint.c +++ b/security/nss/cmd/lib/derprint.c @@ -30,6 +30,13 @@ getInteger256(const unsigned char *data, unsigned int nb) val = (data[0] << 16) | (data[1] << 8) | data[2]; break; case 4: + /* If the most significant bit of data[0] is 1, val would be negative. + * Treat it as an error. + */ + if (data[0] & 0x80) { + PORT_SetError(SEC_ERROR_BAD_DER); + return -1; + } val = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; break; default: @@ -232,6 +239,10 @@ prettyPrintObjectID(FILE *out, const unsigned char *data, if (rv < 0) return rv; + if (len == 0) { + PORT_SetError(SEC_ERROR_BAD_DER); + return -1; + } val = data[0]; i = val % 40; val = val / 40; @@ -282,24 +293,17 @@ prettyPrintObjectID(FILE *out, const unsigned char *data, } } - /* - * Finally, on a new line, print the raw bytes (if requested). - */ - if (raw) { - rv = prettyNewline(out); - if (rv < 0) { - PORT_SetError(SEC_ERROR_IO); - return rv; - } + rv = prettyNewline(out); + if (rv < 0) + return rv; - for (i = 0; i < len; i++) { - rv = prettyPrintByte(out, *data++, level); - if (rv < 0) - return rv; - } + if (raw) { + rv = prettyPrintLeaf(out, data, len, level); + if (rv < 0) + return rv; } - return prettyNewline(out); + return 0; } static char *prettyTagType [32] = { @@ -423,6 +427,7 @@ prettyPrintLength(FILE *out, const unsigned char *data, const unsigned char *end *indefinitep = PR_FALSE; lbyte = *data++; + lenLen = 1; if (lbyte >= 0x80) { /* Multibyte length */ unsigned nb = (unsigned) (lbyte & 0x7f); @@ -444,7 +449,7 @@ prettyPrintLength(FILE *out, const unsigned char *data, const unsigned char *end *lenp = 0; *indefinitep = PR_TRUE; } - lenLen = nb + 1; + lenLen += nb; if (raw) { unsigned int i; @@ -459,7 +464,6 @@ prettyPrintLength(FILE *out, const unsigned char *data, const unsigned char *end } } else { *lenp = lbyte; - lenLen = 1; if (raw) { rv = prettyPrintByte(out, lbyte, lv); if (rv < 0) diff --git a/security/nss/cmd/lib/secutil.c b/security/nss/cmd/lib/secutil.c index 92f64f75c286..e79817b31964 100644 --- a/security/nss/cmd/lib/secutil.c +++ b/security/nss/cmd/lib/secutil.c @@ -420,6 +420,9 @@ SECU_DefaultSSLDir(void) if (!dir) return NULL; + if (strlen(dir) >= PR_ARRAY_SIZE(sslDir)) { + return NULL; + } sprintf(sslDir, "%s", dir); if (sslDir[strlen(sslDir)-1] == '/') @@ -3300,6 +3303,7 @@ SECU_displayVerifyLog(FILE *outfile, CERTVerifyLog *log, errstr = "[unknown usage]."; break; } + break; case SEC_ERROR_INADEQUATE_CERT_TYPE: flags = (unsigned int)((char *)node->arg - (char *)NULL); switch (flags) { @@ -3326,6 +3330,7 @@ SECU_displayVerifyLog(FILE *outfile, CERTVerifyLog *log, errstr = "[unknown usage]."; break; } + break; case SEC_ERROR_UNKNOWN_ISSUER: case SEC_ERROR_UNTRUSTED_ISSUER: case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: diff --git a/security/nss/cmd/libpkix/pkixutil/pkixutil.c b/security/nss/cmd/libpkix/pkixutil/pkixutil.c index 0cd832ac6bc6..8deb883e3c5e 100644 --- a/security/nss/cmd/libpkix/pkixutil/pkixutil.c +++ b/security/nss/cmd/libpkix/pkixutil/pkixutil.c @@ -154,7 +154,7 @@ testFunctionRef testFnRefTable[] = { {"test_mutex3", test_mutex3}, {"test_object", test_object}, {"test_oid", test_oid}, -/* {"test_rwlock", test_rwlock, }*/ +/* {"test_rwlock", test_rwlock }*/ {"test_string", test_string}, {"test_string2", test_string2}, {"build_chain", build_chain}, diff --git a/security/nss/cmd/makepqg/makepqg.c b/security/nss/cmd/makepqg/makepqg.c index 36e2aab5cdb9..01d190d2cfb6 100644 --- a/security/nss/cmd/makepqg/makepqg.c +++ b/security/nss/cmd/makepqg/makepqg.c @@ -28,7 +28,7 @@ const SEC_ASN1Template seckey_PQGParamsTemplate[] = { { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,prime) }, { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,subPrime) }, { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,base) }, - { 0, } + { 0 } }; diff --git a/security/nss/cmd/manifest.mn b/security/nss/cmd/manifest.mn index 1c27f171bfe5..deedd21c8e54 100644 --- a/security/nss/cmd/manifest.mn +++ b/security/nss/cmd/manifest.mn @@ -6,16 +6,36 @@ DEPTH = .. # MODULE = seccmd -REQUIRES = nss nspr libdbm +SOFTOKEN_SRCDIRS= +NSS_SRCDIRS= +LIB_SRCDIRS= -DIRS = lib \ +ifdef NSS_BUILD_UTIL_ONLY +REQUIRES = nspr +else +REQUIRES = nss nspr libdbm +LIB_SRCDIRS = \ + lib \ + $(NULL) +endif + +ifndef NSS_BUILD_UTIL_ONLY +SOFTOKEN_SRCDIRS = \ + $(BLTEST_SRCDIR) \ + $(FIPSTEST_SRCDIR) \ + $(LOWHASHTEST_SRCDIR) \ + $(SHLIBSIGN_SRCDIR) \ + $(NULL) +endif + +ifndef NSS_BUILD_SOFTOKEN_ONLY +ifndef NSS_BUILD_UTIL_ONLY +NSS_SRCDIRS = \ addbuiltin \ atob \ - $(BLTEST_SRCDIR) \ btoa \ certcgi \ certutil \ - checkcert \ chktest \ crlutil \ crmftest \ @@ -23,8 +43,6 @@ DIRS = lib \ derdump \ digest \ httpserv \ - $(FIPSTEST_SRCDIR) \ - $(LOWHASHTEST_SRCDIR) \ listsuites \ makepqg \ multinit \ @@ -47,7 +65,6 @@ DIRS = lib \ selfserv \ signtool \ signver \ - $(SHLIBSIGN_SRCDIR) \ smimetools \ ssltap \ strsclnt \ @@ -58,6 +75,13 @@ DIRS = lib \ vfyserv \ modutil \ $(NULL) +endif +endif + +DIRS = \ + $(LIB_SRCDIRS) \ + $(SOFTOKEN_SRCDIRS) \ + $(NSS_SRCDIRS) TEMPORARILY_DONT_BUILD = \ $(NULL) diff --git a/security/nss/cmd/modutil/install-ds.c b/security/nss/cmd/modutil/install-ds.c index 2ae376dd6962..e0cb58eead66 100644 --- a/security/nss/cmd/modutil/install-ds.c +++ b/security/nss/cmd/modutil/install-ds.c @@ -193,8 +193,7 @@ Pk11Install_File_Generate(Pk11Install_File* _this, goto loser; } _this->relativePath = PR_Strdup(subval->string); - Pk11Install_ListIter_delete(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); /* Absolute directory */ } else if( !PORT_Strcasecmp(subpair->key, ABSOLUTE_DIR_STRING)) { @@ -206,8 +205,7 @@ Pk11Install_File_Generate(Pk11Install_File* _this, goto loser; } _this->absolutePath = PR_Strdup(subval->string); - Pk11Install_ListIter_delete(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); /* file permissions */ } else if( !PORT_Strcasecmp(subpair->key, @@ -227,8 +225,7 @@ Pk11Install_File_Generate(Pk11Install_File* _this, goto loser; } gotPerms = PR_TRUE; - Pk11Install_ListIter_delete(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); } } else { if(!PORT_Strcasecmp(val->string, EXECUTABLE_STRING)) { @@ -260,12 +257,10 @@ Pk11Install_File_Generate(Pk11Install_File* _this, loser: if(iter) { - Pk11Install_ListIter_delete(iter); - PR_Free(iter); + Pk11Install_ListIter_delete(&iter); } if(subiter) { - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); + Pk11Install_ListIter_delete(&subiter); } return errStr; } @@ -636,12 +631,15 @@ Pk11Install_PlatformName_GetVerString(Pk11Install_PlatformName* _this) void Pk11Install_PlatformName_Print(Pk11Install_PlatformName* _this, int pad) { + char *str = NULL; PAD(pad); printf("OS: %s\n", _this->OS ? _this->OS : ""); PAD(pad); printf("Digits: "); if(_this->numDigits == 0) { printf("None\n"); } else { - printf("%s\n", Pk11Install_PlatformName_GetVerString(_this)); + str = Pk11Install_PlatformName_GetVerString(_this); + printf("%s\n", str); + PR_Free(str); } PAD(pad); printf("arch: %s\n", _this->arch ? _this->arch : ""); } @@ -770,9 +768,7 @@ Pk11Install_Platform_Generate(Pk11Install_Platform* _this, goto loser; } _this->moduleFile = PR_Strdup(subval->string); - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); gotModuleFile = PR_TRUE; } else if(!PORT_Strcasecmp(subpair->key, MODULE_NAME_STRING)){ if(gotModuleName) { @@ -788,9 +784,7 @@ Pk11Install_Platform_Generate(Pk11Install_Platform* _this, goto loser; } _this->moduleName = PR_Strdup(subval->string); - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); gotModuleName = PR_TRUE; } else if(!PORT_Strcasecmp(subpair->key, MECH_FLAGS_STRING)) { endptr=NULL; @@ -813,9 +807,7 @@ Pk11Install_Platform_Generate(Pk11Install_Platform* _this, Pk11Install_PlatformName_GetString(&_this->name)); goto loser; } - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); - subiter=NULL; + Pk11Install_ListIter_delete(&subiter); gotMech = PR_TRUE; } else if(!PORT_Strcasecmp(subpair->key,CIPHER_FLAGS_STRING)) { endptr=NULL; @@ -838,9 +830,7 @@ Pk11Install_Platform_Generate(Pk11Install_Platform* _this, Pk11Install_PlatformName_GetString(&_this->name)); goto loser; } - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); - subiter=NULL; + Pk11Install_ListIter_delete(&subiter); gotCipher = PR_TRUE; } else if(!PORT_Strcasecmp(subpair->key, FILES_STRING)) { if(gotFiles) { @@ -1089,9 +1079,7 @@ Pk11Install_Info_Generate(Pk11Install_Info* _this, } } } - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); } else if(!PORT_Strcasecmp(pair->key, PLATFORMS_STRING)) { subiter = Pk11Install_ListIter_new(pair->list); _this->numPlatforms = pair->list->numPairs; @@ -1109,9 +1097,7 @@ Pk11Install_Info_Generate(Pk11Install_Info* _this, } } } - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); } } } @@ -1192,14 +1178,10 @@ Pk11Install_Info_Generate(Pk11Install_Info* _this, loser: if(iter) { - Pk11Install_ListIter_delete(iter); - PR_Free(iter); - iter = NULL; + Pk11Install_ListIter_delete(&iter); } if(subiter) { - Pk11Install_ListIter_delete(subiter); - PR_Free(subiter); - subiter = NULL; + Pk11Install_ListIter_delete(&subiter); } return errStr; } @@ -1348,10 +1330,12 @@ Pk11Install_ListIter_new(const Pk11Install_ValueList *_list) /****************************************************************************/ void -Pk11Install_ListIter_delete(Pk11Install_ListIter* _this) +Pk11Install_ListIter_delete(Pk11Install_ListIter** _this) { - _this->list=NULL; - _this->current=NULL; + (*_this)->list=NULL; + (*_this)->current=NULL; + PR_Free(*_this); + *_this=NULL; } /****************************************************************************/ diff --git a/security/nss/cmd/modutil/install-ds.h b/security/nss/cmd/modutil/install-ds.h index 3a3afb31494b..bb3b28fe3749 100644 --- a/security/nss/cmd/modutil/install-ds.h +++ b/security/nss/cmd/modutil/install-ds.h @@ -124,7 +124,7 @@ Pk11Install_ListIter_init(Pk11Install_ListIter* _this); Pk11Install_ListIter* Pk11Install_ListIter_new(const Pk11Install_ValueList* _list); void -Pk11Install_ListIter_delete(Pk11Install_ListIter* _this); +Pk11Install_ListIter_delete(Pk11Install_ListIter** _this); void Pk11Install_ListIter_reset(Pk11Install_ListIter* _this); Pk11Install_Value* diff --git a/security/nss/cmd/pk1sign/pk1sign.c b/security/nss/cmd/pk1sign/pk1sign.c index 5f58f8c7816e..29019bdcb974 100644 --- a/security/nss/cmd/pk1sign/pk1sign.c +++ b/security/nss/cmd/pk1sign/pk1sign.c @@ -44,8 +44,8 @@ SEC_ASN1Template CERTSignatureDataTemplate[] = offsetof(CERTSignedData,signatureAlgorithm), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_BIT_STRING, - offsetof(CERTSignedData,signature), }, - { 0, } + offsetof(CERTSignedData,signature) }, + { 0 } }; diff --git a/security/nss/cmd/platlibs.mk b/security/nss/cmd/platlibs.mk index 812a27fdc5c1..bff26b523eea 100644 --- a/security/nss/cmd/platlibs.mk +++ b/security/nss/cmd/platlibs.mk @@ -51,6 +51,7 @@ EXTRA_SHARED_LIBS += \ $(NULL) endif +ifndef NSS_BUILD_SOFTOKEN_ONLY PKIXLIB = \ $(DIST)/lib/$(LIB_PREFIX)pkixtop.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)pkixutil.$(LIB_SUFFIX) \ @@ -64,35 +65,100 @@ PKIXLIB = \ $(DIST)/lib/$(LIB_PREFIX)pkixtop.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)pkixresults.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)pkixcertsel.$(LIB_SUFFIX) +endif -# can't do this in manifest.mn because OS_ARCH isn't defined there. +NSS_LIBS_1= +SECTOOL_LIB= +NSS_LIBS_2= +NSS_LIBS_3= +NSS_LIBS_4= + +ifneq ($(NSS_BUILD_UTIL_ONLY),1) +SECTOOL_LIB = \ + $(DIST)/lib/$(LIB_PREFIX)sectool.$(LIB_SUFFIX) \ + $(NULL) +else +SECTOOL_LIB = \ + $(NULL) +endif + +ifneq ($(NSS_BUILD_SOFTOKEN_ONLY),1) ifeq ($(OS_ARCH), WINNT) - -EXTRA_LIBS += \ +# breakdown for windows +NSS_LIBS_1 = \ $(DIST)/lib/$(LIB_PREFIX)smime.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)nss.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)sectool.$(LIB_SUFFIX) \ + $(NULL) +NSS_LIBS_2 = \ $(DIST)/lib/$(LIB_PREFIX)pkcs12.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)pkcs7.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)certhi.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)cryptohi.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)pk11wrap.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)certdb.$(LIB_SUFFIX) \ - $(SOFTOKENLIB) \ - $(CRYPTOLIB) \ + $(NULL) +NSS_LIBS_3 = \ $(DIST)/lib/$(LIB_PREFIX)nsspki.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)nssdev.$(LIB_SUFFIX) \ $(DIST)/lib/$(LIB_PREFIX)nssb.$(LIB_SUFFIX) \ $(PKIXLIB) \ $(DBMLIB) \ + $(NULL) +NSS_LIBS_4 = \ $(SQLITE_LIB_DIR)/$(LIB_PREFIX)$(SQLITE_LIB_NAME).$(LIB_SUFFIX) \ $(NSSUTIL_LIB_DIR)/$(LIB_PREFIX)nssutil3.$(LIB_SUFFIX) \ $(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)plc4.$(LIB_SUFFIX) \ $(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)plds4.$(LIB_SUFFIX) \ $(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)nspr4.$(LIB_SUFFIX) \ $(NULL) +else +# breakdown for others +NSS_LIBS_1 = \ + $(DIST)/lib/$(LIB_PREFIX)smime.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)nss.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \ + $(NULL) +SECTOOL_LIB = \ + $(DIST)/lib/$(LIB_PREFIX)sectool.$(LIB_SUFFIX) \ + $(NULL) +NSS_LIBS_2 = \ + $(DIST)/lib/$(LIB_PREFIX)pkcs12.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)pkcs7.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)certhi.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)cryptohi.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)pk11wrap.$(LIB_SUFFIX) \ + $(NULL) +NSS_LIBS_3 = \ + $(DIST)/lib/$(LIB_PREFIX)certdb.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)nsspki.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)nssdev.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)nssb.$(LIB_SUFFIX) \ + $(NULL) +NSS_LIBS_4 = \ + $(DBMLIB) \ + $(PKIXLIB) \ + $(DIST)/lib/$(LIB_PREFIX)nss.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)pk11wrap.$(LIB_SUFFIX) \ + $(DIST)/lib/$(LIB_PREFIX)certhi.$(LIB_SUFFIX) \ + $(NULL) +endif +endif + +# can't do this in manifest.mn because OS_ARCH isn't defined there. +ifeq ($(OS_ARCH), WINNT) + +EXTRA_LIBS += \ + $(NSS_LIBS_1) \ + $(SECTOOL_LIB) \ + $(NSS_LIBS_2) \ + $(SOFTOKENLIB) \ + $(CRYPTOLIB) \ + $(NSS_LIBS_3) \ + $(NSS_LIBS_4) \ + $(NULL) # $(PROGRAM) has NO explicit dependencies on $(OS_LIBS) #OS_LIBS += \ @@ -102,30 +168,13 @@ EXTRA_LIBS += \ else EXTRA_LIBS += \ - $(DIST)/lib/$(LIB_PREFIX)smime.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)nss.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)sectool.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)pkcs12.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)pkcs7.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)certhi.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)pk11wrap.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)cryptohi.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)certhi.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)nsspki.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)pk11wrap.$(LIB_SUFFIX) \ + $(NSS_LIBS_1) \ + $(SECTOOL_LIB) \ + $(NSS_LIBS_2) \ $(SOFTOKENLIB) \ - $(DIST)/lib/$(LIB_PREFIX)certdb.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)nsspki.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)nssdev.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)nssb.$(LIB_SUFFIX) \ + $(NSS_LIBS_3) \ $(CRYPTOLIB) \ - $(DBMLIB) \ - $(PKIXLIB) \ - $(DIST)/lib/$(LIB_PREFIX)nss.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)pk11wrap.$(LIB_SUFFIX) \ - $(DIST)/lib/$(LIB_PREFIX)certhi.$(LIB_SUFFIX) \ + $(NSS_LIBS_4) \ $(NULL) ifeq ($(OS_ARCH), AIX) diff --git a/security/nss/cmd/selfserv/selfserv.c b/security/nss/cmd/selfserv/selfserv.c index 549fda53ed6e..98986c31882b 100644 --- a/security/nss/cmd/selfserv/selfserv.c +++ b/security/nss/cmd/selfserv/selfserv.c @@ -225,6 +225,7 @@ PrintParameterUsage() "-W override default DHE server weak parameters support, 0: disable, 1: enable\n" "-c Restrict ciphers\n" "-Y prints cipher values allowed for parameter -c and exits\n" +"-G enables the extended master secret extension [RFC7627]\n" , stderr); } diff --git a/security/nss/cmd/tstclnt/tstclnt.c b/security/nss/cmd/tstclnt/tstclnt.c index 93a702220aff..4f4c4d9c48fc 100644 --- a/security/nss/cmd/tstclnt/tstclnt.c +++ b/security/nss/cmd/tstclnt/tstclnt.c @@ -110,6 +110,7 @@ void printSecurityInfo(PRFileDesc *fd) { CERTCertificate * cert; const SECItemArray *csa; + const SECItem *scts; SSL3Statistics * ssl3stats = SSL_GetStatistics(); SECStatus result; SSLChannelInfo channel; @@ -162,6 +163,11 @@ void printSecurityInfo(PRFileDesc *fd) fprintf(stderr, "Received %d Cert Status items (OCSP stapled data)\n", csa->len); } + scts = SSL_PeerSignedCertTimestamps(fd); + if (scts && scts->len) { + fprintf(stderr, "Received a Signed Certificate Timestamp of length" + " %u\n", scts->len); + } } void @@ -184,7 +190,7 @@ static void PrintUsageHeader(const char *progName) "Usage: %s -h host [-a 1st_hs_name ] [-a 2nd_hs_name ] [-p port]\n" "[-D | -d certdir] [-C] [-b | -R root-module] \n" "[-n nickname] [-Bafosvx] [-c ciphers] [-Y]\n" - "[-V [min-version]:[max-version]] [-K] [-T]\n" + "[-V [min-version]:[max-version]] [-K] [-T] [-U]\n" "[-r N] [-w passwd] [-W pwfile] [-q [-t seconds]]\n", progName); } @@ -232,6 +238,7 @@ static void PrintParameterUsage(void) fprintf(stderr, "%-20s Enable compression.\n", "-z"); fprintf(stderr, "%-20s Enable false start.\n", "-g"); fprintf(stderr, "%-20s Enable the cert_status extension (OCSP stapling).\n", "-T"); + fprintf(stderr, "%-20s Enable the signed_certificate_timestamp extension.\n", "-U"); fprintf(stderr, "%-20s Enable the extended master secret extension (session hash).\n", "-G"); fprintf(stderr, "%-20s Require fresh revocation info from side channel.\n" "%-20s -F once means: require for server cert only\n" @@ -250,6 +257,7 @@ static void PrintParameterUsage(void) fprintf(stderr, "%-20s Enforce using an IPv4 destination address\n", "-4"); fprintf(stderr, "%-20s Enforce using an IPv6 destination address\n", "-6"); fprintf(stderr, "%-20s (Options -4 and -6 cannot be combined.)\n", ""); + fprintf(stderr, "%-20s Enable the extended master secret extension [RFC7627]\n", "-G"); } static void Usage(const char *progName) @@ -920,6 +928,7 @@ int main(int argc, char **argv) int enableCompression = 0; int enableFalseStart = 0; int enableCertStatus = 0; + int enableSignedCertTimestamps = 0; int forceFallbackSCSV = 0; int enableExtendedMasterSecret = 0; PRSocketOptionData opt; @@ -970,7 +979,7 @@ int main(int argc, char **argv) SSL_VersionRangeGetSupported(ssl_variant_stream, &enabledVersions); optstate = PL_CreateOptState(argc, argv, - "46BCDFGKM:OR:STV:W:Ya:bc:d:fgh:m:n:op:qr:st:uvw:xz"); + "46BCDFGKM:OR:STUV:W:Ya:bc:d:fgh:m:n:op:qr:st:uvw:xz"); while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) { switch (optstate->option) { case '?': @@ -1023,6 +1032,8 @@ int main(int argc, char **argv) case 'T': enableCertStatus = 1; break; + case 'U': enableSignedCertTimestamps = 1; break; + case 'V': if (SECU_ParseSSLVersionRangeString(optstate->value, enabledVersions, enableSSL2, &enabledVersions, &enableSSL2) != SECSuccess) { @@ -1400,6 +1411,14 @@ int main(int argc, char **argv) } } + /* enable Signed Certificate Timestamps. */ + rv = SSL_OptionSet(s, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS, + enableSignedCertTimestamps); + if (rv != SECSuccess) { + SECU_PrintError(progName, "error enabling signed cert timestamps"); + return 1; + } + SSL_SetPKCS11PinArg(s, &pwdata); serverCertAuth.dbHandle = CERT_GetDefaultCertDB(); diff --git a/security/nss/coreconf/WIN32.mk b/security/nss/coreconf/WIN32.mk index 10e7b52c0800..7ca4c8c804d0 100644 --- a/security/nss/coreconf/WIN32.mk +++ b/security/nss/coreconf/WIN32.mk @@ -104,7 +104,7 @@ endif DLL_SUFFIX = dll ifdef NS_USE_GCC - OS_CFLAGS += -mwindows -mms-bitfields -Werror + OS_CFLAGS += -mwindows -mms-bitfields _GEN_IMPORT_LIB=-Wl,--out-implib,$(IMPORT_LIBRARY) DLLFLAGS += -mwindows -o $@ -shared -Wl,--export-all-symbols $(if $(IMPORT_LIBRARY),$(_GEN_IMPORT_LIB)) ifdef BUILD_OPT diff --git a/security/nss/coreconf/Werror.mk b/security/nss/coreconf/Werror.mk index 6e2588ceba8c..b5ef62551c6e 100644 --- a/security/nss/coreconf/Werror.mk +++ b/security/nss/coreconf/Werror.mk @@ -21,7 +21,7 @@ ifndef WARNING_CFLAGS # and fixing this would require rearchitecture WARNING_CFLAGS += -Qunused-arguments # -Wno-parentheses-equality : because clang warns about macro expansions - OS_CFLAGS += $(call disable_warning,parentheses-equality) + WARNING_CFLAGS += $(call disable_warning,parentheses-equality) ifdef BUILD_OPT # clang is unable to handle glib's expansion of strcmp and similar for optimized # builds, so ignore the resulting errors. diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep index 5182f75552c8..590d1bfaeee3 100644 --- a/security/nss/coreconf/coreconf.dep +++ b/security/nss/coreconf/coreconf.dep @@ -10,3 +10,4 @@ */ #error "Do not include this header file." + diff --git a/security/nss/external_tests/README b/security/nss/external_tests/README index 30e69d1ee559..75c452fd9343 100644 --- a/security/nss/external_tests/README +++ b/security/nss/external_tests/README @@ -2,8 +2,8 @@ GTest-based Unit Tests This directory contains GTest-based unit tests for NSS libssl. -These aren't built by default, because they require C++. -To build them, set ``NSS_BUILD_GTESTS=1'' +If your environment doesn't have C++ compiler suitable to build these tests, +you may disable them using ``NSS_DISABLE_GTESTS=1'' Once built, they are run as part of running ``test/all.sh'' You can run just the GTests by running ``tests/ssl_gtests/ssl_gtests.sh'' diff --git a/security/nss/external_tests/common/gtest.mk b/security/nss/external_tests/common/gtest.mk new file mode 100644 index 000000000000..f435e15ad67d --- /dev/null +++ b/security/nss/external_tests/common/gtest.mk @@ -0,0 +1,27 @@ +#! gmake +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +include ../../cmd/platlibs.mk +include ../../cmd/platrules.mk + +MKPROG = $(CCC) +MKSHLIB = $(CCC) $(DSO_LDOPTS) $(DARWIN_SDK_SHLIBFLAGS) + +ifeq (WINNT,$(OS_ARCH)) + # -EHsc because gtest has exception handlers + OS_CFLAGS += -EHsc -nologo + # http://www.suodenjoki.dk/us/archive/2010/min-max.htm + OS_CFLAGS += -DNOMINMAX + + # Linking to winsock to get htonl + OS_LIBS += Ws2_32.lib + + # On windows, we need to create the parent directory + # Needed because we include files from a subdirectory + MAKE_OBJDIR = $(INSTALL) -D $(dir $@) +else + CXXFLAGS += -std=c++0x +endif diff --git a/security/nss/external_tests/common/scoped_ptrs.h b/security/nss/external_tests/common/scoped_ptrs.h new file mode 100644 index 000000000000..374ad2a046c1 --- /dev/null +++ b/security/nss/external_tests/common/scoped_ptrs.h @@ -0,0 +1,45 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef scoped_ptrs_h__ +#define scoped_ptrs_h__ + +#include "keyhi.h" + +namespace nss_test { + +struct ScopedDelete { + void operator()(PK11SlotInfo* slot) { PK11_FreeSlot(slot); } + void operator()(SECItem* item) { SECITEM_FreeItem(item, true); } + void operator()(PK11SymKey* key) { PK11_FreeSymKey(key); } + void operator()(SECKEYPublicKey* key) { SECKEY_DestroyPublicKey(key); } + void operator()(SECKEYPrivateKey* key) { SECKEY_DestroyPrivateKey(key); } + void operator()(SECAlgorithmID* id) { SECOID_DestroyAlgorithmID(id, true); } + void operator()(CERTSubjectPublicKeyInfo* spki) { + SECKEY_DestroySubjectPublicKeyInfo(spki); + } +}; + +template +struct ScopedMaybeDelete { + void operator()(T* ptr) { if (ptr) { ScopedDelete del; del(ptr); } } +}; + +#define SCOPED(x) typedef std::unique_ptr > Scoped ## x + +SCOPED(PK11SlotInfo); +SCOPED(SECItem); +SCOPED(PK11SymKey); +SCOPED(SECKEYPublicKey); +SCOPED(SECKEYPrivateKey); +SCOPED(SECAlgorithmID); +SCOPED(CERTSubjectPublicKeyInfo); + +#undef SCOPED + +} // namespace nss_test + +#endif diff --git a/security/nss/external_tests/google_test/Makefile b/security/nss/external_tests/google_test/Makefile index c0b762f2698c..21fef55ac2f2 100644 --- a/security/nss/external_tests/google_test/Makefile +++ b/security/nss/external_tests/google_test/Makefile @@ -26,6 +26,7 @@ include $(CORE_DEPTH)/coreconf/config.mk # (4) Include "local" platform-dependent assignments (OPTIONAL). # ####################################################################### +include ../common/gtest.mk ####################################################################### # (5) Execute "global" rules. (OPTIONAL) # @@ -41,12 +42,3 @@ include $(CORE_DEPTH)/coreconf/rules.mk ####################################################################### # (7) Execute "local" rules. (OPTIONAL). # ####################################################################### - -MKSHLIB = $(CCC) $(DSO_LDOPTS) $(DARWIN_SDK_SHLIBFLAGS) -ifeq (WINNT,$(OS_ARCH)) - # -EHsc because gtest has exception handlers - OS_CFLAGS += -EHsc - # On windows, we need to create the parent directory - # Needed because we include files from a subdirectory - MAKE_OBJDIR = $(INSTALL) -D $(dir $@) -endif diff --git a/security/nss/external_tests/manifest.mn b/security/nss/external_tests/manifest.mn index 77a057532fb6..94652aedf6eb 100644 --- a/security/nss/external_tests/manifest.mn +++ b/security/nss/external_tests/manifest.mn @@ -7,5 +7,6 @@ DEPTH = .. DIRS = \ google_test \ + pk11_gtest \ ssl_gtest \ $(NULL) diff --git a/security/nss/cmd/checkcert/Makefile b/security/nss/external_tests/pk11_gtest/Makefile similarity index 97% rename from security/nss/cmd/checkcert/Makefile rename to security/nss/external_tests/pk11_gtest/Makefile index c2039d82b6b3..2f52caa87fd9 100644 --- a/security/nss/cmd/checkcert/Makefile +++ b/security/nss/external_tests/pk11_gtest/Makefile @@ -1,5 +1,5 @@ #! gmake -# +# # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. @@ -20,11 +20,12 @@ include $(CORE_DEPTH)/coreconf/config.mk # (3) Include "component" configuration information. (OPTIONAL) # ####################################################################### + ####################################################################### # (4) Include "local" platform-dependent assignments (OPTIONAL). # ####################################################################### -include ../platlibs.mk +include ../common/gtest.mk ####################################################################### # (5) Execute "global" rules. (OPTIONAL) # @@ -37,12 +38,7 @@ include $(CORE_DEPTH)/coreconf/rules.mk ####################################################################### - ####################################################################### # (7) Execute "local" rules. (OPTIONAL). # ####################################################################### - - -include ../platrules.mk - diff --git a/security/nss/external_tests/pk11_gtest/manifest.mn b/security/nss/external_tests/pk11_gtest/manifest.mn new file mode 100644 index 000000000000..9494fed1822c --- /dev/null +++ b/security/nss/external_tests/pk11_gtest/manifest.mn @@ -0,0 +1,22 @@ +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +CORE_DEPTH = ../.. +DEPTH = ../.. +MODULE = nss + +CPPSRCS = \ + pk11_pbkdf2_unittest.cc \ + pk11_prf_unittest.cc \ + pk11_rsapss_unittest.cc \ + pk11_gtest.cc \ + $(NULL) + +INCLUDES += -I$(CORE_DEPTH)/external_tests/google_test/gtest/include \ + -I$(CORE_DEPTH)/external_tests/common + +REQUIRES = nspr nss libdbm gtest + +PROGRAM = pk11_gtest +EXTRA_LIBS = $(DIST)/lib/$(LIB_PREFIX)gtest.$(LIB_SUFFIX) diff --git a/security/nss/external_tests/pk11_gtest/pk11_gtest.cc b/security/nss/external_tests/pk11_gtest/pk11_gtest.cc new file mode 100644 index 000000000000..1bbfabb1f6d9 --- /dev/null +++ b/security/nss/external_tests/pk11_gtest/pk11_gtest.cc @@ -0,0 +1,21 @@ +#include "nspr.h" +#include "nss.h" +#include "ssl.h" + +#include + +#define GTEST_HAS_RTTI 0 +#include "gtest/gtest.h" + +int main(int argc, char **argv) { + // Start the tests + ::testing::InitGoogleTest(&argc, argv); + + NSS_NoDB_Init(nullptr); + NSS_SetDomesticPolicy(); + int rv = RUN_ALL_TESTS(); + + NSS_Shutdown(); + + return rv; +} diff --git a/security/nss/external_tests/pk11_gtest/pk11_pbkdf2_unittest.cc b/security/nss/external_tests/pk11_gtest/pk11_pbkdf2_unittest.cc new file mode 100644 index 000000000000..60a656661ca5 --- /dev/null +++ b/security/nss/external_tests/pk11_gtest/pk11_pbkdf2_unittest.cc @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nss.h" +#include "pk11pub.h" +#include + +#include "gtest/gtest.h" +#include "scoped_ptrs.h" + +namespace nss_test { + +static unsigned char* ToUcharPtr(std::string& str) { + return const_cast( + reinterpret_cast(str.c_str())); +} + +class Pkcs11Pbkdf2Test : public ::testing::Test { + public: + void Derive(std::vector& derived, SECOidTag hash_alg) + { + // Shared between test vectors. + const unsigned int iterations = 4096; + std::string pass("passwordPASSWORDpassword"); + std::string salt("saltSALTsaltSALTsaltSALTsaltSALTsalt"); + + // Derivation must succeed with the right values. + EXPECT_TRUE(DeriveBytes(pass, salt, derived, hash_alg, iterations)); + + // Derivation must fail when the password is bogus. + std::string bogusPass("PasswordPASSWORDpassword"); + EXPECT_FALSE(DeriveBytes(bogusPass, salt, derived, hash_alg, iterations)); + + // Derivation must fail when the salt is bogus. + std::string bogusSalt("SaltSALTsaltSALTsaltSALTsaltSALTsalt"); + EXPECT_FALSE(DeriveBytes(pass, bogusSalt, derived, hash_alg, iterations)); + + // Derivation must fail when using the wrong hash function. + SECOidTag next_hash_alg = static_cast(hash_alg + 1); + EXPECT_FALSE(DeriveBytes(pass, salt, derived, next_hash_alg, iterations)); + + // Derivation must fail when using the wrong number of iterations. + EXPECT_FALSE(DeriveBytes(pass, salt, derived, hash_alg, iterations + 1)); + } + + private: + bool DeriveBytes(std::string& pass, std::string& salt, + std::vector& derived, SECOidTag hash_alg, + unsigned int iterations) + { + SECItem passItem = { siBuffer, ToUcharPtr(pass), + static_cast(pass.length()) }; + SECItem saltItem = { siBuffer, ToUcharPtr(salt), + static_cast(salt.length()) }; + + // Set up PBKDF2 params. + ScopedSECAlgorithmID alg_id( + PK11_CreatePBEV2AlgorithmID(SEC_OID_PKCS5_PBKDF2, hash_alg, hash_alg, + derived.size(), iterations, &saltItem)); + + // Derive. + ScopedPK11SlotInfo slot(PK11_GetInternalSlot()); + ScopedPK11SymKey symKey( + PK11_PBEKeyGen(slot.get(), alg_id.get(), &passItem, false, nullptr)); + + SECStatus rv = PK11_ExtractKeyValue(symKey.get()); + EXPECT_EQ(rv, SECSuccess); + + SECItem* keyData = PK11_GetKeyData(symKey.get()); + return !memcmp(&derived[0], keyData->data, keyData->len); + } +}; + +// RFC 6070 +TEST_F(Pkcs11Pbkdf2Test, DeriveKnown1) { + std::vector derived = { + 0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b, 0x80, 0xc8, 0xd8, 0x36, + 0x62, 0xc0, 0xe4, 0x4a, 0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70, 0x38 + }; + + Derive(derived, SEC_OID_HMAC_SHA1); +} + +// https://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors +TEST_F(Pkcs11Pbkdf2Test, DeriveKnown2) { + std::vector derived = { + 0x34, 0x8c, 0x89, 0xdb, 0xcb, 0xd3, 0x2b, 0x2f, 0x32, 0xd8, 0x14, 0xb8, + 0x11, 0x6e, 0x84, 0xcf, 0x2b, 0x17, 0x34, 0x7e, 0xbc, 0x18, 0x00, 0x18, + 0x1c, 0x4e, 0x2a, 0x1f, 0xb8, 0xdd, 0x53, 0xe1, 0xc6, 0x35, 0x51, 0x8c, + 0x7d, 0xac, 0x47, 0xe9 + }; + + Derive(derived, SEC_OID_HMAC_SHA256); +} + +} // namespace nss_test + diff --git a/security/nss/external_tests/ssl_gtest/ssl_prf_unittest.cc b/security/nss/external_tests/pk11_gtest/pk11_prf_unittest.cc similarity index 98% rename from security/nss/external_tests/ssl_gtest/ssl_prf_unittest.cc rename to security/nss/external_tests/pk11_gtest/pk11_prf_unittest.cc index ea2478b9a938..d2136022d4ef 100644 --- a/security/nss/external_tests/ssl_gtest/ssl_prf_unittest.cc +++ b/security/nss/external_tests/pk11_gtest/pk11_prf_unittest.cc @@ -8,13 +8,10 @@ #include "pk11pub.h" #include -#include "gtest_utils.h" +#include "gtest/gtest.h" namespace nss_test { -#define CONST_UINT8_TO_UCHAR(a) const_cast( \ - static_cast(a)) - const size_t kPmsSize = 48; const size_t kMasterSecretSize = 48; const size_t kPrfSeedSizeSha256 = 32; @@ -143,7 +140,7 @@ class TlsPrfTest : public ::testing::Test { CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS master_params = { hash_mech, toUcharPtr(kPrfSeed), - seed_len, + static_cast(seed_len), version }; params_.data = reinterpret_cast(&master_params); diff --git a/security/nss/external_tests/pk11_gtest/pk11_rsapss_unittest.cc b/security/nss/external_tests/pk11_gtest/pk11_rsapss_unittest.cc new file mode 100644 index 000000000000..d770c56b355d --- /dev/null +++ b/security/nss/external_tests/pk11_gtest/pk11_rsapss_unittest.cc @@ -0,0 +1,246 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nss.h" +#include "pk11pub.h" +#include "sechash.h" +#include + +#include "gtest/gtest.h" +#include "scoped_ptrs.h" + +namespace nss_test { + +// RSA-PSS test vectors, pss-vect.txt, Example 1: A 1024-bit RSA Key Pair +// +const uint8_t kTestVector1Spki[] = { + 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, + 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, + 0x81, 0x81, 0x00, 0xa5, 0x6e, 0x4a, 0x0e, 0x70, 0x10, 0x17, 0x58, 0x9a, 0x51, + 0x87, 0xdc, 0x7e, 0xa8, 0x41, 0xd1, 0x56, 0xf2, 0xec, 0x0e, 0x36, 0xad, 0x52, + 0xa4, 0x4d, 0xfe, 0xb1, 0xe6, 0x1f, 0x7a, 0xd9, 0x91, 0xd8, 0xc5, 0x10, 0x56, + 0xff, 0xed, 0xb1, 0x62, 0xb4, 0xc0, 0xf2, 0x83, 0xa1, 0x2a, 0x88, 0xa3, 0x94, + 0xdf, 0xf5, 0x26, 0xab, 0x72, 0x91, 0xcb, 0xb3, 0x07, 0xce, 0xab, 0xfc, 0xe0, + 0xb1, 0xdf, 0xd5, 0xcd, 0x95, 0x08, 0x09, 0x6d, 0x5b, 0x2b, 0x8b, 0x6d, 0xf5, + 0xd6, 0x71, 0xef, 0x63, 0x77, 0xc0, 0x92, 0x1c, 0xb2, 0x3c, 0x27, 0x0a, 0x70, + 0xe2, 0x59, 0x8e, 0x6f, 0xf8, 0x9d, 0x19, 0xf1, 0x05, 0xac, 0xc2, 0xd3, 0xf0, + 0xcb, 0x35, 0xf2, 0x92, 0x80, 0xe1, 0x38, 0x6b, 0x6f, 0x64, 0xc4, 0xef, 0x22, + 0xe1, 0xe1, 0xf2, 0x0d, 0x0c, 0xe8, 0xcf, 0xfb, 0x22, 0x49, 0xbd, 0x9a, 0x21, + 0x37, 0x02, 0x03, 0x01, 0x00, 0x01 +}; +// RSA-PSS test vectors, pss-vect.txt, Example 1.1 +const uint8_t kTestVector1Data[] = { + 0xcd, 0xc8, 0x7d, 0xa2, 0x23, 0xd7, 0x86, 0xdf, 0x3b, 0x45, 0xe0, 0xbb, 0xbc, + 0x72, 0x13, 0x26, 0xd1, 0xee, 0x2a, 0xf8, 0x06, 0xcc, 0x31, 0x54, 0x75, 0xcc, + 0x6f, 0x0d, 0x9c, 0x66, 0xe1, 0xb6, 0x23, 0x71, 0xd4, 0x5c, 0xe2, 0x39, 0x2e, + 0x1a, 0xc9, 0x28, 0x44, 0xc3, 0x10, 0x10, 0x2f, 0x15, 0x6a, 0x0d, 0x8d, 0x52, + 0xc1, 0xf4, 0xc4, 0x0b, 0xa3, 0xaa, 0x65, 0x09, 0x57, 0x86, 0xcb, 0x76, 0x97, + 0x57, 0xa6, 0x56, 0x3b, 0xa9, 0x58, 0xfe, 0xd0, 0xbc, 0xc9, 0x84, 0xe8, 0xb5, + 0x17, 0xa3, 0xd5, 0xf5, 0x15, 0xb2, 0x3b, 0x8a, 0x41, 0xe7, 0x4a, 0xa8, 0x67, + 0x69, 0x3f, 0x90, 0xdf, 0xb0, 0x61, 0xa6, 0xe8, 0x6d, 0xfa, 0xae, 0xe6, 0x44, + 0x72, 0xc0, 0x0e, 0x5f, 0x20, 0x94, 0x57, 0x29, 0xcb, 0xeb, 0xe7, 0x7f, 0x06, + 0xce, 0x78, 0xe0, 0x8f, 0x40, 0x98, 0xfb, 0xa4, 0x1f, 0x9d, 0x61, 0x93, 0xc0, + 0x31, 0x7e, 0x8b, 0x60, 0xd4, 0xb6, 0x08, 0x4a, 0xcb, 0x42, 0xd2, 0x9e, 0x38, + 0x08, 0xa3, 0xbc, 0x37, 0x2d, 0x85, 0xe3, 0x31, 0x17, 0x0f, 0xcb, 0xf7, 0xcc, + 0x72, 0xd0, 0xb7, 0x1c, 0x29, 0x66, 0x48, 0xb3, 0xa4, 0xd1, 0x0f, 0x41, 0x62, + 0x95, 0xd0, 0x80, 0x7a, 0xa6, 0x25, 0xca, 0xb2, 0x74, 0x4f, 0xd9, 0xea, 0x8f, + 0xd2, 0x23, 0xc4, 0x25, 0x37, 0x02, 0x98, 0x28, 0xbd, 0x16, 0xbe, 0x02, 0x54, + 0x6f, 0x13, 0x0f, 0xd2, 0xe3, 0x3b, 0x93, 0x6d, 0x26, 0x76, 0xe0, 0x8a, 0xed, + 0x1b, 0x73, 0x31, 0x8b, 0x75, 0x0a, 0x01, 0x67, 0xd0 +}; +const uint8_t kTestVector1Sig[] = { + 0x90, 0x74, 0x30, 0x8f, 0xb5, 0x98, 0xe9, 0x70, 0x1b, 0x22, 0x94, 0x38, 0x8e, + 0x52, 0xf9, 0x71, 0xfa, 0xac, 0x2b, 0x60, 0xa5, 0x14, 0x5a, 0xf1, 0x85, 0xdf, + 0x52, 0x87, 0xb5, 0xed, 0x28, 0x87, 0xe5, 0x7c, 0xe7, 0xfd, 0x44, 0xdc, 0x86, + 0x34, 0xe4, 0x07, 0xc8, 0xe0, 0xe4, 0x36, 0x0b, 0xc2, 0x26, 0xf3, 0xec, 0x22, + 0x7f, 0x9d, 0x9e, 0x54, 0x63, 0x8e, 0x8d, 0x31, 0xf5, 0x05, 0x12, 0x15, 0xdf, + 0x6e, 0xbb, 0x9c, 0x2f, 0x95, 0x79, 0xaa, 0x77, 0x59, 0x8a, 0x38, 0xf9, 0x14, + 0xb5, 0xb9, 0xc1, 0xbd, 0x83, 0xc4, 0xe2, 0xf9, 0xf3, 0x82, 0xa0, 0xd0, 0xaa, + 0x35, 0x42, 0xff, 0xee, 0x65, 0x98, 0x4a, 0x60, 0x1b, 0xc6, 0x9e, 0xb2, 0x8d, + 0xeb, 0x27, 0xdc, 0xa1, 0x2c, 0x82, 0xc2, 0xd4, 0xc3, 0xf6, 0x6c, 0xd5, 0x00, + 0xf1, 0xff, 0x2b, 0x99, 0x4d, 0x8a, 0x4e, 0x30, 0xcb, 0xb3, 0x3c +}; + +// RSA-PSS test vectors, pss-vect.txt, Example 10: A 2048-bit RSA Key Pair +// +const uint8_t kTestVector2Spki[] = { + 0x30, 0x82, 0x01, 0x21, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0e, 0x00, 0x30, 0x82, + 0x01, 0x09, 0x02, 0x82, 0x01, 0x00, 0xa5, 0xdd, 0x86, 0x7a, 0xc4, 0xcb, 0x02, + 0xf9, 0x0b, 0x94, 0x57, 0xd4, 0x8c, 0x14, 0xa7, 0x70, 0xef, 0x99, 0x1c, 0x56, + 0xc3, 0x9c, 0x0e, 0xc6, 0x5f, 0xd1, 0x1a, 0xfa, 0x89, 0x37, 0xce, 0xa5, 0x7b, + 0x9b, 0xe7, 0xac, 0x73, 0xb4, 0x5c, 0x00, 0x17, 0x61, 0x5b, 0x82, 0xd6, 0x22, + 0xe3, 0x18, 0x75, 0x3b, 0x60, 0x27, 0xc0, 0xfd, 0x15, 0x7b, 0xe1, 0x2f, 0x80, + 0x90, 0xfe, 0xe2, 0xa7, 0xad, 0xcd, 0x0e, 0xef, 0x75, 0x9f, 0x88, 0xba, 0x49, + 0x97, 0xc7, 0xa4, 0x2d, 0x58, 0xc9, 0xaa, 0x12, 0xcb, 0x99, 0xae, 0x00, 0x1f, + 0xe5, 0x21, 0xc1, 0x3b, 0xb5, 0x43, 0x14, 0x45, 0xa8, 0xd5, 0xae, 0x4f, 0x5e, + 0x4c, 0x7e, 0x94, 0x8a, 0xc2, 0x27, 0xd3, 0x60, 0x40, 0x71, 0xf2, 0x0e, 0x57, + 0x7e, 0x90, 0x5f, 0xbe, 0xb1, 0x5d, 0xfa, 0xf0, 0x6d, 0x1d, 0xe5, 0xae, 0x62, + 0x53, 0xd6, 0x3a, 0x6a, 0x21, 0x20, 0xb3, 0x1a, 0x5d, 0xa5, 0xda, 0xbc, 0x95, + 0x50, 0x60, 0x0e, 0x20, 0xf2, 0x7d, 0x37, 0x39, 0xe2, 0x62, 0x79, 0x25, 0xfe, + 0xa3, 0xcc, 0x50, 0x9f, 0x21, 0xdf, 0xf0, 0x4e, 0x6e, 0xea, 0x45, 0x49, 0xc5, + 0x40, 0xd6, 0x80, 0x9f, 0xf9, 0x30, 0x7e, 0xed, 0xe9, 0x1f, 0xff, 0x58, 0x73, + 0x3d, 0x83, 0x85, 0xa2, 0x37, 0xd6, 0xd3, 0x70, 0x5a, 0x33, 0xe3, 0x91, 0x90, + 0x09, 0x92, 0x07, 0x0d, 0xf7, 0xad, 0xf1, 0x35, 0x7c, 0xf7, 0xe3, 0x70, 0x0c, + 0xe3, 0x66, 0x7d, 0xe8, 0x3f, 0x17, 0xb8, 0xdf, 0x17, 0x78, 0xdb, 0x38, 0x1d, + 0xce, 0x09, 0xcb, 0x4a, 0xd0, 0x58, 0xa5, 0x11, 0x00, 0x1a, 0x73, 0x81, 0x98, + 0xee, 0x27, 0xcf, 0x55, 0xa1, 0x3b, 0x75, 0x45, 0x39, 0x90, 0x65, 0x82, 0xec, + 0x8b, 0x17, 0x4b, 0xd5, 0x8d, 0x5d, 0x1f, 0x3d, 0x76, 0x7c, 0x61, 0x37, 0x21, + 0xae, 0x05, 0x02, 0x03, 0x01, 0x00, 0x01 +}; +// RSA-PSS test vectors, pss-vect.txt, Example 10.1 +const uint8_t kTestVector2Data[] = { + 0x88, 0x31, 0x77, 0xe5, 0x12, 0x6b, 0x9b, 0xe2, 0xd9, 0xa9, 0x68, 0x03, 0x27, + 0xd5, 0x37, 0x0c, 0x6f, 0x26, 0x86, 0x1f, 0x58, 0x20, 0xc4, 0x3d, 0xa6, 0x7a, + 0x3a, 0xd6, 0x09 +}; +const uint8_t kTestVector2Sig[] = { + 0x82, 0xc2, 0xb1, 0x60, 0x09, 0x3b, 0x8a, 0xa3, 0xc0, 0xf7, 0x52, 0x2b, 0x19, + 0xf8, 0x73, 0x54, 0x06, 0x6c, 0x77, 0x84, 0x7a, 0xbf, 0x2a, 0x9f, 0xce, 0x54, + 0x2d, 0x0e, 0x84, 0xe9, 0x20, 0xc5, 0xaf, 0xb4, 0x9f, 0xfd, 0xfd, 0xac, 0xe1, + 0x65, 0x60, 0xee, 0x94, 0xa1, 0x36, 0x96, 0x01, 0x14, 0x8e, 0xba, 0xd7, 0xa0, + 0xe1, 0x51, 0xcf, 0x16, 0x33, 0x17, 0x91, 0xa5, 0x72, 0x7d, 0x05, 0xf2, 0x1e, + 0x74, 0xe7, 0xeb, 0x81, 0x14, 0x40, 0x20, 0x69, 0x35, 0xd7, 0x44, 0x76, 0x5a, + 0x15, 0xe7, 0x9f, 0x01, 0x5c, 0xb6, 0x6c, 0x53, 0x2c, 0x87, 0xa6, 0xa0, 0x59, + 0x61, 0xc8, 0xbf, 0xad, 0x74, 0x1a, 0x9a, 0x66, 0x57, 0x02, 0x28, 0x94, 0x39, + 0x3e, 0x72, 0x23, 0x73, 0x97, 0x96, 0xc0, 0x2a, 0x77, 0x45, 0x5d, 0x0f, 0x55, + 0x5b, 0x0e, 0xc0, 0x1d, 0xdf, 0x25, 0x9b, 0x62, 0x07, 0xfd, 0x0f, 0xd5, 0x76, + 0x14, 0xce, 0xf1, 0xa5, 0x57, 0x3b, 0xaa, 0xff, 0x4e, 0xc0, 0x00, 0x69, 0x95, + 0x16, 0x59, 0xb8, 0x5f, 0x24, 0x30, 0x0a, 0x25, 0x16, 0x0c, 0xa8, 0x52, 0x2d, + 0xc6, 0xe6, 0x72, 0x7e, 0x57, 0xd0, 0x19, 0xd7, 0xe6, 0x36, 0x29, 0xb8, 0xfe, + 0x5e, 0x89, 0xe2, 0x5c, 0xc1, 0x5b, 0xeb, 0x3a, 0x64, 0x75, 0x77, 0x55, 0x92, + 0x99, 0x28, 0x0b, 0x9b, 0x28, 0xf7, 0x9b, 0x04, 0x09, 0x00, 0x0b, 0xe2, 0x5b, + 0xbd, 0x96, 0x40, 0x8b, 0xa3, 0xb4, 0x3c, 0xc4, 0x86, 0x18, 0x4d, 0xd1, 0xc8, + 0xe6, 0x25, 0x53, 0xfa, 0x1a, 0xf4, 0x04, 0x0f, 0x60, 0x66, 0x3d, 0xe7, 0xf5, + 0xe4, 0x9c, 0x04, 0x38, 0x8e, 0x25, 0x7f, 0x1c, 0xe8, 0x9c, 0x95, 0xda, 0xb4, + 0x8a, 0x31, 0x5d, 0x9b, 0x66, 0xb1, 0xb7, 0x62, 0x82, 0x33, 0x87, 0x6f, 0xf2, + 0x38, 0x52, 0x30, 0xd0, 0x70, 0xd0, 0x7e, 0x16, 0x66 +}; + +static unsigned char* toUcharPtr(const uint8_t* v) { + return const_cast( + static_cast(v)); +} + +class Pkcs11RsaPssTest : public ::testing::Test { +}; + +class Pkcs11RsaPssVectorTest : public Pkcs11RsaPssTest { + public: + void Verify(const uint8_t* spki, size_t spki_len, const uint8_t* data, + size_t data_len, const uint8_t* sig, size_t sig_len) { + // Verify data signed with PSS/SHA-1. + SECOidTag hashOid = SEC_OID_SHA1; + CK_MECHANISM_TYPE hashMech = CKM_SHA_1; + CK_RSA_PKCS_MGF_TYPE mgf = CKG_MGF1_SHA1; + + // Set up PSS parameters. + unsigned int hLen = HASH_ResultLenByOidTag(hashOid); + CK_RSA_PKCS_PSS_PARAMS rsaPssParams = { hashMech, mgf, hLen }; + SECItem params = { siBuffer, + reinterpret_cast(&rsaPssParams), + sizeof(rsaPssParams) }; + + // Import public key. + SECItem spkiItem = { siBuffer, toUcharPtr(spki), + static_cast(spki_len) }; + ScopedCERTSubjectPublicKeyInfo certSpki( + SECKEY_DecodeDERSubjectPublicKeyInfo(&spkiItem)); + ScopedSECKEYPublicKey pubKey(SECKEY_ExtractPublicKey(certSpki.get())); + + // Hash the data. + std::vector hashBuf(hLen); + SECItem hash = { siBuffer, &hashBuf[0], + static_cast(hashBuf.size()) }; + SECStatus rv = PK11_HashBuf(hashOid, hash.data, toUcharPtr(data), + data_len); + EXPECT_EQ(rv, SECSuccess); + + // Verify. + CK_MECHANISM_TYPE mech = CKM_RSA_PKCS_PSS; + SECItem sigItem = { siBuffer, toUcharPtr(sig), + static_cast(sig_len) }; + rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sigItem, &hash, + nullptr); + EXPECT_EQ(rv, SECSuccess); + } +}; + +#define PSS_TEST_VECTOR_VERIFY(spki, data, sig) \ + Verify(spki, sizeof(spki), data, sizeof(data), sig, sizeof(sig)); + +TEST_F(Pkcs11RsaPssTest, GenerateAndSignAndVerify) { + // Sign data with a 1024-bit RSA key, using PSS/SHA-256. + SECOidTag hashOid = SEC_OID_SHA256; + CK_MECHANISM_TYPE hashMech = CKM_SHA256; + CK_RSA_PKCS_MGF_TYPE mgf = CKG_MGF1_SHA256; + PK11RSAGenParams rsaGenParams = { 1024, 0x10001 }; + + // Generate RSA key pair. + ScopedPK11SlotInfo slot(PK11_GetInternalSlot()); + SECKEYPublicKey* pubKeyRaw = nullptr; + ScopedSECKEYPrivateKey privKey(PK11_GenerateKeyPair(slot.get(), + CKM_RSA_PKCS_KEY_PAIR_GEN, + &rsaGenParams, &pubKeyRaw, + false, false, nullptr)); + ASSERT_TRUE(!!privKey && pubKeyRaw); + ScopedSECKEYPublicKey pubKey(pubKeyRaw); + + // Generate random data to sign. + uint8_t dataBuf[50]; + SECItem data = { siBuffer, dataBuf, sizeof(dataBuf) }; + unsigned int hLen = HASH_ResultLenByOidTag(hashOid); + SECStatus rv = PK11_GenerateRandomOnSlot(slot.get(), data.data, data.len); + EXPECT_EQ(rv, SECSuccess); + + // Allocate memory for the signature. + std::vector sigBuf(PK11_SignatureLen(privKey.get())); + SECItem sig = { siBuffer, &sigBuf[0], + static_cast(sigBuf.size()) }; + + // Set up PSS parameters. + CK_RSA_PKCS_PSS_PARAMS rsaPssParams = { hashMech, mgf, hLen }; + SECItem params = { siBuffer, reinterpret_cast(&rsaPssParams), + sizeof(rsaPssParams) }; + + // Sign. + CK_MECHANISM_TYPE mech = CKM_RSA_PKCS_PSS; + rv = PK11_SignWithMechanism(privKey.get(), mech, ¶ms, &sig, &data); + EXPECT_EQ(rv, SECSuccess); + + // Verify. + rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sig, &data, + nullptr); + EXPECT_EQ(rv, SECSuccess); + + // Verification with modified data must fail. + data.data[0] ^= 0xff; + rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sig, &data, + nullptr); + EXPECT_EQ(rv, SECFailure); + + // Verification with original data but the wrong signature must fail. + data.data[0] ^= 0xff; // Revert previous changes. + sig.data[0] ^= 0xff; + rv = PK11_VerifyWithMechanism(pubKey.get(), mech, ¶ms, &sig, &data, + nullptr); + EXPECT_EQ(rv, SECFailure); +} + +// RSA-PSS test vectors, pss-vect.txt, Example 1.1: A 1024-bit RSA Key Pair +// +TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature1) { + PSS_TEST_VECTOR_VERIFY(kTestVector1Spki, kTestVector1Data, kTestVector1Sig); +} + +// RSA-PSS test vectors, pss-vect.txt, Example 10.1: A 2048-bit RSA Key Pair +// +TEST_F(Pkcs11RsaPssVectorTest, VerifyKnownSignature2) { + PSS_TEST_VECTOR_VERIFY(kTestVector2Spki, kTestVector2Data, kTestVector2Sig); +} + +} // namespace nss_test + diff --git a/security/nss/external_tests/ssl_gtest/Makefile b/security/nss/external_tests/ssl_gtest/Makefile index e3bf89d3914e..ad02ec10a5ee 100644 --- a/security/nss/external_tests/ssl_gtest/Makefile +++ b/security/nss/external_tests/ssl_gtest/Makefile @@ -25,7 +25,7 @@ include $(CORE_DEPTH)/coreconf/config.mk # (4) Include "local" platform-dependent assignments (OPTIONAL). # ####################################################################### -include ../../cmd/platlibs.mk +include ../common/gtest.mk ####################################################################### # (5) Execute "global" rules. (OPTIONAL) # @@ -42,19 +42,4 @@ include $(CORE_DEPTH)/coreconf/rules.mk # (7) Execute "local" rules. (OPTIONAL). # ####################################################################### -MKPROG = $(CCC) CFLAGS += -I$(CORE_DEPTH)/lib/ssl - -include ../../cmd/platrules.mk - -ifeq (WINNT,$(OS_ARCH)) - # -EHsc because gtest has exception handlers - OS_CFLAGS += -EHsc -nologo - # http://www.suodenjoki.dk/us/archive/2010/min-max.htm - OS_CFLAGS += -DNOMINMAX - - # Linking to winsock to get htonl - OS_LIBS += Ws2_32.lib -else - CXXFLAGS += -std=c++0x -endif diff --git a/security/nss/external_tests/ssl_gtest/databuffer.h b/security/nss/external_tests/ssl_gtest/databuffer.h index 832b8c3822bd..ca59dd71af7d 100644 --- a/security/nss/external_tests/ssl_gtest/databuffer.h +++ b/security/nss/external_tests/ssl_gtest/databuffer.h @@ -51,9 +51,16 @@ class DataBuffer { void Assign(const DataBuffer& other) { Assign(other.data(), other.len()); } + void Assign(const uint8_t* data, size_t len) { - Allocate(len); - memcpy(static_cast(data_), static_cast(data), len); + if (data) { + Allocate(len); + memcpy(static_cast(data_), static_cast(data), len); + } else { + assert(len == 0); + data_ = nullptr; + len_ = 0; + } } // Write will do a new allocation and expand the size of the buffer if needed. @@ -166,6 +173,15 @@ inline std::ostream& operator<<(std::ostream& stream, const DataBuffer& buf) { return stream; } +inline bool operator==(const DataBuffer& a, const DataBuffer& b) { + return (a.empty() && b.empty()) || + (a.len() == b.len() && 0 == memcmp(a.data(), b.data(), a.len())); +} + +inline bool operator!=(const DataBuffer& a, const DataBuffer& b) { + return !(a == b); +} + } // namespace nss_test #endif diff --git a/security/nss/external_tests/ssl_gtest/manifest.mn b/security/nss/external_tests/ssl_gtest/manifest.mn index 6d70c0b53c2d..237f9646d74e 100644 --- a/security/nss/external_tests/ssl_gtest/manifest.mn +++ b/security/nss/external_tests/ssl_gtest/manifest.mn @@ -15,7 +15,6 @@ CPPSRCS = \ ssl_agent_unittest.cc \ ssl_loopback_unittest.cc \ ssl_extension_unittest.cc \ - ssl_prf_unittest.cc \ ssl_skip_unittest.cc \ ssl_gtest.cc \ test_io.cc \ diff --git a/security/nss/external_tests/ssl_gtest/ssl_extension_unittest.cc b/security/nss/external_tests/ssl_gtest/ssl_extension_unittest.cc index b8e0adf74f9c..75158351005c 100644 --- a/security/nss/external_tests/ssl_gtest/ssl_extension_unittest.cc +++ b/security/nss/external_tests/ssl_gtest/ssl_extension_unittest.cc @@ -609,6 +609,110 @@ TEST_P(TlsExtensionTest12Plus, SignatureAlgorithmConfiguration) { } } +/* + * Tests for Certificate Transparency (RFC 6962) + */ + +// Helper class - stores signed certificate timestamps as provided +// by the relevant callbacks on the client. +class SignedCertificateTimestampsExtractor { + public: + SignedCertificateTimestampsExtractor(TlsAgent& client) { + client.SetAuthCertificateCallback( + [&](TlsAgent& agent, PRBool checksig, PRBool isServer) { + const SECItem *scts = SSL_PeerSignedCertTimestamps(agent.ssl_fd()); + ASSERT_TRUE(scts); + auth_timestamps_.reset(new DataBuffer(scts->data, scts->len)); + } + ); + client.SetHandshakeCallback( + [&](TlsAgent& agent) { + const SECItem *scts = SSL_PeerSignedCertTimestamps(agent.ssl_fd()); + ASSERT_TRUE(scts); + handshake_timestamps_.reset(new DataBuffer(scts->data, scts->len)); + } + ); + } + + void assertTimestamps(const DataBuffer& timestamps) { + ASSERT_TRUE(auth_timestamps_); + ASSERT_EQ(timestamps, *auth_timestamps_); + + ASSERT_TRUE(handshake_timestamps_); + ASSERT_EQ(timestamps, *handshake_timestamps_); + } + + private: + std::unique_ptr auth_timestamps_; + std::unique_ptr handshake_timestamps_; +}; + +// Test timestamps extraction during a successful handshake. +TEST_P(TlsExtensionTestGeneric, SignedCertificateTimestampsHandshake) { + uint8_t val[] = { 0x01, 0x23, 0x45, 0x67, 0x89 }; + const SECItem si_timestamps = { siBuffer, val, sizeof(val) }; + const DataBuffer timestamps(val, sizeof(val)); + + server_->StartConnect(); + ASSERT_EQ(SECSuccess, + SSL_SetSignedCertTimestamps(server_->ssl_fd(), + &si_timestamps, server_->kea())); + + client_->StartConnect(); + ASSERT_EQ(SECSuccess, + SSL_OptionSet(client_->ssl_fd(), + SSL_ENABLE_SIGNED_CERT_TIMESTAMPS, PR_TRUE)); + + SignedCertificateTimestampsExtractor timestamps_extractor(*client_); + Handshake(); + CheckConnected(); + timestamps_extractor.assertTimestamps(timestamps); +} + +// Test SSL_PeerSignedCertTimestamps returning zero-length SECItem +// when the client / the server / both have not enabled the feature. +TEST_P(TlsExtensionTestGeneric, SignedCertificateTimestampsInactiveClient) { + uint8_t val[] = { 0x01, 0x23, 0x45, 0x67, 0x89 }; + const SECItem si_timestamps = { siBuffer, val, sizeof(val) }; + + server_->StartConnect(); + ASSERT_EQ(SECSuccess, + SSL_SetSignedCertTimestamps(server_->ssl_fd(), + &si_timestamps, server_->kea())); + + client_->StartConnect(); + + SignedCertificateTimestampsExtractor timestamps_extractor(*client_); + Handshake(); + CheckConnected(); + timestamps_extractor.assertTimestamps(DataBuffer()); +} + +TEST_P(TlsExtensionTestGeneric, SignedCertificateTimestampsInactiveServer) { + server_->StartConnect(); + + client_->StartConnect(); + ASSERT_EQ(SECSuccess, + SSL_OptionSet(client_->ssl_fd(), + SSL_ENABLE_SIGNED_CERT_TIMESTAMPS, PR_TRUE)); + + SignedCertificateTimestampsExtractor timestamps_extractor(*client_); + Handshake(); + CheckConnected(); + timestamps_extractor.assertTimestamps(DataBuffer()); +} + +TEST_P(TlsExtensionTestGeneric, SignedCertificateTimestampsInactiveBoth) { + server_->StartConnect(); + client_->StartConnect(); + + SignedCertificateTimestampsExtractor timestamps_extractor(*client_); + Handshake(); + CheckConnected(); + timestamps_extractor.assertTimestamps(DataBuffer()); +} + + INSTANTIATE_TEST_CASE_P(ExtensionTls10, TlsExtensionTestGeneric, ::testing::Combine( TlsConnectTestBase::kTlsModesStream, diff --git a/security/nss/external_tests/ssl_gtest/tls_agent.cc b/security/nss/external_tests/ssl_gtest/tls_agent.cc index 2a41ecbc67ac..3758ea315c5a 100644 --- a/security/nss/external_tests/ssl_gtest/tls_agent.cc +++ b/security/nss/external_tests/ssl_gtest/tls_agent.cc @@ -40,7 +40,9 @@ TlsAgent::TlsAgent(const std::string& name, Role role, Mode mode, SSLKEAType kea error_code_(0), send_ctr_(0), recv_ctr_(0), - expected_read_error_(false) { + expected_read_error_(false), + handshake_callback_(), + auth_certificate_callback_() { memset(&info_, 0, sizeof(info_)); memset(&csinfo_, 0, sizeof(csinfo_)); diff --git a/security/nss/external_tests/ssl_gtest/tls_agent.h b/security/nss/external_tests/ssl_gtest/tls_agent.h index f15de13aa0b5..3a1ea68075a3 100644 --- a/security/nss/external_tests/ssl_gtest/tls_agent.h +++ b/security/nss/external_tests/ssl_gtest/tls_agent.h @@ -11,6 +11,7 @@ #include "ssl.h" #include +#include #include "test_io.h" @@ -28,6 +29,16 @@ enum SessionResumptionMode { RESUME_BOTH = RESUME_SESSIONID | RESUME_TICKET }; +class TlsAgent; + +typedef + std::function + AuthCertificateCallbackFunction; + +typedef + std::function + HandshakeCallbackFunction; + class TlsAgent : public PollTarget { public: enum Role { CLIENT, SERVER }; @@ -94,8 +105,12 @@ class TlsAgent : public PollTarget { void CheckExtendedMasterSecret(bool expected); void DisableRollbackDetection(); + Role role() const { return role_; } + State state() const { return state_; } + SSLKEAType kea() const { return kea_; } + const char* state_str() const { return state_str(state()); } const char* state_str(State state) const { return states[state]; } @@ -131,6 +146,15 @@ class TlsAgent : public PollTarget { size_t received_bytes() const { return recv_ctr_; } int32_t error_code() const { return error_code_; } + void SetHandshakeCallback(HandshakeCallbackFunction handshake_callback) { + handshake_callback_ = handshake_callback; + } + + void SetAuthCertificateCallback( + AuthCertificateCallbackFunction auth_certificate_callback) { + auth_certificate_callback_ = auth_certificate_callback; + } + private: const static char* states[]; @@ -148,6 +172,9 @@ class TlsAgent : public PollTarget { TlsAgent* agent = reinterpret_cast(arg); agent->CheckPreliminaryInfo(); agent->auth_certificate_hook_called_ = true; + if (agent->auth_certificate_callback_) { + agent->auth_certificate_callback_(*agent, checksig, isServer); + } return SECSuccess; } @@ -157,6 +184,9 @@ class TlsAgent : public PollTarget { TlsAgent* agent = reinterpret_cast(arg); EXPECT_TRUE(agent->expect_client_auth_); EXPECT_TRUE(isServer); + if (agent->auth_certificate_callback_) { + agent->auth_certificate_callback_(*agent, checksig, isServer); + } return SECSuccess; } @@ -208,6 +238,9 @@ class TlsAgent : public PollTarget { TlsAgent* agent = reinterpret_cast(arg); agent->CheckPreliminaryInfo(); agent->handshake_callback_called_ = true; + if (agent->handshake_callback_) { + agent->handshake_callback_(*agent); + } } void CheckCallbacks() const; @@ -237,6 +270,8 @@ class TlsAgent : public PollTarget { size_t send_ctr_; size_t recv_ctr_; bool expected_read_error_; + HandshakeCallbackFunction handshake_callback_; + AuthCertificateCallbackFunction auth_certificate_callback_; }; class TlsAgentTestBase : public ::testing::Test { diff --git a/security/nss/lib/Makefile b/security/nss/lib/Makefile index a28bfd4db732..f5e4eba3fdde 100644 --- a/security/nss/lib/Makefile +++ b/security/nss/lib/Makefile @@ -46,6 +46,10 @@ ifndef NSS_DISABLE_DBM DBM_SRCDIR = dbm # Add the dbm directory to DIRS. endif +ifeq ($(NSS_BUILD_UTIL_ONLY),1) +SYSINIT_SRCDIR= +endif + ####################################################################### # (5) Execute "global" rules. (OPTIONAL) # ####################################################################### @@ -62,14 +66,28 @@ include $(CORE_DEPTH)/coreconf/rules.mk # (7) Execute "local" rules. (OPTIONAL). # ####################################################################### -ifeq ($(NSS_BUILD_WITHOUT_SOFTOKEN),1) -# Not included when building nss without softoken -UTIL_SRCDIR = -FREEBL_SRCDIR = -SOFTOKEN_SRCDIR = +ifeq ($(NSS_BUILD_UTIL_ONLY),1) + UTIL_SRCDIR = util + FREEBL_SRCDIR = + SOFTOKEN_SRCDIR = else -# default is to include all -UTIL_SRCDIR = util -FREEBL_SRCDIR = freebl -SOFTOKEN_SRCDIR = softoken + ifeq ($(NSS_BUILD_SOFTOKEN_ONLY),1) + UTIL_SRCDIR = + FREEBL_SRCDIR = freebl + SOFTOKEN_SRCDIR = softoken + else + ifeq ($(NSS_BUILD_WITHOUT_SOFTOKEN),1) + # Not included when building nss without softoken + # This build type uses the build results of the prior + # NSS_BUILD_UTIL_ONLY and NSS_BUILD_SOFTOKEN_ONLY builds + UTIL_SRCDIR = + FREEBL_SRCDIR = + SOFTOKEN_SRCDIR = + else + # default is to include all + UTIL_SRCDIR = util + FREEBL_SRCDIR = freebl + SOFTOKEN_SRCDIR = softoken + endif + endif endif diff --git a/security/nss/lib/base/arena.c b/security/nss/lib/base/arena.c index 2b83338ad12b..cefc037040af 100644 --- a/security/nss/lib/base/arena.c +++ b/security/nss/lib/base/arena.c @@ -41,7 +41,7 @@ * nssArena_Mark * nssArena_Release * nssArena_Unmark - * + * * nss_ZAlloc * nss_ZFreeIf * nss_ZRealloc @@ -54,16 +54,16 @@ */ struct NSSArenaStr { - PLArenaPool pool; - PRLock *lock; + PLArenaPool pool; + PRLock *lock; #ifdef ARENA_THREADMARK - PRThread *marking_thread; - nssArenaMark *first_mark; - nssArenaMark *last_mark; + PRThread *marking_thread; + nssArenaMark *first_mark; + nssArenaMark *last_mark; #endif /* ARENA_THREADMARK */ #ifdef ARENA_DESTRUCTOR_LIST - struct arena_destructor_node *first_destructor; - struct arena_destructor_node *last_destructor; + struct arena_destructor_node *first_destructor; + struct arena_destructor_node *last_destructor; #endif /* ARENA_DESTRUCTOR_LIST */ }; @@ -74,14 +74,14 @@ struct NSSArenaStr { */ struct nssArenaMarkStr { - PRUint32 magic; - void *mark; + PRUint32 magic; + void *mark; #ifdef ARENA_THREADMARK - nssArenaMark *next; + nssArenaMark *next; #endif /* ARENA_THREADMARK */ #ifdef ARENA_DESTRUCTOR_LIST - struct arena_destructor_node *next_destructor; - struct arena_destructor_node *prev_destructor; + struct arena_destructor_node *next_destructor; + struct arena_destructor_node *prev_destructor; #endif /* ARENA_DESTRUCTOR_LIST */ }; @@ -96,45 +96,39 @@ extern const NSSError NSS_ERROR_INTERNAL_ERROR; static nssPointerTracker arena_pointer_tracker; static PRStatus -arena_add_pointer -( - const NSSArena *arena -) +arena_add_pointer(const NSSArena *arena) { - PRStatus rv; + PRStatus rv; - rv = nssPointerTracker_initialize(&arena_pointer_tracker); - if( PR_SUCCESS != rv ) { - return rv; - } - - rv = nssPointerTracker_add(&arena_pointer_tracker, arena); - if( PR_SUCCESS != rv ) { - NSSError e = NSS_GetError(); - if( NSS_ERROR_NO_MEMORY != e ) { - nss_SetError(NSS_ERROR_INTERNAL_ERROR); + rv = nssPointerTracker_initialize(&arena_pointer_tracker); + if (PR_SUCCESS != rv) { + return rv; } - return rv; - } + rv = nssPointerTracker_add(&arena_pointer_tracker, arena); + if (PR_SUCCESS != rv) { + NSSError e = NSS_GetError(); + if (NSS_ERROR_NO_MEMORY != e) { + nss_SetError(NSS_ERROR_INTERNAL_ERROR); + } - return PR_SUCCESS; + return rv; + } + + return PR_SUCCESS; } static PRStatus -arena_remove_pointer -( - const NSSArena *arena -) +arena_remove_pointer(const NSSArena *arena) { - PRStatus rv; + PRStatus rv; - rv = nssPointerTracker_remove(&arena_pointer_tracker, arena); - if( PR_SUCCESS != rv ) { - nss_SetError(NSS_ERROR_INTERNAL_ERROR); - } + rv = nssPointerTracker_remove(&arena_pointer_tracker, arena); + if (PR_SUCCESS != rv) { + nss_SetError(NSS_ERROR_INTERNAL_ERROR); + } - return rv; + return rv; } /* @@ -155,45 +149,42 @@ arena_remove_pointer */ NSS_IMPLEMENT PRStatus -nssArena_verifyPointer -( - const NSSArena *arena -) +nssArena_verifyPointer(const NSSArena *arena) { - PRStatus rv; + PRStatus rv; - rv = nssPointerTracker_initialize(&arena_pointer_tracker); - if( PR_SUCCESS != rv ) { - /* - * This is a little disingenious. We have to initialize the - * tracker, because someone could "legitimately" try to verify - * an arena pointer before one is ever created. And this step - * might fail, due to lack of memory. But the only way that - * this step can fail is if it's doing the call_once stuff, - * (later calls just no-op). And if it didn't no-op, there - * aren't any valid arenas.. so the argument certainly isn't one. - */ - nss_SetError(NSS_ERROR_INVALID_ARENA); - return PR_FAILURE; - } + rv = nssPointerTracker_initialize(&arena_pointer_tracker); + if (PR_SUCCESS != rv) { + /* + * This is a little disingenious. We have to initialize the + * tracker, because someone could "legitimately" try to verify + * an arena pointer before one is ever created. And this step + * might fail, due to lack of memory. But the only way that + * this step can fail is if it's doing the call_once stuff, + * (later calls just no-op). And if it didn't no-op, there + * aren't any valid arenas.. so the argument certainly isn't one. + */ + nss_SetError(NSS_ERROR_INVALID_ARENA); + return PR_FAILURE; + } - rv = nssPointerTracker_verify(&arena_pointer_tracker, arena); - if( PR_SUCCESS != rv ) { - nss_SetError(NSS_ERROR_INVALID_ARENA); - return PR_FAILURE; - } + rv = nssPointerTracker_verify(&arena_pointer_tracker, arena); + if (PR_SUCCESS != rv) { + nss_SetError(NSS_ERROR_INVALID_ARENA); + return PR_FAILURE; + } - return PR_SUCCESS; + return PR_SUCCESS; } #endif /* DEBUG */ #ifdef ARENA_DESTRUCTOR_LIST struct arena_destructor_node { - struct arena_destructor_node *next; - struct arena_destructor_node *prev; - void (*destructor)(void *argument); - void *arg; + struct arena_destructor_node *next; + struct arena_destructor_node *prev; + void (*destructor)(void *argument); + void *arg; }; /* @@ -208,9 +199,9 @@ struct arena_destructor_node { * arena, but it may not allocate or cause to be allocated any * memory. This callback facility was included to support our * debug-version pointer-tracker feature; overuse runs counter to - * the the original intent of arenas. This routine returns a - * PRStatus value; if successful, it will return PR_SUCCESS. If - * unsuccessful, it will set an error on the error stack and + * the the original intent of arenas. This routine returns a + * PRStatus value; if successful, it will return PR_SUCCESS. If + * unsuccessful, it will set an error on the error stack and * return PR_FAILURE. * * The error may be one of the following values: @@ -223,108 +214,97 @@ struct arena_destructor_node { */ NSS_IMPLEMENT PRStatus -nssArena_registerDestructor -( - NSSArena *arena, - void (*destructor)(void *argument), - void *arg -) +nssArena_registerDestructor(NSSArena *arena, void (*destructor)(void *argument), + void *arg) { - struct arena_destructor_node *it; + struct arena_destructor_node *it; #ifdef NSSDEBUG - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return PR_FAILURE; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return PR_FAILURE; + } #endif /* NSSDEBUG */ - - it = nss_ZNEW(arena, struct arena_destructor_node); - if( (struct arena_destructor_node *)NULL == it ) { - return PR_FAILURE; - } - it->prev = arena->last_destructor; - arena->last_destructor->next = it; - arena->last_destructor = it; - it->destructor = destructor; - it->arg = arg; + it = nss_ZNEW(arena, struct arena_destructor_node); + if ((struct arena_destructor_node *)NULL == it) { + return PR_FAILURE; + } - if( (nssArenaMark *)NULL != arena->last_mark ) { - arena->last_mark->prev_destructor = it->prev; - arena->last_mark->next_destructor = it->next; - } + it->prev = arena->last_destructor; + arena->last_destructor->next = it; + arena->last_destructor = it; + it->destructor = destructor; + it->arg = arg; - return PR_SUCCESS; + if ((nssArenaMark *)NULL != arena->last_mark) { + arena->last_mark->prev_destructor = it->prev; + arena->last_mark->next_destructor = it->next; + } + + return PR_SUCCESS; } NSS_IMPLEMENT PRStatus -nssArena_deregisterDestructor -( - NSSArena *arena, - void (*destructor)(void *argument), - void *arg -) +nssArena_deregisterDestructor(NSSArena *arena, + void (*destructor)(void *argument), void *arg) { - struct arena_destructor_node *it; + struct arena_destructor_node *it; #ifdef NSSDEBUG - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return PR_FAILURE; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return PR_FAILURE; + } #endif /* NSSDEBUG */ - for( it = arena->first_destructor; it; it = it->next ) { - if( (it->destructor == destructor) && (it->arg == arg) ) { - break; + for (it = arena->first_destructor; it; it = it->next) { + if ((it->destructor == destructor) && (it->arg == arg)) { + break; + } } - } - if( (struct arena_destructor_node *)NULL == it ) { - nss_SetError(NSS_ERROR_NOT_FOUND); - return PR_FAILURE; - } - - if( it == arena->first_destructor ) { - arena->first_destructor = it->next; - } - - if( it == arena->last_destructor ) { - arena->last_destructor = it->prev; - } - - if( (struct arena_destructor_node *)NULL != it->prev ) { - it->prev->next = it->next; - } - - if( (struct arena_destructor_node *)NULL != it->next ) { - it->next->prev = it->prev; - } - - { - nssArenaMark *m; - for( m = arena->first_mark; m; m = m->next ) { - if( m->next_destructor == it ) { - m->next_destructor = it->next; - } - if( m->prev_destructor == it ) { - m->prev_destructor = it->prev; - } + if ((struct arena_destructor_node *)NULL == it) { + nss_SetError(NSS_ERROR_NOT_FOUND); + return PR_FAILURE; } - } - nss_ZFreeIf(it); - return PR_SUCCESS; + if (it == arena->first_destructor) { + arena->first_destructor = it->next; + } + + if (it == arena->last_destructor) { + arena->last_destructor = it->prev; + } + + if ((struct arena_destructor_node *)NULL != it->prev) { + it->prev->next = it->next; + } + + if ((struct arena_destructor_node *)NULL != it->next) { + it->next->prev = it->prev; + } + + { + nssArenaMark *m; + for (m = arena->first_mark; m; m = m->next) { + if (m->next_destructor == it) { + m->next_destructor = it->next; + } + if (m->prev_destructor == it) { + m->prev_destructor = it->prev; + } + } + } + + nss_ZFreeIf(it); + return PR_SUCCESS; } static void -nss_arena_call_destructor_chain -( - struct arena_destructor_node *it -) +nss_arena_call_destructor_chain(struct arena_destructor_node *it) { - for( ; it ; it = it->next ) { - (*(it->destructor))(it->arg); - } + for (; it; it = it->next) { + (*(it->destructor))(it->arg); + } } #endif /* ARENA_DESTRUCTOR_LIST */ @@ -344,20 +324,17 @@ nss_arena_call_destructor_chain */ NSS_IMPLEMENT NSSArena * -NSSArena_Create -( - void -) +NSSArena_Create(void) { - nss_ClearErrorStack(); - return nssArena_Create(); + nss_ClearErrorStack(); + return nssArena_Create(); } /* * nssArena_Create * * This routine creates a new memory arena. This routine may return - * NULL upon error, in which case it will have set an error on the + * NULL upon error, in which case it will have set an error on the * error stack. * * The error may be one of the following values: @@ -369,66 +346,63 @@ NSSArena_Create */ NSS_IMPLEMENT NSSArena * -nssArena_Create -( - void -) +nssArena_Create(void) { - NSSArena *rv = (NSSArena *)NULL; + NSSArena *rv = (NSSArena *)NULL; - rv = nss_ZNEW((NSSArena *)NULL, NSSArena); - if( (NSSArena *)NULL == rv ) { - nss_SetError(NSS_ERROR_NO_MEMORY); - return (NSSArena *)NULL; - } + rv = nss_ZNEW((NSSArena *)NULL, NSSArena); + if ((NSSArena *)NULL == rv) { + nss_SetError(NSS_ERROR_NO_MEMORY); + return (NSSArena *)NULL; + } - rv->lock = PR_NewLock(); - if( (PRLock *)NULL == rv->lock ) { - (void)nss_ZFreeIf(rv); - nss_SetError(NSS_ERROR_NO_MEMORY); - return (NSSArena *)NULL; - } + rv->lock = PR_NewLock(); + if ((PRLock *)NULL == rv->lock) { + (void)nss_ZFreeIf(rv); + nss_SetError(NSS_ERROR_NO_MEMORY); + return (NSSArena *)NULL; + } - /* - * Arena sizes. The current security code has 229 occurrences of - * PORT_NewArena. The default chunksizes specified break down as - * - * Size Mult. Specified as - * 512 1 512 - * 1024 7 1024 - * 2048 5 2048 - * 2048 5 CRMF_DEFAULT_ARENA_SIZE - * 2048 190 DER_DEFAULT_CHUNKSIZE - * 2048 20 SEC_ASN1_DEFAULT_ARENA_SIZE - * 4096 1 4096 - * - * Obviously this "default chunksize" flexibility isn't very - * useful to us, so I'll just pick 2048. - */ + /* + * Arena sizes. The current security code has 229 occurrences of + * PORT_NewArena. The default chunksizes specified break down as + * + * Size Mult. Specified as + * 512 1 512 + * 1024 7 1024 + * 2048 5 2048 + * 2048 5 CRMF_DEFAULT_ARENA_SIZE + * 2048 190 DER_DEFAULT_CHUNKSIZE + * 2048 20 SEC_ASN1_DEFAULT_ARENA_SIZE + * 4096 1 4096 + * + * Obviously this "default chunksize" flexibility isn't very + * useful to us, so I'll just pick 2048. + */ - PL_InitArenaPool(&rv->pool, "NSS", 2048, sizeof(double)); + PL_InitArenaPool(&rv->pool, "NSS", 2048, sizeof(double)); #ifdef DEBUG - { - PRStatus st; - st = arena_add_pointer(rv); - if( PR_SUCCESS != st ) { - PL_FinishArenaPool(&rv->pool); - PR_DestroyLock(rv->lock); - (void)nss_ZFreeIf(rv); - return (NSSArena *)NULL; + { + PRStatus st; + st = arena_add_pointer(rv); + if (PR_SUCCESS != st) { + PL_FinishArenaPool(&rv->pool); + PR_DestroyLock(rv->lock); + (void)nss_ZFreeIf(rv); + return (NSSArena *)NULL; + } } - } #endif /* DEBUG */ - return rv; + return rv; } /* * NSSArena_Destroy * * This routine will destroy the specified arena, freeing all memory - * allocated from it. This routine returns a PRStatus value; if + * allocated from it. This routine returns a PRStatus value; if * successful, it will return PR_SUCCESS. If unsuccessful, it will * create an error stack and return PR_FAILURE. * @@ -441,27 +415,24 @@ nssArena_Create */ NSS_IMPLEMENT PRStatus -NSSArena_Destroy -( - NSSArena *arena -) +NSSArena_Destroy(NSSArena *arena) { - nss_ClearErrorStack(); + nss_ClearErrorStack(); #ifdef DEBUG - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return PR_FAILURE; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return PR_FAILURE; + } #endif /* DEBUG */ - return nssArena_Destroy(arena); + return nssArena_Destroy(arena); } /* * nssArena_Destroy * * This routine will destroy the specified arena, freeing all memory - * allocated from it. This routine returns a PRStatus value; if + * allocated from it. This routine returns a PRStatus value; if * successful, it will return PR_SUCCESS. If unsuccessful, it will * set an error on the error stack and return PR_FAILURE. * @@ -474,45 +445,42 @@ NSSArena_Destroy */ NSS_IMPLEMENT PRStatus -nssArena_Destroy -( - NSSArena *arena -) +nssArena_Destroy(NSSArena *arena) { - PRLock *lock; + PRLock *lock; #ifdef NSSDEBUG - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return PR_FAILURE; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return PR_FAILURE; + } #endif /* NSSDEBUG */ - if( (PRLock *)NULL == arena->lock ) { - /* Just got destroyed */ - nss_SetError(NSS_ERROR_INVALID_ARENA); - return PR_FAILURE; - } - PR_Lock(arena->lock); - + if ((PRLock *)NULL == arena->lock) { + /* Just got destroyed */ + nss_SetError(NSS_ERROR_INVALID_ARENA); + return PR_FAILURE; + } + PR_Lock(arena->lock); + #ifdef DEBUG - if( PR_SUCCESS != arena_remove_pointer(arena) ) { - PR_Unlock(arena->lock); - return PR_FAILURE; - } + if (PR_SUCCESS != arena_remove_pointer(arena)) { + PR_Unlock(arena->lock); + return PR_FAILURE; + } #endif /* DEBUG */ #ifdef ARENA_DESTRUCTOR_LIST - /* Note that the arena is locked at this time */ - nss_arena_call_destructor_chain(arena->first_destructor); + /* Note that the arena is locked at this time */ + nss_arena_call_destructor_chain(arena->first_destructor); #endif /* ARENA_DESTRUCTOR_LIST */ - PL_FinishArenaPool(&arena->pool); - lock = arena->lock; - arena->lock = (PRLock *)NULL; - PR_Unlock(lock); - PR_DestroyLock(lock); - (void)nss_ZFreeIf(arena); - return PR_SUCCESS; + PL_FinishArenaPool(&arena->pool); + lock = arena->lock; + arena->lock = (PRLock *)NULL; + PR_Unlock(lock); + PR_DestroyLock(lock); + (void)nss_ZFreeIf(arena); + return PR_SUCCESS; } static void *nss_zalloc_arena_locked(NSSArena *arena, PRUint32 size); @@ -523,9 +491,9 @@ static void *nss_zalloc_arena_locked(NSSArena *arena, PRUint32 size); * This routine "marks" the current state of an arena. Space * allocated after the arena has been marked can be freed by * releasing the arena back to the mark with nssArena_Release, - * or committed by calling nssArena_Unmark. When successful, - * this routine returns a valid nssArenaMark pointer. This - * routine may return NULL upon error, in which case it will + * or committed by calling nssArena_Unmark. When successful, + * this routine returns a valid nssArenaMark pointer. This + * routine may return NULL upon error, in which case it will * have set an error on the error stack. * * The error may be one of the following values: @@ -539,73 +507,72 @@ static void *nss_zalloc_arena_locked(NSSArena *arena, PRUint32 size); */ NSS_IMPLEMENT nssArenaMark * -nssArena_Mark -( - NSSArena *arena -) +nssArena_Mark(NSSArena *arena) { - nssArenaMark *rv; - void *p; + nssArenaMark *rv; + void *p; #ifdef NSSDEBUG - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return (nssArenaMark *)NULL; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return (nssArenaMark *)NULL; + } #endif /* NSSDEBUG */ - if( (PRLock *)NULL == arena->lock ) { - /* Just got destroyed */ - nss_SetError(NSS_ERROR_INVALID_ARENA); - return (nssArenaMark *)NULL; - } - PR_Lock(arena->lock); - -#ifdef ARENA_THREADMARK - if( (PRThread *)NULL == arena->marking_thread ) { - /* Unmarked. Store our thread ID */ - arena->marking_thread = PR_GetCurrentThread(); - /* This call never fails. */ - } else { - /* Marked. Verify it's the current thread */ - if( PR_GetCurrentThread() != arena->marking_thread ) { - PR_Unlock(arena->lock); - nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); - return (nssArenaMark *)NULL; + if ((PRLock *)NULL == arena->lock) { + /* Just got destroyed */ + nss_SetError(NSS_ERROR_INVALID_ARENA); + return (nssArenaMark *)NULL; } - } -#endif /* ARENA_THREADMARK */ - - p = PL_ARENA_MARK(&arena->pool); - /* No error possible */ - - /* Do this after the mark */ - rv = (nssArenaMark *)nss_zalloc_arena_locked(arena, sizeof(nssArenaMark)); - if( (nssArenaMark *)NULL == rv ) { - PR_Unlock(arena->lock); - nss_SetError(NSS_ERROR_NO_MEMORY); - return (nssArenaMark *)NULL; - } + PR_Lock(arena->lock); #ifdef ARENA_THREADMARK - if ( (nssArenaMark *)NULL == arena->first_mark) { - arena->first_mark = rv; - arena->last_mark = rv; - } else { - arena->last_mark->next = rv; - arena->last_mark = rv; - } + if ((PRThread *)NULL == arena->marking_thread) { + /* Unmarked. Store our thread ID */ + arena->marking_thread = PR_GetCurrentThread(); + /* This call never fails. */ + } + else { + /* Marked. Verify it's the current thread */ + if (PR_GetCurrentThread() != arena->marking_thread) { + PR_Unlock(arena->lock); + nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); + return (nssArenaMark *)NULL; + } + } #endif /* ARENA_THREADMARK */ - rv->mark = p; - rv->magic = MARK_MAGIC; + p = PL_ARENA_MARK(&arena->pool); + /* No error possible */ + + /* Do this after the mark */ + rv = (nssArenaMark *)nss_zalloc_arena_locked(arena, sizeof(nssArenaMark)); + if ((nssArenaMark *)NULL == rv) { + PR_Unlock(arena->lock); + nss_SetError(NSS_ERROR_NO_MEMORY); + return (nssArenaMark *)NULL; + } + +#ifdef ARENA_THREADMARK + if ((nssArenaMark *)NULL == arena->first_mark) { + arena->first_mark = rv; + arena->last_mark = rv; + } + else { + arena->last_mark->next = rv; + arena->last_mark = rv; + } +#endif /* ARENA_THREADMARK */ + + rv->mark = p; + rv->magic = MARK_MAGIC; #ifdef ARENA_DESTRUCTOR_LIST - rv->prev_destructor = arena->last_destructor; + rv->prev_destructor = arena->last_destructor; #endif /* ARENA_DESTRUCTOR_LIST */ - PR_Unlock(arena->lock); + PR_Unlock(arena->lock); - return rv; + return rv; } /* @@ -616,100 +583,98 @@ nssArena_Mark */ static PRStatus -nss_arena_unmark_release -( - NSSArena *arena, - nssArenaMark *arenaMark, - PRBool release -) +nss_arena_unmark_release(NSSArena *arena, nssArenaMark *arenaMark, + PRBool release) { - void *inner_mark; + void *inner_mark; #ifdef NSSDEBUG - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return PR_FAILURE; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return PR_FAILURE; + } #endif /* NSSDEBUG */ - if( MARK_MAGIC != arenaMark->magic ) { - nss_SetError(NSS_ERROR_INVALID_ARENA_MARK); - return PR_FAILURE; - } + if (MARK_MAGIC != arenaMark->magic) { + nss_SetError(NSS_ERROR_INVALID_ARENA_MARK); + return PR_FAILURE; + } - if( (PRLock *)NULL == arena->lock ) { - /* Just got destroyed */ - nss_SetError(NSS_ERROR_INVALID_ARENA); - return PR_FAILURE; - } - PR_Lock(arena->lock); + if ((PRLock *)NULL == arena->lock) { + /* Just got destroyed */ + nss_SetError(NSS_ERROR_INVALID_ARENA); + return PR_FAILURE; + } + PR_Lock(arena->lock); #ifdef ARENA_THREADMARK - if( (PRThread *)NULL != arena->marking_thread ) { - if( PR_GetCurrentThread() != arena->marking_thread ) { - PR_Unlock(arena->lock); - nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); - return PR_FAILURE; + if ((PRThread *)NULL != arena->marking_thread) { + if (PR_GetCurrentThread() != arena->marking_thread) { + PR_Unlock(arena->lock); + nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); + return PR_FAILURE; + } } - } #endif /* ARENA_THREADMARK */ - if( MARK_MAGIC != arenaMark->magic ) { - /* Just got released */ - PR_Unlock(arena->lock); - nss_SetError(NSS_ERROR_INVALID_ARENA_MARK); - return PR_FAILURE; - } + if (MARK_MAGIC != arenaMark->magic) { + /* Just got released */ + PR_Unlock(arena->lock); + nss_SetError(NSS_ERROR_INVALID_ARENA_MARK); + return PR_FAILURE; + } - arenaMark->magic = 0; - inner_mark = arenaMark->mark; + arenaMark->magic = 0; + inner_mark = arenaMark->mark; #ifdef ARENA_THREADMARK - { - nssArenaMark **pMark = &arena->first_mark; - nssArenaMark *rest; - nssArenaMark *last = (nssArenaMark *)NULL; + { + nssArenaMark **pMark = &arena->first_mark; + nssArenaMark *rest; + nssArenaMark *last = (nssArenaMark *)NULL; - /* Find this mark */ - while( *pMark != arenaMark ) { - last = *pMark; - pMark = &(*pMark)->next; + /* Find this mark */ + while (*pMark != arenaMark) { + last = *pMark; + pMark = &(*pMark)->next; + } + + /* Remember the pointer, then zero it */ + rest = (*pMark)->next; + *pMark = (nssArenaMark *)NULL; + + arena->last_mark = last; + + /* Invalidate any later marks being implicitly released */ + for (; (nssArenaMark *)NULL != rest; rest = rest->next) { + rest->magic = 0; + } + + /* If we just got rid of the first mark, clear the thread ID */ + if ((nssArenaMark *)NULL == arena->first_mark) { + arena->marking_thread = (PRThread *)NULL; + } } - - /* Remember the pointer, then zero it */ - rest = (*pMark)->next; - *pMark = (nssArenaMark *)NULL; - - arena->last_mark = last; - - /* Invalidate any later marks being implicitly released */ - for( ; (nssArenaMark *)NULL != rest; rest = rest->next ) { - rest->magic = 0; - } - - /* If we just got rid of the first mark, clear the thread ID */ - if( (nssArenaMark *)NULL == arena->first_mark ) { - arena->marking_thread = (PRThread *)NULL; - } - } #endif /* ARENA_THREADMARK */ - if( release ) { + if (release) { #ifdef ARENA_DESTRUCTOR_LIST - if( (struct arena_destructor_node *)NULL != arenaMark->prev_destructor ) { - arenaMark->prev_destructor->next = (struct arena_destructor_node *)NULL; - } - arena->last_destructor = arenaMark->prev_destructor; + if ((struct arena_destructor_node *)NULL != + arenaMark->prev_destructor) { + arenaMark->prev_destructor->next = + (struct arena_destructor_node *)NULL; + } + arena->last_destructor = arenaMark->prev_destructor; - /* Note that the arena is locked at this time */ - nss_arena_call_destructor_chain(arenaMark->next_destructor); + /* Note that the arena is locked at this time */ + nss_arena_call_destructor_chain(arenaMark->next_destructor); #endif /* ARENA_DESTRUCTOR_LIST */ - PL_ARENA_RELEASE(&arena->pool, inner_mark); - /* No error return */ - } + PL_ARENA_RELEASE(&arena->pool, inner_mark); + /* No error return */ + } - PR_Unlock(arena->lock); - return PR_SUCCESS; + PR_Unlock(arena->lock); + return PR_SUCCESS; } /* @@ -732,13 +697,9 @@ nss_arena_unmark_release */ NSS_IMPLEMENT PRStatus -nssArena_Release -( - NSSArena *arena, - nssArenaMark *arenaMark -) +nssArena_Release(NSSArena *arena, nssArenaMark *arenaMark) { - return nss_arena_unmark_release(arena, arenaMark, PR_TRUE); + return nss_arena_unmark_release(arena, arenaMark, PR_TRUE); } /* @@ -764,13 +725,9 @@ nssArena_Release */ NSS_IMPLEMENT PRStatus -nssArena_Unmark -( - NSSArena *arena, - nssArenaMark *arenaMark -) +nssArena_Unmark(NSSArena *arena, nssArenaMark *arenaMark) { - return nss_arena_unmark_release(arena, arenaMark, PR_FALSE); + return nss_arena_unmark_release(arena, arenaMark, PR_FALSE); } /* @@ -782,49 +739,45 @@ nssArena_Unmark * maybe we should add a magic value? */ struct pointer_header { - NSSArena *arena; - PRUint32 size; + NSSArena *arena; + PRUint32 size; }; static void * -nss_zalloc_arena_locked -( - NSSArena *arena, - PRUint32 size -) +nss_zalloc_arena_locked(NSSArena *arena, PRUint32 size) { - void *p; - void *rv; - struct pointer_header *h; - PRUint32 my_size = size + sizeof(struct pointer_header); - PL_ARENA_ALLOCATE(p, &arena->pool, my_size); - if( (void *)NULL == p ) { - nss_SetError(NSS_ERROR_NO_MEMORY); - return (void *)NULL; - } - /* - * Do this before we unlock. This way if the user is using - * an arena in one thread while destroying it in another, he'll - * fault/FMR in his code, not ours. - */ - h = (struct pointer_header *)p; - h->arena = arena; - h->size = size; - rv = (void *)((char *)h + sizeof(struct pointer_header)); - (void)nsslibc_memset(rv, 0, size); - return rv; + void *p; + void *rv; + struct pointer_header *h; + PRUint32 my_size = size + sizeof(struct pointer_header); + PL_ARENA_ALLOCATE(p, &arena->pool, my_size); + if ((void *)NULL == p) { + nss_SetError(NSS_ERROR_NO_MEMORY); + return (void *)NULL; + } + /* + * Do this before we unlock. This way if the user is using + * an arena in one thread while destroying it in another, he'll + * fault/FMR in his code, not ours. + */ + h = (struct pointer_header *)p; + h->arena = arena; + h->size = size; + rv = (void *)((char *)h + sizeof(struct pointer_header)); + (void)nsslibc_memset(rv, 0, size); + return rv; } /* * NSS_ZAlloc * - * This routine allocates and zeroes a section of memory of the + * This routine allocates and zeroes a section of memory of the * size, and returns to the caller a pointer to that memory. If * the optional arena argument is non-null, the memory will be * obtained from that arena; otherwise, the memory will be obtained * from the heap. This routine may return NULL upon error, in * which case it will have set an error upon the error stack. The - * value specified for size may be zero; in which case a valid + * value specified for size may be zero; in which case a valid * zero-length block of memory will be allocated. This block may * be expanded by calling NSS_ZRealloc. * @@ -839,25 +792,21 @@ nss_zalloc_arena_locked */ NSS_IMPLEMENT void * -NSS_ZAlloc -( - NSSArena *arenaOpt, - PRUint32 size -) +NSS_ZAlloc(NSSArena *arenaOpt, PRUint32 size) { - return nss_ZAlloc(arenaOpt, size); + return nss_ZAlloc(arenaOpt, size); } /* * nss_ZAlloc * - * This routine allocates and zeroes a section of memory of the + * This routine allocates and zeroes a section of memory of the * size, and returns to the caller a pointer to that memory. If * the optional arena argument is non-null, the memory will be * obtained from that arena; otherwise, the memory will be obtained * from the heap. This routine may return NULL upon error, in * which case it will have set an error upon the error stack. The - * value specified for size may be zero; in which case a valid + * value specified for size may be zero; in which case a valid * zero-length block of memory will be allocated. This block may * be expanded by calling nss_ZRealloc. * @@ -872,76 +821,73 @@ NSS_ZAlloc */ NSS_IMPLEMENT void * -nss_ZAlloc -( - NSSArena *arenaOpt, - PRUint32 size -) +nss_ZAlloc(NSSArena *arenaOpt, PRUint32 size) { - struct pointer_header *h; - PRUint32 my_size = size + sizeof(struct pointer_header); + struct pointer_header *h; + PRUint32 my_size = size + sizeof(struct pointer_header); - if( my_size < sizeof(struct pointer_header) ) { - /* Wrapped */ - nss_SetError(NSS_ERROR_NO_MEMORY); - return (void *)NULL; - } - - if( (NSSArena *)NULL == arenaOpt ) { - /* Heap allocation, no locking required. */ - h = (struct pointer_header *)PR_Calloc(1, my_size); - if( (struct pointer_header *)NULL == h ) { - nss_SetError(NSS_ERROR_NO_MEMORY); - return (void *)NULL; + if (my_size < sizeof(struct pointer_header)) { + /* Wrapped */ + nss_SetError(NSS_ERROR_NO_MEMORY); + return (void *)NULL; } - h->arena = (NSSArena *)NULL; - h->size = size; - /* We used calloc: it's already zeroed */ + if ((NSSArena *)NULL == arenaOpt) { + /* Heap allocation, no locking required. */ + h = (struct pointer_header *)PR_Calloc(1, my_size); + if ((struct pointer_header *)NULL == h) { + nss_SetError(NSS_ERROR_NO_MEMORY); + return (void *)NULL; + } - return (void *)((char *)h + sizeof(struct pointer_header)); - } else { - void *rv; - /* Arena allocation */ + h->arena = (NSSArena *)NULL; + h->size = size; + /* We used calloc: it's already zeroed */ + + return (void *)((char *)h + sizeof(struct pointer_header)); + } + else { + void *rv; +/* Arena allocation */ #ifdef NSSDEBUG - if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) { - return (void *)NULL; - } + if (PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) { + return (void *)NULL; + } #endif /* NSSDEBUG */ - if( (PRLock *)NULL == arenaOpt->lock ) { - /* Just got destroyed */ - nss_SetError(NSS_ERROR_INVALID_ARENA); - return (void *)NULL; - } - PR_Lock(arenaOpt->lock); + if ((PRLock *)NULL == arenaOpt->lock) { + /* Just got destroyed */ + nss_SetError(NSS_ERROR_INVALID_ARENA); + return (void *)NULL; + } + PR_Lock(arenaOpt->lock); #ifdef ARENA_THREADMARK - if( (PRThread *)NULL != arenaOpt->marking_thread ) { - if( PR_GetCurrentThread() != arenaOpt->marking_thread ) { - nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); - PR_Unlock(arenaOpt->lock); - return (void *)NULL; - } - } + if ((PRThread *)NULL != arenaOpt->marking_thread) { + if (PR_GetCurrentThread() != arenaOpt->marking_thread) { + nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); + PR_Unlock(arenaOpt->lock); + return (void *)NULL; + } + } #endif /* ARENA_THREADMARK */ - rv = nss_zalloc_arena_locked(arenaOpt, size); + rv = nss_zalloc_arena_locked(arenaOpt, size); - PR_Unlock(arenaOpt->lock); - return rv; - } - /*NOTREACHED*/ + PR_Unlock(arenaOpt->lock); + return rv; + } + /*NOTREACHED*/ } /* * NSS_ZFreeIf * - * If the specified pointer is non-null, then the region of memory - * to which it points -- which must have been allocated with - * NSS_ZAlloc -- will be zeroed and released. This routine + * If the specified pointer is non-null, then the region of memory + * to which it points -- which must have been allocated with + * NSS_ZAlloc -- will be zeroed and released. This routine * returns a PRStatus value; if successful, it will return PR_SUCCESS. - * If unsuccessful, it will set an error on the error stack and return + * If unsuccessful, it will set an error on the error stack and return * PR_FAILURE. * * The error may be one of the following values: @@ -952,22 +898,19 @@ nss_ZAlloc * PR_FAILURE */ NSS_IMPLEMENT PRStatus -NSS_ZFreeIf -( - void *pointer -) +NSS_ZFreeIf(void *pointer) { - return nss_ZFreeIf(pointer); + return nss_ZFreeIf(pointer); } /* * nss_ZFreeIf * - * If the specified pointer is non-null, then the region of memory - * to which it points -- which must have been allocated with - * nss_ZAlloc -- will be zeroed and released. This routine + * If the specified pointer is non-null, then the region of memory + * to which it points -- which must have been allocated with + * nss_ZAlloc -- will be zeroed and released. This routine * returns a PRStatus value; if successful, it will return PR_SUCCESS. - * If unsuccessful, it will set an error on the error stack and return + * If unsuccessful, it will set an error on the error stack and return * PR_FAILURE. * * The error may be one of the following values: @@ -979,60 +922,58 @@ NSS_ZFreeIf */ NSS_IMPLEMENT PRStatus -nss_ZFreeIf -( - void *pointer -) +nss_ZFreeIf(void *pointer) { - struct pointer_header *h; + struct pointer_header *h; - if( (void *)NULL == pointer ) { - return PR_SUCCESS; - } - - h = (struct pointer_header *)((char *)pointer - - sizeof(struct pointer_header)); - - /* Check any magic here */ - - if( (NSSArena *)NULL == h->arena ) { - /* Heap */ - (void)nsslibc_memset(pointer, 0, h->size); - PR_Free(h); - return PR_SUCCESS; - } else { - /* Arena */ -#ifdef NSSDEBUG - if( PR_SUCCESS != nssArena_verifyPointer(h->arena) ) { - return PR_FAILURE; + if ((void *)NULL == pointer) { + return PR_SUCCESS; } + + h = (struct pointer_header *)((char *)pointer - + sizeof(struct pointer_header)); + + /* Check any magic here */ + + if ((NSSArena *)NULL == h->arena) { + /* Heap */ + (void)nsslibc_memset(pointer, 0, h->size); + PR_Free(h); + return PR_SUCCESS; + } + else { +/* Arena */ +#ifdef NSSDEBUG + if (PR_SUCCESS != nssArena_verifyPointer(h->arena)) { + return PR_FAILURE; + } #endif /* NSSDEBUG */ - if( (PRLock *)NULL == h->arena->lock ) { - /* Just got destroyed.. so this pointer is invalid */ - nss_SetError(NSS_ERROR_INVALID_POINTER); - return PR_FAILURE; + if ((PRLock *)NULL == h->arena->lock) { + /* Just got destroyed.. so this pointer is invalid */ + nss_SetError(NSS_ERROR_INVALID_POINTER); + return PR_FAILURE; + } + PR_Lock(h->arena->lock); + + (void)nsslibc_memset(pointer, 0, h->size); + + /* No way to "free" it within an NSPR arena. */ + + PR_Unlock(h->arena->lock); + return PR_SUCCESS; } - PR_Lock(h->arena->lock); - - (void)nsslibc_memset(pointer, 0, h->size); - - /* No way to "free" it within an NSPR arena. */ - - PR_Unlock(h->arena->lock); - return PR_SUCCESS; - } - /*NOTREACHED*/ + /*NOTREACHED*/ } /* * NSS_ZRealloc * * This routine reallocates a block of memory obtained by calling - * nss_ZAlloc or nss_ZRealloc. The portion of memory + * nss_ZAlloc or nss_ZRealloc. The portion of memory * between the new and old sizes -- which is either being newly - * obtained or released -- is in either case zeroed. This routine - * may return NULL upon failure, in which case it will have placed + * obtained or released -- is in either case zeroed. This routine + * may return NULL upon failure, in which case it will have placed * an error on the error stack. * * The error may be one of the following values: @@ -1046,11 +987,7 @@ nss_ZFreeIf */ NSS_EXTERN void * -NSS_ZRealloc -( - void *pointer, - PRUint32 newSize -) +NSS_ZRealloc(void *pointer, PRUint32 newSize) { return nss_ZRealloc(pointer, newSize); } @@ -1059,10 +996,10 @@ NSS_ZRealloc * nss_ZRealloc * * This routine reallocates a block of memory obtained by calling - * nss_ZAlloc or nss_ZRealloc. The portion of memory + * nss_ZAlloc or nss_ZRealloc. The portion of memory * between the new and old sizes -- which is either being newly - * obtained or released -- is in either case zeroed. This routine - * may return NULL upon failure, in which case it will have placed + * obtained or released -- is in either case zeroed. This routine + * may return NULL upon failure, in which case it will have placed * an error on the error stack. * * The error may be one of the following values: @@ -1076,139 +1013,137 @@ NSS_ZRealloc */ NSS_EXTERN void * -nss_ZRealloc -( - void *pointer, - PRUint32 newSize -) +nss_ZRealloc(void *pointer, PRUint32 newSize) { - NSSArena *arena; - struct pointer_header *h, *new_h; - PRUint32 my_newSize = newSize + sizeof(struct pointer_header); - void *rv; + NSSArena *arena; + struct pointer_header *h, *new_h; + PRUint32 my_newSize = newSize + sizeof(struct pointer_header); + void *rv; - if( my_newSize < sizeof(struct pointer_header) ) { - /* Wrapped */ - nss_SetError(NSS_ERROR_NO_MEMORY); - return (void *)NULL; - } - - if( (void *)NULL == pointer ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (void *)NULL; - } - - h = (struct pointer_header *)((char *)pointer - - sizeof(struct pointer_header)); - - /* Check any magic here */ - - if( newSize == h->size ) { - /* saves thrashing */ - return pointer; - } - - arena = h->arena; - if (!arena) { - /* Heap */ - new_h = (struct pointer_header *)PR_Calloc(1, my_newSize); - if( (struct pointer_header *)NULL == new_h ) { - nss_SetError(NSS_ERROR_NO_MEMORY); - return (void *)NULL; + if (my_newSize < sizeof(struct pointer_header)) { + /* Wrapped */ + nss_SetError(NSS_ERROR_NO_MEMORY); + return (void *)NULL; } - new_h->arena = (NSSArena *)NULL; - new_h->size = newSize; - rv = (void *)((char *)new_h + sizeof(struct pointer_header)); - - if( newSize > h->size ) { - (void)nsslibc_memcpy(rv, pointer, h->size); - (void)nsslibc_memset(&((char *)rv)[ h->size ], - 0, (newSize - h->size)); - } else { - (void)nsslibc_memcpy(rv, pointer, newSize); + if ((void *)NULL == pointer) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (void *)NULL; } - (void)nsslibc_memset(pointer, 0, h->size); - h->size = 0; - PR_Free(h); + h = (struct pointer_header *)((char *)pointer - + sizeof(struct pointer_header)); - return rv; - } else { - void *p; - /* Arena */ + /* Check any magic here */ + + if (newSize == h->size) { + /* saves thrashing */ + return pointer; + } + + arena = h->arena; + if (!arena) { + /* Heap */ + new_h = (struct pointer_header *)PR_Calloc(1, my_newSize); + if ((struct pointer_header *)NULL == new_h) { + nss_SetError(NSS_ERROR_NO_MEMORY); + return (void *)NULL; + } + + new_h->arena = (NSSArena *)NULL; + new_h->size = newSize; + rv = (void *)((char *)new_h + sizeof(struct pointer_header)); + + if (newSize > h->size) { + (void)nsslibc_memcpy(rv, pointer, h->size); + (void)nsslibc_memset(&((char *)rv)[h->size], 0, + (newSize - h->size)); + } + else { + (void)nsslibc_memcpy(rv, pointer, newSize); + } + + (void)nsslibc_memset(pointer, 0, h->size); + h->size = 0; + PR_Free(h); + + return rv; + } + else { + void *p; +/* Arena */ #ifdef NSSDEBUG - if (PR_SUCCESS != nssArena_verifyPointer(arena)) { - return (void *)NULL; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return (void *)NULL; + } #endif /* NSSDEBUG */ - if (!arena->lock) { - /* Just got destroyed.. so this pointer is invalid */ - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (void *)NULL; - } - PR_Lock(arena->lock); + if (!arena->lock) { + /* Just got destroyed.. so this pointer is invalid */ + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (void *)NULL; + } + PR_Lock(arena->lock); #ifdef ARENA_THREADMARK - if (arena->marking_thread) { - if (PR_GetCurrentThread() != arena->marking_thread) { - PR_Unlock(arena->lock); - nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); - return (void *)NULL; - } - } + if (arena->marking_thread) { + if (PR_GetCurrentThread() != arena->marking_thread) { + PR_Unlock(arena->lock); + nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD); + return (void *)NULL; + } + } #endif /* ARENA_THREADMARK */ - if( newSize < h->size ) { - /* - * We have no general way of returning memory to the arena - * (mark/release doesn't work because things may have been - * allocated after this object), so the memory is gone - * anyway. We might as well just return the same pointer to - * the user, saying "yeah, uh-hunh, you can only use less of - * it now." We'll zero the leftover part, of course. And - * in fact we might as well *not* adjust h->size-- this way, - * if the user reallocs back up to something not greater than - * the original size, then voila, there's the memory! This - * way a thrash big/small/big/small doesn't burn up the arena. - */ - char *extra = &((char *)pointer)[ newSize ]; - (void)nsslibc_memset(extra, 0, (h->size - newSize)); - PR_Unlock(arena->lock); - return pointer; - } + if (newSize < h->size) { + /* + * We have no general way of returning memory to the arena + * (mark/release doesn't work because things may have been + * allocated after this object), so the memory is gone + * anyway. We might as well just return the same pointer to + * the user, saying "yeah, uh-hunh, you can only use less of + * it now." We'll zero the leftover part, of course. And + * in fact we might as well *not* adjust h->size-- this way, + * if the user reallocs back up to something not greater than + * the original size, then voila, there's the memory! This + * way a thrash big/small/big/small doesn't burn up the arena. + */ + char *extra = &((char *)pointer)[newSize]; + (void)nsslibc_memset(extra, 0, (h->size - newSize)); + PR_Unlock(arena->lock); + return pointer; + } - PL_ARENA_ALLOCATE(p, &arena->pool, my_newSize); - if( (void *)NULL == p ) { - PR_Unlock(arena->lock); - nss_SetError(NSS_ERROR_NO_MEMORY); - return (void *)NULL; - } + PL_ARENA_ALLOCATE(p, &arena->pool, my_newSize); + if ((void *)NULL == p) { + PR_Unlock(arena->lock); + nss_SetError(NSS_ERROR_NO_MEMORY); + return (void *)NULL; + } - new_h = (struct pointer_header *)p; - new_h->arena = arena; - new_h->size = newSize; - rv = (void *)((char *)new_h + sizeof(struct pointer_header)); - if (rv != pointer) { - (void)nsslibc_memcpy(rv, pointer, h->size); - (void)nsslibc_memset(pointer, 0, h->size); + new_h = (struct pointer_header *)p; + new_h->arena = arena; + new_h->size = newSize; + rv = (void *)((char *)new_h + sizeof(struct pointer_header)); + if (rv != pointer) { + (void)nsslibc_memcpy(rv, pointer, h->size); + (void)nsslibc_memset(pointer, 0, h->size); + } + (void)nsslibc_memset(&((char *)rv)[h->size], 0, (newSize - h->size)); + h->arena = (NSSArena *)NULL; + h->size = 0; + PR_Unlock(arena->lock); + return rv; } - (void)nsslibc_memset(&((char *)rv)[ h->size ], 0, (newSize - h->size)); - h->arena = (NSSArena *)NULL; - h->size = 0; - PR_Unlock(arena->lock); - return rv; - } - /*NOTREACHED*/ + /*NOTREACHED*/ } -PRStatus +PRStatus nssArena_Shutdown(void) { - PRStatus rv = PR_SUCCESS; + PRStatus rv = PR_SUCCESS; #ifdef DEBUG - rv = nssPointerTracker_finalize(&arena_pointer_tracker); + rv = nssPointerTracker_finalize(&arena_pointer_tracker); #endif - return rv; + return rv; } diff --git a/security/nss/lib/base/base.h b/security/nss/lib/base/base.h index deff44ceb73d..6d8a1ba6c3cc 100644 --- a/security/nss/lib/base/base.h +++ b/security/nss/lib/base/base.h @@ -8,7 +8,7 @@ /* * base.h * - * This header file contains basic prototypes and preprocessor + * This header file contains basic prototypes and preprocessor * definitions used throughout nss but not available publicly. */ @@ -64,7 +64,7 @@ PR_BEGIN_EXTERN_C * nssArena_Create * * This routine creates a new memory arena. This routine may return - * NULL upon error, in which case it will have set an error on the + * NULL upon error, in which case it will have set an error on the * error stack. * * The error may be one of the following values: @@ -83,11 +83,7 @@ PR_BEGIN_EXTERN_C * call (NSSArena_Create) have it too? */ -NSS_EXTERN NSSArena * -nssArena_Create -( - void -); +NSS_EXTERN NSSArena *nssArena_Create(void); extern const NSSError NSS_ERROR_NO_MEMORY; @@ -95,7 +91,7 @@ extern const NSSError NSS_ERROR_NO_MEMORY; * nssArena_Destroy * * This routine will destroy the specified arena, freeing all memory - * allocated from it. This routine returns a PRStatus value; if + * allocated from it. This routine returns a PRStatus value; if * successful, it will return PR_SUCCESS. If unsuccessful, it will * set an error on the error stack and return PR_FAILURE. * @@ -107,11 +103,7 @@ extern const NSSError NSS_ERROR_NO_MEMORY; * PR_FAILURE */ -NSS_EXTERN PRStatus -nssArena_Destroy -( - NSSArena *arena -); +NSS_EXTERN PRStatus nssArena_Destroy(NSSArena *arena); extern const NSSError NSS_ERROR_INVALID_ARENA; @@ -121,9 +113,9 @@ extern const NSSError NSS_ERROR_INVALID_ARENA; * This routine "marks" the current state of an arena. Space * allocated after the arena has been marked can be freed by * releasing the arena back to the mark with nssArena_Release, - * or committed by calling nssArena_Unmark. When successful, - * this routine returns a valid nssArenaMark pointer. This - * routine may return NULL upon error, in which case it will + * or committed by calling nssArena_Unmark. When successful, + * this routine returns a valid nssArenaMark pointer. This + * routine may return NULL upon error, in which case it will * have set an error on the error stack. * * The error may be one of the following values: @@ -136,11 +128,7 @@ extern const NSSError NSS_ERROR_INVALID_ARENA; * An nssArenaMark pointer upon success */ -NSS_EXTERN nssArenaMark * -nssArena_Mark -( - NSSArena *arena -); +NSS_EXTERN nssArenaMark *nssArena_Mark(NSSArena *arena); extern const NSSError NSS_ERROR_INVALID_ARENA; extern const NSSError NSS_ERROR_NO_MEMORY; @@ -165,12 +153,7 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * PR_FAILURE */ -NSS_EXTERN PRStatus -nssArena_Release -( - NSSArena *arena, - nssArenaMark *arenaMark -); +NSS_EXTERN PRStatus nssArena_Release(NSSArena *arena, nssArenaMark *arenaMark); extern const NSSError NSS_ERROR_INVALID_ARENA; extern const NSSError NSS_ERROR_INVALID_ARENA_MARK; @@ -197,12 +180,7 @@ extern const NSSError NSS_ERROR_INVALID_ARENA_MARK; * PR_FAILURE */ -NSS_EXTERN PRStatus -nssArena_Unmark -( - NSSArena *arena, - nssArenaMark *arenaMark -); +NSS_EXTERN PRStatus nssArena_Unmark(NSSArena *arena, nssArenaMark *arenaMark); extern const NSSError NSS_ERROR_INVALID_ARENA; extern const NSSError NSS_ERROR_INVALID_ARENA_MARK; @@ -222,9 +200,9 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * arena, but it may not allocate or cause to be allocated any * memory. This callback facility was included to support our * debug-version pointer-tracker feature; overuse runs counter to - * the the original intent of arenas. This routine returns a - * PRStatus value; if successful, it will return PR_SUCCESS. If - * unsuccessful, it will set an error on the error stack and + * the the original intent of arenas. This routine returns a + * PRStatus value; if successful, it will return PR_SUCCESS. If + * unsuccessful, it will set an error on the error stack and * return PR_FAILURE. * * The error may be one of the following values: @@ -236,13 +214,8 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * PR_FAILURE */ -NSS_EXTERN PRStatus -nssArena_registerDestructor -( - NSSArena *arena, - void (*destructor)(void *argument), - void *arg -); +NSS_EXTERN PRStatus nssArena_registerDestructor( + NSSArena *arena, void (*destructor)(void *argument), void *arg); extern const NSSError NSS_ERROR_INVALID_ARENA; extern const NSSError NSS_ERROR_NO_MEMORY; @@ -253,8 +226,8 @@ extern const NSSError NSS_ERROR_NO_MEMORY; * This routine will remove the first destructor in the specified * arena which has the specified destructor and argument values. * The destructor will not be called. This routine returns a - * PRStatus value; if successful, it will return PR_SUCCESS. If - * unsuccessful, it will set an error on the error stack and + * PRStatus value; if successful, it will return PR_SUCCESS. If + * unsuccessful, it will set an error on the error stack and * return PR_FAILURE. * * The error may be one of the following values: @@ -266,13 +239,8 @@ extern const NSSError NSS_ERROR_NO_MEMORY; * PR_FAILURE */ -NSS_EXTERN PRStatus -nssArena_deregisterDestructor -( - NSSArena *arena, - void (*destructor)(void *argument), - void *arg -); +NSS_EXTERN PRStatus nssArena_deregisterDestructor( + NSSArena *arena, void (*destructor)(void *argument), void *arg); extern const NSSError NSS_ERROR_INVALID_ITEM; extern const NSSError NSS_ERROR_INVALID_ARENA; @@ -283,13 +251,13 @@ extern const NSSError NSS_ERROR_NOT_FOUND; /* * nss_ZAlloc * - * This routine allocates and zeroes a section of memory of the + * This routine allocates and zeroes a section of memory of the * size, and returns to the caller a pointer to that memory. If * the optional arena argument is non-null, the memory will be * obtained from that arena; otherwise, the memory will be obtained * from the heap. This routine may return NULL upon error, in * which case it will have set an error upon the error stack. The - * value specified for size may be zero; in which case a valid + * value specified for size may be zero; in which case a valid * zero-length block of memory will be allocated. This block may * be expanded by calling nss_ZRealloc. * @@ -303,12 +271,7 @@ extern const NSSError NSS_ERROR_NOT_FOUND; * A pointer to the new segment of zeroed memory */ -NSS_EXTERN void * -nss_ZAlloc -( - NSSArena *arenaOpt, - PRUint32 size -); +NSS_EXTERN void *nss_ZAlloc(NSSArena *arenaOpt, PRUint32 size); extern const NSSError NSS_ERROR_INVALID_ARENA; extern const NSSError NSS_ERROR_NO_MEMORY; @@ -317,11 +280,11 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; /* * nss_ZFreeIf * - * If the specified pointer is non-null, then the region of memory - * to which it points -- which must have been allocated with - * nss_ZAlloc -- will be zeroed and released. This routine + * If the specified pointer is non-null, then the region of memory + * to which it points -- which must have been allocated with + * nss_ZAlloc -- will be zeroed and released. This routine * returns a PRStatus value; if successful, it will return PR_SUCCESS. - * If unsuccessful, it will set an error on the error stack and return + * If unsuccessful, it will set an error on the error stack and return * PR_FAILURE. * * The error may be one of the following values: @@ -332,11 +295,7 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * PR_FAILURE */ -NSS_EXTERN PRStatus -nss_ZFreeIf -( - void *pointer -); +NSS_EXTERN PRStatus nss_ZFreeIf(void *pointer); extern const NSSError NSS_ERROR_INVALID_POINTER; @@ -344,10 +303,10 @@ extern const NSSError NSS_ERROR_INVALID_POINTER; * nss_ZRealloc * * This routine reallocates a block of memory obtained by calling - * nss_ZAlloc or nss_ZRealloc. The portion of memory + * nss_ZAlloc or nss_ZRealloc. The portion of memory * between the new and old sizes -- which is either being newly - * obtained or released -- is in either case zeroed. This routine - * may return NULL upon failure, in which case it will have placed + * obtained or released -- is in either case zeroed. This routine + * may return NULL upon failure, in which case it will have placed * an error on the error stack. * * The error may be one of the following values: @@ -360,12 +319,7 @@ extern const NSSError NSS_ERROR_INVALID_POINTER; * A pointer to the replacement segment of memory */ -NSS_EXTERN void * -nss_ZRealloc -( - void *pointer, - PRUint32 newSize -); +NSS_EXTERN void *nss_ZRealloc(void *pointer, PRUint32 newSize); extern const NSSError NSS_ERROR_INVALID_POINTER; extern const NSSError NSS_ERROR_NO_MEMORY; @@ -376,10 +330,10 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * * This preprocessor macro will allocate memory for a new object * of the specified type with nss_ZAlloc, and will cast the - * return value appropriately. If the optional arena argument is - * non-null, the memory will be obtained from that arena; otherwise, - * the memory will be obtained from the heap. This routine may - * return NULL upon error, in which case it will have set an error + * return value appropriately. If the optional arena argument is + * non-null, the memory will be obtained from that arena; otherwise, + * the memory will be obtained from the heap. This routine may + * return NULL upon error, in which case it will have set an error * upon the error stack. * * The error may be one of the following values: @@ -391,7 +345,6 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * A pointer to the new segment of zeroed memory */ -/* The following line exceeds 72 characters, but emacs screws up if I split it. */ #define nss_ZNEW(arenaOpt, type) ((type *)nss_ZAlloc((arenaOpt), sizeof(type))) /* @@ -399,10 +352,10 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * * This preprocessor macro will allocate memory for an array of * new objects, and will cast the return value appropriately. - * If the optional arena argument is non-null, the memory will - * be obtained from that arena; otherwise, the memory will be - * obtained from the heap. This routine may return NULL upon - * error, in which case it will have set an error upon the error + * If the optional arena argument is non-null, the memory will + * be obtained from that arena; otherwise, the memory will be + * obtained from the heap. This routine may return NULL upon + * error, in which case it will have set an error upon the error * stack. The array size may be specified as zero. * * The error may be one of the following values: @@ -414,15 +367,15 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * A pointer to the new segment of zeroed memory */ -/* The following line exceeds 72 characters, but emacs screws up if I split it. */ -#define nss_ZNEWARRAY(arenaOpt, type, quantity) ((type *)nss_ZAlloc((arenaOpt), sizeof(type) * (quantity))) +#define nss_ZNEWARRAY(arenaOpt, type, quantity) \ + ((type *)nss_ZAlloc((arenaOpt), sizeof(type) * (quantity))) /* * nss_ZREALLOCARRAY * * This preprocessor macro will reallocate memory for an array of * new objects, and will cast the return value appropriately. - * This routine may return NULL upon error, in which case it will + * This routine may return NULL upon error, in which case it will * have set an error upon the error stack. * * The error may be one of the following values: @@ -434,7 +387,8 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; * NULL upon error * A pointer to the replacement segment of memory */ -#define nss_ZREALLOCARRAY(p, type, quantity) ((type *)nss_ZRealloc((p), sizeof(type) * (quantity))) +#define nss_ZREALLOCARRAY(p, type, quantity) \ + ((type *)nss_ZRealloc((p), sizeof(type) * (quantity))) /* * nssArena_verifyPointer @@ -454,11 +408,7 @@ extern const NSSError NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD; */ #ifdef DEBUG -NSS_EXTERN PRStatus -nssArena_verifyPointer -( - const NSSArena *arena -); +NSS_EXTERN PRStatus nssArena_verifyPointer(const NSSArena *arena); extern const NSSError NSS_ERROR_INVALID_ARENA; #endif /* DEBUG */ @@ -479,16 +429,16 @@ extern const NSSError NSS_ERROR_INVALID_ARENA; #ifdef DEBUG #define nssArena_VERIFYPOINTER(p) nssArena_verifyPointer(p) #else /* DEBUG */ -/* The following line exceeds 72 characters, but emacs screws up if I split it. */ -#define nssArena_VERIFYPOINTER(p) (((NSSArena *)NULL == (p))?PR_FAILURE:PR_SUCCESS) + +#define nssArena_VERIFYPOINTER(p) \ + (((NSSArena *)NULL == (p)) ? PR_FAILURE : PR_SUCCESS) #endif /* DEBUG */ /* - * Private function to be called by NSS_Shutdown to cleanup nssArena + * Private function to be called by NSS_Shutdown to cleanup nssArena * bookkeeping. */ -extern PRStatus -nssArena_Shutdown(void); +extern PRStatus nssArena_Shutdown(void); /* * nssArenaHashAllocOps @@ -497,7 +447,7 @@ nssArena_Shutdown(void); * use with the NSPL routine PL_NewHashTable. For example: * * NSSArena *hashTableArena = nssArena_Create(); - * PLHashTable *t = PL_NewHashTable(n, hasher, key_compare, + * PLHashTable *t = PL_NewHashTable(n, hasher, key_compare, * value_compare, nssArenaHashAllocOps, hashTableArena); */ @@ -515,16 +465,12 @@ NSS_EXTERN_DATA PLHashAllocOps nssArenaHashAllocOps; /* * nss_SetError * - * This routine places a new error code on the top of the calling + * This routine places a new error code on the top of the calling * thread's error stack. Calling this routine wiht an error code * of zero will clear the error stack. */ -NSS_EXTERN void -nss_SetError -( - PRUint32 error -); +NSS_EXTERN void nss_SetError(PRUint32 error); /* * nss_ClearErrorStack @@ -532,11 +478,7 @@ nss_SetError * This routine clears the calling thread's error stack. */ -NSS_EXTERN void -nss_ClearErrorStack -( - void -); +NSS_EXTERN void nss_ClearErrorStack(void); /* * nss_DestroyErrorStack @@ -544,11 +486,7 @@ nss_ClearErrorStack * This routine frees the calling thread's error stack. */ -NSS_EXTERN void -nss_DestroyErrorStack -( - void -); +NSS_EXTERN void nss_DestroyErrorStack(void); /* * NSSItem @@ -558,36 +496,16 @@ nss_DestroyErrorStack * nssItem_Equal */ -NSS_EXTERN NSSItem * -nssItem_Create -( - NSSArena *arenaOpt, - NSSItem *rvOpt, - PRUint32 length, - const void *data -); +NSS_EXTERN NSSItem *nssItem_Create(NSSArena *arenaOpt, NSSItem *rvOpt, + PRUint32 length, const void *data); -NSS_EXTERN void -nssItem_Destroy -( - NSSItem *item -); +NSS_EXTERN void nssItem_Destroy(NSSItem *item); -NSS_EXTERN NSSItem * -nssItem_Duplicate -( - NSSItem *obj, - NSSArena *arenaOpt, - NSSItem *rvOpt -); +NSS_EXTERN NSSItem *nssItem_Duplicate(NSSItem *obj, NSSArena *arenaOpt, + NSSItem *rvOpt); -NSS_EXTERN PRBool -nssItem_Equal -( - const NSSItem *one, - const NSSItem *two, - PRStatus *statusOpt -); +NSS_EXTERN PRBool nssItem_Equal(const NSSItem *one, const NSSItem *two, + PRStatus *statusOpt); /* * NSSUTF8 @@ -601,8 +519,8 @@ nssItem_Equal /* * nssUTF8_CaseIgnoreMatch - * - * Returns true if the two UTF8-encoded strings pointed to by the + * + * Returns true if the two UTF8-encoded strings pointed to by the * two specified NSSUTF8 pointers differ only in typcase. * * The error may be one of the following values: @@ -614,13 +532,8 @@ nssItem_Equal * PR_FALSE upon error */ -NSS_EXTERN PRBool -nssUTF8_CaseIgnoreMatch -( - const NSSUTF8 *a, - const NSSUTF8 *b, - PRStatus *statusOpt -); +NSS_EXTERN PRBool nssUTF8_CaseIgnoreMatch(const NSSUTF8 *a, const NSSUTF8 *b, + PRStatus *statusOpt); /* * nssUTF8_Duplicate @@ -630,7 +543,7 @@ nssUTF8_CaseIgnoreMatch * not null, the memory required will be obtained from that arena; * otherwise, the memory required will be obtained from the heap. * A pointer to the new string will be returned. In case of error, - * an error will be placed on the error stack and NULL will be + * an error will be placed on the error stack and NULL will be * returned. * * The error may be one of the following values: @@ -639,20 +552,15 @@ nssUTF8_CaseIgnoreMatch * NSS_ERROR_NO_MEMORY */ -NSS_EXTERN NSSUTF8 * -nssUTF8_Duplicate -( - const NSSUTF8 *s, - NSSArena *arenaOpt -); +NSS_EXTERN NSSUTF8 *nssUTF8_Duplicate(const NSSUTF8 *s, NSSArena *arenaOpt); /* * nssUTF8_PrintableMatch * - * Returns true if the two Printable strings pointed to by the - * two specified NSSUTF8 pointers match when compared with the - * rules for Printable String (leading and trailing spaces are - * disregarded, extents of whitespace match irregardless of length, + * Returns true if the two Printable strings pointed to by the + * two specified NSSUTF8 pointers match when compared with the + * rules for Printable String (leading and trailing spaces are + * disregarded, extents of whitespace match irregardless of length, * and case is not significant), then PR_TRUE will be returned. * Otherwise, PR_FALSE will be returned. Upon failure, PR_FALSE * will be returned. If the optional statusOpt argument is not @@ -668,13 +576,8 @@ nssUTF8_Duplicate * PR_FALSE upon error */ -NSS_EXTERN PRBool -nssUTF8_PrintableMatch -( - const NSSUTF8 *a, - const NSSUTF8 *b, - PRStatus *statusOpt -); +NSS_EXTERN PRBool nssUTF8_PrintableMatch(const NSSUTF8 *a, const NSSUTF8 *b, + PRStatus *statusOpt); /* * nssUTF8_Size @@ -692,12 +595,7 @@ nssUTF8_PrintableMatch * 0 on error */ -NSS_EXTERN PRUint32 -nssUTF8_Size -( - const NSSUTF8 *s, - PRStatus *statusOpt -); +NSS_EXTERN PRUint32 nssUTF8_Size(const NSSUTF8 *s, PRStatus *statusOpt); extern const NSSError NSS_ERROR_INVALID_POINTER; extern const NSSError NSS_ERROR_VALUE_TOO_LARGE; @@ -719,12 +617,7 @@ extern const NSSError NSS_ERROR_VALUE_TOO_LARGE; * 0 on error */ -NSS_EXTERN PRUint32 -nssUTF8_Length -( - const NSSUTF8 *s, - PRStatus *statusOpt -); +NSS_EXTERN PRUint32 nssUTF8_Length(const NSSUTF8 *s, PRStatus *statusOpt); extern const NSSError NSS_ERROR_INVALID_POINTER; extern const NSSError NSS_ERROR_VALUE_TOO_LARGE; @@ -753,34 +646,24 @@ extern const NSSError NSS_ERROR_INVALID_STRING; * A non-null pointer to a new UTF8 string otherwise */ -NSS_EXTERN NSSUTF8 * -nssUTF8_Create -( - NSSArena *arenaOpt, - nssStringType type, - const void *inputString, - PRUint32 size /* in bytes, not characters */ -); +NSS_EXTERN NSSUTF8 *nssUTF8_Create(NSSArena *arenaOpt, nssStringType type, + const void *inputString, + PRUint32 size /* in bytes, not characters */ + ); extern const NSSError NSS_ERROR_INVALID_POINTER; extern const NSSError NSS_ERROR_NO_MEMORY; extern const NSSError NSS_ERROR_UNSUPPORTED_TYPE; -NSS_EXTERN NSSItem * -nssUTF8_GetEncoding -( - NSSArena *arenaOpt, - NSSItem *rvOpt, - nssStringType type, - NSSUTF8 *string -); +NSS_EXTERN NSSItem *nssUTF8_GetEncoding(NSSArena *arenaOpt, NSSItem *rvOpt, + nssStringType type, NSSUTF8 *string); /* * nssUTF8_CopyIntoFixedBuffer * - * This will copy a UTF8 string into a fixed-length buffer, making + * This will copy a UTF8 string into a fixed-length buffer, making * sure that the all characters are valid. Any remaining space will - * be padded with the specified ASCII character, typically either + * be padded with the specified ASCII character, typically either * null or space. * * Blah, blah, blah. @@ -789,27 +672,16 @@ nssUTF8_GetEncoding extern const NSSError NSS_ERROR_INVALID_POINTER; extern const NSSError NSS_ERROR_INVALID_ARGUMENT; -NSS_EXTERN PRStatus -nssUTF8_CopyIntoFixedBuffer -( - NSSUTF8 *string, - char *buffer, - PRUint32 bufferSize, - char pad -); +NSS_EXTERN PRStatus nssUTF8_CopyIntoFixedBuffer(NSSUTF8 *string, char *buffer, + PRUint32 bufferSize, char pad); /* * nssUTF8_Equal * */ -NSS_EXTERN PRBool -nssUTF8_Equal -( - const NSSUTF8 *a, - const NSSUTF8 *b, - PRStatus *statusOpt -); +NSS_EXTERN PRBool nssUTF8_Equal(const NSSUTF8 *a, const NSSUTF8 *b, + PRStatus *statusOpt); /* * nssList @@ -826,28 +698,15 @@ nssUTF8_Equal * If threadsafe is true, the list will be locked during modifications * and traversals. */ -NSS_EXTERN nssList * -nssList_Create -( - NSSArena *arenaOpt, - PRBool threadSafe -); +NSS_EXTERN nssList *nssList_Create(NSSArena *arenaOpt, PRBool threadSafe); /* * nssList_Destroy */ -NSS_EXTERN PRStatus -nssList_Destroy -( - nssList *list -); +NSS_EXTERN PRStatus nssList_Destroy(nssList *list); -NSS_EXTERN void -nssList_Clear -( - nssList *list, - nssListElementDestructorFunc destructor -); +NSS_EXTERN void nssList_Clear(nssList *list, + nssListElementDestructorFunc destructor); /* * nssList_SetCompareFunction @@ -856,34 +715,21 @@ nssList_Clear * data pointers. By setting this function, the user can control * how elements are compared. */ -NSS_EXTERN void -nssList_SetCompareFunction -( - nssList *list, - nssListCompareFunc compareFunc -); +NSS_EXTERN void nssList_SetCompareFunction(nssList *list, + nssListCompareFunc compareFunc); /* * nssList_SetSortFunction * * Sort function to use for an ordered list. */ -NSS_EXTERN void -nssList_SetSortFunction -( - nssList *list, - nssListSortFunc sortFunc -); +NSS_EXTERN void nssList_SetSortFunction(nssList *list, + nssListSortFunc sortFunc); /* * nssList_Add */ -NSS_EXTERN PRStatus -nssList_Add -( - nssList *list, - void *data -); +NSS_EXTERN PRStatus nssList_Add(nssList *list, void *data); /* * nssList_AddUnique @@ -891,20 +737,14 @@ nssList_Add * This will use the compare function to see if the element is already * in the list. */ -NSS_EXTERN PRStatus -nssList_AddUnique -( - nssList *list, - void *data -); +NSS_EXTERN PRStatus nssList_AddUnique(nssList *list, void *data); /* * nssList_Remove * * Uses the compare function to locate the element and remove it. */ -NSS_EXTERN PRStatus -nssList_Remove(nssList *list, void *data); +NSS_EXTERN PRStatus nssList_Remove(nssList *list, void *data); /* * nssList_Get @@ -912,21 +752,12 @@ nssList_Remove(nssList *list, void *data); * Uses the compare function to locate an element. Also serves as * nssList_Exists. */ -NSS_EXTERN void * -nssList_Get -( - nssList *list, - void *data -); +NSS_EXTERN void *nssList_Get(nssList *list, void *data); /* * nssList_Count */ -NSS_EXTERN PRUint32 -nssList_Count -( - nssList *list -); +NSS_EXTERN PRUint32 nssList_Count(nssList *list); /* * nssList_GetArray @@ -934,39 +765,22 @@ nssList_Count * Fill rvArray, up to maxElements, with elements in the list. The * array is NULL-terminated, so its allocated size must be maxElements + 1. */ -NSS_EXTERN PRStatus -nssList_GetArray -( - nssList *list, - void **rvArray, - PRUint32 maxElements -); +NSS_EXTERN PRStatus nssList_GetArray(nssList *list, void **rvArray, + PRUint32 maxElements); /* * nssList_CreateIterator * * Create an iterator for list traversal. */ -NSS_EXTERN nssListIterator * -nssList_CreateIterator -( - nssList *list -); +NSS_EXTERN nssListIterator *nssList_CreateIterator(nssList *list); -NSS_EXTERN nssList * -nssList_Clone -( - nssList *list -); +NSS_EXTERN nssList *nssList_Clone(nssList *list); /* * nssListIterator_Destroy */ -NSS_EXTERN void -nssListIterator_Destroy -( - nssListIterator *iter -); +NSS_EXTERN void nssListIterator_Destroy(nssListIterator *iter); /* * nssListIterator_Start @@ -974,22 +788,14 @@ nssListIterator_Destroy * Begin a list iteration. After this call, if the list is threadSafe, * the list is *locked*. */ -NSS_EXTERN void * -nssListIterator_Start -( - nssListIterator *iter -); +NSS_EXTERN void *nssListIterator_Start(nssListIterator *iter); /* * nssListIterator_Next * * Continue a list iteration. */ -NSS_EXTERN void * -nssListIterator_Next -( - nssListIterator *iter -); +NSS_EXTERN void *nssListIterator_Next(nssListIterator *iter); /* * nssListIterator_Finish @@ -997,11 +803,7 @@ nssListIterator_Next * Complete a list iteration. This *must* be called in order for the * lock to be released. */ -NSS_EXTERN PRStatus -nssListIterator_Finish -( - nssListIterator *iter -); +NSS_EXTERN PRStatus nssListIterator_Finish(nssListIterator *iter); /* * nssHash @@ -1021,46 +823,24 @@ nssListIterator_Finish * */ -NSS_EXTERN nssHash * -nssHash_Create -( - NSSArena *arenaOpt, - PRUint32 numBuckets, - PLHashFunction keyHash, - PLHashComparator keyCompare, - PLHashComparator valueCompare -); +NSS_EXTERN nssHash *nssHash_Create(NSSArena *arenaOpt, PRUint32 numBuckets, + PLHashFunction keyHash, + PLHashComparator keyCompare, + PLHashComparator valueCompare); -NSS_EXTERN nssHash * -nssHash_CreatePointer -( - NSSArena *arenaOpt, - PRUint32 numBuckets -); +NSS_EXTERN nssHash *nssHash_CreatePointer(NSSArena *arenaOpt, + PRUint32 numBuckets); -NSS_EXTERN nssHash * -nssHash_CreateString -( - NSSArena *arenaOpt, - PRUint32 numBuckets -); +NSS_EXTERN nssHash *nssHash_CreateString(NSSArena *arenaOpt, + PRUint32 numBuckets); -NSS_EXTERN nssHash * -nssHash_CreateItem -( - NSSArena *arenaOpt, - PRUint32 numBuckets -); +NSS_EXTERN nssHash *nssHash_CreateItem(NSSArena *arenaOpt, PRUint32 numBuckets); /* * nssHash_Destroy * */ -NSS_EXTERN void -nssHash_Destroy -( - nssHash *hash -); +NSS_EXTERN void nssHash_Destroy(nssHash *hash); /* * nssHash_Add @@ -1069,75 +849,45 @@ nssHash_Destroy extern const NSSError NSS_ERROR_HASH_COLLISION; -NSS_EXTERN PRStatus -nssHash_Add -( - nssHash *hash, - const void *key, - const void *value -); +NSS_EXTERN PRStatus nssHash_Add(nssHash *hash, const void *key, + const void *value); /* * nssHash_Remove * */ -NSS_EXTERN void -nssHash_Remove -( - nssHash *hash, - const void *it -); +NSS_EXTERN void nssHash_Remove(nssHash *hash, const void *it); /* * nssHash_Count * */ -NSS_EXTERN PRUint32 -nssHash_Count -( - nssHash *hash -); +NSS_EXTERN PRUint32 nssHash_Count(nssHash *hash); /* * nssHash_Exists * */ -NSS_EXTERN PRBool -nssHash_Exists -( - nssHash *hash, - const void *it -); +NSS_EXTERN PRBool nssHash_Exists(nssHash *hash, const void *it); /* * nssHash_Lookup * */ -NSS_EXTERN void * -nssHash_Lookup -( - nssHash *hash, - const void *it -); +NSS_EXTERN void *nssHash_Lookup(nssHash *hash, const void *it); /* * nssHash_Iterate * */ -NSS_EXTERN void -nssHash_Iterate -( - nssHash *hash, - nssHashIterator fcn, - void *closure -); - +NSS_EXTERN void nssHash_Iterate(nssHash *hash, nssHashIterator fcn, + void *closure); /* * nssPointerTracker * * This type and these methods are only present in debug builds. - * + * * The nonpublic methods relating to this type are: * * nssPointerTracker_initialize @@ -1151,13 +901,13 @@ nssHash_Iterate * nssPointerTracker_initialize * * This method is only present in debug builds. - * + * * This routine initializes an nssPointerTracker object. Note that * the object must have been declared *static* to guarantee that it * is in a zeroed state initially. This routine is idempotent, and - * may even be safely called by multiple threads simultaneously with - * the same argument. This routine returns a PRStatus value; if - * successful, it will return PR_SUCCESS. On failure it will set an + * may even be safely called by multiple threads simultaneously with + * the same argument. This routine returns a PRStatus value; if + * successful, it will return PR_SUCCESS. On failure it will set an * error on the error stack and return PR_FAILURE. * * The error may be one of the following values: @@ -1169,11 +919,7 @@ nssHash_Iterate */ #ifdef DEBUG -NSS_EXTERN PRStatus -nssPointerTracker_initialize -( - nssPointerTracker *tracker -); +NSS_EXTERN PRStatus nssPointerTracker_initialize(nssPointerTracker *tracker); extern const NSSError NSS_ERROR_NO_MEMORY; #endif /* DEBUG */ @@ -1182,7 +928,7 @@ extern const NSSError NSS_ERROR_NO_MEMORY; * nssPointerTracker_finalize * * This method is only present in debug builds. - * + * * This routine returns the nssPointerTracker object to the pre- * initialized state, releasing all resources used by the object. * It will *NOT* destroy the objects being tracked by the pointer @@ -1202,11 +948,7 @@ extern const NSSError NSS_ERROR_NO_MEMORY; */ #ifdef DEBUG -NSS_EXTERN PRStatus -nssPointerTracker_finalize -( - nssPointerTracker *tracker -); +NSS_EXTERN PRStatus nssPointerTracker_finalize(nssPointerTracker *tracker); extern const NSSError NSS_ERROR_TRACKER_NOT_EMPTY; #endif /* DEBUG */ @@ -1234,12 +976,8 @@ extern const NSSError NSS_ERROR_TRACKER_NOT_EMPTY; */ #ifdef DEBUG -NSS_EXTERN PRStatus -nssPointerTracker_add -( - nssPointerTracker *tracker, - const void *pointer -); +NSS_EXTERN PRStatus nssPointerTracker_add(nssPointerTracker *tracker, + const void *pointer); extern const NSSError NSS_ERROR_NO_MEMORY; extern const NSSError NSS_ERROR_TRACKER_NOT_INITIALIZED; @@ -1251,12 +989,12 @@ extern const NSSError NSS_ERROR_DUPLICATE_POINTER; * * This method is only present in debug builds. * - * This routine removes the specified pointer from the + * This routine removes the specified pointer from the * nssPointerTracker object. It does not call any destructor for the * object; rather, this should be called from the object's destructor. - * The nssPointerTracker is threadsafe, but this call is not - * idempotent. This routine returns a PRStatus value; if successful - * it will return PR_SUCCESS. On failure it will set an error on the + * The nssPointerTracker is threadsafe, but this call is not + * idempotent. This routine returns a PRStatus value; if successful + * it will return PR_SUCCESS. On failure it will set an error on the * error stack and return PR_FAILURE. * * The error may be one of the following values: @@ -1269,12 +1007,8 @@ extern const NSSError NSS_ERROR_DUPLICATE_POINTER; */ #ifdef DEBUG -NSS_EXTERN PRStatus -nssPointerTracker_remove -( - nssPointerTracker *tracker, - const void *pointer -); +NSS_EXTERN PRStatus nssPointerTracker_remove(nssPointerTracker *tracker, + const void *pointer); extern const NSSError NSS_ERROR_TRACKER_NOT_INITIALIZED; extern const NSSError NSS_ERROR_POINTER_NOT_REGISTERED; @@ -1289,10 +1023,10 @@ extern const NSSError NSS_ERROR_POINTER_NOT_REGISTERED; * with the nssPointerTracker object. The nssPointerTracker object is * threadsafe, and this call may be safely called from multiple threads * simultaneously with the same arguments. This routine returns a - * PRStatus value; if the pointer is registered this will return - * PR_SUCCESS. Otherwise it will set an error on the error stack and - * return PR_FAILURE. Although the error is suitable for leaving on - * the stack, callers may wish to augment the information available by + * PRStatus value; if the pointer is registered this will return + * PR_SUCCESS. Otherwise it will set an error on the error stack and + * return PR_FAILURE. Although the error is suitable for leaving on + * the stack, callers may wish to augment the information available by * placing a more type-specific error on the stack. * * The error may be one of the following values: @@ -1304,12 +1038,8 @@ extern const NSSError NSS_ERROR_POINTER_NOT_REGISTERED; */ #ifdef DEBUG -NSS_EXTERN PRStatus -nssPointerTracker_verify -( - nssPointerTracker *tracker, - const void *pointer -); +NSS_EXTERN PRStatus nssPointerTracker_verify(nssPointerTracker *tracker, + const void *pointer); extern const NSSError NSS_ERROR_POINTER_NOT_REGISTERED; #endif /* DEBUG */ @@ -1333,13 +1063,7 @@ extern const NSSError NSS_ERROR_POINTER_NOT_REGISTERED; * The destination pointer on success */ -NSS_EXTERN void * -nsslibc_memcpy -( - void *dest, - const void *source, - PRUint32 n -); +NSS_EXTERN void *nsslibc_memcpy(void *dest, const void *source, PRUint32 n); extern const NSSError NSS_ERROR_INVALID_POINTER; @@ -1354,13 +1078,7 @@ extern const NSSError NSS_ERROR_INVALID_POINTER; * The destination pointer on success */ -NSS_EXTERN void * -nsslibc_memset -( - void *dest, - PRUint8 byte, - PRUint32 n -); +NSS_EXTERN void *nsslibc_memset(void *dest, PRUint8 byte, PRUint32 n); extern const NSSError NSS_ERROR_INVALID_POINTER; @@ -1376,14 +1094,8 @@ extern const NSSError NSS_ERROR_INVALID_POINTER; * PR_FALSE upon error */ -NSS_EXTERN PRBool -nsslibc_memequal -( - const void *a, - const void *b, - PRUint32 len, - PRStatus *statusOpt -); +NSS_EXTERN PRBool nsslibc_memequal(const void *a, const void *b, PRUint32 len, + PRStatus *statusOpt); extern const NSSError NSS_ERROR_INVALID_POINTER; diff --git a/security/nss/lib/base/baset.h b/security/nss/lib/base/baset.h index 3c9f828d0948..3953a755e5bf 100644 --- a/security/nss/lib/base/baset.h +++ b/security/nss/lib/base/baset.h @@ -32,7 +32,7 @@ typedef struct nssArenaMarkStr nssArenaMark; #ifdef DEBUG /* * ARENA_THREADMARK - * + * * Optionally, this arena implementation can be compiled with some * runtime checking enabled, which will catch the situation where * one thread "marks" the arena, another thread allocates memory, @@ -68,14 +68,13 @@ typedef struct nssArenaMarkStr nssArenaMark; typedef struct nssListStr nssList; typedef struct nssListIteratorStr nssListIterator; -typedef PRBool (* nssListCompareFunc)(void *a, void *b); -typedef PRIntn (* nssListSortFunc)(void *a, void *b); -typedef void (* nssListElementDestructorFunc)(void *el); +typedef PRBool (*nssListCompareFunc)(void *a, void *b); +typedef PRIntn (*nssListSortFunc)(void *a, void *b); +typedef void (*nssListElementDestructorFunc)(void *el); typedef struct nssHashStr nssHash; -typedef void (PR_CALLBACK *nssHashIterator)(const void *key, - void *value, - void *arg); +typedef void(PR_CALLBACK *nssHashIterator)(const void *key, void *value, + void *arg); /* * nssPointerTracker @@ -89,9 +88,9 @@ typedef void (PR_CALLBACK *nssHashIterator)(const void *key, #ifdef DEBUG struct nssPointerTrackerStr { - PRCallOnceType once; - PZLock *lock; - PLHashTable *table; + PRCallOnceType once; + PZLock *lock; + PLHashTable *table; }; typedef struct nssPointerTrackerStr nssPointerTracker; #endif /* DEBUG */ @@ -107,16 +106,16 @@ typedef struct nssPointerTrackerStr nssPointerTracker; */ enum nssStringTypeEnum { - nssStringType_DirectoryString, - nssStringType_TeletexString, /* Not "teletext" with trailing 't' */ - nssStringType_PrintableString, - nssStringType_UniversalString, - nssStringType_BMPString, - nssStringType_UTF8String, - nssStringType_PHGString, - nssStringType_GeneralString, + nssStringType_DirectoryString, + nssStringType_TeletexString, /* Not "teletext" with trailing 't' */ + nssStringType_PrintableString, + nssStringType_UniversalString, + nssStringType_BMPString, + nssStringType_UTF8String, + nssStringType_PHGString, + nssStringType_GeneralString, - nssStringType_Unknown = -1 + nssStringType_Unknown = -1 }; typedef enum nssStringTypeEnum nssStringType; diff --git a/security/nss/lib/base/error.c b/security/nss/lib/base/error.c index 807bbd4fff33..679f2ba9ea84 100644 --- a/security/nss/lib/base/error.c +++ b/security/nss/lib/base/error.c @@ -5,13 +5,13 @@ /* * error.c * - * This file contains the code implementing the per-thread error + * This file contains the code implementing the per-thread error * stacks upon which most NSS routines report their errors. */ #ifndef BASE_H #include "base.h" -#endif /* BASE_H */ +#endif /* BASE_H */ #include /* for UINT_MAX */ #include /* for memmove */ @@ -25,13 +25,13 @@ */ struct stack_header_str { - PRUint16 space; - PRUint16 count; + PRUint16 space; + PRUint16 count; }; struct error_stack_str { - struct stack_header_str header; - PRInt32 stack[1]; + struct stack_header_str header; + PRInt32 stack[1]; }; typedef struct error_stack_str error_stack; @@ -62,9 +62,9 @@ static PRCallOnceType error_call_once; * This is the once-called callback. */ static PRStatus -error_once_function ( void) +error_once_function(void) { - return PR_NewThreadPrivateIndex(&error_stack_index, PR_Free); + return PR_NewThreadPrivateIndex(&error_stack_index, PR_Free); } /* @@ -76,48 +76,50 @@ error_once_function ( void) */ static error_stack * -error_get_my_stack ( void) +error_get_my_stack(void) { - PRStatus st; - error_stack *rv; - PRUintn new_size; - PRUint32 new_bytes; - error_stack *new_stack; + PRStatus st; + error_stack *rv; + PRUintn new_size; + PRUint32 new_bytes; + error_stack *new_stack; - if( INVALID_TPD_INDEX == error_stack_index ) { - st = PR_CallOnce(&error_call_once, error_once_function); - if( PR_SUCCESS != st ) { - return (error_stack *)NULL; + if (INVALID_TPD_INDEX == error_stack_index) { + st = PR_CallOnce(&error_call_once, error_once_function); + if (PR_SUCCESS != st) { + return (error_stack *)NULL; + } } - } - rv = (error_stack *)PR_GetThreadPrivate(error_stack_index); - if( (error_stack *)NULL == rv ) { - /* Doesn't exist; create one */ - new_size = 16; - } else if( rv->header.count == rv->header.space && - rv->header.count < NSS_MAX_ERROR_STACK_COUNT ) { - /* Too small, expand it */ - new_size = PR_MIN( rv->header.space * 2, NSS_MAX_ERROR_STACK_COUNT); - } else { - /* Okay, return it */ - return rv; - } - - new_bytes = (new_size * sizeof(PRInt32)) + sizeof(error_stack); - /* Use NSPR's calloc/realloc, not NSS's, to avoid loops! */ - new_stack = PR_Calloc(1, new_bytes); - - if( (error_stack *)NULL != new_stack ) { - if( (error_stack *)NULL != rv ) { - (void)nsslibc_memcpy(new_stack,rv,rv->header.space); + rv = (error_stack *)PR_GetThreadPrivate(error_stack_index); + if ((error_stack *)NULL == rv) { + /* Doesn't exist; create one */ + new_size = 16; + } + else if (rv->header.count == rv->header.space && + rv->header.count < NSS_MAX_ERROR_STACK_COUNT) { + /* Too small, expand it */ + new_size = PR_MIN(rv->header.space * 2, NSS_MAX_ERROR_STACK_COUNT); + } + else { + /* Okay, return it */ + return rv; } - new_stack->header.space = new_size; - } - /* Set the value, whether or not the allocation worked */ - PR_SetThreadPrivate(error_stack_index, new_stack); - return new_stack; + new_bytes = (new_size * sizeof(PRInt32)) + sizeof(error_stack); + /* Use NSPR's calloc/realloc, not NSS's, to avoid loops! */ + new_stack = PR_Calloc(1, new_bytes); + + if ((error_stack *)NULL != new_stack) { + if ((error_stack *)NULL != rv) { + (void)nsslibc_memcpy(new_stack, rv, rv->header.space); + } + new_stack->header.space = new_size; + } + + /* Set the value, whether or not the allocation worked */ + PR_SetThreadPrivate(error_stack_index, new_stack); + return new_stack; } /* @@ -151,19 +153,19 @@ error_get_my_stack ( void) */ NSS_IMPLEMENT PRInt32 -NSS_GetError ( void) +NSS_GetError(void) { - error_stack *es = error_get_my_stack(); + error_stack *es = error_get_my_stack(); - if( (error_stack *)NULL == es ) { - return NSS_ERROR_NO_MEMORY; /* Good guess! */ - } + if ((error_stack *)NULL == es) { + return NSS_ERROR_NO_MEMORY; /* Good guess! */ + } - if( 0 == es->header.count ) { - return 0; - } + if (0 == es->header.count) { + return 0; + } - return es->stack[ es->header.count-1 ]; + return es->stack[es->header.count - 1]; } /* @@ -174,7 +176,7 @@ NSS_GetError ( void) * library routine called by the same thread calling this routine. * NOTE: the caller DOES NOT OWN the memory pointed to by the return * value. The pointer will remain valid until the calling thread - * calls another NSS routine. The lowest-level (most specific) error + * calls another NSS routine. The lowest-level (most specific) error * is first in the array, and the highest-level is last. The array is * zero-terminated. This routine may return NULL upon error; this * indicates a low-memory situation. @@ -185,52 +187,53 @@ NSS_GetError ( void) */ NSS_IMPLEMENT PRInt32 * -NSS_GetErrorStack ( void) +NSS_GetErrorStack(void) { - error_stack *es = error_get_my_stack(); + error_stack *es = error_get_my_stack(); - if( (error_stack *)NULL == es ) { - return (PRInt32 *)NULL; - } + if ((error_stack *)NULL == es) { + return (PRInt32 *)NULL; + } - /* Make sure it's terminated */ - es->stack[ es->header.count ] = 0; + /* Make sure it's terminated */ + es->stack[es->header.count] = 0; - return es->stack; + return es->stack; } /* * nss_SetError * - * This routine places a new error code on the top of the calling + * This routine places a new error code on the top of the calling * thread's error stack. Calling this routine wiht an error code * of zero will clear the error stack. */ NSS_IMPLEMENT void -nss_SetError ( PRUint32 error) +nss_SetError(PRUint32 error) { - error_stack *es; + error_stack *es; - if( 0 == error ) { - nss_ClearErrorStack(); + if (0 == error) { + nss_ClearErrorStack(); + return; + } + + es = error_get_my_stack(); + if ((error_stack *)NULL == es) { + /* Oh, well. */ + return; + } + + if (es->header.count < es->header.space) { + es->stack[es->header.count++] = error; + } + else { + memmove(es->stack, es->stack + 1, + (es->header.space - 1) * (sizeof es->stack[0])); + es->stack[es->header.space - 1] = error; + } return; - } - - es = error_get_my_stack(); - if( (error_stack *)NULL == es ) { - /* Oh, well. */ - return; - } - - if (es->header.count < es->header.space) { - es->stack[ es->header.count++ ] = error; - } else { - memmove(es->stack, es->stack + 1, - (es->header.space - 1) * (sizeof es->stack[0])); - es->stack[ es->header.space - 1 ] = error; - } - return; } /* @@ -240,17 +243,17 @@ nss_SetError ( PRUint32 error) */ NSS_IMPLEMENT void -nss_ClearErrorStack ( void) +nss_ClearErrorStack(void) { - error_stack *es = error_get_my_stack(); - if( (error_stack *)NULL == es ) { - /* Oh, well. */ - return; - } + error_stack *es = error_get_my_stack(); + if ((error_stack *)NULL == es) { + /* Oh, well. */ + return; + } - es->header.count = 0; - es->stack[0] = 0; - return; + es->header.count = 0; + es->stack[0] = 0; + return; } /* @@ -260,10 +263,10 @@ nss_ClearErrorStack ( void) */ NSS_IMPLEMENT void -nss_DestroyErrorStack ( void) +nss_DestroyErrorStack(void) { - if( INVALID_TPD_INDEX != error_stack_index ) { - PR_SetThreadPrivate(error_stack_index, NULL); - } - return; + if (INVALID_TPD_INDEX != error_stack_index) { + PR_SetThreadPrivate(error_stack_index, NULL); + } + return; } diff --git a/security/nss/lib/base/errorval.c b/security/nss/lib/base/errorval.c index 4e6f55588378..b7045a390583 100644 --- a/security/nss/lib/base/errorval.c +++ b/security/nss/lib/base/errorval.c @@ -12,6 +12,8 @@ #include "nssbaset.h" #endif /* NSSBASET_H */ +/* clang-format off */ + const NSSError NSS_ERROR_NO_ERROR = 0; const NSSError NSS_ERROR_INTERNAL_ERROR = 1; const NSSError NSS_ERROR_NO_MEMORY = 2; @@ -60,3 +62,4 @@ const NSSError NSS_ERROR_ALREADY_INITIALIZED = 37; const NSSError NSS_ERROR_PKCS11 = 38; +/* clang-format on */ \ No newline at end of file diff --git a/security/nss/lib/base/hash.c b/security/nss/lib/base/hash.c index 7eaaf6ff0a5c..ab2596f18ad4 100644 --- a/security/nss/lib/base/hash.c +++ b/security/nss/lib/base/hash.c @@ -32,48 +32,42 @@ */ struct nssHashStr { - NSSArena *arena; - PRBool i_alloced_arena; - PRLock *mutex; + NSSArena *arena; + PRBool i_alloced_arena; + PRLock *mutex; - /* - * The invariant that mutex protects is: - * The count accurately reflects the hashtable state. - */ + /* + * The invariant that mutex protects is: + * The count accurately reflects the hashtable state. + */ - PLHashTable *plHashTable; - PRUint32 count; + PLHashTable *plHashTable; + PRUint32 count; }; static PLHashNumber -nss_identity_hash -( - const void *key -) +nss_identity_hash(const void *key) { - return (PLHashNumber)((char *)key - (char *)NULL); + return (PLHashNumber)((char *)key - (char *)NULL); } static PLHashNumber -nss_item_hash -( - const void *key -) +nss_item_hash(const void *key) { - unsigned int i; - PLHashNumber h; - NSSItem *it = (NSSItem *)key; - h = 0; - for (i=0; isize; i++) - h = PR_ROTATE_LEFT32(h, 4) ^ ((unsigned char *)it->data)[i]; - return h; + unsigned int i; + PLHashNumber h; + NSSItem *it = (NSSItem *)key; + h = 0; + for (i = 0; i < it->size; i++) + h = PR_ROTATE_LEFT32(h, 4) ^ ((unsigned char *)it->data)[i]; + return h; } static int nss_compare_items(const void *v1, const void *v2) { - PRStatus ignore; - return (int)nssItem_Equal((NSSItem *)v1, (NSSItem *)v2, &ignore); + PRStatus ignore; + return (int)nssItem_Equal((NSSItem *)v1, (NSSItem *)v2, &ignore); } /* @@ -81,60 +75,55 @@ nss_compare_items(const void *v1, const void *v2) * */ NSS_IMPLEMENT nssHash * -nssHash_Create -( - NSSArena *arenaOpt, - PRUint32 numBuckets, - PLHashFunction keyHash, - PLHashComparator keyCompare, - PLHashComparator valueCompare -) +nssHash_Create(NSSArena *arenaOpt, PRUint32 numBuckets, PLHashFunction keyHash, + PLHashComparator keyCompare, PLHashComparator valueCompare) { - nssHash *rv; - NSSArena *arena; - PRBool i_alloced; + nssHash *rv; + NSSArena *arena; + PRBool i_alloced; #ifdef NSSDEBUG - if( arenaOpt && PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (nssHash *)NULL; - } + if (arenaOpt && PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (nssHash *)NULL; + } #endif /* NSSDEBUG */ - if (arenaOpt) { - arena = arenaOpt; - i_alloced = PR_FALSE; - } else { - arena = nssArena_Create(); - i_alloced = PR_TRUE; - } + if (arenaOpt) { + arena = arenaOpt; + i_alloced = PR_FALSE; + } + else { + arena = nssArena_Create(); + i_alloced = PR_TRUE; + } - rv = nss_ZNEW(arena, nssHash); - if( (nssHash *)NULL == rv ) { - goto loser; - } + rv = nss_ZNEW(arena, nssHash); + if ((nssHash *)NULL == rv) { + goto loser; + } - rv->mutex = PZ_NewLock(nssILockOther); - if( (PZLock *)NULL == rv->mutex ) { - goto loser; - } + rv->mutex = PZ_NewLock(nssILockOther); + if ((PZLock *)NULL == rv->mutex) { + goto loser; + } - rv->plHashTable = PL_NewHashTable(numBuckets, - keyHash, keyCompare, valueCompare, - &nssArenaHashAllocOps, arena); - if( (PLHashTable *)NULL == rv->plHashTable ) { - (void)PZ_DestroyLock(rv->mutex); - goto loser; - } + rv->plHashTable = + PL_NewHashTable(numBuckets, keyHash, keyCompare, valueCompare, + &nssArenaHashAllocOps, arena); + if ((PLHashTable *)NULL == rv->plHashTable) { + (void)PZ_DestroyLock(rv->mutex); + goto loser; + } - rv->count = 0; - rv->arena = arena; - rv->i_alloced_arena = i_alloced; + rv->count = 0; + rv->arena = arena; + rv->i_alloced_arena = i_alloced; - return rv; + return rv; loser: - (void)nss_ZFreeIf(rv); - return (nssHash *)NULL; + (void)nss_ZFreeIf(rv); + return (nssHash *)NULL; } /* @@ -142,14 +131,10 @@ loser: * */ NSS_IMPLEMENT nssHash * -nssHash_CreatePointer -( - NSSArena *arenaOpt, - PRUint32 numBuckets -) +nssHash_CreatePointer(NSSArena *arenaOpt, PRUint32 numBuckets) { - return nssHash_Create(arenaOpt, numBuckets, - nss_identity_hash, PL_CompareValues, PL_CompareValues); + return nssHash_Create(arenaOpt, numBuckets, nss_identity_hash, + PL_CompareValues, PL_CompareValues); } /* @@ -157,14 +142,10 @@ nssHash_CreatePointer * */ NSS_IMPLEMENT nssHash * -nssHash_CreateString -( - NSSArena *arenaOpt, - PRUint32 numBuckets -) +nssHash_CreateString(NSSArena *arenaOpt, PRUint32 numBuckets) { - return nssHash_Create(arenaOpt, numBuckets, - PL_HashString, PL_CompareStrings, PL_CompareStrings); + return nssHash_Create(arenaOpt, numBuckets, PL_HashString, + PL_CompareStrings, PL_CompareStrings); } /* @@ -172,14 +153,10 @@ nssHash_CreateString * */ NSS_IMPLEMENT nssHash * -nssHash_CreateItem -( - NSSArena *arenaOpt, - PRUint32 numBuckets -) +nssHash_CreateItem(NSSArena *arenaOpt, PRUint32 numBuckets) { - return nssHash_Create(arenaOpt, numBuckets, - nss_item_hash, nss_compare_items, PL_CompareValues); + return nssHash_Create(arenaOpt, numBuckets, nss_item_hash, + nss_compare_items, PL_CompareValues); } /* @@ -187,18 +164,16 @@ nssHash_CreateItem * */ NSS_IMPLEMENT void -nssHash_Destroy -( - nssHash *hash -) +nssHash_Destroy(nssHash *hash) { - (void)PZ_DestroyLock(hash->mutex); - PL_HashTableDestroy(hash->plHashTable); - if (hash->i_alloced_arena) { - nssArena_Destroy(hash->arena); - } else { - nss_ZFreeIf(hash); - } + (void)PZ_DestroyLock(hash->mutex); + PL_HashTableDestroy(hash->plHashTable); + if (hash->i_alloced_arena) { + nssArena_Destroy(hash->arena); + } + else { + nss_ZFreeIf(hash); + } } /* @@ -206,31 +181,28 @@ nssHash_Destroy * */ NSS_IMPLEMENT PRStatus -nssHash_Add -( - nssHash *hash, - const void *key, - const void *value -) +nssHash_Add(nssHash *hash, const void *key, const void *value) { - PRStatus error = PR_FAILURE; - PLHashEntry *he; + PRStatus error = PR_FAILURE; + PLHashEntry *he; - PZ_Lock(hash->mutex); - - he = PL_HashTableAdd(hash->plHashTable, key, (void *)value); - if( (PLHashEntry *)NULL == he ) { - nss_SetError(NSS_ERROR_NO_MEMORY); - } else if (he->value != value) { - nss_SetError(NSS_ERROR_HASH_COLLISION); - } else { - hash->count++; - error = PR_SUCCESS; - } + PZ_Lock(hash->mutex); - (void)PZ_Unlock(hash->mutex); + he = PL_HashTableAdd(hash->plHashTable, key, (void *)value); + if ((PLHashEntry *)NULL == he) { + nss_SetError(NSS_ERROR_NO_MEMORY); + } + else if (he->value != value) { + nss_SetError(NSS_ERROR_HASH_COLLISION); + } + else { + hash->count++; + error = PR_SUCCESS; + } - return error; + (void)PZ_Unlock(hash->mutex); + + return error; } /* @@ -238,23 +210,19 @@ nssHash_Add * */ NSS_IMPLEMENT void -nssHash_Remove -( - nssHash *hash, - const void *it -) +nssHash_Remove(nssHash *hash, const void *it) { - PRBool found; + PRBool found; - PZ_Lock(hash->mutex); + PZ_Lock(hash->mutex); - found = PL_HashTableRemove(hash->plHashTable, it); - if( found ) { - hash->count--; - } + found = PL_HashTableRemove(hash->plHashTable, it); + if (found) { + hash->count--; + } - (void)PZ_Unlock(hash->mutex); - return; + (void)PZ_Unlock(hash->mutex); + return; } /* @@ -262,20 +230,17 @@ nssHash_Remove * */ NSS_IMPLEMENT PRUint32 -nssHash_Count -( - nssHash *hash -) +nssHash_Count(nssHash *hash) { - PRUint32 count; + PRUint32 count; - PZ_Lock(hash->mutex); + PZ_Lock(hash->mutex); - count = hash->count; + count = hash->count; - (void)PZ_Unlock(hash->mutex); + (void)PZ_Unlock(hash->mutex); - return count; + return count; } /* @@ -283,25 +248,22 @@ nssHash_Count * */ NSS_IMPLEMENT PRBool -nssHash_Exists -( - nssHash *hash, - const void *it -) +nssHash_Exists(nssHash *hash, const void *it) { - void *value; + void *value; - PZ_Lock(hash->mutex); + PZ_Lock(hash->mutex); - value = PL_HashTableLookup(hash->plHashTable, it); + value = PL_HashTableLookup(hash->plHashTable, it); - (void)PZ_Unlock(hash->mutex); + (void)PZ_Unlock(hash->mutex); - if( (void *)NULL == value ) { - return PR_FALSE; - } else { - return PR_TRUE; - } + if ((void *)NULL == value) { + return PR_FALSE; + } + else { + return PR_TRUE; + } } /* @@ -309,39 +271,30 @@ nssHash_Exists * */ NSS_IMPLEMENT void * -nssHash_Lookup -( - nssHash *hash, - const void *it -) +nssHash_Lookup(nssHash *hash, const void *it) { - void *rv; + void *rv; - PZ_Lock(hash->mutex); + PZ_Lock(hash->mutex); - rv = PL_HashTableLookup(hash->plHashTable, it); + rv = PL_HashTableLookup(hash->plHashTable, it); - (void)PZ_Unlock(hash->mutex); + (void)PZ_Unlock(hash->mutex); - return rv; + return rv; } struct arg_str { - nssHashIterator fcn; - void *closure; + nssHashIterator fcn; + void *closure; }; static PRIntn -nss_hash_enumerator -( - PLHashEntry *he, - PRIntn index, - void *arg -) +nss_hash_enumerator(PLHashEntry *he, PRIntn index, void *arg) { - struct arg_str *as = (struct arg_str *)arg; - as->fcn(he->key, he->value, as->closure); - return HT_ENUMERATE_NEXT; + struct arg_str *as = (struct arg_str *)arg; + as->fcn(he->key, he->value, as->closure); + return HT_ENUMERATE_NEXT; } /* @@ -350,22 +303,17 @@ nss_hash_enumerator * NOTE that the iteration function will be called with the hashtable locked. */ NSS_IMPLEMENT void -nssHash_Iterate -( - nssHash *hash, - nssHashIterator fcn, - void *closure -) +nssHash_Iterate(nssHash *hash, nssHashIterator fcn, void *closure) { - struct arg_str as; - as.fcn = fcn; - as.closure = closure; + struct arg_str as; + as.fcn = fcn; + as.closure = closure; - PZ_Lock(hash->mutex); + PZ_Lock(hash->mutex); - PL_HashTableEnumerateEntries(hash->plHashTable, nss_hash_enumerator, &as); + PL_HashTableEnumerateEntries(hash->plHashTable, nss_hash_enumerator, &as); - (void)PZ_Unlock(hash->mutex); + (void)PZ_Unlock(hash->mutex); - return; + return; } diff --git a/security/nss/lib/base/hashops.c b/security/nss/lib/base/hashops.c index dd048ef79373..57b30dd1fd94 100644 --- a/security/nss/lib/base/hashops.c +++ b/security/nss/lib/base/hashops.c @@ -12,73 +12,53 @@ #include "base.h" #endif /* BASE_H */ -static void * PR_CALLBACK -nss_arena_hash_alloc_table -( - void *pool, - PRSize size -) +static void *PR_CALLBACK +nss_arena_hash_alloc_table(void *pool, PRSize size) { - NSSArena *arena = (NSSArena *)NULL; + NSSArena *arena = (NSSArena *)NULL; #ifdef NSSDEBUG - if( (void *)NULL != arena ) { - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return (void *)NULL; + if ((void *)NULL != arena) { + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return (void *)NULL; + } } - } #endif /* NSSDEBUG */ - return nss_ZAlloc(arena, size); + return nss_ZAlloc(arena, size); } static void PR_CALLBACK -nss_arena_hash_free_table -( - void *pool, - void *item -) +nss_arena_hash_free_table(void *pool, void *item) { - (void)nss_ZFreeIf(item); + (void)nss_ZFreeIf(item); } -static PLHashEntry * PR_CALLBACK -nss_arena_hash_alloc_entry -( - void *pool, - const void *key -) +static PLHashEntry *PR_CALLBACK +nss_arena_hash_alloc_entry(void *pool, const void *key) { - NSSArena *arena = NULL; + NSSArena *arena = NULL; #ifdef NSSDEBUG - if( (void *)NULL != arena ) { - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - return (void *)NULL; + if ((void *)NULL != arena) { + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + return (void *)NULL; + } } - } #endif /* NSSDEBUG */ - return nss_ZNEW(arena, PLHashEntry); + return nss_ZNEW(arena, PLHashEntry); } static void PR_CALLBACK -nss_arena_hash_free_entry -( - void *pool, - PLHashEntry *he, - PRUintn flag -) +nss_arena_hash_free_entry(void *pool, PLHashEntry *he, PRUintn flag) { - if( HT_FREE_ENTRY == flag ) { - (void)nss_ZFreeIf(he); - } + if (HT_FREE_ENTRY == flag) { + (void)nss_ZFreeIf(he); + } } -NSS_IMPLEMENT_DATA PLHashAllocOps -nssArenaHashAllocOps = { - nss_arena_hash_alloc_table, - nss_arena_hash_free_table, - nss_arena_hash_alloc_entry, - nss_arena_hash_free_entry +NSS_IMPLEMENT_DATA PLHashAllocOps nssArenaHashAllocOps = { + nss_arena_hash_alloc_table, nss_arena_hash_free_table, + nss_arena_hash_alloc_entry, nss_arena_hash_free_entry }; diff --git a/security/nss/lib/base/item.c b/security/nss/lib/base/item.c index dd463dcf92c9..6c25911837fc 100644 --- a/security/nss/lib/base/item.c +++ b/security/nss/lib/base/item.c @@ -22,78 +22,70 @@ * NSS_ERROR_NO_MEMORY * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD * NSS_ERROR_INVALID_POINTER - * + * * Return value: * A pointer to an NSSItem upon success * NULL upon failure */ NSS_IMPLEMENT NSSItem * -nssItem_Create -( - NSSArena *arenaOpt, - NSSItem *rvOpt, - PRUint32 length, - const void *data -) +nssItem_Create(NSSArena *arenaOpt, NSSItem *rvOpt, PRUint32 length, + const void *data) { - NSSItem *rv = (NSSItem *)NULL; + NSSItem *rv = (NSSItem *)NULL; #ifdef DEBUG - if( (NSSArena *)NULL != arenaOpt ) { - if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) { - return (NSSItem *)NULL; + if ((NSSArena *)NULL != arenaOpt) { + if (PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) { + return (NSSItem *)NULL; + } } - } - if( (const void *)NULL == data ) { - if( length > 0 ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (NSSItem *)NULL; + if ((const void *)NULL == data) { + if (length > 0) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (NSSItem *)NULL; + } } - } #endif /* DEBUG */ - if( (NSSItem *)NULL == rvOpt ) { - rv = (NSSItem *)nss_ZNEW(arenaOpt, NSSItem); - if( (NSSItem *)NULL == rv ) { - goto loser; + if ((NSSItem *)NULL == rvOpt) { + rv = (NSSItem *)nss_ZNEW(arenaOpt, NSSItem); + if ((NSSItem *)NULL == rv) { + goto loser; + } + } + else { + rv = rvOpt; } - } else { - rv = rvOpt; - } - rv->size = length; - rv->data = nss_ZAlloc(arenaOpt, length); - if( (void *)NULL == rv->data ) { - goto loser; - } + rv->size = length; + rv->data = nss_ZAlloc(arenaOpt, length); + if ((void *)NULL == rv->data) { + goto loser; + } - if( length > 0 ) { - (void)nsslibc_memcpy(rv->data, data, length); - } + if (length > 0) { + (void)nsslibc_memcpy(rv->data, data, length); + } - return rv; + return rv; - loser: - if( rv != rvOpt ) { - nss_ZFreeIf(rv); - } +loser: + if (rv != rvOpt) { + nss_ZFreeIf(rv); + } - return (NSSItem *)NULL; + return (NSSItem *)NULL; } NSS_IMPLEMENT void -nssItem_Destroy -( - NSSItem *item -) +nssItem_Destroy(NSSItem *item) { - nss_ClearErrorStack(); - - nss_ZFreeIf(item->data); - nss_ZFreeIf(item); + nss_ClearErrorStack(); + nss_ZFreeIf(item->data); + nss_ZFreeIf(item); } /* @@ -106,34 +98,29 @@ nssItem_Destroy * NSS_ERROR_NO_MEMORY * NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD * NSS_ERROR_INVALID_ITEM - * + * * Return value: * A pointer to an NSSItem upon success * NULL upon failure */ NSS_IMPLEMENT NSSItem * -nssItem_Duplicate -( - NSSItem *obj, - NSSArena *arenaOpt, - NSSItem *rvOpt -) +nssItem_Duplicate(NSSItem *obj, NSSArena *arenaOpt, NSSItem *rvOpt) { #ifdef DEBUG - if( (NSSArena *)NULL != arenaOpt ) { - if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) { - return (NSSItem *)NULL; + if ((NSSArena *)NULL != arenaOpt) { + if (PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) { + return (NSSItem *)NULL; + } } - } - if( (NSSItem *)NULL == obj ) { - nss_SetError(NSS_ERROR_INVALID_ITEM); - return (NSSItem *)NULL; - } + if ((NSSItem *)NULL == obj) { + nss_SetError(NSS_ERROR_INVALID_ITEM); + return (NSSItem *)NULL; + } #endif /* DEBUG */ - return nssItem_Create(arenaOpt, rvOpt, obj->size, obj->data); + return nssItem_Create(arenaOpt, rvOpt, obj->size, obj->data); } #ifdef DEBUG @@ -151,18 +138,15 @@ nssItem_Duplicate */ NSS_IMPLEMENT PRStatus -nssItem_verifyPointer -( - const NSSItem *item -) +nssItem_verifyPointer(const NSSItem *item) { - if( ((const NSSItem *)NULL == item) || - (((void *)NULL == item->data) && (item->size > 0)) ) { - nss_SetError(NSS_ERROR_INVALID_ITEM); - return PR_FAILURE; - } + if (((const NSSItem *)NULL == item) || + (((void *)NULL == item->data) && (item->size > 0))) { + nss_SetError(NSS_ERROR_INVALID_ITEM); + return PR_FAILURE; + } - return PR_SUCCESS; + return PR_SUCCESS; } #endif /* DEBUG */ @@ -181,28 +165,23 @@ nssItem_verifyPointer */ NSS_IMPLEMENT PRBool -nssItem_Equal -( - const NSSItem *one, - const NSSItem *two, - PRStatus *statusOpt -) +nssItem_Equal(const NSSItem *one, const NSSItem *two, PRStatus *statusOpt) { - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_SUCCESS; - } + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_SUCCESS; + } - if( ((const NSSItem *)NULL == one) && ((const NSSItem *)NULL == two) ) { - return PR_TRUE; - } + if (((const NSSItem *)NULL == one) && ((const NSSItem *)NULL == two)) { + return PR_TRUE; + } - if( ((const NSSItem *)NULL == one) || ((const NSSItem *)NULL == two) ) { - return PR_FALSE; - } + if (((const NSSItem *)NULL == one) || ((const NSSItem *)NULL == two)) { + return PR_FALSE; + } - if( one->size != two->size ) { - return PR_FALSE; - } + if (one->size != two->size) { + return PR_FALSE; + } - return nsslibc_memequal(one->data, two->data, one->size, statusOpt); + return nsslibc_memequal(one->data, two->data, one->size, statusOpt); } diff --git a/security/nss/lib/base/libc.c b/security/nss/lib/base/libc.c index 93a762727d06..721e4a241c39 100644 --- a/security/nss/lib/base/libc.c +++ b/security/nss/lib/base/libc.c @@ -5,10 +5,10 @@ /* * libc.c * - * This file contains our wrappers/reimplementations for "standard" - * libc functions. Things like "memcpy." We add to this as we need - * it. Oh, and let's keep it in alphabetical order, should it ever - * get large. Most string/character stuff should be in utf8.c, not + * This file contains our wrappers/reimplementations for "standard" + * libc functions. Things like "memcpy." We add to this as we need + * it. Oh, and let's keep it in alphabetical order, should it ever + * get large. Most string/character stuff should be in utf8.c, not * here. This file (and maybe utf8.c) should be the only ones in * NSS to include files with angle brackets. */ @@ -38,21 +38,16 @@ */ NSS_IMPLEMENT void * -nsslibc_memcpy -( - void *dest, - const void *source, - PRUint32 n -) +nsslibc_memcpy(void *dest, const void *source, PRUint32 n) { #ifdef NSSDEBUG - if( ((void *)NULL == dest) || ((const void *)NULL == source) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (void *)NULL; - } + if (((void *)NULL == dest) || ((const void *)NULL == source)) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (void *)NULL; + } #endif /* NSSDEBUG */ - return memcpy(dest, source, (size_t)n); + return memcpy(dest, source, (size_t)n); } /* @@ -67,21 +62,16 @@ nsslibc_memcpy */ NSS_IMPLEMENT void * -nsslibc_memset -( - void *dest, - PRUint8 byte, - PRUint32 n -) +nsslibc_memset(void *dest, PRUint8 byte, PRUint32 n) { #ifdef NSSDEBUG - if( ((void *)NULL == dest) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (void *)NULL; - } + if (((void *)NULL == dest)) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (void *)NULL; + } #endif /* NSSDEBUG */ - return memset(dest, (int)byte, (size_t)n); + return memset(dest, (int)byte, (size_t)n); } /* @@ -97,33 +87,29 @@ nsslibc_memset */ NSS_IMPLEMENT PRBool -nsslibc_memequal -( - const void *a, - const void *b, - PRUint32 len, - PRStatus *statusOpt -) +nsslibc_memequal(const void *a, const void *b, PRUint32 len, + PRStatus *statusOpt) { #ifdef NSSDEBUG - if( (((void *)NULL == a) || ((void *)NULL == b)) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; + if ((((void *)NULL == a) || ((void *)NULL == b))) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } + return PR_FALSE; } - return PR_FALSE; - } #endif /* NSSDEBUG */ - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_SUCCESS; - } + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_SUCCESS; + } - if( 0 == memcmp(a, b, len) ) { - return PR_TRUE; - } else { - return PR_FALSE; - } + if (0 == memcmp(a, b, len)) { + return PR_TRUE; + } + else { + return PR_FALSE; + } } /* @@ -131,32 +117,26 @@ nsslibc_memequal */ NSS_IMPLEMENT PRInt32 -nsslibc_memcmp -( - const void *a, - const void *b, - PRUint32 len, - PRStatus *statusOpt -) +nsslibc_memcmp(const void *a, const void *b, PRUint32 len, PRStatus *statusOpt) { - int v; + int v; #ifdef NSSDEBUG - if( (((void *)NULL == a) || ((void *)NULL == b)) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; + if ((((void *)NULL == a) || ((void *)NULL == b))) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } + return -2; } - return -2; - } #endif /* NSSDEBUG */ - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_SUCCESS; - } + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_SUCCESS; + } - v = memcmp(a, b, len); - return (PRInt32)v; + v = memcmp(a, b, len); + return (PRInt32)v; } /* diff --git a/security/nss/lib/base/list.c b/security/nss/lib/base/list.c index 5f34923b2054..da4d7c0d83f5 100644 --- a/security/nss/lib/base/list.c +++ b/security/nss/lib/base/list.c @@ -13,19 +13,19 @@ #endif /* BASE_H */ struct nssListElementStr { - PRCList link; - void *data; + PRCList link; + void *data; }; typedef struct nssListElementStr nssListElement; struct nssListStr { - NSSArena *arena; - PZLock *lock; + NSSArena *arena; + PZLock *lock; nssListElement *head; - PRUint32 count; + PRUint32 count; nssListCompareFunc compareFunc; - nssListSortFunc sortFunc; + nssListSortFunc sortFunc; PRBool i_alloced_arena; }; @@ -35,11 +35,13 @@ struct nssListIteratorStr { nssListElement *current; }; -#define NSSLIST_LOCK_IF(list) \ - if ((list)->lock) PZ_Lock((list)->lock) +#define NSSLIST_LOCK_IF(list) \ + if ((list)->lock) \ + PZ_Lock((list)->lock) -#define NSSLIST_UNLOCK_IF(list) \ - if ((list)->lock) PZ_Unlock((list)->lock) +#define NSSLIST_UNLOCK_IF(list) \ + if ((list)->lock) \ + PZ_Unlock((list)->lock) static PRBool pointer_compare(void *a, void *b) @@ -54,61 +56,59 @@ nsslist_get_matching_element(nssList *list, void *data) nssListElement *node; node = list->head; if (!node) { - return NULL; + return NULL; } link = &node->link; while (node) { - /* using a callback slows things down when it's just compare ... */ - if (list->compareFunc(node->data, data)) { - break; - } - link = &node->link; - if (link == PR_LIST_TAIL(&list->head->link)) { - node = NULL; - break; - } - node = (nssListElement *)PR_NEXT_LINK(&node->link); + /* using a callback slows things down when it's just compare ... */ + if (list->compareFunc(node->data, data)) { + break; + } + link = &node->link; + if (link == PR_LIST_TAIL(&list->head->link)) { + node = NULL; + break; + } + node = (nssListElement *)PR_NEXT_LINK(&node->link); } return node; } NSS_IMPLEMENT nssList * -nssList_Create -( - NSSArena *arenaOpt, - PRBool threadSafe -) +nssList_Create(NSSArena *arenaOpt, PRBool threadSafe) { NSSArena *arena; nssList *list; PRBool i_alloced; if (arenaOpt) { - arena = arenaOpt; - i_alloced = PR_FALSE; - } else { - arena = nssArena_Create(); - i_alloced = PR_TRUE; + arena = arenaOpt; + i_alloced = PR_FALSE; + } + else { + arena = nssArena_Create(); + i_alloced = PR_TRUE; } if (!arena) { - return (nssList *)NULL; + return (nssList *)NULL; } list = nss_ZNEW(arena, nssList); if (!list) { - if (!arenaOpt) { - NSSArena_Destroy(arena); - } - return (nssList *)NULL; + if (!arenaOpt) { + NSSArena_Destroy(arena); + } + return (nssList *)NULL; } if (threadSafe) { - list->lock = PZ_NewLock(nssILockOther); - if (!list->lock) { - if (arenaOpt) { - nss_ZFreeIf(list); - } else { - NSSArena_Destroy(arena); - } - return (nssList *)NULL; - } + list->lock = PZ_NewLock(nssILockOther); + if (!list->lock) { + if (arenaOpt) { + nss_ZFreeIf(list); + } + else { + NSSArena_Destroy(arena); + } + return (nssList *)NULL; + } } list->arena = arena; list->i_alloced_arena = i_alloced; @@ -120,14 +120,14 @@ NSS_IMPLEMENT PRStatus nssList_Destroy(nssList *list) { if (!list->i_alloced_arena) { - nssList_Clear(list, NULL); + nssList_Clear(list, NULL); } if (list->lock) { - (void)PZ_DestroyLock(list->lock); + (void)PZ_DestroyLock(list->lock); } if (list->i_alloced_arena) { - NSSArena_Destroy(list->arena); - list = NULL; + NSSArena_Destroy(list->arena); + list = NULL; } nss_ZFreeIf(list); return PR_SUCCESS; @@ -161,13 +161,14 @@ nssList_Clear(nssList *list, nssListElementDestructorFunc destructor) node = list->head; list->head = NULL; while (node && list->count > 0) { - if (destructor) (*destructor)(node->data); - link = &node->link; - tmp = (nssListElement *)PR_NEXT_LINK(link); - PR_REMOVE_LINK(link); - nss_ZFreeIf(node); - node = tmp; - --list->count; + if (destructor) + (*destructor)(node->data); + link = &node->link; + tmp = (nssListElement *)PR_NEXT_LINK(link); + PR_REMOVE_LINK(link); + nss_ZFreeIf(node); + node = tmp; + --list->count; } NSSLIST_UNLOCK_IF(list); } @@ -177,38 +178,41 @@ nsslist_add_element(nssList *list, void *data) { nssListElement *node = nss_ZNEW(list->arena, nssListElement); if (!node) { - return PR_FAILURE; + return PR_FAILURE; } PR_INIT_CLIST(&node->link); node->data = data; if (list->head) { - if (list->sortFunc) { - PRCList *link; - nssListElement *currNode; - currNode = list->head; - /* insert in ordered list */ - while (currNode) { - link = &currNode->link; - if (list->sortFunc(data, currNode->data) <= 0) { - /* new element goes before current node */ - PR_INSERT_BEFORE(&node->link, link); - /* reset head if this is first */ - if (currNode == list->head) list->head = node; - break; - } - if (link == PR_LIST_TAIL(&list->head->link)) { - /* reached end of list, append */ - PR_INSERT_AFTER(&node->link, link); - break; - } - currNode = (nssListElement *)PR_NEXT_LINK(&currNode->link); - } - } else { - /* not sorting */ - PR_APPEND_LINK(&node->link, &list->head->link); - } - } else { - list->head = node; + if (list->sortFunc) { + PRCList *link; + nssListElement *currNode; + currNode = list->head; + /* insert in ordered list */ + while (currNode) { + link = &currNode->link; + if (list->sortFunc(data, currNode->data) <= 0) { + /* new element goes before current node */ + PR_INSERT_BEFORE(&node->link, link); + /* reset head if this is first */ + if (currNode == list->head) + list->head = node; + break; + } + if (link == PR_LIST_TAIL(&list->head->link)) { + /* reached end of list, append */ + PR_INSERT_AFTER(&node->link, link); + break; + } + currNode = (nssListElement *)PR_NEXT_LINK(&currNode->link); + } + } + else { + /* not sorting */ + PR_APPEND_LINK(&node->link, &list->head->link); + } + } + else { + list->head = node; } ++list->count; return PR_SUCCESS; @@ -231,9 +235,9 @@ nssList_AddUnique(nssList *list, void *data) NSSLIST_LOCK_IF(list); node = nsslist_get_matching_element(list, data); if (node) { - /* already in, finish */ - NSSLIST_UNLOCK_IF(list); - return PR_SUCCESS; + /* already in, finish */ + NSSLIST_UNLOCK_IF(list); + return PR_SUCCESS; } nssrv = nsslist_add_element(list, data); NSSLIST_UNLOCK_IF(list); @@ -247,14 +251,14 @@ nssList_Remove(nssList *list, void *data) NSSLIST_LOCK_IF(list); node = nsslist_get_matching_element(list, data); if (node) { - if (node == list->head) { - list->head = (nssListElement *)PR_NEXT_LINK(&node->link); - } - PR_REMOVE_LINK(&node->link); - nss_ZFreeIf(node); - if (--list->count == 0) { - list->head = NULL; - } + if (node == list->head) { + list->head = (nssListElement *)PR_NEXT_LINK(&node->link); + } + PR_REMOVE_LINK(&node->link); + nss_ZFreeIf(node); + if (--list->count == 0) { + list->head = NULL; + } } NSSLIST_UNLOCK_IF(list); return PR_SUCCESS; @@ -284,16 +288,17 @@ nssList_GetArray(nssList *list, void **rvArray, PRUint32 maxElements) PR_ASSERT(maxElements > 0); node = list->head; if (!node) { - return PR_SUCCESS; + return PR_SUCCESS; } NSSLIST_LOCK_IF(list); while (node) { - rvArray[i++] = node->data; - if (i == maxElements) break; - node = (nssListElement *)PR_NEXT_LINK(&node->link); - if (node == list->head) { - break; - } + rvArray[i++] = node->data; + if (i == maxElements) + break; + node = (nssListElement *)PR_NEXT_LINK(&node->link); + if (node == list->head) { + break; + } } NSSLIST_UNLOCK_IF(list); return PR_SUCCESS; @@ -306,18 +311,18 @@ nssList_Clone(nssList *list) nssListElement *node; rvList = nssList_Create(NULL, (list->lock != NULL)); if (!rvList) { - return NULL; + return NULL; } NSSLIST_LOCK_IF(list); if (list->count > 0) { - node = list->head; - while (PR_TRUE) { - nssList_Add(rvList, node->data); - node = (nssListElement *)PR_NEXT_LINK(&node->link); - if (node == list->head) { - break; - } - } + node = list->head; + while (PR_TRUE) { + nssList_Add(rvList, node->data); + node = (nssListElement *)PR_NEXT_LINK(&node->link); + if (node == list->head) { + break; + } + } } NSSLIST_UNLOCK_IF(list); return rvList; @@ -329,21 +334,21 @@ nssList_CreateIterator(nssList *list) nssListIterator *rvIterator; rvIterator = nss_ZNEW(NULL, nssListIterator); if (!rvIterator) { - return NULL; + return NULL; } rvIterator->list = nssList_Clone(list); if (!rvIterator->list) { - nss_ZFreeIf(rvIterator); - return NULL; + nss_ZFreeIf(rvIterator); + return NULL; } rvIterator->current = rvIterator->list->head; if (list->lock) { - rvIterator->lock = PZ_NewLock(nssILockOther); - if (!rvIterator->lock) { - nssList_Destroy(rvIterator->list); - nss_ZFreeIf(rvIterator); - rvIterator = NULL; - } + rvIterator->lock = PZ_NewLock(nssILockOther); + if (!rvIterator->lock) { + nssList_Destroy(rvIterator->list); + nss_ZFreeIf(rvIterator); + rvIterator = NULL; + } } return rvIterator; } @@ -352,7 +357,7 @@ NSS_IMPLEMENT void nssListIterator_Destroy(nssListIterator *iter) { if (iter->lock) { - (void)PZ_DestroyLock(iter->lock); + (void)PZ_DestroyLock(iter->lock); } nssList_Destroy(iter->list); nss_ZFreeIf(iter); @@ -363,7 +368,7 @@ nssListIterator_Start(nssListIterator *iter) { NSSLIST_LOCK_IF(iter); if (iter->list->count == 0) { - return NULL; + return NULL; } iter->current = iter->list->head; return iter->current->data; @@ -375,17 +380,17 @@ nssListIterator_Next(nssListIterator *iter) nssListElement *node; PRCList *link; if (iter->list->count == 1 || iter->current == NULL) { - /* Reached the end of the list. Don't change the state, force to - * user to call nssList_Finish to clean up. - */ - return NULL; + /* Reached the end of the list. Don't change the state, force to + * user to call nssList_Finish to clean up. + */ + return NULL; } node = (nssListElement *)PR_NEXT_LINK(&iter->current->link); link = &node->link; if (link == PR_LIST_TAIL(&iter->list->head->link)) { - /* Signal the end of the list. */ - iter->current = NULL; - return node->data; + /* Signal the end of the list. */ + iter->current = NULL; + return node->data; } iter->current = node; return node->data; @@ -397,4 +402,3 @@ nssListIterator_Finish(nssListIterator *iter) iter->current = iter->list->head; return (iter->lock) ? PZ_Unlock(iter->lock) : PR_SUCCESS; } - diff --git a/security/nss/lib/base/nssbase.h b/security/nss/lib/base/nssbase.h index 4e14d3b9605f..09c73acf945a 100644 --- a/security/nss/lib/base/nssbase.h +++ b/security/nss/lib/base/nssbase.h @@ -44,11 +44,7 @@ PR_BEGIN_EXTERN_C * A pointer to an NSSArena upon success */ -NSS_EXTERN NSSArena * -NSSArena_Create -( - void -); +NSS_EXTERN NSSArena *NSSArena_Create(void); extern const NSSError NSS_ERROR_NO_MEMORY; @@ -56,7 +52,7 @@ extern const NSSError NSS_ERROR_NO_MEMORY; * NSSArena_Destroy * * This routine will destroy the specified arena, freeing all memory - * allocated from it. This routine returns a PRStatus value; if + * allocated from it. This routine returns a PRStatus value; if * successful, it will return PR_SUCCESS. If unsuccessful, it will * create an error stack and return PR_FAILURE. * @@ -68,11 +64,7 @@ extern const NSSError NSS_ERROR_NO_MEMORY; * PR_FAILURE upon failure */ -NSS_EXTERN PRStatus -NSSArena_Destroy -( - NSSArena *arena -); +NSS_EXTERN PRStatus NSSArena_Destroy(NSSArena *arena); extern const NSSError NSS_ERROR_INVALID_ARENA; @@ -100,25 +92,21 @@ extern const NSSError NSS_ERROR_INVALID_ARENA; * A nonzero error number */ -NSS_EXTERN NSSError -NSS_GetError -( - void -); +NSS_EXTERN NSSError NSS_GetError(void); extern const NSSError NSS_ERROR_NO_ERROR; /* * NSS_GetErrorStack * - * This routine returns a pointer to an array of NSSError values, - * containingthe entire sequence or "stack" of errors set by the most - * recent NSS library routine called by the same thread calling this - * routine. NOTE: the caller DOES NOT OWN the memory pointed to by - * the return value. The pointer will remain valid until the calling - * thread calls another NSS routine. The lowest-level (most specific) - * error is first in the array, and the highest-level is last. The - * array is zero-terminated. This routine may return NULL upon error; + * This routine returns a pointer to an array of NSSError values, + * containingthe entire sequence or "stack" of errors set by the most + * recent NSS library routine called by the same thread calling this + * routine. NOTE: the caller DOES NOT OWN the memory pointed to by + * the return value. The pointer will remain valid until the calling + * thread calls another NSS routine. The lowest-level (most specific) + * error is first in the array, and the highest-level is last. The + * array is zero-terminated. This routine may return NULL upon error; * this indicates a low-memory situation. * * Return value: @@ -126,21 +114,17 @@ extern const NSSError NSS_ERROR_NO_ERROR; * A NON-caller-owned pointer to an array of NSSError values */ -NSS_EXTERN NSSError * -NSS_GetErrorStack -( - void -); +NSS_EXTERN NSSError *NSS_GetErrorStack(void); /* * NSS_ZNEW * * This preprocessor macro will allocate memory for a new object * of the specified type with nss_ZAlloc, and will cast the - * return value appropriately. If the optional arena argument is - * non-null, the memory will be obtained from that arena; otherwise, - * the memory will be obtained from the heap. This routine may - * return NULL upon error, in which case it will have set an error + * return value appropriately. If the optional arena argument is + * non-null, the memory will be obtained from that arena; otherwise, + * the memory will be obtained from the heap. This routine may + * return NULL upon error, in which case it will have set an error * upon the error stack. * * The error may be one of the following values: @@ -152,7 +136,6 @@ NSS_GetErrorStack * A pointer to the new segment of zeroed memory */ -/* The following line exceeds 72 characters, but emacs barfs if we split it. */ #define NSS_ZNEW(arenaOpt, type) ((type *)NSS_ZAlloc((arenaOpt), sizeof(type))) /* @@ -160,10 +143,10 @@ NSS_GetErrorStack * * This preprocessor macro will allocate memory for an array of * new objects, and will cast the return value appropriately. - * If the optional arena argument is non-null, the memory will - * be obtained from that arena; otherwise, the memory will be - * obtained from the heap. This routine may return NULL upon - * error, in which case it will have set an error upon the error + * If the optional arena argument is non-null, the memory will + * be obtained from that arena; otherwise, the memory will be + * obtained from the heap. This routine may return NULL upon + * error, in which case it will have set an error upon the error * stack. The array size may be specified as zero. * * The error may be one of the following values: @@ -175,20 +158,19 @@ NSS_GetErrorStack * A pointer to the new segment of zeroed memory */ -/* The following line exceeds 72 characters, but emacs barfs if we split it. */ -#define NSS_ZNEWARRAY(arenaOpt, type, quantity) ((type *)NSS_ZAlloc((arenaOpt), sizeof(type) * (quantity))) - +#define NSS_ZNEWARRAY(arenaOpt, type, quantity) \ + ((type *)NSS_ZAlloc((arenaOpt), sizeof(type) * (quantity))) /* * NSS_ZAlloc * - * This routine allocates and zeroes a section of memory of the + * This routine allocates and zeroes a section of memory of the * size, and returns to the caller a pointer to that memory. If * the optional arena argument is non-null, the memory will be * obtained from that arena; otherwise, the memory will be obtained * from the heap. This routine may return NULL upon error, in * which case it will have set an error upon the error stack. The - * value specified for size may be zero; in which case a valid + * value specified for size may be zero; in which case a valid * zero-length block of memory will be allocated. This block may * be expanded by calling NSS_ZRealloc. * @@ -202,21 +184,16 @@ NSS_GetErrorStack * A pointer to the new segment of zeroed memory */ -NSS_EXTERN void * -NSS_ZAlloc -( - NSSArena *arenaOpt, - PRUint32 size -); +NSS_EXTERN void *NSS_ZAlloc(NSSArena *arenaOpt, PRUint32 size); /* * NSS_ZRealloc * * This routine reallocates a block of memory obtained by calling - * nss_ZAlloc or nss_ZRealloc. The portion of memory + * nss_ZAlloc or nss_ZRealloc. The portion of memory * between the new and old sizes -- which is either being newly - * obtained or released -- is in either case zeroed. This routine - * may return NULL upon failure, in which case it will have placed + * obtained or released -- is in either case zeroed. This routine + * may return NULL upon failure, in which case it will have placed * an error on the error stack. * * The error may be one of the following values: @@ -229,13 +206,7 @@ NSS_ZAlloc * A pointer to the replacement segment of memory */ -NSS_EXTERN void * -NSS_ZRealloc -( - void *pointer, - PRUint32 newSize -); - +NSS_EXTERN void *NSS_ZRealloc(void *pointer, PRUint32 newSize); /* * NSS_ZFreeIf @@ -255,11 +226,7 @@ NSS_ZRealloc * PR_FAILURE */ -NSS_EXTERN PRStatus -NSS_ZFreeIf -( - void *pointer -); +NSS_EXTERN PRStatus NSS_ZFreeIf(void *pointer); PR_END_EXTERN_C diff --git a/security/nss/lib/base/nssbaset.h b/security/nss/lib/base/nssbaset.h index e5830e1014fa..8bc556e6e9a7 100644 --- a/security/nss/lib/base/nssbaset.h +++ b/security/nss/lib/base/nssbaset.h @@ -18,16 +18,16 @@ * NSS_EXTERN, NSS_IMPLEMENT, NSS_EXTERN_DATA, NSS_IMPLEMENT_DATA * * NSS has its own versions of these NSPR macros, in a form which - * does not confuse ctags and other related utilities. NSPR + * does not confuse ctags and other related utilities. NSPR * defines these macros to take the type as an argument, because * of certain OS requirements on platforms not supported by NSS. */ -#define DUMMY /* dummy */ -#define NSS_EXTERN extern -#define NSS_EXTERN_DATA extern -#define NSS_IMPLEMENT -#define NSS_IMPLEMENT_DATA +#define DUMMY /* dummy */ +#define NSS_EXTERN extern +#define NSS_EXTERN_DATA extern +#define NSS_IMPLEMENT +#define NSS_IMPLEMENT_DATA PR_BEGIN_EXTERN_C @@ -36,7 +36,7 @@ PR_BEGIN_EXTERN_C * * Calls to NSS routines may result in one or more errors being placed * on the calling thread's "error stack." Every possible error that - * may be returned from a function is declared where the function is + * may be returned from a function is declared where the function is * prototyped. All errors are of the following type. */ @@ -47,7 +47,7 @@ typedef PRInt32 NSSError; * * Arenas are logical sets of heap memory, from which memory may be * allocated. When an arena is destroyed, all memory allocated within - * that arena is implicitly freed. These arenas are thread-safe: + * that arena is implicitly freed. These arenas are thread-safe: * an arena pointer may be used by multiple threads simultaneously. * However, as they are not backed by shared memory, they may only be * used within one process. @@ -64,12 +64,11 @@ typedef struct NSSArenaStr NSSArena; */ struct NSSItemStr { - void *data; - PRUint32 size; + void *data; + PRUint32 size; }; typedef struct NSSItemStr NSSItem; - /* * NSSBER * diff --git a/security/nss/lib/base/tracker.c b/security/nss/lib/base/tracker.c index 06e2baf2a46c..850add7c4bb8 100644 --- a/security/nss/lib/base/tracker.c +++ b/security/nss/lib/base/tracker.c @@ -4,7 +4,7 @@ /* * tracker.c - * + * * This file contains the code used by the pointer-tracking calls used * in the debug builds to catch bad pointers. The entire contents are * only available in debug builds (both internal and external builds). @@ -24,12 +24,9 @@ */ static PLHashNumber PR_CALLBACK -identity_hash -( - const void *key -) +identity_hash(const void *key) { - return (PLHashNumber)((char *)key - (char *)NULL); + return (PLHashNumber)((char *)key - (char *)NULL); } /* @@ -41,44 +38,38 @@ identity_hash */ static PRStatus -trackerOnceFunc -( - void *arg -) +trackerOnceFunc(void *arg) { - nssPointerTracker *tracker = (nssPointerTracker *)arg; + nssPointerTracker *tracker = (nssPointerTracker *)arg; - tracker->lock = PZ_NewLock(nssILockOther); - if( (PZLock *)NULL == tracker->lock ) { - return PR_FAILURE; - } + tracker->lock = PZ_NewLock(nssILockOther); + if ((PZLock *)NULL == tracker->lock) { + return PR_FAILURE; + } - tracker->table = PL_NewHashTable(0, - identity_hash, - PL_CompareValues, - PL_CompareValues, - (PLHashAllocOps *)NULL, - (void *)NULL); - if( (PLHashTable *)NULL == tracker->table ) { - PZ_DestroyLock(tracker->lock); - tracker->lock = (PZLock *)NULL; - return PR_FAILURE; - } + tracker->table = + PL_NewHashTable(0, identity_hash, PL_CompareValues, PL_CompareValues, + (PLHashAllocOps *)NULL, (void *)NULL); + if ((PLHashTable *)NULL == tracker->table) { + PZ_DestroyLock(tracker->lock); + tracker->lock = (PZLock *)NULL; + return PR_FAILURE; + } - return PR_SUCCESS; + return PR_SUCCESS; } /* * nssPointerTracker_initialize * * This method is only present in debug builds. - * + * * This routine initializes an nssPointerTracker object. Note that * the object must have been declared *static* to guarantee that it * is in a zeroed state initially. This routine is idempotent, and - * may even be safely called by multiple threads simultaneously with - * the same argument. This routine returns a PRStatus value; if - * successful, it will return PR_SUCCESS. On failure it will set an + * may even be safely called by multiple threads simultaneously with + * the same argument. This routine returns a PRStatus value; if + * successful, it will return PR_SUCCESS. On failure it will set an * error on the error stack and return PR_FAILURE. * * The error may be one of the following values: @@ -90,17 +81,14 @@ trackerOnceFunc */ NSS_IMPLEMENT PRStatus -nssPointerTracker_initialize -( - nssPointerTracker *tracker -) +nssPointerTracker_initialize(nssPointerTracker *tracker) { - PRStatus rv = PR_CallOnceWithArg(&tracker->once, trackerOnceFunc, tracker); - if( PR_SUCCESS != rv ) { - nss_SetError(NSS_ERROR_NO_MEMORY); - } + PRStatus rv = PR_CallOnceWithArg(&tracker->once, trackerOnceFunc, tracker); + if (PR_SUCCESS != rv) { + nss_SetError(NSS_ERROR_NO_MEMORY); + } - return rv; + return rv; } #ifdef DONT_DESTROY_EMPTY_TABLES @@ -114,14 +102,9 @@ nssPointerTracker_initialize */ static PRIntn PR_CALLBACK -count_entries -( - PLHashEntry *he, - PRIntn index, - void *arg -) +count_entries(PLHashEntry *he, PRIntn index, void *arg) { - return HT_ENUMERATE_NEXT; + return HT_ENUMERATE_NEXT; } #endif /* DONT_DESTROY_EMPTY_TABLES */ @@ -138,7 +121,7 @@ static const PRCallOnceType zero_once; * nssPointerTracker_finalize * * This method is only present in debug builds. - * + * * This routine returns the nssPointerTracker object to the pre- * initialized state, releasing all resources used by the object. * It will *NOT* destroy the objects being tracked by the pointer @@ -160,58 +143,54 @@ static const PRCallOnceType zero_once; */ NSS_IMPLEMENT PRStatus -nssPointerTracker_finalize -( - nssPointerTracker *tracker -) +nssPointerTracker_finalize(nssPointerTracker *tracker) { - PZLock *lock; + PZLock *lock; - if( (nssPointerTracker *)NULL == tracker ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return PR_FAILURE; - } + if ((nssPointerTracker *)NULL == tracker) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return PR_FAILURE; + } - if( (PZLock *)NULL == tracker->lock ) { - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } + if ((PZLock *)NULL == tracker->lock) { + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } - lock = tracker->lock; - PZ_Lock(lock); + lock = tracker->lock; + PZ_Lock(lock); - if( (PLHashTable *)NULL == tracker->table ) { - PZ_Unlock(lock); - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } + if ((PLHashTable *)NULL == tracker->table) { + PZ_Unlock(lock); + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } #ifdef DONT_DESTROY_EMPTY_TABLES - /* - * I changed my mind; I think we don't want this after all. - * Comments? - */ - count = PL_HashTableEnumerateEntries(tracker->table, - count_entries, - (void *)NULL); + /* + * I changed my mind; I think we don't want this after all. + * Comments? + */ + count = PL_HashTableEnumerateEntries(tracker->table, count_entries, + (void *)NULL); - if( 0 != count ) { - PZ_Unlock(lock); - nss_SetError(NSS_ERROR_TRACKER_NOT_EMPTY); - return PR_FAILURE; - } + if (0 != count) { + PZ_Unlock(lock); + nss_SetError(NSS_ERROR_TRACKER_NOT_EMPTY); + return PR_FAILURE; + } #endif /* DONT_DESTROY_EMPTY_TABLES */ - PL_HashTableDestroy(tracker->table); - /* memset(tracker, 0, sizeof(nssPointerTracker)); */ - tracker->once = zero_once; - tracker->lock = (PZLock *)NULL; - tracker->table = (PLHashTable *)NULL; + PL_HashTableDestroy(tracker->table); + /* memset(tracker, 0, sizeof(nssPointerTracker)); */ + tracker->once = zero_once; + tracker->lock = (PZLock *)NULL; + tracker->table = (PLHashTable *)NULL; - PZ_Unlock(lock); - PZ_DestroyLock(lock); + PZ_Unlock(lock); + PZ_DestroyLock(lock); - return PR_SUCCESS; + return PR_SUCCESS; } /* @@ -238,63 +217,59 @@ nssPointerTracker_finalize */ NSS_IMPLEMENT PRStatus -nssPointerTracker_add -( - nssPointerTracker *tracker, - const void *pointer -) +nssPointerTracker_add(nssPointerTracker *tracker, const void *pointer) { - void *check; - PLHashEntry *entry; + void *check; + PLHashEntry *entry; - if( (nssPointerTracker *)NULL == tracker ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return PR_FAILURE; - } + if ((nssPointerTracker *)NULL == tracker) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return PR_FAILURE; + } - if( (PZLock *)NULL == tracker->lock ) { - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } + if ((PZLock *)NULL == tracker->lock) { + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } - PZ_Lock(tracker->lock); + PZ_Lock(tracker->lock); + + if ((PLHashTable *)NULL == tracker->table) { + PZ_Unlock(tracker->lock); + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } + + check = PL_HashTableLookup(tracker->table, pointer); + if ((void *)NULL != check) { + PZ_Unlock(tracker->lock); + nss_SetError(NSS_ERROR_DUPLICATE_POINTER); + return PR_FAILURE; + } + + entry = PL_HashTableAdd(tracker->table, pointer, (void *)pointer); - if( (PLHashTable *)NULL == tracker->table ) { PZ_Unlock(tracker->lock); - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } - check = PL_HashTableLookup(tracker->table, pointer); - if( (void *)NULL != check ) { - PZ_Unlock(tracker->lock); - nss_SetError(NSS_ERROR_DUPLICATE_POINTER); - return PR_FAILURE; - } + if ((PLHashEntry *)NULL == entry) { + nss_SetError(NSS_ERROR_NO_MEMORY); + return PR_FAILURE; + } - entry = PL_HashTableAdd(tracker->table, pointer, (void *)pointer); - - PZ_Unlock(tracker->lock); - - if( (PLHashEntry *)NULL == entry ) { - nss_SetError(NSS_ERROR_NO_MEMORY); - return PR_FAILURE; - } - - return PR_SUCCESS; + return PR_SUCCESS; } - + /* * nssPointerTracker_remove * * This method is only present in debug builds. * - * This routine removes the specified pointer from the + * This routine removes the specified pointer from the * nssPointerTracker object. It does not call any destructor for the * object; rather, this should be called from the object's destructor. - * The nssPointerTracker is threadsafe, but this call is not - * idempotent. This routine returns a PRStatus value; if successful - * it will return PR_SUCCESS. On failure it will set an error on the + * The nssPointerTracker is threadsafe, but this call is not + * idempotent. This routine returns a PRStatus value; if successful + * it will return PR_SUCCESS. On failure it will set an error on the * error stack and return PR_FAILURE. * * The error may be one of the following values: @@ -308,41 +283,37 @@ nssPointerTracker_add */ NSS_IMPLEMENT PRStatus -nssPointerTracker_remove -( - nssPointerTracker *tracker, - const void *pointer -) +nssPointerTracker_remove(nssPointerTracker *tracker, const void *pointer) { - PRBool registered; + PRBool registered; - if( (nssPointerTracker *)NULL == tracker ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return PR_FAILURE; - } + if ((nssPointerTracker *)NULL == tracker) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return PR_FAILURE; + } - if( (PZLock *)NULL == tracker->lock ) { - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } + if ((PZLock *)NULL == tracker->lock) { + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } - PZ_Lock(tracker->lock); + PZ_Lock(tracker->lock); - if( (PLHashTable *)NULL == tracker->table ) { + if ((PLHashTable *)NULL == tracker->table) { + PZ_Unlock(tracker->lock); + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } + + registered = PL_HashTableRemove(tracker->table, pointer); PZ_Unlock(tracker->lock); - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } - registered = PL_HashTableRemove(tracker->table, pointer); - PZ_Unlock(tracker->lock); + if (!registered) { + nss_SetError(NSS_ERROR_POINTER_NOT_REGISTERED); + return PR_FAILURE; + } - if( !registered ) { - nss_SetError(NSS_ERROR_POINTER_NOT_REGISTERED); - return PR_FAILURE; - } - - return PR_SUCCESS; + return PR_SUCCESS; } /* @@ -354,10 +325,10 @@ nssPointerTracker_remove * with the nssPointerTracker object. The nssPointerTracker object is * threadsafe, and this call may be safely called from multiple threads * simultaneously with the same arguments. This routine returns a - * PRStatus value; if the pointer is registered this will return - * PR_SUCCESS. Otherwise it will set an error on the error stack and - * return PR_FAILURE. Although the error is suitable for leaving on - * the stack, callers may wish to augment the information available by + * PRStatus value; if the pointer is registered this will return + * PR_SUCCESS. Otherwise it will set an error on the error stack and + * return PR_FAILURE. Although the error is suitable for leaving on + * the stack, callers may wish to augment the information available by * placing a more type-specific error on the stack. * * The error may be one of the following values: @@ -371,41 +342,37 @@ nssPointerTracker_remove */ NSS_IMPLEMENT PRStatus -nssPointerTracker_verify -( - nssPointerTracker *tracker, - const void *pointer -) +nssPointerTracker_verify(nssPointerTracker *tracker, const void *pointer) { - void *check; + void *check; - if( (nssPointerTracker *)NULL == tracker ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return PR_FAILURE; - } + if ((nssPointerTracker *)NULL == tracker) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return PR_FAILURE; + } - if( (PZLock *)NULL == tracker->lock ) { - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } + if ((PZLock *)NULL == tracker->lock) { + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } - PZ_Lock(tracker->lock); + PZ_Lock(tracker->lock); - if( (PLHashTable *)NULL == tracker->table ) { + if ((PLHashTable *)NULL == tracker->table) { + PZ_Unlock(tracker->lock); + nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); + return PR_FAILURE; + } + + check = PL_HashTableLookup(tracker->table, pointer); PZ_Unlock(tracker->lock); - nss_SetError(NSS_ERROR_TRACKER_NOT_INITIALIZED); - return PR_FAILURE; - } - check = PL_HashTableLookup(tracker->table, pointer); - PZ_Unlock(tracker->lock); + if ((void *)NULL == check) { + nss_SetError(NSS_ERROR_POINTER_NOT_REGISTERED); + return PR_FAILURE; + } - if( (void *)NULL == check ) { - nss_SetError(NSS_ERROR_POINTER_NOT_REGISTERED); - return PR_FAILURE; - } - - return PR_SUCCESS; + return PR_SUCCESS; } #endif /* DEBUG */ diff --git a/security/nss/lib/base/utf8.c b/security/nss/lib/base/utf8.c index 490d104e8947..094e7254f068 100644 --- a/security/nss/lib/base/utf8.c +++ b/security/nss/lib/base/utf8.c @@ -24,8 +24,8 @@ /* * nssUTF8_CaseIgnoreMatch - * - * Returns true if the two UTF8-encoded strings pointed to by the + * + * Returns true if the two UTF8-encoded strings pointed to by the * two specified NSSUTF8 pointers differ only in typcase. * * The error may be one of the following values: @@ -38,47 +38,42 @@ */ NSS_IMPLEMENT PRBool -nssUTF8_CaseIgnoreMatch -( - const NSSUTF8 *a, - const NSSUTF8 *b, - PRStatus *statusOpt -) +nssUTF8_CaseIgnoreMatch(const NSSUTF8 *a, const NSSUTF8 *b, PRStatus *statusOpt) { #ifdef NSSDEBUG - if( ((const NSSUTF8 *)NULL == a) || - ((const NSSUTF8 *)NULL == b) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; + if (((const NSSUTF8 *)NULL == a) || ((const NSSUTF8 *)NULL == b)) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } + return PR_FALSE; } - return PR_FALSE; - } #endif /* NSSDEBUG */ - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_SUCCESS; - } + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_SUCCESS; + } - /* - * XXX fgmr - * - * This is, like, so wrong! - */ - if( 0 == PL_strcasecmp((const char *)a, (const char *)b) ) { - return PR_TRUE; - } else { - return PR_FALSE; - } + /* + * XXX fgmr + * + * This is, like, so wrong! + */ + if (0 == PL_strcasecmp((const char *)a, (const char *)b)) { + return PR_TRUE; + } + else { + return PR_FALSE; + } } /* * nssUTF8_PrintableMatch * - * Returns true if the two Printable strings pointed to by the - * two specified NSSUTF8 pointers match when compared with the - * rules for Printable String (leading and trailing spaces are - * disregarded, extents of whitespace match irregardless of length, + * Returns true if the two Printable strings pointed to by the + * two specified NSSUTF8 pointers match when compared with the + * rules for Printable String (leading and trailing spaces are + * disregarded, extents of whitespace match irregardless of length, * and case is not significant), then PR_TRUE will be returned. * Otherwise, PR_FALSE will be returned. Upon failure, PR_FALSE * will be returned. If the optional statusOpt argument is not @@ -95,92 +90,87 @@ nssUTF8_CaseIgnoreMatch */ NSS_IMPLEMENT PRBool -nssUTF8_PrintableMatch -( - const NSSUTF8 *a, - const NSSUTF8 *b, - PRStatus *statusOpt -) +nssUTF8_PrintableMatch(const NSSUTF8 *a, const NSSUTF8 *b, PRStatus *statusOpt) { - PRUint8 *c; - PRUint8 *d; + PRUint8 *c; + PRUint8 *d; #ifdef NSSDEBUG - if( ((const NSSUTF8 *)NULL == a) || - ((const NSSUTF8 *)NULL == b) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; + if (((const NSSUTF8 *)NULL == a) || ((const NSSUTF8 *)NULL == b)) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } + return PR_FALSE; } - return PR_FALSE; - } #endif /* NSSDEBUG */ - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_SUCCESS; - } - - c = (PRUint8 *)a; - d = (PRUint8 *)b; - - while( ' ' == *c ) { - c++; - } - - while( ' ' == *d ) { - d++; - } - - while( ('\0' != *c) && ('\0' != *d) ) { - PRUint8 e, f; - - e = *c; - f = *d; - - if( ('a' <= e) && (e <= 'z') ) { - e -= ('a' - 'A'); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_SUCCESS; } - if( ('a' <= f) && (f <= 'z') ) { - f -= ('a' - 'A'); - } + c = (PRUint8 *)a; + d = (PRUint8 *)b; - if( e != f ) { - return PR_FALSE; - } - - c++; - d++; - - if( ' ' == *c ) { - while( ' ' == *c ) { + while (' ' == *c) { c++; - } - c--; } - if( ' ' == *d ) { - while( ' ' == *d ) { + while (' ' == *d) { d++; - } - d--; } - } - while( ' ' == *c ) { - c++; - } + while (('\0' != *c) && ('\0' != *d)) { + PRUint8 e, f; - while( ' ' == *d ) { - d++; - } + e = *c; + f = *d; - if( *c == *d ) { - /* And both '\0', btw */ - return PR_TRUE; - } else { - return PR_FALSE; - } + if (('a' <= e) && (e <= 'z')) { + e -= ('a' - 'A'); + } + + if (('a' <= f) && (f <= 'z')) { + f -= ('a' - 'A'); + } + + if (e != f) { + return PR_FALSE; + } + + c++; + d++; + + if (' ' == *c) { + while (' ' == *c) { + c++; + } + c--; + } + + if (' ' == *d) { + while (' ' == *d) { + d++; + } + d--; + } + } + + while (' ' == *c) { + c++; + } + + while (' ' == *d) { + d++; + } + + if (*c == *d) { + /* And both '\0', btw */ + return PR_TRUE; + } + else { + return PR_FALSE; + } } /* @@ -191,7 +181,7 @@ nssUTF8_PrintableMatch * not null, the memory required will be obtained from that arena; * otherwise, the memory required will be obtained from the heap. * A pointer to the new string will be returned. In case of error, - * an error will be placed on the error stack and NULL will be + * an error will be placed on the error stack and NULL will be * returned. * * The error may be one of the following values: @@ -201,45 +191,41 @@ nssUTF8_PrintableMatch */ NSS_IMPLEMENT NSSUTF8 * -nssUTF8_Duplicate -( - const NSSUTF8 *s, - NSSArena *arenaOpt -) +nssUTF8_Duplicate(const NSSUTF8 *s, NSSArena *arenaOpt) { - NSSUTF8 *rv; - PRUint32 len; + NSSUTF8 *rv; + PRUint32 len; #ifdef NSSDEBUG - if( (const NSSUTF8 *)NULL == s ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (NSSUTF8 *)NULL; - } - - if( (NSSArena *)NULL != arenaOpt ) { - if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) { - return (NSSUTF8 *)NULL; + if ((const NSSUTF8 *)NULL == s) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (NSSUTF8 *)NULL; + } + + if ((NSSArena *)NULL != arenaOpt) { + if (PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) { + return (NSSUTF8 *)NULL; + } } - } #endif /* NSSDEBUG */ - len = PL_strlen((const char *)s); + len = PL_strlen((const char *)s); #ifdef PEDANTIC - if( '\0' != ((const char *)s)[ len ] ) { - /* must have wrapped, e.g., too big for PRUint32 */ - nss_SetError(NSS_ERROR_NO_MEMORY); - return (NSSUTF8 *)NULL; - } -#endif /* PEDANTIC */ - len++; /* zero termination */ + if ('\0' != ((const char *)s)[len]) { + /* must have wrapped, e.g., too big for PRUint32 */ + nss_SetError(NSS_ERROR_NO_MEMORY); + return (NSSUTF8 *)NULL; + } +#endif /* PEDANTIC */ + len++; /* zero termination */ - rv = nss_ZAlloc(arenaOpt, len); - if( (void *)NULL == rv ) { - return (NSSUTF8 *)NULL; - } + rv = nss_ZAlloc(arenaOpt, len); + if ((void *)NULL == rv) { + return (NSSUTF8 *)NULL; + } - (void)nsslibc_memcpy(rv, s, len); - return rv; + (void)nsslibc_memcpy(rv, s, len); + return rv; } /* @@ -259,41 +245,37 @@ nssUTF8_Duplicate */ NSS_IMPLEMENT PRUint32 -nssUTF8_Size -( - const NSSUTF8 *s, - PRStatus *statusOpt -) +nssUTF8_Size(const NSSUTF8 *s, PRStatus *statusOpt) { - PRUint32 sv; + PRUint32 sv; #ifdef NSSDEBUG - if( (const NSSUTF8 *)NULL == s ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; + if ((const NSSUTF8 *)NULL == s) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } + return 0; } - return 0; - } #endif /* NSSDEBUG */ - sv = PL_strlen((const char *)s) + 1; + sv = PL_strlen((const char *)s) + 1; #ifdef PEDANTIC - if( '\0' != ((const char *)s)[ sv-1 ] ) { - /* wrapped */ - nss_SetError(NSS_ERROR_VALUE_TOO_LARGE); - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; + if ('\0' != ((const char *)s)[sv - 1]) { + /* wrapped */ + nss_SetError(NSS_ERROR_VALUE_TOO_LARGE); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } + return 0; } - return 0; - } #endif /* PEDANTIC */ - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_SUCCESS; - } + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_SUCCESS; + } - return sv; + return sv; } /* @@ -314,91 +296,92 @@ nssUTF8_Size */ NSS_IMPLEMENT PRUint32 -nssUTF8_Length -( - const NSSUTF8 *s, - PRStatus *statusOpt -) +nssUTF8_Length(const NSSUTF8 *s, PRStatus *statusOpt) { - PRUint32 l = 0; - const PRUint8 *c = (const PRUint8 *)s; + PRUint32 l = 0; + const PRUint8 *c = (const PRUint8 *)s; #ifdef NSSDEBUG - if( (const NSSUTF8 *)NULL == s ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - goto loser; - } + if ((const NSSUTF8 *)NULL == s) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + goto loser; + } #endif /* NSSDEBUG */ - /* - * From RFC 2044: - * - * UCS-4 range (hex.) UTF-8 octet sequence (binary) - * 0000 0000-0000 007F 0xxxxxxx - * 0000 0080-0000 07FF 110xxxxx 10xxxxxx - * 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx - * 0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - * 0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - * 0400 0000-7FFF FFFF 1111110x 10xxxxxx ... 10xxxxxx - */ + /* + * From RFC 2044: + * + * UCS-4 range (hex.) UTF-8 octet sequence (binary) + * 0000 0000-0000 007F 0xxxxxxx + * 0000 0080-0000 07FF 110xxxxx 10xxxxxx + * 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx + * 0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + * 0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + * 0400 0000-7FFF FFFF 1111110x 10xxxxxx ... 10xxxxxx + */ - while( 0 != *c ) { - PRUint32 incr; - if( (*c & 0x80) == 0 ) { - incr = 1; - } else if( (*c & 0xE0) == 0xC0 ) { - incr = 2; - } else if( (*c & 0xF0) == 0xE0 ) { - incr = 3; - } else if( (*c & 0xF8) == 0xF0 ) { - incr = 4; - } else if( (*c & 0xFC) == 0xF8 ) { - incr = 5; - } else if( (*c & 0xFE) == 0xFC ) { - incr = 6; - } else { - nss_SetError(NSS_ERROR_INVALID_STRING); - goto loser; - } + while (0 != *c) { + PRUint32 incr; + if ((*c & 0x80) == 0) { + incr = 1; + } + else if ((*c & 0xE0) == 0xC0) { + incr = 2; + } + else if ((*c & 0xF0) == 0xE0) { + incr = 3; + } + else if ((*c & 0xF8) == 0xF0) { + incr = 4; + } + else if ((*c & 0xFC) == 0xF8) { + incr = 5; + } + else if ((*c & 0xFE) == 0xFC) { + incr = 6; + } + else { + nss_SetError(NSS_ERROR_INVALID_STRING); + goto loser; + } - l += incr; + l += incr; #ifdef PEDANTIC - if( l < incr ) { - /* Wrapped-- too big */ - nss_SetError(NSS_ERROR_VALUE_TOO_LARGE); - goto loser; - } - - { - PRUint8 *d; - for( d = &c[1]; d < &c[incr]; d++ ) { - if( (*d & 0xC0) != 0xF0 ) { - nss_SetError(NSS_ERROR_INVALID_STRING); - goto loser; + if (l < incr) { + /* Wrapped-- too big */ + nss_SetError(NSS_ERROR_VALUE_TOO_LARGE); + goto loser; + } + + { + PRUint8 *d; + for (d = &c[1]; d < &c[incr]; d++) { + if ((*d & 0xC0) != 0xF0) { + nss_SetError(NSS_ERROR_INVALID_STRING); + goto loser; + } + } } - } - } #endif /* PEDANTIC */ - c += incr; - } + c += incr; + } - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_SUCCESS; - } + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_SUCCESS; + } - return l; + return l; - loser: - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; - } +loser: + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } - return 0; + return 0; } - /* * nssUTF8_Create * @@ -425,261 +408,250 @@ nssUTF8_Length extern const NSSError NSS_ERROR_INTERNAL_ERROR; /* XXX fgmr */ NSS_IMPLEMENT NSSUTF8 * -nssUTF8_Create -( - NSSArena *arenaOpt, - nssStringType type, - const void *inputString, - PRUint32 size /* in bytes, not characters */ -) +nssUTF8_Create(NSSArena *arenaOpt, nssStringType type, const void *inputString, + PRUint32 size /* in bytes, not characters */ + ) { - NSSUTF8 *rv = NULL; + NSSUTF8 *rv = NULL; #ifdef NSSDEBUG - if( (NSSArena *)NULL != arenaOpt ) { - if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) { - return (NSSUTF8 *)NULL; + if ((NSSArena *)NULL != arenaOpt) { + if (PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) { + return (NSSUTF8 *)NULL; + } } - } - if( (const void *)NULL == inputString ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (NSSUTF8 *)NULL; - } + if ((const void *)NULL == inputString) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (NSSUTF8 *)NULL; + } #endif /* NSSDEBUG */ - switch( type ) { - case nssStringType_DirectoryString: - /* This is a composite type requiring BER */ - nss_SetError(NSS_ERROR_UNSUPPORTED_TYPE); - break; - case nssStringType_TeletexString: - /* - * draft-ietf-pkix-ipki-part1-11 says in part: - * - * In addition, many legacy implementations support names encoded - * in the ISO 8859-1 character set (Latin1String) but tag them as - * TeletexString. The Latin1String includes characters used in - * Western European countries which are not part of the - * TeletexString charcter set. Implementations that process - * TeletexString SHOULD be prepared to handle the entire ISO - * 8859-1 character set.[ISO 8859-1]. - */ - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_PrintableString: - /* - * PrintableString consists of A-Za-z0-9 ,()+,-./:=? - * This is a subset of ASCII, which is a subset of UTF8. - * So we can just duplicate the string over. - */ + switch (type) { + case nssStringType_DirectoryString: + /* This is a composite type requiring BER */ + nss_SetError(NSS_ERROR_UNSUPPORTED_TYPE); + break; + case nssStringType_TeletexString: + /* + * draft-ietf-pkix-ipki-part1-11 says in part: + * + * In addition, many legacy implementations support names encoded + * in the ISO 8859-1 character set (Latin1String) but tag them as + * TeletexString. The Latin1String includes characters used in + * Western European countries which are not part of the + * TeletexString charcter set. Implementations that process + * TeletexString SHOULD be prepared to handle the entire ISO + * 8859-1 character set.[ISO 8859-1]. + */ + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_PrintableString: + /* + * PrintableString consists of A-Za-z0-9 ,()+,-./:=? + * This is a subset of ASCII, which is a subset of UTF8. + * So we can just duplicate the string over. + */ - if( 0 == size ) { - rv = nssUTF8_Duplicate((const NSSUTF8 *)inputString, arenaOpt); - } else { - rv = nss_ZAlloc(arenaOpt, size+1); - if( (NSSUTF8 *)NULL == rv ) { - return (NSSUTF8 *)NULL; - } + if (0 == size) { + rv = nssUTF8_Duplicate((const NSSUTF8 *)inputString, arenaOpt); + } + else { + rv = nss_ZAlloc(arenaOpt, size + 1); + if ((NSSUTF8 *)NULL == rv) { + return (NSSUTF8 *)NULL; + } - (void)nsslibc_memcpy(rv, inputString, size); + (void)nsslibc_memcpy(rv, inputString, size); + } + + break; + case nssStringType_UniversalString: + /* 4-byte unicode */ + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_BMPString: + /* Base Multilingual Plane of Unicode */ + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_UTF8String: + if (0 == size) { + rv = nssUTF8_Duplicate((const NSSUTF8 *)inputString, arenaOpt); + } + else { + rv = nss_ZAlloc(arenaOpt, size + 1); + if ((NSSUTF8 *)NULL == rv) { + return (NSSUTF8 *)NULL; + } + + (void)nsslibc_memcpy(rv, inputString, size); + } + + break; + case nssStringType_PHGString: + /* + * PHGString is an IA5String (with case-insensitive comparisons). + * IA5 is ~almost~ ascii; ascii has dollar-sign where IA5 has + * currency symbol. + */ + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_GeneralString: + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + default: + nss_SetError(NSS_ERROR_UNSUPPORTED_TYPE); + break; } - break; - case nssStringType_UniversalString: - /* 4-byte unicode */ - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_BMPString: - /* Base Multilingual Plane of Unicode */ - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_UTF8String: - if( 0 == size ) { - rv = nssUTF8_Duplicate((const NSSUTF8 *)inputString, arenaOpt); - } else { - rv = nss_ZAlloc(arenaOpt, size+1); - if( (NSSUTF8 *)NULL == rv ) { - return (NSSUTF8 *)NULL; - } - - (void)nsslibc_memcpy(rv, inputString, size); - } - - break; - case nssStringType_PHGString: - /* - * PHGString is an IA5String (with case-insensitive comparisons). - * IA5 is ~almost~ ascii; ascii has dollar-sign where IA5 has - * currency symbol. - */ - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_GeneralString: - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - default: - nss_SetError(NSS_ERROR_UNSUPPORTED_TYPE); - break; - } - - return rv; + return rv; } NSS_IMPLEMENT NSSItem * -nssUTF8_GetEncoding -( - NSSArena *arenaOpt, - NSSItem *rvOpt, - nssStringType type, - NSSUTF8 *string -) +nssUTF8_GetEncoding(NSSArena *arenaOpt, NSSItem *rvOpt, nssStringType type, + NSSUTF8 *string) { - NSSItem *rv = (NSSItem *)NULL; - PRStatus status = PR_SUCCESS; + NSSItem *rv = (NSSItem *)NULL; + PRStatus status = PR_SUCCESS; #ifdef NSSDEBUG - if( (NSSArena *)NULL != arenaOpt ) { - if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) { - return (NSSItem *)NULL; + if ((NSSArena *)NULL != arenaOpt) { + if (PR_SUCCESS != nssArena_verifyPointer(arenaOpt)) { + return (NSSItem *)NULL; + } } - } - if( (NSSUTF8 *)NULL == string ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return (NSSItem *)NULL; - } + if ((NSSUTF8 *)NULL == string) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return (NSSItem *)NULL; + } #endif /* NSSDEBUG */ - switch( type ) { - case nssStringType_DirectoryString: - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_TeletexString: - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_PrintableString: - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_UniversalString: - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_BMPString: - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - case nssStringType_UTF8String: - { - NSSUTF8 *dup = nssUTF8_Duplicate(string, arenaOpt); - if( (NSSUTF8 *)NULL == dup ) { - return (NSSItem *)NULL; - } + switch (type) { + case nssStringType_DirectoryString: + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_TeletexString: + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_PrintableString: + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_UniversalString: + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_BMPString: + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + case nssStringType_UTF8String: { + NSSUTF8 *dup = nssUTF8_Duplicate(string, arenaOpt); + if ((NSSUTF8 *)NULL == dup) { + return (NSSItem *)NULL; + } - if( (NSSItem *)NULL == rvOpt ) { - rv = nss_ZNEW(arenaOpt, NSSItem); - if( (NSSItem *)NULL == rv ) { - (void)nss_ZFreeIf(dup); - return (NSSItem *)NULL; - } - } else { - rv = rvOpt; - } + if ((NSSItem *)NULL == rvOpt) { + rv = nss_ZNEW(arenaOpt, NSSItem); + if ((NSSItem *)NULL == rv) { + (void)nss_ZFreeIf(dup); + return (NSSItem *)NULL; + } + } + else { + rv = rvOpt; + } - rv->data = dup; - dup = (NSSUTF8 *)NULL; - rv->size = nssUTF8_Size(rv->data, &status); - if( (0 == rv->size) && (PR_SUCCESS != status) ) { - if( (NSSItem *)NULL == rvOpt ) { - (void)nss_ZFreeIf(rv); - } - return (NSSItem *)NULL; - } + rv->data = dup; + dup = (NSSUTF8 *)NULL; + rv->size = nssUTF8_Size(rv->data, &status); + if ((0 == rv->size) && (PR_SUCCESS != status)) { + if ((NSSItem *)NULL == rvOpt) { + (void)nss_ZFreeIf(rv); + } + return (NSSItem *)NULL; + } + } break; + case nssStringType_PHGString: + nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ + break; + default: + nss_SetError(NSS_ERROR_UNSUPPORTED_TYPE); + break; } - break; - case nssStringType_PHGString: - nss_SetError(NSS_ERROR_INTERNAL_ERROR); /* unimplemented */ - break; - default: - nss_SetError(NSS_ERROR_UNSUPPORTED_TYPE); - break; - } - return rv; + return rv; } /* * nssUTF8_CopyIntoFixedBuffer * - * This will copy a UTF8 string into a fixed-length buffer, making + * This will copy a UTF8 string into a fixed-length buffer, making * sure that the all characters are valid. Any remaining space will - * be padded with the specified ASCII character, typically either + * be padded with the specified ASCII character, typically either * null or space. * * Blah, blah, blah. */ NSS_IMPLEMENT PRStatus -nssUTF8_CopyIntoFixedBuffer -( - NSSUTF8 *string, - char *buffer, - PRUint32 bufferSize, - char pad -) +nssUTF8_CopyIntoFixedBuffer(NSSUTF8 *string, char *buffer, PRUint32 bufferSize, + char pad) { - PRUint32 stringSize = 0; + PRUint32 stringSize = 0; #ifdef NSSDEBUG - if( (char *)NULL == buffer ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - return PR_FALSE; - } - - if( 0 == bufferSize ) { - nss_SetError(NSS_ERROR_INVALID_ARGUMENT); - return PR_FALSE; - } - - if( (pad & 0x80) != 0x00 ) { - nss_SetError(NSS_ERROR_INVALID_ARGUMENT); - return PR_FALSE; - } -#endif /* NSSDEBUG */ - - if( (NSSUTF8 *)NULL == string ) { - string = (NSSUTF8 *) ""; - } - - stringSize = nssUTF8_Size(string, (PRStatus *)NULL); - stringSize--; /* don't count the trailing null */ - if( stringSize > bufferSize ) { - PRUint32 bs = bufferSize; - (void)nsslibc_memcpy(buffer, string, bufferSize); - - if( ( ((buffer[ bs-1 ] & 0x80) == 0x00)) || - ((bs > 1) && ((buffer[ bs-2 ] & 0xE0) == 0xC0)) || - ((bs > 2) && ((buffer[ bs-3 ] & 0xF0) == 0xE0)) || - ((bs > 3) && ((buffer[ bs-4 ] & 0xF8) == 0xF0)) || - ((bs > 4) && ((buffer[ bs-5 ] & 0xFC) == 0xF8)) || - ((bs > 5) && ((buffer[ bs-6 ] & 0xFE) == 0xFC)) ) { - /* It fit exactly */ - return PR_SUCCESS; + if ((char *)NULL == buffer) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + return PR_FALSE; } - /* Too long. We have to trim the last character */ - for( /*bs*/; bs != 0; bs-- ) { - if( (buffer[bs-1] & 0xC0) != 0x80 ) { - buffer[bs-1] = pad; - break; - } else { - buffer[bs-1] = pad; - } - } - } else { - (void)nsslibc_memset(buffer, pad, bufferSize); - (void)nsslibc_memcpy(buffer, string, stringSize); - } + if (0 == bufferSize) { + nss_SetError(NSS_ERROR_INVALID_ARGUMENT); + return PR_FALSE; + } - return PR_SUCCESS; + if ((pad & 0x80) != 0x00) { + nss_SetError(NSS_ERROR_INVALID_ARGUMENT); + return PR_FALSE; + } +#endif /* NSSDEBUG */ + + if ((NSSUTF8 *)NULL == string) { + string = (NSSUTF8 *)""; + } + + stringSize = nssUTF8_Size(string, (PRStatus *)NULL); + stringSize--; /* don't count the trailing null */ + if (stringSize > bufferSize) { + PRUint32 bs = bufferSize; + (void)nsslibc_memcpy(buffer, string, bufferSize); + + if (( ((buffer[bs - 1] & 0x80) == 0x00)) || + ((bs > 1) && ((buffer[bs - 2] & 0xE0) == 0xC0)) || + ((bs > 2) && ((buffer[bs - 3] & 0xF0) == 0xE0)) || + ((bs > 3) && ((buffer[bs - 4] & 0xF8) == 0xF0)) || + ((bs > 4) && ((buffer[bs - 5] & 0xFC) == 0xF8)) || + ((bs > 5) && ((buffer[bs - 6] & 0xFE) == 0xFC))) { + /* It fit exactly */ + return PR_SUCCESS; + } + + /* Too long. We have to trim the last character */ + for (/*bs*/; bs != 0; bs--) { + if ((buffer[bs - 1] & 0xC0) != 0x80) { + buffer[bs - 1] = pad; + break; + } + else { + buffer[bs - 1] = pad; + } + } + } + else { + (void)nsslibc_memset(buffer, pad, bufferSize); + (void)nsslibc_memcpy(buffer, string, stringSize); + } + + return PR_SUCCESS; } /* @@ -688,39 +660,33 @@ nssUTF8_CopyIntoFixedBuffer */ NSS_IMPLEMENT PRBool -nssUTF8_Equal -( - const NSSUTF8 *a, - const NSSUTF8 *b, - PRStatus *statusOpt -) +nssUTF8_Equal(const NSSUTF8 *a, const NSSUTF8 *b, PRStatus *statusOpt) { - PRUint32 la, lb; + PRUint32 la, lb; #ifdef NSSDEBUG - if( ((const NSSUTF8 *)NULL == a) || - ((const NSSUTF8 *)NULL == b) ) { - nss_SetError(NSS_ERROR_INVALID_POINTER); - if( (PRStatus *)NULL != statusOpt ) { - *statusOpt = PR_FAILURE; + if (((const NSSUTF8 *)NULL == a) || ((const NSSUTF8 *)NULL == b)) { + nss_SetError(NSS_ERROR_INVALID_POINTER); + if ((PRStatus *)NULL != statusOpt) { + *statusOpt = PR_FAILURE; + } + return PR_FALSE; } - return PR_FALSE; - } #endif /* NSSDEBUG */ - la = nssUTF8_Size(a, statusOpt); - if( 0 == la ) { - return PR_FALSE; - } + la = nssUTF8_Size(a, statusOpt); + if (0 == la) { + return PR_FALSE; + } - lb = nssUTF8_Size(b, statusOpt); - if( 0 == lb ) { - return PR_FALSE; - } + lb = nssUTF8_Size(b, statusOpt); + if (0 == lb) { + return PR_FALSE; + } - if( la != lb ) { - return PR_FALSE; - } + if (la != lb) { + return PR_FALSE; + } - return nsslibc_memequal(a, b, la, statusOpt); + return nsslibc_memequal(a, b, la, statusOpt); } diff --git a/security/nss/lib/certdb/alg1485.c b/security/nss/lib/certdb/alg1485.c index ea1621bcf676..9415531ed6b7 100644 --- a/security/nss/lib/certdb/alg1485.c +++ b/security/nss/lib/certdb/alg1485.c @@ -13,26 +13,28 @@ #include "secerr.h" typedef struct NameToKindStr { - const char * name; + const char* name; unsigned int maxLen; /* max bytes in UTF8 encoded string value */ - SECOidTag kind; - int valueType; + SECOidTag kind; + int valueType; } NameToKind; /* local type for directory string--could be printable_string or utf8 */ #define SEC_ASN1_DS SEC_ASN1_HIGH_TAG_NUMBER +/* clang-format off */ + /* Add new entries to this table, and maybe to function ParseRFC1485AVA */ static const NameToKind name2kinds[] = { /* IANA registered type names - * (See: http://www.iana.org/assignments/ldap-parameters) + * (See: http://www.iana.org/assignments/ldap-parameters) */ /* RFC 3280, 4630 MUST SUPPORT */ { "CN", 640, SEC_OID_AVA_COMMON_NAME, SEC_ASN1_DS}, { "ST", 128, SEC_OID_AVA_STATE_OR_PROVINCE, - SEC_ASN1_DS}, + SEC_ASN1_DS}, { "O", 128, SEC_OID_AVA_ORGANIZATION_NAME, - SEC_ASN1_DS}, + SEC_ASN1_DS}, { "OU", 128, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME, SEC_ASN1_DS}, { "dnQualifier", 32767, SEC_OID_AVA_DN_QUALIFIER, SEC_ASN1_PRINTABLE_STRING}, @@ -58,7 +60,7 @@ static const NameToKind name2kinds[] = { * below this line. The first SECOidTag below this line must be used to * conditionally define the "endKind" in function AppendAVA() below. * Most new attribute names should be added below this line. - * Maybe this line should be up higher? Say, after the 3280 MUSTs and + * Maybe this line should be up higher? Say, after the 3280 MUSTs and * before the 3280 SHOULDs? */ @@ -76,11 +78,11 @@ static const NameToKind name2kinds[] = { /* values defined by the CAB Forum for EV */ { "incorporationLocality", 128, SEC_OID_EV_INCORPORATION_LOCALITY, - SEC_ASN1_DS}, + SEC_ASN1_DS}, { "incorporationState", 128, SEC_OID_EV_INCORPORATION_STATE, - SEC_ASN1_DS}, + SEC_ASN1_DS}, { "incorporationCountry", 2, SEC_OID_EV_INCORPORATION_COUNTRY, - SEC_ASN1_PRINTABLE_STRING}, + SEC_ASN1_PRINTABLE_STRING}, { "businessCategory", 64, SEC_OID_BUSINESS_CATEGORY, SEC_ASN1_DS}, /* values defined in X.520 */ @@ -91,21 +93,21 @@ static const NameToKind name2kinds[] = { /* Table facilitates conversion of ASCII hex to binary. */ static const PRInt16 x2b[256] = { -/* #0x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #1x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #2x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #3x */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -/* #4x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #5x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #6x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #7x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #8x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #9x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #ax */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #bx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #cx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #dx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -/* #ex */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #0x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #1x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #2x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #3x */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, +/* #4x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #5x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #6x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #7x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #8x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #9x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #ax */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #bx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #cx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #dx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +/* #ex */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* #fx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; @@ -117,330 +119,336 @@ static const PRInt16 x2b[256] = { #define C_EQUAL '=' -#define OPTIONAL_SPACE(c) \ +#define OPTIONAL_SPACE(c) \ (((c) == ' ') || ((c) == '\r') || ((c) == '\n')) -#define SPECIAL_CHAR(c) \ - (((c) == ',') || ((c) == '=') || ((c) == C_DOUBLE_QUOTE) || \ - ((c) == '\r') || ((c) == '\n') || ((c) == '+') || \ - ((c) == '<') || ((c) == '>') || ((c) == '#') || \ +#define SPECIAL_CHAR(c) \ + (((c) == ',') || ((c) == '=') || ((c) == C_DOUBLE_QUOTE) || \ + ((c) == '\r') || ((c) == '\n') || ((c) == '+') || \ + ((c) == '<') || ((c) == '>') || ((c) == '#') || \ ((c) == ';') || ((c) == C_BACKSLASH)) -#define IS_PRINTABLE(c) \ - ((((c) >= 'a') && ((c) <= 'z')) || \ - (((c) >= 'A') && ((c) <= 'Z')) || \ - (((c) >= '0') && ((c) <= '9')) || \ - ((c) == ' ') || \ - ((c) == '\'') || \ - ((c) == '\050') || /* ( */ \ - ((c) == '\051') || /* ) */ \ - (((c) >= '+') && ((c) <= '/')) || /* + , - . / */ \ - ((c) == ':') || \ - ((c) == '=') || \ +#define IS_PRINTABLE(c) \ + ((((c) >= 'a') && ((c) <= 'z')) || \ + (((c) >= 'A') && ((c) <= 'Z')) || \ + (((c) >= '0') && ((c) <= '9')) || \ + ((c) == ' ') || \ + ((c) == '\'') || \ + ((c) == '\050') || /* ( */ \ + ((c) == '\051') || /* ) */ \ + (((c) >= '+') && ((c) <= '/')) || /* + , - . / */ \ + ((c) == ':') || \ + ((c) == '=') || \ ((c) == '?')) +/* clang-format on */ + /* RFC 2253 says we must escape ",+\"\\<>;=" EXCEPT inside a quoted string. * Inside a quoted string, we only need to escape " and \ * We choose to quote strings containing any of those special characters, * so we only need to escape " and \ */ -#define NEEDS_ESCAPE(c) \ - (c == C_DOUBLE_QUOTE || c == C_BACKSLASH) +#define NEEDS_ESCAPE(c) (c == C_DOUBLE_QUOTE || c == C_BACKSLASH) -#define NEEDS_HEX_ESCAPE(c) \ - ((PRUint8)c < 0x20 || c == 0x7f) +#define NEEDS_HEX_ESCAPE(c) ((PRUint8)c < 0x20 || c == 0x7f) int cert_AVAOidTagToMaxLen(SECOidTag tag) { - const NameToKind *n2k = name2kinds; + const NameToKind* n2k = name2kinds; while (n2k->kind != tag && n2k->kind != SEC_OID_UNKNOWN) { - ++n2k; + ++n2k; } return (n2k->kind != SEC_OID_UNKNOWN) ? n2k->maxLen : -1; } static PRBool -IsPrintable(unsigned char *data, unsigned len) +IsPrintable(unsigned char* data, unsigned len) { unsigned char ch, *end; end = data + len; while (data < end) { - ch = *data++; - if (!IS_PRINTABLE(ch)) { - return PR_FALSE; - } + ch = *data++; + if (!IS_PRINTABLE(ch)) { + return PR_FALSE; + } } return PR_TRUE; } static void -skipSpace(const char **pbp, const char *endptr) +skipSpace(const char** pbp, const char* endptr) { - const char *bp = *pbp; + const char* bp = *pbp; while (bp < endptr && OPTIONAL_SPACE(*bp)) { - bp++; + bp++; } *pbp = bp; } static SECStatus -scanTag(const char **pbp, const char *endptr, char *tagBuf, int tagBufSize) +scanTag(const char** pbp, const char* endptr, char* tagBuf, int tagBufSize) { - const char *bp; - char *tagBufp; + const char* bp; + char* tagBufp; int taglen; PORT_Assert(tagBufSize > 0); - + /* skip optional leading space */ skipSpace(pbp, endptr); if (*pbp == endptr) { - /* nothing left */ - return SECFailure; + /* nothing left */ + return SECFailure; } - + /* fill tagBuf */ taglen = 0; bp = *pbp; tagBufp = tagBuf; while (bp < endptr && !OPTIONAL_SPACE(*bp) && (*bp != C_EQUAL)) { - if (++taglen >= tagBufSize) { - *pbp = bp; - return SECFailure; - } - *tagBufp++ = *bp++; + if (++taglen >= tagBufSize) { + *pbp = bp; + return SECFailure; + } + *tagBufp++ = *bp++; } /* null-terminate tagBuf -- guaranteed at least one space left */ *tagBufp++ = 0; *pbp = bp; - + /* skip trailing spaces till we hit something - should be an equal sign */ skipSpace(pbp, endptr); if (*pbp == endptr) { - /* nothing left */ - return SECFailure; + /* nothing left */ + return SECFailure; } if (**pbp != C_EQUAL) { - /* should be an equal sign */ - return SECFailure; + /* should be an equal sign */ + return SECFailure; } /* skip over the equal sign */ (*pbp)++; - + return SECSuccess; } /* Returns the number of bytes in the value. 0 means failure. */ static int -scanVal(const char **pbp, const char *endptr, char *valBuf, int valBufSize) +scanVal(const char** pbp, const char* endptr, char* valBuf, int valBufSize) { - const char *bp; - char *valBufp; + const char* bp; + char* valBufp; int vallen = 0; PRBool isQuoted; - + PORT_Assert(valBufSize > 0); - + /* skip optional leading space */ skipSpace(pbp, endptr); - if(*pbp == endptr) { - /* nothing left */ - return 0; + if (*pbp == endptr) { + /* nothing left */ + return 0; } - + bp = *pbp; - + /* quoted? */ if (*bp == C_DOUBLE_QUOTE) { - isQuoted = PR_TRUE; - /* skip over it */ - bp++; - } else { - isQuoted = PR_FALSE; + isQuoted = PR_TRUE; + /* skip over it */ + bp++; } - + else { + isQuoted = PR_FALSE; + } + valBufp = valBuf; while (bp < endptr) { - char c = *bp; - if (c == C_BACKSLASH) { - /* escape character */ - bp++; - if (bp >= endptr) { - /* escape charater must appear with paired char */ - *pbp = bp; - return 0; - } - c = *bp; - if (IS_HEX(c) && (endptr - bp) >= 2 && IS_HEX(bp[1])) { - bp++; - c = (char)((x2b[(PRUint8)c] << 4) | x2b[(PRUint8)*bp]); - } - } else if (c == '#' && bp == *pbp) { - /* ignore leading #, quotation not required for it. */ - } else if (!isQuoted && SPECIAL_CHAR(c)) { - /* unescaped special and not within quoted value */ - break; - } else if (c == C_DOUBLE_QUOTE) { - /* reached unescaped double quote */ - break; - } - /* append character */ + char c = *bp; + if (c == C_BACKSLASH) { + /* escape character */ + bp++; + if (bp >= endptr) { + /* escape charater must appear with paired char */ + *pbp = bp; + return 0; + } + c = *bp; + if (IS_HEX(c) && (endptr - bp) >= 2 && IS_HEX(bp[1])) { + bp++; + c = (char)((x2b[(PRUint8)c] << 4) | x2b[(PRUint8)*bp]); + } + } + else if (c == '#' && bp == *pbp) { + /* ignore leading #, quotation not required for it. */ + } + else if (!isQuoted && SPECIAL_CHAR(c)) { + /* unescaped special and not within quoted value */ + break; + } + else if (c == C_DOUBLE_QUOTE) { + /* reached unescaped double quote */ + break; + } + /* append character */ vallen++; - if (vallen >= valBufSize) { - *pbp = bp; - return 0; - } - *valBufp++ = c; - bp++; + if (vallen >= valBufSize) { + *pbp = bp; + return 0; + } + *valBufp++ = c; + bp++; } - + /* strip trailing spaces from unquoted values */ if (!isQuoted) { - while (valBufp > valBuf) { - char c = valBufp[-1]; - if (! OPTIONAL_SPACE(c)) - break; - --valBufp; - } - vallen = valBufp - valBuf; + while (valBufp > valBuf) { + char c = valBufp[-1]; + if (!OPTIONAL_SPACE(c)) + break; + --valBufp; + } + vallen = valBufp - valBuf; } - + if (isQuoted) { - /* insist that we stopped on a double quote */ - if (*bp != C_DOUBLE_QUOTE) { - *pbp = bp; - return 0; - } - /* skip over the quote and skip optional space */ - bp++; - skipSpace(&bp, endptr); + /* insist that we stopped on a double quote */ + if (*bp != C_DOUBLE_QUOTE) { + *pbp = bp; + return 0; + } + /* skip over the quote and skip optional space */ + bp++; + skipSpace(&bp, endptr); } - + *pbp = bp; - + /* null-terminate valBuf -- guaranteed at least one space left */ *valBufp = 0; - + return vallen; } /* Caller must set error code upon failure */ static SECStatus -hexToBin(PLArenaPool *pool, SECItem * destItem, const char * src, int len) +hexToBin(PLArenaPool* pool, SECItem* destItem, const char* src, int len) { - PRUint8 * dest; + PRUint8* dest; - destItem->data = NULL; + destItem->data = NULL; if (len <= 0 || (len & 1)) { - goto loser; + goto loser; } len >>= 1; if (!SECITEM_AllocItem(pool, destItem, len)) - goto loser; + goto loser; dest = destItem->data; for (; len > 0; len--, src += 2) { - PRInt16 bin = (x2b[(PRUint8)src[0]] << 4) | x2b[(PRUint8)src[1]]; - if (bin < 0) - goto loser; - *dest++ = (PRUint8)bin; + PRInt16 bin = (x2b[(PRUint8)src[0]] << 4) | x2b[(PRUint8)src[1]]; + if (bin < 0) + goto loser; + *dest++ = (PRUint8)bin; } return SECSuccess; loser: if (!pool) - SECITEM_FreeItem(destItem, PR_FALSE); + SECITEM_FreeItem(destItem, PR_FALSE); return SECFailure; } /* Parses one AVA, starting at *pbp. Stops at endptr. * Advances *pbp past parsed AVA and trailing separator (if present). * On any error, returns NULL and *pbp is undefined. - * On success, returns CERTAVA allocated from arena, and (*pbp)[-1] was - * the last character parsed. *pbp is either equal to endptr or + * On success, returns CERTAVA allocated from arena, and (*pbp)[-1] was + * the last character parsed. *pbp is either equal to endptr or * points to first character after separator. */ -static CERTAVA * -ParseRFC1485AVA(PLArenaPool *arena, const char **pbp, const char *endptr) +static CERTAVA* +ParseRFC1485AVA(PLArenaPool* arena, const char** pbp, const char* endptr) { - CERTAVA *a; - const NameToKind *n2k; - const char *bp; - int vt = -1; - int valLen; - SECOidTag kind = SEC_OID_UNKNOWN; - SECStatus rv = SECFailure; - SECItem derOid = { 0, NULL, 0 }; - SECItem derVal = { 0, NULL, 0}; - char sep = 0; + CERTAVA* a; + const NameToKind* n2k; + const char* bp; + int vt = -1; + int valLen; + SECOidTag kind = SEC_OID_UNKNOWN; + SECStatus rv = SECFailure; + SECItem derOid = { 0, NULL, 0 }; + SECItem derVal = { 0, NULL, 0 }; + char sep = 0; char tagBuf[32]; char valBuf[1024]; PORT_Assert(arena); if (SECSuccess != scanTag(pbp, endptr, tagBuf, sizeof tagBuf) || - !(valLen = scanVal(pbp, endptr, valBuf, sizeof valBuf))) { - goto loser; + !(valLen = scanVal(pbp, endptr, valBuf, sizeof valBuf))) { + goto loser; } bp = *pbp; if (bp < endptr) { - sep = *bp++; /* skip over separator */ + sep = *bp++; /* skip over separator */ } *pbp = bp; /* if we haven't finished, insist that we've stopped on a separator */ if (sep && sep != ',' && sep != ';' && sep != '+') { - goto loser; + goto loser; } /* is this a dotted decimal OID attribute type ? */ if (!PL_strncasecmp("oid.", tagBuf, 4)) { rv = SEC_StringToOID(arena, &derOid, tagBuf, strlen(tagBuf)); - } else { - for (n2k = name2kinds; n2k->name; n2k++) { - SECOidData *oidrec; - if (PORT_Strcasecmp(n2k->name, tagBuf) == 0) { - kind = n2k->kind; - vt = n2k->valueType; - oidrec = SECOID_FindOIDByTag(kind); - if (oidrec == NULL) - goto loser; - derOid = oidrec->oid; - break; - } - } } - if (kind == SEC_OID_UNKNOWN && rv != SECSuccess) - goto loser; + else { + for (n2k = name2kinds; n2k->name; n2k++) { + SECOidData* oidrec; + if (PORT_Strcasecmp(n2k->name, tagBuf) == 0) { + kind = n2k->kind; + vt = n2k->valueType; + oidrec = SECOID_FindOIDByTag(kind); + if (oidrec == NULL) + goto loser; + derOid = oidrec->oid; + break; + } + } + } + if (kind == SEC_OID_UNKNOWN && rv != SECSuccess) + goto loser; /* Is this a hex encoding of a DER attribute value ? */ if ('#' == valBuf[0]) { - /* convert attribute value from hex to binary */ - rv = hexToBin(arena, &derVal, valBuf + 1, valLen - 1); - if (rv) - goto loser; - a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal); - } else { - if (kind == SEC_OID_UNKNOWN) - goto loser; - if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2) - goto loser; - if (vt == SEC_ASN1_PRINTABLE_STRING && - !IsPrintable((unsigned char*) valBuf, valLen)) - goto loser; - if (vt == SEC_ASN1_DS) { - /* RFC 4630: choose PrintableString or UTF8String */ - if (IsPrintable((unsigned char*) valBuf, valLen)) - vt = SEC_ASN1_PRINTABLE_STRING; - else - vt = SEC_ASN1_UTF8_STRING; - } + /* convert attribute value from hex to binary */ + rv = hexToBin(arena, &derVal, valBuf + 1, valLen - 1); + if (rv) + goto loser; + a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal); + } + else { + if (kind == SEC_OID_UNKNOWN) + goto loser; + if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2) + goto loser; + if (vt == SEC_ASN1_PRINTABLE_STRING && + !IsPrintable((unsigned char*)valBuf, valLen)) + goto loser; + if (vt == SEC_ASN1_DS) { + /* RFC 4630: choose PrintableString or UTF8String */ + if (IsPrintable((unsigned char*)valBuf, valLen)) + vt = SEC_ASN1_PRINTABLE_STRING; + else + vt = SEC_ASN1_UTF8_STRING; + } - derVal.data = (unsigned char*) valBuf; - derVal.len = valLen; - a = CERT_CreateAVAFromSECItem(arena, kind, vt, &derVal); + derVal.data = (unsigned char*)valBuf; + derVal.len = valLen; + a = CERT_CreateAVAFromSECItem(arena, kind, vt, &derVal); } return a; @@ -450,80 +458,82 @@ loser: return 0; } -static CERTName * -ParseRFC1485Name(const char *buf, int len) +static CERTName* +ParseRFC1485Name(const char* buf, int len) { SECStatus rv; - CERTName *name; + CERTName* name; const char *bp, *e; - CERTAVA *ava; - CERTRDN *rdn = NULL; + CERTAVA* ava; + CERTRDN* rdn = NULL; name = CERT_CreateName(NULL); if (name == NULL) { - return NULL; + return NULL; } - + e = buf + len; bp = buf; while (bp < e) { - ava = ParseRFC1485AVA(name->arena, &bp, e); - if (ava == 0) - goto loser; - if (!rdn) { - rdn = CERT_CreateRDN(name->arena, ava, (CERTAVA *)0); - if (rdn == 0) - goto loser; - rv = CERT_AddRDN(name, rdn); - } else { - rv = CERT_AddAVA(name->arena, rdn, ava); - } - if (rv) - goto loser; - if (bp[-1] != '+') - rdn = NULL; /* done with this RDN */ - skipSpace(&bp, e); + ava = ParseRFC1485AVA(name->arena, &bp, e); + if (ava == 0) + goto loser; + if (!rdn) { + rdn = CERT_CreateRDN(name->arena, ava, (CERTAVA*)0); + if (rdn == 0) + goto loser; + rv = CERT_AddRDN(name, rdn); + } + else { + rv = CERT_AddAVA(name->arena, rdn, ava); + } + if (rv) + goto loser; + if (bp[-1] != '+') + rdn = NULL; /* done with this RDN */ + skipSpace(&bp, e); } if (name->rdns[0] == 0) { - /* empty name -- illegal */ - goto loser; + /* empty name -- illegal */ + goto loser; } /* Reverse order of RDNS to comply with RFC */ { - CERTRDN **firstRdn; - CERTRDN **lastRdn; - CERTRDN *tmp; - - /* get first one */ - firstRdn = name->rdns; - - /* find last one */ - lastRdn = name->rdns; - while (*lastRdn) lastRdn++; - lastRdn--; - - /* reverse list */ - for ( ; firstRdn < lastRdn; firstRdn++, lastRdn--) { - tmp = *firstRdn; - *firstRdn = *lastRdn; - *lastRdn = tmp; - } + CERTRDN** firstRdn; + CERTRDN** lastRdn; + CERTRDN* tmp; + + /* get first one */ + firstRdn = name->rdns; + + /* find last one */ + lastRdn = name->rdns; + while (*lastRdn) + lastRdn++; + lastRdn--; + + /* reverse list */ + for (; firstRdn < lastRdn; firstRdn++, lastRdn--) { + tmp = *firstRdn; + *firstRdn = *lastRdn; + *lastRdn = tmp; + } } - + /* return result */ return name; - - loser: + +loser: CERT_DestroyName(name); return NULL; } -CERTName * -CERT_AsciiToName(const char *string) +CERTName* +CERT_AsciiToName(const char* string) { - CERTName *name; + CERTName* name; name = ParseRFC1485Name(string, PORT_Strlen(string)); return name; } @@ -531,7 +541,7 @@ CERT_AsciiToName(const char *string) /************************************************************************/ typedef struct stringBufStr { - char *buffer; + char* buffer; unsigned offset; unsigned size; } stringBuf; @@ -539,9 +549,9 @@ typedef struct stringBufStr { #define DEFAULT_BUFFER_SIZE 200 static SECStatus -AppendStr(stringBuf *bufp, char *str) +AppendStr(stringBuf* bufp, char* str) { - char *buf; + char* buf; unsigned bufLen, bufSize, len; int size = 0; @@ -551,33 +561,35 @@ AppendStr(stringBuf *bufp, char *str) len = PORT_Strlen(str); bufSize = bufLen + len; if (!buf) { - bufSize++; - size = PR_MAX(DEFAULT_BUFFER_SIZE,bufSize*2); - buf = (char *) PORT_Alloc(size); - bufp->size = size; - } else if (bufp->size < bufSize) { - size = bufSize*2; - buf =(char *) PORT_Realloc(buf,size); - bufp->size = size; + bufSize++; + size = PR_MAX(DEFAULT_BUFFER_SIZE, bufSize * 2); + buf = (char*)PORT_Alloc(size); + bufp->size = size; + } + else if (bufp->size < bufSize) { + size = bufSize * 2; + buf = (char*)PORT_Realloc(buf, size); + bufp->size = size; } if (!buf) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return SECFailure; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return SECFailure; } bufp->buffer = buf; bufp->offset = bufSize; /* Concatenate str onto buf */ buf = buf + bufLen; - if (bufLen) buf--; /* stomp on old '\0' */ - PORT_Memcpy(buf, str, len+1); /* put in new null */ + if (bufLen) + buf--; /* stomp on old '\0' */ + PORT_Memcpy(buf, str, len + 1); /* put in new null */ return SECSuccess; } typedef enum { - minimalEscape = 0, /* only hex escapes, and " and \ */ - minimalEscapeAndQuote, /* as above, plus quoting */ - fullEscape /* no quoting, full escaping */ + minimalEscape = 0, /* only hex escapes, and " and \ */ + minimalEscapeAndQuote, /* as above, plus quoting */ + fullEscape /* no quoting, full escaping */ } EQMode; /* Some characters must be escaped as a hex string, e.g. c -> \nn . @@ -590,250 +602,259 @@ typedef enum { * need quoting, then this function changes it to minimalEscape. */ static int -cert_RFC1485_GetRequiredLen(const char *src, int srclen, EQMode *pEQMode) +cert_RFC1485_GetRequiredLen(const char* src, int srclen, EQMode* pEQMode) { - int i, reqLen=0; + int i, reqLen = 0; EQMode mode = pEQMode ? *pEQMode : minimalEscape; PRBool needsQuoting = PR_FALSE; char lastC = 0; /* need to make an initial pass to determine if quoting is needed */ for (i = 0; i < srclen; i++) { - char c = src[i]; - reqLen++; - if (NEEDS_HEX_ESCAPE(c)) { /* c -> \xx */ - reqLen += 2; - } else if (NEEDS_ESCAPE(c)) { /* c -> \c */ - reqLen++; - } else if (SPECIAL_CHAR(c)) { - if (mode == minimalEscapeAndQuote) /* quoting is allowed */ - needsQuoting = PR_TRUE; /* entirety will need quoting */ - else if (mode == fullEscape) - reqLen++; /* MAY escape this character */ - } else if (OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)) { - if (mode == minimalEscapeAndQuote) /* quoting is allowed */ - needsQuoting = PR_TRUE; /* entirety will need quoting */ - } - lastC = c; + char c = src[i]; + reqLen++; + if (NEEDS_HEX_ESCAPE(c)) { /* c -> \xx */ + reqLen += 2; + } + else if (NEEDS_ESCAPE(c)) { /* c -> \c */ + reqLen++; + } + else if (SPECIAL_CHAR(c)) { + if (mode == minimalEscapeAndQuote) /* quoting is allowed */ + needsQuoting = PR_TRUE; /* entirety will need quoting */ + else if (mode == fullEscape) + reqLen++; /* MAY escape this character */ + } + else if (OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)) { + if (mode == minimalEscapeAndQuote) /* quoting is allowed */ + needsQuoting = PR_TRUE; /* entirety will need quoting */ + } + lastC = c; } /* if it begins or ends in optional space it needs quoting */ - if (!needsQuoting && srclen > 0 && mode == minimalEscapeAndQuote && - (OPTIONAL_SPACE(src[srclen-1]) || OPTIONAL_SPACE(src[0]))) { - needsQuoting = PR_TRUE; + if (!needsQuoting && srclen > 0 && mode == minimalEscapeAndQuote && + (OPTIONAL_SPACE(src[srclen - 1]) || OPTIONAL_SPACE(src[0]))) { + needsQuoting = PR_TRUE; } - if (needsQuoting) - reqLen += 2; + if (needsQuoting) + reqLen += 2; if (pEQMode && mode == minimalEscapeAndQuote && !needsQuoting) - *pEQMode = minimalEscape; + *pEQMode = minimalEscape; return reqLen; } static const char hexChars[16] = { "0123456789abcdef" }; static SECStatus -escapeAndQuote(char *dst, int dstlen, char *src, int srclen, EQMode *pEQMode) +escapeAndQuote(char* dst, int dstlen, char* src, int srclen, EQMode* pEQMode) { - int i, reqLen=0; + int i, reqLen = 0; EQMode mode = pEQMode ? *pEQMode : minimalEscape; /* space for terminal null */ reqLen = cert_RFC1485_GetRequiredLen(src, srclen, &mode) + 1; if (reqLen > dstlen) { - PORT_SetError(SEC_ERROR_OUTPUT_LEN); - return SECFailure; + PORT_SetError(SEC_ERROR_OUTPUT_LEN); + return SECFailure; } if (mode == minimalEscapeAndQuote) *dst++ = C_DOUBLE_QUOTE; for (i = 0; i < srclen; i++) { - char c = src[i]; - if (NEEDS_HEX_ESCAPE(c)) { - *dst++ = C_BACKSLASH; - *dst++ = hexChars[ (c >> 4) & 0x0f ]; - *dst++ = hexChars[ c & 0x0f ]; - } else { - if (NEEDS_ESCAPE(c) || (SPECIAL_CHAR(c) && mode == fullEscape)) { - *dst++ = C_BACKSLASH; - } - *dst++ = c; - } + char c = src[i]; + if (NEEDS_HEX_ESCAPE(c)) { + *dst++ = C_BACKSLASH; + *dst++ = hexChars[(c >> 4) & 0x0f]; + *dst++ = hexChars[c & 0x0f]; + } + else { + if (NEEDS_ESCAPE(c) || (SPECIAL_CHAR(c) && mode == fullEscape)) { + *dst++ = C_BACKSLASH; + } + *dst++ = c; + } } if (mode == minimalEscapeAndQuote) - *dst++ = C_DOUBLE_QUOTE; + *dst++ = C_DOUBLE_QUOTE; *dst++ = 0; if (pEQMode) - *pEQMode = mode; + *pEQMode = mode; return SECSuccess; } SECStatus -CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen) +CERT_RFC1485_EscapeAndQuote(char* dst, int dstlen, char* src, int srclen) { EQMode mode = minimalEscapeAndQuote; return escapeAndQuote(dst, dstlen, src, srclen, &mode); } - /* convert an OID to dotted-decimal representation */ /* Returns a string that must be freed with PR_smprintf_free(), */ -char * -CERT_GetOidString(const SECItem *oid) +char* +CERT_GetOidString(const SECItem* oid) { - PRUint8 *stop; /* points to first byte after OID string */ - PRUint8 *first; /* byte of an OID component integer */ - PRUint8 *last; /* byte of an OID component integer */ - char *rvString = NULL; - char *prefix = NULL; + PRUint8* stop; /* points to first byte after OID string */ + PRUint8* first; /* byte of an OID component integer */ + PRUint8* last; /* byte of an OID component integer */ + char* rvString = NULL; + char* prefix = NULL; #define MAX_OID_LEN 1024 /* bytes */ if (oid->len > MAX_OID_LEN) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - return NULL; + PORT_SetError(SEC_ERROR_INPUT_LEN); + return NULL; } /* first will point to the next sequence of bytes to decode */ - first = (PRUint8 *)oid->data; + first = (PRUint8*)oid->data; /* stop points to one past the legitimate data */ - stop = &first[ oid->len ]; + stop = &first[oid->len]; /* - * Check for our pseudo-encoded single-digit OIDs - */ + * Check for our pseudo-encoded single-digit OIDs + */ if ((*first == 0x80) && (2 == oid->len)) { - /* Funky encoding. The second byte is the number */ - rvString = PR_smprintf("%lu", (PRUint32)first[1]); - if (!rvString) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - } - return rvString; + /* Funky encoding. The second byte is the number */ + rvString = PR_smprintf("%lu", (PRUint32)first[1]); + if (!rvString) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + } + return rvString; } for (; first < stop; first = last + 1) { - unsigned int bytesBeforeLast; - - for (last = first; last < stop; last++) { - if (0 == (*last & 0x80)) { - break; - } - } - bytesBeforeLast = (unsigned int)(last - first); - if (bytesBeforeLast <= 3U) { /* 0-28 bit number */ - PRUint32 n = 0; - PRUint32 c; + unsigned int bytesBeforeLast; -#define CGET(i, m) \ - c = last[-i] & m; \ - n |= c << (7 * i) + for (last = first; last < stop; last++) { + if (0 == (*last & 0x80)) { + break; + } + } + bytesBeforeLast = (unsigned int)(last - first); + if (bytesBeforeLast <= 3U) { /* 0-28 bit number */ + PRUint32 n = 0; + PRUint32 c; -#define CASE(i, m) \ - case i: \ - CGET(i, m); \ - if (!n) goto unsupported \ - /* fall-through */ +#define CGET(i, m) \ + c = last[-i] & m; \ + n |= c << (7 * i) - switch (bytesBeforeLast) { - CASE(3, 0x7f); - CASE(2, 0x7f); - CASE(1, 0x7f); - case 0: n |= last[0] & 0x7f; - break; - } - if (last[0] & 0x80) - goto unsupported; - - if (!rvString) { - /* This is the first number.. decompose it */ - PRUint32 one = PR_MIN(n/40, 2); /* never > 2 */ - PRUint32 two = n - (one * 40); - - rvString = PR_smprintf("OID.%lu.%lu", one, two); - } else { - prefix = rvString; - rvString = PR_smprintf("%s.%lu", prefix, n); - } - } else if (bytesBeforeLast <= 9U) { /* 29-64 bit number */ - PRUint64 n = 0; - PRUint64 c; +#define CASE(i, m) \ + case i: \ + CGET(i, m); \ + if (!n) \ + goto unsupported /* fall-through */ - switch (bytesBeforeLast) { - CASE(9, 0x01); - CASE(8, 0x7f); - CASE(7, 0x7f); - CASE(6, 0x7f); - CASE(5, 0x7f); - CASE(4, 0x7f); - CGET(3, 0x7f); - CGET(2, 0x7f); - CGET(1, 0x7f); - CGET(0, 0x7f); - break; - } - if (last[0] & 0x80) - goto unsupported; - - if (!rvString) { - /* This is the first number.. decompose it */ - PRUint64 one = PR_MIN(n/40, 2); /* never > 2 */ - PRUint64 two = n - (one * 40); - - rvString = PR_smprintf("OID.%llu.%llu", one, two); - } else { - prefix = rvString; - rvString = PR_smprintf("%s.%llu", prefix, n); - } - } else { - /* More than a 64-bit number, or not minimal encoding. */ -unsupported: - if (!rvString) - rvString = PR_smprintf("OID.UNSUPPORTED"); - else { - prefix = rvString; - rvString = PR_smprintf("%s.UNSUPPORTED", prefix); - } - } + switch (bytesBeforeLast) { + CASE(3, 0x7f); + CASE(2, 0x7f); + CASE(1, 0x7f); + case 0: + n |= + last[0] & 0x7f; + break; + } + if (last[0] & 0x80) + goto unsupported; - if (prefix) { - PR_smprintf_free(prefix); - prefix = NULL; - } - if (!rvString) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - break; - } + if (!rvString) { + /* This is the first number.. decompose it */ + PRUint32 one = PR_MIN(n / 40, 2); /* never > 2 */ + PRUint32 two = n - (one * 40); + + rvString = PR_smprintf("OID.%lu.%lu", one, two); + } + else { + prefix = rvString; + rvString = PR_smprintf("%s.%lu", prefix, n); + } + } + else if (bytesBeforeLast <= 9U) { /* 29-64 bit number */ + PRUint64 n = 0; + PRUint64 c; + + switch (bytesBeforeLast) { + CASE(9, 0x01); + CASE(8, 0x7f); + CASE(7, 0x7f); + CASE(6, 0x7f); + CASE(5, 0x7f); + CASE(4, 0x7f); + CGET(3, 0x7f); + CGET(2, 0x7f); + CGET(1, 0x7f); + CGET(0, 0x7f); + break; + } + if (last[0] & 0x80) + goto unsupported; + + if (!rvString) { + /* This is the first number.. decompose it */ + PRUint64 one = PR_MIN(n / 40, 2); /* never > 2 */ + PRUint64 two = n - (one * 40); + + rvString = PR_smprintf("OID.%llu.%llu", one, two); + } + else { + prefix = rvString; + rvString = PR_smprintf("%s.%llu", prefix, n); + } + } + else { + /* More than a 64-bit number, or not minimal encoding. */ + unsupported: + if (!rvString) + rvString = PR_smprintf("OID.UNSUPPORTED"); + else { + prefix = rvString; + rvString = PR_smprintf("%s.UNSUPPORTED", prefix); + } + } + + if (prefix) { + PR_smprintf_free(prefix); + prefix = NULL; + } + if (!rvString) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + break; + } } return rvString; } /* convert DER-encoded hex to a string */ -static SECItem * -get_hex_string(SECItem *data) +static SECItem* +get_hex_string(SECItem* data) { - SECItem *rv; + SECItem* rv; unsigned int i, j; static const char hex[] = { "0123456789ABCDEF" }; /* '#' + 2 chars per octet + terminator */ - rv = SECITEM_AllocItem(NULL, NULL, data->len*2 + 2); + rv = SECITEM_AllocItem(NULL, NULL, data->len * 2 + 2); if (!rv) { - return NULL; + return NULL; } rv->data[0] = '#'; rv->len = 1 + 2 * data->len; - for (i=0; ilen; i++) { - j = data->data[i]; - rv->data[2*i+1] = hex[j >> 4]; - rv->data[2*i+2] = hex[j & 15]; + for (i = 0; i < data->len; i++) { + j = data->data[i]; + rv->data[2 * i + 1] = hex[j >> 4]; + rv->data[2 * i + 2] = hex[j & 15]; } rv->data[rv->len] = 0; return rv; } -/* For compliance with RFC 2253, RFC 3280 and RFC 4630, we choose to - * use the NAME=STRING form, rather than the OID.N.N=#hexXXXX form, +/* For compliance with RFC 2253, RFC 3280 and RFC 4630, we choose to + * use the NAME=STRING form, rather than the OID.N.N=#hexXXXX form, * when both of these conditions are met: - * 1) The attribute name OID (kind) has a known name string that is + * 1) The attribute name OID (kind) has a known name string that is * defined in one of those RFCs, or in RFCs that they cite, AND * 2) The attribute's value encoding is RFC compliant for the kind * (e.g., the value's encoding tag is correct for the kind, and @@ -842,79 +863,79 @@ get_hex_string(SECItem *data) * Otherwise, we use the OID.N.N=#hexXXXX form. * * If the caller prefers maximum human readability to RFC compliance, - * then + * then * - We print the kind in NAME= string form if we know the name - * string for the attribute type OID, regardless of whether the + * string for the attribute type OID, regardless of whether the * value is correctly encoded or not. else we use the OID.N.N= form. * - We use the non-hex STRING form for the attribute value if the - * value can be represented in such a form. Otherwise, we use + * value can be represented in such a form. Otherwise, we use * the hex string form. - * This implies that, for maximum human readability, in addition to + * This implies that, for maximum human readability, in addition to * the two forms allowed by the RFC, we allow two other forms of output: - * - the OID.N.N=STRING form, and + * - the OID.N.N=STRING form, and * - the NAME=#hexXXXX form * When the caller prefers maximum human readability, we do not allow * the value of any attribute to exceed the length allowed by the RFC. - * If the attribute value exceeds the allowed length, we truncate it to + * If the attribute value exceeds the allowed length, we truncate it to * the allowed length and append "...". - * Also in this case, we arbitrarily impose a limit on the length of the + * Also in this case, we arbitrarily impose a limit on the length of the * entire AVA encoding, regardless of the form, of 384 bytes per AVA. - * This limit includes the trailing NULL character. If the encoded + * This limit includes the trailing NULL character. If the encoded * AVA length exceeds that limit, this function reports failure to encode * the AVA. * - * An ASCII representation of an AVA is said to be "invertible" if + * An ASCII representation of an AVA is said to be "invertible" if * conversion back to DER reproduces the original DER encoding exactly. * The RFC 2253 rules do not ensure that all ASCII AVAs derived according - * to its rules are invertible. That is because the RFCs allow some + * to its rules are invertible. That is because the RFCs allow some * attribute values to be encoded in any of a number of encodings, * and the encoding type information is lost in the non-hex STRING form. * This is particularly true of attributes of type DirectoryString. - * The encoding type information is always preserved in the hex string + * The encoding type information is always preserved in the hex string * form, because the hex includes the entire DER encoding of the value. * - * So, when the caller perfers maximum invertibility, we apply the - * RFC compliance rules stated above, and add a third required - * condition on the use of the NAME=STRING form. - * 3) The attribute's kind is not is allowed to be encoded in any of + * So, when the caller perfers maximum invertibility, we apply the + * RFC compliance rules stated above, and add a third required + * condition on the use of the NAME=STRING form. + * 3) The attribute's kind is not is allowed to be encoded in any of * several different encodings, such as DirectoryStrings. * * The chief difference between CERT_N2A_STRICT and CERT_N2A_INVERTIBLE * is that the latter forces DirectoryStrings to be hex encoded. * - * As a simplification, we assume the value is correctly encoded for + * As a simplification, we assume the value is correctly encoded for * its encoding type. That is, we do not test that all the characters * in a string encoded type are allowed by that type. We assume it. */ static SECStatus -AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict) +AppendAVA(stringBuf* bufp, CERTAVA* ava, CertStrictnessLevel strict) { #define TMPBUF_LEN 2048 - const NameToKind *pn2k = name2kinds; - SECItem *avaValue = NULL; - char *unknownTag = NULL; - char *encodedAVA = NULL; - PRBool useHex = PR_FALSE; /* use =#hexXXXX form */ - PRBool truncateName = PR_FALSE; - PRBool truncateValue = PR_FALSE; - SECOidTag endKind; - SECStatus rv; + const NameToKind* pn2k = name2kinds; + SECItem* avaValue = NULL; + char* unknownTag = NULL; + char* encodedAVA = NULL; + PRBool useHex = PR_FALSE; /* use =#hexXXXX form */ + PRBool truncateName = PR_FALSE; + PRBool truncateValue = PR_FALSE; + SECOidTag endKind; + SECStatus rv; unsigned int len; unsigned int nameLen, valueLen; unsigned int maxName, maxValue; - EQMode mode = minimalEscapeAndQuote; - NameToKind n2k = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS }; - char tmpBuf[TMPBUF_LEN]; + EQMode mode = minimalEscapeAndQuote; + NameToKind n2k = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS }; + char tmpBuf[TMPBUF_LEN]; -#define tagName n2k.name /* non-NULL means use NAME= form */ +#define tagName n2k.name /* non-NULL means use NAME= form */ #define maxBytes n2k.maxLen -#define tag n2k.kind -#define vt n2k.valueType +#define tag n2k.kind +#define vt n2k.valueType /* READABLE mode recognizes more names from the name2kinds table - * than do STRICT or INVERTIBLE modes. This assignment chooses the - * point in the table where the attribute type name scanning stops. - */ + * than do STRICT or INVERTIBLE modes. This assignment chooses the + * point in the table where the attribute type name scanning stops. + */ endKind = (strict == CERT_N2A_READABLE) ? SEC_OID_UNKNOWN : SEC_OID_AVA_POSTAL_ADDRESS; tag = CERT_GetAVATag(ava); @@ -922,146 +943,152 @@ AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict) ++pn2k; } - if (pn2k->kind != endKind ) { + if (pn2k->kind != endKind) { n2k = *pn2k; - } else if (strict != CERT_N2A_READABLE) { + } + else if (strict != CERT_N2A_READABLE) { useHex = PR_TRUE; } /* For invertable form, force Directory Strings to use hex form. */ if (strict == CERT_N2A_INVERTIBLE && vt == SEC_ASN1_DS) { - tagName = NULL; /* must use OID.N form */ - useHex = PR_TRUE; /* must use hex string */ + tagName = NULL; /* must use OID.N form */ + useHex = PR_TRUE; /* must use hex string */ } if (!useHex) { - avaValue = CERT_DecodeAVAValue(&ava->value); - if (!avaValue) { - useHex = PR_TRUE; - if (strict != CERT_N2A_READABLE) { - tagName = NULL; /* must use OID.N form */ - } - } + avaValue = CERT_DecodeAVAValue(&ava->value); + if (!avaValue) { + useHex = PR_TRUE; + if (strict != CERT_N2A_READABLE) { + tagName = NULL; /* must use OID.N form */ + } + } } if (!tagName) { - /* handle unknown attribute types per RFC 2253 */ - tagName = unknownTag = CERT_GetOidString(&ava->type); - if (!tagName) { - if (avaValue) - SECITEM_FreeItem(avaValue, PR_TRUE); - return SECFailure; - } + /* handle unknown attribute types per RFC 2253 */ + tagName = unknownTag = CERT_GetOidString(&ava->type); + if (!tagName) { + if (avaValue) + SECITEM_FreeItem(avaValue, PR_TRUE); + return SECFailure; + } } if (useHex) { - avaValue = get_hex_string(&ava->value); - if (!avaValue) { - if (unknownTag) - PR_smprintf_free(unknownTag); - return SECFailure; - } + avaValue = get_hex_string(&ava->value); + if (!avaValue) { + if (unknownTag) + PR_smprintf_free(unknownTag); + return SECFailure; + } } - nameLen = strlen(tagName); - valueLen = (useHex ? avaValue->len : - cert_RFC1485_GetRequiredLen((char *)avaValue->data, avaValue->len, - &mode)); + nameLen = strlen(tagName); + valueLen = + (useHex ? avaValue->len : cert_RFC1485_GetRequiredLen( + (char*)avaValue->data, avaValue->len, &mode)); len = nameLen + valueLen + 2; /* Add 2 for '=' and trailing NUL */ - maxName = nameLen; + maxName = nameLen; maxValue = valueLen; if (len <= sizeof(tmpBuf)) { - encodedAVA = tmpBuf; - } else if (strict != CERT_N2A_READABLE) { - encodedAVA = PORT_Alloc(len); - if (!encodedAVA) { - SECITEM_FreeItem(avaValue, PR_TRUE); - if (unknownTag) - PR_smprintf_free(unknownTag); - return SECFailure; - } - } else { - /* Must make output fit in tmpbuf */ - unsigned int fair = (sizeof tmpBuf)/2 - 1; /* for = and \0 */ + encodedAVA = tmpBuf; + } + else if (strict != CERT_N2A_READABLE) { + encodedAVA = PORT_Alloc(len); + if (!encodedAVA) { + SECITEM_FreeItem(avaValue, PR_TRUE); + if (unknownTag) + PR_smprintf_free(unknownTag); + return SECFailure; + } + } + else { + /* Must make output fit in tmpbuf */ + unsigned int fair = (sizeof tmpBuf) / 2 - 1; /* for = and \0 */ - if (nameLen < fair) { - /* just truncate the value */ - maxValue = (sizeof tmpBuf) - (nameLen + 6); /* for "=...\0", - and possibly '"' */ - } else if (valueLen < fair) { - /* just truncate the name */ - maxName = (sizeof tmpBuf) - (valueLen + 5); /* for "=...\0" */ - } else { - /* truncate both */ - maxName = maxValue = fair - 3; /* for "..." */ - } - if (nameLen > maxName) { - PORT_Assert(unknownTag && unknownTag == tagName); - truncateName = PR_TRUE; - nameLen = maxName; - } - encodedAVA = tmpBuf; + if (nameLen < fair) { + /* just truncate the value */ + maxValue = (sizeof tmpBuf) - (nameLen + 6); /* for "=...\0", + and possibly '"' */ + } + else if (valueLen < fair) { + /* just truncate the name */ + maxName = (sizeof tmpBuf) - (valueLen + 5); /* for "=...\0" */ + } + else { + /* truncate both */ + maxName = maxValue = fair - 3; /* for "..." */ + } + if (nameLen > maxName) { + PORT_Assert(unknownTag && unknownTag == tagName); + truncateName = PR_TRUE; + nameLen = maxName; + } + encodedAVA = tmpBuf; } memcpy(encodedAVA, tagName, nameLen); if (truncateName) { - /* If tag name is too long, we know it is an OID form that was - * allocated from the heap, so we can modify it in place - */ - encodedAVA[nameLen-1] = '.'; - encodedAVA[nameLen-2] = '.'; - encodedAVA[nameLen-3] = '.'; + /* If tag name is too long, we know it is an OID form that was + * allocated from the heap, so we can modify it in place + */ + encodedAVA[nameLen - 1] = '.'; + encodedAVA[nameLen - 2] = '.'; + encodedAVA[nameLen - 3] = '.'; } encodedAVA[nameLen++] = '='; - if (unknownTag) - PR_smprintf_free(unknownTag); + if (unknownTag) + PR_smprintf_free(unknownTag); if (strict == CERT_N2A_READABLE && maxValue > maxBytes) - maxValue = maxBytes; + maxValue = maxBytes; if (valueLen > maxValue) { - valueLen = maxValue; - truncateValue = PR_TRUE; + valueLen = maxValue; + truncateValue = PR_TRUE; } /* escape and quote as necessary - don't quote hex strings */ if (useHex) { - char * end = encodedAVA + nameLen + valueLen; - memcpy(encodedAVA + nameLen, (char *)avaValue->data, valueLen); - end[0] = '\0'; - if (truncateValue) { - end[-1] = '.'; - end[-2] = '.'; - end[-3] = '.'; - } - rv = SECSuccess; - } else if (!truncateValue) { - rv = escapeAndQuote(encodedAVA + nameLen, len - nameLen, - (char *)avaValue->data, avaValue->len, &mode); - } else { - /* must truncate the escaped and quoted value */ - char bigTmpBuf[TMPBUF_LEN * 3 + 3]; - PORT_Assert(valueLen < sizeof tmpBuf); - rv = escapeAndQuote(bigTmpBuf, sizeof bigTmpBuf, - (char *)avaValue->data, - PR_MIN(avaValue->len, valueLen), &mode); + char* end = encodedAVA + nameLen + valueLen; + memcpy(encodedAVA + nameLen, (char*)avaValue->data, valueLen); + end[0] = '\0'; + if (truncateValue) { + end[-1] = '.'; + end[-2] = '.'; + end[-3] = '.'; + } + rv = SECSuccess; + } + else if (!truncateValue) { + rv = escapeAndQuote(encodedAVA + nameLen, len - nameLen, + (char*)avaValue->data, avaValue->len, &mode); + } + else { + /* must truncate the escaped and quoted value */ + char bigTmpBuf[TMPBUF_LEN * 3 + 3]; + PORT_Assert(valueLen < sizeof tmpBuf); + rv = escapeAndQuote(bigTmpBuf, sizeof bigTmpBuf, (char*)avaValue->data, + PR_MIN(avaValue->len, valueLen), &mode); - bigTmpBuf[valueLen--] = '\0'; /* hard stop here */ - /* See if we're in the middle of a multi-byte UTF8 character */ - while (((bigTmpBuf[valueLen] & 0xc0) == 0x80) && valueLen > 0) { - bigTmpBuf[valueLen--] = '\0'; - } - /* add ellipsis to signify truncation. */ - bigTmpBuf[++valueLen] = '.'; - bigTmpBuf[++valueLen] = '.'; - bigTmpBuf[++valueLen] = '.'; - if (bigTmpBuf[0] == '"') - bigTmpBuf[++valueLen] = '"'; - bigTmpBuf[++valueLen] = '\0'; - PORT_Assert(nameLen + valueLen <= (sizeof tmpBuf) - 1); - memcpy(encodedAVA + nameLen, bigTmpBuf, valueLen+1); + bigTmpBuf[valueLen--] = '\0'; /* hard stop here */ + /* See if we're in the middle of a multi-byte UTF8 character */ + while (((bigTmpBuf[valueLen] & 0xc0) == 0x80) && valueLen > 0) { + bigTmpBuf[valueLen--] = '\0'; + } + /* add ellipsis to signify truncation. */ + bigTmpBuf[++valueLen] = '.'; + bigTmpBuf[++valueLen] = '.'; + bigTmpBuf[++valueLen] = '.'; + if (bigTmpBuf[0] == '"') + bigTmpBuf[++valueLen] = '"'; + bigTmpBuf[++valueLen] = '\0'; + PORT_Assert(nameLen + valueLen <= (sizeof tmpBuf) - 1); + memcpy(encodedAVA + nameLen, bigTmpBuf, valueLen + 1); } SECITEM_FreeItem(avaValue, PR_TRUE); if (rv == SECSuccess) - rv = AppendStr(bufp, encodedAVA); + rv = AppendStr(bufp, encodedAVA); if (encodedAVA != tmpBuf) - PORT_Free(encodedAVA); + PORT_Free(encodedAVA); return rv; } @@ -1070,63 +1097,67 @@ AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict) #undef tag #undef vt -char * -CERT_NameToAsciiInvertible(CERTName *name, CertStrictnessLevel strict) +char* +CERT_NameToAsciiInvertible(CERTName* name, CertStrictnessLevel strict) { CERTRDN** rdns; CERTRDN** lastRdn; CERTRDN** rdn; PRBool first = PR_TRUE; stringBuf strBuf = { NULL, 0, 0 }; - + rdns = name->rdns; if (rdns == NULL) { - return NULL; + return NULL; } - + /* find last RDN */ lastRdn = rdns; - while (*lastRdn) lastRdn++; + while (*lastRdn) + lastRdn++; lastRdn--; - - /* - * Loop over name contents in _reverse_ RDN order appending to string - */ - for (rdn = lastRdn; rdn >= rdns; rdn--) { - CERTAVA** avas = (*rdn)->avas; - CERTAVA* ava; - PRBool newRDN = PR_TRUE; - /* - * XXX Do we need to traverse the AVAs in reverse order, too? - */ - while (avas && (ava = *avas++) != NULL) { - SECStatus rv; - /* Put in comma or plus separator */ - if (!first) { - /* Use of spaces is deprecated in RFC 2253. */ - rv = AppendStr(&strBuf, newRDN ? "," : "+"); - if (rv) goto loser; - } else { - first = PR_FALSE; - } - - /* Add in tag type plus value into strBuf */ - rv = AppendAVA(&strBuf, ava, strict); - if (rv) goto loser; - newRDN = PR_FALSE; - } + /* + * Loop over name contents in _reverse_ RDN order appending to string + */ + for (rdn = lastRdn; rdn >= rdns; rdn--) { + CERTAVA** avas = (*rdn)->avas; + CERTAVA* ava; + PRBool newRDN = PR_TRUE; + + /* + * XXX Do we need to traverse the AVAs in reverse order, too? + */ + while (avas && (ava = *avas++) != NULL) { + SECStatus rv; + /* Put in comma or plus separator */ + if (!first) { + /* Use of spaces is deprecated in RFC 2253. */ + rv = AppendStr(&strBuf, newRDN ? "," : "+"); + if (rv) + goto loser; + } + else { + first = PR_FALSE; + } + + /* Add in tag type plus value into strBuf */ + rv = AppendAVA(&strBuf, ava, strict); + if (rv) + goto loser; + newRDN = PR_FALSE; + } } return strBuf.buffer; loser: if (strBuf.buffer) { - PORT_Free(strBuf.buffer); + PORT_Free(strBuf.buffer); } return NULL; } -char * -CERT_NameToAscii(CERTName *name) +char* +CERT_NameToAscii(CERTName* name) { return CERT_NameToAsciiInvertible(name, CERT_N2A_READABLE); } @@ -1135,62 +1166,63 @@ CERT_NameToAscii(CERTName *name) * Return the string representation of a DER encoded distinguished name * "dername" - The DER encoded name to convert */ -char * -CERT_DerNameToAscii(SECItem *dername) +char* +CERT_DerNameToAscii(SECItem* dername) { int rv; - PLArenaPool *arena = NULL; + PLArenaPool* arena = NULL; CERTName name; - char *retstr = NULL; - + char* retstr = NULL; + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( arena == NULL) { - goto loser; + + if (arena == NULL) { + goto loser; } - + rv = SEC_QuickDERDecodeItem(arena, &name, CERT_NameTemplate, dername); - - if ( rv != SECSuccess ) { - goto loser; + + if (rv != SECSuccess) { + goto loser; } retstr = CERT_NameToAscii(&name); loser: - if ( arena != NULL ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena != NULL) { + PORT_FreeArena(arena, PR_FALSE); } - - return(retstr); + + return (retstr); } -static char * -avaToString(PLArenaPool *arena, CERTAVA *ava) +static char* +avaToString(PLArenaPool* arena, CERTAVA* ava) { - char * buf = NULL; - SECItem* avaValue; - int valueLen; + char* buf = NULL; + SECItem* avaValue; + int valueLen; avaValue = CERT_DecodeAVAValue(&ava->value); - if(!avaValue) { - return buf; + if (!avaValue) { + return buf; } - valueLen = cert_RFC1485_GetRequiredLen((char *)avaValue->data, - avaValue->len, NULL) + 1; + valueLen = + cert_RFC1485_GetRequiredLen((char*)avaValue->data, avaValue->len, NULL) + 1; if (arena) { - buf = (char *)PORT_ArenaZAlloc(arena, valueLen); - } else { - buf = (char *)PORT_ZAlloc(valueLen); + buf = (char*)PORT_ArenaZAlloc(arena, valueLen); + } + else { + buf = (char*)PORT_ZAlloc(valueLen); } if (buf) { - SECStatus rv = escapeAndQuote(buf, valueLen, (char *)avaValue->data, - avaValue->len, NULL); - if (rv != SECSuccess) { - if (!arena) - PORT_Free(buf); - buf = NULL; - } + SECStatus rv = + escapeAndQuote(buf, valueLen, (char*)avaValue->data, avaValue->len, NULL); + if (rv != SECSuccess) { + if (!arena) + PORT_Free(buf); + buf = NULL; + } } SECITEM_FreeItem(avaValue, PR_TRUE); return buf; @@ -1199,22 +1231,22 @@ avaToString(PLArenaPool *arena, CERTAVA *ava) /* RDNs are sorted from most general to most specific. * This code returns the FIRST one found, the most general one found. */ -static char * -CERT_GetNameElement(PLArenaPool *arena, const CERTName *name, int wantedTag) +static char* +CERT_GetNameElement(PLArenaPool* arena, const CERTName* name, int wantedTag) { CERTRDN** rdns = name->rdns; - CERTRDN* rdn; - CERTAVA* ava = NULL; + CERTRDN* rdn; + CERTAVA* ava = NULL; while (rdns && (rdn = *rdns++) != 0) { - CERTAVA** avas = rdn->avas; - while (avas && (ava = *avas++) != 0) { - int tag = CERT_GetAVATag(ava); - if ( tag == wantedTag ) { - avas = NULL; - rdns = NULL; /* break out of all loops */ - } - } + CERTAVA** avas = rdn->avas; + while (avas && (ava = *avas++) != 0) { + int tag = CERT_GetAVATag(ava); + if (tag == wantedTag) { + avas = NULL; + rdns = NULL; /* break out of all loops */ + } + } } return ava ? avaToString(arena, ava) : NULL; } @@ -1223,119 +1255,124 @@ CERT_GetNameElement(PLArenaPool *arena, const CERTName *name, int wantedTag) * This code returns the LAST one found, the most specific one found. * This is particularly appropriate for Common Name. See RFC 2818. */ -static char * -CERT_GetLastNameElement(PLArenaPool *arena, const CERTName *name, int wantedTag) +static char* +CERT_GetLastNameElement(PLArenaPool* arena, const CERTName* name, int wantedTag) { - CERTRDN** rdns = name->rdns; - CERTRDN* rdn; - CERTAVA* lastAva = NULL; - + CERTRDN** rdns = name->rdns; + CERTRDN* rdn; + CERTAVA* lastAva = NULL; + while (rdns && (rdn = *rdns++) != 0) { - CERTAVA** avas = rdn->avas; - CERTAVA* ava; - while (avas && (ava = *avas++) != 0) { - int tag = CERT_GetAVATag(ava); - if ( tag == wantedTag ) { - lastAva = ava; - } - } + CERTAVA** avas = rdn->avas; + CERTAVA* ava; + while (avas && (ava = *avas++) != 0) { + int tag = CERT_GetAVATag(ava); + if (tag == wantedTag) { + lastAva = ava; + } + } } return lastAva ? avaToString(arena, lastAva) : NULL; } -char * -CERT_GetCertificateEmailAddress(CERTCertificate *cert) +char* +CERT_GetCertificateEmailAddress(CERTCertificate* cert) { - char *rawEmailAddr = NULL; + char* rawEmailAddr = NULL; SECItem subAltName; SECStatus rv; - CERTGeneralName *nameList = NULL; - CERTGeneralName *current; - PLArenaPool *arena = NULL; + CERTGeneralName* nameList = NULL; + CERTGeneralName* current; + PLArenaPool* arena = NULL; int i; - + subAltName.data = NULL; rawEmailAddr = CERT_GetNameElement(cert->arena, &(cert->subject), - SEC_OID_PKCS9_EMAIL_ADDRESS); - if ( rawEmailAddr == NULL ) { - rawEmailAddr = CERT_GetNameElement(cert->arena, &(cert->subject), - SEC_OID_RFC1274_MAIL); + SEC_OID_PKCS9_EMAIL_ADDRESS); + if (rawEmailAddr == NULL) { + rawEmailAddr = + CERT_GetNameElement(cert->arena, &(cert->subject), SEC_OID_RFC1274_MAIL); } - if ( rawEmailAddr == NULL) { + if (rawEmailAddr == NULL) { - rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, - &subAltName); - if (rv != SECSuccess) { - goto finish; - } - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (!arena) { - goto finish; - } - nameList = current = CERT_DecodeAltNameExtension(arena, &subAltName); - if (!nameList ) { - goto finish; - } - if (nameList != NULL) { - do { - if (current->type == certDirectoryName) { - rawEmailAddr = CERT_GetNameElement(cert->arena, - &(current->name.directoryName), - SEC_OID_PKCS9_EMAIL_ADDRESS); - if ( rawEmailAddr == NULL ) { - rawEmailAddr = CERT_GetNameElement(cert->arena, - &(current->name.directoryName), SEC_OID_RFC1274_MAIL); - } - } else if (current->type == certRFC822Name) { - rawEmailAddr = (char*)PORT_ArenaZAlloc(cert->arena, - current->name.other.len + 1); - if (!rawEmailAddr) { - goto finish; - } - PORT_Memcpy(rawEmailAddr, current->name.other.data, - current->name.other.len); - rawEmailAddr[current->name.other.len] = '\0'; - } - if (rawEmailAddr) { - break; - } - current = CERT_GetNextGeneralName(current); - } while (current != nameList); - } + rv = + CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, &subAltName); + if (rv != SECSuccess) { + goto finish; + } + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (!arena) { + goto finish; + } + nameList = current = CERT_DecodeAltNameExtension(arena, &subAltName); + if (!nameList) { + goto finish; + } + if (nameList != NULL) { + do { + if (current->type == certDirectoryName) { + rawEmailAddr = + CERT_GetNameElement(cert->arena, &(current->name.directoryName), + SEC_OID_PKCS9_EMAIL_ADDRESS); + if (rawEmailAddr == + NULL) { + rawEmailAddr = + CERT_GetNameElement(cert->arena, &(current->name.directoryName), + SEC_OID_RFC1274_MAIL); + } + } + else if (current->type == certRFC822Name) { + rawEmailAddr = + (char*)PORT_ArenaZAlloc(cert->arena, current->name.other.len + + 1); + if (!rawEmailAddr) { + goto finish; + } + PORT_Memcpy(rawEmailAddr, current->name.other.data, + current->name.other.len); + rawEmailAddr[current->name.other.len] = + '\0'; + } + if (rawEmailAddr) { + break; + } + current = CERT_GetNextGeneralName(current); + } while (current != nameList); + } } if (rawEmailAddr) { - for (i = 0; i <= (int) PORT_Strlen(rawEmailAddr); i++) { - rawEmailAddr[i] = tolower(rawEmailAddr[i]); - } - } + for (i = 0; i <= (int)PORT_Strlen(rawEmailAddr); i++) { + rawEmailAddr[i] = tolower(rawEmailAddr[i]); + } + } finish: /* Don't free nameList, it's part of the arena. */ if (arena) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } - if ( subAltName.data ) { - SECITEM_FreeItem(&subAltName, PR_FALSE); + if (subAltName.data) { + SECITEM_FreeItem(&subAltName, PR_FALSE); } - return(rawEmailAddr); + return (rawEmailAddr); } -static char * -appendStringToBuf(char *dest, char *src, PRUint32 *pRemaining) +static char* +appendStringToBuf(char* dest, char* src, PRUint32* pRemaining) { PRUint32 len; if (dest && src && src[0] && *pRemaining > (len = PL_strlen(src))) { - PRUint32 i; - for (i = 0; i < len; ++i) - dest[i] = tolower(src[i]); - dest[len] = 0; - dest += len + 1; - *pRemaining -= len + 1; + PRUint32 i; + for (i = 0; i < len; ++i) + dest[i] = tolower(src[i]); + dest[len] = 0; + dest += len + 1; + *pRemaining -= len + 1; } return dest; } @@ -1343,112 +1380,120 @@ appendStringToBuf(char *dest, char *src, PRUint32 *pRemaining) #undef NEEDS_HEX_ESCAPE #define NEEDS_HEX_ESCAPE(c) (c < 0x20) -static char * -appendItemToBuf(char *dest, SECItem *src, PRUint32 *pRemaining) +static char* +appendItemToBuf(char* dest, SECItem* src, PRUint32* pRemaining) { if (dest && src && src->data && src->len && src->data[0]) { - PRUint32 len = src->len; - PRUint32 i; - PRUint32 reqLen = len + 1; - /* are there any embedded control characters ? */ - for (i = 0; i < len; i++) { - if (NEEDS_HEX_ESCAPE(src->data[i])) - reqLen += 2; - } - if (*pRemaining > reqLen) { - for (i = 0; i < len; ++i) { - PRUint8 c = src->data[i]; - if (NEEDS_HEX_ESCAPE(c)) { - *dest++ = C_BACKSLASH; - *dest++ = hexChars[ (c >> 4) & 0x0f ]; - *dest++ = hexChars[ c & 0x0f ]; - } else { - *dest++ = tolower(c); - } - } - *dest++ = '\0'; - *pRemaining -= reqLen; - } + PRUint32 len = src->len; + PRUint32 i; + PRUint32 reqLen = len + 1; + /* are there any embedded control characters ? */ + for (i = 0; i < len; i++) { + if (NEEDS_HEX_ESCAPE(src->data[i])) + reqLen += 2; + } + if (*pRemaining > reqLen) { + for (i = 0; i < len; ++i) { + PRUint8 c = src->data[i]; + if (NEEDS_HEX_ESCAPE(c)) { + *dest++ = + C_BACKSLASH; + *dest++ = + hexChars[(c >> 4) & 0x0f]; + *dest++ = + hexChars[c & 0x0f]; + } + else { + *dest++ = + tolower(c); + } + } + *dest++ = '\0'; + *pRemaining -= reqLen; + } } return dest; } -/* Returns a pointer to an environment-like string, a series of +/* Returns a pointer to an environment-like string, a series of ** null-terminated strings, terminated by a zero-length string. ** This function is intended to be internal to NSS. */ -char * -cert_GetCertificateEmailAddresses(CERTCertificate *cert) +char* +cert_GetCertificateEmailAddresses(CERTCertificate* cert) { - char * rawEmailAddr = NULL; - char * addrBuf = NULL; - char * pBuf = NULL; - PLArenaPool * tmpArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - PRUint32 maxLen = 0; - PRInt32 finalLen = 0; - SECStatus rv; - SECItem subAltName; - - if (!tmpArena) - return addrBuf; + char* rawEmailAddr = NULL; + char* addrBuf = NULL; + char* pBuf = NULL; + PLArenaPool* tmpArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + PRUint32 maxLen = 0; + PRInt32 finalLen = 0; + SECStatus rv; + SECItem subAltName; + + if (!tmpArena) + return addrBuf; subAltName.data = NULL; maxLen = cert->derCert.len; PORT_Assert(maxLen); - if (!maxLen) - maxLen = 2000; /* a guess, should never happen */ + if (!maxLen) + maxLen = 2000; /* a guess, should never happen */ - pBuf = addrBuf = (char *)PORT_ArenaZAlloc(tmpArena, maxLen + 1); - if (!addrBuf) - goto loser; + pBuf = addrBuf = (char*)PORT_ArenaZAlloc(tmpArena, maxLen + 1); + if (!addrBuf) + goto loser; - rawEmailAddr = CERT_GetNameElement(tmpArena, &cert->subject, - SEC_OID_PKCS9_EMAIL_ADDRESS); + rawEmailAddr = + CERT_GetNameElement(tmpArena, &cert->subject, SEC_OID_PKCS9_EMAIL_ADDRESS); pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen); - rawEmailAddr = CERT_GetNameElement(tmpArena, &cert->subject, - SEC_OID_RFC1274_MAIL); + rawEmailAddr = + CERT_GetNameElement(tmpArena, &cert->subject, SEC_OID_RFC1274_MAIL); pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen); - rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, - &subAltName); + rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, &subAltName); if (rv == SECSuccess && subAltName.data) { - CERTGeneralName *nameList = NULL; + CERTGeneralName* nameList = NULL; - if (!!(nameList = CERT_DecodeAltNameExtension(tmpArena, &subAltName))) { - CERTGeneralName *current = nameList; - do { - if (current->type == certDirectoryName) { - rawEmailAddr = CERT_GetNameElement(tmpArena, - ¤t->name.directoryName, - SEC_OID_PKCS9_EMAIL_ADDRESS); - pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen); + if (!!(nameList = CERT_DecodeAltNameExtension(tmpArena, &subAltName))) { + CERTGeneralName* current = nameList; + do { + if (current->type == certDirectoryName) { + rawEmailAddr = + CERT_GetNameElement(tmpArena, ¤t->name.directoryName, + SEC_OID_PKCS9_EMAIL_ADDRESS); + pBuf = + appendStringToBuf(pBuf, rawEmailAddr, &maxLen); - rawEmailAddr = CERT_GetNameElement(tmpArena, - ¤t->name.directoryName, - SEC_OID_RFC1274_MAIL); - pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen); - } else if (current->type == certRFC822Name) { - pBuf = appendItemToBuf(pBuf, ¤t->name.other, &maxLen); - } - current = CERT_GetNextGeneralName(current); - } while (current != nameList); - } - SECITEM_FreeItem(&subAltName, PR_FALSE); - /* Don't free nameList, it's part of the tmpArena. */ + rawEmailAddr = + CERT_GetNameElement( + tmpArena, ¤t->name.directoryName, SEC_OID_RFC1274_MAIL); + pBuf = + appendStringToBuf(pBuf, rawEmailAddr, &maxLen); + } + else if (current->type == certRFC822Name) { + pBuf = + appendItemToBuf(pBuf, ¤t->name.other, &maxLen); + } + current = CERT_GetNextGeneralName(current); + } while (current != nameList); + } + SECITEM_FreeItem(&subAltName, PR_FALSE); + /* Don't free nameList, it's part of the tmpArena. */ } /* now copy superstring to cert's arena */ finalLen = (pBuf - addrBuf) + 1; pBuf = NULL; if (finalLen > 1) { - pBuf = PORT_ArenaAlloc(cert->arena, finalLen); - if (pBuf) { - PORT_Memcpy(pBuf, addrBuf, finalLen); - } + pBuf = PORT_ArenaAlloc(cert->arena, finalLen); + if (pBuf) { + PORT_Memcpy(pBuf, addrBuf, finalLen); + } } loser: if (tmpArena) - PORT_FreeArena(tmpArena, PR_FALSE); + PORT_FreeArena(tmpArena, PR_FALSE); return pBuf; } @@ -1457,11 +1502,11 @@ loser: ** as long as cert's reference count doesn't go to zero. ** Caller should strdup or otherwise copy. */ -const char * /* const so caller won't muck with it. */ -CERT_GetFirstEmailAddress(CERTCertificate * cert) +const char* /* const so caller won't muck with it. */ + CERT_GetFirstEmailAddress(CERTCertificate* cert) { if (cert && cert->emailAddr && cert->emailAddr[0]) - return (const char *)cert->emailAddr; + return (const char*)cert->emailAddr; return NULL; } @@ -1469,92 +1514,91 @@ CERT_GetFirstEmailAddress(CERTCertificate * cert) ** as long as cert's reference count doesn't go to zero. ** Caller should strdup or otherwise copy. */ -const char * /* const so caller won't muck with it. */ -CERT_GetNextEmailAddress(CERTCertificate * cert, const char * prev) +const char* /* const so caller won't muck with it. */ + CERT_GetNextEmailAddress(CERTCertificate* cert, const char* prev) { if (cert && prev && prev[0]) { - PRUint32 len = PL_strlen(prev); - prev += len + 1; - if (prev && prev[0]) - return prev; + PRUint32 len = PL_strlen(prev); + prev += len + 1; + if (prev && prev[0]) + return prev; } return NULL; } /* This is seriously bogus, now that certs store their email addresses in -** subject Alternative Name extensions. +** subject Alternative Name extensions. ** Returns a string allocated by PORT_StrDup, which the caller must free. */ -char * -CERT_GetCertEmailAddress(const CERTName *name) +char* +CERT_GetCertEmailAddress(const CERTName* name) { - char *rawEmailAddr; - char *emailAddr; + char* rawEmailAddr; + char* emailAddr; - rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_PKCS9_EMAIL_ADDRESS); - if ( rawEmailAddr == NULL ) { - rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_MAIL); + if (rawEmailAddr == NULL) { + rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_MAIL); } emailAddr = CERT_FixupEmailAddr(rawEmailAddr); - if ( rawEmailAddr ) { - PORT_Free(rawEmailAddr); + if (rawEmailAddr) { + PORT_Free(rawEmailAddr); } - return(emailAddr); + return (emailAddr); } /* The return value must be freed with PORT_Free. */ -char * -CERT_GetCommonName(const CERTName *name) +char* +CERT_GetCommonName(const CERTName* name) { - return(CERT_GetLastNameElement(NULL, name, SEC_OID_AVA_COMMON_NAME)); + return (CERT_GetLastNameElement(NULL, name, SEC_OID_AVA_COMMON_NAME)); } -char * -CERT_GetCountryName(const CERTName *name) +char* +CERT_GetCountryName(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_COUNTRY_NAME)); + return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_COUNTRY_NAME)); } -char * -CERT_GetLocalityName(const CERTName *name) +char* +CERT_GetLocalityName(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_LOCALITY)); + return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_LOCALITY)); } -char * -CERT_GetStateName(const CERTName *name) +char* +CERT_GetStateName(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_STATE_OR_PROVINCE)); + return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_STATE_OR_PROVINCE)); } -char * -CERT_GetOrgName(const CERTName *name) +char* +CERT_GetOrgName(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATION_NAME)); + return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATION_NAME)); } -char * -CERT_GetDomainComponentName(const CERTName *name) +char* +CERT_GetDomainComponentName(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_DC)); + return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_DC)); } -char * -CERT_GetOrgUnitName(const CERTName *name) +char* +CERT_GetOrgUnitName(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME)); + return ( + CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME)); } -char * -CERT_GetDnQualifier(const CERTName *name) +char* +CERT_GetDnQualifier(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_DN_QUALIFIER)); + return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_DN_QUALIFIER)); } -char * -CERT_GetCertUid(const CERTName *name) +char* +CERT_GetCertUid(const CERTName* name) { - return(CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_UID)); + return (CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_UID)); } - diff --git a/security/nss/lib/certdb/cert.h b/security/nss/lib/certdb/cert.h index 4564dc2ddecb..e0af65ab06d4 100644 --- a/security/nss/lib/certdb/cert.h +++ b/security/nss/lib/certdb/cert.h @@ -22,7 +22,7 @@ #include "certt.h" SEC_BEGIN_PROTOS - + /**************************************************************************** * * RFC1485 ascii to/from X.? RelativeDistinguishedName (aka CERTName) @@ -47,14 +47,14 @@ extern char *CERT_NameToAscii(CERTName *name); ** Returns a string that must be freed with PORT_Free(). ** Caller chooses encoding rules. */ -extern char *CERT_NameToAsciiInvertible(CERTName *name, +extern char *CERT_NameToAsciiInvertible(CERTName *name, CertStrictnessLevel strict); extern CERTAVA *CERT_CopyAVA(PLArenaPool *arena, CERTAVA *src); /* convert an OID to dotted-decimal representation */ /* Returns a string that must be freed with PR_smprintf_free(). */ -extern char * CERT_GetOidString(const SECItem *oid); +extern char *CERT_GetOidString(const SECItem *oid); /* ** Examine an AVA and return the tag that refers to it. The AVA tags are @@ -126,24 +126,24 @@ extern SECComparison CERT_CompareName(const CERTName *a, const CERTName *b); /* ** Convert a CERTName into something readable */ -extern char *CERT_FormatName (CERTName *name); +extern char *CERT_FormatName(CERTName *name); /* ** Convert a der-encoded integer to a hex printable string form. ** Perhaps this should be a SEC function but it's only used for certs. */ -extern char *CERT_Hexify (SECItem *i, int do_colon); +extern char *CERT_Hexify(SECItem *i, int do_colon); /* -** Converts DER string (with explicit length) into zString, if destination -** buffer is big enough to receive it. Does quoting and/or escaping as +** Converts DER string (with explicit length) into zString, if destination +** buffer is big enough to receive it. Does quoting and/or escaping as ** specified in RFC 1485. Input string must be single or multi-byte DER ** character set, (ASCII, UTF8, or ISO 8851-x) not a wide character set. ** Returns SECSuccess or SECFailure with error code set. If output buffer ** is too small, sets error code SEC_ERROR_OUTPUT_LEN. */ -extern SECStatus -CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen); +extern SECStatus CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, + int srclen); /****************************************************************************** * @@ -171,14 +171,14 @@ extern void CERT_DestroyValidity(CERTValidity *v); ** before memory is allocated (use CERT_DestroyValidity(v, PR_FALSE) to do ** that). */ -extern SECStatus CERT_CopyValidity - (PLArenaPool *arena, CERTValidity *dest, CERTValidity *src); +extern SECStatus CERT_CopyValidity(PLArenaPool *arena, CERTValidity *dest, + CERTValidity *src); /* ** The cert lib considers a cert or CRL valid if the "notBefore" time is -** in the not-too-distant future, e.g. within the next 24 hours. This +** in the not-too-distant future, e.g. within the next 24 hours. This ** prevents freshly issued certificates from being considered invalid -** because the local system's time zone is incorrectly set. +** because the local system's time zone is incorrectly set. ** The amount of "pending slop time" is adjustable by the application. ** Units of SlopTime are seconds. Default is 86400 (24 hours). ** Negative SlopTime values are not allowed. @@ -195,9 +195,10 @@ SECStatus CERT_SetSlopTime(PRInt32 slop); ** "validity" the validity period of the certificate ** "req" the certificate request that prompted the certificate issuance */ -extern CERTCertificate * -CERT_CreateCertificate (unsigned long serialNumber, CERTName *issuer, - CERTValidity *validity, CERTCertificateRequest *req); +extern CERTCertificate *CERT_CreateCertificate(unsigned long serialNumber, + CERTName *issuer, + CERTValidity *validity, + CERTCertificateRequest *req); /* ** Destroy a certificate object @@ -221,9 +222,8 @@ extern CERTCertificate *CERT_DupCertificate(CERTCertificate *c); ** "spki" describes/defines the public key the certificate is for ** "attributes" if non-zero, some optional attribute data */ -extern CERTCertificateRequest * -CERT_CreateCertificateRequest (CERTName *name, CERTSubjectPublicKeyInfo *spki, - SECItem **attributes); +extern CERTCertificateRequest *CERT_CreateCertificateRequest( + CERTName *name, CERTSubjectPublicKeyInfo *spki, SECItem **attributes); /* ** Destroy a certificate-request object @@ -235,22 +235,19 @@ extern void CERT_DestroyCertificateRequest(CERTCertificateRequest *r); /* ** Start adding extensions to a certificate request. */ -void * -CERT_StartCertificateRequestAttributes(CERTCertificateRequest *req); +void *CERT_StartCertificateRequestAttributes(CERTCertificateRequest *req); /* ** Reformat the certificate extension list into a CertificateRequest ** attribute list. */ -SECStatus -CERT_FinishCertificateRequestAttributes(CERTCertificateRequest *req); +SECStatus CERT_FinishCertificateRequestAttributes(CERTCertificateRequest *req); /* ** Extract the Extension Requests from a DER CertRequest attribute list. */ -SECStatus -CERT_GetCertificateRequestExtensions(CERTCertificateRequest *req, - CERTCertExtension ***exts); +SECStatus CERT_GetCertificateRequestExtensions(CERTCertificateRequest *req, + CERTCertExtension ***exts); /* ** Extract a public key object from a certificate @@ -261,7 +258,7 @@ extern SECKEYPublicKey *CERT_ExtractPublicKey(CERTCertificate *cert); ** Retrieve the Key Type associated with the cert we're dealing with */ -extern KeyType CERT_GetCertKeyType (const CERTSubjectPublicKeyInfo *spki); +extern KeyType CERT_GetCertKeyType(const CERTSubjectPublicKeyInfo *spki); /* ** Initialize the certificate database. This is called to create @@ -278,13 +275,12 @@ extern void CERT_SetDefaultCertDB(CERTCertDBHandle *handle); extern CERTCertDBHandle *CERT_GetDefaultCertDB(void); -extern CERTCertList *CERT_GetCertChainFromCert(CERTCertificate *cert, - PRTime time, - SECCertUsage usage); -extern CERTCertificate * -CERT_NewTempCertificate (CERTCertDBHandle *handle, SECItem *derCert, - char *nickname, PRBool isperm, PRBool copyDER); - +extern CERTCertList *CERT_GetCertChainFromCert(CERTCertificate *cert, + PRTime time, SECCertUsage usage); +extern CERTCertificate *CERT_NewTempCertificate(CERTCertDBHandle *handle, + SECItem *derCert, + char *nickname, PRBool isperm, + PRBool copyDER); /****************************************************************************** * @@ -300,8 +296,8 @@ CERT_NewTempCertificate (CERTCertDBHandle *handle, SECItem *derCert, ** DER_T61_STRING ** "value" is the null terminated string containing the value */ -extern CERTAVA *CERT_CreateAVA - (PLArenaPool *arena, SECOidTag kind, int valueType, char *value); +extern CERTAVA *CERT_CreateAVA(PLArenaPool *arena, SECOidTag kind, + int valueType, char *value); /* ** Extract the Distinguished Name from a DER encoded certificate @@ -315,18 +311,14 @@ extern SECStatus CERT_NameFromDERCert(SECItem *derCert, SECItem *derName); ** "derCert" is the DER encoded certificate ** "derName" is the SECItem that the name is returned in */ -extern SECStatus CERT_IssuerNameFromDERCert(SECItem *derCert, - SECItem *derName); - -extern SECItem * -CERT_EncodeGeneralName(CERTGeneralName *genName, SECItem *dest, - PLArenaPool *arena); - -extern CERTGeneralName * -CERT_DecodeGeneralName(PLArenaPool *reqArena, SECItem *encodedName, - CERTGeneralName *genName); +extern SECStatus CERT_IssuerNameFromDERCert(SECItem *derCert, SECItem *derName); +extern SECItem *CERT_EncodeGeneralName(CERTGeneralName *genName, SECItem *dest, + PLArenaPool *arena); +extern CERTGeneralName *CERT_DecodeGeneralName(PLArenaPool *reqArena, + SECItem *encodedName, + CERTGeneralName *genName); /* ** Generate a database search key for a certificate, based on the @@ -339,11 +331,10 @@ extern SECStatus CERT_KeyFromDERCert(PLArenaPool *reqArena, SECItem *derCert, SECItem *key); extern SECStatus CERT_KeyFromIssuerAndSN(PLArenaPool *arena, SECItem *issuer, - SECItem *sn, SECItem *key); - -extern SECStatus CERT_SerialNumberFromDERCert(SECItem *derCert, - SECItem *derName); + SECItem *sn, SECItem *key); +extern SECStatus CERT_SerialNumberFromDERCert(SECItem *derCert, + SECItem *derName); /* ** Generate a database search key for a crl, based on the @@ -352,17 +343,18 @@ extern SECStatus CERT_SerialNumberFromDERCert(SECItem *derCert, ** "derCrl" the DER encoded crl ** "key" the returned key */ -extern SECStatus CERT_KeyFromDERCrl(PLArenaPool *arena, SECItem *derCrl, SECItem *key); +extern SECStatus CERT_KeyFromDERCrl(PLArenaPool *arena, SECItem *derCrl, + SECItem *key); /* ** Open the certificate database. Use callback to get name of database. */ extern SECStatus CERT_OpenCertDB(CERTCertDBHandle *handle, PRBool readOnly, - CERTDBNameFunc namecb, void *cbarg); + CERTDBNameFunc namecb, void *cbarg); /* Open the certificate database. Use given filename for database. */ extern SECStatus CERT_OpenCertDBFilename(CERTCertDBHandle *handle, - char *certdbname, PRBool readOnly); + char *certdbname, PRBool readOnly); /* ** Open and initialize a cert database that is entirely in memory. This @@ -374,11 +366,11 @@ extern SECStatus CERT_OpenVolatileCertDB(CERTCertDBHandle *handle); ** Extract the list of host names, host name patters, IP address strings ** this cert is valid for. ** This function does NOT return nicknames. -** Type CERTCertNicknames is being used because it's a convenient +** Type CERTCertNicknames is being used because it's a convenient ** data structure to carry a list of strings and its count. */ -extern CERTCertNicknames * - CERT_GetValidDNSPatternsFromCert(CERTCertificate *cert); +extern CERTCertNicknames *CERT_GetValidDNSPatternsFromCert( + CERTCertificate *cert); /* ** Check the hostname to make sure that it matches the shexp that @@ -391,7 +383,8 @@ extern SECStatus CERT_VerifyCertName(const CERTCertificate *cert, ** Add a domain name to the list of names that the user has explicitly ** allowed (despite cert name mismatches) for use with a server cert. */ -extern SECStatus CERT_AddOKDomainName(CERTCertificate *cert, const char *hostname); +extern SECStatus CERT_AddOKDomainName(CERTCertificate *cert, + const char *hostname); /* ** Decode a DER encoded certificate into an CERTCertificate structure @@ -401,30 +394,31 @@ extern SECStatus CERT_AddOKDomainName(CERTCertificate *cert, const char *hostnam ** "nickname" is the nickname to use in the database. If it is NULL ** then a temporary nickname is generated. */ -extern CERTCertificate * -CERT_DecodeDERCertificate (SECItem *derSignedCert, PRBool copyDER, char *nickname); +extern CERTCertificate *CERT_DecodeDERCertificate(SECItem *derSignedCert, + PRBool copyDER, + char *nickname); /* ** Decode a DER encoded CRL into a CERTSignedCrl structure ** "derSignedCrl" is the DER encoded signed CRL. ** "type" must be SEC_CRL_TYPE. */ -#define SEC_CRL_TYPE 1 -#define SEC_KRL_TYPE 0 /* deprecated */ +#define SEC_CRL_TYPE 1 +#define SEC_KRL_TYPE 0 /* deprecated */ -extern CERTSignedCrl * -CERT_DecodeDERCrl (PLArenaPool *arena, SECItem *derSignedCrl,int type); +extern CERTSignedCrl *CERT_DecodeDERCrl(PLArenaPool *arena, + SECItem *derSignedCrl, int type); /* * same as CERT_DecodeDERCrl, plus allow options to be passed in */ -extern CERTSignedCrl * -CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl, - int type, PRInt32 options); +extern CERTSignedCrl *CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, + SECItem *derSignedCrl, + int type, PRInt32 options); /* CRL options to pass */ -#define CRL_DECODE_DEFAULT_OPTIONS 0x00000000 +#define CRL_DECODE_DEFAULT_OPTIONS 0x00000000 /* when CRL_DECODE_DONT_COPY_DER is set, the DER is not copied . The application must then keep derSignedCrl until it destroys the @@ -432,33 +426,32 @@ CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl, and pass that arena in as the first argument to CERT_DecodeDERCrlWithFlags */ -#define CRL_DECODE_DONT_COPY_DER 0x00000001 -#define CRL_DECODE_SKIP_ENTRIES 0x00000002 -#define CRL_DECODE_KEEP_BAD_CRL 0x00000004 -#define CRL_DECODE_ADOPT_HEAP_DER 0x00000008 +#define CRL_DECODE_DONT_COPY_DER 0x00000001 +#define CRL_DECODE_SKIP_ENTRIES 0x00000002 +#define CRL_DECODE_KEEP_BAD_CRL 0x00000004 +#define CRL_DECODE_ADOPT_HEAP_DER 0x00000008 /* complete the decoding of a partially decoded CRL, ie. decode the entries. Note that entries is an optional field in a CRL, so the "entries" pointer in CERTCrlStr may still be NULL even after function returns SECSuccess */ -extern SECStatus CERT_CompleteCRLDecodeEntries(CERTSignedCrl* crl); +extern SECStatus CERT_CompleteCRLDecodeEntries(CERTSignedCrl *crl); /* Validate CRL then import it to the dbase. If there is already a CRL with the - * same CA in the dbase, it will be replaced if derCRL is more up to date. - * If the process successes, a CRL will be returned. Otherwise, a NULL will - * be returned. The caller should call PORT_GetError() for the exactly error + * same CA in the dbase, it will be replaced if derCRL is more up to date. + * If the process successes, a CRL will be returned. Otherwise, a NULL will + * be returned. The caller should call PORT_GetError() for the exactly error * code. */ -extern CERTSignedCrl * -CERT_ImportCRL (CERTCertDBHandle *handle, SECItem *derCRL, char *url, - int type, void * wincx); +extern CERTSignedCrl *CERT_ImportCRL(CERTCertDBHandle *handle, SECItem *derCRL, + char *url, int type, void *wincx); -extern void CERT_DestroyCrl (CERTSignedCrl *crl); +extern void CERT_DestroyCrl(CERTSignedCrl *crl); /* this is a hint to flush the CRL cache. crlKey is the DER subject of the issuer (CA). */ -void CERT_CRLCacheRefreshIssuer(CERTCertDBHandle* dbhandle, SECItem* crlKey); +void CERT_CRLCacheRefreshIssuer(CERTCertDBHandle *dbhandle, SECItem *crlKey); /* add the specified DER CRL object to the CRL cache. Doing so will allow certificate verification functions (such as CERT_VerifyCertificate) @@ -468,114 +461,113 @@ void CERT_CRLCacheRefreshIssuer(CERTCertDBHandle* dbhandle, SECItem* crlKey); application can only free the object after it calls CERT_UncacheCRL to remove it from the CRL cache. */ -SECStatus CERT_CacheCRL(CERTCertDBHandle* dbhandle, SECItem* newcrl); +SECStatus CERT_CacheCRL(CERTCertDBHandle *dbhandle, SECItem *newcrl); /* remove a previously added CRL object from the CRL cache. It is OK for the application to free the memory after a successful removal */ -SECStatus CERT_UncacheCRL(CERTCertDBHandle* dbhandle, SECItem* oldcrl); +SECStatus CERT_UncacheCRL(CERTCertDBHandle *dbhandle, SECItem *oldcrl); /* ** Find a certificate in the database ** "key" is the database key to look for */ -extern CERTCertificate *CERT_FindCertByKey(CERTCertDBHandle *handle, SECItem *key); +extern CERTCertificate *CERT_FindCertByKey(CERTCertDBHandle *handle, + SECItem *key); /* ** Find a certificate in the database by name ** "name" is the distinguished name to look up */ -extern CERTCertificate * -CERT_FindCertByName (CERTCertDBHandle *handle, SECItem *name); +extern CERTCertificate *CERT_FindCertByName(CERTCertDBHandle *handle, + SECItem *name); /* ** Find a certificate in the database by name ** "name" is the distinguished name to look up (in ascii) */ -extern CERTCertificate * -CERT_FindCertByNameString (CERTCertDBHandle *handle, char *name); +extern CERTCertificate *CERT_FindCertByNameString(CERTCertDBHandle *handle, + char *name); /* ** Find a certificate in the database by name and keyid ** "name" is the distinguished name to look up ** "keyID" is the value of the subjectKeyID to match */ -extern CERTCertificate * -CERT_FindCertByKeyID (CERTCertDBHandle *handle, SECItem *name, SECItem *keyID); +extern CERTCertificate *CERT_FindCertByKeyID(CERTCertDBHandle *handle, + SECItem *name, SECItem *keyID); /* ** 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 CERTCertificate * -CERT_FindCertByIssuerAndSN (CERTCertDBHandle *handle, CERTIssuerAndSN *issuerAndSN); +extern CERTCertificate *CERT_FindCertByIssuerAndSN( + CERTCertDBHandle *handle, CERTIssuerAndSN *issuerAndSN); /* ** Find a certificate in the database by a subject key ID ** "subjKeyID" is the subject Key ID to look for */ -extern CERTCertificate * -CERT_FindCertBySubjectKeyID (CERTCertDBHandle *handle, SECItem *subjKeyID); +extern CERTCertificate *CERT_FindCertBySubjectKeyID(CERTCertDBHandle *handle, + SECItem *subjKeyID); /* ** Encode Certificate SKID (Subject Key ID) extension. ** */ -extern SECStatus -CERT_EncodeSubjectKeyID(PLArenaPool *arena, const SECItem* srcString, - SECItem *encodedValue); +extern SECStatus CERT_EncodeSubjectKeyID(PLArenaPool *arena, + const SECItem *srcString, + SECItem *encodedValue); /* ** Find a certificate in the database by a nickname ** "nickname" is the ascii string nickname to look for */ -extern CERTCertificate * -CERT_FindCertByNickname (CERTCertDBHandle *handle, const char *nickname); +extern CERTCertificate *CERT_FindCertByNickname(CERTCertDBHandle *handle, + const char *nickname); /* ** Find a certificate in the database by a DER encoded certificate ** "derCert" is the DER encoded certificate */ -extern CERTCertificate * -CERT_FindCertByDERCert(CERTCertDBHandle *handle, SECItem *derCert); +extern CERTCertificate *CERT_FindCertByDERCert(CERTCertDBHandle *handle, + SECItem *derCert); /* ** Find a certificate in the database by a email address ** "emailAddr" is the email address to look up */ -CERTCertificate * -CERT_FindCertByEmailAddr(CERTCertDBHandle *handle, char *emailAddr); +CERTCertificate *CERT_FindCertByEmailAddr(CERTCertDBHandle *handle, + char *emailAddr); /* ** Find a certificate in the database by a email address or nickname ** "name" is the email address or nickname to look up */ -CERTCertificate * -CERT_FindCertByNicknameOrEmailAddr(CERTCertDBHandle *handle, const char *name); +CERTCertificate *CERT_FindCertByNicknameOrEmailAddr(CERTCertDBHandle *handle, + const char *name); /* ** Find a certificate in the database by a email address or nickname ** and require it to have the given usage. ** "name" is the email address or nickname to look up */ -CERTCertificate * -CERT_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, - const char *name, - SECCertUsage lookingForUsage); +CERTCertificate *CERT_FindCertByNicknameOrEmailAddrForUsage( + CERTCertDBHandle *handle, const char *name, SECCertUsage lookingForUsage); /* ** Find a certificate in the database by a digest of a subject public key ** "spkDigest" is the digest to look up */ -extern CERTCertificate * -CERT_FindCertBySPKDigest(CERTCertDBHandle *handle, SECItem *spkDigest); +extern CERTCertificate *CERT_FindCertBySPKDigest(CERTCertDBHandle *handle, + SECItem *spkDigest); /* * Find the issuer of a cert */ -CERTCertificate * -CERT_FindCertIssuer(CERTCertificate *cert, PRTime validTime, SECCertUsage usage); +CERTCertificate *CERT_FindCertIssuer(CERTCertificate *cert, PRTime validTime, + SECCertUsage usage); /* ** Check the validity times of a certificate vs. time 't', allowing @@ -586,8 +578,8 @@ CERT_FindCertIssuer(CERTCertificate *cert, PRTime validTime, SECCertUsage usage) ** been overridden by the user. */ extern SECCertTimeValidity CERT_CheckCertValidTimes(const CERTCertificate *cert, - PRTime t, - PRBool allowOverride); + PRTime t, + PRBool allowOverride); /* ** WARNING - this function is deprecated, and will either go away or have @@ -605,15 +597,14 @@ extern SECStatus CERT_CertTimesValid(CERTCertificate *cert); ** "notBefore" is the start of the validity period ** "notAfter" is the end of the validity period */ -extern SECStatus -CERT_GetCertTimes (const CERTCertificate *c, PRTime *notBefore, - PRTime *notAfter); +extern SECStatus CERT_GetCertTimes(const CERTCertificate *c, PRTime *notBefore, + PRTime *notAfter); /* ** Extract the issuer and serial number from a certificate */ -extern CERTIssuerAndSN *CERT_GetCertIssuerAndSN(PLArenaPool *, - CERTCertificate *); +extern CERTIssuerAndSN *CERT_GetCertIssuerAndSN(PLArenaPool *, + CERTCertificate *); /* ** verify the signature of a signed data object with a given certificate @@ -621,23 +612,20 @@ extern CERTIssuerAndSN *CERT_GetCertIssuerAndSN(PLArenaPool *, ** "cert" the certificate to use to check the signature */ extern SECStatus CERT_VerifySignedData(CERTSignedData *sd, - CERTCertificate *cert, - PRTime t, - void *wincx); + CERTCertificate *cert, PRTime t, + void *wincx); /* ** verify the signature of a signed data object with the given DER publickey */ -extern SECStatus -CERT_VerifySignedDataWithPublicKeyInfo(CERTSignedData *sd, - CERTSubjectPublicKeyInfo *pubKeyInfo, - void *wincx); +extern SECStatus CERT_VerifySignedDataWithPublicKeyInfo( + CERTSignedData *sd, CERTSubjectPublicKeyInfo *pubKeyInfo, void *wincx); /* ** verify the signature of a signed data object with a SECKEYPublicKey. */ -extern SECStatus -CERT_VerifySignedDataWithPublicKey(const CERTSignedData *sd, - SECKEYPublicKey *pubKey, void *wincx); +extern SECStatus CERT_VerifySignedDataWithPublicKey(const CERTSignedData *sd, + SECKEYPublicKey *pubKey, + void *wincx); /* ** NEW FUNCTIONS with new bit-field-FIELD SECCertificateUsage - please use @@ -647,27 +635,31 @@ CERT_VerifySignedDataWithPublicKey(const CERTSignedData *sd, ** "cert" the certificate to verify ** "checkSig" only check signatures if true */ -extern SECStatus -CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertificateUsage requiredUsages, - PRTime t, void *wincx, CERTVerifyLog *log, - SECCertificateUsage* returnedUsages); +extern SECStatus CERT_VerifyCertificate(CERTCertDBHandle *handle, + CERTCertificate *cert, PRBool checkSig, + SECCertificateUsage requiredUsages, + PRTime t, void *wincx, + CERTVerifyLog *log, + SECCertificateUsage *returnedUsages); /* same as above, but uses current time */ -extern SECStatus -CERT_VerifyCertificateNow(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertificateUsage requiredUsages, - void *wincx, SECCertificateUsage* returnedUsages); +extern SECStatus CERT_VerifyCertificateNow(CERTCertDBHandle *handle, + CERTCertificate *cert, + PRBool checkSig, + SECCertificateUsage requiredUsages, + void *wincx, + SECCertificateUsage *returnedUsages); /* ** Verify that a CA cert can certify some (unspecified) leaf cert for a given ** purpose. This is used by UI code to help identify where a chain may be ** broken and why. This takes identical parameters to CERT_VerifyCert */ -extern SECStatus -CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, PRTime t, - void *wincx, CERTVerifyLog *log); +extern SECStatus CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, + CERTCertificate *cert, + PRBool checkSig, + SECCertUsage certUsage, PRTime t, + void *wincx, CERTVerifyLog *log); /* ** OLD OBSOLETE FUNCTIONS with enum SECCertUsage - DO NOT USE FOR NEW CODE @@ -677,20 +669,19 @@ CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, CERTCertificate *cert, ** "cert" the certificate to verify ** "checkSig" only check signatures if true */ -extern SECStatus -CERT_VerifyCert(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, PRTime t, - void *wincx, CERTVerifyLog *log); +extern SECStatus CERT_VerifyCert(CERTCertDBHandle *handle, + CERTCertificate *cert, PRBool checkSig, + SECCertUsage certUsage, PRTime t, void *wincx, + CERTVerifyLog *log); /* same as above, but uses current time */ -extern SECStatus -CERT_VerifyCertNow(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, void *wincx); +extern SECStatus CERT_VerifyCertNow(CERTCertDBHandle *handle, + CERTCertificate *cert, PRBool checkSig, + SECCertUsage certUsage, void *wincx); -SECStatus -CERT_VerifyCertChain(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, PRTime t, - void *wincx, CERTVerifyLog *log); +SECStatus CERT_VerifyCertChain(CERTCertDBHandle *handle, CERTCertificate *cert, + PRBool checkSig, SECCertUsage certUsage, + PRTime t, void *wincx, CERTVerifyLog *log); /* ** Read a base64 ascii encoded DER certificate and convert it to our @@ -709,39 +700,37 @@ extern CERTCertificate *CERT_ConvertAndDecodeCertificate(char *certstr); */ extern CERTCertificate *CERT_DecodeCertFromPackage(char *certbuf, int certlen); -extern SECStatus -CERT_ImportCAChain (SECItem *certs, int numcerts, SECCertUsage certUsage); +extern SECStatus CERT_ImportCAChain(SECItem *certs, int numcerts, + SECCertUsage certUsage); -extern SECStatus -CERT_ImportCAChainTrusted(SECItem *certs, int numcerts, SECCertUsage certUsage); +extern SECStatus CERT_ImportCAChainTrusted(SECItem *certs, int numcerts, + SECCertUsage certUsage); /* -** Read a certificate chain in some foreign format, and pass it to a +** Read a certificate chain in some foreign format, and pass it to a ** callback function. ** "certbuf" is the buffer containing the certificate ** "certlen" is the length of the buffer ** "f" is the callback function ** "arg" is the callback argument */ -typedef SECStatus (PR_CALLBACK *CERTImportCertificateFunc) - (void *arg, SECItem **certs, int numcerts); +typedef SECStatus(PR_CALLBACK *CERTImportCertificateFunc)(void *arg, + SECItem **certs, + int numcerts); -extern SECStatus -CERT_DecodeCertPackage(char *certbuf, int certlen, CERTImportCertificateFunc f, - void *arg); +extern SECStatus CERT_DecodeCertPackage(char *certbuf, int certlen, + CERTImportCertificateFunc f, void *arg); -/* -** Returns the value of an AVA. This was a formerly static +/* +** Returns the value of an AVA. This was a formerly static ** function that has been exposed due to the need to decode -** and convert unicode strings to UTF8. +** and convert unicode strings to UTF8. ** ** XXX This function resides in certhtml.c, should it be ** moved elsewhere? */ extern SECItem *CERT_DecodeAVAValue(const SECItem *derAVAValue); - - /* ** extract various element strings from a distinguished name. ** "name" the distinguished name @@ -751,10 +740,10 @@ extern char *CERT_GetCertificateEmailAddress(CERTCertificate *cert); extern char *CERT_GetCertEmailAddress(const CERTName *name); -extern const char * CERT_GetFirstEmailAddress(CERTCertificate * cert); +extern const char *CERT_GetFirstEmailAddress(CERTCertificate *cert); -extern const char * CERT_GetNextEmailAddress(CERTCertificate * cert, - const char * prev); +extern const char *CERT_GetNextEmailAddress(CERTCertificate *cert, + const char *prev); /* The return value must be freed with PORT_Free. */ extern char *CERT_GetCommonName(const CERTName *name); @@ -778,13 +767,13 @@ extern char *CERT_GetCertUid(const CERTName *name); extern SECStatus CERT_GetCertTrust(const CERTCertificate *cert, CERTCertTrust *trust); -extern SECStatus -CERT_ChangeCertTrust (CERTCertDBHandle *handle, CERTCertificate *cert, - CERTCertTrust *trust); +extern SECStatus CERT_ChangeCertTrust(CERTCertDBHandle *handle, + CERTCertificate *cert, + CERTCertTrust *trust); -extern SECStatus -CERT_ChangeCertTrustByUsage(CERTCertDBHandle *certdb, CERTCertificate *cert, - SECCertUsage usage); +extern SECStatus CERT_ChangeCertTrustByUsage(CERTCertDBHandle *certdb, + CERTCertificate *cert, + SECCertUsage usage); /************************************************************************* * @@ -808,23 +797,24 @@ extern void *CERT_StartCertExtensions(CERTCertificate *cert); ** "copyData" is a flag indicating whether the value data should be ** copied. */ -extern SECStatus CERT_AddExtension (void *exthandle, int idtag, - SECItem *value, PRBool critical, PRBool copyData); +extern SECStatus CERT_AddExtension(void *exthandle, int idtag, SECItem *value, + PRBool critical, PRBool copyData); -extern SECStatus CERT_AddExtensionByOID (void *exthandle, SECItem *oid, - SECItem *value, PRBool critical, PRBool copyData); +extern SECStatus CERT_AddExtensionByOID(void *exthandle, SECItem *oid, + SECItem *value, PRBool critical, + PRBool copyData); -extern SECStatus CERT_EncodeAndAddExtension - (void *exthandle, int idtag, void *value, PRBool critical, - const SEC_ASN1Template *atemplate); +extern SECStatus CERT_EncodeAndAddExtension(void *exthandle, int idtag, + void *value, PRBool critical, + const SEC_ASN1Template *atemplate); -extern SECStatus CERT_EncodeAndAddBitStrExtension - (void *exthandle, int idtag, SECItem *value, PRBool critical); - - -extern SECStatus -CERT_EncodeAltNameExtension(PLArenaPool *arena, CERTGeneralName *value, SECItem *encodedValue); +extern SECStatus CERT_EncodeAndAddBitStrExtension(void *exthandle, int idtag, + SECItem *value, + PRBool critical); +extern SECStatus CERT_EncodeAltNameExtension(PLArenaPool *arena, + CERTGeneralName *value, + SECItem *encodedValue); /* ** Finish adding cert extensions. Does final processing on extension @@ -839,17 +829,15 @@ extern SECStatus CERT_FinishExtensions(void *exthandle); ** only when its OID matches none of the cert's existing extensions. Call this ** immediately before calling CERT_FinishExtensions(). */ -SECStatus -CERT_MergeExtensions(void *exthandle, CERTCertExtension **exts); +SECStatus CERT_MergeExtensions(void *exthandle, CERTCertExtension **exts); /* If the extension is found, return its criticality and value. ** This allocate storage for the returning extension value. */ -extern SECStatus CERT_GetExtenCriticality - (CERTCertExtension **extensions, int tag, PRBool *isCritical); +extern SECStatus CERT_GetExtenCriticality(CERTCertExtension **extensions, + int tag, PRBool *isCritical); -extern void -CERT_DestroyOidSequence(CERTOidSequence *oidSeq); +extern void CERT_DestroyOidSequence(CERTOidSequence *oidSeq); /**************************************************************************** * @@ -862,28 +850,29 @@ CERT_DestroyOidSequence(CERTOidSequence *oidSeq); ** value - extension value to encode ** encodedValue - output encoded value */ -extern SECStatus CERT_EncodeBasicConstraintValue - (PLArenaPool *arena, CERTBasicConstraints *value, SECItem *encodedValue); +extern SECStatus CERT_EncodeBasicConstraintValue(PLArenaPool *arena, + CERTBasicConstraints *value, + SECItem *encodedValue); /* ** Encode the value of the authorityKeyIdentifier extension. */ -extern SECStatus CERT_EncodeAuthKeyID - (PLArenaPool *arena, CERTAuthKeyID *value, SECItem *encodedValue); +extern SECStatus CERT_EncodeAuthKeyID(PLArenaPool *arena, CERTAuthKeyID *value, + SECItem *encodedValue); /* ** Encode the value of the crlDistributionPoints extension. */ -extern SECStatus CERT_EncodeCRLDistributionPoints - (PLArenaPool *arena, CERTCrlDistributionPoints *value,SECItem *derValue); +extern SECStatus CERT_EncodeCRLDistributionPoints( + PLArenaPool *arena, CERTCrlDistributionPoints *value, SECItem *derValue); /* ** Decodes a DER encoded basicConstaint extension value into a readable format ** value - decoded value ** encodedValue - value to decoded */ -extern SECStatus CERT_DecodeBasicConstraintValue - (CERTBasicConstraints *value, const SECItem *encodedValue); +extern SECStatus CERT_DecodeBasicConstraintValue(CERTBasicConstraints *value, + const SECItem *encodedValue); /* Decodes a DER encoded authorityKeyIdentifier extension value into a ** readable format. @@ -891,87 +880,84 @@ extern SECStatus CERT_DecodeBasicConstraintValue ** encodedValue - value to be decoded ** Returns a CERTAuthKeyID structure which contains the decoded value */ -extern CERTAuthKeyID *CERT_DecodeAuthKeyID - (PLArenaPool *arena, const SECItem *encodedValue); +extern CERTAuthKeyID *CERT_DecodeAuthKeyID(PLArenaPool *arena, + const SECItem *encodedValue); -/* Decodes a DER encoded crlDistributionPoints extension value into a +/* Decodes a DER encoded crlDistributionPoints extension value into a ** readable format. ** arena - where to allocate memory for the decoded value ** der - value to be decoded -** Returns a CERTCrlDistributionPoints structure which contains the +** Returns a CERTCrlDistributionPoints structure which contains the ** decoded value */ -extern CERTCrlDistributionPoints * CERT_DecodeCRLDistributionPoints - (PLArenaPool *arena, SECItem *der); +extern CERTCrlDistributionPoints *CERT_DecodeCRLDistributionPoints( + PLArenaPool *arena, SECItem *der); /* Extract certain name type from a generalName */ -extern void *CERT_GetGeneralNameByType - (CERTGeneralName *genNames, CERTGeneralNameType type, PRBool derFormat); - - -extern CERTOidSequence * -CERT_DecodeOidSequence(const SECItem *seqItem); - - +extern void *CERT_GetGeneralNameByType(CERTGeneralName *genNames, + CERTGeneralNameType type, + PRBool derFormat); +extern CERTOidSequence *CERT_DecodeOidSequence(const SECItem *seqItem); /**************************************************************************** * - * Find extension values of a certificate + * Find extension values of a certificate * ***************************************************************************/ -extern SECStatus CERT_FindCertExtension - (const CERTCertificate *cert, int tag, SECItem *value); +extern SECStatus CERT_FindCertExtension(const CERTCertificate *cert, int tag, + SECItem *value); -extern SECStatus CERT_FindNSCertTypeExtension - (CERTCertificate *cert, SECItem *value); +extern SECStatus CERT_FindNSCertTypeExtension(CERTCertificate *cert, + SECItem *value); -extern char * CERT_FindNSStringExtension (CERTCertificate *cert, int oidtag); +extern char *CERT_FindNSStringExtension(CERTCertificate *cert, int oidtag); -extern SECStatus CERT_FindCertExtensionByOID - (CERTCertificate *cert, SECItem *oid, SECItem *value); +extern SECStatus CERT_FindCertExtensionByOID(CERTCertificate *cert, + SECItem *oid, SECItem *value); /* Returns the decoded value of the authKeyID extension. ** Note that this uses passed in the arena to allocate storage for the result */ -extern CERTAuthKeyID * CERT_FindAuthKeyIDExten (PLArenaPool *arena,CERTCertificate *cert); +extern CERTAuthKeyID *CERT_FindAuthKeyIDExten(PLArenaPool *arena, + CERTCertificate *cert); /* Returns the decoded value of the basicConstraint extension. */ -extern SECStatus CERT_FindBasicConstraintExten - (CERTCertificate *cert, CERTBasicConstraints *value); +extern SECStatus CERT_FindBasicConstraintExten(CERTCertificate *cert, + CERTBasicConstraints *value); /* Returns the decoded value of the crlDistributionPoints extension. ** Note that the arena in cert is used to allocate storage for the result */ -extern CERTCrlDistributionPoints * CERT_FindCRLDistributionPoints - (CERTCertificate *cert); +extern CERTCrlDistributionPoints *CERT_FindCRLDistributionPoints( + CERTCertificate *cert); -/* Returns value of the keyUsage extension. This uses PR_Alloc to allocate -** buffer for the decoded value. The caller should free up the storage +/* Returns value of the keyUsage extension. This uses PR_Alloc to allocate +** buffer for the decoded value. The caller should free up the storage ** allocated in value->data. */ -extern SECStatus CERT_FindKeyUsageExtension (CERTCertificate *cert, - SECItem *value); +extern SECStatus CERT_FindKeyUsageExtension(CERTCertificate *cert, + SECItem *value); -/* Return the decoded value of the subjectKeyID extension. The caller should +/* Return the decoded value of the subjectKeyID extension. The caller should ** free up the storage allocated in retItem->data. */ -extern SECStatus CERT_FindSubjectKeyIDExtension (CERTCertificate *cert, - SECItem *retItem); +extern SECStatus CERT_FindSubjectKeyIDExtension(CERTCertificate *cert, + SECItem *retItem); /* ** If cert is a v3 certificate, and a critical keyUsage extension is included, -** then check the usage against the extension value. If a non-critical -** keyUsage extension is included, this will return SECSuccess without -** checking, since the extension is an advisory field, not a restriction. +** then check the usage against the extension value. If a non-critical +** keyUsage extension is included, this will return SECSuccess without +** checking, since the extension is an advisory field, not a restriction. ** If cert is not a v3 certificate, this will return SECSuccess. ** cert - certificate ** usage - one of the x.509 v3 the Key Usage Extension flags */ -extern SECStatus CERT_CheckCertUsage (CERTCertificate *cert, - unsigned char usage); +extern SECStatus CERT_CheckCertUsage(CERTCertificate *cert, + unsigned char usage); /**************************************************************************** * @@ -979,14 +965,12 @@ extern SECStatus CERT_CheckCertUsage (CERTCertificate *cert, * ****************************************************************************/ -extern SECStatus CERT_FindCRLExtensionByOID - (CERTCrl *crl, SECItem *oid, SECItem *value); +extern SECStatus CERT_FindCRLExtensionByOID(CERTCrl *crl, SECItem *oid, + SECItem *value); -extern SECStatus CERT_FindCRLExtension - (CERTCrl *crl, int tag, SECItem *value); +extern SECStatus CERT_FindCRLExtension(CERTCrl *crl, int tag, SECItem *value); -extern SECStatus - CERT_FindInvalidDateExten (CERTCrl *crl, PRTime *value); +extern SECStatus CERT_FindInvalidDateExten(CERTCrl *crl, PRTime *value); /* ** Set up a crl for adding X509v3 extensions. Returns an opaque handle @@ -1003,17 +987,17 @@ extern void *CERT_StartCRLExtensions(CERTCrl *crl); */ extern void *CERT_StartCRLEntryExtensions(CERTCrl *crl, CERTCrlEntry *entry); -extern CERTCertNicknames *CERT_GetCertNicknames (CERTCertDBHandle *handle, - int what, void *wincx); +extern CERTCertNicknames *CERT_GetCertNicknames(CERTCertDBHandle *handle, + int what, void *wincx); /* ** Finds the crlNumber extension and decodes its value into 'value' */ -extern SECStatus CERT_FindCRLNumberExten (PLArenaPool *arena, CERTCrl *crl, - SECItem *value); +extern SECStatus CERT_FindCRLNumberExten(PLArenaPool *arena, CERTCrl *crl, + SECItem *value); -extern SECStatus CERT_FindCRLEntryReasonExten (CERTCrlEntry *crlEntry, - CERTCRLEntryReasonCode *value); +extern SECStatus CERT_FindCRLEntryReasonExten(CERTCrlEntry *crlEntry, + CERTCRLEntryReasonCode *value); extern void CERT_FreeNicknames(CERTCertNicknames *nicknames); @@ -1021,7 +1005,7 @@ extern PRBool CERT_CompareCerts(const CERTCertificate *c1, const CERTCertificate *c2); extern PRBool CERT_CompareCertsForRedirection(CERTCertificate *c1, - CERTCertificate *c2); + CERTCertificate *c2); /* ** Generate an array of the Distinguished Names that the given cert database @@ -1037,8 +1021,8 @@ extern CERTDistNames *CERT_DupDistNames(CERTDistNames *orig); /* ** Generate an array of Distinguished names from an array of nicknames */ -extern CERTDistNames *CERT_DistNamesFromNicknames - (CERTCertDBHandle *handle, char **nicknames, int nnames); +extern CERTDistNames *CERT_DistNamesFromNicknames(CERTCertDBHandle *handle, + char **nicknames, int nnames); /* ** Generate an array of Distinguished names from a list of certs. @@ -1048,15 +1032,14 @@ extern CERTDistNames *CERT_DistNamesFromCertList(CERTCertList *list); /* ** Generate a certificate chain from a certificate. */ -extern CERTCertificateList * -CERT_CertChainFromCert(CERTCertificate *cert, SECCertUsage usage, - PRBool includeRoot); +extern CERTCertificateList *CERT_CertChainFromCert(CERTCertificate *cert, + SECCertUsage usage, + PRBool includeRoot); -extern CERTCertificateList * -CERT_CertListFromCert(CERTCertificate *cert); +extern CERTCertificateList *CERT_CertListFromCert(CERTCertificate *cert); -extern CERTCertificateList * -CERT_DupCertList(const CERTCertificateList * oldList); +extern CERTCertificateList *CERT_DupCertList( + const CERTCertificateList *oldList); extern void CERT_DestroyCertificateList(CERTCertificateList *list); @@ -1064,262 +1047,215 @@ extern void CERT_DestroyCertificateList(CERTCertificateList *list); ** is cert a user cert? i.e. does it have CERTDB_USER trust, ** i.e. a private key? */ -PRBool CERT_IsUserCert(CERTCertificate* cert); +PRBool CERT_IsUserCert(CERTCertificate *cert); /* is cert a newer than cert b? */ PRBool CERT_IsNewer(CERTCertificate *certa, CERTCertificate *certb); /* currently a stub for address book */ -PRBool -CERT_IsCertRevoked(CERTCertificate *cert); +PRBool CERT_IsCertRevoked(CERTCertificate *cert); -void -CERT_DestroyCertArray(CERTCertificate **certs, unsigned int ncerts); +void CERT_DestroyCertArray(CERTCertificate **certs, unsigned int ncerts); /* convert an email address to lower case */ char *CERT_FixupEmailAddr(const char *emailAddr); /* decode string representation of trust flags into trust struct */ -SECStatus -CERT_DecodeTrustString(CERTCertTrust *trust, const char *trusts); +SECStatus CERT_DecodeTrustString(CERTCertTrust *trust, const char *trusts); /* encode trust struct into string representation of trust flags */ -char * -CERT_EncodeTrustString(CERTCertTrust *trust); +char *CERT_EncodeTrustString(CERTCertTrust *trust); /* find the next or prev cert in a subject list */ -CERTCertificate * -CERT_PrevSubjectCert(CERTCertificate *cert); -CERTCertificate * -CERT_NextSubjectCert(CERTCertificate *cert); +CERTCertificate *CERT_PrevSubjectCert(CERTCertificate *cert); +CERTCertificate *CERT_NextSubjectCert(CERTCertificate *cert); /* * import a collection of certs into the temporary or permanent cert * database */ -SECStatus -CERT_ImportCerts(CERTCertDBHandle *certdb, SECCertUsage usage, - unsigned int ncerts, SECItem **derCerts, - CERTCertificate ***retCerts, PRBool keepCerts, - PRBool caOnly, char *nickname); +SECStatus CERT_ImportCerts(CERTCertDBHandle *certdb, SECCertUsage usage, + unsigned int ncerts, SECItem **derCerts, + CERTCertificate ***retCerts, PRBool keepCerts, + PRBool caOnly, char *nickname); -char * -CERT_MakeCANickname(CERTCertificate *cert); +char *CERT_MakeCANickname(CERTCertificate *cert); -PRBool -CERT_IsCACert(CERTCertificate *cert, unsigned int *rettype); +PRBool CERT_IsCACert(CERTCertificate *cert, unsigned int *rettype); -PRBool -CERT_IsCADERCert(SECItem *derCert, unsigned int *rettype); +PRBool CERT_IsCADERCert(SECItem *derCert, unsigned int *rettype); -PRBool -CERT_IsRootDERCert(SECItem *derCert); +PRBool CERT_IsRootDERCert(SECItem *derCert); -SECStatus -CERT_SaveSMimeProfile(CERTCertificate *cert, SECItem *emailProfile, - SECItem *profileTime); +SECStatus CERT_SaveSMimeProfile(CERTCertificate *cert, SECItem *emailProfile, + SECItem *profileTime); /* * find the smime symmetric capabilities profile for a given cert */ -SECItem * -CERT_FindSMimeProfile(CERTCertificate *cert); +SECItem *CERT_FindSMimeProfile(CERTCertificate *cert); -SECStatus -CERT_AddNewCerts(CERTCertDBHandle *handle); +SECStatus CERT_AddNewCerts(CERTCertDBHandle *handle); -CERTCertificatePolicies * -CERT_DecodeCertificatePoliciesExtension(const SECItem *extnValue); +CERTCertificatePolicies *CERT_DecodeCertificatePoliciesExtension( + const SECItem *extnValue); -void -CERT_DestroyCertificatePoliciesExtension(CERTCertificatePolicies *policies); +void CERT_DestroyCertificatePoliciesExtension( + CERTCertificatePolicies *policies); -CERTCertificatePolicyMappings * -CERT_DecodePolicyMappingsExtension(SECItem *encodedCertPolicyMaps); +CERTCertificatePolicyMappings *CERT_DecodePolicyMappingsExtension( + SECItem *encodedCertPolicyMaps); -SECStatus -CERT_DestroyPolicyMappingsExtension(CERTCertificatePolicyMappings *mappings); +SECStatus CERT_DestroyPolicyMappingsExtension( + CERTCertificatePolicyMappings *mappings); -SECStatus -CERT_DecodePolicyConstraintsExtension( +SECStatus CERT_DecodePolicyConstraintsExtension( CERTCertificatePolicyConstraints *decodedValue, const SECItem *encodedValue); -SECStatus CERT_DecodeInhibitAnyExtension - (CERTCertificateInhibitAny *decodedValue, SECItem *extnValue); +SECStatus CERT_DecodeInhibitAnyExtension( + CERTCertificateInhibitAny *decodedValue, SECItem *extnValue); -CERTUserNotice * -CERT_DecodeUserNotice(SECItem *noticeItem); +CERTUserNotice *CERT_DecodeUserNotice(SECItem *noticeItem); -extern CERTGeneralName * -CERT_DecodeAltNameExtension(PLArenaPool *reqArena, SECItem *EncodedAltName); +extern CERTGeneralName *CERT_DecodeAltNameExtension(PLArenaPool *reqArena, + SECItem *EncodedAltName); -extern CERTNameConstraints * -CERT_DecodeNameConstraintsExtension(PLArenaPool *arena, - const SECItem *encodedConstraints); +extern CERTNameConstraints *CERT_DecodeNameConstraintsExtension( + PLArenaPool *arena, const SECItem *encodedConstraints); /* returns addr of a NULL termainated array of pointers to CERTAuthInfoAccess */ -extern CERTAuthInfoAccess ** -CERT_DecodeAuthInfoAccessExtension(PLArenaPool *reqArena, - const SECItem *encodedExtension); +extern CERTAuthInfoAccess **CERT_DecodeAuthInfoAccessExtension( + PLArenaPool *reqArena, const SECItem *encodedExtension); -extern CERTPrivKeyUsagePeriod * -CERT_DecodePrivKeyUsagePeriodExtension(PLArenaPool *arena, SECItem *extnValue); +extern CERTPrivKeyUsagePeriod *CERT_DecodePrivKeyUsagePeriodExtension( + PLArenaPool *arena, SECItem *extnValue); -extern CERTGeneralName * -CERT_GetNextGeneralName(CERTGeneralName *current); +extern CERTGeneralName *CERT_GetNextGeneralName(CERTGeneralName *current); -extern CERTGeneralName * -CERT_GetPrevGeneralName(CERTGeneralName *current); +extern CERTGeneralName *CERT_GetPrevGeneralName(CERTGeneralName *current); /* * Look up name constraints for some certs that do not include name constraints * (Most importantly, root certificates) * - * If a matching subject is found, |extensions| will be populated with a copy of the - * DER-encoded name constraints extension. The data in |extensions| will point to + * If a matching subject is found, |extensions| will be populated with a copy of + * the + * DER-encoded name constraints extension. The data in |extensions| will point + * to * memory that the caller owns. * * There is no mechanism to configure imposed name constraints right now. All * imposed name constraints are built into NSS. */ -SECStatus -CERT_GetImposedNameConstraints(const SECItem *derSubject, SECItem *extensions); +SECStatus CERT_GetImposedNameConstraints(const SECItem *derSubject, + SECItem *extensions); -CERTNameConstraint * -CERT_GetNextNameConstraint(CERTNameConstraint *current); +CERTNameConstraint *CERT_GetNextNameConstraint(CERTNameConstraint *current); -CERTNameConstraint * -CERT_GetPrevNameConstraint(CERTNameConstraint *current); +CERTNameConstraint *CERT_GetPrevNameConstraint(CERTNameConstraint *current); -void -CERT_DestroyUserNotice(CERTUserNotice *userNotice); +void CERT_DestroyUserNotice(CERTUserNotice *userNotice); -typedef char * (* CERTPolicyStringCallback)(char *org, - unsigned long noticeNumber, - void *arg); -void -CERT_SetCAPolicyStringCallback(CERTPolicyStringCallback cb, void *cbarg); +typedef char *(*CERTPolicyStringCallback)(char *org, unsigned long noticeNumber, + void *arg); +void CERT_SetCAPolicyStringCallback(CERTPolicyStringCallback cb, void *cbarg); -char * -CERT_GetCertCommentString(CERTCertificate *cert); +char *CERT_GetCertCommentString(CERTCertificate *cert); -PRBool -CERT_GovtApprovedBitSet(CERTCertificate *cert); +PRBool CERT_GovtApprovedBitSet(CERTCertificate *cert); -SECStatus -CERT_AddPermNickname(CERTCertificate *cert, char *nickname); +SECStatus CERT_AddPermNickname(CERTCertificate *cert, char *nickname); -CERTCertList * -CERT_MatchUserCert(CERTCertDBHandle *handle, - SECCertUsage usage, - int nCANames, char **caNames, - void *proto_win); +CERTCertList *CERT_MatchUserCert(CERTCertDBHandle *handle, SECCertUsage usage, + int nCANames, char **caNames, void *proto_win); -CERTCertList * -CERT_NewCertList(void); +CERTCertList *CERT_NewCertList(void); /* free the cert list and all the certs in the list */ -void -CERT_DestroyCertList(CERTCertList *certs); +void CERT_DestroyCertList(CERTCertList *certs); /* remove the node and free the cert */ -void -CERT_RemoveCertListNode(CERTCertListNode *node); +void CERT_RemoveCertListNode(CERTCertListNode *node); /* equivalent to CERT_AddCertToListTailWithData(certs, cert, NULL) */ -SECStatus -CERT_AddCertToListTail(CERTCertList *certs, CERTCertificate *cert); +SECStatus CERT_AddCertToListTail(CERTCertList *certs, CERTCertificate *cert); /* equivalent to CERT_AddCertToListHeadWithData(certs, cert, NULL) */ -SECStatus -CERT_AddCertToListHead(CERTCertList *certs, CERTCertificate *cert); +SECStatus CERT_AddCertToListHead(CERTCertList *certs, CERTCertificate *cert); /* * The new cert list node takes ownership of "cert". "cert" is freed * when the list node is removed. */ -SECStatus -CERT_AddCertToListTailWithData(CERTCertList *certs, CERTCertificate *cert, - void *appData); +SECStatus CERT_AddCertToListTailWithData(CERTCertList *certs, + CERTCertificate *cert, void *appData); /* * The new cert list node takes ownership of "cert". "cert" is freed * when the list node is removed. */ -SECStatus -CERT_AddCertToListHeadWithData(CERTCertList *certs, CERTCertificate *cert, - void *appData); +SECStatus CERT_AddCertToListHeadWithData(CERTCertList *certs, + CERTCertificate *cert, void *appData); -typedef PRBool (* CERTSortCallback)(CERTCertificate *certa, - CERTCertificate *certb, - void *arg); -SECStatus -CERT_AddCertToListSorted(CERTCertList *certs, CERTCertificate *cert, - CERTSortCallback f, void *arg); +typedef PRBool (*CERTSortCallback)(CERTCertificate *certa, + CERTCertificate *certb, void *arg); +SECStatus CERT_AddCertToListSorted(CERTCertList *certs, CERTCertificate *cert, + CERTSortCallback f, void *arg); /* callback for CERT_AddCertToListSorted that sorts based on validity * period and a given time. */ -PRBool -CERT_SortCBValidity(CERTCertificate *certa, - CERTCertificate *certb, - void *arg); +PRBool CERT_SortCBValidity(CERTCertificate *certa, CERTCertificate *certb, + void *arg); -SECStatus -CERT_CheckForEvilCert(CERTCertificate *cert); +SECStatus CERT_CheckForEvilCert(CERTCertificate *cert); -CERTGeneralName * -CERT_GetCertificateNames(CERTCertificate *cert, PLArenaPool *arena); +CERTGeneralName *CERT_GetCertificateNames(CERTCertificate *cert, + PLArenaPool *arena); -CERTGeneralName * -CERT_GetConstrainedCertificateNames(const CERTCertificate *cert, - PLArenaPool *arena, - PRBool includeSubjectCommonName); +CERTGeneralName *CERT_GetConstrainedCertificateNames( + const CERTCertificate *cert, PLArenaPool *arena, + PRBool includeSubjectCommonName); /* * Creates or adds to a list of all certs with a give subject name, sorted by * validity time, newest first. Invalid certs are considered older than * valid certs. If validOnly is set, do not include invalid certs on list. */ -CERTCertList * -CERT_CreateSubjectCertList(CERTCertList *certList, CERTCertDBHandle *handle, - const SECItem *name, PRTime sorttime, - PRBool validOnly); +CERTCertList *CERT_CreateSubjectCertList(CERTCertList *certList, + CERTCertDBHandle *handle, + const SECItem *name, PRTime sorttime, + PRBool validOnly); /* * remove certs from a list that don't have keyUsage and certType * that match the given usage. */ -SECStatus -CERT_FilterCertListByUsage(CERTCertList *certList, SECCertUsage usage, - PRBool ca); +SECStatus CERT_FilterCertListByUsage(CERTCertList *certList, SECCertUsage usage, + PRBool ca); /* * check the key usage of a cert against a set of required values */ -SECStatus -CERT_CheckKeyUsage(CERTCertificate *cert, unsigned int requiredUsage); +SECStatus CERT_CheckKeyUsage(CERTCertificate *cert, unsigned int requiredUsage); /* * return required key usage and cert type based on cert usage */ -SECStatus -CERT_KeyUsageAndTypeForCertUsage(SECCertUsage usage, - PRBool ca, - unsigned int *retKeyUsage, - unsigned int *retCertType); +SECStatus CERT_KeyUsageAndTypeForCertUsage(SECCertUsage usage, PRBool ca, + unsigned int *retKeyUsage, + unsigned int *retCertType); /* * return required trust flags for various cert usages for CAs */ -SECStatus -CERT_TrustFlagsForCACertUsage(SECCertUsage usage, - unsigned int *retFlags, - SECTrustType *retTrustType); +SECStatus CERT_TrustFlagsForCACertUsage(SECCertUsage usage, + unsigned int *retFlags, + SECTrustType *retTrustType); /* * Find all user certificates that match the given criteria. - * + * * "handle" - database to search * "usage" - certificate usage to match * "oneCertPerName" - if set then only return the "best" cert per @@ -1327,28 +1263,24 @@ CERT_TrustFlagsForCACertUsage(SECCertUsage usage, * "validOnly" - only return certs that are curently valid * "proto_win" - window handle passed to pkcs11 */ -CERTCertList * -CERT_FindUserCertsByUsage(CERTCertDBHandle *handle, - SECCertUsage usage, - PRBool oneCertPerName, - PRBool validOnly, - void *proto_win); +CERTCertList *CERT_FindUserCertsByUsage(CERTCertDBHandle *handle, + SECCertUsage usage, + PRBool oneCertPerName, PRBool validOnly, + void *proto_win); /* * Find a user certificate that matchs the given criteria. - * + * * "handle" - database to search * "nickname" - nickname to match * "usage" - certificate usage to match * "validOnly" - only return certs that are curently valid * "proto_win" - window handle passed to pkcs11 */ -CERTCertificate * -CERT_FindUserCertByUsage(CERTCertDBHandle *handle, - const char *nickname, - SECCertUsage usage, - PRBool validOnly, - void *proto_win); +CERTCertificate *CERT_FindUserCertByUsage(CERTCertDBHandle *handle, + const char *nickname, + SECCertUsage usage, PRBool validOnly, + void *proto_win); /* * Filter a list of certificates, removing those certs that do not have @@ -1360,15 +1292,13 @@ CERT_FindUserCertByUsage(CERTCertDBHandle *handle, * "usage" - what use the certs are for, this is used when * selecting CA certs */ -SECStatus -CERT_FilterCertListByCANames(CERTCertList *certList, int nCANames, - char **caNames, SECCertUsage usage); +SECStatus CERT_FilterCertListByCANames(CERTCertList *certList, int nCANames, + char **caNames, SECCertUsage usage); /* * Filter a list of certificates, removing those certs that aren't user certs */ -SECStatus -CERT_FilterCertListForUserCerts(CERTCertList *certList); +SECStatus CERT_FilterCertListForUserCerts(CERTCertList *certList); /* * Collect the nicknames from all certs in a CertList. If the cert is not @@ -1379,9 +1309,9 @@ CERT_FilterCertListForUserCerts(CERTCertList *certList); * "notYetGoodString" - the string to append to the nickname of any cert * that is not yet valid */ -CERTCertNicknames * -CERT_NicknameStringsFromCertList(CERTCertList *certList, char *expiredString, - char *notYetGoodString); +CERTCertNicknames *CERT_NicknameStringsFromCertList(CERTCertList *certList, + char *expiredString, + char *notYetGoodString); /* * Extract the nickname from a nickmake string that may have either @@ -1395,9 +1325,8 @@ CERT_NicknameStringsFromCertList(CERTCertList *certList, char *expiredString, * * Returns the raw nickname */ -char * -CERT_ExtractNicknameString(char *namestring, char *expiredString, - char *notYetGoodString); +char *CERT_ExtractNicknameString(char *namestring, char *expiredString, + char *notYetGoodString); /* * Given a certificate, return a string containing the nickname, and possibly @@ -1412,16 +1341,16 @@ CERT_ExtractNicknameString(char *namestring, char *expiredString, * "notYetGoodString" - the string to append to the nickname if the cert is * not yet good. */ -char * -CERT_GetCertNicknameWithValidity(PLArenaPool *arena, CERTCertificate *cert, - char *expiredString, char *notYetGoodString); +char *CERT_GetCertNicknameWithValidity(PLArenaPool *arena, + CERTCertificate *cert, + char *expiredString, + char *notYetGoodString); /* * Return the string representation of a DER encoded distinguished name * "dername" - The DER encoded name to convert */ -char * -CERT_DerNameToAscii(SECItem *dername); +char *CERT_DerNameToAscii(SECItem *dername); /* * Supported usage values and types: @@ -1433,10 +1362,10 @@ CERT_DerNameToAscii(SECItem *dername); * certUsageObjectSigner */ -CERTCertificate * -CERT_FindMatchingCert(CERTCertDBHandle *handle, SECItem *derName, - CERTCertOwner owner, SECCertUsage usage, - PRBool preferTrusted, PRTime validTime, PRBool validOnly); +CERTCertificate *CERT_FindMatchingCert(CERTCertDBHandle *handle, + SECItem *derName, CERTCertOwner owner, + SECCertUsage usage, PRBool preferTrusted, + PRTime validTime, PRBool validOnly); /* * Acquire the global lock on the cert database. @@ -1446,21 +1375,18 @@ CERT_FindMatchingCert(CERTCertDBHandle *handle, SECItem *derName, * changing(maybe just adding?) the trust of a cert * adjusting the reference count of a cert */ -void -CERT_LockDB(CERTCertDBHandle *handle); +void CERT_LockDB(CERTCertDBHandle *handle); /* * Free the global cert database lock. */ -void -CERT_UnlockDB(CERTCertDBHandle *handle); +void CERT_UnlockDB(CERTCertDBHandle *handle); /* * Get the certificate status checking configuratino data for * the certificate database */ -CERTStatusConfig * -CERT_GetStatusConfig(CERTCertDBHandle *handle); +CERTStatusConfig *CERT_GetStatusConfig(CERTCertDBHandle *handle); /* * Set the certificate status checking information for the @@ -1468,10 +1394,7 @@ CERT_GetStatusConfig(CERTCertDBHandle *handle); * database and will be freed by calling the 'Destroy' function in * the configuration object. */ -void -CERT_SetStatusConfig(CERTCertDBHandle *handle, CERTStatusConfig *config); - - +void CERT_SetStatusConfig(CERTCertDBHandle *handle, CERTStatusConfig *config); /* * Acquire the cert reference count lock @@ -1479,14 +1402,12 @@ CERT_SetStatusConfig(CERTCertDBHandle *handle, CERTStatusConfig *config); * arg here so that it will be easy to make it per-cert in the future if * that turns out to be necessary. */ -void -CERT_LockCertRefCount(CERTCertificate *cert); +void CERT_LockCertRefCount(CERTCertificate *cert); /* * Free the cert reference count lock */ -void -CERT_UnlockCertRefCount(CERTCertificate *cert); +void CERT_UnlockCertRefCount(CERTCertificate *cert); /* * Acquire the cert trust lock @@ -1494,14 +1415,12 @@ CERT_UnlockCertRefCount(CERTCertificate *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 -CERT_LockCertTrust(const CERTCertificate *cert); +void CERT_LockCertTrust(const CERTCertificate *cert); /* * Free the cert trust lock */ -void -CERT_UnlockCertTrust(const CERTCertificate *cert); +void CERT_UnlockCertTrust(const CERTCertificate *cert); /* * Digest the cert's subject public key using the specified algorithm. @@ -1513,47 +1432,44 @@ CERT_UnlockCertTrust(const CERTCertificate *cert); * non-null, the data is put there, otherwise a SECItem is allocated. * Allocation from "arena" if it is non-null, heap otherwise. Any problem * results in a NULL being returned (and an appropriate error set). - */ -extern SECItem * -CERT_GetSubjectPublicKeyDigest(PLArenaPool *arena, const CERTCertificate *cert, - SECOidTag digestAlg, SECItem *fill); + */ +extern SECItem *CERT_GetSubjectPublicKeyDigest(PLArenaPool *arena, + const CERTCertificate *cert, + SECOidTag digestAlg, + SECItem *fill); /* * Digest the cert's subject name using the specified algorithm. */ -extern SECItem * -CERT_GetSubjectNameDigest(PLArenaPool *arena, const CERTCertificate *cert, - SECOidTag digestAlg, SECItem *fill); - -SECStatus CERT_CheckCRL(CERTCertificate* cert, CERTCertificate* issuer, - const SECItem* dp, PRTime t, void* wincx); +extern SECItem *CERT_GetSubjectNameDigest(PLArenaPool *arena, + const CERTCertificate *cert, + SECOidTag digestAlg, SECItem *fill); +SECStatus CERT_CheckCRL(CERTCertificate *cert, CERTCertificate *issuer, + const SECItem *dp, PRTime t, void *wincx); /* * Add a CERTNameConstraint to the CERTNameConstraint list */ -extern CERTNameConstraint * -CERT_AddNameConstraint(CERTNameConstraint *list, - CERTNameConstraint *constraint); +extern CERTNameConstraint *CERT_AddNameConstraint( + CERTNameConstraint *list, CERTNameConstraint *constraint); /* * Allocate space and copy CERTNameConstraint from src to dest. * Arena is used to allocate result(if dest eq NULL) and its members * SECItem data. */ -extern CERTNameConstraint * -CERT_CopyNameConstraint(PLArenaPool *arena, - CERTNameConstraint *dest, - CERTNameConstraint *src); +extern CERTNameConstraint *CERT_CopyNameConstraint(PLArenaPool *arena, + CERTNameConstraint *dest, + CERTNameConstraint *src); /* * Verify name against all the constraints relevant to that type of * the name. */ -extern SECStatus -CERT_CheckNameSpace(PLArenaPool *arena, - const CERTNameConstraints *constraints, - const CERTGeneralName *currentName); +extern SECStatus CERT_CheckNameSpace(PLArenaPool *arena, + const CERTNameConstraints *constraints, + const CERTGeneralName *currentName); /* * Extract and allocate the name constraints extension from the CA cert. @@ -1561,84 +1477,70 @@ CERT_CheckNameSpace(PLArenaPool *arena, * CERT_GetImposedNameConstraints returns a name constraints extension * for the subject of the certificate, then that extension will be returned. */ -extern SECStatus -CERT_FindNameConstraintsExten(PLArenaPool *arena, - CERTCertificate *cert, - CERTNameConstraints **constraints); +extern SECStatus CERT_FindNameConstraintsExten( + PLArenaPool *arena, CERTCertificate *cert, + CERTNameConstraints **constraints); /* * Initialize a new GERTGeneralName fields (link) */ -extern CERTGeneralName * -CERT_NewGeneralName(PLArenaPool *arena, CERTGeneralNameType type); +extern CERTGeneralName *CERT_NewGeneralName(PLArenaPool *arena, + CERTGeneralNameType type); /* * Lookup a CERTGeneralNameType constant by its human readable string. */ -extern CERTGeneralNameType -CERT_GetGeneralNameTypeFromString(const char *string); +extern CERTGeneralNameType CERT_GetGeneralNameTypeFromString( + const char *string); /* * PKIX extension encoding routines */ -extern SECStatus -CERT_EncodePolicyConstraintsExtension(PLArenaPool *arena, - CERTCertificatePolicyConstraints *constr, - SECItem *dest); -extern SECStatus -CERT_EncodeInhibitAnyExtension(PLArenaPool *arena, - CERTCertificateInhibitAny *inhibitAny, - SECItem *dest); -extern SECStatus -CERT_EncodePolicyMappingExtension(PLArenaPool *arena, - CERTCertificatePolicyMappings *maps, - SECItem *dest); +extern SECStatus CERT_EncodePolicyConstraintsExtension( + PLArenaPool *arena, CERTCertificatePolicyConstraints *constr, + SECItem *dest); +extern SECStatus CERT_EncodeInhibitAnyExtension( + PLArenaPool *arena, CERTCertificateInhibitAny *inhibitAny, SECItem *dest); +extern SECStatus CERT_EncodePolicyMappingExtension( + PLArenaPool *arena, CERTCertificatePolicyMappings *maps, SECItem *dest); extern SECStatus CERT_EncodeInfoAccessExtension(PLArenaPool *arena, - CERTAuthInfoAccess **info, - SECItem *dest); -extern SECStatus -CERT_EncodeUserNotice(PLArenaPool *arena, - CERTUserNotice *notice, - SECItem *dest); + CERTAuthInfoAccess **info, + SECItem *dest); +extern SECStatus CERT_EncodeUserNotice(PLArenaPool *arena, + CERTUserNotice *notice, SECItem *dest); -extern SECStatus -CERT_EncodeDisplayText(PLArenaPool *arena, - SECItem *text, - SECItem *dest); +extern SECStatus CERT_EncodeDisplayText(PLArenaPool *arena, SECItem *text, + SECItem *dest); -extern SECStatus -CERT_EncodeCertPoliciesExtension(PLArenaPool *arena, - CERTPolicyInfo **info, - SECItem *dest); -extern SECStatus -CERT_EncodeNoticeReference(PLArenaPool *arena, - CERTNoticeReference *reference, - SECItem *dest); +extern SECStatus CERT_EncodeCertPoliciesExtension(PLArenaPool *arena, + CERTPolicyInfo **info, + SECItem *dest); +extern SECStatus CERT_EncodeNoticeReference(PLArenaPool *arena, + CERTNoticeReference *reference, + SECItem *dest); /* * Returns a pointer to a static structure. */ -extern const CERTRevocationFlags* -CERT_GetPKIXVerifyNistRevocationPolicy(void); +extern const CERTRevocationFlags *CERT_GetPKIXVerifyNistRevocationPolicy(void); /* * Returns a pointer to a static structure. */ -extern const CERTRevocationFlags* -CERT_GetClassicOCSPEnabledSoftFailurePolicy(void); +extern const CERTRevocationFlags *CERT_GetClassicOCSPEnabledSoftFailurePolicy( + void); /* * Returns a pointer to a static structure. */ -extern const CERTRevocationFlags* -CERT_GetClassicOCSPEnabledHardFailurePolicy(void); +extern const CERTRevocationFlags *CERT_GetClassicOCSPEnabledHardFailurePolicy( + void); /* * Returns a pointer to a static structure. */ -extern const CERTRevocationFlags* -CERT_GetClassicOCSPDisabledPolicy(void); +extern const CERTRevocationFlags *CERT_GetClassicOCSPDisabledPolicy(void); /* * Verify a Cert with libpkix @@ -1647,12 +1549,10 @@ CERT_GetClassicOCSPDisabledPolicy(void); * paramsOut specifies the parameters the caller would like to get back. * the caller may pass NULL, in which case no parameters are returned. */ -extern SECStatus CERT_PKIXVerifyCert( - CERTCertificate *cert, - SECCertificateUsage usages, - CERTValInParam *paramsIn, - CERTValOutParam *paramsOut, - void *wincx); +extern SECStatus CERT_PKIXVerifyCert(CERTCertificate *cert, + SECCertificateUsage usages, + CERTValInParam *paramsIn, + CERTValOutParam *paramsOut, void *wincx); /* Makes old cert validation APIs(CERT_VerifyCert, CERT_VerifyCertificate) * to use libpkix validation engine. The function should be called ones at @@ -1669,8 +1569,7 @@ extern PRBool CERT_GetUsePKIXForValidation(void); * and allocate the inner arrays of the given sizes. * To cleanup call CERT_DestroyCERTRevocationFlags. */ -extern CERTRevocationFlags * -CERT_AllocCERTRevocationFlags( +extern CERTRevocationFlags *CERT_AllocCERTRevocationFlags( PRUint32 number_leaf_methods, PRUint32 number_leaf_pref_methods, PRUint32 number_chain_methods, PRUint32 number_chain_pref_methods); @@ -1678,8 +1577,7 @@ CERT_AllocCERTRevocationFlags( * Destroy the arrays inside flags, * and destroy the object pointed to by flags, too. */ -extern void -CERT_DestroyCERTRevocationFlags(CERTRevocationFlags *flags); +extern void CERT_DestroyCERTRevocationFlags(CERTRevocationFlags *flags); SEC_END_PROTOS diff --git a/security/nss/lib/certdb/certdb.c b/security/nss/lib/certdb/certdb.c index f282bbb9ffa4..902e0366df09 100644 --- a/security/nss/lib/certdb/certdb.c +++ b/security/nss/lib/certdb/certdb.c @@ -26,7 +26,7 @@ #include "secerr.h" #include "sslerr.h" #include "pk11func.h" -#include "xconst.h" /* for CERT_DecodeAltNameExtension */ +#include "xconst.h" /* for CERT_DecodeAltNameExtension */ #include "pki.h" #include "pki3hack.h" @@ -41,17 +41,13 @@ SEC_ASN1_MKSUB(SEC_SkipTemplate) * Certificate database handling code */ - const SEC_ASN1Template CERT_CertExtensionTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCertExtension) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTCertExtension,id) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ - offsetof(CERTCertExtension,critical) }, - { SEC_ASN1_OCTET_STRING, - offsetof(CERTCertExtension,value) }, - { 0, } + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCertExtension) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTCertExtension, id) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ + offsetof(CERTCertExtension, critical) }, + { SEC_ASN1_OCTET_STRING, offsetof(CERTCertExtension, value) }, + { 0 } }; const SEC_ASN1Template CERT_SequenceOfCertExtensionTemplate[] = { @@ -59,80 +55,60 @@ const SEC_ASN1Template CERT_SequenceOfCertExtensionTemplate[] = { }; const SEC_ASN1Template CERT_TimeChoiceTemplate[] = { - { SEC_ASN1_CHOICE, offsetof(SECItem, type), 0, sizeof(SECItem) }, - { SEC_ASN1_UTC_TIME, 0, 0, siUTCTime }, - { SEC_ASN1_GENERALIZED_TIME, 0, 0, siGeneralizedTime }, - { 0 } + { SEC_ASN1_CHOICE, offsetof(SECItem, type), 0, sizeof(SECItem) }, + { SEC_ASN1_UTC_TIME, 0, 0, siUTCTime }, + { SEC_ASN1_GENERALIZED_TIME, 0, 0, siGeneralizedTime }, + { 0 } }; const SEC_ASN1Template CERT_ValidityTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTValidity) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTValidity,notBefore), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate), 0 }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTValidity,notAfter), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate), 0 }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTValidity) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTValidity, notBefore), + SEC_ASN1_SUB(CERT_TimeChoiceTemplate), 0 }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTValidity, notAfter), + SEC_ASN1_SUB(CERT_TimeChoiceTemplate), 0 }, { 0 } }; const SEC_ASN1Template CERT_CertificateTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCertificate) }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, /* XXX DER_DEFAULT */ - offsetof(CERTCertificate,version), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, - { SEC_ASN1_INTEGER, - offsetof(CERTCertificate,serialNumber) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCertificate,signature), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_SAVE, - offsetof(CERTCertificate,derIssuer) }, - { SEC_ASN1_INLINE, - offsetof(CERTCertificate,issuer), - CERT_NameTemplate }, - { SEC_ASN1_INLINE, - offsetof(CERTCertificate,validity), - CERT_ValidityTemplate }, - { SEC_ASN1_SAVE, - offsetof(CERTCertificate,derSubject) }, - { SEC_ASN1_INLINE, - offsetof(CERTCertificate,subject), - CERT_NameTemplate }, - { SEC_ASN1_SAVE, - offsetof(CERTCertificate,derPublicKey) }, - { SEC_ASN1_INLINE, - offsetof(CERTCertificate,subjectPublicKeyInfo), - CERT_SubjectPublicKeyInfoTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, - offsetof(CERTCertificate,issuerID), - SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, - offsetof(CERTCertificate,subjectID), - SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 3, - offsetof(CERTCertificate,extensions), - CERT_SequenceOfCertExtensionTemplate }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCertificate) }, + { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, /* XXX DER_DEFAULT */ + offsetof(CERTCertificate, version), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, + { SEC_ASN1_INTEGER, offsetof(CERTCertificate, serialNumber) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTCertificate, signature), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_SAVE, offsetof(CERTCertificate, derIssuer) }, + { SEC_ASN1_INLINE, offsetof(CERTCertificate, issuer), CERT_NameTemplate }, + { SEC_ASN1_INLINE, offsetof(CERTCertificate, validity), + CERT_ValidityTemplate }, + { SEC_ASN1_SAVE, offsetof(CERTCertificate, derSubject) }, + { SEC_ASN1_INLINE, offsetof(CERTCertificate, subject), CERT_NameTemplate }, + { SEC_ASN1_SAVE, offsetof(CERTCertificate, derPublicKey) }, + { SEC_ASN1_INLINE, offsetof(CERTCertificate, subjectPublicKeyInfo), + CERT_SubjectPublicKeyInfoTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, + offsetof(CERTCertificate, issuerID), + SEC_ASN1_SUB(SEC_BitStringTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, + offsetof(CERTCertificate, subjectID), + SEC_ASN1_SUB(SEC_BitStringTemplate) }, + { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | 3, + offsetof(CERTCertificate, extensions), + CERT_SequenceOfCertExtensionTemplate }, { 0 } }; -const SEC_ASN1Template SEC_SignedCertificateTemplate[] = -{ - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCertificate) }, - { SEC_ASN1_SAVE, - offsetof(CERTCertificate,signatureWrap.data) }, - { SEC_ASN1_INLINE, - 0, CERT_CertificateTemplate }, +const SEC_ASN1Template SEC_SignedCertificateTemplate[] = { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCertificate) }, + { SEC_ASN1_SAVE, offsetof(CERTCertificate, signatureWrap.data) }, + { SEC_ASN1_INLINE, 0, CERT_CertificateTemplate }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCertificate,signatureWrap.signatureAlgorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_BIT_STRING, - offsetof(CERTCertificate,signatureWrap.signature) }, + offsetof(CERTCertificate, signatureWrap.signatureAlgorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_BIT_STRING, offsetof(CERTCertificate, signatureWrap.signature) }, { 0 } }; @@ -140,16 +116,15 @@ const SEC_ASN1Template SEC_SignedCertificateTemplate[] = * Find the subjectName in a DER encoded certificate */ const SEC_ASN1Template SEC_CertSubjectTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SECItem) }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ - { SEC_ASN1_SKIP }, /* serial number */ - { SEC_ASN1_SKIP }, /* signature algorithm */ - { SEC_ASN1_SKIP }, /* issuer */ - { SEC_ASN1_SKIP }, /* validity */ - { SEC_ASN1_ANY, 0, NULL }, /* subject */ + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECItem) }, + { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ + { SEC_ASN1_SKIP }, /* serial number */ + { SEC_ASN1_SKIP }, /* signature algorithm */ + { SEC_ASN1_SKIP }, /* issuer */ + { SEC_ASN1_SKIP }, /* validity */ + { SEC_ASN1_ANY, 0, NULL }, /* subject */ { SEC_ASN1_SKIP_REST }, { 0 } }; @@ -158,14 +133,13 @@ const SEC_ASN1Template SEC_CertSubjectTemplate[] = { * Find the issuerName in a DER encoded certificate */ const SEC_ASN1Template SEC_CertIssuerTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SECItem) }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ - { SEC_ASN1_SKIP }, /* serial number */ - { SEC_ASN1_SKIP }, /* signature algorithm */ - { SEC_ASN1_ANY, 0, NULL }, /* issuer */ + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECItem) }, + { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ + { SEC_ASN1_SKIP }, /* serial number */ + { SEC_ASN1_SKIP }, /* signature algorithm */ + { SEC_ASN1_ANY, 0, NULL }, /* issuer */ { SEC_ASN1_SKIP_REST }, { 0 } }; @@ -173,12 +147,11 @@ const SEC_ASN1Template SEC_CertIssuerTemplate[] = { * Find the subjectName in a DER encoded certificate */ const SEC_ASN1Template SEC_CertSerialNumberTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SECItem) }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ - { SEC_ASN1_ANY, 0, NULL }, /* serial number */ + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECItem) }, + { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ + { SEC_ASN1_ANY, 0, NULL }, /* serial number */ { SEC_ASN1_SKIP_REST }, { 0 } }; @@ -189,16 +162,13 @@ const SEC_ASN1Template SEC_CertSerialNumberTemplate[] = { * identifier of a certificate. */ const SEC_ASN1Template CERT_CertKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCertKey) }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ - { SEC_ASN1_INTEGER, - offsetof(CERTCertKey,serialNumber) }, - { SEC_ASN1_SKIP }, /* signature algorithm */ - { SEC_ASN1_ANY, - offsetof(CERTCertKey,derIssuer) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCertKey) }, + { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + 0, SEC_ASN1_SUB(SEC_SkipTemplate) }, /* version */ + { SEC_ASN1_INTEGER, offsetof(CERTCertKey, serialNumber) }, + { SEC_ASN1_SKIP }, /* signature algorithm */ + { SEC_ASN1_ANY, offsetof(CERTCertKey, derIssuer) }, { SEC_ASN1_SKIP_REST }, { 0 } }; @@ -210,17 +180,17 @@ SEC_ASN1_CHOOSER_IMPLEMENT(CERT_SequenceOfCertExtensionTemplate) SECStatus CERT_KeyFromIssuerAndSN(PLArenaPool *arena, SECItem *issuer, SECItem *sn, - SECItem *key) + SECItem *key) { key->len = sn->len + issuer->len; if ((sn->data == NULL) || (issuer->data == NULL)) { - goto loser; + goto loser; } - - key->data = (unsigned char*)PORT_ArenaAlloc(arena, key->len); - if ( !key->data ) { - goto loser; + + key->data = (unsigned char *)PORT_ArenaAlloc(arena, key->len); + if (!key->data) { + goto loser; } /* copy the serialNumber */ @@ -229,13 +199,12 @@ CERT_KeyFromIssuerAndSN(PLArenaPool *arena, SECItem *issuer, SECItem *sn, /* copy the issuer */ PORT_Memcpy(&key->data[sn->len], issuer->data, issuer->len); - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } - /* * Extract the subject name from a DER certificate */ @@ -246,41 +215,42 @@ CERT_NameFromDERCert(SECItem *derCert, SECItem *derName) PLArenaPool *arena; CERTSignedData sd; void *tmpptr; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( ! arena ) { - return(SECFailure); + + if (!arena) { + return (SECFailure); } - + PORT_Memset(&sd, 0, sizeof(CERTSignedData)); rv = SEC_QuickDERDecodeItem(arena, &sd, CERT_SignedDataTemplate, derCert); - - if ( rv ) { - goto loser; - } - - PORT_Memset(derName, 0, sizeof(SECItem)); - rv = SEC_QuickDERDecodeItem(arena, derName, SEC_CertSubjectTemplate, &sd.data); - if ( rv ) { - goto loser; + if (rv) { + goto loser; + } + + PORT_Memset(derName, 0, sizeof(SECItem)); + rv = SEC_QuickDERDecodeItem(arena, derName, SEC_CertSubjectTemplate, + &sd.data); + + if (rv) { + goto loser; } tmpptr = derName->data; - derName->data = (unsigned char*)PORT_Alloc(derName->len); - if ( derName->data == NULL ) { - goto loser; + derName->data = (unsigned char *)PORT_Alloc(derName->len); + if (derName->data == NULL) { + goto loser; } - + PORT_Memcpy(derName->data, tmpptr, derName->len); - + PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: PORT_FreeArena(arena, PR_FALSE); - return(SECFailure); + return (SECFailure); } SECStatus @@ -290,41 +260,42 @@ CERT_IssuerNameFromDERCert(SECItem *derCert, SECItem *derName) PLArenaPool *arena; CERTSignedData sd; void *tmpptr; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( ! arena ) { - return(SECFailure); + + if (!arena) { + return (SECFailure); } - + PORT_Memset(&sd, 0, sizeof(CERTSignedData)); rv = SEC_QuickDERDecodeItem(arena, &sd, CERT_SignedDataTemplate, derCert); - - if ( rv ) { - goto loser; - } - - PORT_Memset(derName, 0, sizeof(SECItem)); - rv = SEC_QuickDERDecodeItem(arena, derName, SEC_CertIssuerTemplate, &sd.data); - if ( rv ) { - goto loser; + if (rv) { + goto loser; + } + + PORT_Memset(derName, 0, sizeof(SECItem)); + rv = SEC_QuickDERDecodeItem(arena, derName, SEC_CertIssuerTemplate, + &sd.data); + + if (rv) { + goto loser; } tmpptr = derName->data; - derName->data = (unsigned char*)PORT_Alloc(derName->len); - if ( derName->data == NULL ) { - goto loser; + derName->data = (unsigned char *)PORT_Alloc(derName->len); + if (derName->data == NULL) { + goto loser; } - + PORT_Memcpy(derName->data, tmpptr, derName->len); - + PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: PORT_FreeArena(arena, PR_FALSE); - return(SECFailure); + return (SECFailure); } SECStatus @@ -334,41 +305,42 @@ CERT_SerialNumberFromDERCert(SECItem *derCert, SECItem *derName) PLArenaPool *arena; CERTSignedData sd; void *tmpptr; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( ! arena ) { - return(SECFailure); + + if (!arena) { + return (SECFailure); } - + PORT_Memset(&sd, 0, sizeof(CERTSignedData)); rv = SEC_QuickDERDecodeItem(arena, &sd, CERT_SignedDataTemplate, derCert); - - if ( rv ) { - goto loser; - } - - PORT_Memset(derName, 0, sizeof(SECItem)); - rv = SEC_QuickDERDecodeItem(arena, derName, SEC_CertSerialNumberTemplate, &sd.data); - if ( rv ) { - goto loser; + if (rv) { + goto loser; + } + + PORT_Memset(derName, 0, sizeof(SECItem)); + rv = SEC_QuickDERDecodeItem(arena, derName, SEC_CertSerialNumberTemplate, + &sd.data); + + if (rv) { + goto loser; } tmpptr = derName->data; - derName->data = (unsigned char*)PORT_Alloc(derName->len); - if ( derName->data == NULL ) { - goto loser; + derName->data = (unsigned char *)PORT_Alloc(derName->len); + if (derName->data == NULL) { + goto loser; } - + PORT_Memcpy(derName->data, tmpptr, derName->len); - + PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: PORT_FreeArena(arena, PR_FALSE); - return(SECFailure); + return (SECFailure); } /* @@ -388,25 +360,25 @@ CERT_KeyFromDERCert(PLArenaPool *reqArena, SECItem *derCert, SECItem *key) } PORT_Memset(&sd, 0, sizeof(CERTSignedData)); - rv = SEC_QuickDERDecodeItem(reqArena, &sd, CERT_SignedDataTemplate, - derCert); - - if ( rv ) { - goto loser; + rv = + SEC_QuickDERDecodeItem(reqArena, &sd, CERT_SignedDataTemplate, derCert); + + if (rv) { + goto loser; } - + PORT_Memset(&certkey, 0, sizeof(CERTCertKey)); rv = SEC_QuickDERDecodeItem(reqArena, &certkey, CERT_CertKeyTemplate, &sd.data); - if ( rv ) { - goto loser; + if (rv) { + goto loser; } - return(CERT_KeyFromIssuerAndSN(reqArena, &certkey.derIssuer, - &certkey.serialNumber, key)); + return (CERT_KeyFromIssuerAndSN(reqArena, &certkey.derIssuer, + &certkey.serialNumber, key)); loser: - return(SECFailure); + return (SECFailure); } /* @@ -418,50 +390,49 @@ GetKeyUsage(CERTCertificate *cert) { SECStatus rv; SECItem tmpitem; - + rv = CERT_FindKeyUsageExtension(cert, &tmpitem); - if ( rv == SECSuccess ) { - /* remember the actual value of the extension */ - cert->rawKeyUsage = tmpitem.data[0]; - cert->keyUsagePresent = PR_TRUE; - cert->keyUsage = tmpitem.data[0]; + if (rv == SECSuccess) { + /* remember the actual value of the extension */ + cert->rawKeyUsage = tmpitem.data[0]; + cert->keyUsagePresent = PR_TRUE; + cert->keyUsage = tmpitem.data[0]; - PORT_Free(tmpitem.data); - tmpitem.data = NULL; - - } else { - /* if the extension is not present, then we allow all uses */ - cert->keyUsage = KU_ALL; - cert->rawKeyUsage = KU_ALL; - cert->keyUsagePresent = PR_FALSE; + PORT_Free(tmpitem.data); + tmpitem.data = NULL; + } + else { + /* if the extension is not present, then we allow all uses */ + cert->keyUsage = KU_ALL; + cert->rawKeyUsage = KU_ALL; + cert->keyUsagePresent = PR_FALSE; } - if ( CERT_GovtApprovedBitSet(cert) ) { - cert->keyUsage |= KU_NS_GOVT_APPROVED; - cert->rawKeyUsage |= KU_NS_GOVT_APPROVED; + if (CERT_GovtApprovedBitSet(cert)) { + cert->keyUsage |= KU_NS_GOVT_APPROVED; + cert->rawKeyUsage |= KU_NS_GOVT_APPROVED; } - - return(SECSuccess); + + return (SECSuccess); } - static SECStatus findOIDinOIDSeqByTagNum(CERTOidSequence *seq, SECOidTag tagnum) { SECItem **oids; SECItem *oid; SECStatus rv = SECFailure; - + if (seq != NULL) { - oids = seq->oids; - while (oids != NULL && *oids != NULL) { - oid = *oids; - if (SECOID_FindOIDTag(oid) == tagnum) { - rv = SECSuccess; - break; - } - oids++; - } + oids = seq->oids; + while (oids != NULL && *oids != NULL) { + oid = *oids; + if (SECOID_FindOIDTag(oid) == tagnum) { + rv = SECSuccess; + break; + } + oids++; + } } return rv; } @@ -500,132 +471,128 @@ cert_ComputeCertType(CERTCertificate *cert) tmpitem.data = NULL; CERT_FindNSCertTypeExtension(cert, &tmpitem); encodedExtKeyUsage.data = NULL; - rv = CERT_FindCertExtension(cert, SEC_OID_X509_EXT_KEY_USAGE, - &encodedExtKeyUsage); + rv = CERT_FindCertExtension(cert, SEC_OID_X509_EXT_KEY_USAGE, + &encodedExtKeyUsage); if (rv == SECSuccess) { - extKeyUsage = CERT_DecodeOidSequence(&encodedExtKeyUsage); + extKeyUsage = CERT_DecodeOidSequence(&encodedExtKeyUsage); } rv = CERT_FindBasicConstraintExten(cert, &basicConstraint); if (rv == SECSuccess) { - basicConstraintPresent = PR_TRUE; + basicConstraintPresent = PR_TRUE; } if (tmpitem.data != NULL || extKeyUsage != NULL) { - if (tmpitem.data == NULL) { - nsCertType = 0; - } else { - nsCertType = tmpitem.data[0]; - } + if (tmpitem.data == NULL) { + nsCertType = 0; + } + else { + nsCertType = tmpitem.data[0]; + } - /* free tmpitem data pointer to avoid memory leak */ - PORT_Free(tmpitem.data); - tmpitem.data = NULL; - - /* - * for this release, we will allow SSL certs with an email address - * to be used for email - */ - if ( ( nsCertType & NS_CERT_TYPE_SSL_CLIENT ) && - cert->emailAddr && cert->emailAddr[0]) { - nsCertType |= NS_CERT_TYPE_EMAIL; - } - /* - * for this release, we will allow SSL intermediate CAs to be - * email intermediate CAs too. - */ - if ( nsCertType & NS_CERT_TYPE_SSL_CA ) { - nsCertType |= NS_CERT_TYPE_EMAIL_CA; - } - /* - * allow a cert with the extended key usage of EMail Protect - * to be used for email or as an email CA, if basic constraints - * indicates that it is a CA. - */ - if (findOIDinOIDSeqByTagNum(extKeyUsage, - SEC_OID_EXT_KEY_USAGE_EMAIL_PROTECT) == - SECSuccess) { - if (basicConstraintPresent == PR_TRUE && - (basicConstraint.isCA)) { - nsCertType |= NS_CERT_TYPE_EMAIL_CA; - } else { - nsCertType |= NS_CERT_TYPE_EMAIL; - } - } - if (findOIDinOIDSeqByTagNum(extKeyUsage, - SEC_OID_EXT_KEY_USAGE_SERVER_AUTH) == - SECSuccess){ - if (basicConstraintPresent == PR_TRUE && - (basicConstraint.isCA)) { - nsCertType |= NS_CERT_TYPE_SSL_CA; - } else { - nsCertType |= NS_CERT_TYPE_SSL_SERVER; - } - } - /* - * Treat certs with step-up OID as also having SSL server type. - * COMODO needs this behaviour until June 2020. See Bug 737802. - */ - if (findOIDinOIDSeqByTagNum(extKeyUsage, - SEC_OID_NS_KEY_USAGE_GOVT_APPROVED) == - SECSuccess){ - if (basicConstraintPresent == PR_TRUE && - (basicConstraint.isCA)) { - nsCertType |= NS_CERT_TYPE_SSL_CA; - } else { - nsCertType |= NS_CERT_TYPE_SSL_SERVER; - } - } - if (findOIDinOIDSeqByTagNum(extKeyUsage, - SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH) == - SECSuccess){ - if (basicConstraintPresent == PR_TRUE && - (basicConstraint.isCA)) { - nsCertType |= NS_CERT_TYPE_SSL_CA; - } else { - nsCertType |= NS_CERT_TYPE_SSL_CLIENT; - } - } - if (findOIDinOIDSeqByTagNum(extKeyUsage, - SEC_OID_EXT_KEY_USAGE_CODE_SIGN) == - SECSuccess) { - if (basicConstraintPresent == PR_TRUE && - (basicConstraint.isCA)) { - nsCertType |= NS_CERT_TYPE_OBJECT_SIGNING_CA; - } else { - nsCertType |= NS_CERT_TYPE_OBJECT_SIGNING; - } - } - if (findOIDinOIDSeqByTagNum(extKeyUsage, - SEC_OID_EXT_KEY_USAGE_TIME_STAMP) == - SECSuccess) { - nsCertType |= EXT_KEY_USAGE_TIME_STAMP; - } - if (findOIDinOIDSeqByTagNum(extKeyUsage, - SEC_OID_OCSP_RESPONDER) == - SECSuccess) { - nsCertType |= EXT_KEY_USAGE_STATUS_RESPONDER; - } - } else { - /* If no NS Cert Type extension and no EKU extension, then */ - nsCertType = 0; - if (CERT_IsCACert(cert, &nsCertType)) - nsCertType |= EXT_KEY_USAGE_STATUS_RESPONDER; - /* if the basic constraint extension says the cert is a CA, then - allow SSL CA and EMAIL CA and Status Responder */ - if (basicConstraintPresent && basicConstraint.isCA ) { - nsCertType |= (NS_CERT_TYPE_SSL_CA | - NS_CERT_TYPE_EMAIL_CA | - EXT_KEY_USAGE_STATUS_RESPONDER); - } - /* allow any ssl or email (no ca or object signing. */ - nsCertType |= NS_CERT_TYPE_SSL_CLIENT | NS_CERT_TYPE_SSL_SERVER | - NS_CERT_TYPE_EMAIL; + /* free tmpitem data pointer to avoid memory leak */ + PORT_Free(tmpitem.data); + tmpitem.data = NULL; + + /* + * for this release, we will allow SSL certs with an email address + * to be used for email + */ + if ((nsCertType & NS_CERT_TYPE_SSL_CLIENT) && cert->emailAddr && + cert->emailAddr[0]) { + nsCertType |= NS_CERT_TYPE_EMAIL; + } + /* + * for this release, we will allow SSL intermediate CAs to be + * email intermediate CAs too. + */ + if (nsCertType & NS_CERT_TYPE_SSL_CA) { + nsCertType |= NS_CERT_TYPE_EMAIL_CA; + } + /* + * allow a cert with the extended key usage of EMail Protect + * to be used for email or as an email CA, if basic constraints + * indicates that it is a CA. + */ + if (findOIDinOIDSeqByTagNum(extKeyUsage, + SEC_OID_EXT_KEY_USAGE_EMAIL_PROTECT) == + SECSuccess) { + if (basicConstraintPresent == PR_TRUE && (basicConstraint.isCA)) { + nsCertType |= NS_CERT_TYPE_EMAIL_CA; + } + else { + nsCertType |= NS_CERT_TYPE_EMAIL; + } + } + if (findOIDinOIDSeqByTagNum( + extKeyUsage, SEC_OID_EXT_KEY_USAGE_SERVER_AUTH) == SECSuccess) { + if (basicConstraintPresent == PR_TRUE && (basicConstraint.isCA)) { + nsCertType |= NS_CERT_TYPE_SSL_CA; + } + else { + nsCertType |= NS_CERT_TYPE_SSL_SERVER; + } + } + /* + * Treat certs with step-up OID as also having SSL server type. + * COMODO needs this behaviour until June 2020. See Bug 737802. + */ + if (findOIDinOIDSeqByTagNum(extKeyUsage, + SEC_OID_NS_KEY_USAGE_GOVT_APPROVED) == + SECSuccess) { + if (basicConstraintPresent == PR_TRUE && (basicConstraint.isCA)) { + nsCertType |= NS_CERT_TYPE_SSL_CA; + } + else { + nsCertType |= NS_CERT_TYPE_SSL_SERVER; + } + } + if (findOIDinOIDSeqByTagNum( + extKeyUsage, SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH) == SECSuccess) { + if (basicConstraintPresent == PR_TRUE && (basicConstraint.isCA)) { + nsCertType |= NS_CERT_TYPE_SSL_CA; + } + else { + nsCertType |= NS_CERT_TYPE_SSL_CLIENT; + } + } + if (findOIDinOIDSeqByTagNum( + extKeyUsage, SEC_OID_EXT_KEY_USAGE_CODE_SIGN) == SECSuccess) { + if (basicConstraintPresent == PR_TRUE && (basicConstraint.isCA)) { + nsCertType |= NS_CERT_TYPE_OBJECT_SIGNING_CA; + } + else { + nsCertType |= NS_CERT_TYPE_OBJECT_SIGNING; + } + } + if (findOIDinOIDSeqByTagNum( + extKeyUsage, SEC_OID_EXT_KEY_USAGE_TIME_STAMP) == SECSuccess) { + nsCertType |= EXT_KEY_USAGE_TIME_STAMP; + } + if (findOIDinOIDSeqByTagNum(extKeyUsage, SEC_OID_OCSP_RESPONDER) == + SECSuccess) { + nsCertType |= EXT_KEY_USAGE_STATUS_RESPONDER; + } + } + else { + /* If no NS Cert Type extension and no EKU extension, then */ + nsCertType = 0; + if (CERT_IsCACert(cert, &nsCertType)) + nsCertType |= EXT_KEY_USAGE_STATUS_RESPONDER; + /* if the basic constraint extension says the cert is a CA, then + allow SSL CA and EMAIL CA and Status Responder */ + if (basicConstraintPresent && basicConstraint.isCA) { + nsCertType |= (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA | + EXT_KEY_USAGE_STATUS_RESPONDER); + } + /* allow any ssl or email (no ca or object signing. */ + nsCertType |= NS_CERT_TYPE_SSL_CLIENT | NS_CERT_TYPE_SSL_SERVER | + NS_CERT_TYPE_EMAIL; } if (encodedExtKeyUsage.data != NULL) { - PORT_Free(encodedExtKeyUsage.data); + PORT_Free(encodedExtKeyUsage.data); } if (extKeyUsage != NULL) { - CERT_DestroyOidSequence(extKeyUsage); + CERT_DestroyOidSequence(extKeyUsage); } return nsCertType; } @@ -638,44 +605,44 @@ cert_GetKeyID(CERTCertificate *cert) { SECItem tmpitem; SECStatus rv; - + cert->subjectKeyID.len = 0; /* see of the cert has a key identifier extension */ rv = CERT_FindSubjectKeyIDExtension(cert, &tmpitem); - if ( rv == SECSuccess ) { - cert->subjectKeyID.data = (unsigned char*) PORT_ArenaAlloc(cert->arena, tmpitem.len); - if ( cert->subjectKeyID.data != NULL ) { - PORT_Memcpy(cert->subjectKeyID.data, tmpitem.data, tmpitem.len); - cert->subjectKeyID.len = tmpitem.len; - cert->keyIDGenerated = PR_FALSE; - } - - PORT_Free(tmpitem.data); + if (rv == SECSuccess) { + cert->subjectKeyID.data = + (unsigned char *)PORT_ArenaAlloc(cert->arena, tmpitem.len); + if (cert->subjectKeyID.data != NULL) { + PORT_Memcpy(cert->subjectKeyID.data, tmpitem.data, tmpitem.len); + cert->subjectKeyID.len = tmpitem.len; + cert->keyIDGenerated = PR_FALSE; + } + + PORT_Free(tmpitem.data); } - + /* if the cert doesn't have a key identifier extension, then generate one*/ - if ( cert->subjectKeyID.len == 0 ) { - /* - * pkix says that if the subjectKeyID is not present, then we should - * use the SHA-1 hash of the DER-encoded publicKeyInfo from the cert - */ - cert->subjectKeyID.data = (unsigned char *)PORT_ArenaAlloc(cert->arena, SHA1_LENGTH); - if ( cert->subjectKeyID.data != NULL ) { - rv = PK11_HashBuf(SEC_OID_SHA1,cert->subjectKeyID.data, - cert->derPublicKey.data, - cert->derPublicKey.len); - if ( rv == SECSuccess ) { - cert->subjectKeyID.len = SHA1_LENGTH; - } - } + if (cert->subjectKeyID.len == 0) { + /* + * pkix says that if the subjectKeyID is not present, then we should + * use the SHA-1 hash of the DER-encoded publicKeyInfo from the cert + */ + cert->subjectKeyID.data = + (unsigned char *)PORT_ArenaAlloc(cert->arena, SHA1_LENGTH); + if (cert->subjectKeyID.data != NULL) { + rv = PK11_HashBuf(SEC_OID_SHA1, cert->subjectKeyID.data, + cert->derPublicKey.data, cert->derPublicKey.len); + if (rv == SECSuccess) { + cert->subjectKeyID.len = SHA1_LENGTH; + } + } } - if ( cert->subjectKeyID.len == 0 ) { - return(SECFailure); + if (cert->subjectKeyID.len == 0) { + return (SECFailure); } - return(SECSuccess); - + return (SECSuccess); } static PRBool @@ -689,48 +656,49 @@ cert_IsRootCert(CERTCertificate *cert) /* it MUST be self-issued to be a root */ if (cert->derIssuer.len == 0 || - !SECITEM_ItemsAreEqual(&cert->derIssuer, &cert->derSubject)) - { - return PR_FALSE; + !SECITEM_ItemsAreEqual(&cert->derIssuer, &cert->derSubject)) { + return PR_FALSE; } /* check the authKeyID extension */ if (cert->authKeyID) { - /* authority key identifier is present */ - if (cert->authKeyID->keyID.len > 0) { - /* the keyIdentifier field is set, look for subjectKeyID */ - rv = CERT_FindSubjectKeyIDExtension(cert, &tmpitem); - if (rv == SECSuccess) { - PRBool match; - /* also present, they MUST match for it to be a root */ - match = SECITEM_ItemsAreEqual(&cert->authKeyID->keyID, - &tmpitem); - PORT_Free(tmpitem.data); - if (!match) return PR_FALSE; /* else fall through */ - } else { - /* the subject key ID is required when AKI is present */ - return PR_FALSE; - } - } - if (cert->authKeyID->authCertIssuer) { - SECItem *caName; - caName = (SECItem *)CERT_GetGeneralNameByType( - cert->authKeyID->authCertIssuer, - certDirectoryName, PR_TRUE); - if (caName) { - if (!SECITEM_ItemsAreEqual(&cert->derIssuer, caName)) { - return PR_FALSE; - } /* else fall through */ - } /* else ??? could not get general name as directory name? */ - } - if (cert->authKeyID->authCertSerialNumber.len > 0) { - if (!SECITEM_ItemsAreEqual(&cert->serialNumber, - &cert->authKeyID->authCertSerialNumber)) { - return PR_FALSE; - } /* else fall through */ - } - /* all of the AKI fields that were present passed the test */ - return PR_TRUE; + /* authority key identifier is present */ + if (cert->authKeyID->keyID.len > 0) { + /* the keyIdentifier field is set, look for subjectKeyID */ + rv = CERT_FindSubjectKeyIDExtension(cert, &tmpitem); + if (rv == SECSuccess) { + PRBool match; + /* also present, they MUST match for it to be a root */ + match = + SECITEM_ItemsAreEqual(&cert->authKeyID->keyID, &tmpitem); + PORT_Free(tmpitem.data); + if (!match) + return PR_FALSE; /* else fall through */ + } + else { + /* the subject key ID is required when AKI is present */ + return PR_FALSE; + } + } + if (cert->authKeyID->authCertIssuer) { + SECItem *caName; + caName = (SECItem *)CERT_GetGeneralNameByType( + cert->authKeyID->authCertIssuer, certDirectoryName, PR_TRUE); + if (caName) { + if (!SECITEM_ItemsAreEqual(&cert->derIssuer, caName)) { + return PR_FALSE; + } /* else fall through */ + } /* else ??? could not get general name as directory name? */ + } + if (cert->authKeyID->authCertSerialNumber.len > 0) { + if (!SECITEM_ItemsAreEqual( + &cert->serialNumber, + &cert->authKeyID->authCertSerialNumber)) { + return PR_FALSE; + } /* else fall through */ + } + /* all of the AKI fields that were present passed the test */ + return PR_TRUE; } /* else the AKI was not present, so this is a root */ return PR_TRUE; @@ -741,7 +709,7 @@ cert_IsRootCert(CERTCertificate *cert) */ CERTCertificate * CERT_DecodeDERCertificate(SECItem *derSignedCert, PRBool copyDER, - char *nickname) + char *nickname) { CERTCertificate *cert; PLArenaPool *arena; @@ -749,83 +717,85 @@ CERT_DecodeDERCertificate(SECItem *derSignedCert, PRBool copyDER, int rv; int len; char *tmpname; - + /* make a new arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( !arena ) { - return 0; + + if (!arena) { + return 0; } /* allocate the certificate structure */ cert = (CERTCertificate *)PORT_ArenaZAlloc(arena, sizeof(CERTCertificate)); - - if ( !cert ) { - goto loser; + + if (!cert) { + goto loser; } - + cert->arena = arena; - - if ( copyDER ) { - /* copy the DER data for the cert into this arena */ - data = (void *)PORT_ArenaAlloc(arena, derSignedCert->len); - if ( !data ) { - goto loser; - } - cert->derCert.data = (unsigned char *)data; - cert->derCert.len = derSignedCert->len; - PORT_Memcpy(data, derSignedCert->data, derSignedCert->len); - } else { - /* point to passed in DER data */ - cert->derCert = *derSignedCert; + + if (copyDER) { + /* copy the DER data for the cert into this arena */ + data = (void *)PORT_ArenaAlloc(arena, derSignedCert->len); + if (!data) { + goto loser; + } + cert->derCert.data = (unsigned char *)data; + cert->derCert.len = derSignedCert->len; + PORT_Memcpy(data, derSignedCert->data, derSignedCert->len); + } + else { + /* point to passed in DER data */ + cert->derCert = *derSignedCert; } /* decode the certificate info */ rv = SEC_QuickDERDecodeItem(arena, cert, SEC_SignedCertificateTemplate, - &cert->derCert); + &cert->derCert); - if ( rv ) { - goto loser; + if (rv) { + goto loser; } - if (cert_HasUnknownCriticalExten (cert->extensions) == PR_TRUE) { + if (cert_HasUnknownCriticalExten(cert->extensions) == PR_TRUE) { cert->options.bits.hasUnsupportedCriticalExt = PR_TRUE; } /* generate and save the database key for the cert */ rv = CERT_KeyFromIssuerAndSN(arena, &cert->derIssuer, &cert->serialNumber, - &cert->certKey); - if ( rv ) { - goto loser; + &cert->certKey); + if (rv) { + goto loser; } /* set the nickname */ - if ( nickname == NULL ) { - cert->nickname = NULL; - } else { - /* copy and install the nickname */ - len = PORT_Strlen(nickname) + 1; - cert->nickname = (char*)PORT_ArenaAlloc(arena, len); - if ( cert->nickname == NULL ) { - goto loser; - } + if (nickname == NULL) { + cert->nickname = NULL; + } + else { + /* copy and install the nickname */ + len = PORT_Strlen(nickname) + 1; + cert->nickname = (char *)PORT_ArenaAlloc(arena, len); + if (cert->nickname == NULL) { + goto loser; + } - PORT_Memcpy(cert->nickname, nickname, len); + PORT_Memcpy(cert->nickname, nickname, len); } /* set the email address */ cert->emailAddr = cert_GetCertificateEmailAddresses(cert); - + /* initialize the subjectKeyID */ rv = cert_GetKeyID(cert); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* initialize keyUsage */ rv = GetKeyUsage(cert); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* determine if this is a root cert */ @@ -833,46 +803,45 @@ CERT_DecodeDERCertificate(SECItem *derSignedCert, PRBool copyDER, /* initialize the certType */ rv = cert_GetCertType(cert); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } tmpname = CERT_NameToAscii(&cert->subject); - if ( tmpname != NULL ) { - cert->subjectName = PORT_ArenaStrdup(cert->arena, tmpname); - PORT_Free(tmpname); + if (tmpname != NULL) { + cert->subjectName = PORT_ArenaStrdup(cert->arena, tmpname); + PORT_Free(tmpname); } - + tmpname = CERT_NameToAscii(&cert->issuer); - if ( tmpname != NULL ) { - cert->issuerName = PORT_ArenaStrdup(cert->arena, tmpname); - PORT_Free(tmpname); + if (tmpname != NULL) { + cert->issuerName = PORT_ArenaStrdup(cert->arena, tmpname); + PORT_Free(tmpname); } - + cert->referenceCount = 1; cert->slot = NULL; cert->pkcs11ID = CK_INVALID_HANDLE; cert->dbnickname = NULL; - - return(cert); - + + return (cert); + loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(0); + + return (0); } CERTCertificate * __CERT_DecodeDERCertificate(SECItem *derSignedCert, PRBool copyDER, - char *nickname) + char *nickname) { return CERT_DecodeDERCertificate(derSignedCert, copyDER, nickname); } - CERTValidity * CERT_CreateValidity(PRTime notBefore, PRTime notAfter) { @@ -881,26 +850,28 @@ CERT_CreateValidity(PRTime notBefore, PRTime notAfter) PLArenaPool *arena; if (notBefore > notAfter) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( !arena ) { - return(0); + + if (!arena) { + return (0); } - - v = (CERTValidity*) PORT_ArenaZAlloc(arena, sizeof(CERTValidity)); + + v = (CERTValidity *)PORT_ArenaZAlloc(arena, sizeof(CERTValidity)); if (v) { - v->arena = arena; - rv = DER_EncodeTimeChoice(arena, &v->notBefore, notBefore); - if (rv) goto loser; - rv = DER_EncodeTimeChoice(arena, &v->notAfter, notAfter); - if (rv) goto loser; + v->arena = arena; + rv = DER_EncodeTimeChoice(arena, &v->notBefore, notBefore); + if (rv) + goto loser; + rv = DER_EncodeTimeChoice(arena, &v->notAfter, notAfter); + if (rv) + goto loser; } return v; - loser: +loser: CERT_DestroyValidity(v); return 0; } @@ -912,9 +883,10 @@ CERT_CopyValidity(PLArenaPool *arena, CERTValidity *to, CERTValidity *from) CERT_DestroyValidity(to); to->arena = arena; - + rv = SECITEM_CopyItem(arena, &to->notBefore, &from->notBefore); - if (rv) return rv; + if (rv) + return rv; rv = SECITEM_CopyItem(arena, &to->notAfter, &from->notAfter); return rv; } @@ -923,7 +895,7 @@ void CERT_DestroyValidity(CERTValidity *v) { if (v && v->arena) { - PORT_FreeArena(v->arena, PR_FALSE); + PORT_FreeArena(v->arena, PR_FALSE); } return; } @@ -934,20 +906,19 @@ CERT_DestroyValidity(CERTValidity *v) ** valid. The slop is designed to allow for some variance in the clocks ** of the machine checking the certificate. */ -#define PENDING_SLOP (24L*60L*60L) /* seconds per day */ -static PRInt32 pendingSlop = PENDING_SLOP; /* seconds */ +#define PENDING_SLOP (24L * 60L * 60L) /* seconds per day */ +static PRInt32 pendingSlop = PENDING_SLOP; /* seconds */ PRInt32 CERT_GetSlopTime(void) { - return pendingSlop; /* seconds */ + return pendingSlop; /* seconds */ } -SECStatus -CERT_SetSlopTime(PRInt32 slop) /* seconds */ +SECStatus CERT_SetSlopTime(PRInt32 slop) /* seconds */ { if (slop < 0) - return SECFailure; + return SECFailure; pendingSlop = slop; return SECSuccess; } @@ -961,20 +932,20 @@ CERT_GetCertTimes(const CERTCertificate *c, PRTime *notBefore, PRTime *notAfter) PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - + /* convert DER not-before time */ rv = DER_DecodeTimeChoice(notBefore, &c->validity.notBefore); if (rv) { - return(SECFailure); + return (SECFailure); } - + /* convert DER not-after time */ rv = DER_DecodeTimeChoice(notAfter, &c->validity.notAfter); if (rv) { - return(SECFailure); + return (SECFailure); } - return(SECSuccess); + return (SECSuccess); } /* @@ -989,77 +960,78 @@ CERT_CheckCertValidTimes(const CERTCertificate *c, PRTime t, if (!c) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - return(secCertTimeUndetermined); + return (secCertTimeUndetermined); } /* if cert is already marked OK, then don't bother to check */ - if ( allowOverride && c->timeOK ) { - return(secCertTimeValid); + if (allowOverride && c->timeOK) { + return (secCertTimeValid); } rv = CERT_GetCertTimes(c, ¬Before, ¬After); - + if (rv) { - return(secCertTimeExpired); /*XXX is this the right thing to do here?*/ + return (secCertTimeExpired); /*XXX is this the right thing to do here?*/ } - + LL_I2L(llPendingSlop, pendingSlop); /* convert to micro seconds */ LL_UI2L(tmp1, PR_USEC_PER_SEC); LL_MUL(llPendingSlop, llPendingSlop, tmp1); LL_SUB(notBefore, notBefore, llPendingSlop); - if ( LL_CMP( t, <, notBefore ) ) { - PORT_SetError(SEC_ERROR_EXPIRED_CERTIFICATE); - return(secCertTimeNotValidYet); + if (LL_CMP(t, <, notBefore)) { + PORT_SetError(SEC_ERROR_EXPIRED_CERTIFICATE); + return (secCertTimeNotValidYet); } - if ( LL_CMP( t, >, notAfter) ) { - PORT_SetError(SEC_ERROR_EXPIRED_CERTIFICATE); - return(secCertTimeExpired); + if (LL_CMP(t, >, notAfter)) { + PORT_SetError(SEC_ERROR_EXPIRED_CERTIFICATE); + return (secCertTimeExpired); } - return(secCertTimeValid); + return (secCertTimeValid); } SECStatus SEC_GetCrlTimes(CERTCrl *date, PRTime *notBefore, PRTime *notAfter) { int rv; - + /* convert DER not-before time */ rv = DER_DecodeTimeChoice(notBefore, &date->lastUpdate); if (rv) { - return(SECFailure); + return (SECFailure); } - + /* convert DER not-after time */ if (date->nextUpdate.data) { - rv = DER_DecodeTimeChoice(notAfter, &date->nextUpdate); - if (rv) { - return(SECFailure); - } + rv = DER_DecodeTimeChoice(notAfter, &date->nextUpdate); + if (rv) { + return (SECFailure); + } } else { - LL_I2L(*notAfter, 0L); + LL_I2L(*notAfter, 0L); } - return(SECSuccess); + return (SECSuccess); } /* These routines should probably be combined with the cert * routines using an common extraction routine. */ SECCertTimeValidity -SEC_CheckCrlTimes(CERTCrl *crl, PRTime t) { +SEC_CheckCrlTimes(CERTCrl *crl, PRTime t) +{ PRTime notBefore, notAfter, llPendingSlop, tmp1; SECStatus rv; if (!crl) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - return(secCertTimeUndetermined); + return (secCertTimeUndetermined); } rv = SEC_GetCrlTimes(crl, ¬Before, ¬After); - + if (rv) { - return(secCertTimeExpired); + return (secCertTimeExpired); } LL_I2L(llPendingSlop, pendingSlop); @@ -1067,155 +1039,158 @@ SEC_CheckCrlTimes(CERTCrl *crl, PRTime t) { LL_I2L(tmp1, PR_USEC_PER_SEC); LL_MUL(llPendingSlop, llPendingSlop, tmp1); LL_SUB(notBefore, notBefore, llPendingSlop); - if ( LL_CMP( t, <, notBefore ) ) { - PORT_SetError(SEC_ERROR_CRL_EXPIRED); - return(secCertTimeNotValidYet); + if (LL_CMP(t, <, notBefore)) { + PORT_SetError(SEC_ERROR_CRL_EXPIRED); + return (secCertTimeNotValidYet); } /* If next update is omitted and the test for notBefore passes, then we assume that the crl is up to date. */ - if ( LL_IS_ZERO(notAfter) ) { - return(secCertTimeValid); + if (LL_IS_ZERO(notAfter)) { + return (secCertTimeValid); } - if ( LL_CMP( t, >, notAfter) ) { - PORT_SetError(SEC_ERROR_CRL_EXPIRED); - return(secCertTimeExpired); + if (LL_CMP(t, >, notAfter)) { + PORT_SetError(SEC_ERROR_CRL_EXPIRED); + return (secCertTimeExpired); } - return(secCertTimeValid); + return (secCertTimeValid); } PRBool -SEC_CrlIsNewer(CERTCrl *inNew, CERTCrl *old) { +SEC_CrlIsNewer(CERTCrl *inNew, CERTCrl *old) +{ PRTime newNotBefore, newNotAfter; PRTime oldNotBefore, oldNotAfter; SECStatus rv; /* problems with the new CRL? reject it */ rv = SEC_GetCrlTimes(inNew, &newNotBefore, &newNotAfter); - if (rv) return PR_FALSE; + if (rv) + return PR_FALSE; /* problems with the old CRL? replace it */ rv = SEC_GetCrlTimes(old, &oldNotBefore, &oldNotAfter); - if (rv) return PR_TRUE; + if (rv) + return PR_TRUE; /* Question: what about the notAfter's? */ return ((PRBool)LL_CMP(oldNotBefore, <, newNotBefore)); } - + /* - * return required key usage and cert type based on cert usage + * return required key usage and cert type based on cert usage */ SECStatus -CERT_KeyUsageAndTypeForCertUsage(SECCertUsage usage, - PRBool ca, - unsigned int *retKeyUsage, - unsigned int *retCertType) +CERT_KeyUsageAndTypeForCertUsage(SECCertUsage usage, PRBool ca, + unsigned int *retKeyUsage, + unsigned int *retCertType) { unsigned int requiredKeyUsage = 0; unsigned int requiredCertType = 0; - - if ( ca ) { - switch ( usage ) { - case certUsageSSLServerWithStepUp: - requiredKeyUsage = KU_NS_GOVT_APPROVED | KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_SSL_CA; - break; - case certUsageSSLClient: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_SSL_CA; - break; - case certUsageSSLServer: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_SSL_CA; - break; - case certUsageSSLCA: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_SSL_CA; - break; - case certUsageEmailSigner: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_EMAIL_CA; - break; - case certUsageEmailRecipient: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_EMAIL_CA; - break; - case certUsageObjectSigner: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_OBJECT_SIGNING_CA; - break; - case certUsageAnyCA: - case certUsageVerifyCA: - case certUsageStatusResponder: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_OBJECT_SIGNING_CA | - NS_CERT_TYPE_EMAIL_CA | - NS_CERT_TYPE_SSL_CA; - break; - default: - PORT_Assert(0); - goto loser; - } - } else { - switch ( usage ) { - case certUsageSSLClient: - /* - * RFC 5280 lists digitalSignature and keyAgreement for - * id-kp-clientAuth. NSS does not support the *_fixed_dh and - * *_fixed_ecdh client certificate types. - */ - requiredKeyUsage = KU_DIGITAL_SIGNATURE; - requiredCertType = NS_CERT_TYPE_SSL_CLIENT; - break; - case certUsageSSLServer: - requiredKeyUsage = KU_KEY_AGREEMENT_OR_ENCIPHERMENT; - requiredCertType = NS_CERT_TYPE_SSL_SERVER; - break; - case certUsageSSLServerWithStepUp: - requiredKeyUsage = KU_KEY_AGREEMENT_OR_ENCIPHERMENT | - KU_NS_GOVT_APPROVED; - requiredCertType = NS_CERT_TYPE_SSL_SERVER; - break; - case certUsageSSLCA: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_SSL_CA; - break; - case certUsageEmailSigner: - requiredKeyUsage = KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION; - requiredCertType = NS_CERT_TYPE_EMAIL; - break; - case certUsageEmailRecipient: - requiredKeyUsage = KU_KEY_AGREEMENT_OR_ENCIPHERMENT; - requiredCertType = NS_CERT_TYPE_EMAIL; - break; - case certUsageObjectSigner: - /* RFC 5280 lists only digitalSignature for id-kp-codeSigning. */ - requiredKeyUsage = KU_DIGITAL_SIGNATURE; - requiredCertType = NS_CERT_TYPE_OBJECT_SIGNING; - break; - case certUsageStatusResponder: - requiredKeyUsage = KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION; - requiredCertType = EXT_KEY_USAGE_STATUS_RESPONDER; - break; - default: - PORT_Assert(0); - goto loser; - } + + if (ca) { + switch (usage) { + case certUsageSSLServerWithStepUp: + requiredKeyUsage = KU_NS_GOVT_APPROVED | KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_SSL_CA; + break; + case certUsageSSLClient: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_SSL_CA; + break; + case certUsageSSLServer: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_SSL_CA; + break; + case certUsageSSLCA: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_SSL_CA; + break; + case certUsageEmailSigner: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_EMAIL_CA; + break; + case certUsageEmailRecipient: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_EMAIL_CA; + break; + case certUsageObjectSigner: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_OBJECT_SIGNING_CA; + break; + case certUsageAnyCA: + case certUsageVerifyCA: + case certUsageStatusResponder: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_OBJECT_SIGNING_CA | + NS_CERT_TYPE_EMAIL_CA | NS_CERT_TYPE_SSL_CA; + break; + default: + PORT_Assert(0); + goto loser; + } + } + else { + switch (usage) { + case certUsageSSLClient: + /* + * RFC 5280 lists digitalSignature and keyAgreement for + * id-kp-clientAuth. NSS does not support the *_fixed_dh and + * *_fixed_ecdh client certificate types. + */ + requiredKeyUsage = KU_DIGITAL_SIGNATURE; + requiredCertType = NS_CERT_TYPE_SSL_CLIENT; + break; + case certUsageSSLServer: + requiredKeyUsage = KU_KEY_AGREEMENT_OR_ENCIPHERMENT; + requiredCertType = NS_CERT_TYPE_SSL_SERVER; + break; + case certUsageSSLServerWithStepUp: + requiredKeyUsage = + KU_KEY_AGREEMENT_OR_ENCIPHERMENT | KU_NS_GOVT_APPROVED; + requiredCertType = NS_CERT_TYPE_SSL_SERVER; + break; + case certUsageSSLCA: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_SSL_CA; + break; + case certUsageEmailSigner: + requiredKeyUsage = KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION; + requiredCertType = NS_CERT_TYPE_EMAIL; + break; + case certUsageEmailRecipient: + requiredKeyUsage = KU_KEY_AGREEMENT_OR_ENCIPHERMENT; + requiredCertType = NS_CERT_TYPE_EMAIL; + break; + case certUsageObjectSigner: + /* RFC 5280 lists only digitalSignature for id-kp-codeSigning. + */ + requiredKeyUsage = KU_DIGITAL_SIGNATURE; + requiredCertType = NS_CERT_TYPE_OBJECT_SIGNING; + break; + case certUsageStatusResponder: + requiredKeyUsage = KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION; + requiredCertType = EXT_KEY_USAGE_STATUS_RESPONDER; + break; + default: + PORT_Assert(0); + goto loser; + } } - if ( retKeyUsage != NULL ) { - *retKeyUsage = requiredKeyUsage; + if (retKeyUsage != NULL) { + *retKeyUsage = requiredKeyUsage; } - if ( retCertType != NULL ) { - *retCertType = requiredCertType; + if (retCertType != NULL) { + *retCertType = requiredCertType; } - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -1226,60 +1201,60 @@ CERT_CheckKeyUsage(CERTCertificate *cert, unsigned int requiredUsage) { if (!cert) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + return SECFailure; } /* choose between key agreement or key encipherment based on key * type in cert */ - if ( requiredUsage & KU_KEY_AGREEMENT_OR_ENCIPHERMENT ) { - KeyType keyType = CERT_GetCertKeyType(&cert->subjectPublicKeyInfo); - /* turn off the special bit */ - requiredUsage &= (~KU_KEY_AGREEMENT_OR_ENCIPHERMENT); + if (requiredUsage & KU_KEY_AGREEMENT_OR_ENCIPHERMENT) { + KeyType keyType = CERT_GetCertKeyType(&cert->subjectPublicKeyInfo); + /* turn off the special bit */ + requiredUsage &= (~KU_KEY_AGREEMENT_OR_ENCIPHERMENT); - switch (keyType) { - case rsaKey: - requiredUsage |= KU_KEY_ENCIPHERMENT; - break; - case dsaKey: - requiredUsage |= KU_DIGITAL_SIGNATURE; - break; - case dhKey: - requiredUsage |= KU_KEY_AGREEMENT; - break; - case ecKey: - /* Accept either signature or agreement. */ - if (!(cert->keyUsage & (KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))) - goto loser; - break; - default: - goto loser; - } + switch (keyType) { + case rsaKey: + requiredUsage |= KU_KEY_ENCIPHERMENT; + break; + case dsaKey: + requiredUsage |= KU_DIGITAL_SIGNATURE; + break; + case dhKey: + requiredUsage |= KU_KEY_AGREEMENT; + break; + case ecKey: + /* Accept either signature or agreement. */ + if (!(cert->keyUsage & + (KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))) + goto loser; + break; + default: + goto loser; + } } /* Allow either digital signature or non-repudiation */ - if ( requiredUsage & KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION ) { - /* turn off the special bit */ - requiredUsage &= (~KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION); + if (requiredUsage & KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION) { + /* turn off the special bit */ + requiredUsage &= (~KU_DIGITAL_SIGNATURE_OR_NON_REPUDIATION); if (!(cert->keyUsage & (KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION))) - goto loser; - } - - if ( (cert->keyUsage & requiredUsage) == requiredUsage ) - return SECSuccess; + goto loser; + } + + if ((cert->keyUsage & requiredUsage) == requiredUsage) + return SECSuccess; loser: PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); return SECFailure; } - CERTCertificate * CERT_DupCertificate(CERTCertificate *c) { if (c) { - NSSCertificate *tmp = STAN_GetNSSCertificate(c); - nssCertificate_AddRef(tmp); + NSSCertificate *tmp = STAN_GetNSSCertificate(c); + nssCertificate_AddRef(tmp); } return c; } @@ -1294,37 +1269,37 @@ void CERT_SetDefaultCertDB(CERTCertDBHandle *handle) { default_cert_db_handle = handle; - + return; } CERTCertDBHandle * CERT_GetDefaultCertDB(void) { - return(default_cert_db_handle); + return (default_cert_db_handle); } /* XXX this would probably be okay/better as an xp routine? */ static void sec_lower_string(char *s) { - if ( s == NULL ) { - return; + if (s == NULL) { + return; } - - while ( *s ) { - *s = PORT_Tolower(*s); - s++; + + while (*s) { + *s = PORT_Tolower(*s); + s++; } - + return; } static PRBool cert_IsIPAddr(const char *hn) { - PRBool isIPaddr = PR_FALSE; - PRNetAddr netAddr; + PRBool isIPaddr = PR_FALSE; + PRNetAddr netAddr; isIPaddr = (PR_SUCCESS == PR_StringToNetAddr(hn, &netAddr)); return isIPaddr; } @@ -1337,16 +1312,16 @@ SECStatus CERT_AddOKDomainName(CERTCertificate *cert, const char *hn) { CERTOKDomainName *domainOK; - int newNameLen; + int newNameLen; if (!hn || !(newNameLen = strlen(hn))) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } - domainOK = (CERTOKDomainName *)PORT_ArenaZAlloc(cert->arena, - (sizeof *domainOK) + newNameLen); - if (!domainOK) - return SECFailure; /* error code is already set. */ + domainOK = (CERTOKDomainName *)PORT_ArenaZAlloc( + cert->arena, (sizeof *domainOK) + newNameLen); + if (!domainOK) + return SECFailure; /* error code is already set. */ PORT_Strcpy(domainOK->name, hn); sec_lower_string(domainOK->name); @@ -1364,7 +1339,7 @@ CERT_AddOKDomainName(CERTCertificate *cert, const char *hn) ** This function may modify string cn, so caller must pass a modifiable copy. */ static SECStatus -cert_TestHostName(char * cn, const char * hn) +cert_TestHostName(char *cn, const char *hn) { static int useShellExp = -1; @@ -1372,169 +1347,179 @@ cert_TestHostName(char * cn, const char * hn) useShellExp = (NULL != PR_GetEnv("NSS_USE_SHEXP_IN_CERT_NAME")); } if (useShellExp) { - /* Backward compatible code, uses Shell Expressions (SHEXP). */ - int regvalid = PORT_RegExpValid(cn); - if (regvalid != NON_SXP) { - SECStatus rv; - /* cn is a regular expression, try to match the shexp */ - int match = PORT_RegExpCaseSearch(hn, cn); + /* Backward compatible code, uses Shell Expressions (SHEXP). */ + int regvalid = PORT_RegExpValid(cn); + if (regvalid != NON_SXP) { + SECStatus rv; + /* cn is a regular expression, try to match the shexp */ + int match = PORT_RegExpCaseSearch(hn, cn); - if ( match == 0 ) { - rv = SECSuccess; - } else { - PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); - rv = SECFailure; - } - return rv; - } - } else { - /* New approach conforms to RFC 6125. */ - char *wildcard = PORT_Strchr(cn, '*'); - char *firstcndot = PORT_Strchr(cn, '.'); - char *secondcndot = firstcndot ? PORT_Strchr(firstcndot+1, '.') : NULL; - char *firsthndot = PORT_Strchr(hn, '.'); - - /* For a cn pattern to be considered valid, the wildcard character... - * - may occur only in a DNS name with at least 3 components, and - * - may occur only as last character in the first component, and - * - may be preceded by additional characters, and - * - must not be preceded by an IDNA ACE prefix (xn--) - */ - if (wildcard && secondcndot && secondcndot[1] && firsthndot - && firstcndot - wildcard == 1 /* wildcard is last char in first component */ - && secondcndot - firstcndot > 1 /* second component is non-empty */ - && PORT_Strrchr(cn, '*') == wildcard /* only one wildcard in cn */ - && !PORT_Strncasecmp(cn, hn, wildcard - cn) - && !PORT_Strcasecmp(firstcndot, firsthndot) - /* If hn starts with xn--, then cn must start with wildcard */ - && (PORT_Strncasecmp(hn, "xn--", 4) || wildcard == cn)) { - /* valid wildcard pattern match */ - return SECSuccess; - } + if (match == 0) { + rv = SECSuccess; + } + else { + PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); + rv = SECFailure; + } + return rv; + } } - /* String cn has no wildcard or shell expression. - * Compare entire string hn with cert name. + else { + /* New approach conforms to RFC 6125. */ + char *wildcard = PORT_Strchr(cn, '*'); + char *firstcndot = PORT_Strchr(cn, '.'); + char *secondcndot = + firstcndot ? PORT_Strchr(firstcndot + 1, '.') : NULL; + char *firsthndot = PORT_Strchr(hn, '.'); + + /* For a cn pattern to be considered valid, the wildcard character... + * - may occur only in a DNS name with at least 3 components, and + * - may occur only as last character in the first component, and + * - may be preceded by additional characters, and + * - must not be preceded by an IDNA ACE prefix (xn--) + */ + if (wildcard && secondcndot && secondcndot[1] && firsthndot && + firstcndot - wildcard == + 1 /* wildcard is last char in first component */ + && secondcndot - firstcndot > 1 /* second component is non-empty */ + && PORT_Strrchr(cn, '*') == wildcard /* only one wildcard in cn */ + && !PORT_Strncasecmp(cn, hn, wildcard - cn) && + !PORT_Strcasecmp(firstcndot, firsthndot) + /* If hn starts with xn--, then cn must start with wildcard */ + && (PORT_Strncasecmp(hn, "xn--", 4) || wildcard == cn)) { + /* valid wildcard pattern match */ + return SECSuccess; + } + } + /* String cn has no wildcard or shell expression. + * Compare entire string hn with cert name. */ if (PORT_Strcasecmp(hn, cn) == 0) { - return SECSuccess; + return SECSuccess; } PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); return SECFailure; } - SECStatus cert_VerifySubjectAltName(const CERTCertificate *cert, const char *hn) { - PLArenaPool * arena = NULL; - CERTGeneralName * nameList = NULL; - CERTGeneralName * current; - char * cn; - int cnBufLen; - int DNSextCount = 0; - int IPextCount = 0; - PRBool isIPaddr = PR_FALSE; - SECStatus rv = SECFailure; - SECItem subAltName; - PRNetAddr netAddr; - char cnbuf[128]; + PLArenaPool *arena = NULL; + CERTGeneralName *nameList = NULL; + CERTGeneralName *current; + char *cn; + int cnBufLen; + int DNSextCount = 0; + int IPextCount = 0; + PRBool isIPaddr = PR_FALSE; + SECStatus rv = SECFailure; + SECItem subAltName; + PRNetAddr netAddr; + char cnbuf[128]; subAltName.data = NULL; - cn = cnbuf; + cn = cnbuf; cnBufLen = sizeof cnbuf; - rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, - &subAltName); + rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, + &subAltName); if (rv != SECSuccess) { - goto fail; + goto fail; } isIPaddr = (PR_SUCCESS == PR_StringToNetAddr(hn, &netAddr)); rv = SECFailure; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (!arena) - goto fail; + if (!arena) + goto fail; nameList = current = CERT_DecodeAltNameExtension(arena, &subAltName); if (!current) - goto fail; + goto fail; do { - switch (current->type) { - case certDNSName: - if (!isIPaddr) { - /* DNS name current->name.other.data is not null terminated. - ** so must copy it. - */ - int cnLen = current->name.other.len; - rv = CERT_RFC1485_EscapeAndQuote(cn, cnBufLen, - (char *)current->name.other.data, - cnLen); - if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_OUTPUT_LEN) { - cnBufLen = cnLen * 3 + 3; /* big enough for worst case */ - cn = (char *)PORT_ArenaAlloc(arena, cnBufLen); - if (!cn) - goto fail; - rv = CERT_RFC1485_EscapeAndQuote(cn, cnBufLen, - (char *)current->name.other.data, - cnLen); - } - if (rv == SECSuccess) - rv = cert_TestHostName(cn ,hn); - if (rv == SECSuccess) - goto finish; - } - DNSextCount++; - break; - case certIPAddress: - if (isIPaddr) { - int match = 0; - PRIPv6Addr v6Addr; - if (current->name.other.len == 4 && /* IP v4 address */ - netAddr.inet.family == PR_AF_INET) { - match = !memcmp(&netAddr.inet.ip, - current->name.other.data, 4); - } else if (current->name.other.len == 16 && /* IP v6 address */ - netAddr.ipv6.family == PR_AF_INET6) { - match = !memcmp(&netAddr.ipv6.ip, - current->name.other.data, 16); - } else if (current->name.other.len == 16 && /* IP v6 address */ - netAddr.inet.family == PR_AF_INET) { - /* convert netAddr to ipv6, then compare. */ - /* ipv4 must be in Network Byte Order on input. */ - PR_ConvertIPv4AddrToIPv6(netAddr.inet.ip, &v6Addr); - match = !memcmp(&v6Addr, current->name.other.data, 16); - } else if (current->name.other.len == 4 && /* IP v4 address */ - netAddr.inet.family == PR_AF_INET6) { - /* convert netAddr to ipv6, then compare. */ - PRUint32 ipv4 = (current->name.other.data[0] << 24) | - (current->name.other.data[1] << 16) | - (current->name.other.data[2] << 8) | - current->name.other.data[3]; - /* ipv4 must be in Network Byte Order on input. */ - PR_ConvertIPv4AddrToIPv6(PR_htonl(ipv4), &v6Addr); - match = !memcmp(&netAddr.ipv6.ip, &v6Addr, 16); - } - if (match) { - rv = SECSuccess; - goto finish; - } - } - IPextCount++; - break; - default: - break; - } - current = CERT_GetNextGeneralName(current); + switch (current->type) { + case certDNSName: + if (!isIPaddr) { + /* DNS name current->name.other.data is not null terminated. + ** so must copy it. + */ + int cnLen = current->name.other.len; + rv = CERT_RFC1485_EscapeAndQuote( + cn, cnBufLen, (char *)current->name.other.data, cnLen); + if (rv != SECSuccess && + PORT_GetError() == SEC_ERROR_OUTPUT_LEN) { + cnBufLen = + cnLen * 3 + 3; /* big enough for worst case */ + cn = (char *)PORT_ArenaAlloc(arena, cnBufLen); + if (!cn) + goto fail; + rv = CERT_RFC1485_EscapeAndQuote( + cn, cnBufLen, (char *)current->name.other.data, + cnLen); + } + if (rv == SECSuccess) + rv = cert_TestHostName(cn, hn); + if (rv == SECSuccess) + goto finish; + } + DNSextCount++; + break; + case certIPAddress: + if (isIPaddr) { + int match = 0; + PRIPv6Addr v6Addr; + if (current->name.other.len == 4 && /* IP v4 address */ + netAddr.inet.family == PR_AF_INET) { + match = !memcmp(&netAddr.inet.ip, + current->name.other.data, 4); + } + else if (current->name.other.len == + 16 && /* IP v6 address */ + netAddr.ipv6.family == PR_AF_INET6) { + match = !memcmp(&netAddr.ipv6.ip, + current->name.other.data, 16); + } + else if (current->name.other.len == + 16 && /* IP v6 address */ + netAddr.inet.family == PR_AF_INET) { + /* convert netAddr to ipv6, then compare. */ + /* ipv4 must be in Network Byte Order on input. */ + PR_ConvertIPv4AddrToIPv6(netAddr.inet.ip, &v6Addr); + match = !memcmp(&v6Addr, current->name.other.data, 16); + } + else if (current->name.other.len == 4 && /* IP v4 address */ + netAddr.inet.family == PR_AF_INET6) { + /* convert netAddr to ipv6, then compare. */ + PRUint32 ipv4 = (current->name.other.data[0] << 24) | + (current->name.other.data[1] << 16) | + (current->name.other.data[2] << 8) | + current->name.other.data[3]; + /* ipv4 must be in Network Byte Order on input. */ + PR_ConvertIPv4AddrToIPv6(PR_htonl(ipv4), &v6Addr); + match = !memcmp(&netAddr.ipv6.ip, &v6Addr, 16); + } + if (match) { + rv = SECSuccess; + goto finish; + } + } + IPextCount++; + break; + default: + break; + } + current = CERT_GetNextGeneralName(current); } while (current != nameList); fail: if (!(isIPaddr ? IPextCount : DNSextCount)) { - /* no relevant value in the extension was found. */ - PORT_SetError(SEC_ERROR_EXTENSION_NOT_FOUND); - } else { - PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); + /* no relevant value in the extension was found. */ + PORT_SetError(SEC_ERROR_EXTENSION_NOT_FOUND); + } + else { + PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); } rv = SECFailure; @@ -1542,11 +1527,11 @@ finish: /* Don't free nameList, it's part of the arena. */ if (arena) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } if (subAltName.data) { - SECITEM_FreeItem(&subAltName, PR_FALSE); + SECITEM_FreeItem(&subAltName, PR_FALSE); } return rv; @@ -1562,19 +1547,19 @@ finish: CERTGeneralName * cert_GetSubjectAltNameList(const CERTCertificate *cert, PLArenaPool *arena) { - CERTGeneralName * nameList = NULL; - SECStatus rv = SECFailure; - SECItem subAltName; + CERTGeneralName *nameList = NULL; + SECStatus rv = SECFailure; + SECItem subAltName; if (!cert || !arena) - return NULL; + return NULL; subAltName.data = NULL; - rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, + rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, &subAltName); if (rv != SECSuccess) - return NULL; + return NULL; nameList = CERT_DecodeAltNameExtension(arena, &subAltName); SECITEM_FreeItem(&subAltName, PR_FALSE); @@ -1584,21 +1569,21 @@ cert_GetSubjectAltNameList(const CERTCertificate *cert, PLArenaPool *arena) PRUint32 cert_CountDNSPatterns(CERTGeneralName *firstName) { - CERTGeneralName * current; + CERTGeneralName *current; PRUint32 count = 0; if (!firstName) - return 0; + return 0; current = firstName; do { switch (current->type) { - case certDNSName: - case certIPAddress: - ++count; - break; - default: - break; + case certDNSName: + case certIPAddress: + ++count; + break; + default: + break; } current = CERT_GetNextGeneralName(current); } while (current != firstName); @@ -1610,27 +1595,27 @@ cert_CountDNSPatterns(CERTGeneralName *firstName) #define INET6_ADDRSTRLEN 46 #endif -/* will fill nickNames, +/* will fill nickNames, * will allocate all data from nickNames->arena, * numberOfGeneralNames should have been obtained from cert_CountDNSPatterns, * will ensure the numberOfGeneralNames matches the number of output entries. */ SECStatus cert_GetDNSPatternsFromGeneralNames(CERTGeneralName *firstName, - PRUint32 numberOfGeneralNames, + PRUint32 numberOfGeneralNames, CERTCertNicknames *nickNames) { CERTGeneralName *currentInput; char **currentOutput; if (!firstName || !nickNames || !numberOfGeneralNames) - return SECFailure; + return SECFailure; nickNames->numnicknames = numberOfGeneralNames; - nickNames->nicknames = PORT_ArenaAlloc(nickNames->arena, - sizeof(char *) * numberOfGeneralNames); + nickNames->nicknames = PORT_ArenaAlloc( + nickNames->arena, sizeof(char *) * numberOfGeneralNames); if (!nickNames->nicknames) - return SECFailure; + return SECFailure; currentInput = firstName; currentOutput = nickNames->nicknames; @@ -1640,47 +1625,50 @@ cert_GetDNSPatternsFromGeneralNames(CERTGeneralName *firstName, PRNetAddr addr; if (numberOfGeneralNames < 1) { - /* internal consistency error */ - return SECFailure; + /* internal consistency error */ + return SECFailure; } switch (currentInput->type) { - case certDNSName: - /* DNS name currentInput->name.other.data is not null terminated. - ** so must copy it. - */ - cn = (char *)PORT_ArenaAlloc(nickNames->arena, - currentInput->name.other.len + 1); - if (!cn) - return SECFailure; - PORT_Memcpy(cn, currentInput->name.other.data, + case certDNSName: + /* DNS name currentInput->name.other.data is not null + *terminated. + ** so must copy it. + */ + cn = (char *)PORT_ArenaAlloc(nickNames->arena, + currentInput->name.other.len + 1); + if (!cn) + return SECFailure; + PORT_Memcpy(cn, currentInput->name.other.data, currentInput->name.other.len); - cn[currentInput->name.other.len] = 0; - break; - case certIPAddress: - if (currentInput->name.other.len == 4) { - addr.inet.family = PR_AF_INET; - memcpy(&addr.inet.ip, currentInput->name.other.data, - currentInput->name.other.len); - } else if (currentInput->name.other.len == 16) { - addr.ipv6.family = PR_AF_INET6; - memcpy(&addr.ipv6.ip, currentInput->name.other.data, - currentInput->name.other.len); - } - if (PR_NetAddrToString(&addr, ipbuf, sizeof(ipbuf)) == PR_FAILURE) - return SECFailure; - cn = PORT_ArenaStrdup(nickNames->arena, ipbuf); - if (!cn) - return SECFailure; - break; - default: - break; + cn[currentInput->name.other.len] = 0; + break; + case certIPAddress: + if (currentInput->name.other.len == 4) { + addr.inet.family = PR_AF_INET; + memcpy(&addr.inet.ip, currentInput->name.other.data, + currentInput->name.other.len); + } + else if (currentInput->name.other.len == 16) { + addr.ipv6.family = PR_AF_INET6; + memcpy(&addr.ipv6.ip, currentInput->name.other.data, + currentInput->name.other.len); + } + if (PR_NetAddrToString(&addr, ipbuf, sizeof(ipbuf)) == + PR_FAILURE) + return SECFailure; + cn = PORT_ArenaStrdup(nickNames->arena, ipbuf); + if (!cn) + return SECFailure; + break; + default: + break; } if (cn) { - *currentOutput = cn; - nickNames->totallen += PORT_Strlen(cn); - ++currentOutput; - --numberOfGeneralNames; + *currentOutput = cn; + nickNames->totallen += PORT_Strlen(cn); + ++currentOutput; + --numberOfGeneralNames; } currentInput = CERT_GetNextGeneralName(currentInput); } while (currentInput != firstName); @@ -1701,16 +1689,16 @@ CERT_GetValidDNSPatternsFromCert(CERTCertificate *cert) CERTCertNicknames *nickNames; PLArenaPool *arena; char *singleName; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (!arena) { return NULL; } - + nickNames = PORT_ArenaAlloc(arena, sizeof(CERTCertNicknames)); if (!nickNames) { - PORT_FreeArena(arena, PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } /* init the structure */ @@ -1722,40 +1710,41 @@ CERT_GetValidDNSPatternsFromCert(CERTCertificate *cert) generalNames = cert_GetSubjectAltNameList(cert, arena); if (generalNames) { - SECStatus rv_getnames = SECFailure; - PRUint32 numNames = cert_CountDNSPatterns(generalNames); + SECStatus rv_getnames = SECFailure; + PRUint32 numNames = cert_CountDNSPatterns(generalNames); - if (numNames) { - rv_getnames = cert_GetDNSPatternsFromGeneralNames(generalNames, - numNames, nickNames); - } - - /* if there were names, we'll exit now, either with success or failure */ - if (numNames) { - if (rv_getnames == SECSuccess) { - return nickNames; + if (numNames) { + rv_getnames = cert_GetDNSPatternsFromGeneralNames( + generalNames, numNames, nickNames); } - /* failure to produce output */ - PORT_FreeArena(arena, PR_FALSE); - return NULL; - } + /* if there were names, we'll exit now, either with success or failure + */ + if (numNames) { + if (rv_getnames == SECSuccess) { + return nickNames; + } + + /* failure to produce output */ + PORT_FreeArena(arena, PR_FALSE); + return NULL; + } } /* no SAN extension or no names found in extension */ singleName = CERT_GetCommonName(&cert->subject); if (singleName) { - nickNames->numnicknames = 1; - nickNames->nicknames = PORT_ArenaAlloc(arena, sizeof(char *)); - if (nickNames->nicknames) { - *nickNames->nicknames = PORT_ArenaStrdup(arena, singleName); - } - PORT_Free(singleName); + nickNames->numnicknames = 1; + nickNames->nicknames = PORT_ArenaAlloc(arena, sizeof(char *)); + if (nickNames->nicknames) { + *nickNames->nicknames = PORT_ArenaStrdup(arena, singleName); + } + PORT_Free(singleName); - /* Did we allocate both the buffer of pointers and the string? */ - if (nickNames->nicknames && *nickNames->nicknames) { - return nickNames; - } + /* Did we allocate both the buffer of pointers and the string? */ + if (nickNames->nicknames && *nickNames->nicknames) { + return nickNames; + } } PORT_FreeArena(arena, PR_FALSE); @@ -1769,20 +1758,20 @@ CERT_GetValidDNSPatternsFromCert(CERTCertificate *cert) SECStatus CERT_VerifyCertName(const CERTCertificate *cert, const char *hn) { - char * cn; + char *cn; SECStatus rv; CERTOKDomainName *domainOK; if (!hn || !strlen(hn)) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } /* if the name is one that the user has already approved, it's OK. */ for (domainOK = cert->domainOK; domainOK; domainOK = domainOK->next) { - if (0 == PORT_Strcasecmp(hn, domainOK->name)) { - return SECSuccess; - } + if (0 == PORT_Strcasecmp(hn, domainOK->name)) { + return SECSuccess; + } } /* Per RFC 2818, if the SubjectAltName extension is present, it must @@ -1790,24 +1779,27 @@ CERT_VerifyCertName(const CERTCertificate *cert, const char *hn) */ rv = cert_VerifySubjectAltName(cert, hn); if (rv == SECSuccess || PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) - return rv; + return rv; cn = CERT_GetCommonName(&cert->subject); - if ( cn ) { + if (cn) { PRBool isIPaddr = cert_IsIPAddr(hn); if (isIPaddr) { if (PORT_Strcasecmp(hn, cn) == 0) { - rv = SECSuccess; - } else { + rv = SECSuccess; + } + else { PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); rv = SECFailure; } - } else { + } + else { rv = cert_TestHostName(cn, hn); } - PORT_Free(cn); - } else - PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); + PORT_Free(cn); + } + else + PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); return rv; } @@ -1815,48 +1807,49 @@ PRBool CERT_CompareCerts(const CERTCertificate *c1, const CERTCertificate *c2) { SECComparison comp; - + comp = SECITEM_CompareItem(&c1->derCert, &c2->derCert); - if ( comp == SECEqual ) { /* certs are the same */ - return(PR_TRUE); - } else { - return(PR_FALSE); + if (comp == SECEqual) { /* certs are the same */ + return (PR_TRUE); + } + else { + return (PR_FALSE); } } static SECStatus -StringsEqual(char *s1, char *s2) { - if ( ( s1 == NULL ) || ( s2 == NULL ) ) { - if ( s1 != s2 ) { /* only one is null */ - return(SECFailure); - } - return(SECSuccess); /* both are null */ - } - - if ( PORT_Strcmp( s1, s2 ) != 0 ) { - return(SECFailure); /* not equal */ +StringsEqual(char *s1, char *s2) +{ + if ((s1 == NULL) || (s2 == NULL)) { + if (s1 != s2) { /* only one is null */ + return (SECFailure); + } + return (SECSuccess); /* both are null */ } - return(SECSuccess); /* strings are equal */ + if (PORT_Strcmp(s1, s2) != 0) { + return (SECFailure); /* not equal */ + } + + return (SECSuccess); /* strings are equal */ } - PRBool CERT_CompareCertsForRedirection(CERTCertificate *c1, CERTCertificate *c2) { SECComparison comp; char *c1str, *c2str; SECStatus eq; - + comp = SECITEM_CompareItem(&c1->derCert, &c2->derCert); - if ( comp == SECEqual ) { /* certs are the same */ - return(PR_TRUE); + if (comp == SECEqual) { /* certs are the same */ + return (PR_TRUE); } - + /* check if they are issued by the same CA */ comp = SECITEM_CompareItem(&c1->derIssuer, &c2->derIssuer); - if ( comp != SECEqual ) { /* different issuer */ - return(PR_FALSE); + if (comp != SECEqual) { /* different issuer */ + return (PR_FALSE); } /* check country name */ @@ -1865,8 +1858,8 @@ CERT_CompareCertsForRedirection(CERTCertificate *c1, CERTCertificate *c2) eq = StringsEqual(c1str, c2str); PORT_Free(c1str); PORT_Free(c2str); - if ( eq != SECSuccess ) { - return(PR_FALSE); + if (eq != SECSuccess) { + return (PR_FALSE); } /* check locality name */ @@ -1875,18 +1868,18 @@ CERT_CompareCertsForRedirection(CERTCertificate *c1, CERTCertificate *c2) eq = StringsEqual(c1str, c2str); PORT_Free(c1str); PORT_Free(c2str); - if ( eq != SECSuccess ) { - return(PR_FALSE); + if (eq != SECSuccess) { + return (PR_FALSE); } - + /* check state name */ c1str = CERT_GetStateName(&c1->subject); c2str = CERT_GetStateName(&c2->subject); eq = StringsEqual(c1str, c2str); PORT_Free(c1str); PORT_Free(c2str); - if ( eq != SECSuccess ) { - return(PR_FALSE); + if (eq != SECSuccess) { + return (PR_FALSE); } /* check org name */ @@ -1895,11 +1888,11 @@ CERT_CompareCertsForRedirection(CERTCertificate *c1, CERTCertificate *c2) eq = StringsEqual(c1str, c2str); PORT_Free(c1str); PORT_Free(c2str); - if ( eq != SECSuccess ) { - return(PR_FALSE); + if (eq != SECSuccess) { + return (PR_FALSE); } -#ifdef NOTDEF +#ifdef NOTDEF /* check orgUnit name */ /* * We need to revisit this and decide which fields should be allowed to be @@ -1910,46 +1903,44 @@ CERT_CompareCertsForRedirection(CERTCertificate *c1, CERTCertificate *c2) eq = StringsEqual(c1str, c2str); PORT_Free(c1str); PORT_Free(c2str); - if ( eq != SECSuccess ) { - return(PR_FALSE); + if (eq != SECSuccess) { + return (PR_FALSE); } #endif - return(PR_TRUE); /* all fields but common name are the same */ + return (PR_TRUE); /* all fields but common name are the same */ } - /* CERT_CertChainFromCert and CERT_DestroyCertificateList moved to certhigh.c */ - CERTIssuerAndSN * CERT_GetCertIssuerAndSN(PLArenaPool *arena, CERTCertificate *cert) { CERTIssuerAndSN *result; SECStatus rv; - if ( arena == NULL ) { - arena = cert->arena; + if (arena == NULL) { + arena = cert->arena; } - - result = (CERTIssuerAndSN*)PORT_ArenaZAlloc(arena, sizeof(*result)); + + result = (CERTIssuerAndSN *)PORT_ArenaZAlloc(arena, sizeof(*result)); if (result == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return NULL; } rv = SECITEM_CopyItem(arena, &result->derIssuer, &cert->derIssuer); if (rv != SECSuccess) - return NULL; + return NULL; rv = CERT_CopyName(arena, &result->issuer, &cert->issuer); if (rv != SECSuccess) - return NULL; + return NULL; rv = SECITEM_CopyItem(arena, &result->serialNumber, &cert->serialNumber); if (rv != SECSuccess) - return NULL; + return NULL; return result; } @@ -1962,85 +1953,88 @@ CERT_MakeCANickname(CERTCertificate *cert) char *nickname = NULL; int count; CERTCertificate *dummycert; - + firstname = CERT_GetCommonName(&cert->subject); - if ( firstname == NULL ) { - firstname = CERT_GetOrgUnitName(&cert->subject); + if (firstname == NULL) { + firstname = CERT_GetOrgUnitName(&cert->subject); } org = CERT_GetOrgName(&cert->issuer); if (org == NULL) { - org = CERT_GetDomainComponentName(&cert->issuer); - if (org == NULL) { - if (firstname) { - org = firstname; - firstname = NULL; - } else { - org = PORT_Strdup("Unknown CA"); - } - } + org = CERT_GetDomainComponentName(&cert->issuer); + if (org == NULL) { + if (firstname) { + org = firstname; + firstname = NULL; + } + else { + org = PORT_Strdup("Unknown CA"); + } + } } /* can only fail if PORT_Strdup fails, in which case * we're having memory problems. */ if (org == NULL) { - goto done; + goto done; } - count = 1; - while ( 1 ) { + while (1) { - if ( firstname ) { - if ( count == 1 ) { - nickname = PR_smprintf("%s - %s", firstname, org); - } else { - nickname = PR_smprintf("%s - %s #%d", firstname, org, count); - } - } else { - if ( count == 1 ) { - nickname = PR_smprintf("%s", org); - } else { - nickname = PR_smprintf("%s #%d", org, count); - } - } - if ( nickname == NULL ) { - goto done; - } + if (firstname) { + if (count == 1) { + nickname = PR_smprintf("%s - %s", firstname, org); + } + else { + nickname = PR_smprintf("%s - %s #%d", firstname, org, count); + } + } + else { + if (count == 1) { + nickname = PR_smprintf("%s", org); + } + else { + nickname = PR_smprintf("%s #%d", org, count); + } + } + if (nickname == NULL) { + goto done; + } - /* look up the nickname to make sure it isn't in use already */ - dummycert = CERT_FindCertByNickname(cert->dbhandle, nickname); + /* look up the nickname to make sure it isn't in use already */ + dummycert = CERT_FindCertByNickname(cert->dbhandle, nickname); - if ( dummycert == NULL ) { - goto done; - } - - /* found a cert, destroy it and loop */ - CERT_DestroyCertificate(dummycert); + if (dummycert == NULL) { + goto done; + } - /* free the nickname */ - PORT_Free(nickname); + /* found a cert, destroy it and loop */ + CERT_DestroyCertificate(dummycert); - count++; + /* free the nickname */ + PORT_Free(nickname); + + count++; } done: - if ( firstname ) { - PORT_Free(firstname); + if (firstname) { + PORT_Free(firstname); } - if ( org ) { - PORT_Free(org); + if (org) { + PORT_Free(org); } - - return(nickname); + + return (nickname); } /* CERT_Import_CAChain moved to certhigh.c */ void -CERT_DestroyCrl (CERTSignedCrl *crl) +CERT_DestroyCrl(CERTSignedCrl *crl) { - SEC_DestroyCrl (crl); + SEC_DestroyCrl(crl); } static int @@ -2048,9 +2042,9 @@ cert_Version(CERTCertificate *cert) { int version = 0; if (cert && cert->version.data && cert->version.len) { - version = DER_GetInteger(&cert->version); - if (version < 0) - version = 0; + version = DER_GetInteger(&cert->version); + if (version < 0) + version = 0; } return version; } @@ -2063,35 +2057,35 @@ cert_ComputeTrustOverrides(CERTCertificate *cert, unsigned int cType) rv = CERT_GetCertTrust(cert, &trust); - if (rv == SECSuccess && (trust.sslFlags | - trust.emailFlags | - trust.objectSigningFlags)) { + if (rv == SECSuccess && + (trust.sslFlags | trust.emailFlags | trust.objectSigningFlags)) { - if (trust.sslFlags & (CERTDB_TERMINAL_RECORD|CERTDB_TRUSTED)) - cType |= NS_CERT_TYPE_SSL_SERVER|NS_CERT_TYPE_SSL_CLIENT; - if (trust.sslFlags & (CERTDB_VALID_CA|CERTDB_TRUSTED_CA)) - cType |= NS_CERT_TYPE_SSL_CA; + if (trust.sslFlags & (CERTDB_TERMINAL_RECORD | CERTDB_TRUSTED)) + cType |= NS_CERT_TYPE_SSL_SERVER | NS_CERT_TYPE_SSL_CLIENT; + if (trust.sslFlags & (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) + cType |= NS_CERT_TYPE_SSL_CA; #if defined(CERTDB_NOT_TRUSTED) - if (trust.sslFlags & CERTDB_NOT_TRUSTED) - cType &= ~(NS_CERT_TYPE_SSL_SERVER|NS_CERT_TYPE_SSL_CLIENT| - NS_CERT_TYPE_SSL_CA); + if (trust.sslFlags & CERTDB_NOT_TRUSTED) + cType &= ~(NS_CERT_TYPE_SSL_SERVER | NS_CERT_TYPE_SSL_CLIENT | + NS_CERT_TYPE_SSL_CA); #endif - if (trust.emailFlags & (CERTDB_TERMINAL_RECORD|CERTDB_TRUSTED)) - cType |= NS_CERT_TYPE_EMAIL; - if (trust.emailFlags & (CERTDB_VALID_CA|CERTDB_TRUSTED_CA)) - cType |= NS_CERT_TYPE_EMAIL_CA; + if (trust.emailFlags & (CERTDB_TERMINAL_RECORD | CERTDB_TRUSTED)) + cType |= NS_CERT_TYPE_EMAIL; + if (trust.emailFlags & (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) + cType |= NS_CERT_TYPE_EMAIL_CA; #if defined(CERTDB_NOT_TRUSTED) - if (trust.emailFlags & CERTDB_NOT_TRUSTED) - cType &= ~(NS_CERT_TYPE_EMAIL|NS_CERT_TYPE_EMAIL_CA); + if (trust.emailFlags & CERTDB_NOT_TRUSTED) + cType &= ~(NS_CERT_TYPE_EMAIL | NS_CERT_TYPE_EMAIL_CA); #endif - if (trust.objectSigningFlags & (CERTDB_TERMINAL_RECORD|CERTDB_TRUSTED)) - cType |= NS_CERT_TYPE_OBJECT_SIGNING; - if (trust.objectSigningFlags & (CERTDB_VALID_CA|CERTDB_TRUSTED_CA)) - cType |= NS_CERT_TYPE_OBJECT_SIGNING_CA; + if (trust.objectSigningFlags & + (CERTDB_TERMINAL_RECORD | CERTDB_TRUSTED)) + cType |= NS_CERT_TYPE_OBJECT_SIGNING; + if (trust.objectSigningFlags & (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) + cType |= NS_CERT_TYPE_OBJECT_SIGNING_CA; #if defined(CERTDB_NOT_TRUSTED) - if (trust.objectSigningFlags & CERTDB_NOT_TRUSTED) - cType &= ~(NS_CERT_TYPE_OBJECT_SIGNING| - NS_CERT_TYPE_OBJECT_SIGNING_CA); + if (trust.objectSigningFlags & CERTDB_NOT_TRUSTED) + cType &= + ~(NS_CERT_TYPE_OBJECT_SIGNING | NS_CERT_TYPE_OBJECT_SIGNING_CA); #endif } return cType; @@ -2107,48 +2101,53 @@ CERT_IsCACert(CERTCertificate *cert, unsigned int *rettype) unsigned int cType = cert->nsCertType; PRBool ret = PR_FALSE; - if (cType & (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA | - NS_CERT_TYPE_OBJECT_SIGNING_CA)) { + if (cType & (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA | + NS_CERT_TYPE_OBJECT_SIGNING_CA)) { ret = PR_TRUE; - } else { - SECStatus rv; - CERTBasicConstraints constraints; + } + else { + SECStatus rv; + CERTBasicConstraints constraints; - rv = CERT_FindBasicConstraintExten(cert, &constraints); - if (rv == SECSuccess && constraints.isCA) { - ret = PR_TRUE; - cType |= (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA); - } + rv = CERT_FindBasicConstraintExten(cert, &constraints); + if (rv == SECSuccess && constraints.isCA) { + ret = PR_TRUE; + cType |= (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA); + } } /* finally check if it's an X.509 v1 root CA */ - if (!ret && + if (!ret && (cert->isRoot && cert_Version(cert) < SEC_CERTIFICATE_VERSION_3)) { - ret = PR_TRUE; - cType |= (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA); + ret = PR_TRUE; + cType |= (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA); } /* Now apply trust overrides, if any */ cType = cert_ComputeTrustOverrides(cert, cType); ret = (cType & (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA | - NS_CERT_TYPE_OBJECT_SIGNING_CA)) ? PR_TRUE : PR_FALSE; + NS_CERT_TYPE_OBJECT_SIGNING_CA)) + ? PR_TRUE + : PR_FALSE; if (rettype != NULL) { - *rettype = cType; + *rettype = cType; } return ret; } PRBool -CERT_IsCADERCert(SECItem *derCert, unsigned int *type) { +CERT_IsCADERCert(SECItem *derCert, unsigned int *type) +{ CERTCertificate *cert; PRBool isCA; /* This is okay -- only looks at extensions */ cert = CERT_DecodeDERCertificate(derCert, PR_FALSE, NULL); - if (cert == NULL) return PR_FALSE; + if (cert == NULL) + return PR_FALSE; - isCA = CERT_IsCACert(cert,type); - CERT_DestroyCertificate (cert); + isCA = CERT_IsCACert(cert, type); + CERT_DestroyCertificate(cert); return isCA; } @@ -2160,51 +2159,51 @@ CERT_IsRootDERCert(SECItem *derCert) /* This is okay -- only looks at extensions */ cert = CERT_DecodeDERCertificate(derCert, PR_FALSE, NULL); - if (cert == NULL) return PR_FALSE; + if (cert == NULL) + return PR_FALSE; isRoot = cert->isRoot; - CERT_DestroyCertificate (cert); + CERT_DestroyCertificate(cert); return isRoot; } CERTCompareValidityStatus -CERT_CompareValidityTimes(CERTValidity* val_a, CERTValidity* val_b) +CERT_CompareValidityTimes(CERTValidity *val_a, CERTValidity *val_b) { PRTime notBeforeA, notBeforeB, notAfterA, notAfterB; - if (!val_a || !val_b) - { + if (!val_a || !val_b) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return certValidityUndetermined; } - if ( SECSuccess != DER_DecodeTimeChoice(¬BeforeA, &val_a->notBefore) || - SECSuccess != DER_DecodeTimeChoice(¬BeforeB, &val_b->notBefore) || - SECSuccess != DER_DecodeTimeChoice(¬AfterA, &val_a->notAfter) || - SECSuccess != DER_DecodeTimeChoice(¬AfterB, &val_b->notAfter) ) { + if (SECSuccess != DER_DecodeTimeChoice(¬BeforeA, &val_a->notBefore) || + SECSuccess != DER_DecodeTimeChoice(¬BeforeB, &val_b->notBefore) || + SECSuccess != DER_DecodeTimeChoice(¬AfterA, &val_a->notAfter) || + SECSuccess != DER_DecodeTimeChoice(¬AfterB, &val_b->notAfter)) { return certValidityUndetermined; } /* sanity check */ - if (LL_CMP(notBeforeA,>,notAfterA) || LL_CMP(notBeforeB,>,notAfterB)) { + if (LL_CMP(notBeforeA, >, notAfterA) || LL_CMP(notBeforeB, >, notAfterB)) { PORT_SetError(SEC_ERROR_INVALID_TIME); return certValidityUndetermined; } - if (LL_CMP(notAfterA,!=,notAfterB)) { + if (LL_CMP(notAfterA, !=, notAfterB)) { /* one cert validity goes farther into the future, select it */ - return LL_CMP(notAfterA,<,notAfterB) ? - certValidityChooseB : certValidityChooseA; + return LL_CMP(notAfterA, <, notAfterB) ? certValidityChooseB + : certValidityChooseA; } /* the two certs have the same expiration date */ - PORT_Assert(LL_CMP(notAfterA, == , notAfterB)); + PORT_Assert(LL_CMP(notAfterA, ==, notAfterB)); /* do they also have the same start date ? */ - if (LL_CMP(notBeforeA,==,notBeforeB)) { - return certValidityEqual; + if (LL_CMP(notBeforeA, ==, notBeforeB)) { + return certValidityEqual; } /* choose cert with the later start date */ - return LL_CMP(notBeforeA,<,notBeforeB) ? - certValidityChooseB : certValidityChooseA; + return LL_CMP(notBeforeA, <, notBeforeB) ? certValidityChooseB + : certValidityChooseA; } /* @@ -2216,52 +2215,53 @@ CERT_IsNewer(CERTCertificate *certa, CERTCertificate *certb) PRTime notBeforeA, notAfterA, notBeforeB, notAfterB, now; SECStatus rv; PRBool newerbefore, newerafter; - + rv = CERT_GetCertTimes(certa, ¬BeforeA, ¬AfterA); - if ( rv != SECSuccess ) { - return(PR_FALSE); + if (rv != SECSuccess) { + return (PR_FALSE); } - + rv = CERT_GetCertTimes(certb, ¬BeforeB, ¬AfterB); - if ( rv != SECSuccess ) { - return(PR_TRUE); + if (rv != SECSuccess) { + return (PR_TRUE); } newerbefore = PR_FALSE; - if ( LL_CMP(notBeforeA, >, notBeforeB) ) { - newerbefore = PR_TRUE; + if (LL_CMP(notBeforeA, >, notBeforeB)) { + newerbefore = PR_TRUE; } newerafter = PR_FALSE; - if ( LL_CMP(notAfterA, >, notAfterB) ) { - newerafter = PR_TRUE; + if (LL_CMP(notAfterA, >, notAfterB)) { + newerafter = PR_TRUE; } - - if ( newerbefore && newerafter ) { - return(PR_TRUE); + + if (newerbefore && newerafter) { + return (PR_TRUE); } - - if ( ( !newerbefore ) && ( !newerafter ) ) { - return(PR_FALSE); + + if ((!newerbefore) && (!newerafter)) { + return (PR_FALSE); } /* get current time */ now = PR_Now(); - if ( newerbefore ) { - /* cert A was issued after cert B, but expires sooner */ - /* if A is expired, then pick B */ - if ( LL_CMP(notAfterA, <, now ) ) { - return(PR_FALSE); - } - return(PR_TRUE); - } 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); + 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); } } @@ -2269,17 +2269,17 @@ void CERT_DestroyCertArray(CERTCertificate **certs, unsigned int ncerts) { unsigned int i; - - if ( certs ) { - for ( i = 0; i < ncerts; i++ ) { - if ( certs[i] ) { - CERT_DestroyCertificate(certs[i]); - } - } - PORT_Free(certs); + if (certs) { + for (i = 0; i < ncerts; i++) { + if (certs[i]) { + CERT_DestroyCertificate(certs[i]); + } + } + + PORT_Free(certs); } - + return; } @@ -2289,23 +2289,23 @@ CERT_FixupEmailAddr(const char *emailAddr) char *retaddr; char *str; - if ( emailAddr == NULL ) { - return(NULL); + if (emailAddr == NULL) { + return (NULL); } - + /* copy the string */ str = retaddr = PORT_Strdup(emailAddr); - if ( str == NULL ) { - return(NULL); + if (str == NULL) { + return (NULL); } - + /* make it lower case */ - while ( *str ) { - *str = tolower( *str ); - str++; + while (*str) { + *str = tolower(*str); + str++; } - - return(retaddr); + + return (retaddr); } /* @@ -2318,67 +2318,68 @@ CERT_DecodeTrustString(CERTCertTrust *trust, const char *trusts) unsigned int *pflags; if (!trust) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } trust->sslFlags = 0; trust->emailFlags = 0; trust->objectSigningFlags = 0; if (!trusts) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } pflags = &trust->sslFlags; - for (i=0; i < PORT_Strlen(trusts); i++) { - switch (trusts[i]) { - case 'p': - *pflags = *pflags | CERTDB_TERMINAL_RECORD; - break; + for (i = 0; i < PORT_Strlen(trusts); i++) { + switch (trusts[i]) { + case 'p': + *pflags = *pflags | CERTDB_TERMINAL_RECORD; + break; - case 'P': - *pflags = *pflags | CERTDB_TRUSTED | CERTDB_TERMINAL_RECORD; - break; + case 'P': + *pflags = *pflags | CERTDB_TRUSTED | CERTDB_TERMINAL_RECORD; + break; - case 'w': - *pflags = *pflags | CERTDB_SEND_WARN; - break; + case 'w': + *pflags = *pflags | CERTDB_SEND_WARN; + break; - case 'c': - *pflags = *pflags | CERTDB_VALID_CA; - break; + case 'c': + *pflags = *pflags | CERTDB_VALID_CA; + break; - case 'T': - *pflags = *pflags | CERTDB_TRUSTED_CLIENT_CA | CERTDB_VALID_CA; - break; + case 'T': + *pflags = *pflags | CERTDB_TRUSTED_CLIENT_CA | CERTDB_VALID_CA; + break; - case 'C' : - *pflags = *pflags | CERTDB_TRUSTED_CA | CERTDB_VALID_CA; - break; + case 'C': + *pflags = *pflags | CERTDB_TRUSTED_CA | CERTDB_VALID_CA; + break; - case 'u': - *pflags = *pflags | CERTDB_USER; - break; + case 'u': + *pflags = *pflags | CERTDB_USER; + break; - case 'i': - *pflags = *pflags | CERTDB_INVISIBLE_CA; - break; - case 'g': - *pflags = *pflags | CERTDB_GOVT_APPROVED_CA; - break; + case 'i': + *pflags = *pflags | CERTDB_INVISIBLE_CA; + break; + case 'g': + *pflags = *pflags | CERTDB_GOVT_APPROVED_CA; + break; - case ',': - if ( pflags == &trust->sslFlags ) { - pflags = &trust->emailFlags; - } else { - pflags = &trust->objectSigningFlags; - } - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } + case ',': + if (pflags == &trust->sslFlags) { + pflags = &trust->emailFlags; + } + else { + pflags = &trust->objectSigningFlags; + } + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } } return SECSuccess; @@ -2388,26 +2389,25 @@ static void EncodeFlags(char *trusts, unsigned int flags) { if (flags & CERTDB_VALID_CA) - if (!(flags & CERTDB_TRUSTED_CA) && - !(flags & CERTDB_TRUSTED_CLIENT_CA)) - PORT_Strcat(trusts, "c"); + if (!(flags & CERTDB_TRUSTED_CA) && !(flags & CERTDB_TRUSTED_CLIENT_CA)) + PORT_Strcat(trusts, "c"); if (flags & CERTDB_TERMINAL_RECORD) - if (!(flags & CERTDB_TRUSTED)) - PORT_Strcat(trusts, "p"); + if (!(flags & CERTDB_TRUSTED)) + PORT_Strcat(trusts, "p"); if (flags & CERTDB_TRUSTED_CA) - PORT_Strcat(trusts, "C"); + PORT_Strcat(trusts, "C"); if (flags & CERTDB_TRUSTED_CLIENT_CA) - PORT_Strcat(trusts, "T"); + PORT_Strcat(trusts, "T"); if (flags & CERTDB_TRUSTED) - PORT_Strcat(trusts, "P"); + PORT_Strcat(trusts, "P"); if (flags & CERTDB_USER) - PORT_Strcat(trusts, "u"); + PORT_Strcat(trusts, "u"); if (flags & CERTDB_SEND_WARN) - PORT_Strcat(trusts, "w"); + PORT_Strcat(trusts, "w"); if (flags & CERTDB_INVISIBLE_CA) - PORT_Strcat(trusts, "I"); + PORT_Strcat(trusts, "I"); if (flags & CERTDB_GOVT_APPROVED_CA) - PORT_Strcat(trusts, "G"); + PORT_Strcat(trusts, "G"); return; } @@ -2419,96 +2419,95 @@ CERT_EncodeTrustString(CERTCertTrust *trust) char tmpTrustSigning[32]; char *retstr = NULL; - if ( trust ) { - tmpTrustSSL[0] = '\0'; - tmpTrustEmail[0] = '\0'; - tmpTrustSigning[0] = '\0'; - - EncodeFlags(tmpTrustSSL, trust->sslFlags); - EncodeFlags(tmpTrustEmail, trust->emailFlags); - EncodeFlags(tmpTrustSigning, trust->objectSigningFlags); - - retstr = PR_smprintf("%s,%s,%s", tmpTrustSSL, tmpTrustEmail, - tmpTrustSigning); + if (trust) { + tmpTrustSSL[0] = '\0'; + tmpTrustEmail[0] = '\0'; + tmpTrustSigning[0] = '\0'; + + EncodeFlags(tmpTrustSSL, trust->sslFlags); + EncodeFlags(tmpTrustEmail, trust->emailFlags); + EncodeFlags(tmpTrustSigning, trust->objectSigningFlags); + + retstr = PR_smprintf("%s,%s,%s", tmpTrustSSL, tmpTrustEmail, + tmpTrustSigning); } - - return(retstr); + + return (retstr); } SECStatus CERT_ImportCerts(CERTCertDBHandle *certdb, SECCertUsage usage, - unsigned int ncerts, SECItem **derCerts, - CERTCertificate ***retCerts, PRBool keepCerts, - PRBool caOnly, char *nickname) + unsigned int ncerts, SECItem **derCerts, + CERTCertificate ***retCerts, PRBool keepCerts, PRBool caOnly, + char *nickname) { unsigned int i; CERTCertificate **certs = NULL; unsigned int fcerts = 0; - if ( ncerts ) { - certs = PORT_ZNewArray(CERTCertificate*, ncerts); - if ( certs == NULL ) { - return(SECFailure); - } - - /* decode all of the certs into the temporary DB */ - for ( i = 0, fcerts= 0; i < ncerts; i++) { - certs[fcerts] = CERT_NewTempCertificate(certdb, - derCerts[i], - NULL, - PR_FALSE, - PR_TRUE); - if (certs[fcerts]) { - SECItem subjKeyID = {siBuffer, NULL, 0}; - if (CERT_FindSubjectKeyIDExtension(certs[fcerts], - &subjKeyID) == SECSuccess) { - if (subjKeyID.data) { - cert_AddSubjectKeyIDMapping(&subjKeyID, certs[fcerts]); - } - SECITEM_FreeItem(&subjKeyID, PR_FALSE); - } - fcerts++; - } - } + if (ncerts) { + certs = PORT_ZNewArray(CERTCertificate *, ncerts); + if (certs == NULL) { + return (SECFailure); + } - if ( keepCerts ) { - for ( i = 0; i < fcerts; i++ ) { - char* canickname = NULL; + /* decode all of the certs into the temporary DB */ + for (i = 0, fcerts = 0; i < ncerts; i++) { + certs[fcerts] = CERT_NewTempCertificate(certdb, derCerts[i], NULL, + PR_FALSE, PR_TRUE); + if (certs[fcerts]) { + SECItem subjKeyID = { siBuffer, NULL, 0 }; + if (CERT_FindSubjectKeyIDExtension(certs[fcerts], &subjKeyID) == + SECSuccess) { + if (subjKeyID.data) { + cert_AddSubjectKeyIDMapping(&subjKeyID, certs[fcerts]); + } + SECITEM_FreeItem(&subjKeyID, PR_FALSE); + } + fcerts++; + } + } + + if (keepCerts) { + for (i = 0; i < fcerts; i++) { + char *canickname = NULL; PRBool isCA; - SECKEY_UpdateCertPQG(certs[i]); - + SECKEY_UpdateCertPQG(certs[i]); + isCA = CERT_IsCACert(certs[i], NULL); - if ( isCA ) { + if (isCA) { canickname = CERT_MakeCANickname(certs[i]); } - if(isCA && (fcerts > 1)) { - /* if we are importing only a single cert and specifying - * a nickname, we want to use that nickname if it a CA, - * otherwise if there are more than one cert, we don't - * know which cert it belongs to. But we still may try + if (isCA && (fcerts > 1)) { + /* if we are importing only a single cert and specifying + * a nickname, we want to use that nickname if it a CA, + * otherwise if there are more than one cert, we don't + * know which cert it belongs to. But we still may try * the individual canickname from the cert itself. - */ + */ /* Bug 1192442 - propagate errors from these calls. */ - (void)CERT_AddTempCertToPerm(certs[i], canickname, NULL); - } else { - (void)CERT_AddTempCertToPerm(certs[i], - nickname?nickname:canickname, NULL); - } + (void)CERT_AddTempCertToPerm(certs[i], canickname, NULL); + } + else { + (void)CERT_AddTempCertToPerm( + certs[i], nickname ? nickname : canickname, NULL); + } PORT_Free(canickname); - /* don't care if it fails - keep going */ - } - } + /* don't care if it fails - keep going */ + } + } } - if ( retCerts ) { - *retCerts = certs; - } else { - if (certs) { - CERT_DestroyCertArray(certs, fcerts); - } + if (retCerts) { + *retCerts = certs; + } + else { + if (certs) { + CERT_DestroyCertArray(certs, fcerts); + } } return (fcerts || !ncerts) ? SECSuccess : SECFailure; @@ -2523,29 +2522,29 @@ CERT_NewCertList(void) { PLArenaPool *arena = NULL; CERTCertList *ret = NULL; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } - + ret = (CERTCertList *)PORT_ArenaZAlloc(arena, sizeof(CERTCertList)); - if ( ret == NULL ) { - goto loser; + if (ret == NULL) { + goto loser; } - + ret->arena = arena; - + PR_INIT_CLIST(&ret->list); - - return(ret); + + return (ret); loser: - if ( arena != NULL ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena != NULL) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } void @@ -2553,14 +2552,14 @@ CERT_DestroyCertList(CERTCertList *certs) { PRCList *node; - while( !PR_CLIST_IS_EMPTY(&certs->list) ) { - node = PR_LIST_HEAD(&certs->list); - CERT_DestroyCertificate(((CERTCertListNode *)node)->cert); - PR_REMOVE_LINK(node); + while (!PR_CLIST_IS_EMPTY(&certs->list)) { + node = PR_LIST_HEAD(&certs->list); + CERT_DestroyCertificate(((CERTCertListNode *)node)->cert); + PR_REMOVE_LINK(node); } - + PORT_FreeArena(certs->arena, PR_FALSE); - + return; } @@ -2572,27 +2571,26 @@ CERT_RemoveCertListNode(CERTCertListNode *node) return; } - SECStatus -CERT_AddCertToListTailWithData(CERTCertList *certs, - CERTCertificate *cert, void *appData) +CERT_AddCertToListTailWithData(CERTCertList *certs, CERTCertificate *cert, + void *appData) { CERTCertListNode *node; - + node = (CERTCertListNode *)PORT_ArenaZAlloc(certs->arena, - sizeof(CERTCertListNode)); - if ( node == NULL ) { - goto loser; + sizeof(CERTCertListNode)); + if (node == NULL) { + goto loser; } - + PR_INSERT_BEFORE(&node->links, &certs->list); /* certs->count++; */ node->cert = cert; node->appData = appData; - return(SECSuccess); - + return (SECSuccess); + loser: - return(SECFailure); + return (SECFailure); } SECStatus @@ -2602,30 +2600,31 @@ CERT_AddCertToListTail(CERTCertList *certs, CERTCertificate *cert) } SECStatus -CERT_AddCertToListHeadWithData(CERTCertList *certs, - CERTCertificate *cert, void *appData) +CERT_AddCertToListHeadWithData(CERTCertList *certs, CERTCertificate *cert, + void *appData) { CERTCertListNode *node; CERTCertListNode *head; - + head = CERT_LIST_HEAD(certs); - if (head == NULL) return CERT_AddCertToListTail(certs,cert); + if (head == NULL) + return CERT_AddCertToListTail(certs, cert); node = (CERTCertListNode *)PORT_ArenaZAlloc(certs->arena, - sizeof(CERTCertListNode)); - if ( node == NULL ) { - goto loser; + sizeof(CERTCertListNode)); + if (node == NULL) { + goto loser; } - + PR_INSERT_BEFORE(&node->links, &head->links); /* certs->count++; */ node->cert = cert; node->appData = appData; - return(SECSuccess); - + return (SECSuccess); + loser: - return(SECFailure); + return (SECFailure); } SECStatus @@ -2639,9 +2638,7 @@ CERT_AddCertToListHead(CERTCertList *certs, CERTCertificate *cert) * Not valid certs are considered older than valid certs. */ PRBool -CERT_SortCBValidity(CERTCertificate *certa, - CERTCertificate *certb, - void *arg) +CERT_SortCBValidity(CERTCertificate *certa, CERTCertificate *certb, void *arg) { PRTime sorttime; PRTime notBeforeA, notAfterA, notBeforeB, notAfterB; @@ -2650,113 +2647,111 @@ CERT_SortCBValidity(CERTCertificate *certa, PRBool aNotValid = PR_FALSE, bNotValid = PR_FALSE; sorttime = *(PRTime *)arg; - + rv = CERT_GetCertTimes(certa, ¬BeforeA, ¬AfterA); - if ( rv != SECSuccess ) { - return(PR_FALSE); + if (rv != SECSuccess) { + return (PR_FALSE); } - + rv = CERT_GetCertTimes(certb, ¬BeforeB, ¬AfterB); - if ( rv != SECSuccess ) { - return(PR_TRUE); + if (rv != SECSuccess) { + return (PR_TRUE); } newerbefore = PR_FALSE; - if ( LL_CMP(notBeforeA, >, notBeforeB) ) { - newerbefore = PR_TRUE; + if (LL_CMP(notBeforeA, >, notBeforeB)) { + newerbefore = PR_TRUE; } newerafter = PR_FALSE; - if ( LL_CMP(notAfterA, >, notAfterB) ) { - newerafter = PR_TRUE; + if (LL_CMP(notAfterA, >, notAfterB)) { + newerafter = PR_TRUE; } /* check if A is valid at sorttime */ - if ( CERT_CheckCertValidTimes(certa, sorttime, PR_FALSE) - != secCertTimeValid ) { - aNotValid = PR_TRUE; + if (CERT_CheckCertValidTimes(certa, sorttime, PR_FALSE) != + secCertTimeValid) { + aNotValid = PR_TRUE; } /* check if B is valid at sorttime */ - if ( CERT_CheckCertValidTimes(certb, sorttime, PR_FALSE) - != secCertTimeValid ) { - bNotValid = PR_TRUE; + if (CERT_CheckCertValidTimes(certb, sorttime, PR_FALSE) != + secCertTimeValid) { + bNotValid = PR_TRUE; } /* a is valid, b is not */ - if ( bNotValid && ( ! aNotValid ) ) { - return(PR_TRUE); + if (bNotValid && (!aNotValid)) { + return (PR_TRUE); } /* b is valid, a is not */ - if ( aNotValid && ( ! bNotValid ) ) { - return(PR_FALSE); - } - - /* a and b are either valid or not valid */ - if ( newerbefore && newerafter ) { - return(PR_TRUE); - } - - if ( ( !newerbefore ) && ( !newerafter ) ) { - return(PR_FALSE); + if (aNotValid && (!bNotValid)) { + return (PR_FALSE); } - if ( newerbefore ) { - /* cert A was issued after cert B, but expires sooner */ - return(PR_TRUE); - } else { - /* cert B was issued after cert A, but expires sooner */ - return(PR_FALSE); + /* a and b are either valid or not valid */ + if (newerbefore && newerafter) { + return (PR_TRUE); + } + + if ((!newerbefore) && (!newerafter)) { + return (PR_FALSE); + } + + if (newerbefore) { + /* cert A was issued after cert B, but expires sooner */ + return (PR_TRUE); + } + else { + /* cert B was issued after cert A, but expires sooner */ + return (PR_FALSE); } } - SECStatus -CERT_AddCertToListSorted(CERTCertList *certs, - CERTCertificate *cert, - CERTSortCallback f, - void *arg) +CERT_AddCertToListSorted(CERTCertList *certs, CERTCertificate *cert, + CERTSortCallback f, void *arg) { CERTCertListNode *node; CERTCertListNode *head; PRBool ret; - + node = (CERTCertListNode *)PORT_ArenaZAlloc(certs->arena, - sizeof(CERTCertListNode)); - if ( node == NULL ) { - goto loser; + sizeof(CERTCertListNode)); + if (node == NULL) { + goto loser; } - + head = CERT_LIST_HEAD(certs); - - while ( !CERT_LIST_END(head, certs) ) { - /* if cert is already in the list, then don't add it again */ - if ( cert == head->cert ) { - /*XXX*/ - /* don't keep a reference */ - CERT_DestroyCertificate(cert); - goto done; - } - - ret = (* f)(cert, head->cert, arg); - /* if sort function succeeds, then insert before current node */ - if ( ret ) { - PR_INSERT_BEFORE(&node->links, &head->links); - goto done; - } + while (!CERT_LIST_END(head, certs)) { - head = CERT_LIST_NEXT(head); + /* if cert is already in the list, then don't add it again */ + if (cert == head->cert) { + /*XXX*/ + /* don't keep a reference */ + CERT_DestroyCertificate(cert); + goto done; + } + + ret = (*f)(cert, head->cert, arg); + /* if sort function succeeds, then insert before current node */ + if (ret) { + PR_INSERT_BEFORE(&node->links, &head->links); + goto done; + } + + head = CERT_LIST_NEXT(head); } /* if we get to the end, then just insert it at the tail */ PR_INSERT_BEFORE(&node->links, &certs->list); -done: +done: /* certs->count++; */ node->cert = cert; - return(SECSuccess); - + return (SECSuccess); + loser: - return(SECFailure); + return (SECFailure); } /* This routine is here because pcertdb.c still has a call to it. @@ -2769,76 +2764,80 @@ loser: */ SECStatus CERT_FilterCertListByUsage(CERTCertList *certList, SECCertUsage usage, - PRBool ca) + PRBool ca) { unsigned int requiredKeyUsage; unsigned int requiredCertType; CERTCertListNode *node, *savenode; SECStatus rv; - - if (certList == NULL) goto loser; + + if (certList == NULL) + goto loser; rv = CERT_KeyUsageAndTypeForCertUsage(usage, ca, &requiredKeyUsage, - &requiredCertType); - if ( rv != SECSuccess ) { - goto loser; + &requiredCertType); + if (rv != SECSuccess) { + goto loser; } node = CERT_LIST_HEAD(certList); - - while ( !CERT_LIST_END(node, certList) ) { - PRBool bad = (PRBool)(!node->cert); + while (!CERT_LIST_END(node, certList)) { - /* bad key usage ? */ - if ( !bad && - CERT_CheckKeyUsage(node->cert, requiredKeyUsage) != SECSuccess ) { - bad = PR_TRUE; - } - /* bad cert type ? */ - if ( !bad ) { - unsigned int certType = 0; - if ( ca ) { - /* This function returns a more comprehensive cert type that - * takes trust flags into consideration. Should probably - * fix the cert decoding code to do this. - */ - (void)CERT_IsCACert(node->cert, &certType); - } else { - certType = node->cert->nsCertType; - } - if ( !( certType & requiredCertType ) ) { - bad = PR_TRUE; - } - } + PRBool bad = (PRBool)(!node->cert); - if ( bad ) { - /* remove the node if it is bad */ - savenode = CERT_LIST_NEXT(node); - CERT_RemoveCertListNode(node); - node = savenode; - } else { - node = CERT_LIST_NEXT(node); - } + /* bad key usage ? */ + if (!bad && + CERT_CheckKeyUsage(node->cert, requiredKeyUsage) != SECSuccess) { + bad = PR_TRUE; + } + /* bad cert type ? */ + if (!bad) { + unsigned int certType = 0; + if (ca) { + /* This function returns a more comprehensive cert type that + * takes trust flags into consideration. Should probably + * fix the cert decoding code to do this. + */ + (void)CERT_IsCACert(node->cert, &certType); + } + else { + certType = node->cert->nsCertType; + } + if (!(certType & requiredCertType)) { + bad = PR_TRUE; + } + } + + if (bad) { + /* remove the node if it is bad */ + savenode = CERT_LIST_NEXT(node); + CERT_RemoveCertListNode(node); + node = savenode; + } + else { + node = CERT_LIST_NEXT(node); + } } - return(SECSuccess); - + return (SECSuccess); + loser: - return(SECFailure); + return (SECFailure); } -PRBool CERT_IsUserCert(CERTCertificate* cert) +PRBool +CERT_IsUserCert(CERTCertificate *cert) { CERTCertTrust trust; SECStatus rv = SECFailure; rv = CERT_GetCertTrust(cert, &trust); if (rv == SECSuccess && - ((trust.sslFlags & CERTDB_USER ) || - (trust.emailFlags & CERTDB_USER ) || - (trust.objectSigningFlags & CERTDB_USER )) ) { + ((trust.sslFlags & CERTDB_USER) || (trust.emailFlags & CERTDB_USER) || + (trust.objectSigningFlags & CERTDB_USER))) { return PR_TRUE; - } else { + } + else { return PR_FALSE; } } @@ -2854,21 +2853,22 @@ CERT_FilterCertListForUserCerts(CERTCertList *certList) } node = CERT_LIST_HEAD(certList); - - while ( ! CERT_LIST_END(node, certList) ) { - cert = node->cert; - if ( PR_TRUE != CERT_IsUserCert(cert) ) { - /* Not a User Cert, so remove this cert from the list */ - freenode = node; - node = CERT_LIST_NEXT(node); - CERT_RemoveCertListNode(freenode); - } else { - /* Is a User cert, so leave it in the list */ - node = CERT_LIST_NEXT(node); - } + + while (!CERT_LIST_END(node, certList)) { + cert = node->cert; + if (PR_TRUE != CERT_IsUserCert(cert)) { + /* Not a User Cert, so remove this cert from the list */ + freenode = node; + node = CERT_LIST_NEXT(node); + CERT_RemoveCertListNode(freenode); + } + else { + /* Is a User cert, so leave it in the list */ + node = CERT_LIST_NEXT(node); + } } - return(SECSuccess); + return (SECSuccess); } static PZLock *certRefCountLock = NULL; @@ -2894,7 +2894,7 @@ void CERT_UnlockCertRefCount(CERTCertificate *cert) { PORT_Assert(certRefCountLock != NULL); - + #ifdef DEBUG { PRStatus prstat = PZ_Unlock(certRefCountLock); @@ -2924,7 +2924,7 @@ CERT_LockCertTrust(const CERTCertificate *cert) SECStatus cert_InitLocks(void) { - if ( certRefCountLock == NULL ) { + if (certRefCountLock == NULL) { certRefCountLock = PZ_NewLock(nssILockRefLock); PORT_Assert(certRefCountLock != NULL); if (!certRefCountLock) { @@ -2932,7 +2932,7 @@ cert_InitLocks(void) } } - if ( certTrustLock == NULL ) { + if (certTrustLock == NULL) { certTrustLock = PZ_NewLock(nssILockCertDB); PORT_Assert(certTrustLock != NULL); if (!certTrustLock) { @@ -2940,7 +2940,7 @@ cert_InitLocks(void) certRefCountLock = NULL; return SECFailure; } - } + } return SECSuccess; } @@ -2954,7 +2954,8 @@ cert_DestroyLocks(void) if (certRefCountLock) { PZ_DestroyLock(certRefCountLock); certRefCountLock = NULL; - } else { + } + else { rv = SECFailure; } @@ -2962,7 +2963,8 @@ cert_DestroyLocks(void) if (certTrustLock) { PZ_DestroyLock(certTrustLock); certTrustLock = NULL; - } else { + } + else { rv = SECFailure; } return rv; @@ -2975,7 +2977,7 @@ void CERT_UnlockCertTrust(const CERTCertificate *cert) { PORT_Assert(certTrustLock != NULL); - + #ifdef DEBUG { PRStatus prstat = PZ_Unlock(certTrustLock); @@ -2986,14 +2988,13 @@ CERT_UnlockCertTrust(const CERTCertificate *cert) #endif } - /* * Get the StatusConfig data for this handle */ CERTStatusConfig * CERT_GetStatusConfig(CERTCertDBHandle *handle) { - return handle->statusConfig; + return handle->statusConfig; } /* @@ -3003,8 +3004,8 @@ CERT_GetStatusConfig(CERTCertDBHandle *handle) void CERT_SetStatusConfig(CERTCertDBHandle *handle, CERTStatusConfig *statusConfig) { - PORT_Assert(handle->statusConfig == NULL); - handle->statusConfig = statusConfig; + PORT_Assert(handle->statusConfig == NULL); + handle->statusConfig = statusConfig; } /* @@ -3012,37 +3013,40 @@ CERT_SetStatusConfig(CERTCertDBHandle *handle, CERTStatusConfig *statusConfig) */ static PLHashTable *gSubjKeyIDHash = NULL; -static PRLock *gSubjKeyIDLock = NULL; +static PRLock *gSubjKeyIDLock = NULL; static PLHashTable *gSubjKeyIDSlotCheckHash = NULL; -static PRLock *gSubjKeyIDSlotCheckLock = NULL; +static PRLock *gSubjKeyIDSlotCheckLock = NULL; -static void *cert_AllocTable(void *pool, PRSize size) +static void * +cert_AllocTable(void *pool, PRSize size) { return PORT_Alloc(size); } -static void cert_FreeTable(void *pool, void *item) +static void +cert_FreeTable(void *pool, void *item) { PORT_Free(item); } -static PLHashEntry* cert_AllocEntry(void *pool, const void *key) +static PLHashEntry * +cert_AllocEntry(void *pool, const void *key) { return PORT_New(PLHashEntry); } -static void cert_FreeEntry(void *pool, PLHashEntry *he, PRUintn flag) +static void +cert_FreeEntry(void *pool, PLHashEntry *he, PRUintn flag) { - SECITEM_FreeItem((SECItem*)(he->value), PR_TRUE); + SECITEM_FreeItem((SECItem *)(he->value), PR_TRUE); if (flag == HT_FREE_ENTRY) { - SECITEM_FreeItem((SECItem*)(he->key), PR_TRUE); + SECITEM_FreeItem((SECItem *)(he->key), PR_TRUE); PORT_Free(he); } } -static PLHashAllocOps cert_AllocOps = { - cert_AllocTable, cert_FreeTable, cert_AllocEntry, cert_FreeEntry -}; +static PLHashAllocOps cert_AllocOps = { cert_AllocTable, cert_FreeTable, + cert_AllocEntry, cert_FreeEntry }; SECStatus cert_CreateSubjectKeyIDSlotCheckHash(void) @@ -3051,10 +3055,9 @@ cert_CreateSubjectKeyIDSlotCheckHash(void) * This hash is used to remember the series of a slot * when we last checked for user certs */ - gSubjKeyIDSlotCheckHash = PL_NewHashTable(0, SECITEM_Hash, - SECITEM_HashCompare, - SECITEM_HashCompare, - &cert_AllocOps, NULL); + gSubjKeyIDSlotCheckHash = + PL_NewHashTable(0, SECITEM_Hash, SECITEM_HashCompare, + SECITEM_HashCompare, &cert_AllocOps, NULL); if (!gSubjKeyIDSlotCheckHash) { PORT_SetError(SEC_ERROR_NO_MEMORY); return SECFailure; @@ -3073,8 +3076,7 @@ SECStatus cert_CreateSubjectKeyIDHashTable(void) { gSubjKeyIDHash = PL_NewHashTable(0, SECITEM_Hash, SECITEM_HashCompare, - SECITEM_HashCompare, - &cert_AllocOps, NULL); + SECITEM_HashCompare, &cert_AllocOps, NULL); if (!gSubjKeyIDHash) { PORT_SetError(SEC_ERROR_NO_MEMORY); return SECFailure; @@ -3088,8 +3090,8 @@ cert_CreateSubjectKeyIDHashTable(void) } /* initialize the companion hash (for remembering slot series) */ if (cert_CreateSubjectKeyIDSlotCheckHash() != SECSuccess) { - cert_DestroySubjectKeyIDHashTable(); - return SECFailure; + cert_DestroySubjectKeyIDHashTable(); + return SECFailure; } return SECSuccess; } @@ -3101,8 +3103,8 @@ cert_AddSubjectKeyIDMapping(SECItem *subjKeyID, CERTCertificate *cert) SECStatus rv = SECFailure; if (!gSubjKeyIDLock) { - /* If one is created, then both are there. So only check for one. */ - return SECFailure; + /* If one is created, then both are there. So only check for one. */ + return SECFailure; } newVal = SECITEM_DupItem(&cert->derCert); @@ -3118,18 +3120,18 @@ cert_AddSubjectKeyIDMapping(SECItem *subjKeyID, CERTCertificate *cert) } PR_Lock(gSubjKeyIDLock); - /* The hash table implementation does not free up the memory - * associated with the key of an already existing entry if we add a - * duplicate, so we would wind up leaking the previously allocated + /* The hash table implementation does not free up the memory + * associated with the key of an already existing entry if we add a + * duplicate, so we would wind up leaking the previously allocated * key if we don't remove before adding. */ - oldVal = (SECItem*)PL_HashTableLookup(gSubjKeyIDHash, subjKeyID); + oldVal = (SECItem *)PL_HashTableLookup(gSubjKeyIDHash, subjKeyID); if (oldVal) { PL_HashTableRemove(gSubjKeyIDHash, subjKeyID); } - rv = (PL_HashTableAdd(gSubjKeyIDHash, newKeyID, newVal)) ? SECSuccess : - SECFailure; + rv = (PL_HashTableAdd(gSubjKeyIDHash, newKeyID, newVal)) ? SECSuccess + : SECFailure; PR_Unlock(gSubjKeyIDLock); done: return rv; @@ -3143,8 +3145,8 @@ cert_RemoveSubjectKeyIDMapping(SECItem *subjKeyID) return SECFailure; PR_Lock(gSubjKeyIDLock); - rv = (PL_HashTableRemove(gSubjKeyIDHash, subjKeyID)) ? SECSuccess : - SECFailure; + rv = (PL_HashTableRemove(gSubjKeyIDHash, subjKeyID)) ? SECSuccess + : SECFailure; PR_Unlock(gSubjKeyIDLock); return rv; } @@ -3156,12 +3158,12 @@ cert_UpdateSubjectKeyIDSlotCheck(SECItem *slotid, int series) SECStatus rv = SECFailure; if (!gSubjKeyIDSlotCheckLock) { - return rv; + return rv; } newSlotid = SECITEM_DupItem(slotid); newSeries = SECITEM_AllocItem(NULL, NULL, sizeof(int)); - if (!newSlotid || !newSeries ) { + if (!newSlotid || !newSeries) { PORT_SetError(SEC_ERROR_NO_MEMORY); goto loser; } @@ -3170,17 +3172,18 @@ cert_UpdateSubjectKeyIDSlotCheck(SECItem *slotid, int series) PR_Lock(gSubjKeyIDSlotCheckLock); oldSeries = (SECItem *)PL_HashTableLookup(gSubjKeyIDSlotCheckHash, slotid); if (oldSeries) { - /* - * make sure we don't leak the key of an existing entry - * (similar to cert_AddSubjectKeyIDMapping, see comment there) - */ + /* + * make sure we don't leak the key of an existing entry + * (similar to cert_AddSubjectKeyIDMapping, see comment there) + */ PL_HashTableRemove(gSubjKeyIDSlotCheckHash, slotid); } - rv = (PL_HashTableAdd(gSubjKeyIDSlotCheckHash, newSlotid, newSeries)) ? - SECSuccess : SECFailure; + rv = (PL_HashTableAdd(gSubjKeyIDSlotCheckHash, newSlotid, newSeries)) + ? SECSuccess + : SECFailure; PR_Unlock(gSubjKeyIDSlotCheckLock); if (rv == SECSuccess) { - return rv; + return rv; } loser: @@ -3200,23 +3203,23 @@ cert_SubjectKeyIDSlotCheckSeries(SECItem *slotid) int series; if (!gSubjKeyIDSlotCheckLock) { - PORT_SetError(SEC_ERROR_NOT_INITIALIZED); - return -1; + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); + return -1; } PR_Lock(gSubjKeyIDSlotCheckLock); seriesItem = (SECItem *)PL_HashTableLookup(gSubjKeyIDSlotCheckHash, slotid); PR_Unlock(gSubjKeyIDSlotCheckLock); - /* getting a null series just means we haven't registered one yet, - * just return 0 */ + /* getting a null series just means we haven't registered one yet, + * just return 0 */ if (seriesItem == NULL) { - return 0; + return 0; } /* if we got a series back, assert if it's not the proper length. */ PORT_Assert(seriesItem->len == sizeof(int)); if (seriesItem->len != sizeof(int)) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return -1; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return -1; } PORT_Memcpy(&series, seriesItem->data, sizeof(int)); return series; @@ -3251,16 +3254,16 @@ cert_DestroySubjectKeyIDHashTable(void) return SECSuccess; } -SECItem* +SECItem * cert_FindDERCertBySubjectKeyID(SECItem *subjKeyID) { - SECItem *val; - + SECItem *val; + if (!gSubjKeyIDLock) return NULL; PR_Lock(gSubjKeyIDLock); - val = (SECItem*)PL_HashTableLookup(gSubjKeyIDHash, subjKeyID); + val = (SECItem *)PL_HashTableLookup(gSubjKeyIDHash, subjKeyID); if (val) { val = SECITEM_DupItem(val); } @@ -3268,7 +3271,7 @@ cert_FindDERCertBySubjectKeyID(SECItem *subjKeyID) return val; } -CERTCertificate* +CERTCertificate * CERT_FindCertBySubjectKeyID(CERTCertDBHandle *handle, SECItem *subjKeyID) { CERTCertificate *cert = NULL; diff --git a/security/nss/lib/certdb/certdb.h b/security/nss/lib/certdb/certdb.h index d358dfd822fe..cb39b9800f1b 100644 --- a/security/nss/lib/certdb/certdb.h +++ b/security/nss/lib/certdb/certdb.h @@ -5,18 +5,17 @@ #ifndef _CERTDB_H_ #define _CERTDB_H_ - /* common flags for all types of certificates */ -#define CERTDB_TERMINAL_RECORD (1u<<0) -#define CERTDB_TRUSTED (1u<<1) -#define CERTDB_SEND_WARN (1u<<2) -#define CERTDB_VALID_CA (1u<<3) -#define CERTDB_TRUSTED_CA (1u<<4) /* trusted for issuing server certs */ -#define CERTDB_NS_TRUSTED_CA (1u<<5) -#define CERTDB_USER (1u<<6) -#define CERTDB_TRUSTED_CLIENT_CA (1u<<7) /* trusted for issuing client certs */ -#define CERTDB_INVISIBLE_CA (1u<<8) /* don't show in UI */ -#define CERTDB_GOVT_APPROVED_CA (1u<<9) /* can do strong crypto in export ver */ +#define CERTDB_TERMINAL_RECORD (1u << 0) +#define CERTDB_TRUSTED (1u << 1) +#define CERTDB_SEND_WARN (1u << 2) +#define CERTDB_VALID_CA (1u << 3) +#define CERTDB_TRUSTED_CA (1u << 4) /* trusted for issuing server certs */ +#define CERTDB_NS_TRUSTED_CA (1u << 5) +#define CERTDB_USER (1u << 6) +#define CERTDB_TRUSTED_CLIENT_CA (1u << 7) /* trusted for issuing client certs */ +#define CERTDB_INVISIBLE_CA (1u << 8) /* don't show in UI */ +#define CERTDB_GOVT_APPROVED_CA (1u << 9) /* can do strong crypto in export ver */ /* old usage, to keep old programs compiling */ /* On Windows, Mac, and Linux (and other gcc platforms), we can give compile @@ -26,54 +25,48 @@ #if (__GNUC__ == 4) && (__GNUC_MINOR__ < 5) typedef unsigned int __CERTDB_VALID_PEER __attribute__((deprecated)); #else -typedef unsigned int __CERTDB_VALID_PEER __attribute__((deprecated - ("CERTDB_VALID_PEER is now CERTDB_TERMINAL_RECORD"))); +typedef unsigned int __CERTDB_VALID_PEER __attribute__(( + deprecated("CERTDB_VALID_PEER is now CERTDB_TERMINAL_RECORD"))); #endif -#define CERTDB_VALID_PEER ((__CERTDB_VALID_PEER) CERTDB_TERMINAL_RECORD) +#define CERTDB_VALID_PEER ((__CERTDB_VALID_PEER)CERTDB_TERMINAL_RECORD) #else #ifdef _WIN32 #pragma deprecated(CERTDB_VALID_PEER) #endif -#define CERTDB_VALID_PEER CERTDB_TERMINAL_RECORD +#define CERTDB_VALID_PEER CERTDB_TERMINAL_RECORD #endif SEC_BEGIN_PROTOS -CERTSignedCrl * -SEC_FindCrlByKey(CERTCertDBHandle *handle, SECItem *crlKey, int type); +CERTSignedCrl *SEC_FindCrlByKey(CERTCertDBHandle *handle, SECItem *crlKey, + int type); -CERTSignedCrl * -SEC_FindCrlByName(CERTCertDBHandle *handle, SECItem *crlKey, int type); +CERTSignedCrl *SEC_FindCrlByName(CERTCertDBHandle *handle, SECItem *crlKey, + int type); -CERTSignedCrl * -SEC_FindCrlByDERCert(CERTCertDBHandle *handle, SECItem *derCrl, int type); +CERTSignedCrl *SEC_FindCrlByDERCert(CERTCertDBHandle *handle, SECItem *derCrl, + int type); -PRBool -SEC_CertNicknameConflict(const char *nickname, const SECItem *derSubject, - CERTCertDBHandle *handle); -CERTSignedCrl * -SEC_NewCrl(CERTCertDBHandle *handle, char *url, SECItem *derCrl, int type); +PRBool SEC_CertNicknameConflict(const char *nickname, const SECItem *derSubject, + CERTCertDBHandle *handle); +CERTSignedCrl *SEC_NewCrl(CERTCertDBHandle *handle, char *url, SECItem *derCrl, + int type); -SECStatus -SEC_DeletePermCRL(CERTSignedCrl *crl); +SECStatus SEC_DeletePermCRL(CERTSignedCrl *crl); +SECStatus SEC_LookupCrls(CERTCertDBHandle *handle, CERTCrlHeadNode **nodes, + int type); -SECStatus -SEC_LookupCrls(CERTCertDBHandle *handle, CERTCrlHeadNode **nodes, int type); +SECStatus SEC_DestroyCrl(CERTSignedCrl *crl); -SECStatus -SEC_DestroyCrl(CERTSignedCrl *crl); +CERTSignedCrl *SEC_DupCrl(CERTSignedCrl *acrl); -CERTSignedCrl* SEC_DupCrl(CERTSignedCrl* acrl); - -SECStatus -CERT_AddTempCertToPerm(CERTCertificate *cert, char *nickname, - CERTCertTrust *trust); +SECStatus CERT_AddTempCertToPerm(CERTCertificate *cert, char *nickname, + CERTCertTrust *trust); SECStatus SEC_DeletePermCertificate(CERTCertificate *cert); -PRBool -SEC_CrlIsNewer(CERTCrl *inNew, CERTCrl *old); +PRBool SEC_CrlIsNewer(CERTCrl *inNew, CERTCrl *old); /* ** Extract the validity times from a CRL @@ -81,8 +74,7 @@ SEC_CrlIsNewer(CERTCrl *inNew, CERTCrl *old); ** "notBefore" is the start of the validity period (last update) ** "notAfter" is the end of the validity period (next update) */ -SECStatus -SEC_GetCrlTimes(CERTCrl *crl, PRTime *notBefore, PRTime *notAfter); +SECStatus SEC_GetCrlTimes(CERTCrl *crl, PRTime *notBefore, PRTime *notAfter); /* ** Check the validity times of a crl vs. time 't', allowing @@ -90,8 +82,7 @@ SEC_GetCrlTimes(CERTCrl *crl, PRTime *notBefore, PRTime *notAfter); ** "crl" is the certificate to be checked ** "t" is the time to check against */ -SECCertTimeValidity -SEC_CheckCrlTimes(CERTCrl *crl, PRTime t); +SECCertTimeValidity SEC_CheckCrlTimes(CERTCrl *crl, PRTime t); SEC_END_PROTOS diff --git a/security/nss/lib/certdb/certi.h b/security/nss/lib/certdb/certi.h index ff7a7b845f86..df0d7c5324fe 100644 --- a/security/nss/lib/certdb/certi.h +++ b/security/nss/lib/certdb/certi.h @@ -38,8 +38,7 @@ struct OpaqueCRLFieldsStr { typedef struct PreAllocatorStr PreAllocator; -struct PreAllocatorStr -{ +struct PreAllocatorStr { PRSize len; void* data; PRSize used; @@ -56,32 +55,31 @@ struct CRLEntryCacheStr { CRLEntryCache *prev, *next; }; -#define CRL_CACHE_INVALID_CRLS 0x0001 /* this state will be set - if we have CRL objects with an invalid DER or signature. Can be - cleared if the invalid objects are deleted from the token */ -#define CRL_CACHE_LAST_FETCH_FAILED 0x0002 /* this state will be set - if the last CRL fetch encountered an error. Can be cleared if a - new fetch succeeds */ +#define CRL_CACHE_INVALID_CRLS 0x0001 /* this state will be set + if we have CRL objects with an invalid DER or signature. Can be + cleared if the invalid objects are deleted from the token */ +#define CRL_CACHE_LAST_FETCH_FAILED 0x0002 /* this state will be set + if the last CRL fetch encountered an error. Can be cleared if a + new fetch succeeds */ -#define CRL_CACHE_OUT_OF_MEMORY 0x0004 /* this state will be set - if we don't have enough memory to build the hash table of entries */ +#define CRL_CACHE_OUT_OF_MEMORY 0x0004 /* this state will be set + if we don't have enough memory to build the hash table of entries */ typedef enum { - CRL_OriginToken = 0, /* CRL came from PKCS#11 token */ - CRL_OriginExplicit = 1 /* CRL was explicitly added to the cache, from RAM */ + CRL_OriginToken = 0, /* CRL came from PKCS#11 token */ + CRL_OriginExplicit = 1 /* CRL was explicitly added to the cache, from RAM */ } CRLOrigin; typedef enum { - dpcacheNoEntry = 0, /* no entry found for this SN */ - dpcacheFoundEntry = 1, /* entry found for this SN */ - dpcacheCallerError = 2, /* invalid args */ - dpcacheInvalidCacheError = 3, /* CRL in cache may be bad DER */ - /* or unverified */ - dpcacheEmpty = 4, /* no CRL in cache */ - dpcacheLookupError = 5 /* internal error */ + dpcacheNoEntry = 0, /* no entry found for this SN */ + dpcacheFoundEntry = 1, /* entry found for this SN */ + dpcacheCallerError = 2, /* invalid args */ + dpcacheInvalidCacheError = 3, /* CRL in cache may be bad DER */ + /* or unverified */ + dpcacheEmpty = 4, /* no CRL in cache */ + dpcacheLookupError = 5 /* internal error */ } dpcacheStatus; - struct CachedCrlStr { CERTSignedCrl* crl; CRLOrigin origin; @@ -98,11 +96,11 @@ struct CachedCrlStr { */ PLHashTable* entries; PreAllocator* prebuffer; /* big pre-allocated buffer mentioned above */ - PRBool sigChecked; /* this CRL signature has already been checked */ - PRBool sigValid; /* signature verification status . - Only meaningful if checked is PR_TRUE . */ - PRBool unbuildable; /* Avoid using assosiated CRL is it fails - * a decoding step */ + PRBool sigChecked; /* this CRL signature has already been checked */ + PRBool sigValid; /* signature verification status . + Only meaningful if checked is PR_TRUE . */ + PRBool unbuildable; /* Avoid using assosiated CRL is it fails + * a decoding step */ }; /* CRL distribution point cache object @@ -116,15 +114,15 @@ struct CRLDPCacheStr { #else PRLock* lock; #endif - SECItem *issuerDERCert; /* issuer DER cert. Don't hold a reference - to the actual cert so the trust can be - updated on the cert automatically. - XXX there may be multiple issuer certs, - with different validity dates. Also - need to deal with SKID/AKID . See - bugzilla 217387, 233118 */ + SECItem* issuerDERCert; /* issuer DER cert. Don't hold a reference + to the actual cert so the trust can be + updated on the cert automatically. + XXX there may be multiple issuer certs, + with different validity dates. Also + need to deal with SKID/AKID . See + bugzilla 217387, 233118 */ - CERTCertDBHandle *dbHandle; + CERTCertDBHandle* dbHandle; SECItem* subject; /* DER of issuer subject */ SECItem* distributionPoint; /* DER of distribution point. This may be @@ -133,31 +131,31 @@ struct CRLDPCacheStr { Currently not used. */ /* array of full CRLs matching this distribution point */ - PRUint32 ncrls; /* total number of CRLs in crls */ - CachedCrl** crls; /* array of all matching CRLs */ + PRUint32 ncrls; /* total number of CRLs in crls */ + CachedCrl** crls; /* array of all matching CRLs */ /* XCRL With iCRLs and multiple DPs, the CRL can be shared accross several issuers. In the future, we'll need to globally recycle the CRL in a separate list in order to avoid extra lookups, decodes, and copies */ /* pointers to good decoded CRLs used to build the cache */ - CachedCrl* selected; /* full CRL selected for use in the cache */ + CachedCrl* selected; /* full CRL selected for use in the cache */ #if 0 /* for future use */ PRInt32 numdeltas; /* number of delta CRLs used for the cache */ CachedCrl** deltas; /* delta CRLs used for the cache */ #endif /* cache invalidity bitflag */ - PRUint16 invalid; /* this state will be set if either - CRL_CACHE_INVALID_CRLS or CRL_CACHE_LAST_FETCH_FAILED is set. - In those cases, all certs are considered to have unknown status. - The invalid state can only be cleared during an update if all - error states are cleared */ - PRBool refresh; /* manual refresh from tokens has been forced */ - PRBool mustchoose; /* trigger reselection algorithm, for case when - RAM CRL objects are dropped from the cache */ - PRTime lastfetch; /* time a CRL token fetch was last performed */ - PRTime lastcheck; /* time CRL token objects were last checked for - existence */ + PRUint16 invalid; /* this state will be set if either + CRL_CACHE_INVALID_CRLS or CRL_CACHE_LAST_FETCH_FAILED is set. + In those cases, all certs are considered to have unknown status. + The invalid state can only be cleared during an update if all + error states are cleared */ + PRBool refresh; /* manual refresh from tokens has been forced */ + PRBool mustchoose; /* trigger reselection algorithm, for case when + RAM CRL objects are dropped from the cache */ + PRTime lastfetch; /* time a CRL token fetch was last performed */ + PRTime lastcheck; /* time CRL token objects were last checked for + existence */ }; /* CRL issuer cache object @@ -168,7 +166,7 @@ struct CRLDPCacheStr { */ struct CRLIssuerCacheStr { - SECItem* subject; /* DER of issuer subject */ + SECItem* subject; /* DER of issuer subject */ CRLDPCache* dpp; }; @@ -194,46 +192,40 @@ SECStatus ShutdownCRLCache(void); ** null-terminated strings, terminated by a zero-length string. ** This function is intended to be internal to NSS. */ -extern char * cert_GetCertificateEmailAddresses(CERTCertificate *cert); +extern char* cert_GetCertificateEmailAddresses(CERTCertificate* cert); /* * These functions are used to map subjectKeyID extension values to certs * and to keep track of the checks for user certificates in each slot */ -SECStatus -cert_CreateSubjectKeyIDHashTable(void); +SECStatus cert_CreateSubjectKeyIDHashTable(void); -SECStatus -cert_AddSubjectKeyIDMapping(SECItem *subjKeyID, CERTCertificate *cert); +SECStatus cert_AddSubjectKeyIDMapping(SECItem* subjKeyID, + CERTCertificate* cert); -SECStatus -cert_UpdateSubjectKeyIDSlotCheck(SECItem *slotid, int series); +SECStatus cert_UpdateSubjectKeyIDSlotCheck(SECItem* slotid, int series); -int -cert_SubjectKeyIDSlotCheckSeries(SECItem *slotid); +int cert_SubjectKeyIDSlotCheckSeries(SECItem* slotid); /* * Call this function to remove an entry from the mapping table. */ -SECStatus -cert_RemoveSubjectKeyIDMapping(SECItem *subjKeyID); +SECStatus cert_RemoveSubjectKeyIDMapping(SECItem* subjKeyID); -SECStatus -cert_DestroySubjectKeyIDHashTable(void); +SECStatus cert_DestroySubjectKeyIDHashTable(void); -SECItem* -cert_FindDERCertBySubjectKeyID(SECItem *subjKeyID); +SECItem* cert_FindDERCertBySubjectKeyID(SECItem* subjKeyID); /* return maximum length of AVA value based on its type OID tag. */ extern int cert_AVAOidTagToMaxLen(SECOidTag tag); /* Make an AVA, allocated from pool, from OID and DER encoded value */ -extern CERTAVA * CERT_CreateAVAFromRaw(PLArenaPool *pool, - const SECItem * OID, const SECItem * value); +extern CERTAVA* CERT_CreateAVAFromRaw(PLArenaPool* pool, const SECItem* OID, + const SECItem* value); /* Make an AVA from binary input specified by SECItem */ -extern CERTAVA * CERT_CreateAVAFromSECItem(PLArenaPool *arena, SECOidTag kind, - int valueType, SECItem *value); +extern CERTAVA* CERT_CreateAVAFromSECItem(PLArenaPool* arena, SECOidTag kind, + int valueType, SECItem* value); /* * get a DPCache object for the given issuer subject and dp @@ -260,10 +252,11 @@ void CERT_MapStanError(); /* Like CERT_VerifyCert, except with an additional argument, flags. The * flags are defined immediately below. */ -SECStatus -cert_VerifyCertWithFlags(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, PRTime t, - PRUint32 flags, void *wincx, CERTVerifyLog *log); +SECStatus cert_VerifyCertWithFlags(CERTCertDBHandle* handle, + CERTCertificate* cert, PRBool checkSig, + SECCertUsage certUsage, PRTime t, + PRUint32 flags, void* wincx, + CERTVerifyLog* log); /* Use the default settings. * cert_VerifyCertWithFlags(..., CERT_VERIFYCERT_USE_DEFAULTS, ...) is @@ -281,15 +274,10 @@ cert_VerifyCertWithFlags(CERTCertDBHandle *handle, CERTCertificate *cert, /* Interface function for libpkix cert validation engine: * cert_verify wrapper. */ -SECStatus -cert_VerifyCertChainPkix(CERTCertificate *cert, - PRBool checkSig, - SECCertUsage requiredUsage, - PRTime time, - void *wincx, - CERTVerifyLog *log, - PRBool *sigError, - PRBool *revoked); +SECStatus cert_VerifyCertChainPkix(CERTCertificate* cert, PRBool checkSig, + SECCertUsage requiredUsage, PRTime time, + void* wincx, CERTVerifyLog* log, + PRBool* sigError, PRBool* revoked); SECStatus cert_InitLocks(void); @@ -298,17 +286,16 @@ SECStatus cert_DestroyLocks(void); /* * fill in nsCertType field of the cert based on the cert extension */ -extern SECStatus cert_GetCertType(CERTCertificate *cert); +extern SECStatus cert_GetCertType(CERTCertificate* cert); /* - * compute and return the value of nsCertType for cert, but do not + * compute and return the value of nsCertType for cert, but do not * update the CERTCertificate. */ -extern PRUint32 cert_ComputeCertType(CERTCertificate *cert); +extern PRUint32 cert_ComputeCertType(CERTCertificate* cert); -void cert_AddToVerifyLog(CERTVerifyLog *log,CERTCertificate *cert, - long errorCode, unsigned int depth, - void *arg); +void cert_AddToVerifyLog(CERTVerifyLog* log, CERTCertificate* cert, + long errorCode, unsigned int depth, void* arg); /* Insert a DER CRL into the CRL cache, and take ownership of it. * @@ -323,7 +310,7 @@ void cert_AddToVerifyLog(CERTVerifyLog *log,CERTCertificate *cert, * the same encoding. To facilitate X.500 name matching, a canonicalized * encoding of the GeneralName should be used, if available. */ - + SECStatus cert_CacheCRLByGeneralName(CERTCertDBHandle* dbhandle, SECItem* crl, const SECItem* canonicalizedName); @@ -336,15 +323,15 @@ struct NamedCRLCacheStr { * and read by cert_FindCRLByGeneralName */ struct NamedCRLCacheEntryStr { SECItem* canonicalizedName; - SECItem* crl; /* DER, kept only if CRL - * is successfully cached */ + SECItem* crl; /* DER, kept only if CRL + * is successfully cached */ PRBool inCRLCache; PRTime successfulInsertionTime; /* insertion time */ PRTime lastAttemptTime; /* time of last call to cert_CacheCRLByGeneralName with this name */ - PRBool badDER; /* ASN.1 error */ - PRBool dupe; /* matching DER CRL already in CRL cache */ - PRBool unsupported; /* IDP, delta, any other reason */ + PRBool badDER; /* ASN.1 error */ + PRBool dupe; /* matching DER CRL already in CRL cache */ + PRBool unsupported; /* IDP, delta, any other reason */ }; typedef enum { @@ -355,12 +342,12 @@ typedef enum { /* Returns detailed status of the cert(revStatus variable). Tells if * issuer cache has OriginFetchedWithTimeout crl in it. */ -SECStatus -cert_CheckCertRevocationStatus(CERTCertificate* cert, CERTCertificate* issuer, - const SECItem* dp, PRTime t, void *wincx, - CERTRevocationStatus *revStatus, - CERTCRLEntryReasonCode *revReason); - +SECStatus cert_CheckCertRevocationStatus(CERTCertificate* cert, + CERTCertificate* issuer, + const SECItem* dp, PRTime t, + void* wincx, + CERTRevocationStatus* revStatus, + CERTCRLEntryReasonCode* revReason); SECStatus cert_AcquireNamedCRLCache(NamedCRLCache** returned); @@ -374,26 +361,21 @@ SECStatus cert_FindCRLByGeneralName(NamedCRLCache* ncc, SECStatus cert_ReleaseNamedCRLCache(NamedCRLCache* ncc); /* This is private for now. Maybe shoule be public. */ -CERTGeneralName * -cert_GetSubjectAltNameList(const CERTCertificate *cert, PLArenaPool *arena); +CERTGeneralName* cert_GetSubjectAltNameList(const CERTCertificate* cert, + PLArenaPool* arena); /* Count DNS names and IP addresses in a list of GeneralNames */ -PRUint32 -cert_CountDNSPatterns(CERTGeneralName *firstName); +PRUint32 cert_CountDNSPatterns(CERTGeneralName* firstName); /* * returns the trust status of the leaf certificate based on usage. - * If the leaf is explicitly untrusted, this function will fail and + * If the leaf is explicitly untrusted, this function will fail and * failedFlags will be set to the trust bit value that lead to the failure. - * If the leaf is trusted, isTrusted is set to true and the function returns - * SECSuccess. This function does not check if the cert is fit for a + * If the leaf is trusted, isTrusted is set to true and the function returns + * SECSuccess. This function does not check if the cert is fit for a * particular usage. */ -SECStatus -cert_CheckLeafTrust(CERTCertificate *cert, - SECCertUsage usage, - unsigned int *failedFlags, - PRBool *isTrusted); +SECStatus cert_CheckLeafTrust(CERTCertificate* cert, SECCertUsage usage, + unsigned int* failedFlags, PRBool* isTrusted); #endif /* _CERTI_H_ */ - diff --git a/security/nss/lib/certdb/certt.h b/security/nss/lib/certdb/certt.h index d8b559c7f87b..4c31c29e0e81 100644 --- a/security/nss/lib/certdb/certt.h +++ b/security/nss/lib/certdb/certt.h @@ -23,49 +23,49 @@ struct NSSCertificateStr; struct NSSTrustDomainStr; /* Non-opaque objects */ -typedef struct CERTAVAStr CERTAVA; -typedef struct CERTAttributeStr CERTAttribute; -typedef struct CERTAuthInfoAccessStr CERTAuthInfoAccess; -typedef struct CERTAuthKeyIDStr CERTAuthKeyID; -typedef struct CERTBasicConstraintsStr CERTBasicConstraints; -typedef struct NSSTrustDomainStr CERTCertDBHandle; -typedef struct CERTCertExtensionStr CERTCertExtension; -typedef struct CERTCertKeyStr CERTCertKey; -typedef struct CERTCertListStr CERTCertList; -typedef struct CERTCertListNodeStr CERTCertListNode; -typedef struct CERTCertNicknamesStr CERTCertNicknames; -typedef struct CERTCertTrustStr CERTCertTrust; -typedef struct CERTCertificateStr CERTCertificate; -typedef struct CERTCertificateListStr CERTCertificateList; -typedef struct CERTCertificateRequestStr CERTCertificateRequest; -typedef struct CERTCrlStr CERTCrl; -typedef struct CERTCrlDistributionPointsStr CERTCrlDistributionPoints; -typedef struct CERTCrlEntryStr CERTCrlEntry; -typedef struct CERTCrlHeadNodeStr CERTCrlHeadNode; -typedef struct CERTCrlKeyStr CERTCrlKey; -typedef struct CERTCrlNodeStr CERTCrlNode; -typedef struct CERTDERCertsStr CERTDERCerts; -typedef struct CERTDistNamesStr CERTDistNames; -typedef struct CERTGeneralNameStr CERTGeneralName; -typedef struct CERTGeneralNameListStr CERTGeneralNameList; -typedef struct CERTIssuerAndSNStr CERTIssuerAndSN; -typedef struct CERTNameStr CERTName; -typedef struct CERTNameConstraintStr CERTNameConstraint; -typedef struct CERTNameConstraintsStr CERTNameConstraints; -typedef struct CERTOKDomainNameStr CERTOKDomainName; -typedef struct CERTPrivKeyUsagePeriodStr CERTPrivKeyUsagePeriod; -typedef struct CERTPublicKeyAndChallengeStr CERTPublicKeyAndChallenge; -typedef struct CERTRDNStr CERTRDN; -typedef struct CERTSignedCrlStr CERTSignedCrl; -typedef struct CERTSignedDataStr CERTSignedData; -typedef struct CERTStatusConfigStr CERTStatusConfig; -typedef struct CERTSubjectListStr CERTSubjectList; -typedef struct CERTSubjectNodeStr CERTSubjectNode; -typedef struct CERTSubjectPublicKeyInfoStr CERTSubjectPublicKeyInfo; -typedef struct CERTValidityStr CERTValidity; -typedef struct CERTVerifyLogStr CERTVerifyLog; -typedef struct CERTVerifyLogNodeStr CERTVerifyLogNode; -typedef struct CRLDistributionPointStr CRLDistributionPoint; +typedef struct CERTAVAStr CERTAVA; +typedef struct CERTAttributeStr CERTAttribute; +typedef struct CERTAuthInfoAccessStr CERTAuthInfoAccess; +typedef struct CERTAuthKeyIDStr CERTAuthKeyID; +typedef struct CERTBasicConstraintsStr CERTBasicConstraints; +typedef struct NSSTrustDomainStr CERTCertDBHandle; +typedef struct CERTCertExtensionStr CERTCertExtension; +typedef struct CERTCertKeyStr CERTCertKey; +typedef struct CERTCertListStr CERTCertList; +typedef struct CERTCertListNodeStr CERTCertListNode; +typedef struct CERTCertNicknamesStr CERTCertNicknames; +typedef struct CERTCertTrustStr CERTCertTrust; +typedef struct CERTCertificateStr CERTCertificate; +typedef struct CERTCertificateListStr CERTCertificateList; +typedef struct CERTCertificateRequestStr CERTCertificateRequest; +typedef struct CERTCrlStr CERTCrl; +typedef struct CERTCrlDistributionPointsStr CERTCrlDistributionPoints; +typedef struct CERTCrlEntryStr CERTCrlEntry; +typedef struct CERTCrlHeadNodeStr CERTCrlHeadNode; +typedef struct CERTCrlKeyStr CERTCrlKey; +typedef struct CERTCrlNodeStr CERTCrlNode; +typedef struct CERTDERCertsStr CERTDERCerts; +typedef struct CERTDistNamesStr CERTDistNames; +typedef struct CERTGeneralNameStr CERTGeneralName; +typedef struct CERTGeneralNameListStr CERTGeneralNameList; +typedef struct CERTIssuerAndSNStr CERTIssuerAndSN; +typedef struct CERTNameStr CERTName; +typedef struct CERTNameConstraintStr CERTNameConstraint; +typedef struct CERTNameConstraintsStr CERTNameConstraints; +typedef struct CERTOKDomainNameStr CERTOKDomainName; +typedef struct CERTPrivKeyUsagePeriodStr CERTPrivKeyUsagePeriod; +typedef struct CERTPublicKeyAndChallengeStr CERTPublicKeyAndChallenge; +typedef struct CERTRDNStr CERTRDN; +typedef struct CERTSignedCrlStr CERTSignedCrl; +typedef struct CERTSignedDataStr CERTSignedData; +typedef struct CERTStatusConfigStr CERTStatusConfig; +typedef struct CERTSubjectListStr CERTSubjectList; +typedef struct CERTSubjectNodeStr CERTSubjectNode; +typedef struct CERTSubjectPublicKeyInfoStr CERTSubjectPublicKeyInfo; +typedef struct CERTValidityStr CERTValidity; +typedef struct CERTVerifyLogStr CERTVerifyLog; +typedef struct CERTVerifyLogNodeStr CERTVerifyLogNode; +typedef struct CRLDistributionPointStr CRLDistributionPoint; /* CRL extensions type */ typedef unsigned long CERTCrlNumber; @@ -150,10 +150,13 @@ typedef enum SECTrustTypeEnum { trustTypeNone = 3 } SECTrustType; -#define SEC_GET_TRUST_FLAGS(trust,type) \ - (((type)==trustSSL)?((trust)->sslFlags): \ - (((type)==trustEmail)?((trust)->emailFlags): \ - (((type)==trustObjectSigning)?((trust)->objectSigningFlags):0))) +#define SEC_GET_TRUST_FLAGS(trust, type) \ + (((type) == trustSSL) \ + ? ((trust)->sslFlags) \ + : (((type) == trustEmail) ? ((trust)->emailFlags) \ + : (((type) == trustObjectSigning) \ + ? ((trust)->objectSigningFlags) \ + : 0))) /* ** An X.509.3 certificate extension @@ -195,12 +198,12 @@ struct CERTCertificateStr { /* The following fields are static after the cert has been decoded */ char *subjectName; char *issuerName; - CERTSignedData signatureWrap; /* XXX */ - SECItem derCert; /* original DER for the cert */ - SECItem derIssuer; /* DER for issuer name */ - SECItem derSubject; /* DER for subject name */ - SECItem derPublicKey; /* DER for the public key */ - SECItem certKey; /* database key for this cert */ + CERTSignedData signatureWrap; /* XXX */ + SECItem derCert; /* original DER for the cert */ + SECItem derIssuer; /* DER for issuer name */ + SECItem derSubject; /* DER for subject name */ + SECItem derPublicKey; /* DER for the public key */ + SECItem certKey; /* database key for this cert */ SECItem version; SECItem serialNumber; SECAlgorithmID signature; @@ -213,21 +216,21 @@ struct CERTCertificateStr { CERTCertExtension **extensions; char *emailAddr; CERTCertDBHandle *dbhandle; - SECItem subjectKeyID; /* x509v3 subject key identifier */ - PRBool keyIDGenerated; /* was the keyid generated? */ - unsigned int keyUsage; /* what uses are allowed for this cert */ - unsigned int rawKeyUsage; /* value of the key usage extension */ - PRBool keyUsagePresent; /* was the key usage extension present */ - PRUint32 nsCertType; /* value of the ns cert type extension */ - /* must be 32-bit for PR_ATOMIC_SET */ + SECItem subjectKeyID; /* x509v3 subject key identifier */ + PRBool keyIDGenerated; /* was the keyid generated? */ + unsigned int keyUsage; /* what uses are allowed for this cert */ + unsigned int rawKeyUsage; /* value of the key usage extension */ + PRBool keyUsagePresent; /* was the key usage extension present */ + PRUint32 nsCertType; /* value of the ns cert type extension */ + /* must be 32-bit for PR_ATOMIC_SET */ /* these values can be set by the application to bypass certain checks * or to keep the cert in memory for an entire session. * XXX - need an api to set these */ - PRBool keepSession; /* keep this cert for entire session*/ - PRBool timeOK; /* is the bad validity time ok? */ - CERTOKDomainName *domainOK; /* these domain names are ok */ + PRBool keepSession; /* keep this cert for entire session*/ + PRBool timeOK; /* is the bad validity time ok? */ + CERTOKDomainName *domainOK; /* these domain names are ok */ /* * these values can change when the cert changes state. These state @@ -238,7 +241,7 @@ struct CERTCertificateStr { PRBool istemp; char *nickname; char *dbnickname; - struct NSSCertificateStr *nssCertificate; /* This is Stan stuff. */ + struct NSSCertificateStr *nssCertificate; /* This is Stan stuff. */ CERTCertTrust *trust; /* the reference count is modified whenever someone looks up, dups @@ -255,8 +258,8 @@ struct CERTCertificateStr { /* these belong in the static section, but are here to maintain * the structure's integrity */ - CERTAuthKeyID * authKeyID; /* x509v3 authority key identifier */ - PRBool isRoot; /* cert is the end of a chain */ + CERTAuthKeyID *authKeyID; /* x509v3 authority key identifier */ + PRBool isRoot; /* cert is the end of a chain */ /* these fields are used by client GUI code to keep track of ssl sockets * that are blocked waiting on GUI feedback related to this cert. @@ -264,33 +267,33 @@ struct CERTCertificateStr { * data structure. They are only used by the browser right now. */ union { - void* apointer; /* was struct SECSocketNode* authsocketlist */ + void *apointer; /* was struct SECSocketNode* authsocketlist */ struct { - unsigned int hasUnsupportedCriticalExt :1; + unsigned int hasUnsupportedCriticalExt : 1; /* add any new option bits needed here */ } bits; } options; int series; /* was int authsocketcount; record the series of the pkcs11ID */ /* This is PKCS #11 stuff. */ - PK11SlotInfo *slot; /*if this cert came of a token, which is it*/ - CK_OBJECT_HANDLE pkcs11ID; /*and which object on that token is it */ - PRBool ownSlot; /*true if the cert owns the slot reference */ + PK11SlotInfo *slot; /*if this cert came of a token, which is it*/ + CK_OBJECT_HANDLE pkcs11ID; /*and which object on that token is it */ + PRBool ownSlot; /*true if the cert owns the slot reference */ }; -#define SEC_CERTIFICATE_VERSION_1 0 /* default created */ -#define SEC_CERTIFICATE_VERSION_2 1 /* v2 */ -#define SEC_CERTIFICATE_VERSION_3 2 /* v3 extensions */ +#define SEC_CERTIFICATE_VERSION_1 0 /* default created */ +#define SEC_CERTIFICATE_VERSION_2 1 /* v2 */ +#define SEC_CERTIFICATE_VERSION_3 2 /* v3 extensions */ -#define SEC_CRL_VERSION_1 0 /* default */ -#define SEC_CRL_VERSION_2 1 /* v2 extensions */ +#define SEC_CRL_VERSION_1 0 /* default */ +#define SEC_CRL_VERSION_2 1 /* v2 extensions */ /* * used to identify class of cert in mime stream code */ -#define SEC_CERT_CLASS_CA 1 -#define SEC_CERT_CLASS_SERVER 2 -#define SEC_CERT_CLASS_USER 3 -#define SEC_CERT_CLASS_EMAIL 4 +#define SEC_CERT_CLASS_CA 1 +#define SEC_CERT_CLASS_SERVER 2 +#define SEC_CERT_CLASS_USER 3 +#define SEC_CERT_CLASS_EMAIL 4 struct CERTDERCertsStr { PLArenaPool *arena; @@ -318,15 +321,14 @@ struct CERTCertificateRequestStr { CERTSubjectPublicKeyInfo subjectPublicKeyInfo; CERTAttribute **attributes; }; -#define SEC_CERTIFICATE_REQUEST_VERSION 0 /* what we *create* */ - +#define SEC_CERTIFICATE_REQUEST_VERSION 0 /* what we *create* */ /* ** A certificate list object. */ struct CERTCertificateListStr { SECItem *certs; - int len; /* number of certs */ + int len; /* number of certs */ PLArenaPool *arena; }; @@ -344,13 +346,13 @@ struct CERTCertListStr { #define CERT_LIST_HEAD(l) ((CERTCertListNode *)PR_LIST_HEAD(&l->list)) #define CERT_LIST_TAIL(l) ((CERTCertListNode *)PR_LIST_TAIL(&l->list)) #define CERT_LIST_NEXT(n) ((CERTCertListNode *)n->links.next) -#define CERT_LIST_END(n,l) (((void *)n) == ((void *)&l->list)) +#define CERT_LIST_END(n, l) (((void *)n) == ((void *)&l->list)) #define CERT_LIST_EMPTY(l) CERT_LIST_END(CERT_LIST_HEAD(l), l) struct CERTCrlEntryStr { SECItem serialNumber; SECItem revocationDate; - CERTCertExtension **extensions; + CERTCertExtension **extensions; }; struct CERTCrlStr { @@ -360,18 +362,18 @@ struct CERTCrlStr { SECItem derName; CERTName name; SECItem lastUpdate; - SECItem nextUpdate; /* optional for x.509 CRL */ + SECItem nextUpdate; /* optional for x.509 CRL */ CERTCrlEntry **entries; - CERTCertExtension **extensions; + CERTCertExtension **extensions; /* can't add anything there for binary backwards compatibility reasons */ }; struct CERTCrlKeyStr { SECItem derName; - SECItem dummy; /* The decoder can not skip a primitive, - this serves as a place holder for the - decoder to finish its task only - */ + SECItem dummy; /* The decoder can not skip a primitive, + this serves as a place holder for the + decoder to finish its task only + */ }; struct CERTSignedCrlStr { @@ -383,15 +385,14 @@ struct CERTSignedCrlStr { PRBool istemp; int referenceCount; CERTCertDBHandle *dbhandle; - CERTSignedData signatureWrap; /* XXX */ + CERTSignedData signatureWrap; /* XXX */ char *url; SECItem *derCrl; PK11SlotInfo *slot; CK_OBJECT_HANDLE pkcs11ID; - void* opaque; /* do not touch */ + void *opaque; /* do not touch */ }; - struct CERTCrlHeadNodeStr { PLArenaPool *arena; CERTCertDBHandle *dbhandle; @@ -399,46 +400,41 @@ struct CERTCrlHeadNodeStr { CERTCrlNode *last; }; - struct CERTCrlNodeStr { CERTCrlNode *next; - int type; + int type; CERTSignedCrl *crl; }; - /* * Array of X.500 Distinguished Names */ struct CERTDistNamesStr { PLArenaPool *arena; int nnames; - SECItem *names; + SECItem *names; void *head; /* private */ }; +#define NS_CERT_TYPE_SSL_CLIENT (0x80) /* bit 0 */ +#define NS_CERT_TYPE_SSL_SERVER (0x40) /* bit 1 */ +#define NS_CERT_TYPE_EMAIL (0x20) /* bit 2 */ +#define NS_CERT_TYPE_OBJECT_SIGNING (0x10) /* bit 3 */ +#define NS_CERT_TYPE_RESERVED (0x08) /* bit 4 */ +#define NS_CERT_TYPE_SSL_CA (0x04) /* bit 5 */ +#define NS_CERT_TYPE_EMAIL_CA (0x02) /* bit 6 */ +#define NS_CERT_TYPE_OBJECT_SIGNING_CA (0x01) /* bit 7 */ -#define NS_CERT_TYPE_SSL_CLIENT (0x80) /* bit 0 */ -#define NS_CERT_TYPE_SSL_SERVER (0x40) /* bit 1 */ -#define NS_CERT_TYPE_EMAIL (0x20) /* bit 2 */ -#define NS_CERT_TYPE_OBJECT_SIGNING (0x10) /* bit 3 */ -#define NS_CERT_TYPE_RESERVED (0x08) /* bit 4 */ -#define NS_CERT_TYPE_SSL_CA (0x04) /* bit 5 */ -#define NS_CERT_TYPE_EMAIL_CA (0x02) /* bit 6 */ -#define NS_CERT_TYPE_OBJECT_SIGNING_CA (0x01) /* bit 7 */ +#define EXT_KEY_USAGE_TIME_STAMP (0x8000) +#define EXT_KEY_USAGE_STATUS_RESPONDER (0x4000) -#define EXT_KEY_USAGE_TIME_STAMP (0x8000) -#define EXT_KEY_USAGE_STATUS_RESPONDER (0x4000) +#define NS_CERT_TYPE_APP \ + (NS_CERT_TYPE_SSL_CLIENT | NS_CERT_TYPE_SSL_SERVER | NS_CERT_TYPE_EMAIL | \ + NS_CERT_TYPE_OBJECT_SIGNING) -#define NS_CERT_TYPE_APP ( NS_CERT_TYPE_SSL_CLIENT | \ - NS_CERT_TYPE_SSL_SERVER | \ - NS_CERT_TYPE_EMAIL | \ - NS_CERT_TYPE_OBJECT_SIGNING ) - -#define NS_CERT_TYPE_CA ( NS_CERT_TYPE_SSL_CA | \ - NS_CERT_TYPE_EMAIL_CA | \ - NS_CERT_TYPE_OBJECT_SIGNING_CA | \ - EXT_KEY_USAGE_STATUS_RESPONDER ) +#define NS_CERT_TYPE_CA \ + (NS_CERT_TYPE_SSL_CA | NS_CERT_TYPE_EMAIL_CA | \ + NS_CERT_TYPE_OBJECT_SIGNING_CA | EXT_KEY_USAGE_STATUS_RESPONDER) typedef enum SECCertUsageEnum { certUsageSSLClient = 0, certUsageSSLServer = 1, @@ -456,19 +452,19 @@ typedef enum SECCertUsageEnum { typedef PRInt64 SECCertificateUsage; -#define certificateUsageCheckAllUsages (0x0000) -#define certificateUsageSSLClient (0x0001) -#define certificateUsageSSLServer (0x0002) -#define certificateUsageSSLServerWithStepUp (0x0004) -#define certificateUsageSSLCA (0x0008) -#define certificateUsageEmailSigner (0x0010) -#define certificateUsageEmailRecipient (0x0020) -#define certificateUsageObjectSigner (0x0040) -#define certificateUsageUserCertImport (0x0080) -#define certificateUsageVerifyCA (0x0100) -#define certificateUsageProtectedObjectSigner (0x0200) -#define certificateUsageStatusResponder (0x0400) -#define certificateUsageAnyCA (0x0800) +#define certificateUsageCheckAllUsages (0x0000) +#define certificateUsageSSLClient (0x0001) +#define certificateUsageSSLServer (0x0002) +#define certificateUsageSSLServerWithStepUp (0x0004) +#define certificateUsageSSLCA (0x0008) +#define certificateUsageEmailSigner (0x0010) +#define certificateUsageEmailRecipient (0x0020) +#define certificateUsageObjectSigner (0x0040) +#define certificateUsageUserCertImport (0x0080) +#define certificateUsageVerifyCA (0x0100) +#define certificateUsageProtectedObjectSigner (0x0200) +#define certificateUsageStatusResponder (0x0400) +#define certificateUsageAnyCA (0x0800) #define certificateUsageHighest certificateUsageAnyCA @@ -498,9 +494,8 @@ typedef enum SECCertTimeValidityEnum { * CERT_CompareValidityTimes. */ -typedef enum CERTCompareValidityStatusEnum -{ - certValidityUndetermined = 0, /* the function is unable to select one cert +typedef enum CERTCompareValidityStatusEnum { + certValidityUndetermined = 0, /* the function is unable to select one cert over another */ certValidityChooseB = 1, /* cert B should be preferred */ certValidityEqual = 2, /* both certs have the same validity period */ @@ -512,10 +507,10 @@ typedef enum CERTCompareValidityStatusEnum */ /* these are values for the what argument below */ -#define SEC_CERT_NICKNAMES_ALL 1 -#define SEC_CERT_NICKNAMES_USER 2 -#define SEC_CERT_NICKNAMES_SERVER 3 -#define SEC_CERT_NICKNAMES_CA 4 +#define SEC_CERT_NICKNAMES_ALL 1 +#define SEC_CERT_NICKNAMES_USER 2 +#define SEC_CERT_NICKNAMES_SERVER 3 +#define SEC_CERT_NICKNAMES_CA 4 struct CERTCertNicknamesStr { PLArenaPool *arena; @@ -532,24 +527,19 @@ struct CERTIssuerAndSNStr { SECItem serialNumber; }; - /* X.509 v3 Key Usage Extension flags */ -#define KU_DIGITAL_SIGNATURE (0x80) /* bit 0 */ -#define KU_NON_REPUDIATION (0x40) /* bit 1 */ -#define KU_KEY_ENCIPHERMENT (0x20) /* bit 2 */ -#define KU_DATA_ENCIPHERMENT (0x10) /* bit 3 */ -#define KU_KEY_AGREEMENT (0x08) /* bit 4 */ -#define KU_KEY_CERT_SIGN (0x04) /* bit 5 */ -#define KU_CRL_SIGN (0x02) /* bit 6 */ -#define KU_ENCIPHER_ONLY (0x01) /* bit 7 */ -#define KU_ALL (KU_DIGITAL_SIGNATURE | \ - KU_NON_REPUDIATION | \ - KU_KEY_ENCIPHERMENT | \ - KU_DATA_ENCIPHERMENT | \ - KU_KEY_AGREEMENT | \ - KU_KEY_CERT_SIGN | \ - KU_CRL_SIGN | \ - KU_ENCIPHER_ONLY) +#define KU_DIGITAL_SIGNATURE (0x80) /* bit 0 */ +#define KU_NON_REPUDIATION (0x40) /* bit 1 */ +#define KU_KEY_ENCIPHERMENT (0x20) /* bit 2 */ +#define KU_DATA_ENCIPHERMENT (0x10) /* bit 3 */ +#define KU_KEY_AGREEMENT (0x08) /* bit 4 */ +#define KU_KEY_CERT_SIGN (0x04) /* bit 5 */ +#define KU_CRL_SIGN (0x02) /* bit 6 */ +#define KU_ENCIPHER_ONLY (0x01) /* bit 7 */ +#define KU_ALL \ + (KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION | KU_KEY_ENCIPHERMENT | \ + KU_DATA_ENCIPHERMENT | KU_KEY_AGREEMENT | KU_KEY_CERT_SIGN | \ + KU_CRL_SIGN | KU_ENCIPHER_ONLY) /* This value will not occur in certs. It is used internally for the case * when either digital signature or non-repudiation is the correct value. @@ -565,40 +555,40 @@ struct CERTIssuerAndSNStr { /* internal bits that do not match bits in the x509v3 spec, but are used * for similar purposes */ -#define KU_NS_GOVT_APPROVED (0x8000) /*don't make part of KU_ALL!*/ +#define KU_NS_GOVT_APPROVED (0x8000) /*don't make part of KU_ALL!*/ /* - * x.509 v3 Basic Constraints Extension - * If isCA is false, the pathLenConstraint is ignored. - * Otherwise, the following pathLenConstraint values will apply: - * < 0 - there is no limit to the certificate path - * 0 - CA can issues end-entity certificates only - * > 0 - the number of certificates in the certificate path is - * limited to this number - */ +* x.509 v3 Basic Constraints Extension +* If isCA is false, the pathLenConstraint is ignored. +* Otherwise, the following pathLenConstraint values will apply: +* < 0 - there is no limit to the certificate path +* 0 - CA can issues end-entity certificates only +* > 0 - the number of certificates in the certificate path is +* limited to this number +*/ #define CERT_UNLIMITED_PATH_CONSTRAINT -2 struct CERTBasicConstraintsStr { - PRBool isCA; /* on if is CA */ - int pathLenConstraint; /* maximum number of certificates that can be - in the cert path. Only applies to a CA - certificate; otherwise, it's ignored. - */ + PRBool isCA; /* on if is CA */ + int pathLenConstraint; /* maximum number of certificates that can be + in the cert path. Only applies to a CA + certificate; otherwise, it's ignored. + */ }; /* Maximum length of a certificate chain */ #define CERT_MAX_CERT_CHAIN 20 -#define CERT_MAX_SERIAL_NUMBER_BYTES 20 /* from RFC 3280 */ -#define CERT_MAX_DN_BYTES 4096 /* arbitrary */ +#define CERT_MAX_SERIAL_NUMBER_BYTES 20 /* from RFC 3280 */ +#define CERT_MAX_DN_BYTES 4096 /* arbitrary */ /* x.509 v3 Reason Flags, used in CRLDistributionPoint Extension */ -#define RF_UNUSED (0x80) /* bit 0 */ -#define RF_KEY_COMPROMISE (0x40) /* bit 1 */ -#define RF_CA_COMPROMISE (0x20) /* bit 2 */ -#define RF_AFFILIATION_CHANGED (0x10) /* bit 3 */ -#define RF_SUPERSEDED (0x08) /* bit 4 */ -#define RF_CESSATION_OF_OPERATION (0x04) /* bit 5 */ -#define RF_CERTIFICATE_HOLD (0x02) /* bit 6 */ +#define RF_UNUSED (0x80) /* bit 0 */ +#define RF_KEY_COMPROMISE (0x40) /* bit 1 */ +#define RF_CA_COMPROMISE (0x20) /* bit 2 */ +#define RF_AFFILIATION_CHANGED (0x10) /* bit 3 */ +#define RF_SUPERSEDED (0x08) /* bit 4 */ +#define RF_CESSATION_OF_OPERATION (0x04) /* bit 5 */ +#define RF_CERTIFICATE_HOLD (0x02) /* bit 6 */ /* enum for CRL Entry Reason Code */ typedef enum CERTCRLEntryReasonCodeEnum { @@ -628,23 +618,20 @@ typedef enum CERTGeneralNameTypeEnum { certRegisterID = 9 } CERTGeneralNameType; - typedef struct OtherNameStr { - SECItem name; - SECItem oid; -}OtherName; - - + SECItem name; + SECItem oid; +} OtherName; struct CERTGeneralNameStr { - CERTGeneralNameType type; /* name type */ + CERTGeneralNameType type; /* name type */ union { - CERTName directoryName; /* distinguish name */ - OtherName OthName; /* Other Name */ - SECItem other; /* the rest of the name forms */ - }name; - SECItem derDirectoryName; /* this is saved to simplify directory name - comparison */ + CERTName directoryName; /* distinguish name */ + OtherName OthName; /* Other Name */ + SECItem other; /* the rest of the name forms */ + } name; + SECItem derDirectoryName; /* this is saved to simplify directory name + comparison */ PRCList l; }; @@ -657,22 +644,20 @@ struct CERTGeneralNameListStr { }; struct CERTNameConstraintStr { - CERTGeneralName name; - SECItem DERName; - SECItem min; - SECItem max; - PRCList l; + CERTGeneralName name; + SECItem DERName; + SECItem min; + SECItem max; + PRCList l; }; - struct CERTNameConstraintsStr { - CERTNameConstraint *permited; - CERTNameConstraint *excluded; - SECItem **DERPermited; - SECItem **DERExcluded; + CERTNameConstraint *permited; + CERTNameConstraint *excluded; + SECItem **DERPermited; + SECItem **DERExcluded; }; - /* Private Key Usage Period extension struct. */ struct CERTPrivKeyUsagePeriodStr { SECItem notBefore; @@ -684,14 +669,14 @@ struct CERTPrivKeyUsagePeriodStr { issuer field, we only support URI now. */ struct CERTAuthKeyIDStr { - SECItem keyID; /* unique key identifier */ - CERTGeneralName *authCertIssuer; /* CA's issuer name. End with a NULL */ - SECItem authCertSerialNumber; /* CA's certificate serial number */ - SECItem **DERAuthCertIssuer; /* This holds the DER encoded format of - the authCertIssuer field. It is used - by the encoding engine. It should be - used as a read only field by the caller. - */ + SECItem keyID; /* unique key identifier */ + CERTGeneralName *authCertIssuer; /* CA's issuer name. End with a NULL */ + SECItem authCertSerialNumber; /* CA's certificate serial number */ + SECItem **DERAuthCertIssuer; /* This holds the DER encoded format of + the authCertIssuer field. It is used + by the encoding engine. It should be + used as a read only field by the caller. + */ }; /* x.509 v3 CRL Distributeion Point */ @@ -700,19 +685,19 @@ struct CERTAuthKeyIDStr { * defined the types of CRL Distribution points */ typedef enum DistributionPointTypesEnum { - generalName = 1, /* only support this for now */ + generalName = 1, /* only support this for now */ relativeDistinguishedName = 2 } DistributionPointTypes; struct CRLDistributionPointStr { DistributionPointTypes distPointType; union { - CERTGeneralName *fullName; - CERTRDN relativeName; + CERTGeneralName *fullName; + CERTRDN relativeName; } distPoint; SECItem reasons; CERTGeneralName *crlIssuer; - + /* Reserved for internal use only*/ SECItem derDistPoint; SECItem derRelativeName; @@ -731,15 +716,14 @@ struct CERTCrlDistributionPointsStr { * once. */ struct CERTVerifyLogNodeStr { - CERTCertificate *cert; /* what cert had the error */ - long error; /* what error was it? */ - unsigned int depth; /* how far up the chain are we */ - void *arg; /* error specific argument */ + CERTCertificate *cert; /* what cert had the error */ + long error; /* what error was it? */ + unsigned int depth; /* how far up the chain are we */ + void *arg; /* error specific argument */ struct CERTVerifyLogNodeStr *next; /* next in the list */ struct CERTVerifyLogNodeStr *prev; /* next in the list */ }; - struct CERTVerifyLogStr { PLArenaPool *arena; unsigned int count; @@ -747,36 +731,32 @@ struct CERTVerifyLogStr { struct CERTVerifyLogNodeStr *tail; }; - struct CERTOKDomainNameStr { CERTOKDomainName *next; - char name[1]; /* actual length may be longer. */ + char name[1]; /* actual length may be longer. */ }; +typedef SECStatus(PR_CALLBACK *CERTStatusChecker)(CERTCertDBHandle *handle, + CERTCertificate *cert, + PRTime time, void *pwArg); -typedef SECStatus (PR_CALLBACK *CERTStatusChecker) (CERTCertDBHandle *handle, - CERTCertificate *cert, - PRTime time, - void *pwArg); - -typedef SECStatus (PR_CALLBACK *CERTStatusDestroy) (CERTStatusConfig *handle); +typedef SECStatus(PR_CALLBACK *CERTStatusDestroy)(CERTStatusConfig *handle); struct CERTStatusConfigStr { - CERTStatusChecker statusChecker; /* NULL means no checking enabled */ - CERTStatusDestroy statusDestroy; /* enabled or no, will clean up */ - void *statusContext; /* cx specific to checking protocol */ + CERTStatusChecker statusChecker; /* NULL means no checking enabled */ + CERTStatusDestroy statusDestroy; /* enabled or no, will clean up */ + void *statusContext; /* cx specific to checking protocol */ }; struct CERTAuthInfoAccessStr { SECItem method; SECItem derLocation; - CERTGeneralName *location; /* decoded location */ + CERTGeneralName *location; /* decoded location */ }; - /* This is the typedef for the callback passed to CERT_OpenCertDB() */ /* callback to return database name based on version number */ -typedef char * (*CERTDBNameFunc)(void *arg, int dbVersion); +typedef char *(*CERTDBNameFunc)(void *arg, int dbVersion); /* * types of cert packages that we can decode @@ -875,10 +855,8 @@ typedef struct { * to indicate an fatal error that will cause path validation to fail * immediately. */ -typedef SECStatus (*CERTChainVerifyCallbackFunc) - (void *isChainValidArg, - const CERTCertList *currentChain, - PRBool *chainOK); +typedef SECStatus (*CERTChainVerifyCallbackFunc)( + void *isChainValidArg, const CERTCertList *currentChain, PRBool *chainOK); /* * Note: If extending this structure, it will be necessary to change the @@ -895,87 +873,91 @@ typedef struct { */ typedef enum { - cert_pi_end = 0, /* SPECIAL: signifies end of array of - * CERTValParam* */ - cert_pi_nbioContext = 1, /* specify a non-blocking IO context used to - * resume a session. If this argument is - * specified, no other arguments should be. - * Specified in value.pointer.p. If the - * operation completes the context will be - * freed. */ - cert_pi_nbioAbort = 2, /* specify a non-blocking IO context for an - * existing operation which the caller wants - * to abort. If this argument is - * specified, no other arguments should be. - * Specified in value.pointer.p. If the - * operation succeeds the context will be - * freed. */ - cert_pi_certList = 3, /* specify the chain to validate against. If - * this value is given, then the path - * construction step in the validation is - * skipped. Specified in value.pointer.chain */ - cert_pi_policyOID = 4, /* validate certificate for policy OID. - * Specified in value.array.oids. Cert must - * be good for at least one OID in order - * to validate. Default is that the user is not - * concerned about certificate policy. */ - cert_pi_policyFlags = 5, /* flags for each policy specified in policyOID. - * Specified in value.scalar.ul. Policy flags - * apply to all specified oids. - * Use CERT_POLICY_FLAG_* macros below. If not - * specified policy flags default to 0 */ - cert_pi_keyusage = 6, /* specify what the keyusages the certificate - * will be evaluated against, specified in - * value.scalar.ui. The cert must validate for - * at least one of the specified key usages. - * Values match the KU_ bit flags defined - * in this file. Default is derived from - * the 'usages' function argument */ - cert_pi_extendedKeyusage= 7, /* specify what the required extended key - * usage of the certificate. Specified as - * an array of oidTags in value.array.oids. - * The cert must validate for at least one - * of the specified extended key usages. - * If not specified, no extended key usages - * will be checked. */ - cert_pi_date = 8, /* validate certificate is valid as of date - * specified in value.scalar.time. A special - * value '0' indicates 'now'. default is '0' */ - cert_pi_revocationFlags = 9, /* Specify what revocation checking to do. - * See CERT_REV_FLAG_* macros below - * Set in value.pointer.revocation */ - cert_pi_certStores = 10,/* Bitmask of Cert Store flags (see below) - * Set in value.scalar.ui */ - cert_pi_trustAnchors = 11,/* Specify the list of trusted roots to - * validate against. - * The default set of trusted roots, these are - * root CA certs from libnssckbi.so or CA - * certs trusted by user, are used in any of - * the following cases: - * * when the parameter is not set. - * * when the list of trust anchors is empty. - * Note that this handling can be further altered by altering the - * cert_pi_useOnlyTrustAnchors flag - * Specified in value.pointer.chain */ - cert_pi_useAIACertFetch = 12, /* Enables cert fetching using AIA extension. - * In NSS 3.12.1 or later. Default is off. - * Value is in value.scalar.b */ - cert_pi_chainVerifyCallback = 13, - /* The callback container for doing extra - * validation on the currently calculated chain. - * Value is in value.pointer.chainVerifyCallback */ - cert_pi_useOnlyTrustAnchors = 14,/* If true, disables trusting any - * certificates other than the ones passed in via cert_pi_trustAnchors. - * If false, then the certificates specified via cert_pi_trustAnchors - * will be combined with the pre-existing trusted roots, but only for - * the certificate validation being performed. - * If no value has been supplied via cert_pi_trustAnchors, this has no - * effect. - * The default value is true, meaning if this is not supplied, only - * trust anchors supplied via cert_pi_trustAnchors are trusted. - * Specified in value.scalar.b */ - cert_pi_max /* SPECIAL: signifies maximum allowed value, - * can increase in future releases */ + cert_pi_end = 0, /* SPECIAL: signifies end of array of + * CERTValParam* */ + cert_pi_nbioContext = 1, /* specify a non-blocking IO context used to + * resume a session. If this argument is + * specified, no other arguments should be. + * Specified in value.pointer.p. If the + * operation completes the context will be + * freed. */ + cert_pi_nbioAbort = 2, /* specify a non-blocking IO context for an + * existing operation which the caller wants + * to abort. If this argument is + * specified, no other arguments should be. + * Specified in value.pointer.p. If the + * operation succeeds the context will be + * freed. */ + cert_pi_certList = 3, /* specify the chain to validate against. If + * this value is given, then the path + * construction step in the validation is + * skipped. Specified in value.pointer.chain */ + cert_pi_policyOID = 4, /* validate certificate for policy OID. + * Specified in value.array.oids. Cert must + * be good for at least one OID in order + * to validate. Default is that the user is not + * concerned about certificate policy. */ + cert_pi_policyFlags = 5, /* flags for each policy specified in policyOID. + * Specified in value.scalar.ul. Policy flags + * apply to all specified oids. + * Use CERT_POLICY_FLAG_* macros below. If not + * specified policy flags default to 0 */ + cert_pi_keyusage = 6, /* specify what the keyusages the certificate + * will be evaluated against, specified in + * value.scalar.ui. The cert must validate for + * at least one of the specified key usages. + * Values match the KU_ bit flags defined + * in this file. Default is derived from + * the 'usages' function argument */ + cert_pi_extendedKeyusage = 7, /* specify what the required extended key + * usage of the certificate. Specified as + * an array of oidTags in value.array.oids. + * The cert must validate for at least one + * of the specified extended key usages. + * If not specified, no extended key usages + * will be checked. */ + cert_pi_date = 8, /* validate certificate is valid as of date + * specified in value.scalar.time. A special + * value '0' indicates 'now'. default is '0' */ + cert_pi_revocationFlags = 9, /* Specify what revocation checking to do. + * See CERT_REV_FLAG_* macros below + * Set in value.pointer.revocation */ + cert_pi_certStores = 10, /* Bitmask of Cert Store flags (see below) + * Set in value.scalar.ui */ + cert_pi_trustAnchors = + 11, /* Specify the list of trusted roots to + * validate against. + * The default set of trusted roots, these are + * root CA certs from libnssckbi.so or CA + * certs trusted by user, are used in any of + * the following cases: + * * when the parameter is not set. + * * when the list of trust anchors is + * empty. + * Note that this handling can be further + * altered by altering the + * cert_pi_useOnlyTrustAnchors flag + * Specified in value.pointer.chain */ + cert_pi_useAIACertFetch = 12, /* Enables cert fetching using AIA extension. + * In NSS 3.12.1 or later. Default is off. + * Value is in value.scalar.b */ + cert_pi_chainVerifyCallback = 13, + /* The callback container for doing extra + * validation on the currently calculated chain. + * Value is in value.pointer.chainVerifyCallback */ + cert_pi_useOnlyTrustAnchors = 14, + /* If true, disables trusting any + * certificates other than the ones passed in via cert_pi_trustAnchors. + * If false, then the certificates specified via cert_pi_trustAnchors + * will be combined with the pre-existing trusted roots, but only + * for the certificate validation being performed. + * If no value has been supplied via cert_pi_trustAnchors, this has + * no effect. + * The default value is true, meaning if this is not supplied, only + * trust anchors supplied via cert_pi_trustAnchors are trusted. + * Specified in value.scalar.b */ + cert_pi_max /* SPECIAL: signifies maximum allowed value, + * can increase in future releases */ } CERTValParamInType; /* @@ -987,39 +969,39 @@ typedef enum { * If SECWouldBlock is returned, only cert_pi_nbioContext is returned. */ typedef enum { - cert_po_end = 0, /* SPECIAL: signifies end of array of - * CERTValParam* */ - cert_po_nbioContext = 1, /* Return a nonblocking context. If no - * non-blocking context is specified, then - * blocking IO will be used. - * Returned in value.pointer.p. The context is - * freed after an abort or a complete operation. - * This value is only returned on SECWouldBlock. - */ - cert_po_trustAnchor = 2, /* Return the trust anchor for the chain that - * was validated. Returned in - * value.pointer.cert, this value is only - * returned on SECSuccess. */ - cert_po_certList = 3, /* Return the entire chain that was validated. - * Returned in value.pointer.certList. If no - * chain could be constructed, this value - * would be NULL. */ - cert_po_policyOID = 4, /* Return the policies that were found to be - * valid. Returned in value.array.oids as an - * array. This is only returned on - * SECSuccess. */ - cert_po_errorLog = 5, /* Return a log of problems with the chain. - * Returned in value.pointer.log */ - cert_po_usages = 6, /* Return what usages the certificate is valid - for. Returned in value.scalar.usages */ - cert_po_keyUsage = 7, /* Return what key usages the certificate - * is valid for. - * Returned in value.scalar.usage */ - cert_po_extendedKeyusage= 8, /* Return what extended key usages the - * certificate is valid for. - * Returned in value.array.oids */ - cert_po_max /* SPECIAL: signifies maximum allowed value, - * can increase in future releases */ + cert_po_end = 0, /* SPECIAL: signifies end of array of + * CERTValParam* */ + cert_po_nbioContext = 1, /* Return a nonblocking context. If no + * non-blocking context is specified, then + * blocking IO will be used. + * Returned in value.pointer.p. The context is + * freed after an abort or a complete operation. + * This value is only returned on SECWouldBlock. + */ + cert_po_trustAnchor = 2, /* Return the trust anchor for the chain that + * was validated. Returned in + * value.pointer.cert, this value is only + * returned on SECSuccess. */ + cert_po_certList = 3, /* Return the entire chain that was validated. + * Returned in value.pointer.certList. If no + * chain could be constructed, this value + * would be NULL. */ + cert_po_policyOID = 4, /* Return the policies that were found to be + * valid. Returned in value.array.oids as an + * array. This is only returned on + * SECSuccess. */ + cert_po_errorLog = 5, /* Return a log of problems with the chain. + * Returned in value.pointer.log */ + cert_po_usages = 6, /* Return what usages the certificate is valid + for. Returned in value.scalar.usages */ + cert_po_keyUsage = 7, /* Return what key usages the certificate + * is valid for. + * Returned in value.scalar.usage */ + cert_po_extendedKeyusage = 8, /* Return what extended key usages the + * certificate is valid for. + * Returned in value.array.oids */ + cert_po_max /* SPECIAL: signifies maximum allowed value, + * can increase in future releases */ } CERTValParamOutType; @@ -1029,7 +1011,6 @@ typedef enum { cert_revocation_method_count } CERTRevocationMethodIndex; - /* * The following flags are supposed to be used to control bits in * each integer contained in the array pointed to be: @@ -1042,8 +1023,8 @@ typedef enum { * Whether or not to use a method for revocation testing. * If set to "do not test", then all other flags are ignored. */ -#define CERT_REV_M_DO_NOT_TEST_USING_THIS_METHOD 0UL -#define CERT_REV_M_TEST_USING_THIS_METHOD 1UL +#define CERT_REV_M_DO_NOT_TEST_USING_THIS_METHOD 0UL +#define CERT_REV_M_TEST_USING_THIS_METHOD 1UL /* * Whether or not NSS is allowed to attempt to fetch fresh information @@ -1051,8 +1032,8 @@ typedef enum { * (Although fetching will never happen if fresh information for the * method is already locally available.) */ -#define CERT_REV_M_ALLOW_NETWORK_FETCHING 0UL -#define CERT_REV_M_FORBID_NETWORK_FETCHING 2UL +#define CERT_REV_M_ALLOW_NETWORK_FETCHING 0UL +#define CERT_REV_M_FORBID_NETWORK_FETCHING 2UL /* * Example for an implicit default source: @@ -1060,14 +1041,14 @@ typedef enum { * IGNORE means: * ignore the implicit default source, whether it's configured or not. * ALLOW means: - * if an implicit default source is configured, + * if an implicit default source is configured, * then it overrides any available or missing source in the cert. * if no implicit default source is configured, - * then we continue to use what's available (or not available) + * then we continue to use what's available (or not available) * in the certs. - */ -#define CERT_REV_M_ALLOW_IMPLICIT_DEFAULT_SOURCE 0UL -#define CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE 4UL + */ +#define CERT_REV_M_ALLOW_IMPLICIT_DEFAULT_SOURCE 0UL +#define CERT_REV_M_IGNORE_IMPLICIT_DEFAULT_SOURCE 4UL /* * Defines the behavior if no fresh information is available, @@ -1075,14 +1056,14 @@ typedef enum { * information is unknown (even after considering implicit sources, * if allowed by other flags). * SKIPT_TEST means: - * We ignore that no fresh information is available and + * We ignore that no fresh information is available and * skip this test. * REQUIRE_INFO means: * We still require that fresh information is available. * Other flags define what happens on missing fresh info. */ -#define CERT_REV_M_SKIP_TEST_ON_MISSING_SOURCE 0UL -#define CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE 8UL +#define CERT_REV_M_SKIP_TEST_ON_MISSING_SOURCE 0UL +#define CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE 8UL /* * Defines the behavior if we are unable to obtain fresh information. @@ -1091,8 +1072,8 @@ typedef enum { * FAIL means: * Return "cert revoked". */ -#define CERT_REV_M_IGNORE_MISSING_FRESH_INFO 0UL -#define CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO 16UL +#define CERT_REV_M_IGNORE_MISSING_FRESH_INFO 0UL +#define CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO 16UL /* * What should happen if we were able to find fresh information using @@ -1104,8 +1085,8 @@ typedef enum { * We will continue and test the next allowed * specified method. */ -#define CERT_REV_M_STOP_TESTING_ON_FRESH_INFO 0UL -#define CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO 32UL +#define CERT_REV_M_STOP_TESTING_ON_FRESH_INFO 0UL +#define CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO 32UL /* When this flag is used, libpkix will never attempt to use the GET HTTP * method for OCSP requests; it will always use POST. @@ -1131,8 +1112,8 @@ typedef enum { * which are already locally available. Only after that is done * consider to fetch from the network (as allowed by other flags). */ -#define CERT_REV_MI_TEST_EACH_METHOD_SEPARATELY 0UL -#define CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST 1UL +#define CERT_REV_MI_TEST_EACH_METHOD_SEPARATELY 0UL +#define CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST 1UL /* * Use this flag to specify that it's necessary that fresh information @@ -1147,10 +1128,9 @@ typedef enum { * This setting overrides the CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO * flag on all methods. */ -#define CERT_REV_MI_NO_OVERALL_INFO_REQUIREMENT 0UL +#define CERT_REV_MI_NO_OVERALL_INFO_REQUIREMENT 0UL #define CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE 2UL - typedef struct { /* * The size of the array that cert_rev_flags_per_method points to, @@ -1163,20 +1143,20 @@ typedef struct { * A pointer to an array of integers. * Each integer defines revocation checking for a single method, * by having individual CERT_REV_M_* bits set or not set. - * The meaning of index numbers into this array are defined by + * The meaning of index numbers into this array are defined by * enum CERTRevocationMethodIndex * The size of the array must be specified by the caller in the separate * variable number_of_defined_methods. - * The size of the array may be smaller than + * The size of the array may be smaller than * cert_revocation_method_count, it can happen if a caller * is not yet aware of the latest revocation methods * (or does not want to use them). - */ + */ PRUint64 *cert_rev_flags_per_method; /* * How many preferred methods are specified? - * This is equivalent to the size of the array that + * This is equivalent to the size of the array that * preferred_methods points to. * It's allowed to set this value to zero, * then NSS will decide which methods to prefer. @@ -1207,50 +1187,49 @@ typedef struct { typedef struct CERTValParamInValueStr { union { - PRBool b; - PRInt32 i; + PRBool b; + PRInt32 i; PRUint32 ui; - PRInt64 l; + PRInt64 l; PRUint64 ul; PRTime time; } scalar; union { - const void* p; - const char* s; - const CERTCertificate* cert; + const void *p; + const char *s; + const CERTCertificate *cert; const CERTCertList *chain; const CERTRevocationFlags *revocation; const CERTChainVerifyCallback *chainVerifyCallback; } pointer; union { - const PRInt32 *pi; + const PRInt32 *pi; const PRUint32 *pui; - const PRInt64 *pl; + const PRInt64 *pl; const PRUint64 *pul; const SECOidTag *oids; } array; int arraySize; } CERTValParamInValue; - typedef struct CERTValParamOutValueStr { union { - PRBool b; - PRInt32 i; + PRBool b; + PRInt32 i; PRUint32 ui; - PRInt64 l; + PRInt64 l; PRUint64 ul; SECCertificateUsage usages; } scalar; union { - void* p; - char* s; + void *p; + char *s; CERTVerifyLog *log; - CERTCertificate* cert; + CERTCertificate *cert; CERTCertList *chain; } pointer; union { - void *p; + void *p; SECOidTag *oids; } array; int arraySize; @@ -1270,35 +1249,35 @@ typedef struct { * Levels of standards conformance strictness for CERT_NameToAsciiInvertible */ typedef enum CertStrictnessLevels { - CERT_N2A_READABLE = 0, /* maximum human readability */ - CERT_N2A_STRICT = 10, /* strict RFC compliance */ - CERT_N2A_INVERTIBLE = 20 /* maximum invertibility, - all DirectoryStrings encoded in hex */ + CERT_N2A_READABLE = 0, /* maximum human readability */ + CERT_N2A_STRICT = 10, /* strict RFC compliance */ + CERT_N2A_INVERTIBLE = 20 /* maximum invertibility, + all DirectoryStrings encoded in hex */ } CertStrictnessLevel; /* * policy flag defines */ -#define CERT_POLICY_FLAG_NO_MAPPING 1 -#define CERT_POLICY_FLAG_EXPLICIT 2 -#define CERT_POLICY_FLAG_NO_ANY 4 +#define CERT_POLICY_FLAG_NO_MAPPING 1 +#define CERT_POLICY_FLAG_EXPLICIT 2 +#define CERT_POLICY_FLAG_NO_ANY 4 /* * CertStore flags */ -#define CERT_ENABLE_LDAP_FETCH 1 -#define CERT_ENABLE_HTTP_FETCH 2 +#define CERT_ENABLE_LDAP_FETCH 1 +#define CERT_ENABLE_HTTP_FETCH 2 /* This functin pointer type may be used for any function that takes * a CERTCertificate * and returns an allocated string, which must be * freed by a call to PORT_Free. */ -typedef char * (*CERT_StringFromCertFcn)(CERTCertificate *cert); +typedef char *(*CERT_StringFromCertFcn)(CERTCertificate *cert); /* XXX Lisa thinks the template declarations belong in cert.h, not here? */ -#include "secasn1t.h" /* way down here because I expect template stuff to - * move out of here anyway */ +#include "secasn1t.h" /* way down here because I expect template stuff to + * move out of here anyway */ SEC_BEGIN_PROTOS diff --git a/security/nss/lib/certdb/certv3.c b/security/nss/lib/certdb/certv3.c index 1735b5e44cd8..da4bb270e693 100644 --- a/security/nss/lib/certdb/certv3.c +++ b/security/nss/lib/certdb/certv3.c @@ -15,17 +15,15 @@ #include "secerr.h" SECStatus -CERT_FindCertExtensionByOID(CERTCertificate *cert, SECItem *oid, - SECItem *value) +CERT_FindCertExtensionByOID(CERTCertificate *cert, SECItem *oid, SECItem *value) { - return (cert_FindExtensionByOID (cert->extensions, oid, value)); + return (cert_FindExtensionByOID(cert->extensions, oid, value)); } - SECStatus CERT_FindCertExtension(const CERTCertificate *cert, int tag, SECItem *value) { - return (cert_FindExtension (cert->extensions, tag, value)); + return (cert_FindExtension(cert->extensions, tag, value)); } static void @@ -34,13 +32,13 @@ SetExts(void *object, CERTCertExtension **exts) CERTCertificate *cert = (CERTCertificate *)object; cert->extensions = exts; - DER_SetUInteger (cert->arena, &(cert->version), SEC_CERTIFICATE_VERSION_3); + DER_SetUInteger(cert->arena, &(cert->version), SEC_CERTIFICATE_VERSION_3); } void * CERT_StartCertExtensions(CERTCertificate *cert) { - return (cert_StartExtensions ((void *)cert, cert->arena, SetExts)); + return (cert_StartExtensions((void *)cert, cert->arena, SetExts)); } /* @@ -50,62 +48,60 @@ SECStatus CERT_FindNSCertTypeExtension(CERTCertificate *cert, SECItem *retItem) { - return (CERT_FindBitStringExtension - (cert->extensions, SEC_OID_NS_CERT_EXT_CERT_TYPE, retItem)); + return (CERT_FindBitStringExtension( + cert->extensions, SEC_OID_NS_CERT_EXT_CERT_TYPE, retItem)); } - /* * get the value of a string type extension */ char * CERT_FindNSStringExtension(CERTCertificate *cert, int oidtag) { - SECItem wrapperItem, tmpItem = {siBuffer,0}; + SECItem wrapperItem, tmpItem = { siBuffer, 0 }; SECStatus rv; PLArenaPool *arena = NULL; char *retstring = NULL; - + wrapperItem.data = NULL; tmpItem.data = NULL; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( ! arena ) { - goto loser; - } - - rv = cert_FindExtension(cert->extensions, oidtag, - &wrapperItem); - if ( rv != SECSuccess ) { - goto loser; + + if (!arena) { + goto loser; } - rv = SEC_QuickDERDecodeItem(arena, &tmpItem, - SEC_ASN1_GET(SEC_IA5StringTemplate), &wrapperItem); - - if ( rv != SECSuccess ) { - goto loser; + rv = cert_FindExtension(cert->extensions, oidtag, &wrapperItem); + if (rv != SECSuccess) { + goto loser; } - retstring = (char *)PORT_Alloc(tmpItem.len + 1 ); - if ( retstring == NULL ) { - goto loser; + rv = SEC_QuickDERDecodeItem( + arena, &tmpItem, SEC_ASN1_GET(SEC_IA5StringTemplate), &wrapperItem); + + if (rv != SECSuccess) { + goto loser; } - + + retstring = (char *)PORT_Alloc(tmpItem.len + 1); + if (retstring == NULL) { + goto loser; + } + PORT_Memcpy(retstring, tmpItem.data, tmpItem.len); retstring[tmpItem.len] = '\0'; loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - if ( wrapperItem.data ) { - PORT_Free(wrapperItem.data); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - return(retstring); + if (wrapperItem.data) { + PORT_Free(wrapperItem.data); + } + + return (retstring); } /* @@ -116,7 +112,7 @@ CERT_FindKeyUsageExtension(CERTCertificate *cert, SECItem *retItem) { return (CERT_FindBitStringExtension(cert->extensions, - SEC_OID_X509_KEY_USAGE, retItem)); + SEC_OID_X509_KEY_USAGE, retItem)); } /* @@ -127,24 +123,25 @@ CERT_FindSubjectKeyIDExtension(CERTCertificate *cert, SECItem *retItem) { SECStatus rv; - SECItem encodedValue = {siBuffer, NULL, 0 }; - SECItem decodedValue = {siBuffer, NULL, 0 }; + SECItem encodedValue = { siBuffer, NULL, 0 }; + SECItem decodedValue = { siBuffer, NULL, 0 }; - rv = cert_FindExtension - (cert->extensions, SEC_OID_X509_SUBJECT_KEY_ID, &encodedValue); + rv = cert_FindExtension(cert->extensions, SEC_OID_X509_SUBJECT_KEY_ID, + &encodedValue); if (rv == SECSuccess) { - PLArenaPool * tmpArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (tmpArena) { - rv = SEC_QuickDERDecodeItem(tmpArena, &decodedValue, - SEC_ASN1_GET(SEC_OctetStringTemplate), - &encodedValue); - if (rv == SECSuccess) { - rv = SECITEM_CopyItem(NULL, retItem, &decodedValue); - } - PORT_FreeArena(tmpArena, PR_FALSE); - } else { - rv = SECFailure; - } + PLArenaPool *tmpArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (tmpArena) { + rv = SEC_QuickDERDecodeItem(tmpArena, &decodedValue, + SEC_ASN1_GET(SEC_OctetStringTemplate), + &encodedValue); + if (rv == SECSuccess) { + rv = SECITEM_CopyItem(NULL, retItem, &decodedValue); + } + PORT_FreeArena(tmpArena, PR_FALSE); + } + else { + rv = SECFailure; + } } SECITEM_FreeItem(&encodedValue, PR_FALSE); return rv; @@ -152,7 +149,7 @@ CERT_FindSubjectKeyIDExtension(CERTCertificate *cert, SECItem *retItem) SECStatus CERT_FindBasicConstraintExten(CERTCertificate *cert, - CERTBasicConstraints *value) + CERTBasicConstraints *value) { SECItem encodedExtenValue; SECStatus rv; @@ -161,42 +158,42 @@ CERT_FindBasicConstraintExten(CERTCertificate *cert, encodedExtenValue.len = 0; rv = cert_FindExtension(cert->extensions, SEC_OID_X509_BASIC_CONSTRAINTS, - &encodedExtenValue); - if ( rv != SECSuccess ) { - return (rv); + &encodedExtenValue); + if (rv != SECSuccess) { + return (rv); } - rv = CERT_DecodeBasicConstraintValue (value, &encodedExtenValue); - + rv = CERT_DecodeBasicConstraintValue(value, &encodedExtenValue); + /* free the raw extension data */ PORT_Free(encodedExtenValue.data); encodedExtenValue.data = NULL; - - return(rv); + + return (rv); } CERTAuthKeyID * -CERT_FindAuthKeyIDExten (PLArenaPool *arena, CERTCertificate *cert) +CERT_FindAuthKeyIDExten(PLArenaPool *arena, CERTCertificate *cert) { SECItem encodedExtenValue; SECStatus rv; CERTAuthKeyID *ret; - + encodedExtenValue.data = NULL; encodedExtenValue.len = 0; rv = cert_FindExtension(cert->extensions, SEC_OID_X509_AUTH_KEY_ID, - &encodedExtenValue); - if ( rv != SECSuccess ) { - return (NULL); + &encodedExtenValue); + if (rv != SECSuccess) { + return (NULL); } - ret = CERT_DecodeAuthKeyID (arena, &encodedExtenValue); + ret = CERT_DecodeAuthKeyID(arena, &encodedExtenValue); PORT_Free(encodedExtenValue.data); encodedExtenValue.data = NULL; - - return(ret); + + return (ret); } SECStatus @@ -207,9 +204,9 @@ CERT_CheckCertUsage(CERTCertificate *cert, unsigned char usage) /* There is no extension, v1 or v2 certificate */ if (cert->extensions == NULL) { - return (SECSuccess); + return (SECSuccess); } - + keyUsage.data = NULL; /* This code formerly ignored the Key Usage extension if it was @@ -218,12 +215,13 @@ CERT_CheckCertUsage(CERTCertificate *cert, unsigned char usage) */ rv = CERT_FindKeyUsageExtension(cert, &keyUsage); if (rv == SECFailure) { - rv = (PORT_GetError () == SEC_ERROR_EXTENSION_NOT_FOUND) ? - SECSuccess : SECFailure; - } else if (!(keyUsage.data[0] & usage)) { - PORT_SetError (SEC_ERROR_CERT_USAGES_INVALID); - rv = SECFailure; + rv = (PORT_GetError() == SEC_ERROR_EXTENSION_NOT_FOUND) ? SECSuccess + : SECFailure; } - PORT_Free (keyUsage.data); + else if (!(keyUsage.data[0] & usage)) { + PORT_SetError(SEC_ERROR_CERT_USAGES_INVALID); + rv = SECFailure; + } + PORT_Free(keyUsage.data); return (rv); } diff --git a/security/nss/lib/certdb/certxutl.c b/security/nss/lib/certdb/certxutl.c index 67dd1a17329c..81070f3a376a 100644 --- a/security/nss/lib/certdb/certxutl.c +++ b/security/nss/lib/certdb/certxutl.c @@ -16,93 +16,93 @@ #include "secerr.h" #ifdef OLD -#include "ocspti.h" /* XXX a better extensions interface would not +#include "ocspti.h" /* XXX a better extensions interface would not * require knowledge of data structures of callers */ #endif static CERTCertExtension * -GetExtension (CERTCertExtension **extensions, SECItem *oid) +GetExtension(CERTCertExtension **extensions, SECItem *oid) { CERTCertExtension **exts; CERTCertExtension *ext = NULL; SECComparison comp; exts = extensions; - - if (exts) { - while ( *exts ) { - ext = *exts; - comp = SECITEM_CompareItem(oid, &ext->id); - if ( comp == SECEqual ) - break; - exts++; - } - return (*exts ? ext : NULL); + if (exts) { + while (*exts) { + ext = *exts; + comp = SECITEM_CompareItem(oid, &ext->id); + if (comp == SECEqual) + break; + + exts++; + } + return (*exts ? ext : NULL); } return (NULL); } SECStatus -cert_FindExtensionByOID (CERTCertExtension **extensions, SECItem *oid, SECItem *value) +cert_FindExtensionByOID(CERTCertExtension **extensions, SECItem *oid, + SECItem *value) { CERTCertExtension *ext; SECStatus rv = SECSuccess; - - ext = GetExtension (extensions, oid); + + ext = GetExtension(extensions, oid); if (ext == NULL) { - PORT_SetError (SEC_ERROR_EXTENSION_NOT_FOUND); - return (SECFailure); + PORT_SetError(SEC_ERROR_EXTENSION_NOT_FOUND); + return (SECFailure); } if (value) - rv = SECITEM_CopyItem(NULL, value, &ext->value); + rv = SECITEM_CopyItem(NULL, value, &ext->value); return (rv); } - SECStatus -CERT_GetExtenCriticality (CERTCertExtension **extensions, int tag, PRBool *isCritical) +CERT_GetExtenCriticality(CERTCertExtension **extensions, int tag, + PRBool *isCritical) { CERTCertExtension *ext; SECOidData *oid; if (!isCritical) - return (SECSuccess); - + return (SECSuccess); + /* find the extension in the extensions list */ oid = SECOID_FindOIDByTag((SECOidTag)tag); - if ( !oid ) { - return(SECFailure); + if (!oid) { + return (SECFailure); } - ext = GetExtension (extensions, &oid->oid); + ext = GetExtension(extensions, &oid->oid); if (ext == NULL) { - PORT_SetError (SEC_ERROR_EXTENSION_NOT_FOUND); - return (SECFailure); + PORT_SetError(SEC_ERROR_EXTENSION_NOT_FOUND); + return (SECFailure); } /* If the criticality is omitted, then it is false by default. ex->critical.data is NULL */ if (ext->critical.data == NULL) - *isCritical = PR_FALSE; + *isCritical = PR_FALSE; else - *isCritical = (ext->critical.data[0] == 0xff) ? PR_TRUE : PR_FALSE; - return (SECSuccess); + *isCritical = (ext->critical.data[0] == 0xff) ? PR_TRUE : PR_FALSE; + return (SECSuccess); } SECStatus cert_FindExtension(CERTCertExtension **extensions, int tag, SECItem *value) { SECOidData *oid; - + oid = SECOID_FindOIDByTag((SECOidTag)tag); - if ( !oid ) { - return(SECFailure); + if (!oid) { + return (SECFailure); } - return(cert_FindExtensionByOID(extensions, &oid->oid, value)); + return (cert_FindExtensionByOID(extensions, &oid->oid, value)); } - typedef struct _extNode { struct _extNode *next; CERTCertExtension *ext; @@ -115,7 +115,7 @@ typedef struct { PLArenaPool *arena; extNode *head; int count; -}extRec; +} extRec; /* * cert_StartExtensions @@ -125,20 +125,20 @@ typedef struct { */ void * cert_StartExtensions(void *owner, PLArenaPool *ownerArena, - void (*setExts)(void *object, CERTCertExtension **exts)) + void (*setExts)(void *object, CERTCertExtension **exts)) { PLArenaPool *arena; extRec *handle; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - return(0); + if (!arena) { + return (0); } handle = (extRec *)PORT_ArenaAlloc(arena, sizeof(extRec)); - if ( !handle ) { - PORT_FreeArena(arena, PR_FALSE); - return(0); + if (!handle) { + PORT_FreeArena(arena, PR_FALSE); + return (0); } handle->object = owner; @@ -148,8 +148,8 @@ cert_StartExtensions(void *owner, PLArenaPool *ownerArena, handle->arena = arena; handle->head = 0; handle->count = 0; - - return(handle); + + return (handle); } static unsigned char hextrue = 0xff; @@ -158,77 +158,78 @@ static unsigned char hextrue = 0xff; * Note - assumes that data pointed to by oid->data will not move */ SECStatus -CERT_AddExtensionByOID (void *exthandle, SECItem *oid, SECItem *value, - PRBool critical, PRBool copyData) +CERT_AddExtensionByOID(void *exthandle, SECItem *oid, SECItem *value, + PRBool critical, PRBool copyData) { CERTCertExtension *ext; SECStatus rv; extNode *node; extRec *handle; - + handle = (extRec *)exthandle; /* allocate space for extension and list node */ - ext = (CERTCertExtension*)PORT_ArenaZAlloc(handle->ownerArena, - sizeof(CERTCertExtension)); - if ( !ext ) { - return(SECFailure); + ext = (CERTCertExtension *)PORT_ArenaZAlloc(handle->ownerArena, + sizeof(CERTCertExtension)); + if (!ext) { + return (SECFailure); } - node = (extNode*)PORT_ArenaAlloc(handle->arena, sizeof(extNode)); - if ( !node ) { - return(SECFailure); + node = (extNode *)PORT_ArenaAlloc(handle->arena, sizeof(extNode)); + if (!node) { + return (SECFailure); } /* add to list */ node->next = handle->head; handle->head = node; - + /* point to ext struct */ node->ext = ext; - + /* the object ID of the extension */ ext->id = *oid; - + /* set critical field */ - if ( critical ) { - ext->critical.data = (unsigned char*)&hextrue; - ext->critical.len = 1; + if (critical) { + ext->critical.data = (unsigned char *)&hextrue; + ext->critical.len = 1; } /* set the value */ - if ( copyData ) { - rv = SECITEM_CopyItem(handle->ownerArena, &ext->value, value); - if ( rv ) { - return(SECFailure); - } - } else { - ext->value = *value; + if (copyData) { + rv = SECITEM_CopyItem(handle->ownerArena, &ext->value, value); + if (rv) { + return (SECFailure); + } + } + else { + ext->value = *value; } - - handle->count++; - - return(SECSuccess); + handle->count++; + + return (SECSuccess); } SECStatus -CERT_AddExtension(void *exthandle, int idtag, SECItem *value, - PRBool critical, PRBool copyData) +CERT_AddExtension(void *exthandle, int idtag, SECItem *value, PRBool critical, + PRBool copyData) { SECOidData *oid; - + oid = SECOID_FindOIDByTag((SECOidTag)idtag); - if ( !oid ) { - return(SECFailure); + if (!oid) { + return (SECFailure); } - return(CERT_AddExtensionByOID(exthandle, &oid->oid, value, critical, copyData)); + return (CERT_AddExtensionByOID(exthandle, &oid->oid, value, critical, + copyData)); } SECStatus CERT_EncodeAndAddExtension(void *exthandle, int idtag, void *value, - PRBool critical, const SEC_ASN1Template *atemplate) + PRBool critical, const SEC_ASN1Template *atemplate) { extRec *handle; SECItem *encitem; @@ -236,45 +237,43 @@ CERT_EncodeAndAddExtension(void *exthandle, int idtag, void *value, handle = (extRec *)exthandle; encitem = SEC_ASN1EncodeItem(handle->ownerArena, NULL, value, atemplate); - if ( encitem == NULL ) { - return(SECFailure); + if (encitem == NULL) { + return (SECFailure); } return CERT_AddExtension(exthandle, idtag, encitem, critical, PR_FALSE); } void -PrepareBitStringForEncoding (SECItem *bitsmap, SECItem *value) +PrepareBitStringForEncoding(SECItem *bitsmap, SECItem *value) { - unsigned char onebyte; - unsigned int i, len = 0; + unsigned char onebyte; + unsigned int i, len = 0; - /* to prevent warning on some platform at compile time */ - onebyte = '\0'; - /* Get the position of the right-most turn-on bit */ - for (i = 0; i < (value->len ) * 8; ++i) { - if (i % 8 == 0) - onebyte = value->data[i/8]; - if (onebyte & 0x80) - len = i; - onebyte <<= 1; - - } - bitsmap->data = value->data; - /* Add one here since we work with base 1 */ - bitsmap->len = len + 1; + /* to prevent warning on some platform at compile time */ + onebyte = '\0'; + /* Get the position of the right-most turn-on bit */ + for (i = 0; i < (value->len) * 8; ++i) { + if (i % 8 == 0) + onebyte = value->data[i / 8]; + if (onebyte & 0x80) + len = i; + onebyte <<= 1; + } + bitsmap->data = value->data; + /* Add one here since we work with base 1 */ + bitsmap->len = len + 1; } SECStatus -CERT_EncodeAndAddBitStrExtension (void *exthandle, int idtag, - SECItem *value, PRBool critical) +CERT_EncodeAndAddBitStrExtension(void *exthandle, int idtag, SECItem *value, + PRBool critical) { - SECItem bitsmap; - - PrepareBitStringForEncoding (&bitsmap, value); - return (CERT_EncodeAndAddExtension - (exthandle, idtag, &bitsmap, critical, - SEC_ASN1_GET(SEC_BitStringTemplate))); + SECItem bitsmap; + + PrepareBitStringForEncoding(&bitsmap, value); + return (CERT_EncodeAndAddExtension(exthandle, idtag, &bitsmap, critical, + SEC_ASN1_GET(SEC_BitStringTemplate))); } SECStatus @@ -284,53 +283,53 @@ CERT_FinishExtensions(void *exthandle) extNode *node; CERTCertExtension **exts; SECStatus rv = SECFailure; - + handle = (extRec *)exthandle; /* allocate space for extensions array */ exts = PORT_ArenaNewArray(handle->ownerArena, CERTCertExtension *, - handle->count + 1); + handle->count + 1); if (exts == NULL) { - goto loser; + goto loser; } - /* put extensions in owner object and update its version number */ +/* put extensions in owner object and update its version number */ #ifdef OLD switch (handle->type) { - case CertificateExtensions: - handle->owner.cert->extensions = exts; - DER_SetUInteger (ownerArena, &(handle->owner.cert->version), - SEC_CERTIFICATE_VERSION_3); - break; - case CrlExtensions: - handle->owner.crl->extensions = exts; - DER_SetUInteger (ownerArena, &(handle->owner.crl->version), - SEC_CRL_VERSION_2); - break; - case OCSPRequestExtensions: - handle->owner.request->tbsRequest->requestExtensions = exts; - break; - case OCSPSingleRequestExtensions: - handle->owner.singleRequest->singleRequestExtensions = exts; - break; - case OCSPResponseSingleExtensions: - handle->owner.singleResponse->singleExtensions = exts; - break; + case CertificateExtensions: + handle->owner.cert->extensions = exts; + DER_SetUInteger(ownerArena, &(handle->owner.cert->version), + SEC_CERTIFICATE_VERSION_3); + break; + case CrlExtensions: + handle->owner.crl->extensions = exts; + DER_SetUInteger(ownerArena, &(handle->owner.crl->version), + SEC_CRL_VERSION_2); + break; + case OCSPRequestExtensions: + handle->owner.request->tbsRequest->requestExtensions = exts; + break; + case OCSPSingleRequestExtensions: + handle->owner.singleRequest->singleRequestExtensions = exts; + break; + case OCSPResponseSingleExtensions: + handle->owner.singleResponse->singleExtensions = exts; + break; } #endif handle->setExts(handle->object, exts); - + /* update the version number */ /* copy each extension pointer */ node = handle->head; - while ( node ) { - *exts = node->ext; - - node = node->next; - exts++; + while (node) { + *exts = node->ext; + + node = node->next; + exts++; } /* terminate the array of extensions */ @@ -352,14 +351,14 @@ CERT_MergeExtensions(void *exthandle, CERTCertExtension **extensions) SECOidTag tag; extNode *node; extRec *handle = exthandle; - + if (!exthandle || !extensions) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } while ((ext = *extensions++) != NULL) { tag = SECOID_FindOIDTag(&ext->id); - for (node=handle->head; node != NULL; node=node->next) { + for (node = handle->head; node != NULL; node = node->next) { if (tag == 0) { if (SECITEM_ItemsAreEqual(&ext->id, &node->ext->id)) break; @@ -372,15 +371,15 @@ CERT_MergeExtensions(void *exthandle, CERTCertExtension **extensions) } if (node == NULL) { PRBool critical = (ext->critical.len != 0 && - ext->critical.data[ext->critical.len - 1] != 0); + ext->critical.data[ext->critical.len - 1] != 0); if (critical && tag == SEC_OID_UNKNOWN) { - PORT_SetError(SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION); - rv = SECFailure; - break; + PORT_SetError(SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION); + rv = SECFailure; + break; } /* add to list */ - rv = CERT_AddExtensionByOID (exthandle, &ext->id, &ext->value, - critical, PR_TRUE); + rv = CERT_AddExtensionByOID(exthandle, &ext->id, &ext->value, + critical, PR_TRUE); if (rv != SECSuccess) break; } @@ -392,108 +391,107 @@ CERT_MergeExtensions(void *exthandle, CERTCertExtension **extensions) * get the value of the Netscape Certificate Type Extension */ SECStatus -CERT_FindBitStringExtension (CERTCertExtension **extensions, int tag, - SECItem *retItem) +CERT_FindBitStringExtension(CERTCertExtension **extensions, int tag, + SECItem *retItem) { - SECItem wrapperItem, tmpItem = {siBuffer,0}; + SECItem wrapperItem, tmpItem = { siBuffer, 0 }; SECStatus rv; PLArenaPool *arena = NULL; - + wrapperItem.data = NULL; tmpItem.data = NULL; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( ! arena ) { - return(SECFailure); + + if (!arena) { + return (SECFailure); } - + rv = cert_FindExtension(extensions, tag, &wrapperItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - rv = SEC_QuickDERDecodeItem(arena, &tmpItem, - SEC_ASN1_GET(SEC_BitStringTemplate), - &wrapperItem); + rv = SEC_QuickDERDecodeItem( + arena, &tmpItem, SEC_ASN1_GET(SEC_BitStringTemplate), &wrapperItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - retItem->data = (unsigned char *)PORT_Alloc( ( tmpItem.len + 7 ) >> 3 ); - if ( retItem->data == NULL ) { - goto loser; + retItem->data = (unsigned char *)PORT_Alloc((tmpItem.len + 7) >> 3); + if (retItem->data == NULL) { + goto loser; } - - PORT_Memcpy(retItem->data, tmpItem.data, ( tmpItem.len + 7 ) >> 3); + + PORT_Memcpy(retItem->data, tmpItem.data, (tmpItem.len + 7) >> 3); retItem->len = tmpItem.len; - + rv = SECSuccess; goto done; - + loser: rv = SECFailure; done: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - } - - if ( wrapperItem.data ) { - PORT_Free(wrapperItem.data); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - return(rv); + if (wrapperItem.data) { + PORT_Free(wrapperItem.data); + } + + return (rv); } PRBool -cert_HasCriticalExtension (CERTCertExtension **extensions) +cert_HasCriticalExtension(CERTCertExtension **extensions) { CERTCertExtension **exts; CERTCertExtension *ext = NULL; PRBool hasCriticalExten = PR_FALSE; - + exts = extensions; - + if (exts) { - while ( *exts ) { - ext = *exts; - /* If the criticality is omitted, it's non-critical */ - if (ext->critical.data && ext->critical.data[0] == 0xff) { - hasCriticalExten = PR_TRUE; - break; - } - exts++; - } + while (*exts) { + ext = *exts; + /* If the criticality is omitted, it's non-critical */ + if (ext->critical.data && ext->critical.data[0] == 0xff) { + hasCriticalExten = PR_TRUE; + break; + } + exts++; + } } return (hasCriticalExten); } PRBool -cert_HasUnknownCriticalExten (CERTCertExtension **extensions) +cert_HasUnknownCriticalExten(CERTCertExtension **extensions) { CERTCertExtension **exts; CERTCertExtension *ext = NULL; PRBool hasUnknownCriticalExten = PR_FALSE; - + exts = extensions; - + if (exts) { - while ( *exts ) { - ext = *exts; - /* If the criticality is omitted, it's non-critical. - If an extension is critical, make sure that we know - how to process the extension. + while (*exts) { + ext = *exts; + /* If the criticality is omitted, it's non-critical. + If an extension is critical, make sure that we know + how to process the extension. */ - if (ext->critical.data && ext->critical.data[0] == 0xff) { - if (SECOID_KnownCertExtenOID (&ext->id) == PR_FALSE) { - hasUnknownCriticalExten = PR_TRUE; - break; - } - } - exts++; - } + if (ext->critical.data && ext->critical.data[0] == 0xff) { + if (SECOID_KnownCertExtenOID(&ext->id) == PR_FALSE) { + hasUnknownCriticalExten = PR_TRUE; + break; + } + } + exts++; + } } return (hasUnknownCriticalExten); } diff --git a/security/nss/lib/certdb/certxutl.h b/security/nss/lib/certdb/certxutl.h index 05ad572fda5c..a8c76b5cfa53 100644 --- a/security/nss/lib/certdb/certxutl.h +++ b/security/nss/lib/certdb/certxutl.h @@ -7,7 +7,6 @@ * */ - #ifndef _CERTXUTL_H_ #define _CERTXUTL_H_ @@ -23,28 +22,23 @@ typedef enum { } ExtensionsType; #endif -extern PRBool -cert_HasCriticalExtension (CERTCertExtension **extensions); +extern PRBool cert_HasCriticalExtension(CERTCertExtension **extensions); -extern SECStatus -CERT_FindBitStringExtension (CERTCertExtension **extensions, - int tag, SECItem *retItem); -extern void * -cert_StartExtensions (void *owner, PLArenaPool *arena, - void (*setExts)(void *object, CERTCertExtension **exts)); +extern SECStatus CERT_FindBitStringExtension(CERTCertExtension **extensions, + int tag, SECItem *retItem); +extern void *cert_StartExtensions(void *owner, PLArenaPool *arena, + void (*setExts)(void *object, + CERTCertExtension **exts)); -extern SECStatus -cert_FindExtension (CERTCertExtension **extensions, int tag, SECItem *value); +extern SECStatus cert_FindExtension(CERTCertExtension **extensions, int tag, + SECItem *value); -extern SECStatus -cert_FindExtensionByOID (CERTCertExtension **extensions, - SECItem *oid, SECItem *value); +extern SECStatus cert_FindExtensionByOID(CERTCertExtension **extensions, + SECItem *oid, SECItem *value); -extern SECStatus -cert_GetExtenCriticality (CERTCertExtension **extensions, - int tag, PRBool *isCritical); +extern SECStatus cert_GetExtenCriticality(CERTCertExtension **extensions, + int tag, PRBool *isCritical); -extern PRBool -cert_HasUnknownCriticalExten (CERTCertExtension **extensions); +extern PRBool cert_HasUnknownCriticalExten(CERTCertExtension **extensions); #endif diff --git a/security/nss/lib/certdb/crl.c b/security/nss/lib/certdb/crl.c index 05ded1368ae5..d8fbe04a0b15 100644 --- a/security/nss/lib/certdb/crl.c +++ b/security/nss/lib/certdb/crl.c @@ -5,7 +5,7 @@ /* * Moved from secpkcs7.c */ - + #include "cert.h" #include "certi.h" #include "secder.h" @@ -25,19 +25,16 @@ #include "pk11priv.h" const SEC_ASN1Template SEC_CERTExtensionTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCertExtension) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTCertExtension,id) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ - offsetof(CERTCertExtension,critical), }, - { SEC_ASN1_OCTET_STRING, - offsetof(CERTCertExtension,value) }, - { 0, } + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCertExtension) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTCertExtension, id) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ + offsetof(CERTCertExtension, critical) }, + { SEC_ASN1_OCTET_STRING, offsetof(CERTCertExtension, value) }, + { 0 } }; static const SEC_ASN1Template SEC_CERTExtensionsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, SEC_CERTExtensionTemplate} + { SEC_ASN1_SEQUENCE_OF, 0, SEC_CERTExtensionTemplate } }; /* @@ -46,15 +43,10 @@ static const SEC_ASN1Template SEC_CERTExtensionsTemplate[] = { */ const SEC_ASN1Template CERT_IssuerAndSNTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTIssuerAndSN) }, - { SEC_ASN1_SAVE, - offsetof(CERTIssuerAndSN,derIssuer) }, - { SEC_ASN1_INLINE, - offsetof(CERTIssuerAndSN,issuer), - CERT_NameTemplate }, - { SEC_ASN1_INTEGER, - offsetof(CERTIssuerAndSN,serialNumber) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTIssuerAndSN) }, + { SEC_ASN1_SAVE, offsetof(CERTIssuerAndSN, derIssuer) }, + { SEC_ASN1_INLINE, offsetof(CERTIssuerAndSN, issuer), CERT_NameTemplate }, + { SEC_ASN1_INTEGER, offsetof(CERTIssuerAndSN, serialNumber) }, { 0 } }; @@ -62,132 +54,97 @@ SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) SEC_ASN1_MKSUB(CERT_TimeChoiceTemplate) static const SEC_ASN1Template cert_CrlKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCrlKey) }, - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof(CERTCrlKey,dummy) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCrlKey) }, + { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof(CERTCrlKey, dummy) }, { SEC_ASN1_SKIP }, - { SEC_ASN1_ANY, offsetof(CERTCrlKey,derName) }, + { SEC_ASN1_ANY, offsetof(CERTCrlKey, derName) }, { SEC_ASN1_SKIP_REST }, { 0 } }; static const SEC_ASN1Template cert_CrlEntryTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCrlEntry) }, - { SEC_ASN1_INTEGER, - offsetof(CERTCrlEntry,serialNumber) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCrlEntry,revocationDate), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCrlEntry) }, + { SEC_ASN1_INTEGER, offsetof(CERTCrlEntry, serialNumber) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTCrlEntry, revocationDate), + SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, - offsetof(CERTCrlEntry, extensions), - SEC_CERTExtensionTemplate}, + offsetof(CERTCrlEntry, extensions), SEC_CERTExtensionTemplate }, { 0 } }; const SEC_ASN1Template CERT_CrlTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCrl) }, - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof (CERTCrl, version) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCrl,signatureAlg), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate)}, - { SEC_ASN1_SAVE, - offsetof(CERTCrl,derName) }, - { SEC_ASN1_INLINE, - offsetof(CERTCrl,name), - CERT_NameTemplate }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCrl,lastUpdate), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCrl) }, + { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof(CERTCrl, version) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTCrl, signatureAlg), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_SAVE, offsetof(CERTCrl, derName) }, + { SEC_ASN1_INLINE, offsetof(CERTCrl, name), CERT_NameTemplate }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTCrl, lastUpdate), + SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, { SEC_ASN1_INLINE | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN, - offsetof(CERTCrl,nextUpdate), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, - offsetof(CERTCrl,entries), - cert_CrlEntryTemplate }, + offsetof(CERTCrl, nextUpdate), SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, offsetof(CERTCrl, entries), + cert_CrlEntryTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(CERTCrl,extensions), - SEC_CERTExtensionsTemplate}, + SEC_ASN1_EXPLICIT | 0, + offsetof(CERTCrl, extensions), SEC_CERTExtensionsTemplate }, { 0 } }; const SEC_ASN1Template CERT_CrlTemplateNoEntries[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCrl) }, - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof (CERTCrl, version) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCrl,signatureAlg), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_SAVE, - offsetof(CERTCrl,derName) }, - { SEC_ASN1_INLINE, - offsetof(CERTCrl,name), - CERT_NameTemplate }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCrl,lastUpdate), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCrl) }, + { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof(CERTCrl, version) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTCrl, signatureAlg), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_SAVE, offsetof(CERTCrl, derName) }, + { SEC_ASN1_INLINE, offsetof(CERTCrl, name), CERT_NameTemplate }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(CERTCrl, lastUpdate), + SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, { SEC_ASN1_INLINE | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN, - offsetof(CERTCrl,nextUpdate), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, + offsetof(CERTCrl, nextUpdate), SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF | SEC_ASN1_SKIP }, /* skip entries */ { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(CERTCrl,extensions), - SEC_CERTExtensionsTemplate }, + SEC_ASN1_EXPLICIT | 0, + offsetof(CERTCrl, extensions), SEC_CERTExtensionsTemplate }, { 0 } }; const SEC_ASN1Template CERT_CrlTemplateEntriesOnly[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCrl) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCrl) }, { SEC_ASN1_SKIP | SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL }, { SEC_ASN1_SKIP }, { SEC_ASN1_SKIP }, { SEC_ASN1_SKIP | SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTCrl,lastUpdate), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, + offsetof(CERTCrl, lastUpdate), SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, { SEC_ASN1_SKIP | SEC_ASN1_INLINE | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN, - offsetof(CERTCrl,nextUpdate), - SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, - offsetof(CERTCrl,entries), - cert_CrlEntryTemplate }, /* decode entries */ + offsetof(CERTCrl, nextUpdate), SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, offsetof(CERTCrl, entries), + cert_CrlEntryTemplate }, /* decode entries */ { SEC_ASN1_SKIP_REST }, { 0 } }; const SEC_ASN1Template CERT_SignedCrlTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTSignedCrl) }, - { SEC_ASN1_SAVE, - offsetof(CERTSignedCrl,signatureWrap.data) }, - { SEC_ASN1_INLINE, - offsetof(CERTSignedCrl,crl), - CERT_CrlTemplate }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN , - offsetof(CERTSignedCrl,signatureWrap.signatureAlgorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_BIT_STRING, - offsetof(CERTSignedCrl,signatureWrap.signature) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTSignedCrl) }, + { SEC_ASN1_SAVE, offsetof(CERTSignedCrl, signatureWrap.data) }, + { SEC_ASN1_INLINE, offsetof(CERTSignedCrl, crl), CERT_CrlTemplate }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, + offsetof(CERTSignedCrl, signatureWrap.signatureAlgorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_BIT_STRING, offsetof(CERTSignedCrl, signatureWrap.signature) }, { 0 } }; static const SEC_ASN1Template cert_SignedCrlTemplateNoEntries[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTSignedCrl) }, - { SEC_ASN1_SAVE, - offsetof(CERTSignedCrl,signatureWrap.data) }, - { SEC_ASN1_INLINE, - offsetof(CERTSignedCrl,crl), - CERT_CrlTemplateNoEntries }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTSignedCrl) }, + { SEC_ASN1_SAVE, offsetof(CERTSignedCrl, signatureWrap.data) }, + { SEC_ASN1_INLINE, offsetof(CERTSignedCrl, crl), + CERT_CrlTemplateNoEntries }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTSignedCrl,signatureWrap.signatureAlgorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_BIT_STRING, - offsetof(CERTSignedCrl,signatureWrap.signature) }, + offsetof(CERTSignedCrl, signatureWrap.signatureAlgorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_BIT_STRING, offsetof(CERTSignedCrl, signatureWrap.signature) }, { 0 } }; @@ -196,22 +153,23 @@ const SEC_ASN1Template CERT_SetOfSignedCrlTemplate[] = { }; /* get CRL version */ -int cert_get_crl_version(CERTCrl * crl) +int +cert_get_crl_version(CERTCrl* crl) { /* CRL version is defaulted to v1 */ int version = SEC_CRL_VERSION_1; if (crl && crl->version.data != 0) { - version = (int)DER_GetUInteger (&crl->version); + version = (int)DER_GetUInteger(&crl->version); } return version; } - /* check the entries in the CRL */ -SECStatus cert_check_crl_entries (CERTCrl *crl) +SECStatus +cert_check_crl_entries(CERTCrl* crl) { - CERTCrlEntry **entries; - CERTCrlEntry *entry; + CERTCrlEntry** entries; + CERTCrlEntry* entry; PRBool hasCriticalExten = PR_FALSE; SECStatus rv = SECSuccess; @@ -229,16 +187,17 @@ SECStatus cert_check_crl_entries (CERTCrl *crl) */ entries = crl->entries; while (*entries) { - entry = *entries; - if (entry->extensions) { - /* If there is a critical extension in the entries, then the - CRL must be of version 2. If we already saw a critical extension, - there is no need to check the version again. - */ + entry = *entries; + if (entry->extensions) { + /* If there is a critical extension in the entries, then the + CRL must be of version 2. If we already saw a critical + extension, + there is no need to check the version again. + */ if (hasCriticalExten == PR_FALSE) { - hasCriticalExten = cert_HasCriticalExtension (entry->extensions); + hasCriticalExten = cert_HasCriticalExtension(entry->extensions); if (hasCriticalExten) { - if (cert_get_crl_version(crl) != SEC_CRL_VERSION_2) { + if (cert_get_crl_version(crl) != SEC_CRL_VERSION_2) { /* only CRL v2 critical extensions are supported */ PORT_SetError(SEC_ERROR_CRL_V1_CRITICAL_EXTENSION); rv = SECFailure; @@ -247,19 +206,19 @@ SECStatus cert_check_crl_entries (CERTCrl *crl) } } - /* For each entry, make sure that it does not contain an unknown - critical extension. If it does, we must reject the CRL since - we don't know how to process the extension. - */ - if (cert_HasUnknownCriticalExten (entry->extensions) == PR_TRUE) { - PORT_SetError (SEC_ERROR_CRL_UNKNOWN_CRITICAL_EXTENSION); - rv = SECFailure; - break; - } - } - ++entries; + /* For each entry, make sure that it does not contain an unknown + critical extension. If it does, we must reject the CRL since + we don't know how to process the extension. + */ + if (cert_HasUnknownCriticalExten(entry->extensions) == PR_TRUE) { + PORT_SetError(SEC_ERROR_CRL_UNKNOWN_CRITICAL_EXTENSION); + rv = SECFailure; + break; + } + } + ++entries; } - return(rv); + return (rv); } /* Check the version of the CRL. If there is a critical extension in the crl @@ -267,33 +226,34 @@ SECStatus cert_check_crl_entries (CERTCrl *crl) the crl contains critical extension(s), then we must recognized the extension's OID. */ -SECStatus cert_check_crl_version (CERTCrl *crl) +SECStatus +cert_check_crl_version(CERTCrl* crl) { PRBool hasCriticalExten = PR_FALSE; int version = cert_get_crl_version(crl); - + if (version > SEC_CRL_VERSION_2) { - PORT_SetError (SEC_ERROR_CRL_INVALID_VERSION); - return (SECFailure); + PORT_SetError(SEC_ERROR_CRL_INVALID_VERSION); + return (SECFailure); } /* Check the crl extensions for a critial extension. If one is found, and the version is not v2, then we are done. */ if (crl->extensions) { - hasCriticalExten = cert_HasCriticalExtension (crl->extensions); - if (hasCriticalExten) { + hasCriticalExten = cert_HasCriticalExtension(crl->extensions); + if (hasCriticalExten) { if (version != SEC_CRL_VERSION_2) { /* only CRL v2 critical extensions are supported */ PORT_SetError(SEC_ERROR_CRL_V1_CRITICAL_EXTENSION); return (SECFailure); } - /* make sure that there is no unknown critical extension */ - if (cert_HasUnknownCriticalExten (crl->extensions) == PR_TRUE) { - PORT_SetError (SEC_ERROR_CRL_UNKNOWN_CRITICAL_EXTENSION); - return (SECFailure); - } - } + /* make sure that there is no unknown critical extension */ + if (cert_HasUnknownCriticalExten(crl->extensions) == PR_TRUE) { + PORT_SetError(SEC_ERROR_CRL_UNKNOWN_CRITICAL_EXTENSION); + return (SECFailure); + } + } } return (SECSuccess); @@ -304,7 +264,7 @@ SECStatus cert_check_crl_version (CERTCrl *crl) * DER crl. */ SECStatus -CERT_KeyFromDERCrl(PLArenaPool *arena, SECItem *derCrl, SECItem *key) +CERT_KeyFromDERCrl(PLArenaPool* arena, SECItem* derCrl, SECItem* key) { SECStatus rv; CERTSignedData sd; @@ -314,14 +274,16 @@ CERT_KeyFromDERCrl(PLArenaPool *arena, SECItem *derCrl, SECItem *key) if (!arena) { /* arena needed for QuickDER */ myArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - } else { + } + else { myArena = arena; } - PORT_Memset (&sd, 0, sizeof (sd)); - rv = SEC_QuickDERDecodeItem (myArena, &sd, CERT_SignedDataTemplate, derCrl); + PORT_Memset(&sd, 0, sizeof(sd)); + rv = SEC_QuickDERDecodeItem(myArena, &sd, CERT_SignedDataTemplate, derCrl); if (SECSuccess == rv) { - PORT_Memset (&crlkey, 0, sizeof (crlkey)); - rv = SEC_QuickDERDecodeItem(myArena, &crlkey, cert_CrlKeyTemplate, &sd.data); + PORT_Memset(&crlkey, 0, sizeof(crlkey)); + rv = SEC_QuickDERDecodeItem(myArena, &crlkey, cert_CrlKeyTemplate, + &sd.data); } /* make a copy so the data doesn't point to memory inside derCrl, which @@ -339,17 +301,18 @@ CERT_KeyFromDERCrl(PLArenaPool *arena, SECItem *derCrl, SECItem *key) #define GetOpaqueCRLFields(x) ((OpaqueCRLFields*)x->opaque) -SECStatus CERT_CompleteCRLDecodeEntries(CERTSignedCrl* crl) +SECStatus +CERT_CompleteCRLDecodeEntries(CERTSignedCrl* crl) { SECStatus rv = SECSuccess; SECItem* crldata = NULL; OpaqueCRLFields* extended = NULL; - if ( (!crl) || - (!(extended = (OpaqueCRLFields*) crl->opaque)) || - (PR_TRUE == extended->decodingError) ) { + if ((!crl) || (!(extended = (OpaqueCRLFields*)crl->opaque)) || + (PR_TRUE == extended->decodingError)) { rv = SECFailure; - } else { + } + else { if (PR_FALSE == extended->partial) { /* the CRL has already been fully decoded */ return SECSuccess; @@ -365,14 +328,13 @@ SECStatus CERT_CompleteCRLDecodeEntries(CERTSignedCrl* crl) } if (SECSuccess == rv) { - rv = SEC_QuickDERDecodeItem(crl->arena, - &crl->crl, - CERT_CrlTemplateEntriesOnly, - crldata); + rv = SEC_QuickDERDecodeItem(crl->arena, &crl->crl, + CERT_CrlTemplateEntriesOnly, crldata); if (SECSuccess == rv) { extended->partial = PR_FALSE; /* successful decode, avoid decoding again */ - } else { + } + else { extended->decodingError = PR_TRUE; extended->badEntries = PR_TRUE; /* cache the decoding failure. If it fails the first time, @@ -391,12 +353,12 @@ SECStatus CERT_CompleteCRLDecodeEntries(CERTSignedCrl* crl) * take a DER CRL and decode it into a CRL structure * allow reusing the input DER without making a copy */ -CERTSignedCrl * -CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl, - int type, PRInt32 options) +CERTSignedCrl* +CERT_DecodeDERCrlWithFlags(PLArenaPool* narena, SECItem* derSignedCrl, int type, + PRInt32 options) { - PLArenaPool *arena; - CERTSignedCrl *crl; + PLArenaPool* arena; + CERTSignedCrl* crl; SECStatus rv; OpaqueCRLFields* extended = NULL; const SEC_ASN1Template* crlTemplate = CERT_SignedCrlTemplate; @@ -408,8 +370,8 @@ CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl, return NULL; } - /* Adopting DER requires not copying it. Code that sets ADOPT flag - * but doesn't set DONT_COPY probably doesn't know What it is doing. + /* Adopting DER requires not copying it. Code that sets ADOPT flag + * but doesn't set DONT_COPY probably doesn't know What it is doing. * That condition is a programming error in the caller. */ testOptions &= (CRL_DECODE_ADOPT_HEAP_DER | CRL_DECODE_DONT_COPY_DER); @@ -421,29 +383,30 @@ CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl, /* make a new arena if needed */ if (narena == NULL) { - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - return NULL; - } - } else { - arena = narena; + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (!arena) { + return NULL; + } + } + else { + arena = narena; } /* allocate the CRL structure */ - crl = (CERTSignedCrl *)PORT_ArenaZAlloc(arena, sizeof(CERTSignedCrl)); - if ( !crl ) { + crl = (CERTSignedCrl*)PORT_ArenaZAlloc(arena, sizeof(CERTSignedCrl)); + if (!crl) { PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + goto loser; } crl->arena = arena; /* allocate opaque fields */ crl->opaque = (void*)PORT_ArenaZAlloc(arena, sizeof(OpaqueCRLFields)); - if ( !crl->opaque ) { - goto loser; + if (!crl->opaque) { + goto loser; } - extended = (OpaqueCRLFields*) crl->opaque; + extended = (OpaqueCRLFields*)crl->opaque; if (options & CRL_DECODE_ADOPT_HEAP_DER) { extended->heapDER = PR_TRUE; } @@ -451,8 +414,9 @@ CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl, crl->derCrl = derSignedCrl; /* DER is not copied . The application must keep derSignedCrl until it destroys the CRL */ - } else { - crl->derCrl = (SECItem *)PORT_ArenaZAlloc(arena,sizeof(SECItem)); + } + else { + crl->derCrl = (SECItem*)PORT_ArenaZAlloc(arena, sizeof(SECItem)); if (crl->derCrl == NULL) { goto loser; } @@ -471,45 +435,45 @@ CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl, /* decode the CRL info */ switch (type) { - case SEC_CRL_TYPE: - rv = SEC_QuickDERDecodeItem(arena, crl, crlTemplate, crl->derCrl); - if (rv != SECSuccess) { - extended->badDER = PR_TRUE; + case SEC_CRL_TYPE: + rv = SEC_QuickDERDecodeItem(arena, crl, crlTemplate, crl->derCrl); + if (rv != SECSuccess) { + extended->badDER = PR_TRUE; + break; + } + /* check for critical extensions */ + rv = cert_check_crl_version(&crl->crl); + if (rv != SECSuccess) { + extended->badExtensions = PR_TRUE; + break; + } + + if (PR_TRUE == extended->partial) { + /* partial decoding, don't verify entries */ + break; + } + + rv = cert_check_crl_entries(&crl->crl); + if (rv != SECSuccess) { + extended->badExtensions = PR_TRUE; + } + break; - } - /* check for critical extensions */ - rv = cert_check_crl_version (&crl->crl); - if (rv != SECSuccess) { - extended->badExtensions = PR_TRUE; + + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; break; - } - - if (PR_TRUE == extended->partial) { - /* partial decoding, don't verify entries */ - break; - } - - rv = cert_check_crl_entries(&crl->crl); - if (rv != SECSuccess) { - extended->badExtensions = PR_TRUE; - } - - break; - - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - break; } if (rv != SECSuccess) { - goto loser; + goto loser; } crl->referenceCount = 1; - - return(crl); - + + return (crl); + loser: if (options & CRL_DECODE_KEEP_BAD_CRL) { if (extended) { @@ -517,22 +481,22 @@ loser: } if (crl) { crl->referenceCount = 1; - return(crl); + return (crl); } } - if ((narena == NULL) && arena ) { - PORT_FreeArena(arena, PR_FALSE); + if ((narena == NULL) && arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(0); + + return (0); } /* * take a DER CRL and decode it into a CRL structure */ -CERTSignedCrl * -CERT_DecodeDERCrl(PLArenaPool *narena, SECItem *derSignedCrl, int type) +CERTSignedCrl* +CERT_DecodeDERCrl(PLArenaPool* narena, SECItem* derSignedCrl, int type) { return CERT_DecodeDERCrlWithFlags(narena, derSignedCrl, type, CRL_DECODE_DEFAULT_OPTIONS); @@ -555,14 +519,14 @@ CERT_DecodeDERCrl(PLArenaPool *narena, SECItem *derSignedCrl, int type) * considered to be revoked */ static SECStatus -SEC_FindCrlByKeyOnSlot(PK11SlotInfo *slot, SECItem *crlKey, int type, +SEC_FindCrlByKeyOnSlot(PK11SlotInfo* slot, SECItem* crlKey, int type, CERTSignedCrl** decoded, PRInt32 decodeoptions) { SECStatus rv = SECSuccess; - CERTSignedCrl *crl = NULL; - SECItem *derCrl = NULL; + CERTSignedCrl* crl = NULL; + SECItem* derCrl = NULL; CK_OBJECT_HANDLE crlHandle = 0; - char *url = NULL; + char* url = NULL; PORT_Assert(decoded); if (!decoded) { @@ -572,46 +536,47 @@ SEC_FindCrlByKeyOnSlot(PK11SlotInfo *slot, SECItem *crlKey, int type, derCrl = PK11_FindCrlByName(&slot, &crlHandle, crlKey, type, &url); if (derCrl == NULL) { - /* if we had a problem other than the CRL just didn't exist, return - * a failure to the upper level */ - int nsserror = PORT_GetError(); - if (nsserror != SEC_ERROR_CRL_NOT_FOUND) { - rv = SECFailure; - } - goto loser; + /* if we had a problem other than the CRL just didn't exist, return + * a failure to the upper level */ + int nsserror = PORT_GetError(); + if (nsserror != SEC_ERROR_CRL_NOT_FOUND) { + rv = SECFailure; + } + goto loser; } PORT_Assert(crlHandle != CK_INVALID_HANDLE); /* PK11_FindCrlByName obtained a slot reference. */ - + /* derCRL is a fresh HEAP copy made for us by PK11_FindCrlByName. - Force adoption of the DER CRL from the heap - this will cause it + Force adoption of the DER CRL from the heap - this will cause it to be automatically freed when SEC_DestroyCrl is invoked */ decodeoptions |= (CRL_DECODE_ADOPT_HEAP_DER | CRL_DECODE_DONT_COPY_DER); crl = CERT_DecodeDERCrlWithFlags(NULL, derCrl, type, decodeoptions); if (crl) { crl->slot = slot; - slot = NULL; /* adopt it */ - derCrl = NULL; /* adopted by the crl struct */ + slot = NULL; /* adopt it */ + derCrl = NULL; /* adopted by the crl struct */ crl->pkcs11ID = crlHandle; if (url) { - crl->url = PORT_ArenaStrdup(crl->arena,url); + crl->url = PORT_ArenaStrdup(crl->arena, url); } - } else { + } + else { rv = SECFailure; } - + if (url) { - PORT_Free(url); + PORT_Free(url); } if (slot) { - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); } loser: if (derCrl) { - SECITEM_FreeItem(derCrl, PR_TRUE); + SECITEM_FreeItem(derCrl, PR_TRUE); } *decoded = crl; @@ -619,10 +584,9 @@ loser: return rv; } - -CERTSignedCrl * -crl_storeCRL (PK11SlotInfo *slot,char *url, - CERTSignedCrl *newCrl, SECItem *derCrl, int type) +CERTSignedCrl* +crl_storeCRL(PK11SlotInfo* slot, char* url, CERTSignedCrl* newCrl, + SECItem* derCrl, int type) { CERTSignedCrl *oldCrl = NULL, *crl = NULL; PRBool deleteOldCrl = PR_FALSE; @@ -639,38 +603,37 @@ crl_storeCRL (PK11SlotInfo *slot,char *url, /* we can't use the cache here because we must look in the same token */ - (void)SEC_FindCrlByKeyOnSlot(slot, &newCrl->crl.derName, type, - &oldCrl, CRL_DECODE_SKIP_ENTRIES); + (void)SEC_FindCrlByKeyOnSlot(slot, &newCrl->crl.derName, type, &oldCrl, + CRL_DECODE_SKIP_ENTRIES); /* if there is an old crl on the token, make sure the one we are installing is newer. If not, exit out, otherwise delete the old crl. */ if (oldCrl != NULL) { - /* if it's already there, quietly continue */ - if (SECITEM_CompareItem(newCrl->derCrl, oldCrl->derCrl) - == SECEqual) { - crl = newCrl; - crl->slot = PK11_ReferenceSlot(slot); - crl->pkcs11ID = oldCrl->pkcs11ID; - if (oldCrl->url && !url) - url = oldCrl->url; - if (url) - crl->url = PORT_ArenaStrdup(crl->arena, url); - goto done; - } - if (!SEC_CrlIsNewer(&newCrl->crl,&oldCrl->crl)) { + /* if it's already there, quietly continue */ + if (SECITEM_CompareItem(newCrl->derCrl, oldCrl->derCrl) == SECEqual) { + crl = newCrl; + crl->slot = PK11_ReferenceSlot(slot); + crl->pkcs11ID = oldCrl->pkcs11ID; + if (oldCrl->url && !url) + url = oldCrl->url; + if (url) + crl->url = PORT_ArenaStrdup(crl->arena, url); + goto done; + } + if (!SEC_CrlIsNewer(&newCrl->crl, &oldCrl->crl)) { PORT_SetError(SEC_ERROR_OLD_CRL); goto done; } /* if we have a url in the database, use that one */ if (oldCrl->url && !url) { - url = oldCrl->url; + url = oldCrl->url; } /* really destroy this crl */ /* first drum it out of the permanment Data base */ - deleteOldCrl = PR_TRUE; + deleteOldCrl = PR_TRUE; } /* invalidate CRL cache for this issuer */ @@ -678,20 +641,20 @@ crl_storeCRL (PK11SlotInfo *slot,char *url, /* Write the new entry into the data base */ crlHandle = PK11_PutCrl(slot, derCrl, &newCrl->crl.derName, url, type); if (crlHandle != CK_INVALID_HANDLE) { - crl = newCrl; - crl->slot = PK11_ReferenceSlot(slot); - crl->pkcs11ID = crlHandle; - if (url) { - crl->url = PORT_ArenaStrdup(crl->arena,url); - } + crl = newCrl; + crl->slot = PK11_ReferenceSlot(slot); + crl->pkcs11ID = crlHandle; + if (url) { + crl->url = PORT_ArenaStrdup(crl->arena, url); + } } done: if (oldCrl) { - if (deleteOldCrl && crlHandle != CK_INVALID_HANDLE) { - SEC_DeletePermCRL(oldCrl); - } - SEC_DestroyCrl(oldCrl); + if (deleteOldCrl && crlHandle != CK_INVALID_HANDLE) { + SEC_DeletePermCRL(oldCrl); + } + SEC_DestroyCrl(oldCrl); } return crl; @@ -704,50 +667,51 @@ done: * The signature on this CRL must be checked before you * load it. ??? */ -CERTSignedCrl * -SEC_NewCrl(CERTCertDBHandle *handle, char *url, SECItem *derCrl, int type) +CERTSignedCrl* +SEC_NewCrl(CERTCertDBHandle* handle, char* url, SECItem* derCrl, int type) { CERTSignedCrl* retCrl = NULL; PK11SlotInfo* slot = PK11_GetInternalKeySlot(); - retCrl = PK11_ImportCRL(slot, derCrl, url, type, NULL, - CRL_IMPORT_BYPASS_CHECKS, NULL, CRL_DECODE_DEFAULT_OPTIONS); + retCrl = + PK11_ImportCRL(slot, derCrl, url, type, NULL, CRL_IMPORT_BYPASS_CHECKS, + NULL, CRL_DECODE_DEFAULT_OPTIONS); PK11_FreeSlot(slot); return retCrl; } - -CERTSignedCrl * -SEC_FindCrlByDERCert(CERTCertDBHandle *handle, SECItem *derCrl, int type) + +CERTSignedCrl* +SEC_FindCrlByDERCert(CERTCertDBHandle* handle, SECItem* derCrl, int type) { - PLArenaPool *arena; + PLArenaPool* arena; SECItem crlKey; SECStatus rv; - CERTSignedCrl *crl = NULL; - + CERTSignedCrl* crl = NULL; + /* create a scratch arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - return(NULL); + if (arena == NULL) { + return (NULL); } - + /* extract the database key from the cert */ rv = CERT_KeyFromDERCrl(arena, derCrl, &crlKey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* find the crl */ crl = SEC_FindCrlByName(handle, &crlKey, type); - + loser: PORT_FreeArena(arena, PR_FALSE); - return(crl); + return (crl); } -CERTSignedCrl* SEC_DupCrl(CERTSignedCrl* acrl) +CERTSignedCrl* +SEC_DupCrl(CERTSignedCrl* acrl) { - if (acrl) - { + if (acrl) { PR_ATOMIC_INCREMENT(&acrl->referenceCount); return acrl; } @@ -755,13 +719,13 @@ CERTSignedCrl* SEC_DupCrl(CERTSignedCrl* acrl) } SECStatus -SEC_DestroyCrl(CERTSignedCrl *crl) +SEC_DestroyCrl(CERTSignedCrl* crl) { if (crl) { - if (PR_ATOMIC_DECREMENT(&crl->referenceCount) < 1) { - if (crl->slot) { - PK11_FreeSlot(crl->slot); - } + if (PR_ATOMIC_DECREMENT(&crl->referenceCount) < 1) { + if (crl->slot) { + PK11_FreeSlot(crl->slot); + } if (GetOpaqueCRLFields(crl) && PR_TRUE == GetOpaqueCRLFields(crl)->heapDER) { SECITEM_FreeItem(crl->derCrl, PR_TRUE); @@ -769,29 +733,30 @@ SEC_DestroyCrl(CERTSignedCrl *crl) if (crl->arena) { PORT_FreeArena(crl->arena, PR_FALSE); } - } + } return SECSuccess; - } else { + } + else { return SECFailure; } } SECStatus -SEC_LookupCrls(CERTCertDBHandle *handle, CERTCrlHeadNode **nodes, int type) +SEC_LookupCrls(CERTCertDBHandle* handle, CERTCrlHeadNode** nodes, int type) { - CERTCrlHeadNode *head; - PLArenaPool *arena = NULL; + CERTCrlHeadNode* head; + PLArenaPool* arena = NULL; SECStatus rv; *nodes = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - return SECFailure; + if (arena == NULL) { + return SECFailure; } /* build a head structure */ - head = (CERTCrlHeadNode *)PORT_ArenaAlloc(arena, sizeof(CERTCrlHeadNode)); + head = (CERTCrlHeadNode*)PORT_ArenaAlloc(arena, sizeof(CERTCrlHeadNode)); head->arena = arena; head->first = NULL; head->last = NULL; @@ -801,12 +766,12 @@ SEC_LookupCrls(CERTCertDBHandle *handle, CERTCrlHeadNode **nodes, int type) *nodes = head; rv = PK11_LookupCrls(head, type, NULL); - + if (rv != SECSuccess) { - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); - *nodes = NULL; - } + if (arena) { + PORT_FreeArena(arena, PR_FALSE); + *nodes = NULL; + } } return rv; @@ -824,7 +789,7 @@ SEC_ASN1_CHOOSER_IMPLEMENT(CERT_SetOfSignedCrlTemplate) /* constructor */ static SECStatus CachedCrl_Create(CachedCrl** returned, CERTSignedCrl* crl, - CRLOrigin origin); + CRLOrigin origin); /* destructor */ static SECStatus CachedCrl_Destroy(CachedCrl* crl); @@ -838,11 +803,11 @@ static SECStatus CachedCrl_Depopulate(CachedCrl* crl); Or are they the same token object, but with different DER ? */ static SECStatus CachedCrl_Compare(CachedCrl* a, CachedCrl* b, PRBool* isDupe, - PRBool* isUpdated); + PRBool* isUpdated); /* create a DPCache object */ static SECStatus DPCache_Create(CRLDPCache** returned, CERTCertificate* issuer, - const SECItem* subject, SECItem* dp); + const SECItem* subject, SECItem* dp); /* destructor for CRL DPCache object */ static SECStatus DPCache_Destroy(CRLDPCache* cache); @@ -859,7 +824,8 @@ static SECStatus DPCache_FetchFromTokens(CRLDPCache* cache, PRTime vfdate, /* update the content of the CRL cache, including fetching of CRLs, and reprocessing with specified issuer and date */ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* issuer, - PRBool readlocked, PRTime vfdate, void* wincx); + PRBool readlocked, PRTime vfdate, + void* wincx); /* returns true if there are CRLs from PKCS#11 slots */ static PRBool DPCache_HasTokenCRLs(CRLDPCache* cache); @@ -872,8 +838,8 @@ static SECStatus DPCache_SelectCRL(CRLDPCache* cache); /* create an issuer cache object (per CA subject ) */ static SECStatus IssuerCache_Create(CRLIssuerCache** returned, - CERTCertificate* issuer, - const SECItem* subject, const SECItem* dp); + CERTCertificate* issuer, + const SECItem* subject, const SECItem* dp); /* destructor for CRL IssuerCache object */ SECStatus IssuerCache_Destroy(CRLIssuerCache* cache); @@ -881,8 +847,8 @@ SECStatus IssuerCache_Destroy(CRLIssuerCache* cache); /* add a DPCache to the issuer cache */ static SECStatus IssuerCache_AddDP(CRLIssuerCache* cache, CERTCertificate* issuer, - const SECItem* subject, - const SECItem* dp, CRLDPCache** newdpc); + const SECItem* subject, const SECItem* dp, + CRLDPCache** newdpc); /* get a particular DPCache object from an IssuerCache */ static CRLDPCache* IssuerCache_GetDPCache(CRLIssuerCache* cache, @@ -893,37 +859,35 @@ static CRLDPCache* IssuerCache_GetDPCache(CRLIssuerCache* cache, */ /* allocate memory for hash table */ -static void * PR_CALLBACK -PreAllocTable(void *pool, PRSize size) +static void* PR_CALLBACK +PreAllocTable(void* pool, PRSize size) { PreAllocator* alloc = (PreAllocator*)pool; PORT_Assert(alloc); - if (!alloc) - { + if (!alloc) { /* no allocator, or buffer full */ return NULL; } - if (size > (alloc->len - alloc->used)) - { + if (size > (alloc->len - alloc->used)) { /* initial buffer full, let's use the arena */ alloc->extra += size; return PORT_ArenaAlloc(alloc->arena, size); } /* use the initial buffer */ alloc->used += size; - return (char*) alloc->data + alloc->used - size; + return (char*)alloc->data + alloc->used - size; } /* free hash table memory. Individual PreAllocator elements cannot be freed, so this is a no-op. */ static void PR_CALLBACK -PreFreeTable(void *pool, void *item) +PreFreeTable(void* pool, void* item) { } /* allocate memory for hash table */ -static PLHashEntry * PR_CALLBACK -PreAllocEntry(void *pool, const void *key) +static PLHashEntry* PR_CALLBACK +PreAllocEntry(void* pool, const void* key) { return PreAllocTable(pool, sizeof(PLHashEntry)); } @@ -931,55 +895,47 @@ PreAllocEntry(void *pool, const void *key) /* free hash table entry. Individual PreAllocator elements cannot be freed, so this is a no-op. */ static void PR_CALLBACK -PreFreeEntry(void *pool, PLHashEntry *he, PRUintn flag) +PreFreeEntry(void* pool, PLHashEntry* he, PRUintn flag) { } /* methods required for PL hash table functions */ -static PLHashAllocOps preAllocOps = -{ - PreAllocTable, PreFreeTable, - PreAllocEntry, PreFreeEntry -}; +static PLHashAllocOps preAllocOps = { PreAllocTable, PreFreeTable, + PreAllocEntry, PreFreeEntry }; /* destructor for PreAllocator object */ -void PreAllocator_Destroy(PreAllocator* PreAllocator) +void +PreAllocator_Destroy(PreAllocator* PreAllocator) { - if (!PreAllocator) - { + if (!PreAllocator) { return; } - if (PreAllocator->arena) - { + if (PreAllocator->arena) { PORT_FreeArena(PreAllocator->arena, PR_TRUE); } } /* constructor for PreAllocator object */ -PreAllocator* PreAllocator_Create(PRSize size) +PreAllocator* +PreAllocator_Create(PRSize size) { PLArenaPool* arena = NULL; PreAllocator* prebuffer = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (!arena) - { + if (!arena) { return NULL; } - prebuffer = (PreAllocator*)PORT_ArenaZAlloc(arena, - sizeof(PreAllocator)); - if (!prebuffer) - { + prebuffer = (PreAllocator*)PORT_ArenaZAlloc(arena, sizeof(PreAllocator)); + if (!prebuffer) { PORT_FreeArena(arena, PR_TRUE); return NULL; } prebuffer->arena = arena; - if (size) - { + if (size) { prebuffer->len = size; prebuffer->data = PORT_ArenaAlloc(arena, size); - if (!prebuffer->data) - { + if (!prebuffer->data) { PORT_FreeArena(arena, PR_TRUE); return NULL; } @@ -1000,25 +956,24 @@ PRTime CRLCache_Empty_TokenFetch_Interval = 60 * 1000000; /* how often to query the tokens for CRL objects, in order to discover new objects, if the cache does not contain any token CRLs . In microseconds */ -PRTime CRLCache_TokenRefetch_Interval = 600 * 1000000 ; /* how often - to query the tokens for CRL objects, in order to discover new objects, if - the cache already contains token CRLs In microseconds */ +PRTime CRLCache_TokenRefetch_Interval = 600 * 1000000; /* how often + to query the tokens for CRL objects, in order to discover new objects, if + the cache already contains token CRLs In microseconds */ PRTime CRLCache_ExistenceCheck_Interval = 60 * 1000000; /* how often to check if a token CRL object still exists. In microseconds */ /* this function is called at NSS initialization time */ -SECStatus InitCRLCache(void) +SECStatus +InitCRLCache(void) { - if (PR_FALSE == crlcache_initialized) - { + if (PR_FALSE == crlcache_initialized) { PORT_Assert(NULL == crlcache.lock); PORT_Assert(NULL == crlcache.issuers); PORT_Assert(NULL == namedCRLCache.lock); PORT_Assert(NULL == namedCRLCache.entries); if (crlcache.lock || crlcache.issuers || namedCRLCache.lock || - namedCRLCache.entries) - { + namedCRLCache.entries) { /* CRL cache already partially initialized */ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; @@ -1030,14 +985,12 @@ SECStatus InitCRLCache(void) #endif namedCRLCache.lock = PR_NewLock(); crlcache.issuers = PL_NewHashTable(0, SECITEM_Hash, SECITEM_HashCompare, - PL_CompareValues, NULL, NULL); - namedCRLCache.entries = PL_NewHashTable(0, SECITEM_Hash, SECITEM_HashCompare, - PL_CompareValues, NULL, NULL); + PL_CompareValues, NULL, NULL); + namedCRLCache.entries = PL_NewHashTable( + 0, SECITEM_Hash, SECITEM_HashCompare, PL_CompareValues, NULL, NULL); if (!crlcache.lock || !namedCRLCache.lock || !crlcache.issuers || - !namedCRLCache.entries) - { - if (crlcache.lock) - { + !namedCRLCache.entries) { + if (crlcache.lock) { #ifdef GLOBAL_RWLOCK NSSRWLock_Destroy(crlcache.lock); #else @@ -1045,18 +998,15 @@ SECStatus InitCRLCache(void) #endif crlcache.lock = NULL; } - if (namedCRLCache.lock) - { + if (namedCRLCache.lock) { PR_DestroyLock(namedCRLCache.lock); namedCRLCache.lock = NULL; } - if (crlcache.issuers) - { + if (crlcache.issuers) { PL_HashTableDestroy(crlcache.issuers); crlcache.issuers = NULL; } - if (namedCRLCache.entries) - { + if (namedCRLCache.entries) { PL_HashTableDestroy(namedCRLCache.entries); namedCRLCache.entries = NULL; } @@ -1066,17 +1016,14 @@ SECStatus InitCRLCache(void) crlcache_initialized = PR_TRUE; return SECSuccess; } - else - { + else { PORT_Assert(crlcache.lock); PORT_Assert(crlcache.issuers); - if ( (NULL == crlcache.lock) || (NULL == crlcache.issuers) ) - { + if ((NULL == crlcache.lock) || (NULL == crlcache.issuers)) { /* CRL cache not fully initialized */ return SECFailure; } - else - { + else { /* CRL cache already initialized */ return SECSuccess; } @@ -1084,56 +1031,48 @@ SECStatus InitCRLCache(void) } /* destructor for CRL DPCache object */ -static SECStatus DPCache_Destroy(CRLDPCache* cache) +static SECStatus +DPCache_Destroy(CRLDPCache* cache) { PRUint32 i = 0; PORT_Assert(cache); - if (!cache) - { + if (!cache) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (cache->lock) - { + if (cache->lock) { #ifdef DPC_RWLOCK NSSRWLock_Destroy(cache->lock); #else PR_DestroyLock(cache->lock); #endif } - else - { + else { PORT_Assert(0); return SECFailure; } /* destroy all our CRL objects */ - for (i=0;incrls;i++) - { + for (i = 0; i < cache->ncrls; i++) { if (!cache->crls || !cache->crls[i] || - SECSuccess != CachedCrl_Destroy(cache->crls[i])) - { + SECSuccess != CachedCrl_Destroy(cache->crls[i])) { return SECFailure; } } /* free the array of CRLs */ - if (cache->crls) - { - PORT_Free(cache->crls); + if (cache->crls) { + PORT_Free(cache->crls); } /* destroy the cert */ - if (cache->issuerDERCert) - { + if (cache->issuerDERCert) { SECITEM_FreeItem(cache->issuerDERCert, PR_TRUE); } /* free the subject */ - if (cache->subject) - { + if (cache->subject) { SECITEM_FreeItem(cache->subject, PR_TRUE); } /* free the distribution points */ - if (cache->distributionPoint) - { + if (cache->distributionPoint) { SECITEM_FreeItem(cache->distributionPoint, PR_TRUE); } PORT_Free(cache); @@ -1141,38 +1080,33 @@ static SECStatus DPCache_Destroy(CRLDPCache* cache) } /* destructor for CRL IssuerCache object */ -SECStatus IssuerCache_Destroy(CRLIssuerCache* cache) +SECStatus +IssuerCache_Destroy(CRLIssuerCache* cache) { PORT_Assert(cache); - if (!cache) - { + if (!cache) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } #ifdef XCRL - if (cache->lock) - { + if (cache->lock) { NSSRWLock_Destroy(cache->lock); } - else - { + else { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (cache->issuer) - { + if (cache->issuer) { CERT_DestroyCertificate(cache->issuer); } #endif /* free the subject */ - if (cache->subject) - { + if (cache->subject) { SECITEM_FreeItem(cache->subject, PR_TRUE); } - if (SECSuccess != DPCache_Destroy(cache->dpp)) - { + if (SECSuccess != DPCache_Destroy(cache->dpp)) { PORT_Assert(0); return SECFailure; } @@ -1181,19 +1115,18 @@ SECStatus IssuerCache_Destroy(CRLIssuerCache* cache) } /* create a named CRL entry object */ -static SECStatus NamedCRLCacheEntry_Create(NamedCRLCacheEntry** returned) +static SECStatus +NamedCRLCacheEntry_Create(NamedCRLCacheEntry** returned) { NamedCRLCacheEntry* entry = NULL; - if (!returned) - { + if (!returned) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } *returned = NULL; - entry = (NamedCRLCacheEntry*) PORT_ZAlloc(sizeof(NamedCRLCacheEntry)); - if (!entry) - { + entry = (NamedCRLCacheEntry*)PORT_ZAlloc(sizeof(NamedCRLCacheEntry)); + if (!entry) { return SECFailure; } *returned = entry; @@ -1201,21 +1134,19 @@ static SECStatus NamedCRLCacheEntry_Create(NamedCRLCacheEntry** returned) } /* destroy a named CRL entry object */ -static SECStatus NamedCRLCacheEntry_Destroy(NamedCRLCacheEntry* entry) +static SECStatus +NamedCRLCacheEntry_Destroy(NamedCRLCacheEntry* entry) { - if (!entry) - { + if (!entry) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (entry->crl) - { + if (entry->crl) { /* named CRL cache owns DER memory */ SECITEM_ZfreeItem(entry->crl, PR_TRUE); } - if (entry->canonicalizedName) - { + if (entry->canonicalizedName) { SECITEM_FreeItem(entry->canonicalizedName, PR_TRUE); } PORT_Free(entry); @@ -1223,25 +1154,22 @@ static SECStatus NamedCRLCacheEntry_Destroy(NamedCRLCacheEntry* entry) } /* callback function used in hash table destructor */ -static PRIntn PR_CALLBACK FreeIssuer(PLHashEntry *he, PRIntn i, void *arg) +static PRIntn PR_CALLBACK +FreeIssuer(PLHashEntry* he, PRIntn i, void* arg) { CRLIssuerCache* issuer = NULL; - SECStatus* rv = (SECStatus*) arg; + SECStatus* rv = (SECStatus*)arg; PORT_Assert(he); - if (!he) - { + if (!he) { return HT_ENUMERATE_NEXT; } - issuer = (CRLIssuerCache*) he->value; + issuer = (CRLIssuerCache*)he->value; PORT_Assert(issuer); - if (issuer) - { - if (SECSuccess != IssuerCache_Destroy(issuer)) - { + if (issuer) { + if (SECSuccess != IssuerCache_Destroy(issuer)) { PORT_Assert(rv); - if (rv) - { + if (rv) { *rv = SECFailure; } return HT_ENUMERATE_NEXT; @@ -1251,25 +1179,22 @@ static PRIntn PR_CALLBACK FreeIssuer(PLHashEntry *he, PRIntn i, void *arg) } /* callback function used in hash table destructor */ -static PRIntn PR_CALLBACK FreeNamedEntries(PLHashEntry *he, PRIntn i, void *arg) +static PRIntn PR_CALLBACK +FreeNamedEntries(PLHashEntry* he, PRIntn i, void* arg) { NamedCRLCacheEntry* entry = NULL; - SECStatus* rv = (SECStatus*) arg; + SECStatus* rv = (SECStatus*)arg; PORT_Assert(he); - if (!he) - { + if (!he) { return HT_ENUMERATE_NEXT; } - entry = (NamedCRLCacheEntry*) he->value; + entry = (NamedCRLCacheEntry*)he->value; PORT_Assert(entry); - if (entry) - { - if (SECSuccess != NamedCRLCacheEntry_Destroy(entry)) - { + if (entry) { + if (SECSuccess != NamedCRLCacheEntry_Destroy(entry)) { PORT_Assert(rv); - if (rv) - { + if (rv) { *rv = SECFailure; } return HT_ENUMERATE_NEXT; @@ -1279,23 +1204,22 @@ static PRIntn PR_CALLBACK FreeNamedEntries(PLHashEntry *he, PRIntn i, void *arg) } /* needs to be called at NSS shutdown time - This will destroy the global CRL cache, including + This will destroy the global CRL cache, including - the hash table of issuer cache objects - the issuer cache objects - DPCache objects in issuer cache objects */ -SECStatus ShutdownCRLCache(void) +SECStatus +ShutdownCRLCache(void) { SECStatus rv = SECSuccess; - if (PR_FALSE == crlcache_initialized && - !crlcache.lock && !crlcache.issuers) - { + if (PR_FALSE == crlcache_initialized && !crlcache.lock && + !crlcache.issuers) { /* CRL cache has already been shut down */ return SECSuccess; } if (PR_TRUE == crlcache_initialized && (!crlcache.lock || !crlcache.issuers || !namedCRLCache.lock || - !namedCRLCache.entries)) - { + !namedCRLCache.entries)) { /* CRL cache has partially been shut down */ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; @@ -1306,7 +1230,7 @@ SECStatus ShutdownCRLCache(void) /* free the hash table of issuers */ PL_HashTableDestroy(crlcache.issuers); crlcache.issuers = NULL; - /* free the global lock */ +/* free the global lock */ #ifdef GLOBAL_RWLOCK NSSRWLock_Destroy(crlcache.lock); #else @@ -1331,57 +1255,49 @@ SECStatus ShutdownCRLCache(void) /* add a new CRL object to the dynamic array of CRLs of the DPCache, and returns the cached CRL object . Needs write access to DPCache. */ -static SECStatus DPCache_AddCRL(CRLDPCache* cache, CachedCrl* newcrl, - PRBool* added) +static SECStatus +DPCache_AddCRL(CRLDPCache* cache, CachedCrl* newcrl, PRBool* added) { CachedCrl** newcrls = NULL; PRUint32 i = 0; PORT_Assert(cache); PORT_Assert(newcrl); PORT_Assert(added); - if (!cache || !newcrl || !added) - { + if (!cache || !newcrl || !added) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } *added = PR_FALSE; /* before adding a new CRL, check if it is a duplicate */ - for (i=0;incrls;i++) - { + for (i = 0; i < cache->ncrls; i++) { CachedCrl* existing = NULL; SECStatus rv = SECSuccess; PRBool dupe = PR_FALSE, updated = PR_FALSE; - if (!cache->crls) - { + if (!cache->crls) { PORT_Assert(0); return SECFailure; } existing = cache->crls[i]; - if (!existing) - { + if (!existing) { PORT_Assert(0); return SECFailure; } rv = CachedCrl_Compare(existing, newcrl, &dupe, &updated); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (PR_TRUE == dupe) - { + if (PR_TRUE == dupe) { /* dupe */ PORT_SetError(SEC_ERROR_CRL_ALREADY_EXISTS); return SECSuccess; } - if (PR_TRUE == updated) - { + if (PR_TRUE == updated) { /* this token CRL is in the same slot and has the same object ID, but different content. We need to remove the old object */ - if (SECSuccess != DPCache_RemoveCRL(cache, i)) - { + if (SECSuccess != DPCache_RemoveCRL(cache, i)) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return PR_FALSE; @@ -1389,44 +1305,41 @@ static SECStatus DPCache_AddCRL(CRLDPCache* cache, CachedCrl* newcrl, } } - newcrls = (CachedCrl**)PORT_Realloc(cache->crls, - (cache->ncrls+1)*sizeof(CachedCrl*)); - if (!newcrls) - { + newcrls = (CachedCrl**)PORT_Realloc(cache->crls, (cache->ncrls + 1) * + sizeof(CachedCrl*)); + if (!newcrls) { return SECFailure; } cache->crls = newcrls; cache->ncrls++; - cache->crls[cache->ncrls-1] = newcrl; + cache->crls[cache->ncrls - 1] = newcrl; *added = PR_TRUE; return SECSuccess; } /* remove CRL at offset specified */ -static SECStatus DPCache_RemoveCRL(CRLDPCache* cache, PRUint32 offset) +static SECStatus +DPCache_RemoveCRL(CRLDPCache* cache, PRUint32 offset) { CachedCrl* acrl = NULL; PORT_Assert(cache); - if (!cache || (!cache->crls) || (!(offsetncrls)) ) - { + if (!cache || (!cache->crls) || (!(offset < cache->ncrls))) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } acrl = cache->crls[offset]; PORT_Assert(acrl); - if (!acrl) - { + if (!acrl) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - cache->crls[offset] = cache->crls[cache->ncrls-1]; - cache->crls[cache->ncrls-1] = NULL; + cache->crls[offset] = cache->crls[cache->ncrls - 1]; + cache->crls[cache->ncrls - 1] = NULL; cache->ncrls--; if (cache->selected == acrl) { cache->selected = NULL; } - if (SECSuccess != CachedCrl_Destroy(acrl)) - { + if (SECSuccess != CachedCrl_Destroy(acrl)) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; @@ -1442,7 +1355,8 @@ static SECStatus DPCache_RemoveCRL(CRLDPCache* cache, PRUint32 offset) PKCS#11 object of the same ID and subject (which actually happens in softoken), but this function has no way of knowing that the object value changed, since CKA_VALUE isn't checked. */ -static PRBool TokenCRLStillExists(CERTSignedCrl* crl) +static PRBool +TokenCRLStillExists(CERTSignedCrl* crl) { NSSItem newsubject; SECItem subject; @@ -1455,20 +1369,17 @@ static PRBool TokenCRLStillExists(CERTSignedCrl* crl) SECItem* oldSubject = NULL; PORT_Assert(crl); - if (!crl) - { + if (!crl) { return PR_FALSE; } slot = crl->slot; PORT_Assert(crl->slot); - if (!slot) - { + if (!slot) { return PR_FALSE; } oldSubject = &crl->crl.derName; PORT_Assert(oldSubject); - if (!oldSubject) - { + if (!oldSubject) { return PR_FALSE; } @@ -1478,14 +1389,12 @@ static PRBool TokenCRLStillExists(CERTSignedCrl* crl) /* first, make an nssCryptokiObject */ instance.handle = crl->pkcs11ID; PORT_Assert(instance.handle); - if (!instance.handle) - { + if (!instance.handle) { return PR_FALSE; } instance.token = PK11Slot_GetNSSToken(slot); PORT_Assert(instance.token); - if (!instance.token) - { + if (!instance.token) { return PR_FALSE; } instance.isTokenObject = PR_TRUE; @@ -1493,34 +1402,26 @@ static PRBool TokenCRLStillExists(CERTSignedCrl* crl) arena = NSSArena_Create(); PORT_Assert(arena); - if (!arena) - { + if (!arena) { return PR_FALSE; } - status = nssCryptokiCRL_GetAttributes(&instance, - NULL, /* XXX sessionOpt */ - arena, - NULL, - &newsubject, /* subject */ - &crl_class, /* class */ - NULL, - NULL); - if (PR_SUCCESS == status) - { + status = + nssCryptokiCRL_GetAttributes(&instance, NULL, /* XXX sessionOpt */ + arena, NULL, &newsubject, /* subject */ + &crl_class, /* class */ + NULL, NULL); + if (PR_SUCCESS == status) { subject.data = newsubject.data; subject.len = newsubject.size; - if (SECITEM_CompareItem(oldSubject, &subject) != SECEqual) - { + if (SECITEM_CompareItem(oldSubject, &subject) != SECEqual) { xstatus = PR_FALSE; } - if (CKO_NETSCAPE_CRL != crl_class) - { + if (CKO_NETSCAPE_CRL != crl_class) { xstatus = PR_FALSE; } } - else - { + else { xstatus = PR_FALSE; } NSSArena_Destroy(arena); @@ -1528,19 +1429,18 @@ static PRBool TokenCRLStillExists(CERTSignedCrl* crl) } /* verify the signature of a CRL against its issuer at a given date */ -static SECStatus CERT_VerifyCRL( - CERTSignedCrl* crlobject, - CERTCertificate* issuer, - PRTime vfdate, - void* wincx) +static SECStatus +CERT_VerifyCRL(CERTSignedCrl* crlobject, CERTCertificate* issuer, PRTime vfdate, + void* wincx) { - return CERT_VerifySignedData(&crlobject->signatureWrap, - issuer, vfdate, wincx); + return CERT_VerifySignedData(&crlobject->signatureWrap, issuer, vfdate, + wincx); } /* verify a CRL and update cache state */ -static SECStatus CachedCrl_Verify(CRLDPCache* cache, CachedCrl* crlobject, - PRTime vfdate, void* wincx) +static SECStatus +CachedCrl_Verify(CRLDPCache* cache, CachedCrl* crlobject, PRTime vfdate, + void* wincx) { /* Check if it is an invalid CRL if we got a bad CRL, we want to cache it in order to avoid @@ -1554,66 +1454,59 @@ static SECStatus CachedCrl_Verify(CRLDPCache* cache, CachedCrl* crlobject, the issuer certificate becomes available if that causes the signature to verify */ - if (!cache || !crlobject) - { + if (!cache || !crlobject) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (PR_TRUE == GetOpaqueCRLFields(crlobject->crl)->decodingError) - { + if (PR_TRUE == GetOpaqueCRLFields(crlobject->crl)->decodingError) { crlobject->sigChecked = PR_TRUE; /* we can never verify a CRL with bogus DER. Mark it checked so we won't try again */ PORT_SetError(SEC_ERROR_BAD_DER); return SECSuccess; } - else - { + else { SECStatus signstatus = SECFailure; - if (cache->issuerDERCert) - { - CERTCertificate *issuer = CERT_NewTempCertificate(cache->dbHandle, - cache->issuerDERCert, NULL, PR_FALSE, PR_TRUE); + if (cache->issuerDERCert) { + CERTCertificate* issuer = CERT_NewTempCertificate( + cache->dbHandle, cache->issuerDERCert, NULL, PR_FALSE, PR_TRUE); - if (issuer) { - signstatus = CERT_VerifyCRL(crlobject->crl, issuer, vfdate, - wincx); - CERT_DestroyCertificate(issuer); - } + if (issuer) { + signstatus = + CERT_VerifyCRL(crlobject->crl, issuer, vfdate, wincx); + CERT_DestroyCertificate(issuer); + } } - if (SECSuccess != signstatus) - { - if (!cache->issuerDERCert) - { + if (SECSuccess != signstatus) { + if (!cache->issuerDERCert) { /* we tried to verify without an issuer cert . This is because this CRL came through a call to SEC_FindCrlByName. So, we don't cache this verification failure. We'll try to verify the CRL again when a certificate from that issuer becomes available */ - } else - { + } + else { crlobject->sigChecked = PR_TRUE; } PORT_SetError(SEC_ERROR_CRL_BAD_SIGNATURE); return SECSuccess; - } else - { + } + else { crlobject->sigChecked = PR_TRUE; crlobject->sigValid = PR_TRUE; } } - + return SECSuccess; } /* fetch the CRLs for this DP from the PKCS#11 tokens */ -static SECStatus DPCache_FetchFromTokens(CRLDPCache* cache, PRTime vfdate, - void* wincx) +static SECStatus +DPCache_FetchFromTokens(CRLDPCache* cache, PRTime vfdate, void* wincx) { SECStatus rv = SECSuccess; CERTCrlHeadNode head; - if (!cache) - { + if (!cache) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; @@ -1626,67 +1519,55 @@ static SECStatus DPCache_FetchFromTokens(CRLDPCache* cache, PRTime vfdate, /* if this function fails, something very wrong happened, such as an out of memory error during CRL decoding. We don't want to proceed and must mark the cache object invalid */ - if (SECFailure == rv) - { + if (SECFailure == rv) { /* fetch failed, add error bit */ cache->invalid |= CRL_CACHE_LAST_FETCH_FAILED; - } else - { + } + else { /* fetch was successful, clear this error bit */ cache->invalid &= (~CRL_CACHE_LAST_FETCH_FAILED); } /* add any CRLs found to our array */ - if (SECSuccess == rv) - { + if (SECSuccess == rv) { CERTCrlNode* crlNode = NULL; - for (crlNode = head.first; crlNode ; crlNode = crlNode->next) - { + for (crlNode = head.first; crlNode; crlNode = crlNode->next) { CachedCrl* returned = NULL; CERTSignedCrl* crlobject = crlNode->crl; - if (!crlobject) - { + if (!crlobject) { PORT_Assert(0); continue; } rv = CachedCrl_Create(&returned, crlobject, CRL_OriginToken); - if (SECSuccess == rv) - { + if (SECSuccess == rv) { PRBool added = PR_FALSE; rv = DPCache_AddCRL(cache, returned, &added); - if (PR_TRUE != added) - { + if (PR_TRUE != added) { rv = CachedCrl_Destroy(returned); returned = NULL; } - else if (vfdate) - { + else if (vfdate) { rv = CachedCrl_Verify(cache, returned, vfdate, wincx); } } - else - { + else { /* not enough memory to add the CRL to the cache. mark it invalid so we will try again . */ cache->invalid |= CRL_CACHE_LAST_FETCH_FAILED; } - if (SECFailure == rv) - { + if (SECFailure == rv) { break; } } } - if (head.arena) - { + if (head.arena) { CERTCrlNode* crlNode = NULL; /* clean up the CRL list in case we got a partial one during a failed fetch */ - for (crlNode = head.first; crlNode ; crlNode = crlNode->next) - { - if (crlNode->crl) - { + for (crlNode = head.first; crlNode; crlNode = crlNode->next) { + if (crlNode->crl) { SEC_DestroyCrl(crlNode->crl); /* free the CRL. Either it got added to the cache and the refcount got bumped, or not, and thus we need to free its RAM */ @@ -1698,69 +1579,59 @@ static SECStatus DPCache_FetchFromTokens(CRLDPCache* cache, PRTime vfdate, return rv; } -static SECStatus CachedCrl_GetEntry(CachedCrl* crl, const SECItem* sn, - CERTCrlEntry** returned) +static SECStatus +CachedCrl_GetEntry(CachedCrl* crl, const SECItem* sn, CERTCrlEntry** returned) { CERTCrlEntry* acrlEntry; - + PORT_Assert(crl); PORT_Assert(crl->entries); PORT_Assert(sn); PORT_Assert(returned); - if (!crl || !sn || !returned || !crl->entries) - { + if (!crl || !sn || !returned || !crl->entries) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } acrlEntry = PL_HashTableLookup(crl->entries, (void*)sn); - if (acrlEntry) - { + if (acrlEntry) { *returned = acrlEntry; } - else - { + else { *returned = NULL; } return SECSuccess; } /* check if a particular SN is in the CRL cache and return its entry */ -dpcacheStatus DPCache_Lookup(CRLDPCache* cache, const SECItem* sn, - CERTCrlEntry** returned) +dpcacheStatus +DPCache_Lookup(CRLDPCache* cache, const SECItem* sn, CERTCrlEntry** returned) { SECStatus rv; - if (!cache || !sn || !returned) - { + if (!cache || !sn || !returned) { PORT_SetError(SEC_ERROR_INVALID_ARGS); /* no cache or SN to look up, or no way to return entry */ return dpcacheCallerError; } *returned = NULL; - if (0 != cache->invalid) - { + if (0 != cache->invalid) { /* the cache contains a bad CRL, or there was a CRL fetching error. */ PORT_SetError(SEC_ERROR_CRL_INVALID); return dpcacheInvalidCacheError; } - if (!cache->selected) - { + if (!cache->selected) { /* no CRL means no entry to return. This is OK, except for * NIST policy */ return dpcacheEmpty; } rv = CachedCrl_GetEntry(cache->selected, sn, returned); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { return dpcacheLookupError; } - else - { - if (*returned) - { + else { + if (*returned) { return dpcacheFoundEntry; } - else - { + else { return dpcacheNoEntry; } } @@ -1768,45 +1639,43 @@ dpcacheStatus DPCache_Lookup(CRLDPCache* cache, const SECItem* sn, #if defined(DPC_RWLOCK) -#define DPCache_LockWrite() \ -{ \ - if (readlocked) \ - { \ - NSSRWLock_UnlockRead(cache->lock); \ - } \ - NSSRWLock_LockWrite(cache->lock); \ -} +#define DPCache_LockWrite() \ + { \ + if (readlocked) { \ + NSSRWLock_UnlockRead(cache->lock); \ + } \ + NSSRWLock_LockWrite(cache->lock); \ + } -#define DPCache_UnlockWrite() \ -{ \ - if (readlocked) \ - { \ - NSSRWLock_LockRead(cache->lock); \ - } \ - NSSRWLock_UnlockWrite(cache->lock); \ -} +#define DPCache_UnlockWrite() \ + { \ + if (readlocked) { \ + NSSRWLock_LockRead(cache->lock); \ + } \ + NSSRWLock_UnlockWrite(cache->lock); \ + } #else /* with a global lock, we are always locked for read before we need write access, so do nothing */ -#define DPCache_LockWrite() \ -{ \ -} +#define DPCache_LockWrite() \ + { \ + } -#define DPCache_UnlockWrite() \ -{ \ -} +#define DPCache_UnlockWrite() \ + { \ + } #endif /* update the content of the CRL cache, including fetching of CRLs, and reprocessing with specified issuer and date . We are always holding either the read or write lock on DPCache upon entry. */ -static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* - issuer, PRBool readlocked, PRTime vfdate, - void* wincx) +static SECStatus +DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* issuer, + PRBool readlocked, PRTime vfdate, void* wincx) { /* Update the CRLDPCache now. We don't cache token CRL lookup misses yet, as we have no way of getting notified of new PKCS#11 object @@ -1821,8 +1690,7 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* PRTime lastfetch = 0; PRBool mustunlock = PR_FALSE; - if (!cache) - { + if (!cache) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } @@ -1839,36 +1707,32 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* */ forcedrefresh = cache->refresh; lastfetch = cache->lastfetch; - if (PR_TRUE != forcedrefresh && - (!(cache->invalid & CRL_CACHE_LAST_FETCH_FAILED))) - { + if (PR_TRUE != forcedrefresh && + (!(cache->invalid & CRL_CACHE_LAST_FETCH_FAILED))) { now = PR_Now(); hastokenCRLs = DPCache_HasTokenCRLs(cache); } - if ( (0 == lastfetch) || + if ((0 == lastfetch) || - (PR_TRUE == forcedrefresh) || + (PR_TRUE == forcedrefresh) || - (cache->invalid & CRL_CACHE_LAST_FETCH_FAILED) || + (cache->invalid & CRL_CACHE_LAST_FETCH_FAILED) || - ( (PR_FALSE == hastokenCRLs) && - ( (now - cache->lastfetch > CRLCache_Empty_TokenFetch_Interval) || - (now < cache->lastfetch)) ) || + ((PR_FALSE == hastokenCRLs) && + ((now - cache->lastfetch > CRLCache_Empty_TokenFetch_Interval) || + (now < cache->lastfetch))) || - ( (PR_TRUE == hastokenCRLs) && - ((now - cache->lastfetch > CRLCache_TokenRefetch_Interval) || - (now < cache->lastfetch)) ) ) - { + ((PR_TRUE == hastokenCRLs) && + ((now - cache->lastfetch > CRLCache_TokenRefetch_Interval) || + (now < cache->lastfetch)))) { /* the cache needs to be refreshed, and/or we had zero CRL for this DP. Try to get one from PKCS#11 tokens */ DPCache_LockWrite(); /* check if another thread updated before us, and skip update if so */ - if (lastfetch == cache->lastfetch) - { + if (lastfetch == cache->lastfetch) { /* we are the first */ rv = DPCache_FetchFromTokens(cache, vfdate, wincx); - if (PR_TRUE == cache->refresh) - { + if (PR_TRUE == cache->refresh) { cache->refresh = PR_FALSE; /* clear refresh state */ } dirty = PR_TRUE; @@ -1881,38 +1745,31 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* we'll do this inexpensive existence check either 1) if there was a token object fetch 2) every minute */ - if (( PR_TRUE != dirty) && (!now) ) - { + if ((PR_TRUE != dirty) && (!now)) { now = PR_Now(); } - if ( (PR_TRUE == dirty) || - ( (now - cache->lastcheck > CRLCache_ExistenceCheck_Interval) || - (now < cache->lastcheck)) ) - { + if ((PR_TRUE == dirty) || + ((now - cache->lastcheck > CRLCache_ExistenceCheck_Interval) || + (now < cache->lastcheck))) { PRTime lastcheck = cache->lastcheck; mustunlock = PR_FALSE; /* check if all CRLs still exist */ - for (i = 0; (i < cache->ncrls) ; i++) - { + for (i = 0; (i < cache->ncrls); i++) { CachedCrl* savcrl = cache->crls[i]; - if ( (!savcrl) || (savcrl && CRL_OriginToken != savcrl->origin)) - { + if ((!savcrl) || (savcrl && CRL_OriginToken != savcrl->origin)) { /* we only want to check token CRLs */ continue; } - if ((PR_TRUE != TokenCRLStillExists(savcrl->crl))) - { - + if ((PR_TRUE != TokenCRLStillExists(savcrl->crl))) { + /* this CRL is gone */ - if (PR_TRUE != mustunlock) - { + if (PR_TRUE != mustunlock) { DPCache_LockWrite(); mustunlock = PR_TRUE; } /* first, we need to check if another thread did an update before we did */ - if (lastcheck == cache->lastcheck) - { + if (lastcheck == cache->lastcheck) { /* the CRL is gone. And we are the one to do the update */ DPCache_RemoveCRL(cache, i); dirty = PR_TRUE; @@ -1921,8 +1778,7 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* updates in this thread for the remaining CRLs */ } } - if (PR_TRUE == mustunlock) - { + if (PR_TRUE == mustunlock) { cache->lastcheck = PR_Now(); DPCache_UnlockWrite(); mustunlock = PR_FALSE; @@ -1931,15 +1787,13 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* /* add issuer certificate if it was previously unavailable */ if (issuer && (NULL == cache->issuerDERCert) && - (SECSuccess == CERT_CheckCertUsage(issuer, KU_CRL_SIGN))) - { + (SECSuccess == CERT_CheckCertUsage(issuer, KU_CRL_SIGN))) { /* if we didn't have a valid issuer cert yet, but we do now. add it */ DPCache_LockWrite(); - if (!cache->issuerDERCert) - { + if (!cache->issuerDERCert) { dirty = PR_TRUE; - cache->dbHandle = issuer->dbhandle; - cache->issuerDERCert = SECITEM_DupItem(&issuer->derCert); + cache->dbHandle = issuer->dbhandle; + cache->issuerDERCert = SECITEM_DupItem(&issuer->derCert); } DPCache_UnlockWrite(); } @@ -1950,21 +1804,16 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* SEC_FindCrlByName, or through manual insertion, rather than through a certificate verification (CERT_CheckCRL) */ - if (cache->issuerDERCert && vfdate ) - { - mustunlock = PR_FALSE; + if (cache->issuerDERCert && vfdate) { + mustunlock = PR_FALSE; /* re-process all unverified CRLs */ - for (i = 0; i < cache->ncrls ; i++) - { + for (i = 0; i < cache->ncrls; i++) { CachedCrl* savcrl = cache->crls[i]; - if (!savcrl) - { + if (!savcrl) { continue; } - if (PR_TRUE != savcrl->sigChecked) - { - if (!mustunlock) - { + if (PR_TRUE != savcrl->sigChecked) { + if (!mustunlock) { DPCache_LockWrite(); mustunlock = PR_TRUE; } @@ -1972,9 +1821,8 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* it before we did, and abort if it has been modified since we acquired the lock. Make sure first that the CRL is still in the array at the same position */ - if ( (incrls) && (savcrl == cache->crls[i]) && - (PR_TRUE != savcrl->sigChecked) ) - { + if ((i < cache->ncrls) && (savcrl == cache->crls[i]) && + (PR_TRUE != savcrl->sigChecked)) { /* the CRL is still there, unverified. Do it */ CachedCrl_Verify(cache, savcrl, vfdate, wincx); dirty = PR_TRUE; @@ -1982,191 +1830,166 @@ static SECStatus DPCache_GetUpToDate(CRLDPCache* cache, CERTCertificate* /* stay locked here intentionally so we do all the other updates in this thread for the remaining CRLs */ } - if (mustunlock && !dirty) - { + if (mustunlock && !dirty) { DPCache_UnlockWrite(); mustunlock = PR_FALSE; } } } - if (dirty || cache->mustchoose) - { + if (dirty || cache->mustchoose) { /* changes to the content of the CRL cache necessitate examining all CRLs for selection of the most appropriate one to cache */ - if (!mustunlock) - { - DPCache_LockWrite(); - mustunlock = PR_TRUE; - } + if (!mustunlock) { + DPCache_LockWrite(); + mustunlock = PR_TRUE; + } DPCache_SelectCRL(cache); cache->mustchoose = PR_FALSE; } if (mustunlock) - DPCache_UnlockWrite(); + DPCache_UnlockWrite(); return rv; } /* callback for qsort to sort by thisUpdate */ -static int SortCRLsByThisUpdate(const void* arg1, const void* arg2) +static int +SortCRLsByThisUpdate(const void* arg1, const void* arg2) { PRTime timea, timeb; SECStatus rv = SECSuccess; - CachedCrl* a, *b; + CachedCrl *a, *b; - a = *(CachedCrl**) arg1; - b = *(CachedCrl**) arg2; + a = *(CachedCrl**)arg1; + b = *(CachedCrl**)arg2; - if (!a || !b) - { + if (!a || !b) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); rv = SECFailure; } - if (SECSuccess == rv) - { + if (SECSuccess == rv) { rv = DER_DecodeTimeChoice(&timea, &a->crl->crl.lastUpdate); - } - if (SECSuccess == rv) - { + } + if (SECSuccess == rv) { rv = DER_DecodeTimeChoice(&timeb, &b->crl->crl.lastUpdate); } - if (SECSuccess == rv) - { - if (timea > timeb) - { + if (SECSuccess == rv) { + if (timea > timeb) { return 1; /* a is better than b */ } - if (timea < timeb ) - { + if (timea < timeb) { return -1; /* a is not as good as b */ } } /* if they are equal, or if all else fails, use pointer differences */ PORT_Assert(a != b); /* they should never be equal */ - return a>b?1:-1; + return a > b ? 1 : -1; } /* callback for qsort to sort a set of disparate CRLs, some of which are invalid DER or failed signature check. - + Validated CRLs are differentiated by thisUpdate . Validated CRLs are preferred over non-validated CRLs . Proper DER CRLs are preferred over non-DER data . */ -static int SortImperfectCRLs(const void* arg1, const void* arg2) +static int +SortImperfectCRLs(const void* arg1, const void* arg2) { - CachedCrl* a, *b; + CachedCrl *a, *b; - a = *(CachedCrl**) arg1; - b = *(CachedCrl**) arg2; + a = *(CachedCrl**)arg1; + b = *(CachedCrl**)arg2; - if (!a || !b) - { + if (!a || !b) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); PORT_Assert(0); } - else - { + else { PRBool aDecoded = PR_FALSE, bDecoded = PR_FALSE; - if ( (PR_TRUE == a->sigValid) && (PR_TRUE == b->sigValid) ) - { + if ((PR_TRUE == a->sigValid) && (PR_TRUE == b->sigValid)) { /* both CRLs have been validated, choose the latest one */ return SortCRLsByThisUpdate(arg1, arg2); } - if (PR_TRUE == a->sigValid) - { + if (PR_TRUE == a->sigValid) { return 1; /* a is greater than b */ } - if (PR_TRUE == b->sigValid) - { + if (PR_TRUE == b->sigValid) { return -1; /* a is not as good as b */ } aDecoded = GetOpaqueCRLFields(a->crl)->decodingError; bDecoded = GetOpaqueCRLFields(b->crl)->decodingError; /* neither CRL had its signature check pass */ - if ( (PR_FALSE == aDecoded) && (PR_FALSE == bDecoded) ) - { + if ((PR_FALSE == aDecoded) && (PR_FALSE == bDecoded)) { /* both CRLs are proper DER, choose the latest one */ return SortCRLsByThisUpdate(arg1, arg2); } - if (PR_FALSE == aDecoded) - { + if (PR_FALSE == aDecoded) { return 1; /* a is better than b */ } - if (PR_FALSE == bDecoded) - { + if (PR_FALSE == bDecoded) { return -1; /* a is not as good as b */ } /* both are invalid DER. sigh. */ } /* if they are equal, or if all else fails, use pointer differences */ PORT_Assert(a != b); /* they should never be equal */ - return a>b?1:-1; + return a > b ? 1 : -1; } - /* Pick best CRL to use . needs write access */ -static SECStatus DPCache_SelectCRL(CRLDPCache* cache) +static SECStatus +DPCache_SelectCRL(CRLDPCache* cache) { PRUint32 i; PRBool valid = PR_TRUE; CachedCrl* selected = NULL; PORT_Assert(cache); - if (!cache) - { + if (!cache) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } /* if any invalid CRL is present, then the CRL cache is considered invalid, for security reasons */ - for (i = 0 ; incrls; i++) - { + for (i = 0; i < cache->ncrls; i++) { if (!cache->crls[i] || !cache->crls[i]->sigChecked || - !cache->crls[i]->sigValid) - { + !cache->crls[i]->sigValid) { valid = PR_FALSE; break; } } - if (PR_TRUE == valid) - { + if (PR_TRUE == valid) { /* all CRLs are valid, clear this error */ cache->invalid &= (~CRL_CACHE_INVALID_CRLS); - } else - { + } + else { /* some CRLs are invalid, set this error */ cache->invalid |= CRL_CACHE_INVALID_CRLS; } - if (cache->invalid) - { + if (cache->invalid) { /* cache is in an invalid state, so reset it */ - if (cache->selected) - { + if (cache->selected) { cache->selected = NULL; } /* also sort the CRLs imperfectly */ - qsort(cache->crls, cache->ncrls, sizeof(CachedCrl*), - SortImperfectCRLs); + qsort(cache->crls, cache->ncrls, sizeof(CachedCrl*), SortImperfectCRLs); return SECSuccess; } /* all CRLs are good, sort them by thisUpdate */ - qsort(cache->crls, cache->ncrls, sizeof(CachedCrl*), - SortCRLsByThisUpdate); + qsort(cache->crls, cache->ncrls, sizeof(CachedCrl*), SortCRLsByThisUpdate); - if (cache->ncrls) - { + if (cache->ncrls) { /* pick the newest CRL */ - selected = cache->crls[cache->ncrls-1]; - + selected = cache->crls[cache->ncrls - 1]; + /* and populate the cache */ - if (SECSuccess != CachedCrl_Populate(selected)) - { + if (SECSuccess != CachedCrl_Populate(selected)) { return SECFailure; } } @@ -2177,22 +2000,21 @@ static SECStatus DPCache_SelectCRL(CRLDPCache* cache) } /* initialize a DPCache object */ -static SECStatus DPCache_Create(CRLDPCache** returned, CERTCertificate* issuer, - const SECItem* subject, SECItem* dp) +static SECStatus +DPCache_Create(CRLDPCache** returned, CERTCertificate* issuer, + const SECItem* subject, SECItem* dp) { CRLDPCache* cache = NULL; PORT_Assert(returned); /* issuer and dp are allowed to be NULL */ - if (!returned || !subject) - { + if (!returned || !subject) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } *returned = NULL; cache = PORT_ZAlloc(sizeof(CRLDPCache)); - if (!cache) - { + if (!cache) { return SECFailure; } #ifdef DPC_RWLOCK @@ -2200,15 +2022,13 @@ static SECStatus DPCache_Create(CRLDPCache** returned, CERTCertificate* issuer, #else cache->lock = PR_NewLock(); #endif - if (!cache->lock) - { - PORT_Free(cache); + if (!cache->lock) { + PORT_Free(cache); return SECFailure; } - if (issuer) - { - cache->dbHandle = issuer->dbhandle; - cache->issuerDERCert = SECITEM_DupItem(&issuer->derCert); + if (issuer) { + cache->dbHandle = issuer->dbhandle; + cache->issuerDERCert = SECITEM_DupItem(&issuer->derCert); } cache->distributionPoint = SECITEM_DupItem(dp); cache->subject = SECITEM_DupItem(subject); @@ -2219,45 +2039,39 @@ static SECStatus DPCache_Create(CRLDPCache** returned, CERTCertificate* issuer, } /* create an issuer cache object (per CA subject ) */ -static SECStatus IssuerCache_Create(CRLIssuerCache** returned, - CERTCertificate* issuer, - const SECItem* subject, const SECItem* dp) +static SECStatus +IssuerCache_Create(CRLIssuerCache** returned, CERTCertificate* issuer, + const SECItem* subject, const SECItem* dp) { SECStatus rv = SECSuccess; CRLIssuerCache* cache = NULL; PORT_Assert(returned); PORT_Assert(subject); /* issuer and dp are allowed to be NULL */ - if (!returned || !subject) - { + if (!returned || !subject) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } *returned = NULL; - cache = (CRLIssuerCache*) PORT_ZAlloc(sizeof(CRLIssuerCache)); - if (!cache) - { + cache = (CRLIssuerCache*)PORT_ZAlloc(sizeof(CRLIssuerCache)); + if (!cache) { return SECFailure; } cache->subject = SECITEM_DupItem(subject); #ifdef XCRL cache->lock = NSSRWLock_New(NSS_RWLOCK_RANK_NONE, NULL); - if (!cache->lock) - { + if (!cache->lock) { rv = SECFailure; } - if (SECSuccess == rv && issuer) - { + if (SECSuccess == rv && issuer) { cache->issuer = CERT_DupCertificate(issuer); - if (!cache->issuer) - { + if (!cache->issuer) { rv = SECFailure; } } #endif - if (SECSuccess != rv) - { + if (SECSuccess != rv) { PORT_Assert(SECSuccess == IssuerCache_Destroy(cache)); return SECFailure; } @@ -2266,31 +2080,26 @@ static SECStatus IssuerCache_Create(CRLIssuerCache** returned, } /* add a DPCache to the issuer cache */ -static SECStatus IssuerCache_AddDP(CRLIssuerCache* cache, - CERTCertificate* issuer, - const SECItem* subject, - const SECItem* dp, - CRLDPCache** newdpc) +static SECStatus +IssuerCache_AddDP(CRLIssuerCache* cache, CERTCertificate* issuer, + const SECItem* subject, const SECItem* dp, + CRLDPCache** newdpc) { /* now create the required DP cache object */ - if (!cache || !subject || !newdpc) - { + if (!cache || !subject || !newdpc) { PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (!dp) - { + if (!dp) { /* default distribution point */ SECStatus rv = DPCache_Create(&cache->dpp, issuer, subject, NULL); - if (SECSuccess == rv) - { + if (SECSuccess == rv) { *newdpc = cache->dpp; return SECSuccess; } } - else - { + else { /* we should never hit this until we support multiple DPs */ PORT_Assert(dp); /* XCRL allocate a new distribution point cache object, initialize it, @@ -2300,27 +2109,26 @@ static SECStatus IssuerCache_AddDP(CRLIssuerCache* cache, } /* add an IssuerCache to the global hash table of issuers */ -static SECStatus CRLCache_AddIssuer(CRLIssuerCache* issuer) -{ +static SECStatus +CRLCache_AddIssuer(CRLIssuerCache* issuer) +{ PORT_Assert(issuer); PORT_Assert(crlcache.issuers); - if (!issuer || !crlcache.issuers) - { + if (!issuer || !crlcache.issuers) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (NULL == PL_HashTableAdd(crlcache.issuers, (void*) issuer->subject, - (void*) issuer)) - { + if (NULL == PL_HashTableAdd(crlcache.issuers, (void*)issuer->subject, + (void*)issuer)) { return SECFailure; } return SECSuccess; } /* retrieve the issuer cache object for a given issuer subject */ -static SECStatus CRLCache_GetIssuerCache(CRLCache* cache, - const SECItem* subject, - CRLIssuerCache** returned) +static SECStatus +CRLCache_GetIssuerCache(CRLCache* cache, const SECItem* subject, + CRLIssuerCache** returned) { /* we need to look up the issuer in the hash table */ SECStatus rv = SECSuccess; @@ -2328,58 +2136,51 @@ static SECStatus CRLCache_GetIssuerCache(CRLCache* cache, PORT_Assert(subject); PORT_Assert(returned); PORT_Assert(crlcache.issuers); - if (!cache || !subject || !returned || !crlcache.issuers) - { + if (!cache || !subject || !returned || !crlcache.issuers) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); rv = SECFailure; } - if (SECSuccess == rv) - { - *returned = (CRLIssuerCache*) PL_HashTableLookup(crlcache.issuers, - (void*) subject); + if (SECSuccess == rv) { + *returned = (CRLIssuerCache*)PL_HashTableLookup(crlcache.issuers, + (void*)subject); } return rv; } /* retrieve the full CRL object that best matches the content of a DPCache */ -static CERTSignedCrl* GetBestCRL(CRLDPCache* cache, PRBool entries) +static CERTSignedCrl* +GetBestCRL(CRLDPCache* cache, PRBool entries) { CachedCrl* acrl = NULL; PORT_Assert(cache); - if (!cache) - { + if (!cache) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return NULL; } - if (0 == cache->ncrls) - { + if (0 == cache->ncrls) { /* empty cache*/ PORT_SetError(SEC_ERROR_CRL_NOT_FOUND); return NULL; - } + } /* if we have a valid full CRL selected, return it */ - if (cache->selected) - { + if (cache->selected) { return SEC_DupCrl(cache->selected->crl); } /* otherwise, use latest valid DER CRL */ - acrl = cache->crls[cache->ncrls-1]; + acrl = cache->crls[cache->ncrls - 1]; - if (acrl && (PR_FALSE == GetOpaqueCRLFields(acrl->crl)->decodingError) ) - { + if (acrl && (PR_FALSE == GetOpaqueCRLFields(acrl->crl)->decodingError)) { SECStatus rv = SECSuccess; - if (PR_TRUE == entries) - { + if (PR_TRUE == entries) { rv = CERT_CompleteCRLDecodeEntries(acrl->crl); } - if (SECSuccess == rv) - { + if (SECSuccess == rv) { return SEC_DupCrl(acrl->crl); } } @@ -2389,7 +2190,8 @@ static CERTSignedCrl* GetBestCRL(CRLDPCache* cache, PRBool entries) } /* get a particular DPCache object from an IssuerCache */ -static CRLDPCache* IssuerCache_GetDPCache(CRLIssuerCache* cache, const SECItem* dp) +static CRLDPCache* +IssuerCache_GetDPCache(CRLIssuerCache* cache, const SECItem* dp) { CRLDPCache* dpp = NULL; PORT_Assert(cache); @@ -2397,8 +2199,7 @@ static CRLDPCache* IssuerCache_GetDPCache(CRLIssuerCache* cache, const SECItem* full CRL. So we can return the global one without locking. In the future we will have a lock */ PORT_Assert(NULL == dp); - if (!cache || dp) - { + if (!cache || dp) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return NULL; } @@ -2415,9 +2216,10 @@ static CRLDPCache* IssuerCache_GetDPCache(CRLIssuerCache* cache, const SECItem* /* get a DPCache object for the given issuer subject and dp Automatically creates the cache object if it doesn't exist yet. */ -SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, - const SECItem* dp, PRTime t, void* wincx, - CRLDPCache** dpcache, PRBool* writeLocked) +SECStatus +AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, + const SECItem* dp, PRTime t, void* wincx, CRLDPCache** dpcache, + PRBool* writeLocked) { SECStatus rv = SECSuccess; CRLIssuerCache* issuercache = NULL; @@ -2425,8 +2227,7 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, PRBool globalwrite = PR_FALSE; #endif PORT_Assert(crlcache.lock); - if (!crlcache.lock) - { + if (!crlcache.lock) { /* CRL cache is not initialized */ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; @@ -2437,8 +2238,7 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, PR_Lock(crlcache.lock); #endif rv = CRLCache_GetIssuerCache(&crlcache, subject, &issuercache); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { #ifdef GLOBAL_RWLOCK NSSRWLock_UnlockRead(crlcache.lock); #else @@ -2447,28 +2247,24 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (!issuercache) - { + if (!issuercache) { /* there is no cache for this issuer yet. This means this is the first time we look up a cert from that issuer, and we need to create the cache. */ - + rv = IssuerCache_Create(&issuercache, issuer, subject, dp); - if (SECSuccess == rv && !issuercache) - { + if (SECSuccess == rv && !issuercache) { PORT_Assert(issuercache); rv = SECFailure; } - if (SECSuccess == rv) - { + if (SECSuccess == rv) { /* This is the first time we look up a cert of this issuer. Create the DPCache for this DP . */ rv = IssuerCache_AddDP(issuercache, issuer, subject, dp, dpcache); } - if (SECSuccess == rv) - { + if (SECSuccess == rv) { /* lock the DPCache for write to ensure the update happens in this thread */ *writeLocked = PR_TRUE; @@ -2478,11 +2274,10 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, PR_Lock((*dpcache)->lock); #endif } - - if (SECSuccess == rv) - { - /* now add the new issuer cache to the global hash table of - issuers */ + + if (SECSuccess == rv) { +/* now add the new issuer cache to the global hash table of + issuers */ #ifdef GLOBAL_RWLOCK CRLIssuerCache* existing = NULL; NSSRWLock_UnlockRead(crlcache.lock); @@ -2491,37 +2286,32 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, NSSRWLock_LockWrite(crlcache.lock); globalwrite = PR_TRUE; rv = CRLCache_GetIssuerCache(&crlcache, subject, &existing); - if (!existing) - { + if (!existing) { #endif rv = CRLCache_AddIssuer(issuercache); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { /* failure */ rv = SECFailure; } #ifdef GLOBAL_RWLOCK } - else - { + else { /* somebody else updated before we did */ IssuerCache_Destroy(issuercache); /* destroy the new object */ - issuercache = existing; /* use the existing one */ + issuercache = existing; /* use the existing one */ *dpcache = IssuerCache_GetDPCache(issuercache, dp); } #endif } - /* now unlock the global cache. We only want to lock the issuer hash - table addition. Holding it longer would hurt scalability */ +/* now unlock the global cache. We only want to lock the issuer hash + table addition. Holding it longer would hurt scalability */ #ifdef GLOBAL_RWLOCK - if (PR_TRUE == globalwrite) - { + if (PR_TRUE == globalwrite) { NSSRWLock_UnlockWrite(crlcache.lock); globalwrite = PR_FALSE; } - else - { + else { NSSRWLock_UnlockRead(crlcache.lock); } #else @@ -2529,10 +2319,8 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, #endif /* if there was a failure adding an issuer cache object, destroy it */ - if (SECSuccess != rv && issuercache) - { - if (PR_TRUE == *writeLocked) - { + if (SECSuccess != rv && issuercache) { + if (PR_TRUE == *writeLocked) { #ifdef DPC_RWLOCK NSSRWLock_UnlockWrite((*dpcache)->lock); #else @@ -2543,12 +2331,11 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, issuercache = NULL; } - if (SECSuccess != rv) - { + if (SECSuccess != rv) { return SECFailure; } - } else - { + } + else { #ifdef GLOBAL_RWLOCK NSSRWLock_UnlockRead(crlcache.lock); #else @@ -2558,27 +2345,23 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, } /* we now have a DPCache that we can use for lookups */ /* lock it for read, unless we already locked for write */ - if (PR_FALSE == *writeLocked) - { + if (PR_FALSE == *writeLocked) { #ifdef DPC_RWLOCK NSSRWLock_LockRead((*dpcache)->lock); #else PR_Lock((*dpcache)->lock); #endif } - - if (SECSuccess == rv) - { + + if (SECSuccess == rv) { /* currently there is always one and only one DPCache per issuer */ PORT_Assert(*dpcache); - if (*dpcache) - { + if (*dpcache) { /* make sure the DP cache is up to date before using it */ rv = DPCache_GetUpToDate(*dpcache, issuer, PR_FALSE == *writeLocked, t, wincx); } - else - { + else { rv = SECFailure; } } @@ -2586,20 +2369,18 @@ SECStatus AcquireDPCache(CERTCertificate* issuer, const SECItem* subject, } /* unlock access to the DPCache */ -void ReleaseDPCache(CRLDPCache* dpcache, PRBool writeLocked) +void +ReleaseDPCache(CRLDPCache* dpcache, PRBool writeLocked) { - if (!dpcache) - { + if (!dpcache) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return; } #ifdef DPC_RWLOCK - if (PR_TRUE == writeLocked) - { + if (PR_TRUE == writeLocked) { NSSRWLock_UnlockWrite(dpcache->lock); } - else - { + else { NSSRWLock_UnlockRead(dpcache->lock); } #else @@ -2609,9 +2390,9 @@ void ReleaseDPCache(CRLDPCache* dpcache, PRBool writeLocked) SECStatus cert_CheckCertRevocationStatus(CERTCertificate* cert, CERTCertificate* issuer, - const SECItem* dp, PRTime t, void *wincx, - CERTRevocationStatus *revStatus, - CERTCRLEntryReasonCode *revReason) + const SECItem* dp, PRTime t, void* wincx, + CERTRevocationStatus* revStatus, + CERTCRLEntryReasonCode* revReason) { PRBool lockedwrite = PR_FALSE; SECStatus rv = SECSuccess; @@ -2621,23 +2402,20 @@ cert_CheckCertRevocationStatus(CERTCertificate* cert, CERTCertificate* issuer, CERTCrlEntry* entry = NULL; dpcacheStatus ds; - if (!cert || !issuer) - { + if (!cert || !issuer) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - if (revStatus) - { + if (revStatus) { *revStatus = status; } - if (revReason) - { + if (revReason) { *revReason = reason; } - if (t && secCertTimeValid != CERT_CheckCertValidTimes(issuer, t, PR_FALSE)) - { + if (t && + secCertTimeValid != CERT_CheckCertValidTimes(issuer, t, PR_FALSE)) { /* we won't be able to check the CRL's signature if the issuer cert is expired as of the time we are verifying. This may cause a valid CRL to be cached as bad. short-circuit to avoid this case. */ @@ -2648,50 +2426,42 @@ cert_CheckCertRevocationStatus(CERTCertificate* cert, CERTCertificate* issuer, rv = AcquireDPCache(issuer, &issuer->derSubject, dp, t, wincx, &dpcache, &lockedwrite); PORT_Assert(SECSuccess == rv); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } /* now look up the certificate SN in the DP cache's CRL */ ds = DPCache_Lookup(dpcache, &cert->serialNumber, &entry); - switch (ds) - { + switch (ds) { case dpcacheFoundEntry: PORT_Assert(entry); /* check the time if we have one */ - if (entry->revocationDate.data && entry->revocationDate.len) - { + if (entry->revocationDate.data && entry->revocationDate.len) { PRTime revocationDate = 0; - if (SECSuccess == DER_DecodeTimeChoice(&revocationDate, - &entry->revocationDate)) - { + if (SECSuccess == + DER_DecodeTimeChoice(&revocationDate, + &entry->revocationDate)) { /* we got a good revocation date, only consider the certificate revoked if the time we are inquiring about is past the revocation date */ - if (t>=revocationDate) - { + if (t >= revocationDate) { rv = SECFailure; } - else - { + else { status = certRevocationStatusValid; } } - else - { + else { /* invalid revocation date, consider the certificate permanently revoked */ rv = SECFailure; } } - else - { + else { /* no revocation date, certificate is permanently revoked */ rv = SECFailure; } - if (SECFailure == rv) - { + if (SECFailure == rv) { (void)CERT_FindCRLEntryReasonExten(entry, &reason); PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE); } @@ -2718,12 +2488,10 @@ cert_CheckCertRevocationStatus(CERTCertificate* cert, CERTCertificate* issuer, } ReleaseDPCache(dpcache, lockedwrite); - if (revStatus) - { + if (revStatus) { *revStatus = status; } - if (revReason) - { + if (revReason) { *revReason = reason; } return rv; @@ -2731,31 +2499,29 @@ cert_CheckCertRevocationStatus(CERTCertificate* cert, CERTCertificate* issuer, /* check CRL revocation status of given certificate and issuer */ SECStatus -CERT_CheckCRL(CERTCertificate* cert, CERTCertificate* issuer, - const SECItem* dp, PRTime t, void* wincx) +CERT_CheckCRL(CERTCertificate* cert, CERTCertificate* issuer, const SECItem* dp, + PRTime t, void* wincx) { - return cert_CheckCertRevocationStatus(cert, issuer, dp, t, wincx, - NULL, NULL); + return cert_CheckCertRevocationStatus(cert, issuer, dp, t, wincx, NULL, + NULL); } /* retrieve full CRL object that best matches the cache status */ -CERTSignedCrl * -SEC_FindCrlByName(CERTCertDBHandle *handle, SECItem *crlKey, int type) +CERTSignedCrl* +SEC_FindCrlByName(CERTCertDBHandle* handle, SECItem* crlKey, int type) { CERTSignedCrl* acrl = NULL; CRLDPCache* dpcache = NULL; SECStatus rv = SECSuccess; PRBool writeLocked = PR_FALSE; - if (!crlKey) - { + if (!crlKey) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; } rv = AcquireDPCache(NULL, crlKey, NULL, 0, NULL, &dpcache, &writeLocked); - if (SECSuccess == rv) - { + if (SECSuccess == rv) { acrl = GetBestCRL(dpcache, PR_TRUE); /* decode entries, because SEC_FindCrlByName always returned fully decoded CRLs in the past */ ReleaseDPCache(dpcache, writeLocked); @@ -2765,24 +2531,24 @@ SEC_FindCrlByName(CERTCertDBHandle *handle, SECItem *crlKey, int type) /* invalidate the CRL cache for a given issuer, which forces a refetch of CRL objects from PKCS#11 tokens */ -void CERT_CRLCacheRefreshIssuer(CERTCertDBHandle* dbhandle, SECItem* crlKey) +void +CERT_CRLCacheRefreshIssuer(CERTCertDBHandle* dbhandle, SECItem* crlKey) { CRLDPCache* cache = NULL; SECStatus rv = SECSuccess; PRBool writeLocked = PR_FALSE; PRBool readlocked; - (void) dbhandle; /* silence compiler warnings */ + (void)dbhandle; /* silence compiler warnings */ /* XCRL we will need to refresh all the DPs of the issuer in the future, not just the default one */ rv = AcquireDPCache(NULL, crlKey, NULL, 0, NULL, &cache, &writeLocked); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { return; } /* we need to invalidate the DPCache here */ - readlocked = (writeLocked == PR_TRUE? PR_FALSE : PR_TRUE); + readlocked = (writeLocked == PR_TRUE ? PR_FALSE : PR_TRUE); DPCache_LockWrite(); cache->refresh = PR_TRUE; DPCache_UnlockWrite(); @@ -2791,7 +2557,8 @@ void CERT_CRLCacheRefreshIssuer(CERTCertDBHandle* dbhandle, SECItem* crlKey) } /* add the specified RAM CRL object to the cache */ -SECStatus CERT_CacheCRL(CERTCertDBHandle* dbhandle, SECItem* newdercrl) +SECStatus +CERT_CacheCRL(CERTCertDBHandle* dbhandle, SECItem* newdercrl) { CRLDPCache* cache = NULL; SECStatus rv = SECSuccess; @@ -2801,9 +2568,8 @@ SECStatus CERT_CacheCRL(CERTCertDBHandle* dbhandle, SECItem* newdercrl) PRBool added = PR_FALSE; CERTSignedCrl* newcrl = NULL; int realerror = 0; - - if (!dbhandle || !newdercrl) - { + + if (!dbhandle || !newdercrl) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } @@ -2811,55 +2577,49 @@ SECStatus CERT_CacheCRL(CERTCertDBHandle* dbhandle, SECItem* newdercrl) /* first decode the DER CRL to make sure it's OK */ newcrl = CERT_DecodeDERCrlWithFlags(NULL, newdercrl, SEC_CRL_TYPE, CRL_DECODE_DONT_COPY_DER | - CRL_DECODE_SKIP_ENTRIES); + CRL_DECODE_SKIP_ENTRIES); - if (!newcrl) - { + if (!newcrl) { return SECFailure; } /* XXX check if it has IDP extension. If so, do not proceed and set error */ - rv = AcquireDPCache(NULL, - &newcrl->crl.derName, - NULL, 0, NULL, &cache, &writeLocked); - if (SECSuccess == rv) - { - readlocked = (writeLocked == PR_TRUE? PR_FALSE : PR_TRUE); - + rv = AcquireDPCache(NULL, &newcrl->crl.derName, NULL, 0, NULL, &cache, + &writeLocked); + if (SECSuccess == rv) { + readlocked = (writeLocked == PR_TRUE ? PR_FALSE : PR_TRUE); + rv = CachedCrl_Create(&returned, newcrl, CRL_OriginExplicit); - if (SECSuccess == rv && returned) - { + if (SECSuccess == rv && returned) { DPCache_LockWrite(); rv = DPCache_AddCRL(cache, returned, &added); - if (PR_TRUE != added) - { + if (PR_TRUE != added) { realerror = PORT_GetError(); CachedCrl_Destroy(returned); returned = NULL; } DPCache_UnlockWrite(); } - + ReleaseDPCache(cache, writeLocked); - - if (!added) - { + + if (!added) { rv = SECFailure; } } SEC_DestroyCrl(newcrl); /* free the CRL. Either it got added to the cache and the refcount got bumped, or not, and thus we need to free its RAM */ - if (realerror) - { + if (realerror) { PORT_SetError(realerror); } return rv; } /* remove the specified RAM CRL object from the cache */ -SECStatus CERT_UncacheCRL(CERTCertDBHandle* dbhandle, SECItem* olddercrl) +SECStatus +CERT_UncacheCRL(CERTCertDBHandle* dbhandle, SECItem* olddercrl) { CRLDPCache* cache = NULL; SECStatus rv = SECSuccess; @@ -2868,9 +2628,8 @@ SECStatus CERT_UncacheCRL(CERTCertDBHandle* dbhandle, SECItem* olddercrl) PRBool removed = PR_FALSE; PRUint32 i; CERTSignedCrl* oldcrl = NULL; - - if (!dbhandle || !olddercrl) - { + + if (!dbhandle || !olddercrl) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } @@ -2878,39 +2637,32 @@ SECStatus CERT_UncacheCRL(CERTCertDBHandle* dbhandle, SECItem* olddercrl) /* first decode the DER CRL to make sure it's OK */ oldcrl = CERT_DecodeDERCrlWithFlags(NULL, olddercrl, SEC_CRL_TYPE, CRL_DECODE_DONT_COPY_DER | - CRL_DECODE_SKIP_ENTRIES); + CRL_DECODE_SKIP_ENTRIES); - if (!oldcrl) - { + if (!oldcrl) { /* if this DER CRL can't decode, it can't be in the cache */ return SECFailure; } - rv = AcquireDPCache(NULL, - &oldcrl->crl.derName, - NULL, 0, NULL, &cache, &writeLocked); - if (SECSuccess == rv) - { + rv = AcquireDPCache(NULL, &oldcrl->crl.derName, NULL, 0, NULL, &cache, + &writeLocked); + if (SECSuccess == rv) { CachedCrl* returned = NULL; - readlocked = (writeLocked == PR_TRUE? PR_FALSE : PR_TRUE); - + readlocked = (writeLocked == PR_TRUE ? PR_FALSE : PR_TRUE); + rv = CachedCrl_Create(&returned, oldcrl, CRL_OriginExplicit); - if (SECSuccess == rv && returned) - { + if (SECSuccess == rv && returned) { DPCache_LockWrite(); - for (i=0;incrls;i++) - { + for (i = 0; i < cache->ncrls; i++) { PRBool dupe = PR_FALSE, updated = PR_FALSE; - rv = CachedCrl_Compare(returned, cache->crls[i], - &dupe, &updated); - if (SECSuccess != rv) - { + rv = CachedCrl_Compare(returned, cache->crls[i], &dupe, + &updated); + if (SECSuccess != rv) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); break; } - if (PR_TRUE == dupe) - { + if (PR_TRUE == dupe) { rv = DPCache_RemoveCRL(cache, i); /* got a match */ if (SECSuccess == rv) { cache->mustchoose = PR_TRUE; @@ -2919,32 +2671,31 @@ SECStatus CERT_UncacheCRL(CERTCertDBHandle* dbhandle, SECItem* olddercrl) break; } } - + DPCache_UnlockWrite(); - if (SECSuccess != CachedCrl_Destroy(returned) ) { + if (SECSuccess != CachedCrl_Destroy(returned)) { rv = SECFailure; } } ReleaseDPCache(cache, writeLocked); } - if (SECSuccess != SEC_DestroyCrl(oldcrl) ) { + if (SECSuccess != SEC_DestroyCrl(oldcrl)) { /* need to do this because object is refcounted */ rv = SECFailure; } - if (SECSuccess == rv && PR_TRUE != removed) - { + if (SECSuccess == rv && PR_TRUE != removed) { PORT_SetError(SEC_ERROR_CRL_NOT_FOUND); } return rv; } -SECStatus cert_AcquireNamedCRLCache(NamedCRLCache** returned) +SECStatus +cert_AcquireNamedCRLCache(NamedCRLCache** returned) { PORT_Assert(returned); - if (!namedCRLCache.lock) - { + if (!namedCRLCache.lock) { PORT_Assert(0); return SECFailure; } @@ -2956,28 +2707,26 @@ SECStatus cert_AcquireNamedCRLCache(NamedCRLCache** returned) /* This must be called only while cache is acquired, and the entry is only * valid until cache is released. */ -SECStatus cert_FindCRLByGeneralName(NamedCRLCache* ncc, - const SECItem* canonicalizedName, - NamedCRLCacheEntry** retEntry) +SECStatus +cert_FindCRLByGeneralName(NamedCRLCache* ncc, const SECItem* canonicalizedName, + NamedCRLCacheEntry** retEntry) { - if (!ncc || !canonicalizedName || !retEntry) - { + if (!ncc || !canonicalizedName || !retEntry) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - *retEntry = (NamedCRLCacheEntry*) PL_HashTableLookup(namedCRLCache.entries, - (void*) canonicalizedName); + *retEntry = (NamedCRLCacheEntry*)PL_HashTableLookup( + namedCRLCache.entries, (void*)canonicalizedName); return SECSuccess; } -SECStatus cert_ReleaseNamedCRLCache(NamedCRLCache* ncc) +SECStatus +cert_ReleaseNamedCRLCache(NamedCRLCache* ncc) { - if (!ncc) - { + if (!ncc) { return SECFailure; } - if (!ncc->lock) - { + if (!ncc->lock) { PORT_Assert(0); return SECFailure; } @@ -2986,16 +2735,15 @@ SECStatus cert_ReleaseNamedCRLCache(NamedCRLCache* ncc) } /* creates new named cache entry from CRL, and tries to add it to CRL cache */ -static SECStatus addCRLToCache(CERTCertDBHandle* dbhandle, SECItem* crl, - const SECItem* canonicalizedName, - NamedCRLCacheEntry** newEntry) +static SECStatus +addCRLToCache(CERTCertDBHandle* dbhandle, SECItem* crl, + const SECItem* canonicalizedName, NamedCRLCacheEntry** newEntry) { SECStatus rv = SECSuccess; NamedCRLCacheEntry* entry = NULL; /* create new named entry */ - if (SECSuccess != NamedCRLCacheEntry_Create(newEntry) || !*newEntry) - { + if (SECSuccess != NamedCRLCacheEntry_Create(newEntry) || !*newEntry) { /* no need to keep unused CRL around */ SECITEM_ZfreeItem(crl, PR_TRUE); return SECFailure; @@ -3004,22 +2752,18 @@ static SECStatus addCRLToCache(CERTCertDBHandle* dbhandle, SECItem* crl, entry->crl = crl; /* named CRL cache owns DER */ entry->lastAttemptTime = PR_Now(); entry->canonicalizedName = SECITEM_DupItem(canonicalizedName); - if (!entry->canonicalizedName) - { + if (!entry->canonicalizedName) { rv = NamedCRLCacheEntry_Destroy(entry); /* destroys CRL too */ PORT_Assert(SECSuccess == rv); return SECFailure; } /* now, attempt to insert CRL into CRL cache */ - if (SECSuccess == CERT_CacheCRL(dbhandle, entry->crl)) - { + if (SECSuccess == CERT_CacheCRL(dbhandle, entry->crl)) { entry->inCRLCache = PR_TRUE; entry->successfulInsertionTime = entry->lastAttemptTime; } - else - { - switch (PR_GetError()) - { + else { + switch (PR_GetError()) { case SEC_ERROR_CRL_ALREADY_EXISTS: entry->dupe = PR_TRUE; break; @@ -3044,18 +2788,18 @@ static SECStatus addCRLToCache(CERTCertDBHandle* dbhandle, SECItem* crl, /* take ownership of CRL, and insert it into the named CRL cache * and indexed CRL cache */ -SECStatus cert_CacheCRLByGeneralName(CERTCertDBHandle* dbhandle, SECItem* crl, - const SECItem* canonicalizedName) +SECStatus +cert_CacheCRLByGeneralName(CERTCertDBHandle* dbhandle, SECItem* crl, + const SECItem* canonicalizedName) { - NamedCRLCacheEntry* oldEntry, * newEntry = NULL; + NamedCRLCacheEntry *oldEntry, *newEntry = NULL; NamedCRLCache* ncc = NULL; SECStatus rv = SECSuccess; PORT_Assert(namedCRLCache.lock); PORT_Assert(namedCRLCache.entries); - if (!crl || !canonicalizedName) - { + if (!crl || !canonicalizedName) { PORT_Assert(0); PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; @@ -3063,106 +2807,90 @@ SECStatus cert_CacheCRLByGeneralName(CERTCertDBHandle* dbhandle, SECItem* crl, rv = cert_AcquireNamedCRLCache(&ncc); PORT_Assert(SECSuccess == rv); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { SECITEM_ZfreeItem(crl, PR_TRUE); return SECFailure; } rv = cert_FindCRLByGeneralName(ncc, canonicalizedName, &oldEntry); PORT_Assert(SECSuccess == rv); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { rv = cert_ReleaseNamedCRLCache(ncc); SECITEM_ZfreeItem(crl, PR_TRUE); return SECFailure; } - if (SECSuccess == addCRLToCache(dbhandle, crl, canonicalizedName, - &newEntry) ) - { - if (!oldEntry) - { + if (SECSuccess == + addCRLToCache(dbhandle, crl, canonicalizedName, &newEntry)) { + if (!oldEntry) { /* add new good entry to the hash table */ if (NULL == PL_HashTableAdd(namedCRLCache.entries, - (void*) newEntry->canonicalizedName, - (void*) newEntry)) - { + (void*)newEntry->canonicalizedName, + (void*)newEntry)) { PORT_Assert(0); NamedCRLCacheEntry_Destroy(newEntry); rv = SECFailure; } } - else - { + else { PRBool removed; /* remove the old CRL from the cache if needed */ - if (oldEntry->inCRLCache) - { + if (oldEntry->inCRLCache) { rv = CERT_UncacheCRL(dbhandle, oldEntry->crl); PORT_Assert(SECSuccess == rv); } removed = PL_HashTableRemove(namedCRLCache.entries, - (void*) oldEntry->canonicalizedName); + (void*)oldEntry->canonicalizedName); PORT_Assert(removed); - if (!removed) - { + if (!removed) { rv = SECFailure; - /* leak old entry since we couldn't remove it from the hash table */ + /* leak old entry since we couldn't remove it from the hash + * table */ } - else - { + else { PORT_CheckSuccess(NamedCRLCacheEntry_Destroy(oldEntry)); } if (NULL == PL_HashTableAdd(namedCRLCache.entries, - (void*) newEntry->canonicalizedName, - (void*) newEntry)) - { + (void*)newEntry->canonicalizedName, + (void*)newEntry)) { PORT_Assert(0); rv = SECFailure; } } - } else - { + } + else { /* error adding new CRL to cache */ - if (!oldEntry) - { + if (!oldEntry) { /* no old cache entry, use the new one even though it's bad */ if (NULL == PL_HashTableAdd(namedCRLCache.entries, - (void*) newEntry->canonicalizedName, - (void*) newEntry)) - { + (void*)newEntry->canonicalizedName, + (void*)newEntry)) { PORT_Assert(0); rv = SECFailure; } } - else - { - if (oldEntry->inCRLCache) - { + else { + if (oldEntry->inCRLCache) { /* previous cache entry was good, keep it and update time */ - oldEntry-> lastAttemptTime = newEntry->lastAttemptTime; + oldEntry->lastAttemptTime = newEntry->lastAttemptTime; /* throw away new bad entry */ rv = NamedCRLCacheEntry_Destroy(newEntry); PORT_Assert(SECSuccess == rv); } - else - { + else { /* previous cache entry was bad, just replace it */ - PRBool removed = PL_HashTableRemove(namedCRLCache.entries, - (void*) oldEntry->canonicalizedName); + PRBool removed = PL_HashTableRemove( + namedCRLCache.entries, (void*)oldEntry->canonicalizedName); PORT_Assert(removed); - if (!removed) - { - /* leak old entry since we couldn't remove it from the hash table */ + if (!removed) { + /* leak old entry since we couldn't remove it from the hash + * table */ rv = SECFailure; } - else - { + else { PORT_CheckSuccess(NamedCRLCacheEntry_Destroy(oldEntry)); } if (NULL == PL_HashTableAdd(namedCRLCache.entries, - (void*) newEntry->canonicalizedName, - (void*) newEntry)) - { + (void*)newEntry->canonicalizedName, + (void*)newEntry)) { PORT_Assert(0); rv = SECFailure; } @@ -3174,18 +2902,16 @@ SECStatus cert_CacheCRLByGeneralName(CERTCertDBHandle* dbhandle, SECItem* crl, return rv; } -static SECStatus CachedCrl_Create(CachedCrl** returned, CERTSignedCrl* crl, - CRLOrigin origin) +static SECStatus +CachedCrl_Create(CachedCrl** returned, CERTSignedCrl* crl, CRLOrigin origin) { CachedCrl* newcrl = NULL; - if (!returned) - { + if (!returned) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } newcrl = PORT_ZAlloc(sizeof(CachedCrl)); - if (!newcrl) - { + if (!newcrl) { return SECFailure; } newcrl->crl = SEC_DupCrl(crl); @@ -3195,33 +2921,31 @@ static SECStatus CachedCrl_Create(CachedCrl** returned, CERTSignedCrl* crl, } /* empty the cache content */ -static SECStatus CachedCrl_Depopulate(CachedCrl* crl) +static SECStatus +CachedCrl_Depopulate(CachedCrl* crl) { - if (!crl) - { + if (!crl) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - /* destroy the hash table */ - if (crl->entries) - { + /* destroy the hash table */ + if (crl->entries) { PL_HashTableDestroy(crl->entries); crl->entries = NULL; } /* free the pre buffer */ - if (crl->prebuffer) - { + if (crl->prebuffer) { PreAllocator_Destroy(crl->prebuffer); crl->prebuffer = NULL; } return SECSuccess; } -static SECStatus CachedCrl_Destroy(CachedCrl* crl) +static SECStatus +CachedCrl_Destroy(CachedCrl* crl) { - if (!crl) - { + if (!crl) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } @@ -3232,56 +2956,52 @@ static SECStatus CachedCrl_Destroy(CachedCrl* crl) } /* create hash table of CRL entries */ -static SECStatus CachedCrl_Populate(CachedCrl* crlobject) +static SECStatus +CachedCrl_Populate(CachedCrl* crlobject) { SECStatus rv = SECFailure; CERTCrlEntry** crlEntry = NULL; PRUint32 numEntries = 0; - if (!crlobject) - { + if (!crlobject) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } /* complete the entry decoding . XXX thread-safety of CRL object */ rv = CERT_CompleteCRLDecodeEntries(crlobject->crl); - if (SECSuccess != rv) - { + if (SECSuccess != rv) { crlobject->unbuildable = PR_TRUE; /* don't try to build this again */ return SECFailure; } - if (crlobject->entries && crlobject->prebuffer) - { + if (crlobject->entries && crlobject->prebuffer) { /* cache is already built */ return SECSuccess; } - /* build the hash table from the full CRL */ + /* build the hash table from the full CRL */ /* count CRL entries so we can pre-allocate space for hash table entries */ for (crlEntry = crlobject->crl->crl.entries; crlEntry && *crlEntry; - crlEntry++) - { + crlEntry++) { numEntries++; } - crlobject->prebuffer = PreAllocator_Create(numEntries*sizeof(PLHashEntry)); + crlobject->prebuffer = + PreAllocator_Create(numEntries * sizeof(PLHashEntry)); PORT_Assert(crlobject->prebuffer); - if (!crlobject->prebuffer) - { + if (!crlobject->prebuffer) { return SECFailure; } /* create a new hash table */ - crlobject->entries = PL_NewHashTable(0, SECITEM_Hash, SECITEM_HashCompare, - PL_CompareValues, &preAllocOps, crlobject->prebuffer); + crlobject->entries = + PL_NewHashTable(0, SECITEM_Hash, SECITEM_HashCompare, PL_CompareValues, + &preAllocOps, crlobject->prebuffer); PORT_Assert(crlobject->entries); - if (!crlobject->entries) - { + if (!crlobject->entries) { return SECFailure; } /* add all serial numbers to the hash table */ for (crlEntry = crlobject->crl->crl.entries; crlEntry && *crlEntry; - crlEntry++) - { + crlEntry++) { PL_HashTableAdd(crlobject->entries, &(*crlEntry)->serialNumber, *crlEntry); } @@ -3290,14 +3010,13 @@ static SECStatus CachedCrl_Populate(CachedCrl* crlobject) } /* returns true if there are CRLs from PKCS#11 slots */ -static PRBool DPCache_HasTokenCRLs(CRLDPCache* cache) +static PRBool +DPCache_HasTokenCRLs(CRLDPCache* cache) { PRBool answer = PR_FALSE; PRUint32 i; - for (i=0;incrls;i++) - { - if (cache->crls[i] && (CRL_OriginToken == cache->crls[i]->origin) ) - { + for (i = 0; i < cache->ncrls; i++) { + if (cache->crls[i] && (CRL_OriginToken == cache->crls[i]->origin)) { answer = PR_TRUE; break; } @@ -3310,63 +3029,54 @@ static PRBool DPCache_HasTokenCRLs(CRLDPCache* cache) This can happen if the DER CRL got updated in the token, but the PKCS#11 object ID did not change. NSS softoken has the unfortunate property to never change the object ID for CRL objects. */ -static SECStatus CachedCrl_Compare(CachedCrl* a, CachedCrl* b, PRBool* isDupe, - PRBool* isUpdated) +static SECStatus +CachedCrl_Compare(CachedCrl* a, CachedCrl* b, PRBool* isDupe, PRBool* isUpdated) { PORT_Assert(a); PORT_Assert(b); PORT_Assert(isDupe); PORT_Assert(isUpdated); - if (!a || !b || !isDupe || !isUpdated || !a->crl || !b->crl) - { + if (!a || !b || !isDupe || !isUpdated || !a->crl || !b->crl) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } *isDupe = *isUpdated = PR_FALSE; - if (a == b) - { + if (a == b) { /* dupe */ *isDupe = PR_TRUE; *isUpdated = PR_FALSE; return SECSuccess; } - if (b->origin != a->origin) - { + if (b->origin != a->origin) { /* CRLs of different origins are not considered dupes, and can't be updated either */ return SECSuccess; } - if (CRL_OriginToken == b->origin) - { + if (CRL_OriginToken == b->origin) { /* for token CRLs, slot and PKCS#11 object handle must match for CRL to truly be a dupe */ - if ( (b->crl->slot == a->crl->slot) && - (b->crl->pkcs11ID == a->crl->pkcs11ID) ) - { + if ((b->crl->slot == a->crl->slot) && + (b->crl->pkcs11ID == a->crl->pkcs11ID)) { /* ASN.1 DER needs to match for dupe check */ /* could optimize by just checking a few fields like thisUpdate */ - if ( SECEqual == SECITEM_CompareItem(b->crl->derCrl, - a->crl->derCrl) ) - { + if (SECEqual == + SECITEM_CompareItem(b->crl->derCrl, a->crl->derCrl)) { *isDupe = PR_TRUE; } - else - { + else { *isUpdated = PR_TRUE; } } return SECSuccess; } - if (CRL_OriginExplicit == b->origin) - { + if (CRL_OriginExplicit == b->origin) { /* We need to make sure this is the same object that the user provided to CERT_CacheCRL previously. That API takes a SECItem*, thus, we just do a pointer comparison here. */ - if (b->crl->derCrl == a->crl->derCrl) - { + if (b->crl->derCrl == a->crl->derCrl) { *isDupe = PR_TRUE; } } diff --git a/security/nss/lib/certdb/genname.c b/security/nss/lib/certdb/genname.c index 6529a6a097a0..8e679415ed63 100644 --- a/security/nss/lib/certdb/genname.c +++ b/security/nss/lib/certdb/genname.c @@ -26,13 +26,11 @@ SEC_ASN1_MKSUB(SEC_OctetStringTemplate) static const SEC_ASN1Template CERTNameConstraintTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTNameConstraint) }, { SEC_ASN1_ANY, offsetof(CERTNameConstraint, DERName) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(CERTNameConstraint, min), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, - offsetof(CERTNameConstraint, max), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, - { 0, } + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(CERTNameConstraint, min), SEC_ASN1_SUB(SEC_IntegerTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, + offsetof(CERTNameConstraint, max), SEC_ASN1_SUB(SEC_IntegerTemplate) }, + { 0 } }; const SEC_ASN1Template CERT_NameConstraintSubtreeSubTemplate[] = { @@ -41,119 +39,108 @@ const SEC_ASN1Template CERT_NameConstraintSubtreeSubTemplate[] = { static const SEC_ASN1Template CERTNameConstraintsTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTNameConstraints) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(CERTNameConstraints, DERPermited), - CERT_NameConstraintSubtreeSubTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(CERTNameConstraints, DERExcluded), - CERT_NameConstraintSubtreeSubTemplate}, - { 0, } + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(CERTNameConstraints, DERPermited), + CERT_NameConstraintSubtreeSubTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(CERTNameConstraints, DERExcluded), + CERT_NameConstraintSubtreeSubTemplate }, + { 0 } }; - static const SEC_ASN1Template CERTOthNameTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(OtherName) }, - { SEC_ASN1_OBJECT_ID, - offsetof(OtherName, oid) }, + { SEC_ASN1_OBJECT_ID, offsetof(OtherName, oid) }, { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | - SEC_ASN1_XTRN | 0, offsetof(OtherName, name), - SEC_ASN1_SUB(SEC_AnyTemplate) }, - { 0, } + SEC_ASN1_XTRN | 0, + offsetof(OtherName, name), SEC_ASN1_SUB(SEC_AnyTemplate) }, + { 0 } }; static const SEC_ASN1Template CERTOtherNameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0 , - offsetof(CERTGeneralName, name.OthName), CERTOthNameTemplate, + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0, + offsetof(CERTGeneralName, name.OthName), CERTOthNameTemplate, sizeof(CERTGeneralName) } }; static const SEC_ASN1Template CERT_RFC822NameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1 , - offsetof(CERTGeneralName, name.other), - SEC_ASN1_SUB(SEC_IA5StringTemplate), - sizeof (CERTGeneralName)} + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, + offsetof(CERTGeneralName, name.other), + SEC_ASN1_SUB(SEC_IA5StringTemplate), sizeof(CERTGeneralName) } }; static const SEC_ASN1Template CERT_DNSNameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2 , - offsetof(CERTGeneralName, name.other), - SEC_ASN1_SUB(SEC_IA5StringTemplate), - sizeof (CERTGeneralName)} + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, + offsetof(CERTGeneralName, name.other), + SEC_ASN1_SUB(SEC_IA5StringTemplate), sizeof(CERTGeneralName) } }; static const SEC_ASN1Template CERT_X400AddressTemplate[] = { { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | SEC_ASN1_XTRN | 3, - offsetof(CERTGeneralName, name.other), SEC_ASN1_SUB(SEC_AnyTemplate), - sizeof (CERTGeneralName)} + offsetof(CERTGeneralName, name.other), SEC_ASN1_SUB(SEC_AnyTemplate), + sizeof(CERTGeneralName) } }; static const SEC_ASN1Template CERT_DirectoryNameTemplate[] = { { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | - SEC_ASN1_XTRN | 4, offsetof(CERTGeneralName, derDirectoryName), - SEC_ASN1_SUB(SEC_AnyTemplate), sizeof (CERTGeneralName)} + SEC_ASN1_XTRN | 4, + offsetof(CERTGeneralName, derDirectoryName), + SEC_ASN1_SUB(SEC_AnyTemplate), sizeof(CERTGeneralName) } }; - static const SEC_ASN1Template CERT_EDIPartyNameTemplate[] = { { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | SEC_ASN1_XTRN | 5, - offsetof(CERTGeneralName, name.other), SEC_ASN1_SUB(SEC_AnyTemplate), - sizeof (CERTGeneralName)} + offsetof(CERTGeneralName, name.other), SEC_ASN1_SUB(SEC_AnyTemplate), + sizeof(CERTGeneralName) } }; static const SEC_ASN1Template CERT_URITemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 6 , - offsetof(CERTGeneralName, name.other), - SEC_ASN1_SUB(SEC_IA5StringTemplate), - sizeof (CERTGeneralName)} + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 6, + offsetof(CERTGeneralName, name.other), + SEC_ASN1_SUB(SEC_IA5StringTemplate), sizeof(CERTGeneralName) } }; static const SEC_ASN1Template CERT_IPAddressTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 7 , - offsetof(CERTGeneralName, name.other), - SEC_ASN1_SUB(SEC_OctetStringTemplate), - sizeof (CERTGeneralName)} + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 7, + offsetof(CERTGeneralName, name.other), + SEC_ASN1_SUB(SEC_OctetStringTemplate), sizeof(CERTGeneralName) } }; static const SEC_ASN1Template CERT_RegisteredIDTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 8 , - offsetof(CERTGeneralName, name.other), - SEC_ASN1_SUB(SEC_ObjectIDTemplate), - sizeof (CERTGeneralName)} + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 8, + offsetof(CERTGeneralName, name.other), SEC_ASN1_SUB(SEC_ObjectIDTemplate), + sizeof(CERTGeneralName) } }; - const SEC_ASN1Template CERT_GeneralNamesTemplate[] = { - { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN , 0, SEC_ASN1_SUB(SEC_AnyTemplate) } + { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN, 0, SEC_ASN1_SUB(SEC_AnyTemplate) } }; - static struct { CERTGeneralNameType type; char *name; -} typesArray[] = { - { certOtherName, "other" }, - { certRFC822Name, "email" }, - { certRFC822Name, "rfc822" }, - { certDNSName, "dns" }, - { certX400Address, "x400" }, - { certX400Address, "x400addr" }, - { certDirectoryName, "directory" }, - { certDirectoryName, "dn" }, - { certEDIPartyName, "edi" }, - { certEDIPartyName, "ediparty" }, - { certURI, "uri" }, - { certIPAddress, "ip" }, - { certIPAddress, "ipaddr" }, - { certRegisterID, "registerid" } -}; +} typesArray[] = { { certOtherName, "other" }, + { certRFC822Name, "email" }, + { certRFC822Name, "rfc822" }, + { certDNSName, "dns" }, + { certX400Address, "x400" }, + { certX400Address, "x400addr" }, + { certDirectoryName, "directory" }, + { certDirectoryName, "dn" }, + { certEDIPartyName, "edi" }, + { certEDIPartyName, "ediparty" }, + { certURI, "uri" }, + { certIPAddress, "ip" }, + { certIPAddress, "ipaddr" }, + { certRegisterID, "registerid" } }; CERTGeneralNameType CERT_GetGeneralNameTypeFromString(const char *string) { - int types_count = sizeof(typesArray)/sizeof(typesArray[0]); + int types_count = sizeof(typesArray) / sizeof(typesArray[0]); int i; - for (i=0; i < types_count; i++) { + for (i = 0; i < types_count; i++) { if (PORT_Strcasecmp(string, typesArray[i].name) == 0) { return typesArray[i].type; } @@ -164,12 +151,11 @@ CERT_GetGeneralNameTypeFromString(const char *string) CERTGeneralName * CERT_NewGeneralName(PLArenaPool *arena, CERTGeneralNameType type) { - CERTGeneralName *name = arena - ? PORT_ArenaZNew(arena, CERTGeneralName) - : PORT_ZNew(CERTGeneralName); + CERTGeneralName *name = arena ? PORT_ArenaZNew(arena, CERTGeneralName) + : PORT_ZNew(CERTGeneralName); if (name) { - name->type = type; - name->l.prev = name->l.next = &name->l; + name->type = type; + name->l.prev = name->l.next = &name->l; } return name; } @@ -179,9 +165,8 @@ CERT_NewGeneralName(PLArenaPool *arena, CERTGeneralNameType type) ** This function does not change the destinate's GeneralName's list linkage. */ SECStatus -cert_CopyOneGeneralName(PLArenaPool *arena, - CERTGeneralName *dest, - CERTGeneralName *src) +cert_CopyOneGeneralName(PLArenaPool *arena, CERTGeneralName *dest, + CERTGeneralName *src) { SECStatus rv; void *mark = NULL; @@ -192,80 +177,80 @@ cert_CopyOneGeneralName(PLArenaPool *arena, mark = PORT_ArenaMark(arena); switch (src->type) { - case certDirectoryName: - rv = SECITEM_CopyItem(arena, &dest->derDirectoryName, - &src->derDirectoryName); - if (rv == SECSuccess) - rv = CERT_CopyName(arena, &dest->name.directoryName, - &src->name.directoryName); - break; + case certDirectoryName: + rv = SECITEM_CopyItem(arena, &dest->derDirectoryName, + &src->derDirectoryName); + if (rv == SECSuccess) + rv = CERT_CopyName(arena, &dest->name.directoryName, + &src->name.directoryName); + break; - case certOtherName: - rv = SECITEM_CopyItem(arena, &dest->name.OthName.name, - &src->name.OthName.name); - if (rv == SECSuccess) - rv = SECITEM_CopyItem(arena, &dest->name.OthName.oid, - &src->name.OthName.oid); - break; - - default: - rv = SECITEM_CopyItem(arena, &dest->name.other, - &src->name.other); - break; + case certOtherName: + rv = SECITEM_CopyItem(arena, &dest->name.OthName.name, + &src->name.OthName.name); + if (rv == SECSuccess) + rv = SECITEM_CopyItem(arena, &dest->name.OthName.oid, + &src->name.OthName.oid); + break; + default: + rv = SECITEM_CopyItem(arena, &dest->name.other, &src->name.other); + break; } if (rv != SECSuccess) { PORT_ArenaRelease(arena, mark); - } else { + } + else { PORT_ArenaUnmark(arena, mark); } return rv; } - void CERT_DestroyGeneralNameList(CERTGeneralNameList *list) { PZLock *lock; if (list != NULL) { - lock = list->lock; - PZ_Lock(lock); - if (--list->refCount <= 0 && list->arena != NULL) { - PORT_FreeArena(list->arena, PR_FALSE); - PZ_Unlock(lock); - PZ_DestroyLock(lock); - } else { - PZ_Unlock(lock); - } + lock = list->lock; + PZ_Lock(lock); + if (--list->refCount <= 0 && list->arena != NULL) { + PORT_FreeArena(list->arena, PR_FALSE); + PZ_Unlock(lock); + PZ_DestroyLock(lock); + } + else { + PZ_Unlock(lock); + } } return; } CERTGeneralNameList * -CERT_CreateGeneralNameList(CERTGeneralName *name) { +CERT_CreateGeneralNameList(CERTGeneralName *name) +{ PLArenaPool *arena; CERTGeneralNameList *list = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - goto done; + goto done; } list = PORT_ArenaZNew(arena, CERTGeneralNameList); if (!list) - goto loser; + goto loser; if (name != NULL) { - SECStatus rv; - list->name = CERT_NewGeneralName(arena, (CERTGeneralNameType)0); - if (!list->name) - goto loser; - rv = CERT_CopyGeneralName(arena, list->name, name); - if (rv != SECSuccess) - goto loser; + SECStatus rv; + list->name = CERT_NewGeneralName(arena, (CERTGeneralNameType)0); + if (!list->name) + goto loser; + rv = CERT_CopyGeneralName(arena, list->name, name); + if (rv != SECSuccess) + goto loser; } list->lock = PZ_NewLock(nssILockList); if (!list->lock) - goto loser; + goto loser; list->arena = arena; list->refCount = 1; done: @@ -280,9 +265,9 @@ CERTGeneralName * CERT_GetNextGeneralName(CERTGeneralName *current) { PRCList *next; - + next = current->l.next; - return (CERTGeneralName *) (((char *) next) - offsetof(CERTGeneralName, l)); + return (CERTGeneralName *)(((char *)next) - offsetof(CERTGeneralName, l)); } CERTGeneralName * @@ -290,16 +275,17 @@ CERT_GetPrevGeneralName(CERTGeneralName *current) { PRCList *prev; prev = current->l.prev; - return (CERTGeneralName *) (((char *) prev) - offsetof(CERTGeneralName, l)); + return (CERTGeneralName *)(((char *)prev) - offsetof(CERTGeneralName, l)); } CERTNameConstraint * CERT_GetNextNameConstraint(CERTNameConstraint *current) { PRCList *next; - + next = current->l.next; - return (CERTNameConstraint *) (((char *) next) - offsetof(CERTNameConstraint, l)); + return (CERTNameConstraint *)(((char *)next) - + offsetof(CERTNameConstraint, l)); } CERTNameConstraint * @@ -307,58 +293,78 @@ CERT_GetPrevNameConstraint(CERTNameConstraint *current) { PRCList *prev; prev = current->l.prev; - return (CERTNameConstraint *) (((char *) prev) - offsetof(CERTNameConstraint, l)); + return (CERTNameConstraint *)(((char *)prev) - + offsetof(CERTNameConstraint, l)); } SECItem * -CERT_EncodeGeneralName(CERTGeneralName *genName, SECItem *dest, PLArenaPool *arena) +CERT_EncodeGeneralName(CERTGeneralName *genName, SECItem *dest, + PLArenaPool *arena) { - const SEC_ASN1Template * template; + const SEC_ASN1Template *template; PORT_Assert(arena); if (arena == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } /* TODO: mark arena */ if (dest == NULL) { - dest = PORT_ArenaZNew(arena, SECItem); - if (!dest) - goto loser; + dest = PORT_ArenaZNew(arena, SECItem); + if (!dest) + goto loser; } if (genName->type == certDirectoryName) { - if (genName->derDirectoryName.data == NULL) { - /* The field hasn't been encoded yet. */ - SECItem * pre_dest = - SEC_ASN1EncodeItem (arena, &(genName->derDirectoryName), - &(genName->name.directoryName), - CERT_NameTemplate); + if (genName->derDirectoryName.data == NULL) { + /* The field hasn't been encoded yet. */ + SECItem *pre_dest = SEC_ASN1EncodeItem( + arena, &(genName->derDirectoryName), + &(genName->name.directoryName), CERT_NameTemplate); if (!pre_dest) goto loser; - } - if (genName->derDirectoryName.data == NULL) { - goto loser; - } + } + if (genName->derDirectoryName.data == NULL) { + goto loser; + } } switch (genName->type) { - case certURI: template = CERT_URITemplate; break; - case certRFC822Name: template = CERT_RFC822NameTemplate; break; - case certDNSName: template = CERT_DNSNameTemplate; break; - case certIPAddress: template = CERT_IPAddressTemplate; break; - case certOtherName: template = CERTOtherNameTemplate; break; - case certRegisterID: template = CERT_RegisteredIDTemplate; break; - /* for this type, we expect the value is already encoded */ - case certEDIPartyName: template = CERT_EDIPartyNameTemplate; break; - /* for this type, we expect the value is already encoded */ - case certX400Address: template = CERT_X400AddressTemplate; break; - case certDirectoryName: template = CERT_DirectoryNameTemplate; break; - default: - PORT_Assert(0); goto loser; + case certURI: + template = CERT_URITemplate; + break; + case certRFC822Name: + template = CERT_RFC822NameTemplate; + break; + case certDNSName: + template = CERT_DNSNameTemplate; + break; + case certIPAddress: + template = CERT_IPAddressTemplate; + break; + case certOtherName: + template = CERTOtherNameTemplate; + break; + case certRegisterID: + template = CERT_RegisteredIDTemplate; + break; + /* for this type, we expect the value is already encoded */ + case certEDIPartyName: + template = CERT_EDIPartyNameTemplate; + break; + /* for this type, we expect the value is already encoded */ + case certX400Address: + template = CERT_X400AddressTemplate; + break; + case certDirectoryName: + template = CERT_DirectoryNameTemplate; + break; + default: + PORT_Assert(0); + goto loser; } dest = SEC_ASN1EncodeItem(arena, dest, genName, template); if (!dest) { - goto loser; + goto loser; } /* TODO: unmark arena */ return dest; @@ -370,34 +376,34 @@ loser: SECItem ** cert_EncodeGeneralNames(PLArenaPool *arena, CERTGeneralName *names) { - CERTGeneralName *current_name; - SECItem **items = NULL; - int count = 0; - int i; - PRCList *head; + CERTGeneralName *current_name; + SECItem **items = NULL; + int count = 0; + int i; + PRCList *head; PORT_Assert(arena); /* TODO: mark arena */ current_name = names; if (names != NULL) { - count = 1; + count = 1; } head = &(names->l); while (current_name->l.next != head) { - current_name = CERT_GetNextGeneralName(current_name); - ++count; + current_name = CERT_GetNextGeneralName(current_name); + ++count; } current_name = CERT_GetNextGeneralName(current_name); items = PORT_ArenaNewArray(arena, SECItem *, count + 1); if (items == NULL) { - goto loser; + goto loser; } for (i = 0; i < count; i++) { - items[i] = CERT_EncodeGeneralName(current_name, (SECItem *)NULL, arena); - if (items[i] == NULL) { - goto loser; - } - current_name = CERT_GetNextGeneralName(current_name); + items[i] = CERT_EncodeGeneralName(current_name, (SECItem *)NULL, arena); + if (items[i] == NULL) { + goto loser; + } + current_name = CERT_GetNextGeneralName(current_name); } items[i] = NULL; /* TODO: unmark arena */ @@ -408,14 +414,13 @@ loser: } CERTGeneralName * -CERT_DecodeGeneralName(PLArenaPool *reqArena, - SECItem *encodedName, - CERTGeneralName *genName) +CERT_DecodeGeneralName(PLArenaPool *reqArena, SECItem *encodedName, + CERTGeneralName *genName) { - const SEC_ASN1Template * template; - CERTGeneralNameType genNameType; - SECStatus rv = SECSuccess; - SECItem* newEncodedName; + const SEC_ASN1Template *template; + CERTGeneralNameType genNameType; + SECStatus rv = SECSuccess; + SECItem *newEncodedName; if (!reqArena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -430,36 +435,55 @@ CERT_DecodeGeneralName(PLArenaPool *reqArena, /* TODO: mark arena */ genNameType = (CERTGeneralNameType)((*(newEncodedName->data) & 0x0f) + 1); if (genName == NULL) { - genName = CERT_NewGeneralName(reqArena, genNameType); - if (!genName) - goto loser; - } else { - genName->type = genNameType; - genName->l.prev = genName->l.next = &genName->l; + genName = CERT_NewGeneralName(reqArena, genNameType); + if (!genName) + goto loser; + } + else { + genName->type = genNameType; + genName->l.prev = genName->l.next = &genName->l; } switch (genNameType) { - case certURI: template = CERT_URITemplate; break; - case certRFC822Name: template = CERT_RFC822NameTemplate; break; - case certDNSName: template = CERT_DNSNameTemplate; break; - case certIPAddress: template = CERT_IPAddressTemplate; break; - case certOtherName: template = CERTOtherNameTemplate; break; - case certRegisterID: template = CERT_RegisteredIDTemplate; break; - case certEDIPartyName: template = CERT_EDIPartyNameTemplate; break; - case certX400Address: template = CERT_X400AddressTemplate; break; - case certDirectoryName: template = CERT_DirectoryNameTemplate; break; - default: - goto loser; + case certURI: + template = CERT_URITemplate; + break; + case certRFC822Name: + template = CERT_RFC822NameTemplate; + break; + case certDNSName: + template = CERT_DNSNameTemplate; + break; + case certIPAddress: + template = CERT_IPAddressTemplate; + break; + case certOtherName: + template = CERTOtherNameTemplate; + break; + case certRegisterID: + template = CERT_RegisteredIDTemplate; + break; + case certEDIPartyName: + template = CERT_EDIPartyNameTemplate; + break; + case certX400Address: + template = CERT_X400AddressTemplate; + break; + case certDirectoryName: + template = CERT_DirectoryNameTemplate; + break; + default: + goto loser; } rv = SEC_QuickDERDecodeItem(reqArena, genName, template, newEncodedName); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; if (genNameType == certDirectoryName) { - rv = SEC_QuickDERDecodeItem(reqArena, &(genName->name.directoryName), - CERT_NameTemplate, - &(genName->derDirectoryName)); + rv = SEC_QuickDERDecodeItem(reqArena, &(genName->name.directoryName), + CERT_NameTemplate, + &(genName->derDirectoryName)); if (rv != SECSuccess) - goto loser; + goto loser; } /* TODO: unmark arena */ @@ -470,35 +494,34 @@ loser: } CERTGeneralName * -cert_DecodeGeneralNames (PLArenaPool *arena, - SECItem **encodedGenName) +cert_DecodeGeneralNames(PLArenaPool *arena, SECItem **encodedGenName) { - PRCList *head = NULL; - PRCList *tail = NULL; - CERTGeneralName *currentName = NULL; + PRCList *head = NULL; + PRCList *tail = NULL; + CERTGeneralName *currentName = NULL; PORT_Assert(arena); if (!encodedGenName || !arena) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } /* TODO: mark arena */ while (*encodedGenName != NULL) { - currentName = CERT_DecodeGeneralName(arena, *encodedGenName, NULL); - if (currentName == NULL) - break; - if (head == NULL) { - head = &(currentName->l); - tail = head; - } - currentName->l.next = head; - currentName->l.prev = tail; - tail = head->prev = tail->next = &(currentName->l); - encodedGenName++; + currentName = CERT_DecodeGeneralName(arena, *encodedGenName, NULL); + if (currentName == NULL) + break; + if (head == NULL) { + head = &(currentName->l); + tail = head; + } + currentName->l.next = head; + currentName->l.prev = tail; + tail = head->prev = tail->next = &(currentName->l); + encodedGenName++; } if (currentName) { - /* TODO: unmark arena */ - return CERT_GetNextGeneralName(currentName); + /* TODO: unmark arena */ + return CERT_GetNextGeneralName(currentName); } /* TODO: release arena to mark */ return NULL; @@ -513,76 +536,73 @@ CERT_DestroyGeneralName(CERTGeneralName *name) SECStatus cert_DestroyGeneralNames(CERTGeneralName *name) { - CERTGeneralName *first; - CERTGeneralName *next = NULL; - + CERTGeneralName *first; + CERTGeneralName *next = NULL; first = name; do { - next = CERT_GetNextGeneralName(name); - PORT_Free(name); - name = next; + next = CERT_GetNextGeneralName(name); + PORT_Free(name); + name = next; } while (name != first); return SECSuccess; } static SECItem * -cert_EncodeNameConstraint(CERTNameConstraint *constraint, - SECItem *dest, - PLArenaPool *arena) +cert_EncodeNameConstraint(CERTNameConstraint *constraint, SECItem *dest, + PLArenaPool *arena) { PORT_Assert(arena); if (dest == NULL) { - dest = PORT_ArenaZNew(arena, SECItem); - if (dest == NULL) { - return NULL; - } + dest = PORT_ArenaZNew(arena, SECItem); + if (dest == NULL) { + return NULL; + } } CERT_EncodeGeneralName(&(constraint->name), &(constraint->DERName), arena); - - dest = SEC_ASN1EncodeItem (arena, dest, constraint, - CERTNameConstraintTemplate); - return dest; -} -SECStatus -cert_EncodeNameConstraintSubTree(CERTNameConstraint *constraints, - PLArenaPool *arena, - SECItem ***dest, - PRBool permited) + dest = + SEC_ASN1EncodeItem(arena, dest, constraint, CERTNameConstraintTemplate); + return dest; +} + +SECStatus +cert_EncodeNameConstraintSubTree(CERTNameConstraint *constraints, + PLArenaPool *arena, SECItem ***dest, + PRBool permited) { - CERTNameConstraint *current_constraint = constraints; - SECItem **items = NULL; - int count = 0; - int i; - PRCList *head; + CERTNameConstraint *current_constraint = constraints; + SECItem **items = NULL; + int count = 0; + int i; + PRCList *head; PORT_Assert(arena); /* TODO: mark arena */ if (constraints != NULL) { - count = 1; + count = 1; } head = &constraints->l; while (current_constraint->l.next != head) { - current_constraint = CERT_GetNextNameConstraint(current_constraint); - ++count; + current_constraint = CERT_GetNextNameConstraint(current_constraint); + ++count; } current_constraint = CERT_GetNextNameConstraint(current_constraint); items = PORT_ArenaZNewArray(arena, SECItem *, count + 1); if (items == NULL) { - goto loser; + goto loser; } for (i = 0; i < count; i++) { - items[i] = cert_EncodeNameConstraint(current_constraint, - (SECItem *) NULL, arena); - if (items[i] == NULL) { - goto loser; - } - current_constraint = CERT_GetNextNameConstraint(current_constraint); + items[i] = cert_EncodeNameConstraint(current_constraint, + (SECItem *)NULL, arena); + if (items[i] == NULL) { + goto loser; + } + current_constraint = CERT_GetNextNameConstraint(current_constraint); } *dest = items; if (*dest == NULL) { - goto loser; + goto loser; } /* TODO: unmark arena */ return SECSuccess; @@ -591,35 +611,32 @@ loser: return SECFailure; } -SECStatus -cert_EncodeNameConstraints(CERTNameConstraints *constraints, - PLArenaPool *arena, - SECItem *dest) +SECStatus +cert_EncodeNameConstraints(CERTNameConstraints *constraints, PLArenaPool *arena, + SECItem *dest) { - SECStatus rv = SECSuccess; + SECStatus rv = SECSuccess; PORT_Assert(arena); /* TODO: mark arena */ if (constraints->permited != NULL) { - rv = cert_EncodeNameConstraintSubTree(constraints->permited, arena, - &constraints->DERPermited, - PR_TRUE); - if (rv == SECFailure) { - goto loser; - } + rv = cert_EncodeNameConstraintSubTree( + constraints->permited, arena, &constraints->DERPermited, PR_TRUE); + if (rv == SECFailure) { + goto loser; + } } if (constraints->excluded != NULL) { - rv = cert_EncodeNameConstraintSubTree(constraints->excluded, arena, - &constraints->DERExcluded, - PR_FALSE); - if (rv == SECFailure) { - goto loser; - } + rv = cert_EncodeNameConstraintSubTree( + constraints->excluded, arena, &constraints->DERExcluded, PR_FALSE); + if (rv == SECFailure) { + goto loser; + } } - dest = SEC_ASN1EncodeItem(arena, dest, constraints, - CERTNameConstraintsTemplate); + dest = SEC_ASN1EncodeItem(arena, dest, constraints, + CERTNameConstraintsTemplate); if (dest == NULL) { - goto loser; + goto loser; } /* TODO: unmark arena */ return SECSuccess; @@ -628,15 +645,13 @@ loser: return SECFailure; } - CERTNameConstraint * -cert_DecodeNameConstraint(PLArenaPool *reqArena, - SECItem *encodedConstraint) +cert_DecodeNameConstraint(PLArenaPool *reqArena, SECItem *encodedConstraint) { - CERTNameConstraint *constraint; - SECStatus rv = SECSuccess; - CERTGeneralName *temp; - SECItem* newEncodedConstraint; + CERTNameConstraint *constraint; + SECStatus rv = SECSuccess; + CERTGeneralName *temp; + SECItem *newEncodedConstraint; if (!reqArena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -649,21 +664,20 @@ cert_DecodeNameConstraint(PLArenaPool *reqArena, /* TODO: mark arena */ constraint = PORT_ArenaZNew(reqArena, CERTNameConstraint); if (!constraint) - goto loser; - rv = SEC_QuickDERDecodeItem(reqArena, constraint, - CERTNameConstraintTemplate, - newEncodedConstraint); + goto loser; + rv = SEC_QuickDERDecodeItem( + reqArena, constraint, CERTNameConstraintTemplate, newEncodedConstraint); if (rv != SECSuccess) { - goto loser; + goto loser; } temp = CERT_DecodeGeneralName(reqArena, &(constraint->DERName), &(constraint->name)); if (temp != &(constraint->name)) { - goto loser; + goto loser; } - /* ### sjlee: since the name constraint contains only one - * CERTGeneralName, the list within CERTGeneralName shouldn't + /* ### sjlee: since the name constraint contains only one + * CERTGeneralName, the list within CERTGeneralName shouldn't * point anywhere else. Otherwise, bad things will happen. */ constraint->name.l.prev = constraint->name.l.next = &(constraint->name.l); @@ -675,30 +689,30 @@ loser: } static CERTNameConstraint * -cert_DecodeNameConstraintSubTree(PLArenaPool *arena, - SECItem **subTree, - PRBool permited) +cert_DecodeNameConstraintSubTree(PLArenaPool *arena, SECItem **subTree, + PRBool permited) { - CERTNameConstraint *current = NULL; - CERTNameConstraint *first = NULL; - CERTNameConstraint *last = NULL; - int i = 0; + CERTNameConstraint *current = NULL; + CERTNameConstraint *first = NULL; + CERTNameConstraint *last = NULL; + int i = 0; PORT_Assert(arena); /* TODO: mark arena */ while (subTree[i] != NULL) { - current = cert_DecodeNameConstraint(arena, subTree[i]); - if (current == NULL) { - goto loser; - } - if (first == NULL) { - first = current; - } else { - current->l.prev = &(last->l); - last->l.next = &(current->l); - } - last = current; - i++; + current = cert_DecodeNameConstraint(arena, subTree[i]); + if (current == NULL) { + goto loser; + } + if (first == NULL) { + first = current; + } + else { + current->l.prev = &(last->l); + last->l.next = &(current->l); + } + last = current; + i++; } first->l.prev = &(last->l); last->l.next = &(first->l); @@ -710,12 +724,12 @@ loser: } CERTNameConstraints * -cert_DecodeNameConstraints(PLArenaPool *reqArena, - const SECItem *encodedConstraints) +cert_DecodeNameConstraints(PLArenaPool *reqArena, + const SECItem *encodedConstraints) { - CERTNameConstraints *constraints; - SECStatus rv; - SECItem* newEncodedConstraints; + CERTNameConstraints *constraints; + SECStatus rv; + SECItem *newEncodedConstraints; if (!reqArena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -727,33 +741,29 @@ cert_DecodeNameConstraints(PLArenaPool *reqArena, /* TODO: mark arena */ constraints = PORT_ArenaZNew(reqArena, CERTNameConstraints); if (constraints == NULL) { - goto loser; + goto loser; } rv = SEC_QuickDERDecodeItem(reqArena, constraints, CERTNameConstraintsTemplate, newEncodedConstraints); if (rv != SECSuccess) { - goto loser; + goto loser; } - if (constraints->DERPermited != NULL && + if (constraints->DERPermited != NULL && constraints->DERPermited[0] != NULL) { - constraints->permited = - cert_DecodeNameConstraintSubTree(reqArena, - constraints->DERPermited, - PR_TRUE); - if (constraints->permited == NULL) { - goto loser; - } + constraints->permited = cert_DecodeNameConstraintSubTree( + reqArena, constraints->DERPermited, PR_TRUE); + if (constraints->permited == NULL) { + goto loser; + } } - if (constraints->DERExcluded != NULL && + if (constraints->DERExcluded != NULL && constraints->DERExcluded[0] != NULL) { - constraints->excluded = - cert_DecodeNameConstraintSubTree(reqArena, - constraints->DERExcluded, - PR_FALSE); - if (constraints->excluded == NULL) { - goto loser; - } + constraints->excluded = cert_DecodeNameConstraintSubTree( + reqArena, constraints->DERExcluded, PR_FALSE); + if (constraints->excluded == NULL) { + goto loser; + } } /* TODO: unmark arena */ return constraints; @@ -763,22 +773,21 @@ loser: } /* Copy a chain of one or more general names to a destination chain. -** Caller has allocated at least the first destination GeneralName struct. +** Caller has allocated at least the first destination GeneralName struct. ** Both source and destination chains are circular doubly-linked lists. ** The first source struct is copied to the first destination struct. -** If the source chain has more than one member, and the destination chain -** has only one member, then this function allocates new structs for all but -** the first copy from the arena and links them into the destination list. +** If the source chain has more than one member, and the destination chain +** has only one member, then this function allocates new structs for all but +** the first copy from the arena and links them into the destination list. ** If the destination struct is part of a list with more than one member, ** then this function traverses both the source and destination lists, ** copying each source struct to the corresponding dest struct. -** In that case, the destination list MUST contain at least as many +** In that case, the destination list MUST contain at least as many ** structs as the source list or some dest entries will be overwritten. */ SECStatus -CERT_CopyGeneralName(PLArenaPool *arena, - CERTGeneralName *dest, - CERTGeneralName *src) +CERT_CopyGeneralName(PLArenaPool *arena, CERTGeneralName *dest, + CERTGeneralName *src) { SECStatus rv; CERTGeneralName *destHead = dest; @@ -786,31 +795,32 @@ CERT_CopyGeneralName(PLArenaPool *arena, PORT_Assert(dest != NULL); if (!dest) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } /* TODO: mark arena */ do { - rv = cert_CopyOneGeneralName(arena, dest, src); - if (rv != SECSuccess) - goto loser; - src = CERT_GetNextGeneralName(src); - /* if there is only one general name, we shouldn't do this */ - if (src != srcHead) { - if (dest->l.next == &destHead->l) { - CERTGeneralName *temp; - temp = CERT_NewGeneralName(arena, (CERTGeneralNameType)0); - if (!temp) - goto loser; - temp->l.next = &destHead->l; - temp->l.prev = &dest->l; - destHead->l.prev = &temp->l; - dest->l.next = &temp->l; - dest = temp; - } else { - dest = CERT_GetNextGeneralName(dest); - } - } + rv = cert_CopyOneGeneralName(arena, dest, src); + if (rv != SECSuccess) + goto loser; + src = CERT_GetNextGeneralName(src); + /* if there is only one general name, we shouldn't do this */ + if (src != srcHead) { + if (dest->l.next == &destHead->l) { + CERTGeneralName *temp; + temp = CERT_NewGeneralName(arena, (CERTGeneralNameType)0); + if (!temp) + goto loser; + temp->l.next = &destHead->l; + temp->l.prev = &dest->l; + destHead->l.prev = &temp->l; + dest->l.next = &temp->l; + dest = temp; + } + else { + dest = CERT_GetNextGeneralName(dest); + } + } } while (src != srcHead && rv == SECSuccess); /* TODO: unmark arena */ return rv; @@ -819,49 +829,47 @@ loser: return SECFailure; } - CERTGeneralNameList * CERT_DupGeneralNameList(CERTGeneralNameList *list) { if (list != NULL) { - PZ_Lock(list->lock); - list->refCount++; - PZ_Unlock(list->lock); + PZ_Lock(list->lock); + list->refCount++; + PZ_Unlock(list->lock); } return list; } /* Allocate space and copy CERTNameConstraint from src to dest */ CERTNameConstraint * -CERT_CopyNameConstraint(PLArenaPool *arena, - CERTNameConstraint *dest, - CERTNameConstraint *src) +CERT_CopyNameConstraint(PLArenaPool *arena, CERTNameConstraint *dest, + CERTNameConstraint *src) { - SECStatus rv; - + SECStatus rv; + /* TODO: mark arena */ if (dest == NULL) { - dest = PORT_ArenaZNew(arena, CERTNameConstraint); - if (!dest) - goto loser; - /* mark that it is not linked */ - dest->name.l.prev = dest->name.l.next = &(dest->name.l); + dest = PORT_ArenaZNew(arena, CERTNameConstraint); + if (!dest) + goto loser; + /* mark that it is not linked */ + dest->name.l.prev = dest->name.l.next = &(dest->name.l); } rv = CERT_CopyGeneralName(arena, &dest->name, &src->name); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SECITEM_CopyItem(arena, &dest->DERName, &src->DERName); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SECITEM_CopyItem(arena, &dest->min, &src->min); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SECITEM_CopyItem(arena, &dest->max, &src->max); if (rv != SECSuccess) { - goto loser; + goto loser; } dest->l.prev = dest->l.next = &dest->l; /* TODO: unmark arena */ @@ -871,7 +879,6 @@ loser: return NULL; } - CERTGeneralName * cert_CombineNamesLists(CERTGeneralName *list1, CERTGeneralName *list2) { @@ -880,54 +887,56 @@ cert_CombineNamesLists(CERTGeneralName *list1, CERTGeneralName *list2) PRCList *end1; PRCList *end2; - if (list1 == NULL){ - return list2; - } else if (list2 == NULL) { - return list1; - } else { - begin1 = &list1->l; - begin2 = &list2->l; - end1 = list1->l.prev; - end2 = list2->l.prev; - end1->next = begin2; - end2->next = begin1; - begin1->prev = end2; - begin2->prev = end1; - return list1; + if (list1 == NULL) { + return list2; + } + else if (list2 == NULL) { + return list1; + } + else { + begin1 = &list1->l; + begin2 = &list2->l; + end1 = list1->l.prev; + end2 = list2->l.prev; + end1->next = begin2; + end2->next = begin1; + begin1->prev = end2; + begin2->prev = end1; + return list1; } } - CERTNameConstraint * -cert_CombineConstraintsLists(CERTNameConstraint *list1, CERTNameConstraint *list2) +cert_CombineConstraintsLists(CERTNameConstraint *list1, + CERTNameConstraint *list2) { PRCList *begin1; PRCList *begin2; PRCList *end1; PRCList *end2; - if (list1 == NULL){ - return list2; - } else if (list2 == NULL) { - return list1; - } else { - begin1 = &list1->l; - begin2 = &list2->l; - end1 = list1->l.prev; - end2 = list2->l.prev; - end1->next = begin2; - end2->next = begin1; - begin1->prev = end2; - begin2->prev = end1; - return list1; + if (list1 == NULL) { + return list2; + } + else if (list2 == NULL) { + return list1; + } + else { + begin1 = &list1->l; + begin2 = &list2->l; + end1 = list1->l.prev; + end2 = list2->l.prev; + end1->next = begin2; + end2->next = begin1; + begin1->prev = end2; + begin2->prev = end1; + return list1; } } - /* Add a CERTNameConstraint to the CERTNameConstraint list */ CERTNameConstraint * -CERT_AddNameConstraint(CERTNameConstraint *list, - CERTNameConstraint *constraint) +CERT_AddNameConstraint(CERTNameConstraint *list, CERTNameConstraint *constraint) { PORT_Assert(constraint != NULL); constraint->l.next = constraint->l.prev = &constraint->l; @@ -935,33 +944,32 @@ CERT_AddNameConstraint(CERTNameConstraint *list, return list; } - SECStatus -CERT_GetNameConstraintByType (CERTNameConstraint *constraints, - CERTGeneralNameType type, - CERTNameConstraint **returnList, - PLArenaPool *arena) +CERT_GetNameConstraintByType(CERTNameConstraint *constraints, + CERTGeneralNameType type, + CERTNameConstraint **returnList, + PLArenaPool *arena) { CERTNameConstraint *current = NULL; - void *mark = NULL; + void *mark = NULL; *returnList = NULL; if (!constraints) - return SECSuccess; + return SECSuccess; mark = PORT_ArenaMark(arena); current = constraints; do { - PORT_Assert(current->name.type); - if (current->name.type == type) { - CERTNameConstraint *temp; - temp = CERT_CopyNameConstraint(arena, NULL, current); - if (temp == NULL) - goto loser; - *returnList = CERT_AddNameConstraint(*returnList, temp); - } - current = CERT_GetNextNameConstraint(current); + PORT_Assert(current->name.type); + if (current->name.type == type) { + CERTNameConstraint *temp; + temp = CERT_CopyNameConstraint(arena, NULL, current); + if (temp == NULL) + goto loser; + *returnList = CERT_AddNameConstraint(*returnList, temp); + } + current = CERT_GetNextNameConstraint(current); } while (current != constraints); PORT_ArenaUnmark(arena, mark); return SECSuccess; @@ -972,39 +980,41 @@ loser: } void * -CERT_GetGeneralNameByType (CERTGeneralName *genNames, - CERTGeneralNameType type, PRBool derFormat) +CERT_GetGeneralNameByType(CERTGeneralName *genNames, CERTGeneralNameType type, + PRBool derFormat) { CERTGeneralName *current; - + if (!genNames) - return NULL; + return NULL; current = genNames; do { - if (current->type == type) { - switch (type) { - case certDNSName: - case certEDIPartyName: - case certIPAddress: - case certRegisterID: - case certRFC822Name: - case certX400Address: - case certURI: - return (void *)¤t->name.other; /* SECItem * */ + if (current->type == type) { + switch (type) { + case certDNSName: + case certEDIPartyName: + case certIPAddress: + case certRegisterID: + case certRFC822Name: + case certX400Address: + case certURI: + return (void *)¤t->name.other; /* SECItem * */ - case certOtherName: - return (void *)¤t->name.OthName; /* OthName * */ + case certOtherName: + return (void *)¤t->name.OthName; /* OthName * */ - case certDirectoryName: - return derFormat - ? (void *)¤t->derDirectoryName /* SECItem * */ - : (void *)¤t->name.directoryName; /* CERTName * */ - } - PORT_Assert(0); - return NULL; - } - current = CERT_GetNextGeneralName(current); + case certDirectoryName: + return derFormat + ? (void *)¤t + ->derDirectoryName /* SECItem * */ + : (void *)¤t->name + .directoryName; /* CERTName * */ + } + PORT_Assert(0); + return NULL; + } + current = CERT_GetNextGeneralName(current); } while (current != genNames); return NULL; } @@ -1012,60 +1022,61 @@ CERT_GetGeneralNameByType (CERTGeneralName *genNames, int CERT_GetNamesLength(CERTGeneralName *names) { - int length = 0; - CERTGeneralName *first; + int length = 0; + CERTGeneralName *first; first = names; if (names != NULL) { - do { - length++; - names = CERT_GetNextGeneralName(names); - } while (names != first); + do { + length++; + names = CERT_GetNextGeneralName(names); + } while (names != first); } return length; } -/* Creates new GeneralNames for any email addresses found in the +/* Creates new GeneralNames for any email addresses found in the ** input DN, and links them onto the list for the DN. */ SECStatus cert_ExtractDNEmailAddrs(CERTGeneralName *name, PLArenaPool *arena) { CERTGeneralName *nameList = NULL; - const CERTRDN **nRDNs = (const CERTRDN **)(name->name.directoryName.rdns); - SECStatus rv = SECSuccess; + const CERTRDN **nRDNs = (const CERTRDN **)(name->name.directoryName.rdns); + SECStatus rv = SECSuccess; PORT_Assert(name->type == certDirectoryName); if (name->type != certDirectoryName) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + return SECFailure; } /* TODO: mark arena */ while (nRDNs && *nRDNs) { /* loop over RDNs */ - const CERTRDN *nRDN = *nRDNs++; - CERTAVA **nAVAs = nRDN->avas; - while (nAVAs && *nAVAs) { /* loop over AVAs */ - int tag; - CERTAVA *nAVA = *nAVAs++; - tag = CERT_GetAVATag(nAVA); - if ( tag == SEC_OID_PKCS9_EMAIL_ADDRESS || - tag == SEC_OID_RFC1274_MAIL) { /* email AVA */ - CERTGeneralName *newName = NULL; - SECItem *avaValue = CERT_DecodeAVAValue(&nAVA->value); - if (!avaValue) - goto loser; - rv = SECFailure; + const CERTRDN *nRDN = *nRDNs++; + CERTAVA **nAVAs = nRDN->avas; + while (nAVAs && *nAVAs) { /* loop over AVAs */ + int tag; + CERTAVA *nAVA = *nAVAs++; + tag = CERT_GetAVATag(nAVA); + if (tag == SEC_OID_PKCS9_EMAIL_ADDRESS || + tag == SEC_OID_RFC1274_MAIL) { /* email AVA */ + CERTGeneralName *newName = NULL; + SECItem *avaValue = CERT_DecodeAVAValue(&nAVA->value); + if (!avaValue) + goto loser; + rv = SECFailure; newName = CERT_NewGeneralName(arena, certRFC822Name); - if (newName) { - rv = SECITEM_CopyItem(arena, &newName->name.other, avaValue); - } - SECITEM_FreeItem(avaValue, PR_TRUE); - if (rv != SECSuccess) - goto loser; - nameList = cert_CombineNamesLists(nameList, newName); - } /* handle one email AVA */ - } /* loop over AVAs */ - } /* loop over RDNs */ + if (newName) { + rv = + SECITEM_CopyItem(arena, &newName->name.other, avaValue); + } + SECITEM_FreeItem(avaValue, PR_TRUE); + if (rv != SECSuccess) + goto loser; + nameList = cert_CombineNamesLists(nameList, newName); + } /* handle one email AVA */ + } /* loop over AVAs */ + } /* loop over RDNs */ /* combine new names with old one. */ name = cert_CombineNamesLists(name, nameList); /* TODO: unmark arena */ @@ -1076,7 +1087,7 @@ loser: return SECFailure; } -/* Extract all names except Subject Common Name from a cert +/* Extract all names except Subject Common Name from a cert ** in preparation for a name constraints test. */ CERTGeneralName * @@ -1093,30 +1104,30 @@ CERT_GetConstrainedCertificateNames(const CERTCertificate *cert, PLArenaPool *arena, PRBool includeSubjectCommonName) { - CERTGeneralName *DN; - CERTGeneralName *SAN; - PRUint32 numDNSNames = 0; - SECStatus rv; + CERTGeneralName *DN; + CERTGeneralName *SAN; + PRUint32 numDNSNames = 0; + SECStatus rv; if (!arena) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } /* TODO: mark arena */ DN = CERT_NewGeneralName(arena, certDirectoryName); if (DN == NULL) { - goto loser; + goto loser; } rv = CERT_CopyName(arena, &DN->name.directoryName, &cert->subject); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SECITEM_CopyItem(arena, &DN->derDirectoryName, &cert->derSubject); if (rv != SECSuccess) { - goto loser; + goto loser; } - /* Extract email addresses from DN, construct CERTGeneralName structs - ** for them, add them to the name list + /* Extract email addresses from DN, construct CERTGeneralName structs + ** for them, add them to the name list */ rv = cert_ExtractDNEmailAddrs(DN, arena); if (rv != SECSuccess) @@ -1125,35 +1136,35 @@ CERT_GetConstrainedCertificateNames(const CERTCertificate *cert, /* Now extract any GeneralNames from the subject name names extension. */ SAN = cert_GetSubjectAltNameList(cert, arena); if (SAN) { - numDNSNames = cert_CountDNSPatterns(SAN); - DN = cert_CombineNamesLists(DN, SAN); + numDNSNames = cert_CountDNSPatterns(SAN); + DN = cert_CombineNamesLists(DN, SAN); } if (!numDNSNames && includeSubjectCommonName) { - char *cn = CERT_GetCommonName(&cert->subject); - if (cn) { - CERTGeneralName *CN = CERT_NewGeneralName(arena, certDNSName); - if (CN) { - SECItem cnItem = {siBuffer, NULL, 0}; - cnItem.data = (unsigned char *)cn; - cnItem.len = strlen(cn); - rv = SECITEM_CopyItem(arena, &CN->name.other, &cnItem); - if (rv == SECSuccess) { - DN = cert_CombineNamesLists(DN, CN); - } - } - PORT_Free(cn); - } + char *cn = CERT_GetCommonName(&cert->subject); + if (cn) { + CERTGeneralName *CN = CERT_NewGeneralName(arena, certDNSName); + if (CN) { + SECItem cnItem = { siBuffer, NULL, 0 }; + cnItem.data = (unsigned char *)cn; + cnItem.len = strlen(cn); + rv = SECITEM_CopyItem(arena, &CN->name.other, &cnItem); + if (rv == SECSuccess) { + DN = cert_CombineNamesLists(DN, CN); + } + } + PORT_Free(cn); + } } if (rv == SECSuccess) { - /* TODO: unmark arena */ - return DN; + /* TODO: unmark arena */ + return DN; } loser: /* TODO: release arena to mark */ return NULL; } -/* Returns SECSuccess if name matches constraint per RFC 3280 rules for +/* Returns SECSuccess if name matches constraint per RFC 3280 rules for ** URI name constraints. SECFailure otherwise. ** If the constraint begins with a dot, it is a domain name, otherwise ** It is a host name. Examples: @@ -1177,24 +1188,24 @@ compareURIN2C(const SECItem *name, const SECItem *constraint) */ if (!constraint->len) return SECFailure; - if (constraint->data[0] != '.') { - /* constraint is a host name. */ - if (name->len != constraint->len || - PL_strncasecmp((char *)name->data, - (char *)constraint->data, constraint->len)) - return SECFailure; - return SECSuccess; + if (constraint->data[0] != '.') { + /* constraint is a host name. */ + if (name->len != constraint->len || + PL_strncasecmp((char *)name->data, (char *)constraint->data, + constraint->len)) + return SECFailure; + return SECSuccess; } /* constraint is a domain name. */ if (name->len < constraint->len) return SECFailure; offset = name->len - constraint->len; - if (PL_strncasecmp((char *)(name->data + offset), - (char *)constraint->data, constraint->len)) + if (PL_strncasecmp((char *)(name->data + offset), (char *)constraint->data, + constraint->len)) return SECFailure; - if (!offset || + if (!offset || (name->data[offset - 1] == '.') + (constraint->data[0] == '.') == 1) - return SECSuccess; + return SECSuccess; return SECFailure; } @@ -1217,9 +1228,9 @@ compareURIN2C(const SECItem *name, const SECItem *constraint) ** foo.bar.com nofoo.bar.com MATCHES NO MATCH ** .foo.bar.com www.foo.bar.com matches matches? disallowed? ** .foo.bar.com foo.bar.com no match no match -** .foo.bar.com www..foo.bar.com matches probably not +** .foo.bar.com www..foo.bar.com matches probably not ** -** We will try to conform to NIST's PKITS tests, and the unstated +** We will try to conform to NIST's PKITS tests, and the unstated ** rules they imply. */ static SECStatus @@ -1234,12 +1245,12 @@ compareDNSN2C(const SECItem *name, const SECItem *constraint) if (name->len < constraint->len) return SECFailure; offset = name->len - constraint->len; - if (PL_strncasecmp((char *)(name->data + offset), - (char *)constraint->data, constraint->len)) + if (PL_strncasecmp((char *)(name->data + offset), (char *)constraint->data, + constraint->len)) return SECFailure; - if (!offset || + if (!offset || (name->data[offset - 1] == '.') + (constraint->data[0] == '.') == 1) - return SECSuccess; + return SECSuccess; return SECFailure; } @@ -1247,7 +1258,7 @@ compareDNSN2C(const SECItem *name, const SECItem *constraint) ** internet email addresses. SECFailure otherwise. ** If constraint contains a '@' then the two strings much match exactly. ** Else if constraint starts with a '.'. then it must match the right-most -** substring of the name, +** substring of the name, ** else constraint string must match entire name after the name's '@'. ** Empty constraint string matches all names. All comparisons case insensitive. */ @@ -1262,16 +1273,17 @@ compareRFC822N2C(const SECItem *name, const SECItem *constraint) if (constraint->len == 1 && constraint->data[0] == '.') return SECSuccess; for (offset = constraint->len - 1; offset >= 0; --offset) { - if (constraint->data[offset] == '@') { - return (name->len == constraint->len && - !PL_strncasecmp((char *)name->data, - (char *)constraint->data, constraint->len)) - ? SECSuccess : SECFailure; - } + if (constraint->data[offset] == '@') { + return (name->len == constraint->len && + !PL_strncasecmp((char *)name->data, + (char *)constraint->data, constraint->len)) + ? SECSuccess + : SECFailure; + } } offset = name->len - constraint->len; - if (PL_strncasecmp((char *)(name->data + offset), - (char *)constraint->data, constraint->len)) + if (PL_strncasecmp((char *)(name->data + offset), (char *)constraint->data, + constraint->len)) return SECFailure; if (constraint->data[0] == '.') return SECSuccess; @@ -1282,9 +1294,9 @@ compareRFC822N2C(const SECItem *name, const SECItem *constraint) /* name contains either a 4 byte IPv4 address or a 16 byte IPv6 address. ** constraint contains an address of the same length, and a subnet mask -** of the same length. Compare name's address to the constraint's +** of the same length. Compare name's address to the constraint's ** address, subject to the mask. -** Return SECSuccess if they match, SECFailure if they don't. +** Return SECSuccess if they match, SECFailure if they don't. */ static SECStatus compareIPaddrN2C(const SECItem *name, const SECItem *constraint) @@ -1292,67 +1304,67 @@ compareIPaddrN2C(const SECItem *name, const SECItem *constraint) int i; if (name->len == 4 && constraint->len == 8) { /* ipv4 addr */ for (i = 0; i < 4; i++) { - if ((name->data[i] ^ constraint->data[i]) & constraint->data[i+4]) - goto loser; - } - return SECSuccess; + if ((name->data[i] ^ constraint->data[i]) & constraint->data[i + 4]) + goto loser; + } + return SECSuccess; } if (name->len == 16 && constraint->len == 32) { /* ipv6 addr */ for (i = 0; i < 16; i++) { - if ((name->data[i] ^ constraint->data[i]) & constraint->data[i+16]) - goto loser; - } - return SECSuccess; + if ((name->data[i] ^ constraint->data[i]) & + constraint->data[i + 16]) + goto loser; + } + return SECSuccess; } loser: return SECFailure; } -/* start with a SECItem that points to a URI. Parse it lookingg for +/* start with a SECItem that points to a URI. Parse it lookingg for ** a hostname. Modify item->data and item->len to define the hostname, -** but do not modify and data at item->data. +** but do not modify and data at item->data. ** If anything goes wrong, the contents of *item are undefined. */ static SECStatus -parseUriHostname(SECItem * item) +parseUriHostname(SECItem *item) { int i; PRBool found = PR_FALSE; - for (i = 0; (unsigned)(i+2) < item->len; ++i) { - if (item->data[i ] == ':' && - item->data[i+1] == '/' && - item->data[i+2] == '/') { - i += 3; - item->data += i; - item->len -= i; - found = PR_TRUE; - break; - } + for (i = 0; (unsigned)(i + 2) < item->len; ++i) { + if (item->data[i] == ':' && item->data[i + 1] == '/' && + item->data[i + 2] == '/') { + i += 3; + item->data += i; + item->len -= i; + found = PR_TRUE; + break; + } } - if (!found) + if (!found) return SECFailure; /* now look for a '/', which is an upper bound in the end of the name */ for (i = 0; (unsigned)i < item->len; ++i) { - if (item->data[i] == '/') { - item->len = i; - break; - } + if (item->data[i] == '/') { + item->len = i; + break; + } } /* now look for a ':', which marks the end of the name */ - for (i = item->len; --i >= 0; ) { + for (i = item->len; --i >= 0;) { if (item->data[i] == ':') { - item->len = i; - break; - } + item->len = i; + break; + } } /* now look for an '@', which marks the beginning of the hostname */ for (i = 0; (unsigned)i < item->len; ++i) { - if (item->data[i] == '@') { - ++i; - item->data += i; - item->len -= i; - break; - } + if (item->data[i] == '@') { + ++i; + item->data += i; + item->len -= i; + break; + } } return item->len ? SECSuccess : SECFailure; } @@ -1360,144 +1372,145 @@ parseUriHostname(SECItem * item) /* This function takes one name, and a list of constraints. ** It searches the constraints looking for a match. ** It returns SECSuccess if the name satisfies the constraints, i.e., -** if excluded, then the name does not match any constraint, +** if excluded, then the name does not match any constraint, ** if permitted, then the name matches at least one constraint. ** It returns SECFailure if the name fails to satisfy the constraints, ** or if some code fails (e.g. out of memory, or invalid constraint) */ SECStatus -cert_CompareNameWithConstraints(const CERTGeneralName *name, - const CERTNameConstraint *constraints, - PRBool excluded) +cert_CompareNameWithConstraints(const CERTGeneralName *name, + const CERTNameConstraint *constraints, + PRBool excluded) { - SECStatus rv = SECSuccess; - SECStatus matched = SECFailure; + SECStatus rv = SECSuccess; + SECStatus matched = SECFailure; const CERTNameConstraint *current; - PORT_Assert(constraints); /* caller should not call with NULL */ + PORT_Assert(constraints); /* caller should not call with NULL */ if (!constraints) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } current = constraints; do { - rv = SECSuccess; - matched = SECFailure; - PORT_Assert(name->type == current->name.type); - switch (name->type) { + rv = SECSuccess; + matched = SECFailure; + PORT_Assert(name->type == current->name.type); + switch (name->type) { - case certDNSName: - matched = compareDNSN2C(&name->name.other, - ¤t->name.name.other); - break; + case certDNSName: + matched = + compareDNSN2C(&name->name.other, ¤t->name.name.other); + break; - case certRFC822Name: - matched = compareRFC822N2C(&name->name.other, - ¤t->name.name.other); - break; + case certRFC822Name: + matched = compareRFC822N2C(&name->name.other, + ¤t->name.name.other); + break; - case certURI: - { - /* make a modifiable copy of the URI SECItem. */ - SECItem uri = name->name.other; - /* find the hostname in the URI */ - rv = parseUriHostname(&uri); - if (rv == SECSuccess) { - /* does our hostname meet the constraint? */ - matched = compareURIN2C(&uri, ¤t->name.name.other); - } - } - break; + case certURI: { + /* make a modifiable copy of the URI SECItem. */ + SECItem uri = name->name.other; + /* find the hostname in the URI */ + rv = parseUriHostname(&uri); + if (rv == SECSuccess) { + /* does our hostname meet the constraint? */ + matched = compareURIN2C(&uri, ¤t->name.name.other); + } + } break; - case certDirectoryName: - /* Determine if the constraint directory name is a "prefix" - ** for the directory name being tested. - */ - { - /* status defaults to SECEqual, so that a constraint with - ** no AVAs will be a wildcard, matching all directory names. - */ - SECComparison status = SECEqual; - const CERTRDN **cRDNs = - (const CERTRDN **)current->name.name.directoryName.rdns; - const CERTRDN **nRDNs = - (const CERTRDN **)name->name.directoryName.rdns; - while (cRDNs && *cRDNs && nRDNs && *nRDNs) { - /* loop over name RDNs and constraint RDNs in lock step */ - const CERTRDN *cRDN = *cRDNs++; - const CERTRDN *nRDN = *nRDNs++; - CERTAVA **cAVAs = cRDN->avas; - while (cAVAs && *cAVAs) { /* loop over constraint AVAs */ - CERTAVA *cAVA = *cAVAs++; - CERTAVA **nAVAs = nRDN->avas; - while (nAVAs && *nAVAs) { /* loop over name AVAs */ - CERTAVA *nAVA = *nAVAs++; - status = CERT_CompareAVA(cAVA, nAVA); - if (status == SECEqual) - break; - } /* loop over name AVAs */ - if (status != SECEqual) - break; - } /* loop over constraint AVAs */ - if (status != SECEqual) - break; - } /* loop over name RDNs and constraint RDNs */ - matched = (status == SECEqual) ? SECSuccess : SECFailure; - break; - } + case certDirectoryName: + /* Determine if the constraint directory name is a "prefix" + ** for the directory name being tested. + */ + { + /* status defaults to SECEqual, so that a constraint with + ** no AVAs will be a wildcard, matching all directory names. + */ + SECComparison status = SECEqual; + const CERTRDN **cRDNs = + (const CERTRDN **)current->name.name.directoryName.rdns; + const CERTRDN **nRDNs = + (const CERTRDN **)name->name.directoryName.rdns; + while (cRDNs && *cRDNs && nRDNs && *nRDNs) { + /* loop over name RDNs and constraint RDNs in lock step + */ + const CERTRDN *cRDN = *cRDNs++; + const CERTRDN *nRDN = *nRDNs++; + CERTAVA **cAVAs = cRDN->avas; + while (cAVAs && + *cAVAs) { /* loop over constraint AVAs */ + CERTAVA *cAVA = *cAVAs++; + CERTAVA **nAVAs = nRDN->avas; + while (nAVAs && *nAVAs) { /* loop over name AVAs */ + CERTAVA *nAVA = *nAVAs++; + status = CERT_CompareAVA(cAVA, nAVA); + if (status == SECEqual) + break; + } /* loop over name AVAs */ + if (status != SECEqual) + break; + } /* loop over constraint AVAs */ + if (status != SECEqual) + break; + } /* loop over name RDNs and constraint RDNs */ + matched = (status == SECEqual) ? SECSuccess : SECFailure; + break; + } - case certIPAddress: /* type 8 */ - matched = compareIPaddrN2C(&name->name.other, - ¤t->name.name.other); - break; + case certIPAddress: /* type 8 */ + matched = compareIPaddrN2C(&name->name.other, + ¤t->name.name.other); + break; - /* NSS does not know how to compare these "Other" type names with - ** their respective constraints. But it does know how to tell - ** if the constraint applies to the type of name (by comparing - ** the constraint OID to the name OID). NSS makes no use of "Other" - ** type names at all, so NSS errs on the side of leniency for these - ** types, provided that their OIDs match. So, when an "Other" - ** name constraint appears in an excluded subtree, it never causes - ** a name to fail. When an "Other" name constraint appears in a - ** permitted subtree, AND the constraint's OID matches the name's - ** OID, then name is treated as if it matches the constraint. - */ - case certOtherName: /* type 1 */ - matched = (!excluded && - name->type == current->name.type && - SECITEM_ItemsAreEqual(&name->name.OthName.oid, - ¤t->name.name.OthName.oid)) - ? SECSuccess : SECFailure; - break; + /* NSS does not know how to compare these "Other" type names with + ** their respective constraints. But it does know how to tell + ** if the constraint applies to the type of name (by comparing + ** the constraint OID to the name OID). NSS makes no use of "Other" + ** type names at all, so NSS errs on the side of leniency for these + ** types, provided that their OIDs match. So, when an "Other" + ** name constraint appears in an excluded subtree, it never causes + ** a name to fail. When an "Other" name constraint appears in a + ** permitted subtree, AND the constraint's OID matches the name's + ** OID, then name is treated as if it matches the constraint. + */ + case certOtherName: /* type 1 */ + matched = + (!excluded && name->type == current->name.type && + SECITEM_ItemsAreEqual(&name->name.OthName.oid, + ¤t->name.name.OthName.oid)) + ? SECSuccess + : SECFailure; + break; - /* NSS does not know how to compare these types of names with their - ** respective constraints. But NSS makes no use of these types of - ** names at all, so it errs on the side of leniency for these types. - ** Constraints for these types of names never cause the name to - ** fail the constraints test. NSS behaves as if the name matched - ** for permitted constraints, and did not match for excluded ones. - */ - case certX400Address: /* type 4 */ - case certEDIPartyName: /* type 6 */ - case certRegisterID: /* type 9 */ - matched = excluded ? SECFailure : SECSuccess; - break; + /* NSS does not know how to compare these types of names with their + ** respective constraints. But NSS makes no use of these types of + ** names at all, so it errs on the side of leniency for these types. + ** Constraints for these types of names never cause the name to + ** fail the constraints test. NSS behaves as if the name matched + ** for permitted constraints, and did not match for excluded ones. + */ + case certX400Address: /* type 4 */ + case certEDIPartyName: /* type 6 */ + case certRegisterID: /* type 9 */ + matched = excluded ? SECFailure : SECSuccess; + break; - default: /* non-standard types are not supported */ - rv = SECFailure; - break; - } - if (matched == SECSuccess || rv != SECSuccess) - break; - current = CERT_GetNextNameConstraint((CERTNameConstraint*)current); + default: /* non-standard types are not supported */ + rv = SECFailure; + break; + } + if (matched == SECSuccess || rv != SECSuccess) + break; + current = CERT_GetNextNameConstraint((CERTNameConstraint *)current); } while (current != constraints); if (rv == SECSuccess) { - if (matched == SECSuccess) - rv = excluded ? SECFailure : SECSuccess; - else - rv = excluded ? SECSuccess : SECFailure; - return rv; + if (matched == SECSuccess) + rv = excluded ? SECFailure : SECSuccess; + else + rv = excluded ? SECSuccess : SECFailure; + return rv; } return SECFailure; @@ -1524,25 +1537,27 @@ CERT_AddNameConstraintByGeneralName(PLArenaPool *arena, rv = SECFailure; goto done; } - + rv = cert_CopyOneGeneralName(arena, ¤t->name, name); if (rv != SECSuccess) { goto done; } - + current->name.l.prev = current->name.l.next = &(current->name.l); - + if (first == NULL) { *constraints = current; PR_INIT_CLIST(¤t->l); - } else { + } + else { PR_INSERT_BEFORE(¤t->l, &first->l); } done: if (rv == SECFailure) { PORT_ArenaRelease(arena, mark); - } else { + } + else { PORT_ArenaUnmark(arena, mark); } return rv; @@ -1569,51 +1584,55 @@ done: * */ -#define STRING_TO_SECITEM(str) \ -{ siBuffer, (unsigned char*) str, sizeof(str) - 1 } +#define STRING_TO_SECITEM(str) \ + { \ + siBuffer, (unsigned char *)str, sizeof(str) - 1 \ + } -#define NAME_CONSTRAINTS_ENTRY(CA) \ - { \ - STRING_TO_SECITEM(CA ## _SUBJECT_DN), \ - STRING_TO_SECITEM(CA ## _NAME_CONSTRAINTS) \ +#define NAME_CONSTRAINTS_ENTRY(CA) \ + { \ + STRING_TO_SECITEM(CA##_SUBJECT_DN), \ + STRING_TO_SECITEM(CA##_NAME_CONSTRAINTS) \ } /* Agence Nationale de la Securite des Systemes d'Information (ANSSI) */ -#define ANSSI_SUBJECT_DN \ - "\x30\x81\x85" \ - "\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02" "FR" /* C */ \ - "\x31\x0F\x30\x0D\x06\x03\x55\x04\x08\x13\x06" "France" /* ST */ \ - "\x31\x0E\x30\x0C\x06\x03\x55\x04\x07\x13\x05" "Paris" /* L */ \ - "\x31\x10\x30\x0E\x06\x03\x55\x04\x0A\x13\x07" "PM/SGDN" /* O */ \ - "\x31\x0E\x30\x0C\x06\x03\x55\x04\x0B\x13\x05" "DCSSI" /* OU */ \ - "\x31\x0E\x30\x0C\x06\x03\x55\x04\x03\x13\x05" "IGC/A" /* CN */ \ - "\x31\x23\x30\x21\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x09\x01" \ - "\x16\x14" "igca@sgdn.pm.gouv.fr" /* emailAddress */ \ +/* clang-format off */ -#define ANSSI_NAME_CONSTRAINTS \ - "\x30\x5D\xA0\x5B" \ - "\x30\x05\x82\x03" ".fr" \ - "\x30\x05\x82\x03" ".gp" \ - "\x30\x05\x82\x03" ".gf" \ - "\x30\x05\x82\x03" ".mq" \ - "\x30\x05\x82\x03" ".re" \ - "\x30\x05\x82\x03" ".yt" \ - "\x30\x05\x82\x03" ".pm" \ - "\x30\x05\x82\x03" ".bl" \ - "\x30\x05\x82\x03" ".mf" \ - "\x30\x05\x82\x03" ".wf" \ - "\x30\x05\x82\x03" ".pf" \ - "\x30\x05\x82\x03" ".nc" \ - "\x30\x05\x82\x03" ".tf" \ +#define ANSSI_SUBJECT_DN \ + "\x30\x81\x85" \ + "\x31\x0B\x30\x09\x06\x03\x55\x04\x06\x13\x02" "FR" /* C */ \ + "\x31\x0F\x30\x0D\x06\x03\x55\x04\x08\x13\x06" "France" /* ST */ \ + "\x31\x0E\x30\x0C\x06\x03\x55\x04\x07\x13\x05" "Paris" /* L */ \ + "\x31\x10\x30\x0E\x06\x03\x55\x04\x0A\x13\x07" "PM/SGDN" /* O */ \ + "\x31\x0E\x30\x0C\x06\x03\x55\x04\x0B\x13\x05" "DCSSI" /* OU */ \ + "\x31\x0E\x30\x0C\x06\x03\x55\x04\x03\x13\x05" "IGC/A" /* CN */ \ + "\x31\x23\x30\x21\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x09\x01" \ + "\x16\x14" "igca@sgdn.pm.gouv.fr" /* emailAddress */ \ -static const SECItem builtInNameConstraints[][2] = { - NAME_CONSTRAINTS_ENTRY(ANSSI) -}; +#define ANSSI_NAME_CONSTRAINTS \ + "\x30\x5D\xA0\x5B" \ + "\x30\x05\x82\x03" ".fr" \ + "\x30\x05\x82\x03" ".gp" \ + "\x30\x05\x82\x03" ".gf" \ + "\x30\x05\x82\x03" ".mq" \ + "\x30\x05\x82\x03" ".re" \ + "\x30\x05\x82\x03" ".yt" \ + "\x30\x05\x82\x03" ".pm" \ + "\x30\x05\x82\x03" ".bl" \ + "\x30\x05\x82\x03" ".mf" \ + "\x30\x05\x82\x03" ".wf" \ + "\x30\x05\x82\x03" ".pf" \ + "\x30\x05\x82\x03" ".nc" \ + "\x30\x05\x82\x03" ".tf" + +/* clang-format on */ + +static const SECItem builtInNameConstraints[][2] = { NAME_CONSTRAINTS_ENTRY( + ANSSI) }; SECStatus -CERT_GetImposedNameConstraints(const SECItem *derSubject, - SECItem *extensions) +CERT_GetImposedNameConstraints(const SECItem *derSubject, SECItem *extensions) { size_t i; @@ -1624,8 +1643,7 @@ CERT_GetImposedNameConstraints(const SECItem *derSubject, for (i = 0; i < PR_ARRAY_SIZE(builtInNameConstraints); ++i) { if (SECITEM_ItemsAreEqual(derSubject, &builtInNameConstraints[i][0])) { - return SECITEM_CopyItem(NULL, - extensions, + return SECITEM_CopyItem(NULL, extensions, &builtInNameConstraints[i][1]); } } @@ -1634,24 +1652,23 @@ CERT_GetImposedNameConstraints(const SECItem *derSubject, return SECFailure; } -/* +/* * Extract the name constraints extension from the CA cert. * If the certificate contains no name constraints extension, but * CERT_GetImposedNameConstraints returns a name constraints extension * for the subject of the certificate, then that extension will be returned. */ SECStatus -CERT_FindNameConstraintsExten(PLArenaPool *arena, - CERTCertificate *cert, +CERT_FindNameConstraintsExten(PLArenaPool *arena, CERTCertificate *cert, CERTNameConstraints **constraints) { - SECStatus rv = SECSuccess; - SECItem constraintsExtension; - void *mark = NULL; - + SECStatus rv = SECSuccess; + SECItem constraintsExtension; + void *mark = NULL; + *constraints = NULL; - rv = CERT_FindCertExtension(cert, SEC_OID_X509_NAME_CONSTRAINTS, + rv = CERT_FindCertExtension(cert, SEC_OID_X509_NAME_CONSTRAINTS, &constraintsExtension); if (rv != SECSuccess) { if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) { @@ -1660,10 +1677,10 @@ CERT_FindNameConstraintsExten(PLArenaPool *arena, rv = CERT_GetImposedNameConstraints(&cert->derSubject, &constraintsExtension); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_EXTENSION_NOT_FOUND) { - return SECSuccess; - } - return rv; + if (PORT_GetError() == SEC_ERROR_EXTENSION_NOT_FOUND) { + return SECSuccess; + } + return rv; } } @@ -1673,11 +1690,12 @@ CERT_FindNameConstraintsExten(PLArenaPool *arena, if (*constraints == NULL) { /* decode failed */ rv = SECFailure; } - PORT_Free (constraintsExtension.data); + PORT_Free(constraintsExtension.data); if (rv == SECFailure) { PORT_ArenaRelease(arena, mark); - } else { + } + else { PORT_ArenaUnmark(arena, mark); } @@ -1688,42 +1706,39 @@ CERT_FindNameConstraintsExten(PLArenaPool *arena, ** the name. */ SECStatus -CERT_CheckNameSpace(PLArenaPool *arena, - const CERTNameConstraints *constraints, - const CERTGeneralName *currentName) +CERT_CheckNameSpace(PLArenaPool *arena, const CERTNameConstraints *constraints, + const CERTGeneralName *currentName) { - CERTNameConstraint *matchingConstraints; - SECStatus rv = SECSuccess; - + CERTNameConstraint *matchingConstraints; + SECStatus rv = SECSuccess; + if (constraints->excluded != NULL) { - rv = CERT_GetNameConstraintByType(constraints->excluded, - currentName->type, + rv = CERT_GetNameConstraintByType(constraints->excluded, + currentName->type, &matchingConstraints, arena); if (rv == SECSuccess && matchingConstraints != NULL) { - rv = cert_CompareNameWithConstraints(currentName, - matchingConstraints, - PR_TRUE); + rv = cert_CompareNameWithConstraints(currentName, + matchingConstraints, PR_TRUE); } if (rv != SECSuccess) { - return(rv); - } - } - - if (constraints->permited != NULL) { - rv = CERT_GetNameConstraintByType(constraints->permited, - currentName->type, - &matchingConstraints, arena); - if (rv == SECSuccess && matchingConstraints != NULL) { - rv = cert_CompareNameWithConstraints(currentName, - matchingConstraints, - PR_FALSE); - } - if (rv != SECSuccess) { - return(rv); + return (rv); } } - return(SECSuccess); + if (constraints->permited != NULL) { + rv = CERT_GetNameConstraintByType(constraints->permited, + currentName->type, + &matchingConstraints, arena); + if (rv == SECSuccess && matchingConstraints != NULL) { + rv = cert_CompareNameWithConstraints(currentName, + matchingConstraints, PR_FALSE); + } + if (rv != SECSuccess) { + return (rv); + } + } + + return (SECSuccess); } /* Extract the name constraints extension from the CA cert. @@ -1734,45 +1749,43 @@ CERT_CheckNameSpace(PLArenaPool *arena, ** contained that name. */ SECStatus -CERT_CompareNameSpace(CERTCertificate *cert, - CERTGeneralName *namesList, - CERTCertificate **certsList, - PLArenaPool *reqArena, - CERTCertificate **pBadCert) +CERT_CompareNameSpace(CERTCertificate *cert, CERTGeneralName *namesList, + CERTCertificate **certsList, PLArenaPool *reqArena, + CERTCertificate **pBadCert) { - SECStatus rv = SECSuccess; - CERTNameConstraints *constraints; - CERTGeneralName *currentName; - int count = 0; - CERTCertificate *badCert = NULL; + SECStatus rv = SECSuccess; + CERTNameConstraints *constraints; + CERTGeneralName *currentName; + int count = 0; + CERTCertificate *badCert = NULL; /* If no names to check, then no names can be bad. */ if (!namesList) - goto done; + goto done; rv = CERT_FindNameConstraintsExten(reqArena, cert, &constraints); if (rv != SECSuccess) { - count = -1; - goto done; + count = -1; + goto done; } currentName = namesList; do { - if (constraints){ - rv = CERT_CheckNameSpace(reqArena, constraints, currentName); - if (rv != SECSuccess) { - break; - } - } - currentName = CERT_GetNextGeneralName(currentName); - count ++; + if (constraints) { + rv = CERT_CheckNameSpace(reqArena, constraints, currentName); + if (rv != SECSuccess) { + break; + } + } + currentName = CERT_GetNextGeneralName(currentName); + count++; } while (currentName != namesList); done: if (rv != SECSuccess) { - badCert = (count >= 0) ? certsList[count] : cert; + badCert = (count >= 0) ? certsList[count] : cert; } if (pBadCert) - *pBadCert = badCert; + *pBadCert = badCert; return rv; } @@ -1789,7 +1802,7 @@ CERT_CompareGeneralName(CERTGeneralName *a, CERTGeneralName *b) currentA = a; currentB = b; if (a != NULL) { - do { + do { if (currentB == NULL) { return SECFailure; } @@ -1815,14 +1828,14 @@ CERT_CompareGeneralName(CERTGeneralName *a, CERTGeneralName *b) case certX400Address: case certURI: if (SECITEM_CompareItem(¤tA->name.other, - ¤tB->name.other) + ¤tB->name.other) == SECEqual) { found = PR_TRUE; } break; case certOtherName: if (SECITEM_CompareItem(¤tA->name.OthName.oid, - ¤tB->name.OthName.oid) + ¤tB->name.OthName.oid) == SECEqual && SECITEM_CompareItem(¤tA->name.OthName.name, ¤tB->name.OthName.name) @@ -1837,7 +1850,7 @@ CERT_CompareGeneralName(CERTGeneralName *a, CERTGeneralName *b) found = PR_TRUE; } } - + } currentB = CERT_GetNextGeneralName(currentB); } while (currentB != b && found != PR_TRUE); @@ -1880,7 +1893,7 @@ CERT_GetGeneralNameFromListByType(CERTGeneralNameList *list, CERTGeneralNameType type, PLArenaPool *arena) { - CERTName *name = NULL; + CERTName *name = NULL; SECItem *item = NULL; OtherName *other = NULL; OtherName *tmpOther = NULL; @@ -1902,7 +1915,7 @@ CERT_GetGeneralNameFromListByType(CERTGeneralNameList *list, if (item != NULL) { XXX SECITEM_CopyItem(arena, item, (SECItem *) data); } - } else { + } else { item = SECITEM_DupItem((SECItem *) data); } PZ_Unlock(list->lock); @@ -1943,7 +1956,7 @@ XXX CERT_CopyName(arena, name, (CERTName *) data); ** that can fail. */ void -CERT_AddGeneralNameToList(CERTGeneralNameList *list, +CERT_AddGeneralNameToList(CERTGeneralNameList *list, CERTGeneralNameType type, void *data, SECItem *oid) { diff --git a/security/nss/lib/certdb/genname.h b/security/nss/lib/certdb/genname.h index 091c82c1273d..5824157108b3 100644 --- a/security/nss/lib/certdb/genname.h +++ b/security/nss/lib/certdb/genname.h @@ -17,89 +17,76 @@ SEC_BEGIN_PROTOS extern const SEC_ASN1Template CERT_GeneralNamesTemplate[]; -extern SECItem ** -cert_EncodeGeneralNames(PLArenaPool *arena, CERTGeneralName *names); +extern SECItem **cert_EncodeGeneralNames(PLArenaPool *arena, + CERTGeneralName *names); -extern CERTGeneralName * -cert_DecodeGeneralNames(PLArenaPool *arena, SECItem **encodedGenName); +extern CERTGeneralName *cert_DecodeGeneralNames(PLArenaPool *arena, + SECItem **encodedGenName); -extern SECStatus -cert_DestroyGeneralNames(CERTGeneralName *name); +extern SECStatus cert_DestroyGeneralNames(CERTGeneralName *name); -extern SECStatus -cert_EncodeNameConstraints(CERTNameConstraints *constraints, PLArenaPool *arena, - SECItem *dest); +extern SECStatus cert_EncodeNameConstraints(CERTNameConstraints *constraints, + PLArenaPool *arena, SECItem *dest); -extern CERTNameConstraints * -cert_DecodeNameConstraints(PLArenaPool *arena, const SECItem *encodedConstraints); +extern CERTNameConstraints *cert_DecodeNameConstraints( + PLArenaPool *arena, const SECItem *encodedConstraints); -extern CERTGeneralName * -cert_CombineNamesLists(CERTGeneralName *list1, CERTGeneralName *list2); +extern CERTGeneralName *cert_CombineNamesLists(CERTGeneralName *list1, + CERTGeneralName *list2); -extern CERTNameConstraint * -cert_CombineConstraintsLists(CERTNameConstraint *list1, CERTNameConstraint *list2); +extern CERTNameConstraint *cert_CombineConstraintsLists( + CERTNameConstraint *list1, CERTNameConstraint *list2); /*********************************************************************/ /* A thread safe implementation of General Names */ /*********************************************************************/ /* Destroy a Single CERTGeneralName */ -void -CERT_DestroyGeneralName(CERTGeneralName *name); +void CERT_DestroyGeneralName(CERTGeneralName *name); -SECStatus -CERT_CompareGeneralName(CERTGeneralName *a, CERTGeneralName *b); +SECStatus CERT_CompareGeneralName(CERTGeneralName *a, CERTGeneralName *b); -SECStatus -CERT_CopyGeneralName(PLArenaPool *arena, - CERTGeneralName *dest, - CERTGeneralName *src); +SECStatus CERT_CopyGeneralName(PLArenaPool *arena, CERTGeneralName *dest, + CERTGeneralName *src); -/* General Name Lists are a thread safe, reference counting layer to +/* General Name Lists are a thread safe, reference counting layer to * general names */ /* Destroys a CERTGeneralNameList */ -void -CERT_DestroyGeneralNameList(CERTGeneralNameList *list); +void CERT_DestroyGeneralNameList(CERTGeneralNameList *list); /* Creates a CERTGeneralNameList */ -CERTGeneralNameList * -CERT_CreateGeneralNameList(CERTGeneralName *name); +CERTGeneralNameList *CERT_CreateGeneralNameList(CERTGeneralName *name); /* Compares two CERTGeneralNameList */ -SECStatus -CERT_CompareGeneralNameLists(CERTGeneralNameList *a, CERTGeneralNameList *b); +SECStatus CERT_CompareGeneralNameLists(CERTGeneralNameList *a, + CERTGeneralNameList *b); /* returns a copy of the first name of the type requested */ -void * -CERT_GetGeneralNameFromListByType(CERTGeneralNameList *list, - CERTGeneralNameType type, - PLArenaPool *arena); +void *CERT_GetGeneralNameFromListByType(CERTGeneralNameList *list, + CERTGeneralNameType type, + PLArenaPool *arena); /* Adds a name to the tail of the list */ -void -CERT_AddGeneralNameToList(CERTGeneralNameList *list, - CERTGeneralNameType type, - void *data, SECItem *oid); +void CERT_AddGeneralNameToList(CERTGeneralNameList *list, + CERTGeneralNameType type, void *data, + SECItem *oid); /* returns a duplicate of the CERTGeneralNameList */ -CERTGeneralNameList * -CERT_DupGeneralNameList(CERTGeneralNameList *list); +CERTGeneralNameList *CERT_DupGeneralNameList(CERTGeneralNameList *list); /* returns the number of CERTGeneralName objects in the doubly linked ** list of which *names is a member. */ -extern int -CERT_GetNamesLength(CERTGeneralName *names); +extern int CERT_GetNamesLength(CERTGeneralName *names); /************************************************************************/ -SECStatus -CERT_CompareNameSpace(CERTCertificate *cert, - CERTGeneralName *namesList, - CERTCertificate **certsList, - PLArenaPool *reqArena, - CERTCertificate **pBadCert); +SECStatus CERT_CompareNameSpace(CERTCertificate *cert, + CERTGeneralName *namesList, + CERTCertificate **certsList, + PLArenaPool *reqArena, + CERTCertificate **pBadCert); SEC_END_PROTOS diff --git a/security/nss/lib/certdb/polcyxtn.c b/security/nss/lib/certdb/polcyxtn.c index cef4783cea93..664d7dd786e3 100644 --- a/security/nss/lib/certdb/polcyxtn.c +++ b/security/nss/lib/certdb/polcyxtn.c @@ -20,95 +20,81 @@ SEC_ASN1_MKSUB(SEC_ObjectIDTemplate) const SEC_ASN1Template CERT_DisplayTextTypeTemplate[] = { { SEC_ASN1_CHOICE, offsetof(SECItem, type), 0, sizeof(SECItem) }, - { SEC_ASN1_IA5_STRING, 0, 0, siAsciiString}, - { SEC_ASN1_VISIBLE_STRING , 0, 0, siVisibleString}, - { SEC_ASN1_BMP_STRING , 0, 0, siBMPString }, - { SEC_ASN1_UTF8_STRING , 0, 0, siUTF8String }, + { SEC_ASN1_IA5_STRING, 0, 0, siAsciiString }, + { SEC_ASN1_VISIBLE_STRING, 0, 0, siVisibleString }, + { SEC_ASN1_BMP_STRING, 0, 0, siBMPString }, + { SEC_ASN1_UTF8_STRING, 0, 0, siUTF8String }, { 0 } }; const SEC_ASN1Template CERT_NoticeReferenceTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTNoticeReference) }, - { SEC_ASN1_INLINE, - offsetof(CERTNoticeReference, organization), - CERT_DisplayTextTypeTemplate, 0 }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTNoticeReference) }, + { SEC_ASN1_INLINE, offsetof(CERTNoticeReference, organization), + CERT_DisplayTextTypeTemplate, 0 }, { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN, - offsetof(CERTNoticeReference, noticeNumbers), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, + offsetof(CERTNoticeReference, noticeNumbers), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, { 0 } }; const SEC_ASN1Template CERT_UserNoticeTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTUserNotice) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTUserNotice) }, { SEC_ASN1_INLINE | SEC_ASN1_OPTIONAL, - offsetof(CERTUserNotice, noticeReference), - CERT_NoticeReferenceTemplate, 0 }, + offsetof(CERTUserNotice, noticeReference), CERT_NoticeReferenceTemplate, + 0 }, { SEC_ASN1_INLINE | SEC_ASN1_OPTIONAL, - offsetof(CERTUserNotice, displayText), - CERT_DisplayTextTypeTemplate, 0 }, + offsetof(CERTUserNotice, displayText), CERT_DisplayTextTypeTemplate, 0 }, { 0 } }; const SEC_ASN1Template CERT_PolicyQualifierTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTPolicyQualifier) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTPolicyQualifier, qualifierID) }, - { SEC_ASN1_ANY, - offsetof(CERTPolicyQualifier, qualifierValue) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTPolicyQualifier) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTPolicyQualifier, qualifierID) }, + { SEC_ASN1_ANY, offsetof(CERTPolicyQualifier, qualifierValue) }, { 0 } }; const SEC_ASN1Template CERT_PolicyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTPolicyInfo) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTPolicyInfo, policyID) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTPolicyInfo) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTPolicyInfo, policyID) }, { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_OPTIONAL, - offsetof(CERTPolicyInfo, policyQualifiers), - CERT_PolicyQualifierTemplate }, + offsetof(CERTPolicyInfo, policyQualifiers), + CERT_PolicyQualifierTemplate }, { 0 } }; const SEC_ASN1Template CERT_CertificatePoliciesTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(CERTCertificatePolicies, policyInfos), - CERT_PolicyInfoTemplate, sizeof(CERTCertificatePolicies) } + { SEC_ASN1_SEQUENCE_OF, offsetof(CERTCertificatePolicies, policyInfos), + CERT_PolicyInfoTemplate, sizeof(CERTCertificatePolicies) } }; const SEC_ASN1Template CERT_PolicyMapTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTPolicyMap) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTPolicyMap, issuerDomainPolicy) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTPolicyMap, subjectDomainPolicy) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTPolicyMap) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTPolicyMap, issuerDomainPolicy) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTPolicyMap, subjectDomainPolicy) }, { 0 } }; const SEC_ASN1Template CERT_PolicyMappingsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(CERTCertificatePolicyMappings, policyMaps), - CERT_PolicyMapTemplate, sizeof(CERTPolicyMap) } + { SEC_ASN1_SEQUENCE_OF, offsetof(CERTCertificatePolicyMappings, policyMaps), + CERT_PolicyMapTemplate, sizeof(CERTPolicyMap) } }; const SEC_ASN1Template CERT_PolicyConstraintsTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTCertificatePolicyConstraints) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(CERTCertificatePolicyConstraints, explicitPolicySkipCerts), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, + offsetof(CERTCertificatePolicyConstraints, explicitPolicySkipCerts), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, - offsetof(CERTCertificatePolicyConstraints, inhibitMappingSkipCerts), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, + offsetof(CERTCertificatePolicyConstraints, inhibitMappingSkipCerts), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, { 0 } }; const SEC_ASN1Template CERT_InhibitAnyTemplate[] = { { SEC_ASN1_INTEGER, - offsetof(CERTCertificateInhibitAny, inhibitAnySkipCerts), - NULL, sizeof(CERTCertificateInhibitAny) } + offsetof(CERTCertificateInhibitAny, inhibitAnySkipCerts), NULL, + sizeof(CERTCertificateInhibitAny) } }; static void @@ -118,30 +104,30 @@ breakLines(char *string) char *lastspace = NULL; int curlen = 0; int c; - + tmpstr = string; - while ( ( c = *tmpstr ) != '\0' ) { - switch ( c ) { - case ' ': - lastspace = tmpstr; - break; - case '\n': - lastspace = NULL; - curlen = 0; - break; - } - - if ( ( curlen >= 55 ) && ( lastspace != NULL ) ) { - *lastspace = '\n'; - curlen = ( tmpstr - lastspace ); - lastspace = NULL; - } - - curlen++; - tmpstr++; + while ((c = *tmpstr) != '\0') { + switch (c) { + case ' ': + lastspace = tmpstr; + break; + case '\n': + lastspace = NULL; + curlen = 0; + break; + } + + if ((curlen >= 55) && (lastspace != NULL)) { + *lastspace = '\n'; + curlen = (tmpstr - lastspace); + lastspace = NULL; + } + + curlen++; + tmpstr++; } - + return; } @@ -154,69 +140,69 @@ CERT_DecodeCertificatePoliciesExtension(const SECItem *extnValue) CERTPolicyInfo **policyInfos, *policyInfo; CERTPolicyQualifier **policyQualifiers, *policyQualifier; SECItem newExtnValue; - + /* make a new arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( !arena ) { - goto loser; + + if (!arena) { + goto loser; } /* allocate the certificate policies structure */ - policies = (CERTCertificatePolicies *) - PORT_ArenaZAlloc(arena, sizeof(CERTCertificatePolicies)); - - if ( policies == NULL ) { - goto loser; + policies = (CERTCertificatePolicies *)PORT_ArenaZAlloc( + arena, sizeof(CERTCertificatePolicies)); + + if (policies == NULL) { + goto loser; } - + policies->arena = arena; /* 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, &newExtnValue, extnValue); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* decode the policy info */ - rv = SEC_QuickDERDecodeItem(arena, policies, CERT_CertificatePoliciesTemplate, - &newExtnValue); + rv = SEC_QuickDERDecodeItem( + arena, policies, CERT_CertificatePoliciesTemplate, &newExtnValue); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* initialize the oid tags */ policyInfos = policies->policyInfos; - while (*policyInfos != NULL ) { - policyInfo = *policyInfos; - policyInfo->oid = SECOID_FindOIDTag(&policyInfo->policyID); - policyQualifiers = policyInfo->policyQualifiers; - while ( policyQualifiers != NULL && *policyQualifiers != NULL ) { - policyQualifier = *policyQualifiers; - policyQualifier->oid = - SECOID_FindOIDTag(&policyQualifier->qualifierID); - policyQualifiers++; - } - policyInfos++; + while (*policyInfos != NULL) { + policyInfo = *policyInfos; + policyInfo->oid = SECOID_FindOIDTag(&policyInfo->policyID); + policyQualifiers = policyInfo->policyQualifiers; + while (policyQualifiers != NULL && *policyQualifiers != NULL) { + policyQualifier = *policyQualifiers; + policyQualifier->oid = + SECOID_FindOIDTag(&policyQualifier->qualifierID); + policyQualifiers++; + } + policyInfos++; } - return(policies); - + return (policies); + loser: - if ( arena != NULL ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena != NULL) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } void CERT_DestroyCertificatePoliciesExtension(CERTCertificatePolicies *policies) { - if ( policies != NULL ) { - PORT_FreeArena(policies->arena, PR_FALSE); + if (policies != NULL) { + PORT_FreeArena(policies->arena, PR_FALSE); } return; } @@ -228,17 +214,17 @@ CERT_DecodePolicyMappingsExtension(SECItem *extnValue) SECStatus rv; CERTCertificatePolicyMappings *mappings; SECItem newExtnValue; - + /* make a new arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { goto loser; } /* allocate the policy mappings structure */ - mappings = (CERTCertificatePolicyMappings *) - PORT_ArenaZAlloc(arena, sizeof(CERTCertificatePolicyMappings)); - if ( mappings == NULL ) { + mappings = (CERTCertificatePolicyMappings *)PORT_ArenaZAlloc( + arena, sizeof(CERTCertificatePolicyMappings)); + if (mappings == NULL) { goto loser; } mappings->arena = arena; @@ -246,40 +232,39 @@ CERT_DecodePolicyMappingsExtension(SECItem *extnValue) /* 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, &newExtnValue, extnValue); - if ( rv != SECSuccess ) { + if (rv != SECSuccess) { goto loser; } /* decode the policy mappings */ - rv = SEC_QuickDERDecodeItem - (arena, mappings, CERT_PolicyMappingsTemplate, &newExtnValue); - if ( rv != SECSuccess ) { + rv = SEC_QuickDERDecodeItem(arena, mappings, CERT_PolicyMappingsTemplate, + &newExtnValue); + if (rv != SECSuccess) { goto loser; } - return(mappings); - + return (mappings); + loser: - if ( arena != NULL ) { + if (arena != NULL) { PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } SECStatus CERT_DestroyPolicyMappingsExtension(CERTCertificatePolicyMappings *mappings) { - if ( mappings != NULL ) { + if (mappings != NULL) { PORT_FreeArena(mappings->arena, PR_FALSE); } return SECSuccess; } SECStatus -CERT_DecodePolicyConstraintsExtension - (CERTCertificatePolicyConstraints *decodedValue, - const SECItem *encodedValue) +CERT_DecodePolicyConstraintsExtension( + CERTCertificatePolicyConstraints *decodedValue, const SECItem *encodedValue) { CERTCertificatePolicyConstraints decodeContext; PLArenaPool *arena = NULL; @@ -296,46 +281,50 @@ CERT_DecodePolicyConstraintsExtension do { /* decode the policy constraints */ - rv = SEC_QuickDERDecodeItem(arena, - &decodeContext, CERT_PolicyConstraintsTemplate, encodedValue); + rv = SEC_QuickDERDecodeItem(arena, &decodeContext, + CERT_PolicyConstraintsTemplate, + encodedValue); - if ( rv != SECSuccess ) { + if (rv != SECSuccess) { break; } if (decodeContext.explicitPolicySkipCerts.len == 0) { *(PRInt32 *)decodedValue->explicitPolicySkipCerts.data = -1; - } else { + } + else { *(PRInt32 *)decodedValue->explicitPolicySkipCerts.data = - DER_GetInteger(&decodeContext.explicitPolicySkipCerts); + DER_GetInteger(&decodeContext.explicitPolicySkipCerts); } if (decodeContext.inhibitMappingSkipCerts.len == 0) { *(PRInt32 *)decodedValue->inhibitMappingSkipCerts.data = -1; - } else { + } + else { *(PRInt32 *)decodedValue->inhibitMappingSkipCerts.data = - DER_GetInteger(&decodeContext.inhibitMappingSkipCerts); + DER_GetInteger(&decodeContext.inhibitMappingSkipCerts); } if ((*(PRInt32 *)decodedValue->explicitPolicySkipCerts.data == - PR_INT32_MIN) || + PR_INT32_MIN) || (*(PRInt32 *)decodedValue->explicitPolicySkipCerts.data == - PR_INT32_MAX) || + PR_INT32_MAX) || (*(PRInt32 *)decodedValue->inhibitMappingSkipCerts.data == - PR_INT32_MIN) || + PR_INT32_MIN) || (*(PRInt32 *)decodedValue->inhibitMappingSkipCerts.data == - PR_INT32_MAX)) { + PR_INT32_MAX)) { rv = SECFailure; } - + } while (0); PORT_FreeArena(arena, PR_FALSE); - return(rv); + return (rv); } -SECStatus CERT_DecodeInhibitAnyExtension - (CERTCertificateInhibitAny *decodedValue, SECItem *encodedValue) +SECStatus +CERT_DecodeInhibitAnyExtension(CERTCertificateInhibitAny *decodedValue, + SECItem *encodedValue) { CERTCertificateInhibitAny decodeContext; PLArenaPool *arena = NULL; @@ -343,7 +332,7 @@ SECStatus CERT_DecodeInhibitAnyExtension /* make a new arena */ arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if ( !arena ) { + if (!arena) { return SECFailure; } @@ -351,20 +340,20 @@ SECStatus CERT_DecodeInhibitAnyExtension /* decode the policy mappings */ decodeContext.inhibitAnySkipCerts.type = siUnsignedInteger; - rv = SEC_QuickDERDecodeItem(arena, - &decodeContext, CERT_InhibitAnyTemplate, encodedValue); + rv = SEC_QuickDERDecodeItem(arena, &decodeContext, + CERT_InhibitAnyTemplate, encodedValue); - if ( rv != SECSuccess ) { + if (rv != SECSuccess) { break; } *(PRInt32 *)decodedValue->inhibitAnySkipCerts.data = - DER_GetInteger(&decodeContext.inhibitAnySkipCerts); + DER_GetInteger(&decodeContext.inhibitAnySkipCerts); } while (0); PORT_FreeArena(arena, PR_FALSE); - return(rv); + return (rv); } CERTUserNotice * @@ -374,37 +363,37 @@ CERT_DecodeUserNotice(SECItem *noticeItem) SECStatus rv; CERTUserNotice *userNotice; SECItem newNoticeItem; - + /* make a new arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( !arena ) { - goto loser; + + if (!arena) { + goto loser; } /* allocate the userNotice structure */ - userNotice = (CERTUserNotice *)PORT_ArenaZAlloc(arena, - sizeof(CERTUserNotice)); - - if ( userNotice == NULL ) { - goto loser; + userNotice = + (CERTUserNotice *)PORT_ArenaZAlloc(arena, sizeof(CERTUserNotice)); + + if (userNotice == NULL) { + goto loser; } - + userNotice->arena = arena; /* 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, &newNoticeItem, noticeItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* decode the user notice */ - rv = SEC_QuickDERDecodeItem(arena, userNotice, CERT_UserNoticeTemplate, - &newNoticeItem); + rv = SEC_QuickDERDecodeItem(arena, userNotice, CERT_UserNoticeTemplate, + &newNoticeItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } if (userNotice->derNoticeReference.data != NULL) { @@ -414,24 +403,24 @@ CERT_DecodeUserNotice(SECItem *noticeItem) &userNotice->derNoticeReference); if (rv == SECFailure) { goto loser; - } + } } - return(userNotice); - + return (userNotice); + loser: - if ( arena != NULL ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena != NULL) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } void CERT_DestroyUserNotice(CERTUserNotice *userNotice) { - if ( userNotice != NULL ) { - PORT_FreeArena(userNotice->arena, PR_FALSE); + if (userNotice != NULL) { + PORT_FreeArena(userNotice->arena, PR_FALSE); } return; } @@ -459,74 +448,74 @@ stringFromUserNotice(SECItem *noticeItem) SECItem *displayText; SECItem **noticeNumbers; unsigned int strnum; - + /* decode the user notice */ userNotice = CERT_DecodeUserNotice(noticeItem); - if ( userNotice == NULL ) { - return(NULL); + if (userNotice == NULL) { + return (NULL); } - + org = &userNotice->noticeReference.organization; - if ( (org->len != 0 ) && ( policyStringCB != NULL ) ) { - /* has a noticeReference */ + if ((org->len != 0) && (policyStringCB != NULL)) { + /* has a noticeReference */ - /* extract the org string */ - len = org->len; - stringbuf = (char*)PORT_Alloc(len + 1); - if ( stringbuf != NULL ) { - PORT_Memcpy(stringbuf, org->data, len); - stringbuf[len] = '\0'; + /* extract the org string */ + len = org->len; + stringbuf = (char *)PORT_Alloc(len + 1); + if (stringbuf != NULL) { + PORT_Memcpy(stringbuf, org->data, len); + stringbuf[len] = '\0'; - noticeNumbers = userNotice->noticeReference.noticeNumbers; - while ( *noticeNumbers != NULL ) { - /* XXX - only one byte integers right now*/ - strnum = (*noticeNumbers)->data[0]; - policystr = (* policyStringCB)(stringbuf, - strnum, - policyStringCBArg); - if ( policystr != NULL ) { - if ( retstr != NULL ) { - retstr = PR_sprintf_append(retstr, "\n%s", policystr); - } else { - retstr = PR_sprintf_append(retstr, "%s", policystr); - } + noticeNumbers = userNotice->noticeReference.noticeNumbers; + while (*noticeNumbers != NULL) { + /* XXX - only one byte integers right now*/ + strnum = (*noticeNumbers)->data[0]; + policystr = + (*policyStringCB)(stringbuf, strnum, policyStringCBArg); + if (policystr != NULL) { + if (retstr != NULL) { + retstr = PR_sprintf_append(retstr, "\n%s", policystr); + } + else { + retstr = PR_sprintf_append(retstr, "%s", policystr); + } - PORT_Free(policystr); - } - - noticeNumbers++; - } + PORT_Free(policystr); + } - PORT_Free(stringbuf); - } + noticeNumbers++; + } + + PORT_Free(stringbuf); + } } - if ( retstr == NULL ) { - if ( userNotice->displayText.len != 0 ) { - displayText = &userNotice->displayText; + if (retstr == NULL) { + if (userNotice->displayText.len != 0) { + displayText = &userNotice->displayText; - if ( displayText->len > 2 ) { - if ( displayText->data[0] == SEC_ASN1_VISIBLE_STRING ) { - headerlen = 2; - if ( displayText->data[1] & 0x80 ) { - /* multibyte length */ - headerlen += ( displayText->data[1] & 0x7f ); - } + if (displayText->len > 2) { + if (displayText->data[0] == SEC_ASN1_VISIBLE_STRING) { + headerlen = 2; + if (displayText->data[1] & 0x80) { + /* multibyte length */ + headerlen += (displayText->data[1] & 0x7f); + } - len = displayText->len - headerlen; - retstr = (char*)PORT_Alloc(len + 1); - if ( retstr != NULL ) { - PORT_Memcpy(retstr, &displayText->data[headerlen],len); - retstr[len] = '\0'; - } - } - } - } + len = displayText->len - headerlen; + retstr = (char *)PORT_Alloc(len + 1); + if (retstr != NULL) { + PORT_Memcpy(retstr, &displayText->data[headerlen], len); + retstr[len] = '\0'; + } + } + } + } } - + CERT_DestroyUserNotice(userNotice); - - return(retstr); + + return (retstr); } char * @@ -540,65 +529,63 @@ CERT_GetCertCommentString(CERTCertificate *cert) CERTPolicyQualifier **policyQualifiers, *qualifier; policyItem.data = NULL; - + rv = CERT_FindCertExtension(cert, SEC_OID_X509_CERTIFICATE_POLICIES, - &policyItem); - if ( rv != SECSuccess ) { - goto nopolicy; + &policyItem); + if (rv != SECSuccess) { + goto nopolicy; } policies = CERT_DecodeCertificatePoliciesExtension(&policyItem); - if ( policies == NULL ) { - goto nopolicy; + if (policies == NULL) { + goto nopolicy; } policyInfos = policies->policyInfos; /* search through policyInfos looking for the verisign policy */ - while (*policyInfos != NULL ) { - if ( (*policyInfos)->oid == SEC_OID_VERISIGN_USER_NOTICES ) { - policyQualifiers = (*policyInfos)->policyQualifiers; - /* search through the policy qualifiers looking for user notice */ - while ( policyQualifiers != NULL && *policyQualifiers != NULL ) { - qualifier = *policyQualifiers; - if ( qualifier->oid == SEC_OID_PKIX_USER_NOTICE_QUALIFIER ) { - retstring = - stringFromUserNotice(&qualifier->qualifierValue); - break; - } + while (*policyInfos != NULL) { + if ((*policyInfos)->oid == SEC_OID_VERISIGN_USER_NOTICES) { + policyQualifiers = (*policyInfos)->policyQualifiers; + /* search through the policy qualifiers looking for user notice */ + while (policyQualifiers != NULL && *policyQualifiers != NULL) { + qualifier = *policyQualifiers; + if (qualifier->oid == SEC_OID_PKIX_USER_NOTICE_QUALIFIER) { + retstring = + stringFromUserNotice(&qualifier->qualifierValue); + break; + } - policyQualifiers++; - } - break; - } - policyInfos++; + policyQualifiers++; + } + break; + } + policyInfos++; } nopolicy: - if ( policyItem.data != NULL ) { - PORT_Free(policyItem.data); + if (policyItem.data != NULL) { + PORT_Free(policyItem.data); } - if ( policies != NULL ) { - CERT_DestroyCertificatePoliciesExtension(policies); + if (policies != NULL) { + CERT_DestroyCertificatePoliciesExtension(policies); } - - if ( retstring == NULL ) { - retstring = CERT_FindNSStringExtension(cert, - SEC_OID_NS_CERT_EXT_COMMENT); + + if (retstring == NULL) { + retstring = + CERT_FindNSStringExtension(cert, SEC_OID_NS_CERT_EXT_COMMENT); } - - if ( retstring != NULL ) { - breakLines(retstring); + + if (retstring != NULL) { + breakLines(retstring); } - - return(retstring); + + return (retstring); } - const SEC_ASN1Template CERT_OidSeqTemplate[] = { - { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN, - offsetof(CERTOidSequence, oids), - SEC_ASN1_SUB(SEC_ObjectIDTemplate) } + { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN, offsetof(CERTOidSequence, oids), + SEC_ASN1_SUB(SEC_ObjectIDTemplate) } }; CERTOidSequence * @@ -608,53 +595,53 @@ CERT_DecodeOidSequence(const SECItem *seqItem) SECStatus rv; CERTOidSequence *oidSeq; SECItem newSeqItem; - + /* make a new arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( !arena ) { - goto loser; + + if (!arena) { + goto loser; } /* allocate the userNotice structure */ - oidSeq = (CERTOidSequence *)PORT_ArenaZAlloc(arena, - sizeof(CERTOidSequence)); - - if ( oidSeq == NULL ) { - goto loser; + oidSeq = + (CERTOidSequence *)PORT_ArenaZAlloc(arena, sizeof(CERTOidSequence)); + + if (oidSeq == NULL) { + goto loser; } - + oidSeq->arena = arena; /* 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, &newSeqItem, seqItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* decode the user notice */ - rv = SEC_QuickDERDecodeItem(arena, oidSeq, CERT_OidSeqTemplate, &newSeqItem); + rv = + SEC_QuickDERDecodeItem(arena, oidSeq, CERT_OidSeqTemplate, &newSeqItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - return(oidSeq); - + return (oidSeq); + loser: if (arena) { PORT_FreeArena(arena, PR_FALSE); } - return(NULL); + return (NULL); } - void CERT_DestroyOidSequence(CERTOidSequence *oidSeq) { - if ( oidSeq != NULL ) { - PORT_FreeArena(oidSeq->arena, PR_FALSE); + if (oidSeq != NULL) { + PORT_FreeArena(oidSeq->arena, PR_FALSE); } return; } @@ -669,29 +656,29 @@ CERT_GovtApprovedBitSet(CERTCertificate *cert) SECItem **oids; SECItem *oid; SECOidTag oidTag; - + extItem.data = NULL; rv = CERT_FindCertExtension(cert, SEC_OID_X509_EXT_KEY_USAGE, &extItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } oidSeq = CERT_DecodeOidSequence(&extItem); - if ( oidSeq == NULL ) { - goto loser; + if (oidSeq == NULL) { + goto loser; } oids = oidSeq->oids; - while ( oids != NULL && *oids != NULL ) { - oid = *oids; - - oidTag = SECOID_FindOIDTag(oid); - - if ( oidTag == SEC_OID_NS_KEY_USAGE_GOVT_APPROVED ) { - goto success; - } - - oids++; + while (oids != NULL && *oids != NULL) { + oid = *oids; + + oidTag = SECOID_FindOIDTag(oid); + + if (oidTag == SEC_OID_NS_KEY_USAGE_GOVT_APPROVED) { + goto success; + } + + oids++; } loser: @@ -700,16 +687,15 @@ loser: success: ret = PR_TRUE; done: - if ( oidSeq != NULL ) { - CERT_DestroyOidSequence(oidSeq); + if (oidSeq != NULL) { + CERT_DestroyOidSequence(oidSeq); } if (extItem.data != NULL) { - PORT_Free(extItem.data); + PORT_Free(extItem.data); } - return(ret); + return (ret); } - SECStatus CERT_EncodePolicyConstraintsExtension(PLArenaPool *arena, CERTCertificatePolicyConstraints *constr, @@ -719,14 +705,14 @@ CERT_EncodePolicyConstraintsExtension(PLArenaPool *arena, PORT_Assert(constr != NULL && dest != NULL); if (constr == NULL || dest == NULL) { - return SECFailure; + return SECFailure; } - if (SEC_ASN1EncodeItem (arena, dest, constr, - CERT_PolicyConstraintsTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, dest, constr, + CERT_PolicyConstraintsTemplate) == NULL) { + rv = SECFailure; } - return(rv); + return (rv); } SECStatus @@ -738,75 +724,69 @@ CERT_EncodePolicyMappingExtension(PLArenaPool *arena, PORT_Assert(mapping != NULL && dest != NULL); if (mapping == NULL || dest == NULL) { - return SECFailure; + return SECFailure; } - if (SEC_ASN1EncodeItem (arena, dest, mapping, - CERT_PolicyMappingsTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, dest, mapping, CERT_PolicyMappingsTemplate) == + NULL) { + rv = SECFailure; } - return(rv); + return (rv); } - - SECStatus -CERT_EncodeCertPoliciesExtension(PLArenaPool *arena, - CERTPolicyInfo **info, +CERT_EncodeCertPoliciesExtension(PLArenaPool *arena, CERTPolicyInfo **info, SECItem *dest) { SECStatus rv = SECSuccess; PORT_Assert(info != NULL && dest != NULL); if (info == NULL || dest == NULL) { - return SECFailure; + return SECFailure; } - if (SEC_ASN1EncodeItem (arena, dest, info, - CERT_CertificatePoliciesTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, dest, info, + CERT_CertificatePoliciesTemplate) == NULL) { + rv = SECFailure; } - return(rv); + return (rv); } SECStatus -CERT_EncodeUserNotice(PLArenaPool *arena, - CERTUserNotice *notice, - SECItem *dest) +CERT_EncodeUserNotice(PLArenaPool *arena, CERTUserNotice *notice, SECItem *dest) { SECStatus rv = SECSuccess; PORT_Assert(notice != NULL && dest != NULL); if (notice == NULL || dest == NULL) { - return SECFailure; + return SECFailure; } - if (SEC_ASN1EncodeItem(arena, dest, - notice, CERT_UserNoticeTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, dest, notice, CERT_UserNoticeTemplate) == + NULL) { + rv = SECFailure; } - return(rv); + return (rv); } SECStatus -CERT_EncodeNoticeReference(PLArenaPool *arena, - CERTNoticeReference *reference, +CERT_EncodeNoticeReference(PLArenaPool *arena, CERTNoticeReference *reference, SECItem *dest) { SECStatus rv = SECSuccess; - + PORT_Assert(reference != NULL && dest != NULL); if (reference == NULL || dest == NULL) { - return SECFailure; + return SECFailure; } - if (SEC_ASN1EncodeItem (arena, dest, reference, - CERT_NoticeReferenceTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, dest, reference, + CERT_NoticeReferenceTemplate) == NULL) { + rv = SECFailure; } - return(rv); + return (rv); } SECStatus @@ -818,12 +798,12 @@ CERT_EncodeInhibitAnyExtension(PLArenaPool *arena, PORT_Assert(certInhibitAny != NULL && dest != NULL); if (certInhibitAny == NULL || dest == NULL) { - return SECFailure; + return SECFailure; } - if (SEC_ASN1EncodeItem (arena, dest, certInhibitAny, - CERT_InhibitAnyTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, dest, certInhibitAny, + CERT_InhibitAnyTemplate) == NULL) { + rv = SECFailure; } - return(rv); + return (rv); } diff --git a/security/nss/lib/certdb/secname.c b/security/nss/lib/certdb/secname.c index 88a0cf75ef3c..fad76adf1329 100644 --- a/security/nss/lib/certdb/secname.c +++ b/security/nss/lib/certdb/secname.c @@ -4,7 +4,7 @@ #include "cert.h" #include "secoid.h" -#include "secder.h" /* XXX remove this when remove the DERTemplates */ +#include "secder.h" /* XXX remove this when remove the DERTemplates */ #include "secasn1.h" #include "secitem.h" #include @@ -12,29 +12,25 @@ #include "certi.h" static const SEC_ASN1Template cert_AVATemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTAVA) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTAVA,type), }, - { SEC_ASN1_ANY, - offsetof(CERTAVA,value), }, - { 0, } + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTAVA) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTAVA, type) }, + { SEC_ASN1_ANY, offsetof(CERTAVA, value) }, + { 0 } }; const SEC_ASN1Template CERT_RDNTemplate[] = { - { SEC_ASN1_SET_OF, - offsetof(CERTRDN,avas), cert_AVATemplate, sizeof(CERTRDN) } + { SEC_ASN1_SET_OF, offsetof(CERTRDN, avas), cert_AVATemplate, + sizeof(CERTRDN) } }; - static int CountArray(void **array) { int count = 0; if (array) { - while (*array++) { - count++; - } + while (*array++) { + count++; + } } return count; } @@ -49,36 +45,37 @@ AddToArray(PLArenaPool *arena, void **array, void *element) count = 0; ap = array; if (ap) { - while (*ap++) { - count++; - } + while (*ap++) { + count++; + } } if (array) { - array = (void**) PORT_ArenaGrow(arena, array, - (count + 1) * sizeof(void *), - (count + 2) * sizeof(void *)); - } else { - array = (void**) PORT_ArenaAlloc(arena, (count + 2) * sizeof(void *)); + array = + (void **)PORT_ArenaGrow(arena, array, (count + 1) * sizeof(void *), + (count + 2) * sizeof(void *)); + } + else { + array = (void **)PORT_ArenaAlloc(arena, (count + 2) * sizeof(void *)); } if (array) { - array[count] = element; - array[count+1] = 0; + array[count] = element; + array[count + 1] = 0; } return array; } - SECOidTag CERT_GetAVATag(CERTAVA *ava) { SECOidData *oid; - if (!ava->type.data) return (SECOidTag)-1; + if (!ava->type.data) + return (SECOidTag)-1; oid = SECOID_FindOID(&ava->type); - - if ( oid ) { - return(oid->offset); + + if (oid) { + return (oid->offset); } return (SECOidTag)-1; } @@ -89,25 +86,25 @@ SetupAVAType(PLArenaPool *arena, SECOidTag type, SECItem *it, unsigned *maxLenp) unsigned char *oid; unsigned oidLen; unsigned char *cp; - int maxLen; + int maxLen; SECOidData *oidrec; oidrec = SECOID_FindOIDByTag(type); if (oidrec == NULL) - return SECFailure; + return SECFailure; oid = oidrec->oid.data; oidLen = oidrec->oid.len; maxLen = cert_AVAOidTagToMaxLen(type); if (maxLen < 0) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } - it->data = cp = (unsigned char*) PORT_ArenaAlloc(arena, oidLen); + it->data = cp = (unsigned char *)PORT_ArenaAlloc(arena, oidLen); if (cp == NULL) { - return SECFailure; + return SECFailure; } it->len = oidLen; PORT_Memcpy(cp, oid, oidLen); @@ -123,65 +120,66 @@ SetupAVAValue(PLArenaPool *arena, int valueType, const SECItem *in, unsigned valueLen, valueLenLen, total; unsigned ucs4Len = 0, ucs4MaxLen; - value = in->data; + value = in->data; valueLen = in->len; switch (valueType) { - case SEC_ASN1_PRINTABLE_STRING: - case SEC_ASN1_IA5_STRING: - case SEC_ASN1_T61_STRING: - case SEC_ASN1_UTF8_STRING: /* no conversion required */ - break; - case SEC_ASN1_UNIVERSAL_STRING: - ucs4MaxLen = valueLen * 6; - ucs4Val = (PRUint8 *)PORT_ArenaZAlloc(arena, ucs4MaxLen); - if(!ucs4Val || !PORT_UCS4_UTF8Conversion(PR_TRUE, value, valueLen, - ucs4Val, ucs4MaxLen, &ucs4Len)) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - value = ucs4Val; - valueLen = ucs4Len; - maxLen *= 4; - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + case SEC_ASN1_PRINTABLE_STRING: + case SEC_ASN1_IA5_STRING: + case SEC_ASN1_T61_STRING: + case SEC_ASN1_UTF8_STRING: /* no conversion required */ + break; + case SEC_ASN1_UNIVERSAL_STRING: + ucs4MaxLen = valueLen * 6; + ucs4Val = (PRUint8 *)PORT_ArenaZAlloc(arena, ucs4MaxLen); + if (!ucs4Val || + !PORT_UCS4_UTF8Conversion(PR_TRUE, value, valueLen, ucs4Val, + ucs4MaxLen, &ucs4Len)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + value = ucs4Val; + valueLen = ucs4Len; + maxLen *= 4; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } if (valueLen > maxLen) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } valueLenLen = DER_LengthLength(valueLen); total = 1 + valueLenLen + valueLen; - cp = (PRUint8*)PORT_ArenaAlloc(arena, total); + cp = (PRUint8 *)PORT_ArenaAlloc(arena, total); if (!cp) { - return SECFailure; + return SECFailure; } out->data = cp; - out->len = total; + out->len = total; cp = (PRUint8 *)DER_StoreHeader(cp, valueType, valueLen); PORT_Memcpy(cp, value, valueLen); return SECSuccess; } CERTAVA * -CERT_CreateAVAFromRaw(PLArenaPool *pool, const SECItem * OID, - const SECItem * value) +CERT_CreateAVAFromRaw(PLArenaPool *pool, const SECItem *OID, + const SECItem *value) { CERTAVA *ava; int rv; ava = PORT_ArenaZNew(pool, CERTAVA); if (ava) { - rv = SECITEM_CopyItem(pool, &ava->type, OID); - if (rv) - return NULL; + rv = SECITEM_CopyItem(pool, &ava->type, OID); + if (rv) + return NULL; - rv = SECITEM_CopyItem(pool, &ava->value, value); - if (rv) - return NULL; + rv = SECITEM_CopyItem(pool, &ava->value, value); + if (rv) + return NULL; } return ava; } @@ -194,18 +192,18 @@ CERT_CreateAVAFromSECItem(PLArenaPool *arena, SECOidTag kind, int valueType, int rv; unsigned maxLen; - ava = (CERTAVA*) PORT_ArenaZAlloc(arena, sizeof(CERTAVA)); + ava = (CERTAVA *)PORT_ArenaZAlloc(arena, sizeof(CERTAVA)); if (ava) { - rv = SetupAVAType(arena, kind, &ava->type, &maxLen); - if (rv) { - /* Illegal AVA type */ - return NULL; - } - rv = SetupAVAValue(arena, valueType, value, &ava->value, maxLen); - if (rv) { - /* Illegal value type */ - return NULL; - } + rv = SetupAVAType(arena, kind, &ava->type, &maxLen); + if (rv) { + /* Illegal AVA type */ + return NULL; + } + rv = SetupAVAValue(arena, valueType, value, &ava->value, maxLen); + if (rv) { + /* Illegal value type */ + return NULL; + } } return ava; } @@ -216,7 +214,7 @@ CERT_CreateAVA(PLArenaPool *arena, SECOidTag kind, int valueType, char *value) SECItem item = { siBuffer, NULL, 0 }; item.data = (PRUint8 *)value; - item.len = PORT_Strlen(value); + item.len = PORT_Strlen(value); return CERT_CreateAVAFromSECItem(arena, kind, valueType, &item); } @@ -227,16 +225,18 @@ CERT_CopyAVA(PLArenaPool *arena, CERTAVA *from) CERTAVA *ava; int rv; - ava = (CERTAVA*) PORT_ArenaZAlloc(arena, sizeof(CERTAVA)); + ava = (CERTAVA *)PORT_ArenaZAlloc(arena, sizeof(CERTAVA)); if (ava) { - rv = SECITEM_CopyItem(arena, &ava->type, &from->type); - if (rv) goto loser; - rv = SECITEM_CopyItem(arena, &ava->value, &from->value); - if (rv) goto loser; + rv = SECITEM_CopyItem(arena, &ava->type, &from->type); + if (rv) + goto loser; + rv = SECITEM_CopyItem(arena, &ava->value, &from->value); + if (rv) + goto loser; } return ava; - loser: +loser: return 0; } @@ -249,34 +249,34 @@ CERT_CreateRDN(PLArenaPool *arena, CERTAVA *ava0, ...) unsigned count; CERTAVA **avap; - rdn = (CERTRDN*) PORT_ArenaAlloc(arena, sizeof(CERTRDN)); + rdn = (CERTRDN *)PORT_ArenaAlloc(arena, sizeof(CERTRDN)); if (rdn) { - /* Count number of avas going into the rdn */ - count = 0; - if (ava0) { - count++; - va_start(ap, ava0); - while ((ava = va_arg(ap, CERTAVA*)) != 0) { - count++; - } - va_end(ap); - } + /* Count number of avas going into the rdn */ + count = 0; + if (ava0) { + count++; + va_start(ap, ava0); + while ((ava = va_arg(ap, CERTAVA *)) != 0) { + count++; + } + va_end(ap); + } - /* Now fill in the pointers */ - rdn->avas = avap = - (CERTAVA**) PORT_ArenaAlloc( arena, (count + 1)*sizeof(CERTAVA*)); - if (!avap) { - return 0; - } - if (ava0) { - *avap++ = ava0; - va_start(ap, ava0); - while ((ava = va_arg(ap, CERTAVA*)) != 0) { - *avap++ = ava; - } - va_end(ap); - } - *avap++ = 0; + /* Now fill in the pointers */ + rdn->avas = avap = + (CERTAVA **)PORT_ArenaAlloc(arena, (count + 1) * sizeof(CERTAVA *)); + if (!avap) { + return 0; + } + if (ava0) { + *avap++ = ava0; + va_start(ap, ava0); + while ((ava = va_arg(ap, CERTAVA *)) != 0) { + *avap++ = ava; + } + va_end(ap); + } + *avap++ = 0; } return rdn; } @@ -284,7 +284,7 @@ CERT_CreateRDN(PLArenaPool *arena, CERTAVA *ava0, ...) SECStatus CERT_AddAVA(PLArenaPool *arena, CERTRDN *rdn, CERTAVA *ava) { - rdn->avas = (CERTAVA**) AddToArray(arena, (void**) rdn->avas, ava); + rdn->avas = (CERTAVA **)AddToArray(arena, (void **)rdn->avas, ava); return rdn->avas ? SECSuccess : SECFailure; } @@ -297,20 +297,20 @@ CERT_CopyRDN(PLArenaPool *arena, CERTRDN *to, CERTRDN *from) /* Copy each ava from from */ avas = from->avas; if (avas) { - if (avas[0] == NULL) { - rv = CERT_AddAVA(arena, to, NULL); - return rv; - } - while ((fava = *avas++) != 0) { - tava = CERT_CopyAVA(arena, fava); - if (!tava) { - rv = SECFailure; - break; - } - rv = CERT_AddAVA(arena, to, tava); - if (rv != SECSuccess) - break; - } + if (avas[0] == NULL) { + rv = CERT_AddAVA(arena, to, NULL); + return rv; + } + while ((fava = *avas++) != 0) { + tava = CERT_CopyAVA(arena, fava); + if (!tava) { + rv = SECFailure; + break; + } + rv = CERT_AddAVA(arena, to, tava); + if (rv != SECSuccess) + break; + } } return rv; } @@ -318,8 +318,8 @@ CERT_CopyRDN(PLArenaPool *arena, CERTRDN *to, CERTRDN *from) /************************************************************************/ const SEC_ASN1Template CERT_NameTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(CERTName,rdns), CERT_RDNTemplate, sizeof(CERTName) } + { SEC_ASN1_SEQUENCE_OF, offsetof(CERTName, rdns), CERT_RDNTemplate, + sizeof(CERTName) } }; SEC_ASN1_CHOOSER_IMPLEMENT(CERT_NameTemplate) @@ -333,71 +333,72 @@ CERT_CreateName(CERTRDN *rdn0, ...) unsigned count; CERTRDN **rdnp; PLArenaPool *arena; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - return(0); + if (!arena) { + return (0); } - - name = (CERTName*) PORT_ArenaAlloc(arena, sizeof(CERTName)); + + name = (CERTName *)PORT_ArenaAlloc(arena, sizeof(CERTName)); if (name) { - name->arena = arena; - - /* Count number of RDNs going into the Name */ - if (!rdn0) { - count = 0; - } else { - count = 1; - va_start(ap, rdn0); - while ((rdn = va_arg(ap, CERTRDN*)) != 0) { - count++; - } - va_end(ap); - } + name->arena = arena; - /* Allocate space (including space for terminal null ptr) */ - name->rdns = rdnp = - (CERTRDN**) PORT_ArenaAlloc(arena, (count + 1) * sizeof(CERTRDN*)); - if (!name->rdns) { - goto loser; - } + /* Count number of RDNs going into the Name */ + if (!rdn0) { + count = 0; + } + else { + count = 1; + va_start(ap, rdn0); + while ((rdn = va_arg(ap, CERTRDN *)) != 0) { + count++; + } + va_end(ap); + } - /* Now fill in the pointers */ - if (count > 0) { - *rdnp++ = rdn0; - va_start(ap, rdn0); - while ((rdn = va_arg(ap, CERTRDN*)) != 0) { - *rdnp++ = rdn; - } - va_end(ap); - } + /* Allocate space (including space for terminal null ptr) */ + name->rdns = rdnp = + (CERTRDN **)PORT_ArenaAlloc(arena, (count + 1) * sizeof(CERTRDN *)); + if (!name->rdns) { + goto loser; + } - /* null terminate the list */ - *rdnp++ = 0; + /* Now fill in the pointers */ + if (count > 0) { + *rdnp++ = rdn0; + va_start(ap, rdn0); + while ((rdn = va_arg(ap, CERTRDN *)) != 0) { + *rdnp++ = rdn; + } + va_end(ap); + } + + /* null terminate the list */ + *rdnp++ = 0; } return name; loser: PORT_FreeArena(arena, PR_FALSE); - return(0); + return (0); } void CERT_DestroyName(CERTName *name) { - if (name) - { + if (name) { PLArenaPool *arena = name->arena; name->rdns = NULL; - name->arena = NULL; - if (arena) PORT_FreeArena(arena, PR_FALSE); + name->arena = NULL; + if (arena) + PORT_FreeArena(arena, PR_FALSE); } } SECStatus CERT_AddRDN(CERTName *name, CERTRDN *rdn) { - name->rdns = (CERTRDN**) AddToArray(name->arena, (void**) name->rdns, rdn); + name->rdns = (CERTRDN **)AddToArray(name->arena, (void **)name->rdns, rdn); return name->rdns ? SECSuccess : SECFailure; } @@ -408,8 +409,8 @@ CERT_CopyName(PLArenaPool *arena, CERTName *to, const CERTName *from) SECStatus rv = SECSuccess; if (!to || !from) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } CERT_DestroyName(to); @@ -418,23 +419,23 @@ CERT_CopyName(PLArenaPool *arena, CERTName *to, const CERTName *from) /* Copy each rdn from from */ rdns = from->rdns; if (rdns) { - if (rdns[0] == NULL) { - rv = CERT_AddRDN(to, NULL); - return rv; - } - while ((frdn = *rdns++) != NULL) { - trdn = CERT_CreateRDN(arena, NULL); - if (!trdn) { - rv = SECFailure; - break; - } - rv = CERT_CopyRDN(arena, trdn, frdn); - if (rv != SECSuccess) - break; - rv = CERT_AddRDN(to, trdn); - if (rv != SECSuccess) - break; - } + if (rdns[0] == NULL) { + rv = CERT_AddRDN(to, NULL); + return rv; + } + while ((frdn = *rdns++) != NULL) { + trdn = CERT_CreateRDN(arena, NULL); + if (!trdn) { + rv = SECFailure; + break; + } + rv = CERT_CopyRDN(arena, trdn, frdn); + if (rv != SECSuccess) + break; + rv = CERT_AddRDN(to, trdn); + if (rv != SECSuccess) + break; + } } return rv; } @@ -442,34 +443,36 @@ CERT_CopyName(PLArenaPool *arena, CERTName *to, const CERTName *from) /************************************************************************/ static void -canonicalize(SECItem * foo) +canonicalize(SECItem *foo) { int ch, lastch, len, src, dest; /* strip trailing whitespace. */ len = foo->len; - while (len > 0 && ((ch = foo->data[len - 1]) == ' ' || - ch == '\t' || ch == '\r' || ch == '\n')) { - len--; + while (len > 0 && ((ch = foo->data[len - 1]) == ' ' || ch == '\t' || + ch == '\r' || ch == '\n')) { + len--; } src = 0; /* strip leading whitespace. */ - while (src < len && ((ch = foo->data[src]) == ' ' || - ch == '\t' || ch == '\r' || ch == '\n')) { - src++; + while (src < len && ((ch = foo->data[src]) == ' ' || ch == '\t' || + ch == '\r' || ch == '\n')) { + src++; } - dest = 0; lastch = ' '; + dest = 0; + lastch = ' '; while (src < len) { ch = foo->data[src++]; - if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') { - ch = ' '; - if (ch == lastch) - continue; - } else if (ch >= 'A' && ch <= 'Z') { - ch |= 0x20; /* downshift */ - } - foo->data[dest++] = lastch = ch; + if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') { + ch = ' '; + if (ch == lastch) + continue; + } + else if (ch >= 'A' && ch <= 'Z') { + ch |= 0x20; /* downshift */ + } + foo->data[dest++] = lastch = ch; } foo->len = dest; } @@ -479,14 +482,13 @@ SECComparison CERT_CompareDERPrintableStrings(const SECItem *a, const SECItem *b) { SECComparison rv = SECLessThan; - SECItem * aVal = CERT_DecodeAVAValue(a); - SECItem * bVal = CERT_DecodeAVAValue(b); + SECItem *aVal = CERT_DecodeAVAValue(a); + SECItem *bVal = CERT_DecodeAVAValue(b); - if (aVal && aVal->len && aVal->data && - bVal && bVal->len && bVal->data) { - canonicalize(aVal); - canonicalize(bVal); - rv = SECITEM_CompareItem(aVal, bVal); + if (aVal && aVal->len && aVal->data && bVal && bVal->len && bVal->data) { + canonicalize(aVal); + canonicalize(bVal); + rv = SECITEM_CompareItem(aVal, bVal); } SECITEM_FreeItem(aVal, PR_TRUE); SECITEM_FreeItem(bVal, PR_TRUE); @@ -500,30 +502,31 @@ CERT_CompareAVA(const CERTAVA *a, const CERTAVA *b) rv = SECITEM_CompareItem(&a->type, &b->type); if (SECEqual != rv) - return rv; /* Attribute types don't match. */ + return rv; /* Attribute types don't match. */ /* Let's be optimistic. Maybe the values will just compare equal. */ rv = SECITEM_CompareItem(&a->value, &b->value); if (SECEqual == rv) - return rv; /* values compared exactly. */ + return rv; /* values compared exactly. */ if (a->value.len && a->value.data && b->value.len && b->value.data) { - /* Here, the values did not match. - ** If the values had different encodings, convert them to the same - ** encoding and compare that way. - */ - if (a->value.data[0] != b->value.data[0]) { - /* encodings differ. Convert both to UTF-8 and compare. */ - SECItem * aVal = CERT_DecodeAVAValue(&a->value); - SECItem * bVal = CERT_DecodeAVAValue(&b->value); - if (aVal && aVal->len && aVal->data && - bVal && bVal->len && bVal->data) { - rv = SECITEM_CompareItem(aVal, bVal); - } - SECITEM_FreeItem(aVal, PR_TRUE); - SECITEM_FreeItem(bVal, PR_TRUE); - } else if (a->value.data[0] == 0x13) { /* both are printable strings. */ - /* printable strings */ - rv = CERT_CompareDERPrintableStrings(&a->value, &b->value); - } + /* Here, the values did not match. + ** If the values had different encodings, convert them to the same + ** encoding and compare that way. + */ + if (a->value.data[0] != b->value.data[0]) { + /* encodings differ. Convert both to UTF-8 and compare. */ + SECItem *aVal = CERT_DecodeAVAValue(&a->value); + SECItem *bVal = CERT_DecodeAVAValue(&b->value); + if (aVal && aVal->len && aVal->data && bVal && bVal->len && + bVal->data) { + rv = SECITEM_CompareItem(aVal, bVal); + } + SECITEM_FreeItem(aVal, PR_TRUE); + SECITEM_FreeItem(bVal, PR_TRUE); + } + else if (a->value.data[0] == 0x13) { /* both are printable strings. */ + /* printable strings */ + rv = CERT_CompareDERPrintableStrings(&a->value, &b->value); + } } return rv; } @@ -543,23 +546,25 @@ CERT_CompareRDN(const CERTRDN *a, const CERTRDN *b) ** Make sure array of ava's are the same length. If not, then we are ** not equal */ - ac = CountArray((void**) aavas); - bc = CountArray((void**) bavas); - if (ac < bc) return SECLessThan; - if (ac > bc) return SECGreaterThan; + ac = CountArray((void **)aavas); + bc = CountArray((void **)bavas); + if (ac < bc) + return SECLessThan; + if (ac > bc) + return SECGreaterThan; while (NULL != (aava = *aavas++)) { - for (bavas = b->avas; NULL != (bava = *bavas++); ) { - rv = SECITEM_CompareItem(&aava->type, &bava->type); - if (SECEqual == rv) { - rv = CERT_CompareAVA(aava, bava); - if (SECEqual != rv) - return rv; - break; - } - } - if (!bava) /* didn't find a match */ - return SECGreaterThan; + for (bavas = b->avas; NULL != (bava = *bavas++);) { + rv = SECITEM_CompareItem(&aava->type, &bava->type); + if (SECEqual == rv) { + rv = CERT_CompareAVA(aava, bava); + if (SECEqual != rv) + return rv; + break; + } + } + if (!bava) /* didn't find a match */ + return SECGreaterThan; } return rv; } @@ -579,19 +584,22 @@ CERT_CompareName(const CERTName *a, const CERTName *b) ** Make sure array of rdn's are the same length. If not, then we are ** not equal */ - ac = CountArray((void**) ardns); - bc = CountArray((void**) brdns); - if (ac < bc) return SECLessThan; - if (ac > bc) return SECGreaterThan; + ac = CountArray((void **)ardns); + bc = CountArray((void **)brdns); + if (ac < bc) + return SECLessThan; + if (ac > bc) + return SECGreaterThan; for (;;) { - ardn = *ardns++; - brdn = *brdns++; - if (!ardn) { - break; - } - rv = CERT_CompareRDN(ardn, brdn); - if (rv) return rv; + ardn = *ardns++; + brdn = *brdns++; + if (!ardn) { + break; + } + rv = CERT_CompareRDN(ardn, brdn); + if (rv) + return rv; } return rv; } @@ -600,47 +608,47 @@ CERT_CompareName(const CERTName *a, const CERTName *b) SECItem * CERT_DecodeAVAValue(const SECItem *derAVAValue) { - SECItem *retItem; - const SEC_ASN1Template *theTemplate = NULL; - enum { conv_none, conv_ucs4, conv_ucs2, conv_iso88591 } convert = conv_none; - SECItem avaValue = {siBuffer, 0}; - PLArenaPool *newarena = NULL; + SECItem *retItem; + const SEC_ASN1Template *theTemplate = NULL; + enum { conv_none, conv_ucs4, conv_ucs2, conv_iso88591 } convert = conv_none; + SECItem avaValue = { siBuffer, 0 }; + PLArenaPool *newarena = NULL; if (!derAVAValue || !derAVAValue->len || !derAVAValue->data) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } - switch(derAVAValue->data[0]) { - case SEC_ASN1_UNIVERSAL_STRING: - convert = conv_ucs4; - theTemplate = SEC_ASN1_GET(SEC_UniversalStringTemplate); - break; - case SEC_ASN1_IA5_STRING: - theTemplate = SEC_ASN1_GET(SEC_IA5StringTemplate); - break; - case SEC_ASN1_PRINTABLE_STRING: - theTemplate = SEC_ASN1_GET(SEC_PrintableStringTemplate); - break; - case SEC_ASN1_T61_STRING: - /* - * Per common practice, we're not decoding actual T.61, but instead - * treating T61-labeled strings as containing ISO-8859-1. - */ - convert = conv_iso88591; - theTemplate = SEC_ASN1_GET(SEC_T61StringTemplate); - break; - case SEC_ASN1_BMP_STRING: - convert = conv_ucs2; - theTemplate = SEC_ASN1_GET(SEC_BMPStringTemplate); - break; - case SEC_ASN1_UTF8_STRING: - /* No conversion needed ! */ - theTemplate = SEC_ASN1_GET(SEC_UTF8StringTemplate); - break; - default: - PORT_SetError(SEC_ERROR_INVALID_AVA); - return NULL; + switch (derAVAValue->data[0]) { + case SEC_ASN1_UNIVERSAL_STRING: + convert = conv_ucs4; + theTemplate = SEC_ASN1_GET(SEC_UniversalStringTemplate); + break; + case SEC_ASN1_IA5_STRING: + theTemplate = SEC_ASN1_GET(SEC_IA5StringTemplate); + break; + case SEC_ASN1_PRINTABLE_STRING: + theTemplate = SEC_ASN1_GET(SEC_PrintableStringTemplate); + break; + case SEC_ASN1_T61_STRING: + /* + * Per common practice, we're not decoding actual T.61, but instead + * treating T61-labeled strings as containing ISO-8859-1. + */ + convert = conv_iso88591; + theTemplate = SEC_ASN1_GET(SEC_T61StringTemplate); + break; + case SEC_ASN1_BMP_STRING: + convert = conv_ucs2; + theTemplate = SEC_ASN1_GET(SEC_BMPStringTemplate); + break; + case SEC_ASN1_UTF8_STRING: + /* No conversion needed ! */ + theTemplate = SEC_ASN1_GET(SEC_UTF8StringTemplate); + break; + default: + PORT_SetError(SEC_ERROR_INVALID_AVA); + return NULL; } PORT_Memset(&avaValue, 0, sizeof(SECItem)); @@ -648,51 +656,54 @@ CERT_DecodeAVAValue(const SECItem *derAVAValue) if (!newarena) { return NULL; } - if(SEC_QuickDERDecodeItem(newarena, &avaValue, theTemplate, derAVAValue) - != SECSuccess) { - PORT_FreeArena(newarena, PR_FALSE); - return NULL; + if (SEC_QuickDERDecodeItem(newarena, &avaValue, theTemplate, derAVAValue) != + SECSuccess) { + PORT_FreeArena(newarena, PR_FALSE); + return NULL; } if (convert != conv_none) { - unsigned int utf8ValLen = avaValue.len * 3; - unsigned char *utf8Val = (unsigned char*) - PORT_ArenaZAlloc(newarena, utf8ValLen); + unsigned int utf8ValLen = avaValue.len * 3; + unsigned char *utf8Val = + (unsigned char *)PORT_ArenaZAlloc(newarena, utf8ValLen); switch (convert) { - case conv_ucs4: - if(avaValue.len % 4 != 0 || - !PORT_UCS4_UTF8Conversion(PR_FALSE, avaValue.data, avaValue.len, - utf8Val, utf8ValLen, &utf8ValLen)) { - PORT_FreeArena(newarena, PR_FALSE); - PORT_SetError(SEC_ERROR_INVALID_AVA); - return NULL; - } - break; - case conv_ucs2: - if(avaValue.len % 2 != 0 || - !PORT_UCS2_UTF8Conversion(PR_FALSE, avaValue.data, avaValue.len, - utf8Val, utf8ValLen, &utf8ValLen)) { - PORT_FreeArena(newarena, PR_FALSE); - PORT_SetError(SEC_ERROR_INVALID_AVA); - return NULL; - } - break; - case conv_iso88591: - if(!PORT_ISO88591_UTF8Conversion(avaValue.data, avaValue.len, - utf8Val, utf8ValLen, &utf8ValLen)) { - PORT_FreeArena(newarena, PR_FALSE); - PORT_SetError(SEC_ERROR_INVALID_AVA); - return NULL; - } - break; - case conv_none: - PORT_Assert(0); /* not reached */ - break; - } - - avaValue.data = utf8Val; - avaValue.len = utf8ValLen; + case conv_ucs4: + if (avaValue.len % 4 != 0 || + !PORT_UCS4_UTF8Conversion(PR_FALSE, avaValue.data, + avaValue.len, utf8Val, utf8ValLen, + &utf8ValLen)) { + PORT_FreeArena(newarena, PR_FALSE); + PORT_SetError(SEC_ERROR_INVALID_AVA); + return NULL; + } + break; + case conv_ucs2: + if (avaValue.len % 2 != 0 || + !PORT_UCS2_UTF8Conversion(PR_FALSE, avaValue.data, + avaValue.len, utf8Val, utf8ValLen, + &utf8ValLen)) { + PORT_FreeArena(newarena, PR_FALSE); + PORT_SetError(SEC_ERROR_INVALID_AVA); + return NULL; + } + break; + case conv_iso88591: + if (!PORT_ISO88591_UTF8Conversion(avaValue.data, avaValue.len, + utf8Val, utf8ValLen, + &utf8ValLen)) { + PORT_FreeArena(newarena, PR_FALSE); + PORT_SetError(SEC_ERROR_INVALID_AVA); + return NULL; + } + break; + case conv_none: + PORT_Assert(0); /* not reached */ + break; + } + + avaValue.data = utf8Val; + avaValue.len = utf8ValLen; } retItem = SECITEM_DupItem(&avaValue); diff --git a/security/nss/lib/certdb/stanpcertdb.c b/security/nss/lib/certdb/stanpcertdb.c index 1e1e06c230dd..20a4fdfdc6ea 100644 --- a/security/nss/lib/certdb/stanpcertdb.c +++ b/security/nss/lib/certdb/stanpcertdb.c @@ -33,18 +33,18 @@ PRBool SEC_CertNicknameConflict(const char *nickname, const SECItem *derSubject, - CERTCertDBHandle *handle) + CERTCertDBHandle *handle) { CERTCertificate *cert; PRBool conflict = PR_FALSE; - cert=CERT_FindCertByNickname(handle, nickname); + cert = CERT_FindCertByNickname(handle, nickname); if (!cert) { - return conflict; + return conflict; } - conflict = !SECITEM_ItemsAreEqual(derSubject,&cert->derSubject); + conflict = !SECITEM_ItemsAreEqual(derSubject, &cert->derSubject); CERT_DestroyCertificate(cert); return conflict; } @@ -64,15 +64,15 @@ SEC_DeletePermCertificate(CERTCertificate *cert) certTrust = nssTrust_GetCERTCertTrustForCert(c, cert); if (certTrust) { - NSSTrust *nssTrust = nssTrustDomain_FindTrustForCertificate(td, c); - if (nssTrust) { - nssrv = STAN_DeleteCertTrustMatchingSlot(c); - if (nssrv != PR_SUCCESS) { - CERT_MapStanError(); - } - /* This call always returns PR_SUCCESS! */ - (void) nssTrust_Destroy(nssTrust); - } + NSSTrust *nssTrust = nssTrustDomain_FindTrustForCertificate(td, c); + if (nssTrust) { + nssrv = STAN_DeleteCertTrustMatchingSlot(c); + if (nssrv != PR_SUCCESS) { + CERT_MapStanError(); + } + /* This call always returns PR_SUCCESS! */ + (void)nssTrust_Destroy(nssTrust); + } } /* get rid of the token instances */ @@ -91,14 +91,15 @@ CERT_GetCertTrust(const CERTCertificate *cert, CERTCertTrust *trust) { SECStatus rv; CERT_LockCertTrust(cert); - if ( cert->trust == NULL ) { - rv = SECFailure; - } else { - *trust = *cert->trust; - rv = SECSuccess; + if (cert->trust == NULL) { + rv = SECFailure; + } + else { + *trust = *cert->trust; + rv = SECSuccess; } CERT_UnlockCertTrust(cert); - return(rv); + return (rv); } extern const NSSError NSS_ERROR_NO_ERROR; @@ -141,14 +142,11 @@ extern const NSSError NSS_ERROR_BUSY; extern const NSSError NSS_ERROR_ALREADY_INITIALIZED; extern const NSSError NSS_ERROR_PKCS11; - /* Look at the stan error stack and map it to NSS 3 errors */ -#define STAN_MAP_ERROR(x,y) \ - else if (error == (x)) { \ - secError = y; \ - } \ +#define STAN_MAP_ERROR(x, y) \ + else if (error == (x)) { secError = y; } -/* +/* * map Stan errors into NSS errors * This function examines the stan error stack and automatically sets * PORT_SetError(); to the appropriate SEC_ERROR value. @@ -165,85 +163,79 @@ CERT_MapStanError() errorStack = NSS_GetErrorStack(); if (errorStack == 0) { - PORT_SetError(0); - return; - } + PORT_SetError(0); + return; + } error = prevError = CKR_GENERAL_ERROR; /* get the 'top 2' error codes from the stack */ - for (i=0; errorStack[i]; i++) { - prevError = error; - error = errorStack[i]; + for (i = 0; errorStack[i]; i++) { + prevError = error; + error = errorStack[i]; } if (error == NSS_ERROR_PKCS11) { - /* map it */ - secError = PK11_MapError(prevError); + /* map it */ + secError = PK11_MapError(prevError); } - STAN_MAP_ERROR(NSS_ERROR_NO_ERROR, 0) - STAN_MAP_ERROR(NSS_ERROR_NO_MEMORY, SEC_ERROR_NO_MEMORY) - STAN_MAP_ERROR(NSS_ERROR_INVALID_BASE64, SEC_ERROR_BAD_DATA) - STAN_MAP_ERROR(NSS_ERROR_INVALID_BER, SEC_ERROR_BAD_DER) - STAN_MAP_ERROR(NSS_ERROR_INVALID_ATAV, SEC_ERROR_INVALID_AVA) - STAN_MAP_ERROR(NSS_ERROR_INVALID_PASSWORD,SEC_ERROR_BAD_PASSWORD) - STAN_MAP_ERROR(NSS_ERROR_BUSY, SEC_ERROR_BUSY) - STAN_MAP_ERROR(NSS_ERROR_DEVICE_ERROR, SEC_ERROR_IO) - STAN_MAP_ERROR(NSS_ERROR_CERTIFICATE_ISSUER_NOT_FOUND, - SEC_ERROR_UNKNOWN_ISSUER) - STAN_MAP_ERROR(NSS_ERROR_INVALID_CERTIFICATE, SEC_ERROR_CERT_NOT_VALID) - STAN_MAP_ERROR(NSS_ERROR_INVALID_UTF8, SEC_ERROR_BAD_DATA) - STAN_MAP_ERROR(NSS_ERROR_INVALID_NSSOID, SEC_ERROR_BAD_DATA) + STAN_MAP_ERROR(NSS_ERROR_NO_ERROR, 0) + STAN_MAP_ERROR(NSS_ERROR_NO_MEMORY, SEC_ERROR_NO_MEMORY) + STAN_MAP_ERROR(NSS_ERROR_INVALID_BASE64, SEC_ERROR_BAD_DATA) + STAN_MAP_ERROR(NSS_ERROR_INVALID_BER, SEC_ERROR_BAD_DER) + STAN_MAP_ERROR(NSS_ERROR_INVALID_ATAV, SEC_ERROR_INVALID_AVA) + STAN_MAP_ERROR(NSS_ERROR_INVALID_PASSWORD, SEC_ERROR_BAD_PASSWORD) + STAN_MAP_ERROR(NSS_ERROR_BUSY, SEC_ERROR_BUSY) + STAN_MAP_ERROR(NSS_ERROR_DEVICE_ERROR, SEC_ERROR_IO) + STAN_MAP_ERROR(NSS_ERROR_CERTIFICATE_ISSUER_NOT_FOUND, + SEC_ERROR_UNKNOWN_ISSUER) + STAN_MAP_ERROR(NSS_ERROR_INVALID_CERTIFICATE, SEC_ERROR_CERT_NOT_VALID) + STAN_MAP_ERROR(NSS_ERROR_INVALID_UTF8, SEC_ERROR_BAD_DATA) + STAN_MAP_ERROR(NSS_ERROR_INVALID_NSSOID, SEC_ERROR_BAD_DATA) - /* these are library failure for lack of a better error code */ - STAN_MAP_ERROR(NSS_ERROR_NOT_FOUND, SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_CERTIFICATE_IN_CACHE, - SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_MAXIMUM_FOUND, SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_USER_CANCELED, SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_TRACKER_NOT_INITIALIZED, - SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_ALREADY_INITIALIZED, SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD, - SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_HASH_COLLISION, SEC_ERROR_LIBRARY_FAILURE) + /* these are library failure for lack of a better error code */ + STAN_MAP_ERROR(NSS_ERROR_NOT_FOUND, SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_CERTIFICATE_IN_CACHE, SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_MAXIMUM_FOUND, SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_USER_CANCELED, SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_TRACKER_NOT_INITIALIZED, SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_ALREADY_INITIALIZED, SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD, + SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_HASH_COLLISION, SEC_ERROR_LIBRARY_FAILURE) - STAN_MAP_ERROR(NSS_ERROR_INTERNAL_ERROR, SEC_ERROR_LIBRARY_FAILURE) + STAN_MAP_ERROR(NSS_ERROR_INTERNAL_ERROR, SEC_ERROR_LIBRARY_FAILURE) - /* these are all invalid arguments */ - STAN_MAP_ERROR(NSS_ERROR_INVALID_ARGUMENT, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_POINTER, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_ARENA, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_ARENA_MARK, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_DUPLICATE_POINTER, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_POINTER_NOT_REGISTERED, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_TRACKER_NOT_EMPTY, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_VALUE_TOO_LARGE, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_UNSUPPORTED_TYPE, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_BUFFER_TOO_SHORT, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_ATOB_CONTEXT, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_BTOA_CONTEXT, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_ITEM, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_STRING, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_ASN1ENCODER, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_INVALID_ASN1DECODER, SEC_ERROR_INVALID_ARGS) - STAN_MAP_ERROR(NSS_ERROR_UNKNOWN_ATTRIBUTE, SEC_ERROR_INVALID_ARGS) - else { - secError = SEC_ERROR_LIBRARY_FAILURE; - } + /* these are all invalid arguments */ + STAN_MAP_ERROR(NSS_ERROR_INVALID_ARGUMENT, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_POINTER, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_ARENA, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_ARENA_MARK, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_DUPLICATE_POINTER, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_POINTER_NOT_REGISTERED, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_TRACKER_NOT_EMPTY, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_VALUE_TOO_LARGE, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_UNSUPPORTED_TYPE, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_BUFFER_TOO_SHORT, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_ATOB_CONTEXT, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_BTOA_CONTEXT, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_ITEM, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_STRING, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_ASN1ENCODER, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_INVALID_ASN1DECODER, SEC_ERROR_INVALID_ARGS) + STAN_MAP_ERROR(NSS_ERROR_UNKNOWN_ATTRIBUTE, SEC_ERROR_INVALID_ARGS) + else { secError = SEC_ERROR_LIBRARY_FAILURE; } PORT_SetError(secError); } - - SECStatus CERT_ChangeCertTrust(CERTCertDBHandle *handle, CERTCertificate *cert, - CERTCertTrust *trust) + CERTCertTrust *trust) { SECStatus rv = SECSuccess; PRStatus ret; ret = STAN_ChangeCertTrust(cert, trust); if (ret != PR_SUCCESS) { - rv = SECFailure; - CERT_MapStanError(); + rv = SECFailure; + CERT_MapStanError(); } return rv; } @@ -252,7 +244,7 @@ extern const NSSError NSS_ERROR_INVALID_CERTIFICATE; SECStatus __CERT_AddTempCertToPerm(CERTCertificate *cert, char *nickname, - CERTCertTrust *trust) + CERTCertTrust *trust) { NSSUTF8 *stanNick; PK11SlotInfo *slot; @@ -260,31 +252,31 @@ __CERT_AddTempCertToPerm(CERTCertificate *cert, char *nickname, NSSCryptoContext *context; nssCryptokiObject *permInstance; NSSCertificate *c = STAN_GetNSSCertificate(cert); - nssCertificateStoreTrace lockTrace = {NULL, NULL, PR_FALSE, PR_FALSE}; - nssCertificateStoreTrace unlockTrace = {NULL, NULL, PR_FALSE, PR_FALSE}; + nssCertificateStoreTrace lockTrace = { NULL, NULL, PR_FALSE, PR_FALSE }; + nssCertificateStoreTrace unlockTrace = { NULL, NULL, PR_FALSE, PR_FALSE }; SECStatus rv; PRStatus ret; if (c == NULL) { - CERT_MapStanError(); + CERT_MapStanError(); return SECFailure; } context = c->object.cryptoContext; if (!context) { - PORT_SetError(SEC_ERROR_ADDING_CERT); - return SECFailure; /* wasn't a temp cert */ + PORT_SetError(SEC_ERROR_ADDING_CERT); + return SECFailure; /* wasn't a temp cert */ } stanNick = nssCertificate_GetNickname(c, NULL); if (stanNick && nickname && strcmp(nickname, stanNick) != 0) { - /* different: take the new nickname */ - cert->nickname = NULL; + /* different: take the new nickname */ + cert->nickname = NULL; nss_ZFreeIf(stanNick); - stanNick = NULL; + stanNick = NULL; } if (!stanNick && nickname) { /* Either there was no nickname yet, or we have a new nickname */ - stanNick = nssUTF8_Duplicate((NSSUTF8 *)nickname, NULL); + stanNick = nssUTF8_Duplicate((NSSUTF8 *)nickname, NULL); } /* else: old stanNick is identical to new nickname */ /* Delete the temp instance */ nssCertificateStore_Lock(context->certStore, &lockTrace); @@ -294,24 +286,17 @@ __CERT_AddTempCertToPerm(CERTCertificate *cert, char *nickname, /* Import the perm instance onto the internal token */ slot = PK11_GetInternalKeySlot(); internal = PK11Slot_GetNSSToken(slot); - permInstance = nssToken_ImportCertificate(internal, NULL, - NSSCertificateType_PKIX, - &c->id, - stanNick, - &c->encoding, - &c->issuer, - &c->subject, - &c->serial, - cert->emailAddr, - PR_TRUE); + permInstance = nssToken_ImportCertificate( + internal, NULL, NSSCertificateType_PKIX, &c->id, stanNick, &c->encoding, + &c->issuer, &c->subject, &c->serial, cert->emailAddr, PR_TRUE); nss_ZFreeIf(stanNick); stanNick = NULL; PK11_FreeSlot(slot); if (!permInstance) { - if (NSS_GetError() == NSS_ERROR_INVALID_CERTIFICATE) { - PORT_SetError(SEC_ERROR_REUSED_ISSUER_AND_SERIAL); - } - return SECFailure; + if (NSS_GetError() == NSS_ERROR_INVALID_CERTIFICATE) { + PORT_SetError(SEC_ERROR_REUSED_ISSUER_AND_SERIAL); + } + return SECFailure; } nssPKIObject_AddInstance(&c->object, permInstance); nssTrustDomain_AddCertsToCache(STAN_GetDefaultTrustDomain(), &c, 1); @@ -319,33 +304,33 @@ __CERT_AddTempCertToPerm(CERTCertificate *cert, char *nickname, cert->nssCertificate = NULL; cert = STAN_GetCERTCertificateOrRelease(c); /* should return same pointer */ if (!cert) { - CERT_MapStanError(); + CERT_MapStanError(); return SECFailure; } cert->istemp = PR_FALSE; cert->isperm = PR_TRUE; if (!trust) { - return SECSuccess; + return SECSuccess; } ret = STAN_ChangeCertTrust(cert, trust); rv = SECSuccess; if (ret != PR_SUCCESS) { - rv = SECFailure; - CERT_MapStanError(); + rv = SECFailure; + CERT_MapStanError(); } return rv; } SECStatus CERT_AddTempCertToPerm(CERTCertificate *cert, char *nickname, - CERTCertTrust *trust) + CERTCertTrust *trust) { return __CERT_AddTempCertToPerm(cert, nickname, trust); } CERTCertificate * CERT_NewTempCertificate(CERTCertDBHandle *handle, SECItem *derCert, - char *nickname, PRBool isperm, PRBool copyDER) + char *nickname, PRBool isperm, PRBool copyDER) { NSSCertificate *c; CERTCertificate *cc; @@ -354,52 +339,54 @@ CERT_NewTempCertificate(CERTCertDBHandle *handle, SECItem *derCert, NSSCryptoContext *gCC = STAN_GetDefaultCryptoContext(); NSSTrustDomain *gTD = STAN_GetDefaultTrustDomain(); if (!isperm) { - NSSDER encoding; - NSSITEM_FROM_SECITEM(&encoding, derCert); - /* First, see if it is already a temp cert */ - c = NSSCryptoContext_FindCertificateByEncodedCertificate(gCC, - &encoding); - if (!c) { - /* Then, see if it is already a perm cert */ - c = NSSTrustDomain_FindCertificateByEncodedCertificate(handle, - &encoding); - } - if (c) { - /* actually, that search ends up going by issuer/serial, - * so it is still possible to return a cert with the same - * issuer/serial but a different encoding, and we're - * going to reject that - */ - if (!nssItem_Equal(&c->encoding, &encoding, NULL)) { - nssCertificate_Destroy(c); - PORT_SetError(SEC_ERROR_REUSED_ISSUER_AND_SERIAL); - cc = NULL; - } else { - cc = STAN_GetCERTCertificateOrRelease(c); - if (cc == NULL) { - CERT_MapStanError(); - } - } - return cc; - } + NSSDER encoding; + NSSITEM_FROM_SECITEM(&encoding, derCert); + /* First, see if it is already a temp cert */ + c = NSSCryptoContext_FindCertificateByEncodedCertificate(gCC, + &encoding); + if (!c) { + /* Then, see if it is already a perm cert */ + c = NSSTrustDomain_FindCertificateByEncodedCertificate(handle, + &encoding); + } + if (c) { + /* actually, that search ends up going by issuer/serial, + * so it is still possible to return a cert with the same + * issuer/serial but a different encoding, and we're + * going to reject that + */ + if (!nssItem_Equal(&c->encoding, &encoding, NULL)) { + nssCertificate_Destroy(c); + PORT_SetError(SEC_ERROR_REUSED_ISSUER_AND_SERIAL); + cc = NULL; + } + else { + cc = STAN_GetCERTCertificateOrRelease(c); + if (cc == NULL) { + CERT_MapStanError(); + } + } + return cc; + } } pkio = nssPKIObject_Create(NULL, NULL, gTD, gCC, nssPKIMonitor); if (!pkio) { - CERT_MapStanError(); - return NULL; + CERT_MapStanError(); + return NULL; } c = nss_ZNEW(pkio->arena, NSSCertificate); if (!c) { - CERT_MapStanError(); - nssPKIObject_Destroy(pkio); - return NULL; + CERT_MapStanError(); + nssPKIObject_Destroy(pkio); + return NULL; } c->object = *pkio; if (copyDER) { - nssItem_Create(c->object.arena, &c->encoding, - derCert->len, derCert->data); - } else { - NSSITEM_FROM_SECITEM(&c->encoding, derCert); + nssItem_Create(c->object.arena, &c->encoding, derCert->len, + derCert->data); + } + else { + NSSITEM_FROM_SECITEM(&c->encoding, derCert); } /* Forces a decoding of the cert in order to obtain the parts used * below @@ -408,40 +395,40 @@ CERT_NewTempCertificate(CERTCertDBHandle *handle, SECItem *derCert, * allocated so far for 'c' */ cc = STAN_GetCERTCertificate(c); if (!cc) { - CERT_MapStanError(); + CERT_MapStanError(); goto loser; } - nssItem_Create(c->object.arena, - &c->issuer, cc->derIssuer.len, cc->derIssuer.data); - nssItem_Create(c->object.arena, - &c->subject, cc->derSubject.len, cc->derSubject.data); + nssItem_Create(c->object.arena, &c->issuer, cc->derIssuer.len, + cc->derIssuer.data); + nssItem_Create(c->object.arena, &c->subject, cc->derSubject.len, + cc->derSubject.data); if (PR_TRUE) { - /* CERTCertificate stores serial numbers decoded. I need the DER - * here. sigh. - */ - SECItem derSerial = { 0 }; - CERT_SerialNumberFromDERCert(&cc->derCert, &derSerial); - if (!derSerial.data) goto loser; - nssItem_Create(c->object.arena, &c->serial, derSerial.len, derSerial.data); - PORT_Free(derSerial.data); + /* CERTCertificate stores serial numbers decoded. I need the DER + * here. sigh. + */ + SECItem derSerial = { 0 }; + CERT_SerialNumberFromDERCert(&cc->derCert, &derSerial); + if (!derSerial.data) + goto loser; + nssItem_Create(c->object.arena, &c->serial, derSerial.len, + derSerial.data); + PORT_Free(derSerial.data); } if (nickname) { - c->object.tempName = nssUTF8_Create(c->object.arena, - nssStringType_UTF8String, - (NSSUTF8 *)nickname, - PORT_Strlen(nickname)); + c->object.tempName = + nssUTF8_Create(c->object.arena, nssStringType_UTF8String, + (NSSUTF8 *)nickname, PORT_Strlen(nickname)); } if (cc->emailAddr && cc->emailAddr[0]) { - c->email = nssUTF8_Create(c->object.arena, - nssStringType_PrintableString, - (NSSUTF8 *)cc->emailAddr, - PORT_Strlen(cc->emailAddr)); + c->email = nssUTF8_Create( + c->object.arena, nssStringType_PrintableString, + (NSSUTF8 *)cc->emailAddr, PORT_Strlen(cc->emailAddr)); } tempCert = NSSCryptoContext_FindOrImportCertificate(gCC, c); if (!tempCert) { - CERT_MapStanError(); - goto loser; + CERT_MapStanError(); + goto loser; } /* destroy our copy */ NSSCertificate_Destroy(c); @@ -449,9 +436,9 @@ CERT_NewTempCertificate(CERTCertDBHandle *handle, SECItem *derCert, c = tempCert; cc = STAN_GetCERTCertificateOrRelease(c); if (!cc) { - /* STAN_GetCERTCertificateOrRelease destroys c on failure. */ - CERT_MapStanError(); - return NULL; + /* STAN_GetCERTCertificateOrRelease destroys c on failure. */ + CERT_MapStanError(); + return NULL; } cc->istemp = PR_TRUE; @@ -466,20 +453,20 @@ loser: /* This symbol is exported for backward compatibility. */ CERTCertificate * __CERT_NewTempCertificate(CERTCertDBHandle *handle, SECItem *derCert, - char *nickname, PRBool isperm, PRBool copyDER) + char *nickname, PRBool isperm, PRBool copyDER) { - return CERT_NewTempCertificate(handle, derCert, nickname, - isperm, copyDER); + return CERT_NewTempCertificate(handle, derCert, nickname, isperm, copyDER); } /* maybe all the wincx's should be some const for internal token login? */ CERTCertificate * -CERT_FindCertByIssuerAndSN(CERTCertDBHandle *handle, CERTIssuerAndSN *issuerAndSN) +CERT_FindCertByIssuerAndSN(CERTCertDBHandle *handle, + CERTIssuerAndSN *issuerAndSN) { PK11SlotInfo *slot; CERTCertificate *cert; - cert = PK11_FindCertByIssuerAndSN(&slot,issuerAndSN,NULL); + cert = PK11_FindCertByIssuerAndSN(&slot, issuerAndSN, NULL); if (cert && slot) { PK11_FreeSlot(slot); } @@ -493,9 +480,10 @@ get_best_temp_or_perm(NSSCertificate *ct, NSSCertificate *cp) NSSUsage usage; NSSCertificate *arr[3]; if (!ct) { - return nssCertificate_AddRef(cp); - } else if (!cp) { - return nssCertificate_AddRef(ct); + return nssCertificate_AddRef(cp); + } + else if (!cp) { + return nssCertificate_AddRef(ct); } arr[0] = ct; arr[1] = cp; @@ -514,16 +502,16 @@ CERT_FindCertByName(CERTCertDBHandle *handle, SECItem *name) NSSITEM_FROM_SECITEM(&subject, name); usage.anyUsage = PR_TRUE; cc = STAN_GetDefaultCryptoContext(); - ct = NSSCryptoContext_FindBestCertificateBySubject(cc, &subject, - NULL, &usage, NULL); - cp = NSSTrustDomain_FindBestCertificateBySubject(handle, &subject, - NULL, &usage, NULL); + ct = NSSCryptoContext_FindBestCertificateBySubject(cc, &subject, NULL, + &usage, NULL); + cp = NSSTrustDomain_FindBestCertificateBySubject(handle, &subject, NULL, + &usage, NULL); c = get_best_temp_or_perm(ct, cp); if (ct) { - CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); + CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); } if (cp) { - CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(cp)); + CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(cp)); } return c ? STAN_GetCERTCertificateOrRelease(c) : NULL; } @@ -535,19 +523,20 @@ CERT_FindCertByKeyID(CERTCertDBHandle *handle, SECItem *name, SECItem *keyID) CERTCertificate *cert = NULL; CERTCertListNode *node, *head; - list = CERT_CreateSubjectCertList(NULL,handle,name,0,PR_FALSE); - if (list == NULL) return NULL; + list = CERT_CreateSubjectCertList(NULL, handle, name, 0, PR_FALSE); + if (list == NULL) + return NULL; node = head = CERT_LIST_HEAD(list); if (head) { - do { - if (node->cert && - SECITEM_ItemsAreEqual(&node->cert->subjectKeyID, keyID) ) { - cert = CERT_DupCertificate(node->cert); - goto done; - } - node = CERT_LIST_NEXT(node); - } while (node && head != node); + do { + if (node->cert && + SECITEM_ItemsAreEqual(&node->cert->subjectKeyID, keyID)) { + cert = CERT_DupCertificate(node->cert); + goto done; + } + node = CERT_LIST_NEXT(node); + } while (node && head != node); } PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER); done: @@ -566,18 +555,19 @@ CERT_FindCertByNickname(CERTCertDBHandle *handle, const char *nickname) NSSUsage usage; usage.anyUsage = PR_TRUE; cc = STAN_GetDefaultCryptoContext(); - ct = NSSCryptoContext_FindBestCertificateByNickname(cc, nickname, - NULL, &usage, NULL); + ct = NSSCryptoContext_FindBestCertificateByNickname(cc, nickname, NULL, + &usage, NULL); cert = PK11_FindCertFromNickname(nickname, NULL); c = NULL; if (cert) { - c = get_best_temp_or_perm(ct, STAN_GetNSSCertificate(cert)); - CERT_DestroyCertificate(cert); - if (ct) { - CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); - } - } else { - c = ct; + c = get_best_temp_or_perm(ct, STAN_GetNSSCertificate(cert)); + CERT_DestroyCertificate(cert); + if (ct) { + CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); + } + } + else { + c = ct; } return c ? STAN_GetCERTCertificateOrRelease(c) : NULL; } @@ -592,17 +582,17 @@ CERT_FindCertByDERCert(CERTCertDBHandle *handle, SECItem *derCert) cc = STAN_GetDefaultCryptoContext(); c = NSSCryptoContext_FindCertificateByEncodedCertificate(cc, &encoding); if (!c) { - c = NSSTrustDomain_FindCertificateByEncodedCertificate(handle, - &encoding); - if (!c) return NULL; + c = NSSTrustDomain_FindCertificateByEncodedCertificate(handle, + &encoding); + if (!c) + return NULL; } return STAN_GetCERTCertificateOrRelease(c); } static CERTCertificate * -common_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, - const char *name, - PRBool anyUsage, +common_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, + const char *name, PRBool anyUsage, SECCertUsage lookingForUsage) { NSSCryptoContext *cc; @@ -613,63 +603,63 @@ common_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, if (NULL == name) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + return NULL; } usage.anyUsage = anyUsage; if (!anyUsage) { - usage.nss3lookingForCA = PR_FALSE; - usage.nss3usage = lookingForUsage; + usage.nss3lookingForCA = PR_FALSE; + usage.nss3usage = lookingForUsage; } cc = STAN_GetDefaultCryptoContext(); - ct = NSSCryptoContext_FindBestCertificateByNickname(cc, name, - NULL, &usage, NULL); + ct = NSSCryptoContext_FindBestCertificateByNickname(cc, name, NULL, &usage, + NULL); if (!ct && PORT_Strchr(name, '@') != NULL) { - char* lowercaseName = CERT_FixupEmailAddr(name); + char *lowercaseName = CERT_FixupEmailAddr(name); if (lowercaseName) { - ct = NSSCryptoContext_FindBestCertificateByEmail(cc, lowercaseName, - NULL, &usage, NULL); + ct = NSSCryptoContext_FindBestCertificateByEmail( + cc, lowercaseName, NULL, &usage, NULL); PORT_Free(lowercaseName); } } if (anyUsage) { - cert = PK11_FindCertFromNickname(name, NULL); + cert = PK11_FindCertFromNickname(name, NULL); } else { - if (ct) { - /* Does ct really have the required usage? */ - nssDecodedCert *dc; - dc = nssCertificate_GetDecoding(ct); - if (!dc->matchUsage(dc, &usage)) { - CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); - ct = NULL; - } - } - - certlist = PK11_FindCertsFromNickname(name, NULL); - if (certlist) { - SECStatus rv = CERT_FilterCertListByUsage(certlist, - lookingForUsage, - PR_FALSE); - if (SECSuccess == rv && - !CERT_LIST_END(CERT_LIST_HEAD(certlist), certlist)) { - cert = CERT_DupCertificate(CERT_LIST_HEAD(certlist)->cert); + if (ct) { + /* Does ct really have the required usage? */ + nssDecodedCert *dc; + dc = nssCertificate_GetDecoding(ct); + if (!dc->matchUsage(dc, &usage)) { + CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); + ct = NULL; + } + } + + certlist = PK11_FindCertsFromNickname(name, NULL); + if (certlist) { + SECStatus rv = + CERT_FilterCertListByUsage(certlist, lookingForUsage, PR_FALSE); + if (SECSuccess == rv && + !CERT_LIST_END(CERT_LIST_HEAD(certlist), certlist)) { + cert = CERT_DupCertificate(CERT_LIST_HEAD(certlist)->cert); + } + CERT_DestroyCertList(certlist); } - CERT_DestroyCertList(certlist); - } } if (cert) { - c = get_best_temp_or_perm(ct, STAN_GetNSSCertificate(cert)); - CERT_DestroyCertificate(cert); - if (ct) { - CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); - } - } else { - c = ct; + c = get_best_temp_or_perm(ct, STAN_GetNSSCertificate(cert)); + CERT_DestroyCertificate(cert); + if (ct) { + CERT_DestroyCertificate(STAN_GetCERTCertificateOrRelease(ct)); + } + } + else { + c = ct; } return c ? STAN_GetCERTCertificateOrRelease(c) : NULL; } @@ -677,43 +667,42 @@ common_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, CERTCertificate * CERT_FindCertByNicknameOrEmailAddr(CERTCertDBHandle *handle, const char *name) { - return common_FindCertByNicknameOrEmailAddrForUsage(handle, name, - PR_TRUE, 0); + return common_FindCertByNicknameOrEmailAddrForUsage(handle, name, PR_TRUE, + 0); } CERTCertificate * -CERT_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, - const char *name, +CERT_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, + const char *name, SECCertUsage lookingForUsage) { - return common_FindCertByNicknameOrEmailAddrForUsage(handle, name, - PR_FALSE, - lookingForUsage); + return common_FindCertByNicknameOrEmailAddrForUsage(handle, name, PR_FALSE, + lookingForUsage); } -static void +static void add_to_subject_list(CERTCertList *certList, CERTCertificate *cert, PRBool validOnly, PRTime sorttime) { SECStatus secrv; if (!validOnly || - CERT_CheckCertValidTimes(cert, sorttime, PR_FALSE) - == secCertTimeValid) { - secrv = CERT_AddCertToListSorted(certList, cert, - CERT_SortCBValidity, - (void *)&sorttime); - if (secrv != SECSuccess) { - CERT_DestroyCertificate(cert); - } - } else { - CERT_DestroyCertificate(cert); + CERT_CheckCertValidTimes(cert, sorttime, PR_FALSE) == + secCertTimeValid) { + secrv = CERT_AddCertToListSorted(certList, cert, CERT_SortCBValidity, + (void *)&sorttime); + if (secrv != SECSuccess) { + CERT_DestroyCertificate(cert); + } + } + else { + CERT_DestroyCertificate(cert); } } CERTCertList * CERT_CreateSubjectCertList(CERTCertList *certList, CERTCertDBHandle *handle, - const SECItem *name, PRTime sorttime, - PRBool validOnly) + const SECItem *name, PRTime sorttime, + PRBool validOnly) { NSSCryptoContext *cc; NSSCertificate **tSubjectCerts, **pSubjectCerts; @@ -724,45 +713,40 @@ CERT_CreateSubjectCertList(CERTCertList *certList, CERTCertDBHandle *handle, cc = STAN_GetDefaultCryptoContext(); NSSITEM_FROM_SECITEM(&subject, name); /* Collect both temp and perm certs for the subject */ - tSubjectCerts = NSSCryptoContext_FindCertificatesBySubject(cc, - &subject, - NULL, - 0, - NULL); - pSubjectCerts = NSSTrustDomain_FindCertificatesBySubject(handle, - &subject, - NULL, - 0, - NULL); + tSubjectCerts = + NSSCryptoContext_FindCertificatesBySubject(cc, &subject, NULL, 0, NULL); + pSubjectCerts = NSSTrustDomain_FindCertificatesBySubject(handle, &subject, + NULL, 0, NULL); if (!tSubjectCerts && !pSubjectCerts) { - return NULL; + return NULL; } if (certList == NULL) { - certList = CERT_NewCertList(); - myList = PR_TRUE; - if (!certList) goto loser; + certList = CERT_NewCertList(); + myList = PR_TRUE; + if (!certList) + goto loser; } /* Iterate over the matching temp certs. Add them to the list */ ci = tSubjectCerts; while (ci && *ci) { - cert = STAN_GetCERTCertificateOrRelease(*ci); - /* *ci may be invalid at this point, don't reference it again */ + cert = STAN_GetCERTCertificateOrRelease(*ci); + /* *ci may be invalid at this point, don't reference it again */ if (cert) { - /* NOTE: add_to_subject_list adopts the incoming cert. */ - add_to_subject_list(certList, cert, validOnly, sorttime); + /* NOTE: add_to_subject_list adopts the incoming cert. */ + add_to_subject_list(certList, cert, validOnly, sorttime); } - ci++; + ci++; } /* Iterate over the matching perm certs. Add them to the list */ ci = pSubjectCerts; while (ci && *ci) { - cert = STAN_GetCERTCertificateOrRelease(*ci); - /* *ci may be invalid at this point, don't reference it again */ + cert = STAN_GetCERTCertificateOrRelease(*ci); + /* *ci may be invalid at this point, don't reference it again */ if (cert) { - /* NOTE: add_to_subject_list adopts the incoming cert. */ - add_to_subject_list(certList, cert, validOnly, sorttime); + /* NOTE: add_to_subject_list adopts the incoming cert. */ + add_to_subject_list(certList, cert, validOnly, sorttime); } - ci++; + ci++; } /* all the references have been adopted or freed at this point, just * free the arrays now */ @@ -774,7 +758,7 @@ loser: nssCertificateArray_Destroy(tSubjectCerts); nssCertificateArray_Destroy(pSubjectCerts); if (myList && certList != NULL) { - CERT_DestroyCertList(certList); + CERT_DestroyCertList(certList); } return NULL; } @@ -782,19 +766,20 @@ loser: void CERT_DestroyCertificate(CERTCertificate *cert) { - if ( cert ) { - /* don't use STAN_GetNSSCertificate because we don't want to - * go to the trouble of translating the CERTCertificate into - * an NSSCertificate just to destroy it. If it hasn't been done - * yet, don't do it at all. - */ - NSSCertificate *tmp = cert->nssCertificate; - if (tmp) { - /* delete the NSSCertificate */ - NSSCertificate_Destroy(tmp); - } else if (cert->arena) { - PORT_FreeArena(cert->arena, PR_FALSE); - } + if (cert) { + /* don't use STAN_GetNSSCertificate because we don't want to + * go to the trouble of translating the CERTCertificate into + * an NSSCertificate just to destroy it. If it hasn't been done + * yet, don't do it at all. + */ + NSSCertificate *tmp = cert->nssCertificate; + if (tmp) { + /* delete the NSSCertificate */ + NSSCertificate_Destroy(tmp); + } + else if (cert->arena) { + PORT_FreeArena(cert->arena, PR_FALSE); + } } return; } @@ -807,8 +792,8 @@ CERT_GetDBContentVersion(CERTCertDBHandle *handle) } SECStatus -certdb_SaveSingleProfile(CERTCertificate *cert, const char *emailAddr, - SECItem *emailProfile, SECItem *profileTime) +certdb_SaveSingleProfile(CERTCertificate *cert, const char *emailAddr, + SECItem *emailProfile, SECItem *profileTime) { PRTime oldtime; PRTime newtime; @@ -824,111 +809,117 @@ certdb_SaveSingleProfile(CERTCertificate *cert, const char *emailAddr, PRBool freeOldProfile = PR_FALSE; c = STAN_GetNSSCertificate(cert); - if (!c) return SECFailure; + if (!c) + return SECFailure; cc = c->object.cryptoContext; if (cc != NULL) { - stanProfile = nssCryptoContext_FindSMIMEProfileForCertificate(cc, c); - if (stanProfile) { - PORT_Assert(stanProfile->profileData); - SECITEM_FROM_NSSITEM(&oldprof, stanProfile->profileData); - oldProfile = &oldprof; - SECITEM_FROM_NSSITEM(&oldproftime, stanProfile->profileTime); - oldProfileTime = &oldproftime; - } - } else { - oldProfile = PK11_FindSMimeProfile(&slot, (char *)emailAddr, - &cert->derSubject, &oldProfileTime); - freeOldProfile = PR_TRUE; + stanProfile = nssCryptoContext_FindSMIMEProfileForCertificate(cc, c); + if (stanProfile) { + PORT_Assert(stanProfile->profileData); + SECITEM_FROM_NSSITEM(&oldprof, stanProfile->profileData); + oldProfile = &oldprof; + SECITEM_FROM_NSSITEM(&oldproftime, stanProfile->profileTime); + oldProfileTime = &oldproftime; + } + } + else { + oldProfile = PK11_FindSMimeProfile(&slot, (char *)emailAddr, + &cert->derSubject, &oldProfileTime); + freeOldProfile = PR_TRUE; } saveit = PR_FALSE; - + /* both profileTime and emailProfile have to exist or not exist */ - if ( emailProfile == NULL ) { - profileTime = NULL; - } else if ( profileTime == NULL ) { - emailProfile = NULL; + if (emailProfile == NULL) { + profileTime = NULL; } - - if ( oldProfileTime == NULL ) { - saveit = PR_TRUE; - } else { - /* there was already a profile for this email addr */ - if ( profileTime ) { - /* we have an old and new profile - save whichever is more recent*/ - if ( oldProfileTime->len == 0 ) { - /* always replace if old entry doesn't have a time */ - oldtime = LL_MININT; - } else { - rv = DER_UTCTimeToTime(&oldtime, oldProfileTime); - if ( rv != SECSuccess ) { - goto loser; - } - } - - rv = DER_UTCTimeToTime(&newtime, profileTime); - if ( rv != SECSuccess ) { - goto loser; - } - - if ( LL_CMP(newtime, >, oldtime ) ) { - /* this is a newer profile, save it and cert */ - saveit = PR_TRUE; - } - } else { - saveit = PR_TRUE; - } + else if (profileTime == NULL) { + emailProfile = NULL; } + if (oldProfileTime == NULL) { + saveit = PR_TRUE; + } + else { + /* there was already a profile for this email addr */ + if (profileTime) { + /* we have an old and new profile - save whichever is more recent*/ + if (oldProfileTime->len == 0) { + /* always replace if old entry doesn't have a time */ + oldtime = LL_MININT; + } + else { + rv = DER_UTCTimeToTime(&oldtime, oldProfileTime); + if (rv != SECSuccess) { + goto loser; + } + } + + rv = DER_UTCTimeToTime(&newtime, profileTime); + if (rv != SECSuccess) { + goto loser; + } + + if (LL_CMP(newtime, >, oldtime)) { + /* this is a newer profile, save it and cert */ + saveit = PR_TRUE; + } + } + else { + saveit = PR_TRUE; + } + } if (saveit) { - if (cc) { - if (stanProfile) { - /* stanProfile is already stored in the crypto context, - * overwrite the data - */ - NSSArena *arena = stanProfile->object.arena; - stanProfile->profileTime = nssItem_Create(arena, - NULL, - profileTime->len, - profileTime->data); - stanProfile->profileData = nssItem_Create(arena, - NULL, - emailProfile->len, - emailProfile->data); - } else if (profileTime && emailProfile) { - PRStatus nssrv; - NSSItem profTime, profData; - NSSITEM_FROM_SECITEM(&profTime, profileTime); - NSSITEM_FROM_SECITEM(&profData, emailProfile); - stanProfile = nssSMIMEProfile_Create(c, &profTime, &profData); - if (!stanProfile) goto loser; - nssrv = nssCryptoContext_ImportSMIMEProfile(cc, stanProfile); - rv = (nssrv == PR_SUCCESS) ? SECSuccess : SECFailure; - } - } else { - rv = PK11_SaveSMimeProfile(slot, (char *)emailAddr, - &cert->derSubject, emailProfile, profileTime); - } - } else { - rv = SECSuccess; + if (cc) { + if (stanProfile) { + /* stanProfile is already stored in the crypto context, + * overwrite the data + */ + NSSArena *arena = stanProfile->object.arena; + stanProfile->profileTime = nssItem_Create( + arena, NULL, profileTime->len, profileTime->data); + stanProfile->profileData = nssItem_Create( + arena, NULL, emailProfile->len, emailProfile->data); + } + else if (profileTime && emailProfile) { + PRStatus nssrv; + NSSItem profTime, profData; + NSSITEM_FROM_SECITEM(&profTime, profileTime); + NSSITEM_FROM_SECITEM(&profData, emailProfile); + stanProfile = nssSMIMEProfile_Create(c, &profTime, &profData); + if (!stanProfile) + goto loser; + nssrv = nssCryptoContext_ImportSMIMEProfile(cc, stanProfile); + rv = (nssrv == PR_SUCCESS) ? SECSuccess : SECFailure; + } + } + else { + rv = PK11_SaveSMimeProfile(slot, (char *)emailAddr, + &cert->derSubject, emailProfile, + profileTime); + } + } + else { + rv = SECSuccess; } loser: if (oldProfile && freeOldProfile) { - SECITEM_FreeItem(oldProfile,PR_TRUE); + SECITEM_FreeItem(oldProfile, PR_TRUE); } if (oldProfileTime && freeOldProfile) { - SECITEM_FreeItem(oldProfileTime,PR_TRUE); + SECITEM_FreeItem(oldProfileTime, PR_TRUE); } if (stanProfile) { - nssSMIMEProfile_Destroy(stanProfile); + nssSMIMEProfile_Destroy(stanProfile); } if (slot) { - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); } - - return(rv); + + return (rv); } /* @@ -939,7 +930,7 @@ loser: SECStatus CERT_SaveSMimeProfile(CERTCertificate *cert, SECItem *emailProfile, - SECItem *profileTime) + SECItem *profileTime) { const char *emailAddr; SECStatus rv; @@ -948,40 +939,39 @@ CERT_SaveSMimeProfile(CERTCertificate *cert, SECItem *emailProfile, return SECFailure; } - if (cert->slot && !PK11_IsInternal(cert->slot)) { + if (cert->slot && !PK11_IsInternal(cert->slot)) { /* this cert comes from an external source, we need to add it to the cert db before creating an S/MIME profile */ - PK11SlotInfo* internalslot = PK11_GetInternalKeySlot(); + PK11SlotInfo *internalslot = PK11_GetInternalKeySlot(); if (!internalslot) { return SECFailure; } - rv = PK11_ImportCert(internalslot, cert, - CK_INVALID_HANDLE, NULL, PR_FALSE); + rv = PK11_ImportCert(internalslot, cert, CK_INVALID_HANDLE, NULL, + PR_FALSE); PK11_FreeSlot(internalslot); - if (rv != SECSuccess ) { + if (rv != SECSuccess) { return SECFailure; } } if (cert->slot && cert->isperm && CERT_IsUserCert(cert) && - (!emailProfile || !emailProfile->len)) { - /* Don't clobber emailProfile for user certs. */ - return SECSuccess; + (!emailProfile || !emailProfile->len)) { + /* Don't clobber emailProfile for user certs. */ + return SECSuccess; } for (emailAddr = CERT_GetFirstEmailAddress(cert); emailAddr != NULL; - emailAddr = CERT_GetNextEmailAddress(cert,emailAddr)) { - rv = certdb_SaveSingleProfile(cert,emailAddr,emailProfile,profileTime); - if (rv != SECSuccess) { - return SECFailure; - } + emailAddr = CERT_GetNextEmailAddress(cert, emailAddr)) { + rv = certdb_SaveSingleProfile(cert, emailAddr, emailProfile, + profileTime); + if (rv != SECSuccess) { + return SECFailure; + } } return SECSuccess; - } - SECItem * CERT_FindSMimeProfile(CERTCertificate *cert) { @@ -991,29 +981,30 @@ CERT_FindSMimeProfile(CERTCertificate *cert) SECItem *rvItem = NULL; if (!cert || !cert->emailAddr || !cert->emailAddr[0]) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } c = STAN_GetNSSCertificate(cert); - if (!c) return NULL; + if (!c) + return NULL; cc = c->object.cryptoContext; if (cc != NULL) { - nssSMIMEProfile *stanProfile; - stanProfile = nssCryptoContext_FindSMIMEProfileForCertificate(cc, c); - if (stanProfile) { - rvItem = SECITEM_AllocItem(NULL, NULL, - stanProfile->profileData->size); - if (rvItem) { - rvItem->data = stanProfile->profileData->data; - } - nssSMIMEProfile_Destroy(stanProfile); - } - return rvItem; + nssSMIMEProfile *stanProfile; + stanProfile = nssCryptoContext_FindSMIMEProfileForCertificate(cc, c); + if (stanProfile) { + rvItem = + SECITEM_AllocItem(NULL, NULL, stanProfile->profileData->size); + if (rvItem) { + rvItem->data = stanProfile->profileData->data; + } + nssSMIMEProfile_Destroy(stanProfile); + } + return rvItem; } rvItem = - PK11_FindSMimeProfile(&slot, cert->emailAddr, &cert->derSubject, NULL); + PK11_FindSMimeProfile(&slot, cert->emailAddr, &cert->derSubject, NULL); if (slot) { - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); } return rvItem; } @@ -1050,23 +1041,18 @@ SECKEY_HashPassword(char *pw, SECItem *salt) SECStatus __CERT_TraversePermCertsForSubject(CERTCertDBHandle *handle, - SECItem *derSubject, - void *cb, void *cbarg) + SECItem *derSubject, void *cb, void *cbarg) { PORT_Assert("CERT_TraversePermCertsForSubject is Deprecated" == NULL); PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); return SECFailure; } - SECStatus __CERT_TraversePermCertsForNickname(CERTCertDBHandle *handle, char *nickname, - void *cb, void *cbarg) + void *cb, void *cbarg) { PORT_Assert("CERT_TraversePermCertsForNickname is Deprecated" == NULL); PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); return SECFailure; } - - - diff --git a/security/nss/lib/certdb/xauthkid.c b/security/nss/lib/certdb/xauthkid.c index 4faf017a194e..3f95fed9a656 100644 --- a/security/nss/lib/certdb/xauthkid.c +++ b/security/nss/lib/certdb/xauthkid.c @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * X.509 v3 Subject Key Usage Extension + * X.509 v3 Subject Key Usage Extension * */ @@ -14,7 +14,7 @@ #include "secasn1t.h" #include "secasn1.h" #include "secport.h" -#include "certt.h" +#include "certt.h" #include "genname.h" #include "secerr.h" @@ -24,105 +24,106 @@ SEC_ASN1_MKSUB(SEC_OctetStringTemplate) const SEC_ASN1Template CERTAuthKeyIDTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTAuthKeyID) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(CERTAuthKeyID,keyID), SEC_ASN1_SUB(SEC_OctetStringTemplate)}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(CERTAuthKeyID, DERAuthCertIssuer), CERT_GeneralNamesTemplate}, + offsetof(CERTAuthKeyID, keyID), SEC_ASN1_SUB(SEC_OctetStringTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(CERTAuthKeyID, DERAuthCertIssuer), CERT_GeneralNamesTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, - offsetof(CERTAuthKeyID,authCertSerialNumber), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, + offsetof(CERTAuthKeyID, authCertSerialNumber), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, { 0 } }; - - -SECStatus CERT_EncodeAuthKeyID (PLArenaPool *arena, CERTAuthKeyID *value, SECItem *encodedValue) +SECStatus +CERT_EncodeAuthKeyID(PLArenaPool *arena, CERTAuthKeyID *value, + SECItem *encodedValue) { SECStatus rv = SECFailure; - - PORT_Assert (value); - PORT_Assert (arena); - PORT_Assert (value->DERAuthCertIssuer == NULL); - PORT_Assert (encodedValue); + + PORT_Assert(value); + PORT_Assert(arena); + PORT_Assert(value->DERAuthCertIssuer == NULL); + PORT_Assert(encodedValue); do { - - /* If both of the authCertIssuer and the serial number exist, encode - the name first. Otherwise, it is an error if one exist and the other - is not. - */ - if (value->authCertIssuer) { - if (!value->authCertSerialNumber.data) { - PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID); - break; - } - value->DERAuthCertIssuer = cert_EncodeGeneralNames - (arena, value->authCertIssuer); - if (!value->DERAuthCertIssuer) { - PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID); - break; - } - } - else if (value->authCertSerialNumber.data) { - PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID); - break; - } + /* If both of the authCertIssuer and the serial number exist, encode + the name first. Otherwise, it is an error if one exist and the other + is not. + */ + if (value->authCertIssuer) { + if (!value->authCertSerialNumber.data) { + PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID); + break; + } - if (SEC_ASN1EncodeItem (arena, encodedValue, value, - CERTAuthKeyIDTemplate) == NULL) - break; - rv = SECSuccess; + value->DERAuthCertIssuer = + cert_EncodeGeneralNames(arena, value->authCertIssuer); + if (!value->DERAuthCertIssuer) { + PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID); + break; + } + } + else if (value->authCertSerialNumber.data) { + PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID); + break; + } + + if (SEC_ASN1EncodeItem(arena, encodedValue, value, + CERTAuthKeyIDTemplate) == NULL) + break; + rv = SECSuccess; } while (0); - return(rv); + return (rv); } CERTAuthKeyID * -CERT_DecodeAuthKeyID (PLArenaPool *arena, const SECItem *encodedValue) +CERT_DecodeAuthKeyID(PLArenaPool *arena, const SECItem *encodedValue) { - CERTAuthKeyID * value = NULL; - SECStatus rv = SECFailure; - void * mark; - SECItem newEncodedValue; + CERTAuthKeyID *value = NULL; + SECStatus rv = SECFailure; + void *mark; + SECItem newEncodedValue; + + PORT_Assert(arena); - PORT_Assert (arena); - do { - mark = PORT_ArenaMark (arena); - value = (CERTAuthKeyID*)PORT_ArenaZAlloc (arena, sizeof (*value)); - if (value == NULL) - break; - value->DERAuthCertIssuer = NULL; + mark = PORT_ArenaMark(arena); + value = (CERTAuthKeyID *)PORT_ArenaZAlloc(arena, sizeof(*value)); + if (value == NULL) + break; + value->DERAuthCertIssuer = NULL; /* 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, &newEncodedValue, encodedValue); - if ( rv != SECSuccess ) { - break; + if (rv != SECSuccess) { + break; } - rv = SEC_QuickDERDecodeItem - (arena, value, CERTAuthKeyIDTemplate, &newEncodedValue); - if (rv != SECSuccess) - break; + rv = SEC_QuickDERDecodeItem(arena, value, CERTAuthKeyIDTemplate, + &newEncodedValue); + if (rv != SECSuccess) + break; - value->authCertIssuer = cert_DecodeGeneralNames (arena, value->DERAuthCertIssuer); - if (value->authCertIssuer == NULL) - break; - - /* what if the general name contains other format but not URI ? - hl - */ - if ((value->authCertSerialNumber.data && !value->authCertIssuer) || - (!value->authCertSerialNumber.data && value->authCertIssuer)){ - PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID); - break; - } + value->authCertIssuer = + cert_DecodeGeneralNames(arena, value->DERAuthCertIssuer); + if (value->authCertIssuer == NULL) + break; + + /* what if the general name contains other format but not URI ? + hl + */ + if ((value->authCertSerialNumber.data && !value->authCertIssuer) || + (!value->authCertSerialNumber.data && value->authCertIssuer)) { + PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID); + break; + } } while (0); if (rv != SECSuccess) { - PORT_ArenaRelease (arena, mark); - return ((CERTAuthKeyID *)NULL); - } + PORT_ArenaRelease(arena, mark); + return ((CERTAuthKeyID *)NULL); + } PORT_ArenaUnmark(arena, mark); return (value); } diff --git a/security/nss/lib/certdb/xbsconst.c b/security/nss/lib/certdb/xbsconst.c index 7a3cb1cd0474..a74c28089603 100644 --- a/security/nss/lib/certdb/xbsconst.c +++ b/security/nss/lib/certdb/xbsconst.c @@ -3,11 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * X.509 v3 Basic Constraints Extension + * X.509 v3 Basic Constraints Extension */ #include "prtypes.h" -#include /* for LONG_MAX */ +#include /* for LONG_MAX */ #include "seccomon.h" #include "secdert.h" #include "secoidt.h" @@ -18,128 +18,132 @@ #include "prprf.h" #include "secerr.h" -typedef struct EncodedContext{ +typedef struct EncodedContext { SECItem isCA; SECItem pathLenConstraint; SECItem encodedValue; PLArenaPool *arena; -}EncodedContext; +} EncodedContext; static const SEC_ASN1Template CERTBasicConstraintsTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(EncodedContext) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ - offsetof(EncodedContext,isCA)}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(EncodedContext) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ + offsetof(EncodedContext, isCA) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_INTEGER, - offsetof(EncodedContext,pathLenConstraint) }, - { 0, } + offsetof(EncodedContext, pathLenConstraint) }, + { 0 } }; static unsigned char hexTrue = 0xff; static unsigned char hexFalse = 0x00; -#define GEN_BREAK(status) rv = status; break; +#define GEN_BREAK(status) \ + rv = status; \ + break; -SECStatus CERT_EncodeBasicConstraintValue - (PLArenaPool *arena, CERTBasicConstraints *value, SECItem *encodedValue) +SECStatus +CERT_EncodeBasicConstraintValue(PLArenaPool *arena, CERTBasicConstraints *value, + SECItem *encodedValue) { EncodedContext encodeContext; PLArenaPool *our_pool = NULL; SECStatus rv = SECSuccess; do { - PORT_Memset (&encodeContext, 0, sizeof (encodeContext)); - if (!value->isCA && value->pathLenConstraint >= 0) { - PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID); - GEN_BREAK (SECFailure); - } + PORT_Memset(&encodeContext, 0, sizeof(encodeContext)); + if (!value->isCA && value->pathLenConstraint >= 0) { + PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID); + GEN_BREAK(SECFailure); + } encodeContext.arena = arena; - if (value->isCA == PR_TRUE) { - encodeContext.isCA.data = &hexTrue ; - encodeContext.isCA.len = 1; - } + if (value->isCA == PR_TRUE) { + encodeContext.isCA.data = &hexTrue; + encodeContext.isCA.len = 1; + } - /* If the pathLenConstraint is less than 0, then it should be - * omitted from the encoding. - */ - if (value->isCA && value->pathLenConstraint >= 0) { - our_pool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE); - if (our_pool == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - GEN_BREAK (SECFailure); - } - if (SEC_ASN1EncodeUnsignedInteger - (our_pool, &encodeContext.pathLenConstraint, - (unsigned long)value->pathLenConstraint) == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - GEN_BREAK (SECFailure); - } - } - if (SEC_ASN1EncodeItem (arena, encodedValue, &encodeContext, - CERTBasicConstraintsTemplate) == NULL) { - GEN_BREAK (SECFailure); - } + /* If the pathLenConstraint is less than 0, then it should be + * omitted from the encoding. + */ + if (value->isCA && value->pathLenConstraint >= 0) { + our_pool = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); + if (our_pool == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + GEN_BREAK(SECFailure); + } + if (SEC_ASN1EncodeUnsignedInteger( + our_pool, &encodeContext.pathLenConstraint, + (unsigned long)value->pathLenConstraint) == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + GEN_BREAK(SECFailure); + } + } + if (SEC_ASN1EncodeItem(arena, encodedValue, &encodeContext, + CERTBasicConstraintsTemplate) == NULL) { + GEN_BREAK(SECFailure); + } } while (0); if (our_pool) - PORT_FreeArena (our_pool, PR_FALSE); - return(rv); - + PORT_FreeArena(our_pool, PR_FALSE); + return (rv); } -SECStatus CERT_DecodeBasicConstraintValue - (CERTBasicConstraints *value, const SECItem *encodedValue) +SECStatus +CERT_DecodeBasicConstraintValue(CERTBasicConstraints *value, + const SECItem *encodedValue) { EncodedContext decodeContext; PLArenaPool *our_pool; SECStatus rv = SECSuccess; do { - PORT_Memset (&decodeContext, 0, sizeof (decodeContext)); - /* initialize the value just in case we got "0x30 00", or when the - pathLenConstraint is omitted. + PORT_Memset(&decodeContext, 0, sizeof(decodeContext)); + /* initialize the value just in case we got "0x30 00", or when the + pathLenConstraint is omitted. */ - decodeContext.isCA.data =&hexFalse; - decodeContext.isCA.len = 1; - - our_pool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE); - if (our_pool == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - GEN_BREAK (SECFailure); - } + decodeContext.isCA.data = &hexFalse; + decodeContext.isCA.len = 1; + + our_pool = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); + if (our_pool == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + GEN_BREAK(SECFailure); + } + + rv = SEC_QuickDERDecodeItem(our_pool, &decodeContext, + CERTBasicConstraintsTemplate, encodedValue); + if (rv == SECFailure) + break; + + value->isCA = decodeContext.isCA.data + ? (PRBool)(decodeContext.isCA.data[0] != 0) + : PR_FALSE; + if (decodeContext.pathLenConstraint.data == NULL) { + /* if the pathLenConstraint is not encoded, and the current setting + is CA, then the pathLenConstraint should be set to a negative + number + for unlimited certificate path. + */ + if (value->isCA) + value->pathLenConstraint = CERT_UNLIMITED_PATH_CONSTRAINT; + } + else if (value->isCA) { + long len = DER_GetInteger(&decodeContext.pathLenConstraint); + if (len < 0 || len == LONG_MAX) { + PORT_SetError(SEC_ERROR_BAD_DER); + GEN_BREAK(SECFailure); + } + value->pathLenConstraint = len; + } + else { + /* here we get an error where the subject is not a CA, but + the pathLenConstraint is set */ + PORT_SetError(SEC_ERROR_BAD_DER); + GEN_BREAK(SECFailure); + break; + } - rv = SEC_QuickDERDecodeItem - (our_pool, &decodeContext, CERTBasicConstraintsTemplate, encodedValue); - if (rv == SECFailure) - break; - - value->isCA = decodeContext.isCA.data - ? (PRBool)(decodeContext.isCA.data[0] != 0) - : PR_FALSE; - if (decodeContext.pathLenConstraint.data == NULL) { - /* if the pathLenConstraint is not encoded, and the current setting - is CA, then the pathLenConstraint should be set to a negative number - for unlimited certificate path. - */ - if (value->isCA) - value->pathLenConstraint = CERT_UNLIMITED_PATH_CONSTRAINT; - } else if (value->isCA) { - long len = DER_GetInteger (&decodeContext.pathLenConstraint); - if (len < 0 || len == LONG_MAX) { - PORT_SetError (SEC_ERROR_BAD_DER); - GEN_BREAK (SECFailure); - } - value->pathLenConstraint = len; - } else { - /* here we get an error where the subject is not a CA, but - the pathLenConstraint is set */ - PORT_SetError (SEC_ERROR_BAD_DER); - GEN_BREAK (SECFailure); - break; - } - } while (0); - PORT_FreeArena (our_pool, PR_FALSE); + PORT_FreeArena(our_pool, PR_FALSE); return (rv); - } diff --git a/security/nss/lib/certdb/xconst.c b/security/nss/lib/certdb/xconst.c index 495987c488c2..9a5634a906b1 100644 --- a/security/nss/lib/certdb/xconst.c +++ b/security/nss/lib/certdb/xconst.c @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * X.509 Extension Encoding + * X.509 Extension Encoding */ #include "prtypes.h" @@ -20,12 +20,10 @@ #include "secasn1.h" #include "secerr.h" - static const SEC_ASN1Template CERTSubjectKeyIDTemplate[] = { { SEC_ASN1_OCTET_STRING } }; - static const SEC_ASN1Template CERTIA5TypeTemplate[] = { { SEC_ASN1_IA5_STRING } }; @@ -33,40 +31,34 @@ static const SEC_ASN1Template CERTIA5TypeTemplate[] = { SEC_ASN1_MKSUB(SEC_GeneralizedTimeTemplate) static const SEC_ASN1Template CERTPrivateKeyUsagePeriodTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTPrivKeyUsagePeriod) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(CERTPrivKeyUsagePeriod, notBefore), - SEC_ASN1_SUB(SEC_GeneralizedTimeTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, - offsetof(CERTPrivKeyUsagePeriod, notAfter), - SEC_ASN1_SUB(SEC_GeneralizedTimeTemplate)}, - { 0, } + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTPrivKeyUsagePeriod) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(CERTPrivKeyUsagePeriod, notBefore), + SEC_ASN1_SUB(SEC_GeneralizedTimeTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, + offsetof(CERTPrivKeyUsagePeriod, notAfter), + SEC_ASN1_SUB(SEC_GeneralizedTimeTemplate) }, + { 0 } }; - const SEC_ASN1Template CERTAltNameTemplate[] = { - { SEC_ASN1_CONSTRUCTED, offsetof(CERTAltNameEncodedContext, encodedGenName), - CERT_GeneralNamesTemplate} + { SEC_ASN1_CONSTRUCTED, offsetof(CERTAltNameEncodedContext, encodedGenName), + CERT_GeneralNamesTemplate } }; const SEC_ASN1Template CERTAuthInfoAccessItemTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTAuthInfoAccess) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CERTAuthInfoAccess, method) }, - { SEC_ASN1_ANY, - offsetof(CERTAuthInfoAccess, derLocation) }, - { 0, } + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTAuthInfoAccess) }, + { SEC_ASN1_OBJECT_ID, offsetof(CERTAuthInfoAccess, method) }, + { SEC_ASN1_ANY, offsetof(CERTAuthInfoAccess, derLocation) }, + { 0 } }; const SEC_ASN1Template CERTAuthInfoAccessTemplate[] = { { SEC_ASN1_SEQUENCE_OF, 0, CERTAuthInfoAccessItemTemplate } }; - -SECStatus -CERT_EncodeSubjectKeyID(PLArenaPool *arena, const SECItem* srcString, +SECStatus +CERT_EncodeSubjectKeyID(PLArenaPool *arena, const SECItem *srcString, SECItem *encodedValue) { SECStatus rv = SECSuccess; @@ -75,27 +67,26 @@ CERT_EncodeSubjectKeyID(PLArenaPool *arena, const SECItem* srcString, PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - if (SEC_ASN1EncodeItem (arena, encodedValue, srcString, - CERTSubjectKeyIDTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, encodedValue, srcString, + CERTSubjectKeyIDTemplate) == NULL) { + rv = SECFailure; } - - return(rv); -} + return (rv); +} SECStatus CERT_EncodePrivateKeyUsagePeriod(PLArenaPool *arena, - CERTPrivKeyUsagePeriod *pkup, - SECItem *encodedValue) + CERTPrivKeyUsagePeriod *pkup, + SECItem *encodedValue) { SECStatus rv = SECSuccess; - if (SEC_ASN1EncodeItem (arena, encodedValue, pkup, - CERTPrivateKeyUsagePeriodTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, encodedValue, pkup, + CERTPrivateKeyUsagePeriodTemplate) == NULL) { + rv = SECFailure; } - return(rv); + return (rv); } CERTPrivKeyUsagePeriod * @@ -107,63 +98,62 @@ CERT_DecodePrivKeyUsagePeriodExtension(PLArenaPool *arena, SECItem *extnValue) /* allocate the certificate policies structure */ pPeriod = PORT_ArenaZNew(arena, CERTPrivKeyUsagePeriod); - if ( pPeriod == NULL ) { - goto loser; + if (pPeriod == NULL) { + goto loser; } - + pPeriod->arena = arena; /* 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, &newExtnValue, extnValue); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - rv = SEC_QuickDERDecodeItem(arena, pPeriod, - CERTPrivateKeyUsagePeriodTemplate, - &newExtnValue); - if ( rv != SECSuccess ) { - goto loser; + rv = SEC_QuickDERDecodeItem( + arena, pPeriod, CERTPrivateKeyUsagePeriodTemplate, &newExtnValue); + if (rv != SECSuccess) { + goto loser; } return pPeriod; - + loser: return NULL; } - -SECStatus -CERT_EncodeIA5TypeExtension(PLArenaPool *arena, char *value, SECItem *encodedValue) +SECStatus +CERT_EncodeIA5TypeExtension(PLArenaPool *arena, char *value, + SECItem *encodedValue) { SECItem encodeContext; SECStatus rv = SECSuccess; + PORT_Memset(&encodeContext, 0, sizeof(encodeContext)); - PORT_Memset (&encodeContext, 0, sizeof (encodeContext)); - if (value != NULL) { - encodeContext.data = (unsigned char *)value; - encodeContext.len = strlen(value); + encodeContext.data = (unsigned char *)value; + encodeContext.len = strlen(value); } - if (SEC_ASN1EncodeItem (arena, encodedValue, &encodeContext, - CERTIA5TypeTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, encodedValue, &encodeContext, + CERTIA5TypeTemplate) == NULL) { + rv = SECFailure; } - - return(rv); + + return (rv); } SECStatus -CERT_EncodeAltNameExtension(PLArenaPool *arena, CERTGeneralName *value, SECItem *encodedValue) +CERT_EncodeAltNameExtension(PLArenaPool *arena, CERTGeneralName *value, + SECItem *encodedValue) { - SECItem **encodedGenName; - SECStatus rv = SECSuccess; + SECItem **encodedGenName; + SECStatus rv = SECSuccess; encodedGenName = cert_EncodeGeneralNames(arena, value); - if (SEC_ASN1EncodeItem (arena, encodedValue, &encodedGenName, - CERT_GeneralNamesTemplate) == NULL) { - rv = SECFailure; + if (SEC_ASN1EncodeItem(arena, encodedValue, &encodedGenName, + CERT_GeneralNamesTemplate) == NULL) { + rv = SECFailure; } return rv; @@ -172,9 +162,9 @@ CERT_EncodeAltNameExtension(PLArenaPool *arena, CERTGeneralName *value, SECIte CERTGeneralName * CERT_DecodeAltNameExtension(PLArenaPool *reqArena, SECItem *EncodedAltName) { - SECStatus rv = SECSuccess; - CERTAltNameEncodedContext encodedContext; - SECItem* newEncodedAltName; + SECStatus rv = SECSuccess; + CERTAltNameEncodedContext encodedContext; + SECItem *newEncodedAltName; if (!reqArena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -188,14 +178,13 @@ CERT_DecodeAltNameExtension(PLArenaPool *reqArena, SECItem *EncodedAltName) encodedContext.encodedGenName = NULL; PORT_Memset(&encodedContext, 0, sizeof(CERTAltNameEncodedContext)); - rv = SEC_QuickDERDecodeItem (reqArena, &encodedContext, - CERT_GeneralNamesTemplate, newEncodedAltName); + rv = SEC_QuickDERDecodeItem(reqArena, &encodedContext, + CERT_GeneralNamesTemplate, newEncodedAltName); if (rv == SECFailure) { - goto loser; + goto loser; } if (encodedContext.encodedGenName && encodedContext.encodedGenName[0]) - return cert_DecodeGeneralNames(reqArena, - encodedContext.encodedGenName); + return cert_DecodeGeneralNames(reqArena, encodedContext.encodedGenName); /* Extension contained an empty GeneralNames sequence */ /* Treat as extension not found */ PORT_SetError(SEC_ERROR_EXTENSION_NOT_FOUND); @@ -203,35 +192,32 @@ loser: return NULL; } - SECStatus -CERT_EncodeNameConstraintsExtension(PLArenaPool *arena, - CERTNameConstraints *value, - SECItem *encodedValue) +CERT_EncodeNameConstraintsExtension(PLArenaPool *arena, + CERTNameConstraints *value, + SECItem *encodedValue) { - SECStatus rv = SECSuccess; - + SECStatus rv = SECSuccess; + rv = cert_EncodeNameConstraints(value, arena, encodedValue); return rv; } - CERTNameConstraints * -CERT_DecodeNameConstraintsExtension(PLArenaPool *arena, - const SECItem *encodedConstraints) +CERT_DecodeNameConstraintsExtension(PLArenaPool *arena, + const SECItem *encodedConstraints) { return cert_DecodeNameConstraints(arena, encodedConstraints); } - CERTAuthInfoAccess ** CERT_DecodeAuthInfoAccessExtension(PLArenaPool *reqArena, - const SECItem *encodedExtension) + const SECItem *encodedExtension) { CERTAuthInfoAccess **info = NULL; SECStatus rv; int i; - SECItem* newEncodedExtension; + SECItem *newEncodedExtension; if (!reqArena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -243,24 +229,22 @@ CERT_DecodeAuthInfoAccessExtension(PLArenaPool *reqArena, return NULL; } - rv = SEC_QuickDERDecodeItem(reqArena, &info, CERTAuthInfoAccessTemplate, - newEncodedExtension); + rv = SEC_QuickDERDecodeItem(reqArena, &info, CERTAuthInfoAccessTemplate, + newEncodedExtension); if (rv != SECSuccess || info == NULL) { - return NULL; + return NULL; } for (i = 0; info[i] != NULL; i++) { - info[i]->location = CERT_DecodeGeneralName(reqArena, - &(info[i]->derLocation), - NULL); + info[i]->location = + CERT_DecodeGeneralName(reqArena, &(info[i]->derLocation), NULL); } return info; } SECStatus -CERT_EncodeInfoAccessExtension(PLArenaPool *arena, - CERTAuthInfoAccess **info, - SECItem *dest) +CERT_EncodeInfoAccessExtension(PLArenaPool *arena, CERTAuthInfoAccess **info, + SECItem *dest) { SECItem *dummy; int i; @@ -268,19 +252,18 @@ CERT_EncodeInfoAccessExtension(PLArenaPool *arena, PORT_Assert(info != NULL); PORT_Assert(dest != NULL); if (info == NULL || dest == NULL) { - return SECFailure; + return SECFailure; } for (i = 0; info[i] != NULL; i++) { - if (CERT_EncodeGeneralName(info[i]->location, &(info[i]->derLocation), - arena) == NULL) - /* Note that this may leave some of the locations filled in. */ - return SECFailure; + if (CERT_EncodeGeneralName(info[i]->location, &(info[i]->derLocation), + arena) == NULL) + /* Note that this may leave some of the locations filled in. */ + return SECFailure; } - dummy = SEC_ASN1EncodeItem(arena, dest, &info, - CERTAuthInfoAccessTemplate); + dummy = SEC_ASN1EncodeItem(arena, dest, &info, CERTAuthInfoAccessTemplate); if (dummy == NULL) { - return SECFailure; + return SECFailure; } return SECSuccess; } diff --git a/security/nss/lib/certdb/xconst.h b/security/nss/lib/certdb/xconst.h index 72767c30a0e3..8cf2e826e038 100644 --- a/security/nss/lib/certdb/xconst.h +++ b/security/nss/lib/certdb/xconst.h @@ -10,27 +10,21 @@ typedef struct CERTAltNameEncodedContextStr { SECItem **encodedGenName; } CERTAltNameEncodedContext; - - SEC_BEGIN_PROTOS -extern SECStatus -CERT_EncodePrivateKeyUsagePeriod(PLArenaPool *arena, - CERTPrivKeyUsagePeriod *pkup, - SECItem *encodedValue); +extern SECStatus CERT_EncodePrivateKeyUsagePeriod(PLArenaPool *arena, + CERTPrivKeyUsagePeriod *pkup, + SECItem *encodedValue); -extern SECStatus -CERT_EncodeNameConstraintsExtension(PLArenaPool *arena, - CERTNameConstraints *value, - SECItem *encodedValue); +extern SECStatus CERT_EncodeNameConstraintsExtension(PLArenaPool *arena, + CERTNameConstraints *value, + SECItem *encodedValue); -extern SECStatus -CERT_EncodeIA5TypeExtension(PLArenaPool *arena, char *value, - SECItem *encodedValue); +extern SECStatus CERT_EncodeIA5TypeExtension(PLArenaPool *arena, char *value, + SECItem *encodedValue); -SECStatus -cert_EncodeAuthInfoAccessExtension(PLArenaPool *arena, - CERTAuthInfoAccess **info, - SECItem *dest); +SECStatus cert_EncodeAuthInfoAccessExtension(PLArenaPool *arena, + CERTAuthInfoAccess **info, + SECItem *dest); SEC_END_PROTOS #endif diff --git a/security/nss/lib/certhigh/certhigh.c b/security/nss/lib/certhigh/certhigh.c index b06b7af331d0..2cb6b8c81a9a 100644 --- a/security/nss/lib/certhigh/certhigh.c +++ b/security/nss/lib/certhigh/certhigh.c @@ -17,36 +17,37 @@ #include "pkitm.h" #include "pki3hack.h" - PRBool -CERT_MatchNickname(char *name1, char *name2) { - char *nickname1= NULL; +CERT_MatchNickname(char *name1, char *name2) +{ + char *nickname1 = NULL; char *nickname2 = NULL; char *token1; char *token2; /* first deal with the straight comparison */ if (PORT_Strcmp(name1, name2) == 0) { - return PR_TRUE; + return PR_TRUE; } /* we need to handle the case where one name has an explicit token and the other * doesn't */ - token1 = PORT_Strchr(name1,':'); - token2 = PORT_Strchr(name2,':'); + token1 = PORT_Strchr(name1, ':'); + token2 = PORT_Strchr(name2, ':'); if ((token1 && token2) || (!token1 && !token2)) { - /* either both token names are specified or neither are, not match */ - return PR_FALSE; + /* either both token names are specified or neither are, not match */ + return PR_FALSE; } if (token1) { - nickname1=token1; - nickname2=name2; - } else { - nickname1=token2; - nickname2=name1; + nickname1 = token1; + nickname2 = name2; + } + else { + nickname1 = token2; + nickname2 = name1; } nickname1++; - if (PORT_Strcmp(nickname1,nickname2) != 0) { - return PR_FALSE; + if (PORT_Strcmp(nickname1, nickname2) != 0) { + return PR_FALSE; } /* Bug 1192443 - compare the other token with the internal slot here */ return PR_TRUE; @@ -54,7 +55,7 @@ CERT_MatchNickname(char *name1, char *name2) { /* * Find all user certificates that match the given criteria. - * + * * "handle" - database to search * "usage" - certificate usage to match * "oneCertPerName" - if set then only return the "best" cert per @@ -64,10 +65,10 @@ CERT_MatchNickname(char *name1, char *name2) { */ CERTCertList * CERT_FindUserCertsByUsage(CERTCertDBHandle *handle, - SECCertUsage usage, - PRBool oneCertPerName, - PRBool validOnly, - void *proto_win) + SECCertUsage usage, + PRBool oneCertPerName, + PRBool validOnly, + void *proto_win) { CERTCertNicknames *nicknames = NULL; char **nnptr; @@ -79,29 +80,29 @@ CERT_FindUserCertsByUsage(CERTCertDBHandle *handle, CERTCertListNode *node = NULL; CERTCertListNode *freenode = NULL; int n; - + time = PR_Now(); - + nicknames = CERT_GetCertNicknames(handle, SEC_CERT_NICKNAMES_USER, - proto_win); - - if ( ( nicknames == NULL ) || ( nicknames->numnicknames == 0 ) ) { - goto loser; + proto_win); + + if ((nicknames == NULL) || (nicknames->numnicknames == 0)) { + goto loser; } nnptr = nicknames->nicknames; nn = nicknames->numnicknames; - while ( nn > 0 ) { - cert = NULL; - /* use the pk11 call so that we pick up any certs on tokens, + while (nn > 0) { + cert = NULL; + /* use the pk11 call so that we pick up any certs on tokens, * which may require login */ - if ( proto_win != NULL ) { - cert = PK11_FindCertFromNickname(*nnptr,proto_win); - } + if (proto_win != NULL) { + cert = PK11_FindCertFromNickname(*nnptr, proto_win); + } - /* Sigh, It turns out if the cert is already in the temp db, because + /* Sigh, It turns out if the cert is already in the temp db, because * it's in the perm db, then the nickname lookup doesn't work. * since we already have the cert here, though, than we can just call * CERT_CreateSubjectCertList directly. For those cases where we didn't @@ -109,104 +110,105 @@ CERT_FindUserCertsByUsage(CERTCertDBHandle *handle, * or because the nickname is for a peer, server, or CA cert, then we * go look the cert up. */ - if (cert == NULL) { - cert = CERT_FindCertByNickname(handle,*nnptr); - } + if (cert == NULL) { + cert = CERT_FindCertByNickname(handle, *nnptr); + } - if ( cert != NULL ) { - /* collect certs for this nickname, sorting them into the list */ - certList = CERT_CreateSubjectCertList(certList, handle, - &cert->derSubject, time, validOnly); + if (cert != NULL) { + /* collect certs for this nickname, sorting them into the list */ + certList = CERT_CreateSubjectCertList(certList, handle, + &cert->derSubject, time, validOnly); - CERT_FilterCertListForUserCerts(certList); - - /* drop the extra reference */ - CERT_DestroyCertificate(cert); - } - - nnptr++; - nn--; + CERT_FilterCertListForUserCerts(certList); + + /* drop the extra reference */ + CERT_DestroyCertificate(cert); + } + + nnptr++; + nn--; } /* remove certs with incorrect usage */ rv = CERT_FilterCertListByUsage(certList, usage, PR_FALSE); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* remove any extra certs for each name */ - if ( oneCertPerName ) { - PRBool *flags; + if (oneCertPerName) { + PRBool *flags; - nn = nicknames->numnicknames; - nnptr = nicknames->nicknames; - - flags = (PRBool *)PORT_ZAlloc(sizeof(PRBool) * nn); - if ( flags == NULL ) { - goto loser; - } - - node = CERT_LIST_HEAD(certList); - - /* treverse all certs in the list */ - while ( !CERT_LIST_END(node, certList) ) { + nn = nicknames->numnicknames; + nnptr = nicknames->nicknames; - /* find matching nickname index */ - for ( n = 0; n < nn; n++ ) { - if ( CERT_MatchNickname(nnptr[n], node->cert->nickname) ) { - /* We found a match. If this is the first one, then + flags = (PRBool *)PORT_ZAlloc(sizeof(PRBool) * nn); + if (flags == NULL) { + goto loser; + } + + node = CERT_LIST_HEAD(certList); + + /* treverse all certs in the list */ + while (!CERT_LIST_END(node, certList)) { + + /* find matching nickname index */ + for (n = 0; n < nn; n++) { + if (CERT_MatchNickname(nnptr[n], node->cert->nickname)) { + /* We found a match. If this is the first one, then * set the flag and move on to the next cert. If this * is not the first one then delete it from the list. */ - if ( flags[n] ) { - /* We have already seen a cert with this nickname, + if (flags[n]) { + /* We have already seen a cert with this nickname, * so delete this one. */ - freenode = node; - node = CERT_LIST_NEXT(node); - CERT_RemoveCertListNode(freenode); - } else { - /* keep the first cert for each nickname, but set the + freenode = node; + node = CERT_LIST_NEXT(node); + CERT_RemoveCertListNode(freenode); + } + else { + /* keep the first cert for each nickname, but set the * flag so we know to delete any others with the same * nickname. */ - flags[n] = PR_TRUE; - node = CERT_LIST_NEXT(node); - } - break; - } - } - if ( n == nn ) { - /* if we get here it means that we didn't find a matching + flags[n] = PR_TRUE; + node = CERT_LIST_NEXT(node); + } + break; + } + } + if (n == nn) { + /* if we get here it means that we didn't find a matching * nickname, which should not happen. */ - PORT_Assert(0); - node = CERT_LIST_NEXT(node); - } - } - PORT_Free(flags); + PORT_Assert(0); + node = CERT_LIST_NEXT(node); + } + } + PORT_Free(flags); } goto done; - + loser: - if ( certList != NULL ) { - CERT_DestroyCertList(certList); - certList = NULL; + if (certList != NULL) { + CERT_DestroyCertList(certList); + certList = NULL; } done: - if ( nicknames != NULL ) { - CERT_FreeNicknames(nicknames); + if (nicknames != NULL) { + CERT_FreeNicknames(nicknames); } - return(certList); + return (certList); } /* * Find a user certificate that matchs the given criteria. - * + * * "handle" - database to search * "nickname" - nickname to match * "usage" - certificate usage to match @@ -215,131 +217,129 @@ done: */ CERTCertificate * CERT_FindUserCertByUsage(CERTCertDBHandle *handle, - const char *nickname, - SECCertUsage usage, - PRBool validOnly, - void *proto_win) + const char *nickname, + SECCertUsage usage, + PRBool validOnly, + void *proto_win) { CERTCertificate *cert = NULL; CERTCertList *certList = NULL; SECStatus rv; PRTime time; - + time = PR_Now(); - + /* use the pk11 call so that we pick up any certs on tokens, * which may require login */ /* XXX - why is this restricted? */ - if ( proto_win != NULL ) { - cert = PK11_FindCertFromNickname(nickname,proto_win); + if (proto_win != NULL) { + cert = PK11_FindCertFromNickname(nickname, proto_win); } - /* sigh, There are still problems find smart cards from the temp * db. This will get smart cards working again. The real fix * is to make sure we can search the temp db by their token nickname. */ if (cert == NULL) { - cert = CERT_FindCertByNickname(handle,nickname); + cert = CERT_FindCertByNickname(handle, nickname); } - if ( cert != NULL ) { - unsigned int requiredKeyUsage; - unsigned int requiredCertType; + if (cert != NULL) { + unsigned int requiredKeyUsage; + unsigned int requiredCertType; - rv = CERT_KeyUsageAndTypeForCertUsage(usage, PR_FALSE, - &requiredKeyUsage, &requiredCertType); - if ( rv != SECSuccess ) { - /* drop the extra reference */ - CERT_DestroyCertificate(cert); - cert = NULL; - goto loser; - } - /* If we already found the right cert, just return it */ - if ( (!validOnly || CERT_CheckCertValidTimes(cert, time, PR_FALSE) - == secCertTimeValid) && - (CERT_CheckKeyUsage(cert, requiredKeyUsage) == SECSuccess) && - (cert->nsCertType & requiredCertType) && - CERT_IsUserCert(cert) ) { - return(cert); - } + rv = CERT_KeyUsageAndTypeForCertUsage(usage, PR_FALSE, + &requiredKeyUsage, &requiredCertType); + if (rv != SECSuccess) { + /* drop the extra reference */ + CERT_DestroyCertificate(cert); + cert = NULL; + goto loser; + } + /* If we already found the right cert, just return it */ + if ((!validOnly || CERT_CheckCertValidTimes(cert, time, PR_FALSE) == + secCertTimeValid) && + (CERT_CheckKeyUsage(cert, requiredKeyUsage) == SECSuccess) && + (cert->nsCertType & requiredCertType) && + CERT_IsUserCert(cert)) { + return (cert); + } - /* collect certs for this nickname, sorting them into the list */ - certList = CERT_CreateSubjectCertList(certList, handle, - &cert->derSubject, time, validOnly); + /* collect certs for this nickname, sorting them into the list */ + certList = CERT_CreateSubjectCertList(certList, handle, + &cert->derSubject, time, validOnly); - CERT_FilterCertListForUserCerts(certList); + CERT_FilterCertListForUserCerts(certList); - /* drop the extra reference */ - CERT_DestroyCertificate(cert); - cert = NULL; + /* drop the extra reference */ + CERT_DestroyCertificate(cert); + cert = NULL; } - - if ( certList == NULL ) { - goto loser; + + if (certList == NULL) { + goto loser; } - + /* remove certs with incorrect usage */ rv = CERT_FilterCertListByUsage(certList, usage, PR_FALSE); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - if ( ! CERT_LIST_END(CERT_LIST_HEAD(certList), certList) ) { - cert = CERT_DupCertificate(CERT_LIST_HEAD(certList)->cert); + if (!CERT_LIST_END(CERT_LIST_HEAD(certList), certList)) { + cert = CERT_DupCertificate(CERT_LIST_HEAD(certList)->cert); } - + loser: - if ( certList != NULL ) { - CERT_DestroyCertList(certList); + if (certList != NULL) { + CERT_DestroyCertList(certList); } - return(cert); + return (cert); } CERTCertList * CERT_MatchUserCert(CERTCertDBHandle *handle, - SECCertUsage usage, - int nCANames, char **caNames, - void *proto_win) + SECCertUsage usage, + int nCANames, char **caNames, + void *proto_win) { CERTCertList *certList = NULL; SECStatus rv; certList = CERT_FindUserCertsByUsage(handle, usage, PR_TRUE, PR_TRUE, - proto_win); - if ( certList == NULL ) { - goto loser; + proto_win); + if (certList == NULL) { + goto loser; } - + rv = CERT_FilterCertListByCANames(certList, nCANames, caNames, usage); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + goto done; - + loser: - if ( certList != NULL ) { - CERT_DestroyCertList(certList); - certList = NULL; + if (certList != NULL) { + CERT_DestroyCertList(certList); + certList = NULL; } done: - return(certList); + return (certList); } - typedef struct stringNode { struct stringNode *next; char *string; } stringNode; - + static PRStatus -CollectNicknames( NSSCertificate *c, void *data) +CollectNicknames(NSSCertificate *c, void *data) { CERTCertNicknames *names; PRBool saveit = PR_FALSE; @@ -351,103 +351,104 @@ CollectNicknames( NSSCertificate *c, void *data) #endif char *stanNickname; char *nickname = NULL; - + names = (CERTCertNicknames *)data; - stanNickname = nssCertificate_GetNickname(c,NULL); - - if ( stanNickname ) { + stanNickname = nssCertificate_GetNickname(c, NULL); + + if (stanNickname) { nss_ZFreeIf(stanNickname); stanNickname = NULL; - if (names->what == SEC_CERT_NICKNAMES_USER) { - saveit = NSSCertificate_IsPrivateKeyAvailable(c, NULL, NULL); - } + if (names->what == SEC_CERT_NICKNAMES_USER) { + saveit = NSSCertificate_IsPrivateKeyAvailable(c, NULL, NULL); + } #ifdef notdef - else { - td = NSSCertificate_GetTrustDomain(c); - if (!td) { - return PR_SUCCESS; - } - trust = nssTrustDomain_FindTrustForCertificate(td,c); - - switch(names->what) { - case SEC_CERT_NICKNAMES_ALL: - if ((trust->sslFlags & (CERTDB_VALID_CA|CERTDB_VALID_PEER) ) || - (trust->emailFlags & (CERTDB_VALID_CA|CERTDB_VALID_PEER) ) || - (trust->objectSigningFlags & - (CERTDB_VALID_CA|CERTDB_VALID_PEER))) { - saveit = PR_TRUE; - } - - break; - case SEC_CERT_NICKNAMES_SERVER: - if ( trust->sslFlags & CERTDB_VALID_PEER ) { - saveit = PR_TRUE; - } - - break; - case SEC_CERT_NICKNAMES_CA: - if (((trust->sslFlags & CERTDB_VALID_CA ) == CERTDB_VALID_CA)|| - ((trust->emailFlags & CERTDB_VALID_CA ) == CERTDB_VALID_CA) || - ((trust->objectSigningFlags & CERTDB_VALID_CA ) - == CERTDB_VALID_CA)) { - saveit = PR_TRUE; - } - break; - } - } + else { + td = NSSCertificate_GetTrustDomain(c); + if (!td) { + return PR_SUCCESS; + } + trust = nssTrustDomain_FindTrustForCertificate(td, c); + + switch (names->what) { + case SEC_CERT_NICKNAMES_ALL: + if ((trust->sslFlags & (CERTDB_VALID_CA | CERTDB_VALID_PEER)) || + (trust->emailFlags & (CERTDB_VALID_CA | CERTDB_VALID_PEER)) || + (trust->objectSigningFlags & + (CERTDB_VALID_CA | CERTDB_VALID_PEER))) { + saveit = PR_TRUE; + } + + break; + case SEC_CERT_NICKNAMES_SERVER: + if (trust->sslFlags & CERTDB_VALID_PEER) { + saveit = PR_TRUE; + } + + break; + case SEC_CERT_NICKNAMES_CA: + if (((trust->sslFlags & CERTDB_VALID_CA) == CERTDB_VALID_CA) || + ((trust->emailFlags & CERTDB_VALID_CA) == CERTDB_VALID_CA) || + ((trust->objectSigningFlags & CERTDB_VALID_CA) == + CERTDB_VALID_CA)) { + saveit = PR_TRUE; + } + break; + } + } #endif } /* traverse the list of collected nicknames and make sure we don't make * a duplicate */ - if ( saveit ) { - nickname = STAN_GetCERTCertificateName(NULL, c); - /* nickname can only be NULL here if we are having memory + if (saveit) { + nickname = STAN_GetCERTCertificateName(NULL, c); + /* nickname can only be NULL here if we are having memory * alloc problems */ - if (nickname == NULL) { - return PR_FAILURE; - } - node = (stringNode *)names->head; - while ( node != NULL ) { - if ( PORT_Strcmp(nickname, node->string) == 0 ) { - /* if the string matches, then don't save this one */ - saveit = PR_FALSE; - break; - } - node = node->next; - } + if (nickname == NULL) { + return PR_FAILURE; + } + node = (stringNode *)names->head; + while (node != NULL) { + if (PORT_Strcmp(nickname, node->string) == 0) { + /* if the string matches, then don't save this one */ + saveit = PR_FALSE; + break; + } + node = node->next; + } } - if ( saveit ) { - - /* allocate the node */ - node = (stringNode*)PORT_ArenaAlloc(names->arena, sizeof(stringNode)); - if ( node == NULL ) { - PORT_Free(nickname); - return PR_FAILURE; - } + if (saveit) { - /* copy the string */ - len = PORT_Strlen(nickname) + 1; - node->string = (char*)PORT_ArenaAlloc(names->arena, len); - if ( node->string == NULL ) { - PORT_Free(nickname); - return PR_FAILURE; - } - PORT_Memcpy(node->string, nickname, len); + /* allocate the node */ + node = (stringNode *)PORT_ArenaAlloc(names->arena, sizeof(stringNode)); + if (node == NULL) { + PORT_Free(nickname); + return PR_FAILURE; + } - /* link it into the list */ - node->next = (stringNode *)names->head; - names->head = (void *)node; + /* copy the string */ + len = PORT_Strlen(nickname) + 1; + node->string = (char *)PORT_ArenaAlloc(names->arena, len); + if (node->string == NULL) { + PORT_Free(nickname); + return PR_FAILURE; + } + PORT_Memcpy(node->string, nickname, len); - /* bump the count */ - names->numnicknames++; + /* link it into the list */ + node->next = (stringNode *)names->head; + names->head = (void *)node; + + /* bump the count */ + names->numnicknames++; } - - if (nickname) PORT_Free(nickname); - return(PR_SUCCESS); + + if (nickname) + PORT_Free(nickname); + return (PR_SUCCESS); } CERTCertNicknames * @@ -457,16 +458,16 @@ CERT_GetCertNicknames(CERTCertDBHandle *handle, int what, void *wincx) CERTCertNicknames *names; int i; stringNode *node; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(NULL); + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + return (NULL); } - + names = (CERTCertNicknames *)PORT_ArenaAlloc(arena, sizeof(CERTCertNicknames)); - if ( names == NULL ) { - goto loser; + if (names == NULL) { + goto loser; } names->arena = arena; @@ -477,43 +478,44 @@ CERT_GetCertNicknames(CERTCertDBHandle *handle, int what, void *wincx) names->totallen = 0; /* make sure we are logged in */ - (void) pk11_TraverseAllSlots(NULL, NULL, PR_TRUE, wincx); - + (void)pk11_TraverseAllSlots(NULL, NULL, PR_TRUE, wincx); + NSSTrustDomain_TraverseCertificates(handle, - CollectNicknames, (void *)names); - if ( names->numnicknames ) { - names->nicknames = (char**)PORT_ArenaAlloc(arena, - names->numnicknames * sizeof(char *)); + CollectNicknames, (void *)names); + if (names->numnicknames) { + names->nicknames = (char **)PORT_ArenaAlloc(arena, + names->numnicknames * + sizeof(char *)); - if ( names->nicknames == NULL ) { - goto loser; - } - - node = (stringNode *)names->head; - - for ( i = 0; i < names->numnicknames; i++ ) { - PORT_Assert(node != NULL); - - names->nicknames[i] = node->string; - names->totallen += PORT_Strlen(node->string); - node = node->next; - } + if (names->nicknames == NULL) { + goto loser; + } - PORT_Assert(node == NULL); + node = (stringNode *)names->head; + + for (i = 0; i < names->numnicknames; i++) { + PORT_Assert(node != NULL); + + names->nicknames[i] = node->string; + names->totallen += PORT_Strlen(node->string); + node = node->next; + } + + PORT_Assert(node == NULL); } - return(names); - + return (names); + loser: PORT_FreeArena(arena, PR_FALSE); - return(NULL); + return (NULL); } void CERT_FreeNicknames(CERTCertNicknames *nicknames) { PORT_FreeArena(nicknames->arena, PR_FALSE); - + return; } @@ -528,53 +530,53 @@ void CERT_FreeDistNames(CERTDistNames *names) { PORT_FreeArena(names->arena, PR_FALSE); - + return; } static SECStatus -CollectDistNames( CERTCertificate *cert, SECItem *k, void *data) +CollectDistNames(CERTCertificate *cert, SECItem *k, void *data) { CERTDistNames *names; PRBool saveit = PR_FALSE; CERTCertTrust trust; dnameNode *node; int len; - + names = (CERTDistNames *)data; - - if ( CERT_GetCertTrust(cert, &trust) == SECSuccess ) { - /* only collect names of CAs trusted for issuing SSL clients */ - if ( trust.sslFlags & CERTDB_TRUSTED_CLIENT_CA ) { - saveit = PR_TRUE; - } + + if (CERT_GetCertTrust(cert, &trust) == SECSuccess) { + /* only collect names of CAs trusted for issuing SSL clients */ + if (trust.sslFlags & CERTDB_TRUSTED_CLIENT_CA) { + saveit = PR_TRUE; + } } - if ( saveit ) { - /* allocate the node */ - node = (dnameNode*)PORT_ArenaAlloc(names->arena, sizeof(dnameNode)); - if ( node == NULL ) { - return(SECFailure); - } + if (saveit) { + /* allocate the node */ + node = (dnameNode *)PORT_ArenaAlloc(names->arena, sizeof(dnameNode)); + if (node == NULL) { + return (SECFailure); + } - /* copy the name */ - node->name.len = len = cert->derSubject.len; - node->name.type = siBuffer; - node->name.data = (unsigned char*)PORT_ArenaAlloc(names->arena, len); - if ( node->name.data == NULL ) { - return(SECFailure); - } - PORT_Memcpy(node->name.data, cert->derSubject.data, len); + /* copy the name */ + node->name.len = len = cert->derSubject.len; + node->name.type = siBuffer; + node->name.data = (unsigned char *)PORT_ArenaAlloc(names->arena, len); + if (node->name.data == NULL) { + return (SECFailure); + } + PORT_Memcpy(node->name.data, cert->derSubject.data, len); - /* link it into the list */ - node->next = (dnameNode *)names->head; - names->head = (void *)node; + /* link it into the list */ + node->next = (dnameNode *)names->head; + names->head = (void *)node; - /* bump the count */ - names->nnames++; + /* bump the count */ + names->nnames++; } - - return(SECSuccess); + + return (SECSuccess); } /* @@ -587,18 +589,18 @@ CERT_DupDistNames(CERTDistNames *orig) CERTDistNames *names; int i; SECStatus rv; - + /* allocate an arena to use */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(NULL); + PORT_SetError(SEC_ERROR_NO_MEMORY); + return (NULL); } - + /* allocate the header structure */ names = (CERTDistNames *)PORT_ArenaAlloc(arena, sizeof(CERTDistNames)); if (names == NULL) { - goto loser; + goto loser; } /* initialize the header struct */ @@ -606,26 +608,26 @@ CERT_DupDistNames(CERTDistNames *orig) names->head = NULL; names->nnames = orig->nnames; names->names = NULL; - + /* construct the array from the list */ if (orig->nnames) { - names->names = (SECItem*)PORT_ArenaNewArray(arena, SECItem, - orig->nnames); - if (names->names == NULL) { - goto loser; - } - for (i = 0; i < orig->nnames; i++) { + names->names = (SECItem *)PORT_ArenaNewArray(arena, SECItem, + orig->nnames); + if (names->names == NULL) { + goto loser; + } + for (i = 0; i < orig->nnames; i++) { rv = SECITEM_CopyItem(arena, &names->names[i], &orig->names[i]); if (rv != SECSuccess) { goto loser; } } } - return(names); - + return (names); + loser: PORT_FreeArena(arena, PR_FALSE); - return(NULL); + return (NULL); } CERTDistNames * @@ -636,18 +638,18 @@ CERT_GetSSLCACerts(CERTCertDBHandle *handle) int i; SECStatus rv; dnameNode *node; - + /* allocate an arena to use */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(NULL); + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + return (NULL); } - + /* allocate the header structure */ names = (CERTDistNames *)PORT_ArenaAlloc(arena, sizeof(CERTDistNames)); - if ( names == NULL ) { - goto loser; + if (names == NULL) { + goto loser; } /* initialize the header struct */ @@ -655,48 +657,48 @@ CERT_GetSSLCACerts(CERTCertDBHandle *handle) names->head = NULL; names->nnames = 0; names->names = NULL; - + /* collect the names from the database */ rv = PK11_TraverseSlotCerts(CollectDistNames, (void *)names, NULL); - if ( rv ) { - goto loser; + if (rv) { + goto loser; } /* construct the array from the list */ - if ( names->nnames ) { - names->names = (SECItem*)PORT_ArenaAlloc(arena, names->nnames * sizeof(SECItem)); + if (names->nnames) { + names->names = (SECItem *)PORT_ArenaAlloc(arena, names->nnames * sizeof(SECItem)); - if ( names->names == NULL ) { - goto loser; - } - - node = (dnameNode *)names->head; - - for ( i = 0; i < names->nnames; i++ ) { - PORT_Assert(node != NULL); - - names->names[i] = node->name; - node = node->next; - } + if (names->names == NULL) { + goto loser; + } - PORT_Assert(node == NULL); + node = (dnameNode *)names->head; + + for (i = 0; i < names->nnames; i++) { + PORT_Assert(node != NULL); + + names->names[i] = node->name; + node = node->next; + } + + PORT_Assert(node == NULL); } - return(names); - + return (names); + loser: PORT_FreeArena(arena, PR_FALSE); - return(NULL); + return (NULL); } CERTDistNames * CERT_DistNamesFromCertList(CERTCertList *certList) { - CERTDistNames * dnames = NULL; - PLArenaPool * arena; + CERTDistNames *dnames = NULL; + PLArenaPool *arena; CERTCertListNode *node = NULL; - SECItem * names = NULL; - int listLen = 0, i = 0; + SECItem *names = NULL; + int listLen = 0, i = 0; if (certList == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -704,23 +706,26 @@ CERT_DistNamesFromCertList(CERTCertList *certList) } node = CERT_LIST_HEAD(certList); - while ( ! CERT_LIST_END(node, certList) ) { + while (!CERT_LIST_END(node, certList)) { listLen += 1; node = CERT_LIST_NEXT(node); } - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) goto loser; + if (arena == NULL) + goto loser; dnames = PORT_ArenaZNew(arena, CERTDistNames); - if (dnames == NULL) goto loser; + if (dnames == NULL) + goto loser; dnames->arena = arena; dnames->nnames = listLen; dnames->names = names = PORT_ArenaZNewArray(arena, SECItem, listLen); - if (names == NULL) goto loser; + if (names == NULL) + goto loser; node = CERT_LIST_HEAD(certList); - while ( ! CERT_LIST_END(node, certList) ) { + while (!CERT_LIST_END(node, certList)) { CERTCertificate *cert = node->cert; SECStatus rv = SECITEM_CopyItem(arena, &names[i++], &cert->derSubject); if (rv == SECFailure) { @@ -738,38 +743,43 @@ loser: CERTDistNames * CERT_DistNamesFromNicknames(CERTCertDBHandle *handle, char **nicknames, - int nnames) + int nnames) { CERTDistNames *dnames = NULL; PLArenaPool *arena; int i, rv; SECItem *names = NULL; CERTCertificate *cert = NULL; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) goto loser; + if (arena == NULL) + goto loser; dnames = PORT_ArenaZNew(arena, CERTDistNames); - if (dnames == NULL) goto loser; + if (dnames == NULL) + goto loser; dnames->arena = arena; dnames->nnames = nnames; dnames->names = names = PORT_ArenaZNewArray(arena, SECItem, nnames); - if (names == NULL) goto loser; - + if (names == NULL) + goto loser; + for (i = 0; i < nnames; i++) { - cert = CERT_FindCertByNicknameOrEmailAddr(handle, nicknames[i]); - if (cert == NULL) goto loser; - rv = SECITEM_CopyItem(arena, &names[i], &cert->derSubject); - if (rv == SECFailure) goto loser; - CERT_DestroyCertificate(cert); + cert = CERT_FindCertByNicknameOrEmailAddr(handle, nicknames[i]); + if (cert == NULL) + goto loser; + rv = SECITEM_CopyItem(arena, &names[i], &cert->derSubject); + if (rv == SECFailure) + goto loser; + CERT_DestroyCertificate(cert); } return dnames; - + loser: if (cert != NULL) - CERT_DestroyCertificate(cert); + CERT_DestroyCertificate(cert); if (arena != NULL) - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return NULL; } @@ -784,36 +794,36 @@ CERT_FindCertByNameString(CERTCertDBHandle *handle, char *nameStr) SECItem *nameItem; CERTCertificate *cert = NULL; PLArenaPool *arena = NULL; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( arena == NULL ) { - goto loser; + + if (arena == NULL) { + goto loser; } - + name = CERT_AsciiToName(nameStr); - - if ( name ) { - nameItem = SEC_ASN1EncodeItem (arena, NULL, (void *)name, - CERT_NameTemplate); - if ( nameItem != NULL ) { + + if (name) { + nameItem = SEC_ASN1EncodeItem(arena, NULL, (void *)name, + CERT_NameTemplate); + if (nameItem != NULL) { cert = CERT_FindCertByName(handle, nameItem); - } - CERT_DestroyName(name); + } + CERT_DestroyName(name); } loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(cert); + + return (cert); } /* From certv3.c */ CERTCrlDistributionPoints * -CERT_FindCRLDistributionPoints (CERTCertificate *cert) +CERT_FindCRLDistributionPoints(CERTCertificate *cert) { SECItem encodedExtenValue; SECStatus rv; @@ -823,9 +833,9 @@ CERT_FindCRLDistributionPoints (CERTCertificate *cert) encodedExtenValue.len = 0; rv = cert_FindExtension(cert->extensions, SEC_OID_X509_CRL_DIST_POINTS, - &encodedExtenValue); - if ( rv != SECSuccess ) { - return (NULL); + &encodedExtenValue); + if (rv != SECSuccess) { + return (NULL); } dps = CERT_DecodeCRLDistributionPoints(cert->arena, &encodedExtenValue); @@ -836,13 +846,13 @@ CERT_FindCRLDistributionPoints (CERTCertificate *cert) } /* From crl.c */ -CERTSignedCrl * CERT_ImportCRL - (CERTCertDBHandle *handle, SECItem *derCRL, char *url, int type, void *wincx) +CERTSignedCrl * +CERT_ImportCRL(CERTCertDBHandle *handle, SECItem *derCRL, char *url, int type, void *wincx) { - CERTSignedCrl* retCrl = NULL; - PK11SlotInfo* slot = PK11_GetInternalKeySlot(); + CERTSignedCrl *retCrl = NULL; + PK11SlotInfo *slot = PK11_GetInternalKeySlot(); retCrl = PK11_ImportCRL(slot, derCRL, url, type, wincx, - CRL_IMPORT_DEFAULT_OPTIONS, NULL, CRL_DECODE_DEFAULT_OPTIONS); + CRL_IMPORT_DEFAULT_OPTIONS, NULL, CRL_DECODE_DEFAULT_OPTIONS); PK11_FreeSlot(slot); return retCrl; @@ -861,110 +871,111 @@ cert_ImportCAChain(SECItem *certs, int numcerts, SECCertUsage certUsage, PRBool PRBool isca; char *nickname; unsigned int certtype; - + handle = CERT_GetDefaultCertDB(); - + while (numcerts--) { - derCert = certs; - certs++; + derCert = certs; + certs++; - /* decode my certificate */ - /* This use is ok -- only looks at decoded parts, calls NewTemp later */ - newcert = CERT_DecodeDERCertificate(derCert, PR_FALSE, NULL); - if ( newcert == NULL ) { - goto loser; - } + /* decode my certificate */ + /* This use is ok -- only looks at decoded parts, calls NewTemp later */ + newcert = CERT_DecodeDERCertificate(derCert, PR_FALSE, NULL); + if (newcert == NULL) { + goto loser; + } - if (!trusted) { - /* make sure that cert is valid */ - rv = CERT_CertTimesValid(newcert); - if ( rv == SECFailure ) { - goto endloop; - } - } + if (!trusted) { + /* make sure that cert is valid */ + rv = CERT_CertTimesValid(newcert); + if (rv == SECFailure) { + goto endloop; + } + } - /* does it have the CA extension */ - - /* + /* does it have the CA extension */ + + /* * Make sure that if this is an intermediate CA in the chain that * it was given permission by its signer to be a CA. */ - isca = CERT_IsCACert(newcert, &certtype); + isca = CERT_IsCACert(newcert, &certtype); - if ( !isca ) { - if (!trusted) { - goto endloop; - } - trust.sslFlags = CERTDB_VALID_CA; - trust.emailFlags = CERTDB_VALID_CA; - trust.objectSigningFlags = CERTDB_VALID_CA; - } else { - /* SSL ca's must have the ssl bit set */ - if ( ( certUsage == certUsageSSLCA ) && - (( certtype & NS_CERT_TYPE_SSL_CA ) != NS_CERT_TYPE_SSL_CA )) { - goto endloop; - } + if (!isca) { + if (!trusted) { + goto endloop; + } + trust.sslFlags = CERTDB_VALID_CA; + trust.emailFlags = CERTDB_VALID_CA; + trust.objectSigningFlags = CERTDB_VALID_CA; + } + else { + /* SSL ca's must have the ssl bit set */ + if ((certUsage == certUsageSSLCA) && + ((certtype & NS_CERT_TYPE_SSL_CA) != NS_CERT_TYPE_SSL_CA)) { + goto endloop; + } - /* it passed all of the tests, so lets add it to the database */ - /* mark it as a CA */ - PORT_Memset((void *)&trust, 0, sizeof(trust)); - switch ( certUsage ) { - case certUsageSSLCA: - trust.sslFlags = CERTDB_VALID_CA; - break; - case certUsageUserCertImport: - if ((certtype & NS_CERT_TYPE_SSL_CA) == NS_CERT_TYPE_SSL_CA) { - trust.sslFlags = CERTDB_VALID_CA; - } - if ((certtype & NS_CERT_TYPE_EMAIL_CA) - == NS_CERT_TYPE_EMAIL_CA ) { - trust.emailFlags = CERTDB_VALID_CA; - } - if ( ( certtype & NS_CERT_TYPE_OBJECT_SIGNING_CA ) == - NS_CERT_TYPE_OBJECT_SIGNING_CA ) { - trust.objectSigningFlags = CERTDB_VALID_CA; - } - break; - default: - PORT_Assert(0); - break; - } - } - - cert = CERT_NewTempCertificate(handle, derCert, NULL, - PR_FALSE, PR_FALSE); - if ( cert == NULL ) { - goto loser; - } - - /* if the cert is temp, make it perm; otherwise we're done */ - if (cert->istemp) { - /* get a default nickname for it */ - nickname = CERT_MakeCANickname(cert); + /* it passed all of the tests, so lets add it to the database */ + /* mark it as a CA */ + PORT_Memset((void *)&trust, 0, sizeof(trust)); + switch (certUsage) { + case certUsageSSLCA: + trust.sslFlags = CERTDB_VALID_CA; + break; + case certUsageUserCertImport: + if ((certtype & NS_CERT_TYPE_SSL_CA) == NS_CERT_TYPE_SSL_CA) { + trust.sslFlags = CERTDB_VALID_CA; + } + if ((certtype & NS_CERT_TYPE_EMAIL_CA) == + NS_CERT_TYPE_EMAIL_CA) { + trust.emailFlags = CERTDB_VALID_CA; + } + if ((certtype & NS_CERT_TYPE_OBJECT_SIGNING_CA) == + NS_CERT_TYPE_OBJECT_SIGNING_CA) { + trust.objectSigningFlags = CERTDB_VALID_CA; + } + break; + default: + PORT_Assert(0); + break; + } + } - rv = CERT_AddTempCertToPerm(cert, nickname, &trust); + cert = CERT_NewTempCertificate(handle, derCert, NULL, + PR_FALSE, PR_FALSE); + if (cert == NULL) { + goto loser; + } - /* free the nickname */ - if ( nickname ) { - PORT_Free(nickname); - } - } else { - rv = SECSuccess; - } + /* if the cert is temp, make it perm; otherwise we're done */ + if (cert->istemp) { + /* get a default nickname for it */ + nickname = CERT_MakeCANickname(cert); - CERT_DestroyCertificate(cert); - cert = NULL; - - if ( rv != SECSuccess ) { - goto loser; - } + rv = CERT_AddTempCertToPerm(cert, nickname, &trust); -endloop: - if ( newcert ) { - CERT_DestroyCertificate(newcert); - newcert = NULL; - } - + /* free the nickname */ + if (nickname) { + PORT_Free(nickname); + } + } + else { + rv = SECSuccess; + } + + CERT_DestroyCertificate(cert); + cert = NULL; + + if (rv != SECSuccess) { + goto loser; + } + + endloop: + if (newcert) { + CERT_DestroyCertificate(newcert); + newcert = NULL; + } } rv = SECSuccess; @@ -972,18 +983,18 @@ endloop: loser: rv = SECFailure; done: - - if ( newcert ) { - CERT_DestroyCertificate(newcert); - newcert = NULL; + + if (newcert) { + CERT_DestroyCertificate(newcert); + newcert = NULL; } - - if ( cert ) { - CERT_DestroyCertificate(cert); - cert = NULL; + + if (cert) { + CERT_DestroyCertificate(cert); + cert = NULL; } - - return(rv); + + return (rv); } SECStatus @@ -993,7 +1004,8 @@ CERT_ImportCAChain(SECItem *certs, int numcerts, SECCertUsage certUsage) } SECStatus -CERT_ImportCAChainTrusted(SECItem *certs, int numcerts, SECCertUsage certUsage) { +CERT_ImportCAChainTrusted(SECItem *certs, int numcerts, SECCertUsage certUsage) +{ return cert_ImportCAChain(certs, numcerts, certUsage, PR_TRUE); } @@ -1014,7 +1026,7 @@ typedef struct certNode { CERTCertificateList * CERT_CertChainFromCert(CERTCertificate *cert, SECCertUsage usage, - PRBool includeRoot) + PRBool includeRoot) { CERTCertificateList *chain = NULL; NSSCertificate **stanChain; @@ -1022,7 +1034,7 @@ CERT_CertChainFromCert(CERTCertificate *cert, SECCertUsage usage, PLArenaPool *arena; NSSUsage nssUsage; int i, len; - NSSTrustDomain *td = STAN_GetDefaultTrustDomain(); + NSSTrustDomain *td = STAN_GetDefaultTrustDomain(); NSSCryptoContext *cc = STAN_GetDefaultCryptoContext(); stanCert = STAN_GetNSSCertificate(cert); @@ -1034,55 +1046,58 @@ CERT_CertChainFromCert(CERTCertificate *cert, SECCertUsage usage, nssUsage.nss3usage = usage; nssUsage.nss3lookingForCA = PR_FALSE; stanChain = NSSCertificate_BuildChain(stanCert, NULL, &nssUsage, NULL, NULL, - CERT_MAX_CERT_CHAIN, NULL, NULL, td, cc); + CERT_MAX_CERT_CHAIN, NULL, NULL, td, cc); if (!stanChain) { - PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER); - return NULL; + PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER); + return NULL; } len = 0; stanCert = stanChain[0]; while (stanCert) { - stanCert = stanChain[++len]; + stanCert = stanChain[++len]; } arena = PORT_NewArena(4096); if (arena == NULL) { - goto loser; + goto loser; } - chain = (CERTCertificateList *)PORT_ArenaAlloc(arena, - sizeof(CERTCertificateList)); - if (!chain) goto loser; - chain->certs = (SECItem*)PORT_ArenaAlloc(arena, len * sizeof(SECItem)); - if (!chain->certs) goto loser; + chain = (CERTCertificateList *)PORT_ArenaAlloc(arena, + sizeof(CERTCertificateList)); + if (!chain) + goto loser; + chain->certs = (SECItem *)PORT_ArenaAlloc(arena, len * sizeof(SECItem)); + if (!chain->certs) + goto loser; i = 0; stanCert = stanChain[i]; while (stanCert) { - SECItem derCert; - CERTCertificate *cCert = STAN_GetCERTCertificate(stanCert); - if (!cCert) { - goto loser; - } - derCert.len = (unsigned int)stanCert->encoding.size; - derCert.data = (unsigned char *)stanCert->encoding.data; - derCert.type = siBuffer; - SECITEM_CopyItem(arena, &chain->certs[i], &derCert); - stanCert = stanChain[++i]; - if (!stanCert && !cCert->isRoot) { - /* reached the end of the chain, but the final cert is + SECItem derCert; + CERTCertificate *cCert = STAN_GetCERTCertificate(stanCert); + if (!cCert) { + goto loser; + } + derCert.len = (unsigned int)stanCert->encoding.size; + derCert.data = (unsigned char *)stanCert->encoding.data; + derCert.type = siBuffer; + SECITEM_CopyItem(arena, &chain->certs[i], &derCert); + stanCert = stanChain[++i]; + if (!stanCert && !cCert->isRoot) { + /* reached the end of the chain, but the final cert is * not a root. Don't discard it. */ - includeRoot = PR_TRUE; - } - CERT_DestroyCertificate(cCert); + includeRoot = PR_TRUE; + } + CERT_DestroyCertificate(cCert); } - if ( !includeRoot && len > 1) { - chain->len = len - 1; - } else { - chain->len = len; + if (!includeRoot && len > 1) { + chain->len = len - 1; } - + else { + chain->len = len; + } + chain->arena = arena; nss_ZFreeIf(stanChain); return chain; @@ -1090,15 +1105,15 @@ loser: i = 0; stanCert = stanChain[i]; while (stanCert) { - CERTCertificate *cCert = STAN_GetCERTCertificate(stanCert); - if (cCert) { - CERT_DestroyCertificate(cCert); - } - stanCert = stanChain[++i]; + CERTCertificate *cCert = STAN_GetCERTCertificate(stanCert); + if (cCert) { + CERT_DestroyCertificate(cCert); + } + stanCert = stanChain[++i]; } nss_ZFreeIf(stanChain); if (arena) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return NULL; } @@ -1115,15 +1130,19 @@ CERT_CertListFromCert(CERTCertificate *cert) /* arena for SecCertificateList */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) goto no_memory; + if (arena == NULL) + goto no_memory; /* build the CERTCertificateList */ chain = (CERTCertificateList *)PORT_ArenaAlloc(arena, sizeof(CERTCertificateList)); - if (chain == NULL) goto no_memory; - chain->certs = (SECItem*)PORT_ArenaAlloc(arena, 1 * sizeof(SECItem)); - if (chain->certs == NULL) goto no_memory; + if (chain == NULL) + goto no_memory; + chain->certs = (SECItem *)PORT_ArenaAlloc(arena, 1 * sizeof(SECItem)); + if (chain->certs == NULL) + goto no_memory; rv = SECITEM_CopyItem(arena, chain->certs, &(cert->derCert)); - if (rv < 0) goto loser; + if (rv < 0) + goto loser; chain->len = 1; chain->arena = arena; @@ -1133,41 +1152,41 @@ no_memory: PORT_SetError(SEC_ERROR_NO_MEMORY); loser: if (arena != NULL) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return NULL; } CERTCertificateList * -CERT_DupCertList(const CERTCertificateList * oldList) +CERT_DupCertList(const CERTCertificateList *oldList) { CERTCertificateList *newList = NULL; - PLArenaPool *arena = NULL; - SECItem *newItem; - SECItem *oldItem; - int len = oldList->len; - int rv; + PLArenaPool *arena = NULL; + SECItem *newItem; + SECItem *oldItem; + int len = oldList->len; + int rv; /* arena for SecCertificateList */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) - goto no_memory; + if (arena == NULL) + goto no_memory; /* now build the CERTCertificateList */ newList = PORT_ArenaNew(arena, CERTCertificateList); - if (newList == NULL) - goto no_memory; + if (newList == NULL) + goto no_memory; newList->arena = arena; - newItem = (SECItem*)PORT_ArenaAlloc(arena, len * sizeof(SECItem)); - if (newItem == NULL) - goto no_memory; + newItem = (SECItem *)PORT_ArenaAlloc(arena, len * sizeof(SECItem)); + if (newItem == NULL) + goto no_memory; newList->certs = newItem; - newList->len = len; + newList->len = len; for (oldItem = oldList->certs; len > 0; --len, ++newItem, ++oldItem) { - rv = SECITEM_CopyItem(arena, newItem, oldItem); - if (rv < 0) - goto loser; + rv = SECITEM_CopyItem(arena, newItem, oldItem); + if (rv < 0) + goto loser; } return newList; @@ -1175,7 +1194,7 @@ no_memory: PORT_SetError(SEC_ERROR_NO_MEMORY); loser: if (arena != NULL) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return NULL; } @@ -1185,4 +1204,3 @@ CERT_DestroyCertificateList(CERTCertificateList *list) { PORT_FreeArena(list->arena, PR_FALSE); } - diff --git a/security/nss/lib/certhigh/certhtml.c b/security/nss/lib/certhigh/certhtml.c index aad66b0ecd3a..a522f6925501 100644 --- a/security/nss/lib/certhigh/certhtml.c +++ b/security/nss/lib/certhigh/certhtml.c @@ -22,31 +22,33 @@ static char *hex = "0123456789ABCDEF"; /* ** Convert a der-encoded integer to a hex printable string form */ -char *CERT_Hexify (SECItem *i, int do_colon) +char * +CERT_Hexify(SECItem *i, int do_colon) { unsigned char *cp, *end; char *rv, *o; if (!i->len) { - return PORT_Strdup("00"); + return PORT_Strdup("00"); } - rv = o = (char*) PORT_Alloc(i->len * 3); - if (!rv) return rv; + rv = o = (char *)PORT_Alloc(i->len * 3); + if (!rv) + return rv; cp = i->data; end = cp + i->len; while (cp < end) { - unsigned char ch = *cp++; - *o++ = hex[(ch >> 4) & 0xf]; - *o++ = hex[ch & 0xf]; - if (cp != end) { - if (do_colon) { - *o++ = ':'; - } - } + unsigned char ch = *cp++; + *o++ = hex[(ch >> 4) & 0xf]; + *o++ = hex[ch & 0xf]; + if (cp != end) { + if (do_colon) { + *o++ = ':'; + } + } } - *o = 0; /* Null terminate the string */ + *o = 0; /* Null terminate the string */ return rv; } @@ -58,132 +60,132 @@ char *CERT_Hexify (SECItem *i, int do_colon) #define MAX_OUS 20 #define MAX_DC MAX_OUS - -char *CERT_FormatName (CERTName *name) +char * +CERT_FormatName(CERTName *name) { - CERTRDN** rdns; - CERTRDN * rdn; - CERTAVA** avas; - CERTAVA* ava; - char * buf = 0; - char * tmpbuf = 0; - SECItem * cn = 0; - SECItem * email = 0; - SECItem * org = 0; - SECItem * loc = 0; - SECItem * state = 0; - SECItem * country = 0; - SECItem * dq = 0; + CERTRDN **rdns; + CERTRDN *rdn; + CERTAVA **avas; + CERTAVA *ava; + char *buf = 0; + char *tmpbuf = 0; + SECItem *cn = 0; + SECItem *email = 0; + SECItem *org = 0; + SECItem *loc = 0; + SECItem *state = 0; + SECItem *country = 0; + SECItem *dq = 0; - unsigned len = 0; - int tag; - int i; - int ou_count = 0; - int dc_count = 0; - PRBool first; - SECItem * orgunit[MAX_OUS]; - SECItem * dc[MAX_DC]; + unsigned len = 0; + int tag; + int i; + int ou_count = 0; + int dc_count = 0; + PRBool first; + SECItem *orgunit[MAX_OUS]; + SECItem *dc[MAX_DC]; /* Loop over name components and gather the interesting ones */ rdns = name->rdns; while ((rdn = *rdns++) != 0) { - avas = rdn->avas; - while ((ava = *avas++) != 0) { - tag = CERT_GetAVATag(ava); - switch(tag) { - case SEC_OID_AVA_COMMON_NAME: - if (cn) { - break; - } - cn = CERT_DecodeAVAValue(&ava->value); - if (!cn) { - goto loser; - } - len += cn->len; - break; - case SEC_OID_AVA_COUNTRY_NAME: - if (country) { - break; - } - country = CERT_DecodeAVAValue(&ava->value); - if (!country) { - goto loser; - } - len += country->len; - break; - case SEC_OID_AVA_LOCALITY: - if (loc) { - break; - } - loc = CERT_DecodeAVAValue(&ava->value); - if (!loc) { - goto loser; - } - len += loc->len; - break; - case SEC_OID_AVA_STATE_OR_PROVINCE: - if (state) { - break; - } - state = CERT_DecodeAVAValue(&ava->value); - if (!state) { - goto loser; - } - len += state->len; - break; - case SEC_OID_AVA_ORGANIZATION_NAME: - if (org) { - break; - } - org = CERT_DecodeAVAValue(&ava->value); - if (!org) { - goto loser; - } - len += org->len; - break; - case SEC_OID_AVA_DN_QUALIFIER: - if (dq) { - break; - } - dq = CERT_DecodeAVAValue(&ava->value); - if (!dq) { - goto loser; - } - len += dq->len; - break; - case SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME: - if (ou_count < MAX_OUS) { - orgunit[ou_count] = CERT_DecodeAVAValue(&ava->value); - if (!orgunit[ou_count]) { - goto loser; + avas = rdn->avas; + while ((ava = *avas++) != 0) { + tag = CERT_GetAVATag(ava); + switch (tag) { + case SEC_OID_AVA_COMMON_NAME: + if (cn) { + break; + } + cn = CERT_DecodeAVAValue(&ava->value); + if (!cn) { + goto loser; + } + len += cn->len; + break; + case SEC_OID_AVA_COUNTRY_NAME: + if (country) { + break; + } + country = CERT_DecodeAVAValue(&ava->value); + if (!country) { + goto loser; + } + len += country->len; + break; + case SEC_OID_AVA_LOCALITY: + if (loc) { + break; + } + loc = CERT_DecodeAVAValue(&ava->value); + if (!loc) { + goto loser; + } + len += loc->len; + break; + case SEC_OID_AVA_STATE_OR_PROVINCE: + if (state) { + break; + } + state = CERT_DecodeAVAValue(&ava->value); + if (!state) { + goto loser; + } + len += state->len; + break; + case SEC_OID_AVA_ORGANIZATION_NAME: + if (org) { + break; + } + org = CERT_DecodeAVAValue(&ava->value); + if (!org) { + goto loser; + } + len += org->len; + break; + case SEC_OID_AVA_DN_QUALIFIER: + if (dq) { + break; + } + dq = CERT_DecodeAVAValue(&ava->value); + if (!dq) { + goto loser; + } + len += dq->len; + break; + case SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME: + if (ou_count < MAX_OUS) { + orgunit[ou_count] = CERT_DecodeAVAValue(&ava->value); + if (!orgunit[ou_count]) { + goto loser; } - len += orgunit[ou_count++]->len; - } - break; - case SEC_OID_AVA_DC: - if (dc_count < MAX_DC) { - dc[dc_count] = CERT_DecodeAVAValue(&ava->value); - if (!dc[dc_count]) { - goto loser; - } - len += dc[dc_count++]->len; - } - break; - case SEC_OID_PKCS9_EMAIL_ADDRESS: - case SEC_OID_RFC1274_MAIL: - if (email) { - break; - } - email = CERT_DecodeAVAValue(&ava->value); - if (!email) { - goto loser; - } - len += email->len; - break; - default: - break; - } - } + len += orgunit[ou_count++]->len; + } + break; + case SEC_OID_AVA_DC: + if (dc_count < MAX_DC) { + dc[dc_count] = CERT_DecodeAVAValue(&ava->value); + if (!dc[dc_count]) { + goto loser; + } + len += dc[dc_count++]->len; + } + break; + case SEC_OID_PKCS9_EMAIL_ADDRESS: + case SEC_OID_RFC1274_MAIL: + if (email) { + break; + } + email = CERT_DecodeAVAValue(&ava->value); + if (!email) { + goto loser; + } + len += email->len; + break; + default: + break; + } + } } /* XXX - add some for formatting */ @@ -191,109 +193,108 @@ char *CERT_FormatName (CERTName *name) /* allocate buffer */ buf = (char *)PORT_Alloc(len); - if ( !buf ) { - goto loser; + if (!buf) { + goto loser; } tmpbuf = buf; - - if ( cn ) { - PORT_Memcpy(tmpbuf, cn->data, cn->len); - tmpbuf += cn->len; - PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); - tmpbuf += BREAKLEN; + + if (cn) { + PORT_Memcpy(tmpbuf, cn->data, cn->len); + tmpbuf += cn->len; + PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); + tmpbuf += BREAKLEN; } - if ( email ) { - PORT_Memcpy(tmpbuf, email->data, email->len); - tmpbuf += ( email->len ); - PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); - tmpbuf += BREAKLEN; + if (email) { + PORT_Memcpy(tmpbuf, email->data, email->len); + tmpbuf += (email->len); + PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); + tmpbuf += BREAKLEN; } - for (i=ou_count-1; i >= 0; i--) { - PORT_Memcpy(tmpbuf, orgunit[i]->data, orgunit[i]->len); - tmpbuf += ( orgunit[i]->len ); - PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); - tmpbuf += BREAKLEN; + for (i = ou_count - 1; i >= 0; i--) { + PORT_Memcpy(tmpbuf, orgunit[i]->data, orgunit[i]->len); + tmpbuf += (orgunit[i]->len); + PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); + tmpbuf += BREAKLEN; } - if ( dq ) { - PORT_Memcpy(tmpbuf, dq->data, dq->len); - tmpbuf += ( dq->len ); - PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); - tmpbuf += BREAKLEN; + if (dq) { + PORT_Memcpy(tmpbuf, dq->data, dq->len); + tmpbuf += (dq->len); + PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); + tmpbuf += BREAKLEN; } - if ( org ) { - PORT_Memcpy(tmpbuf, org->data, org->len); - tmpbuf += ( org->len ); - PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); - tmpbuf += BREAKLEN; + if (org) { + PORT_Memcpy(tmpbuf, org->data, org->len); + tmpbuf += (org->len); + PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); + tmpbuf += BREAKLEN; } - for (i=dc_count-1; i >= 0; i--) { - PORT_Memcpy(tmpbuf, dc[i]->data, dc[i]->len); - tmpbuf += ( dc[i]->len ); - PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); - tmpbuf += BREAKLEN; + for (i = dc_count - 1; i >= 0; i--) { + PORT_Memcpy(tmpbuf, dc[i]->data, dc[i]->len); + tmpbuf += (dc[i]->len); + PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); + tmpbuf += BREAKLEN; } first = PR_TRUE; - if ( loc ) { - PORT_Memcpy(tmpbuf, loc->data, loc->len); - tmpbuf += ( loc->len ); - first = PR_FALSE; + if (loc) { + PORT_Memcpy(tmpbuf, loc->data, loc->len); + tmpbuf += (loc->len); + first = PR_FALSE; } - if ( state ) { - if ( !first ) { - PORT_Memcpy(tmpbuf, COMMA, COMMALEN); - tmpbuf += COMMALEN; - } - PORT_Memcpy(tmpbuf, state->data, state->len); - tmpbuf += ( state->len ); - first = PR_FALSE; + if (state) { + if (!first) { + PORT_Memcpy(tmpbuf, COMMA, COMMALEN); + tmpbuf += COMMALEN; + } + PORT_Memcpy(tmpbuf, state->data, state->len); + tmpbuf += (state->len); + first = PR_FALSE; } - if ( country ) { - if ( !first ) { - PORT_Memcpy(tmpbuf, COMMA, COMMALEN); - tmpbuf += COMMALEN; - } - PORT_Memcpy(tmpbuf, country->data, country->len); - tmpbuf += ( country->len ); - first = PR_FALSE; + if (country) { + if (!first) { + PORT_Memcpy(tmpbuf, COMMA, COMMALEN); + tmpbuf += COMMALEN; + } + PORT_Memcpy(tmpbuf, country->data, country->len); + tmpbuf += (country->len); + first = PR_FALSE; } - if ( !first ) { - PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); - tmpbuf += BREAKLEN; + if (!first) { + PORT_Memcpy(tmpbuf, BREAK, BREAKLEN); + tmpbuf += BREAKLEN; } *tmpbuf = 0; - /* fall through and clean */ +/* fall through and clean */ loser: - if ( cn ) { - SECITEM_FreeItem(cn, PR_TRUE); + if (cn) { + SECITEM_FreeItem(cn, PR_TRUE); } - if ( email ) { - SECITEM_FreeItem(email, PR_TRUE); + if (email) { + SECITEM_FreeItem(email, PR_TRUE); } - for (i=ou_count-1; i >= 0; i--) { - SECITEM_FreeItem(orgunit[i], PR_TRUE); + for (i = ou_count - 1; i >= 0; i--) { + SECITEM_FreeItem(orgunit[i], PR_TRUE); } - if ( dq ) { - SECITEM_FreeItem(dq, PR_TRUE); + if (dq) { + SECITEM_FreeItem(dq, PR_TRUE); } - if ( org ) { - SECITEM_FreeItem(org, PR_TRUE); + if (org) { + SECITEM_FreeItem(org, PR_TRUE); } - for (i=dc_count-1; i >= 0; i--) { - SECITEM_FreeItem(dc[i], PR_TRUE); + for (i = dc_count - 1; i >= 0; i--) { + SECITEM_FreeItem(dc[i], PR_TRUE); } - if ( loc ) { - SECITEM_FreeItem(loc, PR_TRUE); + if (loc) { + SECITEM_FreeItem(loc, PR_TRUE); } - if ( state ) { - SECITEM_FreeItem(state, PR_TRUE); + if (state) { + SECITEM_FreeItem(state, PR_TRUE); } - if ( country ) { - SECITEM_FreeItem(country, PR_TRUE); + if (country) { + SECITEM_FreeItem(country, PR_TRUE); } - return(buf); + return (buf); } - diff --git a/security/nss/lib/certhigh/certreq.c b/security/nss/lib/certhigh/certreq.c index f5098a0dd9c7..4087bc978e26 100644 --- a/security/nss/lib/certhigh/certreq.c +++ b/security/nss/lib/certhigh/certreq.c @@ -14,10 +14,10 @@ SEC_ASN1_MKSUB(SEC_AnyTemplate) const SEC_ASN1Template CERT_AttributeTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTAttribute) }, + 0, NULL, sizeof(CERTAttribute) }, { SEC_ASN1_OBJECT_ID, offsetof(CERTAttribute, attrType) }, { SEC_ASN1_SET_OF | SEC_ASN1_XTRN, offsetof(CERTAttribute, attrValue), - SEC_ASN1_SUB(SEC_AnyTemplate) }, + SEC_ASN1_SUB(SEC_AnyTemplate) }, { 0 } }; @@ -27,18 +27,18 @@ const SEC_ASN1Template CERT_SetOfAttributeTemplate[] = { const SEC_ASN1Template CERT_CertificateRequestTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCertificateRequest) }, + 0, NULL, sizeof(CERTCertificateRequest) }, { SEC_ASN1_INTEGER, - offsetof(CERTCertificateRequest,version) }, + offsetof(CERTCertificateRequest, version) }, { SEC_ASN1_INLINE, - offsetof(CERTCertificateRequest,subject), - CERT_NameTemplate }, + offsetof(CERTCertificateRequest, subject), + CERT_NameTemplate }, { SEC_ASN1_INLINE, - offsetof(CERTCertificateRequest,subjectPublicKeyInfo), - CERT_SubjectPublicKeyInfoTemplate }, + offsetof(CERTCertificateRequest, subjectPublicKeyInfo), + CERT_SubjectPublicKeyInfoTemplate }, { SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(CERTCertificateRequest,attributes), - CERT_SetOfAttributeTemplate }, + offsetof(CERTCertificateRequest, attributes), + CERT_SetOfAttributeTemplate }, { 0 } }; @@ -46,25 +46,25 @@ SEC_ASN1_CHOOSER_IMPLEMENT(CERT_CertificateRequestTemplate) CERTCertificate * CERT_CreateCertificate(unsigned long serialNumber, - CERTName *issuer, - CERTValidity *validity, - CERTCertificateRequest *req) + CERTName *issuer, + CERTValidity *validity, + CERTCertificateRequest *req) { CERTCertificate *c; int rv; PLArenaPool *arena; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - - if ( !arena ) { - return(0); + + if (!arena) { + return (0); } c = (CERTCertificate *)PORT_ArenaZAlloc(arena, sizeof(CERTCertificate)); - + if (!c) { - PORT_FreeArena(arena, PR_FALSE); - return 0; + PORT_FreeArena(arena, PR_FALSE); + return 0; } c->referenceCount = 1; @@ -75,44 +75,50 @@ CERT_CreateCertificate(unsigned long serialNumber, * If extensions are added, it will get changed as appropriate. */ rv = DER_SetUInteger(arena, &c->version, SEC_CERTIFICATE_VERSION_1); - if (rv) goto loser; + if (rv) + goto loser; rv = DER_SetUInteger(arena, &c->serialNumber, serialNumber); - if (rv) goto loser; + if (rv) + goto loser; rv = CERT_CopyName(arena, &c->issuer, issuer); - if (rv) goto loser; + if (rv) + goto loser; rv = CERT_CopyValidity(arena, &c->validity, validity); - if (rv) goto loser; + if (rv) + goto loser; rv = CERT_CopyName(arena, &c->subject, &req->subject); - if (rv) goto loser; + if (rv) + goto loser; rv = SECKEY_CopySubjectPublicKeyInfo(arena, &c->subjectPublicKeyInfo, - &req->subjectPublicKeyInfo); - if (rv) goto loser; + &req->subjectPublicKeyInfo); + if (rv) + goto loser; return c; - loser: +loser: CERT_DestroyCertificate(c); return 0; } /************************************************************************/ -/* It's clear from the comments that the original author of this +/* It's clear from the comments that the original author of this * function expected the template for certificate requests to treat - * the attributes as a SET OF ANY. This function expected to be + * the attributes as a SET OF ANY. This function expected to be * passed an array of SECItems each of which contained an already encoded - * Attribute. But the cert request template does not treat the + * Attribute. But the cert request template does not treat the * Attributes as a SET OF ANY, and AFAIK never has. Instead the template * encodes attributes as a SET OF xxxxxxx. That is, it expects to encode - * each of the Attributes, not have them pre-encoded. Consequently an - * array of SECItems containing encoded Attributes is of no value to this + * each of the Attributes, not have them pre-encoded. Consequently an + * array of SECItems containing encoded Attributes is of no value to this * function. But we cannot change the signature of this public function. * It must continue to take SECItems. * - * I have recoded this function so that each SECItem contains an + * I have recoded this function so that each SECItem contains an * encoded cert extension. The encoded cert extensions form the list for the * single attribute of the cert request. In this implementation there is at most * one attribute and it is always of type SEC_OID_PKCS9_EXTENSION_REQUEST. @@ -120,95 +126,95 @@ CERT_CreateCertificate(unsigned long serialNumber, CERTCertificateRequest * CERT_CreateCertificateRequest(CERTName *subject, - CERTSubjectPublicKeyInfo *spki, - SECItem **attributes) + CERTSubjectPublicKeyInfo *spki, + SECItem **attributes) { CERTCertificateRequest *certreq; PLArenaPool *arena; - CERTAttribute * attribute; - SECOidData * oidData; + CERTAttribute *attribute; + SECOidData *oidData; SECStatus rv; int i = 0; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - return NULL; + if (arena == NULL) { + return NULL; } - + certreq = PORT_ArenaZNew(arena, CERTCertificateRequest); if (!certreq) { - PORT_FreeArena(arena, PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } /* below here it is safe to goto loser */ certreq->arena = arena; - + rv = DER_SetUInteger(arena, &certreq->version, - SEC_CERTIFICATE_REQUEST_VERSION); + SEC_CERTIFICATE_REQUEST_VERSION); if (rv != SECSuccess) - goto loser; + goto loser; rv = CERT_CopyName(arena, &certreq->subject, subject); if (rv != SECSuccess) - goto loser; + goto loser; rv = SECKEY_CopySubjectPublicKeyInfo(arena, - &certreq->subjectPublicKeyInfo, - spki); + &certreq->subjectPublicKeyInfo, + spki); if (rv != SECSuccess) - goto loser; + goto loser; - certreq->attributes = PORT_ArenaZNewArray(arena, CERTAttribute*, 2); - if(!certreq->attributes) - goto loser; + certreq->attributes = PORT_ArenaZNewArray(arena, CERTAttribute *, 2); + if (!certreq->attributes) + goto loser; /* Copy over attribute information */ if (!attributes || !attributes[0]) { - /* + /* ** Invent empty attribute information. According to the ** pkcs#10 spec, attributes has this ASN.1 type: ** ** attributes [0] IMPLICIT Attributes - ** + ** ** Which means, we should create a NULL terminated list ** with the first entry being NULL; */ - certreq->attributes[0] = NULL; - return certreq; - } + certreq->attributes[0] = NULL; + return certreq; + } /* allocate space for attributes */ attribute = PORT_ArenaZNew(arena, CERTAttribute); - if (!attribute) - goto loser; + if (!attribute) + goto loser; - oidData = SECOID_FindOIDByTag( SEC_OID_PKCS9_EXTENSION_REQUEST ); + oidData = SECOID_FindOIDByTag(SEC_OID_PKCS9_EXTENSION_REQUEST); PORT_Assert(oidData); if (!oidData) - goto loser; + goto loser; rv = SECITEM_CopyItem(arena, &attribute->attrType, &oidData->oid); if (rv != SECSuccess) - goto loser; + goto loser; - for (i = 0; attributes[i] != NULL ; i++) - ; - attribute->attrValue = PORT_ArenaZNewArray(arena, SECItem *, i+1); - if (!attribute->attrValue) - goto loser; + for (i = 0; attributes[i] != NULL; i++) + ; + attribute->attrValue = PORT_ArenaZNewArray(arena, SECItem *, i + 1); + if (!attribute->attrValue) + goto loser; /* copy attributes */ for (i = 0; attributes[i]; i++) { - /* + /* ** Attributes are a SetOf Attribute which implies ** lexigraphical ordering. It is assumes that the ** attributes are passed in sorted. If we need to ** add functionality to sort them, there is an ** example in the PKCS 7 code. */ - attribute->attrValue[i] = SECITEM_ArenaDupItem(arena, attributes[i]); - if(!attribute->attrValue[i]) - goto loser; + attribute->attrValue[i] = SECITEM_ArenaDupItem(arena, attributes[i]); + if (!attribute->attrValue[i]) + goto loser; } certreq->attributes[0] = attribute; @@ -224,7 +230,7 @@ void CERT_DestroyCertificateRequest(CERTCertificateRequest *req) { if (req && req->arena) { - PORT_FreeArena(req->arena, PR_FALSE); + PORT_FreeArena(req->arena, PR_FALSE); } return; } @@ -241,11 +247,11 @@ setCRExt(void *o, CERTCertExtension **exts) ** attribute list by CERT_FinishCRAttributes(). */ extern void *cert_StartExtensions(void *owner, PLArenaPool *ownerArena, - void (*setExts)(void *object, CERTCertExtension **exts)); + void (*setExts)(void *object, CERTCertExtension **exts)); void * CERT_StartCertificateRequestAttributes(CERTCertificateRequest *req) { - return (cert_StartExtensions ((void *)req, req->arena, setCRExt)); + return (cert_StartExtensions((void *)req, req->arena, setCRExt)); } /* @@ -257,38 +263,39 @@ CERT_StartCertificateRequestAttributes(CERTCertificateRequest *req) */ SECStatus CERT_FinishCertificateRequestAttributes(CERTCertificateRequest *req) -{ SECItem *extlist; +{ + SECItem *extlist; SECOidData *oidrec; CERTAttribute *attribute; - + if (!req || !req->arena) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } if (req->attributes == NULL || req->attributes[0] == NULL) return SECSuccess; extlist = SEC_ASN1EncodeItem(req->arena, NULL, &req->attributes, - SEC_ASN1_GET(CERT_SequenceOfCertExtensionTemplate)); + SEC_ASN1_GET(CERT_SequenceOfCertExtensionTemplate)); if (extlist == NULL) - return(SECFailure); + return (SECFailure); oidrec = SECOID_FindOIDByTag(SEC_OID_PKCS9_EXTENSION_REQUEST); if (oidrec == NULL) - return SECFailure; + return SECFailure; /* now change the list of cert extensions into a list of attributes */ - req->attributes = PORT_ArenaZNewArray(req->arena, CERTAttribute*, 2); + req->attributes = PORT_ArenaZNewArray(req->arena, CERTAttribute *, 2); attribute = PORT_ArenaZNew(req->arena, CERTAttribute); - + if (req->attributes == NULL || attribute == NULL || SECITEM_CopyItem(req->arena, &attribute->attrType, &oidrec->oid) != 0) { PORT_SetError(SEC_ERROR_NO_MEMORY); - return SECFailure; + return SECFailure; } - attribute->attrValue = PORT_ArenaZNewArray(req->arena, SECItem*, 2); + attribute->attrValue = PORT_ArenaZNewArray(req->arena, SECItem *, 2); if (attribute->attrValue == NULL) return SECFailure; @@ -303,22 +310,22 @@ CERT_FinishCertificateRequestAttributes(CERTCertificateRequest *req) SECStatus CERT_GetCertificateRequestExtensions(CERTCertificateRequest *req, - CERTCertExtension ***exts) + CERTCertExtension ***exts) { if (req == NULL || exts == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - if (req->attributes == NULL || *req->attributes == NULL) - return SECSuccess; - - if ((*req->attributes)->attrValue == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - return(SEC_ASN1DecodeItem(req->arena, exts, - SEC_ASN1_GET(CERT_SequenceOfCertExtensionTemplate), - (*req->attributes)->attrValue[0])); + if (req->attributes == NULL || *req->attributes == NULL) + return SECSuccess; + + if ((*req->attributes)->attrValue == NULL) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + + return (SEC_ASN1DecodeItem(req->arena, exts, + SEC_ASN1_GET(CERT_SequenceOfCertExtensionTemplate), + (*req->attributes)->attrValue[0])); } diff --git a/security/nss/lib/certhigh/certvfy.c b/security/nss/lib/certhigh/certvfy.c index d5dcbe8a10a8..cb23ab374b73 100644 --- a/security/nss/lib/certhigh/certvfy.c +++ b/security/nss/lib/certhigh/certvfy.c @@ -16,7 +16,6 @@ /*#include "pkix_sample_modules.h" */ #include "pkix_pl_cert.h" - #include "nsspki.h" #include "pkitm.h" #include "pkim.h" @@ -34,9 +33,10 @@ CERT_CertTimesValid(CERTCertificate *c) return (valid == secCertTimeValid) ? SECSuccess : SECFailure; } -SECStatus checkKeyParams(const SECAlgorithmID *sigAlgorithm, const SECKEYPublicKey *key) +SECStatus +checkKeyParams(const SECAlgorithmID *sigAlgorithm, const SECKEYPublicKey *key) { - SECStatus rv; + SECStatus rv; SECOidTag sigAlg; SECOidTag curve; PRUint32 policyFlags = 0; @@ -44,81 +44,83 @@ SECStatus checkKeyParams(const SECAlgorithmID *sigAlgorithm, const SECKEYPublicK sigAlg = SECOID_GetAlgorithmTag(sigAlgorithm); - switch(sigAlg) { + switch (sigAlg) { case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: - if (key->keyType != ecKey) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; - } + case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: + if (key->keyType != ecKey) { + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return SECFailure; + } curve = SECKEY_GetECCOid(&key->u.ec.DEREncodedParams); - if (curve != 0) { - if (NSS_GetAlgorithmPolicy(curve, &policyFlags) == SECFailure || - !(policyFlags & NSS_USE_ALG_IN_CERT_SIGNATURE)) { - PORT_SetError(SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED); - return SECFailure; - } else { - return SECSuccess; + if (curve != 0) { + if (NSS_GetAlgorithmPolicy(curve, &policyFlags) == SECFailure || + !(policyFlags & NSS_USE_ALG_IN_CERT_SIGNATURE)) { + PORT_SetError(SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED); + return SECFailure; } - } else { - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - return SECFailure; - } + else { + return SECSuccess; + } + } + else { + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); + return SECFailure; + } return SECSuccess; - case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: - case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE: - case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE: - if (key->keyType != rsaKey && key->keyType != rsaPssKey) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; - } + case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: + case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE: + case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE: + if (key->keyType != rsaKey && key->keyType != rsaPssKey) { + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return SECFailure; + } len = 8 * key->u.rsa.modulus.len; rv = NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minLen); if (rv != SECSuccess) { return SECFailure; - } + } if (len < minLen) { return SECFailure; - } + } return SECSuccess; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST: - case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST: - case SEC_OID_SDN702_DSA_SIGNATURE: - case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST: - case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST: - if (key->keyType != dsaKey) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; - } + case SEC_OID_ANSIX9_DSA_SIGNATURE: + case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST: + case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST: + case SEC_OID_SDN702_DSA_SIGNATURE: + case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST: + case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST: + if (key->keyType != dsaKey) { + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return SECFailure; + } len = 8 * key->u.dsa.params.prime.len; rv = NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minLen); if (rv != SECSuccess) { return SECFailure; - } + } if (len < minLen) { return SECFailure; - } + } return SECSuccess; - default: - return SECSuccess; + default: + return SECSuccess; } } @@ -128,38 +130,38 @@ SECStatus checkKeyParams(const SECAlgorithmID *sigAlgorithm, const SECKEYPublicK SECStatus CERT_VerifySignedDataWithPublicKey(const CERTSignedData *sd, SECKEYPublicKey *pubKey, - void *wincx) + void *wincx) { - SECStatus rv; - SECItem sig; - SECOidTag hashAlg = SEC_OID_UNKNOWN; + SECStatus rv; + SECItem sig; + SECOidTag hashAlg = SEC_OID_UNKNOWN; - if ( !pubKey || !sd ) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + if (!pubKey || !sd) { + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } /* check the signature */ sig = sd->signature; /* convert sig->len from bit counts to byte count. */ DER_ConvertBitString(&sig); - rv = VFY_VerifyDataWithAlgorithmID(sd->data.data, sd->data.len, pubKey, - &sig, &sd->signatureAlgorithm, &hashAlg, wincx); + rv = VFY_VerifyDataWithAlgorithmID(sd->data.data, sd->data.len, pubKey, + &sig, &sd->signatureAlgorithm, &hashAlg, wincx); if (rv == SECSuccess) { /* Are we honoring signatures for this algorithm? */ - PRUint32 policyFlags = 0; - rv = checkKeyParams(&sd->signatureAlgorithm, pubKey); - if (rv != SECSuccess) { - PORT_SetError(SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED); - return SECFailure; - } + PRUint32 policyFlags = 0; + rv = checkKeyParams(&sd->signatureAlgorithm, pubKey); + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED); + return SECFailure; + } - rv = NSS_GetAlgorithmPolicy(hashAlg, &policyFlags); - if (rv == SECSuccess && - !(policyFlags & NSS_USE_ALG_IN_CERT_SIGNATURE)) { - PORT_SetError(SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED); - return SECFailure; - } + rv = NSS_GetAlgorithmPolicy(hashAlg, &policyFlags); + if (rv == SECSuccess && + !(policyFlags & NSS_USE_ALG_IN_CERT_SIGNATURE)) { + PORT_SetError(SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED); + return SECFailure; + } } return rv; } @@ -168,18 +170,18 @@ CERT_VerifySignedDataWithPublicKey(const CERTSignedData *sd, * verify the signature of a signed data object with the given DER publickey */ SECStatus -CERT_VerifySignedDataWithPublicKeyInfo(CERTSignedData *sd, +CERT_VerifySignedDataWithPublicKeyInfo(CERTSignedData *sd, CERTSubjectPublicKeyInfo *pubKeyInfo, - void *wincx) + void *wincx) { SECKEYPublicKey *pubKey; - SECStatus rv = SECFailure; + SECStatus rv = SECFailure; /* get cert's public key */ pubKey = SECKEY_ExtractPublicKey(pubKeyInfo); if (pubKey) { - rv = CERT_VerifySignedDataWithPublicKey(sd, pubKey, wincx); - SECKEY_DestroyPublicKey(pubKey); + rv = CERT_VerifySignedDataWithPublicKey(sd, pubKey, wincx); + SECKEY_DestroyPublicKey(pubKey); } return rv; } @@ -189,31 +191,30 @@ CERT_VerifySignedDataWithPublicKeyInfo(CERTSignedData *sd, */ SECStatus CERT_VerifySignedData(CERTSignedData *sd, CERTCertificate *cert, - PRTime t, void *wincx) + PRTime t, void *wincx) { SECKEYPublicKey *pubKey = 0; - SECStatus rv = SECFailure; + SECStatus rv = SECFailure; SECCertTimeValidity validity; /* check the certificate's validity */ validity = CERT_CheckCertValidTimes(cert, t, PR_FALSE); - if ( validity != secCertTimeValid ) { - return rv; + if (validity != secCertTimeValid) { + return rv; } /* get cert's public key */ pubKey = CERT_ExtractPublicKey(cert); if (pubKey) { - rv = CERT_VerifySignedDataWithPublicKey(sd, pubKey, wincx); - SECKEY_DestroyPublicKey(pubKey); + rv = CERT_VerifySignedDataWithPublicKey(sd, pubKey, wincx); + SECKEY_DestroyPublicKey(pubKey); } return rv; } - SECStatus -SEC_CheckCRL(CERTCertDBHandle *handle,CERTCertificate *cert, - CERTCertificate *caCert, PRTime t, void * wincx) +SEC_CheckCRL(CERTCertDBHandle *handle, CERTCertificate *cert, + CERTCertificate *caCert, PRTime t, void *wincx) { return CERT_CheckCRL(cert, caCert, NULL, t, wincx); } @@ -235,33 +236,33 @@ CERT_FindCertIssuer(CERTCertificate *cert, PRTime validTime, SECCertUsage usage) me = STAN_GetNSSCertificate(cert); if (!me) { PORT_SetError(SEC_ERROR_NO_MEMORY); - return NULL; + return NULL; } nssTime = NSSTime_SetPRTime(NULL, validTime); nssUsage.anyUsage = PR_FALSE; nssUsage.nss3usage = usage; nssUsage.nss3lookingForCA = PR_TRUE; - memset(chain, 0, 3*sizeof(NSSCertificate *)); - td = STAN_GetDefaultTrustDomain(); + memset(chain, 0, 3 * sizeof(NSSCertificate *)); + td = STAN_GetDefaultTrustDomain(); cc = STAN_GetDefaultCryptoContext(); - (void)NSSCertificate_BuildChain(me, nssTime, &nssUsage, NULL, + (void)NSSCertificate_BuildChain(me, nssTime, &nssUsage, NULL, chain, 2, NULL, &status, td, cc); nss_ZFreeIf(nssTime); if (status == PR_SUCCESS) { - PORT_Assert(me == chain[0]); - /* if it's a root, the chain will only have one cert */ - if (!chain[1]) { - /* already has a reference from the call to BuildChain */ - return cert; - } - NSSCertificate_Destroy(chain[0]); /* the first cert in the chain */ - return STAN_GetCERTCertificate(chain[1]); /* return the 2nd */ - } - if (chain[0]) { - PORT_Assert(me == chain[0]); - NSSCertificate_Destroy(chain[0]); /* the first cert in the chain */ + PORT_Assert(me == chain[0]); + /* if it's a root, the chain will only have one cert */ + if (!chain[1]) { + /* already has a reference from the call to BuildChain */ + return cert; + } + NSSCertificate_Destroy(chain[0]); /* the first cert in the chain */ + return STAN_GetCERTCertificate(chain[1]); /* return the 2nd */ } - PORT_SetError (SEC_ERROR_UNKNOWN_ISSUER); + if (chain[0]) { + PORT_Assert(me == chain[0]); + NSSCertificate_Destroy(chain[0]); /* the first cert in the chain */ + } + PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER); return NULL; } @@ -270,136 +271,140 @@ CERT_FindCertIssuer(CERTCertificate *cert, PRTime validTime, SECCertUsage usage) */ SECStatus CERT_TrustFlagsForCACertUsage(SECCertUsage usage, - unsigned int *retFlags, - SECTrustType *retTrustType) + unsigned int *retFlags, + SECTrustType *retTrustType) { unsigned int requiredFlags; SECTrustType trustType; - switch ( usage ) { - case certUsageSSLClient: - requiredFlags = CERTDB_TRUSTED_CLIENT_CA; - trustType = trustSSL; - break; - case certUsageSSLServer: - case certUsageSSLCA: - requiredFlags = CERTDB_TRUSTED_CA; - trustType = trustSSL; - break; - case certUsageSSLServerWithStepUp: - requiredFlags = CERTDB_TRUSTED_CA | CERTDB_GOVT_APPROVED_CA; - trustType = trustSSL; - break; - case certUsageEmailSigner: - case certUsageEmailRecipient: - requiredFlags = CERTDB_TRUSTED_CA; - trustType = trustEmail; - break; - case certUsageObjectSigner: - requiredFlags = CERTDB_TRUSTED_CA; - trustType = trustObjectSigning; - break; - case certUsageVerifyCA: - case certUsageAnyCA: - case certUsageStatusResponder: - requiredFlags = CERTDB_TRUSTED_CA; - trustType = trustTypeNone; - break; - default: - PORT_Assert(0); - goto loser; + switch (usage) { + case certUsageSSLClient: + requiredFlags = CERTDB_TRUSTED_CLIENT_CA; + trustType = trustSSL; + break; + case certUsageSSLServer: + case certUsageSSLCA: + requiredFlags = CERTDB_TRUSTED_CA; + trustType = trustSSL; + break; + case certUsageSSLServerWithStepUp: + requiredFlags = CERTDB_TRUSTED_CA | CERTDB_GOVT_APPROVED_CA; + trustType = trustSSL; + break; + case certUsageEmailSigner: + case certUsageEmailRecipient: + requiredFlags = CERTDB_TRUSTED_CA; + trustType = trustEmail; + break; + case certUsageObjectSigner: + requiredFlags = CERTDB_TRUSTED_CA; + trustType = trustObjectSigning; + break; + case certUsageVerifyCA: + case certUsageAnyCA: + case certUsageStatusResponder: + requiredFlags = CERTDB_TRUSTED_CA; + trustType = trustTypeNone; + break; + default: + PORT_Assert(0); + goto loser; } - if ( retFlags != NULL ) { - *retFlags = requiredFlags; + if (retFlags != NULL) { + *retFlags = requiredFlags; } - if ( retTrustType != NULL ) { - *retTrustType = trustType; + if (retTrustType != NULL) { + *retTrustType = trustType; } - - return(SECSuccess); + + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } void cert_AddToVerifyLog(CERTVerifyLog *log, CERTCertificate *cert, long error, - unsigned int depth, void *arg) + unsigned int depth, void *arg) { CERTVerifyLogNode *node, *tnode; PORT_Assert(log != NULL); - + node = (CERTVerifyLogNode *)PORT_ArenaAlloc(log->arena, - sizeof(CERTVerifyLogNode)); - if ( node != NULL ) { - node->cert = CERT_DupCertificate(cert); - node->error = error; - node->depth = depth; - node->arg = arg; - - if ( log->tail == NULL ) { - /* empty list */ - log->head = log->tail = node; - node->prev = NULL; - node->next = NULL; - } else if ( depth >= log->tail->depth ) { - /* add to tail */ - node->prev = log->tail; - log->tail->next = node; - log->tail = node; - node->next = NULL; - } else if ( depth < log->head->depth ) { - /* add at head */ - node->prev = NULL; - node->next = log->head; - log->head->prev = node; - log->head = node; - } else { - /* add in middle */ - tnode = log->tail; - while ( tnode != NULL ) { - if ( depth >= tnode->depth ) { - /* insert after tnode */ - node->prev = tnode; - node->next = tnode->next; - tnode->next->prev = node; - tnode->next = node; - break; - } + sizeof(CERTVerifyLogNode)); + if (node != NULL) { + node->cert = CERT_DupCertificate(cert); + node->error = error; + node->depth = depth; + node->arg = arg; - tnode = tnode->prev; - } - } + if (log->tail == NULL) { + /* empty list */ + log->head = log->tail = node; + node->prev = NULL; + node->next = NULL; + } + else if (depth >= log->tail->depth) { + /* add to tail */ + node->prev = log->tail; + log->tail->next = node; + log->tail = node; + node->next = NULL; + } + else if (depth < log->head->depth) { + /* add at head */ + node->prev = NULL; + node->next = log->head; + log->head->prev = node; + log->head = node; + } + else { + /* add in middle */ + tnode = log->tail; + while (tnode != NULL) { + if (depth >= tnode->depth) { + /* insert after tnode */ + node->prev = tnode; + node->next = tnode->next; + tnode->next->prev = node; + tnode->next = node; + break; + } - log->count++; + tnode = tnode->prev; + } + } + + log->count++; } return; } #define EXIT_IF_NOT_LOGGING(log) \ - if ( log == NULL ) { \ - goto loser; \ + if (log == NULL) { \ + goto loser; \ } -#define LOG_ERROR_OR_EXIT(log,cert,depth,arg) \ - if ( log != NULL ) { \ - cert_AddToVerifyLog(log, cert, PORT_GetError(), depth, \ - (void *)(PRWord)arg); \ - } else { \ - goto loser; \ +#define LOG_ERROR_OR_EXIT(log, cert, depth, arg) \ + if (log != NULL) { \ + cert_AddToVerifyLog(log, cert, PORT_GetError(), depth, \ + (void *)(PRWord)arg); \ + } \ + else { \ + goto loser; \ } -#define LOG_ERROR(log,cert,depth,arg) \ - if ( log != NULL ) { \ - cert_AddToVerifyLog(log, cert, PORT_GetError(), depth, \ - (void *)(PRWord)arg); \ +#define LOG_ERROR(log, cert, depth, arg) \ + if (log != NULL) { \ + cert_AddToVerifyLog(log, cert, PORT_GetError(), depth, \ + (void *)(PRWord)arg); \ } static SECStatus cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, PRBool* sigerror, - SECCertUsage certUsage, PRTime t, void *wincx, - CERTVerifyLog *log, PRBool* revoked) + PRBool checkSig, PRBool *sigerror, + SECCertUsage certUsage, PRTime t, void *wincx, + CERTVerifyLog *log, PRBool *revoked) { SECTrustType trustType; CERTBasicConstraints basicConstraint; @@ -417,7 +422,7 @@ cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert, unsigned int requiredFlags; PLArenaPool *arena = NULL; CERTGeneralName *namesList = NULL; - CERTCertificate **certsList = NULL; + CERTCertificate **certsList = NULL; int certsListLen = 16; int namesCount = 0; PRBool subjectCertIsSelfIssued; @@ -428,177 +433,180 @@ cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert, } if (CERT_KeyUsageAndTypeForCertUsage(certUsage, PR_TRUE, - &requiredCAKeyUsage, - &caCertType) - != SECSuccess ) { - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - requiredCAKeyUsage = 0; - caCertType = 0; + &requiredCAKeyUsage, + &caCertType) != + SECSuccess) { + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + requiredCAKeyUsage = 0; + caCertType = 0; } - switch ( certUsage ) { - case certUsageSSLClient: - case certUsageSSLServer: - case certUsageSSLCA: - case certUsageSSLServerWithStepUp: - case certUsageEmailSigner: - case certUsageEmailRecipient: - case certUsageObjectSigner: - case certUsageVerifyCA: - case certUsageAnyCA: - case certUsageStatusResponder: - if ( CERT_TrustFlagsForCACertUsage(certUsage, &requiredFlags, - &trustType) != SECSuccess ) { - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - /* XXX continuing with requiredFlags = 0 seems wrong. It'll - * cause the following test to be true incorrectly: - * flags = SEC_GET_TRUST_FLAGS(issuerCert->trust, trustType); - * if (( flags & requiredFlags ) == requiredFlags) { - * rv = rvFinal; - * goto done; - * } - * There are three other instances of this problem. - */ - requiredFlags = 0; - trustType = trustSSL; - } - break; - default: - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - requiredFlags = 0; - trustType = trustSSL;/* This used to be 0, but we need something + switch (certUsage) { + case certUsageSSLClient: + case certUsageSSLServer: + case certUsageSSLCA: + case certUsageSSLServerWithStepUp: + case certUsageEmailSigner: + case certUsageEmailRecipient: + case certUsageObjectSigner: + case certUsageVerifyCA: + case certUsageAnyCA: + case certUsageStatusResponder: + if (CERT_TrustFlagsForCACertUsage(certUsage, &requiredFlags, + &trustType) != SECSuccess) { + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + /* XXX continuing with requiredFlags = 0 seems wrong. It'll + * cause the following test to be true incorrectly: + * flags = SEC_GET_TRUST_FLAGS(issuerCert->trust, trustType); + * if (( flags & requiredFlags ) == requiredFlags) { + * rv = rvFinal; + * goto done; + * } + * There are three other instances of this problem. + */ + requiredFlags = 0; + trustType = trustSSL; + } + break; + default: + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + requiredFlags = 0; + trustType = trustSSL; /* This used to be 0, but we need something * that matches the enumeration type. */ - caCertType = 0; + caCertType = 0; } - + subjectCert = CERT_DupCertificate(cert); - if ( subjectCert == NULL ) { - goto loser; + if (subjectCert == NULL) { + goto loser; } arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - goto loser; + goto loser; } certsList = PORT_ZNewArray(CERTCertificate *, certsListLen); if (certsList == NULL) - goto loser; + goto loser; /* RFC 3280 says that the name constraints will apply to the names ** in the leaf (EE) cert, whether it is self issued or not, so ** we pretend that it is not. */ subjectCertIsSelfIssued = PR_FALSE; - for ( count = 0; count < CERT_MAX_CERT_CHAIN; count++ ) { - PRBool validCAOverride = PR_FALSE; + for (count = 0; count < CERT_MAX_CERT_CHAIN; count++) { + PRBool validCAOverride = PR_FALSE; - /* Construct a list of names for the current and all previous - * certifcates (except leaf (EE) certs, root CAs, and self-issued - * intermediate CAs) to be verified against the name constraints - * extension of the issuer certificate. - */ - if (subjectCertIsSelfIssued == PR_FALSE) { - CERTGeneralName *subjectNameList; - int subjectNameListLen; - int i; - PRBool getSubjectCN = (!count && certUsage == certUsageSSLServer); - subjectNameList = - CERT_GetConstrainedCertificateNames(subjectCert, arena, - getSubjectCN); - if (!subjectNameList) - goto loser; - subjectNameListLen = CERT_GetNamesLength(subjectNameList); - if (!subjectNameListLen) - goto loser; - if (certsListLen <= namesCount + subjectNameListLen) { - CERTCertificate **tmpCertsList; - certsListLen = (namesCount + subjectNameListLen) * 2; - tmpCertsList = - (CERTCertificate **)PORT_Realloc(certsList, - certsListLen * sizeof(CERTCertificate *)); - if (tmpCertsList == NULL) { - goto loser; - } - certsList = tmpCertsList; - } - for (i = 0; i < subjectNameListLen; i++) { - certsList[namesCount + i] = subjectCert; - } - namesCount += subjectNameListLen; - namesList = cert_CombineNamesLists(namesList, subjectNameList); - } + /* Construct a list of names for the current and all previous + * certifcates (except leaf (EE) certs, root CAs, and self-issued + * intermediate CAs) to be verified against the name constraints + * extension of the issuer certificate. + */ + if (subjectCertIsSelfIssued == PR_FALSE) { + CERTGeneralName *subjectNameList; + int subjectNameListLen; + int i; + PRBool getSubjectCN = (!count && certUsage == certUsageSSLServer); + subjectNameList = + CERT_GetConstrainedCertificateNames(subjectCert, arena, + getSubjectCN); + if (!subjectNameList) + goto loser; + subjectNameListLen = CERT_GetNamesLength(subjectNameList); + if (!subjectNameListLen) + goto loser; + if (certsListLen <= namesCount + subjectNameListLen) { + CERTCertificate **tmpCertsList; + certsListLen = (namesCount + subjectNameListLen) * 2; + tmpCertsList = + (CERTCertificate **)PORT_Realloc(certsList, + certsListLen * + sizeof(CERTCertificate *)); + if (tmpCertsList == NULL) { + goto loser; + } + certsList = tmpCertsList; + } + for (i = 0; i < subjectNameListLen; i++) { + certsList[namesCount + i] = subjectCert; + } + namesCount += subjectNameListLen; + namesList = cert_CombineNamesLists(namesList, subjectNameList); + } /* check if the cert has an unsupported critical extension */ - if ( subjectCert->options.bits.hasUnsupportedCriticalExt ) { - PORT_SetError(SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION); - LOG_ERROR_OR_EXIT(log,subjectCert,count,0); - } + if (subjectCert->options.bits.hasUnsupportedCriticalExt) { + PORT_SetError(SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION); + LOG_ERROR_OR_EXIT(log, subjectCert, count, 0); + } - /* find the certificate of the issuer */ - issuerCert = CERT_FindCertIssuer(subjectCert, t, certUsage); - if ( ! issuerCert ) { - PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER); - LOG_ERROR(log,subjectCert,count,0); - goto loser; - } + /* find the certificate of the issuer */ + issuerCert = CERT_FindCertIssuer(subjectCert, t, certUsage); + if (!issuerCert) { + PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER); + LOG_ERROR(log, subjectCert, count, 0); + goto loser; + } - /* verify the signature on the cert */ - if ( checkSig ) { - rv = CERT_VerifySignedData(&subjectCert->signatureWrap, - issuerCert, t, wincx); - - if ( rv != SECSuccess ) { + /* verify the signature on the cert */ + if (checkSig) { + rv = CERT_VerifySignedData(&subjectCert->signatureWrap, + issuerCert, t, wincx); + + if (rv != SECSuccess) { if (sigerror) { *sigerror = PR_TRUE; } - if ( PORT_GetError() == SEC_ERROR_EXPIRED_CERTIFICATE ) { - PORT_SetError(SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE); - LOG_ERROR_OR_EXIT(log,issuerCert,count+1,0); - } else { - if (PORT_GetError() != - SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED) { - PORT_SetError(SEC_ERROR_BAD_SIGNATURE); - } - LOG_ERROR_OR_EXIT(log,subjectCert,count,0); - } - } - } + if (PORT_GetError() == SEC_ERROR_EXPIRED_CERTIFICATE) { + PORT_SetError(SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE); + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, 0); + } + else { + if (PORT_GetError() != + SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED) { + PORT_SetError(SEC_ERROR_BAD_SIGNATURE); + } + LOG_ERROR_OR_EXIT(log, subjectCert, count, 0); + } + } + } - /* If the basicConstraint extension is included in an immediate CA - * certificate, make sure that the isCA flag is on. If the - * pathLenConstraint component exists, it must be greater than the - * number of CA certificates we have seen so far. If the extension - * is omitted, we will assume that this is a CA certificate with - * an unlimited pathLenConstraint (since it already passes the - * netscape-cert-type extension checking). - */ + /* If the basicConstraint extension is included in an immediate CA + * certificate, make sure that the isCA flag is on. If the + * pathLenConstraint component exists, it must be greater than the + * number of CA certificates we have seen so far. If the extension + * is omitted, we will assume that this is a CA certificate with + * an unlimited pathLenConstraint (since it already passes the + * netscape-cert-type extension checking). + */ - rv = CERT_FindBasicConstraintExten(issuerCert, &basicConstraint); - if ( rv != SECSuccess ) { - if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) { - LOG_ERROR_OR_EXIT(log,issuerCert,count+1,0); - } - pathLengthLimit = CERT_UNLIMITED_PATH_CONSTRAINT; - /* no basic constraints found, we aren't (yet) a CA. */ - isca = PR_FALSE; - } else { - if ( basicConstraint.isCA == PR_FALSE ) { - PORT_SetError (SEC_ERROR_CA_CERT_INVALID); - LOG_ERROR_OR_EXIT(log,issuerCert,count+1,0); - } - pathLengthLimit = basicConstraint.pathLenConstraint; - isca = PR_TRUE; - } - /* make sure that the path len constraint is properly set.*/ - if (pathLengthLimit >= 0 && currentPathLen > pathLengthLimit) { - PORT_SetError (SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID); - LOG_ERROR_OR_EXIT(log, issuerCert, count+1, pathLengthLimit); - } + rv = CERT_FindBasicConstraintExten(issuerCert, &basicConstraint); + if (rv != SECSuccess) { + if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) { + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, 0); + } + pathLengthLimit = CERT_UNLIMITED_PATH_CONSTRAINT; + /* no basic constraints found, we aren't (yet) a CA. */ + isca = PR_FALSE; + } + else { + if (basicConstraint.isCA == PR_FALSE) { + PORT_SetError(SEC_ERROR_CA_CERT_INVALID); + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, 0); + } + pathLengthLimit = basicConstraint.pathLenConstraint; + isca = PR_TRUE; + } + /* make sure that the path len constraint is properly set.*/ + if (pathLengthLimit >= 0 && currentPathLen > pathLengthLimit) { + PORT_SetError(SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID); + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, pathLengthLimit); + } /* make sure that the entire chain is within the name space of the * current issuer certificate. @@ -611,17 +619,18 @@ cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert, goto loser; } - /* XXX - the error logging may need to go down into CRL stuff at some - * point - */ - /* check revoked list (issuer) */ + /* XXX - the error logging may need to go down into CRL stuff at some + * point + */ + /* check revoked list (issuer) */ rv = SEC_CheckCRL(handle, subjectCert, issuerCert, t, wincx); if (rv == SECFailure) { if (revoked) { *revoked = PR_TRUE; } - LOG_ERROR_OR_EXIT(log,subjectCert,count,0); - } else if (rv == SECWouldBlock) { + LOG_ERROR_OR_EXIT(log, subjectCert, count, 0); + } + else if (rv == SECWouldBlock) { /* We found something fishy, so we intend to issue an * error to the user, but the user may wish to continue * processing, in which case we better make sure nothing @@ -630,163 +639,167 @@ cert_VerifyCertChainOld(CERTCertDBHandle *handle, CERTCertificate *cert, if (revoked) { *revoked = PR_TRUE; } - LOG_ERROR(log,subjectCert,count,0); + LOG_ERROR(log, subjectCert, count, 0); } - if ( CERT_GetCertTrust(issuerCert, &issuerTrust) == SECSuccess) { - /* we have some trust info, but this does NOT imply that this - * cert is actually trusted for any purpose. The cert may be - * explicitly UNtrusted. We won't know until we examine the - * trust bits. - */ - unsigned int flags; + if (CERT_GetCertTrust(issuerCert, &issuerTrust) == SECSuccess) { + /* we have some trust info, but this does NOT imply that this + * cert is actually trusted for any purpose. The cert may be + * explicitly UNtrusted. We won't know until we examine the + * trust bits. + */ + unsigned int flags; - if (certUsage != certUsageAnyCA && - certUsage != certUsageStatusResponder) { + if (certUsage != certUsageAnyCA && + certUsage != certUsageStatusResponder) { - /* - * XXX This choice of trustType seems arbitrary. - */ - if ( certUsage == certUsageVerifyCA ) { - if ( subjectCert->nsCertType & NS_CERT_TYPE_EMAIL_CA ) { - trustType = trustEmail; - } else if ( subjectCert->nsCertType & NS_CERT_TYPE_SSL_CA ) { - trustType = trustSSL; - } else { - trustType = trustObjectSigning; - } - } + /* + * XXX This choice of trustType seems arbitrary. + */ + if (certUsage == certUsageVerifyCA) { + if (subjectCert->nsCertType & NS_CERT_TYPE_EMAIL_CA) { + trustType = trustEmail; + } + else if (subjectCert->nsCertType & NS_CERT_TYPE_SSL_CA) { + trustType = trustSSL; + } + else { + trustType = trustObjectSigning; + } + } - flags = SEC_GET_TRUST_FLAGS(&issuerTrust, trustType); - if (( flags & requiredFlags ) == requiredFlags) { - /* we found a trusted one, so return */ - rv = rvFinal; - goto done; - } - if (flags & CERTDB_VALID_CA) { - validCAOverride = PR_TRUE; - } - /* is it explicitly distrusted? */ - if ((flags & CERTDB_TERMINAL_RECORD) && - ((flags & (CERTDB_TRUSTED|CERTDB_TRUSTED_CA)) == 0)) { - /* untrusted -- the cert is explicitly untrusted, not - * just that it doesn't chain to a trusted cert */ - PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); - LOG_ERROR_OR_EXIT(log,issuerCert,count+1,flags); - } - } else { + flags = SEC_GET_TRUST_FLAGS(&issuerTrust, trustType); + if ((flags & requiredFlags) == requiredFlags) { + /* we found a trusted one, so return */ + rv = rvFinal; + goto done; + } + if (flags & CERTDB_VALID_CA) { + validCAOverride = PR_TRUE; + } + /* is it explicitly distrusted? */ + if ((flags & CERTDB_TERMINAL_RECORD) && + ((flags & (CERTDB_TRUSTED | CERTDB_TRUSTED_CA)) == 0)) { + /* untrusted -- the cert is explicitly untrusted, not + * just that it doesn't chain to a trusted cert */ + PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, flags); + } + } + else { /* Check if we have any valid trust when cheching for * certUsageAnyCA or certUsageStatusResponder. */ for (trustType = trustSSL; trustType < trustTypeNone; trustType++) { flags = SEC_GET_TRUST_FLAGS(&issuerTrust, trustType); if ((flags & requiredFlags) == requiredFlags) { - rv = rvFinal; - goto done; + rv = rvFinal; + goto done; } if (flags & CERTDB_VALID_CA) validCAOverride = PR_TRUE; } - /* We have 2 separate loops because we want any single trust - * bit to allow this usage to return trusted. Only if none of - * the trust bits are on do we check to see if the cert is - * untrusted */ + /* We have 2 separate loops because we want any single trust + * bit to allow this usage to return trusted. Only if none of + * the trust bits are on do we check to see if the cert is + * untrusted */ for (trustType = trustSSL; trustType < trustTypeNone; trustType++) { flags = SEC_GET_TRUST_FLAGS(&issuerTrust, trustType); - /* is it explicitly distrusted? */ - if ((flags & CERTDB_TERMINAL_RECORD) && - ((flags & (CERTDB_TRUSTED|CERTDB_TRUSTED_CA)) == 0)) { - /* untrusted -- the cert is explicitly untrusted, not - * just that it doesn't chain to a trusted cert */ - PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); - LOG_ERROR_OR_EXIT(log,issuerCert,count+1,flags); - } + /* is it explicitly distrusted? */ + if ((flags & CERTDB_TERMINAL_RECORD) && + ((flags & (CERTDB_TRUSTED | CERTDB_TRUSTED_CA)) == 0)) { + /* untrusted -- the cert is explicitly untrusted, not + * just that it doesn't chain to a trusted cert */ + PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, flags); + } } } } - if (!validCAOverride) { - /* - * Make sure that if this is an intermediate CA in the chain that - * it was given permission by its signer to be a CA. - */ - /* - * if basicConstraints says it is a ca, then we check the - * nsCertType. If the nsCertType has any CA bits set, then - * it must have the right one. - */ - if (!isca || (issuerCert->nsCertType & NS_CERT_TYPE_CA)) { - isca = (issuerCert->nsCertType & caCertType) ? PR_TRUE : PR_FALSE; - } - - if ( !isca ) { - PORT_SetError(SEC_ERROR_CA_CERT_INVALID); - LOG_ERROR_OR_EXIT(log,issuerCert,count+1,0); - } + if (!validCAOverride) { + /* + * Make sure that if this is an intermediate CA in the chain that + * it was given permission by its signer to be a CA. + */ + /* + * if basicConstraints says it is a ca, then we check the + * nsCertType. If the nsCertType has any CA bits set, then + * it must have the right one. + */ + if (!isca || (issuerCert->nsCertType & NS_CERT_TYPE_CA)) { + isca = (issuerCert->nsCertType & caCertType) ? PR_TRUE : PR_FALSE; + } - /* make sure key usage allows cert signing */ - if (CERT_CheckKeyUsage(issuerCert, requiredCAKeyUsage) != SECSuccess) { - PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); - LOG_ERROR_OR_EXIT(log,issuerCert,count+1,requiredCAKeyUsage); - } - } + if (!isca) { + PORT_SetError(SEC_ERROR_CA_CERT_INVALID); + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, 0); + } - /* make sure that the issuer is not self signed. If it is, then - * stop here to prevent looping. - */ - if (issuerCert->isRoot) { - PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); - LOG_ERROR(log, issuerCert, count+1, 0); - goto loser; - } - /* The issuer cert will be the subject cert in the next loop. - * A cert is self-issued if its subject and issuer are equal and - * both are of non-zero length. - */ - subjectCertIsSelfIssued = (PRBool) - SECITEM_ItemsAreEqual(&issuerCert->derIssuer, - &issuerCert->derSubject) && - issuerCert->derSubject.len > 0; - if (subjectCertIsSelfIssued == PR_FALSE) { - /* RFC 3280 says only non-self-issued intermediate CA certs - * count in path length. - */ - ++currentPathLen; - } + /* make sure key usage allows cert signing */ + if (CERT_CheckKeyUsage(issuerCert, requiredCAKeyUsage) != SECSuccess) { + PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); + LOG_ERROR_OR_EXIT(log, issuerCert, count + 1, requiredCAKeyUsage); + } + } - CERT_DestroyCertificate(subjectCert); - subjectCert = issuerCert; - issuerCert = NULL; + /* make sure that the issuer is not self signed. If it is, then + * stop here to prevent looping. + */ + if (issuerCert->isRoot) { + PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); + LOG_ERROR(log, issuerCert, count + 1, 0); + goto loser; + } + /* The issuer cert will be the subject cert in the next loop. + * A cert is self-issued if its subject and issuer are equal and + * both are of non-zero length. + */ + subjectCertIsSelfIssued = (PRBool) + SECITEM_ItemsAreEqual(&issuerCert->derIssuer, + &issuerCert->derSubject) && + issuerCert->derSubject.len > + 0; + if (subjectCertIsSelfIssued == PR_FALSE) { + /* RFC 3280 says only non-self-issued intermediate CA certs + * count in path length. + */ + ++currentPathLen; + } + + CERT_DestroyCertificate(subjectCert); + subjectCert = issuerCert; + issuerCert = NULL; } PORT_SetError(SEC_ERROR_UNKNOWN_ISSUER); - LOG_ERROR(log,subjectCert,count,0); + LOG_ERROR(log, subjectCert, count, 0); loser: rv = SECFailure; done: if (certsList != NULL) { - PORT_Free(certsList); + PORT_Free(certsList); } - if ( issuerCert ) { - CERT_DestroyCertificate(issuerCert); - } - - if ( subjectCert ) { - CERT_DestroyCertificate(subjectCert); + if (issuerCert) { + CERT_DestroyCertificate(issuerCert); } - if ( arena != NULL ) { - PORT_FreeArena(arena, PR_FALSE); + if (subjectCert) { + CERT_DestroyCertificate(subjectCert); + } + + if (arena != NULL) { + PORT_FreeArena(arena, PR_FALSE); } return rv; } SECStatus cert_VerifyCertChain(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, PRBool* sigerror, + PRBool checkSig, PRBool *sigerror, SECCertUsage certUsage, PRTime t, void *wincx, - CERTVerifyLog *log, PRBool* revoked) + CERTVerifyLog *log, PRBool *revoked) { if (CERT_GetUsePKIXForValidation()) { return cert_VerifyCertChainPkix(cert, checkSig, certUsage, t, @@ -798,11 +811,11 @@ cert_VerifyCertChain(CERTCertDBHandle *handle, CERTCertificate *cert, SECStatus CERT_VerifyCertChain(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, PRTime t, - void *wincx, CERTVerifyLog *log) + PRBool checkSig, SECCertUsage certUsage, PRTime t, + void *wincx, CERTVerifyLog *log) { return cert_VerifyCertChain(handle, cert, checkSig, NULL, certUsage, t, - wincx, log, NULL); + wincx, log, NULL); } /* @@ -810,8 +823,8 @@ CERT_VerifyCertChain(CERTCertDBHandle *handle, CERTCertificate *cert, */ SECStatus CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, PRTime t, - void *wincx, CERTVerifyLog *log) + PRBool checkSig, SECCertUsage certUsage, PRTime t, + void *wincx, CERTVerifyLog *log) { SECTrustType trustType; CERTBasicConstraints basicConstraint; @@ -826,44 +839,43 @@ CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, CERTCertificate *cert, CERTCertificate *issuerCert; CERTCertTrust certTrust; - if (CERT_KeyUsageAndTypeForCertUsage(certUsage, PR_TRUE, - &requiredCAKeyUsage, - &caCertType) != SECSuccess ) { - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - requiredCAKeyUsage = 0; - caCertType = 0; + &requiredCAKeyUsage, + &caCertType) != SECSuccess) { + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + requiredCAKeyUsage = 0; + caCertType = 0; } - switch ( certUsage ) { - case certUsageSSLClient: - case certUsageSSLServer: - case certUsageSSLCA: - case certUsageSSLServerWithStepUp: - case certUsageEmailSigner: - case certUsageEmailRecipient: - case certUsageObjectSigner: - case certUsageVerifyCA: - case certUsageStatusResponder: - if ( CERT_TrustFlagsForCACertUsage(certUsage, &requiredFlags, - &trustType) != SECSuccess ) { - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - requiredFlags = 0; - trustType = trustSSL; - } - break; - default: - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - requiredFlags = 0; - trustType = trustSSL;/* This used to be 0, but we need something - * that matches the enumeration type. - */ - caCertType = 0; + switch (certUsage) { + case certUsageSSLClient: + case certUsageSSLServer: + case certUsageSSLCA: + case certUsageSSLServerWithStepUp: + case certUsageEmailSigner: + case certUsageEmailRecipient: + case certUsageObjectSigner: + case certUsageVerifyCA: + case certUsageStatusResponder: + if (CERT_TrustFlagsForCACertUsage(certUsage, &requiredFlags, + &trustType) != SECSuccess) { + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + requiredFlags = 0; + trustType = trustSSL; + } + break; + default: + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + requiredFlags = 0; + trustType = trustSSL; /* This used to be 0, but we need something + * that matches the enumeration type. + */ + caCertType = 0; } - + /* If the basicConstraint extension is included in an intermmediate CA * certificate, make sure that the isCA flag is on. If the * pathLenConstraint component exists, it must be greater than the @@ -874,133 +886,137 @@ CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, CERTCertificate *cert, */ rv = CERT_FindBasicConstraintExten(cert, &basicConstraint); - if ( rv != SECSuccess ) { - if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) { - LOG_ERROR_OR_EXIT(log,cert,0,0); - } - /* no basic constraints found, we aren't (yet) a CA. */ - isca = PR_FALSE; - } else { - if ( basicConstraint.isCA == PR_FALSE ) { - PORT_SetError (SEC_ERROR_CA_CERT_INVALID); - LOG_ERROR_OR_EXIT(log,cert,0,0); - } - - /* can't check path length if we don't know the previous path */ - isca = PR_TRUE; + if (rv != SECSuccess) { + if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) { + LOG_ERROR_OR_EXIT(log, cert, 0, 0); + } + /* no basic constraints found, we aren't (yet) a CA. */ + isca = PR_FALSE; } - - if ( CERT_GetCertTrust(cert, &certTrust) == SECSuccess ) { - /* we have some trust info, but this does NOT imply that this - * cert is actually trusted for any purpose. The cert may be - * explicitly UNtrusted. We won't know until we examine the - * trust bits. - */ + else { + if (basicConstraint.isCA == PR_FALSE) { + PORT_SetError(SEC_ERROR_CA_CERT_INVALID); + LOG_ERROR_OR_EXIT(log, cert, 0, 0); + } + + /* can't check path length if we don't know the previous path */ + isca = PR_TRUE; + } + + if (CERT_GetCertTrust(cert, &certTrust) == SECSuccess) { + /* we have some trust info, but this does NOT imply that this + * cert is actually trusted for any purpose. The cert may be + * explicitly UNtrusted. We won't know until we examine the + * trust bits. + */ if (certUsage == certUsageStatusResponder) { - /* Check the special case of certUsageStatusResponder */ + /* Check the special case of certUsageStatusResponder */ issuerCert = CERT_FindCertIssuer(cert, t, certUsage); if (issuerCert) { - if (SEC_CheckCRL(handle, cert, issuerCert, t, wincx) - != SECSuccess) { + if (SEC_CheckCRL(handle, cert, issuerCert, t, wincx) != + SECSuccess) { PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE); CERT_DestroyCertificate(issuerCert); goto loser; } CERT_DestroyCertificate(issuerCert); } - /* XXX We have NOT determined that this cert is trusted. - * For years, NSS has treated this as trusted, - * but it seems incorrect. - */ - rv = rvFinal; - goto done; + /* XXX We have NOT determined that this cert is trusted. + * For years, NSS has treated this as trusted, + * but it seems incorrect. + */ + rv = rvFinal; + goto done; } - /* - * check the trust params of the issuer - */ - flags = SEC_GET_TRUST_FLAGS(&certTrust, trustType); - if ( ( flags & requiredFlags ) == requiredFlags) { - /* we found a trusted one, so return */ - rv = rvFinal; - goto done; - } - if (flags & CERTDB_VALID_CA) { - validCAOverride = PR_TRUE; - } - /* is it explicitly distrusted? */ - if ((flags & CERTDB_TERMINAL_RECORD) && - ((flags & (CERTDB_TRUSTED|CERTDB_TRUSTED_CA)) == 0)) { - /* untrusted -- the cert is explicitly untrusted, not - * just that it doesn't chain to a trusted cert */ - PORT_SetError(SEC_ERROR_UNTRUSTED_CERT); - LOG_ERROR_OR_EXIT(log,cert,0,flags); - } + /* + * check the trust params of the issuer + */ + flags = SEC_GET_TRUST_FLAGS(&certTrust, trustType); + if ((flags & requiredFlags) == requiredFlags) { + /* we found a trusted one, so return */ + rv = rvFinal; + goto done; + } + if (flags & CERTDB_VALID_CA) { + validCAOverride = PR_TRUE; + } + /* is it explicitly distrusted? */ + if ((flags & CERTDB_TERMINAL_RECORD) && + ((flags & (CERTDB_TRUSTED | CERTDB_TRUSTED_CA)) == 0)) { + /* untrusted -- the cert is explicitly untrusted, not + * just that it doesn't chain to a trusted cert */ + PORT_SetError(SEC_ERROR_UNTRUSTED_CERT); + LOG_ERROR_OR_EXIT(log, cert, 0, flags); + } } if (!validCAOverride) { - /* - * Make sure that if this is an intermediate CA in the chain that - * it was given permission by its signer to be a CA. - */ - /* - * if basicConstraints says it is a ca, then we check the - * nsCertType. If the nsCertType has any CA bits set, then - * it must have the right one. - */ - if (!isca || (cert->nsCertType & NS_CERT_TYPE_CA)) { - isca = (cert->nsCertType & caCertType) ? PR_TRUE : PR_FALSE; - } - - if (!isca) { - PORT_SetError(SEC_ERROR_CA_CERT_INVALID); - LOG_ERROR_OR_EXIT(log,cert,0,0); - } - - /* make sure key usage allows cert signing */ - if (CERT_CheckKeyUsage(cert, requiredCAKeyUsage) != SECSuccess) { - PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); - LOG_ERROR_OR_EXIT(log,cert,0,requiredCAKeyUsage); - } + /* + * Make sure that if this is an intermediate CA in the chain that + * it was given permission by its signer to be a CA. + */ + /* + * if basicConstraints says it is a ca, then we check the + * nsCertType. If the nsCertType has any CA bits set, then + * it must have the right one. + */ + if (!isca || (cert->nsCertType & NS_CERT_TYPE_CA)) { + isca = (cert->nsCertType & caCertType) ? PR_TRUE : PR_FALSE; + } + + if (!isca) { + PORT_SetError(SEC_ERROR_CA_CERT_INVALID); + LOG_ERROR_OR_EXIT(log, cert, 0, 0); + } + + /* make sure key usage allows cert signing */ + if (CERT_CheckKeyUsage(cert, requiredCAKeyUsage) != SECSuccess) { + PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); + LOG_ERROR_OR_EXIT(log, cert, 0, requiredCAKeyUsage); + } } /* make sure that the issuer is not self signed. If it is, then * stop here to prevent looping. */ if (cert->isRoot) { - PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); - LOG_ERROR(log, cert, 0, 0); - goto loser; + PORT_SetError(SEC_ERROR_UNTRUSTED_ISSUER); + LOG_ERROR(log, cert, 0, 0); + goto loser; } - return CERT_VerifyCertChain(handle, cert, checkSig, certUsage, t, - wincx, log); + return CERT_VerifyCertChain(handle, cert, checkSig, certUsage, t, + wincx, log); loser: rv = SECFailure; done: return rv; } -#define NEXT_USAGE() { \ - i*=2; \ - certUsage++; \ - continue; \ -} +#define NEXT_USAGE() \ + { \ + i *= 2; \ + certUsage++; \ + continue; \ + } -#define VALID_USAGE() { \ - NEXT_USAGE(); \ -} +#define VALID_USAGE() \ + { \ + NEXT_USAGE(); \ + } -#define INVALID_USAGE() { \ - if (returnedUsages) { \ - *returnedUsages &= (~i); \ - } \ - if (PR_TRUE == requiredUsage) { \ - valid = SECFailure; \ - } \ - NEXT_USAGE(); \ -} +#define INVALID_USAGE() \ + { \ + if (returnedUsages) { \ + *returnedUsages &= (~i); \ + } \ + if (PR_TRUE == requiredUsage) { \ + valid = SECFailure; \ + } \ + NEXT_USAGE(); \ + } /* - * check the leaf cert against trust and usage. + * check the leaf cert against trust and usage. * returns success if the cert is not distrusted. If the cert is * trusted, then the trusted bool will be true. * returns failure if the cert is distrusted. If failure, flags @@ -1008,141 +1024,143 @@ done: */ SECStatus cert_CheckLeafTrust(CERTCertificate *cert, SECCertUsage certUsage, - unsigned int *failedFlags, PRBool *trusted) + unsigned int *failedFlags, PRBool *trusted) { unsigned int flags; CERTCertTrust trust; *failedFlags = 0; *trusted = PR_FALSE; - - /* check trust flags to see if this cert is directly trusted */ - if ( CERT_GetCertTrust(cert, &trust) == SECSuccess ) { - switch ( certUsage ) { - case certUsageSSLClient: - case certUsageSSLServer: - flags = trust.sslFlags; - - /* is the cert directly trusted or not trusted ? */ - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is - * authoritative */ - if ( flags & CERTDB_TRUSTED ) { /* trust this cert */ - *trusted = PR_TRUE; - return SECSuccess; - } else { /* don't trust this cert */ - *failedFlags = flags; - return SECFailure; - } - } - break; - case certUsageSSLServerWithStepUp: - /* XXX - step up certs can't be directly trusted, only distrust */ - flags = trust.sslFlags; - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is - * authoritative */ - if (( flags & CERTDB_TRUSTED ) == 0) { - /* don't trust this cert */ - *failedFlags = flags; - return SECFailure; - } - } - break; - case certUsageSSLCA: - flags = trust.sslFlags; - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is - * authoritative */ - if (( flags & (CERTDB_TRUSTED|CERTDB_TRUSTED_CA) ) == 0) { - /* don't trust this cert */ - *failedFlags = flags; - return SECFailure; - } - } - break; - case certUsageEmailSigner: - case certUsageEmailRecipient: - flags = trust.emailFlags; - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is - * authoritative */ - if ( flags & CERTDB_TRUSTED ) { /* trust this cert */ - *trusted = PR_TRUE; - return SECSuccess; - } - else { /* don't trust this cert */ - *failedFlags = flags; - return SECFailure; - } - } - - break; - case certUsageObjectSigner: - flags = trust.objectSigningFlags; - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + /* check trust flags to see if this cert is directly trusted */ + if (CERT_GetCertTrust(cert, &trust) == SECSuccess) { + switch (certUsage) { + case certUsageSSLClient: + case certUsageSSLServer: + flags = trust.sslFlags; + + /* is the cert directly trusted or not trusted ? */ + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is * authoritative */ - if ( flags & CERTDB_TRUSTED ) { /* trust this cert */ - *trusted = PR_TRUE; - return SECSuccess; - } else { /* don't trust this cert */ - *failedFlags = flags; - return SECFailure; - } - } - break; - case certUsageVerifyCA: - case certUsageStatusResponder: - flags = trust.sslFlags; - /* is the cert directly trusted or not trusted ? */ - if ( ( flags & ( CERTDB_VALID_CA | CERTDB_TRUSTED_CA ) ) == - ( CERTDB_VALID_CA | CERTDB_TRUSTED_CA ) ) { - *trusted = PR_TRUE; - return SECSuccess; - } - flags = trust.emailFlags; - /* is the cert directly trusted or not trusted ? */ - if ( ( flags & ( CERTDB_VALID_CA | CERTDB_TRUSTED_CA ) ) == - ( CERTDB_VALID_CA | CERTDB_TRUSTED_CA ) ) { - *trusted = PR_TRUE; - return SECSuccess; - } - flags = trust.objectSigningFlags; - /* is the cert directly trusted or not trusted ? */ - if ( ( flags & ( CERTDB_VALID_CA | CERTDB_TRUSTED_CA ) ) == - ( CERTDB_VALID_CA | CERTDB_TRUSTED_CA ) ) { - *trusted = PR_TRUE; - return SECSuccess; - } - /* fall through to test distrust */ - case certUsageAnyCA: - case certUsageUserCertImport: - /* do we distrust these certs explicitly */ - flags = trust.sslFlags; - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + if (flags & CERTDB_TRUSTED) { /* trust this cert */ + *trusted = PR_TRUE; + return SECSuccess; + } + else { /* don't trust this cert */ + *failedFlags = flags; + return SECFailure; + } + } + break; + case certUsageSSLServerWithStepUp: + /* XXX - step up certs can't be directly trusted, only distrust */ + flags = trust.sslFlags; + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + * authoritative */ + if ((flags & CERTDB_TRUSTED) == 0) { + /* don't trust this cert */ + *failedFlags = flags; + return SECFailure; + } + } + break; + case certUsageSSLCA: + flags = trust.sslFlags; + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + * authoritative */ + if ((flags & (CERTDB_TRUSTED | CERTDB_TRUSTED_CA)) == 0) { + /* don't trust this cert */ + *failedFlags = flags; + return SECFailure; + } + } + break; + case certUsageEmailSigner: + case certUsageEmailRecipient: + flags = trust.emailFlags; + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + * authoritative */ + if (flags & CERTDB_TRUSTED) { /* trust this cert */ + *trusted = PR_TRUE; + return SECSuccess; + } + else { /* don't trust this cert */ + *failedFlags = flags; + return SECFailure; + } + } + + break; + case certUsageObjectSigner: + flags = trust.objectSigningFlags; + + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + * authoritative */ + if (flags & CERTDB_TRUSTED) { /* trust this cert */ + *trusted = PR_TRUE; + return SECSuccess; + } + else { /* don't trust this cert */ + *failedFlags = flags; + return SECFailure; + } + } + break; + case certUsageVerifyCA: + case certUsageStatusResponder: + flags = trust.sslFlags; + /* is the cert directly trusted or not trusted ? */ + if ((flags & (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) == + (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) { + *trusted = PR_TRUE; + return SECSuccess; + } + flags = trust.emailFlags; + /* is the cert directly trusted or not trusted ? */ + if ((flags & (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) == + (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) { + *trusted = PR_TRUE; + return SECSuccess; + } + flags = trust.objectSigningFlags; + /* is the cert directly trusted or not trusted ? */ + if ((flags & (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) == + (CERTDB_VALID_CA | CERTDB_TRUSTED_CA)) { + *trusted = PR_TRUE; + return SECSuccess; + } + /* fall through to test distrust */ + case certUsageAnyCA: + case certUsageUserCertImport: + /* do we distrust these certs explicitly */ + flags = trust.sslFlags; + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is * authoritative */ - if ((flags & (CERTDB_TRUSTED|CERTDB_TRUSTED_CA)) == 0) { - *failedFlags = flags; - return SECFailure; - } - } - flags = trust.emailFlags; - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + if ((flags & (CERTDB_TRUSTED | CERTDB_TRUSTED_CA)) == 0) { + *failedFlags = flags; + return SECFailure; + } + } + flags = trust.emailFlags; + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is * authoritative */ - if ((flags & (CERTDB_TRUSTED|CERTDB_TRUSTED_CA)) == 0) { - *failedFlags = flags; - return SECFailure; - } - } - /* fall through */ - case certUsageProtectedObjectSigner: - flags = trust.objectSigningFlags; - if ( flags & CERTDB_TERMINAL_RECORD) { /* the trust record is - * authoritative */ - if ((flags & (CERTDB_TRUSTED|CERTDB_TRUSTED_CA)) == 0) { - *failedFlags = flags; - return SECFailure; - } - } - break; - } + if ((flags & (CERTDB_TRUSTED | CERTDB_TRUSTED_CA)) == 0) { + *failedFlags = flags; + return SECFailure; + } + } + /* fall through */ + case certUsageProtectedObjectSigner: + flags = trust.objectSigningFlags; + if (flags & CERTDB_TERMINAL_RECORD) { /* the trust record is + * authoritative */ + if ((flags & (CERTDB_TRUSTED | CERTDB_TRUSTED_CA)) == 0) { + *failedFlags = flags; + return SECFailure; + } + } + break; + } } return SECSuccess; } @@ -1161,8 +1179,8 @@ cert_CheckLeafTrust(CERTCertificate *cert, SECCertUsage certUsage, */ SECStatus CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertificateUsage requiredUsages, PRTime t, - void *wincx, CERTVerifyLog *log, SECCertificateUsage* returnedUsages) + PRBool checkSig, SECCertificateUsage requiredUsages, PRTime t, + void *wincx, CERTVerifyLog *log, SECCertificateUsage *returnedUsages) { SECStatus rv; SECStatus valid; @@ -1170,7 +1188,7 @@ CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert, unsigned int requiredCertType; unsigned int flags; unsigned int certType; - PRBool allowOverride; + PRBool allowOverride; SECCertTimeValidity validity; CERTStatusConfig *statusConfig; PRInt32 i; @@ -1189,28 +1207,29 @@ CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert, if (returnedUsages) { *returnedUsages = 0; - } else { + } + else { /* we don't have a place to return status for all usages, so we can skip checks for usages that aren't required */ checkAllUsages = PR_FALSE; } - valid = SECSuccess ; /* start off assuming cert is valid */ - + valid = SECSuccess; /* start off assuming cert is valid */ + /* make sure that the cert is valid at time t */ allowOverride = (PRBool)((requiredUsages & certificateUsageSSLServer) || (requiredUsages & certificateUsageSSLServerWithStepUp)); validity = CERT_CheckCertValidTimes(cert, t, allowOverride); - if ( validity != secCertTimeValid ) { + if (validity != secCertTimeValid) { valid = SECFailure; - LOG_ERROR_OR_EXIT(log,cert,0,validity); + LOG_ERROR_OR_EXIT(log, cert, 0, validity); } /* check key usage and netscape cert type */ cert_GetCertType(cert); certType = cert->nsCertType; - for (i=1; i<=certificateUsageHighest && - (SECSuccess == valid || returnedUsages || log) ; ) { + for (i = 1; i <= certificateUsageHighest && + (SECSuccess == valid || returnedUsages || log);) { PRBool requiredUsage = (i & requiredUsages) ? PR_TRUE : PR_FALSE; if (PR_FALSE == requiredUsage && PR_FALSE == checkAllUsages) { NEXT_USAGE(); @@ -1218,74 +1237,75 @@ CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert, if (returnedUsages) { *returnedUsages |= i; /* start off assuming this usage is valid */ } - switch ( certUsage ) { - case certUsageSSLClient: - case certUsageSSLServer: - case certUsageSSLServerWithStepUp: - case certUsageSSLCA: - case certUsageEmailSigner: - case certUsageEmailRecipient: - case certUsageObjectSigner: - case certUsageStatusResponder: - rv = CERT_KeyUsageAndTypeForCertUsage(certUsage, PR_FALSE, - &requiredKeyUsage, - &requiredCertType); - if ( rv != SECSuccess ) { + switch (certUsage) { + case certUsageSSLClient: + case certUsageSSLServer: + case certUsageSSLServerWithStepUp: + case certUsageSSLCA: + case certUsageEmailSigner: + case certUsageEmailRecipient: + case certUsageObjectSigner: + case certUsageStatusResponder: + rv = CERT_KeyUsageAndTypeForCertUsage(certUsage, PR_FALSE, + &requiredKeyUsage, + &requiredCertType); + if (rv != SECSuccess) { + PORT_Assert(0); + /* EXIT_IF_NOT_LOGGING(log); XXX ??? */ + requiredKeyUsage = 0; + requiredCertType = 0; + INVALID_USAGE(); + } + break; + + case certUsageAnyCA: + case certUsageProtectedObjectSigner: + case certUsageUserCertImport: + case certUsageVerifyCA: + /* these usages cannot be verified */ + NEXT_USAGE(); + + default: PORT_Assert(0); - /* EXIT_IF_NOT_LOGGING(log); XXX ??? */ requiredKeyUsage = 0; requiredCertType = 0; INVALID_USAGE(); - } - break; - - case certUsageAnyCA: - case certUsageProtectedObjectSigner: - case certUsageUserCertImport: - case certUsageVerifyCA: - /* these usages cannot be verified */ - NEXT_USAGE(); - - default: - PORT_Assert(0); - requiredKeyUsage = 0; - requiredCertType = 0; - INVALID_USAGE(); } - if ( CERT_CheckKeyUsage(cert, requiredKeyUsage) != SECSuccess ) { + if (CERT_CheckKeyUsage(cert, requiredKeyUsage) != SECSuccess) { if (PR_TRUE == requiredUsage) { PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); } - LOG_ERROR(log,cert,0,requiredKeyUsage); + LOG_ERROR(log, cert, 0, requiredKeyUsage); INVALID_USAGE(); } - if ( !( certType & requiredCertType ) ) { + if (!(certType & requiredCertType)) { if (PR_TRUE == requiredUsage) { PORT_SetError(SEC_ERROR_INADEQUATE_CERT_TYPE); } - LOG_ERROR(log,cert,0,requiredCertType); + LOG_ERROR(log, cert, 0, requiredCertType); INVALID_USAGE(); } - rv = cert_CheckLeafTrust(cert, certUsage, &flags, &trusted); - if (rv == SECFailure) { - if (PR_TRUE == requiredUsage) { - PORT_SetError(SEC_ERROR_UNTRUSTED_CERT); - } - LOG_ERROR(log, cert, 0, flags); - INVALID_USAGE(); - } else if (trusted) { - VALID_USAGE(); - } + rv = cert_CheckLeafTrust(cert, certUsage, &flags, &trusted); + if (rv == SECFailure) { + if (PR_TRUE == requiredUsage) { + PORT_SetError(SEC_ERROR_UNTRUSTED_CERT); + } + LOG_ERROR(log, cert, 0, flags); + INVALID_USAGE(); + } + else if (trusted) { + VALID_USAGE(); + } - if (PR_TRUE == revoked || PR_TRUE == sigerror) { - INVALID_USAGE(); - } + if (PR_TRUE == revoked || PR_TRUE == sigerror) { + INVALID_USAGE(); + } rv = cert_VerifyCertChain(handle, cert, - checkSig, &sigerror, - certUsage, t, wincx, log, - &revoked); + checkSig, &sigerror, + certUsage, t, wincx, log, + &revoked); if (rv != SECSuccess) { /* EXIT_IF_NOT_LOGGING(log); XXX ???? */ @@ -1306,10 +1326,10 @@ CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert, if (requiredUsages != certificateUsageStatusResponder && statusConfig != NULL) { if (statusConfig->statusChecker != NULL) { - rv = (* statusConfig->statusChecker)(handle, cert, - t, wincx); + rv = (*statusConfig->statusChecker)(handle, cert, + t, wincx); if (rv != SECSuccess) { - LOG_ERROR(log,cert,0,0); + LOG_ERROR(log, cert, 0, 0); revoked = PR_TRUE; INVALID_USAGE(); } @@ -1319,15 +1339,15 @@ CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert, NEXT_USAGE(); } - + loser: - return(valid); + return (valid); } SECStatus CERT_VerifyCert(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, PRTime t, - void *wincx, CERTVerifyLog *log) + PRBool checkSig, SECCertUsage certUsage, PRTime t, + void *wincx, CERTVerifyLog *log) { return cert_VerifyCertWithFlags(handle, cert, checkSig, certUsage, t, CERT_VERIFYCERT_USE_DEFAULTS, wincx, log); @@ -1343,86 +1363,86 @@ cert_VerifyCertWithFlags(CERTCertDBHandle *handle, CERTCertificate *cert, unsigned int requiredCertType; unsigned int failedFlags; unsigned int certType; - PRBool trusted; - PRBool allowOverride; + PRBool trusted; + PRBool allowOverride; SECCertTimeValidity validity; CERTStatusConfig *statusConfig; - -#ifdef notdef + +#ifdef notdef /* check if this cert is in the Evil list */ rv = CERT_CheckForEvilCert(cert); - if ( rv != SECSuccess ) { - PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE); - LOG_ERROR_OR_EXIT(log,cert,0,0); + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE); + LOG_ERROR_OR_EXIT(log, cert, 0, 0); } #endif - + /* make sure that the cert is valid at time t */ allowOverride = (PRBool)((certUsage == certUsageSSLServer) || (certUsage == certUsageSSLServerWithStepUp)); validity = CERT_CheckCertValidTimes(cert, t, allowOverride); - if ( validity != secCertTimeValid ) { - LOG_ERROR_OR_EXIT(log,cert,0,validity); + if (validity != secCertTimeValid) { + LOG_ERROR_OR_EXIT(log, cert, 0, validity); } /* check key usage and netscape cert type */ cert_GetCertType(cert); certType = cert->nsCertType; - switch ( certUsage ) { - case certUsageSSLClient: - case certUsageSSLServer: - case certUsageSSLServerWithStepUp: - case certUsageSSLCA: - case certUsageEmailSigner: - case certUsageEmailRecipient: - case certUsageObjectSigner: - case certUsageStatusResponder: - rv = CERT_KeyUsageAndTypeForCertUsage(certUsage, PR_FALSE, - &requiredKeyUsage, - &requiredCertType); - if ( rv != SECSuccess ) { - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - requiredKeyUsage = 0; - requiredCertType = 0; - } - break; - case certUsageVerifyCA: - case certUsageAnyCA: - requiredKeyUsage = KU_KEY_CERT_SIGN; - requiredCertType = NS_CERT_TYPE_CA; - if ( ! ( certType & NS_CERT_TYPE_CA ) ) { - certType |= NS_CERT_TYPE_CA; - } - break; - default: - PORT_Assert(0); - EXIT_IF_NOT_LOGGING(log); - requiredKeyUsage = 0; - requiredCertType = 0; + switch (certUsage) { + case certUsageSSLClient: + case certUsageSSLServer: + case certUsageSSLServerWithStepUp: + case certUsageSSLCA: + case certUsageEmailSigner: + case certUsageEmailRecipient: + case certUsageObjectSigner: + case certUsageStatusResponder: + rv = CERT_KeyUsageAndTypeForCertUsage(certUsage, PR_FALSE, + &requiredKeyUsage, + &requiredCertType); + if (rv != SECSuccess) { + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + requiredKeyUsage = 0; + requiredCertType = 0; + } + break; + case certUsageVerifyCA: + case certUsageAnyCA: + requiredKeyUsage = KU_KEY_CERT_SIGN; + requiredCertType = NS_CERT_TYPE_CA; + if (!(certType & NS_CERT_TYPE_CA)) { + certType |= NS_CERT_TYPE_CA; + } + break; + default: + PORT_Assert(0); + EXIT_IF_NOT_LOGGING(log); + requiredKeyUsage = 0; + requiredCertType = 0; } - if ( CERT_CheckKeyUsage(cert, requiredKeyUsage) != SECSuccess ) { - PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); - LOG_ERROR_OR_EXIT(log,cert,0,requiredKeyUsage); + if (CERT_CheckKeyUsage(cert, requiredKeyUsage) != SECSuccess) { + PORT_SetError(SEC_ERROR_INADEQUATE_KEY_USAGE); + LOG_ERROR_OR_EXIT(log, cert, 0, requiredKeyUsage); } - if ( !( certType & requiredCertType ) ) { - PORT_SetError(SEC_ERROR_INADEQUATE_CERT_TYPE); - LOG_ERROR_OR_EXIT(log,cert,0,requiredCertType); + if (!(certType & requiredCertType)) { + PORT_SetError(SEC_ERROR_INADEQUATE_CERT_TYPE); + LOG_ERROR_OR_EXIT(log, cert, 0, requiredCertType); } rv = cert_CheckLeafTrust(cert, certUsage, &failedFlags, &trusted); - if (rv == SECFailure) { - PORT_SetError(SEC_ERROR_UNTRUSTED_CERT); - LOG_ERROR_OR_EXIT(log, cert, 0, failedFlags); - } else if (trusted) { - goto done; + if (rv == SECFailure) { + PORT_SetError(SEC_ERROR_UNTRUSTED_CERT); + LOG_ERROR_OR_EXIT(log, cert, 0, failedFlags); + } + else if (trusted) { + goto done; } - rv = CERT_VerifyCertChain(handle, cert, checkSig, certUsage, - t, wincx, log); + t, wincx, log); if (rv != SECSuccess) { - EXIT_IF_NOT_LOGGING(log); + EXIT_IF_NOT_LOGGING(log); } /* @@ -1434,27 +1454,27 @@ cert_VerifyCertWithFlags(CERTCertDBHandle *handle, CERTCertificate *cert, * code. */ if (!(flags & CERT_VERIFYCERT_SKIP_OCSP) && - certUsage != certUsageStatusResponder) { - statusConfig = CERT_GetStatusConfig(handle); - if (statusConfig && statusConfig->statusChecker) { - rv = (* statusConfig->statusChecker)(handle, cert, - t, wincx); - if (rv != SECSuccess) { - LOG_ERROR_OR_EXIT(log,cert,0,0); - } - } + certUsage != certUsageStatusResponder) { + statusConfig = CERT_GetStatusConfig(handle); + if (statusConfig && statusConfig->statusChecker) { + rv = (*statusConfig->statusChecker)(handle, cert, + t, wincx); + if (rv != SECSuccess) { + LOG_ERROR_OR_EXIT(log, cert, 0, 0); + } + } } done: if (log && log->head) { - return SECFailure; + return SECFailure; } - return(SECSuccess); + return (SECSuccess); loser: rv = SECFailure; - - return(rv); + + return (rv); } /* @@ -1463,23 +1483,22 @@ loser: */ SECStatus CERT_VerifyCertificateNow(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertificateUsage requiredUsages, - void *wincx, SECCertificateUsage* returnedUsages) + PRBool checkSig, SECCertificateUsage requiredUsages, + void *wincx, SECCertificateUsage *returnedUsages) { - return(CERT_VerifyCertificate(handle, cert, checkSig, - requiredUsages, PR_Now(), wincx, NULL, returnedUsages)); + return (CERT_VerifyCertificate(handle, cert, checkSig, + requiredUsages, PR_Now(), wincx, NULL, returnedUsages)); } /* obsolete, do not use for new code */ SECStatus CERT_VerifyCertNow(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool checkSig, SECCertUsage certUsage, void *wincx) + PRBool checkSig, SECCertUsage certUsage, void *wincx) { - return(CERT_VerifyCert(handle, cert, checkSig, - certUsage, PR_Now(), wincx, NULL)); + return (CERT_VerifyCert(handle, cert, checkSig, + certUsage, PR_Now(), wincx, NULL)); } - /* [ FROM pcertdb.c ] */ /* * Supported usage values and types: @@ -1493,8 +1512,8 @@ CERT_VerifyCertNow(CERTCertDBHandle *handle, CERTCertificate *cert, CERTCertificate * CERT_FindMatchingCert(CERTCertDBHandle *handle, SECItem *derName, - CERTCertOwner owner, SECCertUsage usage, - PRBool preferTrusted, PRTime validTime, PRBool validOnly) + CERTCertOwner owner, SECCertUsage usage, + PRBool preferTrusted, PRTime validTime, PRBool validOnly) { CERTCertList *certList = NULL; CERTCertificate *cert = NULL; @@ -1502,94 +1521,94 @@ CERT_FindMatchingCert(CERTCertDBHandle *handle, SECItem *derName, unsigned int requiredTrustFlags; SECTrustType requiredTrustType; unsigned int flags; - + PRBool lookingForCA = PR_FALSE; SECStatus rv; CERTCertListNode *node; CERTCertificate *saveUntrustedCA = NULL; - + /* if preferTrusted is set, must be a CA cert */ - PORT_Assert( ! ( preferTrusted && ( owner != certOwnerCA ) ) ); - - if ( owner == certOwnerCA ) { - lookingForCA = PR_TRUE; - if ( preferTrusted ) { - rv = CERT_TrustFlagsForCACertUsage(usage, &requiredTrustFlags, - &requiredTrustType); - if ( rv != SECSuccess ) { - goto loser; - } - requiredTrustFlags |= CERTDB_VALID_CA; - } + PORT_Assert(!(preferTrusted && (owner != certOwnerCA))); + + if (owner == certOwnerCA) { + lookingForCA = PR_TRUE; + if (preferTrusted) { + rv = CERT_TrustFlagsForCACertUsage(usage, &requiredTrustFlags, + &requiredTrustType); + if (rv != SECSuccess) { + goto loser; + } + requiredTrustFlags |= CERTDB_VALID_CA; + } } certList = CERT_CreateSubjectCertList(NULL, handle, derName, validTime, - validOnly); - if ( certList != NULL ) { - rv = CERT_FilterCertListByUsage(certList, usage, lookingForCA); - if ( rv != SECSuccess ) { - goto loser; - } - - node = CERT_LIST_HEAD(certList); - - while ( !CERT_LIST_END(node, certList) ) { - cert = node->cert; + validOnly); + if (certList != NULL) { + rv = CERT_FilterCertListByUsage(certList, usage, lookingForCA); + if (rv != SECSuccess) { + goto loser; + } - /* looking for a trusted CA cert */ - if ( ( owner == certOwnerCA ) && preferTrusted && - ( requiredTrustType != trustTypeNone ) ) { + node = CERT_LIST_HEAD(certList); - if ( CERT_GetCertTrust(cert, &certTrust) != SECSuccess ) { - flags = 0; - } else { - flags = SEC_GET_TRUST_FLAGS(&certTrust, requiredTrustType); - } + while (!CERT_LIST_END(node, certList)) { + cert = node->cert; - if ( ( flags & requiredTrustFlags ) != requiredTrustFlags ) { - /* cert is not trusted */ - /* if this is the first cert to get this far, then save + /* looking for a trusted CA cert */ + if ((owner == certOwnerCA) && preferTrusted && + (requiredTrustType != trustTypeNone)) { + + if (CERT_GetCertTrust(cert, &certTrust) != SECSuccess) { + flags = 0; + } + else { + flags = SEC_GET_TRUST_FLAGS(&certTrust, requiredTrustType); + } + + if ((flags & requiredTrustFlags) != requiredTrustFlags) { + /* cert is not trusted */ + /* if this is the first cert to get this far, then save * it, so we can use it if we can't find a trusted one */ - if ( saveUntrustedCA == NULL ) { - saveUntrustedCA = cert; - } - goto endloop; - } - } - /* if we got this far, then this cert meets all criteria */ - break; - -endloop: - node = CERT_LIST_NEXT(node); - cert = NULL; - } + if (saveUntrustedCA == NULL) { + saveUntrustedCA = cert; + } + goto endloop; + } + } + /* if we got this far, then this cert meets all criteria */ + break; - /* use the saved one if we have it */ - if ( cert == NULL ) { - cert = saveUntrustedCA; - } + endloop: + node = CERT_LIST_NEXT(node); + cert = NULL; + } - /* if we found one then bump the ref count before freeing the list */ - if ( cert != NULL ) { - /* bump the ref count */ - cert = CERT_DupCertificate(cert); - } - - CERT_DestroyCertList(certList); + /* use the saved one if we have it */ + if (cert == NULL) { + cert = saveUntrustedCA; + } + + /* if we found one then bump the ref count before freeing the list */ + if (cert != NULL) { + /* bump the ref count */ + cert = CERT_DupCertificate(cert); + } + + CERT_DestroyCertList(certList); } - return(cert); + return (cert); loser: - if ( certList != NULL ) { - CERT_DestroyCertList(certList); + if (certList != NULL) { + CERT_DestroyCertList(certList); } - return(NULL); + return (NULL); } - /* [ From certdb.c ] */ /* * Filter a list of certificates, removing those certs that do not have @@ -1603,7 +1622,7 @@ loser: */ SECStatus CERT_FilterCertListByCANames(CERTCertList *certList, int nCANames, - char **caNames, SECCertUsage usage) + char **caNames, SECCertUsage usage) { CERTCertificate *issuerCert = NULL; CERTCertificate *subjectCert; @@ -1613,65 +1632,65 @@ CERT_FilterCertListByCANames(CERTCertList *certList, int nCANames, char **names; PRBool found; PRTime time; - - if ( nCANames <= 0 ) { - return(SECSuccess); + + if (nCANames <= 0) { + return (SECSuccess); } time = PR_Now(); - + node = CERT_LIST_HEAD(certList); - - while ( ! CERT_LIST_END(node, certList) ) { - cert = node->cert; - - subjectCert = CERT_DupCertificate(cert); - /* traverse the CA certs for this cert */ - found = PR_FALSE; - while ( subjectCert != NULL ) { - n = nCANames; - names = caNames; - - if (subjectCert->issuerName != NULL) { - while ( n > 0 ) { - if ( PORT_Strcmp(*names, subjectCert->issuerName) == 0 ) { - found = PR_TRUE; - break; - } + while (!CERT_LIST_END(node, certList)) { + cert = node->cert; - n--; - names++; + subjectCert = CERT_DupCertificate(cert); + + /* traverse the CA certs for this cert */ + found = PR_FALSE; + while (subjectCert != NULL) { + n = nCANames; + names = caNames; + + if (subjectCert->issuerName != NULL) { + while (n > 0) { + if (PORT_Strcmp(*names, subjectCert->issuerName) == 0) { + found = PR_TRUE; + break; + } + + n--; + names++; } - } + } - if ( found ) { - break; - } - - issuerCert = CERT_FindCertIssuer(subjectCert, time, usage); - if ( issuerCert == subjectCert ) { - CERT_DestroyCertificate(issuerCert); - issuerCert = NULL; - break; - } - CERT_DestroyCertificate(subjectCert); - subjectCert = issuerCert; + if (found) { + break; + } - } - CERT_DestroyCertificate(subjectCert); - if ( !found ) { - /* CA was not found, so remove this cert from the list */ - freenode = node; - node = CERT_LIST_NEXT(node); - CERT_RemoveCertListNode(freenode); - } else { - /* CA was found, so leave it in the list */ - node = CERT_LIST_NEXT(node); - } + issuerCert = CERT_FindCertIssuer(subjectCert, time, usage); + if (issuerCert == subjectCert) { + CERT_DestroyCertificate(issuerCert); + issuerCert = NULL; + break; + } + CERT_DestroyCertificate(subjectCert); + subjectCert = issuerCert; + } + CERT_DestroyCertificate(subjectCert); + if (!found) { + /* CA was not found, so remove this cert from the list */ + freenode = node; + node = CERT_LIST_NEXT(node); + CERT_RemoveCertListNode(freenode); + } + else { + /* CA was found, so leave it in the list */ + node = CERT_LIST_NEXT(node); + } } - - return(SECSuccess); + + return (SECSuccess); } /* @@ -1689,61 +1708,66 @@ CERT_FilterCertListByCANames(CERTCertList *certList, int nCANames, */ char * CERT_GetCertNicknameWithValidity(PLArenaPool *arena, CERTCertificate *cert, - char *expiredString, char *notYetGoodString) + char *expiredString, char *notYetGoodString) { SECCertTimeValidity validity; char *nickname = NULL, *tmpstr = NULL; - + validity = CERT_CheckCertValidTimes(cert, PR_Now(), PR_FALSE); /* if the cert is good, then just use the nickname directly */ - if ( validity == secCertTimeValid ) { - if ( arena == NULL ) { - nickname = PORT_Strdup(cert->nickname); - } else { - nickname = PORT_ArenaStrdup(arena, cert->nickname); - } - - if ( nickname == NULL ) { - goto loser; - } - } else { - - /* if the cert is not valid, then tack one of the strings on the - * end - */ - if ( validity == secCertTimeExpired ) { - tmpstr = PR_smprintf("%s%s", cert->nickname, - expiredString); - } else if ( validity == secCertTimeNotValidYet ) { - /* not yet valid */ - tmpstr = PR_smprintf("%s%s", cert->nickname, - notYetGoodString); - } else { - /* undetermined */ - tmpstr = PR_smprintf("%s", - "(NULL) (Validity Unknown)"); + if (validity == secCertTimeValid) { + if (arena == NULL) { + nickname = PORT_Strdup(cert->nickname); + } + else { + nickname = PORT_ArenaStrdup(arena, cert->nickname); } - if ( tmpstr == NULL ) { - goto loser; - } + if (nickname == NULL) { + goto loser; + } + } + else { - if ( arena ) { - /* copy the string into the arena and free the malloc'd one */ - nickname = PORT_ArenaStrdup(arena, tmpstr); - PORT_Free(tmpstr); - } else { - nickname = tmpstr; - } - if ( nickname == NULL ) { - goto loser; - } - } - return(nickname); + /* if the cert is not valid, then tack one of the strings on the + * end + */ + if (validity == secCertTimeExpired) { + tmpstr = PR_smprintf("%s%s", cert->nickname, + expiredString); + } + else if (validity == secCertTimeNotValidYet) { + /* not yet valid */ + tmpstr = PR_smprintf("%s%s", cert->nickname, + notYetGoodString); + } + else { + /* undetermined */ + tmpstr = PR_smprintf("%s", + "(NULL) (Validity Unknown)"); + } + + if (tmpstr == NULL) { + goto loser; + } + + if (arena) { + /* copy the string into the arena and free the malloc'd one */ + nickname = PORT_ArenaStrdup(arena, tmpstr); + PORT_Free(tmpstr); + } + else { + nickname = tmpstr; + } + if (nickname == NULL) { + goto loser; + } + } + return (nickname); loser: - return(NULL); + return (NULL); } /* @@ -1757,23 +1781,23 @@ loser: */ CERTCertNicknames * CERT_NicknameStringsFromCertList(CERTCertList *certList, char *expiredString, - char *notYetGoodString) + char *notYetGoodString) { CERTCertNicknames *names; PLArenaPool *arena; CERTCertListNode *node; char **nn; - + /* allocate an arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - return(NULL); + if (arena == NULL) { + return (NULL); } - + /* allocate the structure */ names = PORT_ArenaAlloc(arena, sizeof(CERTCertNicknames)); - if ( names == NULL ) { - goto loser; + if (names == NULL) { + goto loser; } /* init the structure */ @@ -1785,49 +1809,49 @@ CERT_NicknameStringsFromCertList(CERTCertList *certList, char *expiredString, /* count the certs in the list */ node = CERT_LIST_HEAD(certList); - while ( ! CERT_LIST_END(node, certList) ) { - names->numnicknames++; - node = CERT_LIST_NEXT(node); + while (!CERT_LIST_END(node, certList)) { + names->numnicknames++; + node = CERT_LIST_NEXT(node); } - + /* allocate nicknames array */ names->nicknames = PORT_ArenaAlloc(arena, - sizeof(char *) * names->numnicknames); - if ( names->nicknames == NULL ) { - goto loser; + sizeof(char *) * names->numnicknames); + if (names->nicknames == NULL) { + goto loser; } /* just in case printf can't deal with null strings */ - if (expiredString == NULL ) { - expiredString = ""; + if (expiredString == NULL) { + expiredString = ""; } - if ( notYetGoodString == NULL ) { - notYetGoodString = ""; + if (notYetGoodString == NULL) { + notYetGoodString = ""; } - + /* traverse the list of certs and collect the nicknames */ nn = names->nicknames; node = CERT_LIST_HEAD(certList); - while ( ! CERT_LIST_END(node, certList) ) { - *nn = CERT_GetCertNicknameWithValidity(arena, node->cert, - expiredString, - notYetGoodString); - if ( *nn == NULL ) { - goto loser; - } + while (!CERT_LIST_END(node, certList)) { + *nn = CERT_GetCertNicknameWithValidity(arena, node->cert, + expiredString, + notYetGoodString); + if (*nn == NULL) { + goto loser; + } - names->totallen += PORT_Strlen(*nn); - - nn++; - node = CERT_LIST_NEXT(node); + names->totallen += PORT_Strlen(*nn); + + nn++; + node = CERT_LIST_NEXT(node); } - return(names); + return (names); loser: PORT_FreeArena(arena, PR_FALSE); - return(NULL); + return (NULL); } /* @@ -1844,54 +1868,54 @@ loser: */ char * CERT_ExtractNicknameString(char *namestring, char *expiredString, - char *notYetGoodString) + char *notYetGoodString) { int explen, nyglen, namelen; int retlen; char *retstr; - + namelen = PORT_Strlen(namestring); explen = PORT_Strlen(expiredString); nyglen = PORT_Strlen(notYetGoodString); - - if ( namelen > explen ) { - if ( PORT_Strcmp(expiredString, &namestring[namelen-explen]) == 0 ) { - retlen = namelen - explen; - retstr = (char *)PORT_Alloc(retlen+1); - if ( retstr == NULL ) { - goto loser; - } - - PORT_Memcpy(retstr, namestring, retlen); - retstr[retlen] = '\0'; - goto done; - } + + if (namelen > explen) { + if (PORT_Strcmp(expiredString, &namestring[namelen - explen]) == 0) { + retlen = namelen - explen; + retstr = (char *)PORT_Alloc(retlen + 1); + if (retstr == NULL) { + goto loser; + } + + PORT_Memcpy(retstr, namestring, retlen); + retstr[retlen] = '\0'; + goto done; + } } - if ( namelen > nyglen ) { - if ( PORT_Strcmp(notYetGoodString, &namestring[namelen-nyglen]) == 0) { - retlen = namelen - nyglen; - retstr = (char *)PORT_Alloc(retlen+1); - if ( retstr == NULL ) { - goto loser; - } - - PORT_Memcpy(retstr, namestring, retlen); - retstr[retlen] = '\0'; - goto done; - } + if (namelen > nyglen) { + if (PORT_Strcmp(notYetGoodString, &namestring[namelen - nyglen]) == 0) { + retlen = namelen - nyglen; + retstr = (char *)PORT_Alloc(retlen + 1); + if (retstr == NULL) { + goto loser; + } + + PORT_Memcpy(retstr, namestring, retlen); + retstr[retlen] = '\0'; + goto done; + } } /* if name string is shorter than either invalid string, then it must * be a raw nickname */ retstr = PORT_Strdup(namestring); - + done: - return(retstr); + return (retstr); loser: - return(NULL); + return (NULL); } CERTCertList * @@ -1903,7 +1927,7 @@ CERT_GetCertChainFromCert(CERTCertificate *cert, PRTime time, SECCertUsage usage if (NULL == cert) { return NULL; } - + cert = CERT_DupCertificate(cert); if (NULL == cert) { PORT_SetError(SEC_ERROR_NO_MEMORY); @@ -1917,18 +1941,18 @@ CERT_GetCertChainFromCert(CERTCertificate *cert, PRTime time, SECCertUsage usage } while (cert != NULL && ++count <= CERT_MAX_CERT_CHAIN) { - if (SECSuccess != CERT_AddCertToListTail(chain, cert)) { + if (SECSuccess != CERT_AddCertToListTail(chain, cert)) { /* return partial chain */ PORT_SetError(SEC_ERROR_NO_MEMORY); return chain; } - if (cert->isRoot) { + if (cert->isRoot) { /* return complete chain */ - return chain; - } + return chain; + } - cert = CERT_FindCertIssuer(cert, time, usage); + cert = CERT_FindCertIssuer(cert, time, usage); } /* return partial chain */ diff --git a/security/nss/lib/certhigh/certvfypkix.c b/security/nss/lib/certhigh/certvfypkix.c index b89fe215fe84..7ae10b0c169a 100644 --- a/security/nss/lib/certhigh/certvfypkix.c +++ b/security/nss/lib/certhigh/certvfypkix.c @@ -12,7 +12,7 @@ */ #include "prerror.h" #include "prprf.h" - + #include "nspr.h" #include "pk11func.h" #include "certdb.h" @@ -38,7 +38,6 @@ pkix_pl_lifecycle_ObjectTableUpdate(int *objCountTable); PRInt32 parallelFnInvocationCount; #endif /* PKIX_OBJECT_LEAK_TEST */ - static PRBool usePKIXValidationEngine = PR_FALSE; /* @@ -104,7 +103,7 @@ CERT_GetUsePKIXForValidation() * Returns NULL if the function succeeds. * Returns a Fatal Error if the function fails in an unrecoverable way. */ -static PKIX_Error* +static PKIX_Error * cert_NssKeyUsagesToPkix( PRUint32 nssKeyUsage, PKIX_UInt32 *pPkixKeyUsage, @@ -120,7 +119,7 @@ cert_NssKeyUsagesToPkix( if (nssKeyUsage & KU_DIGITAL_SIGNATURE) { pkixKeyUsage |= PKIX_DIGITAL_SIGNATURE; } - + if (nssKeyUsage & KU_NON_REPUDIATION) { pkixKeyUsage |= PKIX_NON_REPUDIATION; } @@ -128,19 +127,19 @@ cert_NssKeyUsagesToPkix( if (nssKeyUsage & KU_KEY_ENCIPHERMENT) { pkixKeyUsage |= PKIX_KEY_ENCIPHERMENT; } - + if (nssKeyUsage & KU_DATA_ENCIPHERMENT) { pkixKeyUsage |= PKIX_DATA_ENCIPHERMENT; } - + if (nssKeyUsage & KU_KEY_AGREEMENT) { pkixKeyUsage |= PKIX_KEY_AGREEMENT; } - + if (nssKeyUsage & KU_KEY_CERT_SIGN) { pkixKeyUsage |= PKIX_KEY_CERT_SIGN; } - + if (nssKeyUsage & KU_CRL_SIGN) { pkixKeyUsage |= PKIX_CRL_SIGN; } @@ -148,7 +147,7 @@ cert_NssKeyUsagesToPkix( if (nssKeyUsage & KU_ENCIPHER_ONLY) { pkixKeyUsage |= PKIX_ENCIPHER_ONLY; } - + /* Not supported. XXX we should support this once it is * fixed in NSS */ /* pkixKeyUsage |= PKIX_DECIPHER_ONLY; */ @@ -176,17 +175,17 @@ typedef struct { } SECCertUsageToEku; const SECCertUsageToEku certUsageEkuStringMap[] = { - {certUsageSSLClient, ekuIndexSSLClient}, - {certUsageSSLServer, ekuIndexSSLServer}, - {certUsageSSLCA, ekuIndexSSLServer}, - {certUsageEmailSigner, ekuIndexEmail}, - {certUsageEmailRecipient, ekuIndexEmail}, - {certUsageObjectSigner, ekuIndexCodeSigner}, - {certUsageUserCertImport, ekuIndexUnknown}, - {certUsageVerifyCA, ekuIndexUnknown}, - {certUsageProtectedObjectSigner, ekuIndexUnknown}, - {certUsageStatusResponder, ekuIndexStatusResponder}, - {certUsageAnyCA, ekuIndexUnknown}, + { certUsageSSLClient, ekuIndexSSLClient }, + { certUsageSSLServer, ekuIndexSSLServer }, + { certUsageSSLCA, ekuIndexSSLServer }, + { certUsageEmailSigner, ekuIndexEmail }, + { certUsageEmailRecipient, ekuIndexEmail }, + { certUsageObjectSigner, ekuIndexCodeSigner }, + { certUsageUserCertImport, ekuIndexUnknown }, + { certUsageVerifyCA, ekuIndexUnknown }, + { certUsageProtectedObjectSigner, ekuIndexUnknown }, + { certUsageStatusResponder, ekuIndexStatusResponder }, + { certUsageAnyCA, ekuIndexUnknown }, }; /* @@ -200,15 +199,15 @@ const SECCertUsageToEku certUsageEkuStringMap[] = { * "cert" * Pointer to CERTCertificate structure of validating cert. * "requiredCertUsages" - * Required usage that will be converted to pkix eku and ku. + * Required usage that will be converted to pkix eku and ku. * "requiredKeyUsage", * Additional key usages impose to cert. * "isCA", - * it true, convert usages for cert that is a CA cert. + * it true, convert usages for cert that is a CA cert. * "ppkixEKUList" * Returned address of a list of pkix extended key usages. * "ppkixKU" - * Returned address of pkix required key usages bit field. + * Returned address of pkix required key usages bit field. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: @@ -218,29 +217,29 @@ const SECCertUsageToEku certUsageEkuStringMap[] = { * Returns a Cert Verify Error if the function fails in an unrecoverable way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ -static PKIX_Error* +static PKIX_Error * cert_NssCertificateUsageToPkixKUAndEKU( CERTCertificate *cert, - SECCertUsage requiredCertUsage, - PRUint32 requiredKeyUsages, - PRBool isCA, - PKIX_List **ppkixEKUList, - PKIX_UInt32 *ppkixKU, - void *plContext) + SECCertUsage requiredCertUsage, + PRUint32 requiredKeyUsages, + PRBool isCA, + PKIX_List **ppkixEKUList, + PKIX_UInt32 *ppkixKU, + void *plContext) { - PKIX_List *ekuOidsList = NULL; - PKIX_PL_OID *ekuOid = NULL; - int i = 0; - int ekuIndex = ekuIndexUnknown; + PKIX_List *ekuOidsList = NULL; + PKIX_PL_OID *ekuOid = NULL; + int i = 0; + int ekuIndex = ekuIndexUnknown; PKIX_ENTER(CERTVFYPKIX, "cert_NssCertificateUsageToPkixEku"); PKIX_NULLCHECK_TWO(ppkixEKUList, ppkixKU); - + PKIX_CHECK( PKIX_List_Create(&ekuOidsList, plContext), PKIX_LISTCREATEFAILED); - for (;i < PR_ARRAY_SIZE(certUsageEkuStringMap);i++) { + for (; i < PR_ARRAY_SIZE(certUsageEkuStringMap); i++) { const SECCertUsageToEku *usageToEkuElem = &certUsageEkuStringMap[i]; if (usageToEkuElem->certUsage == requiredCertUsage) { @@ -249,25 +248,25 @@ cert_NssCertificateUsageToPkixKUAndEKU( } } if (ekuIndex != ekuIndexUnknown) { - PRUint32 reqKeyUsage = 0; - PRUint32 reqCertType = 0; + PRUint32 reqKeyUsage = 0; + PRUint32 reqCertType = 0; CERT_KeyUsageAndTypeForCertUsage(requiredCertUsage, isCA, &reqKeyUsage, &reqCertType); - + requiredKeyUsages |= reqKeyUsage; - + PKIX_CHECK( PKIX_PL_OID_Create(ekuOidStrings[ekuIndex], &ekuOid, plContext), PKIX_OIDCREATEFAILED); - + PKIX_CHECK( PKIX_List_AppendItem(ekuOidsList, (PKIX_PL_Object *)ekuOid, plContext), PKIX_LISTAPPENDITEMFAILED); - + PKIX_DECREF(ekuOid); } @@ -279,7 +278,7 @@ cert_NssCertificateUsageToPkixKUAndEKU( ekuOidsList = NULL; cleanup: - + PKIX_DECREF(ekuOid); PKIX_DECREF(ekuOidsList); @@ -313,37 +312,36 @@ cleanup: * Returns a Cert Verify Error if the function fails in an unrecoverable way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ -static PKIX_Error* +static PKIX_Error * cert_ProcessingParamsSetKeyAndCertUsage( PKIX_ProcessingParams *procParams, - SECCertUsage requiredCertUsage, - PRUint32 requiredKeyUsages, - void *plContext) + SECCertUsage requiredCertUsage, + PRUint32 requiredKeyUsages, + void *plContext) { - PKIX_CertSelector *certSelector = NULL; + PKIX_CertSelector *certSelector = NULL; PKIX_ComCertSelParams *certSelParams = NULL; - PKIX_PL_NssContext *nssContext = (PKIX_PL_NssContext*)plContext; - + PKIX_PL_NssContext *nssContext = (PKIX_PL_NssContext *)plContext; + PKIX_ENTER(CERTVFYPKIX, "cert_ProcessingParamsSetKeyAndCertUsage"); PKIX_NULLCHECK_TWO(procParams, nssContext); - + PKIX_CHECK( pkix_pl_NssContext_SetCertUsage( - ((SECCertificateUsage)1) << requiredCertUsage, nssContext), - PKIX_NSSCONTEXTSETCERTUSAGEFAILED); + ((SECCertificateUsage)1) << requiredCertUsage, nssContext), + PKIX_NSSCONTEXTSETCERTUSAGEFAILED); if (requiredKeyUsages) { PKIX_CHECK( PKIX_ProcessingParams_GetTargetCertConstraints(procParams, &certSelector, plContext), PKIX_PROCESSINGPARAMSGETTARGETCERTCONSTRAINTSFAILED); - + PKIX_CHECK( PKIX_CertSelector_GetCommonCertSelectorParams(certSelector, &certSelParams, plContext), PKIX_CERTSELECTORGETCOMMONCERTSELECTORPARAMSFAILED); - - + PKIX_CHECK( PKIX_ComCertSelParams_SetKeyUsage(certSelParams, requiredKeyUsages, plContext), @@ -357,7 +355,7 @@ cleanup: } /* - * Unused parameters: + * Unused parameters: * * CERTCertList *initialChain, * CERTCertStores certStores, @@ -398,44 +396,44 @@ cleanup: * Returns a Cert Verify Error if the function fails in an unrecoverable way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ -static PKIX_Error* +static PKIX_Error * cert_CreatePkixProcessingParams( - CERTCertificate *cert, - PRBool checkSig, /* not used yet. See bug 391476 */ - PRTime time, - void *wincx, - PRBool useArena, - PRBool disableOCSPRemoteFetching, + CERTCertificate *cert, + PRBool checkSig, /* not used yet. See bug 391476 */ + PRTime time, + void *wincx, + PRBool useArena, + PRBool disableOCSPRemoteFetching, PKIX_ProcessingParams **pprocParams, - void **pplContext) + void **pplContext) { - PKIX_List *anchors = NULL; - PKIX_PL_Cert *targetCert = NULL; - PKIX_PL_Date *date = NULL; + PKIX_List *anchors = NULL; + PKIX_PL_Cert *targetCert = NULL; + PKIX_PL_Date *date = NULL; PKIX_ProcessingParams *procParams = NULL; - PKIX_CertSelector *certSelector = NULL; + PKIX_CertSelector *certSelector = NULL; PKIX_ComCertSelParams *certSelParams = NULL; - PKIX_CertStore *certStore = NULL; - PKIX_List *certStores = NULL; + PKIX_CertStore *certStore = NULL; + PKIX_List *certStores = NULL; PKIX_RevocationChecker *revChecker = NULL; - PKIX_UInt32 methodFlags = 0; - void *plContext = NULL; - CERTStatusConfig *statusConfig = NULL; - + PKIX_UInt32 methodFlags = 0; + void *plContext = NULL; + CERTStatusConfig *statusConfig = NULL; + PKIX_ENTER(CERTVFYPKIX, "cert_CreatePkixProcessingParams"); PKIX_NULLCHECK_TWO(cert, pprocParams); - + PKIX_CHECK( PKIX_PL_NssContext_Create(0, useArena, wincx, &plContext), PKIX_NSSCONTEXTCREATEFAILED); *pplContext = plContext; -#ifdef PKIX_NOTDEF +#ifdef PKIX_NOTDEF /* Functions should be implemented in patch for 390532 */ PKIX_CHECK( pkix_pl_NssContext_SetCertSignatureCheck(checkSig, - (PKIX_PL_NssContext*)plContext), + (PKIX_PL_NssContext *)plContext), PKIX_NSSCONTEXTSETCERTSIGNCHECKFAILED); #endif /* PKIX_NOTDEF */ @@ -443,11 +441,11 @@ cert_CreatePkixProcessingParams( PKIX_CHECK( PKIX_ProcessingParams_Create(&procParams, plContext), PKIX_PROCESSINGPARAMSCREATEFAILED); - + PKIX_CHECK( PKIX_ComCertSelParams_Create(&certSelParams, plContext), PKIX_COMCERTSELPARAMSCREATEFAILED); - + PKIX_CHECK( PKIX_PL_Cert_CreateFromCERTCertificate(cert, &targetCert, plContext), PKIX_CERTCREATEWITHNSSCERTFAILED); @@ -456,16 +454,16 @@ cert_CreatePkixProcessingParams( PKIX_ComCertSelParams_SetCertificate(certSelParams, targetCert, plContext), PKIX_COMCERTSELPARAMSSETCERTIFICATEFAILED); - + PKIX_CHECK( PKIX_CertSelector_Create(NULL, NULL, &certSelector, plContext), PKIX_COULDNOTCREATECERTSELECTOROBJECT); - + PKIX_CHECK( PKIX_CertSelector_SetCommonCertSelectorParams(certSelector, certSelParams, plContext), PKIX_CERTSELECTORSETCOMMONCERTSELECTORPARAMSFAILED); - + PKIX_CHECK( PKIX_ProcessingParams_SetTargetCertConstraints(procParams, certSelector, plContext), @@ -482,11 +480,11 @@ cert_CreatePkixProcessingParams( PKIX_CHECK( PKIX_PL_Pk11CertStore_Create(&certStore, plContext), PKIX_PK11CERTSTORECREATEFAILED); - + PKIX_CHECK( PKIX_List_Create(&certStores, plContext), PKIX_UNABLETOCREATELIST); - + PKIX_CHECK( PKIX_List_AppendItem(certStores, (PKIX_PL_Object *)certStore, plContext), @@ -507,11 +505,11 @@ cert_CreatePkixProcessingParams( PKIX_CHECK( PKIX_RevocationChecker_Create( - PKIX_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST | - PKIX_REV_MI_NO_OVERALL_INFO_REQUIREMENT, - PKIX_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST | - PKIX_REV_MI_NO_OVERALL_INFO_REQUIREMENT, - &revChecker, plContext), + PKIX_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST | + PKIX_REV_MI_NO_OVERALL_INFO_REQUIREMENT, + PKIX_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST | + PKIX_REV_MI_NO_OVERALL_INFO_REQUIREMENT, + &revChecker, plContext), PKIX_REVOCATIONCHECKERCREATEFAILED); PKIX_CHECK( @@ -520,27 +518,27 @@ cert_CreatePkixProcessingParams( PKIX_PROCESSINGPARAMSSETREVOCATIONCHECKERFAILED); /* CRL method flags */ - methodFlags = + methodFlags = PKIX_REV_M_TEST_USING_THIS_METHOD | PKIX_REV_M_FORBID_NETWORK_FETCHING | - PKIX_REV_M_SKIP_TEST_ON_MISSING_SOURCE | /* 0 */ - PKIX_REV_M_IGNORE_MISSING_FRESH_INFO | /* 0 */ + PKIX_REV_M_SKIP_TEST_ON_MISSING_SOURCE | /* 0 */ + PKIX_REV_M_IGNORE_MISSING_FRESH_INFO | /* 0 */ PKIX_REV_M_CONTINUE_TESTING_ON_FRESH_INFO; /* add CRL revocation method to check the leaf certificate */ PKIX_CHECK( PKIX_RevocationChecker_CreateAndAddMethod(revChecker, procParams, - PKIX_RevocationMethod_CRL, methodFlags, - 0, NULL, PKIX_TRUE, plContext), + PKIX_RevocationMethod_CRL, methodFlags, + 0, NULL, PKIX_TRUE, plContext), PKIX_REVOCATIONCHECKERADDMETHODFAILED); /* add CRL revocation method for other certs in the chain. */ PKIX_CHECK( PKIX_RevocationChecker_CreateAndAddMethod(revChecker, procParams, - PKIX_RevocationMethod_CRL, methodFlags, - 0, NULL, PKIX_FALSE, plContext), + PKIX_RevocationMethod_CRL, methodFlags, + 0, NULL, PKIX_FALSE, plContext), PKIX_REVOCATIONCHECKERADDMETHODFAILED); - + /* For compatibility with the old code, need to check that * statusConfig is set in the db handle and status checker * is defined befor allow ocsp status check on the leaf cert.*/ @@ -551,30 +549,30 @@ cert_CreatePkixProcessingParams( /* OCSP method flags */ methodFlags = PKIX_REV_M_TEST_USING_THIS_METHOD | - PKIX_REV_M_ALLOW_NETWORK_FETCHING | /* 0 */ - PKIX_REV_M_ALLOW_IMPLICIT_DEFAULT_SOURCE | /* 0 */ - PKIX_REV_M_SKIP_TEST_ON_MISSING_SOURCE | /* 0 */ - PKIX_REV_M_IGNORE_MISSING_FRESH_INFO | /* 0 */ + PKIX_REV_M_ALLOW_NETWORK_FETCHING | /* 0 */ + PKIX_REV_M_ALLOW_IMPLICIT_DEFAULT_SOURCE | /* 0 */ + PKIX_REV_M_SKIP_TEST_ON_MISSING_SOURCE | /* 0 */ + PKIX_REV_M_IGNORE_MISSING_FRESH_INFO | /* 0 */ PKIX_REV_M_CONTINUE_TESTING_ON_FRESH_INFO; - + /* Disabling ocsp fetching when checking the status * of ocsp response signer. Here and in the next if, * adjust flags for ocsp signer cert validation case. */ if (disableOCSPRemoteFetching) { methodFlags |= PKIX_REV_M_FORBID_NETWORK_FETCHING; } - - if (ocsp_FetchingFailureIsVerificationFailure() - && !disableOCSPRemoteFetching) { + + if (ocsp_FetchingFailureIsVerificationFailure() && + !disableOCSPRemoteFetching) { methodFlags |= PKIX_REV_M_FAIL_ON_MISSING_FRESH_INFO; } - + /* add OCSP revocation method to check only the leaf certificate.*/ PKIX_CHECK( PKIX_RevocationChecker_CreateAndAddMethod(revChecker, procParams, - PKIX_RevocationMethod_OCSP, methodFlags, - 1, NULL, PKIX_TRUE, plContext), + PKIX_RevocationMethod_OCSP, methodFlags, + 1, NULL, PKIX_TRUE, plContext), PKIX_REVOCATIONCHECKERADDMETHODFAILED); } @@ -585,14 +583,14 @@ cert_CreatePkixProcessingParams( PKIX_CHECK( PKIX_ProcessingParams_SetExplicitPolicyRequired(procParams, PR_FALSE, - plContext), + plContext), PKIX_PROCESSINGPARAMSSETEXPLICITPOLICYREQUIRED); PKIX_CHECK( PKIX_ProcessingParams_SetPolicyMappingInhibited(procParams, PR_FALSE, plContext), PKIX_PROCESSINGPARAMSSETPOLICYMAPPINGINHIBITED); - + *pprocParams = procParams; procParams = NULL; @@ -615,10 +613,10 @@ cleanup: * DESCRIPTION: * * Converts pkix cert list into nss cert list. - * + * * PARAMETERS: * "pkixCertChain" - * Pkix certificate list. + * Pkix certificate list. * "pvalidChain" * An address of returned nss certificate list. * "plContext" @@ -630,18 +628,18 @@ cleanup: * Returns a Cert Verify Error if the function fails in an unrecoverable way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ -static PKIX_Error* +static PKIX_Error * cert_PkixToNssCertsChain( - PKIX_List *pkixCertChain, - CERTCertList **pvalidChain, + PKIX_List *pkixCertChain, + CERTCertList **pvalidChain, void *plContext) { - PLArenaPool *arena = NULL; + PLArenaPool *arena = NULL; CERTCertificate *nssCert = NULL; - CERTCertList *validChain = NULL; - PKIX_PL_Object *certItem = NULL; - PKIX_UInt32 length = 0; - PKIX_UInt32 i = 0; + CERTCertList *validChain = NULL; + PKIX_PL_Object *certItem = NULL; + PKIX_UInt32 length = 0; + PKIX_UInt32 i = 0; PKIX_ENTER(CERTVFYPKIX, "cert_PkixToNssCertsChain"); PKIX_NULLCHECK_ONE(pvalidChain); @@ -653,7 +651,7 @@ cert_PkixToNssCertsChain( if (arena == NULL) { PKIX_ERROR(PKIX_OUTOFMEMORY); } - validChain = (CERTCertList*)PORT_ArenaZAlloc(arena, sizeof(CERTCertList)); + validChain = (CERTCertList *)PORT_ArenaZAlloc(arena, sizeof(CERTCertList)); if (validChain == NULL) { PKIX_ERROR(PKIX_PORTARENAALLOCFAILED); } @@ -665,22 +663,22 @@ cert_PkixToNssCertsChain( PKIX_List_GetLength(pkixCertChain, &length, plContext), PKIX_LISTGETLENGTHFAILED); - for (i = 0; i < length; i++){ + for (i = 0; i < length; i++) { CERTCertListNode *node = NULL; PKIX_CHECK( PKIX_List_GetItem(pkixCertChain, i, &certItem, plContext), PKIX_LISTGETITEMFAILED); - + PKIX_CHECK( - PKIX_PL_Cert_GetCERTCertificate((PKIX_PL_Cert*)certItem, &nssCert, - plContext), + PKIX_PL_Cert_GetCERTCertificate((PKIX_PL_Cert *)certItem, &nssCert, + plContext), PKIX_CERTGETCERTCERTIFICATEFAILED); - + node = (CERTCertListNode *)PORT_ArenaZAlloc(validChain->arena, sizeof(CERTCertListNode)); - if ( node == NULL ) { + if (node == NULL) { PKIX_ERROR(PKIX_PORTARENAALLOCFAILED); } @@ -695,10 +693,11 @@ cert_PkixToNssCertsChain( *pvalidChain = validChain; cleanup: - if (PKIX_ERROR_RECEIVED){ + if (PKIX_ERROR_RECEIVED) { if (validChain) { CERT_DestroyCertList(validChain); - } else if (arena) { + } + else if (arena) { PORT_FreeArena(arena, PR_FALSE); } if (nssCert) { @@ -710,7 +709,6 @@ cleanup: PKIX_RETURN(CERTVFYPKIX); } - /* * FUNCTION: cert_BuildAndValidateChain * DESCRIPTION: @@ -738,7 +736,7 @@ cleanup: * Returns a Cert Verify Error if the function fails in an unrecoverable way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ -static PKIX_Error* +static PKIX_Error * cert_BuildAndValidateChain( PKIX_ProcessingParams *procParams, PKIX_BuildResult **pResult, @@ -746,19 +744,19 @@ cert_BuildAndValidateChain( void *plContext) { PKIX_BuildResult *result = NULL; - PKIX_VerifyNode *verifyNode = NULL; - void *nbioContext = NULL; - void *state = NULL; - + PKIX_VerifyNode *verifyNode = NULL; + void *nbioContext = NULL; + void *state = NULL; + PKIX_ENTER(CERTVFYPKIX, "cert_BuildAndVerifyChain"); PKIX_NULLCHECK_TWO(procParams, pResult); - + do { if (nbioContext && state) { /* PKIX-XXX: need to test functionality of NBIO handling in libPkix. * See bug 391180 */ PRInt32 filesReady = 0; - PRPollDesc *pollDesc = (PRPollDesc*)nbioContext; + PRPollDesc *pollDesc = (PRPollDesc *)nbioContext; filesReady = PR_Poll(pollDesc, 1, PR_INTERVAL_NO_TIMEOUT); if (filesReady <= 0) { PKIX_ERROR(PKIX_PRPOLLRETBADFILENUM); @@ -769,7 +767,7 @@ cert_BuildAndValidateChain( PKIX_BuildChain(procParams, &nbioContext, &state, &result, &verifyNode, plContext), PKIX_UNABLETOBUILDCHAIN); - + } while (nbioContext && state); *pResult = result; @@ -782,7 +780,6 @@ cleanup: PKIX_RETURN(CERTVFYPKIX); } - /* * FUNCTION: cert_PkixErrorToNssCode * DESCRIPTION: @@ -817,16 +814,17 @@ cert_PkixErrorToNssCode( PKIX_ENTER(CERTVFYPKIX, "cert_PkixErrorToNssCode"); PKIX_NULLCHECK_TWO(error, pNssErr); - + /* Loop until we find at least one error with non-null * plErr code, that is going to be nss error code. */ while (errPtr) { if (errPtr->plErr && !nssErr) { nssErr = errPtr->plErr; - if (!pkixLog) break; + if (!pkixLog) + break; } if (pkixLog) { -#ifdef PKIX_ERROR_DESCRIPTION +#ifdef PKIX_ERROR_DESCRIPTION PR_LOG(pkixLog, 2, ("Error at level %d: %s\n", errLevel, PKIX_ErrorText[errPtr->errCode])); #else @@ -835,12 +833,13 @@ cert_PkixErrorToNssCode( #endif /* PKIX_ERROR_DESCRIPTION */ } errPtr = errPtr->cause; - errLevel += 1; + errLevel += 1; } PORT_Assert(nssErr); if (!nssErr) { *pNssErr = SEC_ERROR_LIBPKIX_INTERNAL; - } else { + } + else { *pNssErr = nssErr; } @@ -856,7 +855,7 @@ cert_PkixErrorToNssCode( * * PARAMETERS: * "log" - * Pointed to already allocated CERTVerifyLog structure. + * Pointed to already allocated CERTVerifyLog structure. * "node" * A node of PKIX_VerifyNode tree. * "plContext" @@ -874,7 +873,7 @@ cert_GetLogFromVerifyNode( PKIX_VerifyNode *node, void *plContext) { - PKIX_List *children = NULL; + PKIX_List *children = NULL; PKIX_VerifyNode *childNode = NULL; PKIX_ENTER(CERTVFYPKIX, "cert_GetLogFromVerifyNode"); @@ -894,26 +893,27 @@ cert_GetLogFromVerifyNode( cert_PkixErrorToNssCode(node->error, &nssErrorCode, plContext), PKIX_GETPKIXERRORCODEFAILED); - + cert_AddToVerifyLog(log, cert, nssErrorCode, node->depth, NULL); } } PKIX_RETURN(CERTVFYPKIX); - } else { - PRUint32 i = 0; - PKIX_UInt32 length = 0; + } + else { + PRUint32 i = 0; + PKIX_UInt32 length = 0; PKIX_CHECK( PKIX_List_GetLength(children, &length, plContext), PKIX_LISTGETLENGTHFAILED); - - for (i = 0; i < length; i++){ + + for (i = 0; i < length; i++) { PKIX_CHECK( - PKIX_List_GetItem(children, i, (PKIX_PL_Object**)&childNode, + PKIX_List_GetItem(children, i, (PKIX_PL_Object **)&childNode, plContext), PKIX_LISTGETITEMFAILED); - + PKIX_CHECK( cert_GetLogFromVerifyNode(log, childNode, plContext), PKIX_ERRORINRECURSIVEEQUALSCALL); @@ -943,7 +943,7 @@ cleanup: * In case of failure it will convert: * * pkix error to PR error code(will set it with PORT_SetError) * * pkix validation log to nss CERTVerifyLog - * + * * PARAMETERS: * "buildResult" * Build results returned by PKIX_BuildChain. @@ -968,23 +968,23 @@ cleanup: * Returns a Cert Verify Error if the function fails in an unrecoverable way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ -static PKIX_Error* +static PKIX_Error * cert_GetBuildResults( PKIX_BuildResult *buildResult, - PKIX_VerifyNode *verifyNode, - PKIX_Error *error, - CERTVerifyLog *log, + PKIX_VerifyNode *verifyNode, + PKIX_Error *error, + CERTVerifyLog *log, CERTCertificate **ptrustedRoot, - CERTCertList **pvalidChain, - void *plContext) + CERTCertList **pvalidChain, + void *plContext) { PKIX_ValidateResult *validResult = NULL; - CERTCertList *validChain = NULL; - CERTCertificate *trustedRoot = NULL; - PKIX_TrustAnchor *trustAnchor = NULL; - PKIX_PL_Cert *trustedCert = NULL; - PKIX_List *pkixCertChain = NULL; - + CERTCertList *validChain = NULL; + CERTCertificate *trustedRoot = NULL; + PKIX_TrustAnchor *trustAnchor = NULL; + PKIX_PL_Cert *trustedCert = NULL; + PKIX_List *pkixCertChain = NULL; + PKIX_ENTER(CERTVFYPKIX, "cert_GetBuildResults"); if (buildResult == NULL && error == NULL) { PKIX_ERROR(PKIX_NULLARGUMENT); @@ -1036,7 +1036,7 @@ cert_GetBuildResults( plContext), PKIX_CERTGETCERTCERTIFICATEFAILED); } - + PORT_Assert(!PKIX_ERROR_RECEIVED); if (trustedRoot) { @@ -1062,7 +1062,7 @@ cleanup: PKIX_DECREF(error); PKIX_DECREF(verifyNode); PKIX_DECREF(buildResult); - + PKIX_RETURN(CERTVFYPKIX); } @@ -1103,27 +1103,27 @@ cleanup: SECStatus cert_VerifyCertChainPkix( CERTCertificate *cert, - PRBool checkSig, - SECCertUsage requiredUsage, - PRTime time, - void *wincx, - CERTVerifyLog *log, - PRBool *pSigerror, - PRBool *pRevoked) + PRBool checkSig, + SECCertUsage requiredUsage, + PRTime time, + void *wincx, + CERTVerifyLog *log, + PRBool *pSigerror, + PRBool *pRevoked) { PKIX_ProcessingParams *procParams = NULL; - PKIX_BuildResult *result = NULL; - PKIX_VerifyNode *verifyNode = NULL; - PKIX_Error *error = NULL; + PKIX_BuildResult *result = NULL; + PKIX_VerifyNode *verifyNode = NULL; + PKIX_Error *error = NULL; - SECStatus rv = SECFailure; - void *plContext = NULL; + SECStatus rv = SECFailure; + void *plContext = NULL; #ifdef PKIX_OBJECT_LEAK_TEST - int leakedObjNum = 0; - int memLeakLoopCount = 0; - int objCountTable[PKIX_NUMTYPES]; - int fnInvLocalCount = 0; + int leakedObjNum = 0; + int memLeakLoopCount = 0; + int objCountTable[PKIX_NUMTYPES]; + int fnInvLocalCount = 0; PKIX_Boolean savedUsePkixEngFlag = usePKIXValidationEngine; if (usePKIXValidationEngine) { @@ -1136,93 +1136,95 @@ cert_VerifyCertChainPkix( testStartFnStackPosition = 2; fnStackNameArr[0] = "cert_VerifyCertChainPkix"; fnStackInvCountArr[0] = 0; - PKIX_Boolean abortOnLeak = + PKIX_Boolean abortOnLeak = (PR_GetEnv("PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK") == NULL) ? - PKIX_FALSE : PKIX_TRUE; + PKIX_FALSE + : PKIX_TRUE; runningLeakTest = PKIX_TRUE; /* Prevent multi-threaded run of object leak test */ fnInvLocalCount = PR_ATOMIC_INCREMENT(¶llelFnInvocationCount); PORT_Assert(fnInvLocalCount == 1); -do { - rv = SECFailure; - plContext = NULL; - procParams = NULL; - result = NULL; - verifyNode = NULL; - error = NULL; - errorGenerated = PKIX_FALSE; - stackPosition = 0; + do { + rv = SECFailure; + plContext = NULL; + procParams = NULL; + result = NULL; + verifyNode = NULL; + error = NULL; + errorGenerated = PKIX_FALSE; + stackPosition = 0; - if (leakedObjNum) { - pkix_pl_lifecycle_ObjectTableUpdate(objCountTable); - } - memLeakLoopCount += 1; + if (leakedObjNum) { + pkix_pl_lifecycle_ObjectTableUpdate(objCountTable); + } + memLeakLoopCount += 1; #endif /* PKIX_OBJECT_LEAK_TEST */ - error = - cert_CreatePkixProcessingParams(cert, checkSig, time, wincx, - PR_FALSE/*use arena*/, - requiredUsage == certUsageStatusResponder, - &procParams, &plContext); - if (error) { - goto cleanup; - } + error = + cert_CreatePkixProcessingParams(cert, checkSig, time, wincx, + PR_FALSE /*use arena*/, + requiredUsage == certUsageStatusResponder, + &procParams, &plContext); + if (error) { + goto cleanup; + } - error = - cert_ProcessingParamsSetKeyAndCertUsage(procParams, requiredUsage, 0, - plContext); - if (error) { - goto cleanup; - } + error = + cert_ProcessingParamsSetKeyAndCertUsage(procParams, requiredUsage, 0, + plContext); + if (error) { + goto cleanup; + } - error = - cert_BuildAndValidateChain(procParams, &result, &verifyNode, plContext); - if (error) { - goto cleanup; - } - - if (pRevoked) { - /* Currently always PR_FALSE. Will be fixed as a part of 394077 */ - *pRevoked = PR_FALSE; - } - if (pSigerror) { - /* Currently always PR_FALSE. Will be fixed as a part of 394077 */ - *pSigerror = PR_FALSE; - } - rv = SECSuccess; + error = + cert_BuildAndValidateChain(procParams, &result, &verifyNode, plContext); + if (error) { + goto cleanup; + } -cleanup: - error = cert_GetBuildResults(result, verifyNode, error, log, NULL, NULL, - plContext); - if (error) { - PKIX_PL_Object_DecRef((PKIX_PL_Object *)error, plContext); - } - if (procParams) { - PKIX_PL_Object_DecRef((PKIX_PL_Object *)procParams, plContext); - } - if (plContext) { - PKIX_PL_NssContext_Destroy(plContext); - } + if (pRevoked) { + /* Currently always PR_FALSE. Will be fixed as a part of 394077 */ + *pRevoked = PR_FALSE; + } + if (pSigerror) { + /* Currently always PR_FALSE. Will be fixed as a part of 394077 */ + *pSigerror = PR_FALSE; + } + rv = SECSuccess; + + cleanup: + error = cert_GetBuildResults(result, verifyNode, error, log, NULL, NULL, + plContext); + if (error) { + PKIX_PL_Object_DecRef((PKIX_PL_Object *)error, plContext); + } + if (procParams) { + PKIX_PL_Object_DecRef((PKIX_PL_Object *)procParams, plContext); + } + if (plContext) { + PKIX_PL_NssContext_Destroy(plContext); + } #ifdef PKIX_OBJECT_LEAK_TEST - leakedObjNum = - pkix_pl_lifecycle_ObjectLeakCheck(leakedObjNum ? objCountTable : NULL); - - if (pkixLog && leakedObjNum) { - PR_LOG(pkixLog, 1, ("The generated error caused an object leaks. Loop %d." - "Stack %s\n", memLeakLoopCount, errorFnStackString)); - } - PR_Free(errorFnStackString); - errorFnStackString = NULL; - if (abortOnLeak) { - PORT_Assert(leakedObjNum == 0); - } + leakedObjNum = + pkix_pl_lifecycle_ObjectLeakCheck(leakedObjNum ? objCountTable : NULL); -} while (errorGenerated); + if (pkixLog && leakedObjNum) { + PR_LOG(pkixLog, 1, ("The generated error caused an object leaks. Loop %d." + "Stack %s\n", + memLeakLoopCount, errorFnStackString)); + } + PR_Free(errorFnStackString); + errorFnStackString = NULL; + if (abortOnLeak) { + PORT_Assert(leakedObjNum == 0); + } - runningLeakTest = PKIX_FALSE; + } while (errorGenerated); + + runningLeakTest = PKIX_FALSE; PR_ATOMIC_DECREMENT(¶llelFnInvocationCount); usePKIXValidationEngine = savedUsePkixEngFlag; #endif /* PKIX_OBJECT_LEAK_TEST */ @@ -1231,50 +1233,55 @@ cleanup: } PKIX_CertSelector * -cert_GetTargetCertConstraints(CERTCertificate *target, void *plContext) +cert_GetTargetCertConstraints(CERTCertificate *target, void *plContext) { PKIX_ComCertSelParams *certSelParams = NULL; PKIX_CertSelector *certSelector = NULL; - PKIX_CertSelector *r= NULL; + PKIX_CertSelector *r = NULL; PKIX_PL_Cert *eeCert = NULL; PKIX_Error *error = NULL; error = PKIX_PL_Cert_CreateFromCERTCertificate(target, &eeCert, plContext); - if (error != NULL) goto cleanup; + if (error != NULL) + goto cleanup; error = PKIX_CertSelector_Create(NULL, NULL, &certSelector, plContext); - if (error != NULL) goto cleanup; + if (error != NULL) + goto cleanup; error = PKIX_ComCertSelParams_Create(&certSelParams, plContext); - if (error != NULL) goto cleanup; + if (error != NULL) + goto cleanup; error = PKIX_ComCertSelParams_SetCertificate( - certSelParams, eeCert, plContext); - if (error != NULL) goto cleanup; + certSelParams, eeCert, plContext); + if (error != NULL) + goto cleanup; - error = PKIX_CertSelector_SetCommonCertSelectorParams - (certSelector, certSelParams, plContext); - if (error != NULL) goto cleanup; + error = PKIX_CertSelector_SetCommonCertSelectorParams(certSelector, certSelParams, plContext); + if (error != NULL) + goto cleanup; error = PKIX_PL_Object_IncRef((PKIX_PL_Object *)certSelector, plContext); - if (error == NULL) r = certSelector; + if (error == NULL) + r = certSelector; cleanup: - if (certSelParams != NULL) + if (certSelParams != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)certSelParams, plContext); - if (eeCert != NULL) + if (eeCert != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)eeCert, plContext); - if (certSelector != NULL) + if (certSelector != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)certSelector, plContext); if (error != NULL) { - SECErrorCodes nssErr; + SECErrorCodes nssErr; - cert_PkixErrorToNssCode(error, &nssErr, plContext); + cert_PkixErrorToNssCode(error, &nssErr, plContext); PKIX_PL_Object_DecRef((PKIX_PL_Object *)error, plContext); - PORT_SetError(nssErr); + PORT_SetError(nssErr); } return r; @@ -1289,39 +1296,42 @@ cert_GetCertStores(void *plContext) PKIX_Error *error = NULL; error = PKIX_PL_Pk11CertStore_Create(&certStore, plContext); - if (error != NULL) goto cleanup; + if (error != NULL) + goto cleanup; error = PKIX_List_Create(&certStores, plContext); - if (error != NULL) goto cleanup; + if (error != NULL) + goto cleanup; - error = PKIX_List_AppendItem( certStores, - (PKIX_PL_Object *)certStore, plContext); - if (error != NULL) goto cleanup; + error = PKIX_List_AppendItem(certStores, + (PKIX_PL_Object *)certStore, plContext); + if (error != NULL) + goto cleanup; error = PKIX_PL_Object_IncRef((PKIX_PL_Object *)certStores, plContext); - if (error == NULL) r = certStores; + if (error == NULL) + r = certStores; cleanup: - if (certStores != NULL) + if (certStores != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)certStores, plContext); - if (certStore != NULL) + if (certStore != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)certStore, plContext); if (error != NULL) { - SECErrorCodes nssErr; + SECErrorCodes nssErr; - cert_PkixErrorToNssCode(error, &nssErr, plContext); + cert_PkixErrorToNssCode(error, &nssErr, plContext); PKIX_PL_Object_DecRef((PKIX_PL_Object *)error, plContext); - PORT_SetError(nssErr); + PORT_SetError(nssErr); } return r; } - struct fake_PKIX_PL_CertStruct { - CERTCertificate *nssCert; + CERTCertificate *nssCert; }; /* This needs to be part of the PKIX_PL_* */ @@ -1332,12 +1342,13 @@ cert_NSSCertFromPKIXCert(const PKIX_PL_Cert *pkix_cert) { struct fake_PKIX_PL_CertStruct *fcert = NULL; - fcert = (struct fake_PKIX_PL_CertStruct*)pkix_cert; + fcert = (struct fake_PKIX_PL_CertStruct *)pkix_cert; return CERT_DupCertificate(fcert->nssCert); } -PKIX_List *cert_PKIXMakeOIDList(const SECOidTag *oids, int oidCount, void *plContext) +PKIX_List * +cert_PKIXMakeOIDList(const SECOidTag *oids, int oidCount, void *plContext) { PKIX_List *r = NULL; PKIX_List *policyList = NULL; @@ -1347,16 +1358,16 @@ PKIX_List *cert_PKIXMakeOIDList(const SECOidTag *oids, int oidCount, void *plCon error = PKIX_List_Create(&policyList, plContext); if (error != NULL) { - goto cleanup; + goto cleanup; } - for (i=0; itype != cert_po_end; i++) { if (i->type == t) { - return i; + return i; } } return NULL; } - -static PKIX_Error* +static PKIX_Error * setRevocationMethod(PKIX_RevocationChecker *revChecker, PKIX_ProcessingParams *procParams, const CERTRevocationTests *revTest, @@ -1413,14 +1425,14 @@ setRevocationMethod(PKIX_RevocationChecker *revChecker, PKIX_UInt32 methodFlags = 0; PKIX_Error *error = NULL; PKIX_UInt32 priority = 0; - + if (revTest->number_of_defined_methods <= (PRUint32)certRevMethod) { return NULL; } if (revTest->preferred_methods) { unsigned int i = 0; - for (;i < revTest->number_of_preferred_methods;i++) { - if (revTest->preferred_methods[i] == certRevMethod) + for (; i < revTest->number_of_preferred_methods; i++) { + if (revTest->preferred_methods[i] == certRevMethod) break; } priority = i; @@ -1432,19 +1444,18 @@ setRevocationMethod(PKIX_RevocationChecker *revChecker, } error = PKIX_RevocationChecker_CreateAndAddMethod(revChecker, procParams, - pkixRevMethod, methodFlags, - priority, NULL, - isLeafTest, plContext); + pkixRevMethod, methodFlags, + priority, NULL, + isLeafTest, plContext); return error; } - SECStatus -cert_pkixSetParam(PKIX_ProcessingParams *procParams, - const CERTValInParam *param, void *plContext) +cert_pkixSetParam(PKIX_ProcessingParams *procParams, + const CERTValInParam *param, void *plContext) { - PKIX_Error * error = NULL; - SECStatus r=SECSuccess; + PKIX_Error *error = NULL; + SECStatus r = SECSuccess; PKIX_PL_Date *date = NULL; PKIX_List *policyOIDList = NULL; PKIX_List *certListPkix = NULL; @@ -1465,22 +1476,22 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, /* needed? */ error = PKIX_ProcessingParams_SetExplicitPolicyRequired( - procParams, PKIX_TRUE, plContext); + procParams, PKIX_TRUE, plContext); - if (error != NULL) { + if (error != NULL) { break; } policyOIDList = cert_PKIXMakeOIDList(param->value.array.oids, - param->value.arraySize,plContext); - if (policyOIDList == NULL) { - r = SECFailure; - PORT_SetError(SEC_ERROR_INVALID_ARGS); - break; - } + param->value.arraySize, plContext); + if (policyOIDList == NULL) { + r = SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + break; + } error = PKIX_ProcessingParams_SetInitialPolicies( - procParams,policyOIDList,plContext); + procParams, policyOIDList, plContext); break; case cert_pi_date: @@ -1490,9 +1501,10 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, errCode = SEC_ERROR_INVALID_TIME; break; } - } else { + } + else { error = pkix_pl_Date_CreateFromPRTime(param->value.scalar.time, - &date, plContext); + &date, plContext); if (error != NULL) { errCode = SEC_ERROR_INVALID_TIME; break; @@ -1505,8 +1517,7 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, } break; - case cert_pi_revocationFlags: - { + case cert_pi_revocationFlags: { PKIX_UInt32 leafIMFlags = 0; PKIX_UInt32 chainIMFlags = 0; PKIX_Boolean validatingResponderCert = PKIX_FALSE; @@ -1518,7 +1529,7 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, break; } - leafIMFlags = + leafIMFlags = flags->leafTests.cert_rev_method_independent_flags; chainIMFlags = flags->chainTests.cert_rev_method_independent_flags; @@ -1532,12 +1543,12 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, error = PKIX_ProcessingParams_SetRevocationChecker(procParams, - revChecker, plContext); + revChecker, plContext); if (error) { break; } - if (((PKIX_PL_NssContext*)plContext)->certificateUsage & + if (((PKIX_PL_NssContext *)plContext)->certificateUsage & certificateUsageStatusResponder) { validatingResponderCert = PKIX_TRUE; } @@ -1582,8 +1593,7 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, break; } - } - break; + } break; case cert_pi_trustAnchors: certList = param->value.pointer.chain; @@ -1596,10 +1606,10 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, if (error != NULL) { break; } - for(node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node, certList); - node = CERT_LIST_NEXT(node) ) { + for (node = CERT_LIST_HEAD(certList); !CERT_LIST_END(node, certList); + node = CERT_LIST_NEXT(node)) { error = PKIX_PL_Cert_CreateFromCERTCertificate(node->cert, - &certPkix, plContext); + &certPkix, plContext); if (error) { break; } @@ -1609,8 +1619,8 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, break; } error = PKIX_List_AppendItem(certListPkix, - (PKIX_PL_Object*)trustAnchor, plContext); - if (error) { + (PKIX_PL_Object *)trustAnchor, plContext); + if (error) { break; } PKIX_PL_Object_DecRef((PKIX_PL_Object *)trustAnchor, plContext); @@ -1626,12 +1636,12 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, case cert_pi_useAIACertFetch: error = PKIX_ProcessingParams_SetUseAIAForCertFetching(procParams, - (PRBool)(param->value.scalar.b != 0), + (PRBool)(param->value.scalar.b != + 0), plContext); break; - case cert_pi_chainVerifyCallback: - { + case cert_pi_chainVerifyCallback: { const CERTChainVerifyCallback *chainVerifyCallback = param->value.pointer.chainVerifyCallback; if (!chainVerifyCallback || !chainVerifyCallback->isChainValid) { @@ -1641,13 +1651,13 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, } nssContext->chainVerifyCallback = *chainVerifyCallback; - } - break; + } break; case cert_pi_useOnlyTrustAnchors: error = PKIX_ProcessingParams_SetUseOnlyTrustAnchors(procParams, - (PRBool)(param->value.scalar.b != 0), + (PRBool)(param->value.scalar.b != + 0), plContext); break; @@ -1660,19 +1670,19 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, if (policyOIDList != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)policyOIDList, plContext); - if (date != NULL) + if (date != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)date, plContext); - if (revChecker != NULL) + if (revChecker != NULL) PKIX_PL_Object_DecRef((PKIX_PL_Object *)revChecker, plContext); - if (certListPkix) + if (certListPkix) PKIX_PL_Object_DecRef((PKIX_PL_Object *)certListPkix, plContext); - if (trustAnchor) + if (trustAnchor) PKIX_PL_Object_DecRef((PKIX_PL_Object *)trustAnchor, plContext); - if (certPkix) + if (certPkix) PKIX_PL_Object_DecRef((PKIX_PL_Object *)certPkix, plContext); if (error != NULL) { @@ -1681,8 +1691,7 @@ cert_pkixSetParam(PKIX_ProcessingParams *procParams, r = SECFailure; } - return r; - + return r; } void @@ -1695,207 +1704,188 @@ cert_pkixDestroyValOutParam(CERTValOutParam *params) } for (i = params; i->type != cert_po_end; i++) { switch (i->type) { - case cert_po_trustAnchor: - if (i->value.pointer.cert) { - CERT_DestroyCertificate(i->value.pointer.cert); - i->value.pointer.cert = NULL; - } - break; + case cert_po_trustAnchor: + if (i->value.pointer.cert) { + CERT_DestroyCertificate(i->value.pointer.cert); + i->value.pointer.cert = NULL; + } + break; - case cert_po_certList: - if (i->value.pointer.chain) { - CERT_DestroyCertList(i->value.pointer.chain); - i->value.pointer.chain = NULL; - } - break; + case cert_po_certList: + if (i->value.pointer.chain) { + CERT_DestroyCertList(i->value.pointer.chain); + i->value.pointer.chain = NULL; + } + break; - default: - break; + default: + break; } } } static PRUint64 certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_LeafFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FORBID_NETWORK_FETCHING - | CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, - /* ocsp */ - CERT_REV_M_TEST_USING_THIS_METHOD + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FORBID_NETWORK_FETCHING | + CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, + /* ocsp */ + CERT_REV_M_TEST_USING_THIS_METHOD }; static PRUint64 certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_ChainFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FORBID_NETWORK_FETCHING - | CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, - /* ocsp */ - 0 + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FORBID_NETWORK_FETCHING | + CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, + /* ocsp */ + 0 }; -static CERTRevocationMethodIndex -certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_Method_Preference = { - cert_revocation_method_crl -}; +static CERTRevocationMethodIndex + certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_Method_Preference = { + cert_revocation_method_crl + }; static const CERTRevocationFlags certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy = { - { - /* leafTests */ - 2, - certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_LeafFlags, - 1, - &certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_Method_Preference, - 0 - }, - { - /* chainTests */ - 2, - certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_ChainFlags, - 0, - 0, - 0 - } + { /* leafTests */ + 2, + certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_LeafFlags, + 1, + &certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_Method_Preference, + 0 }, + { /* chainTests */ + 2, + certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_ChainFlags, + 0, + 0, + 0 } }; -extern const CERTRevocationFlags* +extern const CERTRevocationFlags * CERT_GetClassicOCSPEnabledSoftFailurePolicy() { return &certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy; } - static PRUint64 certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_LeafFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FORBID_NETWORK_FETCHING - | CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, - /* ocsp */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FORBID_NETWORK_FETCHING | + CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, + /* ocsp */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO }; static PRUint64 certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_ChainFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FORBID_NETWORK_FETCHING - | CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, - /* ocsp */ - 0 + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FORBID_NETWORK_FETCHING | + CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, + /* ocsp */ + 0 }; -static CERTRevocationMethodIndex -certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_Method_Preference = { - cert_revocation_method_crl -}; +static CERTRevocationMethodIndex + certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_Method_Preference = { + cert_revocation_method_crl + }; static const CERTRevocationFlags certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy = { - { - /* leafTests */ - 2, - certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_LeafFlags, - 1, - &certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_Method_Preference, - 0 - }, - { - /* chainTests */ - 2, - certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_ChainFlags, - 0, - 0, - 0 - } + { /* leafTests */ + 2, + certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_LeafFlags, + 1, + &certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_Method_Preference, + 0 }, + { /* chainTests */ + 2, + certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy_ChainFlags, + 0, + 0, + 0 } }; -extern const CERTRevocationFlags* +extern const CERTRevocationFlags * CERT_GetClassicOCSPEnabledHardFailurePolicy() { return &certRev_NSS_3_11_Ocsp_Enabled_Hard_Policy; } - static PRUint64 certRev_NSS_3_11_Ocsp_Disabled_Policy_LeafFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FORBID_NETWORK_FETCHING - | CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, - /* ocsp */ - 0 + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FORBID_NETWORK_FETCHING | + CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, + /* ocsp */ + 0 }; static PRUint64 certRev_NSS_3_11_Ocsp_Disabled_Policy_ChainFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FORBID_NETWORK_FETCHING - | CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, - /* ocsp */ - 0 + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FORBID_NETWORK_FETCHING | + CERT_REV_M_CONTINUE_TESTING_ON_FRESH_INFO, + /* ocsp */ + 0 }; static const CERTRevocationFlags certRev_NSS_3_11_Ocsp_Disabled_Policy = { - { - /* leafTests */ - 2, - certRev_NSS_3_11_Ocsp_Disabled_Policy_LeafFlags, - 0, - 0, - 0 - }, - { - /* chainTests */ - 2, - certRev_NSS_3_11_Ocsp_Disabled_Policy_ChainFlags, - 0, - 0, - 0 - } + { /* leafTests */ + 2, + certRev_NSS_3_11_Ocsp_Disabled_Policy_LeafFlags, + 0, + 0, + 0 }, + { /* chainTests */ + 2, + certRev_NSS_3_11_Ocsp_Disabled_Policy_ChainFlags, + 0, + 0, + 0 } }; -extern const CERTRevocationFlags* +extern const CERTRevocationFlags * CERT_GetClassicOCSPDisabledPolicy() { return &certRev_NSS_3_11_Ocsp_Disabled_Policy; } - static PRUint64 certRev_PKIX_Verify_Nist_Policy_LeafFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO - | CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE, - /* ocsp */ - 0 + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO | + CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE, + /* ocsp */ + 0 }; static PRUint64 certRev_PKIX_Verify_Nist_Policy_ChainFlags[2] = { - /* crl */ - CERT_REV_M_TEST_USING_THIS_METHOD - | CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO - | CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE, - /* ocsp */ - 0 + /* crl */ + CERT_REV_M_TEST_USING_THIS_METHOD | + CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO | + CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE, + /* ocsp */ + 0 }; static const CERTRevocationFlags certRev_PKIX_Verify_Nist_Policy = { - { - /* leafTests */ - 2, - certRev_PKIX_Verify_Nist_Policy_LeafFlags, - 0, - 0, - 0 - }, - { - /* chainTests */ - 2, - certRev_PKIX_Verify_Nist_Policy_ChainFlags, - 0, - 0, - 0 - } + { /* leafTests */ + 2, + certRev_PKIX_Verify_Nist_Policy_LeafFlags, + 0, + 0, + 0 }, + { /* chainTests */ + 2, + certRev_PKIX_Verify_Nist_Policy_ChainFlags, + 0, + 0, + 0 } }; -extern const CERTRevocationFlags* +extern const CERTRevocationFlags * CERT_GetPKIXVerifyNistRevocationPolicy() { return &certRev_PKIX_Verify_Nist_Policy; @@ -1907,56 +1897,57 @@ CERT_AllocCERTRevocationFlags( PRUint32 number_chain_methods, PRUint32 number_chain_pref_methods) { CERTRevocationFlags *flags; - + flags = PORT_New(CERTRevocationFlags); if (!flags) - return(NULL); - + return (NULL); + flags->leafTests.number_of_defined_methods = number_leaf_methods; - flags->leafTests.cert_rev_flags_per_method = + flags->leafTests.cert_rev_flags_per_method = PORT_NewArray(PRUint64, number_leaf_methods); flags->leafTests.number_of_preferred_methods = number_leaf_pref_methods; - flags->leafTests.preferred_methods = + flags->leafTests.preferred_methods = PORT_NewArray(CERTRevocationMethodIndex, number_leaf_pref_methods); flags->chainTests.number_of_defined_methods = number_chain_methods; - flags->chainTests.cert_rev_flags_per_method = + flags->chainTests.cert_rev_flags_per_method = PORT_NewArray(PRUint64, number_chain_methods); flags->chainTests.number_of_preferred_methods = number_chain_pref_methods; - flags->chainTests.preferred_methods = + flags->chainTests.preferred_methods = PORT_NewArray(CERTRevocationMethodIndex, number_chain_pref_methods); - - if (!flags->leafTests.cert_rev_flags_per_method - || !flags->leafTests.preferred_methods - || !flags->chainTests.cert_rev_flags_per_method - || !flags->chainTests.preferred_methods) { + + if (!flags->leafTests.cert_rev_flags_per_method || + !flags->leafTests.preferred_methods || + !flags->chainTests.cert_rev_flags_per_method || + !flags->chainTests.preferred_methods) { CERT_DestroyCERTRevocationFlags(flags); return (NULL); } - + return flags; } -void CERT_DestroyCERTRevocationFlags(CERTRevocationFlags *flags) +void +CERT_DestroyCERTRevocationFlags(CERTRevocationFlags *flags) { if (!flags) - return; - + return; + if (flags->leafTests.cert_rev_flags_per_method) PORT_Free(flags->leafTests.cert_rev_flags_per_method); if (flags->leafTests.preferred_methods) PORT_Free(flags->leafTests.preferred_methods); - + if (flags->chainTests.cert_rev_flags_per_method) PORT_Free(flags->chainTests.cert_rev_flags_per_method); if (flags->chainTests.preferred_methods) PORT_Free(flags->chainTests.preferred_methods); - PORT_Free(flags); + PORT_Free(flags); } /* @@ -1984,36 +1975,37 @@ void CERT_DestroyCERTRevocationFlags(CERTRevocationFlags *flags) * * CERT_PKIXVerifyCert(cert, &output, args */ -SECStatus CERT_PKIXVerifyCert( - CERTCertificate *cert, - SECCertificateUsage usages, - CERTValInParam *paramsIn, - CERTValOutParam *paramsOut, - void *wincx) +SECStatus +CERT_PKIXVerifyCert( + CERTCertificate *cert, + SECCertificateUsage usages, + CERTValInParam *paramsIn, + CERTValOutParam *paramsOut, + void *wincx) { - SECStatus r = SECFailure; - PKIX_Error * error = NULL; + SECStatus r = SECFailure; + PKIX_Error *error = NULL; PKIX_ProcessingParams *procParams = NULL; - PKIX_BuildResult * buildResult = NULL; - void * nbioContext = NULL; /* for non-blocking IO */ - void * buildState = NULL; /* for non-blocking IO */ - PKIX_CertSelector * certSelector = NULL; - PKIX_List * certStores = NULL; - PKIX_ValidateResult * valResult = NULL; - PKIX_VerifyNode * verifyNode = NULL; - PKIX_TrustAnchor * trustAnchor = NULL; - PKIX_PL_Cert * trustAnchorCert = NULL; - PKIX_List * builtCertList = NULL; - CERTValOutParam * oparam = NULL; - int i=0; + PKIX_BuildResult *buildResult = NULL; + void *nbioContext = NULL; /* for non-blocking IO */ + void *buildState = NULL; /* for non-blocking IO */ + PKIX_CertSelector *certSelector = NULL; + PKIX_List *certStores = NULL; + PKIX_ValidateResult *valResult = NULL; + PKIX_VerifyNode *verifyNode = NULL; + PKIX_TrustAnchor *trustAnchor = NULL; + PKIX_PL_Cert *trustAnchorCert = NULL; + PKIX_List *builtCertList = NULL; + CERTValOutParam *oparam = NULL; + int i = 0; void *plContext = NULL; #ifdef PKIX_OBJECT_LEAK_TEST - int leakedObjNum = 0; - int memLeakLoopCount = 0; - int objCountTable[PKIX_NUMTYPES]; - int fnInvLocalCount = 0; + int leakedObjNum = 0; + int memLeakLoopCount = 0; + int objCountTable[PKIX_NUMTYPES]; + int fnInvLocalCount = 0; PKIX_Boolean savedUsePkixEngFlag = usePKIXValidationEngine; if (usePKIXValidationEngine) { @@ -2026,227 +2018,231 @@ SECStatus CERT_PKIXVerifyCert( testStartFnStackPosition = 1; fnStackNameArr[0] = "CERT_PKIXVerifyCert"; fnStackInvCountArr[0] = 0; - PKIX_Boolean abortOnLeak = + PKIX_Boolean abortOnLeak = (PR_GetEnv("PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK") == NULL) ? - PKIX_FALSE : PKIX_TRUE; + PKIX_FALSE + : PKIX_TRUE; runningLeakTest = PKIX_TRUE; /* Prevent multi-threaded run of object leak test */ fnInvLocalCount = PR_ATOMIC_INCREMENT(¶llelFnInvocationCount); PORT_Assert(fnInvLocalCount == 1); -do { - r = SECFailure; - error = NULL; - procParams = NULL; - buildResult = NULL; - nbioContext = NULL; /* for non-blocking IO */ - buildState = NULL; /* for non-blocking IO */ - certSelector = NULL; - certStores = NULL; - valResult = NULL; - verifyNode = NULL; - trustAnchor = NULL; - trustAnchorCert = NULL; - builtCertList = NULL; - oparam = NULL; - i=0; - errorGenerated = PKIX_FALSE; - stackPosition = 0; + do { + r = SECFailure; + error = NULL; + procParams = NULL; + buildResult = NULL; + nbioContext = NULL; /* for non-blocking IO */ + buildState = NULL; /* for non-blocking IO */ + certSelector = NULL; + certStores = NULL; + valResult = NULL; + verifyNode = NULL; + trustAnchor = NULL; + trustAnchorCert = NULL; + builtCertList = NULL; + oparam = NULL; + i = 0; + errorGenerated = PKIX_FALSE; + stackPosition = 0; - if (leakedObjNum) { - pkix_pl_lifecycle_ObjectTableUpdate(objCountTable); - } - memLeakLoopCount += 1; + if (leakedObjNum) { + pkix_pl_lifecycle_ObjectTableUpdate(objCountTable); + } + memLeakLoopCount += 1; #endif /* PKIX_OBJECT_LEAK_TEST */ - error = PKIX_PL_NssContext_Create( + error = PKIX_PL_NssContext_Create( 0, PR_FALSE /*use arena*/, wincx, &plContext); - if (error != NULL) { /* need pkix->nss error map */ - PORT_SetError(SEC_ERROR_CERT_NOT_VALID); - goto cleanup; - } - - error = pkix_pl_NssContext_SetCertUsage(usages, plContext); - if (error != NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto cleanup; - } - - error = PKIX_ProcessingParams_Create(&procParams, plContext); - if (error != NULL) { /* need pkix->nss error map */ - PORT_SetError(SEC_ERROR_CERT_NOT_VALID); - goto cleanup; - } - - /* local cert store should be set into procParams before - * filling in revocation settings. */ - certStores = cert_GetCertStores(plContext); - if (certStores == NULL) { - goto cleanup; - } - error = PKIX_ProcessingParams_SetCertStores - (procParams, certStores, plContext); - if (error != NULL) { - goto cleanup; - } - - /* now process the extensible input parameters structure */ - if (paramsIn != NULL) { - i=0; - while (paramsIn[i].type != cert_pi_end) { - if (paramsIn[i].type >= cert_pi_max) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto cleanup; - } - if (cert_pkixSetParam(procParams, - ¶msIn[i],plContext) != SECSuccess) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto cleanup; - } - i++; + if (error != NULL) { /* need pkix->nss error map */ + PORT_SetError(SEC_ERROR_CERT_NOT_VALID); + goto cleanup; } - } - certSelector = cert_GetTargetCertConstraints(cert, plContext); - if (certSelector == NULL) { - goto cleanup; - } - error = PKIX_ProcessingParams_SetTargetCertConstraints - (procParams, certSelector, plContext); - if (error != NULL) { - goto cleanup; - } + error = pkix_pl_NssContext_SetCertUsage(usages, plContext); + if (error != NULL) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto cleanup; + } - error = PKIX_BuildChain( procParams, &nbioContext, - &buildState, &buildResult, &verifyNode, - plContext); - if (error != NULL) { - goto cleanup; - } + error = PKIX_ProcessingParams_Create(&procParams, plContext); + if (error != NULL) { /* need pkix->nss error map */ + PORT_SetError(SEC_ERROR_CERT_NOT_VALID); + goto cleanup; + } - error = PKIX_BuildResult_GetValidateResult( buildResult, &valResult, - plContext); - if (error != NULL) { - goto cleanup; - } - - error = PKIX_ValidateResult_GetTrustAnchor( valResult, &trustAnchor, - plContext); - if (error != NULL) { - goto cleanup; - } - - if (trustAnchor != NULL) { - error = PKIX_TrustAnchor_GetTrustedCert( trustAnchor, &trustAnchorCert, - plContext); + /* local cert store should be set into procParams before + * filling in revocation settings. */ + certStores = cert_GetCertStores(plContext); + if (certStores == NULL) { + goto cleanup; + } + error = PKIX_ProcessingParams_SetCertStores(procParams, certStores, plContext); if (error != NULL) { goto cleanup; } - } -#ifdef PKIX_OBJECT_LEAK_TEST - /* Can not continue if error was generated but not returned. - * Jumping to cleanup. */ - if (errorGenerated) goto cleanup; -#endif /* PKIX_OBJECT_LEAK_TEST */ - - oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_trustAnchor); - if (oparam != NULL) { - if (trustAnchorCert != NULL) { - oparam->value.pointer.cert = - cert_NSSCertFromPKIXCert(trustAnchorCert); - } else { - oparam->value.pointer.cert = NULL; - } - } - - error = PKIX_BuildResult_GetCertChain( buildResult, &builtCertList, - plContext); - if (error != NULL) { - goto cleanup; - } - - oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_certList); - if (oparam != NULL) { - error = cert_PkixToNssCertsChain(builtCertList, - &oparam->value.pointer.chain, - plContext); - if (error) goto cleanup; - } - - r = SECSuccess; - -cleanup: - if (verifyNode) { - /* Return validation log only upon error. */ - oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_errorLog); -#ifdef PKIX_OBJECT_LEAK_TEST - if (!errorGenerated) -#endif /* PKIX_OBJECT_LEAK_TEST */ - if (r && oparam != NULL) { - PKIX_Error *tmpError = - cert_GetLogFromVerifyNode(oparam->value.pointer.log, - verifyNode, plContext); - if (tmpError) { - PKIX_PL_Object_DecRef((PKIX_PL_Object *)tmpError, plContext); + /* now process the extensible input parameters structure */ + if (paramsIn != NULL) { + i = 0; + while (paramsIn[i].type != cert_pi_end) { + if (paramsIn[i].type >= cert_pi_max) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto cleanup; + } + if (cert_pkixSetParam(procParams, + ¶msIn[i], plContext) != + SECSuccess) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto cleanup; + } + i++; } } - PKIX_PL_Object_DecRef((PKIX_PL_Object *)verifyNode, plContext); - } - if (procParams != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)procParams, plContext); + certSelector = cert_GetTargetCertConstraints(cert, plContext); + if (certSelector == NULL) { + goto cleanup; + } + error = PKIX_ProcessingParams_SetTargetCertConstraints(procParams, certSelector, plContext); + if (error != NULL) { + goto cleanup; + } - if (trustAnchorCert != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)trustAnchorCert, plContext); + error = PKIX_BuildChain(procParams, &nbioContext, + &buildState, &buildResult, &verifyNode, + plContext); + if (error != NULL) { + goto cleanup; + } - if (trustAnchor != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)trustAnchor, plContext); + error = PKIX_BuildResult_GetValidateResult(buildResult, &valResult, + plContext); + if (error != NULL) { + goto cleanup; + } - if (valResult != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)valResult, plContext); + error = PKIX_ValidateResult_GetTrustAnchor(valResult, &trustAnchor, + plContext); + if (error != NULL) { + goto cleanup; + } - if (buildResult != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)buildResult, plContext); - - if (certStores != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)certStores, plContext); - - if (certSelector != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)certSelector, plContext); - - if (builtCertList != NULL) - PKIX_PL_Object_DecRef((PKIX_PL_Object *)builtCertList, plContext); - - if (error != NULL) { - SECErrorCodes nssErrorCode = 0; - - cert_PkixErrorToNssCode(error, &nssErrorCode, plContext); - cert_pkixDestroyValOutParam(paramsOut); - PORT_SetError(nssErrorCode); - PKIX_PL_Object_DecRef((PKIX_PL_Object *)error, plContext); - } - - PKIX_PL_NssContext_Destroy(plContext); + if (trustAnchor != NULL) { + error = PKIX_TrustAnchor_GetTrustedCert(trustAnchor, &trustAnchorCert, + plContext); + if (error != NULL) { + goto cleanup; + } + } #ifdef PKIX_OBJECT_LEAK_TEST - leakedObjNum = - pkix_pl_lifecycle_ObjectLeakCheck(leakedObjNum ? objCountTable : NULL); + /* Can not continue if error was generated but not returned. + * Jumping to cleanup. */ + if (errorGenerated) + goto cleanup; +#endif /* PKIX_OBJECT_LEAK_TEST */ - if (pkixLog && leakedObjNum) { - PR_LOG(pkixLog, 1, ("The generated error caused an object leaks. Loop %d." - "Stack %s\n", memLeakLoopCount, errorFnStackString)); - } - PR_Free(errorFnStackString); - errorFnStackString = NULL; - if (abortOnLeak) { - PORT_Assert(leakedObjNum == 0); - } - -} while (errorGenerated); + oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_trustAnchor); + if (oparam != NULL) { + if (trustAnchorCert != NULL) { + oparam->value.pointer.cert = + cert_NSSCertFromPKIXCert(trustAnchorCert); + } + else { + oparam->value.pointer.cert = NULL; + } + } - runningLeakTest = PKIX_FALSE; + error = PKIX_BuildResult_GetCertChain(buildResult, &builtCertList, + plContext); + if (error != NULL) { + goto cleanup; + } + + oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_certList); + if (oparam != NULL) { + error = cert_PkixToNssCertsChain(builtCertList, + &oparam->value.pointer.chain, + plContext); + if (error) + goto cleanup; + } + + r = SECSuccess; + + cleanup: + if (verifyNode) { + /* Return validation log only upon error. */ + oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_errorLog); +#ifdef PKIX_OBJECT_LEAK_TEST + if (!errorGenerated) +#endif /* PKIX_OBJECT_LEAK_TEST */ + if (r && oparam != NULL) { + PKIX_Error *tmpError = + cert_GetLogFromVerifyNode(oparam->value.pointer.log, + verifyNode, plContext); + if (tmpError) { + PKIX_PL_Object_DecRef((PKIX_PL_Object *)tmpError, plContext); + } + } + PKIX_PL_Object_DecRef((PKIX_PL_Object *)verifyNode, plContext); + } + + if (procParams != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)procParams, plContext); + + if (trustAnchorCert != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)trustAnchorCert, plContext); + + if (trustAnchor != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)trustAnchor, plContext); + + if (valResult != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)valResult, plContext); + + if (buildResult != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)buildResult, plContext); + + if (certStores != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)certStores, plContext); + + if (certSelector != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)certSelector, plContext); + + if (builtCertList != NULL) + PKIX_PL_Object_DecRef((PKIX_PL_Object *)builtCertList, plContext); + + if (error != NULL) { + SECErrorCodes nssErrorCode = 0; + + cert_PkixErrorToNssCode(error, &nssErrorCode, plContext); + cert_pkixDestroyValOutParam(paramsOut); + PORT_SetError(nssErrorCode); + PKIX_PL_Object_DecRef((PKIX_PL_Object *)error, plContext); + } + + PKIX_PL_NssContext_Destroy(plContext); + +#ifdef PKIX_OBJECT_LEAK_TEST + leakedObjNum = + pkix_pl_lifecycle_ObjectLeakCheck(leakedObjNum ? objCountTable : NULL); + + if (pkixLog && leakedObjNum) { + PR_LOG(pkixLog, 1, ("The generated error caused an object leaks. Loop %d." + "Stack %s\n", + memLeakLoopCount, errorFnStackString)); + } + PR_Free(errorFnStackString); + errorFnStackString = NULL; + if (abortOnLeak) { + PORT_Assert(leakedObjNum == 0); + } + + } while (errorGenerated); + + runningLeakTest = PKIX_FALSE; PR_ATOMIC_DECREMENT(¶llelFnInvocationCount); usePKIXValidationEngine = savedUsePkixEngFlag; #endif /* PKIX_OBJECT_LEAK_TEST */ diff --git a/security/nss/lib/certhigh/crlv2.c b/security/nss/lib/certhigh/crlv2.c index 7d8dbb9fa6b9..beb90cbe202a 100644 --- a/security/nss/lib/certhigh/crlv2.c +++ b/security/nss/lib/certhigh/crlv2.c @@ -17,17 +17,15 @@ SECStatus CERT_FindCRLExtensionByOID(CERTCrl *crl, SECItem *oid, SECItem *value) { - return (cert_FindExtensionByOID (crl->extensions, oid, value)); + return (cert_FindExtensionByOID(crl->extensions, oid, value)); } - SECStatus CERT_FindCRLExtension(CERTCrl *crl, int tag, SECItem *value) { - return (cert_FindExtension (crl->extensions, tag, value)); + return (cert_FindExtension(crl->extensions, tag, value)); } - /* Callback to set extensions and adjust verison */ static void SetCrlExts(void *object, CERTCertExtension **exts) @@ -35,13 +33,13 @@ SetCrlExts(void *object, CERTCertExtension **exts) CERTCrl *crl = (CERTCrl *)object; crl->extensions = exts; - DER_SetUInteger (crl->arena, &crl->version, SEC_CRL_VERSION_2); + DER_SetUInteger(crl->arena, &crl->version, SEC_CRL_VERSION_2); } void * CERT_StartCRLExtensions(CERTCrl *crl) { - return (cert_StartExtensions ((void *)crl, crl->arena, SetCrlExts)); + return (cert_StartExtensions((void *)crl, crl->arena, SetCrlExts)); } static void @@ -55,11 +53,12 @@ SetCrlEntryExts(void *object, CERTCertExtension **exts) void * CERT_StartCRLEntryExtensions(CERTCrl *crl, CERTCrlEntry *entry) { - return (cert_StartExtensions (entry, crl->arena, SetCrlEntryExts)); + return (cert_StartExtensions(entry, crl->arena, SetCrlEntryExts)); } -SECStatus CERT_FindCRLNumberExten (PLArenaPool *arena, CERTCrl *crl, - SECItem *value) +SECStatus +CERT_FindCRLNumberExten(PLArenaPool *arena, CERTCrl *crl, + SECItem *value) { SECItem encodedExtenValue; SECItem *tmpItem = NULL; @@ -70,91 +69,94 @@ SECStatus CERT_FindCRLNumberExten (PLArenaPool *arena, CERTCrl *crl, encodedExtenValue.len = 0; rv = cert_FindExtension(crl->extensions, SEC_OID_X509_CRL_NUMBER, - &encodedExtenValue); - if ( rv != SECSuccess ) - return (rv); + &encodedExtenValue); + if (rv != SECSuccess) + return (rv); mark = PORT_ArenaMark(arena); tmpItem = SECITEM_ArenaDupItem(arena, &encodedExtenValue); if (tmpItem) { - rv = SEC_QuickDERDecodeItem (arena, value, - SEC_ASN1_GET(SEC_IntegerTemplate), - tmpItem); - } else { + rv = SEC_QuickDERDecodeItem(arena, value, + SEC_ASN1_GET(SEC_IntegerTemplate), + tmpItem); + } + else { rv = SECFailure; } - PORT_Free (encodedExtenValue.data); + PORT_Free(encodedExtenValue.data); if (rv == SECFailure) { PORT_ArenaRelease(arena, mark); - } else { + } + else { PORT_ArenaUnmark(arena, mark); } return (rv); } -SECStatus CERT_FindCRLEntryReasonExten (CERTCrlEntry *crlEntry, - CERTCRLEntryReasonCode *value) +SECStatus +CERT_FindCRLEntryReasonExten(CERTCrlEntry *crlEntry, + CERTCRLEntryReasonCode *value) { - SECItem wrapperItem = {siBuffer,0}; - SECItem tmpItem = {siBuffer,0}; + SECItem wrapperItem = { siBuffer, 0 }; + SECItem tmpItem = { siBuffer, 0 }; SECStatus rv; PLArenaPool *arena = NULL; - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( ! arena ) { - return(SECFailure); + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (!arena) { + return (SECFailure); } - - rv = cert_FindExtension(crlEntry->extensions, SEC_OID_X509_REASON_CODE, + + rv = cert_FindExtension(crlEntry->extensions, SEC_OID_X509_REASON_CODE, &wrapperItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = SEC_QuickDERDecodeItem(arena, &tmpItem, SEC_ASN1_GET(SEC_EnumeratedTemplate), &wrapperItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - *value = (CERTCRLEntryReasonCode) DER_GetInteger(&tmpItem); + *value = (CERTCRLEntryReasonCode)DER_GetInteger(&tmpItem); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - if ( wrapperItem.data ) { - PORT_Free(wrapperItem.data); + + if (wrapperItem.data) { + PORT_Free(wrapperItem.data); } return (rv); } -SECStatus CERT_FindInvalidDateExten (CERTCrl *crl, PRTime *value) +SECStatus +CERT_FindInvalidDateExten(CERTCrl *crl, PRTime *value) { SECItem encodedExtenValue; - SECItem decodedExtenValue = {siBuffer,0}; + SECItem decodedExtenValue = { siBuffer, 0 }; SECStatus rv; encodedExtenValue.data = decodedExtenValue.data = NULL; encodedExtenValue.len = decodedExtenValue.len = 0; - rv = cert_FindExtension - (crl->extensions, SEC_OID_X509_INVALID_DATE, &encodedExtenValue); - if ( rv != SECSuccess ) - return (rv); + rv = cert_FindExtension(crl->extensions, SEC_OID_X509_INVALID_DATE, &encodedExtenValue); + if (rv != SECSuccess) + return (rv); - rv = SEC_ASN1DecodeItem (NULL, &decodedExtenValue, - SEC_ASN1_GET(SEC_GeneralizedTimeTemplate), - &encodedExtenValue); + rv = SEC_ASN1DecodeItem(NULL, &decodedExtenValue, + SEC_ASN1_GET(SEC_GeneralizedTimeTemplate), + &encodedExtenValue); if (rv == SECSuccess) - rv = DER_GeneralizedTimeToTime(value, &encodedExtenValue); - PORT_Free (decodedExtenValue.data); - PORT_Free (encodedExtenValue.data); + rv = DER_GeneralizedTimeToTime(value, &encodedExtenValue); + PORT_Free(decodedExtenValue.data); + PORT_Free(encodedExtenValue.data); return (rv); } diff --git a/security/nss/lib/certhigh/ocsp.c b/security/nss/lib/certhigh/ocsp.c index 86ae0a063b32..e6c9c219ea0f 100644 --- a/security/nss/lib/certhigh/ocsp.c +++ b/security/nss/lib/certhigh/ocsp.c @@ -33,13 +33,13 @@ #include "ocspi.h" #include "genname.h" #include "certxutl.h" -#include "pk11func.h" /* for PK11_HashBuf */ +#include "pk11func.h" /* for PK11_HashBuf */ #include #include #define DEFAULT_OCSP_CACHE_SIZE 1000 -#define DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 1*60*60L -#define DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 24*60*60L +#define DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 1 * 60 * 60L +#define DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 24 * 60 * 60L #define DEFAULT_OSCP_TIMEOUT_SECONDS 60 #define MICROSECONDS_PER_SECOND 1000000L @@ -89,48 +89,45 @@ static struct OCSPGlobalStruct { SEC_OcspFailureMode ocspFailureMode; CERT_StringFromCertFcn alternateOCSPAIAFcn; PRBool forcePost; -} OCSP_Global = { NULL, - NULL, - DEFAULT_OCSP_CACHE_SIZE, +} OCSP_Global = { NULL, + NULL, + DEFAULT_OCSP_CACHE_SIZE, DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT, DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT, DEFAULT_OSCP_TIMEOUT_SECONDS, - {NULL, 0, NULL, NULL}, + { NULL, 0, NULL, NULL }, ocspMode_FailureIsVerificationFailure, NULL, - PR_FALSE - }; - - + PR_FALSE }; /* Forward declarations */ static SECItem * -ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena, +ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena, CERTOCSPRequest *request, const char *location, - const char *method, - PRTime time, + const char *method, + PRTime time, PRBool addServiceLocator, void *pwArg, CERTOCSPRequest **pRequest); static SECStatus -ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, - CERTOCSPCertID *certID, - CERTCertificate *cert, - PRTime time, +ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, + CERTOCSPCertID *certID, + CERTCertificate *cert, + PRTime time, void *pwArg, PRBool *certIDWasConsumed, SECStatus *rv_ocsp); static SECStatus ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle, - CERTOCSPCertID *certID, - CERTCertificate *cert, - PRTime time, - void *pwArg, - const SECItem *encodedResponse, - CERTOCSPResponse **pDecodedResponse, - CERTOCSPSingleResponse **pSingle); + CERTOCSPCertID *certID, + CERTCertificate *cert, + PRTime time, + void *pwArg, + const SECItem *encodedResponse, + CERTOCSPResponse **pDecodedResponse, + CERTOCSPSingleResponse **pSingle); static SECStatus ocsp_CertRevokedAfter(ocspRevokedInfo *revokedInfo, PRTime time); @@ -149,12 +146,13 @@ cert_DupOCSPCertID(const CERTOCSPCertID *src); #define OCSP_TRACE_CERT(cert) dumpCertificate(cert) #define OCSP_TRACE_CERTID(certid) dumpCertID(certid) -#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS) \ - || defined(XP_MACOSX) +#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS) || \ + defined(XP_MACOSX) #define NSS_HAVE_GETENV 1 #endif -static PRBool wantOcspTrace(void) +static PRBool +wantOcspTrace(void) { static PRBool firstTime = PR_TRUE; static PRBool wantTrace = PR_FALSE; @@ -176,7 +174,7 @@ ocsp_Trace(const char *format, ...) { char buf[2000]; va_list args; - + if (!wantOcspTrace()) return; va_start(args, format); @@ -208,7 +206,8 @@ printHexString(const char *prefix, SECItem *hexval) for (i = 0; i < hexval->len; i++) { if (i != hexval->len - 1) { hexbuf = PR_sprintf_append(hexbuf, "%02x:", hexval->data[i]); - } else { + } + else { hexbuf = PR_sprintf_append(hexbuf, "%02x", hexval->data[i]); } } @@ -235,10 +234,10 @@ dumpCertificate(CERTCertificate *cert) DER_DecodeTimeChoice(&timeAfter, &cert->validity.notAfter); PR_ExplodeTime(timeBefore, PR_GMTParameters, &beforePrintable); PR_ExplodeTime(timeAfter, PR_GMTParameters, &afterPrintable); - rv1 = PR_FormatTime(beforestr, 256, "%a %b %d %H:%M:%S %Y", - &beforePrintable); - rv2 = PR_FormatTime(afterstr, 256, "%a %b %d %H:%M:%S %Y", - &afterPrintable); + rv1 = PR_FormatTime(beforestr, 256, "%a %b %d %H:%M:%S %Y", + &beforePrintable); + rv2 = PR_FormatTime(afterstr, 256, "%a %b %d %H:%M:%S %Y", + &afterPrintable); ocsp_Trace("OCSP ## VALIDITY: %s to %s\n", rv1 ? beforestr : "", rv2 ? afterstr : ""); } @@ -261,27 +260,27 @@ SECStatus SEC_RegisterDefaultHttpClient(const SEC_HttpClientFcn *fcnTable) { if (!OCSP_Global.monitor) { - PORT_SetError(SEC_ERROR_NOT_INITIALIZED); - return SECFailure; + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); + return SECFailure; } - + PR_EnterMonitor(OCSP_Global.monitor); OCSP_Global.defaultHttpClientFcn = fcnTable; PR_ExitMonitor(OCSP_Global.monitor); - + return SECSuccess; } SECStatus CERT_RegisterAlternateOCSPAIAInfoCallBack( - CERT_StringFromCertFcn newCallback, - CERT_StringFromCertFcn * oldCallback) + CERT_StringFromCertFcn newCallback, + CERT_StringFromCertFcn *oldCallback) { CERT_StringFromCertFcn old; if (!OCSP_Global.monitor) { - PORT_SetError(SEC_ERROR_NOT_INITIALIZED); - return SECFailure; + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); + return SECFailure; } PR_EnterMonitor(OCSP_Global.monitor); @@ -289,7 +288,7 @@ CERT_RegisterAlternateOCSPAIAInfoCallBack( OCSP_Global.alternateOCSPAIAFcn = newCallback; PR_ExitMonitor(OCSP_Global.monitor); if (oldCallback) - *oldCallback = old; + *oldCallback = old; return SECSuccess; } @@ -300,18 +299,18 @@ ocsp_CacheKeyHashFunction(const void *key) PLHashNumber hash = 0; unsigned int i; unsigned char *walk; - + /* a very simple hash calculation for the initial coding phase */ - walk = (unsigned char*)cid->issuerNameHash.data; - for (i=0; i < cid->issuerNameHash.len; ++i, ++walk) { + walk = (unsigned char *)cid->issuerNameHash.data; + for (i = 0; i < cid->issuerNameHash.len; ++i, ++walk) { hash += *walk; } - walk = (unsigned char*)cid->issuerKeyHash.data; - for (i=0; i < cid->issuerKeyHash.len; ++i, ++walk) { + walk = (unsigned char *)cid->issuerKeyHash.data; + for (i = 0; i < cid->issuerKeyHash.len; ++i, ++walk) { hash += *walk; } - walk = (unsigned char*)cid->serialNumber.data; - for (i=0; i < cid->serialNumber.len; ++i, ++walk) { + walk = (unsigned char *)cid->serialNumber.data; + for (i = 0; i < cid->serialNumber.len; ++i, ++walk) { hash += *walk; } return hash; @@ -322,13 +321,13 @@ ocsp_CacheKeyCompareFunction(const void *v1, const void *v2) { CERTOCSPCertID *cid1 = (CERTOCSPCertID *)v1; CERTOCSPCertID *cid2 = (CERTOCSPCertID *)v2; - - return (SECEqual == SECITEM_CompareItem(&cid1->issuerNameHash, - &cid2->issuerNameHash) - && SECEqual == SECITEM_CompareItem(&cid1->issuerKeyHash, - &cid2->issuerKeyHash) - && SECEqual == SECITEM_CompareItem(&cid1->serialNumber, - &cid2->serialNumber)); + + return (SECEqual == SECITEM_CompareItem(&cid1->issuerNameHash, + &cid2->issuerNameHash) && + SECEqual == SECITEM_CompareItem(&cid1->issuerKeyHash, + &cid2->issuerKeyHash) && + SECEqual == SECITEM_CompareItem(&cid1->serialNumber, + &cid2->serialNumber)); } static SECStatus @@ -337,32 +336,33 @@ ocsp_CopyRevokedInfo(PLArenaPool *arena, ocspCertStatus *dest, { SECStatus rv = SECFailure; void *mark; - + mark = PORT_ArenaMark(arena); - - dest->certStatusInfo.revokedInfo = - (ocspRevokedInfo *) PORT_ArenaZAlloc(arena, sizeof(ocspRevokedInfo)); + + dest->certStatusInfo.revokedInfo = + (ocspRevokedInfo *)PORT_ArenaZAlloc(arena, sizeof(ocspRevokedInfo)); if (!dest->certStatusInfo.revokedInfo) { goto loser; } - - rv = SECITEM_CopyItem(arena, - &dest->certStatusInfo.revokedInfo->revocationTime, + + rv = SECITEM_CopyItem(arena, + &dest->certStatusInfo.revokedInfo->revocationTime, &src->revocationTime); if (rv != SECSuccess) { goto loser; } - + if (src->revocationReason) { - dest->certStatusInfo.revokedInfo->revocationReason = + dest->certStatusInfo.revokedInfo->revocationReason = SECITEM_ArenaDupItem(arena, src->revocationReason); if (!dest->certStatusInfo.revokedInfo->revocationReason) { goto loser; } - } else { + } + else { dest->certStatusInfo.revokedInfo->revocationReason = NULL; } - + PORT_ArenaUnmark(arena, mark); return SECSuccess; @@ -373,39 +373,39 @@ loser: static SECStatus ocsp_CopyCertStatus(PLArenaPool *arena, ocspCertStatus *dest, - ocspCertStatus*src) + ocspCertStatus *src) { SECStatus rv = SECFailure; dest->certStatusType = src->certStatusType; - + switch (src->certStatusType) { - case ocspCertStatus_good: - dest->certStatusInfo.goodInfo = - SECITEM_ArenaDupItem(arena, src->certStatusInfo.goodInfo); - if (dest->certStatusInfo.goodInfo != NULL) { - rv = SECSuccess; - } - break; - case ocspCertStatus_revoked: - rv = ocsp_CopyRevokedInfo(arena, dest, - src->certStatusInfo.revokedInfo); - break; - case ocspCertStatus_unknown: - dest->certStatusInfo.unknownInfo = - SECITEM_ArenaDupItem(arena, src->certStatusInfo.unknownInfo); - if (dest->certStatusInfo.unknownInfo != NULL) { - rv = SECSuccess; - } - break; - case ocspCertStatus_other: - default: - PORT_Assert(src->certStatusType == ocspCertStatus_other); - dest->certStatusInfo.otherInfo = - SECITEM_ArenaDupItem(arena, src->certStatusInfo.otherInfo); - if (dest->certStatusInfo.otherInfo != NULL) { - rv = SECSuccess; - } - break; + case ocspCertStatus_good: + dest->certStatusInfo.goodInfo = + SECITEM_ArenaDupItem(arena, src->certStatusInfo.goodInfo); + if (dest->certStatusInfo.goodInfo != NULL) { + rv = SECSuccess; + } + break; + case ocspCertStatus_revoked: + rv = ocsp_CopyRevokedInfo(arena, dest, + src->certStatusInfo.revokedInfo); + break; + case ocspCertStatus_unknown: + dest->certStatusInfo.unknownInfo = + SECITEM_ArenaDupItem(arena, src->certStatusInfo.unknownInfo); + if (dest->certStatusInfo.unknownInfo != NULL) { + rv = SECSuccess; + } + break; + case ocspCertStatus_other: + default: + PORT_Assert(src->certStatusType == ocspCertStatus_other); + dest->certStatusInfo.otherInfo = + SECITEM_ArenaDupItem(arena, src->certStatusInfo.otherInfo); + if (dest->certStatusInfo.otherInfo != NULL) { + rv = SECSuccess; + } + break; } return rv; } @@ -453,7 +453,7 @@ ocsp_RemoveCacheItemFromLinkedList(OCSPCacheData *cache, OCSPCacheItem *item) } PORT_Assert(cache->numberOfEntries > 1); - + if (item == cache->LRUitem) { PORT_Assert(item != cache->MRUitem); PORT_Assert(item->lessRecent == NULL); @@ -468,7 +468,8 @@ ocsp_RemoveCacheItemFromLinkedList(OCSPCacheData *cache, OCSPCacheItem *item) PORT_Assert(item->lessRecent->moreRecent == item); cache->MRUitem = item->lessRecent; cache->MRUitem->moreRecent = NULL; - } else { + } + else { /* remove an entry in the middle of the list */ PORT_Assert(item->moreRecent != NULL); PORT_Assert(item->lessRecent != NULL); @@ -487,7 +488,7 @@ ocsp_RemoveCacheItemFromLinkedList(OCSPCacheData *cache, OCSPCacheItem *item) static void ocsp_MakeCacheEntryMostRecent(OCSPCacheData *cache, OCSPCacheItem *new_most_recent) { - OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent THREADID %p\n", + OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent THREADID %p\n", PR_GetCurrentThread())); PR_EnterMonitor(OCSP_Global.monitor); if (cache->MRUitem == new_most_recent) { @@ -504,7 +505,7 @@ ocsp_MakeCacheEntryMostRecent(OCSPCacheData *cache, OCSPCacheItem *new_most_rece static PRBool ocsp_IsCacheDisabled(void) { - /* + /* * maxCacheEntries == 0 means unlimited cache entries * maxCacheEntries < 0 means cache is disabled */ @@ -524,12 +525,12 @@ ocsp_FindCacheEntry(OCSPCacheData *cache, CERTOCSPCertID *certID) PR_EnterMonitor(OCSP_Global.monitor); if (ocsp_IsCacheDisabled()) goto loser; - + found_ocsp_item = (OCSPCacheItem *)PL_HashTableLookup( - cache->entries, certID); + cache->entries, certID); if (!found_ocsp_item) goto loser; - + OCSP_TRACE(("OCSP ocsp_FindCacheEntry FOUND!\n")); ocsp_MakeCacheEntryMostRecent(cache, found_ocsp_item); @@ -556,7 +557,7 @@ ocsp_RemoveCacheItem(OCSPCacheData *cache, OCSPCacheItem *item) { /* The item we're removing could be either the least recently used item, * or it could be an item that couldn't get updated with newer status info - * because of an allocation failure, or it could get removed because we're + * because of an allocation failure, or it could get removed because we're * cleaning up. */ OCSP_TRACE(("OCSP ocsp_RemoveCacheItem, THREADID %p\n", PR_GetCurrentThread())); @@ -586,8 +587,8 @@ ocsp_CheckCacheSize(OCSPCacheData *cache) /* Cache is not disabled. Number of cache entries is limited. * The monitor ensures that maxCacheEntries remains positive. */ - while (cache->numberOfEntries > - (PRUint32)OCSP_Global.maxCacheEntries) { + while (cache->numberOfEntries > + (PRUint32)OCSP_Global.maxCacheEntries) { ocsp_RemoveCacheItem(cache, cache->LRUitem); } } @@ -600,7 +601,7 @@ CERT_ClearOCSPCache(void) OCSP_TRACE(("OCSP CERT_ClearOCSPCache\n")); PR_EnterMonitor(OCSP_Global.monitor); while (OCSP_Global.cache.numberOfEntries > 0) { - ocsp_RemoveCacheItem(&OCSP_Global.cache, + ocsp_RemoveCacheItem(&OCSP_Global.cache, OCSP_Global.cache.LRUitem); } PR_ExitMonitor(OCSP_Global.monitor); @@ -609,30 +610,30 @@ CERT_ClearOCSPCache(void) static SECStatus ocsp_CreateCacheItemAndConsumeCertID(OCSPCacheData *cache, - CERTOCSPCertID *certID, + CERTOCSPCertID *certID, OCSPCacheItem **pCacheItem) { PLArenaPool *arena; void *mark; PLHashEntry *new_hash_entry; OCSPCacheItem *item; - + PORT_Assert(pCacheItem != NULL); *pCacheItem = NULL; PR_EnterMonitor(OCSP_Global.monitor); arena = certID->poolp; mark = PORT_ArenaMark(arena); - + /* ZAlloc will init all Bools to False and all Pointers to NULL and all error codes to zero/good. */ - item = (OCSPCacheItem *)PORT_ArenaZAlloc(certID->poolp, + item = (OCSPCacheItem *)PORT_ArenaZAlloc(certID->poolp, sizeof(OCSPCacheItem)); if (!item) { - goto loser; + goto loser; } item->certID = certID; - new_hash_entry = PL_HashTableAdd(cache->entries, item->certID, + new_hash_entry = PL_HashTableAdd(cache->entries, item->certID, item); if (!new_hash_entry) { goto loser; @@ -644,7 +645,7 @@ ocsp_CreateCacheItemAndConsumeCertID(OCSPCacheData *cache, PR_ExitMonitor(OCSP_Global.monitor); return SECSuccess; - + loser: PORT_ArenaRelease(arena, mark); PR_ExitMonitor(OCSP_Global.monitor); @@ -666,7 +667,7 @@ ocsp_SetCacheItemResponse(OCSPCacheItem *item, if (item->certStatusArena == NULL) { return SECFailure; } - rv = ocsp_CopyCertStatus(item->certStatusArena, &item->certStatus, + rv = ocsp_CopyCertStatus(item->certStatusArena, &item->certStatus, response->certStatus); if (rv != SECSuccess) { PORT_FreeArena(item->certStatusArena, PR_FALSE); @@ -674,14 +675,15 @@ ocsp_SetCacheItemResponse(OCSPCacheItem *item, return rv; } item->missingResponseError = 0; - rv = DER_GeneralizedTimeToTime(&item->thisUpdate, + rv = DER_GeneralizedTimeToTime(&item->thisUpdate, &response->thisUpdate); item->haveThisUpdate = (rv == SECSuccess); if (response->nextUpdate) { - rv = DER_GeneralizedTimeToTime(&item->nextUpdate, + rv = DER_GeneralizedTimeToTime(&item->nextUpdate, response->nextUpdate); item->haveNextUpdate = (rv == SECSuccess); - } else { + } + else { item->haveNextUpdate = PR_FALSE; } } @@ -694,60 +696,61 @@ ocsp_FreshenCacheItemNextFetchAttemptTime(OCSPCacheItem *cacheItem) PRTime now; PRTime earliestAllowedNextFetchAttemptTime; PRTime latestTimeWhenResponseIsConsideredFresh; - + OCSP_TRACE(("OCSP ocsp_FreshenCacheItemNextFetchAttemptTime\n")); PR_EnterMonitor(OCSP_Global.monitor); - + now = PR_Now(); OCSP_TRACE_TIME("now:", now); - + if (cacheItem->haveThisUpdate) { OCSP_TRACE_TIME("thisUpdate:", cacheItem->thisUpdate); latestTimeWhenResponseIsConsideredFresh = cacheItem->thisUpdate + - OCSP_Global.maximumSecondsToNextFetchAttempt * - MICROSECONDS_PER_SECOND; - OCSP_TRACE_TIME("latestTimeWhenResponseIsConsideredFresh:", - latestTimeWhenResponseIsConsideredFresh); - } else { - latestTimeWhenResponseIsConsideredFresh = now + - OCSP_Global.minimumSecondsToNextFetchAttempt * - MICROSECONDS_PER_SECOND; - OCSP_TRACE_TIME("no thisUpdate, " - "latestTimeWhenResponseIsConsideredFresh:", + OCSP_Global.maximumSecondsToNextFetchAttempt * + MICROSECONDS_PER_SECOND; + OCSP_TRACE_TIME("latestTimeWhenResponseIsConsideredFresh:", latestTimeWhenResponseIsConsideredFresh); } - + else { + latestTimeWhenResponseIsConsideredFresh = now + + OCSP_Global.minimumSecondsToNextFetchAttempt * + MICROSECONDS_PER_SECOND; + OCSP_TRACE_TIME("no thisUpdate, " + "latestTimeWhenResponseIsConsideredFresh:", + latestTimeWhenResponseIsConsideredFresh); + } + if (cacheItem->haveNextUpdate) { OCSP_TRACE_TIME("have nextUpdate:", cacheItem->nextUpdate); } - + if (cacheItem->haveNextUpdate && cacheItem->nextUpdate < latestTimeWhenResponseIsConsideredFresh) { latestTimeWhenResponseIsConsideredFresh = cacheItem->nextUpdate; OCSP_TRACE_TIME("nextUpdate is smaller than latestFresh, setting " - "latestTimeWhenResponseIsConsideredFresh:", + "latestTimeWhenResponseIsConsideredFresh:", latestTimeWhenResponseIsConsideredFresh); } - + earliestAllowedNextFetchAttemptTime = now + - OCSP_Global.minimumSecondsToNextFetchAttempt * - MICROSECONDS_PER_SECOND; - OCSP_TRACE_TIME("earliestAllowedNextFetchAttemptTime:", + OCSP_Global.minimumSecondsToNextFetchAttempt * + MICROSECONDS_PER_SECOND; + OCSP_TRACE_TIME("earliestAllowedNextFetchAttemptTime:", earliestAllowedNextFetchAttemptTime); - - if (latestTimeWhenResponseIsConsideredFresh < + + if (latestTimeWhenResponseIsConsideredFresh < earliestAllowedNextFetchAttemptTime) { - latestTimeWhenResponseIsConsideredFresh = + latestTimeWhenResponseIsConsideredFresh = earliestAllowedNextFetchAttemptTime; - OCSP_TRACE_TIME("latest < earliest, setting latest to:", + OCSP_TRACE_TIME("latest < earliest, setting latest to:", latestTimeWhenResponseIsConsideredFresh); } - - cacheItem->nextFetchAttemptTime = + + cacheItem->nextFetchAttemptTime = latestTimeWhenResponseIsConsideredFresh; - OCSP_TRACE_TIME("nextFetchAttemptTime", - latestTimeWhenResponseIsConsideredFresh); + OCSP_TRACE_TIME("nextFetchAttemptTime", + latestTimeWhenResponseIsConsideredFresh); PR_ExitMonitor(OCSP_Global.monitor); } @@ -776,14 +779,14 @@ ocsp_IsCacheItemFresh(OCSPCacheItem *cacheItem) } /* - * Status in *certIDWasConsumed will always be correct, regardless of + * Status in *certIDWasConsumed will always be correct, regardless of * return value. * If the caller is unable to transfer ownership of certID, * then the caller must set certIDWasConsumed to NULL, * and this function will potentially duplicate the certID object. */ static SECStatus -ocsp_CreateOrUpdateCacheEntry(OCSPCacheData *cache, +ocsp_CreateOrUpdateCacheEntry(OCSPCacheData *cache, CERTOCSPCertID *certID, CERTOCSPSingleResponse *single, PRBool *certIDWasConsumed) @@ -791,13 +794,13 @@ ocsp_CreateOrUpdateCacheEntry(OCSPCacheData *cache, SECStatus rv; OCSPCacheItem *cacheItem; OCSP_TRACE(("OCSP ocsp_CreateOrUpdateCacheEntry\n")); - + if (certIDWasConsumed) *certIDWasConsumed = PR_FALSE; - + PR_EnterMonitor(OCSP_Global.monitor); PORT_Assert(OCSP_Global.maxCacheEntries >= 0); - + cacheItem = ocsp_FindCacheEntry(cache, certID); /* Don't replace an unknown or revoked entry with an error entry, even if @@ -817,7 +820,8 @@ ocsp_CreateOrUpdateCacheEntry(OCSPCacheData *cache, if (certIDWasConsumed) { myCertID = certID; *certIDWasConsumed = PR_TRUE; - } else { + } + else { myCertID = cert_DupOCSPCertID(certID); if (!myCertID) { PR_ExitMonitor(OCSP_Global.monitor); @@ -845,11 +849,13 @@ ocsp_CreateOrUpdateCacheEntry(OCSPCacheData *cache, PR_ExitMonitor(OCSP_Global.monitor); return rv; } - } else { + } + else { OCSP_TRACE(("Not caching response because the response is not " "newer than the cache")); } - } else { + } + else { cacheItem->missingResponseError = PORT_GetError(); if (cacheItem->certStatusArena) { PORT_FreeArena(cacheItem->certStatusArena, PR_FALSE); @@ -867,12 +873,12 @@ extern SECStatus CERT_SetOCSPFailureMode(SEC_OcspFailureMode ocspFailureMode) { switch (ocspFailureMode) { - case ocspMode_FailureIsVerificationFailure: - case ocspMode_FailureIsNotAVerificationFailure: - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + case ocspMode_FailureIsVerificationFailure: + case ocspMode_FailureIsNotAVerificationFailure: + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } PR_EnterMonitor(OCSP_Global.monitor); @@ -886,39 +892,41 @@ CERT_OCSPCacheSettings(PRInt32 maxCacheEntries, PRUint32 minimumSecondsToNextFetchAttempt, PRUint32 maximumSecondsToNextFetchAttempt) { - if (minimumSecondsToNextFetchAttempt > maximumSecondsToNextFetchAttempt - || maxCacheEntries < -1) { + if (minimumSecondsToNextFetchAttempt > maximumSecondsToNextFetchAttempt || + maxCacheEntries < -1) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - + PR_EnterMonitor(OCSP_Global.monitor); - + if (maxCacheEntries < 0) { OCSP_Global.maxCacheEntries = -1; /* disable cache */ - } else if (maxCacheEntries == 0) { + } + else if (maxCacheEntries == 0) { OCSP_Global.maxCacheEntries = 0; /* unlimited cache entries */ - } else { + } + else { OCSP_Global.maxCacheEntries = maxCacheEntries; } - - if (minimumSecondsToNextFetchAttempt < - OCSP_Global.minimumSecondsToNextFetchAttempt - || maximumSecondsToNextFetchAttempt < + + if (minimumSecondsToNextFetchAttempt < + OCSP_Global.minimumSecondsToNextFetchAttempt || + maximumSecondsToNextFetchAttempt < OCSP_Global.maximumSecondsToNextFetchAttempt) { /* - * Ensure our existing cache entries are not used longer than the + * Ensure our existing cache entries are not used longer than the * new settings allow, we're lazy and just clear the cache */ CERT_ClearOCSPCache(); } - - OCSP_Global.minimumSecondsToNextFetchAttempt = + + OCSP_Global.minimumSecondsToNextFetchAttempt = minimumSecondsToNextFetchAttempt; - OCSP_Global.maximumSecondsToNextFetchAttempt = + OCSP_Global.maximumSecondsToNextFetchAttempt = maximumSecondsToNextFetchAttempt; ocsp_CheckCacheSize(&OCSP_Global.cache); - + PR_ExitMonitor(OCSP_Global.monitor); return SECSuccess; } @@ -932,7 +940,8 @@ CERT_SetOCSPTimeout(PRUint32 seconds) } /* this function is called at NSS initialization time */ -SECStatus OCSP_InitGlobal(void) +SECStatus +OCSP_InitGlobal(void) { SECStatus rv = SECFailure; @@ -944,18 +953,19 @@ SECStatus OCSP_InitGlobal(void) PR_EnterMonitor(OCSP_Global.monitor); if (!OCSP_Global.cache.entries) { - OCSP_Global.cache.entries = - PL_NewHashTable(0, - ocsp_CacheKeyHashFunction, - ocsp_CacheKeyCompareFunction, - PL_CompareValues, - NULL, + OCSP_Global.cache.entries = + PL_NewHashTable(0, + ocsp_CacheKeyHashFunction, + ocsp_CacheKeyCompareFunction, + PL_CompareValues, + NULL, NULL); OCSP_Global.ocspFailureMode = ocspMode_FailureIsVerificationFailure; OCSP_Global.cache.numberOfEntries = 0; OCSP_Global.cache.MRUitem = NULL; OCSP_Global.cache.LRUitem = NULL; - } else { + } + else { /* * NSS might call this function twice while attempting to init. * But it's not allowed to call this again after any activity. @@ -969,7 +979,8 @@ SECStatus OCSP_InitGlobal(void) return rv; } -SECStatus OCSP_ShutdownGlobal(void) +SECStatus +OCSP_ShutdownGlobal(void) { if (!OCSP_Global.monitor) return SECSuccess; @@ -986,12 +997,12 @@ SECStatus OCSP_ShutdownGlobal(void) OCSP_Global.defaultHttpClientFcn = NULL; OCSP_Global.maxCacheEntries = DEFAULT_OCSP_CACHE_SIZE; - OCSP_Global.minimumSecondsToNextFetchAttempt = - DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT; + OCSP_Global.minimumSecondsToNextFetchAttempt = + DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT; OCSP_Global.maximumSecondsToNextFetchAttempt = - DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT; + DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT; OCSP_Global.ocspFailureMode = - ocspMode_FailureIsVerificationFailure; + ocspMode_FailureIsVerificationFailure; PR_ExitMonitor(OCSP_Global.monitor); PR_DestroyMonitor(OCSP_Global.monitor); @@ -1000,22 +1011,23 @@ SECStatus OCSP_ShutdownGlobal(void) } /* - * A return value of NULL means: + * A return value of NULL means: * The application did not register it's own HTTP client. */ -const SEC_HttpClientFcn *SEC_GetRegisteredHttpClient(void) +const SEC_HttpClientFcn * +SEC_GetRegisteredHttpClient(void) { const SEC_HttpClientFcn *retval; if (!OCSP_Global.monitor) { - PORT_SetError(SEC_ERROR_NOT_INITIALIZED); - return NULL; + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); + return NULL; } PR_EnterMonitor(OCSP_Global.monitor); retval = OCSP_Global.defaultHttpClientFcn; PR_ExitMonitor(OCSP_Global.monitor); - + return retval; } @@ -1057,7 +1069,6 @@ extern const SEC_ASN1Template ocsp_SingleRequestTemplate[]; extern const SEC_ASN1Template ocsp_SingleResponseTemplate[]; extern const SEC_ASN1Template ocsp_TBSRequestTemplate[]; - /* * Request-related templates... */ @@ -1069,14 +1080,14 @@ extern const SEC_ASN1Template ocsp_TBSRequestTemplate[]; */ static const SEC_ASN1Template ocsp_OCSPRequestTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTOCSPRequest) }, + 0, NULL, sizeof(CERTOCSPRequest) }, { SEC_ASN1_POINTER, - offsetof(CERTOCSPRequest, tbsRequest), - ocsp_TBSRequestTemplate }, + offsetof(CERTOCSPRequest, tbsRequest), + ocsp_TBSRequestTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(CERTOCSPRequest, optionalSignature), - ocsp_PointerToSignatureTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(CERTOCSPRequest, optionalSignature), + ocsp_PointerToSignatureTemplate }, { 0 } }; @@ -1095,22 +1106,22 @@ static const SEC_ASN1Template ocsp_OCSPRequestTemplate[] = { */ const SEC_ASN1Template ocsp_TBSRequestTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspTBSRequest) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(ocspTBSRequest, version), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, + 0, NULL, sizeof(ocspTBSRequest) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(ocspTBSRequest, version), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, - offsetof(ocspTBSRequest, derRequestorName), - SEC_ASN1_SUB(SEC_PointerToAnyTemplate) }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, + offsetof(ocspTBSRequest, derRequestorName), + SEC_ASN1_SUB(SEC_PointerToAnyTemplate) }, { SEC_ASN1_SEQUENCE_OF, - offsetof(ocspTBSRequest, requestList), - ocsp_SingleRequestTemplate }, + offsetof(ocspTBSRequest, requestList), + ocsp_SingleRequestTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 2, - offsetof(ocspTBSRequest, requestExtensions), - CERT_SequenceOfCertExtensionTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 2, + offsetof(ocspTBSRequest, requestExtensions), + CERT_SequenceOfCertExtensionTemplate }, { 0 } }; @@ -1122,16 +1133,16 @@ const SEC_ASN1Template ocsp_TBSRequestTemplate[] = { */ static const SEC_ASN1Template ocsp_SignatureTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspSignature) }, + 0, NULL, sizeof(ocspSignature) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(ocspSignature, signatureAlgorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(ocspSignature, signatureAlgorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_BIT_STRING, - offsetof(ocspSignature, signature) }, + offsetof(ocspSignature, signature) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(ocspSignature, derCerts), - SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(ocspSignature, derCerts), + SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) }, { 0 } }; @@ -1157,19 +1168,18 @@ const SEC_ASN1Template ocsp_PointerToSignatureTemplate[] = { * is the only way it will compile. */ const SEC_ASN1Template ocsp_SingleRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspSingleRequest) }, + { SEC_ASN1_SEQUENCE, + 0, NULL, sizeof(ocspSingleRequest) }, { SEC_ASN1_POINTER, - offsetof(ocspSingleRequest, reqCert), - ocsp_CertIDTemplate }, + offsetof(ocspSingleRequest, reqCert), + ocsp_CertIDTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(ocspSingleRequest, singleRequestExtensions), - CERT_SequenceOfCertExtensionTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(ocspSingleRequest, singleRequestExtensions), + CERT_SequenceOfCertExtensionTemplate }, { 0 } }; - /* * This data structure and template (CertID) is used by both OCSP * requests and responses. It is the only one that is shared. @@ -1187,21 +1197,20 @@ const SEC_ASN1Template ocsp_SingleRequestTemplate[] = { * is the only way it will compile. */ const SEC_ASN1Template ocsp_CertIDTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTOCSPCertID) }, + { SEC_ASN1_SEQUENCE, + 0, NULL, sizeof(CERTOCSPCertID) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTOCSPCertID, hashAlgorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(CERTOCSPCertID, hashAlgorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_OCTET_STRING, - offsetof(CERTOCSPCertID, issuerNameHash) }, + offsetof(CERTOCSPCertID, issuerNameHash) }, { SEC_ASN1_OCTET_STRING, - offsetof(CERTOCSPCertID, issuerKeyHash) }, - { SEC_ASN1_INTEGER, - offsetof(CERTOCSPCertID, serialNumber) }, + offsetof(CERTOCSPCertID, issuerKeyHash) }, + { SEC_ASN1_INTEGER, + offsetof(CERTOCSPCertID, serialNumber) }, { 0 } }; - /* * Response-related templates... */ @@ -1212,14 +1221,14 @@ const SEC_ASN1Template ocsp_CertIDTemplate[] = { * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL } */ const SEC_ASN1Template ocsp_OCSPResponseTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTOCSPResponse) }, - { SEC_ASN1_ENUMERATED, - offsetof(CERTOCSPResponse, responseStatus) }, + { SEC_ASN1_SEQUENCE, + 0, NULL, sizeof(CERTOCSPResponse) }, + { SEC_ASN1_ENUMERATED, + offsetof(CERTOCSPResponse, responseStatus) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(CERTOCSPResponse, responseBytes), - ocsp_PointerToResponseBytesTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(CERTOCSPResponse, responseBytes), + ocsp_PointerToResponseBytesTemplate }, { 0 } }; @@ -1230,11 +1239,11 @@ const SEC_ASN1Template ocsp_OCSPResponseTemplate[] = { */ const SEC_ASN1Template ocsp_ResponseBytesTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspResponseBytes) }, + 0, NULL, sizeof(ocspResponseBytes) }, { SEC_ASN1_OBJECT_ID, - offsetof(ocspResponseBytes, responseType) }, + offsetof(ocspResponseBytes, responseType) }, { SEC_ASN1_OCTET_STRING, - offsetof(ocspResponseBytes, response) }, + offsetof(ocspResponseBytes, response) }, { 0 } }; @@ -1259,21 +1268,21 @@ const SEC_ASN1Template ocsp_PointerToResponseBytesTemplate[] = { */ static const SEC_ASN1Template ocsp_BasicOCSPResponseTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspBasicOCSPResponse) }, + 0, NULL, sizeof(ocspBasicOCSPResponse) }, { SEC_ASN1_ANY | SEC_ASN1_SAVE, - offsetof(ocspBasicOCSPResponse, tbsResponseDataDER) }, + offsetof(ocspBasicOCSPResponse, tbsResponseDataDER) }, { SEC_ASN1_POINTER, - offsetof(ocspBasicOCSPResponse, tbsResponseData), - ocsp_ResponseDataTemplate }, + offsetof(ocspBasicOCSPResponse, tbsResponseData), + ocsp_ResponseDataTemplate }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(ocspBasicOCSPResponse, responseSignature.signatureAlgorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(ocspBasicOCSPResponse, responseSignature.signatureAlgorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_BIT_STRING, - offsetof(ocspBasicOCSPResponse, responseSignature.signature) }, + offsetof(ocspBasicOCSPResponse, responseSignature.signature) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(ocspBasicOCSPResponse, responseSignature.derCerts), - SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(ocspBasicOCSPResponse, responseSignature.derCerts), + SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) }, { 0 } }; @@ -1291,22 +1300,22 @@ static const SEC_ASN1Template ocsp_BasicOCSPResponseTemplate[] = { */ const SEC_ASN1Template ocsp_ResponseDataTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspResponseData) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(ocspResponseData, version), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, + 0, NULL, sizeof(ocspResponseData) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(ocspResponseData, version), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, { SEC_ASN1_ANY, - offsetof(ocspResponseData, derResponderID) }, + offsetof(ocspResponseData, derResponderID) }, { SEC_ASN1_GENERALIZED_TIME, - offsetof(ocspResponseData, producedAt) }, + offsetof(ocspResponseData, producedAt) }, { SEC_ASN1_SEQUENCE_OF, - offsetof(ocspResponseData, responses), - ocsp_SingleResponseTemplate }, + offsetof(ocspResponseData, responses), + ocsp_SingleResponseTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(ocspResponseData, responseExtensions), - CERT_SequenceOfCertExtensionTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(ocspResponseData, responseExtensions), + CERT_SequenceOfCertExtensionTemplate }, { 0 } }; @@ -1327,24 +1336,25 @@ const SEC_ASN1Template ocsp_ResponseDataTemplate[] = { */ const SEC_ASN1Template ocsp_ResponderIDByNameTemplate[] = { { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(ocspResponderID, responderIDValue.name), - CERT_NameTemplate } + offsetof(ocspResponderID, responderIDValue.name), + CERT_NameTemplate } }; const SEC_ASN1Template ocsp_ResponderIDByKeyTemplate[] = { { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 2, - offsetof(ocspResponderID, responderIDValue.keyHash), - SEC_ASN1_SUB(SEC_OctetStringTemplate) } + SEC_ASN1_XTRN | 2, + offsetof(ocspResponderID, responderIDValue.keyHash), + SEC_ASN1_SUB(SEC_OctetStringTemplate) } }; static const SEC_ASN1Template ocsp_ResponderIDOtherTemplate[] = { { SEC_ASN1_ANY, - offsetof(ocspResponderID, responderIDValue.other) } + offsetof(ocspResponderID, responderIDValue.other) } }; /* Decode choice container, but leave x509 name object encoded */ static const SEC_ASN1Template ocsp_ResponderIDDerNameTemplate[] = { { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 1, 0, SEC_ASN1_SUB(SEC_AnyTemplate) } + SEC_ASN1_XTRN | 1, + 0, SEC_ASN1_SUB(SEC_AnyTemplate) } }; /* @@ -1361,22 +1371,22 @@ static const SEC_ASN1Template ocsp_ResponderIDDerNameTemplate[] = { */ const SEC_ASN1Template ocsp_SingleResponseTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTOCSPSingleResponse) }, + 0, NULL, sizeof(CERTOCSPSingleResponse) }, { SEC_ASN1_POINTER, - offsetof(CERTOCSPSingleResponse, certID), - ocsp_CertIDTemplate }, + offsetof(CERTOCSPSingleResponse, certID), + ocsp_CertIDTemplate }, { SEC_ASN1_ANY, - offsetof(CERTOCSPSingleResponse, derCertStatus) }, + offsetof(CERTOCSPSingleResponse, derCertStatus) }, { SEC_ASN1_GENERALIZED_TIME, - offsetof(CERTOCSPSingleResponse, thisUpdate) }, + offsetof(CERTOCSPSingleResponse, thisUpdate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(CERTOCSPSingleResponse, nextUpdate), - SEC_ASN1_SUB(SEC_PointerToGeneralizedTimeTemplate) }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(CERTOCSPSingleResponse, nextUpdate), + SEC_ASN1_SUB(SEC_PointerToGeneralizedTimeTemplate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(CERTOCSPSingleResponse, singleExtensions), - CERT_SequenceOfCertExtensionTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(CERTOCSPSingleResponse, singleExtensions), + CERT_SequenceOfCertExtensionTemplate }, { 0 } }; @@ -1395,23 +1405,23 @@ const SEC_ASN1Template ocsp_SingleResponseTemplate[] = { */ static const SEC_ASN1Template ocsp_CertStatusGoodTemplate[] = { { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(ocspCertStatus, certStatusInfo.goodInfo), - SEC_ASN1_SUB(SEC_NullTemplate) } + offsetof(ocspCertStatus, certStatusInfo.goodInfo), + SEC_ASN1_SUB(SEC_NullTemplate) } }; static const SEC_ASN1Template ocsp_CertStatusRevokedTemplate[] = { - { SEC_ASN1_POINTER | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(ocspCertStatus, certStatusInfo.revokedInfo), - ocsp_RevokedInfoTemplate } + { SEC_ASN1_POINTER | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(ocspCertStatus, certStatusInfo.revokedInfo), + ocsp_RevokedInfoTemplate } }; static const SEC_ASN1Template ocsp_CertStatusUnknownTemplate[] = { { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, - offsetof(ocspCertStatus, certStatusInfo.unknownInfo), - SEC_ASN1_SUB(SEC_NullTemplate) } + offsetof(ocspCertStatus, certStatusInfo.unknownInfo), + SEC_ASN1_SUB(SEC_NullTemplate) } }; static const SEC_ASN1Template ocsp_CertStatusOtherTemplate[] = { { SEC_ASN1_POINTER | SEC_ASN1_XTRN, - offsetof(ocspCertStatus, certStatusInfo.otherInfo), - SEC_ASN1_SUB(SEC_AnyTemplate) } + offsetof(ocspCertStatus, certStatusInfo.otherInfo), + SEC_ASN1_SUB(SEC_AnyTemplate) } }; /* @@ -1425,18 +1435,17 @@ static const SEC_ASN1Template ocsp_CertStatusOtherTemplate[] = { */ const SEC_ASN1Template ocsp_RevokedInfoTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspRevokedInfo) }, + 0, NULL, sizeof(ocspRevokedInfo) }, { SEC_ASN1_GENERALIZED_TIME, - offsetof(ocspRevokedInfo, revocationTime) }, + offsetof(ocspRevokedInfo, revocationTime) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 0, - offsetof(ocspRevokedInfo, revocationReason), - SEC_ASN1_SUB(SEC_PointerToEnumeratedTemplate) }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_XTRN | 0, + offsetof(ocspRevokedInfo, revocationReason), + SEC_ASN1_SUB(SEC_PointerToEnumeratedTemplate) }, { 0 } }; - /* * OCSP-specific extension templates: */ @@ -1448,25 +1457,24 @@ const SEC_ASN1Template ocsp_RevokedInfoTemplate[] = { */ static const SEC_ASN1Template ocsp_ServiceLocatorTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspServiceLocator) }, + 0, NULL, sizeof(ocspServiceLocator) }, { SEC_ASN1_POINTER, - offsetof(ocspServiceLocator, issuer), - CERT_NameTemplate }, + offsetof(ocspServiceLocator, issuer), + CERT_NameTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, - offsetof(ocspServiceLocator, locator) }, + offsetof(ocspServiceLocator, locator) }, { 0 } }; - /* * REQUEST SUPPORT FUNCTIONS (encode/create/decode/destroy): */ -/* +/* * FUNCTION: CERT_EncodeOCSPRequest * DER encodes an OCSP Request, possibly adding a signature as well. * XXX Signing is not yet supported, however; see comments in code. - * INPUTS: + * INPUTS: * PLArenaPool *arena * The return value is allocated from here. * If a NULL is passed in, allocation is done from the heap instead. @@ -1482,7 +1490,7 @@ static const SEC_ASN1Template ocsp_ServiceLocatorTemplate[] = { */ SECItem * CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request, - void *pwArg) + void *pwArg) { SECStatus rv; @@ -1491,10 +1499,10 @@ CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request, PORT_Assert(request->tbsRequest); if (request->tbsRequest->extensionHandle != NULL) { - rv = CERT_FinishExtensions(request->tbsRequest->extensionHandle); - request->tbsRequest->extensionHandle = NULL; - if (rv != SECSuccess) - return NULL; + rv = CERT_FinishExtensions(request->tbsRequest->extensionHandle); + request->tbsRequest->extensionHandle = NULL; + if (rv != SECSuccess) + return NULL; } /* @@ -1510,7 +1518,6 @@ CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request, return SEC_ASN1EncodeItem(arena, NULL, request, ocsp_OCSPRequestTemplate); } - /* * FUNCTION: CERT_DecodeOCSPRequest * Decode a DER encoded OCSP Request. @@ -1533,27 +1540,27 @@ CERT_DecodeOCSPRequest(const SECItem *src) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - goto loser; + goto loser; } - dest = (CERTOCSPRequest *) PORT_ArenaZAlloc(arena, - sizeof(CERTOCSPRequest)); + dest = (CERTOCSPRequest *)PORT_ArenaZAlloc(arena, + sizeof(CERTOCSPRequest)); if (dest == NULL) { - goto loser; + goto loser; } dest->arena = arena; /* 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, &newSrc, src); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = SEC_QuickDERDecodeItem(arena, dest, ocsp_OCSPRequestTemplate, &newSrc); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_BAD_DER) - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); - goto loser; + if (PORT_GetError() == SEC_ERROR_BAD_DER) + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); + goto loser; } /* @@ -1561,24 +1568,24 @@ CERT_DecodeOCSPRequest(const SECItem *src) * of doing this copying of the arena pointer. */ for (i = 0; dest->tbsRequest->requestList[i] != NULL; i++) { - dest->tbsRequest->requestList[i]->arena = arena; + dest->tbsRequest->requestList[i]->arena = arena; } return dest; loser: if (arena != NULL) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return NULL; } SECStatus -CERT_DestroyOCSPCertID(CERTOCSPCertID* certID) +CERT_DestroyOCSPCertID(CERTOCSPCertID *certID) { if (certID && certID->poolp) { - PORT_FreeArena(certID->poolp, PR_FALSE); - return SECSuccess; + PORT_FreeArena(certID->poolp, PR_FALSE); + return SECSuccess; } PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; @@ -1593,7 +1600,7 @@ CERT_DestroyOCSPCertID(CERTOCSPCertID* certID) */ SECItem * -ocsp_DigestValue(PLArenaPool *arena, SECOidTag digestAlg, +ocsp_DigestValue(PLArenaPool *arena, SECOidTag digestAlg, SECItem *fill, const SECItem *src) { const SECHashObject *digestObject; @@ -1601,27 +1608,28 @@ ocsp_DigestValue(PLArenaPool *arena, SECOidTag digestAlg, void *mark = NULL; void *digestBuff = NULL; - if ( arena != NULL ) { + if (arena != NULL) { mark = PORT_ArenaMark(arena); } digestObject = HASH_GetHashObjectByOidTag(digestAlg); - if ( digestObject == NULL ) { + if (digestObject == NULL) { goto loser; } if (fill == NULL || fill->data == NULL) { - result = SECITEM_AllocItem(arena, fill, digestObject->length); - if ( result == NULL ) { - goto loser; - } - digestBuff = result->data; - } else { - if (fill->len < digestObject->length) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto loser; - } - digestBuff = fill->data; + result = SECITEM_AllocItem(arena, fill, digestObject->length); + if (result == NULL) { + goto loser; + } + digestBuff = result->data; + } + else { + if (fill->len < digestObject->length) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + digestBuff = fill->data; } if (PK11_HashBuf(digestAlg, digestBuff, @@ -1629,7 +1637,7 @@ ocsp_DigestValue(PLArenaPool *arena, SECOidTag digestAlg, goto loser; } - if ( arena != NULL ) { + if (arena != NULL) { PORT_ArenaUnmark(arena, mark); } @@ -1641,12 +1649,13 @@ ocsp_DigestValue(PLArenaPool *arena, SECOidTag digestAlg, loser: if (arena != NULL) { PORT_ArenaRelease(arena, mark); - } else { + } + else { if (result != NULL) { SECITEM_FreeItem(result, (fill == NULL) ? PR_TRUE : PR_FALSE); } } - return(NULL); + return (NULL); } /* @@ -1713,18 +1722,18 @@ ocsp_CreateCertID(PLArenaPool *arena, CERTCertificate *cert, PRTime time) certID = PORT_ArenaZNew(arena, CERTOCSPCertID); if (certID == NULL) { - goto loser; + goto loser; } rv = SECOID_SetAlgorithmID(arena, &certID->hashAlgorithm, SEC_OID_SHA1, - NULL); + NULL); if (rv != SECSuccess) { - goto loser; + goto loser; } issuerCert = CERT_FindCertIssuer(cert, time, certUsageAnyCA); if (issuerCert == NULL) { - goto loser; + goto loser; } if (CERT_GetSubjectNameDigest(arena, issuerCert, SEC_OID_SHA1, @@ -1745,29 +1754,28 @@ ocsp_CreateCertID(PLArenaPool *arena, CERTCertificate *cert, PRTime time) } if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_SHA1, - &certID->issuerKeyHash) == NULL) { - goto loser; + &certID->issuerKeyHash) == NULL) { + goto loser; } certID->issuerSHA1KeyHash.data = certID->issuerKeyHash.data; certID->issuerSHA1KeyHash.len = certID->issuerKeyHash.len; /* cache the other two hash algorithms as well */ if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_MD5, - &certID->issuerMD5KeyHash) == NULL) { - goto loser; + &certID->issuerMD5KeyHash) == NULL) { + goto loser; } if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_MD2, - &certID->issuerMD2KeyHash) == NULL) { - goto loser; + &certID->issuerMD2KeyHash) == NULL) { + goto loser; } - /* now we are done with issuerCert */ CERT_DestroyCertificate(issuerCert); issuerCert = NULL; rv = SECITEM_CopyItem(arena, &certID->serialNumber, &cert->serialNumber); if (rv != SECSuccess) { - goto loser; + goto loser; } PORT_ArenaUnmark(arena, mark); @@ -1775,25 +1783,25 @@ ocsp_CreateCertID(PLArenaPool *arena, CERTCertificate *cert, PRTime time) loser: if (issuerCert != NULL) { - CERT_DestroyCertificate(issuerCert); + CERT_DestroyCertificate(issuerCert); } PORT_ArenaRelease(arena, mark); return NULL; } -CERTOCSPCertID* +CERTOCSPCertID * CERT_CreateOCSPCertID(CERTCertificate *cert, PRTime time) { PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); CERTOCSPCertID *certID; PORT_Assert(arena != NULL); if (!arena) - return NULL; - + return NULL; + certID = ocsp_CreateCertID(arena, cert, time); if (!certID) { - PORT_FreeArena(arena, PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } certID->poolp = arena; return certID; @@ -1818,11 +1826,11 @@ cert_DupOCSPCertID(const CERTOCSPCertID *src) if (!dest) goto loser; -#define DUPHELP(element) \ - if (src->element.data && \ - SECITEM_CopyItem(arena, &dest->element, &src->element) \ - != SECSuccess) { \ - goto loser; \ +#define DUPHELP(element) \ + if (src->element.data && \ + SECITEM_CopyItem(arena, &dest->element, &src->element) != \ + SECSuccess) { \ + goto loser; \ } DUPHELP(hashAlgorithm.algorithm) @@ -1850,12 +1858,13 @@ loser: /* * Callback to set Extensions in request object */ -void SetSingleReqExts(void *object, CERTCertExtension **exts) +void +SetSingleReqExts(void *object, CERTCertExtension **exts) { - ocspSingleRequest *singleRequest = - (ocspSingleRequest *)object; + ocspSingleRequest *singleRequest = + (ocspSingleRequest *)object; - singleRequest->singleRequestExtensions = exts; + singleRequest->singleRequestExtensions = exts; } /* @@ -1866,7 +1875,7 @@ void SetSingleReqExts(void *object, CERTCertExtension **exts) */ static SECStatus ocsp_AddServiceLocatorExtension(ocspSingleRequest *singleRequest, - CERTCertificate *cert) + CERTCertificate *cert) { ocspServiceLocator *serviceLocator = NULL; void *extensionHandle = NULL; @@ -1874,7 +1883,7 @@ ocsp_AddServiceLocatorExtension(ocspSingleRequest *singleRequest, serviceLocator = PORT_ZNew(ocspServiceLocator); if (serviceLocator == NULL) - goto loser; + goto loser; /* * Normally it would be a bad idea to do a direct reference like @@ -1886,10 +1895,10 @@ ocsp_AddServiceLocatorExtension(ocspSingleRequest *singleRequest, serviceLocator->issuer = &cert->issuer; rv = CERT_FindCertExtension(cert, SEC_OID_X509_AUTH_INFO_ACCESS, - &serviceLocator->locator); + &serviceLocator->locator); if (rv != SECSuccess) { - if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) - goto loser; + if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND) + goto loser; } /* prepare for following loser gotos */ @@ -1897,33 +1906,33 @@ ocsp_AddServiceLocatorExtension(ocspSingleRequest *singleRequest, PORT_SetError(0); extensionHandle = cert_StartExtensions(singleRequest, - singleRequest->arena, SetSingleReqExts); + singleRequest->arena, SetSingleReqExts); if (extensionHandle == NULL) - goto loser; + goto loser; rv = CERT_EncodeAndAddExtension(extensionHandle, - SEC_OID_PKIX_OCSP_SERVICE_LOCATOR, - serviceLocator, PR_FALSE, - ocsp_ServiceLocatorTemplate); + SEC_OID_PKIX_OCSP_SERVICE_LOCATOR, + serviceLocator, PR_FALSE, + ocsp_ServiceLocatorTemplate); loser: if (extensionHandle != NULL) { - /* + /* * Either way we have to finish out the extension context (so it gets * freed). But careful not to override any already-set bad status. */ - SECStatus tmprv = CERT_FinishExtensions(extensionHandle); - if (rv == SECSuccess) - rv = tmprv; + SECStatus tmprv = CERT_FinishExtensions(extensionHandle); + if (rv == SECSuccess) + rv = tmprv; } /* * Finally, free the serviceLocator structure itself and we are done. */ if (serviceLocator != NULL) { - if (serviceLocator->locator.data != NULL) - SECITEM_FreeItem(&serviceLocator->locator, PR_FALSE); - PORT_Free(serviceLocator); + if (serviceLocator->locator.data != NULL) + SECITEM_FreeItem(&serviceLocator->locator, PR_FALSE); + PORT_Free(serviceLocator); } return rv; @@ -1949,18 +1958,18 @@ ocsp_CreateSingleRequestList(PLArenaPool *arena, CERTCertList *certList, CERTCertListNode *node = NULL; int i, count; void *mark = PORT_ArenaMark(arena); - + node = CERT_LIST_HEAD(certList); for (count = 0; !CERT_LIST_END(node, certList); count++) { node = CERT_LIST_NEXT(node); } if (count == 0) - goto loser; + goto loser; requestList = PORT_ArenaNewArray(arena, ocspSingleRequest *, count + 1); if (requestList == NULL) - goto loser; + goto loser; node = CERT_LIST_HEAD(certList); for (i = 0; !CERT_LIST_END(node, certList); i++) { @@ -1998,7 +2007,7 @@ loser: static ocspSingleRequest ** ocsp_CreateRequestFromCert(PLArenaPool *arena, - CERTOCSPCertID *certID, + CERTOCSPCertID *certID, CERTCertificate *singleCert, PRTime time, PRBool includeLocator) @@ -2016,7 +2025,7 @@ ocsp_CreateRequestFromCert(PLArenaPool *arena, goto loser; requestList[0]->arena = arena; /* certID will live longer than the request */ - requestList[0]->reqCert = certID; + requestList[0]->reqCert = certID; if (includeLocator == PR_TRUE) { SECStatus rv; @@ -2067,8 +2076,8 @@ loser: } CERTOCSPRequest * -cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, - CERTCertificate *singleCert, +cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, + CERTCertificate *singleCert, PRTime time, PRBool addServiceLocator, CERTCertificate *signerCert) @@ -2091,8 +2100,8 @@ cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, * Version 1 is the default, so we need not fill in a version number. * Now create the list of single requests, one for each cert. */ - request->tbsRequest->requestList = - ocsp_CreateRequestFromCert(request->arena, + request->tbsRequest->requestList = + ocsp_CreateRequestFromCert(request->arena, certID, singleCert, time, @@ -2106,7 +2115,7 @@ cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, /* * FUNCTION: CERT_CreateOCSPRequest - * Creates a CERTOCSPRequest, requesting the status of the certs in + * Creates a CERTOCSPRequest, requesting the status of the certs in * the given list. * INPUTS: * CERTCertList *certList @@ -2118,7 +2127,7 @@ cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, * to this routine), who knows about where the request(s) are being * sent and whether there are any trusted responders in place. * PRTime time - * Indicates the time for which the certificate status is to be + * Indicates the time for which the certificate status is to be * determined -- this may be used in the search for the cert's issuer * but has no effect on the request itself. * PRBool addServiceLocator @@ -2137,8 +2146,8 @@ cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, */ CERTOCSPRequest * CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, - PRBool addServiceLocator, - CERTCertificate *signerCert) + PRBool addServiceLocator, + CERTCertificate *signerCert) { CERTOCSPRequest *request = NULL; @@ -2147,7 +2156,7 @@ CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, return NULL; } /* - * XXX When we are prepared to put signing of requests back in, + * XXX When we are prepared to put signing of requests back in, * we will need to allocate a signature * structure for the request, fill in the "derCerts" field in it, * save the signerCert there, as well as fill in the "requestorName" @@ -2163,8 +2172,8 @@ CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, /* * Now create the list of single requests, one for each cert. */ - request->tbsRequest->requestList = - ocsp_CreateSingleRequestList(request->arena, + request->tbsRequest->requestList = + ocsp_CreateSingleRequestList(request->arena, certList, time, addServiceLocator); @@ -2192,16 +2201,17 @@ CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, * All errors are internal or low-level problems (e.g. no memory). */ -void SetRequestExts(void *object, CERTCertExtension **exts) +void +SetRequestExts(void *object, CERTCertExtension **exts) { - CERTOCSPRequest *request = (CERTOCSPRequest *)object; + CERTOCSPRequest *request = (CERTOCSPRequest *)object; - request->tbsRequest->requestExtensions = exts; + request->tbsRequest->requestExtensions = exts; } SECStatus CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request, - SECOidTag responseType0, ...) + SECOidTag responseType0, ...) { void *extHandle; va_list ap; @@ -2213,60 +2223,59 @@ CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request, extHandle = request->tbsRequest->extensionHandle; if (extHandle == NULL) { - extHandle = cert_StartExtensions(request, request->arena, SetRequestExts); - if (extHandle == NULL) - goto loser; + extHandle = cert_StartExtensions(request, request->arena, SetRequestExts); + if (extHandle == NULL) + goto loser; } /* Count number of OIDS going into the extension value. */ count = 1; if (responseType0 != SEC_OID_PKIX_OCSP_BASIC_RESPONSE) { - va_start(ap, responseType0); - do { - count++; - responseType = va_arg(ap, SECOidTag); - } while (responseType != SEC_OID_PKIX_OCSP_BASIC_RESPONSE); - va_end(ap); + va_start(ap, responseType0); + do { + count++; + responseType = va_arg(ap, SECOidTag); + } while (responseType != SEC_OID_PKIX_OCSP_BASIC_RESPONSE); + va_end(ap); } acceptableResponses = PORT_NewArray(SECItem *, count + 1); if (acceptableResponses == NULL) - goto loser; + goto loser; i = 0; responseOid = SECOID_FindOIDByTag(responseType0); acceptableResponses[i++] = &(responseOid->oid); if (count > 1) { - va_start(ap, responseType0); - for ( ; i < count; i++) { - responseType = va_arg(ap, SECOidTag); - responseOid = SECOID_FindOIDByTag(responseType); - acceptableResponses[i] = &(responseOid->oid); - } - va_end(ap); + va_start(ap, responseType0); + for (; i < count; i++) { + responseType = va_arg(ap, SECOidTag); + responseOid = SECOID_FindOIDByTag(responseType); + acceptableResponses[i] = &(responseOid->oid); + } + va_end(ap); } acceptableResponses[i] = NULL; rv = CERT_EncodeAndAddExtension(extHandle, SEC_OID_PKIX_OCSP_RESPONSE, - &acceptableResponses, PR_FALSE, - SEC_ASN1_GET(SEC_SequenceOfObjectIDTemplate)); + &acceptableResponses, PR_FALSE, + SEC_ASN1_GET(SEC_SequenceOfObjectIDTemplate)); if (rv != SECSuccess) - goto loser; + goto loser; PORT_Free(acceptableResponses); if (request->tbsRequest->extensionHandle == NULL) - request->tbsRequest->extensionHandle = extHandle; + request->tbsRequest->extensionHandle = extHandle; return SECSuccess; loser: if (acceptableResponses != NULL) - PORT_Free(acceptableResponses); + PORT_Free(acceptableResponses); if (extHandle != NULL) - (void) CERT_FinishExtensions(extHandle); + (void)CERT_FinishExtensions(extHandle); return rv; } - /* * FUNCTION: CERT_DestroyOCSPRequest * Frees an OCSP Request structure. @@ -2280,20 +2289,20 @@ void CERT_DestroyOCSPRequest(CERTOCSPRequest *request) { if (request == NULL) - return; + return; if (request->tbsRequest != NULL) { - if (request->tbsRequest->requestorName != NULL) - CERT_DestroyGeneralNameList(request->tbsRequest->requestorName); - if (request->tbsRequest->extensionHandle != NULL) - (void) CERT_FinishExtensions(request->tbsRequest->extensionHandle); + if (request->tbsRequest->requestorName != NULL) + CERT_DestroyGeneralNameList(request->tbsRequest->requestorName); + if (request->tbsRequest->extensionHandle != NULL) + (void)CERT_FinishExtensions(request->tbsRequest->extensionHandle); } if (request->optionalSignature != NULL) { - if (request->optionalSignature->cert != NULL) - CERT_DestroyCertificate(request->optionalSignature->cert); + if (request->optionalSignature->cert != NULL) + CERT_DestroyCertificate(request->optionalSignature->cert); - /* + /* * XXX Need to free derCerts? Or do they come out of arena? * (Currently we never fill in derCerts, which is why the * answer is not obvious. Once we do, add any necessary code @@ -2308,10 +2317,9 @@ CERT_DestroyOCSPRequest(CERTOCSPRequest *request) */ PORT_Assert(request->arena != NULL); if (request->arena != NULL) - PORT_FreeArena(request->arena, PR_FALSE); + PORT_FreeArena(request->arena, PR_FALSE); } - /* * RESPONSE SUPPORT FUNCTIONS (encode/create/decode/destroy): */ @@ -2326,17 +2334,17 @@ ocsp_ResponderIDTemplateByType(CERTOCSPResponderIDType responderIDType) const SEC_ASN1Template *responderIDTemplate; switch (responderIDType) { - case ocspResponderID_byName: - responderIDTemplate = ocsp_ResponderIDByNameTemplate; - break; - case ocspResponderID_byKey: - responderIDTemplate = ocsp_ResponderIDByKeyTemplate; - break; - case ocspResponderID_other: - default: - PORT_Assert(responderIDType == ocspResponderID_other); - responderIDTemplate = ocsp_ResponderIDOtherTemplate; - break; + case ocspResponderID_byName: + responderIDTemplate = ocsp_ResponderIDByNameTemplate; + break; + case ocspResponderID_byKey: + responderIDTemplate = ocsp_ResponderIDByKeyTemplate; + break; + case ocspResponderID_other: + default: + PORT_Assert(responderIDType == ocspResponderID_other); + responderIDTemplate = ocsp_ResponderIDOtherTemplate; + break; } return responderIDTemplate; @@ -2352,20 +2360,20 @@ ocsp_CertStatusTemplateByType(ocspCertStatusType certStatusType) const SEC_ASN1Template *certStatusTemplate; switch (certStatusType) { - case ocspCertStatus_good: - certStatusTemplate = ocsp_CertStatusGoodTemplate; - break; - case ocspCertStatus_revoked: - certStatusTemplate = ocsp_CertStatusRevokedTemplate; - break; - case ocspCertStatus_unknown: - certStatusTemplate = ocsp_CertStatusUnknownTemplate; - break; - case ocspCertStatus_other: - default: - PORT_Assert(certStatusType == ocspCertStatus_other); - certStatusTemplate = ocsp_CertStatusOtherTemplate; - break; + case ocspCertStatus_good: + certStatusTemplate = ocsp_CertStatusGoodTemplate; + break; + case ocspCertStatus_revoked: + certStatusTemplate = ocsp_CertStatusRevokedTemplate; + break; + case ocspCertStatus_unknown: + certStatusTemplate = ocsp_CertStatusUnknownTemplate; + break; + case ocspCertStatus_other: + default: + PORT_Assert(certStatusType == ocspCertStatus_other); + certStatusTemplate = ocsp_CertStatusOtherTemplate; + break; } return certStatusTemplate; @@ -2381,18 +2389,18 @@ ocsp_CertStatusTypeByTag(int derTag) ocspCertStatusType certStatusType; switch (derTag) { - case 0: - certStatusType = ocspCertStatus_good; - break; - case 1: - certStatusType = ocspCertStatus_revoked; - break; - case 2: - certStatusType = ocspCertStatus_unknown; - break; - default: - certStatusType = ocspCertStatus_other; - break; + case 0: + certStatusType = ocspCertStatus_good; + break; + case 1: + certStatusType = ocspCertStatus_revoked; + break; + case 2: + certStatusType = ocspCertStatus_unknown; + break; + default: + certStatusType = ocspCertStatus_other; + break; } return certStatusType; @@ -2407,7 +2415,7 @@ ocsp_CertStatusTypeByTag(int derTag) */ static SECStatus ocsp_FinishDecodingSingleResponses(PLArenaPool *reqArena, - CERTOCSPSingleResponse **responses) + CERTOCSPSingleResponse **responses) { ocspCertStatus *certStatus; ocspCertStatusType certStatusType; @@ -2421,39 +2429,39 @@ ocsp_FinishDecodingSingleResponses(PLArenaPool *reqArena, return SECFailure; } - if (responses == NULL) /* nothing to do */ - return SECSuccess; + if (responses == NULL) /* nothing to do */ + return SECSuccess; for (i = 0; responses[i] != NULL; i++) { - SECItem* newStatus; - /* + SECItem *newStatus; + /* * The following assert points out internal errors (problems in * the template definitions or in the ASN.1 decoder itself, etc.). */ - PORT_Assert(responses[i]->derCertStatus.data != NULL); + PORT_Assert(responses[i]->derCertStatus.data != NULL); - derTag = responses[i]->derCertStatus.data[0] & SEC_ASN1_TAGNUM_MASK; - certStatusType = ocsp_CertStatusTypeByTag(derTag); - certStatusTemplate = ocsp_CertStatusTemplateByType(certStatusType); + derTag = responses[i]->derCertStatus.data[0] & SEC_ASN1_TAGNUM_MASK; + certStatusType = ocsp_CertStatusTypeByTag(derTag); + certStatusTemplate = ocsp_CertStatusTemplateByType(certStatusType); - certStatus = PORT_ArenaZAlloc(reqArena, sizeof(ocspCertStatus)); - if (certStatus == NULL) { - goto loser; - } + certStatus = PORT_ArenaZAlloc(reqArena, sizeof(ocspCertStatus)); + if (certStatus == NULL) { + goto loser; + } newStatus = SECITEM_ArenaDupItem(reqArena, &responses[i]->derCertStatus); if (!newStatus) { goto loser; } - rv = SEC_QuickDERDecodeItem(reqArena, certStatus, certStatusTemplate, - newStatus); - if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_BAD_DER) - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); - goto loser; - } + rv = SEC_QuickDERDecodeItem(reqArena, certStatus, certStatusTemplate, + newStatus); + if (rv != SECSuccess) { + if (PORT_GetError() == SEC_ERROR_BAD_DER) + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); + goto loser; + } - certStatus->certStatusType = certStatusType; - responses[i]->certStatus = certStatus; + certStatus->certStatusType = certStatusType; + responses[i]->certStatus = certStatus; } return SECSuccess; @@ -2472,15 +2480,15 @@ ocsp_ResponderIDTypeByTag(int derTag) CERTOCSPResponderIDType responderIDType; switch (derTag) { - case 1: - responderIDType = ocspResponderID_byName; - break; - case 2: - responderIDType = ocspResponderID_byKey; - break; - default: - responderIDType = ocspResponderID_other; - break; + case 1: + responderIDType = ocspResponderID_byName; + break; + case 2: + responderIDType = ocspResponderID_byKey; + break; + default: + responderIDType = ocspResponderID_other; + break; } return responderIDType; @@ -2506,22 +2514,22 @@ ocsp_DecodeBasicOCSPResponse(PLArenaPool *arena, SECItem *src) basicResponse = PORT_ArenaZAlloc(arena, sizeof(ocspBasicOCSPResponse)); if (basicResponse == NULL) { - goto loser; + goto loser; } /* 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, &newsrc, src); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = SEC_QuickDERDecodeItem(arena, basicResponse, - ocsp_BasicOCSPResponseTemplate, &newsrc); + ocsp_BasicOCSPResponseTemplate, &newsrc); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_BAD_DER) - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); - goto loser; + if (PORT_GetError() == SEC_ERROR_BAD_DER) + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); + goto loser; } responseData = basicResponse->tbsResponseData; @@ -2543,15 +2551,15 @@ ocsp_DecodeBasicOCSPResponse(PLArenaPool *arena, SECItem *src) responderID = PORT_ArenaZAlloc(arena, sizeof(ocspResponderID)); if (responderID == NULL) { - goto loser; + goto loser; } rv = SEC_QuickDERDecodeItem(arena, responderID, responderIDTemplate, - &responseData->derResponderID); + &responseData->derResponderID); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_BAD_DER) - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); - goto loser; + if (PORT_GetError() == SEC_ERROR_BAD_DER) + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); + goto loser; } responderID->responderIDType = responderIDType; @@ -2563,7 +2571,7 @@ ocsp_DecodeBasicOCSPResponse(PLArenaPool *arena, SECItem *src) */ rv = ocsp_FinishDecodingSingleResponses(arena, responseData->responses); if (rv != SECSuccess) { - goto loser; + goto loser; } PORT_ArenaUnmark(arena, mark); @@ -2574,7 +2582,6 @@ loser: return NULL; } - /* * Decode the responseBytes based on the responseType found in "rbytes", * leaving the resulting translated/decoded information in there as well. @@ -2583,38 +2590,35 @@ static SECStatus ocsp_DecodeResponseBytes(PLArenaPool *arena, ocspResponseBytes *rbytes) { if (rbytes == NULL) { - PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE); - return SECFailure; + PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE); + return SECFailure; } rbytes->responseTypeTag = SECOID_FindOIDTag(&rbytes->responseType); switch (rbytes->responseTypeTag) { - case SEC_OID_PKIX_OCSP_BASIC_RESPONSE: - { - ocspBasicOCSPResponse *basicResponse; + case SEC_OID_PKIX_OCSP_BASIC_RESPONSE: { + ocspBasicOCSPResponse *basicResponse; - basicResponse = ocsp_DecodeBasicOCSPResponse(arena, - &rbytes->response); - if (basicResponse == NULL) - return SECFailure; + basicResponse = ocsp_DecodeBasicOCSPResponse(arena, + &rbytes->response); + if (basicResponse == NULL) + return SECFailure; - rbytes->decodedResponse.basic = basicResponse; - } - break; + rbytes->decodedResponse.basic = basicResponse; + } break; - /* + /* * Add new/future response types here. */ - default: - PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE); - return SECFailure; + default: + PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE); + return SECFailure; } return SECSuccess; } - /* * FUNCTION: CERT_DecodeOCSPResponse * Decode a DER encoded OCSP Response. @@ -2639,37 +2643,37 @@ CERT_DecodeOCSPResponse(const SECItem *src) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - goto loser; + goto loser; } - response = (CERTOCSPResponse *) PORT_ArenaZAlloc(arena, - sizeof(CERTOCSPResponse)); + response = (CERTOCSPResponse *)PORT_ArenaZAlloc(arena, + sizeof(CERTOCSPResponse)); if (response == NULL) { - goto loser; + goto loser; } response->arena = arena; /* 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, &newSrc, src); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = SEC_QuickDERDecodeItem(arena, response, ocsp_OCSPResponseTemplate, &newSrc); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_BAD_DER) - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); - goto loser; + if (PORT_GetError() == SEC_ERROR_BAD_DER) + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); + goto loser; } - sv = (ocspResponseStatus) DER_GetInteger(&response->responseStatus); + sv = (ocspResponseStatus)DER_GetInteger(&response->responseStatus); response->statusValue = sv; if (sv != ocspResponse_successful) { - /* + /* * If the response status is anything but successful, then we * are all done with decoding; the status is all there is. */ - return response; + return response; } /* @@ -2678,14 +2682,14 @@ CERT_DecodeOCSPResponse(const SECItem *src) */ rv = ocsp_DecodeResponseBytes(arena, response->responseBytes); if (rv != SECSuccess) { - goto loser; + goto loser; } return response; loser: if (arena != NULL) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return NULL; } @@ -2711,7 +2715,7 @@ loser: * * FUNCTION: ocsp_GetResponseData * Returns ocspResponseData structure and a pointer to tbs response - * data DER from a valid ocsp response. + * data DER from a valid ocsp response. * INPUTS: * CERTOCSPResponse *response * structure of a valid ocsp response @@ -2729,8 +2733,8 @@ ocsp_GetResponseData(CERTOCSPResponse *response, SECItem **tbsResponseDataDER) PORT_Assert(response->responseBytes != NULL); - PORT_Assert(response->responseBytes->responseTypeTag - == SEC_OID_PKIX_OCSP_BASIC_RESPONSE); + PORT_Assert(response->responseBytes->responseTypeTag == + SEC_OID_PKIX_OCSP_BASIC_RESPONSE); basic = response->responseBytes->decodedResponse.basic; PORT_Assert(basic != NULL); @@ -2761,8 +2765,8 @@ ocsp_GetResponseSignature(CERTOCSPResponse *response) if (NULL == response->responseBytes) { return NULL; } - if (response->responseBytes->responseTypeTag - != SEC_OID_PKIX_OCSP_BASIC_RESPONSE) { + if (response->responseBytes->responseTypeTag != + SEC_OID_PKIX_OCSP_BASIC_RESPONSE) { return NULL; } basic = response->responseBytes->decodedResponse.basic; @@ -2771,7 +2775,6 @@ ocsp_GetResponseSignature(CERTOCSPResponse *response) return &(basic->responseSignature); } - /* * FUNCTION: CERT_DestroyOCSPResponse * Frees an OCSP Response structure. @@ -2785,28 +2788,26 @@ void CERT_DestroyOCSPResponse(CERTOCSPResponse *response) { if (response != NULL) { - ocspSignature *signature = ocsp_GetResponseSignature(response); - if (signature && signature->cert != NULL) - CERT_DestroyCertificate(signature->cert); + ocspSignature *signature = ocsp_GetResponseSignature(response); + if (signature && signature->cert != NULL) + CERT_DestroyCertificate(signature->cert); - /* + /* * We should actually never have a response without an arena, * but check just in case. (If there isn't one, there is not * much we can do about it...) */ - PORT_Assert(response->arena != NULL); - if (response->arena != NULL) { - PORT_FreeArena(response->arena, PR_FALSE); - } + PORT_Assert(response->arena != NULL); + if (response->arena != NULL) { + PORT_FreeArena(response->arena, PR_FALSE); + } } } - /* * OVERALL OCSP CLIENT SUPPORT (make and send a request, verify a response): */ - /* * Pick apart a URL, saving the important things in the passed-in pointers. * @@ -2822,7 +2823,7 @@ CERT_DestroyOCSPResponse(CERTOCSPResponse *response) static SECStatus ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) { - unsigned short port = 80; /* default, in case not in url */ + unsigned short port = 80; /* default, in case not in url */ char *hostname = NULL; char *path = NULL; const char *save; @@ -2830,25 +2831,25 @@ ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) int len; if (url == NULL) - goto loser; + goto loser; /* * Skip beginning whitespace. */ c = *url; while ((c == ' ' || c == '\t') && c != '\0') { - url++; - c = *url; + url++; + c = *url; } if (c == '\0') - goto loser; + goto loser; /* * Confirm, then skip, protocol. (Since we only know how to do http, * that is all we will accept). */ if (PORT_Strncasecmp(url, "http://", 7) != 0) - goto loser; + goto loser; url += 7; /* @@ -2866,13 +2867,13 @@ ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) save = url; c = *url; while (c != '/' && c != ':' && c != '\0' && c != ' ' && c != '\t') { - url++; - c = *url; + url++; + c = *url; } len = url - save; hostname = PORT_Alloc(len + 1); if (hostname == NULL) - goto loser; + goto loser; PORT_Memcpy(hostname, save, len); hostname[len] = '\0'; @@ -2881,15 +2882,15 @@ ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) * If so, we need to parse it (as a number) and skip it. */ if (c == ':') { - url++; - port = (unsigned short) PORT_Atoi(url); - c = *url; - while (c != '/' && c != '\0' && c != ' ' && c != '\t') { - if (c < '0' || c > '9') - goto loser; - url++; - c = *url; - } + url++; + port = (unsigned short)PORT_Atoi(url); + c = *url; + while (c != '/' && c != '\0' && c != ' ' && c != '\t') { + if (c < '0' || c > '9') + goto loser; + url++; + c = *url; + } } /* @@ -2897,21 +2898,22 @@ ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) * if nothing else -- but if there is not we provide one. */ if (c == '/') { - save = url; - while (c != '\0' && c != ' ' && c != '\t') { - url++; - c = *url; - } - len = url - save; - path = PORT_Alloc(len + 1); - if (path == NULL) - goto loser; - PORT_Memcpy(path, save, len); - path[len] = '\0'; - } else { - path = PORT_Strdup("/"); - if (path == NULL) - goto loser; + save = url; + while (c != '\0' && c != ' ' && c != '\t') { + url++; + c = *url; + } + len = url - save; + path = PORT_Alloc(len + 1); + if (path == NULL) + goto loser; + PORT_Memcpy(path, save, len); + path[len] = '\0'; + } + else { + path = PORT_Strdup("/"); + if (path == NULL) + goto loser; } *pHostname = hostname; @@ -2921,7 +2923,7 @@ ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) loser: if (hostname != NULL) - PORT_Free(hostname); + PORT_Free(hostname); PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); return SECFailure; } @@ -2940,7 +2942,7 @@ ocsp_ConnectToHost(const char *host, PRUint16 port) sock = PR_NewTCPSocket(); if (sock == NULL) - goto loser; + goto loser; /* XXX Some day need a way to set (and get?) the following value */ timeout = PR_SecondsToInterval(30); @@ -2954,42 +2956,43 @@ ocsp_ConnectToHost(const char *host, PRUint16 port) * valid numerical IP address from a hostname. */ if (PR_StringToNetAddr(host, &addr) != PR_SUCCESS) { - PRIntn hostIndex; - PRHostEnt hostEntry; + PRIntn hostIndex; + PRHostEnt hostEntry; - netdbbuf = PORT_Alloc(PR_NETDB_BUF_SIZE); - if (netdbbuf == NULL) - goto loser; + netdbbuf = PORT_Alloc(PR_NETDB_BUF_SIZE); + if (netdbbuf == NULL) + goto loser; - if (PR_GetHostByName(host, netdbbuf, PR_NETDB_BUF_SIZE, - &hostEntry) != PR_SUCCESS) - goto loser; + if (PR_GetHostByName(host, netdbbuf, PR_NETDB_BUF_SIZE, + &hostEntry) != PR_SUCCESS) + goto loser; - hostIndex = 0; - do { - hostIndex = PR_EnumerateHostEnt(hostIndex, &hostEntry, port, &addr); - if (hostIndex <= 0) - goto loser; - } while (PR_Connect(sock, &addr, timeout) != PR_SUCCESS); + hostIndex = 0; + do { + hostIndex = PR_EnumerateHostEnt(hostIndex, &hostEntry, port, &addr); + if (hostIndex <= 0) + goto loser; + } while (PR_Connect(sock, &addr, timeout) != PR_SUCCESS); - PORT_Free(netdbbuf); - } else { - /* + PORT_Free(netdbbuf); + } + else { + /* * First put the port into the address, then connect. */ - if (PR_InitializeNetAddr(PR_IpAddrNull, port, &addr) != PR_SUCCESS) - goto loser; - if (PR_Connect(sock, &addr, timeout) != PR_SUCCESS) - goto loser; + if (PR_InitializeNetAddr(PR_IpAddrNull, port, &addr) != PR_SUCCESS) + goto loser; + if (PR_Connect(sock, &addr, timeout) != PR_SUCCESS) + goto loser; } return sock; loser: if (sock != NULL) - PR_Close(sock); + PR_Close(sock); if (netdbbuf != NULL) - PORT_Free(netdbbuf); + PORT_Free(netdbbuf); return NULL; } @@ -3024,14 +3027,14 @@ ocsp_SendEncodedRequest(const char *location, const SECItem *encodedRequest) */ rv = ocsp_ParseURL(location, &hostname, &port, &path); if (rv != SECSuccess) - goto loser; + goto loser; PORT_Assert(hostname != NULL); PORT_Assert(path != NULL); sock = ocsp_ConnectToHost(hostname, port); if (sock == NULL) - goto loser; + goto loser; portstr[0] = '\0'; if (port != 80) { @@ -3039,38 +3042,38 @@ ocsp_SendEncodedRequest(const char *location, const SECItem *encodedRequest) } if (!encodedRequest) { - header = PR_smprintf("GET %s HTTP/1.0\r\n" - "Host: %s%s\r\n\r\n", - path, hostname, portstr); - if (header == NULL) - goto loser; + header = PR_smprintf("GET %s HTTP/1.0\r\n" + "Host: %s%s\r\n\r\n", + path, hostname, portstr); + if (header == NULL) + goto loser; - /* - * The NSPR documentation promises that if it can, it will write the full - * amount; this will not return a partial value expecting us to loop. - */ - if (PR_Write(sock, header, (PRInt32) PORT_Strlen(header)) < 0) - goto loser; + /* + * The NSPR documentation promises that if it can, it will write the full + * amount; this will not return a partial value expecting us to loop. + */ + if (PR_Write(sock, header, (PRInt32)PORT_Strlen(header)) < 0) + goto loser; } else { - header = PR_smprintf("POST %s HTTP/1.0\r\n" - "Host: %s%s\r\n" - "Content-Type: application/ocsp-request\r\n" - "Content-Length: %u\r\n\r\n", - path, hostname, portstr, encodedRequest->len); - if (header == NULL) - goto loser; + header = PR_smprintf("POST %s HTTP/1.0\r\n" + "Host: %s%s\r\n" + "Content-Type: application/ocsp-request\r\n" + "Content-Length: %u\r\n\r\n", + path, hostname, portstr, encodedRequest->len); + if (header == NULL) + goto loser; - /* - * The NSPR documentation promises that if it can, it will write the full - * amount; this will not return a partial value expecting us to loop. - */ - if (PR_Write(sock, header, (PRInt32) PORT_Strlen(header)) < 0) - goto loser; + /* + * The NSPR documentation promises that if it can, it will write the full + * amount; this will not return a partial value expecting us to loop. + */ + if (PR_Write(sock, header, (PRInt32)PORT_Strlen(header)) < 0) + goto loser; - if (PR_Write(sock, encodedRequest->data, - (PRInt32) encodedRequest->len) < 0) - goto loser; + if (PR_Write(sock, encodedRequest->data, + (PRInt32)encodedRequest->len) < 0) + goto loser; } returnSock = sock; @@ -3078,13 +3081,13 @@ ocsp_SendEncodedRequest(const char *location, const SECItem *encodedRequest) loser: if (header != NULL) - PORT_Free(header); + PORT_Free(header); if (sock != NULL) - PR_Close(sock); + PR_Close(sock); if (path != NULL) - PORT_Free(path); + PORT_Free(path); if (hostname != NULL) - PORT_Free(hostname); + PORT_Free(hostname); return returnSock; } @@ -3099,22 +3102,17 @@ ocsp_read(PRFileDesc *fd, char *buf, int toread, PRIntervalTime timeout) { int total = 0; - while (total < toread) - { + while (total < toread) { PRInt32 got; - got = PR_Recv(fd, buf + total, (PRInt32) (toread - total), 0, timeout); - if (got < 0) - { - if (0 == total) - { + got = PR_Recv(fd, buf + total, (PRInt32)(toread - total), 0, timeout); + if (got < 0) { + if (0 == total) { total = -1; /* report the error if we didn't read anything yet */ } break; } - else - if (got == 0) - { /* EOS */ + else if (got == 0) { /* EOS */ break; } @@ -3126,14 +3124,13 @@ ocsp_read(PRFileDesc *fd, char *buf, int toread, PRIntervalTime timeout) #define OCSP_BUFSIZE 1024 -#define AbortHttpDecode(error) \ -{ \ - if (inBuffer) \ +#define AbortHttpDecode(error) \ + { \ + if (inBuffer) \ PORT_Free(inBuffer); \ - PORT_SetError(error); \ - return NULL; \ -} - + PORT_SetError(error); \ + return NULL; \ + } /* * Reads on the given socket and returns an encoded response when received. @@ -3148,92 +3145,82 @@ ocsp_GetEncodedResponse(PLArenaPool *arena, PRFileDesc *sock) { /* first read HTTP status line and headers */ - char* inBuffer = NULL; + char *inBuffer = NULL; PRInt32 offset = 0; PRInt32 inBufsize = 0; - const PRInt32 bufSizeIncrement = OCSP_BUFSIZE; /* 1 KB at a time */ - const PRInt32 maxBufSize = 8 * bufSizeIncrement ; /* 8 KB max */ - const char* CRLF = "\r\n"; + const PRInt32 bufSizeIncrement = OCSP_BUFSIZE; /* 1 KB at a time */ + const PRInt32 maxBufSize = 8 * bufSizeIncrement; /* 8 KB max */ + const char *CRLF = "\r\n"; const PRInt32 CRLFlen = strlen(CRLF); - const char* headerEndMark = "\r\n\r\n"; + const char *headerEndMark = "\r\n\r\n"; const PRInt32 markLen = strlen(headerEndMark); const PRIntervalTime ocsptimeout = PR_SecondsToInterval(30); /* hardcoded to 30s for now */ - char* headerEnd = NULL; + char *headerEnd = NULL; PRBool EOS = PR_FALSE; - const char* httpprotocol = "HTTP/"; + const char *httpprotocol = "HTTP/"; const PRInt32 httplen = strlen(httpprotocol); - const char* httpcode = NULL; - const char* contenttype = NULL; + const char *httpcode = NULL; + const char *contenttype = NULL; PRInt32 contentlength = 0; PRInt32 bytesRead = 0; - char* statusLineEnd = NULL; - char* space = NULL; - char* nextHeader = NULL; - SECItem* result = NULL; + char *statusLineEnd = NULL; + char *space = NULL; + char *nextHeader = NULL; + SECItem *result = NULL; /* read up to at least the end of the HTTP headers */ - do - { + do { inBufsize += bufSizeIncrement; - inBuffer = PORT_Realloc(inBuffer, inBufsize+1); - if (NULL == inBuffer) - { + inBuffer = PORT_Realloc(inBuffer, inBufsize + 1); + if (NULL == inBuffer) { AbortHttpDecode(SEC_ERROR_NO_MEMORY); } bytesRead = ocsp_read(sock, inBuffer + offset, bufSizeIncrement, - ocsptimeout); - if (bytesRead > 0) - { - PRInt32 searchOffset = (offset - markLen) >0 ? offset-markLen : 0; + ocsptimeout); + if (bytesRead > 0) { + PRInt32 searchOffset = (offset - markLen) > 0 ? offset - markLen : 0; offset += bytesRead; *(inBuffer + offset) = '\0'; /* NULL termination */ - headerEnd = strstr((const char*)inBuffer + searchOffset, headerEndMark); - if (bytesRead < bufSizeIncrement) - { + headerEnd = strstr((const char *)inBuffer + searchOffset, headerEndMark); + if (bytesRead < bufSizeIncrement) { /* we read less data than requested, therefore we are at EOS or there was a read error */ EOS = PR_TRUE; } } - else - { + else { /* recv error or EOS */ EOS = PR_TRUE; } - } while ( (!headerEnd) && (PR_FALSE == EOS) && - (inBufsize < maxBufSize) ); + } while ((!headerEnd) && (PR_FALSE == EOS) && + (inBufsize < maxBufSize)); - if (!headerEnd) - { + if (!headerEnd) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } /* parse the HTTP status line */ - statusLineEnd = strstr((const char*)inBuffer, CRLF); - if (!statusLineEnd) - { + statusLineEnd = strstr((const char *)inBuffer, CRLF); + if (!statusLineEnd) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } *statusLineEnd = '\0'; /* check for HTTP/ response */ - space = strchr((const char*)inBuffer, ' '); - if (!space || PORT_Strncasecmp((const char*)inBuffer, httpprotocol, httplen) != 0 ) - { + space = strchr((const char *)inBuffer, ' '); + if (!space || PORT_Strncasecmp((const char *)inBuffer, httpprotocol, httplen) != 0) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } /* check the HTTP status code of 200 */ - httpcode = space +1; + httpcode = space + 1; space = strchr(httpcode, ' '); - if (!space) - { + if (!space) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } *space = 0; - if (0 != strcmp(httpcode, "200")) - { + if (0 != strcmp(httpcode, "200")) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } @@ -3243,14 +3230,12 @@ ocsp_GetEncodedResponse(PLArenaPool *arena, PRFileDesc *sock) nextHeader = statusLineEnd + CRLFlen; *headerEnd = '\0'; /* terminate */ - do - { - char* thisHeaderEnd = NULL; - char* value = NULL; - char* colon = strchr(nextHeader, ':'); - - if (!colon) - { + do { + char *thisHeaderEnd = NULL; + char *value = NULL; + char *colon = strchr(nextHeader, ':'); + + if (!colon) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } @@ -3263,90 +3248,74 @@ ocsp_GetEncodedResponse(PLArenaPool *arena, PRFileDesc *sock) and should not be an issue, but it could become one in the future */ - if (*value != ' ') - { + if (*value != ' ') { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } value++; - thisHeaderEnd = strstr(value, CRLF); - if (thisHeaderEnd ) - { - *thisHeaderEnd = '\0'; + thisHeaderEnd = strstr(value, CRLF); + if (thisHeaderEnd) { + *thisHeaderEnd = '\0'; } - if (0 == PORT_Strcasecmp(nextHeader, "content-type")) - { + if (0 == PORT_Strcasecmp(nextHeader, "content-type")) { contenttype = value; } - else - if (0 == PORT_Strcasecmp(nextHeader, "content-length")) - { + else if (0 == PORT_Strcasecmp(nextHeader, "content-length")) { contentlength = atoi(value); } - if (thisHeaderEnd ) - { + if (thisHeaderEnd) { nextHeader = thisHeaderEnd + CRLFlen; } - else - { + else { nextHeader = NULL; } - } while (nextHeader && (nextHeader < (headerEnd + CRLFlen) ) ); + } while (nextHeader && (nextHeader < (headerEnd + CRLFlen))); /* check content-type */ if (!contenttype || - (0 != PORT_Strcasecmp(contenttype, "application/ocsp-response")) ) - { + (0 != PORT_Strcasecmp(contenttype, "application/ocsp-response"))) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } /* read the body of the OCSP response */ - offset = offset - (PRInt32) (headerEnd - (const char*)inBuffer) - markLen; - if (offset) - { + offset = offset - (PRInt32)(headerEnd - (const char *)inBuffer) - markLen; + if (offset) { /* move all data to the beginning of the buffer */ PORT_Memmove(inBuffer, headerEnd + markLen, offset); } /* resize buffer to only what's needed to hold the current response */ - inBufsize = (1 + (offset-1) / bufSizeIncrement ) * bufSizeIncrement ; + inBufsize = (1 + (offset - 1) / bufSizeIncrement) * bufSizeIncrement; - while ( (PR_FALSE == EOS) && - ( (contentlength == 0) || (offset < contentlength) ) && - (inBufsize < maxBufSize) - ) - { + while ((PR_FALSE == EOS) && + ((contentlength == 0) || (offset < contentlength)) && + (inBufsize < maxBufSize)) { /* we still need to receive more body data */ inBufsize += bufSizeIncrement; - inBuffer = PORT_Realloc(inBuffer, inBufsize+1); - if (NULL == inBuffer) - { + inBuffer = PORT_Realloc(inBuffer, inBufsize + 1); + if (NULL == inBuffer) { AbortHttpDecode(SEC_ERROR_NO_MEMORY); } bytesRead = ocsp_read(sock, inBuffer + offset, bufSizeIncrement, ocsptimeout); - if (bytesRead > 0) - { + if (bytesRead > 0) { offset += bytesRead; - if (bytesRead < bufSizeIncrement) - { + if (bytesRead < bufSizeIncrement) { /* we read less data than requested, therefore we are at EOS or there was a read error */ EOS = PR_TRUE; } } - else - { + else { /* recv error or EOS */ EOS = PR_TRUE; } } - if (0 == offset) - { + if (0 == offset) { AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE); } @@ -3354,14 +3323,13 @@ ocsp_GetEncodedResponse(PLArenaPool *arena, PRFileDesc *sock) * Now allocate the item to hold the data. */ result = SECITEM_AllocItem(arena, NULL, offset); - if (NULL == result) - { + if (NULL == result) { AbortHttpDecode(SEC_ERROR_NO_MEMORY); } /* * And copy the data left in the buffer. - */ + */ PORT_Memcpy(result->data, inBuffer, offset); /* and free the temporary buffer */ @@ -3378,7 +3346,7 @@ CERT_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) /* * Limit the size of http responses we are willing to accept. */ -#define MAX_WANTED_OCSP_RESPONSE_LEN 64*1024 +#define MAX_WANTED_OCSP_RESPONSE_LEN 64 * 1024 /* if (encodedRequest == NULL) * then location MUST already include the full request, @@ -3388,9 +3356,9 @@ CERT_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath) * then the request will be sent with POST */ static SECItem * -fetchOcspHttpClientV1(PLArenaPool *arena, - const SEC_HttpClientFcnV1 *hcv1, - const char *location, +fetchOcspHttpClientV1(PLArenaPool *arena, + const SEC_HttpClientFcnV1 *hcv1, + const char *location, const SECItem *encodedRequest) { char *hostname = NULL; @@ -3407,13 +3375,13 @@ fetchOcspHttpClientV1(PLArenaPool *arena, PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); goto loser; } - + PORT_Assert(hostname != NULL); PORT_Assert(path != NULL); if ((*hcv1->createSessionFcn)( - hostname, - port, + hostname, + port, &pServerSession) != SECSuccess) { PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); goto loser; @@ -3439,8 +3407,8 @@ fetchOcspHttpClientV1(PLArenaPool *arena, if (encodedRequest && (*hcv1->setPostDataFcn)( - pRequestSession, - (char*)encodedRequest->data, + pRequestSession, + (char *)encodedRequest->data, encodedRequest->len, "application/ocsp-request") != SECSuccess) { PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); @@ -3453,7 +3421,7 @@ fetchOcspHttpClientV1(PLArenaPool *arena, OCSP_TRACE(("OCSP trySendAndReceive %s\n", location)); if ((*hcv1->trySendAndReceiveFcn)( - pRequestSession, + pRequestSession, NULL, &myHttpResponseCode, NULL, @@ -3481,15 +3449,15 @@ fetchOcspHttpClientV1(PLArenaPool *arena, PORT_Memcpy(encodedResponse->data, myHttpResponseData, myHttpResponseDataLen); loser: - if (pRequestSession != NULL) + if (pRequestSession != NULL) (*hcv1->freeFcn)(pRequestSession); if (pServerSession != NULL) (*hcv1->freeSessionFcn)(pServerSession); if (path != NULL) - PORT_Free(path); + PORT_Free(path); if (hostname != NULL) - PORT_Free(hostname); - + PORT_Free(hostname); + return encodedResponse; } @@ -3518,7 +3486,7 @@ loser: * Additionals methods for http or other protocols might be added * in the future. * PRTime time - * Indicates the time for which the certificate status is to be + * Indicates the time for which the certificate status is to be * determined -- this may be used in the search for the cert's issuer * but has no other bearing on the operation. * PRBool addServiceLocator @@ -3546,10 +3514,10 @@ loser: */ SECItem * CERT_GetEncodedOCSPResponseByMethod(PLArenaPool *arena, CERTCertList *certList, - const char *location, const char *method, - PRTime time, PRBool addServiceLocator, - CERTCertificate *signerCert, void *pwArg, - CERTOCSPRequest **pRequest) + const char *location, const char *method, + PRTime time, PRBool addServiceLocator, + CERTCertificate *signerCert, void *pwArg, + CERTOCSPRequest **pRequest) { CERTOCSPRequest *request; request = CERT_CreateOCSPRequest(certList, time, addServiceLocator, @@ -3571,25 +3539,25 @@ CERT_GetEncodedOCSPResponseByMethod(PLArenaPool *arena, CERTCertList *certList, */ SECItem * CERT_GetEncodedOCSPResponse(PLArenaPool *arena, CERTCertList *certList, - const char *location, PRTime time, - PRBool addServiceLocator, - CERTCertificate *signerCert, void *pwArg, - CERTOCSPRequest **pRequest) + const char *location, PRTime time, + PRBool addServiceLocator, + CERTCertificate *signerCert, void *pwArg, + CERTOCSPRequest **pRequest) { return CERT_GetEncodedOCSPResponseByMethod(arena, certList, location, - "POST", time, addServiceLocator, - signerCert, pwArg, pRequest); + "POST", time, addServiceLocator, + signerCert, pwArg, pRequest); } /* URL encode a buffer that consists of base64-characters, only, * which means we can use a simple encoding logic. - * + * * No output buffer size checking is performed. * You should call the function twice, to calculate the required buffer size. - * - * If the outpufBuf parameter is NULL, the function will calculate the + * + * If the outpufBuf parameter is NULL, the function will calculate the * required size, including the trailing zero termination char. - * + * * The function returns the number of bytes calculated or produced. */ size_t @@ -3598,44 +3566,44 @@ ocsp_UrlEncodeBase64Buf(const char *base64Buf, char *outputBuf) const char *walkInput = NULL; char *walkOutput = outputBuf; size_t count = 0; - - for (walkInput=base64Buf; *walkInput; ++walkInput) { - char c = *walkInput; - if (isspace(c)) - continue; - switch (c) { - case '+': - if (outputBuf) { - strcpy(walkOutput, "%2B"); - walkOutput += 3; - } - count += 3; - break; - case '/': - if (outputBuf) { - strcpy(walkOutput, "%2F"); - walkOutput += 3; - } - count += 3; - break; - case '=': - if (outputBuf) { - strcpy(walkOutput, "%3D"); - walkOutput += 3; - } - count += 3; - break; - default: - if (outputBuf) { - *walkOutput = *walkInput; - ++walkOutput; - } - ++count; - break; - } + + for (walkInput = base64Buf; *walkInput; ++walkInput) { + char c = *walkInput; + if (isspace(c)) + continue; + switch (c) { + case '+': + if (outputBuf) { + strcpy(walkOutput, "%2B"); + walkOutput += 3; + } + count += 3; + break; + case '/': + if (outputBuf) { + strcpy(walkOutput, "%2F"); + walkOutput += 3; + } + count += 3; + break; + case '=': + if (outputBuf) { + strcpy(walkOutput, "%3D"); + walkOutput += 3; + } + count += 3; + break; + default: + if (outputBuf) { + *walkOutput = *walkInput; + ++walkOutput; + } + ++count; + break; + } } if (outputBuf) { - *walkOutput = 0; + *walkOutput = 0; } ++count; return count; @@ -3644,15 +3612,15 @@ ocsp_UrlEncodeBase64Buf(const char *base64Buf, char *outputBuf) enum { max_get_request_size = 255 }; /* defined by RFC2560 */ static SECItem * -cert_GetOCSPResponse(PLArenaPool *arena, const char *location, +cert_GetOCSPResponse(PLArenaPool *arena, const char *location, const SECItem *encodedRequest); static SECItem * ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena, CERTOCSPRequest *request, const char *location, - const char *method, - PRTime time, + const char *method, + PRTime time, PRBool addServiceLocator, void *pwArg, CERTOCSPRequest **pRequest) @@ -3665,13 +3633,13 @@ ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena, goto loser; rv = CERT_AddOCSPAcceptableResponses(request, - SEC_OID_PKIX_OCSP_BASIC_RESPONSE); + SEC_OID_PKIX_OCSP_BASIC_RESPONSE); if (rv != SECSuccess) - goto loser; + goto loser; encodedRequest = CERT_EncodeOCSPRequest(NULL, request, pwArg); if (encodedRequest == NULL) - goto loser; + goto loser; if (!strcmp(method, "GET")) { encodedResponse = cert_GetOCSPResponse(arena, location, encodedRequest); @@ -3680,29 +3648,29 @@ ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena, encodedResponse = CERT_PostOCSPRequest(arena, location, encodedRequest); } else { - goto loser; + goto loser; } if (encodedResponse != NULL && pRequest != NULL) { - *pRequest = request; - request = NULL; /* avoid destroying below */ + *pRequest = request; + request = NULL; /* avoid destroying below */ } loser: if (request != NULL) - CERT_DestroyOCSPRequest(request); + CERT_DestroyOCSPRequest(request); if (encodedRequest != NULL) - SECITEM_FreeItem(encodedRequest, PR_TRUE); + SECITEM_FreeItem(encodedRequest, PR_TRUE); return encodedResponse; } static SECItem * -cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, +cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, const SECItem *encodedRequest); /* using HTTP GET method */ static SECItem * -cert_GetOCSPResponse(PLArenaPool *arena, const char *location, +cert_GetOCSPResponse(PLArenaPool *arena, const char *location, const SECItem *encodedRequest) { char *walkOutput = NULL; @@ -3710,49 +3678,50 @@ cert_GetOCSPResponse(PLArenaPool *arena, const char *location, size_t pathLength; PRInt32 urlEncodedBufLength; size_t base64size; - char b64ReqBuf[max_get_request_size+1]; + char b64ReqBuf[max_get_request_size + 1]; size_t slashLengthIfNeeded = 0; size_t getURLLength; SECItem *item; if (!location || !*location) { - return NULL; + return NULL; } - + pathLength = strlen(location); - if (location[pathLength-1] != '/') { - slashLengthIfNeeded = 1; + if (location[pathLength - 1] != '/') { + slashLengthIfNeeded = 1; } - + /* Calculation as documented by PL_Base64Encode function. * Use integer conversion to avoid having to use function ceil(). */ - base64size = (((encodedRequest->len +2)/3) * 4); + base64size = (((encodedRequest->len + 2) / 3) * 4); if (base64size > max_get_request_size) { - return NULL; + return NULL; } memset(b64ReqBuf, 0, sizeof(b64ReqBuf)); - PL_Base64Encode((const char*)encodedRequest->data, encodedRequest->len, - b64ReqBuf); + PL_Base64Encode((const char *)encodedRequest->data, encodedRequest->len, + b64ReqBuf); urlEncodedBufLength = ocsp_UrlEncodeBase64Buf(b64ReqBuf, NULL); getURLLength = pathLength + urlEncodedBufLength + slashLengthIfNeeded; - + /* urlEncodedBufLength already contains room for the zero terminator. * Add another if we must add the '/' char. */ if (arena) { - fullGetPath = (char*)PORT_ArenaAlloc(arena, getURLLength); - } else { - fullGetPath = (char*)PORT_Alloc(getURLLength); + fullGetPath = (char *)PORT_ArenaAlloc(arena, getURLLength); + } + else { + fullGetPath = (char *)PORT_Alloc(getURLLength); } if (!fullGetPath) { - return NULL; + return NULL; } - + strcpy(fullGetPath, location); walkOutput = fullGetPath + pathLength; - + if (walkOutput > fullGetPath && slashLengthIfNeeded) { strcpy(walkOutput, "/"); ++walkOutput; @@ -3761,20 +3730,20 @@ cert_GetOCSPResponse(PLArenaPool *arena, const char *location, item = cert_FetchOCSPResponse(arena, fullGetPath, NULL); if (!arena) { - PORT_Free(fullGetPath); + PORT_Free(fullGetPath); } return item; } SECItem * -CERT_PostOCSPRequest(PLArenaPool *arena, const char *location, +CERT_PostOCSPRequest(PLArenaPool *arena, const char *location, const SECItem *encodedRequest) { return cert_FetchOCSPResponse(arena, location, encodedRequest); } SECItem * -cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, +cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, const SECItem *encodedRequest) { const SEC_HttpClientFcn *registeredHttpClient; @@ -3784,11 +3753,12 @@ cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, if (registeredHttpClient && registeredHttpClient->version == 1) { encodedResponse = fetchOcspHttpClientV1( - arena, - ®isteredHttpClient->fcnTable.ftable1, - location, - encodedRequest); - } else { + arena, + ®isteredHttpClient->fcnTable.ftable1, + location, + encodedRequest); + } + else { /* use internal http client */ PRFileDesc *sock = ocsp_SendEncodedRequest(location, encodedRequest); if (sock) { @@ -3801,18 +3771,18 @@ cert_FetchOCSPResponse(PLArenaPool *arena, const char *location, } static SECItem * -ocsp_GetEncodedOCSPResponseForSingleCert(PLArenaPool *arena, - CERTOCSPCertID *certID, - CERTCertificate *singleCert, +ocsp_GetEncodedOCSPResponseForSingleCert(PLArenaPool *arena, + CERTOCSPCertID *certID, + CERTCertificate *singleCert, const char *location, - const char *method, - PRTime time, + const char *method, + PRTime time, PRBool addServiceLocator, void *pwArg, CERTOCSPRequest **pRequest) { CERTOCSPRequest *request; - request = cert_CreateSingleCertOCSPRequest(certID, singleCert, time, + request = cert_CreateSingleCertOCSPRequest(certID, singleCert, time, addServiceLocator, NULL); if (!request) return NULL; @@ -3833,29 +3803,28 @@ ocsp_CertIsOCSPDesignatedResponder(CERTCertificate *cert) PRBool retval; CERTOidSequence *oidSeq = NULL; - extItem.data = NULL; rv = CERT_FindCertExtension(cert, SEC_OID_X509_EXT_KEY_USAGE, &extItem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } oidSeq = CERT_DecodeOidSequence(&extItem); - if ( oidSeq == NULL ) { - goto loser; + if (oidSeq == NULL) { + goto loser; } oids = oidSeq->oids; - while ( *oids != NULL ) { - oid = *oids; - - oidTag = SECOID_FindOIDTag(oid); - - if ( oidTag == SEC_OID_OCSP_RESPONDER ) { - goto success; - } - - oids++; + while (*oids != NULL) { + oid = *oids; + + oidTag = SECOID_FindOIDTag(oid); + + if (oidTag == SEC_OID_OCSP_RESPONDER) { + goto success; + } + + oids++; } loser: @@ -3865,42 +3834,41 @@ loser: success: retval = PR_TRUE; done: - if ( extItem.data != NULL ) { - PORT_Free(extItem.data); + if (extItem.data != NULL) { + PORT_Free(extItem.data); } - if ( oidSeq != NULL ) { - CERT_DestroyOidSequence(oidSeq); + if (oidSeq != NULL) { + CERT_DestroyOidSequence(oidSeq); } - - return(retval); + + return (retval); } - -#ifdef LATER /* - * XXX This function is not currently used, but will - * be needed later when we do revocation checking of - * the responder certificate. Of course, it may need - * revising then, if the cert extension interface has - * changed. (Hopefully it will!) - */ +#ifdef LATER /* + * XXX This function is not currently used, but will + * be needed later when we do revocation checking of + * the responder certificate. Of course, it may need + * revising then, if the cert extension interface has + * changed. (Hopefully it will!) + */ /* Checks a certificate to see if it has the OCSP no check extension. */ static PRBool ocsp_CertHasNoCheckExtension(CERTCertificate *cert) { SECStatus rv; - - rv = CERT_FindCertExtension(cert, SEC_OID_PKIX_OCSP_NO_CHECK, - NULL); + + rv = CERT_FindCertExtension(cert, SEC_OID_PKIX_OCSP_NO_CHECK, + NULL); if (rv == SECSuccess) { - return PR_TRUE; + return PR_TRUE; } return PR_FALSE; } -#endif /* LATER */ +#endif /* LATER */ static PRBool -ocsp_matchcert(SECItem *certIndex,CERTCertificate *testCert) +ocsp_matchcert(SECItem *certIndex, CERTCertificate *testCert) { SECItem item; unsigned char buf[HASH_LENGTH_MAX]; @@ -3908,33 +3876,33 @@ ocsp_matchcert(SECItem *certIndex,CERTCertificate *testCert) item.data = buf; item.len = SHA1_LENGTH; - if (CERT_GetSubjectPublicKeyDigest(NULL,testCert,SEC_OID_SHA1, - &item) == NULL) { - return PR_FALSE; + if (CERT_GetSubjectPublicKeyDigest(NULL, testCert, SEC_OID_SHA1, + &item) == NULL) { + return PR_FALSE; } - if (SECITEM_ItemsAreEqual(certIndex,&item)) { - return PR_TRUE; + if (SECITEM_ItemsAreEqual(certIndex, &item)) { + return PR_TRUE; } - if (CERT_GetSubjectPublicKeyDigest(NULL,testCert,SEC_OID_MD5, - &item) == NULL) { - return PR_FALSE; + if (CERT_GetSubjectPublicKeyDigest(NULL, testCert, SEC_OID_MD5, + &item) == NULL) { + return PR_FALSE; } - if (SECITEM_ItemsAreEqual(certIndex,&item)) { - return PR_TRUE; + if (SECITEM_ItemsAreEqual(certIndex, &item)) { + return PR_TRUE; } - if (CERT_GetSubjectPublicKeyDigest(NULL,testCert,SEC_OID_MD2, - &item) == NULL) { - return PR_FALSE; + if (CERT_GetSubjectPublicKeyDigest(NULL, testCert, SEC_OID_MD2, + &item) == NULL) { + return PR_FALSE; } - if (SECITEM_ItemsAreEqual(certIndex,&item)) { - return PR_TRUE; + if (SECITEM_ItemsAreEqual(certIndex, &item)) { + return PR_TRUE; } return PR_FALSE; } static CERTCertificate * -ocsp_CertGetDefaultResponder(CERTCertDBHandle *handle,CERTOCSPCertID *certID); +ocsp_CertGetDefaultResponder(CERTCertDBHandle *handle, CERTOCSPCertID *certID); CERTCertificate * ocsp_GetSignerCertificate(CERTCertDBHandle *handle, ocspResponseData *tbsData, @@ -3949,19 +3917,19 @@ ocsp_GetSignerCertificate(CERTCertDBHandle *handle, ocspResponseData *tbsData, PORT_Assert(tbsData->responderID != NULL); switch (tbsData->responderID->responderIDType) { - case ocspResponderID_byName: - lookupByName = PR_TRUE; - certIndex = &tbsData->derResponderID; - break; - case ocspResponderID_byKey: - lookupByName = PR_FALSE; - certIndex = &tbsData->responderID->responderIDValue.keyHash; - break; - case ocspResponderID_other: - default: - PORT_Assert(0); - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); - return NULL; + case ocspResponderID_byName: + lookupByName = PR_TRUE; + certIndex = &tbsData->derResponderID; + break; + case ocspResponderID_byKey: + lookupByName = PR_FALSE; + certIndex = &tbsData->responderID->responderIDValue.keyHash; + break; + case ocspResponderID_other: + default: + PORT_Assert(0); + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); + return NULL; } /* @@ -3972,14 +3940,14 @@ ocsp_GetSignerCertificate(CERTCertDBHandle *handle, ocspResponseData *tbsData, * to be destroyed. */ if (signature->derCerts != NULL) { - for (; signature->derCerts[certCount] != NULL; certCount++) { - /* just counting */ - } - rv = CERT_ImportCerts(handle, certUsageStatusResponder, certCount, - signature->derCerts, &certs, - PR_FALSE, PR_FALSE, NULL); - if (rv != SECSuccess) - goto finish; + for (; signature->derCerts[certCount] != NULL; certCount++) { + /* just counting */ + } + rv = CERT_ImportCerts(handle, certUsageStatusResponder, certCount, + signature->derCerts, &certs, + PR_FALSE, PR_FALSE, NULL); + if (rv != SECSuccess) + goto finish; } /* @@ -3987,51 +3955,54 @@ ocsp_GetSignerCertificate(CERTCertDBHandle *handle, ocspResponseData *tbsData, * The signer can be specified either by name or by key hash. */ if (lookupByName) { - SECItem *crIndex = (SECItem*)certIndex; - SECItem encodedName; - PLArenaPool *arena; + SECItem *crIndex = (SECItem *)certIndex; + SECItem encodedName; + PLArenaPool *arena; - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena != NULL) { + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (arena != NULL) { - rv = SEC_QuickDERDecodeItem(arena, &encodedName, - ocsp_ResponderIDDerNameTemplate, - crIndex); - if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_BAD_DER) - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); - } else { - signerCert = CERT_FindCertByName(handle, &encodedName); - } - PORT_FreeArena(arena, PR_FALSE); - } - } else { - /* - * The signer is either 1) a known issuer CA we passed in, - * 2) the default OCSP responder, or 3) an intermediate CA - * passed in the cert list to use. Figure out which it is. - */ - int i; - CERTCertificate *responder = + rv = SEC_QuickDERDecodeItem(arena, &encodedName, + ocsp_ResponderIDDerNameTemplate, + crIndex); + if (rv != SECSuccess) { + if (PORT_GetError() == SEC_ERROR_BAD_DER) + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); + } + else { + signerCert = CERT_FindCertByName(handle, &encodedName); + } + PORT_FreeArena(arena, PR_FALSE); + } + } + else { + /* + * The signer is either 1) a known issuer CA we passed in, + * 2) the default OCSP responder, or 3) an intermediate CA + * passed in the cert list to use. Figure out which it is. + */ + int i; + CERTCertificate *responder = ocsp_CertGetDefaultResponder(handle, NULL); - if (responder && ocsp_matchcert(certIndex,responder)) { - signerCert = CERT_DupCertificate(responder); - } else if (issuer && ocsp_matchcert(certIndex,issuer)) { - signerCert = CERT_DupCertificate(issuer); - } - for (i=0; (signerCert == NULL) && (i < certCount); i++) { - if (ocsp_matchcert(certIndex,certs[i])) { - signerCert = CERT_DupCertificate(certs[i]); - } - } - if (signerCert == NULL) { - PORT_SetError(SEC_ERROR_UNKNOWN_CERT); - } + if (responder && ocsp_matchcert(certIndex, responder)) { + signerCert = CERT_DupCertificate(responder); + } + else if (issuer && ocsp_matchcert(certIndex, issuer)) { + signerCert = CERT_DupCertificate(issuer); + } + for (i = 0; (signerCert == NULL) && (i < certCount); i++) { + if (ocsp_matchcert(certIndex, certs[i])) { + signerCert = CERT_DupCertificate(certs[i]); + } + } + if (signerCert == NULL) { + PORT_SetError(SEC_ERROR_UNKNOWN_CERT); + } } finish: if (certs != NULL) { - CERT_DestroyCertArray(certs, certCount); + CERT_DestroyCertArray(certs, certCount); } return signerCert; @@ -4067,7 +4038,7 @@ ocsp_VerifyResponseSignature(CERTCertificate *signerCert, rv = CERT_VerifySignedDataWithPublicKey(&signedData, signerKey, pwArg); if (rv != SECSuccess && - (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE || + (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE || PORT_GetError() == SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED)) { PORT_SetError(SEC_ERROR_OCSP_BAD_SIGNATURE); } @@ -4079,7 +4050,6 @@ ocsp_VerifyResponseSignature(CERTCertificate *signerCert, return rv; } - /* * FUNCTION: CERT_VerifyOCSPResponseSignature * Check the signature on an OCSP Response. Will also perform a @@ -4110,10 +4080,10 @@ ocsp_VerifyResponseSignature(CERTCertificate *signerCert, * verifying the signer's cert, or low-level problems (no memory, etc.) */ SECStatus -CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, - CERTCertDBHandle *handle, void *pwArg, - CERTCertificate **pSignerCert, - CERTCertificate *issuer) +CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, + CERTCertDBHandle *handle, void *pwArg, + CERTCertificate **pSignerCert, + CERTCertificate *issuer) { SECItem *tbsResponseDataDER; CERTCertificate *signerCert = NULL; @@ -4138,24 +4108,25 @@ CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, * return the cached result. */ if (signature->wasChecked) { - if (signature->status == SECSuccess) { - if (pSignerCert != NULL) - *pSignerCert = CERT_DupCertificate(signature->cert); - } else { - PORT_SetError(signature->failureReason); - } - return signature->status; + if (signature->status == SECSuccess) { + if (pSignerCert != NULL) + *pSignerCert = CERT_DupCertificate(signature->cert); + } + else { + PORT_SetError(signature->failureReason); + } + return signature->status; } signerCert = ocsp_GetSignerCertificate(handle, tbsData, signature, issuer); if (signerCert == NULL) { - rv = SECFailure; - if (PORT_GetError() == SEC_ERROR_UNKNOWN_CERT) { - /* Make the error a little more specific. */ - PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT); - } - goto finish; + rv = SECFailure; + if (PORT_GetError() == SEC_ERROR_UNKNOWN_CERT) { + /* Make the error a little more specific. */ + PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT); + } + goto finish; } /* @@ -4182,11 +4153,13 @@ CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, */ if (ocsp_CertIsOCSPDefaultResponder(handle, signerCert)) { rv = SECSuccess; - } else { + } + else { SECCertUsage certUsage; if (CERT_IsCACert(signerCert, NULL)) { certUsage = certUsageAnyCA; - } else { + } + else { certUsage = certUsageStatusResponder; } rv = cert_VerifyCertWithFlags(handle, signerCert, PR_TRUE, certUsage, @@ -4204,24 +4177,25 @@ CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, finish: if (signature->wasChecked) - signature->status = rv; + signature->status = rv; if (rv != SECSuccess) { - signature->failureReason = PORT_GetError(); - if (signerCert != NULL) - CERT_DestroyCertificate(signerCert); - } else { - /* - * Save signer's certificate in signature. - */ - signature->cert = signerCert; - if (pSignerCert != NULL) { - /* - * Pass pointer to signer's certificate back to our caller, - * who is also now responsible for destroying it. - */ - *pSignerCert = CERT_DupCertificate(signerCert); - } + signature->failureReason = PORT_GetError(); + if (signerCert != NULL) + CERT_DestroyCertificate(signerCert); + } + else { + /* + * Save signer's certificate in signature. + */ + signature->cert = signerCert; + if (pSignerCert != NULL) { + /* + * Pass pointer to signer's certificate back to our caller, + * who is also now responsible for destroying it. + */ + *pSignerCert = CERT_DupCertificate(signerCert); + } } return rv; @@ -4234,7 +4208,7 @@ finish: */ static PRBool ocsp_CertIDsMatch(CERTOCSPCertID *requestCertID, - CERTOCSPCertID *responseCertID) + CERTOCSPCertID *responseCertID) { PRBool match = PR_FALSE; SECOidTag hashAlg; @@ -4248,8 +4222,8 @@ ocsp_CertIDsMatch(CERTOCSPCertID *requestCertID, * We just compare the easier things first. */ if (SECITEM_CompareItem(&requestCertID->serialNumber, - &responseCertID->serialNumber) != SECEqual) { - goto done; + &responseCertID->serialNumber) != SECEqual) { + goto done; } /* @@ -4257,48 +4231,49 @@ ocsp_CertIDsMatch(CERTOCSPCertID *requestCertID, * requestCertID->hashAlgorithm, we don't need to check it. */ if (responseCertID->hashAlgorithm.parameters.len > 2) { - goto done; + goto done; } if (SECITEM_CompareItem(&requestCertID->hashAlgorithm.algorithm, - &responseCertID->hashAlgorithm.algorithm) == SECEqual) { - /* - * If the hash algorithms match then we can do a simple compare - * of the hash values themselves. - */ - if ((SECITEM_CompareItem(&requestCertID->issuerNameHash, - &responseCertID->issuerNameHash) == SECEqual) - && (SECITEM_CompareItem(&requestCertID->issuerKeyHash, - &responseCertID->issuerKeyHash) == SECEqual)) { - match = PR_TRUE; - } - goto done; + &responseCertID->hashAlgorithm.algorithm) == + SECEqual) { + /* + * If the hash algorithms match then we can do a simple compare + * of the hash values themselves. + */ + if ((SECITEM_CompareItem(&requestCertID->issuerNameHash, + &responseCertID->issuerNameHash) == SECEqual) && + (SECITEM_CompareItem(&requestCertID->issuerKeyHash, + &responseCertID->issuerKeyHash) == SECEqual)) { + match = PR_TRUE; + } + goto done; } hashAlg = SECOID_FindOIDTag(&responseCertID->hashAlgorithm.algorithm); switch (hashAlg) { - case SEC_OID_SHA1: - keyHash = &requestCertID->issuerSHA1KeyHash; - nameHash = &requestCertID->issuerSHA1NameHash; - break; - case SEC_OID_MD5: - keyHash = &requestCertID->issuerMD5KeyHash; - nameHash = &requestCertID->issuerMD5NameHash; - break; - case SEC_OID_MD2: - keyHash = &requestCertID->issuerMD2KeyHash; - nameHash = &requestCertID->issuerMD2NameHash; - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return PR_FALSE; + case SEC_OID_SHA1: + keyHash = &requestCertID->issuerSHA1KeyHash; + nameHash = &requestCertID->issuerSHA1NameHash; + break; + case SEC_OID_MD5: + keyHash = &requestCertID->issuerMD5KeyHash; + nameHash = &requestCertID->issuerMD5NameHash; + break; + case SEC_OID_MD2: + keyHash = &requestCertID->issuerMD2KeyHash; + nameHash = &requestCertID->issuerMD2NameHash; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return PR_FALSE; } - if ((keyHash != NULL) - && (SECITEM_CompareItem(nameHash, - &responseCertID->issuerNameHash) == SECEqual) - && (SECITEM_CompareItem(keyHash, - &responseCertID->issuerKeyHash) == SECEqual)) { - match = PR_TRUE; + if ((keyHash != NULL) && + (SECITEM_CompareItem(nameHash, + &responseCertID->issuerNameHash) == SECEqual) && + (SECITEM_CompareItem(keyHash, + &responseCertID->issuerKeyHash) == SECEqual)) { + match = PR_TRUE; } done: @@ -4313,27 +4288,27 @@ done: */ static CERTOCSPSingleResponse * ocsp_GetSingleResponseForCertID(CERTOCSPSingleResponse **responses, - CERTCertDBHandle *handle, - CERTOCSPCertID *certID) + CERTCertDBHandle *handle, + CERTOCSPCertID *certID) { CERTOCSPSingleResponse *single; int i; if (responses == NULL) - return NULL; + return NULL; for (i = 0; responses[i] != NULL; i++) { - single = responses[i]; - if (ocsp_CertIDsMatch(certID, single->certID)) { - return single; - } + single = responses[i]; + if (ocsp_CertIDsMatch(certID, single->certID)) { + return single; + } } /* * The OCSP server should have included a response even if it knew * nothing about the certificate in question. Since it did not, * this will make it look as if it had. - * + * * XXX Should we make this a separate error to notice the server's * bad behavior? */ @@ -4349,19 +4324,19 @@ ocsp_GetCheckingContext(CERTCertDBHandle *handle) statusConfig = CERT_GetStatusConfig(handle); if (statusConfig != NULL) { - ocspcx = statusConfig->statusContext; + ocspcx = statusConfig->statusContext; - /* - * This is actually an internal error, because we should never - * have a good statusConfig without a good statusContext, too. - * For lack of anything better, though, we just assert and use - * the same error as if there were no statusConfig (set below). - */ - PORT_Assert(ocspcx != NULL); + /* + * This is actually an internal error, because we should never + * have a good statusConfig without a good statusContext, too. + * For lack of anything better, though, we just assert and use + * the same error as if there were no statusConfig (set below). + */ + PORT_Assert(ocspcx != NULL); } if (ocspcx == NULL) - PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED); + PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED); return ocspcx; } @@ -4377,19 +4352,19 @@ ocsp_CertGetDefaultResponder(CERTCertDBHandle *handle, CERTOCSPCertID *certID) ocspcx = ocsp_GetCheckingContext(handle); if (ocspcx == NULL) - goto loser; + goto loser; - /* - * Right now we have only one default responder. It applies to - * all certs when it is used, so the check is simple and certID - * has no bearing on the answer. Someday in the future we may - * allow configuration of different responders for different - * issuers, and then we would have to use the issuer specified - * in certID to determine if signerCert is the right one. - */ + /* + * Right now we have only one default responder. It applies to + * all certs when it is used, so the check is simple and certID + * has no bearing on the answer. Someday in the future we may + * allow configuration of different responders for different + * issuers, and then we would have to use the issuer specified + * in certID to determine if signerCert is the right one. + */ if (ocspcx->useDefaultResponder) { - PORT_Assert(ocspcx->defaultResponderCert != NULL); - return ocspcx->defaultResponderCert; + PORT_Assert(ocspcx->defaultResponderCert != NULL); + return ocspcx->defaultResponderCert; } loser: @@ -4407,19 +4382,19 @@ ocsp_CertIsOCSPDefaultResponder(CERTCertDBHandle *handle, CERTCertificate *cert) ocspcx = ocsp_GetCheckingContext(handle); if (ocspcx == NULL) - return PR_FALSE; + return PR_FALSE; - /* - * Right now we have only one default responder. It applies to - * all certs when it is used, so the check is simple and certID - * has no bearing on the answer. Someday in the future we may - * allow configuration of different responders for different - * issuers, and then we would have to use the issuer specified - * in certID to determine if signerCert is the right one. - */ + /* + * Right now we have only one default responder. It applies to + * all certs when it is used, so the check is simple and certID + * has no bearing on the answer. Someday in the future we may + * allow configuration of different responders for different + * issuers, and then we would have to use the issuer specified + * in certID to determine if signerCert is the right one. + */ if (ocspcx->useDefaultResponder && CERT_CompareCerts(ocspcx->defaultResponderCert, cert)) { - return PR_TRUE; + return PR_TRUE; } return PR_FALSE; @@ -4444,9 +4419,9 @@ ocsp_CertIsOCSPDefaultResponder(CERTCertDBHandle *handle, CERTCertificate *cert) */ static PRBool ocsp_AuthorizedResponderForCertID(CERTCertDBHandle *handle, - CERTCertificate *signerCert, - CERTOCSPCertID *certID, - PRTime thisUpdate) + CERTCertificate *signerCert, + CERTOCSPCertID *certID, + PRTime thisUpdate) { CERTCertificate *issuerCert = NULL, *defRespCert; SECItem *keyHash = NULL; @@ -4490,7 +4465,7 @@ ocsp_AuthorizedResponderForCertID(CERTCertDBHandle *handle, nameHashEQ = (SECITEM_CompareItem(nameHash, &certID->issuerNameHash) == SECEqual); - + SECITEM_FreeItem(nameHash, PR_TRUE); if (nameHashEQ) { /* The issuer of the cert is the the signer of the response */ @@ -4498,7 +4473,6 @@ ocsp_AuthorizedResponderForCertID(CERTCertDBHandle *handle, } } - keyHashEQ = PR_FALSE; nameHashEQ = PR_FALSE; @@ -4529,7 +4503,7 @@ ocsp_AuthorizedResponderForCertID(CERTCertDBHandle *handle, CERT_DestroyCertificate(issuerCert); if (keyHash != NULL && nameHash != NULL) { - keyHashEQ = + keyHashEQ = (SECITEM_CompareItem(keyHash, &certID->issuerKeyHash) == SECEqual); @@ -4565,7 +4539,7 @@ ocsp_AuthorizedResponderForCertID(CERTCertDBHandle *handle, * want something from within the last 24 hours. This macro defines that * number in seconds. */ -#define OCSP_ALLOWABLE_LAPSE_SECONDS (24L * 60L * 60L) +#define OCSP_ALLOWABLE_LAPSE_SECONDS (24L * 60L * 60L) static PRBool ocsp_TimeIsRecent(PRTime checkTime) @@ -4575,19 +4549,19 @@ ocsp_TimeIsRecent(PRTime checkTime) LL_I2L(lapse, OCSP_ALLOWABLE_LAPSE_SECONDS); LL_I2L(tmp, PR_USEC_PER_SEC); - LL_MUL(lapse, lapse, tmp); /* allowable lapse in microseconds */ + LL_MUL(lapse, lapse, tmp); /* allowable lapse in microseconds */ LL_ADD(checkTime, checkTime, lapse); if (LL_CMP(now, >, checkTime)) - return PR_FALSE; + return PR_FALSE; return PR_TRUE; } -#define OCSP_SLOP (5L*60L) /* OCSP responses are allowed to be 5 minutes - in the future by default */ +#define OCSP_SLOP (5L * 60L) /* OCSP responses are allowed to be 5 minutes \ + in the future by default */ -static PRUint32 ocspsloptime = OCSP_SLOP; /* seconds */ +static PRUint32 ocspsloptime = OCSP_SLOP; /* seconds */ /* * If an old response contains the revoked certificate status, we want @@ -4610,7 +4584,6 @@ ocsp_HandleOldSingleResponse(CERTOCSPSingleResponse *single, PRTime time) */ return SECSuccess; } - } PORT_SetError(SEC_ERROR_OCSP_OLD_RESPONSE); return SECFailure; @@ -4638,19 +4611,19 @@ ocsp_HandleOldSingleResponse(CERTOCSPSingleResponse *single, PRTime time) * SEC_ERROR_OCSP_OLD_RESPONSE * SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE * Other errors are low-level problems (no memory, bad database, etc.). - */ + */ static SECStatus ocsp_VerifySingleResponse(CERTOCSPSingleResponse *single, - CERTCertDBHandle *handle, - CERTCertificate *signerCert, - PRTime producedAt) + CERTCertDBHandle *handle, + CERTCertificate *signerCert, + PRTime producedAt) { CERTOCSPCertID *certID = single->certID; PRTime now, thisUpdate, nextUpdate, tmstamp, tmp; SECStatus rv; - OCSP_TRACE(("OCSP ocsp_VerifySingleResponse, nextUpdate: %d\n", - ((single->nextUpdate) != 0))); + OCSP_TRACE(("OCSP ocsp_VerifySingleResponse, nextUpdate: %d\n", + ((single->nextUpdate) != 0))); /* * If all the responder said was that the given cert was unknown to it, * that is a valid response. Not very interesting to us, of course, @@ -4659,7 +4632,7 @@ ocsp_VerifySingleResponse(CERTOCSPSingleResponse *single, */ PORT_Assert(single->certStatus != NULL); if (single->certStatus->certStatusType == ocspCertStatus_unknown) - return SECSuccess; + return SECSuccess; /* * We need to extract "thisUpdate" for use below and to pass along @@ -4668,14 +4641,14 @@ ocsp_VerifySingleResponse(CERTOCSPSingleResponse *single, */ rv = DER_GeneralizedTimeToTime(&thisUpdate, &single->thisUpdate); if (rv != SECSuccess) - return rv; + return rv; /* * First confirm that signerCert is authorized to give this status. */ if (ocsp_AuthorizedResponderForCertID(handle, signerCert, certID, - thisUpdate) != PR_TRUE) - return SECFailure; + thisUpdate) != PR_TRUE) + return SECFailure; /* * Now check the time stuff, as described above. @@ -4688,25 +4661,25 @@ ocsp_VerifySingleResponse(CERTOCSPSingleResponse *single, LL_ADD(tmstamp, tmp, now); /* add current time to it */ if (LL_CMP(thisUpdate, >, tmstamp) || LL_CMP(producedAt, <, thisUpdate)) { - PORT_SetError(SEC_ERROR_OCSP_FUTURE_RESPONSE); - return SECFailure; + PORT_SetError(SEC_ERROR_OCSP_FUTURE_RESPONSE); + return SECFailure; } if (single->nextUpdate != NULL) { - rv = DER_GeneralizedTimeToTime(&nextUpdate, single->nextUpdate); - if (rv != SECSuccess) - return rv; + rv = DER_GeneralizedTimeToTime(&nextUpdate, single->nextUpdate); + if (rv != SECSuccess) + return rv; - LL_ADD(tmp, tmp, nextUpdate); - if (LL_CMP(tmp, <, now) || LL_CMP(producedAt, >, nextUpdate)) - return ocsp_HandleOldSingleResponse(single, now); - } else if (ocsp_TimeIsRecent(thisUpdate) != PR_TRUE) { - return ocsp_HandleOldSingleResponse(single, now); + LL_ADD(tmp, tmp, nextUpdate); + if (LL_CMP(tmp, <, now) || LL_CMP(producedAt, >, nextUpdate)) + return ocsp_HandleOldSingleResponse(single, now); + } + else if (ocsp_TimeIsRecent(thisUpdate) != PR_TRUE) { + return ocsp_HandleOldSingleResponse(single, now); } return SECSuccess; } - /* * FUNCTION: CERT_GetOCSPAuthorityInfoAccessLocation * Get the value of the URI of the OCSP responder for the given cert. @@ -4721,7 +4694,7 @@ ocsp_VerifySingleResponse(CERTOCSPSingleResponse *single, * extension is not present or it does not contain an entry for OCSP, * SEC_ERROR_CERT_BAD_ACCESS_LOCATION will be set and a NULL returned. * Any other error will also result in a NULL being returned. - * + * * This result should be freed (via PORT_Free) when no longer in use. */ char * @@ -4743,13 +4716,13 @@ CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert) */ encodedAuthInfoAccess = SECITEM_AllocItem(NULL, NULL, 0); if (encodedAuthInfoAccess == NULL) - goto loser; + goto loser; rv = CERT_FindCertExtension(cert, SEC_OID_X509_AUTH_INFO_ACCESS, - encodedAuthInfoAccess); + encodedAuthInfoAccess); if (rv == SECFailure) { - PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); - goto loser; + PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); + goto loser; } /* @@ -4760,16 +4733,16 @@ CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert) */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) - goto loser; + goto loser; authInfoAccess = CERT_DecodeAuthInfoAccessExtension(arena, - encodedAuthInfoAccess); + encodedAuthInfoAccess); if (authInfoAccess == NULL) - goto loser; + goto loser; for (i = 0; authInfoAccess[i] != NULL; i++) { - if (SECOID_FindOIDTag(&authInfoAccess[i]->method) == SEC_OID_PKIX_OCSP) - locname = authInfoAccess[i]->location; + if (SECOID_FindOIDTag(&authInfoAccess[i]->method) == SEC_OID_PKIX_OCSP) + locname = authInfoAccess[i]->location; } /* @@ -4780,8 +4753,8 @@ CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert) * not there at all. */ if (locname == NULL) { - PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); - goto loser; + PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); + goto loser; } /* @@ -4790,15 +4763,15 @@ CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert) */ location = CERT_GetGeneralNameByType(locname, certURI, PR_FALSE); if (location == NULL) { - /* - * XXX Appears that CERT_GetGeneralNameByType does not set an - * error if there is no name by that type. For lack of anything - * better, act as if the extension was not found. In the future - * this should probably be something more like the extension was - * badly formed. - */ - PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); - goto loser; + /* + * XXX Appears that CERT_GetGeneralNameByType does not set an + * error if there is no name by that type. For lack of anything + * better, act as if the extension was not found. In the future + * this should probably be something more like the extension was + * badly formed. + */ + PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION); + goto loser; } /* @@ -4809,22 +4782,21 @@ CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert) */ locURI = PORT_Alloc(location->len + 1); if (locURI == NULL) { - goto loser; + goto loser; } PORT_Memcpy(locURI, location->data, location->len); locURI[location->len] = '\0'; loser: if (arena != NULL) - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); if (encodedAuthInfoAccess != NULL) - SECITEM_FreeItem(encodedAuthInfoAccess, PR_TRUE); + SECITEM_FreeItem(encodedAuthInfoAccess, PR_TRUE); return locURI; } - /* * Figure out where we should go to find out the status of the given cert * via OCSP. If allowed to use a default responder uri and a default @@ -4840,7 +4812,7 @@ loser: */ char * ocsp_GetResponderLocation(CERTCertDBHandle *handle, CERTCertificate *cert, - PRBool canUseDefault, PRBool *isDefault) + PRBool canUseDefault, PRBool *isDefault) { ocspCheckingContext *ocspcx = NULL; char *ocspUrl = NULL; @@ -4849,15 +4821,15 @@ ocsp_GetResponderLocation(CERTCertDBHandle *handle, CERTCertificate *cert, ocspcx = ocsp_GetCheckingContext(handle); } if (ocspcx != NULL && ocspcx->useDefaultResponder) { - /* - * A default responder wins out, if specified. - * XXX Someday this may be a more complicated determination based - * on the cert's issuer. (That is, we could have different default - * responders configured for different issuers.) - */ - PORT_Assert(ocspcx->defaultResponderURI != NULL); - *isDefault = PR_TRUE; - return (PORT_Strdup(ocspcx->defaultResponderURI)); + /* + * A default responder wins out, if specified. + * XXX Someday this may be a more complicated determination based + * on the cert's issuer. (That is, we could have different default + * responders configured for different issuers.) + */ + PORT_Assert(ocspcx->defaultResponderURI != NULL); + *isDefault = PR_TRUE; + return (PORT_Strdup(ocspcx->defaultResponderURI)); } /* @@ -4867,16 +4839,16 @@ ocsp_GetResponderLocation(CERTCertDBHandle *handle, CERTCertificate *cert, *isDefault = PR_FALSE; ocspUrl = CERT_GetOCSPAuthorityInfoAccessLocation(cert); if (!ocspUrl) { - CERT_StringFromCertFcn altFcn; + CERT_StringFromCertFcn altFcn; - PR_EnterMonitor(OCSP_Global.monitor); - altFcn = OCSP_Global.alternateOCSPAIAFcn; - PR_ExitMonitor(OCSP_Global.monitor); - if (altFcn) { - ocspUrl = (*altFcn)(cert); - if (ocspUrl) - *isDefault = PR_TRUE; - } + PR_EnterMonitor(OCSP_Global.monitor); + altFcn = OCSP_Global.alternateOCSPAIAFcn; + PR_ExitMonitor(OCSP_Global.monitor); + if (altFcn) { + ocspUrl = (*altFcn)(cert); + if (ocspUrl) + *isDefault = PR_TRUE; + } } return ocspUrl; } @@ -4893,7 +4865,7 @@ ocsp_CertRevokedAfter(ocspRevokedInfo *revokedInfo, PRTime time) rv = DER_GeneralizedTimeToTime(&revokedTime, &revokedInfo->revocationTime); if (rv != SECSuccess) - return rv; + return rv; /* * Set the error even if we will return success; someone might care. @@ -4901,7 +4873,7 @@ ocsp_CertRevokedAfter(ocspRevokedInfo *revokedInfo, PRTime time) PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE); if (LL_CMP(revokedTime, >, time)) - return SECSuccess; + return SECSuccess; return SECFailure; } @@ -4915,28 +4887,28 @@ ocsp_CertHasGoodStatus(ocspCertStatus *status, PRTime time) { SECStatus rv; switch (status->certStatusType) { - case ocspCertStatus_good: - rv = SECSuccess; - break; - case ocspCertStatus_revoked: - rv = ocsp_CertRevokedAfter(status->certStatusInfo.revokedInfo, time); - break; - case ocspCertStatus_unknown: - PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_CERT); - rv = SECFailure; - break; - case ocspCertStatus_other: - default: - PORT_Assert(0); - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); - rv = SECFailure; - break; + case ocspCertStatus_good: + rv = SECSuccess; + break; + case ocspCertStatus_revoked: + rv = ocsp_CertRevokedAfter(status->certStatusInfo.revokedInfo, time); + break; + case ocspCertStatus_unknown: + PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_CERT); + rv = SECFailure; + break; + case ocspCertStatus_other: + default: + PORT_Assert(0); + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE); + rv = SECFailure; + break; } return rv; } static SECStatus -ocsp_SingleResponseCertHasGoodStatus(CERTOCSPSingleResponse *single, +ocsp_SingleResponseCertHasGoodStatus(CERTOCSPSingleResponse *single, PRTime time) { return ocsp_CertHasGoodStatus(single->certStatus, time); @@ -4963,7 +4935,7 @@ ocsp_GetCachedOCSPResponseStatus(CERTOCSPCertID *certID, OCSPFreshness *cacheFreshness) { OCSPCacheItem *cacheItem = NULL; - + if (!certID || !missingResponseError || !rvOcsp || !cacheFreshness) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; @@ -4971,7 +4943,7 @@ ocsp_GetCachedOCSPResponseStatus(CERTOCSPCertID *certID, *rvOcsp = SECFailure; *missingResponseError = 0; *cacheFreshness = ocspMissing; - + PR_EnterMonitor(OCSP_Global.monitor); cacheItem = ocsp_FindCacheEntry(&OCSP_Global.cache, certID); if (cacheItem) { @@ -4983,16 +4955,17 @@ ocsp_GetCachedOCSPResponseStatus(CERTOCSPCertID *certID, if (*rvOcsp != SECSuccess) { *missingResponseError = PORT_GetError(); } - } else { + } + else { /* * No status cached, the previous attempt failed. - * If OCSP is required, we never decide based on a failed attempt + * If OCSP is required, we never decide based on a failed attempt * However, if OCSP is optional, a recent OCSP failure is * an allowed good state. */ if (*cacheFreshness == ocspFresh && !ignoreGlobalOcspFailureSetting && - OCSP_Global.ocspFailureMode == + OCSP_Global.ocspFailureMode == ocspMode_FailureIsNotAVerificationFailure) { *rvOcsp = SECSuccess; } @@ -5064,10 +5037,10 @@ ocsp_FetchingFailureIsVerificationFailure(void) * (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when * verifying the signer's cert, or low-level problems (error allocating * memory, error performing ASN.1 decoding, etc.). - */ -SECStatus + */ +SECStatus CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, - PRTime time, void *pwArg) + PRTime time, void *pwArg) { CERTOCSPCertID *certID; PRBool certIDWasConsumed = PR_FALSE; @@ -5075,10 +5048,10 @@ CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, SECStatus rvOcsp; SECErrorCodes cachedErrorCode; OCSPFreshness cachedResponseFreshness; - + OCSP_TRACE_CERT(cert); OCSP_TRACE_TIME("## requested validity time:", time); - + certID = CERT_CreateOCSPCertID(cert, time); if (!certID) return SECFailure; @@ -5098,16 +5071,17 @@ CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, } rv = ocsp_GetOCSPStatusFromNetwork(handle, certID, cert, time, pwArg, - &certIDWasConsumed, + &certIDWasConsumed, &rvOcsp); if (rv != SECSuccess) { PRErrorCode err = PORT_GetError(); if (ocsp_FetchingFailureIsVerificationFailure()) { PORT_SetError(err); rvOcsp = SECFailure; - } else if (cachedResponseFreshness == ocspStale && - (cachedErrorCode == SEC_ERROR_OCSP_UNKNOWN_CERT || - cachedErrorCode == SEC_ERROR_REVOKED_CERTIFICATE)) { + } + else if (cachedResponseFreshness == ocspStale && + (cachedErrorCode == SEC_ERROR_OCSP_UNKNOWN_CERT || + cachedErrorCode == SEC_ERROR_REVOKED_CERTIFICATE)) { /* If we couldn't get a response for a certificate that the OCSP * responder previously told us was bad, then assume it is still * bad until we hear otherwise, as it is very unlikely that the @@ -5117,7 +5091,8 @@ CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, */ PORT_SetError(cachedErrorCode); rvOcsp = SECFailure; - } else { + } + else { rvOcsp = SECSuccess; } } @@ -5157,10 +5132,10 @@ CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, */ SECStatus CERT_CacheOCSPResponseFromSideChannel(CERTCertDBHandle *handle, - CERTCertificate *cert, - PRTime time, - const SECItem *encodedResponse, - void *pwArg) + CERTCertificate *cert, + PRTime time, + const SECItem *encodedResponse, + void *pwArg) { CERTOCSPCertID *certID = NULL; PRBool certIDWasConsumed = PR_FALSE; @@ -5235,17 +5210,17 @@ CERT_CacheOCSPResponseFromSideChannel(CERTCertDBHandle *handle, * ocsp_CacheSingleResponse. */ rv = ocsp_GetDecodedVerifiedSingleResponseForID(handle, certID, cert, - time, pwArg, - encodedResponse, - &decodedResponse, - &singleResponse); + time, pwArg, + encodedResponse, + &decodedResponse, + &singleResponse); if (rv == SECSuccess) { - rvOcsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time); - /* Cache any valid singleResponse, regardless of status. */ - ocsp_CacheSingleResponse(certID, singleResponse, &certIDWasConsumed); + rvOcsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time); + /* Cache any valid singleResponse, regardless of status. */ + ocsp_CacheSingleResponse(certID, singleResponse, &certIDWasConsumed); } if (decodedResponse) { - CERT_DestroyOCSPResponse(decodedResponse); + CERT_DestroyOCSPResponse(decodedResponse); } if (!certIDWasConsumed) { CERT_DestroyOCSPCertID(certID); @@ -5254,13 +5229,13 @@ CERT_CacheOCSPResponseFromSideChannel(CERTCertDBHandle *handle, } /* - * Status in *certIDWasConsumed will always be correct, regardless of + * Status in *certIDWasConsumed will always be correct, regardless of * return value. */ static SECStatus -ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, - CERTOCSPCertID *certID, - CERTCertificate *cert, +ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, + CERTOCSPCertID *certID, + CERTCertificate *cert, PRTime time, void *pwArg, PRBool *certIDWasConsumed, @@ -5274,7 +5249,8 @@ ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, CERTOCSPResponse *decodedResponse = NULL; CERTOCSPSingleResponse *singleResponse = NULL; - enum { stageGET, stagePOST } currentStage; + enum { stageGET, + stagePOST } currentStage; PRBool retry = PR_FALSE; if (!certIDWasConsumed || !rv_ocsp) { @@ -5291,7 +5267,8 @@ ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, PR_EnterMonitor(OCSP_Global.monitor); if (OCSP_Global.forcePost) { currentStage = stagePOST; - } else { + } + else { currentStage = stageGET; } PR_ExitMonitor(OCSP_Global.monitor); @@ -5310,14 +5287,14 @@ ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, location = ocsp_GetResponderLocation(handle, cert, PR_TRUE, &locationIsDefault); if (location == NULL) { - int err = PORT_GetError(); - if (err == SEC_ERROR_EXTENSION_NOT_FOUND || - err == SEC_ERROR_CERT_BAD_ACCESS_LOCATION) { - PORT_SetError(0); - *rv_ocsp = SECSuccess; - return SECSuccess; - } - return SECFailure; + int err = PORT_GetError(); + if (err == SEC_ERROR_EXTENSION_NOT_FOUND || + err == SEC_ERROR_CERT_BAD_ACCESS_LOCATION) { + PORT_SetError(0); + *rv_ocsp = SECSuccess; + return SECSuccess; + } + return SECFailure; } /* @@ -5343,75 +5320,79 @@ ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, */ do { - const char *method; - PRBool validResponseWithAccurateInfo = PR_FALSE; - retry = PR_FALSE; - *rv_ocsp = SECFailure; + const char *method; + PRBool validResponseWithAccurateInfo = PR_FALSE; + retry = PR_FALSE; + *rv_ocsp = SECFailure; - if (currentStage == stageGET) { - method = "GET"; - } else { - PORT_Assert(currentStage == stagePOST); - method = "POST"; - } + if (currentStage == stageGET) { + method = "GET"; + } + else { + PORT_Assert(currentStage == stagePOST); + method = "POST"; + } - encodedResponse = - ocsp_GetEncodedOCSPResponseForSingleCert(NULL, certID, cert, - location, method, - time, locationIsDefault, - pwArg, &request); + encodedResponse = + ocsp_GetEncodedOCSPResponseForSingleCert(NULL, certID, cert, + location, method, + time, locationIsDefault, + pwArg, &request); - if (encodedResponse) { - rv = ocsp_GetDecodedVerifiedSingleResponseForID(handle, certID, cert, - time, pwArg, - encodedResponse, - &decodedResponse, - &singleResponse); - if (rv == SECSuccess) { - switch (singleResponse->certStatus->certStatusType) { - case ocspCertStatus_good: - case ocspCertStatus_revoked: - validResponseWithAccurateInfo = PR_TRUE; - break; - default: - break; - } - *rv_ocsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time); - } - } + if (encodedResponse) { + rv = ocsp_GetDecodedVerifiedSingleResponseForID(handle, certID, cert, + time, pwArg, + encodedResponse, + &decodedResponse, + &singleResponse); + if (rv == SECSuccess) { + switch (singleResponse->certStatus->certStatusType) { + case ocspCertStatus_good: + case ocspCertStatus_revoked: + validResponseWithAccurateInfo = PR_TRUE; + break; + default: + break; + } + *rv_ocsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time); + } + } - if (currentStage == stageGET) { - /* only accept GET response if good or revoked */ - if (validResponseWithAccurateInfo) { - ocsp_CacheSingleResponse(certID, singleResponse, - certIDWasConsumed); - } else { - retry = PR_TRUE; - currentStage = stagePOST; - } - } else { - /* cache the POST respone, regardless of status */ - if (!singleResponse) { - cert_RememberOCSPProcessingFailure(certID, certIDWasConsumed); - } else { - ocsp_CacheSingleResponse(certID, singleResponse, - certIDWasConsumed); - } - } + if (currentStage == stageGET) { + /* only accept GET response if good or revoked */ + if (validResponseWithAccurateInfo) { + ocsp_CacheSingleResponse(certID, singleResponse, + certIDWasConsumed); + } + else { + retry = PR_TRUE; + currentStage = stagePOST; + } + } + else { + /* cache the POST respone, regardless of status */ + if (!singleResponse) { + cert_RememberOCSPProcessingFailure(certID, certIDWasConsumed); + } + else { + ocsp_CacheSingleResponse(certID, singleResponse, + certIDWasConsumed); + } + } - if (encodedResponse) { - SECITEM_FreeItem(encodedResponse, PR_TRUE); - encodedResponse = NULL; - } - if (request) { - CERT_DestroyOCSPRequest(request); - request = NULL; - } - if (decodedResponse) { - CERT_DestroyOCSPResponse(decodedResponse); - decodedResponse = NULL; - } - singleResponse = NULL; + if (encodedResponse) { + SECITEM_FreeItem(encodedResponse, PR_TRUE); + encodedResponse = NULL; + } + if (request) { + CERT_DestroyOCSPRequest(request); + request = NULL; + } + if (decodedResponse) { + CERT_DestroyOCSPResponse(decodedResponse); + decodedResponse = NULL; + } + singleResponse = NULL; } while (retry); @@ -5454,25 +5435,25 @@ ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle, */ static SECStatus ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle, - CERTOCSPCertID *certID, - CERTCertificate *cert, - PRTime time, - void *pwArg, - const SECItem *encodedResponse, - CERTOCSPResponse **pDecodedResponse, - CERTOCSPSingleResponse **pSingle) + CERTOCSPCertID *certID, + CERTCertificate *cert, + PRTime time, + void *pwArg, + const SECItem *encodedResponse, + CERTOCSPResponse **pDecodedResponse, + CERTOCSPSingleResponse **pSingle) { CERTCertificate *signerCert = NULL; CERTCertificate *issuerCert = NULL; SECStatus rv = SECFailure; if (!pSingle || !pDecodedResponse) { - return SECFailure; + return SECFailure; } *pSingle = NULL; *pDecodedResponse = CERT_DecodeOCSPResponse(encodedResponse); if (!*pDecodedResponse) { - return SECFailure; + return SECFailure; } /* @@ -5485,7 +5466,7 @@ ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle, * in the response. */ if (CERT_GetOCSPResponseStatus(*pDecodedResponse) != SECSuccess) { - goto loser; + goto loser; } /* @@ -5496,32 +5477,32 @@ ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle, rv = CERT_VerifyOCSPResponseSignature(*pDecodedResponse, handle, pwArg, &signerCert, issuerCert); if (rv != SECSuccess) { - goto loser; + goto loser; } - PORT_Assert(signerCert != NULL); /* internal consistency check */ + PORT_Assert(signerCert != NULL); /* internal consistency check */ /* XXX probably should set error, return failure if signerCert is null */ /* * Again, we are only doing one request for one cert. * XXX When we handle cert chains, the following code will obviously * have to be modified, in coordation with the code above that will - * have to determine how to make multiple requests, etc. + * have to determine how to make multiple requests, etc. */ - rv = ocsp_GetVerifiedSingleResponseForCertID(handle, *pDecodedResponse, certID, + rv = ocsp_GetVerifiedSingleResponseForCertID(handle, *pDecodedResponse, certID, signerCert, time, pSingle); loser: if (issuerCert != NULL) - CERT_DestroyCertificate(issuerCert); + CERT_DestroyCertificate(issuerCert); if (signerCert != NULL) - CERT_DestroyCertificate(signerCert); + CERT_DestroyCertificate(signerCert); return rv; } /* * FUNCTION: ocsp_CacheSingleResponse * This function requires that the caller has checked that the response - * is valid and verified. + * is valid and verified. * The (positive or negative) valid response will be used to update the cache. * INPUTS: * CERTOCSPCertID *certID @@ -5532,27 +5513,27 @@ loser: */ void ocsp_CacheSingleResponse(CERTOCSPCertID *certID, - CERTOCSPSingleResponse *single, - PRBool *certIDWasConsumed) + CERTOCSPSingleResponse *single, + PRBool *certIDWasConsumed) { if (single != NULL) { - PR_EnterMonitor(OCSP_Global.monitor); - if (OCSP_Global.maxCacheEntries >= 0) { - ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, single, - certIDWasConsumed); - /* ignore cache update failures */ - } - PR_ExitMonitor(OCSP_Global.monitor); + PR_EnterMonitor(OCSP_Global.monitor); + if (OCSP_Global.maxCacheEntries >= 0) { + ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, single, + certIDWasConsumed); + /* ignore cache update failures */ + } + PR_ExitMonitor(OCSP_Global.monitor); } } SECStatus -ocsp_GetVerifiedSingleResponseForCertID(CERTCertDBHandle *handle, - CERTOCSPResponse *response, - CERTOCSPCertID *certID, - CERTCertificate *signerCert, - PRTime time, - CERTOCSPSingleResponse +ocsp_GetVerifiedSingleResponseForCertID(CERTCertDBHandle *handle, + CERTOCSPResponse *response, + CERTOCSPCertID *certID, + CERTCertificate *signerCert, + PRTime time, + CERTOCSPSingleResponse **pSingleResponse) { SECStatus rv; @@ -5596,11 +5577,11 @@ loser: } SECStatus -CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, - CERTOCSPResponse *response, - CERTOCSPCertID *certID, - CERTCertificate *signerCert, - PRTime time) +CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, + CERTOCSPResponse *response, + CERTOCSPCertID *certID, + CERTCertificate *signerCert, + PRTime time) { /* * We do not update the cache, because: @@ -5612,17 +5593,17 @@ CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, * requires the ability to transfer ownership of the the given certID to * the cache. The external API doesn't allow us to prevent the caller from * destroying the certID. We don't have the original certificate available, - * therefore we are unable to produce another certID object (that could + * therefore we are unable to produce another certID object (that could * be stored in the cache). * * Should we ever implement code to produce a deep copy of certID, * then this could be changed to allow updating the cache. - * The duplication would have to be done in + * The duplication would have to be done in * cert_ProcessOCSPResponse, if the out parameter to indicate * a transfer of ownership is NULL. */ - return cert_ProcessOCSPResponse(handle, response, certID, - signerCert, time, + return cert_ProcessOCSPResponse(handle, response, certID, + signerCert, time, NULL, NULL); } @@ -5630,23 +5611,23 @@ CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, * The first 5 parameters match the definition of CERT_GetOCSPStatusForCertID. */ SECStatus -cert_ProcessOCSPResponse(CERTCertDBHandle *handle, - CERTOCSPResponse *response, - CERTOCSPCertID *certID, - CERTCertificate *signerCert, - PRTime time, - PRBool *certIDWasConsumed, - SECStatus *cacheUpdateStatus) +cert_ProcessOCSPResponse(CERTCertDBHandle *handle, + CERTOCSPResponse *response, + CERTOCSPCertID *certID, + CERTCertificate *signerCert, + PRTime time, + PRBool *certIDWasConsumed, + SECStatus *cacheUpdateStatus) { SECStatus rv; SECStatus rv_cache = SECSuccess; CERTOCSPSingleResponse *single = NULL; - rv = ocsp_GetVerifiedSingleResponseForCertID(handle, response, certID, + rv = ocsp_GetVerifiedSingleResponseForCertID(handle, response, certID, signerCert, time, &single); if (rv == SECSuccess) { /* - * Check whether the status says revoked, and if so + * Check whether the status says revoked, and if so * how that compares to the time value passed into this routine. */ rv = ocsp_SingleResponseCertHasGoodStatus(single, time); @@ -5654,15 +5635,15 @@ cert_ProcessOCSPResponse(CERTCertDBHandle *handle, if (certIDWasConsumed) { /* - * We don't have copy-of-certid implemented. In order to update - * the cache, the caller must supply an out variable + * We don't have copy-of-certid implemented. In order to update + * the cache, the caller must supply an out variable * certIDWasConsumed, allowing us to return ownership status. */ - + PR_EnterMonitor(OCSP_Global.monitor); if (OCSP_Global.maxCacheEntries >= 0) { /* single == NULL means: remember response failure */ - rv_cache = + rv_cache = ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, single, certIDWasConsumed); } @@ -5677,12 +5658,12 @@ cert_ProcessOCSPResponse(CERTCertDBHandle *handle, SECStatus cert_RememberOCSPProcessingFailure(CERTOCSPCertID *certID, - PRBool *certIDWasConsumed) + PRBool *certIDWasConsumed) { SECStatus rv = SECSuccess; PR_EnterMonitor(OCSP_Global.monitor); if (OCSP_Global.maxCacheEntries >= 0) { - rv = ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, NULL, + rv = ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, NULL, certIDWasConsumed); } PR_ExitMonitor(OCSP_Global.monitor); @@ -5705,12 +5686,12 @@ ocsp_DestroyStatusChecking(CERTStatusConfig *statusConfig) statusContext = statusConfig->statusContext; PORT_Assert(statusContext != NULL); if (statusContext == NULL) - return SECFailure; + return SECFailure; if (statusContext->defaultResponderURI != NULL) - PORT_Free(statusContext->defaultResponderURI); + PORT_Free(statusContext->defaultResponderURI); if (statusContext->defaultResponderNickname != NULL) - PORT_Free(statusContext->defaultResponderNickname); + PORT_Free(statusContext->defaultResponderNickname); PORT_Free(statusContext); statusConfig->statusContext = NULL; @@ -5720,7 +5701,6 @@ ocsp_DestroyStatusChecking(CERTStatusConfig *statusConfig) return SECSuccess; } - /* * FUNCTION: CERT_DisableOCSPChecking * Turns off OCSP checking for the given certificate database. @@ -5743,22 +5723,22 @@ CERT_DisableOCSPChecking(CERTCertDBHandle *handle) ocspCheckingContext *statusContext; if (handle == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } statusConfig = CERT_GetStatusConfig(handle); statusContext = ocsp_GetCheckingContext(handle); if (statusContext == NULL) - return SECFailure; + return SECFailure; if (statusConfig->statusChecker != CERT_CheckOCSPStatus) { - /* - * Status configuration is present, but either not currently - * enabled or not for OCSP. - */ - PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED); - return SECFailure; + /* + * Status configuration is present, but either not currently + * enabled or not for OCSP. + */ + PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED); + return SECFailure; } /* cache no longer necessary */ @@ -5786,17 +5766,17 @@ ocsp_InitStatusChecking(CERTCertDBHandle *handle) PORT_Assert(CERT_GetStatusConfig(handle) == NULL); if (CERT_GetStatusConfig(handle) != NULL) { - /* XXX or call statusConfig->statusDestroy and continue? */ - return SECFailure; + /* XXX or call statusConfig->statusDestroy and continue? */ + return SECFailure; } statusConfig = PORT_ZNew(CERTStatusConfig); if (statusConfig == NULL) - goto loser; + goto loser; statusContext = PORT_ZNew(ocspCheckingContext); if (statusContext == NULL) - goto loser; + goto loser; statusConfig->statusDestroy = ocsp_DestroyStatusChecking; statusConfig->statusContext = statusContext; @@ -5807,11 +5787,10 @@ ocsp_InitStatusChecking(CERTCertDBHandle *handle) loser: if (statusConfig != NULL) - PORT_Free(statusConfig); + PORT_Free(statusConfig); return SECFailure; } - /* * FUNCTION: CERT_EnableOCSPChecking * Turns on OCSP checking for the given certificate database. @@ -5826,23 +5805,23 @@ SECStatus CERT_EnableOCSPChecking(CERTCertDBHandle *handle) { CERTStatusConfig *statusConfig; - + SECStatus rv; if (handle == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } statusConfig = CERT_GetStatusConfig(handle); if (statusConfig == NULL) { - rv = ocsp_InitStatusChecking(handle); - if (rv != SECSuccess) - return rv; + rv = ocsp_InitStatusChecking(handle); + if (rv != SECSuccess) + return rv; - /* Get newly established value */ - statusConfig = CERT_GetStatusConfig(handle); - PORT_Assert(statusConfig != NULL); + /* Get newly established value */ + statusConfig = CERT_GetStatusConfig(handle); + PORT_Assert(statusConfig != NULL); } /* @@ -5854,7 +5833,6 @@ CERT_EnableOCSPChecking(CERTCertDBHandle *handle) return SECSuccess; } - /* * FUNCTION: CERT_SetOCSPDefaultResponder * Specify the location and cert of the default responder. @@ -5881,7 +5859,7 @@ CERT_EnableOCSPChecking(CERTCertDBHandle *handle) */ SECStatus CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, - const char *url, const char *name) + const char *url, const char *name) { CERTCertificate *cert; ocspCheckingContext *statusContext; @@ -5890,12 +5868,12 @@ CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, SECStatus rv; if (handle == NULL || url == NULL || name == NULL) { - /* - * XXX When interface is exported, probably want better errors; - * perhaps different one for each parameter. - */ - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + /* + * XXX When interface is exported, probably want better errors; + * perhaps different one for each parameter. + */ + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } /* @@ -5905,15 +5883,15 @@ CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, * XXX Shouldn't need that cast if the FindCertByNickname interface * used const to convey that it does not modify the name. Maybe someday. */ - cert = CERT_FindCertByNickname(handle, (char *) name); + cert = CERT_FindCertByNickname(handle, (char *)name); if (cert == NULL) { - /* - * look for the cert on an external token. - */ - cert = PK11_FindCertFromNickname((char *)name, NULL); + /* + * look for the cert on an external token. + */ + cert = PK11_FindCertFromNickname((char *)name, NULL); } if (cert == NULL) - return SECFailure; + return SECFailure; /* * Make a copy of the url and nickname. @@ -5921,8 +5899,8 @@ CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, url_copy = PORT_Strdup(url); name_copy = PORT_Strdup(name); if (url_copy == NULL || name_copy == NULL) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } statusContext = ocsp_GetCheckingContext(handle); @@ -5931,12 +5909,12 @@ CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, * Allocate and init the context if it doesn't already exist. */ if (statusContext == NULL) { - rv = ocsp_InitStatusChecking(handle); - if (rv != SECSuccess) - goto loser; + rv = ocsp_InitStatusChecking(handle); + if (rv != SECSuccess) + goto loser; - statusContext = ocsp_GetCheckingContext(handle); - PORT_Assert(statusContext != NULL); /* extreme paranoia */ + statusContext = ocsp_GetCheckingContext(handle); + PORT_Assert(statusContext != NULL); /* extreme paranoia */ } /* @@ -5949,9 +5927,9 @@ CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, * Get rid of old url and name if there. */ if (statusContext->defaultResponderNickname != NULL) - PORT_Free(statusContext->defaultResponderNickname); + PORT_Free(statusContext->defaultResponderNickname); if (statusContext->defaultResponderURI != NULL) - PORT_Free(statusContext->defaultResponderURI); + PORT_Free(statusContext->defaultResponderURI); /* * And replace them with the new ones. @@ -5966,13 +5944,14 @@ CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, * enabled. */ if (statusContext->defaultResponderCert != NULL) { - CERT_DestroyCertificate(statusContext->defaultResponderCert); - statusContext->defaultResponderCert = cert; + CERT_DestroyCertificate(statusContext->defaultResponderCert); + statusContext->defaultResponderCert = cert; /*OCSP enabled, switching responder: clear cache*/ CERT_ClearOCSPCache(); - } else { - PORT_Assert(statusContext->useDefaultResponder == PR_FALSE); - CERT_DestroyCertificate(cert); + } + else { + PORT_Assert(statusContext->useDefaultResponder == PR_FALSE); + CERT_DestroyCertificate(cert); /*OCSP currently not enabled, no need to clear cache*/ } @@ -5981,13 +5960,12 @@ CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, loser: CERT_DestroyCertificate(cert); if (url_copy != NULL) - PORT_Free(url_copy); + PORT_Free(url_copy); if (name_copy != NULL) - PORT_Free(name_copy); + PORT_Free(name_copy); return rv; } - /* * FUNCTION: CERT_EnableOCSPDefaultResponder * Turns on use of a default responder when OCSP checking. @@ -6014,36 +5992,36 @@ CERT_EnableOCSPDefaultResponder(CERTCertDBHandle *handle) SECCertificateUsage usage; if (handle == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } statusContext = ocsp_GetCheckingContext(handle); if (statusContext == NULL) { - /* - * Strictly speaking, the error already set is "correct", - * but cover over it with one more helpful in this context. - */ - PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); - return SECFailure; + /* + * Strictly speaking, the error already set is "correct", + * but cover over it with one more helpful in this context. + */ + PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); + return SECFailure; } if (statusContext->defaultResponderURI == NULL) { - PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); - return SECFailure; + PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); + return SECFailure; } if (statusContext->defaultResponderNickname == NULL) { - PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); - return SECFailure; + PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER); + return SECFailure; } /* * Find the cert for the nickname. */ cert = CERT_FindCertByNickname(handle, - statusContext->defaultResponderNickname); + statusContext->defaultResponderNickname); if (cert == NULL) { cert = PK11_FindCertFromNickname(statusContext->defaultResponderNickname, NULL); @@ -6054,13 +6032,13 @@ CERT_EnableOCSPDefaultResponder(CERTCertDBHandle *handle) */ PORT_Assert(cert != NULL); if (cert == NULL) - return SECFailure; + return SECFailure; - /* - * Supplied cert should at least have a signing capability in order for us - * to use it as a trusted responder cert. Ability to sign is guaranteed if - * cert is validated to have any set of the usages below. - */ + /* + * Supplied cert should at least have a signing capability in order for us + * to use it as a trusted responder cert. Ability to sign is guaranteed if + * cert is validated to have any set of the usages below. + */ rv = CERT_VerifyCertificateNow(handle, cert, PR_TRUE, certificateUsageCheckAllUsages, NULL, &usage); @@ -6071,8 +6049,8 @@ CERT_EnableOCSPDefaultResponder(CERTCertDBHandle *handle) certificateUsageObjectSigner | certificateUsageStatusResponder | certificateUsageSSLCA)) == 0) { - PORT_SetError(SEC_ERROR_OCSP_RESPONDER_CERT_INVALID); - return SECFailure; + PORT_SetError(SEC_ERROR_OCSP_RESPONDER_CERT_INVALID); + return SECFailure; } /* @@ -6090,7 +6068,6 @@ CERT_EnableOCSPDefaultResponder(CERTCertDBHandle *handle) return SECSuccess; } - /* * FUNCTION: CERT_DisableOCSPDefaultResponder * Turns off use of a default responder when OCSP checking. @@ -6111,23 +6088,23 @@ CERT_DisableOCSPDefaultResponder(CERTCertDBHandle *handle) CERTCertificate *tmpCert; if (handle == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } statusConfig = CERT_GetStatusConfig(handle); if (statusConfig == NULL) - return SECSuccess; + return SECSuccess; statusContext = ocsp_GetCheckingContext(handle); PORT_Assert(statusContext != NULL); if (statusContext == NULL) - return SECFailure; + return SECFailure; tmpCert = statusContext->defaultResponderCert; if (tmpCert) { - statusContext->defaultResponderCert = NULL; - CERT_DestroyCertificate(tmpCert); + statusContext->defaultResponderCert = NULL; + CERT_DestroyCertificate(tmpCert); /* we don't allow a mix of cache entries from different responders */ CERT_ClearOCSPCache(); } @@ -6159,29 +6136,29 @@ CERT_GetOCSPResponseStatus(CERTOCSPResponse *response) { PORT_Assert(response); if (response->statusValue == ocspResponse_successful) - return SECSuccess; + return SECSuccess; switch (response->statusValue) { - case ocspResponse_malformedRequest: - PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); - break; - case ocspResponse_internalError: - PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); - break; - case ocspResponse_tryLater: - PORT_SetError(SEC_ERROR_OCSP_TRY_SERVER_LATER); - break; - case ocspResponse_sigRequired: - /* XXX We *should* retry with a signature, if possible. */ - PORT_SetError(SEC_ERROR_OCSP_REQUEST_NEEDS_SIG); - break; - case ocspResponse_unauthorized: - PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST); - break; - case ocspResponse_unused: - default: - PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS); - break; + case ocspResponse_malformedRequest: + PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST); + break; + case ocspResponse_internalError: + PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR); + break; + case ocspResponse_tryLater: + PORT_SetError(SEC_ERROR_OCSP_TRY_SERVER_LATER); + break; + case ocspResponse_sigRequired: + /* XXX We *should* retry with a signature, if possible. */ + PORT_SetError(SEC_ERROR_OCSP_REQUEST_NEEDS_SIG); + break; + case ocspResponse_unauthorized: + PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST); + break; + case ocspResponse_unused: + default: + PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS); + break; } return SECFailure; } diff --git a/security/nss/lib/certhigh/ocsp.h b/security/nss/lib/certhigh/ocsp.h index 75225eb036dd..ac9dd6465675 100644 --- a/security/nss/lib/certhigh/ocsp.h +++ b/security/nss/lib/certhigh/ocsp.h @@ -9,7 +9,6 @@ #ifndef _OCSP_H_ #define _OCSP_H_ - #include "plarena.h" #include "seccomon.h" #include "secoidt.h" @@ -17,7 +16,6 @@ #include "certt.h" #include "ocspt.h" - /************************************************************************/ SEC_BEGIN_PROTOS @@ -134,7 +132,7 @@ CERT_DisableOCSPChecking(CERTCertDBHandle *handle); */ extern SECStatus CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle, - const char *url, const char *name); + const char *url, const char *name); /* * FUNCTION: CERT_EnableOCSPDefaultResponder @@ -174,7 +172,7 @@ CERT_DisableOCSPDefaultResponder(CERTCertDBHandle *handle); /* If forcePost is set, OCSP requests will only be sent using the HTTP POST * method. When forcePost is not set, OCSP requests will be sent using the * HTTP GET method, with a fallback to POST when we fail to receive a response - * and/or when we receive an uncacheable response like "Unknown." + * and/or when we receive an uncacheable response like "Unknown." * * The default is to use GET and fallback to POST. */ @@ -191,7 +189,7 @@ extern SECStatus CERT_ForcePostMethodForOCSP(PRBool forcePost); /* * FUNCTION: CERT_CreateOCSPRequest - * Creates a CERTOCSPRequest, requesting the status of the certs in + * Creates a CERTOCSPRequest, requesting the status of the certs in * the given list. * INPUTS: * CERTCertList *certList @@ -203,7 +201,7 @@ extern SECStatus CERT_ForcePostMethodForOCSP(PRBool forcePost); * to this routine), who knows about where the request(s) are being * sent and whether there are any trusted responders in place. * PRTime time - * Indicates the time for which the certificate status is to be + * Indicates the time for which the certificate status is to be * determined -- this may be used in the search for the cert's issuer * but has no effect on the request itself. * PRBool addServiceLocator @@ -221,9 +219,9 @@ extern SECStatus CERT_ForcePostMethodForOCSP(PRBool forcePost); * Other errors are low-level problems (no memory, bad database, etc.). */ extern CERTOCSPRequest * -CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, - PRBool addServiceLocator, - CERTCertificate *signerCert); +CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, + PRBool addServiceLocator, + CERTCertificate *signerCert); /* * FUNCTION: CERT_AddOCSPAcceptableResponses @@ -243,13 +241,13 @@ CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, */ extern SECStatus CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request, - SECOidTag responseType0, ...); + SECOidTag responseType0, ...); -/* +/* * FUNCTION: CERT_EncodeOCSPRequest * DER encodes an OCSP Request, possibly adding a signature as well. * XXX Signing is not yet supported, however; see comments in code. - * INPUTS: + * INPUTS: * PLArenaPool *arena * The return value is allocated from here. * If a NULL is passed in, allocation is done from the heap instead. @@ -264,8 +262,8 @@ CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request, * (e.g. no memory). */ extern SECItem * -CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request, - void *pwArg); +CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request, + void *pwArg); /* * FUNCTION: CERT_DecodeOCSPRequest @@ -341,7 +339,7 @@ CERT_DestroyOCSPResponse(CERTOCSPResponse *response); * const char *location * The location of the OCSP responder (a URL). * PRTime time - * Indicates the time for which the certificate status is to be + * Indicates the time for which the certificate status is to be * determined -- this may be used in the search for the cert's issuer * but has no other bearing on the operation. * PRBool addServiceLocator @@ -369,10 +367,10 @@ CERT_DestroyOCSPResponse(CERTOCSPResponse *response); */ extern SECItem * CERT_GetEncodedOCSPResponse(PLArenaPool *arena, CERTCertList *certList, - const char *location, PRTime time, - PRBool addServiceLocator, - CERTCertificate *signerCert, void *pwArg, - CERTOCSPRequest **pRequest); + const char *location, PRTime time, + PRBool addServiceLocator, + CERTCertificate *signerCert, void *pwArg, + CERTOCSPRequest **pRequest); /* * FUNCTION: CERT_VerifyOCSPResponseSignature @@ -406,10 +404,10 @@ CERT_GetEncodedOCSPResponse(PLArenaPool *arena, CERTCertList *certList, * verifying the signer's cert, or low-level problems (no memory, etc.) */ extern SECStatus -CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, - CERTCertDBHandle *handle, void *pwArg, - CERTCertificate **pSignerCert, - CERTCertificate *issuerCert); +CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, + CERTCertDBHandle *handle, void *pwArg, + CERTCertificate **pSignerCert, + CERTCertificate *issuerCert); /* * FUNCTION: CERT_GetOCSPAuthorityInfoAccessLocation @@ -425,7 +423,7 @@ CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response, * extension is not present or it does not contain an entry for OCSP, * SEC_ERROR_EXTENSION_NOT_FOUND will be set and a NULL returned. * Any other error will also result in a NULL being returned. - * + * * This result should be freed (via PORT_Free) when no longer in use. */ extern char * @@ -433,21 +431,21 @@ CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert); /* * FUNCTION: CERT_RegisterAlternateOCSPAIAInfoCallBack - * This function serves two purposes. - * 1) It registers the address of a callback function that will be - * called for certs that have no OCSP AIA extension, to see if the + * This function serves two purposes. + * 1) It registers the address of a callback function that will be + * called for certs that have no OCSP AIA extension, to see if the * callback wishes to supply an alternative URL for such an OCSP inquiry. - * 2) It outputs the previously registered function's address to the + * 2) It outputs the previously registered function's address to the * address supplied by the caller, unless that is NULL. - * The registered callback function returns NULL, or an allocated string + * The registered callback function returns NULL, or an allocated string * that may be subsequently freed by calling PORT_Free(). * RETURN: * SECSuccess or SECFailure (if the library is not yet intialized) */ extern SECStatus CERT_RegisterAlternateOCSPAIAInfoCallBack( - CERT_StringFromCertFcn newCallback, - CERT_StringFromCertFcn * oldCallback); + CERT_StringFromCertFcn newCallback, + CERT_StringFromCertFcn *oldCallback); /* * FUNCTION: CERT_ParseURL @@ -521,10 +519,10 @@ CERT_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath); * (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when * verifying the signer's cert, or low-level problems (error allocating * memory, error performing ASN.1 decoding, etc.). - */ -extern SECStatus + */ +extern SECStatus CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, - PRTime time, void *pwArg); + PRTime time, void *pwArg); /* * FUNCTION: CERT_CacheOCSPResponseFromSideChannel @@ -556,10 +554,10 @@ CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert, */ extern SECStatus CERT_CacheOCSPResponseFromSideChannel(CERTCertDBHandle *handle, - CERTCertificate *cert, - PRTime time, - const SECItem *encodedResponse, - void *pwArg); + CERTCertificate *cert, + PRTime time, + const SECItem *encodedResponse, + void *pwArg); /* * FUNCTION: CERT_GetOCSPStatusForCertID @@ -581,11 +579,11 @@ CERT_CacheOCSPResponseFromSideChannel(CERTCertDBHandle *handle, * Return values are the same as those for CERT_CheckOCSPStatus */ extern SECStatus -CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, - CERTOCSPResponse *response, - CERTOCSPCertID *certID, - CERTCertificate *signerCert, - PRTime time); +CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, + CERTOCSPResponse *response, + CERTOCSPCertID *certID, + CERTCertificate *signerCert, + PRTime time); /* * FUNCTION CERT_GetOCSPResponseStatus @@ -619,10 +617,10 @@ CERT_GetOCSPResponseStatus(CERTOCSPResponse *response); * the issuing CA may be an older expired certificate. * RETURN: * A new copy of a CERTOCSPCertID*. The memory for this certID - * should be freed by calling CERT_DestroyOCSPCertID when the + * should be freed by calling CERT_DestroyOCSPCertID when the * certID is no longer necessary. */ -extern CERTOCSPCertID* +extern CERTOCSPCertID * CERT_CreateOCSPCertID(CERTCertificate *cert, PRTime time); /* @@ -630,7 +628,7 @@ CERT_CreateOCSPCertID(CERTCertificate *cert, PRTime time); * Frees the memory associated with the certID passed in. * INPUTS: * CERTOCSPCertID* certID - * The certID that the caller no longer needs and wants to + * The certID that the caller no longer needs and wants to * free the associated memory. * RETURN: * SECSuccess if freeing the memory was successful. Returns @@ -638,31 +636,30 @@ CERT_CreateOCSPCertID(CERTCertificate *cert, PRTime time); * a call to CERT_CreateOCSPCertID. */ extern SECStatus -CERT_DestroyOCSPCertID(CERTOCSPCertID* certID); +CERT_DestroyOCSPCertID(CERTOCSPCertID *certID); - -extern CERTOCSPSingleResponse* +extern CERTOCSPSingleResponse * CERT_CreateOCSPSingleResponseGood(PLArenaPool *arena, CERTOCSPCertID *id, PRTime thisUpdate, const PRTime *nextUpdate); -extern CERTOCSPSingleResponse* +extern CERTOCSPSingleResponse * CERT_CreateOCSPSingleResponseUnknown(PLArenaPool *arena, CERTOCSPCertID *id, PRTime thisUpdate, const PRTime *nextUpdate); -extern CERTOCSPSingleResponse* +extern CERTOCSPSingleResponse * CERT_CreateOCSPSingleResponseRevoked( PLArenaPool *arena, CERTOCSPCertID *id, PRTime thisUpdate, const PRTime *nextUpdate, PRTime revocationTime, - const CERTCRLEntryReasonCode* revocationReason); + const CERTCRLEntryReasonCode *revocationReason); -extern SECItem* +extern SECItem * CERT_CreateEncodedOCSPSuccessResponse( PLArenaPool *arena, CERTCertificate *responderCert, @@ -703,7 +700,7 @@ CERT_CreateEncodedOCSPSuccessResponse( * SEC_ERROR_INVALID_ARGS * Other errors are low-level problems (no memory, bad database, etc.). */ -extern SECItem* +extern SECItem * CERT_CreateEncodedOCSPErrorResponse(PLArenaPool *arena, int error); /* Sends an OCSP request using the HTTP POST method to the location addressed @@ -717,7 +714,7 @@ CERT_CreateEncodedOCSPErrorResponse(PLArenaPool *arena, int error); * SEC_RegisterDefaultHttpClient then that client is used. Otherwise, an * internal HTTP client is used. */ -SECItem* CERT_PostOCSPRequest(PLArenaPool *arena, const char *location, +SECItem *CERT_PostOCSPRequest(PLArenaPool *arena, const char *location, const SECItem *encodedRequest); /************************************************************************/ diff --git a/security/nss/lib/certhigh/ocspi.h b/security/nss/lib/certhigh/ocspi.h index 01c20daec5a5..c946d9f51c9f 100644 --- a/security/nss/lib/certhigh/ocspi.h +++ b/security/nss/lib/certhigh/ocspi.h @@ -35,13 +35,15 @@ ocsp_VerifyResponseSignature(CERTCertificate *signerCert, void *pwArg); CERTOCSPRequest * -cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, - CERTCertificate *singleCert, +cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID, + CERTCertificate *singleCert, PRTime time, PRBool addServiceLocator, CERTCertificate *signerCert); -typedef enum { ocspMissing, ocspFresh, ocspStale } OCSPFreshness; +typedef enum { ocspMissing, + ocspFresh, + ocspStale } OCSPFreshness; SECStatus ocsp_GetCachedOCSPResponseStatus(CERTOCSPCertID *certID, @@ -84,13 +86,13 @@ ocsp_GetCachedOCSPResponseStatus(CERTOCSPCertID *certID, */ SECStatus -cert_ProcessOCSPResponse(CERTCertDBHandle *handle, - CERTOCSPResponse *response, - CERTOCSPCertID *certID, - CERTCertificate *signerCert, - PRTime time, - PRBool *certIDWasConsumed, - SECStatus *cacheUpdateStatus); +cert_ProcessOCSPResponse(CERTCertDBHandle *handle, + CERTOCSPResponse *response, + CERTOCSPCertID *certID, + CERTCertificate *signerCert, + PRTime time, + PRBool *certIDWasConsumed, + SECStatus *cacheUpdateStatus); /* * FUNCTION: cert_RememberOCSPProcessingFailure @@ -109,7 +111,7 @@ cert_ProcessOCSPResponse(CERTCertDBHandle *handle, SECStatus cert_RememberOCSPProcessingFailure(CERTOCSPCertID *certID, - PRBool *certIDWasConsumed); + PRBool *certIDWasConsumed); /* * FUNCTION: ocsp_GetResponderLocation @@ -146,11 +148,11 @@ size_t ocsp_UrlEncodeBase64Buf(const char *base64Buf, char *outputBuf); SECStatus -ocsp_GetVerifiedSingleResponseForCertID(CERTCertDBHandle *handle, - CERTOCSPResponse *response, - CERTOCSPCertID *certID, - CERTCertificate *signerCert, - PRTime time, +ocsp_GetVerifiedSingleResponseForCertID(CERTCertDBHandle *handle, + CERTOCSPResponse *response, + CERTOCSPCertID *certID, + CERTCertificate *signerCert, + PRTime time, CERTOCSPSingleResponse **pSingleResponse); SECStatus @@ -158,7 +160,7 @@ ocsp_CertHasGoodStatus(ocspCertStatus *status, PRTime time); void ocsp_CacheSingleResponse(CERTOCSPCertID *certID, - CERTOCSPSingleResponse *single, - PRBool *certIDWasConsumed); + CERTOCSPSingleResponse *single, + PRBool *certIDWasConsumed); #endif /* _OCSPI_H_ */ diff --git a/security/nss/lib/certhigh/ocspsig.c b/security/nss/lib/certhigh/ocspsig.c index 0c4c2019523c..958dee02979f 100644 --- a/security/nss/lib/certhigh/ocspsig.c +++ b/security/nss/lib/certhigh/ocspsig.c @@ -19,12 +19,11 @@ #include "ocspi.h" #include "pk11pub.h" - extern const SEC_ASN1Template ocsp_ResponderIDByNameTemplate[]; extern const SEC_ASN1Template ocsp_ResponderIDByKeyTemplate[]; extern const SEC_ASN1Template ocsp_OCSPResponseTemplate[]; -ocspCertStatus* +ocspCertStatus * ocsp_CreateCertStatus(PLArenaPool *arena, ocspCertStatusType status, PRTime revocationTime) @@ -45,7 +44,7 @@ ocsp_CreateCertStatus(PLArenaPool *arena, PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; } - + cs = PORT_ArenaZNew(arena, ocspCertStatus); if (!cs) return NULL; @@ -71,8 +70,9 @@ ocsp_CreateCertStatus(PLArenaPool *arena, if (!cs->certStatusInfo.revokedInfo->revocationReason) return NULL; if (DER_TimeToGeneralizedTimeArena(arena, - &cs->certStatusInfo.revokedInfo->revocationTime, - revocationTime) != SECSuccess) + &cs->certStatusInfo.revokedInfo->revocationTime, + revocationTime) != + SECSuccess) return NULL; break; default: @@ -91,11 +91,11 @@ static const SEC_ASN1Template mySEC_PointerToEnumeratedTemplate[] = { static const SEC_ASN1Template ocsp_EncodeRevokedInfoTemplate[] = { { SEC_ASN1_GENERALIZED_TIME, - offsetof(ocspRevokedInfo, revocationTime) }, + offsetof(ocspRevokedInfo, revocationTime) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC| 0, - offsetof(ocspRevokedInfo, revocationReason), - mySEC_PointerToEnumeratedTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(ocspRevokedInfo, revocationReason), + mySEC_PointerToEnumeratedTemplate }, { 0 } }; @@ -110,26 +110,26 @@ static const SEC_ASN1Template mySEC_NullTemplate[] = { static const SEC_ASN1Template ocsp_CertStatusTemplate[] = { { SEC_ASN1_CHOICE, offsetof(ocspCertStatus, certStatusType), - 0, sizeof(ocspCertStatus) }, + 0, sizeof(ocspCertStatus) }, { SEC_ASN1_CONTEXT_SPECIFIC | 0, - 0, mySEC_NullTemplate, ocspCertStatus_good }, + 0, mySEC_NullTemplate, ocspCertStatus_good }, { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(ocspCertStatus, certStatusInfo.revokedInfo), - ocsp_PointerToEncodeRevokedInfoTemplate, ocspCertStatus_revoked }, + SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(ocspCertStatus, certStatusInfo.revokedInfo), + ocsp_PointerToEncodeRevokedInfoTemplate, ocspCertStatus_revoked }, { SEC_ASN1_CONTEXT_SPECIFIC | 2, - 0, mySEC_NullTemplate, ocspCertStatus_unknown }, + 0, mySEC_NullTemplate, ocspCertStatus_unknown }, { 0 } }; static const SEC_ASN1Template mySECOID_AlgorithmIDTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SECAlgorithmID) }, + 0, NULL, sizeof(SECAlgorithmID) }, { SEC_ASN1_OBJECT_ID, - offsetof(SECAlgorithmID,algorithm), }, + offsetof(SECAlgorithmID, algorithm) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, - offsetof(SECAlgorithmID,parameters), }, - { 0, } + offsetof(SECAlgorithmID, parameters) }, + { 0 } }; static const SEC_ASN1Template mySEC_AnyTemplate[] = { @@ -153,7 +153,7 @@ static const SEC_ASN1Template mySEC_PointerToIntegerTemplate[] = { }; static const SEC_ASN1Template mySEC_GeneralizedTimeTemplate[] = { - { SEC_ASN1_GENERALIZED_TIME | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SECItem)} + { SEC_ASN1_GENERALIZED_TIME | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SECItem) } }; static const SEC_ASN1Template mySEC_PointerToGeneralizedTimeTemplate[] = { @@ -162,29 +162,29 @@ static const SEC_ASN1Template mySEC_PointerToGeneralizedTimeTemplate[] = { static const SEC_ASN1Template ocsp_myCertIDTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTOCSPCertID) }, + 0, NULL, sizeof(CERTOCSPCertID) }, { SEC_ASN1_INLINE, - offsetof(CERTOCSPCertID, hashAlgorithm), - mySECOID_AlgorithmIDTemplate }, + offsetof(CERTOCSPCertID, hashAlgorithm), + mySECOID_AlgorithmIDTemplate }, { SEC_ASN1_OCTET_STRING, - offsetof(CERTOCSPCertID, issuerNameHash) }, + offsetof(CERTOCSPCertID, issuerNameHash) }, { SEC_ASN1_OCTET_STRING, - offsetof(CERTOCSPCertID, issuerKeyHash) }, + offsetof(CERTOCSPCertID, issuerKeyHash) }, { SEC_ASN1_INTEGER, - offsetof(CERTOCSPCertID, serialNumber) }, + offsetof(CERTOCSPCertID, serialNumber) }, { 0 } }; static const SEC_ASN1Template myCERT_CertExtensionTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTCertExtension) }, + 0, NULL, sizeof(CERTCertExtension) }, { SEC_ASN1_OBJECT_ID, - offsetof(CERTCertExtension,id) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ - offsetof(CERTCertExtension,critical) }, + offsetof(CERTCertExtension, id) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ + offsetof(CERTCertExtension, critical) }, { SEC_ASN1_OCTET_STRING, - offsetof(CERTCertExtension,value) }, - { 0, } + offsetof(CERTCertExtension, value) }, + { 0 } }; static const SEC_ASN1Template myCERT_SequenceOfCertExtensionTemplate[] = { @@ -197,66 +197,65 @@ static const SEC_ASN1Template myCERT_PointerToSequenceOfCertExtensionTemplate[] static const SEC_ASN1Template ocsp_mySingleResponseTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTOCSPSingleResponse) }, + 0, NULL, sizeof(CERTOCSPSingleResponse) }, { SEC_ASN1_POINTER, - offsetof(CERTOCSPSingleResponse, certID), - ocsp_myCertIDTemplate }, + offsetof(CERTOCSPSingleResponse, certID), + ocsp_myCertIDTemplate }, { SEC_ASN1_ANY, - offsetof(CERTOCSPSingleResponse, derCertStatus) }, + offsetof(CERTOCSPSingleResponse, derCertStatus) }, { SEC_ASN1_GENERALIZED_TIME, - offsetof(CERTOCSPSingleResponse, thisUpdate) }, + offsetof(CERTOCSPSingleResponse, thisUpdate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(CERTOCSPSingleResponse, nextUpdate), - mySEC_PointerToGeneralizedTimeTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(CERTOCSPSingleResponse, nextUpdate), + mySEC_PointerToGeneralizedTimeTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(CERTOCSPSingleResponse, singleExtensions), - myCERT_PointerToSequenceOfCertExtensionTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(CERTOCSPSingleResponse, singleExtensions), + myCERT_PointerToSequenceOfCertExtensionTemplate }, { 0 } }; static const SEC_ASN1Template ocsp_myResponseDataTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspResponseData) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(ocspResponseData, version), - mySEC_PointerToIntegerTemplate }, + 0, NULL, sizeof(ocspResponseData) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */ + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(ocspResponseData, version), + mySEC_PointerToIntegerTemplate }, { SEC_ASN1_ANY, - offsetof(ocspResponseData, derResponderID) }, + offsetof(ocspResponseData, derResponderID) }, { SEC_ASN1_GENERALIZED_TIME, - offsetof(ocspResponseData, producedAt) }, + offsetof(ocspResponseData, producedAt) }, { SEC_ASN1_SEQUENCE_OF, - offsetof(ocspResponseData, responses), - ocsp_mySingleResponseTemplate }, + offsetof(ocspResponseData, responses), + ocsp_mySingleResponseTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(ocspResponseData, responseExtensions), - myCERT_PointerToSequenceOfCertExtensionTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(ocspResponseData, responseExtensions), + myCERT_PointerToSequenceOfCertExtensionTemplate }, { 0 } }; - static const SEC_ASN1Template ocsp_EncodeBasicOCSPResponseTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(ocspBasicOCSPResponse) }, + 0, NULL, sizeof(ocspBasicOCSPResponse) }, { SEC_ASN1_POINTER, - offsetof(ocspBasicOCSPResponse, tbsResponseData), - ocsp_myResponseDataTemplate }, + offsetof(ocspBasicOCSPResponse, tbsResponseData), + ocsp_myResponseDataTemplate }, { SEC_ASN1_INLINE, - offsetof(ocspBasicOCSPResponse, responseSignature.signatureAlgorithm), - mySECOID_AlgorithmIDTemplate }, + offsetof(ocspBasicOCSPResponse, responseSignature.signatureAlgorithm), + mySECOID_AlgorithmIDTemplate }, { SEC_ASN1_BIT_STRING, - offsetof(ocspBasicOCSPResponse, responseSignature.signature) }, + offsetof(ocspBasicOCSPResponse, responseSignature.signature) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(ocspBasicOCSPResponse, responseSignature.derCerts), - mySEC_PointerToSequenceOfAnyTemplate }, + SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(ocspBasicOCSPResponse, responseSignature.derCerts), + mySEC_PointerToSequenceOfAnyTemplate }, { 0 } }; -static CERTOCSPSingleResponse* +static CERTOCSPSingleResponse * ocsp_CreateSingleResponse(PLArenaPool *arena, CERTOCSPCertID *id, ocspCertStatus *status, PRTime thisUpdate, const PRTime *nextUpdate) @@ -274,25 +273,25 @@ ocsp_CreateSingleResponse(PLArenaPool *arena, sr->arena = arena; sr->certID = id; sr->certStatus = status; - if (DER_TimeToGeneralizedTimeArena(arena, &sr->thisUpdate, thisUpdate) - != SECSuccess) + if (DER_TimeToGeneralizedTimeArena(arena, &sr->thisUpdate, thisUpdate) != + SECSuccess) return NULL; sr->nextUpdate = NULL; if (nextUpdate) { sr->nextUpdate = SECITEM_AllocItem(arena, NULL, 0); if (!sr->nextUpdate) return NULL; - if (DER_TimeToGeneralizedTimeArena(arena, sr->nextUpdate, *nextUpdate) - != SECSuccess) + if (DER_TimeToGeneralizedTimeArena(arena, sr->nextUpdate, *nextUpdate) != + SECSuccess) return NULL; } - sr->singleExtensions = PORT_ArenaNewArray(arena, CERTCertExtension*, 1); + sr->singleExtensions = PORT_ArenaNewArray(arena, CERTCertExtension *, 1); if (!sr->singleExtensions) return NULL; sr->singleExtensions[0] = NULL; - + if (!SEC_ASN1EncodeItem(arena, &sr->derCertStatus, status, ocsp_CertStatusTemplate)) return NULL; @@ -300,13 +299,13 @@ ocsp_CreateSingleResponse(PLArenaPool *arena, return sr; } -CERTOCSPSingleResponse* +CERTOCSPSingleResponse * CERT_CreateOCSPSingleResponseGood(PLArenaPool *arena, CERTOCSPCertID *id, PRTime thisUpdate, const PRTime *nextUpdate) { - ocspCertStatus * cs; + ocspCertStatus *cs; if (!arena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; @@ -317,13 +316,13 @@ CERT_CreateOCSPSingleResponseGood(PLArenaPool *arena, return ocsp_CreateSingleResponse(arena, id, cs, thisUpdate, nextUpdate); } -CERTOCSPSingleResponse* +CERTOCSPSingleResponse * CERT_CreateOCSPSingleResponseUnknown(PLArenaPool *arena, CERTOCSPCertID *id, PRTime thisUpdate, const PRTime *nextUpdate) { - ocspCertStatus * cs; + ocspCertStatus *cs; if (!arena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; @@ -334,16 +333,16 @@ CERT_CreateOCSPSingleResponseUnknown(PLArenaPool *arena, return ocsp_CreateSingleResponse(arena, id, cs, thisUpdate, nextUpdate); } -CERTOCSPSingleResponse* +CERTOCSPSingleResponse * CERT_CreateOCSPSingleResponseRevoked( PLArenaPool *arena, CERTOCSPCertID *id, PRTime thisUpdate, const PRTime *nextUpdate, PRTime revocationTime, - const CERTCRLEntryReasonCode* revocationReason) + const CERTCRLEntryReasonCode *revocationReason) { - ocspCertStatus * cs; + ocspCertStatus *cs; /* revocationReason is not yet supported, so it must be NULL. */ if (!arena || revocationReason) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -357,7 +356,7 @@ CERT_CreateOCSPSingleResponseRevoked( /* responderCert == 0 means: * create a response with an invalid signature (for testing purposes) */ -SECItem* +SECItem * CERT_CreateEncodedOCSPSuccessResponse( PLArenaPool *arena, CERTCertificate *responderCert, @@ -373,12 +372,12 @@ CERT_CreateEncodedOCSPSuccessResponse( ocspBasicOCSPResponse *br = NULL; ocspResponseBytes *rb = NULL; CERTOCSPResponse *response = NULL; - + SECOidTag algID; SECOidData *od = NULL; SECKEYPrivateKey *privKey = NULL; SECItem *result = NULL; - + if (!arena || !responses) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; @@ -408,114 +407,114 @@ CERT_CreateEncodedOCSPSuccessResponse( response = PORT_ArenaZNew(tmpArena, CERTOCSPResponse); if (!response) goto done; - - rd->version.data=NULL; - rd->version.len=0; + + rd->version.data = NULL; + rd->version.len = 0; rd->responseExtensions = NULL; rd->responses = responses; - if (DER_TimeToGeneralizedTimeArena(tmpArena, &rd->producedAt, producedAt) - != SECSuccess) + if (DER_TimeToGeneralizedTimeArena(tmpArena, &rd->producedAt, producedAt) != + SECSuccess) goto done; if (!responderCert) { - /* use invalid signature for testing purposes */ - unsigned char dummyChar = 'd'; - SECItem dummy; + /* use invalid signature for testing purposes */ + unsigned char dummyChar = 'd'; + SECItem dummy; - dummy.len = 1; - dummy.data = &dummyChar; + dummy.len = 1; + dummy.data = &dummyChar; - /* it's easier to produdce a keyHash out of nowhere, - * than to produce an encoded subject, - * so for our dummy response we always use byKey - */ - - rid->responderIDType = ocspResponderID_byKey; - if (!ocsp_DigestValue(tmpArena, SEC_OID_SHA1, &rid->responderIDValue.keyHash, - &dummy)) - goto done; + /* it's easier to produdce a keyHash out of nowhere, + * than to produce an encoded subject, + * so for our dummy response we always use byKey + */ - if (!SEC_ASN1EncodeItem(tmpArena, &rd->derResponderID, rid, - ocsp_ResponderIDByKeyTemplate)) - goto done; + rid->responderIDType = ocspResponderID_byKey; + if (!ocsp_DigestValue(tmpArena, SEC_OID_SHA1, &rid->responderIDValue.keyHash, + &dummy)) + goto done; - br->tbsResponseData = rd; + if (!SEC_ASN1EncodeItem(tmpArena, &rd->derResponderID, rid, + ocsp_ResponderIDByKeyTemplate)) + goto done; - if (!SEC_ASN1EncodeItem(tmpArena, &br->tbsResponseDataDER, br->tbsResponseData, - ocsp_myResponseDataTemplate)) - goto done; + br->tbsResponseData = rd; - br->responseSignature.derCerts = PORT_ArenaNewArray(tmpArena, SECItem*, 1); - if (!br->responseSignature.derCerts) - goto done; - br->responseSignature.derCerts[0] = NULL; + if (!SEC_ASN1EncodeItem(tmpArena, &br->tbsResponseDataDER, br->tbsResponseData, + ocsp_myResponseDataTemplate)) + goto done; - algID = SEC_GetSignatureAlgorithmOidTag(rsaKey, SEC_OID_SHA1); - if (algID == SEC_OID_UNKNOWN) - goto done; + br->responseSignature.derCerts = PORT_ArenaNewArray(tmpArena, SECItem *, 1); + if (!br->responseSignature.derCerts) + goto done; + br->responseSignature.derCerts[0] = NULL; - /* match the regular signature code, which doesn't use the arena */ - if (!SECITEM_AllocItem(NULL, &br->responseSignature.signature, 1)) - goto done; - PORT_Memcpy(br->responseSignature.signature.data, &dummyChar, 1); + algID = SEC_GetSignatureAlgorithmOidTag(rsaKey, SEC_OID_SHA1); + if (algID == SEC_OID_UNKNOWN) + goto done; - /* convert len-in-bytes to len-in-bits */ - br->responseSignature.signature.len = br->responseSignature.signature.len << 3; + /* match the regular signature code, which doesn't use the arena */ + if (!SECITEM_AllocItem(NULL, &br->responseSignature.signature, 1)) + goto done; + PORT_Memcpy(br->responseSignature.signature.data, &dummyChar, 1); + + /* convert len-in-bytes to len-in-bits */ + br->responseSignature.signature.len = br->responseSignature.signature.len << 3; } else { - rid->responderIDType = responderIDType; - if (responderIDType == ocspResponderID_byName) { - responderIDTemplate = ocsp_ResponderIDByNameTemplate; - if (CERT_CopyName(tmpArena, &rid->responderIDValue.name, - &responderCert->subject) != SECSuccess) - goto done; - } - else { - responderIDTemplate = ocsp_ResponderIDByKeyTemplate; - if (!CERT_GetSubjectPublicKeyDigest(tmpArena, responderCert, - SEC_OID_SHA1, &rid->responderIDValue.keyHash)) - goto done; - } + rid->responderIDType = responderIDType; + if (responderIDType == ocspResponderID_byName) { + responderIDTemplate = ocsp_ResponderIDByNameTemplate; + if (CERT_CopyName(tmpArena, &rid->responderIDValue.name, + &responderCert->subject) != SECSuccess) + goto done; + } + else { + responderIDTemplate = ocsp_ResponderIDByKeyTemplate; + if (!CERT_GetSubjectPublicKeyDigest(tmpArena, responderCert, + SEC_OID_SHA1, &rid->responderIDValue.keyHash)) + goto done; + } - if (!SEC_ASN1EncodeItem(tmpArena, &rd->derResponderID, rid, - responderIDTemplate)) - goto done; + if (!SEC_ASN1EncodeItem(tmpArena, &rd->derResponderID, rid, + responderIDTemplate)) + goto done; - br->tbsResponseData = rd; + br->tbsResponseData = rd; - if (!SEC_ASN1EncodeItem(tmpArena, &br->tbsResponseDataDER, br->tbsResponseData, - ocsp_myResponseDataTemplate)) - goto done; + if (!SEC_ASN1EncodeItem(tmpArena, &br->tbsResponseDataDER, br->tbsResponseData, + ocsp_myResponseDataTemplate)) + goto done; - br->responseSignature.derCerts = PORT_ArenaNewArray(tmpArena, SECItem*, 1); - if (!br->responseSignature.derCerts) - goto done; - br->responseSignature.derCerts[0] = NULL; + br->responseSignature.derCerts = PORT_ArenaNewArray(tmpArena, SECItem *, 1); + if (!br->responseSignature.derCerts) + goto done; + br->responseSignature.derCerts[0] = NULL; - privKey = PK11_FindKeyByAnyCert(responderCert, wincx); - if (!privKey) - goto done; + privKey = PK11_FindKeyByAnyCert(responderCert, wincx); + if (!privKey) + goto done; - algID = SEC_GetSignatureAlgorithmOidTag(privKey->keyType, SEC_OID_SHA1); - if (algID == SEC_OID_UNKNOWN) - goto done; + algID = SEC_GetSignatureAlgorithmOidTag(privKey->keyType, SEC_OID_SHA1); + if (algID == SEC_OID_UNKNOWN) + goto done; - if (SEC_SignData(&br->responseSignature.signature, - br->tbsResponseDataDER.data, br->tbsResponseDataDER.len, - privKey, algID) - != SECSuccess) - goto done; + if (SEC_SignData(&br->responseSignature.signature, + br->tbsResponseDataDER.data, br->tbsResponseDataDER.len, + privKey, algID) != + SECSuccess) + goto done; - /* convert len-in-bytes to len-in-bits */ - br->responseSignature.signature.len = br->responseSignature.signature.len << 3; + /* convert len-in-bytes to len-in-bits */ + br->responseSignature.signature.len = br->responseSignature.signature.len << 3; - /* br->responseSignature.signature wasn't allocated from arena, - * we must free it when done. */ + /* br->responseSignature.signature wasn't allocated from arena, + * we must free it when done. */ } - if (SECOID_SetAlgorithmID(tmpArena, &br->responseSignature.signatureAlgorithm, algID, 0) - != SECSuccess) - goto done; + if (SECOID_SetAlgorithmID(tmpArena, &br->responseSignature.signatureAlgorithm, algID, 0) != + SECSuccess) + goto done; if (!SEC_ASN1EncodeItem(tmpArena, &rb->response, br, ocsp_EncodeBasicOCSPResponseTemplate)) @@ -552,15 +551,15 @@ done: static const SEC_ASN1Template ocsp_OCSPErrorResponseTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTOCSPResponse) }, + 0, NULL, sizeof(CERTOCSPResponse) }, { SEC_ASN1_ENUMERATED, - offsetof(CERTOCSPResponse, responseStatus) }, + offsetof(CERTOCSPResponse, responseStatus) }, { 0, 0, - mySEC_NullTemplate }, + mySEC_NullTemplate }, { 0 } }; -SECItem* +SECItem * CERT_CreateEncodedOCSPErrorResponse(PLArenaPool *arena, int error) { CERTOCSPResponse response; diff --git a/security/nss/lib/certhigh/ocspt.h b/security/nss/lib/certhigh/ocspt.h index 888fd32c7e7d..db429ff05823 100644 --- a/security/nss/lib/certhigh/ocspt.h +++ b/security/nss/lib/certhigh/ocspt.h @@ -46,8 +46,8 @@ typedef struct CERTOCSPSingleResponseStr CERTOCSPSingleResponse; * dependent, and should be opaque to the user. */ -typedef void * SEC_HTTP_SERVER_SESSION; -typedef void * SEC_HTTP_REQUEST_SESSION; +typedef void *SEC_HTTP_SERVER_SESSION; +typedef void *SEC_HTTP_REQUEST_SESSION; /* * This function creates a SEC_HTTP_SERVER_SESSION object. The implementer of a @@ -61,9 +61,9 @@ typedef void * SEC_HTTP_REQUEST_SESSION; * after processing is finished. */ typedef SECStatus (*SEC_HttpServer_CreateSessionFcn)( - const char *host, - PRUint16 portnum, - SEC_HTTP_SERVER_SESSION *pSession); + const char *host, + PRUint16 portnum, + SEC_HTTP_SERVER_SESSION *pSession); /* * This function is called to allow the implementation to attempt to keep @@ -77,10 +77,10 @@ typedef SECStatus (*SEC_HttpServer_CreateSessionFcn)( * SECWouldBlock and store a nonzero value at "pPollDesc". In that case * the caller may wait on the poll descriptor, and should call this function * again until SECSuccess (and a zero value at "pPollDesc") is obtained. - */ + */ typedef SECStatus (*SEC_HttpServer_KeepAliveSessionFcn)( - SEC_HTTP_SERVER_SESSION session, - PRPollDesc **pPollDesc); + SEC_HTTP_SERVER_SESSION session, + PRPollDesc **pPollDesc); /* * This function frees the client SEC_HTTP_SERVER_SESSION object, closes all @@ -88,9 +88,9 @@ typedef SECStatus (*SEC_HttpServer_KeepAliveSessionFcn)( * frees any memory that was allocated by the client, and invalidates any * response pointers that might have been returned by prior server or request * functions. - */ + */ typedef SECStatus (*SEC_HttpServer_FreeSessionFcn)( - SEC_HTTP_SERVER_SESSION session); + SEC_HTTP_SERVER_SESSION session); /* * This function creates a SEC_HTTP_REQUEST_SESSION object. The implementer of a @@ -111,30 +111,30 @@ typedef SECStatus (*SEC_HttpServer_FreeSessionFcn)( * after processing is finished. */ typedef SECStatus (*SEC_HttpRequest_CreateFcn)( - SEC_HTTP_SERVER_SESSION session, - const char *http_protocol_variant, /* usually "http" */ - const char *path_and_query_string, - const char *http_request_method, - const PRIntervalTime timeout, - SEC_HTTP_REQUEST_SESSION *pRequest); + SEC_HTTP_SERVER_SESSION session, + const char *http_protocol_variant, /* usually "http" */ + const char *path_and_query_string, + const char *http_request_method, + const PRIntervalTime timeout, + SEC_HTTP_REQUEST_SESSION *pRequest); /* * This function sets data to be sent to the server for an HTTP request - * of http_request_method == POST. If a particular implementation - * supports it, the details for the POST request can be set by calling + * of http_request_method == POST. If a particular implementation + * supports it, the details for the POST request can be set by calling * this function, prior to activating the request with TrySendAndReceiveFcn. * - * An implementation that does not support the POST method should + * An implementation that does not support the POST method should * implement a SetPostDataFcn function that returns immediately. * * Setting http_content_type is optional, the parameter may * by NULL or the empty string. - */ + */ typedef SECStatus (*SEC_HttpRequest_SetPostDataFcn)( - SEC_HTTP_REQUEST_SESSION request, - const char *http_data, - const PRUint32 http_data_len, - const char *http_content_type); + SEC_HTTP_REQUEST_SESSION request, + const char *http_data, + const PRUint32 http_data_len, + const char *http_content_type); /* * This function sets an additional HTTP protocol request header. @@ -144,11 +144,11 @@ typedef SECStatus (*SEC_HttpRequest_SetPostDataFcn)( * * An implementation that does not support setting additional headers * should implement an AddRequestHeaderFcn function that returns immediately. - */ + */ typedef SECStatus (*SEC_HttpRequest_AddHeaderFcn)( - SEC_HTTP_REQUEST_SESSION request, - const char *http_header_name, - const char *http_header_value); + SEC_HTTP_REQUEST_SESSION request, + const char *http_header_name, + const char *http_header_value); /* * This function initiates or continues an HTTP request. After @@ -180,10 +180,10 @@ typedef SECStatus (*SEC_HttpRequest_AddHeaderFcn)( * size, the function will return SECFailure. * http_response_data_len will be set to a value different from zero to * indicate the reason of the failure. - * An out value of "0" means, the failure was unrelated to the + * An out value of "0" means, the failure was unrelated to the * acceptable size. * An out value of "1" means, the result data is larger than the - * accpeptable size, but the real size is not yet known to the http client + * accpeptable size, but the real size is not yet known to the http client * implementation and it stopped retrieving it, * Any other out value combined with a return value of SECFailure * will indicate the actual size of the server data. @@ -195,64 +195,64 @@ typedef SECStatus (*SEC_HttpRequest_AddHeaderFcn)( * the completion of the operation. * * All returned pointers will be owned by the the HttpClient - * implementation and will remain valid until the call to + * implementation and will remain valid until the call to * SEC_HttpRequest_FreeFcn. - */ + */ typedef SECStatus (*SEC_HttpRequest_TrySendAndReceiveFcn)( - SEC_HTTP_REQUEST_SESSION request, - PRPollDesc **pPollDesc, - PRUint16 *http_response_code, - const char **http_response_content_type, - const char **http_response_headers, - const char **http_response_data, - PRUint32 *http_response_data_len); + SEC_HTTP_REQUEST_SESSION request, + PRPollDesc **pPollDesc, + PRUint16 *http_response_code, + const char **http_response_content_type, + const char **http_response_headers, + const char **http_response_data, + PRUint32 *http_response_data_len); /* * Calling CancelFcn asks for premature termination of the request. * * Future calls to SEC_HttpRequest_TrySendAndReceive should - * by avoided, but in this case the HttpClient implementation + * by avoided, but in this case the HttpClient implementation * is expected to return immediately with SECFailure. * - * After calling CancelFcn, a separate call to SEC_HttpRequest_FreeFcn + * After calling CancelFcn, a separate call to SEC_HttpRequest_FreeFcn * is still necessary to free resources. - */ + */ typedef SECStatus (*SEC_HttpRequest_CancelFcn)( - SEC_HTTP_REQUEST_SESSION request); + SEC_HTTP_REQUEST_SESSION request); /* * Before calling this function, it must be assured the request * has been completed, i.e. either SEC_HttpRequest_TrySendAndReceiveFcn has * returned SECSuccess, or the request has been canceled with * a call to SEC_HttpRequest_CancelFcn. - * - * This function frees the client state object, closes all sockets, - * discards all partial results, frees any memory that was allocated + * + * This function frees the client state object, closes all sockets, + * discards all partial results, frees any memory that was allocated * by the client, and invalidates all response pointers that might * have been returned by SEC_HttpRequest_TrySendAndReceiveFcn - */ + */ typedef SECStatus (*SEC_HttpRequest_FreeFcn)( - SEC_HTTP_REQUEST_SESSION request); + SEC_HTTP_REQUEST_SESSION request); typedef struct SEC_HttpClientFcnV1Struct { - SEC_HttpServer_CreateSessionFcn createSessionFcn; - SEC_HttpServer_KeepAliveSessionFcn keepAliveSessionFcn; - SEC_HttpServer_FreeSessionFcn freeSessionFcn; - SEC_HttpRequest_CreateFcn createFcn; - SEC_HttpRequest_SetPostDataFcn setPostDataFcn; - SEC_HttpRequest_AddHeaderFcn addHeaderFcn; - SEC_HttpRequest_TrySendAndReceiveFcn trySendAndReceiveFcn; - SEC_HttpRequest_CancelFcn cancelFcn; - SEC_HttpRequest_FreeFcn freeFcn; + SEC_HttpServer_CreateSessionFcn createSessionFcn; + SEC_HttpServer_KeepAliveSessionFcn keepAliveSessionFcn; + SEC_HttpServer_FreeSessionFcn freeSessionFcn; + SEC_HttpRequest_CreateFcn createFcn; + SEC_HttpRequest_SetPostDataFcn setPostDataFcn; + SEC_HttpRequest_AddHeaderFcn addHeaderFcn; + SEC_HttpRequest_TrySendAndReceiveFcn trySendAndReceiveFcn; + SEC_HttpRequest_CancelFcn cancelFcn; + SEC_HttpRequest_FreeFcn freeFcn; } SEC_HttpClientFcnV1; typedef struct SEC_HttpClientFcnStruct { - PRInt16 version; - union { - SEC_HttpClientFcnV1 ftable1; - /* SEC_HttpClientFcnV2 ftable2; */ - /* ... */ - } fcnTable; + PRInt16 version; + union { + SEC_HttpClientFcnV1 ftable1; + /* SEC_HttpClientFcnV2 ftable2; */ + /* ... */ + } fcnTable; } SEC_HttpClientFcn; /* @@ -293,7 +293,7 @@ typedef enum { */ typedef enum { - ocspResponderID_other = -1, /* unknown kind of responderID */ + ocspResponderID_other = -1, /* unknown kind of responderID */ ocspResponderID_byName = 1, ocspResponderID_byKey = 2 } CERTOCSPResponderIDType; diff --git a/security/nss/lib/certhigh/ocspti.h b/security/nss/lib/certhigh/ocspti.h index a2b3852f25cd..d9297dba6a64 100644 --- a/security/nss/lib/certhigh/ocspti.h +++ b/security/nss/lib/certhigh/ocspti.h @@ -16,7 +16,6 @@ #include "seccomon.h" #include "secoidt.h" - /* * Some notes about naming conventions... * @@ -49,7 +48,6 @@ * way around (reference before definition). */ - /* * Forward-declarations of internal-only data structures. * @@ -67,12 +65,11 @@ typedef struct ocspSingleRequestStr ocspSingleRequest; typedef struct ocspSingleResponseStr ocspSingleResponse; typedef struct ocspTBSRequestStr ocspTBSRequest; - /* * An OCSPRequest; this is what is sent (encoded) to an OCSP responder. */ struct CERTOCSPRequestStr { - PLArenaPool *arena; /* local; not part of encoding */ + PLArenaPool *arena; /* local; not part of encoding */ ocspTBSRequest *tbsRequest; ocspSignature *optionalSignature; }; @@ -92,12 +89,12 @@ struct CERTOCSPRequestStr { * in-progress extensions as they are optionally added to the request. */ struct ocspTBSRequestStr { - SECItem version; /* an INTEGER */ - SECItem *derRequestorName; /* encoded GeneralName; see above */ - CERTGeneralNameList *requestorName; /* local; not part of encoding */ + SECItem version; /* an INTEGER */ + SECItem *derRequestorName; /* encoded GeneralName; see above */ + CERTGeneralNameList *requestorName; /* local; not part of encoding */ ocspSingleRequest **requestList; CERTCertExtension **requestExtensions; - void *extensionHandle; /* local; not part of encoding */ + void *extensionHandle; /* local; not part of encoding */ }; /* @@ -124,12 +121,12 @@ struct ocspTBSRequestStr { */ struct ocspSignatureStr { SECAlgorithmID signatureAlgorithm; - SECItem signature; /* a BIT STRING */ - SECItem **derCerts; /* a SEQUENCE OF Certificate */ - CERTCertificate *cert; /* local; not part of encoding */ - PRBool wasChecked; /* local; not part of encoding */ - SECStatus status; /* local; not part of encoding */ - int failureReason; /* local; not part of encoding */ + SECItem signature; /* a BIT STRING */ + SECItem **derCerts; /* a SEQUENCE OF Certificate */ + CERTCertificate *cert; /* local; not part of encoding */ + PRBool wasChecked; /* local; not part of encoding */ + SECStatus status; /* local; not part of encoding */ + int failureReason; /* local; not part of encoding */ }; /* @@ -140,11 +137,11 @@ struct ocspSignatureStr { * but since that seemed confusing (vs. an OCSPRequest) and to be more * consistent with the parallel type "SingleResponse", I called it a * "SingleRequest". - * + * * XXX figure out how to get rid of that arena -- there must be a way */ struct ocspSingleRequestStr { - PLArenaPool *arena; /* just a copy of the response arena, + PLArenaPool *arena; /* just a copy of the response arena, * needed here for extension handling * routines, on creation only */ CERTOCSPCertID *reqCert; @@ -160,14 +157,14 @@ struct ocspSingleRequestStr { */ struct CERTOCSPCertIDStr { SECAlgorithmID hashAlgorithm; - SECItem issuerNameHash; /* an OCTET STRING */ - SECItem issuerKeyHash; /* an OCTET STRING */ - SECItem serialNumber; /* an INTEGER */ - SECItem issuerSHA1NameHash; /* keep other hashes around when */ - SECItem issuerMD5NameHash; /* we have them */ + SECItem issuerNameHash; /* an OCTET STRING */ + SECItem issuerKeyHash; /* an OCTET STRING */ + SECItem serialNumber; /* an INTEGER */ + SECItem issuerSHA1NameHash; /* keep other hashes around when */ + SECItem issuerMD5NameHash; /* we have them */ SECItem issuerMD2NameHash; - SECItem issuerSHA1KeyHash; /* keep other hashes around when */ - SECItem issuerMD5KeyHash; /* we have them */ + SECItem issuerSHA1KeyHash; /* keep other hashes around when */ + SECItem issuerMD5KeyHash; /* we have them */ SECItem issuerMD2KeyHash; PLArenaPool *poolp; }; @@ -209,10 +206,10 @@ typedef enum { * type ocspResponseStatus. */ struct CERTOCSPResponseStr { - PLArenaPool *arena; /* local; not part of encoding */ - SECItem responseStatus; /* an ENUMERATED, see above */ - ocspResponseStatus statusValue; /* local; not part of encoding */ - ocspResponseBytes *responseBytes; /* only when status is successful */ + PLArenaPool *arena; /* local; not part of encoding */ + SECItem responseStatus; /* an ENUMERATED, see above */ + ocspResponseStatus statusValue; /* local; not part of encoding */ + ocspResponseBytes *responseBytes; /* only when status is successful */ }; /* @@ -230,12 +227,12 @@ struct CERTOCSPResponseStr { * response types, just add them to the union. */ struct ocspResponseBytesStr { - SECItem responseType; /* an OBJECT IDENTIFIER */ - SECOidTag responseTypeTag; /* local; not part of encoding */ - SECItem response; /* an OCTET STRING */ + SECItem responseType; /* an OBJECT IDENTIFIER */ + SECOidTag responseTypeTag; /* local; not part of encoding */ + SECItem response; /* an OCTET STRING */ union { - ocspBasicOCSPResponse *basic; /* when type is id-pkix-ocsp-basic */ - } decodedResponse; /* local; not part of encoding */ + ocspBasicOCSPResponse *basic; /* when type is id-pkix-ocsp-basic */ + } decodedResponse; /* local; not part of encoding */ }; /* @@ -250,7 +247,7 @@ struct ocspResponseBytesStr { */ struct ocspBasicOCSPResponseStr { SECItem tbsResponseDataDER; - ocspResponseData *tbsResponseData; /* "tbs" == To Be Signed */ + ocspResponseData *tbsResponseData; /* "tbs" == To Be Signed */ ocspSignature responseSignature; }; @@ -260,38 +257,38 @@ struct ocspBasicOCSPResponseStr { * (a per-certificate status). */ struct ocspResponseDataStr { - SECItem version; /* an INTEGER */ + SECItem version; /* an INTEGER */ SECItem derResponderID; - ocspResponderID *responderID; /* local; not part of encoding */ - SECItem producedAt; /* a GeneralizedTime */ + ocspResponderID *responderID; /* local; not part of encoding */ + SECItem producedAt; /* a GeneralizedTime */ CERTOCSPSingleResponse **responses; CERTCertExtension **responseExtensions; }; struct ocspResponderIDStr { - CERTOCSPResponderIDType responderIDType;/* local; not part of encoding */ + CERTOCSPResponderIDType responderIDType; /* local; not part of encoding */ union { - CERTName name; /* when ocspResponderID_byName */ - SECItem keyHash; /* when ocspResponderID_byKey */ - SECItem other; /* when ocspResponderID_other */ + CERTName name; /* when ocspResponderID_byName */ + SECItem keyHash; /* when ocspResponderID_byKey */ + SECItem other; /* when ocspResponderID_other */ } responderIDValue; }; /* * The ResponseData in a BasicOCSPResponse contains a SEQUENCE OF * SingleResponse -- one for each certificate whose status is being supplied. - * + * * XXX figure out how to get rid of that arena -- there must be a way */ struct CERTOCSPSingleResponseStr { - PLArenaPool *arena; /* just a copy of the response arena, + PLArenaPool *arena; /* just a copy of the response arena, * needed here for extension handling * routines, on creation only */ CERTOCSPCertID *certID; SECItem derCertStatus; - ocspCertStatus *certStatus; /* local; not part of encoding */ - SECItem thisUpdate; /* a GeneralizedTime */ - SECItem *nextUpdate; /* a GeneralizedTime */ + ocspCertStatus *certStatus; /* local; not part of encoding */ + SECItem thisUpdate; /* a GeneralizedTime */ + SECItem *nextUpdate; /* a GeneralizedTime */ CERTCertExtension **singleExtensions; }; @@ -313,10 +310,10 @@ struct CERTOCSPSingleResponseStr { */ typedef enum { - ocspCertStatus_good, /* cert is not revoked */ - ocspCertStatus_revoked, /* cert is revoked */ - ocspCertStatus_unknown, /* cert was unknown to the responder */ - ocspCertStatus_other /* status was not an expected value */ + ocspCertStatus_good, /* cert is not revoked */ + ocspCertStatus_revoked, /* cert is revoked */ + ocspCertStatus_unknown, /* cert was unknown to the responder */ + ocspCertStatus_other /* status was not an expected value */ } ocspCertStatusType; /* @@ -327,13 +324,13 @@ typedef enum { * gives more detailed information.) */ struct ocspCertStatusStr { - ocspCertStatusType certStatusType; /* local; not part of encoding */ + ocspCertStatusType certStatusType; /* local; not part of encoding */ union { - SECItem *goodInfo; /* when ocspCertStatus_good */ - ocspRevokedInfo *revokedInfo; /* when ocspCertStatus_revoked */ - SECItem *unknownInfo; /* when ocspCertStatus_unknown */ - SECItem *otherInfo; /* when ocspCertStatus_other */ - } certStatusInfo; + SECItem *goodInfo; /* when ocspCertStatus_good */ + ocspRevokedInfo *revokedInfo; /* when ocspCertStatus_revoked */ + SECItem *unknownInfo; /* when ocspCertStatus_unknown */ + SECItem *otherInfo; /* when ocspCertStatus_other */ + } certStatusInfo; }; /* @@ -341,8 +338,8 @@ struct ocspCertStatusStr { * was revoked and why. */ struct ocspRevokedInfoStr { - SECItem revocationTime; /* a GeneralizedTime */ - SECItem *revocationReason; /* a CRLReason; ignored for now */ + SECItem revocationTime; /* a GeneralizedTime */ + SECItem *revocationReason; /* a CRLReason; ignored for now */ }; /* @@ -353,7 +350,7 @@ struct ocspRevokedInfoStr { */ struct ocspServiceLocatorStr { CERTName *issuer; - SECItem locator; /* DER encoded authInfoAccess extension from cert */ + SECItem locator; /* DER encoded authInfoAccess extension from cert */ }; #endif /* _OCSPTI_H_ */ diff --git a/security/nss/lib/certhigh/xcrldist.c b/security/nss/lib/certhigh/xcrldist.c index 291a9d888e72..4f74cdb2597e 100644 --- a/security/nss/lib/certhigh/xcrldist.c +++ b/security/nss/lib/certhigh/xcrldist.c @@ -12,203 +12,201 @@ SEC_ASN1_MKSUB(SEC_AnyTemplate) SEC_ASN1_MKSUB(SEC_BitStringTemplate) -extern void PrepareBitStringForEncoding (SECItem *bitMap, SECItem *value); +extern void PrepareBitStringForEncoding(SECItem *bitMap, SECItem *value); static const SEC_ASN1Template FullNameTemplate[] = { - {SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0, - offsetof (CRLDistributionPoint,derFullName), - CERT_GeneralNamesTemplate} + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0, + offsetof(CRLDistributionPoint, derFullName), + CERT_GeneralNamesTemplate } }; static const SEC_ASN1Template RelativeNameTemplate[] = { - {SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, - offsetof (CRLDistributionPoint,distPoint.relativeName), - CERT_RDNTemplate} + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, + offsetof(CRLDistributionPoint, distPoint.relativeName), + CERT_RDNTemplate } }; static const SEC_ASN1Template DistributionPointNameTemplate[] = { { SEC_ASN1_CHOICE, - offsetof(CRLDistributionPoint, distPointType), NULL, - sizeof(CRLDistributionPoint) }, + offsetof(CRLDistributionPoint, distPointType), NULL, + sizeof(CRLDistributionPoint) }, { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0, - offsetof (CRLDistributionPoint, derFullName), - CERT_GeneralNamesTemplate, generalName }, - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, - offsetof (CRLDistributionPoint, distPoint.relativeName), - CERT_RDNTemplate, relativeDistinguishedName }, + offsetof(CRLDistributionPoint, derFullName), + CERT_GeneralNamesTemplate, generalName }, + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, + offsetof(CRLDistributionPoint, distPoint.relativeName), + CERT_RDNTemplate, relativeDistinguishedName }, { 0 } }; static const SEC_ASN1Template CRLDistributionPointTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRLDistributionPoint) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | SEC_ASN1_XTRN | 0, - offsetof(CRLDistributionPoint,derDistPoint), - SEC_ASN1_SUB(SEC_AnyTemplate)}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, - offsetof(CRLDistributionPoint,bitsmap), - SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | 2, - offsetof(CRLDistributionPoint, derCrlIssuer), - CERT_GeneralNamesTemplate}, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | SEC_ASN1_XTRN | 0, + offsetof(CRLDistributionPoint, derDistPoint), + SEC_ASN1_SUB(SEC_AnyTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, + offsetof(CRLDistributionPoint, bitsmap), + SEC_ASN1_SUB(SEC_BitStringTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_CONSTRUCTED | 2, + offsetof(CRLDistributionPoint, derCrlIssuer), + CERT_GeneralNamesTemplate }, { 0 } }; const SEC_ASN1Template CERTCRLDistributionPointsTemplate[] = { - {SEC_ASN1_SEQUENCE_OF, 0, CRLDistributionPointTemplate} + { SEC_ASN1_SEQUENCE_OF, 0, CRLDistributionPointTemplate } }; SECStatus -CERT_EncodeCRLDistributionPoints (PLArenaPool *arena, - CERTCrlDistributionPoints *value, - SECItem *derValue) +CERT_EncodeCRLDistributionPoints(PLArenaPool *arena, + CERTCrlDistributionPoints *value, + SECItem *derValue) { CRLDistributionPoint **pointList, *point; PLArenaPool *ourPool = NULL; SECStatus rv = SECSuccess; - PORT_Assert (derValue); - PORT_Assert (value && value->distPoints); + PORT_Assert(derValue); + PORT_Assert(value && value->distPoints); do { - ourPool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE); - if (ourPool == NULL) { - rv = SECFailure; - break; - } - - pointList = value->distPoints; - while (*pointList) { - point = *pointList; - point->derFullName = NULL; - point->derDistPoint.data = NULL; + ourPool = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); + if (ourPool == NULL) { + rv = SECFailure; + break; + } - switch (point->distPointType) { - case generalName: - point->derFullName = cert_EncodeGeneralNames - (ourPool, point->distPoint.fullName); - - if (!point->derFullName || - !SEC_ASN1EncodeItem (ourPool, &point->derDistPoint, - point, FullNameTemplate)) - rv = SECFailure; - break; + pointList = value->distPoints; + while (*pointList) { + point = *pointList; + point->derFullName = NULL; + point->derDistPoint.data = NULL; - case relativeDistinguishedName: - if (!SEC_ASN1EncodeItem(ourPool, &point->derDistPoint, - point, RelativeNameTemplate)) - rv = SECFailure; - break; + switch (point->distPointType) { + case generalName: + point->derFullName = cert_EncodeGeneralNames(ourPool, point->distPoint.fullName); - default: - PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID); - rv = SECFailure; - break; - } + if (!point->derFullName || + !SEC_ASN1EncodeItem(ourPool, &point->derDistPoint, + point, FullNameTemplate)) + rv = SECFailure; + break; - if (rv != SECSuccess) - break; + case relativeDistinguishedName: + if (!SEC_ASN1EncodeItem(ourPool, &point->derDistPoint, + point, RelativeNameTemplate)) + rv = SECFailure; + break; - if (point->reasons.data) - PrepareBitStringForEncoding (&point->bitsmap, &point->reasons); + default: + PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID); + rv = SECFailure; + break; + } - if (point->crlIssuer) { - point->derCrlIssuer = cert_EncodeGeneralNames - (ourPool, point->crlIssuer); - if (!point->derCrlIssuer) { - rv = SECFailure; - break; - } - } - ++pointList; - } - if (rv != SECSuccess) - break; - if (!SEC_ASN1EncodeItem(arena, derValue, value, - CERTCRLDistributionPointsTemplate)) { - rv = SECFailure; - break; - } + if (rv != SECSuccess) + break; + + if (point->reasons.data) + PrepareBitStringForEncoding(&point->bitsmap, &point->reasons); + + if (point->crlIssuer) { + point->derCrlIssuer = cert_EncodeGeneralNames(ourPool, point->crlIssuer); + if (!point->derCrlIssuer) { + rv = SECFailure; + break; + } + } + ++pointList; + } + if (rv != SECSuccess) + break; + if (!SEC_ASN1EncodeItem(arena, derValue, value, + CERTCRLDistributionPointsTemplate)) { + rv = SECFailure; + break; + } } while (0); - PORT_FreeArena (ourPool, PR_FALSE); + PORT_FreeArena(ourPool, PR_FALSE); return rv; } CERTCrlDistributionPoints * -CERT_DecodeCRLDistributionPoints (PLArenaPool *arena, SECItem *encodedValue) +CERT_DecodeCRLDistributionPoints(PLArenaPool *arena, SECItem *encodedValue) { - CERTCrlDistributionPoints *value = NULL; - CRLDistributionPoint **pointList, *point; - SECStatus rv = SECSuccess; - SECItem newEncodedValue; + CERTCrlDistributionPoints *value = NULL; + CRLDistributionPoint **pointList, *point; + SECStatus rv = SECSuccess; + SECItem newEncodedValue; - PORT_Assert (arena); - do { - value = PORT_ArenaZNew(arena, CERTCrlDistributionPoints); - if (value == NULL) { - rv = SECFailure; - break; - } + PORT_Assert(arena); + do { + value = PORT_ArenaZNew(arena, CERTCrlDistributionPoints); + if (value == NULL) { + rv = SECFailure; + break; + } /* 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, &newEncodedValue, encodedValue); if (rv != SECSuccess) - break; + break; - rv = SEC_QuickDERDecodeItem(arena, &value->distPoints, - CERTCRLDistributionPointsTemplate, &newEncodedValue); - if (rv != SECSuccess) - break; + rv = SEC_QuickDERDecodeItem(arena, &value->distPoints, + CERTCRLDistributionPointsTemplate, &newEncodedValue); + if (rv != SECSuccess) + break; - pointList = value->distPoints; - while (NULL != (point = *pointList)) { + pointList = value->distPoints; + while (NULL != (point = *pointList)) { - /* get the data if the distributionPointName is not omitted */ - if (point->derDistPoint.data != NULL) { - rv = SEC_QuickDERDecodeItem(arena, point, - DistributionPointNameTemplate, &(point->derDistPoint)); - if (rv != SECSuccess) - break; + /* get the data if the distributionPointName is not omitted */ + if (point->derDistPoint.data != NULL) { + rv = SEC_QuickDERDecodeItem(arena, point, + DistributionPointNameTemplate, &(point->derDistPoint)); + if (rv != SECSuccess) + break; - switch (point->distPointType) { - case generalName: - point->distPoint.fullName = - cert_DecodeGeneralNames(arena, point->derFullName); - rv = point->distPoint.fullName ? SECSuccess : SECFailure; - break; + switch (point->distPointType) { + case generalName: + point->distPoint.fullName = + cert_DecodeGeneralNames(arena, point->derFullName); + rv = point->distPoint.fullName ? SECSuccess : SECFailure; + break; - case relativeDistinguishedName: - break; + case relativeDistinguishedName: + break; - default: - PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID); - rv = SECFailure; - break; - } /* end switch */ - if (rv != SECSuccess) - break; - } /* end if */ + default: + PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID); + rv = SECFailure; + break; + } /* end switch */ + if (rv != SECSuccess) + break; + } /* end if */ - /* Get the reason code if it's not omitted in the encoding */ - if (point->bitsmap.data != NULL) { - SECItem bitsmap = point->bitsmap; - DER_ConvertBitString(&bitsmap); - rv = SECITEM_CopyItem(arena, &point->reasons, &bitsmap); - if (rv != SECSuccess) - break; - } + /* Get the reason code if it's not omitted in the encoding */ + if (point->bitsmap.data != NULL) { + SECItem bitsmap = point->bitsmap; + DER_ConvertBitString(&bitsmap); + rv = SECITEM_CopyItem(arena, &point->reasons, &bitsmap); + if (rv != SECSuccess) + break; + } - /* Get the crl issuer name if it's not omitted in the encoding */ - if (point->derCrlIssuer != NULL) { - point->crlIssuer = cert_DecodeGeneralNames(arena, - point->derCrlIssuer); - if (!point->crlIssuer) - break; - } - ++pointList; - } /* end while points remain */ - } while (0); - return (rv == SECSuccess ? value : NULL); + /* Get the crl issuer name if it's not omitted in the encoding */ + if (point->derCrlIssuer != NULL) { + point->crlIssuer = cert_DecodeGeneralNames(arena, + point->derCrlIssuer); + if (!point->crlIssuer) + break; + } + ++pointList; + } /* end while points remain */ + } while (0); + return (rv == SECSuccess ? value : NULL); } diff --git a/security/nss/lib/ckfw/builtins/anchor.c b/security/nss/lib/ckfw/builtins/anchor.c index 51b4a56886b5..cc0d0c09fa5d 100644 --- a/security/nss/lib/ckfw/builtins/anchor.c +++ b/security/nss/lib/ckfw/builtins/anchor.c @@ -6,12 +6,12 @@ * builtins/anchor.c * * This file "anchors" the actual cryptoki entry points in this module's - * shared library, which is required for dynamic loading. See the + * shared library, which is required for dynamic loading. See the * comments in nssck.api for more information. */ #include "builtins.h" #define MODULE_NAME builtins -#define INSTANCE_NAME (NSSCKMDInstance *)&nss_builtins_mdInstance +#define INSTANCE_NAME (NSSCKMDInstance *) & nss_builtins_mdInstance #include "nssck.api" diff --git a/security/nss/lib/ckfw/builtins/bfind.c b/security/nss/lib/ckfw/builtins/bfind.c index df35ed8b689f..ee145b68ae34 100644 --- a/security/nss/lib/ckfw/builtins/bfind.c +++ b/security/nss/lib/ckfw/builtins/bfind.c @@ -14,258 +14,250 @@ */ struct builtinsFOStr { - NSSArena *arena; - CK_ULONG n; - CK_ULONG i; - builtinsInternalObject **objs; + NSSArena *arena; + CK_ULONG n; + CK_ULONG i; + builtinsInternalObject **objs; }; static void -builtins_mdFindObjects_Final -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdFindObjects_Final( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - struct builtinsFOStr *fo = (struct builtinsFOStr *)mdFindObjects->etc; - NSSArena *arena = fo->arena; + struct builtinsFOStr *fo = (struct builtinsFOStr *)mdFindObjects->etc; + NSSArena *arena = fo->arena; - nss_ZFreeIf(fo->objs); - nss_ZFreeIf(fo); - nss_ZFreeIf(mdFindObjects); - if ((NSSArena *)NULL != arena) { - NSSArena_Destroy(arena); - } + nss_ZFreeIf(fo->objs); + nss_ZFreeIf(fo); + nss_ZFreeIf(mdFindObjects); + if ((NSSArena *)NULL != arena) { + NSSArena_Destroy(arena); + } - return; + return; } static NSSCKMDObject * -builtins_mdFindObjects_Next -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +builtins_mdFindObjects_Next( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { - struct builtinsFOStr *fo = (struct builtinsFOStr *)mdFindObjects->etc; - builtinsInternalObject *io; + struct builtinsFOStr *fo = (struct builtinsFOStr *)mdFindObjects->etc; + builtinsInternalObject *io; - if( fo->i == fo->n ) { - *pError = CKR_OK; - return (NSSCKMDObject *)NULL; - } + if (fo->i == fo->n) { + *pError = CKR_OK; + return (NSSCKMDObject *)NULL; + } - io = fo->objs[ fo->i ]; - fo->i++; + io = fo->objs[fo->i]; + fo->i++; - return nss_builtins_CreateMDObject(arena, io, pError); + return nss_builtins_CreateMDObject(arena, io, pError); } static int -builtins_derUnwrapInt(unsigned char *src, int size, unsigned char **dest) { +builtins_derUnwrapInt(unsigned char *src, int size, unsigned char **dest) +{ unsigned char *start = src; int len = 0; - if (*src ++ != 2) { - return 0; + if (*src++ != 2) { + return 0; } len = *src++; if (len & 0x80) { - int count = len & 0x7f; - len =0; + int count = len & 0x7f; + len = 0; - if (count+2 > size) { - return 0; - } - while (count-- > 0) { - len = (len << 8) | *src++; - } + if (count + 2 > size) { + return 0; + } + while (count-- > 0) { + len = (len << 8) | *src++; + } } - if (len + (src-start) != size) { - return 0; + if (len + (src - start) != size) { + return 0; } *dest = src; return len; } static CK_BBOOL -builtins_attrmatch -( - CK_ATTRIBUTE_PTR a, - const NSSItem *b -) +builtins_attrmatch( + CK_ATTRIBUTE_PTR a, + const NSSItem *b) { - PRBool prb; + PRBool prb; - if( a->ulValueLen != b->size ) { - /* match a decoded serial number */ - if ((a->type == CKA_SERIAL_NUMBER) && (a->ulValueLen < b->size)) { - int len; - unsigned char *data = NULL; + if (a->ulValueLen != b->size) { + /* match a decoded serial number */ + if ((a->type == CKA_SERIAL_NUMBER) && (a->ulValueLen < b->size)) { + int len; + unsigned char *data = NULL; - len = builtins_derUnwrapInt(b->data,b->size,&data); - if (data && - (len == a->ulValueLen) && - nsslibc_memequal(a->pValue, data, len, (PRStatus *)NULL)) { - return CK_TRUE; - } + len = builtins_derUnwrapInt(b->data, b->size, &data); + if (data && + (len == a->ulValueLen) && + nsslibc_memequal(a->pValue, data, len, (PRStatus *)NULL)) { + return CK_TRUE; + } + } + return CK_FALSE; } - return CK_FALSE; - } - prb = nsslibc_memequal(a->pValue, b->data, b->size, (PRStatus *)NULL); + prb = nsslibc_memequal(a->pValue, b->data, b->size, (PRStatus *)NULL); - if( PR_TRUE == prb ) { - return CK_TRUE; - } else { - return CK_FALSE; - } + if (PR_TRUE == prb) { + return CK_TRUE; + } + else { + return CK_FALSE; + } } - static CK_BBOOL -builtins_match -( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - builtinsInternalObject *o -) +builtins_match( + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + builtinsInternalObject *o) { - CK_ULONG i; + CK_ULONG i; - for( i = 0; i < ulAttributeCount; i++ ) { - CK_ULONG j; + for (i = 0; i < ulAttributeCount; i++) { + CK_ULONG j; - for( j = 0; j < o->n; j++ ) { - if( o->types[j] == pTemplate[i].type ) { - if( CK_FALSE == builtins_attrmatch(&pTemplate[i], &o->items[j]) ) { - return CK_FALSE; - } else { - break; + for (j = 0; j < o->n; j++) { + if (o->types[j] == pTemplate[i].type) { + if (CK_FALSE == builtins_attrmatch(&pTemplate[i], &o->items[j])) { + return CK_FALSE; + } + else { + break; + } + } + } + + if (j == o->n) { + /* Loop ran to the end: no matching attribute */ + return CK_FALSE; } - } } - if( j == o->n ) { - /* Loop ran to the end: no matching attribute */ - return CK_FALSE; - } - } - - /* Every attribute passed */ - return CK_TRUE; + /* Every attribute passed */ + return CK_TRUE; } NSS_IMPLEMENT NSSCKMDFindObjects * -nss_builtins_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_builtins_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - /* This could be made more efficient. I'm rather rushed. */ - NSSArena *arena; - NSSCKMDFindObjects *rv = (NSSCKMDFindObjects *)NULL; - struct builtinsFOStr *fo = (struct builtinsFOStr *)NULL; + /* This could be made more efficient. I'm rather rushed. */ + NSSArena *arena; + NSSCKMDFindObjects *rv = (NSSCKMDFindObjects *)NULL; + struct builtinsFOStr *fo = (struct builtinsFOStr *)NULL; - /* +/* * 99% of the time we get 0 or 1 matches. So we start with a small * stack-allocated array to hold the matches and switch to a heap-allocated * array later if the number of matches exceeds STACK_BUF_LENGTH. */ - #define STACK_BUF_LENGTH 1 - builtinsInternalObject *stackTemp[STACK_BUF_LENGTH]; - builtinsInternalObject **temp = stackTemp; - PRBool tempIsHeapAllocated = PR_FALSE; - PRUint32 i; +#define STACK_BUF_LENGTH 1 + builtinsInternalObject *stackTemp[STACK_BUF_LENGTH]; + builtinsInternalObject **temp = stackTemp; + PRBool tempIsHeapAllocated = PR_FALSE; + PRUint32 i; - arena = NSSArena_Create(); - if( (NSSArena *)NULL == arena ) { - goto loser; - } - - rv = nss_ZNEW(arena, NSSCKMDFindObjects); - if( (NSSCKMDFindObjects *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - - fo = nss_ZNEW(arena, struct builtinsFOStr); - if( (struct builtinsFOStr *)NULL == fo ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - - fo->arena = arena; - /* fo->n and fo->i are already zero */ - - rv->etc = (void *)fo; - rv->Final = builtins_mdFindObjects_Final; - rv->Next = builtins_mdFindObjects_Next; - rv->null = (void *)NULL; - - for( i = 0; i < nss_builtins_nObjects; i++ ) { - builtinsInternalObject *o = (builtinsInternalObject *)&nss_builtins_data[i]; - - if( CK_TRUE == builtins_match(pTemplate, ulAttributeCount, o) ) { - if( fo->n == STACK_BUF_LENGTH ) { - /* Switch from the small stack array to a heap-allocated array large - * enough to handle matches in all remaining cases. */ - temp = nss_ZNEWARRAY((NSSArena *)NULL, builtinsInternalObject *, - fo->n + nss_builtins_nObjects - i); - if( (builtinsInternalObject **)NULL == temp ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - tempIsHeapAllocated = PR_TRUE; - (void)nsslibc_memcpy(temp, stackTemp, - sizeof(builtinsInternalObject *) * fo->n); - } - - temp[ fo->n ] = o; - fo->n++; + arena = NSSArena_Create(); + if ((NSSArena *)NULL == arena) { + goto loser; } - } - fo->objs = nss_ZNEWARRAY(arena, builtinsInternalObject *, fo->n); - if( (builtinsInternalObject **)NULL == fo->objs ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + rv = nss_ZNEW(arena, NSSCKMDFindObjects); + if ((NSSCKMDFindObjects *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - (void)nsslibc_memcpy(fo->objs, temp, sizeof(builtinsInternalObject *) * fo->n); - if (tempIsHeapAllocated) { - nss_ZFreeIf(temp); - temp = (builtinsInternalObject **)NULL; - } + fo = nss_ZNEW(arena, struct builtinsFOStr); + if ((struct builtinsFOStr *)NULL == fo) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - return rv; + fo->arena = arena; + /* fo->n and fo->i are already zero */ - loser: - if (tempIsHeapAllocated) { - nss_ZFreeIf(temp); - } - nss_ZFreeIf(fo); - nss_ZFreeIf(rv); - if ((NSSArena *)NULL != arena) { - NSSArena_Destroy(arena); - } - return (NSSCKMDFindObjects *)NULL; + rv->etc = (void *)fo; + rv->Final = builtins_mdFindObjects_Final; + rv->Next = builtins_mdFindObjects_Next; + rv->null = (void *)NULL; + + for (i = 0; i < nss_builtins_nObjects; i++) { + builtinsInternalObject *o = (builtinsInternalObject *)&nss_builtins_data[i]; + + if (CK_TRUE == builtins_match(pTemplate, ulAttributeCount, o)) { + if (fo->n == STACK_BUF_LENGTH) { + /* Switch from the small stack array to a heap-allocated array large + * enough to handle matches in all remaining cases. */ + temp = nss_ZNEWARRAY((NSSArena *)NULL, builtinsInternalObject *, + fo->n + nss_builtins_nObjects - i); + if ((builtinsInternalObject **)NULL == temp) { + *pError = + CKR_HOST_MEMORY; + goto loser; + } + tempIsHeapAllocated = PR_TRUE; + (void)nsslibc_memcpy(temp, stackTemp, + sizeof(builtinsInternalObject *) * fo->n); + } + + temp[fo->n] = o; + fo->n++; + } + } + + fo->objs = nss_ZNEWARRAY(arena, builtinsInternalObject *, fo->n); + if ((builtinsInternalObject **)NULL == fo->objs) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + + (void)nsslibc_memcpy(fo->objs, temp, sizeof(builtinsInternalObject *) * fo->n); + if (tempIsHeapAllocated) { + nss_ZFreeIf(temp); + temp = (builtinsInternalObject **)NULL; + } + + return rv; + +loser: + if (tempIsHeapAllocated) { + nss_ZFreeIf(temp); + } + nss_ZFreeIf(fo); + nss_ZFreeIf(rv); + if ((NSSArena *)NULL != arena) { + NSSArena_Destroy(arena); + } + return (NSSCKMDFindObjects *)NULL; } - diff --git a/security/nss/lib/ckfw/builtins/binst.c b/security/nss/lib/ckfw/builtins/binst.c index 8cb057d96659..ca1dac89cd4f 100644 --- a/security/nss/lib/ckfw/builtins/binst.c +++ b/security/nss/lib/ckfw/builtins/binst.c @@ -7,7 +7,7 @@ /* * builtins/instance.c * - * This file implements the NSSCKMDInstance object for the + * This file implements the NSSCKMDInstance object for the * "builtin objects" cryptoki module. */ @@ -16,84 +16,72 @@ */ static CK_ULONG -builtins_mdInstance_GetNSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdInstance_GetNSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (CK_ULONG)1; + return (CK_ULONG)1; } static CK_VERSION -builtins_mdInstance_GetCryptokiVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdInstance_GetCryptokiVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_builtins_CryptokiVersion; + return nss_builtins_CryptokiVersion; } static NSSUTF8 * -builtins_mdInstance_GetManufacturerID -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdInstance_GetManufacturerID( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_ManufacturerID; + return (NSSUTF8 *)nss_builtins_ManufacturerID; } static NSSUTF8 * -builtins_mdInstance_GetLibraryDescription -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdInstance_GetLibraryDescription( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_LibraryDescription; + return (NSSUTF8 *)nss_builtins_LibraryDescription; } static CK_VERSION -builtins_mdInstance_GetLibraryVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdInstance_GetLibraryVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { #define NSS_VERSION_VARIABLE __nss_builtins_version #include "verref.h" - return nss_builtins_LibraryVersion; + return nss_builtins_LibraryVersion; } static CK_RV -builtins_mdInstance_GetSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDSlot *slots[] -) +builtins_mdInstance_GetSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDSlot *slots[]) { - slots[0] = (NSSCKMDSlot *)&nss_builtins_mdSlot; - return CKR_OK; + slots[0] = (NSSCKMDSlot *)&nss_builtins_mdSlot; + return CKR_OK; } const NSSCKMDInstance -nss_builtins_mdInstance = { - (void *)NULL, /* etc */ - NULL, /* Initialize */ - NULL, /* Finalize */ - builtins_mdInstance_GetNSlots, - builtins_mdInstance_GetCryptokiVersion, - builtins_mdInstance_GetManufacturerID, - builtins_mdInstance_GetLibraryDescription, - builtins_mdInstance_GetLibraryVersion, - NULL, /* ModuleHandlesSessionObjects -- defaults to false */ - builtins_mdInstance_GetSlots, - NULL, /* WaitForSlotEvent */ - (void *)NULL /* null terminator */ -}; + nss_builtins_mdInstance = { + (void *)NULL, /* etc */ + NULL, /* Initialize */ + NULL, /* Finalize */ + builtins_mdInstance_GetNSlots, + builtins_mdInstance_GetCryptokiVersion, + builtins_mdInstance_GetManufacturerID, + builtins_mdInstance_GetLibraryDescription, + builtins_mdInstance_GetLibraryVersion, + NULL, /* ModuleHandlesSessionObjects -- defaults to false */ + builtins_mdInstance_GetSlots, + NULL, /* WaitForSlotEvent */ + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/builtins/bobject.c b/security/nss/lib/ckfw/builtins/bobject.c index 55876c0f21f3..1c0babdd66cd 100644 --- a/security/nss/lib/ckfw/builtins/bobject.c +++ b/security/nss/lib/ckfw/builtins/bobject.c @@ -24,199 +24,183 @@ */ static CK_RV -builtins_mdObject_Destroy -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdObject_Destroy( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CKR_SESSION_READ_ONLY; + return CKR_SESSION_READ_ONLY; } static CK_BBOOL -builtins_mdObject_IsTokenObject -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdObject_IsTokenObject( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_TRUE; + return CK_TRUE; } static CK_ULONG -builtins_mdObject_GetAttributeCount -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdObject_GetAttributeCount( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; - return io->n; + builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; + return io->n; } static CK_RV -builtins_mdObject_GetAttributeTypes -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -) +builtins_mdObject_GetAttributeTypes( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount) { - builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; - CK_ULONG i; + builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; + CK_ULONG i; - if( io->n != ulCount ) { - return CKR_BUFFER_TOO_SMALL; - } + if (io->n != ulCount) { + return CKR_BUFFER_TOO_SMALL; + } - for( i = 0; i < io->n; i++ ) { - typeArray[i] = io->types[i]; - } + for (i = 0; i < io->n; i++) { + typeArray[i] = io->types[i]; + } - return CKR_OK; + return CKR_OK; } static CK_ULONG -builtins_mdObject_GetAttributeSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +builtins_mdObject_GetAttributeSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; - CK_ULONG i; + builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; + CK_ULONG i; - for( i = 0; i < io->n; i++ ) { - if( attribute == io->types[i] ) { - return (CK_ULONG)(io->items[i].size); + for (i = 0; i < io->n; i++) { + if (attribute == io->types[i]) { + return (CK_ULONG)(io->items[i].size); + } } - } - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - return 0; + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + return 0; } static NSSCKFWItem -builtins_mdObject_GetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +builtins_mdObject_GetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - NSSCKFWItem mdItem; - builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; - CK_ULONG i; + NSSCKFWItem mdItem; + builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; + CK_ULONG i; - mdItem.needsFreeing = PR_FALSE; - mdItem.item = (NSSItem*) NULL; + mdItem.needsFreeing = PR_FALSE; + mdItem.item = (NSSItem *)NULL; - for( i = 0; i < io->n; i++ ) { - if( attribute == io->types[i] ) { - mdItem.item = (NSSItem*) &io->items[i]; - return mdItem; + for (i = 0; i < io->n; i++) { + if (attribute == io->types[i]) { + mdItem.item = (NSSItem *)&io->items[i]; + return mdItem; + } } - } - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - return mdItem; + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + return mdItem; } static CK_ULONG -builtins_mdObject_GetObjectSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdObject_GetObjectSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; - CK_ULONG i; - CK_ULONG rv = sizeof(CK_ULONG); + builtinsInternalObject *io = (builtinsInternalObject *)mdObject->etc; + CK_ULONG i; + CK_ULONG rv = sizeof(CK_ULONG); - for( i = 0; i < io->n; i++ ) { - rv += sizeof(CK_ATTRIBUTE_TYPE) + sizeof(NSSItem) + io->items[i].size; - } + for (i = 0; i < io->n; i++) { + rv += sizeof(CK_ATTRIBUTE_TYPE) + sizeof(NSSItem) + io->items[i].size; + } - return rv; + return rv; } static const NSSCKMDObject -builtins_prototype_mdObject = { - (void *)NULL, /* etc */ - NULL, /* Finalize */ - builtins_mdObject_Destroy, - builtins_mdObject_IsTokenObject, - builtins_mdObject_GetAttributeCount, - builtins_mdObject_GetAttributeTypes, - builtins_mdObject_GetAttributeSize, - builtins_mdObject_GetAttribute, - NULL, /* FreeAttribute */ - NULL, /* SetAttribute */ - builtins_mdObject_GetObjectSize, - (void *)NULL /* null terminator */ -}; + builtins_prototype_mdObject = { + (void *)NULL, /* etc */ + NULL, /* Finalize */ + builtins_mdObject_Destroy, + builtins_mdObject_IsTokenObject, + builtins_mdObject_GetAttributeCount, + builtins_mdObject_GetAttributeTypes, + builtins_mdObject_GetAttributeSize, + builtins_mdObject_GetAttribute, + NULL, /* FreeAttribute */ + NULL, /* SetAttribute */ + builtins_mdObject_GetObjectSize, + (void *)NULL /* null terminator */ + }; NSS_IMPLEMENT NSSCKMDObject * -nss_builtins_CreateMDObject -( - NSSArena *arena, - builtinsInternalObject *io, - CK_RV *pError -) +nss_builtins_CreateMDObject( + NSSArena *arena, + builtinsInternalObject *io, + CK_RV *pError) { - if ( (void*)NULL == io->mdObject.etc) { - (void) nsslibc_memcpy(&io->mdObject,&builtins_prototype_mdObject, - sizeof(builtins_prototype_mdObject)); - io->mdObject.etc = (void *)io; - } + if ((void *)NULL == io->mdObject.etc) { + (void)nsslibc_memcpy(&io->mdObject, &builtins_prototype_mdObject, + sizeof(builtins_prototype_mdObject)); + io->mdObject.etc = (void *)io; + } - return &io->mdObject; + return &io->mdObject; } diff --git a/security/nss/lib/ckfw/builtins/bsession.c b/security/nss/lib/ckfw/builtins/bsession.c index 6705bfc61357..6828a49affa1 100644 --- a/security/nss/lib/ckfw/builtins/bsession.c +++ b/security/nss/lib/ckfw/builtins/bsession.c @@ -7,69 +7,65 @@ /* * builtins/session.c * - * This file implements the NSSCKMDSession object for the + * This file implements the NSSCKMDSession object for the * "builtin objects" cryptoki module. */ static NSSCKMDFindObjects * -builtins_mdSession_FindObjectsInit -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +builtins_mdSession_FindObjectsInit( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - return nss_builtins_FindObjectsInit(fwSession, pTemplate, ulAttributeCount, pError); + return nss_builtins_FindObjectsInit(fwSession, pTemplate, ulAttributeCount, pError); } NSS_IMPLEMENT NSSCKMDSession * -nss_builtins_CreateSession -( - NSSCKFWSession *fwSession, - CK_RV *pError -) +nss_builtins_CreateSession( + NSSCKFWSession *fwSession, + CK_RV *pError) { - NSSArena *arena; - NSSCKMDSession *rv; + NSSArena *arena; + NSSCKMDSession *rv; - arena = NSSCKFWSession_GetArena(fwSession, pError); - if( (NSSArena *)NULL == arena ) { - return (NSSCKMDSession *)NULL; - } + arena = NSSCKFWSession_GetArena(fwSession, pError); + if ((NSSArena *)NULL == arena) { + return (NSSCKMDSession *)NULL; + } - rv = nss_ZNEW(arena, NSSCKMDSession); - if( (NSSCKMDSession *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDSession *)NULL; - } + rv = nss_ZNEW(arena, NSSCKMDSession); + if ((NSSCKMDSession *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDSession *)NULL; + } - /* - * rv was zeroed when allocated, so we only - * need to set the non-zero members. - */ + /* + * rv was zeroed when allocated, so we only + * need to set the non-zero members. + */ - rv->etc = (void *)fwSession; - /* rv->Close */ - /* rv->GetDeviceError */ - /* rv->Login */ - /* rv->Logout */ - /* rv->InitPIN */ - /* rv->SetPIN */ - /* rv->GetOperationStateLen */ - /* rv->GetOperationState */ - /* rv->SetOperationState */ - /* rv->CreateObject */ - /* rv->CopyObject */ - rv->FindObjectsInit = builtins_mdSession_FindObjectsInit; - /* rv->SeedRandom */ - /* rv->GetRandom */ - /* rv->null */ + rv->etc = (void *)fwSession; + /* rv->Close */ + /* rv->GetDeviceError */ + /* rv->Login */ + /* rv->Logout */ + /* rv->InitPIN */ + /* rv->SetPIN */ + /* rv->GetOperationStateLen */ + /* rv->GetOperationState */ + /* rv->SetOperationState */ + /* rv->CreateObject */ + /* rv->CopyObject */ + rv->FindObjectsInit = builtins_mdSession_FindObjectsInit; + /* rv->SeedRandom */ + /* rv->GetRandom */ + /* rv->null */ - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/builtins/bslot.c b/security/nss/lib/ckfw/builtins/bslot.c index 7cc9dcde0c05..f2ef1efb92c2 100644 --- a/security/nss/lib/ckfw/builtins/bslot.c +++ b/security/nss/lib/ckfw/builtins/bslot.c @@ -12,80 +12,70 @@ */ static NSSUTF8 * -builtins_mdSlot_GetSlotDescription -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdSlot_GetSlotDescription( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_SlotDescription; + return (NSSUTF8 *)nss_builtins_SlotDescription; } static NSSUTF8 * -builtins_mdSlot_GetManufacturerID -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdSlot_GetManufacturerID( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_ManufacturerID; + return (NSSUTF8 *)nss_builtins_ManufacturerID; } static CK_VERSION -builtins_mdSlot_GetHardwareVersion -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdSlot_GetHardwareVersion( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_builtins_HardwareVersion; + return nss_builtins_HardwareVersion; } static CK_VERSION -builtins_mdSlot_GetFirmwareVersion -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdSlot_GetFirmwareVersion( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_builtins_FirmwareVersion; + return nss_builtins_FirmwareVersion; } static NSSCKMDToken * -builtins_mdSlot_GetToken -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdSlot_GetToken( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSCKMDToken *)&nss_builtins_mdToken; + return (NSSCKMDToken *)&nss_builtins_mdToken; } const NSSCKMDSlot -nss_builtins_mdSlot = { - (void *)NULL, /* etc */ - NULL, /* Initialize */ - NULL, /* Destroy */ - builtins_mdSlot_GetSlotDescription, - builtins_mdSlot_GetManufacturerID, - NULL, /* GetTokenPresent -- defaults to true */ - NULL, /* GetRemovableDevice -- defaults to false */ - NULL, /* GetHardwareSlot -- defaults to false */ - builtins_mdSlot_GetHardwareVersion, - builtins_mdSlot_GetFirmwareVersion, - builtins_mdSlot_GetToken, - (void *)NULL /* null terminator */ -}; + nss_builtins_mdSlot = { + (void *)NULL, /* etc */ + NULL, /* Initialize */ + NULL, /* Destroy */ + builtins_mdSlot_GetSlotDescription, + builtins_mdSlot_GetManufacturerID, + NULL, /* GetTokenPresent -- defaults to true */ + NULL, /* GetRemovableDevice -- defaults to false */ + NULL, /* GetHardwareSlot -- defaults to false */ + builtins_mdSlot_GetHardwareVersion, + builtins_mdSlot_GetFirmwareVersion, + builtins_mdSlot_GetToken, + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/builtins/btoken.c b/security/nss/lib/ckfw/builtins/btoken.c index a68d51151811..ae1e1380bda2 100644 --- a/security/nss/lib/ckfw/builtins/btoken.c +++ b/security/nss/lib/ckfw/builtins/btoken.c @@ -12,140 +12,124 @@ */ static NSSUTF8 * -builtins_mdToken_GetLabel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdToken_GetLabel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_TokenLabel; + return (NSSUTF8 *)nss_builtins_TokenLabel; } static NSSUTF8 * -builtins_mdToken_GetManufacturerID -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdToken_GetManufacturerID( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_ManufacturerID; + return (NSSUTF8 *)nss_builtins_ManufacturerID; } static NSSUTF8 * -builtins_mdToken_GetModel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdToken_GetModel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_TokenModel; + return (NSSUTF8 *)nss_builtins_TokenModel; } static NSSUTF8 * -builtins_mdToken_GetSerialNumber -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +builtins_mdToken_GetSerialNumber( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_builtins_TokenSerialNumber; + return (NSSUTF8 *)nss_builtins_TokenSerialNumber; } static CK_BBOOL -builtins_mdToken_GetIsWriteProtected -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdToken_GetIsWriteProtected( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_TRUE; + return CK_TRUE; } static CK_VERSION -builtins_mdToken_GetHardwareVersion -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdToken_GetHardwareVersion( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_builtins_HardwareVersion; + return nss_builtins_HardwareVersion; } static CK_VERSION -builtins_mdToken_GetFirmwareVersion -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +builtins_mdToken_GetFirmwareVersion( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_builtins_FirmwareVersion; + return nss_builtins_FirmwareVersion; } static NSSCKMDSession * -builtins_mdToken_OpenSession -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession, - CK_BBOOL rw, - CK_RV *pError -) +builtins_mdToken_OpenSession( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession, + CK_BBOOL rw, + CK_RV *pError) { - return nss_builtins_CreateSession(fwSession, pError); + return nss_builtins_CreateSession(fwSession, pError); } const NSSCKMDToken -nss_builtins_mdToken = { - (void *)NULL, /* etc */ - NULL, /* Setup */ - NULL, /* Invalidate */ - NULL, /* InitToken -- default errs */ - builtins_mdToken_GetLabel, - builtins_mdToken_GetManufacturerID, - builtins_mdToken_GetModel, - builtins_mdToken_GetSerialNumber, - NULL, /* GetHasRNG -- default is false */ - builtins_mdToken_GetIsWriteProtected, - NULL, /* GetLoginRequired -- default is false */ - NULL, /* GetUserPinInitialized -- default is false */ - NULL, /* GetRestoreKeyNotNeeded -- irrelevant */ - NULL, /* GetHasClockOnToken -- default is false */ - NULL, /* GetHasProtectedAuthenticationPath -- default is false */ - NULL, /* GetSupportsDualCryptoOperations -- default is false */ - NULL, /* GetMaxSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetMaxRwSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetMaxPinLen -- irrelevant */ - NULL, /* GetMinPinLen -- irrelevant */ - NULL, /* GetTotalPublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetFreePublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetTotalPrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetFreePrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ - builtins_mdToken_GetHardwareVersion, - builtins_mdToken_GetFirmwareVersion, - NULL, /* GetUTCTime -- no clock */ - builtins_mdToken_OpenSession, - NULL, /* GetMechanismCount -- default is zero */ - NULL, /* GetMechanismTypes -- irrelevant */ - NULL, /* GetMechanism -- irrelevant */ - (void *)NULL /* null terminator */ -}; + nss_builtins_mdToken = { + (void *)NULL, /* etc */ + NULL, /* Setup */ + NULL, /* Invalidate */ + NULL, /* InitToken -- default errs */ + builtins_mdToken_GetLabel, + builtins_mdToken_GetManufacturerID, + builtins_mdToken_GetModel, + builtins_mdToken_GetSerialNumber, + NULL, /* GetHasRNG -- default is false */ + builtins_mdToken_GetIsWriteProtected, + NULL, /* GetLoginRequired -- default is false */ + NULL, /* GetUserPinInitialized -- default is false */ + NULL, /* GetRestoreKeyNotNeeded -- irrelevant */ + NULL, /* GetHasClockOnToken -- default is false */ + NULL, /* GetHasProtectedAuthenticationPath -- default is false */ + NULL, /* GetSupportsDualCryptoOperations -- default is false */ + NULL, /* GetMaxSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetMaxRwSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetMaxPinLen -- irrelevant */ + NULL, /* GetMinPinLen -- irrelevant */ + NULL, /* GetTotalPublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetFreePublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetTotalPrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetFreePrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ + builtins_mdToken_GetHardwareVersion, + builtins_mdToken_GetFirmwareVersion, + NULL, /* GetUTCTime -- no clock */ + builtins_mdToken_OpenSession, + NULL, /* GetMechanismCount -- default is zero */ + NULL, /* GetMechanismTypes -- irrelevant */ + NULL, /* GetMechanism -- irrelevant */ + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/builtins/builtins.h b/security/nss/lib/ckfw/builtins/builtins.h index a4a90f16c7b8..a1693c29ca45 100644 --- a/security/nss/lib/ckfw/builtins/builtins.h +++ b/security/nss/lib/ckfw/builtins/builtins.h @@ -21,52 +21,46 @@ #endif /* CKT_H */ struct builtinsInternalObjectStr { - CK_ULONG n; - const CK_ATTRIBUTE_TYPE *types; - const NSSItem *items; - NSSCKMDObject mdObject; + CK_ULONG n; + const CK_ATTRIBUTE_TYPE *types; + const NSSItem *items; + NSSCKMDObject mdObject; }; typedef struct builtinsInternalObjectStr builtinsInternalObject; -extern builtinsInternalObject nss_builtins_data[]; -extern const PRUint32 nss_builtins_nObjects; +extern builtinsInternalObject nss_builtins_data[]; +extern const PRUint32 nss_builtins_nObjects; -extern const CK_VERSION nss_builtins_CryptokiVersion; -extern const CK_VERSION nss_builtins_LibraryVersion; -extern const CK_VERSION nss_builtins_HardwareVersion; -extern const CK_VERSION nss_builtins_FirmwareVersion; +extern const CK_VERSION nss_builtins_CryptokiVersion; +extern const CK_VERSION nss_builtins_LibraryVersion; +extern const CK_VERSION nss_builtins_HardwareVersion; +extern const CK_VERSION nss_builtins_FirmwareVersion; -extern const NSSUTF8 nss_builtins_ManufacturerID[]; -extern const NSSUTF8 nss_builtins_LibraryDescription[]; -extern const NSSUTF8 nss_builtins_SlotDescription[]; -extern const NSSUTF8 nss_builtins_TokenLabel[]; -extern const NSSUTF8 nss_builtins_TokenModel[]; -extern const NSSUTF8 nss_builtins_TokenSerialNumber[]; +extern const NSSUTF8 nss_builtins_ManufacturerID[]; +extern const NSSUTF8 nss_builtins_LibraryDescription[]; +extern const NSSUTF8 nss_builtins_SlotDescription[]; +extern const NSSUTF8 nss_builtins_TokenLabel[]; +extern const NSSUTF8 nss_builtins_TokenModel[]; +extern const NSSUTF8 nss_builtins_TokenSerialNumber[]; extern const NSSCKMDInstance nss_builtins_mdInstance; -extern const NSSCKMDSlot nss_builtins_mdSlot; -extern const NSSCKMDToken nss_builtins_mdToken; +extern const NSSCKMDSlot nss_builtins_mdSlot; +extern const NSSCKMDToken nss_builtins_mdToken; NSS_EXTERN NSSCKMDSession * -nss_builtins_CreateSession -( - NSSCKFWSession *fwSession, - CK_RV *pError -); +nss_builtins_CreateSession( + NSSCKFWSession *fwSession, + CK_RV *pError); NSS_EXTERN NSSCKMDFindObjects * -nss_builtins_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nss_builtins_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); NSS_EXTERN NSSCKMDObject * -nss_builtins_CreateMDObject -( - NSSArena *arena, - builtinsInternalObject *io, - CK_RV *pError -); +nss_builtins_CreateMDObject( + NSSArena *arena, + builtinsInternalObject *io, + CK_RV *pError); diff --git a/security/nss/lib/ckfw/builtins/ckbiver.c b/security/nss/lib/ckfw/builtins/ckbiver.c index 41783b2fbb1e..208066ca36f7 100644 --- a/security/nss/lib/ckfw/builtins/ckbiver.c +++ b/security/nss/lib/ckfw/builtins/ckbiver.c @@ -15,5 +15,4 @@ /* * Version information */ -const char __nss_builtins_version[] = "Version: NSS Builtin Trusted Root CAs " - NSS_BUILTINS_LIBRARY_VERSION _DEBUG_STRING; +const char __nss_builtins_version[] = "Version: NSS Builtin Trusted Root CAs " NSS_BUILTINS_LIBRARY_VERSION _DEBUG_STRING; diff --git a/security/nss/lib/ckfw/builtins/constants.c b/security/nss/lib/ckfw/builtins/constants.c index 71146e60d45d..f5d267b3d0d7 100644 --- a/security/nss/lib/ckfw/builtins/constants.c +++ b/security/nss/lib/ckfw/builtins/constants.c @@ -21,41 +21,44 @@ #endif /* NSSCKBI_H */ const CK_VERSION -nss_builtins_CryptokiVersion = { - NSS_BUILTINS_CRYPTOKI_VERSION_MAJOR, - NSS_BUILTINS_CRYPTOKI_VERSION_MINOR }; + nss_builtins_CryptokiVersion = { + NSS_BUILTINS_CRYPTOKI_VERSION_MAJOR, + NSS_BUILTINS_CRYPTOKI_VERSION_MINOR + }; const CK_VERSION -nss_builtins_LibraryVersion = { - NSS_BUILTINS_LIBRARY_VERSION_MAJOR, - NSS_BUILTINS_LIBRARY_VERSION_MINOR}; + nss_builtins_LibraryVersion = { + NSS_BUILTINS_LIBRARY_VERSION_MAJOR, + NSS_BUILTINS_LIBRARY_VERSION_MINOR + }; const CK_VERSION -nss_builtins_HardwareVersion = { - NSS_BUILTINS_HARDWARE_VERSION_MAJOR, - NSS_BUILTINS_HARDWARE_VERSION_MINOR }; + nss_builtins_HardwareVersion = { + NSS_BUILTINS_HARDWARE_VERSION_MAJOR, + NSS_BUILTINS_HARDWARE_VERSION_MINOR + }; const CK_VERSION -nss_builtins_FirmwareVersion = { - NSS_BUILTINS_FIRMWARE_VERSION_MAJOR, - NSS_BUILTINS_FIRMWARE_VERSION_MINOR }; + nss_builtins_FirmwareVersion = { + NSS_BUILTINS_FIRMWARE_VERSION_MAJOR, + NSS_BUILTINS_FIRMWARE_VERSION_MINOR + }; -const NSSUTF8 -nss_builtins_ManufacturerID[] = { "Mozilla Foundation" }; +const NSSUTF8 + nss_builtins_ManufacturerID[] = { "Mozilla Foundation" }; -const NSSUTF8 -nss_builtins_LibraryDescription[] = { "NSS Builtin Object Cryptoki Module" }; +const NSSUTF8 + nss_builtins_LibraryDescription[] = { "NSS Builtin Object Cryptoki Module" }; -const NSSUTF8 -nss_builtins_SlotDescription[] = { "NSS Builtin Objects" }; +const NSSUTF8 + nss_builtins_SlotDescription[] = { "NSS Builtin Objects" }; -const NSSUTF8 -nss_builtins_TokenLabel[] = { "Builtin Object Token" }; +const NSSUTF8 + nss_builtins_TokenLabel[] = { "Builtin Object Token" }; -const NSSUTF8 -nss_builtins_TokenModel[] = { "1" }; +const NSSUTF8 + nss_builtins_TokenModel[] = { "1" }; /* should this be e.g. the certdata.txt RCS revision number? */ -const NSSUTF8 -nss_builtins_TokenSerialNumber[] = { "1" }; - +const NSSUTF8 + nss_builtins_TokenSerialNumber[] = { "1" }; diff --git a/security/nss/lib/ckfw/builtins/nssckbi.h b/security/nss/lib/ckfw/builtins/nssckbi.h index 5ef3a49fbc8a..3ee2e83af30f 100644 --- a/security/nss/lib/ckfw/builtins/nssckbi.h +++ b/security/nss/lib/ckfw/builtins/nssckbi.h @@ -18,7 +18,7 @@ #define NSS_BUILTINS_CRYPTOKI_VERSION_MAJOR 2 #define NSS_BUILTINS_CRYPTOKI_VERSION_MINOR 20 -/* These version numbers detail the changes +/* These version numbers detail the changes * to the list of trusted certificates. * * The NSS_BUILTINS_LIBRARY_VERSION_MINOR macro needs to be bumped @@ -52,7 +52,7 @@ #define NSS_BUILTINS_HARDWARE_VERSION_MAJOR 1 #define NSS_BUILTINS_HARDWARE_VERSION_MINOR 0 -/* These version numbers detail the semantic changes to ckbi itself +/* These version numbers detail the semantic changes to ckbi itself * (new PKCS #11 objects), etc. */ #define NSS_BUILTINS_FIRMWARE_VERSION_MAJOR 1 #define NSS_BUILTINS_FIRMWARE_VERSION_MINOR 0 diff --git a/security/nss/lib/ckfw/capi/anchor.c b/security/nss/lib/ckfw/capi/anchor.c index 97f3f0d01778..c8aff60392d4 100644 --- a/security/nss/lib/ckfw/capi/anchor.c +++ b/security/nss/lib/ckfw/capi/anchor.c @@ -6,12 +6,12 @@ * capi/canchor.c * * This file "anchors" the actual cryptoki entry points in this module's - * shared library, which is required for dynamic loading. See the + * shared library, which is required for dynamic loading. See the * comments in nssck.api for more information. */ #include "ckcapi.h" #define MODULE_NAME ckcapi -#define INSTANCE_NAME (NSSCKMDInstance *)&nss_ckcapi_mdInstance +#define INSTANCE_NAME (NSSCKMDInstance *) & nss_ckcapi_mdInstance #include "nssck.api" diff --git a/security/nss/lib/ckfw/capi/cfind.c b/security/nss/lib/ckfw/capi/cfind.c index c17ed3c0e570..5fb11e35e51d 100644 --- a/security/nss/lib/ckfw/capi/cfind.c +++ b/security/nss/lib/ckfw/capi/cfind.c @@ -14,245 +14,237 @@ */ struct ckcapiFOStr { - NSSArena *arena; - CK_ULONG n; - CK_ULONG i; - ckcapiInternalObject **objs; + NSSArena *arena; + CK_ULONG n; + CK_ULONG i; + ckcapiInternalObject **objs; }; static void -ckcapi_mdFindObjects_Final -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdFindObjects_Final( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - struct ckcapiFOStr *fo = (struct ckcapiFOStr *)mdFindObjects->etc; - NSSArena *arena = fo->arena; - PRUint32 i; + struct ckcapiFOStr *fo = (struct ckcapiFOStr *)mdFindObjects->etc; + NSSArena *arena = fo->arena; + PRUint32 i; - /* walk down an free the unused 'objs' */ - for (i=fo->i; i < fo->n ; i++) { - nss_ckcapi_DestroyInternalObject(fo->objs[i]); - } + /* walk down an free the unused 'objs' */ + for (i = fo->i; i < fo->n; i++) { + nss_ckcapi_DestroyInternalObject(fo->objs[i]); + } - nss_ZFreeIf(fo->objs); - nss_ZFreeIf(fo); - nss_ZFreeIf(mdFindObjects); - if ((NSSArena *)NULL != arena) { - NSSArena_Destroy(arena); - } + nss_ZFreeIf(fo->objs); + nss_ZFreeIf(fo); + nss_ZFreeIf(mdFindObjects); + if ((NSSArena *)NULL != arena) { + NSSArena_Destroy(arena); + } - return; + return; } static NSSCKMDObject * -ckcapi_mdFindObjects_Next -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +ckcapi_mdFindObjects_Next( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { - struct ckcapiFOStr *fo = (struct ckcapiFOStr *)mdFindObjects->etc; - ckcapiInternalObject *io; + struct ckcapiFOStr *fo = (struct ckcapiFOStr *)mdFindObjects->etc; + ckcapiInternalObject *io; - if( fo->i == fo->n ) { - *pError = CKR_OK; - return (NSSCKMDObject *)NULL; - } + if (fo->i == fo->n) { + *pError = CKR_OK; + return (NSSCKMDObject *)NULL; + } - io = fo->objs[ fo->i ]; - fo->i++; + io = fo->objs[fo->i]; + fo->i++; - return nss_ckcapi_CreateMDObject(arena, io, pError); + return nss_ckcapi_CreateMDObject(arena, io, pError); } static CK_BBOOL -ckcapi_attrmatch -( - CK_ATTRIBUTE_PTR a, - ckcapiInternalObject *o -) +ckcapi_attrmatch( + CK_ATTRIBUTE_PTR a, + ckcapiInternalObject *o) { - PRBool prb; - const NSSItem *b; + PRBool prb; + const NSSItem *b; - b = nss_ckcapi_FetchAttribute(o, a->type); - if (b == NULL) { - return CK_FALSE; - } - - if( a->ulValueLen != b->size ) { - /* match a decoded serial number */ - if ((a->type == CKA_SERIAL_NUMBER) && (a->ulValueLen < b->size)) { - unsigned int len; - unsigned char *data; - - data = nss_ckcapi_DERUnwrap(b->data, b->size, &len, NULL); - if ((len == a->ulValueLen) && - nsslibc_memequal(a->pValue, data, len, (PRStatus *)NULL)) { - return CK_TRUE; - } + b = nss_ckcapi_FetchAttribute(o, a->type); + if (b == NULL) { + return CK_FALSE; } - return CK_FALSE; - } - prb = nsslibc_memequal(a->pValue, b->data, b->size, (PRStatus *)NULL); + if (a->ulValueLen != b->size) { + /* match a decoded serial number */ + if ((a->type == CKA_SERIAL_NUMBER) && (a->ulValueLen < b->size)) { + unsigned int len; + unsigned char *data; - if( PR_TRUE == prb ) { + data = nss_ckcapi_DERUnwrap(b->data, b->size, &len, NULL); + if ((len == a->ulValueLen) && + nsslibc_memequal(a->pValue, data, len, (PRStatus *)NULL)) { + return CK_TRUE; + } + } + return CK_FALSE; + } + + prb = nsslibc_memequal(a->pValue, b->data, b->size, (PRStatus *)NULL); + + if (PR_TRUE == prb) { + return CK_TRUE; + } + else { + return CK_FALSE; + } +} + +static CK_BBOOL +ckcapi_match( + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckcapiInternalObject *o) +{ + CK_ULONG i; + + for (i = 0; i < ulAttributeCount; i++) { + if (CK_FALSE == ckcapi_attrmatch(&pTemplate[i], o)) { + return CK_FALSE; + } + } + + /* Every attribute passed */ return CK_TRUE; - } else { - return CK_FALSE; - } } +#define CKAPI_ITEM_CHUNK 20 -static CK_BBOOL -ckcapi_match -( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckcapiInternalObject *o -) -{ - CK_ULONG i; - - for( i = 0; i < ulAttributeCount; i++ ) { - if (CK_FALSE == ckcapi_attrmatch(&pTemplate[i], o)) { - return CK_FALSE; +#define PUT_Object(obj, err) \ + { \ + if (count >= size) { \ + *listp = *listp ? \ + nss_ZREALLOCARRAY(*listp, ckcapiInternalObject *, \ + (size + \ + CKAPI_ITEM_CHUNK)) \ + : \ + nss_ZNEWARRAY(NULL, ckcapiInternalObject *, \ + (size + \ + CKAPI_ITEM_CHUNK)); \ + if ((ckcapiInternalObject **)NULL == *listp) { \ + err = CKR_HOST_MEMORY; \ + goto loser; \ + } \ + size += CKAPI_ITEM_CHUNK; \ + } \ + (*listp)[count] = (obj); \ + count++; \ } - } - - /* Every attribute passed */ - return CK_TRUE; -} - -#define CKAPI_ITEM_CHUNK 20 - -#define PUT_Object(obj,err) \ - { \ - if (count >= size) { \ - *listp = *listp ? \ - nss_ZREALLOCARRAY(*listp, ckcapiInternalObject *, \ - (size+CKAPI_ITEM_CHUNK) ) : \ - nss_ZNEWARRAY(NULL, ckcapiInternalObject *, \ - (size+CKAPI_ITEM_CHUNK) ) ; \ - if ((ckcapiInternalObject **)NULL == *listp) { \ - err = CKR_HOST_MEMORY; \ - goto loser; \ - } \ - size += CKAPI_ITEM_CHUNK; \ - } \ - (*listp)[ count ] = (obj); \ - count++; \ - } - /* * pass parameters back through the callback. */ typedef struct BareCollectParamsStr { - CK_OBJECT_CLASS objClass; - CK_ATTRIBUTE_PTR pTemplate; - CK_ULONG ulAttributeCount; - ckcapiInternalObject ***listp; - PRUint32 size; - PRUint32 count; + CK_OBJECT_CLASS objClass; + CK_ATTRIBUTE_PTR pTemplate; + CK_ULONG ulAttributeCount; + ckcapiInternalObject ***listp; + PRUint32 size; + PRUint32 count; } BareCollectParams; /* collect_bare's callback. Called for each object that * supposedly has a PROVINDER_INFO property */ static BOOL WINAPI -doBareCollect -( - const CRYPT_HASH_BLOB *msKeyID, - DWORD flags, - void *reserved, - void *args, - DWORD cProp, - DWORD *propID, - void **propData, - DWORD *propSize -) +doBareCollect( + const CRYPT_HASH_BLOB *msKeyID, + DWORD flags, + void *reserved, + void *args, + DWORD cProp, + DWORD *propID, + void **propData, + DWORD *propSize) { - BareCollectParams *bcp = (BareCollectParams *) args; - PRUint32 size = bcp->size; - PRUint32 count = bcp->count; - ckcapiInternalObject ***listp = bcp->listp; - ckcapiInternalObject *io = NULL; - DWORD i; - CRYPT_KEY_PROV_INFO *keyProvInfo = NULL; - void *idData; - CK_RV error; - - /* make sure there is a Key Provider Info property */ - for (i=0; i < cProp; i++) { - if (CERT_KEY_PROV_INFO_PROP_ID == propID[i]) { - keyProvInfo = (CRYPT_KEY_PROV_INFO *)propData[i]; - break; + BareCollectParams *bcp = (BareCollectParams *)args; + PRUint32 size = bcp->size; + PRUint32 count = bcp->count; + ckcapiInternalObject ***listp = bcp->listp; + ckcapiInternalObject *io = NULL; + DWORD i; + CRYPT_KEY_PROV_INFO *keyProvInfo = NULL; + void *idData; + CK_RV error; + + /* make sure there is a Key Provider Info property */ + for (i = 0; i < cProp; i++) { + if (CERT_KEY_PROV_INFO_PROP_ID == propID[i]) { + keyProvInfo = (CRYPT_KEY_PROV_INFO *)propData[i]; + break; + } } - } - if ((CRYPT_KEY_PROV_INFO *)NULL == keyProvInfo) { + if ((CRYPT_KEY_PROV_INFO *)NULL == keyProvInfo) { + return 1; + } + + /* copy the key ID */ + idData = nss_ZNEWARRAY(NULL, char, msKeyID->cbData); + if ((void *)NULL == idData) { + goto loser; + } + nsslibc_memcpy(idData, msKeyID->pbData, msKeyID->cbData); + + /* build a bare internal object */ + io = nss_ZNEW(NULL, ckcapiInternalObject); + if ((ckcapiInternalObject *)NULL == io) { + goto loser; + } + io->type = ckcapiBareKey; + io->objClass = bcp->objClass; + io->u.key.provInfo = *keyProvInfo; + io->u.key.provInfo.pwszContainerName = + nss_ckcapi_WideDup(keyProvInfo->pwszContainerName); + io->u.key.provInfo.pwszProvName = + nss_ckcapi_WideDup(keyProvInfo->pwszProvName); + io->u.key.provName = nss_ckcapi_WideToUTF8(keyProvInfo->pwszProvName); + io->u.key.containerName = + nss_ckcapi_WideToUTF8(keyProvInfo->pwszContainerName); + io->u.key.hProv = 0; + io->idData = idData; + io->id.data = idData; + io->id.size = msKeyID->cbData; + idData = NULL; + + /* see if it matches */ + if (CK_FALSE == ckcapi_match(bcp->pTemplate, bcp->ulAttributeCount, io)) { + goto loser; + } + PUT_Object(io, error); + bcp->size = size; + bcp->count = count; return 1; - } - - /* copy the key ID */ - idData = nss_ZNEWARRAY(NULL, char, msKeyID->cbData); - if ((void *)NULL == idData) { - goto loser; - } - nsslibc_memcpy(idData, msKeyID->pbData, msKeyID->cbData); - - /* build a bare internal object */ - io = nss_ZNEW(NULL, ckcapiInternalObject); - if ((ckcapiInternalObject *)NULL == io) { - goto loser; - } - io->type = ckcapiBareKey; - io->objClass = bcp->objClass; - io->u.key.provInfo = *keyProvInfo; - io->u.key.provInfo.pwszContainerName = - nss_ckcapi_WideDup(keyProvInfo->pwszContainerName); - io->u.key.provInfo.pwszProvName = - nss_ckcapi_WideDup(keyProvInfo->pwszProvName); - io->u.key.provName = nss_ckcapi_WideToUTF8(keyProvInfo->pwszProvName); - io->u.key.containerName = - nss_ckcapi_WideToUTF8(keyProvInfo->pwszContainerName); - io->u.key.hProv = 0; - io->idData = idData; - io->id.data = idData; - io->id.size = msKeyID->cbData; - idData = NULL; - - /* see if it matches */ - if( CK_FALSE == ckcapi_match(bcp->pTemplate, bcp->ulAttributeCount, io) ) { - goto loser; - } - PUT_Object(io, error); - bcp->size = size; - bcp->count = count; - return 1; loser: - if (io) { - nss_ckcapi_DestroyInternalObject(io); - } - nss_ZFreeIf(idData); - return 1; + if (io) { + nss_ckcapi_DestroyInternalObject(io); + } + nss_ZFreeIf(idData); + return 1; } /* @@ -260,30 +252,29 @@ loser: */ static PRUint32 collect_bare( - CK_OBJECT_CLASS objClass, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckcapiInternalObject ***listp, - PRUint32 *sizep, - PRUint32 count, - CK_RV *pError -) + CK_OBJECT_CLASS objClass, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckcapiInternalObject ***listp, + PRUint32 *sizep, + PRUint32 count, + CK_RV *pError) { - BOOL rc; - BareCollectParams bareCollectParams; + BOOL rc; + BareCollectParams bareCollectParams; - bareCollectParams.objClass = objClass; - bareCollectParams.pTemplate = pTemplate; - bareCollectParams.ulAttributeCount = ulAttributeCount; - bareCollectParams.listp = listp; - bareCollectParams.size = *sizep; - bareCollectParams.count = count; + bareCollectParams.objClass = objClass; + bareCollectParams.pTemplate = pTemplate; + bareCollectParams.ulAttributeCount = ulAttributeCount; + bareCollectParams.listp = listp; + bareCollectParams.size = *sizep; + bareCollectParams.count = count; - rc = CryptEnumKeyIdentifierProperties(NULL, CERT_KEY_PROV_INFO_PROP_ID, 0, - NULL, NULL, &bareCollectParams, doBareCollect); + rc = CryptEnumKeyIdentifierProperties(NULL, CERT_KEY_PROV_INFO_PROP_ID, 0, + NULL, NULL, &bareCollectParams, doBareCollect); - *sizep = bareCollectParams.size; - return bareCollectParams.count; + *sizep = bareCollectParams.size; + return bareCollectParams.count; } /* find all the certs that represent the appropriate object (cert, priv key, or @@ -291,291 +282,286 @@ collect_bare( */ static PRUint32 collect_class( - CK_OBJECT_CLASS objClass, - LPCSTR storeStr, - PRBool hasID, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckcapiInternalObject ***listp, - PRUint32 *sizep, - PRUint32 count, - CK_RV *pError -) + CK_OBJECT_CLASS objClass, + LPCSTR storeStr, + PRBool hasID, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckcapiInternalObject ***listp, + PRUint32 *sizep, + PRUint32 count, + CK_RV *pError) { - PRUint32 size = *sizep; - ckcapiInternalObject *next = NULL; - HCERTSTORE hStore; - PCCERT_CONTEXT certContext = NULL; - PRBool isKey = - (objClass == CKO_PUBLIC_KEY) | (objClass == CKO_PRIVATE_KEY); + PRUint32 size = *sizep; + ckcapiInternalObject *next = NULL; + HCERTSTORE hStore; + PCCERT_CONTEXT certContext = NULL; + PRBool isKey = + (objClass == CKO_PUBLIC_KEY) | (objClass == CKO_PRIVATE_KEY); - hStore = CertOpenSystemStore((HCRYPTPROV)NULL, storeStr); - if (NULL == hStore) { - return count; /* none found does not imply an error */ - } + hStore = CertOpenSystemStore((HCRYPTPROV)NULL, storeStr); + if (NULL == hStore) { + return count; /* none found does not imply an error */ + } - /* FUTURE: use CertFindCertificateInStore to filter better -- so we don't + /* FUTURE: use CertFindCertificateInStore to filter better -- so we don't * have to enumerate all the certificates */ - while ((PCERT_CONTEXT) NULL != - (certContext= CertEnumCertificatesInStore(hStore, certContext))) { - /* first filter out non user certs if we are looking for keys */ - if (isKey) { - /* make sure there is a Key Provider Info property */ - CRYPT_KEY_PROV_INFO *keyProvInfo; - DWORD size = 0; - BOOL rv; - rv =CertGetCertificateContextProperty(certContext, - CERT_KEY_PROV_INFO_PROP_ID, NULL, &size); - if (!rv) { - int reason = GetLastError(); - /* we only care if it exists, we don't really need to fetch it yet */ - if (reason == CRYPT_E_NOT_FOUND) { - continue; - } - } - /* filter out the non-microsoft providers */ - keyProvInfo = (CRYPT_KEY_PROV_INFO *)nss_ZAlloc(NULL, size); - if (keyProvInfo) { - rv =CertGetCertificateContextProperty(certContext, - CERT_KEY_PROV_INFO_PROP_ID, keyProvInfo, &size); - if (rv) { - char *provName = nss_ckcapi_WideToUTF8(keyProvInfo->pwszProvName); - nss_ZFreeIf(keyProvInfo); + while ((PCERT_CONTEXT)NULL != + (certContext = CertEnumCertificatesInStore(hStore, certContext))) { + /* first filter out non user certs if we are looking for keys */ + if (isKey) { + /* make sure there is a Key Provider Info property */ + CRYPT_KEY_PROV_INFO *keyProvInfo; + DWORD size = 0; + BOOL rv; + rv = CertGetCertificateContextProperty(certContext, + CERT_KEY_PROV_INFO_PROP_ID, NULL, &size); + if (!rv) { + int reason = GetLastError(); + /* we only care if it exists, we don't really need to fetch it yet */ + if (reason == CRYPT_E_NOT_FOUND) { + continue; + } + } + /* filter out the non-microsoft providers */ + keyProvInfo = (CRYPT_KEY_PROV_INFO *)nss_ZAlloc(NULL, size); + if (keyProvInfo) { + rv = CertGetCertificateContextProperty(certContext, + CERT_KEY_PROV_INFO_PROP_ID, keyProvInfo, &size); + if (rv) { + char *provName = + nss_ckcapi_WideToUTF8(keyProvInfo->pwszProvName); + nss_ZFreeIf(keyProvInfo); - if (provName && - (strncmp(provName, "Microsoft", sizeof("Microsoft")-1) != 0)) { - continue; - } - } else { - int reason = GetLastError(); - /* we only care if it exists, we don't really need to fetch it yet */ - nss_ZFreeIf(keyProvInfo); - if (reason == CRYPT_E_NOT_FOUND) { - continue; - } - + if (provName && + (strncmp(provName, "Microsoft", sizeof("Microsoft") - + 1) != 0)) { + continue; + } + } + else { + int reason = + GetLastError(); + /* we only care if it exists, we don't really need to fetch it yet */ + nss_ZFreeIf(keyProvInfo); + if (reason == + CRYPT_E_NOT_FOUND) { + continue; + } + } + } + } + + if ((ckcapiInternalObject *)NULL == next) { + next = nss_ZNEW(NULL, ckcapiInternalObject); + if ((ckcapiInternalObject *)NULL == next) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + } + next->type = ckcapiCert; + next->objClass = objClass; + next->u.cert.certContext = certContext; + next->u.cert.hasID = hasID; + next->u.cert.certStore = storeStr; + if (CK_TRUE == ckcapi_match(pTemplate, ulAttributeCount, next)) { + /* clear cached values that may be dependent on our old certContext */ + memset(&next->u.cert, 0, sizeof(next->u.cert)); + /* get a 'permanent' context */ + next->u.cert.certContext = CertDuplicateCertificateContext(certContext); + next->objClass = objClass; + next->u.cert.certContext = certContext; + next->u.cert.hasID = hasID; + next->u.cert.certStore = storeStr; + PUT_Object(next, *pError); + next = NULL; /* need to allocate a new one now */ + } + else { + /* don't cache the values we just loaded */ + memset(&next->u.cert, 0, sizeof(next->u.cert)); } - } } - - if ((ckcapiInternalObject *)NULL == next) { - next = nss_ZNEW(NULL, ckcapiInternalObject); - if ((ckcapiInternalObject *)NULL == next) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - } - next->type = ckcapiCert; - next->objClass = objClass; - next->u.cert.certContext = certContext; - next->u.cert.hasID = hasID; - next->u.cert.certStore = storeStr; - if( CK_TRUE == ckcapi_match(pTemplate, ulAttributeCount, next) ) { - /* clear cached values that may be dependent on our old certContext */ - memset(&next->u.cert, 0, sizeof(next->u.cert)); - /* get a 'permanent' context */ - next->u.cert.certContext = CertDuplicateCertificateContext(certContext); - next->objClass = objClass; - next->u.cert.certContext = certContext; - next->u.cert.hasID = hasID; - next->u.cert.certStore = storeStr; - PUT_Object(next, *pError); - next = NULL; /* need to allocate a new one now */ - } else { - /* don't cache the values we just loaded */ - memset(&next->u.cert, 0, sizeof(next->u.cert)); - } - } loser: - CertCloseStore(hStore, 0); - nss_ZFreeIf(next); - *sizep = size; - return count; + CertCloseStore(hStore, 0); + nss_ZFreeIf(next); + *sizep = size; + return count; } NSS_IMPLEMENT PRUint32 nss_ckcapi_collect_all_certs( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckcapiInternalObject ***listp, - PRUint32 *sizep, - PRUint32 count, - CK_RV *pError -) + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckcapiInternalObject ***listp, + PRUint32 *sizep, + PRUint32 count, + CK_RV *pError) { - count = collect_class(CKO_CERTIFICATE, "My", PR_TRUE, pTemplate, - ulAttributeCount, listp, sizep, count, pError); - /*count = collect_class(CKO_CERTIFICATE, "AddressBook", PR_FALSE, pTemplate, + count = collect_class(CKO_CERTIFICATE, "My", PR_TRUE, pTemplate, + ulAttributeCount, listp, sizep, count, pError); + /*count = collect_class(CKO_CERTIFICATE, "AddressBook", PR_FALSE, pTemplate, ulAttributeCount, listp, sizep, count, pError); */ - count = collect_class(CKO_CERTIFICATE, "CA", PR_FALSE, pTemplate, - ulAttributeCount, listp, sizep, count, pError); - count = collect_class(CKO_CERTIFICATE, "Root", PR_FALSE, pTemplate, - ulAttributeCount, listp, sizep, count, pError); - count = collect_class(CKO_CERTIFICATE, "Trust", PR_FALSE, pTemplate, - ulAttributeCount, listp, sizep, count, pError); - count = collect_class(CKO_CERTIFICATE, "TrustedPeople", PR_FALSE, pTemplate, - ulAttributeCount, listp, sizep, count, pError); - count = collect_class(CKO_CERTIFICATE, "AuthRoot", PR_FALSE, pTemplate, - ulAttributeCount, listp, sizep, count, pError); - return count; + count = collect_class(CKO_CERTIFICATE, "CA", PR_FALSE, pTemplate, + ulAttributeCount, listp, sizep, count, pError); + count = collect_class(CKO_CERTIFICATE, "Root", PR_FALSE, pTemplate, + ulAttributeCount, listp, sizep, count, pError); + count = collect_class(CKO_CERTIFICATE, "Trust", PR_FALSE, pTemplate, + ulAttributeCount, listp, sizep, count, pError); + count = collect_class(CKO_CERTIFICATE, "TrustedPeople", PR_FALSE, pTemplate, + ulAttributeCount, listp, sizep, count, pError); + count = collect_class(CKO_CERTIFICATE, "AuthRoot", PR_FALSE, pTemplate, + ulAttributeCount, listp, sizep, count, pError); + return count; } CK_OBJECT_CLASS -ckcapi_GetObjectClass(CK_ATTRIBUTE_PTR pTemplate, +ckcapi_GetObjectClass(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount) { - CK_ULONG i; + CK_ULONG i; - for (i=0; i < ulAttributeCount; i++) - { - if (pTemplate[i].type == CKA_CLASS) { - return *(CK_OBJECT_CLASS *) pTemplate[i].pValue; + for (i = 0; i < ulAttributeCount; i++) { + if (pTemplate[i].type == CKA_CLASS) { + return *(CK_OBJECT_CLASS *)pTemplate[i].pValue; + } } - } - /* need to return a value that says 'fetch them all' */ - return CK_INVALID_HANDLE; + /* need to return a value that says 'fetch them all' */ + return CK_INVALID_HANDLE; } static PRUint32 collect_objects( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckcapiInternalObject ***listp, - CK_RV *pError -) + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckcapiInternalObject ***listp, + CK_RV *pError) { - PRUint32 i; - PRUint32 count = 0; - PRUint32 size = 0; - CK_OBJECT_CLASS objClass; + PRUint32 i; + PRUint32 count = 0; + PRUint32 size = 0; + CK_OBJECT_CLASS objClass; - /* - * first handle the static build in objects (if any) - */ - for( i = 0; i < nss_ckcapi_nObjects; i++ ) { - ckcapiInternalObject *o = (ckcapiInternalObject *)&nss_ckcapi_data[i]; + /* + * first handle the static build in objects (if any) + */ + for (i = 0; i < nss_ckcapi_nObjects; i++) { + ckcapiInternalObject *o = (ckcapiInternalObject *)&nss_ckcapi_data[i]; - if( CK_TRUE == ckcapi_match(pTemplate, ulAttributeCount, o) ) { - PUT_Object(o, *pError); + if (CK_TRUE == ckcapi_match(pTemplate, ulAttributeCount, o)) { + PUT_Object(o, *pError); + } } - } - - /* - * now handle the various object types - */ - objClass = ckcapi_GetObjectClass(pTemplate, ulAttributeCount); - *pError = CKR_OK; - switch (objClass) { - case CKO_CERTIFICATE: - count = nss_ckcapi_collect_all_certs(pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - case CKO_PUBLIC_KEY: - count = collect_class(objClass, "My", PR_TRUE, pTemplate, - ulAttributeCount, listp, &size, count, pError); - count = collect_bare(objClass, pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - case CKO_PRIVATE_KEY: - count = collect_class(objClass, "My", PR_TRUE, pTemplate, - ulAttributeCount, listp, &size, count, pError); - count = collect_bare(objClass, pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - /* all of them */ - case CK_INVALID_HANDLE: - count = nss_ckcapi_collect_all_certs(pTemplate, ulAttributeCount, listp, - &size, count, pError); - count = collect_class(CKO_PUBLIC_KEY, "My", PR_TRUE, pTemplate, - ulAttributeCount, listp, &size, count, pError); - count = collect_bare(CKO_PUBLIC_KEY, pTemplate, ulAttributeCount, listp, - &size, count, pError); - count = collect_class(CKO_PRIVATE_KEY, "My", PR_TRUE, pTemplate, - ulAttributeCount, listp, &size, count, pError); - count = collect_bare(CKO_PRIVATE_KEY, pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - default: - goto done; /* no other object types we understand in this module */ - } - if (CKR_OK != *pError) { - goto loser; - } + /* + * now handle the various object types + */ + objClass = ckcapi_GetObjectClass(pTemplate, ulAttributeCount); + *pError = CKR_OK; + switch (objClass) { + case CKO_CERTIFICATE: + count = nss_ckcapi_collect_all_certs(pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + case CKO_PUBLIC_KEY: + count = collect_class(objClass, "My", PR_TRUE, pTemplate, + ulAttributeCount, listp, &size, count, pError); + count = collect_bare(objClass, pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + case CKO_PRIVATE_KEY: + count = collect_class(objClass, "My", PR_TRUE, pTemplate, + ulAttributeCount, listp, &size, count, pError); + count = collect_bare(objClass, pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + /* all of them */ + case CK_INVALID_HANDLE: + count = nss_ckcapi_collect_all_certs(pTemplate, ulAttributeCount, listp, + &size, count, pError); + count = collect_class(CKO_PUBLIC_KEY, "My", PR_TRUE, pTemplate, + ulAttributeCount, listp, &size, count, pError); + count = collect_bare(CKO_PUBLIC_KEY, pTemplate, ulAttributeCount, listp, + &size, count, pError); + count = collect_class(CKO_PRIVATE_KEY, "My", PR_TRUE, pTemplate, + ulAttributeCount, listp, &size, count, pError); + count = collect_bare(CKO_PRIVATE_KEY, pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + default: + goto done; /* no other object types we understand in this module */ + } + if (CKR_OK != *pError) { + goto loser; + } done: - return count; + return count; loser: - nss_ZFreeIf(*listp); - return 0; + nss_ZFreeIf(*listp); + return 0; } - - NSS_IMPLEMENT NSSCKMDFindObjects * -nss_ckcapi_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckcapi_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - /* This could be made more efficient. I'm rather rushed. */ - NSSArena *arena; - NSSCKMDFindObjects *rv = (NSSCKMDFindObjects *)NULL; - struct ckcapiFOStr *fo = (struct ckcapiFOStr *)NULL; - ckcapiInternalObject **temp = (ckcapiInternalObject **)NULL; + /* This could be made more efficient. I'm rather rushed. */ + NSSArena *arena; + NSSCKMDFindObjects *rv = (NSSCKMDFindObjects *)NULL; + struct ckcapiFOStr *fo = (struct ckcapiFOStr *)NULL; + ckcapiInternalObject **temp = (ckcapiInternalObject **)NULL; - arena = NSSArena_Create(); - if( (NSSArena *)NULL == arena ) { - goto loser; - } + arena = NSSArena_Create(); + if ((NSSArena *)NULL == arena) { + goto loser; + } - rv = nss_ZNEW(arena, NSSCKMDFindObjects); - if( (NSSCKMDFindObjects *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + rv = nss_ZNEW(arena, NSSCKMDFindObjects); + if ((NSSCKMDFindObjects *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - fo = nss_ZNEW(arena, struct ckcapiFOStr); - if( (struct ckcapiFOStr *)NULL == fo ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + fo = nss_ZNEW(arena, struct ckcapiFOStr); + if ((struct ckcapiFOStr *)NULL == fo) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - fo->arena = arena; - /* fo->n and fo->i are already zero */ + fo->arena = arena; + /* fo->n and fo->i are already zero */ - rv->etc = (void *)fo; - rv->Final = ckcapi_mdFindObjects_Final; - rv->Next = ckcapi_mdFindObjects_Next; - rv->null = (void *)NULL; + rv->etc = (void *)fo; + rv->Final = ckcapi_mdFindObjects_Final; + rv->Next = ckcapi_mdFindObjects_Next; + rv->null = (void *)NULL; - fo->n = collect_objects(pTemplate, ulAttributeCount, &temp, pError); - if (*pError != CKR_OK) { - goto loser; - } + fo->n = collect_objects(pTemplate, ulAttributeCount, &temp, pError); + if (*pError != CKR_OK) { + goto loser; + } - fo->objs = nss_ZNEWARRAY(arena, ckcapiInternalObject *, fo->n); - if( (ckcapiInternalObject **)NULL == fo->objs ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + fo->objs = nss_ZNEWARRAY(arena, ckcapiInternalObject *, fo->n); + if ((ckcapiInternalObject **)NULL == fo->objs) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - (void)nsslibc_memcpy(fo->objs, temp, sizeof(ckcapiInternalObject *) * fo->n); - nss_ZFreeIf(temp); - temp = (ckcapiInternalObject **)NULL; + (void)nsslibc_memcpy(fo->objs, temp, sizeof(ckcapiInternalObject *) * fo->n); + nss_ZFreeIf(temp); + temp = (ckcapiInternalObject **)NULL; - return rv; + return rv; - loser: - nss_ZFreeIf(temp); - nss_ZFreeIf(fo); - nss_ZFreeIf(rv); - if ((NSSArena *)NULL != arena) { - NSSArena_Destroy(arena); - } - return (NSSCKMDFindObjects *)NULL; +loser: + nss_ZFreeIf(temp); + nss_ZFreeIf(fo); + nss_ZFreeIf(rv); + if ((NSSArena *)NULL != arena) { + NSSArena_Destroy(arena); + } + return (NSSCKMDFindObjects *)NULL; } - diff --git a/security/nss/lib/ckfw/capi/cinst.c b/security/nss/lib/ckfw/capi/cinst.c index 8aac1ca0c985..937c289a19b6 100644 --- a/security/nss/lib/ckfw/capi/cinst.c +++ b/security/nss/lib/ckfw/capi/cinst.c @@ -7,7 +7,7 @@ /* * ckcapi/cinstance.c * - * This file implements the NSSCKMDInstance object for the + * This file implements the NSSCKMDInstance object for the * "capi" cryptoki module. */ @@ -16,96 +16,82 @@ */ static CK_ULONG -ckcapi_mdInstance_GetNSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdInstance_GetNSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (CK_ULONG)1; + return (CK_ULONG)1; } static CK_VERSION -ckcapi_mdInstance_GetCryptokiVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdInstance_GetCryptokiVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckcapi_CryptokiVersion; + return nss_ckcapi_CryptokiVersion; } static NSSUTF8 * -ckcapi_mdInstance_GetManufacturerID -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdInstance_GetManufacturerID( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_ManufacturerID; + return (NSSUTF8 *)nss_ckcapi_ManufacturerID; } static NSSUTF8 * -ckcapi_mdInstance_GetLibraryDescription -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdInstance_GetLibraryDescription( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_LibraryDescription; + return (NSSUTF8 *)nss_ckcapi_LibraryDescription; } static CK_VERSION -ckcapi_mdInstance_GetLibraryVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdInstance_GetLibraryVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckcapi_LibraryVersion; + return nss_ckcapi_LibraryVersion; } static CK_RV -ckcapi_mdInstance_GetSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDSlot *slots[] -) +ckcapi_mdInstance_GetSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDSlot *slots[]) { - slots[0] = (NSSCKMDSlot *)&nss_ckcapi_mdSlot; - return CKR_OK; + slots[0] = (NSSCKMDSlot *)&nss_ckcapi_mdSlot; + return CKR_OK; } static CK_BBOOL -ckcapi_mdInstance_ModuleHandlesSessionObjects -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdInstance_ModuleHandlesSessionObjects( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - /* we don't want to allow any session object creation, at least - * until we can investigate whether or not we can use those objects - */ - return CK_TRUE; + /* we don't want to allow any session object creation, at least + * until we can investigate whether or not we can use those objects + */ + return CK_TRUE; } NSS_IMPLEMENT_DATA const NSSCKMDInstance -nss_ckcapi_mdInstance = { - (void *)NULL, /* etc */ - NULL, /* Initialize */ - NULL, /* Finalize */ - ckcapi_mdInstance_GetNSlots, - ckcapi_mdInstance_GetCryptokiVersion, - ckcapi_mdInstance_GetManufacturerID, - ckcapi_mdInstance_GetLibraryDescription, - ckcapi_mdInstance_GetLibraryVersion, - ckcapi_mdInstance_ModuleHandlesSessionObjects, - /*NULL, /* HandleSessionObjects */ - ckcapi_mdInstance_GetSlots, - NULL, /* WaitForSlotEvent */ - (void *)NULL /* null terminator */ -}; + nss_ckcapi_mdInstance = { + (void *)NULL, /* etc */ + NULL, /* Initialize */ + NULL, /* Finalize */ + ckcapi_mdInstance_GetNSlots, + ckcapi_mdInstance_GetCryptokiVersion, + ckcapi_mdInstance_GetManufacturerID, + ckcapi_mdInstance_GetLibraryDescription, + ckcapi_mdInstance_GetLibraryVersion, + ckcapi_mdInstance_ModuleHandlesSessionObjects, + /*NULL, /* HandleSessionObjects */ + ckcapi_mdInstance_GetSlots, + NULL, /* WaitForSlotEvent */ + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/capi/ckcapi.h b/security/nss/lib/ckfw/capi/ckcapi.h index 2ae01e35ffb5..2c4b12aac359 100644 --- a/security/nss/lib/ckfw/capi/ckcapi.h +++ b/security/nss/lib/ckfw/capi/ckcapi.h @@ -31,28 +31,27 @@ * to this PKCS #11 module. */ struct ckcapiRawObjectStr { - CK_ULONG n; - const CK_ATTRIBUTE_TYPE *types; - const NSSItem *items; + CK_ULONG n; + const CK_ATTRIBUTE_TYPE *types; + const NSSItem *items; }; typedef struct ckcapiRawObjectStr ckcapiRawObject; - /* * common values needed for both bare keys and cert referenced keys. */ struct ckcapiKeyParamsStr { - NSSItem modulus; - NSSItem exponent; - NSSItem privateExponent; - NSSItem prime1; - NSSItem prime2; - NSSItem exponent1; - NSSItem exponent2; - NSSItem coefficient; - unsigned char publicExponentData[sizeof(CK_ULONG)]; - void *privateKey; - void *pubKey; + NSSItem modulus; + NSSItem exponent; + NSSItem privateExponent; + NSSItem prime1; + NSSItem prime2; + NSSItem exponent1; + NSSItem exponent2; + NSSItem coefficient; + unsigned char publicExponentData[sizeof(CK_ULONG)]; + void *privateKey; + void *pubKey; }; typedef struct ckcapiKeyParamsStr ckcapiKeyParams; @@ -62,11 +61,11 @@ typedef struct ckcapiKeyParamsStr ckcapiKeyParams; * while the CA is issuing the certificate. */ struct ckcapiKeyObjectStr { - CRYPT_KEY_PROV_INFO provInfo; - char *provName; - char *containerName; - HCRYPTPROV hProv; - ckcapiKeyParams key; + CRYPT_KEY_PROV_INFO provInfo; + char *provName; + char *containerName; + HCRYPTPROV hProv; + ckcapiKeyParams key; }; typedef struct ckcapiKeyObjectStr ckcapiKeyObject; @@ -74,25 +73,25 @@ typedef struct ckcapiKeyObjectStr ckcapiKeyObject; * Certificate and certificate referenced keys. */ struct ckcapiCertObjectStr { - PCCERT_CONTEXT certContext; - PRBool hasID; - const char *certStore; - NSSItem label; - NSSItem subject; - NSSItem issuer; - NSSItem serial; - NSSItem derCert; - ckcapiKeyParams key; - unsigned char *labelData; - /* static data: to do, make this dynamic like labelData */ - unsigned char derSerial[128]; + PCCERT_CONTEXT certContext; + PRBool hasID; + const char *certStore; + NSSItem label; + NSSItem subject; + NSSItem issuer; + NSSItem serial; + NSSItem derCert; + ckcapiKeyParams key; + unsigned char *labelData; + /* static data: to do, make this dynamic like labelData */ + unsigned char derSerial[128]; }; typedef struct ckcapiCertObjectStr ckcapiCertObject; typedef enum { - ckcapiRaw, - ckcapiCert, - ckcapiBareKey + ckcapiRaw, + ckcapiCert, + ckcapiBareKey } ckcapiObjectType; /* @@ -100,98 +99,84 @@ typedef enum { * cfind as ckcapiInternalObjects. */ struct ckcapiInternalObjectStr { - ckcapiObjectType type; - union { - ckcapiRawObject raw; - ckcapiCertObject cert; - ckcapiKeyObject key; - } u; - CK_OBJECT_CLASS objClass; - NSSItem hashKey; - NSSItem id; - void *idData; - unsigned char hashKeyData[128]; - NSSCKMDObject mdObject; + ckcapiObjectType type; + union { + ckcapiRawObject raw; + ckcapiCertObject cert; + ckcapiKeyObject key; + } u; + CK_OBJECT_CLASS objClass; + NSSItem hashKey; + NSSItem id; + void *idData; + unsigned char hashKeyData[128]; + NSSCKMDObject mdObject; }; typedef struct ckcapiInternalObjectStr ckcapiInternalObject; /* our raw object data array */ NSS_EXTERN_DATA ckcapiInternalObject nss_ckcapi_data[]; -NSS_EXTERN_DATA const PRUint32 nss_ckcapi_nObjects; +NSS_EXTERN_DATA const PRUint32 nss_ckcapi_nObjects; -NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_CryptokiVersion; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckcapi_ManufacturerID; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckcapi_LibraryDescription; -NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_LibraryVersion; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckcapi_SlotDescription; -NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_HardwareVersion; -NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_FirmwareVersion; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckcapi_TokenLabel; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckcapi_TokenModel; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckcapi_TokenSerialNumber; +NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_CryptokiVersion; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckcapi_ManufacturerID; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckcapi_LibraryDescription; +NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_LibraryVersion; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckcapi_SlotDescription; +NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_HardwareVersion; +NSS_EXTERN_DATA const CK_VERSION nss_ckcapi_FirmwareVersion; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckcapi_TokenLabel; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckcapi_TokenModel; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckcapi_TokenSerialNumber; -NSS_EXTERN_DATA const NSSCKMDInstance nss_ckcapi_mdInstance; -NSS_EXTERN_DATA const NSSCKMDSlot nss_ckcapi_mdSlot; -NSS_EXTERN_DATA const NSSCKMDToken nss_ckcapi_mdToken; +NSS_EXTERN_DATA const NSSCKMDInstance nss_ckcapi_mdInstance; +NSS_EXTERN_DATA const NSSCKMDSlot nss_ckcapi_mdSlot; +NSS_EXTERN_DATA const NSSCKMDToken nss_ckcapi_mdToken; NSS_EXTERN_DATA const NSSCKMDMechanism nss_ckcapi_mdMechanismRSA; NSS_EXTERN NSSCKMDSession * -nss_ckcapi_CreateSession -( - NSSCKFWSession *fwSession, - CK_RV *pError -); +nss_ckcapi_CreateSession( + NSSCKFWSession *fwSession, + CK_RV *pError); NSS_EXTERN NSSCKMDFindObjects * -nss_ckcapi_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nss_ckcapi_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); /* * Object Utilities */ NSS_EXTERN NSSCKMDObject * -nss_ckcapi_CreateMDObject -( - NSSArena *arena, - ckcapiInternalObject *io, - CK_RV *pError -); +nss_ckcapi_CreateMDObject( + NSSArena *arena, + ckcapiInternalObject *io, + CK_RV *pError); NSS_EXTERN NSSCKMDObject * -nss_ckcapi_CreateObject -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nss_ckcapi_CreateObject( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); NSS_EXTERN const NSSItem * -nss_ckcapi_FetchAttribute -( - ckcapiInternalObject *io, - CK_ATTRIBUTE_TYPE type -); +nss_ckcapi_FetchAttribute( + ckcapiInternalObject *io, + CK_ATTRIBUTE_TYPE type); NSS_EXTERN void -nss_ckcapi_DestroyInternalObject -( - ckcapiInternalObject *io -); +nss_ckcapi_DestroyInternalObject( + ckcapiInternalObject *io); NSS_EXTERN CK_RV -nss_ckcapi_FetchKeyContainer -( - ckcapiInternalObject *iKey, - HCRYPTPROV *hProv, - DWORD *keySpec, - HCRYPTKEY *hKey -); +nss_ckcapi_FetchKeyContainer( + ckcapiInternalObject *iKey, + HCRYPTPROV *hProv, + DWORD *keySpec, + HCRYPTKEY *hKey); /* * generic utilities @@ -202,70 +187,56 @@ nss_ckcapi_FetchKeyContainer * Microsoft, we need to byte swap everything coming into and out of CAPI. */ void -ckcapi_ReverseData -( - NSSItem *item -); +ckcapi_ReverseData( + NSSItem *item); /* * unwrap a single DER value */ unsigned char * -nss_ckcapi_DERUnwrap -( - unsigned char *src, - unsigned int size, - unsigned int *outSize, - unsigned char **next -); +nss_ckcapi_DERUnwrap( + unsigned char *src, + unsigned int size, + unsigned int *outSize, + unsigned char **next); /* * Return the size in bytes of a wide string */ -int -nss_ckcapi_WideSize -( - LPCWSTR wide -); +int +nss_ckcapi_WideSize( + LPCWSTR wide); /* * Covert a Unicode wide character string to a UTF8 string */ char * -nss_ckcapi_WideToUTF8 -( - LPCWSTR wide -); +nss_ckcapi_WideToUTF8( + LPCWSTR wide); /* * Return a Wide String duplicated with nss allocated memory. */ LPWSTR -nss_ckcapi_WideDup -( - LPCWSTR wide -); +nss_ckcapi_WideDup( + LPCWSTR wide); /* * Covert a UTF8 string to Unicode wide character */ LPWSTR -nss_ckcapi_UTF8ToWide -( - char *buf -); - +nss_ckcapi_UTF8ToWide( + char *buf); NSS_EXTERN PRUint32 nss_ckcapi_collect_all_certs( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckcapiInternalObject ***listp, - PRUint32 *sizep, - PRUint32 count, - CK_RV *pError -); + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckcapiInternalObject ***listp, + PRUint32 *sizep, + PRUint32 count, + CK_RV *pError); + +#define NSS_CKCAPI_ARRAY_SIZE(x) ((sizeof(x)) / (sizeof((x)[0]))) -#define NSS_CKCAPI_ARRAY_SIZE(x) ((sizeof (x))/(sizeof ((x)[0]))) - #endif diff --git a/security/nss/lib/ckfw/capi/ckcapiver.c b/security/nss/lib/ckfw/capi/ckcapiver.c index 54e488756856..825b6307403e 100644 --- a/security/nss/lib/ckfw/capi/ckcapiver.c +++ b/security/nss/lib/ckfw/capi/ckcapiver.c @@ -14,5 +14,4 @@ /* * Version information */ -const char __nss_ckcapi_version[] = "Version: NSS Access to Microsoft Certificate Store " - NSS_CKCAPI_LIBRARY_VERSION _DEBUG_STRING; +const char __nss_ckcapi_version[] = "Version: NSS Access to Microsoft Certificate Store " NSS_CKCAPI_LIBRARY_VERSION _DEBUG_STRING; diff --git a/security/nss/lib/ckfw/capi/cobject.c b/security/nss/lib/ckfw/capi/cobject.c index 1da5f7d203aa..03a8a5e7b387 100644 --- a/security/nss/lib/ckfw/capi/cobject.c +++ b/security/nss/lib/ckfw/capi/cobject.c @@ -76,22 +76,30 @@ static const CK_KEY_TYPE ckk_rsa = CKK_RSA; static const CK_OBJECT_CLASS cko_certificate = CKO_CERTIFICATE; static const CK_OBJECT_CLASS cko_private_key = CKO_PRIVATE_KEY; static const CK_OBJECT_CLASS cko_public_key = CKO_PUBLIC_KEY; -static const NSSItem ckcapi_trueItem = { - (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) }; -static const NSSItem ckcapi_falseItem = { - (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }; -static const NSSItem ckcapi_x509Item = { - (void *)&ckc_x509, (PRUint32)sizeof(CK_CERTIFICATE_TYPE) }; -static const NSSItem ckcapi_rsaItem = { - (void *)&ckk_rsa, (PRUint32)sizeof(CK_KEY_TYPE) }; -static const NSSItem ckcapi_certClassItem = { - (void *)&cko_certificate, (PRUint32)sizeof(CK_OBJECT_CLASS) }; +static const NSSItem ckcapi_trueItem = { + (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) +}; +static const NSSItem ckcapi_falseItem = { + (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) +}; +static const NSSItem ckcapi_x509Item = { + (void *)&ckc_x509, (PRUint32)sizeof(CK_CERTIFICATE_TYPE) +}; +static const NSSItem ckcapi_rsaItem = { + (void *)&ckk_rsa, (PRUint32)sizeof(CK_KEY_TYPE) +}; +static const NSSItem ckcapi_certClassItem = { + (void *)&cko_certificate, (PRUint32)sizeof(CK_OBJECT_CLASS) +}; static const NSSItem ckcapi_privKeyClassItem = { - (void *)&cko_private_key, (PRUint32)sizeof(CK_OBJECT_CLASS) }; + (void *)&cko_private_key, (PRUint32)sizeof(CK_OBJECT_CLASS) +}; static const NSSItem ckcapi_pubKeyClassItem = { - (void *)&cko_public_key, (PRUint32)sizeof(CK_OBJECT_CLASS) }; -static const NSSItem ckcapi_emptyItem = { - (void *)&ck_true, 0}; + (void *)&cko_public_key, (PRUint32)sizeof(CK_OBJECT_CLASS) +}; +static const NSSItem ckcapi_emptyItem = { + (void *)&ck_true, 0 +}; /* * these are utilities. The chould be moved to a new utilities file. @@ -101,117 +109,111 @@ static const NSSItem ckcapi_emptyItem = { * unwrap a single DER value */ unsigned char * -nss_ckcapi_DERUnwrap -( - unsigned char *src, - unsigned int size, - unsigned int *outSize, - unsigned char **next -) +nss_ckcapi_DERUnwrap( + unsigned char *src, + unsigned int size, + unsigned int *outSize, + unsigned char **next) { - unsigned char *start = src; - unsigned char *end = src+size; - unsigned int len = 0; + unsigned char *start = src; + unsigned char *end = src + size; + unsigned int len = 0; - /* initialize error condition return values */ - *outSize = 0; - if (next) { - *next = src; - } - - if (size < 2) { - return start; - } - src++; /* skip the tag -- should check it against an expected value! */ - len = (unsigned) *src++; - if (len & 0x80) { - unsigned int count = len & 0x7f; - len = 0; - - if (count+2 > size) { - return start; + /* initialize error condition return values */ + *outSize = 0; + if (next) { + *next = src; } - while (count-- > 0) { - len = (len << 8) | (unsigned) *src++; - } - } - if (len + (src-start) > size) { - return start; - } - if (next) { - *next = src+len; - } - *outSize = len; - return src; + if (size < 2) { + return start; + } + src++; /* skip the tag -- should check it against an expected value! */ + len = (unsigned)*src++; + if (len & 0x80) { + unsigned int count = len & 0x7f; + len = 0; + + if (count + 2 > size) { + return start; + } + while (count-- > 0) { + len = (len << 8) | (unsigned)*src++; + } + } + if (len + (src - start) > size) { + return start; + } + if (next) { + *next = src + len; + } + *outSize = len; + + return src; } /* * convert a PKCS #11 bytestrin into a CK_ULONG, the byte stream must be * less than sizeof (CK_ULONG). */ -CK_ULONG -nss_ckcapi_DataToInt -( - NSSItem *data, - CK_RV *pError -) +CK_ULONG +nss_ckcapi_DataToInt( + NSSItem *data, + CK_RV *pError) { - CK_ULONG value = 0; - unsigned long count = data->size; - unsigned char *dataPtr = data->data; - unsigned long size = 0; + CK_ULONG value = 0; + unsigned long count = data->size; + unsigned char *dataPtr = data->data; + unsigned long size = 0; - *pError = CKR_OK; + *pError = CKR_OK; - while (count--) { - value = value << 8; - value = value + *dataPtr++; - if (size || value) { - size++; + while (count--) { + value = value << 8; + value = value + *dataPtr++; + if (size || value) { + size++; + } } - } - if (size > sizeof(CK_ULONG)) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - } - return value; + if (size > sizeof(CK_ULONG)) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + } + return value; } /* * convert a CK_ULONG to a bytestream. Data is stored in the buffer 'buf' * and must be at least CK_ULONG. Caller must provide buf. */ -CK_ULONG -nss_ckcapi_IntToData -( - CK_ULONG value, - NSSItem *data, - unsigned char *dataPtr, - CK_RV *pError -) +CK_ULONG +nss_ckcapi_IntToData( + CK_ULONG value, + NSSItem *data, + unsigned char *dataPtr, + CK_RV *pError) { - unsigned long count = 0; - unsigned long i; -#define SHIFT ((sizeof(CK_ULONG)-1)*8) - PRBool first = 0; + unsigned long count = 0; + unsigned long i; +#define SHIFT ((sizeof(CK_ULONG) - 1) * 8) + PRBool first = 0; - *pError = CKR_OK; + *pError = CKR_OK; - data->data = dataPtr; - for (i=0; i < sizeof(CK_ULONG); i++) { - unsigned char digit = (unsigned char)((value >> SHIFT) & 0xff); + data->data = dataPtr; + for (i = 0; i < sizeof(CK_ULONG); i++) { + unsigned char digit = (unsigned char)((value >> SHIFT) & 0xff); - value = value << 8; + value = value << 8; - /* drop leading zero bytes */ - if (first && (0 == digit)) { - continue; + /* drop leading zero bytes */ + if (first && (0 == digit)) { + continue; + } + *dataPtr++ = digit; + count++; } - *dataPtr++ = digit; - count++; - } - data->size = count; - return count; + data->size = count; + return count; } /* @@ -219,107 +221,99 @@ nss_ckcapi_IntToData * data for the item is owned by the template. */ CK_RV -nss_ckcapi_GetAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - NSSItem *item -) +nss_ckcapi_GetAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + NSSItem *item) { - CK_ULONG i; + CK_ULONG i; - for (i=0; i < templateSize; i++) { - if (template[i].type == type) { - item->data = template[i].pValue; - item->size = template[i].ulValueLen; - return CKR_OK; + for (i = 0; i < templateSize; i++) { + if (template[i].type == type) { + item->data = template[i].pValue; + item->size = template[i].ulValueLen; + return CKR_OK; + } } - } - return CKR_TEMPLATE_INCOMPLETE; + return CKR_TEMPLATE_INCOMPLETE; } /* * get an attribute which is type CK_ULONG. */ CK_ULONG -nss_ckcapi_GetULongAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - CK_RV *pError -) +nss_ckcapi_GetULongAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + CK_RV *pError) { - NSSItem item; + NSSItem item; - *pError = nss_ckcapi_GetAttribute(type, template, templateSize, &item); - if (CKR_OK != *pError) { - return (CK_ULONG) 0; - } - if (item.size != sizeof(CK_ULONG)) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (CK_ULONG) 0; - } - return *(CK_ULONG *)item.data; + *pError = nss_ckcapi_GetAttribute(type, template, templateSize, &item); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } + if (item.size != sizeof(CK_ULONG)) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + return (CK_ULONG)0; + } + return *(CK_ULONG *)item.data; } /* * get an attribute which is type CK_BBOOL. */ CK_BBOOL -nss_ckcapi_GetBoolAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - CK_RV *pError -) +nss_ckcapi_GetBoolAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + CK_RV *pError) { - NSSItem item; + NSSItem item; - *pError = nss_ckcapi_GetAttribute(type, template, templateSize, &item); - if (CKR_OK != *pError) { - return (CK_BBOOL) 0; - } - if (item.size != sizeof(CK_BBOOL)) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (CK_BBOOL) 0; - } - return *(CK_BBOOL *)item.data; + *pError = nss_ckcapi_GetAttribute(type, template, templateSize, &item); + if (CKR_OK != *pError) { + return (CK_BBOOL)0; + } + if (item.size != sizeof(CK_BBOOL)) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + return (CK_BBOOL)0; + } + return *(CK_BBOOL *)item.data; } /* * get an attribute which is type CK_BBOOL. */ char * -nss_ckcapi_GetStringAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - CK_RV *pError -) +nss_ckcapi_GetStringAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + CK_RV *pError) { - NSSItem item; - char *str; + NSSItem item; + char *str; - /* get the attribute */ - *pError = nss_ckcapi_GetAttribute(type, template, templateSize, &item); - if (CKR_OK != *pError) { - return (char *)NULL; - } - /* make sure it is null terminated */ - str = nss_ZNEWARRAY(NULL, char, item.size+1); - if ((char *)NULL == str) { - *pError = CKR_HOST_MEMORY; - return (char *)NULL; - } + /* get the attribute */ + *pError = nss_ckcapi_GetAttribute(type, template, templateSize, &item); + if (CKR_OK != *pError) { + return (char *)NULL; + } + /* make sure it is null terminated */ + str = nss_ZNEWARRAY(NULL, char, item.size + 1); + if ((char *)NULL == str) { + *pError = CKR_HOST_MEMORY; + return (char *)NULL; + } - nsslibc_memcpy(str, item.data, item.size); - str[item.size] = 0; + nsslibc_memcpy(str, item.data, item.size); + str[item.size] = 0; - return str; + return str; } /* @@ -327,105 +321,96 @@ nss_ckcapi_GetStringAttribute * character */ int -nss_ckcapi_WideSize -( - LPCWSTR wide -) +nss_ckcapi_WideSize( + LPCWSTR wide) { - DWORD size; + DWORD size; - if ((LPWSTR)NULL == wide) { - return 0; - } - size = wcslen(wide)+1; - return size*sizeof(WCHAR); + if ((LPWSTR)NULL == wide) { + return 0; + } + size = wcslen(wide) + 1; + return size * sizeof(WCHAR); } /* * Covert a Unicode wide character string to a UTF8 string */ char * -nss_ckcapi_WideToUTF8 -( - LPCWSTR wide -) +nss_ckcapi_WideToUTF8( + LPCWSTR wide) { - DWORD size; - char *buf; + DWORD size; + char *buf; - if ((LPWSTR)NULL == wide) { - return (char *)NULL; - } + if ((LPWSTR)NULL == wide) { + return (char *)NULL; + } - size = WideCharToMultiByte(CP_UTF8, 0, wide, -1, NULL, 0, NULL, 0); - if (size == 0) { - return (char *)NULL; - } - buf = nss_ZNEWARRAY(NULL, char, size); - size = WideCharToMultiByte(CP_UTF8, 0, wide, -1, buf, size, NULL, 0); - if (size == 0) { - nss_ZFreeIf(buf); - return (char *)NULL; - } - return buf; + size = WideCharToMultiByte(CP_UTF8, 0, wide, -1, NULL, 0, NULL, 0); + if (size == 0) { + return (char *)NULL; + } + buf = nss_ZNEWARRAY(NULL, char, size); + size = WideCharToMultiByte(CP_UTF8, 0, wide, -1, buf, size, NULL, 0); + if (size == 0) { + nss_ZFreeIf(buf); + return (char *)NULL; + } + return buf; } /* * Return a Wide String duplicated with nss allocated memory. */ LPWSTR -nss_ckcapi_WideDup -( - LPCWSTR wide -) +nss_ckcapi_WideDup( + LPCWSTR wide) { - DWORD len; - LPWSTR buf; + DWORD len; + LPWSTR buf; - if ((LPWSTR)NULL == wide) { - return (LPWSTR)NULL; - } + if ((LPWSTR)NULL == wide) { + return (LPWSTR)NULL; + } - len = wcslen(wide)+1; + len = wcslen(wide) + 1; - buf = nss_ZNEWARRAY(NULL, WCHAR, len); - if ((LPWSTR) NULL == buf) { + buf = nss_ZNEWARRAY(NULL, WCHAR, len); + if ((LPWSTR)NULL == buf) { + return buf; + } + nsslibc_memcpy(buf, wide, len * sizeof(WCHAR)); return buf; - } - nsslibc_memcpy(buf, wide, len*sizeof(WCHAR)); - return buf; } /* * Covert a UTF8 string to Unicode wide character */ LPWSTR -nss_ckcapi_UTF8ToWide -( - char *buf -) +nss_ckcapi_UTF8ToWide( + char *buf) { - DWORD size; - LPWSTR wide; + DWORD size; + LPWSTR wide; - if ((char *)NULL == buf) { - return (LPWSTR) NULL; - } - - size = MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0); - if (size == 0) { - return (LPWSTR) NULL; - } - wide = nss_ZNEWARRAY(NULL, WCHAR, size); - size = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wide, size); - if (size == 0) { - nss_ZFreeIf(wide); - return (LPWSTR) NULL; - } - return wide; + if ((char *)NULL == buf) { + return (LPWSTR)NULL; + } + + size = MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0); + if (size == 0) { + return (LPWSTR)NULL; + } + wide = nss_ZNEWARRAY(NULL, WCHAR, size); + size = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wide, size); + if (size == 0) { + nss_ZFreeIf(wide); + return (LPWSTR)NULL; + } + return wide; } - /* * keep all the knowlege of how the internalObject is laid out in this function * @@ -436,281 +421,274 @@ nss_ckcapi_UTF8ToWide * this function fails with CKR_KEY_TYPE_INCONSISTENT */ NSS_EXTERN CK_RV -nss_ckcapi_FetchKeyContainer -( - ckcapiInternalObject *iKey, - HCRYPTPROV *hProv, - DWORD *keySpec, - HCRYPTKEY *hKey -) +nss_ckcapi_FetchKeyContainer( + ckcapiInternalObject *iKey, + HCRYPTPROV *hProv, + DWORD *keySpec, + HCRYPTKEY *hKey) { - ckcapiCertObject *co; - ckcapiKeyObject *ko; - BOOL rc, dummy; - DWORD msError; + ckcapiCertObject *co; + ckcapiKeyObject *ko; + BOOL rc, dummy; + DWORD msError; + switch (iKey->type) { + default: + case ckcapiRaw: + /* can't have raw private keys */ + return CKR_KEY_TYPE_INCONSISTENT; + case ckcapiCert: + if (iKey->objClass != CKO_PRIVATE_KEY) { + /* Only private keys have private key provider handles */ + return CKR_KEY_TYPE_INCONSISTENT; + } + co = &iKey->u.cert; - switch (iKey->type) { - default: - case ckcapiRaw: - /* can't have raw private keys */ - return CKR_KEY_TYPE_INCONSISTENT; - case ckcapiCert: - if (iKey->objClass != CKO_PRIVATE_KEY) { - /* Only private keys have private key provider handles */ - return CKR_KEY_TYPE_INCONSISTENT; + /* OK, get the Provider */ + rc = CryptAcquireCertificatePrivateKey(co->certContext, + CRYPT_ACQUIRE_CACHE_FLAG | + CRYPT_ACQUIRE_COMPARE_KEY_FLAG, + NULL, hProv, + keySpec, &dummy); + if (!rc) { + goto loser; + } + break; + case ckcapiBareKey: + if (iKey->objClass != CKO_PRIVATE_KEY) { + /* Only private keys have private key provider handles */ + return CKR_KEY_TYPE_INCONSISTENT; + } + ko = &iKey->u.key; + + /* OK, get the Provider */ + if (0 == ko->hProv) { + rc = + CryptAcquireContext(hProv, + ko->containerName, + ko->provName, + ko->provInfo.dwProvType, 0); + if (!rc) { + goto loser; + } + } + else { + *hProv = + ko->hProv; + } + *keySpec = ko->provInfo.dwKeySpec; + break; } - co = &iKey->u.cert; - /* OK, get the Provider */ - rc = CryptAcquireCertificatePrivateKey(co->certContext, - CRYPT_ACQUIRE_CACHE_FLAG|CRYPT_ACQUIRE_COMPARE_KEY_FLAG, NULL, hProv, - keySpec, &dummy); + /* and get the crypto handle */ + rc = CryptGetUserKey(*hProv, *keySpec, hKey); if (!rc) { - goto loser; - } - break; - case ckcapiBareKey: - if (iKey->objClass != CKO_PRIVATE_KEY) { - /* Only private keys have private key provider handles */ - return CKR_KEY_TYPE_INCONSISTENT; - } - ko = &iKey->u.key; - - /* OK, get the Provider */ - if (0 == ko->hProv) { - rc = CryptAcquireContext(hProv, - ko->containerName, - ko->provName, - ko->provInfo.dwProvType , 0); - if (!rc) { goto loser; - } - } else { - *hProv = ko->hProv; } - *keySpec = ko->provInfo.dwKeySpec; - break; - } - - /* and get the crypto handle */ - rc = CryptGetUserKey(*hProv, *keySpec, hKey); - if (!rc) { - goto loser; - } - return CKR_OK; + return CKR_OK; loser: - /* map the microsoft error before leaving */ - msError = GetLastError(); - switch (msError) { - case ERROR_INVALID_HANDLE: - case ERROR_INVALID_PARAMETER: - case NTE_BAD_KEY: - case NTE_NO_KEY: - case NTE_BAD_PUBLIC_KEY: - case NTE_BAD_KEYSET: - case NTE_KEYSET_NOT_DEF: - return CKR_KEY_TYPE_INCONSISTENT; - case NTE_BAD_UID: - case NTE_KEYSET_ENTRY_BAD: - return CKR_DEVICE_ERROR; - } - return CKR_GENERAL_ERROR; + /* map the microsoft error before leaving */ + msError = GetLastError(); + switch (msError) { + case ERROR_INVALID_HANDLE: + case ERROR_INVALID_PARAMETER: + case NTE_BAD_KEY: + case NTE_NO_KEY: + case NTE_BAD_PUBLIC_KEY: + case NTE_BAD_KEYSET: + case NTE_KEYSET_NOT_DEF: + return CKR_KEY_TYPE_INCONSISTENT; + case NTE_BAD_UID: + case NTE_KEYSET_ENTRY_BAD: + return CKR_DEVICE_ERROR; + } + return CKR_GENERAL_ERROR; } - /* * take a DER PUBLIC Key block and return the modulus and exponent */ static void -ckcapi_CertPopulateModulusExponent -( - ckcapiInternalObject *io -) +ckcapi_CertPopulateModulusExponent( + ckcapiInternalObject *io) { - ckcapiKeyParams *kp = &io->u.cert.key; - PCCERT_CONTEXT certContext = io->u.cert.certContext; - unsigned char *pkData = - certContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData; - unsigned int size= - certContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData; - unsigned int newSize; - unsigned char *ptr, *newptr; + ckcapiKeyParams *kp = &io->u.cert.key; + PCCERT_CONTEXT certContext = io->u.cert.certContext; + unsigned char *pkData = + certContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData; + unsigned int size = + certContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData; + unsigned int newSize; + unsigned char *ptr, *newptr; - /* find the start of the modulus -- this will not give good results if - * the key isn't an rsa key! */ - ptr = nss_ckcapi_DERUnwrap(pkData, size, &newSize, NULL); - kp->modulus.data = nss_ckcapi_DERUnwrap(ptr, newSize, - &kp->modulus.size, &newptr); - /* changed from signed to unsigned int */ - if (0 == *(char *)kp->modulus.data) { - kp->modulus.data = ((char *)kp->modulus.data)+1; - kp->modulus.size = kp->modulus.size - 1; - } - /* changed from signed to unsigned int */ - kp->exponent.data = nss_ckcapi_DERUnwrap(newptr, (newptr-ptr)+newSize, - &kp->exponent.size, NULL); - if (0 == *(char *)kp->exponent.data) { - kp->exponent.data = ((char *)kp->exponent.data)+1; - kp->exponent.size = kp->exponent.size - 1; - } - return; + /* find the start of the modulus -- this will not give good results if + * the key isn't an rsa key! */ + ptr = nss_ckcapi_DERUnwrap(pkData, size, &newSize, NULL); + kp->modulus.data = nss_ckcapi_DERUnwrap(ptr, newSize, + &kp->modulus.size, &newptr); + /* changed from signed to unsigned int */ + if (0 == *(char *)kp->modulus.data) { + kp->modulus.data = ((char *)kp->modulus.data) + 1; + kp->modulus.size = kp->modulus.size - 1; + } + /* changed from signed to unsigned int */ + kp->exponent.data = nss_ckcapi_DERUnwrap(newptr, (newptr - ptr) + newSize, + &kp->exponent.size, NULL); + if (0 == *(char *)kp->exponent.data) { + kp->exponent.data = ((char *)kp->exponent.data) + 1; + kp->exponent.size = kp->exponent.size - 1; + } + return; } typedef struct _CAPI_RSA_KEY_BLOB { - PUBLICKEYSTRUC header; - RSAPUBKEY rsa; - char data[1]; + PUBLICKEYSTRUC header; + RSAPUBKEY rsa; + char data[1]; } CAPI_RSA_KEY_BLOB; -#define CAPI_MODULUS_OFFSET(modSize) 0 -#define CAPI_PRIME_1_OFFSET(modSize) (modSize) -#define CAPI_PRIME_2_OFFSET(modSize) ((modSize)+(modSize)/2) -#define CAPI_EXPONENT_1_OFFSET(modSize) ((modSize)*2) -#define CAPI_EXPONENT_2_OFFSET(modSize) ((modSize)*2+(modSize)/2) +#define CAPI_MODULUS_OFFSET(modSize) 0 +#define CAPI_PRIME_1_OFFSET(modSize) (modSize) +#define CAPI_PRIME_2_OFFSET(modSize) ((modSize) + (modSize) / 2) +#define CAPI_EXPONENT_1_OFFSET(modSize) ((modSize)*2) +#define CAPI_EXPONENT_2_OFFSET(modSize) ((modSize)*2 + (modSize) / 2) #define CAPI_COEFFICIENT_OFFSET(modSize) ((modSize)*3) -#define CAPI_PRIVATE_EXP_OFFSET(modSize) ((modSize)*3+(modSize)/2) +#define CAPI_PRIVATE_EXP_OFFSET(modSize) ((modSize)*3 + (modSize) / 2) void -ckcapi_FetchPublicKey -( - ckcapiInternalObject *io -) +ckcapi_FetchPublicKey( + ckcapiInternalObject *io) { - ckcapiKeyParams *kp; - HCRYPTPROV hProv; - DWORD keySpec; - HCRYPTKEY hKey = 0; - CK_RV error; - DWORD bufLen; - BOOL rc; - unsigned long modulus; - char *buf = NULL; - CAPI_RSA_KEY_BLOB *blob; + ckcapiKeyParams *kp; + HCRYPTPROV hProv; + DWORD keySpec; + HCRYPTKEY hKey = 0; + CK_RV error; + DWORD bufLen; + BOOL rc; + unsigned long modulus; + char *buf = NULL; + CAPI_RSA_KEY_BLOB *blob; - error = nss_ckcapi_FetchKeyContainer(io, &hProv, &keySpec, &hKey); - if (CKR_OK != error) { - goto loser; - } - kp = (ckcapiCert == io->type) ? &io->u.cert.key : &io->u.key.key; + error = nss_ckcapi_FetchKeyContainer(io, &hProv, &keySpec, &hKey); + if (CKR_OK != error) { + goto loser; + } + kp = (ckcapiCert == io->type) ? &io->u.cert.key : &io->u.key.key; - rc = CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, buf, &bufLen); - if (!rc) { - goto loser; - } - buf = nss_ZNEWARRAY(NULL, char, bufLen); - rc = CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, buf, &bufLen); - if (!rc) { - goto loser; - } - /* validate the blob */ - blob = (CAPI_RSA_KEY_BLOB *)buf; - if ((PUBLICKEYBLOB != blob->header.bType) || - (0x02 != blob->header.bVersion) || - (0x31415352 != blob->rsa.magic)) { - goto loser; - } - modulus = blob->rsa.bitlen/8; - kp->pubKey = buf; - buf = NULL; + rc = CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, buf, &bufLen); + if (!rc) { + goto loser; + } + buf = nss_ZNEWARRAY(NULL, char, bufLen); + rc = CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, buf, &bufLen); + if (!rc) { + goto loser; + } + /* validate the blob */ + blob = (CAPI_RSA_KEY_BLOB *)buf; + if ((PUBLICKEYBLOB != blob->header.bType) || + (0x02 != blob->header.bVersion) || + (0x31415352 != blob->rsa.magic)) { + goto loser; + } + modulus = blob->rsa.bitlen / 8; + kp->pubKey = buf; + buf = NULL; - kp->modulus.data = &blob->data[CAPI_MODULUS_OFFSET(modulus)]; - kp->modulus.size = modulus; - ckcapi_ReverseData(&kp->modulus); - nss_ckcapi_IntToData(blob->rsa.pubexp, &kp->exponent, - kp->publicExponentData, &error); + kp->modulus.data = &blob->data[CAPI_MODULUS_OFFSET(modulus)]; + kp->modulus.size = modulus; + ckcapi_ReverseData(&kp->modulus); + nss_ckcapi_IntToData(blob->rsa.pubexp, &kp->exponent, + kp->publicExponentData, &error); loser: - nss_ZFreeIf(buf); - if (0 != hKey) { - CryptDestroyKey(hKey); - } - return; + nss_ZFreeIf(buf); + if (0 != hKey) { + CryptDestroyKey(hKey); + } + return; } void -ckcapi_FetchPrivateKey -( - ckcapiInternalObject *io -) +ckcapi_FetchPrivateKey( + ckcapiInternalObject *io) { - ckcapiKeyParams *kp; - HCRYPTPROV hProv; - DWORD keySpec; - HCRYPTKEY hKey = 0; - CK_RV error; - DWORD bufLen; - BOOL rc; - unsigned long modulus; - char *buf = NULL; - CAPI_RSA_KEY_BLOB *blob; + ckcapiKeyParams *kp; + HCRYPTPROV hProv; + DWORD keySpec; + HCRYPTKEY hKey = 0; + CK_RV error; + DWORD bufLen; + BOOL rc; + unsigned long modulus; + char *buf = NULL; + CAPI_RSA_KEY_BLOB *blob; - error = nss_ckcapi_FetchKeyContainer(io, &hProv, &keySpec, &hKey); - if (CKR_OK != error) { - goto loser; - } - kp = (ckcapiCert == io->type) ? &io->u.cert.key : &io->u.key.key; + error = nss_ckcapi_FetchKeyContainer(io, &hProv, &keySpec, &hKey); + if (CKR_OK != error) { + goto loser; + } + kp = (ckcapiCert == io->type) ? &io->u.cert.key : &io->u.key.key; - rc = CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, buf, &bufLen); - if (!rc) { - goto loser; - } - buf = nss_ZNEWARRAY(NULL, char, bufLen); - rc = CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, buf, &bufLen); - if (!rc) { - goto loser; - } - /* validate the blob */ - blob = (CAPI_RSA_KEY_BLOB *)buf; - if ((PRIVATEKEYBLOB != blob->header.bType) || - (0x02 != blob->header.bVersion) || - (0x32415352 != blob->rsa.magic)) { - goto loser; - } - modulus = blob->rsa.bitlen/8; - kp->privateKey = buf; - buf = NULL; + rc = CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, buf, &bufLen); + if (!rc) { + goto loser; + } + buf = nss_ZNEWARRAY(NULL, char, bufLen); + rc = CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, buf, &bufLen); + if (!rc) { + goto loser; + } + /* validate the blob */ + blob = (CAPI_RSA_KEY_BLOB *)buf; + if ((PRIVATEKEYBLOB != blob->header.bType) || + (0x02 != blob->header.bVersion) || + (0x32415352 != blob->rsa.magic)) { + goto loser; + } + modulus = blob->rsa.bitlen / 8; + kp->privateKey = buf; + buf = NULL; - kp->privateExponent.data = &blob->data[CAPI_PRIVATE_EXP_OFFSET(modulus)]; - kp->privateExponent.size = modulus; - ckcapi_ReverseData(&kp->privateExponent); - kp->prime1.data = &blob->data[CAPI_PRIME_1_OFFSET(modulus)]; - kp->prime1.size = modulus/2; - ckcapi_ReverseData(&kp->prime1); - kp->prime2.data = &blob->data[CAPI_PRIME_2_OFFSET(modulus)]; - kp->prime2.size = modulus/2; - ckcapi_ReverseData(&kp->prime2); - kp->exponent1.data = &blob->data[CAPI_EXPONENT_1_OFFSET(modulus)]; - kp->exponent1.size = modulus/2; - ckcapi_ReverseData(&kp->exponent1); - kp->exponent2.data = &blob->data[CAPI_EXPONENT_2_OFFSET(modulus)]; - kp->exponent2.size = modulus/2; - ckcapi_ReverseData(&kp->exponent2); - kp->coefficient.data = &blob->data[CAPI_COEFFICIENT_OFFSET(modulus)]; - kp->coefficient.size = modulus/2; - ckcapi_ReverseData(&kp->coefficient); + kp->privateExponent.data = &blob->data[CAPI_PRIVATE_EXP_OFFSET(modulus)]; + kp->privateExponent.size = modulus; + ckcapi_ReverseData(&kp->privateExponent); + kp->prime1.data = &blob->data[CAPI_PRIME_1_OFFSET(modulus)]; + kp->prime1.size = modulus / 2; + ckcapi_ReverseData(&kp->prime1); + kp->prime2.data = &blob->data[CAPI_PRIME_2_OFFSET(modulus)]; + kp->prime2.size = modulus / 2; + ckcapi_ReverseData(&kp->prime2); + kp->exponent1.data = &blob->data[CAPI_EXPONENT_1_OFFSET(modulus)]; + kp->exponent1.size = modulus / 2; + ckcapi_ReverseData(&kp->exponent1); + kp->exponent2.data = &blob->data[CAPI_EXPONENT_2_OFFSET(modulus)]; + kp->exponent2.size = modulus / 2; + ckcapi_ReverseData(&kp->exponent2); + kp->coefficient.data = &blob->data[CAPI_COEFFICIENT_OFFSET(modulus)]; + kp->coefficient.size = modulus / 2; + ckcapi_ReverseData(&kp->coefficient); loser: - nss_ZFreeIf(buf); - if (0 != hKey) { - CryptDestroyKey(hKey); - } - return; + nss_ZFreeIf(buf); + if (0 != hKey) { + CryptDestroyKey(hKey); + } + return; } - void -ckcapi_PopulateModulusExponent -( - ckcapiInternalObject *io -) +ckcapi_PopulateModulusExponent( + ckcapiInternalObject *io) { - if (ckcapiCert == io->type) { - ckcapi_CertPopulateModulusExponent(io); - } else { - ckcapi_FetchPublicKey(io); - } - return; + if (ckcapiCert == io->type) { + ckcapi_CertPopulateModulusExponent(io); + } + else { + ckcapi_FetchPublicKey(io); + } + return; } /* @@ -718,442 +696,435 @@ ckcapi_PopulateModulusExponent * can only be called with ckcapiCert type objects! */ void -ckcapi_FetchLabel -( - ckcapiInternalObject *io -) +ckcapi_FetchLabel( + ckcapiInternalObject *io) { - ckcapiCertObject *co = &io->u.cert; - char *label; - PCCERT_CONTEXT certContext = io->u.cert.certContext; - char labelDataUTF16[128]; - DWORD size = sizeof(labelDataUTF16); - DWORD size8 = sizeof(co->labelData); - BOOL rv; + ckcapiCertObject *co = &io->u.cert; + char *label; + PCCERT_CONTEXT certContext = io->u.cert.certContext; + char labelDataUTF16[128]; + DWORD size = sizeof(labelDataUTF16); + DWORD size8 = sizeof(co->labelData); + BOOL rv; - rv = CertGetCertificateContextProperty(certContext, - CERT_FRIENDLY_NAME_PROP_ID, labelDataUTF16, &size); - if (rv) { - co->labelData = nss_ckcapi_WideToUTF8((LPCWSTR)labelDataUTF16); - if ((CHAR *)NULL == co->labelData) { - rv = 0; - } else { - size = strlen(co->labelData); + rv = CertGetCertificateContextProperty(certContext, + CERT_FRIENDLY_NAME_PROP_ID, labelDataUTF16, &size); + if (rv) { + co->labelData = nss_ckcapi_WideToUTF8((LPCWSTR)labelDataUTF16); + if ((CHAR *)NULL == co->labelData) { + rv = 0; + } + else { + size = strlen(co->labelData); + } } - } - label = co->labelData; - /* we are presuming a user cert, make sure it has a nickname, even if - * Microsoft never gave it one */ - if (!rv && co->hasID) { - DWORD mserror = GetLastError(); + label = co->labelData; + /* we are presuming a user cert, make sure it has a nickname, even if + * Microsoft never gave it one */ + if (!rv && co->hasID) { + DWORD mserror = GetLastError(); #define DEFAULT_NICKNAME "no Microsoft nickname" - label = DEFAULT_NICKNAME; - size = sizeof(DEFAULT_NICKNAME); - rv = 1; - } - - if (rv) { - co->label.data = label; - co->label.size = size; - } - return; + label = DEFAULT_NICKNAME; + size = sizeof(DEFAULT_NICKNAME); + rv = 1; + } + + if (rv) { + co->label.data = label; + co->label.size = size; + } + return; } void -ckcapi_FetchSerial -( - ckcapiInternalObject *io -) +ckcapi_FetchSerial( + ckcapiInternalObject *io) { - ckcapiCertObject *co = &io->u.cert; - PCCERT_CONTEXT certContext = io->u.cert.certContext; - DWORD size = sizeof(co->derSerial); + ckcapiCertObject *co = &io->u.cert; + PCCERT_CONTEXT certContext = io->u.cert.certContext; + DWORD size = sizeof(co->derSerial); - BOOL rc = CryptEncodeObject(X509_ASN_ENCODING, - X509_MULTI_BYTE_INTEGER, - &certContext->pCertInfo->SerialNumber, - co->derSerial, - &size); - if (rc) { - co->serial.data = co->derSerial; - co->serial.size = size; - } - return; + BOOL rc = CryptEncodeObject(X509_ASN_ENCODING, + X509_MULTI_BYTE_INTEGER, + &certContext->pCertInfo->SerialNumber, + co->derSerial, + &size); + if (rc) { + co->serial.data = co->derSerial; + co->serial.size = size; + } + return; } /* * fetch the key ID. */ void -ckcapi_FetchID -( - ckcapiInternalObject *io -) +ckcapi_FetchID( + ckcapiInternalObject *io) { - PCCERT_CONTEXT certContext = io->u.cert.certContext; - DWORD size = 0; - BOOL rc; + PCCERT_CONTEXT certContext = io->u.cert.certContext; + DWORD size = 0; + BOOL rc; - rc = CertGetCertificateContextProperty(certContext, - CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size); - if (!rc) { - return; - } - io->idData = nss_ZNEWARRAY(NULL, char, size); - if (io->idData == NULL) { - return; - } + rc = CertGetCertificateContextProperty(certContext, + CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size); + if (!rc) { + return; + } + io->idData = nss_ZNEWARRAY(NULL, char, size); + if (io->idData == NULL) { + return; + } - rc = CertGetCertificateContextProperty(certContext, - CERT_KEY_IDENTIFIER_PROP_ID, io->idData, &size); - if (!rc) { - nss_ZFreeIf(io->idData); - io->idData = NULL; + rc = CertGetCertificateContextProperty(certContext, + CERT_KEY_IDENTIFIER_PROP_ID, io->idData, &size); + if (!rc) { + nss_ZFreeIf(io->idData); + io->idData = NULL; + return; + } + io->id.data = io->idData; + io->id.size = size; return; - } - io->id.data = io->idData; - io->id.size = size; - return; } /* * fetch the hash key. */ void -ckcapi_CertFetchHashKey -( - ckcapiInternalObject *io -) +ckcapi_CertFetchHashKey( + ckcapiInternalObject *io) { - ckcapiCertObject *co = &io->u.cert; - PCCERT_CONTEXT certContext = io->u.cert.certContext; - DWORD size = certContext->cbCertEncoded; - DWORD max = sizeof(io->hashKeyData)-1; - DWORD offset = 0; + ckcapiCertObject *co = &io->u.cert; + PCCERT_CONTEXT certContext = io->u.cert.certContext; + DWORD size = certContext->cbCertEncoded; + DWORD max = sizeof(io->hashKeyData) - 1; + DWORD offset = 0; - /* make sure we don't over flow. NOTE: cutting the top of a cert is - * not a big issue because the signature for will be unique for the cert */ - if (size > max) { - offset = size - max; - size = max; - } + /* make sure we don't over flow. NOTE: cutting the top of a cert is + * not a big issue because the signature for will be unique for the cert */ + if (size > max) { + offset = size - max; + size = max; + } - nsslibc_memcpy(io->hashKeyData,certContext->pbCertEncoded+offset, size); - io->hashKeyData[size] = (char)(io->objClass & 0xff); + nsslibc_memcpy(io->hashKeyData, certContext->pbCertEncoded + offset, size); + io->hashKeyData[size] = (char)(io->objClass & 0xff); - io->hashKey.data = io->hashKeyData; - io->hashKey.size = size+1; - return; + io->hashKey.data = io->hashKeyData; + io->hashKey.size = size + 1; + return; } /* * fetch the hash key. */ void -ckcapi_KeyFetchHashKey -( - ckcapiInternalObject *io -) +ckcapi_KeyFetchHashKey( + ckcapiInternalObject *io) { - ckcapiKeyObject *ko = &io->u.key; - DWORD size; - DWORD max = sizeof(io->hashKeyData)-2; - DWORD offset = 0; - DWORD provLen = strlen(ko->provName); - DWORD containerLen = strlen(ko->containerName); + ckcapiKeyObject *ko = &io->u.key; + DWORD size; + DWORD max = sizeof(io->hashKeyData) - 2; + DWORD offset = 0; + DWORD provLen = strlen(ko->provName); + DWORD containerLen = strlen(ko->containerName); - - size = provLen + containerLen; + size = provLen + containerLen; - /* make sure we don't overflow, try to keep things unique */ - if (size > max) { - DWORD diff = ((size - max)+1)/2; - provLen -= diff; - containerLen -= diff; - size = provLen+containerLen; - } + /* make sure we don't overflow, try to keep things unique */ + if (size > max) { + DWORD diff = ((size - max) + 1) / 2; + provLen -= diff; + containerLen -= diff; + size = provLen + containerLen; + } - nsslibc_memcpy(io->hashKeyData, ko->provName, provLen); - nsslibc_memcpy(&io->hashKeyData[provLen], - ko->containerName, - containerLen); - io->hashKeyData[size] = (char)(io->objClass & 0xff); - io->hashKeyData[size+1] = (char)(ko->provInfo.dwKeySpec & 0xff); + nsslibc_memcpy(io->hashKeyData, ko->provName, provLen); + nsslibc_memcpy(&io->hashKeyData[provLen], + ko->containerName, + containerLen); + io->hashKeyData[size] = (char)(io->objClass & 0xff); + io->hashKeyData[size + 1] = (char)(ko->provInfo.dwKeySpec & 0xff); - io->hashKey.data = io->hashKeyData; - io->hashKey.size = size+2; - return; + io->hashKey.data = io->hashKeyData; + io->hashKey.size = size + 2; + return; } /* * fetch the hash key. */ void -ckcapi_FetchHashKey -( - ckcapiInternalObject *io -) +ckcapi_FetchHashKey( + ckcapiInternalObject *io) { - if (ckcapiCert == io->type) { - ckcapi_CertFetchHashKey(io); - } else { - ckcapi_KeyFetchHashKey(io); - } - return; -} - -const NSSItem * -ckcapi_FetchCertAttribute -( - ckcapiInternalObject *io, - CK_ATTRIBUTE_TYPE type -) -{ - PCCERT_CONTEXT certContext = io->u.cert.certContext; - switch(type) { - case CKA_CLASS: - return &ckcapi_certClassItem; - case CKA_TOKEN: - return &ckcapi_trueItem; - case CKA_MODIFIABLE: - case CKA_PRIVATE: - return &ckcapi_falseItem; - case CKA_CERTIFICATE_TYPE: - return &ckcapi_x509Item; - case CKA_LABEL: - if (0 == io->u.cert.label.size) { - ckcapi_FetchLabel(io); + if (ckcapiCert == io->type) { + ckcapi_CertFetchHashKey(io); } - return &io->u.cert.label; - case CKA_SUBJECT: - if (0 == io->u.cert.subject.size) { - io->u.cert.subject.data = certContext->pCertInfo->Subject.pbData; - io->u.cert.subject.size = certContext->pCertInfo->Subject.cbData; + else { + ckcapi_KeyFetchHashKey(io); } - return &io->u.cert.subject; - case CKA_ISSUER: - if (0 == io->u.cert.issuer.size) { - io->u.cert.issuer.data = certContext->pCertInfo->Issuer.pbData; - io->u.cert.issuer.size = certContext->pCertInfo->Issuer.cbData; - } - return &io->u.cert.issuer; - case CKA_SERIAL_NUMBER: - if (0 == io->u.cert.serial.size) { - /* not exactly right. This should be the encoded serial number, but - * it's the decoded serial number! */ - ckcapi_FetchSerial(io); - } - return &io->u.cert.serial; - case CKA_VALUE: - if (0 == io->u.cert.derCert.size) { - io->u.cert.derCert.data = io->u.cert.certContext->pbCertEncoded; - io->u.cert.derCert.size = io->u.cert.certContext->cbCertEncoded; - } - return &io->u.cert.derCert; - case CKA_ID: - if (!io->u.cert.hasID) { - return NULL; - } - if (0 == io->id.size) { - ckcapi_FetchID(io); - } - return &io->id; - default: - break; - } - return NULL; + return; } const NSSItem * -ckcapi_FetchPubKeyAttribute -( - ckcapiInternalObject *io, - CK_ATTRIBUTE_TYPE type -) +ckcapi_FetchCertAttribute( + ckcapiInternalObject *io, + CK_ATTRIBUTE_TYPE type) { - PRBool isCertType = (ckcapiCert == io->type); - ckcapiKeyParams *kp = isCertType ? &io->u.cert.key : &io->u.key.key; - - switch(type) { - case CKA_CLASS: - return &ckcapi_pubKeyClassItem; - case CKA_TOKEN: - case CKA_LOCAL: - case CKA_ENCRYPT: - case CKA_VERIFY: - case CKA_VERIFY_RECOVER: - return &ckcapi_trueItem; - case CKA_PRIVATE: - case CKA_MODIFIABLE: - case CKA_DERIVE: - case CKA_WRAP: - return &ckcapi_falseItem; - case CKA_KEY_TYPE: - return &ckcapi_rsaItem; - case CKA_LABEL: - if (!isCertType) { - return &ckcapi_emptyItem; - } - if (0 == io->u.cert.label.size) { - ckcapi_FetchLabel(io); - } - return &io->u.cert.label; - case CKA_SUBJECT: - if (!isCertType) { - return &ckcapi_emptyItem; - } - if (0 == io->u.cert.subject.size) { - PCCERT_CONTEXT certContext= io->u.cert.certContext; - io->u.cert.subject.data = certContext->pCertInfo->Subject.pbData; - io->u.cert.subject.size = certContext->pCertInfo->Subject.cbData; - } - return &io->u.cert.subject; - case CKA_MODULUS: - if (0 == kp->modulus.size) { - ckcapi_PopulateModulusExponent(io); - } - return &kp->modulus; - case CKA_PUBLIC_EXPONENT: - if (0 == kp->modulus.size) { - ckcapi_PopulateModulusExponent(io); - } - return &kp->exponent; - case CKA_ID: - if (0 == io->id.size) { - ckcapi_FetchID(io); - } - return &io->id; - default: - break; - } - return NULL; -} - -const NSSItem * -ckcapi_FetchPrivKeyAttribute -( - ckcapiInternalObject *io, - CK_ATTRIBUTE_TYPE type -) -{ - PRBool isCertType = (ckcapiCert == io->type); - ckcapiKeyParams *kp = isCertType ? &io->u.cert.key : &io->u.key.key; - - switch(type) { - case CKA_CLASS: - return &ckcapi_privKeyClassItem; - case CKA_TOKEN: - case CKA_LOCAL: - case CKA_SIGN: - case CKA_DECRYPT: - case CKA_SIGN_RECOVER: - return &ckcapi_trueItem; - case CKA_SENSITIVE: - case CKA_PRIVATE: /* should move in the future */ - case CKA_MODIFIABLE: - case CKA_DERIVE: - case CKA_UNWRAP: - case CKA_EXTRACTABLE: /* will probably move in the future */ - case CKA_ALWAYS_SENSITIVE: - case CKA_NEVER_EXTRACTABLE: - return &ckcapi_falseItem; - case CKA_KEY_TYPE: - return &ckcapi_rsaItem; - case CKA_LABEL: - if (!isCertType) { - return &ckcapi_emptyItem; - } - if (0 == io->u.cert.label.size) { - ckcapi_FetchLabel(io); - } - return &io->u.cert.label; - case CKA_SUBJECT: - if (!isCertType) { - return &ckcapi_emptyItem; - } - if (0 == io->u.cert.subject.size) { - PCCERT_CONTEXT certContext= io->u.cert.certContext; - io->u.cert.subject.data = certContext->pCertInfo->Subject.pbData; - io->u.cert.subject.size = certContext->pCertInfo->Subject.cbData; - } - return &io->u.cert.subject; - case CKA_MODULUS: - if (0 == kp->modulus.size) { - ckcapi_PopulateModulusExponent(io); - } - return &kp->modulus; - case CKA_PUBLIC_EXPONENT: - if (0 == kp->modulus.size) { - ckcapi_PopulateModulusExponent(io); - } - return &kp->exponent; - case CKA_PRIVATE_EXPONENT: - if (0 == kp->privateExponent.size) { - ckcapi_FetchPrivateKey(io); - } - return &kp->privateExponent; - case CKA_PRIME_1: - if (0 == kp->privateExponent.size) { - ckcapi_FetchPrivateKey(io); - } - return &kp->prime1; - case CKA_PRIME_2: - if (0 == kp->privateExponent.size) { - ckcapi_FetchPrivateKey(io); - } - return &kp->prime2; - case CKA_EXPONENT_1: - if (0 == kp->privateExponent.size) { - ckcapi_FetchPrivateKey(io); - } - return &kp->exponent1; - case CKA_EXPONENT_2: - if (0 == kp->privateExponent.size) { - ckcapi_FetchPrivateKey(io); - } - return &kp->exponent2; - case CKA_COEFFICIENT: - if (0 == kp->privateExponent.size) { - ckcapi_FetchPrivateKey(io); - } - return &kp->coefficient; - case CKA_ID: - if (0 == io->id.size) { - ckcapi_FetchID(io); - } - return &io->id; - default: - return NULL; - } -} - -const NSSItem * -nss_ckcapi_FetchAttribute -( - ckcapiInternalObject *io, - CK_ATTRIBUTE_TYPE type -) -{ - CK_ULONG i; - - if (io->type == ckcapiRaw) { - for( i = 0; i < io->u.raw.n; i++ ) { - if( type == io->u.raw.types[i] ) { - return &io->u.raw.items[i]; - } + PCCERT_CONTEXT certContext = io->u.cert.certContext; + switch (type) { + case CKA_CLASS: + return &ckcapi_certClassItem; + case CKA_TOKEN: + return &ckcapi_trueItem; + case CKA_MODIFIABLE: + case CKA_PRIVATE: + return &ckcapi_falseItem; + case CKA_CERTIFICATE_TYPE: + return &ckcapi_x509Item; + case CKA_LABEL: + if (0 == io->u.cert.label.size) { + ckcapi_FetchLabel(io); + } + return &io->u.cert.label; + case CKA_SUBJECT: + if (0 == io->u.cert.subject.size) { + io->u.cert.subject.data = + certContext->pCertInfo->Subject.pbData; + io->u.cert.subject.size = + certContext->pCertInfo->Subject.cbData; + } + return &io->u.cert.subject; + case CKA_ISSUER: + if (0 == io->u.cert.issuer.size) { + io->u.cert.issuer.data = + certContext->pCertInfo->Issuer.pbData; + io->u.cert.issuer.size = + certContext->pCertInfo->Issuer.cbData; + } + return &io->u.cert.issuer; + case CKA_SERIAL_NUMBER: + if (0 == io->u.cert.serial.size) { + /* not exactly right. This should be the encoded serial number, but + * it's the decoded serial number! */ + ckcapi_FetchSerial(io); + } + return &io->u.cert.serial; + case CKA_VALUE: + if (0 == io->u.cert.derCert.size) { + io->u.cert.derCert.data = + io->u.cert.certContext->pbCertEncoded; + io->u.cert.derCert.size = + io->u.cert.certContext->cbCertEncoded; + } + return &io->u.cert.derCert; + case CKA_ID: + if (!io->u.cert.hasID) { + return NULL; + } + if (0 == io->id.size) { + ckcapi_FetchID(io); + } + return &io->id; + default: + break; + } + return NULL; +} + +const NSSItem * +ckcapi_FetchPubKeyAttribute( + ckcapiInternalObject *io, + CK_ATTRIBUTE_TYPE type) +{ + PRBool isCertType = (ckcapiCert == io->type); + ckcapiKeyParams *kp = isCertType ? &io->u.cert.key : &io->u.key.key; + + switch (type) { + case CKA_CLASS: + return &ckcapi_pubKeyClassItem; + case CKA_TOKEN: + case CKA_LOCAL: + case CKA_ENCRYPT: + case CKA_VERIFY: + case CKA_VERIFY_RECOVER: + return &ckcapi_trueItem; + case CKA_PRIVATE: + case CKA_MODIFIABLE: + case CKA_DERIVE: + case CKA_WRAP: + return &ckcapi_falseItem; + case CKA_KEY_TYPE: + return &ckcapi_rsaItem; + case CKA_LABEL: + if (!isCertType) { + return &ckcapi_emptyItem; + } + if (0 == io->u.cert.label.size) { + ckcapi_FetchLabel(io); + } + return &io->u.cert.label; + case CKA_SUBJECT: + if (!isCertType) { + return &ckcapi_emptyItem; + } + if (0 == io->u.cert.subject.size) { + PCCERT_CONTEXT certContext = + io->u.cert.certContext; + io->u.cert.subject.data = + certContext->pCertInfo->Subject.pbData; + io->u.cert.subject.size = + certContext->pCertInfo->Subject.cbData; + } + return &io->u.cert.subject; + case CKA_MODULUS: + if (0 == kp->modulus.size) { + ckcapi_PopulateModulusExponent(io); + } + return &kp->modulus; + case CKA_PUBLIC_EXPONENT: + if (0 == kp->modulus.size) { + ckcapi_PopulateModulusExponent(io); + } + return &kp->exponent; + case CKA_ID: + if (0 == io->id.size) { + ckcapi_FetchID(io); + } + return &io->id; + default: + break; + } + return NULL; +} + +const NSSItem * +ckcapi_FetchPrivKeyAttribute( + ckcapiInternalObject *io, + CK_ATTRIBUTE_TYPE type) +{ + PRBool isCertType = (ckcapiCert == io->type); + ckcapiKeyParams *kp = isCertType ? &io->u.cert.key : &io->u.key.key; + + switch (type) { + case CKA_CLASS: + return &ckcapi_privKeyClassItem; + case CKA_TOKEN: + case CKA_LOCAL: + case CKA_SIGN: + case CKA_DECRYPT: + case CKA_SIGN_RECOVER: + return &ckcapi_trueItem; + case CKA_SENSITIVE: + case CKA_PRIVATE: /* should move in the future */ + case CKA_MODIFIABLE: + case CKA_DERIVE: + case CKA_UNWRAP: + case CKA_EXTRACTABLE: /* will probably move in the future */ + case CKA_ALWAYS_SENSITIVE: + case CKA_NEVER_EXTRACTABLE: + return &ckcapi_falseItem; + case CKA_KEY_TYPE: + return &ckcapi_rsaItem; + case CKA_LABEL: + if (!isCertType) { + return &ckcapi_emptyItem; + } + if (0 == io->u.cert.label.size) { + ckcapi_FetchLabel(io); + } + return &io->u.cert.label; + case CKA_SUBJECT: + if (!isCertType) { + return &ckcapi_emptyItem; + } + if (0 == io->u.cert.subject.size) { + PCCERT_CONTEXT certContext = + io->u.cert.certContext; + io->u.cert.subject.data = + certContext->pCertInfo->Subject.pbData; + io->u.cert.subject.size = + certContext->pCertInfo->Subject.cbData; + } + return &io->u.cert.subject; + case CKA_MODULUS: + if (0 == kp->modulus.size) { + ckcapi_PopulateModulusExponent(io); + } + return &kp->modulus; + case CKA_PUBLIC_EXPONENT: + if (0 == kp->modulus.size) { + ckcapi_PopulateModulusExponent(io); + } + return &kp->exponent; + case CKA_PRIVATE_EXPONENT: + if (0 == kp->privateExponent.size) { + ckcapi_FetchPrivateKey(io); + } + return &kp->privateExponent; + case CKA_PRIME_1: + if (0 == kp->privateExponent.size) { + ckcapi_FetchPrivateKey(io); + } + return &kp->prime1; + case CKA_PRIME_2: + if (0 == kp->privateExponent.size) { + ckcapi_FetchPrivateKey(io); + } + return &kp->prime2; + case CKA_EXPONENT_1: + if (0 == kp->privateExponent.size) { + ckcapi_FetchPrivateKey(io); + } + return &kp->exponent1; + case CKA_EXPONENT_2: + if (0 == kp->privateExponent.size) { + ckcapi_FetchPrivateKey(io); + } + return &kp->exponent2; + case CKA_COEFFICIENT: + if (0 == kp->privateExponent.size) { + ckcapi_FetchPrivateKey(io); + } + return &kp->coefficient; + case CKA_ID: + if (0 == io->id.size) { + ckcapi_FetchID(io); + } + return &io->id; + default: + return NULL; + } +} + +const NSSItem * +nss_ckcapi_FetchAttribute( + ckcapiInternalObject *io, + CK_ATTRIBUTE_TYPE type) +{ + CK_ULONG i; + + if (io->type == ckcapiRaw) { + for (i = 0; i < io->u.raw.n; i++) { + if (type == io->u.raw.types[i]) { + return &io->u.raw.items[i]; + } + } + return NULL; + } + /* deal with the common attributes */ + switch (io->objClass) { + case CKO_CERTIFICATE: + return ckcapi_FetchCertAttribute(io, type); + case CKO_PRIVATE_KEY: + return ckcapi_FetchPrivKeyAttribute(io, type); + case CKO_PUBLIC_KEY: + return ckcapi_FetchPubKeyAttribute(io, type); } return NULL; - } - /* deal with the common attributes */ - switch (io->objClass) { - case CKO_CERTIFICATE: - return ckcapi_FetchCertAttribute(io, type); - case CKO_PRIVATE_KEY: - return ckcapi_FetchPrivKeyAttribute(io, type); - case CKO_PUBLIC_KEY: - return ckcapi_FetchPubKeyAttribute(io, type); - } - return NULL; } /* @@ -1161,173 +1132,160 @@ nss_ckcapi_FetchAttribute */ static PRBool ckcapi_cert_exists( - NSSItem *value, - ckcapiInternalObject **io -) + NSSItem *value, + ckcapiInternalObject **io) { - int count,i; - PRUint32 size = 0; - ckcapiInternalObject **listp = NULL; - CK_ATTRIBUTE myTemplate[2]; - CK_OBJECT_CLASS cert_class = CKO_CERTIFICATE; - CK_ULONG templateCount = 2; - CK_RV error; - PRBool found = PR_FALSE; + int count, i; + PRUint32 size = 0; + ckcapiInternalObject **listp = NULL; + CK_ATTRIBUTE myTemplate[2]; + CK_OBJECT_CLASS cert_class = CKO_CERTIFICATE; + CK_ULONG templateCount = 2; + CK_RV error; + PRBool found = PR_FALSE; - myTemplate[0].type = CKA_CLASS; - myTemplate[0].pValue = &cert_class; - myTemplate[0].ulValueLen = sizeof(cert_class); - myTemplate[1].type = CKA_VALUE; - myTemplate[1].pValue = value->data; - myTemplate[1].ulValueLen = value->size; + myTemplate[0].type = CKA_CLASS; + myTemplate[0].pValue = &cert_class; + myTemplate[0].ulValueLen = sizeof(cert_class); + myTemplate[1].type = CKA_VALUE; + myTemplate[1].pValue = value->data; + myTemplate[1].ulValueLen = value->size; - count = nss_ckcapi_collect_all_certs(myTemplate, templateCount, &listp, - &size, 0, &error); + count = nss_ckcapi_collect_all_certs(myTemplate, templateCount, &listp, + &size, 0, &error); - /* free them */ - if (count > 1) { - *io = listp[0]; - found = PR_TRUE; - } - - for (i=1; i < count; i++) { - nss_ckcapi_DestroyInternalObject(listp[i]); - } - nss_ZFreeIf(listp); - return found; + /* free them */ + if (count > 1) { + *io = listp[0]; + found = PR_TRUE; + } + + for (i = 1; i < count; i++) { + nss_ckcapi_DestroyInternalObject(listp[i]); + } + nss_ZFreeIf(listp); + return found; } static PRBool -ckcapi_cert_hasEmail -( - PCCERT_CONTEXT certContext -) +ckcapi_cert_hasEmail( + PCCERT_CONTEXT certContext) { - int count; + int count; - count = CertGetNameString(certContext, CERT_NAME_EMAIL_TYPE, - 0, NULL, NULL, 0); + count = CertGetNameString(certContext, CERT_NAME_EMAIL_TYPE, + 0, NULL, NULL, 0); - return count > 1 ? PR_TRUE : PR_FALSE; + return count > 1 ? PR_TRUE : PR_FALSE; } static PRBool -ckcapi_cert_isRoot -( - PCCERT_CONTEXT certContext -) +ckcapi_cert_isRoot( + PCCERT_CONTEXT certContext) { - return CertCompareCertificateName(certContext->dwCertEncodingType, - &certContext->pCertInfo->Issuer, &certContext->pCertInfo->Subject); + return CertCompareCertificateName(certContext->dwCertEncodingType, + &certContext->pCertInfo->Issuer, &certContext->pCertInfo->Subject); } static PRBool -ckcapi_cert_isCA -( - PCCERT_CONTEXT certContext -) +ckcapi_cert_isCA( + PCCERT_CONTEXT certContext) { - PCERT_EXTENSION extension; - CERT_BASIC_CONSTRAINTS2_INFO basicInfo; - DWORD size = sizeof(basicInfo); - BOOL rc; + PCERT_EXTENSION extension; + CERT_BASIC_CONSTRAINTS2_INFO basicInfo; + DWORD size = sizeof(basicInfo); + BOOL rc; - extension = CertFindExtension (szOID_BASIC_CONSTRAINTS, - certContext->pCertInfo->cExtension, - certContext->pCertInfo->rgExtension); - if ((PCERT_EXTENSION) NULL == extension ) { - return PR_FALSE; - } - rc = CryptDecodeObject(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS2, - extension->Value.pbData, extension->Value.cbData, - 0, &basicInfo, &size); - if (!rc) { - return PR_FALSE; - } - return (PRBool) basicInfo.fCA; + extension = CertFindExtension(szOID_BASIC_CONSTRAINTS, + certContext->pCertInfo->cExtension, + certContext->pCertInfo->rgExtension); + if ((PCERT_EXTENSION)NULL == extension) { + return PR_FALSE; + } + rc = CryptDecodeObject(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS2, + extension->Value.pbData, extension->Value.cbData, + 0, &basicInfo, &size); + if (!rc) { + return PR_FALSE; + } + return (PRBool)basicInfo.fCA; } static CRYPT_KEY_PROV_INFO * -ckcapi_cert_getPrivateKeyInfo -( - PCCERT_CONTEXT certContext, - NSSItem *keyID -) +ckcapi_cert_getPrivateKeyInfo( + PCCERT_CONTEXT certContext, + NSSItem *keyID) { - BOOL rc; - CRYPT_HASH_BLOB msKeyID; - DWORD size = 0; - CRYPT_KEY_PROV_INFO *prov = NULL; + BOOL rc; + CRYPT_HASH_BLOB msKeyID; + DWORD size = 0; + CRYPT_KEY_PROV_INFO *prov = NULL; - msKeyID.cbData = keyID->size; - msKeyID.pbData = keyID->data; + msKeyID.cbData = keyID->size; + msKeyID.pbData = keyID->data; - rc = CryptGetKeyIdentifierProperty( - &msKeyID, - CERT_KEY_PROV_INFO_PROP_ID, - 0, NULL, NULL, NULL, &size); - if (!rc) { - return (CRYPT_KEY_PROV_INFO *)NULL; - } - prov = (CRYPT_KEY_PROV_INFO *)nss_ZAlloc(NULL, size); - if ((CRYPT_KEY_PROV_INFO *)prov == NULL) { - return (CRYPT_KEY_PROV_INFO *) NULL; - } - rc = CryptGetKeyIdentifierProperty( - &msKeyID, - CERT_KEY_PROV_INFO_PROP_ID, - 0, NULL, NULL, prov, &size); - if (!rc) { - nss_ZFreeIf(prov); - return (CRYPT_KEY_PROV_INFO *)NULL; - } - - return prov; + rc = CryptGetKeyIdentifierProperty( + &msKeyID, + CERT_KEY_PROV_INFO_PROP_ID, + 0, NULL, NULL, NULL, &size); + if (!rc) { + return (CRYPT_KEY_PROV_INFO *)NULL; + } + prov = (CRYPT_KEY_PROV_INFO *)nss_ZAlloc(NULL, size); + if ((CRYPT_KEY_PROV_INFO *)prov == NULL) { + return (CRYPT_KEY_PROV_INFO *)NULL; + } + rc = CryptGetKeyIdentifierProperty( + &msKeyID, + CERT_KEY_PROV_INFO_PROP_ID, + 0, NULL, NULL, prov, &size); + if (!rc) { + nss_ZFreeIf(prov); + return (CRYPT_KEY_PROV_INFO *)NULL; + } + + return prov; } static CRYPT_KEY_PROV_INFO * -ckcapi_cert_getProvInfo -( - ckcapiInternalObject *io -) +ckcapi_cert_getProvInfo( + ckcapiInternalObject *io) { - BOOL rc; - DWORD size = 0; - CRYPT_KEY_PROV_INFO *prov = NULL; + BOOL rc; + DWORD size = 0; + CRYPT_KEY_PROV_INFO *prov = NULL; - rc = CertGetCertificateContextProperty( - io->u.cert.certContext, - CERT_KEY_PROV_INFO_PROP_ID, - NULL, &size); - if (!rc) { - return (CRYPT_KEY_PROV_INFO *)NULL; - } - prov = (CRYPT_KEY_PROV_INFO *)nss_ZAlloc(NULL, size); - if ((CRYPT_KEY_PROV_INFO *)prov == NULL) { - return (CRYPT_KEY_PROV_INFO *) NULL; - } - rc = CertGetCertificateContextProperty( - io->u.cert.certContext, - CERT_KEY_PROV_INFO_PROP_ID, - prov, &size); - if (!rc) { - nss_ZFreeIf(prov); - return (CRYPT_KEY_PROV_INFO *)NULL; - } + rc = CertGetCertificateContextProperty( + io->u.cert.certContext, + CERT_KEY_PROV_INFO_PROP_ID, + NULL, &size); + if (!rc) { + return (CRYPT_KEY_PROV_INFO *)NULL; + } + prov = (CRYPT_KEY_PROV_INFO *)nss_ZAlloc(NULL, size); + if ((CRYPT_KEY_PROV_INFO *)prov == NULL) { + return (CRYPT_KEY_PROV_INFO *)NULL; + } + rc = CertGetCertificateContextProperty( + io->u.cert.certContext, + CERT_KEY_PROV_INFO_PROP_ID, + prov, &size); + if (!rc) { + nss_ZFreeIf(prov); + return (CRYPT_KEY_PROV_INFO *)NULL; + } - return prov; + return prov; } - + /* forward declaration */ static void -ckcapi_removeObjectFromHash -( - ckcapiInternalObject *io -); +ckcapi_removeObjectFromHash( + ckcapiInternalObject *io); /* * Finalize - unneeded - * Destroy + * Destroy * IsTokenObject - CK_TRUE * GetAttributeCount * GetAttributeTypes @@ -1338,968 +1296,944 @@ ckcapi_removeObjectFromHash */ static CK_RV -ckcapi_mdObject_Destroy -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdObject_Destroy( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; - CK_OBJECT_CLASS objClass; - BOOL rc; - DWORD provType; - DWORD msError; - PRBool isCertType = (PRBool)(ckcapiCert == io->type); - HCERTSTORE hStore = 0; + ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; + CK_OBJECT_CLASS objClass; + BOOL rc; + DWORD provType; + DWORD msError; + PRBool isCertType = (PRBool)(ckcapiCert == io->type); + HCERTSTORE hStore = 0; - if (ckcapiRaw == io->type) { - /* there is not 'object write protected' error, use the next best thing */ - return CKR_TOKEN_WRITE_PROTECTED; - } - - objClass = io->objClass; - if (CKO_CERTIFICATE == objClass) { - PCCERT_CONTEXT certContext; - - /* get the store */ - hStore = CertOpenSystemStore(0, io->u.cert.certStore); - if (0 == hStore) { - rc = 0; - goto loser; - } - certContext = CertFindCertificateInStore(hStore, X509_ASN_ENCODING, 0, - CERT_FIND_EXISTING, io->u.cert.certContext, NULL); - if ((PCCERT_CONTEXT)NULL == certContext) { - rc = 0; - goto loser; - } - rc = CertDeleteCertificateFromStore(certContext); - } else { - char *provName = NULL; - char *containerName = NULL; - HCRYPTPROV hProv; - CRYPT_HASH_BLOB msKeyID; - - if (0 == io->id.size) { - ckcapi_FetchID(io); + if (ckcapiRaw == io->type) { + /* there is not 'object write protected' error, use the next best thing */ + return CKR_TOKEN_WRITE_PROTECTED; } - if (isCertType) { - CRYPT_KEY_PROV_INFO * provInfo = ckcapi_cert_getProvInfo(io); - provName = nss_ckcapi_WideToUTF8(provInfo->pwszProvName); - containerName = nss_ckcapi_WideToUTF8(provInfo->pwszContainerName); - provType = provInfo->dwProvType; - nss_ZFreeIf(provInfo); - } else { - provName = io->u.key.provName; - containerName = io->u.key.containerName; - provType = io->u.key.provInfo.dwProvType; - io->u.key.provName = NULL; - io->u.key.containerName = NULL; + objClass = io->objClass; + if (CKO_CERTIFICATE == objClass) { + PCCERT_CONTEXT certContext; + + /* get the store */ + hStore = CertOpenSystemStore(0, io->u.cert.certStore); + if (0 == hStore) { + rc = 0; + goto loser; + } + certContext = CertFindCertificateInStore(hStore, X509_ASN_ENCODING, 0, + CERT_FIND_EXISTING, io->u.cert.certContext, NULL); + if ((PCCERT_CONTEXT)NULL == certContext) { + rc = 0; + goto loser; + } + rc = CertDeleteCertificateFromStore(certContext); } - /* first remove the key id pointer */ - msKeyID.cbData = io->id.size; - msKeyID.pbData = io->id.data; - rc = CryptSetKeyIdentifierProperty(&msKeyID, - CERT_KEY_PROV_INFO_PROP_ID, CRYPT_KEYID_DELETE_FLAG, NULL, NULL, NULL); - if (rc) { - rc = CryptAcquireContext(&hProv, containerName, provName, provType, - CRYPT_DELETEKEYSET); + else { + char *provName = NULL; + char *containerName = NULL; + HCRYPTPROV hProv; + CRYPT_HASH_BLOB msKeyID; + + if (0 == io->id.size) { + ckcapi_FetchID(io); + } + + if (isCertType) { + CRYPT_KEY_PROV_INFO *provInfo = ckcapi_cert_getProvInfo(io); + provName = nss_ckcapi_WideToUTF8(provInfo->pwszProvName); + containerName = nss_ckcapi_WideToUTF8(provInfo->pwszContainerName); + provType = provInfo->dwProvType; + nss_ZFreeIf(provInfo); + } + else { + provName = io->u.key.provName; + containerName = io->u.key.containerName; + provType = io->u.key.provInfo.dwProvType; + io->u.key.provName = NULL; + io->u.key.containerName = NULL; + } + /* first remove the key id pointer */ + msKeyID.cbData = io->id.size; + msKeyID.pbData = io->id.data; + rc = CryptSetKeyIdentifierProperty(&msKeyID, + CERT_KEY_PROV_INFO_PROP_ID, CRYPT_KEYID_DELETE_FLAG, NULL, NULL, NULL); + if (rc) { + rc = CryptAcquireContext(&hProv, containerName, provName, provType, + CRYPT_DELETEKEYSET); + } + nss_ZFreeIf(provName); + nss_ZFreeIf(containerName); } - nss_ZFreeIf(provName); - nss_ZFreeIf(containerName); - } loser: - if (hStore) { - CertCloseStore(hStore, 0); - } - if (!rc) { - msError = GetLastError(); - return CKR_GENERAL_ERROR; - } + if (hStore) { + CertCloseStore(hStore, 0); + } + if (!rc) { + msError = GetLastError(); + return CKR_GENERAL_ERROR; + } - /* remove it from the hash */ - ckcapi_removeObjectFromHash(io); + /* remove it from the hash */ + ckcapi_removeObjectFromHash(io); - /* free the puppy.. */ - nss_ckcapi_DestroyInternalObject(io); - return CKR_OK; + /* free the puppy.. */ + nss_ckcapi_DestroyInternalObject(io); + return CKR_OK; } static CK_BBOOL -ckcapi_mdObject_IsTokenObject -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdObject_IsTokenObject( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_TRUE; + return CK_TRUE; } static CK_ULONG -ckcapi_mdObject_GetAttributeCount -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdObject_GetAttributeCount( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; + ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; - if (ckcapiRaw == io->type) { - return io->u.raw.n; - } - switch (io->objClass) { - case CKO_CERTIFICATE: - return certAttrsCount; - case CKO_PUBLIC_KEY: - return pubKeyAttrsCount; - case CKO_PRIVATE_KEY: - return privKeyAttrsCount; - default: - break; - } - return 0; -} - -static CK_RV -ckcapi_mdObject_GetAttributeTypes -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -) -{ - ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; - CK_ULONG i; - CK_RV error = CKR_OK; - const CK_ATTRIBUTE_TYPE *attrs = NULL; - CK_ULONG size = ckcapi_mdObject_GetAttributeCount( - mdObject, fwObject, mdSession, fwSession, - mdToken, fwToken, mdInstance, fwInstance, &error); - - if( size != ulCount ) { - return CKR_BUFFER_TOO_SMALL; - } - if (io->type == ckcapiRaw) { - attrs = io->u.raw.types; - } else switch(io->objClass) { - case CKO_CERTIFICATE: - attrs = certAttrs; - break; - case CKO_PUBLIC_KEY: - attrs = pubKeyAttrs; - break; - case CKO_PRIVATE_KEY: - attrs = privKeyAttrs; - break; - default: - return CKR_OK; - } - - for( i = 0; i < size; i++) { - typeArray[i] = attrs[i]; - } - - return CKR_OK; -} - -static CK_ULONG -ckcapi_mdObject_GetAttributeSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) -{ - ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; - - const NSSItem *b; - - b = nss_ckcapi_FetchAttribute(io, attribute); - - if ((const NSSItem *)NULL == b) { - *pError = CKR_ATTRIBUTE_TYPE_INVALID; + if (ckcapiRaw == io->type) { + return io->u.raw.n; + } + switch (io->objClass) { + case CKO_CERTIFICATE: + return certAttrsCount; + case CKO_PUBLIC_KEY: + return pubKeyAttrsCount; + case CKO_PRIVATE_KEY: + return privKeyAttrsCount; + default: + break; + } return 0; - } - return b->size; } static CK_RV -ckcapi_mdObject_SetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value -) +ckcapi_mdObject_GetAttributeTypes( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount) { - return CKR_OK; + ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; + CK_ULONG i; + CK_RV error = CKR_OK; + const CK_ATTRIBUTE_TYPE *attrs = NULL; + CK_ULONG size = ckcapi_mdObject_GetAttributeCount( + mdObject, fwObject, mdSession, fwSession, + mdToken, fwToken, mdInstance, fwInstance, &error); + + if (size != ulCount) { + return CKR_BUFFER_TOO_SMALL; + } + if (io->type == ckcapiRaw) { + attrs = io->u.raw.types; + } + else + switch (io->objClass) { + case CKO_CERTIFICATE: + attrs = + certAttrs; + break; + case CKO_PUBLIC_KEY: + attrs = + pubKeyAttrs; + break; + case CKO_PRIVATE_KEY: + attrs = + privKeyAttrs; + break; + default: + return CKR_OK; + } + + for (i = 0; i < size; i++) { + typeArray[i] = attrs[i]; + } + + return CKR_OK; +} + +static CK_ULONG +ckcapi_mdObject_GetAttributeSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) +{ + ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; + + const NSSItem *b; + + b = nss_ckcapi_FetchAttribute(io, attribute); + + if ((const NSSItem *)NULL == b) { + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + return 0; + } + return b->size; +} + +static CK_RV +ckcapi_mdObject_SetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value) +{ + return CKR_OK; } static NSSCKFWItem -ckcapi_mdObject_GetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +ckcapi_mdObject_GetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - NSSCKFWItem mdItem; - ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; + NSSCKFWItem mdItem; + ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; - mdItem.needsFreeing = PR_FALSE; - mdItem.item = (NSSItem*)nss_ckcapi_FetchAttribute(io, attribute); + mdItem.needsFreeing = PR_FALSE; + mdItem.item = (NSSItem *)nss_ckcapi_FetchAttribute(io, attribute); - if ((NSSItem *)NULL == mdItem.item) { - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - } + if ((NSSItem *)NULL == mdItem.item) { + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + } - return mdItem; + return mdItem; } static CK_ULONG -ckcapi_mdObject_GetObjectSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdObject_GetObjectSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; - CK_ULONG rv = 1; + ckcapiInternalObject *io = (ckcapiInternalObject *)mdObject->etc; + CK_ULONG rv = 1; - /* size is irrelevant to this token */ - return rv; + /* size is irrelevant to this token */ + return rv; } static const NSSCKMDObject -ckcapi_prototype_mdObject = { - (void *)NULL, /* etc */ - NULL, /* Finalize */ - ckcapi_mdObject_Destroy, - ckcapi_mdObject_IsTokenObject, - ckcapi_mdObject_GetAttributeCount, - ckcapi_mdObject_GetAttributeTypes, - ckcapi_mdObject_GetAttributeSize, - ckcapi_mdObject_GetAttribute, - NULL, /* FreeAttribute */ - ckcapi_mdObject_SetAttribute, - ckcapi_mdObject_GetObjectSize, - (void *)NULL /* null terminator */ -}; + ckcapi_prototype_mdObject = { + (void *)NULL, /* etc */ + NULL, /* Finalize */ + ckcapi_mdObject_Destroy, + ckcapi_mdObject_IsTokenObject, + ckcapi_mdObject_GetAttributeCount, + ckcapi_mdObject_GetAttributeTypes, + ckcapi_mdObject_GetAttributeSize, + ckcapi_mdObject_GetAttribute, + NULL, /* FreeAttribute */ + ckcapi_mdObject_SetAttribute, + ckcapi_mdObject_GetObjectSize, + (void *)NULL /* null terminator */ + }; static nssHash *ckcapiInternalObjectHash = NULL; NSS_IMPLEMENT NSSCKMDObject * -nss_ckcapi_CreateMDObject -( - NSSArena *arena, - ckcapiInternalObject *io, - CK_RV *pError -) +nss_ckcapi_CreateMDObject( + NSSArena *arena, + ckcapiInternalObject *io, + CK_RV *pError) { - if ((nssHash *)NULL == ckcapiInternalObjectHash) { - ckcapiInternalObjectHash = nssHash_CreateItem(NULL, 10); - } - if (ckcapiCert == io->type) { - /* the hash key, not a cryptographic key */ - NSSItem *key = &io->hashKey; - ckcapiInternalObject *old_o = NULL; + if ((nssHash *)NULL == ckcapiInternalObjectHash) { + ckcapiInternalObjectHash = nssHash_CreateItem(NULL, 10); + } + if (ckcapiCert == io->type) { + /* the hash key, not a cryptographic key */ + NSSItem *key = &io->hashKey; + ckcapiInternalObject *old_o = NULL; - if (key->size == 0) { - ckcapi_FetchHashKey(io); + if (key->size == 0) { + ckcapi_FetchHashKey(io); + } + old_o = (ckcapiInternalObject *) + nssHash_Lookup(ckcapiInternalObjectHash, key); + if (!old_o) { + nssHash_Add(ckcapiInternalObjectHash, key, io); + } + else if (old_o != io) { + nss_ckcapi_DestroyInternalObject(io); + io = old_o; + } } - old_o = (ckcapiInternalObject *) - nssHash_Lookup(ckcapiInternalObjectHash, key); - if (!old_o) { - nssHash_Add(ckcapiInternalObjectHash, key, io); - } else if (old_o != io) { - nss_ckcapi_DestroyInternalObject(io); - io = old_o; + + if ((void *)NULL == io->mdObject.etc) { + (void)nsslibc_memcpy(&io->mdObject, &ckcapi_prototype_mdObject, + sizeof(ckcapi_prototype_mdObject)); + io->mdObject.etc = (void *)io; } - } - - if ( (void*)NULL == io->mdObject.etc) { - (void) nsslibc_memcpy(&io->mdObject,&ckcapi_prototype_mdObject, - sizeof(ckcapi_prototype_mdObject)); - io->mdObject.etc = (void *)io; - } - return &io->mdObject; + return &io->mdObject; } static void -ckcapi_removeObjectFromHash -( - ckcapiInternalObject *io -) +ckcapi_removeObjectFromHash( + ckcapiInternalObject *io) { - NSSItem *key = &io->hashKey; + NSSItem *key = &io->hashKey; - if ((nssHash *)NULL == ckcapiInternalObjectHash) { + if ((nssHash *)NULL == ckcapiInternalObjectHash) { + return; + } + if (key->size == 0) { + ckcapi_FetchHashKey(io); + } + nssHash_Remove(ckcapiInternalObjectHash, key); return; - } - if (key->size == 0) { - ckcapi_FetchHashKey(io); - } - nssHash_Remove(ckcapiInternalObjectHash, key); - return; } void -nss_ckcapi_DestroyInternalObject -( - ckcapiInternalObject *io -) +nss_ckcapi_DestroyInternalObject( + ckcapiInternalObject *io) { - switch (io->type) { - case ckcapiRaw: - return; - case ckcapiCert: - CertFreeCertificateContext(io->u.cert.certContext); - nss_ZFreeIf(io->u.cert.labelData); - nss_ZFreeIf(io->u.cert.key.privateKey); - nss_ZFreeIf(io->u.cert.key.pubKey); - nss_ZFreeIf(io->idData); - break; - case ckcapiBareKey: - nss_ZFreeIf(io->u.key.provInfo.pwszContainerName); - nss_ZFreeIf(io->u.key.provInfo.pwszProvName); - nss_ZFreeIf(io->u.key.provName); - nss_ZFreeIf(io->u.key.containerName); - nss_ZFreeIf(io->u.key.key.privateKey); - nss_ZFreeIf(io->u.key.key.pubKey); - if (0 != io->u.key.hProv) { - CryptReleaseContext(io->u.key.hProv, 0); + switch (io->type) { + case ckcapiRaw: + return; + case ckcapiCert: + CertFreeCertificateContext(io->u.cert.certContext); + nss_ZFreeIf(io->u.cert.labelData); + nss_ZFreeIf(io->u.cert.key.privateKey); + nss_ZFreeIf(io->u.cert.key.pubKey); + nss_ZFreeIf(io->idData); + break; + case ckcapiBareKey: + nss_ZFreeIf(io->u.key.provInfo.pwszContainerName); + nss_ZFreeIf(io->u.key.provInfo.pwszProvName); + nss_ZFreeIf(io->u.key.provName); + nss_ZFreeIf(io->u.key.containerName); + nss_ZFreeIf(io->u.key.key.privateKey); + nss_ZFreeIf(io->u.key.key.pubKey); + if (0 != io->u.key.hProv) { + CryptReleaseContext(io->u.key.hProv, 0); + } + nss_ZFreeIf(io->idData); + break; } - nss_ZFreeIf(io->idData); - break; - } - nss_ZFreeIf(io); - return; + nss_ZFreeIf(io); + return; } static ckcapiInternalObject * -nss_ckcapi_CreateCertificate -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckcapi_CreateCertificate( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSItem value; - NSSItem keyID; - char *storeStr; - ckcapiInternalObject *io = NULL; - PCCERT_CONTEXT certContext = NULL; - PCCERT_CONTEXT storedCertContext = NULL; - CRYPT_KEY_PROV_INFO *prov_info = NULL; - char *nickname = NULL; - HCERTSTORE hStore = 0; - DWORD msError = 0; - PRBool hasID; - CK_RV dummy; - BOOL rc; + NSSItem value; + NSSItem keyID; + char *storeStr; + ckcapiInternalObject *io = NULL; + PCCERT_CONTEXT certContext = NULL; + PCCERT_CONTEXT storedCertContext = NULL; + CRYPT_KEY_PROV_INFO *prov_info = NULL; + char *nickname = NULL; + HCERTSTORE hStore = 0; + DWORD msError = 0; + PRBool hasID; + CK_RV dummy; + BOOL rc; - *pError = nss_ckcapi_GetAttribute(CKA_VALUE, pTemplate, - ulAttributeCount, &value); + *pError = nss_ckcapi_GetAttribute(CKA_VALUE, pTemplate, + ulAttributeCount, &value); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } - *pError = nss_ckcapi_GetAttribute(CKA_ID, pTemplate, - ulAttributeCount, &keyID); + *pError = nss_ckcapi_GetAttribute(CKA_ID, pTemplate, + ulAttributeCount, &keyID); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } - if (ckcapi_cert_exists(&value, &io)) { - return io; - } + if (ckcapi_cert_exists(&value, &io)) { + return io; + } - /* OK, we are creating a new one, figure out what store it belongs to.. + /* OK, we are creating a new one, figure out what store it belongs to.. * first get a certContext handle.. */ - certContext = CertCreateCertificateContext(X509_ASN_ENCODING, - value.data, value.size); - if ((PCCERT_CONTEXT) NULL == certContext) { - msError = GetLastError(); - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - - /* do we have a private key laying around... */ - prov_info = ckcapi_cert_getPrivateKeyInfo(certContext, &keyID); - if (prov_info) { - CRYPT_DATA_BLOB msKeyID; - storeStr = "My"; - hasID = PR_TRUE; - rc = CertSetCertificateContextProperty(certContext, - CERT_KEY_PROV_INFO_PROP_ID, - 0, prov_info); - nss_ZFreeIf(prov_info); - if (!rc) { - msError = GetLastError(); - *pError = CKR_DEVICE_ERROR; - goto loser; + certContext = CertCreateCertificateContext(X509_ASN_ENCODING, + value.data, value.size); + if ((PCCERT_CONTEXT)NULL == certContext) { + msError = GetLastError(); + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; } - msKeyID.cbData = keyID.size; - msKeyID.pbData = keyID.data; - rc = CertSetCertificateContextProperty(certContext, - CERT_KEY_IDENTIFIER_PROP_ID, - 0, &msKeyID); - if (!rc) { - msError = GetLastError(); - *pError = CKR_DEVICE_ERROR; - goto loser; + + /* do we have a private key laying around... */ + prov_info = ckcapi_cert_getPrivateKeyInfo(certContext, &keyID); + if (prov_info) { + CRYPT_DATA_BLOB msKeyID; + storeStr = "My"; + hasID = PR_TRUE; + rc = CertSetCertificateContextProperty(certContext, + CERT_KEY_PROV_INFO_PROP_ID, + 0, prov_info); + nss_ZFreeIf(prov_info); + if (!rc) { + msError = GetLastError(); + *pError = CKR_DEVICE_ERROR; + goto loser; + } + msKeyID.cbData = keyID.size; + msKeyID.pbData = keyID.data; + rc = CertSetCertificateContextProperty(certContext, + CERT_KEY_IDENTIFIER_PROP_ID, + 0, &msKeyID); + if (!rc) { + msError = GetLastError(); + *pError = CKR_DEVICE_ERROR; + goto loser; + } + + /* does it look like a CA */ } - - /* does it look like a CA */ - } else if (ckcapi_cert_isCA(certContext)) { - storeStr = ckcapi_cert_isRoot(certContext) ? "CA" : "Root"; - /* does it look like an S/MIME cert */ - } else if (ckcapi_cert_hasEmail(certContext)) { - storeStr = "AddressBook"; - } else { - /* just pick a store */ - storeStr = "CA"; - } - - /* get the nickname, not an error if we can't find it */ - nickname = nss_ckcapi_GetStringAttribute(CKA_LABEL, pTemplate, - ulAttributeCount, &dummy); - if (nickname) { - LPWSTR nicknameUTF16 = NULL; - CRYPT_DATA_BLOB nicknameBlob; - - nicknameUTF16 = nss_ckcapi_UTF8ToWide(nickname); - nss_ZFreeIf(nickname); - nickname = NULL; - if ((LPWSTR)NULL == nicknameUTF16) { - *pError = CKR_HOST_MEMORY; - goto loser; + else if (ckcapi_cert_isCA(certContext)) { + storeStr = ckcapi_cert_isRoot(certContext) ? "CA" : "Root"; + /* does it look like an S/MIME cert */ } - nicknameBlob.cbData = nss_ckcapi_WideSize(nicknameUTF16); - nicknameBlob.pbData = (BYTE *)nicknameUTF16; - rc = CertSetCertificateContextProperty(certContext, - CERT_FRIENDLY_NAME_PROP_ID, 0, &nicknameBlob); - nss_ZFreeIf(nicknameUTF16); - if (!rc) { - msError = GetLastError(); - *pError = CKR_DEVICE_ERROR; - goto loser; + else if (ckcapi_cert_hasEmail(certContext)) { + storeStr = "AddressBook"; + } + else { + /* just pick a store */ + storeStr = "CA"; } - } - hStore = CertOpenSystemStore((HCRYPTPROV) NULL, storeStr); - if (0 == hStore) { - msError = GetLastError(); - *pError = CKR_DEVICE_ERROR; - goto loser; - } + /* get the nickname, not an error if we can't find it */ + nickname = nss_ckcapi_GetStringAttribute(CKA_LABEL, pTemplate, + ulAttributeCount, &dummy); + if (nickname) { + LPWSTR nicknameUTF16 = NULL; + CRYPT_DATA_BLOB nicknameBlob; - rc = CertAddCertificateContextToStore(hStore, certContext, - CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, &storedCertContext); - CertFreeCertificateContext(certContext); - certContext = NULL; - CertCloseStore(hStore, 0); - hStore = 0; - if (!rc) { - msError = GetLastError(); - *pError = CKR_DEVICE_ERROR; - goto loser; - } + nicknameUTF16 = nss_ckcapi_UTF8ToWide(nickname); + nss_ZFreeIf(nickname); + nickname = NULL; + if ((LPWSTR)NULL == nicknameUTF16) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + nicknameBlob.cbData = nss_ckcapi_WideSize(nicknameUTF16); + nicknameBlob.pbData = (BYTE *)nicknameUTF16; + rc = CertSetCertificateContextProperty(certContext, + CERT_FRIENDLY_NAME_PROP_ID, 0, &nicknameBlob); + nss_ZFreeIf(nicknameUTF16); + if (!rc) { + msError = GetLastError(); + *pError = CKR_DEVICE_ERROR; + goto loser; + } + } - io = nss_ZNEW(NULL, ckcapiInternalObject); - if ((ckcapiInternalObject *)NULL == io) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - io->type = ckcapiCert; - io->objClass = CKO_CERTIFICATE; - io->u.cert.certContext = storedCertContext; - io->u.cert.hasID = hasID; - return io; + hStore = CertOpenSystemStore((HCRYPTPROV)NULL, storeStr); + if (0 == hStore) { + msError = GetLastError(); + *pError = CKR_DEVICE_ERROR; + goto loser; + } -loser: - if (certContext) { + rc = CertAddCertificateContextToStore(hStore, certContext, + CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, &storedCertContext); CertFreeCertificateContext(certContext); certContext = NULL; - } - if (storedCertContext) { - CertFreeCertificateContext(storedCertContext); - storedCertContext = NULL; - } - if (0 != hStore) { CertCloseStore(hStore, 0); - } - return (ckcapiInternalObject *)NULL; + hStore = 0; + if (!rc) { + msError = GetLastError(); + *pError = CKR_DEVICE_ERROR; + goto loser; + } + io = nss_ZNEW(NULL, ckcapiInternalObject); + if ((ckcapiInternalObject *)NULL == io) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + io->type = ckcapiCert; + io->objClass = CKO_CERTIFICATE; + io->u.cert.certContext = storedCertContext; + io->u.cert.hasID = hasID; + return io; + +loser: + if (certContext) { + CertFreeCertificateContext(certContext); + certContext = NULL; + } + if (storedCertContext) { + CertFreeCertificateContext(storedCertContext); + storedCertContext = NULL; + } + if (0 != hStore) { + CertCloseStore(hStore, 0); + } + return (ckcapiInternalObject *)NULL; } static char * -ckcapi_getDefaultProvider -( - CK_RV *pError -) +ckcapi_getDefaultProvider( + CK_RV *pError) { - char *name = NULL; - BOOL rc; - DWORD nameLength = 0; + char *name = NULL; + BOOL rc; + DWORD nameLength = 0; - rc = CryptGetDefaultProvider(PROV_RSA_FULL, NULL, CRYPT_USER_DEFAULT, NULL, - &nameLength); - if (!rc) { - return (char *)NULL; - } + rc = CryptGetDefaultProvider(PROV_RSA_FULL, NULL, CRYPT_USER_DEFAULT, NULL, + &nameLength); + if (!rc) { + return (char *)NULL; + } - name = nss_ZNEWARRAY(NULL, char, nameLength); - if ((char *)NULL == name ) { - return (char *)NULL; - } - rc = CryptGetDefaultProvider(PROV_RSA_FULL, NULL, CRYPT_USER_DEFAULT, name, - &nameLength); - if (!rc) { - nss_ZFreeIf(name); - return (char *)NULL; - } + name = nss_ZNEWARRAY(NULL, char, nameLength); + if ((char *)NULL == name) { + return (char *)NULL; + } + rc = CryptGetDefaultProvider(PROV_RSA_FULL, NULL, CRYPT_USER_DEFAULT, name, + &nameLength); + if (!rc) { + nss_ZFreeIf(name); + return (char *)NULL; + } - return name; + return name; } static char * -ckcapi_getContainer -( - CK_RV *pError, - NSSItem *id -) +ckcapi_getContainer( + CK_RV *pError, + NSSItem *id) { - RPC_STATUS rstat; - UUID uuid; - char *uuidStr; - char *container; + RPC_STATUS rstat; + UUID uuid; + char *uuidStr; + char *container; - rstat = UuidCreate(&uuid); - rstat = UuidToString(&uuid, &uuidStr); + rstat = UuidCreate(&uuid); + rstat = UuidToString(&uuid, &uuidStr); - /* convert it from rcp memory to our own */ - container = nssUTF8_Duplicate(uuidStr, NULL); - RpcStringFree(&uuidStr); - - return container; + /* convert it from rcp memory to our own */ + container = nssUTF8_Duplicate(uuidStr, NULL); + RpcStringFree(&uuidStr); + + return container; } static CK_RV -ckcapi_buildPrivateKeyBlob -( - NSSItem *keyBlob, - NSSItem *modulus, - NSSItem *publicExponent, - NSSItem *privateExponent, - NSSItem *prime1, - NSSItem *prime2, - NSSItem *exponent1, - NSSItem *exponent2, - NSSItem *coefficient, - PRBool isKeyExchange -) +ckcapi_buildPrivateKeyBlob( + NSSItem *keyBlob, + NSSItem *modulus, + NSSItem *publicExponent, + NSSItem *privateExponent, + NSSItem *prime1, + NSSItem *prime2, + NSSItem *exponent1, + NSSItem *exponent2, + NSSItem *coefficient, + PRBool isKeyExchange) { - CAPI_RSA_KEY_BLOB *keyBlobData = NULL; - unsigned char *target; - unsigned long modSize = modulus->size; - unsigned long dataSize; - CK_RV error = CKR_OK; + CAPI_RSA_KEY_BLOB *keyBlobData = NULL; + unsigned char *target; + unsigned long modSize = modulus->size; + unsigned long dataSize; + CK_RV error = CKR_OK; - /* validate extras */ - if (privateExponent->size != modSize) { - error = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - if (prime1->size != modSize/2) { - error = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - if (prime2->size != modSize/2) { - error = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - if (exponent1->size != modSize/2) { - error = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - if (exponent2->size != modSize/2) { - error = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - if (coefficient->size != modSize/2) { - error = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - dataSize = (modSize*4)+(modSize/2) + sizeof(CAPI_RSA_KEY_BLOB); - keyBlobData = (CAPI_RSA_KEY_BLOB *)nss_ZAlloc(NULL, dataSize); - if ((CAPI_RSA_KEY_BLOB *)NULL == keyBlobData) { - error = CKR_HOST_MEMORY; - goto loser; - } + /* validate extras */ + if (privateExponent->size != modSize) { + error = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; + } + if (prime1->size != modSize / 2) { + error = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; + } + if (prime2->size != modSize / 2) { + error = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; + } + if (exponent1->size != modSize / 2) { + error = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; + } + if (exponent2->size != modSize / 2) { + error = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; + } + if (coefficient->size != modSize / 2) { + error = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; + } + dataSize = (modSize * 4) + (modSize / 2) + sizeof(CAPI_RSA_KEY_BLOB); + keyBlobData = (CAPI_RSA_KEY_BLOB *)nss_ZAlloc(NULL, dataSize); + if ((CAPI_RSA_KEY_BLOB *)NULL == keyBlobData) { + error = CKR_HOST_MEMORY; + goto loser; + } - keyBlobData->header.bType = PRIVATEKEYBLOB; - keyBlobData->header.bVersion = 0x02; - keyBlobData->header.reserved = 0x00; - keyBlobData->header.aiKeyAlg = isKeyExchange ? CALG_RSA_KEYX:CALG_RSA_SIGN; - keyBlobData->rsa.magic = 0x32415352; - keyBlobData->rsa.bitlen = modSize * 8; - keyBlobData->rsa.pubexp = nss_ckcapi_DataToInt(publicExponent,&error); - if (CKR_OK != error) { - goto loser; - } + keyBlobData->header.bType = PRIVATEKEYBLOB; + keyBlobData->header.bVersion = 0x02; + keyBlobData->header.reserved = 0x00; + keyBlobData->header.aiKeyAlg = isKeyExchange ? CALG_RSA_KEYX : CALG_RSA_SIGN; + keyBlobData->rsa.magic = 0x32415352; + keyBlobData->rsa.bitlen = modSize * 8; + keyBlobData->rsa.pubexp = nss_ckcapi_DataToInt(publicExponent, &error); + if (CKR_OK != error) { + goto loser; + } - target = &keyBlobData->data[CAPI_MODULUS_OFFSET(modSize)]; - nsslibc_memcpy(target, modulus->data, modulus->size); - modulus->data = target; - ckcapi_ReverseData(modulus); + target = &keyBlobData->data[CAPI_MODULUS_OFFSET(modSize)]; + nsslibc_memcpy(target, modulus->data, modulus->size); + modulus->data = target; + ckcapi_ReverseData(modulus); - target = &keyBlobData->data[CAPI_PRIVATE_EXP_OFFSET(modSize)]; - nsslibc_memcpy(target, privateExponent->data, privateExponent->size); - privateExponent->data = target; - ckcapi_ReverseData(privateExponent); + target = &keyBlobData->data[CAPI_PRIVATE_EXP_OFFSET(modSize)]; + nsslibc_memcpy(target, privateExponent->data, privateExponent->size); + privateExponent->data = target; + ckcapi_ReverseData(privateExponent); - target = &keyBlobData->data[CAPI_PRIME_1_OFFSET(modSize)]; - nsslibc_memcpy(target, prime1->data, prime1->size); - prime1->data = target; - ckcapi_ReverseData(prime1); + target = &keyBlobData->data[CAPI_PRIME_1_OFFSET(modSize)]; + nsslibc_memcpy(target, prime1->data, prime1->size); + prime1->data = target; + ckcapi_ReverseData(prime1); - target = &keyBlobData->data[CAPI_PRIME_2_OFFSET(modSize)]; - nsslibc_memcpy(target, prime2->data, prime2->size); - prime2->data = target; - ckcapi_ReverseData(prime2); + target = &keyBlobData->data[CAPI_PRIME_2_OFFSET(modSize)]; + nsslibc_memcpy(target, prime2->data, prime2->size); + prime2->data = target; + ckcapi_ReverseData(prime2); - target = &keyBlobData->data[CAPI_EXPONENT_1_OFFSET(modSize)]; - nsslibc_memcpy(target, exponent1->data, exponent1->size); - exponent1->data = target; - ckcapi_ReverseData(exponent1); + target = &keyBlobData->data[CAPI_EXPONENT_1_OFFSET(modSize)]; + nsslibc_memcpy(target, exponent1->data, exponent1->size); + exponent1->data = target; + ckcapi_ReverseData(exponent1); - target = &keyBlobData->data[CAPI_EXPONENT_2_OFFSET(modSize)]; - nsslibc_memcpy(target, exponent2->data, exponent2->size); - exponent2->data = target; - ckcapi_ReverseData(exponent2); + target = &keyBlobData->data[CAPI_EXPONENT_2_OFFSET(modSize)]; + nsslibc_memcpy(target, exponent2->data, exponent2->size); + exponent2->data = target; + ckcapi_ReverseData(exponent2); - target = &keyBlobData->data[CAPI_COEFFICIENT_OFFSET(modSize)]; - nsslibc_memcpy(target, coefficient->data, coefficient->size); - coefficient->data = target; - ckcapi_ReverseData(coefficient); + target = &keyBlobData->data[CAPI_COEFFICIENT_OFFSET(modSize)]; + nsslibc_memcpy(target, coefficient->data, coefficient->size); + coefficient->data = target; + ckcapi_ReverseData(coefficient); - keyBlob->data = keyBlobData; - keyBlob->size = dataSize; + keyBlob->data = keyBlobData; + keyBlob->size = dataSize; - return CKR_OK; + return CKR_OK; loser: - nss_ZFreeIf(keyBlobData); - return error; + nss_ZFreeIf(keyBlobData); + return error; } static ckcapiInternalObject * -nss_ckcapi_CreatePrivateKey -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckcapi_CreatePrivateKey( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSItem modulus; - NSSItem publicExponent; - NSSItem privateExponent; - NSSItem exponent1; - NSSItem exponent2; - NSSItem prime1; - NSSItem prime2; - NSSItem coefficient; - NSSItem keyID; - NSSItem keyBlob; - ckcapiInternalObject *io = NULL; - char *providerName = NULL; - char *containerName = NULL; - char *idData = NULL; - CRYPT_KEY_PROV_INFO provInfo; - CRYPT_HASH_BLOB msKeyID; - CK_KEY_TYPE keyType; - HCRYPTPROV hProv = 0; - HCRYPTKEY hKey = 0; - PRBool decrypt; - DWORD keySpec; - DWORD msError; - BOOL rc; + NSSItem modulus; + NSSItem publicExponent; + NSSItem privateExponent; + NSSItem exponent1; + NSSItem exponent2; + NSSItem prime1; + NSSItem prime2; + NSSItem coefficient; + NSSItem keyID; + NSSItem keyBlob; + ckcapiInternalObject *io = NULL; + char *providerName = NULL; + char *containerName = NULL; + char *idData = NULL; + CRYPT_KEY_PROV_INFO provInfo; + CRYPT_HASH_BLOB msKeyID; + CK_KEY_TYPE keyType; + HCRYPTPROV hProv = 0; + HCRYPTKEY hKey = 0; + PRBool decrypt; + DWORD keySpec; + DWORD msError; + BOOL rc; - keyType = nss_ckcapi_GetULongAttribute - (CKA_KEY_TYPE, pTemplate, ulAttributeCount, pError); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - if (CKK_RSA != keyType) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (ckcapiInternalObject *)NULL; - } + keyType = nss_ckcapi_GetULongAttribute(CKA_KEY_TYPE, pTemplate, ulAttributeCount, pError); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + if (CKK_RSA != keyType) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + return (ckcapiInternalObject *)NULL; + } - decrypt = nss_ckcapi_GetBoolAttribute(CKA_DECRYPT, - pTemplate, ulAttributeCount, pError); - if (CKR_TEMPLATE_INCOMPLETE == *pError) { - decrypt = PR_TRUE; /* default to true */ - } - decrypt = decrypt || nss_ckcapi_GetBoolAttribute(CKA_UNWRAP, - pTemplate, ulAttributeCount, pError); - if (CKR_TEMPLATE_INCOMPLETE == *pError) { - decrypt = PR_TRUE; /* default to true */ - } - keySpec = decrypt ? AT_KEYEXCHANGE : AT_SIGNATURE; + decrypt = nss_ckcapi_GetBoolAttribute(CKA_DECRYPT, + pTemplate, ulAttributeCount, pError); + if (CKR_TEMPLATE_INCOMPLETE == *pError) { + decrypt = PR_TRUE; /* default to true */ + } + decrypt = decrypt || nss_ckcapi_GetBoolAttribute(CKA_UNWRAP, + pTemplate, ulAttributeCount, pError); + if (CKR_TEMPLATE_INCOMPLETE == *pError) { + decrypt = PR_TRUE; /* default to true */ + } + keySpec = decrypt ? AT_KEYEXCHANGE : AT_SIGNATURE; - *pError = nss_ckcapi_GetAttribute(CKA_MODULUS, pTemplate, - ulAttributeCount, &modulus); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_PUBLIC_EXPONENT, pTemplate, - ulAttributeCount, &publicExponent); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_PRIVATE_EXPONENT, pTemplate, - ulAttributeCount, &privateExponent); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_PRIME_1, pTemplate, - ulAttributeCount, &prime1); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_PRIME_2, pTemplate, - ulAttributeCount, &prime2); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_EXPONENT_1, pTemplate, - ulAttributeCount, &exponent1); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_EXPONENT_2, pTemplate, - ulAttributeCount, &exponent2); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_COEFFICIENT, pTemplate, - ulAttributeCount, &coefficient); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - *pError = nss_ckcapi_GetAttribute(CKA_ID, pTemplate, - ulAttributeCount, &keyID); - if (CKR_OK != *pError) { - return (ckcapiInternalObject *)NULL; - } - providerName = ckcapi_getDefaultProvider(pError); - if ((char *)NULL == providerName ) { - return (ckcapiInternalObject *)NULL; - } - containerName = ckcapi_getContainer(pError, &keyID); - if ((char *)NULL == containerName) { - goto loser; - } - rc = CryptAcquireContext(&hProv, containerName, providerName, - PROV_RSA_FULL, CRYPT_NEWKEYSET); - if (!rc) { - msError = GetLastError(); - *pError = CKR_DEVICE_ERROR; - goto loser; - } + *pError = nss_ckcapi_GetAttribute(CKA_MODULUS, pTemplate, + ulAttributeCount, &modulus); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_PUBLIC_EXPONENT, pTemplate, + ulAttributeCount, &publicExponent); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_PRIVATE_EXPONENT, pTemplate, + ulAttributeCount, &privateExponent); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_PRIME_1, pTemplate, + ulAttributeCount, &prime1); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_PRIME_2, pTemplate, + ulAttributeCount, &prime2); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_EXPONENT_1, pTemplate, + ulAttributeCount, &exponent1); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_EXPONENT_2, pTemplate, + ulAttributeCount, &exponent2); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_COEFFICIENT, pTemplate, + ulAttributeCount, &coefficient); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + *pError = nss_ckcapi_GetAttribute(CKA_ID, pTemplate, + ulAttributeCount, &keyID); + if (CKR_OK != *pError) { + return (ckcapiInternalObject *)NULL; + } + providerName = ckcapi_getDefaultProvider(pError); + if ((char *)NULL == providerName) { + return (ckcapiInternalObject *)NULL; + } + containerName = ckcapi_getContainer(pError, &keyID); + if ((char *)NULL == containerName) { + goto loser; + } + rc = CryptAcquireContext(&hProv, containerName, providerName, + PROV_RSA_FULL, CRYPT_NEWKEYSET); + if (!rc) { + msError = GetLastError(); + *pError = CKR_DEVICE_ERROR; + goto loser; + } - *pError = ckcapi_buildPrivateKeyBlob( - &keyBlob, - &modulus, - &publicExponent, - &privateExponent, - &prime1, - &prime2, - &exponent1, - &exponent2, - &coefficient, - decrypt); - if (CKR_OK != *pError) { - goto loser; - } + *pError = ckcapi_buildPrivateKeyBlob( + &keyBlob, + &modulus, + &publicExponent, + &privateExponent, + &prime1, + &prime2, + &exponent1, + &exponent2, + &coefficient, + decrypt); + if (CKR_OK != *pError) { + goto loser; + } - rc = CryptImportKey(hProv, keyBlob.data, keyBlob.size, - 0, CRYPT_EXPORTABLE, &hKey); - if (!rc) { - msError = GetLastError(); - *pError = CKR_DEVICE_ERROR; - goto loser; - } + rc = CryptImportKey(hProv, keyBlob.data, keyBlob.size, + 0, CRYPT_EXPORTABLE, &hKey); + if (!rc) { + msError = GetLastError(); + *pError = CKR_DEVICE_ERROR; + goto loser; + } - idData = nss_ZNEWARRAY(NULL, char, keyID.size); - if ((void *)NULL == idData) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - nsslibc_memcpy(idData, keyID.data, keyID.size); + idData = nss_ZNEWARRAY(NULL, char, keyID.size); + if ((void *)NULL == idData) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + nsslibc_memcpy(idData, keyID.data, keyID.size); - provInfo.pwszContainerName = nss_ckcapi_UTF8ToWide(containerName); - provInfo.pwszProvName = nss_ckcapi_UTF8ToWide(providerName); - provInfo.dwProvType = PROV_RSA_FULL; - provInfo.dwFlags = 0; - provInfo.cProvParam = 0; - provInfo.rgProvParam = NULL; - provInfo.dwKeySpec = keySpec; + provInfo.pwszContainerName = nss_ckcapi_UTF8ToWide(containerName); + provInfo.pwszProvName = nss_ckcapi_UTF8ToWide(providerName); + provInfo.dwProvType = PROV_RSA_FULL; + provInfo.dwFlags = 0; + provInfo.cProvParam = 0; + provInfo.rgProvParam = NULL; + provInfo.dwKeySpec = keySpec; - msKeyID.cbData = keyID.size; - msKeyID.pbData = keyID.data; + msKeyID.cbData = keyID.size; + msKeyID.pbData = keyID.data; - rc = CryptSetKeyIdentifierProperty(&msKeyID, CERT_KEY_PROV_INFO_PROP_ID, - 0, NULL, NULL, &provInfo); - if (!rc) { - goto loser; - } + rc = CryptSetKeyIdentifierProperty(&msKeyID, CERT_KEY_PROV_INFO_PROP_ID, + 0, NULL, NULL, &provInfo); + if (!rc) { + goto loser; + } - /* handle error here */ - io = nss_ZNEW(NULL, ckcapiInternalObject); - if ((ckcapiInternalObject *)NULL == io) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - io->type = ckcapiBareKey; - io->objClass = CKO_PRIVATE_KEY; - io->u.key.provInfo = provInfo; - io->u.key.provName = providerName; - io->u.key.containerName = containerName; - io->u.key.hProv = hProv; /* save the handle */ - io->idData = idData; - io->id.data = idData; - io->id.size = keyID.size; - /* done with the key handle */ - CryptDestroyKey(hKey); - return io; + /* handle error here */ + io = nss_ZNEW(NULL, ckcapiInternalObject); + if ((ckcapiInternalObject *)NULL == io) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + io->type = ckcapiBareKey; + io->objClass = CKO_PRIVATE_KEY; + io->u.key.provInfo = provInfo; + io->u.key.provName = providerName; + io->u.key.containerName = containerName; + io->u.key.hProv = hProv; /* save the handle */ + io->idData = idData; + io->id.data = idData; + io->id.size = keyID.size; + /* done with the key handle */ + CryptDestroyKey(hKey); + return io; loser: - nss_ZFreeIf(containerName); - nss_ZFreeIf(providerName); - nss_ZFreeIf(idData); - if (0 != hProv) { - CryptReleaseContext(hProv, 0); - } - if (0 != hKey) { - CryptDestroyKey(hKey); - } - return (ckcapiInternalObject *)NULL; + nss_ZFreeIf(containerName); + nss_ZFreeIf(providerName); + nss_ZFreeIf(idData); + if (0 != hProv) { + CryptReleaseContext(hProv, 0); + } + if (0 != hKey) { + CryptDestroyKey(hKey); + } + return (ckcapiInternalObject *)NULL; } - NSS_EXTERN NSSCKMDObject * -nss_ckcapi_CreateObject -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckcapi_CreateObject( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - CK_OBJECT_CLASS objClass; - ckcapiInternalObject *io = NULL; - CK_BBOOL isToken; + CK_OBJECT_CLASS objClass; + ckcapiInternalObject *io = NULL; + CK_BBOOL isToken; - /* - * only create token objects - */ - isToken = nss_ckcapi_GetBoolAttribute(CKA_TOKEN, pTemplate, - ulAttributeCount, pError); - if (CKR_OK != *pError) { - return (NSSCKMDObject *) NULL; - } - if (!isToken) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (NSSCKMDObject *) NULL; - } + /* + * only create token objects + */ + isToken = nss_ckcapi_GetBoolAttribute(CKA_TOKEN, pTemplate, + ulAttributeCount, pError); + if (CKR_OK != *pError) { + return (NSSCKMDObject *)NULL; + } + if (!isToken) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + return (NSSCKMDObject *)NULL; + } - /* - * only create keys and certs. - */ - objClass = nss_ckcapi_GetULongAttribute(CKA_CLASS, pTemplate, - ulAttributeCount, pError); - if (CKR_OK != *pError) { - return (NSSCKMDObject *) NULL; - } + /* + * only create keys and certs. + */ + objClass = nss_ckcapi_GetULongAttribute(CKA_CLASS, pTemplate, + ulAttributeCount, pError); + if (CKR_OK != *pError) { + return (NSSCKMDObject *)NULL; + } #ifdef notdef - if (objClass == CKO_PUBLIC_KEY) { - return CKR_OK; /* fake public key creation, happens as a side effect of - * private key creation */ - } + if (objClass == CKO_PUBLIC_KEY) { + return CKR_OK; /* fake public key creation, happens as a side effect of + * private key creation */ + } #endif - if (objClass == CKO_CERTIFICATE) { - io = nss_ckcapi_CreateCertificate(fwSession, pTemplate, - ulAttributeCount, pError); - } else if (objClass == CKO_PRIVATE_KEY) { - io = nss_ckcapi_CreatePrivateKey(fwSession, pTemplate, - ulAttributeCount, pError); - } else { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - } + if (objClass == CKO_CERTIFICATE) { + io = nss_ckcapi_CreateCertificate(fwSession, pTemplate, + ulAttributeCount, pError); + } + else if (objClass == CKO_PRIVATE_KEY) { + io = nss_ckcapi_CreatePrivateKey(fwSession, pTemplate, + ulAttributeCount, pError); + } + else { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + } - if ((ckcapiInternalObject *)NULL == io) { - return (NSSCKMDObject *) NULL; - } - return nss_ckcapi_CreateMDObject(NULL, io, pError); + if ((ckcapiInternalObject *)NULL == io) { + return (NSSCKMDObject *)NULL; + } + return nss_ckcapi_CreateMDObject(NULL, io, pError); } diff --git a/security/nss/lib/ckfw/capi/constants.c b/security/nss/lib/ckfw/capi/constants.c index 9b919aa6d155..0d4b70110ecd 100644 --- a/security/nss/lib/ckfw/capi/constants.c +++ b/security/nss/lib/ckfw/capi/constants.c @@ -21,40 +21,43 @@ #endif /* NSSCAPI_H */ NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckcapi_CryptokiVersion = { - NSS_CKCAPI_CRYPTOKI_VERSION_MAJOR, - NSS_CKCAPI_CRYPTOKI_VERSION_MINOR }; + nss_ckcapi_CryptokiVersion = { + NSS_CKCAPI_CRYPTOKI_VERSION_MAJOR, + NSS_CKCAPI_CRYPTOKI_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckcapi_ManufacturerID = (NSSUTF8 *) "Mozilla Foundation"; + nss_ckcapi_ManufacturerID = (NSSUTF8 *)"Mozilla Foundation"; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckcapi_LibraryDescription = (NSSUTF8 *) "NSS Access to Microsoft Certificate Store"; + nss_ckcapi_LibraryDescription = (NSSUTF8 *)"NSS Access to Microsoft Certificate Store"; NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckcapi_LibraryVersion = { - NSS_CKCAPI_LIBRARY_VERSION_MAJOR, - NSS_CKCAPI_LIBRARY_VERSION_MINOR}; + nss_ckcapi_LibraryVersion = { + NSS_CKCAPI_LIBRARY_VERSION_MAJOR, + NSS_CKCAPI_LIBRARY_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckcapi_SlotDescription = (NSSUTF8 *) "Microsoft Certificate Store"; + nss_ckcapi_SlotDescription = (NSSUTF8 *)"Microsoft Certificate Store"; NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckcapi_HardwareVersion = { - NSS_CKCAPI_HARDWARE_VERSION_MAJOR, - NSS_CKCAPI_HARDWARE_VERSION_MINOR }; + nss_ckcapi_HardwareVersion = { + NSS_CKCAPI_HARDWARE_VERSION_MAJOR, + NSS_CKCAPI_HARDWARE_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckcapi_FirmwareVersion = { - NSS_CKCAPI_FIRMWARE_VERSION_MAJOR, - NSS_CKCAPI_FIRMWARE_VERSION_MINOR }; + nss_ckcapi_FirmwareVersion = { + NSS_CKCAPI_FIRMWARE_VERSION_MAJOR, + NSS_CKCAPI_FIRMWARE_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckcapi_TokenLabel = (NSSUTF8 *) "Microsoft Certificate Store"; + nss_ckcapi_TokenLabel = (NSSUTF8 *)"Microsoft Certificate Store"; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckcapi_TokenModel = (NSSUTF8 *) "1"; + nss_ckcapi_TokenModel = (NSSUTF8 *)"1"; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckcapi_TokenSerialNumber = (NSSUTF8 *) "1"; - + nss_ckcapi_TokenSerialNumber = (NSSUTF8 *)"1"; diff --git a/security/nss/lib/ckfw/capi/crsa.c b/security/nss/lib/ckfw/capi/crsa.c index 9acc7e78072d..62f90acb6a35 100644 --- a/security/nss/lib/ckfw/capi/crsa.c +++ b/security/nss/lib/ckfw/capi/crsa.c @@ -5,7 +5,7 @@ #include "ckcapi.h" #include "secdert.h" -#define SSL3_SHAMD5_HASH_SIZE 36 /* LEN_MD5 (16) + LEN_SHA1 (20) */ +#define SSL3_SHAMD5_HASH_SIZE 36 /* LEN_MD5 (16) + LEN_SHA1 (20) */ /* * ckcapi/crsa.c @@ -21,115 +21,109 @@ static char * putDecimalString(char *cstr, unsigned long value) { - unsigned long tenpower; - int first = 1; + unsigned long tenpower; + int first = 1; - for (tenpower=10000000; tenpower; tenpower /= 10) { - unsigned char digit = (unsigned char )(value/tenpower); - value = value % tenpower; + for (tenpower = 10000000; tenpower; tenpower /= 10) { + unsigned char digit = (unsigned char)(value / tenpower); + value = value % tenpower; - /* drop leading zeros */ - if (first && (0 == digit)) { - continue; + /* drop leading zeros */ + if (first && (0 == digit)) { + continue; + } + first = 0; + *cstr++ = digit + '0'; } - first = 0; - *cstr++ = digit + '0'; - } - /* if value was zero, put one of them out */ - if (first) { - *cstr++ = '0'; - } - return cstr; + /* if value was zero, put one of them out */ + if (first) { + *cstr++ = '0'; + } + return cstr; } - /* * Create a Capi OID string value from a DER OID */ static char * -nss_ckcapi_GetOidString -( - unsigned char *oidTag, - unsigned int oidTagSize, - CK_RV *pError -) +nss_ckcapi_GetOidString( + unsigned char *oidTag, + unsigned int oidTagSize, + CK_RV *pError) { - unsigned char *oid; - char *oidStr; - char *cstr; - unsigned long value; - unsigned int oidSize; + unsigned char *oid; + char *oidStr; + char *cstr; + unsigned long value; + unsigned int oidSize; - if (DER_OBJECT_ID != *oidTag) { - /* wasn't an oid */ - *pError = CKR_DATA_INVALID; - return NULL; - } - oid = nss_ckcapi_DERUnwrap(oidTag, oidTagSize, &oidSize, NULL); - - if (oidSize < 2) { - *pError = CKR_DATA_INVALID; - return NULL; - } - - oidStr = nss_ZNEWARRAY( NULL, char, oidSize*4 ); - if ((char *)NULL == oidStr) { - *pError = CKR_HOST_MEMORY; - return NULL; - } - cstr = oidStr; - cstr = putDecimalString(cstr, (*oid) / 40); - *cstr++ = '.'; - cstr = putDecimalString(cstr, (*oid) % 40); - oidSize--; - - value = 0; - while (oidSize--) { - oid++; - value = (value << 7) + (*oid & 0x7f); - if (0 == (*oid & 0x80)) { - *cstr++ = '.'; - cstr = putDecimalString(cstr, value); - value = 0; + if (DER_OBJECT_ID != *oidTag) { + /* wasn't an oid */ + *pError = CKR_DATA_INVALID; + return NULL; } - } + oid = nss_ckcapi_DERUnwrap(oidTag, oidTagSize, &oidSize, NULL); - *cstr = 0; /* NULL terminate */ + if (oidSize < 2) { + *pError = CKR_DATA_INVALID; + return NULL; + } - if (value != 0) { - nss_ZFreeIf(oidStr); - *pError = CKR_DATA_INVALID; - return NULL; - } - return oidStr; + oidStr = nss_ZNEWARRAY(NULL, char, oidSize * 4); + if ((char *)NULL == oidStr) { + *pError = CKR_HOST_MEMORY; + return NULL; + } + cstr = oidStr; + cstr = putDecimalString(cstr, (*oid) / 40); + *cstr++ = '.'; + cstr = putDecimalString(cstr, (*oid) % 40); + oidSize--; + + value = 0; + while (oidSize--) { + oid++; + value = (value << 7) + (*oid & 0x7f); + if (0 == (*oid & 0x80)) { + *cstr++ = '.'; + cstr = putDecimalString(cstr, value); + value = 0; + } + } + + *cstr = 0; /* NULL terminate */ + + if (value != 0) { + nss_ZFreeIf(oidStr); + *pError = CKR_DATA_INVALID; + return NULL; + } + return oidStr; } - /* - * PKCS #11 sign for RSA expects to take a fully DER-encoded hash value, - * which includes the hash OID. CAPI expects to take a Hash Context. While - * CAPI does have the capability of setting a raw hash value, it does not + * PKCS #11 sign for RSA expects to take a fully DER-encoded hash value, + * which includes the hash OID. CAPI expects to take a Hash Context. While + * CAPI does have the capability of setting a raw hash value, it does not * have the ability to sign an arbitrary value. This function tries to * reduce the passed in data into something that CAPI could actually sign. */ static CK_RV -ckcapi_GetRawHash -( - const NSSItem *input, - NSSItem *hash, - ALG_ID *hashAlg -) +ckcapi_GetRawHash( + const NSSItem *input, + NSSItem *hash, + ALG_ID *hashAlg) { - unsigned char *current; - unsigned char *algid; - unsigned char *oid; - unsigned char *hashData; - char *oidStr; - CK_RV error; - unsigned int oidSize; - unsigned int size; - /* + unsigned char *current; + unsigned char *algid; + unsigned char *oid; + unsigned char *hashData; + char *oidStr; + CK_RV error; + unsigned int oidSize; + unsigned int size; + /* * there are 2 types of hashes NSS typically tries to sign, regular * RSA signature format (with encoded DER_OIDS), and SSL3 Signed hashes. * CAPI knows not to add any oids to SSL3_Signed hashes, so if we have any @@ -138,73 +132,73 @@ ckcapi_GetRawHash * is really a combined hash or some other arbitrary data, so it's safe to * handle this case first. */ - if (SSL3_SHAMD5_HASH_SIZE == input->size) { - hash->data = input->data; - hash->size = input->size; - *hashAlg = CALG_SSL3_SHAMD5; + if (SSL3_SHAMD5_HASH_SIZE == input->size) { + hash->data = input->data; + hash->size = input->size; + *hashAlg = CALG_SSL3_SHAMD5; + return CKR_OK; + } + + current = (unsigned char *)input->data; + + /* make sure we have a sequence tag */ + if ((DER_SEQUENCE | DER_CONSTRUCTED) != *current) { + return CKR_DATA_INVALID; + } + + /* parse the input block to get 1) the hash oid, and 2) the raw hash value. + * unfortunatly CAPI doesn't have a builtin function to do this work, so + * we go ahead and do it by hand here. + * + * format is: + * SEQUENCE { + * SECQUENCE { // algid + * OID {} // oid + * ANY {} // optional params + * } + * OCTECT {} // hash + */ + + /* unwrap */ + algid = nss_ckcapi_DERUnwrap(current, input->size, &size, NULL); + + if (algid + size != current + input->size) { + /* make sure there is not extra data at the end */ + return CKR_DATA_INVALID; + } + + if ((DER_SEQUENCE | DER_CONSTRUCTED) != *algid) { + /* wasn't an algid */ + return CKR_DATA_INVALID; + } + oid = nss_ckcapi_DERUnwrap(algid, size, &oidSize, &hashData); + + if (DER_OCTET_STRING != *hashData) { + /* wasn't a hash */ + return CKR_DATA_INVALID; + } + + /* get the real hash */ + current = hashData; + size = size - (hashData - algid); + hash->data = nss_ckcapi_DERUnwrap(current, size, &hash->size, NULL); + + /* get the real oid as a string. Again, Microsoft does not + * export anything that does this for us */ + oidStr = nss_ckcapi_GetOidString(oid, oidSize, &error); + if ((char *)NULL == oidStr) { + return error; + } + + /* look up the hash alg from the oid (fortunately CAPI does to this) */ + *hashAlg = CertOIDToAlgId(oidStr); + nss_ZFreeIf(oidStr); + if (0 == *hashAlg) { + return CKR_HOST_MEMORY; + } + + /* hash looks reasonably consistent, we should be able to sign it now */ return CKR_OK; - } - - current = (unsigned char *)input->data; - - /* make sure we have a sequence tag */ - if ((DER_SEQUENCE|DER_CONSTRUCTED) != *current) { - return CKR_DATA_INVALID; - } - - /* parse the input block to get 1) the hash oid, and 2) the raw hash value. - * unfortunatly CAPI doesn't have a builtin function to do this work, so - * we go ahead and do it by hand here. - * - * format is: - * SEQUENCE { - * SECQUENCE { // algid - * OID {} // oid - * ANY {} // optional params - * } - * OCTECT {} // hash - */ - - /* unwrap */ - algid = nss_ckcapi_DERUnwrap(current,input->size, &size, NULL); - - if (algid+size != current+input->size) { - /* make sure there is not extra data at the end */ - return CKR_DATA_INVALID; - } - - if ((DER_SEQUENCE|DER_CONSTRUCTED) != *algid) { - /* wasn't an algid */ - return CKR_DATA_INVALID; - } - oid = nss_ckcapi_DERUnwrap(algid, size, &oidSize, &hashData); - - if (DER_OCTET_STRING != *hashData) { - /* wasn't a hash */ - return CKR_DATA_INVALID; - } - - /* get the real hash */ - current = hashData; - size = size - (hashData-algid); - hash->data = nss_ckcapi_DERUnwrap(current, size, &hash->size, NULL); - - /* get the real oid as a string. Again, Microsoft does not - * export anything that does this for us */ - oidStr = nss_ckcapi_GetOidString(oid, oidSize, &error); - if ((char *)NULL == oidStr ) { - return error; - } - - /* look up the hash alg from the oid (fortunately CAPI does to this) */ - *hashAlg = CertOIDToAlgId(oidStr); - nss_ZFreeIf(oidStr); - if (0 == *hashAlg) { - return CKR_HOST_MEMORY; - } - - /* hash looks reasonably consistent, we should be able to sign it now */ - return CKR_OK; } /* @@ -214,133 +208,125 @@ ckcapi_GetRawHash void ckcapi_ReverseData(NSSItem *item) { - int end = (item->size)-1; - int middle = (item->size)/2; - unsigned char *buf = item->data; - int i; + int end = (item->size) - 1; + int middle = (item->size) / 2; + unsigned char *buf = item->data; + int i; - for (i=0; i < middle; i++) { - unsigned char tmp = buf[i]; - buf[i] = buf[end-i]; - buf[end-i] = tmp; - } - return; + for (i = 0; i < middle; i++) { + unsigned char tmp = buf[i]; + buf[i] = buf[end - i]; + buf[end - i] = tmp; + } + return; } -typedef struct ckcapiInternalCryptoOperationRSAPrivStr - ckcapiInternalCryptoOperationRSAPriv; -struct ckcapiInternalCryptoOperationRSAPrivStr -{ - NSSCKMDCryptoOperation mdOperation; - NSSCKMDMechanism *mdMechanism; - ckcapiInternalObject *iKey; - HCRYPTPROV hProv; - DWORD keySpec; - HCRYPTKEY hKey; - NSSItem *buffer; +typedef struct ckcapiInternalCryptoOperationRSAPrivStr + ckcapiInternalCryptoOperationRSAPriv; +struct ckcapiInternalCryptoOperationRSAPrivStr { + NSSCKMDCryptoOperation mdOperation; + NSSCKMDMechanism *mdMechanism; + ckcapiInternalObject *iKey; + HCRYPTPROV hProv; + DWORD keySpec; + HCRYPTKEY hKey; + NSSItem *buffer; }; /* * ckcapi_mdCryptoOperationRSAPriv_Create */ static NSSCKMDCryptoOperation * -ckcapi_mdCryptoOperationRSAPriv_Create -( - const NSSCKMDCryptoOperation *proto, - NSSCKMDMechanism *mdMechanism, - NSSCKMDObject *mdKey, - CK_RV *pError -) +ckcapi_mdCryptoOperationRSAPriv_Create( + const NSSCKMDCryptoOperation *proto, + NSSCKMDMechanism *mdMechanism, + NSSCKMDObject *mdKey, + CK_RV *pError) { - ckcapiInternalObject *iKey = (ckcapiInternalObject *)mdKey->etc; - const NSSItem *classItem = nss_ckcapi_FetchAttribute(iKey, CKA_CLASS); - const NSSItem *keyType = nss_ckcapi_FetchAttribute(iKey, CKA_KEY_TYPE); - ckcapiInternalCryptoOperationRSAPriv *iOperation; - CK_RV error; - HCRYPTPROV hProv; - DWORD keySpec; - HCRYPTKEY hKey; + ckcapiInternalObject *iKey = (ckcapiInternalObject *)mdKey->etc; + const NSSItem *classItem = nss_ckcapi_FetchAttribute(iKey, CKA_CLASS); + const NSSItem *keyType = nss_ckcapi_FetchAttribute(iKey, CKA_KEY_TYPE); + ckcapiInternalCryptoOperationRSAPriv *iOperation; + CK_RV error; + HCRYPTPROV hProv; + DWORD keySpec; + HCRYPTKEY hKey; - /* make sure we have the right objects */ - if (((const NSSItem *)NULL == classItem) || - (sizeof(CK_OBJECT_CLASS) != classItem->size) || - (CKO_PRIVATE_KEY != *(CK_OBJECT_CLASS *)classItem->data) || - ((const NSSItem *)NULL == keyType) || - (sizeof(CK_KEY_TYPE) != keyType->size) || - (CKK_RSA != *(CK_KEY_TYPE *)keyType->data)) { - *pError = CKR_KEY_TYPE_INCONSISTENT; - return (NSSCKMDCryptoOperation *)NULL; - } + /* make sure we have the right objects */ + if (((const NSSItem *)NULL == classItem) || + (sizeof(CK_OBJECT_CLASS) != classItem->size) || + (CKO_PRIVATE_KEY != *(CK_OBJECT_CLASS *)classItem->data) || + ((const NSSItem *)NULL == keyType) || + (sizeof(CK_KEY_TYPE) != keyType->size) || + (CKK_RSA != *(CK_KEY_TYPE *)keyType->data)) { + *pError = CKR_KEY_TYPE_INCONSISTENT; + return (NSSCKMDCryptoOperation *)NULL; + } - error = nss_ckcapi_FetchKeyContainer(iKey, &hProv, &keySpec, &hKey); - if (error != CKR_OK) { - *pError = error; - return (NSSCKMDCryptoOperation *)NULL; - } + error = nss_ckcapi_FetchKeyContainer(iKey, &hProv, &keySpec, &hKey); + if (error != CKR_OK) { + *pError = error; + return (NSSCKMDCryptoOperation *)NULL; + } - iOperation = nss_ZNEW(NULL, ckcapiInternalCryptoOperationRSAPriv); - if ((ckcapiInternalCryptoOperationRSAPriv *)NULL == iOperation) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDCryptoOperation *)NULL; - } - iOperation->mdMechanism = mdMechanism; - iOperation->iKey = iKey; - iOperation->hProv = hProv; - iOperation->keySpec = keySpec; - iOperation->hKey = hKey; + iOperation = nss_ZNEW(NULL, ckcapiInternalCryptoOperationRSAPriv); + if ((ckcapiInternalCryptoOperationRSAPriv *)NULL == iOperation) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDCryptoOperation *)NULL; + } + iOperation->mdMechanism = mdMechanism; + iOperation->iKey = iKey; + iOperation->hProv = hProv; + iOperation->keySpec = keySpec; + iOperation->hKey = hKey; - nsslibc_memcpy(&iOperation->mdOperation, - proto, sizeof(NSSCKMDCryptoOperation)); - iOperation->mdOperation.etc = iOperation; + nsslibc_memcpy(&iOperation->mdOperation, + proto, sizeof(NSSCKMDCryptoOperation)); + iOperation->mdOperation.etc = iOperation; - return &iOperation->mdOperation; + return &iOperation->mdOperation; } static CK_RV -ckcapi_mdCryptoOperationRSAPriv_Destroy -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdCryptoOperationRSAPriv_Destroy( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - ckcapiInternalCryptoOperationRSAPriv *iOperation = - (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; + ckcapiInternalCryptoOperationRSAPriv *iOperation = + (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; - if (iOperation->hKey) { - CryptDestroyKey(iOperation->hKey); - } - if (iOperation->buffer) { - nssItem_Destroy(iOperation->buffer); - } - nss_ZFreeIf(iOperation); - return CKR_OK; + if (iOperation->hKey) { + CryptDestroyKey(iOperation->hKey); + } + if (iOperation->buffer) { + nssItem_Destroy(iOperation->buffer); + } + nss_ZFreeIf(iOperation); + return CKR_OK; } static CK_ULONG -ckcapi_mdCryptoOperationRSA_GetFinalLength -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdCryptoOperationRSA_GetFinalLength( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - ckcapiInternalCryptoOperationRSAPriv *iOperation = - (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; - const NSSItem *modulus = - nss_ckcapi_FetchAttribute(iOperation->iKey, CKA_MODULUS); + ckcapiInternalCryptoOperationRSAPriv *iOperation = + (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; + const NSSItem *modulus = + nss_ckcapi_FetchAttribute(iOperation->iKey, CKA_MODULUS); - return modulus->size; + return modulus->size; } - /* * ckcapi_mdCryptoOperationRSADecrypt_GetOperationLength * we won't know the length until we actually decrypt the @@ -348,86 +334,85 @@ ckcapi_mdCryptoOperationRSA_GetFinalLength * the block, we'll save if for when the block is asked for */ static CK_ULONG -ckcapi_mdCryptoOperationRSADecrypt_GetOperationLength -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *input, - CK_RV *pError -) +ckcapi_mdCryptoOperationRSADecrypt_GetOperationLength( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *input, + CK_RV *pError) { - ckcapiInternalCryptoOperationRSAPriv *iOperation = - (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; - BOOL rc; + ckcapiInternalCryptoOperationRSAPriv *iOperation = + (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; + BOOL rc; - /* Microsoft's Decrypt operation works in place. Since we don't want - * to trash our input buffer, we make a copy of it */ - iOperation->buffer = nssItem_Duplicate((NSSItem *)input, NULL, NULL); - if ((NSSItem *) NULL == iOperation->buffer) { - *pError = CKR_HOST_MEMORY; - return 0; - } - /* Sigh, reverse it */ - ckcapi_ReverseData(iOperation->buffer); - - rc = CryptDecrypt(iOperation->hKey, 0, TRUE, 0, - iOperation->buffer->data, &iOperation->buffer->size); - if (!rc) { - DWORD msError = GetLastError(); - switch (msError) { - case NTE_BAD_DATA: - *pError = CKR_ENCRYPTED_DATA_INVALID; - break; - case NTE_FAIL: - case NTE_BAD_UID: - *pError = CKR_DEVICE_ERROR; - break; - default: - *pError = CKR_GENERAL_ERROR; + /* Microsoft's Decrypt operation works in place. Since we don't want + * to trash our input buffer, we make a copy of it */ + iOperation->buffer = nssItem_Duplicate((NSSItem *)input, NULL, NULL); + if ((NSSItem *)NULL == iOperation->buffer) { + *pError = CKR_HOST_MEMORY; + return 0; } - return 0; - } + /* Sigh, reverse it */ + ckcapi_ReverseData(iOperation->buffer); - return iOperation->buffer->size; + rc = CryptDecrypt(iOperation->hKey, 0, TRUE, 0, + iOperation->buffer->data, &iOperation->buffer->size); + if (!rc) { + DWORD msError = GetLastError(); + switch (msError) { + case NTE_BAD_DATA: + *pError = + CKR_ENCRYPTED_DATA_INVALID; + break; + case NTE_FAIL: + case NTE_BAD_UID: + *pError = + CKR_DEVICE_ERROR; + break; + default: + *pError = + CKR_GENERAL_ERROR; + } + return 0; + } + + return iOperation->buffer->size; } /* * ckcapi_mdCryptoOperationRSADecrypt_UpdateFinal * - * NOTE: ckcapi_mdCryptoOperationRSADecrypt_GetOperationLength is presumed to + * NOTE: ckcapi_mdCryptoOperationRSADecrypt_GetOperationLength is presumed to * have been called previously. */ static CK_RV -ckcapi_mdCryptoOperationRSADecrypt_UpdateFinal -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *input, - NSSItem *output -) +ckcapi_mdCryptoOperationRSADecrypt_UpdateFinal( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *input, + NSSItem *output) { - ckcapiInternalCryptoOperationRSAPriv *iOperation = - (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; - NSSItem *buffer = iOperation->buffer; + ckcapiInternalCryptoOperationRSAPriv *iOperation = + (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; + NSSItem *buffer = iOperation->buffer; - if ((NSSItem *)NULL == buffer) { - return CKR_GENERAL_ERROR; - } - nsslibc_memcpy(output->data, buffer->data, buffer->size); - output->size = buffer->size; - return CKR_OK; + if ((NSSItem *)NULL == buffer) { + return CKR_GENERAL_ERROR; + } + nsslibc_memcpy(output->data, buffer->data, buffer->size); + output->size = buffer->size; + return CKR_OK; } /* @@ -435,277 +420,268 @@ ckcapi_mdCryptoOperationRSADecrypt_UpdateFinal * */ static CK_RV -ckcapi_mdCryptoOperationRSASign_UpdateFinal -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *input, - NSSItem *output -) +ckcapi_mdCryptoOperationRSASign_UpdateFinal( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *input, + NSSItem *output) { - ckcapiInternalCryptoOperationRSAPriv *iOperation = - (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; - CK_RV error = CKR_OK; - DWORD msError; - NSSItem hash; - HCRYPTHASH hHash = 0; - ALG_ID hashAlg; - DWORD hashSize; - DWORD len; /* temp length value we throw away */ - BOOL rc; + ckcapiInternalCryptoOperationRSAPriv *iOperation = + (ckcapiInternalCryptoOperationRSAPriv *)mdOperation->etc; + CK_RV error = CKR_OK; + DWORD msError; + NSSItem hash; + HCRYPTHASH hHash = 0; + ALG_ID hashAlg; + DWORD hashSize; + DWORD len; /* temp length value we throw away */ + BOOL rc; - /* - * PKCS #11 sign for RSA expects to take a fully DER-encoded hash value, - * which includes the hash OID. CAPI expects to take a Hash Context. While - * CAPI does have the capability of setting a raw hash value, it does not - * have the ability to sign an arbitrary value. This function tries to - * reduce the passed in data into something that CAPI could actually sign. - */ - error = ckcapi_GetRawHash(input, &hash, &hashAlg); - if (CKR_OK != error) { - goto loser; - } + /* + * PKCS #11 sign for RSA expects to take a fully DER-encoded hash value, + * which includes the hash OID. CAPI expects to take a Hash Context. While + * CAPI does have the capability of setting a raw hash value, it does not + * have the ability to sign an arbitrary value. This function tries to + * reduce the passed in data into something that CAPI could actually sign. + */ + error = ckcapi_GetRawHash(input, &hash, &hashAlg); + if (CKR_OK != error) { + goto loser; + } - rc = CryptCreateHash(iOperation->hProv, hashAlg, 0, 0, &hHash); - if (!rc) { - goto loser; - } + rc = CryptCreateHash(iOperation->hProv, hashAlg, 0, 0, &hHash); + if (!rc) { + goto loser; + } - /* make sure the hash lens match before we set it */ - len = sizeof(DWORD); - rc = CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&hashSize, &len, 0); - if (!rc) { - goto loser; - } + /* make sure the hash lens match before we set it */ + len = sizeof(DWORD); + rc = CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&hashSize, &len, 0); + if (!rc) { + goto loser; + } - if (hash.size != hashSize) { - /* The input must have been bad for this to happen */ - error = CKR_DATA_INVALID; - goto loser; - } + if (hash.size != hashSize) { + /* The input must have been bad for this to happen */ + error = CKR_DATA_INVALID; + goto loser; + } - /* we have an explicit hash, set it, note that the length is - * implicit by the hashAlg used in create */ - rc = CryptSetHashParam(hHash, HP_HASHVAL, hash.data, 0); - if (!rc) { - goto loser; - } + /* we have an explicit hash, set it, note that the length is + * implicit by the hashAlg used in create */ + rc = CryptSetHashParam(hHash, HP_HASHVAL, hash.data, 0); + if (!rc) { + goto loser; + } - /* OK, we have the data in a hash structure, sign it! */ - rc = CryptSignHash(hHash, iOperation->keySpec, NULL, 0, - output->data, &output->size); - if (!rc) { - goto loser; - } + /* OK, we have the data in a hash structure, sign it! */ + rc = CryptSignHash(hHash, iOperation->keySpec, NULL, 0, + output->data, &output->size); + if (!rc) { + goto loser; + } - /* Don't return a signature that might have been broken because of a cosmic - * ray, or a broken processor, verify that it is valid... */ - rc = CryptVerifySignature(hHash, output->data, output->size, - iOperation->hKey, NULL, 0); - if (!rc) { - goto loser; - } + /* Don't return a signature that might have been broken because of a cosmic + * ray, or a broken processor, verify that it is valid... */ + rc = CryptVerifySignature(hHash, output->data, output->size, + iOperation->hKey, NULL, 0); + if (!rc) { + goto loser; + } - /* OK, Microsoft likes to do things completely differently than anyone - * else. We need to reverse the data we received here */ - ckcapi_ReverseData(output); - CryptDestroyHash(hHash); - return CKR_OK; + /* OK, Microsoft likes to do things completely differently than anyone + * else. We need to reverse the data we received here */ + ckcapi_ReverseData(output); + CryptDestroyHash(hHash); + return CKR_OK; loser: - /* map the microsoft error */ - if (CKR_OK == error) { - msError = GetLastError(); - switch (msError) { - case ERROR_NOT_ENOUGH_MEMORY: - error = CKR_HOST_MEMORY; - break; - case NTE_NO_MEMORY: - error = CKR_DEVICE_MEMORY; - break; - case ERROR_MORE_DATA: - return CKR_BUFFER_TOO_SMALL; - case ERROR_INVALID_PARAMETER: /* these params were derived from the */ - case ERROR_INVALID_HANDLE: /* inputs, so if they are bad, the input */ - case NTE_BAD_ALGID: /* data is bad */ - case NTE_BAD_HASH: - error = CKR_DATA_INVALID; - break; - case ERROR_BUSY: - case NTE_FAIL: - case NTE_BAD_UID: - error = CKR_DEVICE_ERROR; - break; - default: - error = CKR_GENERAL_ERROR; - break; + /* map the microsoft error */ + if (CKR_OK == error) { + msError = GetLastError(); + switch (msError) { + case ERROR_NOT_ENOUGH_MEMORY: + error = + CKR_HOST_MEMORY; + break; + case NTE_NO_MEMORY: + error = + CKR_DEVICE_MEMORY; + break; + case ERROR_MORE_DATA: + return CKR_BUFFER_TOO_SMALL; + case ERROR_INVALID_PARAMETER: /* these params were derived from the */ + case ERROR_INVALID_HANDLE: /* inputs, so if they are bad, the input */ + case NTE_BAD_ALGID: /* data is bad */ + case NTE_BAD_HASH: + error = + CKR_DATA_INVALID; + break; + case ERROR_BUSY: + case NTE_FAIL: + case NTE_BAD_UID: + error = + CKR_DEVICE_ERROR; + break; + default: + error = + CKR_GENERAL_ERROR; + break; + } } - } - if (hHash) { - CryptDestroyHash(hHash); - } - return error; + if (hHash) { + CryptDestroyHash(hHash); + } + return error; } - NSS_IMPLEMENT_DATA const NSSCKMDCryptoOperation -ckcapi_mdCryptoOperationRSADecrypt_proto = { - NULL, /* etc */ - ckcapi_mdCryptoOperationRSAPriv_Destroy, - NULL, /* GetFinalLengh - not needed for one shot Decrypt/Encrypt */ - ckcapi_mdCryptoOperationRSADecrypt_GetOperationLength, - NULL, /* Final - not needed for one shot operation */ - NULL, /* Update - not needed for one shot operation */ - NULL, /* DigetUpdate - not needed for one shot operation */ - ckcapi_mdCryptoOperationRSADecrypt_UpdateFinal, - NULL, /* UpdateCombo - not needed for one shot operation */ - NULL, /* DigetKey - not needed for one shot operation */ - (void *)NULL /* null terminator */ -}; + ckcapi_mdCryptoOperationRSADecrypt_proto = { + NULL, /* etc */ + ckcapi_mdCryptoOperationRSAPriv_Destroy, + NULL, /* GetFinalLengh - not needed for one shot Decrypt/Encrypt */ + ckcapi_mdCryptoOperationRSADecrypt_GetOperationLength, + NULL, /* Final - not needed for one shot operation */ + NULL, /* Update - not needed for one shot operation */ + NULL, /* DigetUpdate - not needed for one shot operation */ + ckcapi_mdCryptoOperationRSADecrypt_UpdateFinal, + NULL, /* UpdateCombo - not needed for one shot operation */ + NULL, /* DigetKey - not needed for one shot operation */ + (void *)NULL /* null terminator */ + }; NSS_IMPLEMENT_DATA const NSSCKMDCryptoOperation -ckcapi_mdCryptoOperationRSASign_proto = { - NULL, /* etc */ - ckcapi_mdCryptoOperationRSAPriv_Destroy, - ckcapi_mdCryptoOperationRSA_GetFinalLength, - NULL, /* GetOperationLengh - not needed for one shot Sign/Verify */ - NULL, /* Final - not needed for one shot operation */ - NULL, /* Update - not needed for one shot operation */ - NULL, /* DigetUpdate - not needed for one shot operation */ - ckcapi_mdCryptoOperationRSASign_UpdateFinal, - NULL, /* UpdateCombo - not needed for one shot operation */ - NULL, /* DigetKey - not needed for one shot operation */ - (void *)NULL /* null terminator */ -}; + ckcapi_mdCryptoOperationRSASign_proto = { + NULL, /* etc */ + ckcapi_mdCryptoOperationRSAPriv_Destroy, + ckcapi_mdCryptoOperationRSA_GetFinalLength, + NULL, /* GetOperationLengh - not needed for one shot Sign/Verify */ + NULL, /* Final - not needed for one shot operation */ + NULL, /* Update - not needed for one shot operation */ + NULL, /* DigetUpdate - not needed for one shot operation */ + ckcapi_mdCryptoOperationRSASign_UpdateFinal, + NULL, /* UpdateCombo - not needed for one shot operation */ + NULL, /* DigetKey - not needed for one shot operation */ + (void *)NULL /* null terminator */ + }; /********** NSSCKMDMechansim functions ***********************/ /* * ckcapi_mdMechanismRSA_Destroy */ static void -ckcapi_mdMechanismRSA_Destroy -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdMechanismRSA_Destroy( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_ZFreeIf(fwMechanism); + nss_ZFreeIf(fwMechanism); } /* * ckcapi_mdMechanismRSA_GetMinKeySize */ static CK_ULONG -ckcapi_mdMechanismRSA_GetMinKeySize -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdMechanismRSA_GetMinKeySize( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return 384; + return 384; } /* * ckcapi_mdMechanismRSA_GetMaxKeySize */ static CK_ULONG -ckcapi_mdMechanismRSA_GetMaxKeySize -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdMechanismRSA_GetMaxKeySize( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return 16384; + return 16384; } /* * ckcapi_mdMechanismRSA_DecryptInit */ -static NSSCKMDCryptoOperation * -ckcapi_mdMechanismRSA_DecryptInit -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError -) +static NSSCKMDCryptoOperation * +ckcapi_mdMechanismRSA_DecryptInit( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError) { - return ckcapi_mdCryptoOperationRSAPriv_Create( - &ckcapi_mdCryptoOperationRSADecrypt_proto, - mdMechanism, mdKey, pError); + return ckcapi_mdCryptoOperationRSAPriv_Create( + &ckcapi_mdCryptoOperationRSADecrypt_proto, + mdMechanism, mdKey, pError); } /* * ckcapi_mdMechanismRSA_SignInit */ -static NSSCKMDCryptoOperation * -ckcapi_mdMechanismRSA_SignInit -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError -) +static NSSCKMDCryptoOperation * +ckcapi_mdMechanismRSA_SignInit( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError) { - return ckcapi_mdCryptoOperationRSAPriv_Create( - &ckcapi_mdCryptoOperationRSASign_proto, - mdMechanism, mdKey, pError); + return ckcapi_mdCryptoOperationRSAPriv_Create( + &ckcapi_mdCryptoOperationRSASign_proto, + mdMechanism, mdKey, pError); } - NSS_IMPLEMENT_DATA const NSSCKMDMechanism -nss_ckcapi_mdMechanismRSA = { - (void *)NULL, /* etc */ - ckcapi_mdMechanismRSA_Destroy, - ckcapi_mdMechanismRSA_GetMinKeySize, - ckcapi_mdMechanismRSA_GetMaxKeySize, - NULL, /* GetInHardware - default false */ - NULL, /* EncryptInit - default errs */ - ckcapi_mdMechanismRSA_DecryptInit, - NULL, /* DigestInit - default errs*/ - ckcapi_mdMechanismRSA_SignInit, - NULL, /* VerifyInit - default errs */ - ckcapi_mdMechanismRSA_SignInit, /* SignRecoverInit */ - NULL, /* VerifyRecoverInit - default errs */ - NULL, /* GenerateKey - default errs */ - NULL, /* GenerateKeyPair - default errs */ - NULL, /* GetWrapKeyLength - default errs */ - NULL, /* WrapKey - default errs */ - NULL, /* UnwrapKey - default errs */ - NULL, /* DeriveKey - default errs */ - (void *)NULL /* null terminator */ -}; + nss_ckcapi_mdMechanismRSA = { + (void *)NULL, /* etc */ + ckcapi_mdMechanismRSA_Destroy, + ckcapi_mdMechanismRSA_GetMinKeySize, + ckcapi_mdMechanismRSA_GetMaxKeySize, + NULL, /* GetInHardware - default false */ + NULL, /* EncryptInit - default errs */ + ckcapi_mdMechanismRSA_DecryptInit, + NULL, /* DigestInit - default errs*/ + ckcapi_mdMechanismRSA_SignInit, + NULL, /* VerifyInit - default errs */ + ckcapi_mdMechanismRSA_SignInit, /* SignRecoverInit */ + NULL, /* VerifyRecoverInit - default errs */ + NULL, /* GenerateKey - default errs */ + NULL, /* GenerateKeyPair - default errs */ + NULL, /* GetWrapKeyLength - default errs */ + NULL, /* WrapKey - default errs */ + NULL, /* UnwrapKey - default errs */ + NULL, /* DeriveKey - default errs */ + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/capi/csession.c b/security/nss/lib/ckfw/capi/csession.c index 4c253541df94..5b268ead1ecf 100644 --- a/security/nss/lib/ckfw/capi/csession.c +++ b/security/nss/lib/ckfw/capi/csession.c @@ -7,87 +7,81 @@ /* * ckcapi/csession.c * - * This file implements the NSSCKMDSession object for the + * This file implements the NSSCKMDSession object for the * "nss to capi" cryptoki module. */ static NSSCKMDFindObjects * -ckcapi_mdSession_FindObjectsInit -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +ckcapi_mdSession_FindObjectsInit( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - return nss_ckcapi_FindObjectsInit(fwSession, pTemplate, ulAttributeCount, pError); + return nss_ckcapi_FindObjectsInit(fwSession, pTemplate, ulAttributeCount, pError); } static NSSCKMDObject * -ckcapi_mdSession_CreateObject -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +ckcapi_mdSession_CreateObject( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - return nss_ckcapi_CreateObject(fwSession, pTemplate, ulAttributeCount, pError); + return nss_ckcapi_CreateObject(fwSession, pTemplate, ulAttributeCount, pError); } NSS_IMPLEMENT NSSCKMDSession * -nss_ckcapi_CreateSession -( - NSSCKFWSession *fwSession, - CK_RV *pError -) +nss_ckcapi_CreateSession( + NSSCKFWSession *fwSession, + CK_RV *pError) { - NSSArena *arena; - NSSCKMDSession *rv; + NSSArena *arena; + NSSCKMDSession *rv; - arena = NSSCKFWSession_GetArena(fwSession, pError); - if( (NSSArena *)NULL == arena ) { - return (NSSCKMDSession *)NULL; - } + arena = NSSCKFWSession_GetArena(fwSession, pError); + if ((NSSArena *)NULL == arena) { + return (NSSCKMDSession *)NULL; + } - rv = nss_ZNEW(arena, NSSCKMDSession); - if( (NSSCKMDSession *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDSession *)NULL; - } + rv = nss_ZNEW(arena, NSSCKMDSession); + if ((NSSCKMDSession *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDSession *)NULL; + } - /* - * rv was zeroed when allocated, so we only - * need to set the non-zero members. - */ + /* + * rv was zeroed when allocated, so we only + * need to set the non-zero members. + */ - rv->etc = (void *)fwSession; - /* rv->Close */ - /* rv->GetDeviceError */ - /* rv->Login */ - /* rv->Logout */ - /* rv->InitPIN */ - /* rv->SetPIN */ - /* rv->GetOperationStateLen */ - /* rv->GetOperationState */ - /* rv->SetOperationState */ - rv->CreateObject = ckcapi_mdSession_CreateObject; - /* rv->CopyObject */ - rv->FindObjectsInit = ckcapi_mdSession_FindObjectsInit; - /* rv->SeedRandom */ - /* rv->GetRandom */ - /* rv->null */ + rv->etc = (void *)fwSession; + /* rv->Close */ + /* rv->GetDeviceError */ + /* rv->Login */ + /* rv->Logout */ + /* rv->InitPIN */ + /* rv->SetPIN */ + /* rv->GetOperationStateLen */ + /* rv->GetOperationState */ + /* rv->SetOperationState */ + rv->CreateObject = ckcapi_mdSession_CreateObject; + /* rv->CopyObject */ + rv->FindObjectsInit = ckcapi_mdSession_FindObjectsInit; + /* rv->SeedRandom */ + /* rv->GetRandom */ + /* rv->null */ - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/capi/cslot.c b/security/nss/lib/ckfw/capi/cslot.c index 779161fc5371..8a39b7888fd4 100644 --- a/security/nss/lib/ckfw/capi/cslot.c +++ b/security/nss/lib/ckfw/capi/cslot.c @@ -12,80 +12,70 @@ */ static NSSUTF8 * -ckcapi_mdSlot_GetSlotDescription -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdSlot_GetSlotDescription( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_SlotDescription; + return (NSSUTF8 *)nss_ckcapi_SlotDescription; } static NSSUTF8 * -ckcapi_mdSlot_GetManufacturerID -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdSlot_GetManufacturerID( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_ManufacturerID; + return (NSSUTF8 *)nss_ckcapi_ManufacturerID; } static CK_VERSION -ckcapi_mdSlot_GetHardwareVersion -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdSlot_GetHardwareVersion( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckcapi_HardwareVersion; + return nss_ckcapi_HardwareVersion; } static CK_VERSION -ckcapi_mdSlot_GetFirmwareVersion -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdSlot_GetFirmwareVersion( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckcapi_FirmwareVersion; + return nss_ckcapi_FirmwareVersion; } static NSSCKMDToken * -ckcapi_mdSlot_GetToken -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdSlot_GetToken( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSCKMDToken *)&nss_ckcapi_mdToken; + return (NSSCKMDToken *)&nss_ckcapi_mdToken; } NSS_IMPLEMENT_DATA const NSSCKMDSlot -nss_ckcapi_mdSlot = { - (void *)NULL, /* etc */ - NULL, /* Initialize */ - NULL, /* Destroy */ - ckcapi_mdSlot_GetSlotDescription, - ckcapi_mdSlot_GetManufacturerID, - NULL, /* GetTokenPresent -- defaults to true */ - NULL, /* GetRemovableDevice -- defaults to false */ - NULL, /* GetHardwareSlot -- defaults to false */ - ckcapi_mdSlot_GetHardwareVersion, - ckcapi_mdSlot_GetFirmwareVersion, - ckcapi_mdSlot_GetToken, - (void *)NULL /* null terminator */ -}; + nss_ckcapi_mdSlot = { + (void *)NULL, /* etc */ + NULL, /* Initialize */ + NULL, /* Destroy */ + ckcapi_mdSlot_GetSlotDescription, + ckcapi_mdSlot_GetManufacturerID, + NULL, /* GetTokenPresent -- defaults to true */ + NULL, /* GetRemovableDevice -- defaults to false */ + NULL, /* GetHardwareSlot -- defaults to false */ + ckcapi_mdSlot_GetHardwareVersion, + ckcapi_mdSlot_GetFirmwareVersion, + ckcapi_mdSlot_GetToken, + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/capi/ctoken.c b/security/nss/lib/ckfw/capi/ctoken.c index 7f0e633ea209..cc95c17b6811 100644 --- a/security/nss/lib/ckfw/capi/ctoken.c +++ b/security/nss/lib/ckfw/capi/ctoken.c @@ -12,197 +12,173 @@ */ static NSSUTF8 * -ckcapi_mdToken_GetLabel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdToken_GetLabel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_TokenLabel; + return (NSSUTF8 *)nss_ckcapi_TokenLabel; } static NSSUTF8 * -ckcapi_mdToken_GetManufacturerID -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdToken_GetManufacturerID( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_ManufacturerID; + return (NSSUTF8 *)nss_ckcapi_ManufacturerID; } static NSSUTF8 * -ckcapi_mdToken_GetModel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdToken_GetModel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_TokenModel; + return (NSSUTF8 *)nss_ckcapi_TokenModel; } static NSSUTF8 * -ckcapi_mdToken_GetSerialNumber -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckcapi_mdToken_GetSerialNumber( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckcapi_TokenSerialNumber; + return (NSSUTF8 *)nss_ckcapi_TokenSerialNumber; } static CK_BBOOL -ckcapi_mdToken_GetIsWriteProtected -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdToken_GetIsWriteProtected( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_FALSE; + return CK_FALSE; } /* fake out Mozilla so we don't try to initialize the token */ static CK_BBOOL -ckcapi_mdToken_GetUserPinInitialized -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdToken_GetUserPinInitialized( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_TRUE; + return CK_TRUE; } static CK_VERSION -ckcapi_mdToken_GetHardwareVersion -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdToken_GetHardwareVersion( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckcapi_HardwareVersion; + return nss_ckcapi_HardwareVersion; } static CK_VERSION -ckcapi_mdToken_GetFirmwareVersion -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdToken_GetFirmwareVersion( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckcapi_FirmwareVersion; + return nss_ckcapi_FirmwareVersion; } static NSSCKMDSession * -ckcapi_mdToken_OpenSession -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession, - CK_BBOOL rw, - CK_RV *pError -) +ckcapi_mdToken_OpenSession( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession, + CK_BBOOL rw, + CK_RV *pError) { - return nss_ckcapi_CreateSession(fwSession, pError); + return nss_ckcapi_CreateSession(fwSession, pError); } static CK_ULONG -ckcapi_mdToken_GetMechanismCount -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckcapi_mdToken_GetMechanismCount( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return (CK_ULONG)1; + return (CK_ULONG)1; } static CK_RV -ckcapi_mdToken_GetMechanismTypes -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_MECHANISM_TYPE types[] -) +ckcapi_mdToken_GetMechanismTypes( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_MECHANISM_TYPE types[]) { - types[0] = CKM_RSA_PKCS; - return CKR_OK; + types[0] = CKM_RSA_PKCS; + return CKR_OK; } static NSSCKMDMechanism * -ckcapi_mdToken_GetMechanism -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_MECHANISM_TYPE which, - CK_RV *pError -) +ckcapi_mdToken_GetMechanism( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_MECHANISM_TYPE which, + CK_RV *pError) { - if (which != CKM_RSA_PKCS) { - *pError = CKR_MECHANISM_INVALID; - return (NSSCKMDMechanism *)NULL; - } - return (NSSCKMDMechanism *)&nss_ckcapi_mdMechanismRSA; + if (which != CKM_RSA_PKCS) { + *pError = CKR_MECHANISM_INVALID; + return (NSSCKMDMechanism *)NULL; + } + return (NSSCKMDMechanism *)&nss_ckcapi_mdMechanismRSA; } NSS_IMPLEMENT_DATA const NSSCKMDToken -nss_ckcapi_mdToken = { - (void *)NULL, /* etc */ - NULL, /* Setup */ - NULL, /* Invalidate */ - NULL, /* InitToken -- default errs */ - ckcapi_mdToken_GetLabel, - ckcapi_mdToken_GetManufacturerID, - ckcapi_mdToken_GetModel, - ckcapi_mdToken_GetSerialNumber, - NULL, /* GetHasRNG -- default is false */ - ckcapi_mdToken_GetIsWriteProtected, - NULL, /* GetLoginRequired -- default is false */ - ckcapi_mdToken_GetUserPinInitialized, - NULL, /* GetRestoreKeyNotNeeded -- irrelevant */ - NULL, /* GetHasClockOnToken -- default is false */ - NULL, /* GetHasProtectedAuthenticationPath -- default is false */ - NULL, /* GetSupportsDualCryptoOperations -- default is false */ - NULL, /* GetMaxSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetMaxRwSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetMaxPinLen -- irrelevant */ - NULL, /* GetMinPinLen -- irrelevant */ - NULL, /* GetTotalPublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetFreePublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetTotalPrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetFreePrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ - ckcapi_mdToken_GetHardwareVersion, - ckcapi_mdToken_GetFirmwareVersion, - NULL, /* GetUTCTime -- no clock */ - ckcapi_mdToken_OpenSession, - ckcapi_mdToken_GetMechanismCount, - ckcapi_mdToken_GetMechanismTypes, - ckcapi_mdToken_GetMechanism, - (void *)NULL /* null terminator */ -}; + nss_ckcapi_mdToken = { + (void *)NULL, /* etc */ + NULL, /* Setup */ + NULL, /* Invalidate */ + NULL, /* InitToken -- default errs */ + ckcapi_mdToken_GetLabel, + ckcapi_mdToken_GetManufacturerID, + ckcapi_mdToken_GetModel, + ckcapi_mdToken_GetSerialNumber, + NULL, /* GetHasRNG -- default is false */ + ckcapi_mdToken_GetIsWriteProtected, + NULL, /* GetLoginRequired -- default is false */ + ckcapi_mdToken_GetUserPinInitialized, + NULL, /* GetRestoreKeyNotNeeded -- irrelevant */ + NULL, /* GetHasClockOnToken -- default is false */ + NULL, /* GetHasProtectedAuthenticationPath -- default is false */ + NULL, /* GetSupportsDualCryptoOperations -- default is false */ + NULL, /* GetMaxSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetMaxRwSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetMaxPinLen -- irrelevant */ + NULL, /* GetMinPinLen -- irrelevant */ + NULL, /* GetTotalPublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetFreePublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetTotalPrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetFreePrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ + ckcapi_mdToken_GetHardwareVersion, + ckcapi_mdToken_GetFirmwareVersion, + NULL, /* GetUTCTime -- no clock */ + ckcapi_mdToken_OpenSession, + ckcapi_mdToken_GetMechanismCount, + ckcapi_mdToken_GetMechanismTypes, + ckcapi_mdToken_GetMechanism, + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/capi/nsscapi.h b/security/nss/lib/ckfw/capi/nsscapi.h index d98312031dc6..78bf38b2848f 100644 --- a/security/nss/lib/ckfw/capi/nsscapi.h +++ b/security/nss/lib/ckfw/capi/nsscapi.h @@ -18,7 +18,7 @@ #define NSS_CKCAPI_CRYPTOKI_VERSION_MAJOR 2 #define NSS_CKCAPI_CRYPTOKI_VERSION_MINOR 20 -/* These version numbers detail the changes +/* These version numbers detail the changes * to the list of trusted certificates. * * NSS_CKCAPI_LIBRARY_VERSION_MINOR is a CK_BYTE. It's not clear @@ -33,7 +33,7 @@ #define NSS_CKCAPI_HARDWARE_VERSION_MAJOR 1 #define NSS_CKCAPI_HARDWARE_VERSION_MINOR 0 -/* These version numbers detail the semantic changes to ckbi itself +/* These version numbers detail the semantic changes to ckbi itself * (new PKCS #11 objects), etc. */ #define NSS_CKCAPI_FIRMWARE_VERSION_MAJOR 1 #define NSS_CKCAPI_FIRMWARE_VERSION_MINOR 0 diff --git a/security/nss/lib/ckfw/capi/staticobj.c b/security/nss/lib/ckfw/capi/staticobj.c index c14c8121b1cb..2d67a34b3f12 100644 --- a/security/nss/lib/ckfw/capi/staticobj.c +++ b/security/nss/lib/ckfw/capi/staticobj.c @@ -17,22 +17,23 @@ static const CK_BBOOL ck_false = CK_FALSE; static const CK_OBJECT_CLASS cko_netscape_builtin_root_list = CKO_NETSCAPE_BUILTIN_ROOT_LIST; /* example of a static object */ -static const CK_ATTRIBUTE_TYPE nss_ckcapi_types_1 [] = { - CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_MODIFIABLE, CKA_LABEL +static const CK_ATTRIBUTE_TYPE nss_ckcapi_types_1[] = { + CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_MODIFIABLE, CKA_LABEL }; -static const NSSItem nss_ckcapi_items_1 [] = { - { (void *)&cko_data, (PRUint32)sizeof(CK_OBJECT_CLASS) }, - { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) }, - { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, - { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, - { (void *)"Mozilla CAPI Access", (PRUint32)20 } +static const NSSItem nss_ckcapi_items_1[] = { + { (void *)&cko_data, (PRUint32)sizeof(CK_OBJECT_CLASS) }, + { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) }, + { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, + { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, + { (void *)"Mozilla CAPI Access", (PRUint32)20 } }; ckcapiInternalObject nss_ckcapi_data[] = { - { ckcapiRaw, - { 5, nss_ckcapi_types_1, nss_ckcapi_items_1} , - }, + { + ckcapiRaw, + { 5, nss_ckcapi_types_1, nss_ckcapi_items_1 }, + }, }; diff --git a/security/nss/lib/ckfw/ckfw.h b/security/nss/lib/ckfw/ckfw.h index e5d2e1bff255..d4a2ead992f1 100644 --- a/security/nss/lib/ckfw/ckfw.h +++ b/security/nss/lib/ckfw/ckfw.h @@ -40,7 +40,7 @@ * nssCKFWInstance_MayCreatePthreads * nssCKFWInstance_CreateMutex * nssCKFWInstance_GetConfigurationData - * nssCKFWInstance_GetInitArgs + * nssCKFWInstance_GetInitArgs * * -- private accessors -- * nssCKFWInstance_CreateSessionHandle @@ -72,295 +72,240 @@ * */ NSS_EXTERN NSSCKFWInstance * -nssCKFWInstance_Create -( - CK_C_INITIALIZE_ARGS_PTR pInitArgs, - CryptokiLockingState LockingState, - NSSCKMDInstance *mdInstance, - CK_RV *pError -); +nssCKFWInstance_Create( + CK_C_INITIALIZE_ARGS_PTR pInitArgs, + CryptokiLockingState LockingState, + NSSCKMDInstance *mdInstance, + CK_RV *pError); /* * nssCKFWInstance_Destroy * */ NSS_EXTERN CK_RV -nssCKFWInstance_Destroy -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_Destroy( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_GetMDInstance * */ NSS_EXTERN NSSCKMDInstance * -nssCKFWInstance_GetMDInstance -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_GetMDInstance( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_GetArena * */ NSS_EXTERN NSSArena * -nssCKFWInstance_GetArena -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -); +nssCKFWInstance_GetArena( + NSSCKFWInstance *fwInstance, + CK_RV *pError); /* * nssCKFWInstance_MayCreatePthreads * */ NSS_EXTERN CK_BBOOL -nssCKFWInstance_MayCreatePthreads -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_MayCreatePthreads( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_CreateMutex * */ NSS_EXTERN NSSCKFWMutex * -nssCKFWInstance_CreateMutex -( - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -); +nssCKFWInstance_CreateMutex( + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError); /* * nssCKFWInstance_GetConfigurationData * */ NSS_EXTERN NSSUTF8 * -nssCKFWInstance_GetConfigurationData -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_GetConfigurationData( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_GetInitArgs * */ NSS_EXTERN CK_C_INITIALIZE_ARGS_PTR -nssCKFWInstance_GetInitArgs -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_GetInitArgs( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_CreateSessionHandle * */ NSS_EXTERN CK_SESSION_HANDLE -nssCKFWInstance_CreateSessionHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession, - CK_RV *pError -); +nssCKFWInstance_CreateSessionHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession, + CK_RV *pError); /* * nssCKFWInstance_ResolveSessionHandle * */ NSS_EXTERN NSSCKFWSession * -nssCKFWInstance_ResolveSessionHandle -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -); +nssCKFWInstance_ResolveSessionHandle( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession); /* * nssCKFWInstance_DestroySessionHandle * */ NSS_EXTERN void -nssCKFWInstance_DestroySessionHandle -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -); +nssCKFWInstance_DestroySessionHandle( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession); /* * nssCKFWInstance_FindSessionHandle * */ NSS_EXTERN CK_SESSION_HANDLE -nssCKFWInstance_FindSessionHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession -); +nssCKFWInstance_FindSessionHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession); /* * nssCKFWInstance_CreateObjectHandle * */ NSS_EXTERN CK_OBJECT_HANDLE -nssCKFWInstance_CreateObjectHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWObject *fwObject, - CK_RV *pError -); +nssCKFWInstance_CreateObjectHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWObject *fwObject, + CK_RV *pError); /* * nssCKFWInstance_ResolveObjectHandle * */ NSS_EXTERN NSSCKFWObject * -nssCKFWInstance_ResolveObjectHandle -( - NSSCKFWInstance *fwInstance, - CK_OBJECT_HANDLE hObject -); +nssCKFWInstance_ResolveObjectHandle( + NSSCKFWInstance *fwInstance, + CK_OBJECT_HANDLE hObject); /* * nssCKFWInstance_ReassignObjectHandle * */ NSS_EXTERN CK_RV -nssCKFWInstance_ReassignObjectHandle -( - NSSCKFWInstance *fwInstance, - CK_OBJECT_HANDLE hObject, - NSSCKFWObject *fwObject -); +nssCKFWInstance_ReassignObjectHandle( + NSSCKFWInstance *fwInstance, + CK_OBJECT_HANDLE hObject, + NSSCKFWObject *fwObject); /* * nssCKFWInstance_DestroyObjectHandle * */ NSS_EXTERN void -nssCKFWInstance_DestroyObjectHandle -( - NSSCKFWInstance *fwInstance, - CK_OBJECT_HANDLE hObject -); +nssCKFWInstance_DestroyObjectHandle( + NSSCKFWInstance *fwInstance, + CK_OBJECT_HANDLE hObject); /* * nssCKFWInstance_FindObjectHandle * */ NSS_EXTERN CK_OBJECT_HANDLE -nssCKFWInstance_FindObjectHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWObject *fwObject -); +nssCKFWInstance_FindObjectHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWObject *fwObject); /* * nssCKFWInstance_GetNSlots * */ NSS_EXTERN CK_ULONG -nssCKFWInstance_GetNSlots -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -); +nssCKFWInstance_GetNSlots( + NSSCKFWInstance *fwInstance, + CK_RV *pError); /* * nssCKFWInstance_GetCryptokiVersion * */ NSS_EXTERN CK_VERSION -nssCKFWInstance_GetCryptokiVersion -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_GetCryptokiVersion( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_GetManufacturerID * */ NSS_EXTERN CK_RV -nssCKFWInstance_GetManufacturerID -( - NSSCKFWInstance *fwInstance, - CK_CHAR manufacturerID[32] -); +nssCKFWInstance_GetManufacturerID( + NSSCKFWInstance *fwInstance, + CK_CHAR manufacturerID[32]); /* * nssCKFWInstance_GetFlags * */ NSS_EXTERN CK_ULONG -nssCKFWInstance_GetFlags -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_GetFlags( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_GetLibraryDescription * */ NSS_EXTERN CK_RV -nssCKFWInstance_GetLibraryDescription -( - NSSCKFWInstance *fwInstance, - CK_CHAR libraryDescription[32] -); +nssCKFWInstance_GetLibraryDescription( + NSSCKFWInstance *fwInstance, + CK_CHAR libraryDescription[32]); /* * nssCKFWInstance_GetLibraryVersion * */ NSS_EXTERN CK_VERSION -nssCKFWInstance_GetLibraryVersion -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_GetLibraryVersion( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_GetModuleHandlesSessionObjects * */ NSS_EXTERN CK_BBOOL -nssCKFWInstance_GetModuleHandlesSessionObjects -( - NSSCKFWInstance *fwInstance -); +nssCKFWInstance_GetModuleHandlesSessionObjects( + NSSCKFWInstance *fwInstance); /* * nssCKFWInstance_GetSlots * */ NSS_EXTERN NSSCKFWSlot ** -nssCKFWInstance_GetSlots -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -); +nssCKFWInstance_GetSlots( + NSSCKFWInstance *fwInstance, + CK_RV *pError); /* * nssCKFWInstance_WaitForSlotEvent * */ NSS_EXTERN NSSCKFWSlot * -nssCKFWInstance_WaitForSlotEvent -( - NSSCKFWInstance *fwInstance, - CK_BBOOL block, - CK_RV *pError -); +nssCKFWInstance_WaitForSlotEvent( + NSSCKFWInstance *fwInstance, + CK_BBOOL block, + CK_RV *pError); /* * nssCKFWInstance_verifyPointer * */ NSS_EXTERN CK_RV -nssCKFWInstance_verifyPointer -( - const NSSCKFWInstance *fwInstance -); - +nssCKFWInstance_verifyPointer( + const NSSCKFWInstance *fwInstance); /* * NSSCKFWSlot @@ -393,33 +338,27 @@ nssCKFWInstance_verifyPointer * */ NSS_EXTERN NSSCKFWSlot * -nssCKFWSlot_Create -( - NSSCKFWInstance *fwInstance, - NSSCKMDSlot *mdSlot, - CK_SLOT_ID slotID, - CK_RV *pError -); +nssCKFWSlot_Create( + NSSCKFWInstance *fwInstance, + NSSCKMDSlot *mdSlot, + CK_SLOT_ID slotID, + CK_RV *pError); /* * nssCKFWSlot_Destroy * */ NSS_EXTERN CK_RV -nssCKFWSlot_Destroy -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_Destroy( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetMDSlot * */ NSS_EXTERN NSSCKMDSlot * -nssCKFWSlot_GetMDSlot -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetMDSlot( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetFWInstance @@ -427,10 +366,8 @@ nssCKFWSlot_GetMDSlot */ NSS_EXTERN NSSCKFWInstance * -nssCKFWSlot_GetFWInstance -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetFWInstance( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetMDInstance @@ -438,113 +375,91 @@ nssCKFWSlot_GetFWInstance */ NSS_EXTERN NSSCKMDInstance * -nssCKFWSlot_GetMDInstance -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetMDInstance( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetSlotID * */ NSS_EXTERN CK_SLOT_ID -nssCKFWSlot_GetSlotID -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetSlotID( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetSlotDescription * */ NSS_EXTERN CK_RV -nssCKFWSlot_GetSlotDescription -( - NSSCKFWSlot *fwSlot, - CK_CHAR slotDescription[64] -); +nssCKFWSlot_GetSlotDescription( + NSSCKFWSlot *fwSlot, + CK_CHAR slotDescription[64]); /* * nssCKFWSlot_GetManufacturerID * */ NSS_EXTERN CK_RV -nssCKFWSlot_GetManufacturerID -( - NSSCKFWSlot *fwSlot, - CK_CHAR manufacturerID[32] -); +nssCKFWSlot_GetManufacturerID( + NSSCKFWSlot *fwSlot, + CK_CHAR manufacturerID[32]); /* * nssCKFWSlot_GetTokenPresent * */ NSS_EXTERN CK_BBOOL -nssCKFWSlot_GetTokenPresent -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetTokenPresent( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetRemovableDevice * */ NSS_EXTERN CK_BBOOL -nssCKFWSlot_GetRemovableDevice -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetRemovableDevice( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetHardwareSlot * */ NSS_EXTERN CK_BBOOL -nssCKFWSlot_GetHardwareSlot -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetHardwareSlot( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetHardwareVersion * */ NSS_EXTERN CK_VERSION -nssCKFWSlot_GetHardwareVersion -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetHardwareVersion( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetFirmwareVersion * */ NSS_EXTERN CK_VERSION -nssCKFWSlot_GetFirmwareVersion -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_GetFirmwareVersion( + NSSCKFWSlot *fwSlot); /* * nssCKFWSlot_GetToken - * + * */ NSS_EXTERN NSSCKFWToken * -nssCKFWSlot_GetToken -( - NSSCKFWSlot *fwSlot, - CK_RV *pError -); +nssCKFWSlot_GetToken( + NSSCKFWSlot *fwSlot, + CK_RV *pError); /* * nssCKFWSlot_ClearToken * */ NSS_EXTERN void -nssCKFWSlot_ClearToken -( - NSSCKFWSlot *fwSlot -); +nssCKFWSlot_ClearToken( + NSSCKFWSlot *fwSlot); /* * NSSCKFWToken @@ -606,459 +521,371 @@ nssCKFWSlot_ClearToken * */ NSS_EXTERN NSSCKFWToken * -nssCKFWToken_Create -( - NSSCKFWSlot *fwSlot, - NSSCKMDToken *mdToken, - CK_RV *pError -); +nssCKFWToken_Create( + NSSCKFWSlot *fwSlot, + NSSCKMDToken *mdToken, + CK_RV *pError); /* * nssCKFWToken_Destroy * */ NSS_EXTERN CK_RV -nssCKFWToken_Destroy -( - NSSCKFWToken *fwToken -); +nssCKFWToken_Destroy( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMDToken * */ NSS_EXTERN NSSCKMDToken * -nssCKFWToken_GetMDToken -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMDToken( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetArena * */ NSS_EXTERN NSSArena * -nssCKFWToken_GetArena -( - NSSCKFWToken *fwToken, - CK_RV *pError -); +nssCKFWToken_GetArena( + NSSCKFWToken *fwToken, + CK_RV *pError); /* * nssCKFWToken_GetFWSlot * */ NSS_EXTERN NSSCKFWSlot * -nssCKFWToken_GetFWSlot -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetFWSlot( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMDSlot * */ NSS_EXTERN NSSCKMDSlot * -nssCKFWToken_GetMDSlot -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMDSlot( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetSessionState * */ NSS_EXTERN CK_STATE -nssCKFWToken_GetSessionState -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetSessionState( + NSSCKFWToken *fwToken); /* * nssCKFWToken_InitToken * */ NSS_EXTERN CK_RV -nssCKFWToken_InitToken -( - NSSCKFWToken *fwToken, - NSSItem *pin, - NSSUTF8 *label -); +nssCKFWToken_InitToken( + NSSCKFWToken *fwToken, + NSSItem *pin, + NSSUTF8 *label); /* * nssCKFWToken_GetLabel * */ NSS_EXTERN CK_RV -nssCKFWToken_GetLabel -( - NSSCKFWToken *fwToken, - CK_CHAR label[32] -); +nssCKFWToken_GetLabel( + NSSCKFWToken *fwToken, + CK_CHAR label[32]); /* * nssCKFWToken_GetManufacturerID * */ NSS_EXTERN CK_RV -nssCKFWToken_GetManufacturerID -( - NSSCKFWToken *fwToken, - CK_CHAR manufacturerID[32] -); +nssCKFWToken_GetManufacturerID( + NSSCKFWToken *fwToken, + CK_CHAR manufacturerID[32]); /* * nssCKFWToken_GetModel * */ NSS_EXTERN CK_RV -nssCKFWToken_GetModel -( - NSSCKFWToken *fwToken, - CK_CHAR model[16] -); +nssCKFWToken_GetModel( + NSSCKFWToken *fwToken, + CK_CHAR model[16]); /* * nssCKFWToken_GetSerialNumber * */ NSS_EXTERN CK_RV -nssCKFWToken_GetSerialNumber -( - NSSCKFWToken *fwToken, - CK_CHAR serialNumber[16] -); +nssCKFWToken_GetSerialNumber( + NSSCKFWToken *fwToken, + CK_CHAR serialNumber[16]); /* * nssCKFWToken_GetHasRNG * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetHasRNG -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetHasRNG( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetIsWriteProtected * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetIsWriteProtected -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetIsWriteProtected( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetLoginRequired * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetLoginRequired -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetLoginRequired( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetUserPinInitialized * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetUserPinInitialized -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetUserPinInitialized( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetRestoreKeyNotNeeded * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetRestoreKeyNotNeeded -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetRestoreKeyNotNeeded( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetHasClockOnToken * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetHasClockOnToken -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetHasClockOnToken( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetHasProtectedAuthenticationPath * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetHasProtectedAuthenticationPath -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetHasProtectedAuthenticationPath( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetSupportsDualCryptoOperations * */ NSS_EXTERN CK_BBOOL -nssCKFWToken_GetSupportsDualCryptoOperations -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetSupportsDualCryptoOperations( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMaxSessionCount * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetMaxSessionCount -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMaxSessionCount( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMaxRwSessionCount * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetMaxRwSessionCount -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMaxRwSessionCount( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMaxPinLen * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetMaxPinLen -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMaxPinLen( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMinPinLen * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetMinPinLen -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMinPinLen( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetTotalPublicMemory * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetTotalPublicMemory -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetTotalPublicMemory( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetFreePublicMemory * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetFreePublicMemory -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetFreePublicMemory( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetTotalPrivateMemory * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetTotalPrivateMemory -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetTotalPrivateMemory( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetFreePrivateMemory * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetFreePrivateMemory -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetFreePrivateMemory( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetHardwareVersion * */ NSS_EXTERN CK_VERSION -nssCKFWToken_GetHardwareVersion -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetHardwareVersion( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetFirmwareVersion * */ NSS_EXTERN CK_VERSION -nssCKFWToken_GetFirmwareVersion -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetFirmwareVersion( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetUTCTime * */ NSS_EXTERN CK_RV -nssCKFWToken_GetUTCTime -( - NSSCKFWToken *fwToken, - CK_CHAR utcTime[16] -); +nssCKFWToken_GetUTCTime( + NSSCKFWToken *fwToken, + CK_CHAR utcTime[16]); /* * nssCKFWToken_OpenSession * */ NSS_EXTERN NSSCKFWSession * -nssCKFWToken_OpenSession -( - NSSCKFWToken *fwToken, - CK_BBOOL rw, - CK_VOID_PTR pApplication, - CK_NOTIFY Notify, - CK_RV *pError -); +nssCKFWToken_OpenSession( + NSSCKFWToken *fwToken, + CK_BBOOL rw, + CK_VOID_PTR pApplication, + CK_NOTIFY Notify, + CK_RV *pError); /* * nssCKFWToken_GetMechanismCount * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetMechanismCount -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMechanismCount( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMechanismTypes * */ NSS_EXTERN CK_RV -nssCKFWToken_GetMechanismTypes -( - NSSCKFWToken *fwToken, - CK_MECHANISM_TYPE types[] -); +nssCKFWToken_GetMechanismTypes( + NSSCKFWToken *fwToken, + CK_MECHANISM_TYPE types[]); /* * nssCKFWToken_GetMechanism * */ NSS_EXTERN NSSCKFWMechanism * -nssCKFWToken_GetMechanism -( - NSSCKFWToken *fwToken, - CK_MECHANISM_TYPE which, - CK_RV *pError -); +nssCKFWToken_GetMechanism( + NSSCKFWToken *fwToken, + CK_MECHANISM_TYPE which, + CK_RV *pError); /* * nssCKFWToken_SetSessionState * */ NSS_EXTERN CK_RV -nssCKFWToken_SetSessionState -( - NSSCKFWToken *fwToken, - CK_STATE newState -); +nssCKFWToken_SetSessionState( + NSSCKFWToken *fwToken, + CK_STATE newState); /* * nssCKFWToken_RemoveSession * */ NSS_EXTERN CK_RV -nssCKFWToken_RemoveSession -( - NSSCKFWToken *fwToken, - NSSCKFWSession *fwSession -); +nssCKFWToken_RemoveSession( + NSSCKFWToken *fwToken, + NSSCKFWSession *fwSession); /* * nssCKFWToken_CloseAllSessions * */ NSS_EXTERN CK_RV -nssCKFWToken_CloseAllSessions -( - NSSCKFWToken *fwToken -); +nssCKFWToken_CloseAllSessions( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetSessionCount * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetSessionCount -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetSessionCount( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetRwSessionCount * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetRwSessionCount -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetRwSessionCount( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetRoSessionCount * */ NSS_EXTERN CK_ULONG -nssCKFWToken_GetRoSessionCount -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetRoSessionCount( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetSessionObjectHash * */ NSS_EXTERN nssCKFWHash * -nssCKFWToken_GetSessionObjectHash -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetSessionObjectHash( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetMDObjectHash * */ NSS_EXTERN nssCKFWHash * -nssCKFWToken_GetMDObjectHash -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetMDObjectHash( + NSSCKFWToken *fwToken); /* * nssCKFWToken_GetObjectHandleHash * */ NSS_EXTERN nssCKFWHash * -nssCKFWToken_GetObjectHandleHash -( - NSSCKFWToken *fwToken -); +nssCKFWToken_GetObjectHandleHash( + NSSCKFWToken *fwToken); /* * NSSCKFWMechanism @@ -1107,24 +934,20 @@ nssCKFWToken_GetObjectHandleHash * */ NSS_EXTERN NSSCKFWMechanism * -nssCKFWMechanism_Create -( - NSSCKMDMechanism *mdMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -); +nssCKFWMechanism_Create( + NSSCKMDMechanism *mdMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); /* * nssCKFWMechanism_Destroy * */ NSS_EXTERN void -nssCKFWMechanism_Destroy -( - NSSCKFWMechanism *fwMechanism -); +nssCKFWMechanism_Destroy( + NSSCKFWMechanism *fwMechanism); /* * nssCKFWMechanism_GetMDMechanism @@ -1132,43 +955,35 @@ nssCKFWMechanism_Destroy */ NSS_EXTERN NSSCKMDMechanism * -nssCKFWMechanism_GetMDMechanism -( - NSSCKFWMechanism *fwMechanism -); +nssCKFWMechanism_GetMDMechanism( + NSSCKFWMechanism *fwMechanism); /* * nssCKFWMechanism_GetMinKeySize * */ NSS_EXTERN CK_ULONG -nssCKFWMechanism_GetMinKeySize -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetMinKeySize( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetMaxKeySize * */ NSS_EXTERN CK_ULONG -nssCKFWMechanism_GetMaxKeySize -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetMaxKeySize( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetInHardware * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetInHardware -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetInHardware( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * the following are determined automatically by which of the cryptographic @@ -1179,305 +994,255 @@ nssCKFWMechanism_GetInHardware * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanEncrypt -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanEncrypt( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanDecrypt * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanDecrypt -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanDecrypt( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanDigest * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanDigest -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanDigest( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanSign * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanSign -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanSign( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanSignRecover * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanSignRecover -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanSignRecover( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanVerify * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanVerify -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanVerify( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanVerifyRecover * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanVerifyRecover -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanVerifyRecover( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanGenerate * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanGenerate -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanGenerate( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanGenerateKeyPair * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanGenerateKeyPair -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanGenerateKeyPair( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanWrap * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanWrap -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanWrap( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanUnwrap * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanUnwrap -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanUnwrap( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_GetCanDerive * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanDerive -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -); +nssCKFWMechanism_GetCanDerive( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError); /* * nssCKFWMechanism_EncryptInit */ NSS_EXTERN CK_RV -nssCKFWMechanism_EncryptInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWMechanism_EncryptInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWMechanism_DecryptInit */ NSS_EXTERN CK_RV -nssCKFWMechanism_DecryptInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWMechanism_DecryptInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWMechanism_DigestInit */ NSS_EXTERN CK_RV -nssCKFWMechanism_DigestInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession -); +nssCKFWMechanism_DigestInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession); /* * nssCKFWMechanism_SignInit */ NSS_EXTERN CK_RV -nssCKFWMechanism_SignInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWMechanism_SignInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWMechanism_SignRecoverInit */ NSS_EXTERN CK_RV -nssCKFWMechanism_SignRecoverInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWMechanism_SignRecoverInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWMechanism_VerifyInit */ NSS_EXTERN CK_RV -nssCKFWMechanism_VerifyInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWMechanism_VerifyInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWMechanism_VerifyRecoverInit */ NSS_EXTERN CK_RV -nssCKFWMechanism_VerifyRecoverInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWMechanism_VerifyRecoverInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWMechanism_GenerateKey */ NSS_EXTERN NSSCKFWObject * -nssCKFWMechanism_GenerateKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nssCKFWMechanism_GenerateKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); /* * nssCKFWMechanism_GenerateKeyPair */ NSS_EXTERN CK_RV -nssCKFWMechanism_GenerateKeyPair -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG ulPublicKeyAttributeCount, - CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG ulPrivateKeyAttributeCount, - NSSCKFWObject **fwPublicKeyObject, - NSSCKFWObject **fwPrivateKeyObject -); +nssCKFWMechanism_GenerateKeyPair( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG ulPublicKeyAttributeCount, + CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG ulPrivateKeyAttributeCount, + NSSCKFWObject **fwPublicKeyObject, + NSSCKFWObject **fwPrivateKeyObject); /* * nssCKFWMechanism_GetWrapKeyLength */ NSS_EXTERN CK_ULONG -nssCKFWMechanism_GetWrapKeyLength -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwWrappingKeyObject, - NSSCKFWObject *fwObject, - CK_RV *pError -); +nssCKFWMechanism_GetWrapKeyLength( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwWrappingKeyObject, + NSSCKFWObject *fwObject, + CK_RV *pError); /* * nssCKFWMechanism_WrapKey */ NSS_EXTERN CK_RV -nssCKFWMechanism_WrapKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwWrappingKeyObject, - NSSCKFWObject *fwObject, - NSSItem *wrappedKey -); +nssCKFWMechanism_WrapKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwWrappingKeyObject, + NSSCKFWObject *fwObject, + NSSItem *wrappedKey); /* * nssCKFWMechanism_UnwrapKey */ NSS_EXTERN NSSCKFWObject * -nssCKFWMechanism_UnwrapKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwWrappingKeyObject, - NSSItem *wrappedKey, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nssCKFWMechanism_UnwrapKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwWrappingKeyObject, + NSSItem *wrappedKey, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); -/* +/* * nssCKFWMechanism_DeriveKey */ NSS_EXTERN NSSCKFWObject * -nssCKFWMechanism_DeriveKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwBaseKeyObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nssCKFWMechanism_DeriveKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwBaseKeyObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); /* * NSSCKFWCryptoOperation @@ -1506,130 +1271,106 @@ nssCKFWMechanism_DeriveKey * nssCKFWCrytoOperation_Create */ NSS_EXTERN NSSCKFWCryptoOperation * -nssCKFWCryptoOperation_Create -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKFWCryptoOperationType type, - CK_RV *pError -); +nssCKFWCryptoOperation_Create( + NSSCKMDCryptoOperation *mdOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKFWCryptoOperationType type, + CK_RV *pError); /* * nssCKFWCryptoOperation_Destroy */ NSS_EXTERN void -nssCKFWCryptoOperation_Destroy -( - NSSCKFWCryptoOperation *fwOperation -); +nssCKFWCryptoOperation_Destroy( + NSSCKFWCryptoOperation *fwOperation); /* * nssCKFWCryptoOperation_GetMDCryptoOperation */ NSS_EXTERN NSSCKMDCryptoOperation * -nssCKFWCryptoOperation_GetMDCryptoOperation -( - NSSCKFWCryptoOperation *fwOperation -); +nssCKFWCryptoOperation_GetMDCryptoOperation( + NSSCKFWCryptoOperation *fwOperation); /* * nssCKFWCryptoOperation_GetType */ NSS_EXTERN NSSCKFWCryptoOperationType -nssCKFWCryptoOperation_GetType -( - NSSCKFWCryptoOperation *fwOperation -); +nssCKFWCryptoOperation_GetType( + NSSCKFWCryptoOperation *fwOperation); /* * nssCKFWCryptoOperation_GetFinalLength */ NSS_EXTERN CK_ULONG -nssCKFWCryptoOperation_GetFinalLength -( - NSSCKFWCryptoOperation *fwOperation, - CK_RV *pError -); +nssCKFWCryptoOperation_GetFinalLength( + NSSCKFWCryptoOperation *fwOperation, + CK_RV *pError); /* * nssCKFWCryptoOperation_GetOperationLength */ NSS_EXTERN CK_ULONG -nssCKFWCryptoOperation_GetOperationLength -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer, - CK_RV *pError -); +nssCKFWCryptoOperation_GetOperationLength( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer, + CK_RV *pError); /* * nssCKFWCryptoOperation_Final */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_Final -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *outputBuffer -); +nssCKFWCryptoOperation_Final( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *outputBuffer); /* * nssCKFWCryptoOperation_Update */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_Update -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer, - NSSItem *outputBuffer -); +nssCKFWCryptoOperation_Update( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer, + NSSItem *outputBuffer); /* * nssCKFWCryptoOperation_DigestUpdate */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_DigestUpdate -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer -); +nssCKFWCryptoOperation_DigestUpdate( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer); /* * nssCKFWCryptoOperation_DigestKey */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_DigestKey -( - NSSCKFWCryptoOperation *fwOperation, - NSSCKFWObject *fwKey -); +nssCKFWCryptoOperation_DigestKey( + NSSCKFWCryptoOperation *fwOperation, + NSSCKFWObject *fwKey); /* * nssCKFWCryptoOperation_UpdateFinal */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_UpdateFinal -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer, - NSSItem *outputBuffer -); +nssCKFWCryptoOperation_UpdateFinal( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer, + NSSItem *outputBuffer); /* * nssCKFWCryptoOperation_UpdateCombo */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_UpdateCombo -( - NSSCKFWCryptoOperation *fwOperation, - NSSCKFWCryptoOperation *fwPeerOperation, - NSSItem *inputBuffer, - NSSItem *outputBuffer -); +nssCKFWCryptoOperation_UpdateCombo( + NSSCKFWCryptoOperation *fwOperation, + NSSCKFWCryptoOperation *fwPeerOperation, + NSSItem *inputBuffer, + NSSItem *outputBuffer); /* * NSSCKFWSession @@ -1685,434 +1426,360 @@ nssCKFWCryptoOperation_UpdateCombo * */ NSS_EXTERN NSSCKFWSession * -nssCKFWSession_Create -( - NSSCKFWToken *fwToken, - CK_BBOOL rw, - CK_VOID_PTR pApplication, - CK_NOTIFY Notify, - CK_RV *pError -); +nssCKFWSession_Create( + NSSCKFWToken *fwToken, + CK_BBOOL rw, + CK_VOID_PTR pApplication, + CK_NOTIFY Notify, + CK_RV *pError); /* * nssCKFWSession_Destroy * */ NSS_EXTERN CK_RV -nssCKFWSession_Destroy -( - NSSCKFWSession *fwSession, - CK_BBOOL removeFromTokenHash -); +nssCKFWSession_Destroy( + NSSCKFWSession *fwSession, + CK_BBOOL removeFromTokenHash); /* * nssCKFWSession_GetMDSession * */ NSS_EXTERN NSSCKMDSession * -nssCKFWSession_GetMDSession -( - NSSCKFWSession *fwSession -); +nssCKFWSession_GetMDSession( + NSSCKFWSession *fwSession); /* * nssCKFWSession_GetArena * */ NSS_EXTERN NSSArena * -nssCKFWSession_GetArena -( - NSSCKFWSession *fwSession, - CK_RV *pError -); +nssCKFWSession_GetArena( + NSSCKFWSession *fwSession, + CK_RV *pError); /* * nssCKFWSession_CallNotification * */ NSS_EXTERN CK_RV -nssCKFWSession_CallNotification -( - NSSCKFWSession *fwSession, - CK_NOTIFICATION event -); +nssCKFWSession_CallNotification( + NSSCKFWSession *fwSession, + CK_NOTIFICATION event); /* * nssCKFWSession_IsRWSession * */ NSS_EXTERN CK_BBOOL -nssCKFWSession_IsRWSession -( - NSSCKFWSession *fwSession -); +nssCKFWSession_IsRWSession( + NSSCKFWSession *fwSession); /* * nssCKFWSession_IsSO * */ NSS_EXTERN CK_BBOOL -nssCKFWSession_IsSO -( - NSSCKFWSession *fwSession -); +nssCKFWSession_IsSO( + NSSCKFWSession *fwSession); /* * nssCKFWSession_GetFWSlot * */ NSS_EXTERN NSSCKFWSlot * -nssCKFWSession_GetFWSlot -( - NSSCKFWSession *fwSession -); +nssCKFWSession_GetFWSlot( + NSSCKFWSession *fwSession); /* * nssCFKWSession_GetSessionState * */ NSS_EXTERN CK_STATE -nssCKFWSession_GetSessionState -( - NSSCKFWSession *fwSession -); +nssCKFWSession_GetSessionState( + NSSCKFWSession *fwSession); /* * nssCKFWSession_SetFWFindObjects * */ NSS_EXTERN CK_RV -nssCKFWSession_SetFWFindObjects -( - NSSCKFWSession *fwSession, - NSSCKFWFindObjects *fwFindObjects -); +nssCKFWSession_SetFWFindObjects( + NSSCKFWSession *fwSession, + NSSCKFWFindObjects *fwFindObjects); /* * nssCKFWSession_GetFWFindObjects * */ NSS_EXTERN NSSCKFWFindObjects * -nssCKFWSession_GetFWFindObjects -( - NSSCKFWSession *fwSesssion, - CK_RV *pError -); +nssCKFWSession_GetFWFindObjects( + NSSCKFWSession *fwSesssion, + CK_RV *pError); /* * nssCKFWSession_SetMDSession * */ NSS_EXTERN CK_RV -nssCKFWSession_SetMDSession -( - NSSCKFWSession *fwSession, - NSSCKMDSession *mdSession -); +nssCKFWSession_SetMDSession( + NSSCKFWSession *fwSession, + NSSCKMDSession *mdSession); /* * nssCKFWSession_SetHandle * */ NSS_EXTERN CK_RV -nssCKFWSession_SetHandle -( - NSSCKFWSession *fwSession, - CK_SESSION_HANDLE hSession -); +nssCKFWSession_SetHandle( + NSSCKFWSession *fwSession, + CK_SESSION_HANDLE hSession); /* * nssCKFWSession_GetHandle * */ NSS_EXTERN CK_SESSION_HANDLE -nssCKFWSession_GetHandle -( - NSSCKFWSession *fwSession -); +nssCKFWSession_GetHandle( + NSSCKFWSession *fwSession); /* * nssCKFWSession_RegisterSessionObject * */ NSS_EXTERN CK_RV -nssCKFWSession_RegisterSessionObject -( - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWSession_RegisterSessionObject( + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWSession_DeregisterSessionObject * */ NSS_EXTERN CK_RV -nssCKFWSession_DeregisterSessionObject -( - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -); +nssCKFWSession_DeregisterSessionObject( + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject); /* * nssCKFWSession_GetDeviceError * */ NSS_EXTERN CK_ULONG -nssCKFWSession_GetDeviceError -( - NSSCKFWSession *fwSession -); +nssCKFWSession_GetDeviceError( + NSSCKFWSession *fwSession); /* * nssCKFWSession_Login * */ NSS_EXTERN CK_RV -nssCKFWSession_Login -( - NSSCKFWSession *fwSession, - CK_USER_TYPE userType, - NSSItem *pin -); +nssCKFWSession_Login( + NSSCKFWSession *fwSession, + CK_USER_TYPE userType, + NSSItem *pin); /* * nssCKFWSession_Logout * */ NSS_EXTERN CK_RV -nssCKFWSession_Logout -( - NSSCKFWSession *fwSession -); +nssCKFWSession_Logout( + NSSCKFWSession *fwSession); /* * nssCKFWSession_InitPIN * */ NSS_EXTERN CK_RV -nssCKFWSession_InitPIN -( - NSSCKFWSession *fwSession, - NSSItem *pin -); +nssCKFWSession_InitPIN( + NSSCKFWSession *fwSession, + NSSItem *pin); /* * nssCKFWSession_SetPIN * */ NSS_EXTERN CK_RV -nssCKFWSession_SetPIN -( - NSSCKFWSession *fwSession, - NSSItem *newPin, - NSSItem *oldPin -); +nssCKFWSession_SetPIN( + NSSCKFWSession *fwSession, + NSSItem *newPin, + NSSItem *oldPin); /* * nssCKFWSession_GetOperationStateLen * */ NSS_EXTERN CK_ULONG -nssCKFWSession_GetOperationStateLen -( - NSSCKFWSession *fwSession, - CK_RV *pError -); +nssCKFWSession_GetOperationStateLen( + NSSCKFWSession *fwSession, + CK_RV *pError); /* * nssCKFWSession_GetOperationState * */ NSS_EXTERN CK_RV -nssCKFWSession_GetOperationState -( - NSSCKFWSession *fwSession, - NSSItem *buffer -); +nssCKFWSession_GetOperationState( + NSSCKFWSession *fwSession, + NSSItem *buffer); /* * nssCKFWSession_SetOperationState * */ NSS_EXTERN CK_RV -nssCKFWSession_SetOperationState -( - NSSCKFWSession *fwSession, - NSSItem *state, - NSSCKFWObject *encryptionKey, - NSSCKFWObject *authenticationKey -); +nssCKFWSession_SetOperationState( + NSSCKFWSession *fwSession, + NSSItem *state, + NSSCKFWObject *encryptionKey, + NSSCKFWObject *authenticationKey); /* * nssCKFWSession_CreateObject * */ NSS_EXTERN NSSCKFWObject * -nssCKFWSession_CreateObject -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nssCKFWSession_CreateObject( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); /* * nssCKFWSession_CopyObject * */ NSS_EXTERN NSSCKFWObject * -nssCKFWSession_CopyObject -( - NSSCKFWSession *fwSession, - NSSCKFWObject *object, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nssCKFWSession_CopyObject( + NSSCKFWSession *fwSession, + NSSCKFWObject *object, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); /* * nssCKFWSession_FindObjectsInit * */ NSS_EXTERN NSSCKFWFindObjects * -nssCKFWSession_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nssCKFWSession_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); /* * nssCKFWSession_SetCurrentCryptoOperation */ NSS_IMPLEMENT void -nssCKFWSession_SetCurrentCryptoOperation -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperation * fwOperation, - NSSCKFWCryptoOperationState state -); +nssCKFWSession_SetCurrentCryptoOperation( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperation *fwOperation, + NSSCKFWCryptoOperationState state); /* * nssCKFWSession_GetCurrentCryptoOperation */ NSS_IMPLEMENT NSSCKFWCryptoOperation * -nssCKFWSession_GetCurrentCryptoOperation -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationState state -); +nssCKFWSession_GetCurrentCryptoOperation( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationState state); /* * nssCKFWSession_Final * (terminate a cryptographic operation and get the result) */ NSS_IMPLEMENT CK_RV -nssCKFWSession_Final -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -); +nssCKFWSession_Final( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen); /* * nssCKFWSession_Update * (get the next step of an encrypt/decrypt operation) */ NSS_IMPLEMENT CK_RV -nssCKFWSession_Update -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -); +nssCKFWSession_Update( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen); /* * nssCKFWSession_DigestUpdate * (do the next step of an digest/sign/verify operation) */ NSS_IMPLEMENT CK_RV -nssCKFWSession_DigestUpdate -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen -); +nssCKFWSession_DigestUpdate( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen); /* * nssCKFWSession_DigestKey * (do the next step of an digest/sign/verify operation) */ NSS_IMPLEMENT CK_RV -nssCKFWSession_DigestKey -( - NSSCKFWSession *fwSession, - NSSCKFWObject *fwKey -); +nssCKFWSession_DigestKey( + NSSCKFWSession *fwSession, + NSSCKFWObject *fwKey); /* * nssCKFWSession_UpdateFinal * (do a single-step of a cryptographic operation and get the result) */ NSS_IMPLEMENT CK_RV -nssCKFWSession_UpdateFinal -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -); +nssCKFWSession_UpdateFinal( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen); /* * nssCKFWSession_UpdateCombo * (do a combination encrypt/decrypt and sign/digest/verify operation) */ NSS_IMPLEMENT CK_RV -nssCKFWSession_UpdateCombo -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType encryptType, - NSSCKFWCryptoOperationType digestType, - NSSCKFWCryptoOperationState digestState, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -); +nssCKFWSession_UpdateCombo( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType encryptType, + NSSCKFWCryptoOperationType digestType, + NSSCKFWCryptoOperationState digestState, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen); /* * nssCKFWSession_SeedRandom * */ NSS_EXTERN CK_RV -nssCKFWSession_SeedRandom -( - NSSCKFWSession *fwSession, - NSSItem *seed -); +nssCKFWSession_SeedRandom( + NSSCKFWSession *fwSession, + NSSItem *seed); /* * nssCKFWSession_GetRandom * */ NSS_EXTERN CK_RV -nssCKFWSession_GetRandom -( - NSSCKFWSession *fwSession, - NSSItem *buffer -); +nssCKFWSession_GetRandom( + NSSCKFWSession *fwSession, + NSSItem *buffer); /* * NSSCKFWObject @@ -2145,123 +1812,101 @@ nssCKFWSession_GetRandom * */ NSS_EXTERN NSSCKFWObject * -nssCKFWObject_Create -( - NSSArena *arena, - NSSCKMDObject *mdObject, - NSSCKFWSession *fwSession, - NSSCKFWToken *fwToken, - NSSCKFWInstance *fwInstance, - CK_RV *pError -); +nssCKFWObject_Create( + NSSArena *arena, + NSSCKMDObject *mdObject, + NSSCKFWSession *fwSession, + NSSCKFWToken *fwToken, + NSSCKFWInstance *fwInstance, + CK_RV *pError); /* * nssCKFWObject_Finalize * */ NSS_EXTERN void -nssCKFWObject_Finalize -( - NSSCKFWObject *fwObject, - PRBool removeFromHash -); +nssCKFWObject_Finalize( + NSSCKFWObject *fwObject, + PRBool removeFromHash); /* * nssCKFWObject_Destroy * */ NSS_EXTERN void -nssCKFWObject_Destroy -( - NSSCKFWObject *fwObject -); +nssCKFWObject_Destroy( + NSSCKFWObject *fwObject); /* * nssCKFWObject_GetMDObject * */ NSS_EXTERN NSSCKMDObject * -nssCKFWObject_GetMDObject -( - NSSCKFWObject *fwObject -); +nssCKFWObject_GetMDObject( + NSSCKFWObject *fwObject); /* * nssCKFWObject_GetArena * */ NSS_EXTERN NSSArena * -nssCKFWObject_GetArena -( - NSSCKFWObject *fwObject, - CK_RV *pError -); +nssCKFWObject_GetArena( + NSSCKFWObject *fwObject, + CK_RV *pError); /* * nssCKFWObject_SetHandle * */ NSS_EXTERN CK_RV -nssCKFWObject_SetHandle -( - NSSCKFWObject *fwObject, - CK_OBJECT_HANDLE hObject -); +nssCKFWObject_SetHandle( + NSSCKFWObject *fwObject, + CK_OBJECT_HANDLE hObject); /* * nssCKFWObject_GetHandle * */ NSS_EXTERN CK_OBJECT_HANDLE -nssCKFWObject_GetHandle -( - NSSCKFWObject *fwObject -); +nssCKFWObject_GetHandle( + NSSCKFWObject *fwObject); /* * nssCKFWObject_IsTokenObject * */ NSS_EXTERN CK_BBOOL -nssCKFWObject_IsTokenObject -( - NSSCKFWObject *fwObject -); +nssCKFWObject_IsTokenObject( + NSSCKFWObject *fwObject); /* * nssCKFWObject_GetAttributeCount * */ NSS_EXTERN CK_ULONG -nssCKFWObject_GetAttributeCount -( - NSSCKFWObject *fwObject, - CK_RV *pError -); +nssCKFWObject_GetAttributeCount( + NSSCKFWObject *fwObject, + CK_RV *pError); /* * nssCKFWObject_GetAttributeTypes * */ NSS_EXTERN CK_RV -nssCKFWObject_GetAttributeTypes -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -); +nssCKFWObject_GetAttributeTypes( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount); /* * nssCKFWObject_GetAttributeSize * */ NSS_EXTERN CK_ULONG -nssCKFWObject_GetAttributeSize -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -); +nssCKFWObject_GetAttributeSize( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError); /* * nssCKFWObject_GetAttribute @@ -2274,38 +1919,32 @@ nssCKFWObject_GetAttributeSize * specified. */ NSS_EXTERN NSSItem * -nssCKFWObject_GetAttribute -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *itemOpt, - NSSArena *arenaOpt, - CK_RV *pError -); +nssCKFWObject_GetAttribute( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *itemOpt, + NSSArena *arenaOpt, + CK_RV *pError); /* * nssCKFWObject_SetAttribute * */ NSS_EXTERN CK_RV -nssCKFWObject_SetAttribute -( - NSSCKFWObject *fwObject, - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value -); +nssCKFWObject_SetAttribute( + NSSCKFWObject *fwObject, + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value); /* * nssCKFWObject_GetObjectSize * */ NSS_EXTERN CK_ULONG -nssCKFWObject_GetObjectSize -( - NSSCKFWObject *fwObject, - CK_RV *pError -); +nssCKFWObject_GetObjectSize( + NSSCKFWObject *fwObject, + CK_RV *pError); /* * NSSCKFWFindObjects @@ -2328,47 +1967,39 @@ nssCKFWObject_GetObjectSize * */ NSS_EXTERN NSSCKFWFindObjects * -nssCKFWFindObjects_Create -( - NSSCKFWSession *fwSession, - NSSCKFWToken *fwToken, - NSSCKFWInstance *fwInstance, - NSSCKMDFindObjects *mdFindObjects1, - NSSCKMDFindObjects *mdFindObjects2, - CK_RV *pError -); +nssCKFWFindObjects_Create( + NSSCKFWSession *fwSession, + NSSCKFWToken *fwToken, + NSSCKFWInstance *fwInstance, + NSSCKMDFindObjects *mdFindObjects1, + NSSCKMDFindObjects *mdFindObjects2, + CK_RV *pError); /* * nssCKFWFindObjects_Destroy * */ NSS_EXTERN void -nssCKFWFindObjects_Destroy -( - NSSCKFWFindObjects *fwFindObjects -); +nssCKFWFindObjects_Destroy( + NSSCKFWFindObjects *fwFindObjects); /* * nssCKFWFindObjects_GetMDFindObjects * */ NSS_EXTERN NSSCKMDFindObjects * -nssCKFWFindObjects_GetMDFindObjects -( - NSSCKFWFindObjects *fwFindObjects -); +nssCKFWFindObjects_GetMDFindObjects( + NSSCKFWFindObjects *fwFindObjects); /* * nssCKFWFindObjects_Next * */ NSS_EXTERN NSSCKFWObject * -nssCKFWFindObjects_Next -( - NSSCKFWFindObjects *fwFindObjects, - NSSArena *arenaOpt, - CK_RV *pError -); +nssCKFWFindObjects_Next( + NSSCKFWFindObjects *fwFindObjects, + NSSArena *arenaOpt, + CK_RV *pError); /* * NSSCKFWMutex @@ -2385,42 +2016,34 @@ nssCKFWFindObjects_Next * */ NSS_EXTERN NSSCKFWMutex * -nssCKFWMutex_Create -( - CK_C_INITIALIZE_ARGS_PTR pInitArgs, - CryptokiLockingState LockingState, - NSSArena *arena, - CK_RV *pError -); +nssCKFWMutex_Create( + CK_C_INITIALIZE_ARGS_PTR pInitArgs, + CryptokiLockingState LockingState, + NSSArena *arena, + CK_RV *pError); /* * nssCKFWMutex_Destroy * */ NSS_EXTERN CK_RV -nssCKFWMutex_Destroy -( - NSSCKFWMutex *mutex -); +nssCKFWMutex_Destroy( + NSSCKFWMutex *mutex); /* * nssCKFWMutex_Lock * */ NSS_EXTERN CK_RV -nssCKFWMutex_Lock -( - NSSCKFWMutex *mutex -); +nssCKFWMutex_Lock( + NSSCKFWMutex *mutex); /* * nssCKFWMutex_Unlock * */ NSS_EXTERN CK_RV -nssCKFWMutex_Unlock -( - NSSCKFWMutex *mutex -); +nssCKFWMutex_Unlock( + NSSCKFWMutex *mutex); #endif /* CKFW_H */ diff --git a/security/nss/lib/ckfw/ckfwm.h b/security/nss/lib/ckfw/ckfwm.h index ed0aec31362b..7b14d209ea92 100644 --- a/security/nss/lib/ckfw/ckfwm.h +++ b/security/nss/lib/ckfw/ckfwm.h @@ -41,88 +41,72 @@ * */ NSS_EXTERN nssCKFWHash * -nssCKFWHash_Create -( - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -); +nssCKFWHash_Create( + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError); /* * nssCKFWHash_Destroy * */ NSS_EXTERN void -nssCKFWHash_Destroy -( - nssCKFWHash *hash -); +nssCKFWHash_Destroy( + nssCKFWHash *hash); /* * nssCKFWHash_Add * */ NSS_EXTERN CK_RV -nssCKFWHash_Add -( - nssCKFWHash *hash, - const void *key, - const void *value -); +nssCKFWHash_Add( + nssCKFWHash *hash, + const void *key, + const void *value); /* * nssCKFWHash_Remove * */ NSS_EXTERN void -nssCKFWHash_Remove -( - nssCKFWHash *hash, - const void *it -); +nssCKFWHash_Remove( + nssCKFWHash *hash, + const void *it); /* * nssCKFWHash_Count * */ NSS_EXTERN CK_ULONG -nssCKFWHash_Count -( - nssCKFWHash *hash -); +nssCKFWHash_Count( + nssCKFWHash *hash); /* * nssCKFWHash_Exists * */ NSS_EXTERN CK_BBOOL -nssCKFWHash_Exists -( - nssCKFWHash *hash, - const void *it -); +nssCKFWHash_Exists( + nssCKFWHash *hash, + const void *it); /* * nssCKFWHash_Lookup * */ NSS_EXTERN void * -nssCKFWHash_Lookup -( - nssCKFWHash *hash, - const void *it -); +nssCKFWHash_Lookup( + nssCKFWHash *hash, + const void *it); /* * nssCKFWHash_Iterate * */ NSS_EXTERN void -nssCKFWHash_Iterate -( - nssCKFWHash *hash, - nssCKFWHashIterator fcn, - void *closure -); +nssCKFWHash_Iterate( + nssCKFWHash *hash, + nssCKFWHashIterator fcn, + void *closure); #endif /* CKFWM_H */ diff --git a/security/nss/lib/ckfw/ckfwtm.h b/security/nss/lib/ckfw/ckfwtm.h index ac8f55080c13..6702984634cb 100644 --- a/security/nss/lib/ckfw/ckfwtm.h +++ b/security/nss/lib/ckfw/ckfwtm.h @@ -18,6 +18,6 @@ struct nssCKFWHashStr; typedef struct nssCKFWHashStr nssCKFWHash; -typedef void (PR_CALLBACK *nssCKFWHashIterator)(const void *key, void *value, void *closure); +typedef void(PR_CALLBACK *nssCKFWHashIterator)(const void *key, void *value, void *closure); #endif /* CKFWTM_H */ diff --git a/security/nss/lib/ckfw/ckmd.h b/security/nss/lib/ckfw/ckmd.h index 0a6dc907008c..820cf9021574 100644 --- a/security/nss/lib/ckfw/ckmd.h +++ b/security/nss/lib/ckfw/ckmd.h @@ -11,22 +11,18 @@ */ NSS_EXTERN NSSCKMDObject * -nssCKMDSessionObject_Create -( - NSSCKFWToken *fwToken, - NSSArena *arena, - CK_ATTRIBUTE_PTR attributes, - CK_ULONG ulCount, - CK_RV *pError -); +nssCKMDSessionObject_Create( + NSSCKFWToken *fwToken, + NSSArena *arena, + CK_ATTRIBUTE_PTR attributes, + CK_ULONG ulCount, + CK_RV *pError); NSS_EXTERN NSSCKMDFindObjects * -nssCKMDFindSessionObjects_Create -( - NSSCKFWToken *fwToken, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_RV *pError -); +nssCKMDFindSessionObjects_Create( + NSSCKFWToken *fwToken, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_RV *pError); #endif /* CKMD_H */ diff --git a/security/nss/lib/ckfw/crypto.c b/security/nss/lib/ckfw/crypto.c index d97cf6c3af24..66afb773a2f8 100644 --- a/security/nss/lib/ckfw/crypto.c +++ b/security/nss/lib/ckfw/crypto.c @@ -35,15 +35,15 @@ */ struct NSSCKFWCryptoOperationStr { - /* NSSArena *arena; */ - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - NSSCKFWSession *fwSession; - NSSCKMDToken *mdToken; - NSSCKFWToken *fwToken; - NSSCKMDInstance *mdInstance; - NSSCKFWInstance *fwInstance; - NSSCKFWCryptoOperationType type; + /* NSSArena *arena; */ + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + NSSCKFWSession *fwSession; + NSSCKMDToken *mdToken; + NSSCKFWToken *fwToken; + NSSCKMDInstance *mdInstance; + NSSCKFWInstance *fwInstance; + NSSCKFWCryptoOperationType type; }; /* @@ -51,290 +51,268 @@ struct NSSCKFWCryptoOperationStr { */ NSS_EXTERN NSSCKFWCryptoOperation * nssCKFWCryptoOperation_Create( - NSSCKMDCryptoOperation *mdOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKFWCryptoOperationType type, - CK_RV *pError -) + NSSCKMDCryptoOperation *mdOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKFWCryptoOperationType type, + CK_RV *pError) { - NSSCKFWCryptoOperation *fwOperation; - fwOperation = nss_ZNEW(NULL, NSSCKFWCryptoOperation); - if (!fwOperation) { - *pError = CKR_HOST_MEMORY; - return (NSSCKFWCryptoOperation *)NULL; - } - fwOperation->mdOperation = mdOperation; - fwOperation->mdSession = mdSession; - fwOperation->fwSession = fwSession; - fwOperation->mdToken = mdToken; - fwOperation->fwToken = fwToken; - fwOperation->mdInstance = mdInstance; - fwOperation->fwInstance = fwInstance; - fwOperation->type = type; - return fwOperation; + NSSCKFWCryptoOperation *fwOperation; + fwOperation = nss_ZNEW(NULL, NSSCKFWCryptoOperation); + if (!fwOperation) { + *pError = CKR_HOST_MEMORY; + return (NSSCKFWCryptoOperation *)NULL; + } + fwOperation->mdOperation = mdOperation; + fwOperation->mdSession = mdSession; + fwOperation->fwSession = fwSession; + fwOperation->mdToken = mdToken; + fwOperation->fwToken = fwToken; + fwOperation->mdInstance = mdInstance; + fwOperation->fwInstance = fwInstance; + fwOperation->type = type; + return fwOperation; } /* * nssCKFWCryptoOperation_Destroy */ NSS_EXTERN void -nssCKFWCryptoOperation_Destroy -( - NSSCKFWCryptoOperation *fwOperation -) +nssCKFWCryptoOperation_Destroy( + NSSCKFWCryptoOperation *fwOperation) { - if ((NSSCKMDCryptoOperation *) NULL != fwOperation->mdOperation) { - if (fwOperation->mdOperation->Destroy) { - fwOperation->mdOperation->Destroy( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdInstance, - fwOperation->fwInstance); + if ((NSSCKMDCryptoOperation *)NULL != fwOperation->mdOperation) { + if (fwOperation->mdOperation->Destroy) { + fwOperation->mdOperation->Destroy( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdInstance, + fwOperation->fwInstance); + } } - } - nss_ZFreeIf(fwOperation); + nss_ZFreeIf(fwOperation); } /* * nssCKFWCryptoOperation_GetMDCryptoOperation */ NSS_EXTERN NSSCKMDCryptoOperation * -nssCKFWCryptoOperation_GetMDCryptoOperation -( - NSSCKFWCryptoOperation *fwOperation -) +nssCKFWCryptoOperation_GetMDCryptoOperation( + NSSCKFWCryptoOperation *fwOperation) { - return fwOperation->mdOperation; + return fwOperation->mdOperation; } /* * nssCKFWCryptoOperation_GetType */ NSS_EXTERN NSSCKFWCryptoOperationType -nssCKFWCryptoOperation_GetType -( - NSSCKFWCryptoOperation *fwOperation -) +nssCKFWCryptoOperation_GetType( + NSSCKFWCryptoOperation *fwOperation) { - return fwOperation->type; + return fwOperation->type; } /* * nssCKFWCryptoOperation_GetFinalLength */ NSS_EXTERN CK_ULONG -nssCKFWCryptoOperation_GetFinalLength -( - NSSCKFWCryptoOperation *fwOperation, - CK_RV *pError -) +nssCKFWCryptoOperation_GetFinalLength( + NSSCKFWCryptoOperation *fwOperation, + CK_RV *pError) { - if (!fwOperation->mdOperation->GetFinalLength) { - *pError = CKR_FUNCTION_FAILED; - return 0; - } - return fwOperation->mdOperation->GetFinalLength( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdSession, - fwOperation->fwSession, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - pError); + if (!fwOperation->mdOperation->GetFinalLength) { + *pError = CKR_FUNCTION_FAILED; + return 0; + } + return fwOperation->mdOperation->GetFinalLength( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdSession, + fwOperation->fwSession, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + pError); } /* * nssCKFWCryptoOperation_GetOperationLength */ NSS_EXTERN CK_ULONG -nssCKFWCryptoOperation_GetOperationLength -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer, - CK_RV *pError -) +nssCKFWCryptoOperation_GetOperationLength( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer, + CK_RV *pError) { - if (!fwOperation->mdOperation->GetOperationLength) { - *pError = CKR_FUNCTION_FAILED; - return 0; - } - return fwOperation->mdOperation->GetOperationLength( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdSession, - fwOperation->fwSession, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - inputBuffer, - pError); + if (!fwOperation->mdOperation->GetOperationLength) { + *pError = CKR_FUNCTION_FAILED; + return 0; + } + return fwOperation->mdOperation->GetOperationLength( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdSession, + fwOperation->fwSession, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + inputBuffer, + pError); } /* * nssCKFWCryptoOperation_Final */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_Final -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *outputBuffer -) +nssCKFWCryptoOperation_Final( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *outputBuffer) { - if (!fwOperation->mdOperation->Final) { - return CKR_FUNCTION_FAILED; - } - return fwOperation->mdOperation->Final( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdSession, - fwOperation->fwSession, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - outputBuffer); + if (!fwOperation->mdOperation->Final) { + return CKR_FUNCTION_FAILED; + } + return fwOperation->mdOperation->Final( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdSession, + fwOperation->fwSession, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + outputBuffer); } /* * nssCKFWCryptoOperation_Update */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_Update -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer, - NSSItem *outputBuffer -) +nssCKFWCryptoOperation_Update( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer, + NSSItem *outputBuffer) { - if (!fwOperation->mdOperation->Update) { - return CKR_FUNCTION_FAILED; - } - return fwOperation->mdOperation->Update( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdSession, - fwOperation->fwSession, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - inputBuffer, - outputBuffer); + if (!fwOperation->mdOperation->Update) { + return CKR_FUNCTION_FAILED; + } + return fwOperation->mdOperation->Update( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdSession, + fwOperation->fwSession, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + inputBuffer, + outputBuffer); } /* * nssCKFWCryptoOperation_DigestUpdate */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_DigestUpdate -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer -) +nssCKFWCryptoOperation_DigestUpdate( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer) { - if (!fwOperation->mdOperation->DigestUpdate) { - return CKR_FUNCTION_FAILED; - } - return fwOperation->mdOperation->DigestUpdate( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdSession, - fwOperation->fwSession, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - inputBuffer); + if (!fwOperation->mdOperation->DigestUpdate) { + return CKR_FUNCTION_FAILED; + } + return fwOperation->mdOperation->DigestUpdate( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdSession, + fwOperation->fwSession, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + inputBuffer); } /* * nssCKFWCryptoOperation_DigestKey */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_DigestKey -( - NSSCKFWCryptoOperation *fwOperation, - NSSCKFWObject *fwObject /* Key */ -) +nssCKFWCryptoOperation_DigestKey( + NSSCKFWCryptoOperation *fwOperation, + NSSCKFWObject *fwObject /* Key */ + ) { - NSSCKMDObject *mdObject; + NSSCKMDObject *mdObject; - if (!fwOperation->mdOperation->DigestKey) { - return CKR_FUNCTION_FAILED; - } - mdObject = nssCKFWObject_GetMDObject(fwObject); - return fwOperation->mdOperation->DigestKey( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - mdObject, - fwObject); + if (!fwOperation->mdOperation->DigestKey) { + return CKR_FUNCTION_FAILED; + } + mdObject = nssCKFWObject_GetMDObject(fwObject); + return fwOperation->mdOperation->DigestKey( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + mdObject, + fwObject); } /* * nssCKFWCryptoOperation_UpdateFinal */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_UpdateFinal -( - NSSCKFWCryptoOperation *fwOperation, - NSSItem *inputBuffer, - NSSItem *outputBuffer -) +nssCKFWCryptoOperation_UpdateFinal( + NSSCKFWCryptoOperation *fwOperation, + NSSItem *inputBuffer, + NSSItem *outputBuffer) { - if (!fwOperation->mdOperation->UpdateFinal) { - return CKR_FUNCTION_FAILED; - } - return fwOperation->mdOperation->UpdateFinal( - fwOperation->mdOperation, - fwOperation, - fwOperation->mdSession, - fwOperation->fwSession, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - inputBuffer, - outputBuffer); + if (!fwOperation->mdOperation->UpdateFinal) { + return CKR_FUNCTION_FAILED; + } + return fwOperation->mdOperation->UpdateFinal( + fwOperation->mdOperation, + fwOperation, + fwOperation->mdSession, + fwOperation->fwSession, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + inputBuffer, + outputBuffer); } /* * nssCKFWCryptoOperation_UpdateCombo */ NSS_EXTERN CK_RV -nssCKFWCryptoOperation_UpdateCombo -( - NSSCKFWCryptoOperation *fwOperation, - NSSCKFWCryptoOperation *fwPeerOperation, - NSSItem *inputBuffer, - NSSItem *outputBuffer -) +nssCKFWCryptoOperation_UpdateCombo( + NSSCKFWCryptoOperation *fwOperation, + NSSCKFWCryptoOperation *fwPeerOperation, + NSSItem *inputBuffer, + NSSItem *outputBuffer) { - if (!fwOperation->mdOperation->UpdateCombo) { - return CKR_FUNCTION_FAILED; - } - return fwOperation->mdOperation->UpdateCombo( - fwOperation->mdOperation, - fwOperation, - fwPeerOperation->mdOperation, - fwPeerOperation, - fwOperation->mdSession, - fwOperation->fwSession, - fwOperation->mdToken, - fwOperation->fwToken, - fwOperation->mdInstance, - fwOperation->fwInstance, - inputBuffer, - outputBuffer); + if (!fwOperation->mdOperation->UpdateCombo) { + return CKR_FUNCTION_FAILED; + } + return fwOperation->mdOperation->UpdateCombo( + fwOperation->mdOperation, + fwOperation, + fwPeerOperation->mdOperation, + fwPeerOperation, + fwOperation->mdSession, + fwOperation->fwSession, + fwOperation->mdToken, + fwOperation->fwToken, + fwOperation->mdInstance, + fwOperation->fwInstance, + inputBuffer, + outputBuffer); } diff --git a/security/nss/lib/ckfw/dbm/anchor.c b/security/nss/lib/ckfw/dbm/anchor.c index f004b1e8439b..2ac7e96432eb 100644 --- a/security/nss/lib/ckfw/dbm/anchor.c +++ b/security/nss/lib/ckfw/dbm/anchor.c @@ -6,12 +6,12 @@ * dbm/anchor.c * * This file "anchors" the actual cryptoki entry points in this module's - * shared library, which is required for dynamic loading. See the + * shared library, which is required for dynamic loading. See the * comments in nssck.api for more information. */ #include "ckdbm.h" #define MODULE_NAME dbm -#define INSTANCE_NAME (NSSCKMDInstance *)&nss_dbm_mdInstance +#define INSTANCE_NAME (NSSCKMDInstance *) & nss_dbm_mdInstance #include "nssck.api" diff --git a/security/nss/lib/ckfw/dbm/ckdbm.h b/security/nss/lib/ckfw/dbm/ckdbm.h index 4f9df9343e14..8c2607cb3559 100644 --- a/security/nss/lib/ckfw/dbm/ckdbm.h +++ b/security/nss/lib/ckfw/dbm/ckdbm.h @@ -29,220 +29,182 @@ NSS_EXTERN_DATA NSSCKMDInstance nss_dbm_mdInstance; typedef struct nss_dbm_db_struct nss_dbm_db_t; struct nss_dbm_db_struct { - DB *db; - NSSCKFWMutex *crustylock; + DB *db; + NSSCKFWMutex *crustylock; }; typedef struct nss_dbm_dbt_struct nss_dbm_dbt_t; struct nss_dbm_dbt_struct { - DBT dbt; - nss_dbm_db_t *my_db; + DBT dbt; + nss_dbm_db_t *my_db; }; typedef struct nss_dbm_instance_struct nss_dbm_instance_t; struct nss_dbm_instance_struct { - NSSArena *arena; - CK_ULONG nSlots; - char **filenames; - int *flags; /* e.g. O_RDONLY, O_RDWR */ + NSSArena *arena; + CK_ULONG nSlots; + char **filenames; + int *flags; /* e.g. O_RDONLY, O_RDWR */ }; typedef struct nss_dbm_slot_struct nss_dbm_slot_t; struct nss_dbm_slot_struct { - nss_dbm_instance_t *instance; - char *filename; - int flags; - nss_dbm_db_t *token_db; + nss_dbm_instance_t *instance; + char *filename; + int flags; + nss_dbm_db_t *token_db; }; typedef struct nss_dbm_token_struct nss_dbm_token_t; struct nss_dbm_token_struct { - NSSArena *arena; - nss_dbm_slot_t *slot; - nss_dbm_db_t *session_db; - NSSUTF8 *label; + NSSArena *arena; + nss_dbm_slot_t *slot; + nss_dbm_db_t *session_db; + NSSUTF8 *label; }; struct nss_dbm_dbt_node { - struct nss_dbm_dbt_node *next; - nss_dbm_dbt_t *dbt; + struct nss_dbm_dbt_node *next; + nss_dbm_dbt_t *dbt; }; typedef struct nss_dbm_session_struct nss_dbm_session_t; struct nss_dbm_session_struct { - NSSArena *arena; - nss_dbm_token_t *token; - CK_ULONG deviceError; - struct nss_dbm_dbt_node *session_objects; - NSSCKFWMutex *list_lock; + NSSArena *arena; + nss_dbm_token_t *token; + CK_ULONG deviceError; + struct nss_dbm_dbt_node *session_objects; + NSSCKFWMutex *list_lock; }; typedef struct nss_dbm_object_struct nss_dbm_object_t; struct nss_dbm_object_struct { - NSSArena *arena; /* token or session */ - nss_dbm_dbt_t *handle; + NSSArena *arena; /* token or session */ + nss_dbm_dbt_t *handle; }; typedef struct nss_dbm_find_struct nss_dbm_find_t; struct nss_dbm_find_struct { - NSSArena *arena; - struct nss_dbm_dbt_node *found; - NSSCKFWMutex *list_lock; + NSSArena *arena; + struct nss_dbm_dbt_node *found; + NSSCKFWMutex *list_lock; }; NSS_EXTERN NSSCKMDSlot * -nss_dbm_mdSlot_factory -( - nss_dbm_instance_t *instance, - char *filename, - int flags, - CK_RV *pError -); +nss_dbm_mdSlot_factory( + nss_dbm_instance_t *instance, + char *filename, + int flags, + CK_RV *pError); NSS_EXTERN NSSCKMDToken * -nss_dbm_mdToken_factory -( - nss_dbm_slot_t *slot, - CK_RV *pError -); +nss_dbm_mdToken_factory( + nss_dbm_slot_t *slot, + CK_RV *pError); NSS_EXTERN NSSCKMDSession * -nss_dbm_mdSession_factory -( - nss_dbm_token_t *token, - NSSCKFWSession *fwSession, - NSSCKFWInstance *fwInstance, - CK_BBOOL rw, - CK_RV *pError -); +nss_dbm_mdSession_factory( + nss_dbm_token_t *token, + NSSCKFWSession *fwSession, + NSSCKFWInstance *fwInstance, + CK_BBOOL rw, + CK_RV *pError); NSS_EXTERN NSSCKMDObject * -nss_dbm_mdObject_factory -( - nss_dbm_object_t *object, - CK_RV *pError -); +nss_dbm_mdObject_factory( + nss_dbm_object_t *object, + CK_RV *pError); NSS_EXTERN NSSCKMDFindObjects * -nss_dbm_mdFindObjects_factory -( - nss_dbm_find_t *find, - CK_RV *pError -); +nss_dbm_mdFindObjects_factory( + nss_dbm_find_t *find, + CK_RV *pError); NSS_EXTERN nss_dbm_db_t * -nss_dbm_db_open -( - NSSArena *arena, - NSSCKFWInstance *fwInstance, - char *filename, - int flags, - CK_RV *pError -); +nss_dbm_db_open( + NSSArena *arena, + NSSCKFWInstance *fwInstance, + char *filename, + int flags, + CK_RV *pError); NSS_EXTERN void -nss_dbm_db_close -( - nss_dbm_db_t *db -); +nss_dbm_db_close( + nss_dbm_db_t *db); NSS_EXTERN CK_VERSION -nss_dbm_db_get_format_version -( - nss_dbm_db_t *db -); +nss_dbm_db_get_format_version( + nss_dbm_db_t *db); NSS_EXTERN CK_RV -nss_dbm_db_set_label -( - nss_dbm_db_t *db, - NSSUTF8 *label -); +nss_dbm_db_set_label( + nss_dbm_db_t *db, + NSSUTF8 *label); NSS_EXTERN NSSUTF8 * -nss_dbm_db_get_label -( - nss_dbm_db_t *db, - NSSArena *arena, - CK_RV *pError -); +nss_dbm_db_get_label( + nss_dbm_db_t *db, + NSSArena *arena, + CK_RV *pError); NSS_EXTERN CK_RV -nss_dbm_db_delete_object -( - nss_dbm_dbt_t *dbt -); +nss_dbm_db_delete_object( + nss_dbm_dbt_t *dbt); NSS_EXTERN nss_dbm_dbt_t * -nss_dbm_db_create_object -( - NSSArena *arena, - nss_dbm_db_t *db, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError, - CK_ULONG *pdbrv -); +nss_dbm_db_create_object( + NSSArena *arena, + nss_dbm_db_t *db, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError, + CK_ULONG *pdbrv); NSS_EXTERN CK_RV -nss_dbm_db_find_objects -( - nss_dbm_find_t *find, - nss_dbm_db_t *db, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_ULONG *pdbrv -); +nss_dbm_db_find_objects( + nss_dbm_find_t *find, + nss_dbm_db_t *db, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_ULONG *pdbrv); NSS_EXTERN CK_BBOOL -nss_dbm_db_object_still_exists -( - nss_dbm_dbt_t *dbt -); +nss_dbm_db_object_still_exists( + nss_dbm_dbt_t *dbt); NSS_EXTERN CK_ULONG -nss_dbm_db_get_object_attribute_count -( - nss_dbm_dbt_t *dbt, - CK_RV *pError, - CK_ULONG *pdbrv -); +nss_dbm_db_get_object_attribute_count( + nss_dbm_dbt_t *dbt, + CK_RV *pError, + CK_ULONG *pdbrv); NSS_EXTERN CK_RV -nss_dbm_db_get_object_attribute_types -( - nss_dbm_dbt_t *dbt, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount, - CK_ULONG *pdbrv -); +nss_dbm_db_get_object_attribute_types( + nss_dbm_dbt_t *dbt, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount, + CK_ULONG *pdbrv); NSS_EXTERN CK_ULONG -nss_dbm_db_get_object_attribute_size -( - nss_dbm_dbt_t *dbt, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError, - CK_ULONG *pdbrv -); +nss_dbm_db_get_object_attribute_size( + nss_dbm_dbt_t *dbt, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError, + CK_ULONG *pdbrv); NSS_EXTERN NSSItem * -nss_dbm_db_get_object_attribute -( - nss_dbm_dbt_t *dbt, - NSSArena *arena, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError, - CK_ULONG *pdbrv -); +nss_dbm_db_get_object_attribute( + nss_dbm_dbt_t *dbt, + NSSArena *arena, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError, + CK_ULONG *pdbrv); NSS_EXTERN CK_RV -nss_dbm_db_set_object_attribute -( - nss_dbm_dbt_t *dbt, - CK_ATTRIBUTE_TYPE type, - NSSItem *value, - CK_ULONG *pdbrv -); +nss_dbm_db_set_object_attribute( + nss_dbm_dbt_t *dbt, + CK_ATTRIBUTE_TYPE type, + NSSItem *value, + CK_ULONG *pdbrv); #endif /* CKDBM_H */ diff --git a/security/nss/lib/ckfw/dbm/db.c b/security/nss/lib/ckfw/dbm/db.c index 8d0a6cba8d8c..44b47e7f3d24 100644 --- a/security/nss/lib/ckfw/dbm/db.c +++ b/security/nss/lib/ckfw/dbm/db.c @@ -5,303 +5,294 @@ #include "ckdbm.h" #define PREFIX_METADATA "0000" -#define PREFIX_OBJECT "0001" -#define PREFIX_INDEX "0002" +#define PREFIX_OBJECT "0001" +#define PREFIX_INDEX "0002" static CK_VERSION nss_dbm_db_format_version = { 1, 0 }; struct handle { - char prefix[4]; - CK_ULONG id; + char prefix[4]; + CK_ULONG id; }; NSS_IMPLEMENT nss_dbm_db_t * -nss_dbm_db_open -( - NSSArena *arena, - NSSCKFWInstance *fwInstance, - char *filename, - int flags, - CK_RV *pError -) +nss_dbm_db_open( + NSSArena *arena, + NSSCKFWInstance *fwInstance, + char *filename, + int flags, + CK_RV *pError) { - nss_dbm_db_t *rv; - CK_VERSION db_version; + nss_dbm_db_t *rv; + CK_VERSION db_version; - rv = nss_ZNEW(arena, nss_dbm_db_t); - if( (nss_dbm_db_t *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (nss_dbm_db_t *)NULL; - } + rv = nss_ZNEW(arena, nss_dbm_db_t); + if ((nss_dbm_db_t *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (nss_dbm_db_t *)NULL; + } - rv->db = dbopen(filename, flags, 0600, DB_HASH, (const void *)NULL); - if( (DB *)NULL == rv->db ) { - *pError = CKR_TOKEN_NOT_PRESENT; - return (nss_dbm_db_t *)NULL; - } + rv->db = dbopen(filename, flags, 0600, DB_HASH, (const void *)NULL); + if ((DB *)NULL == rv->db) { + *pError = CKR_TOKEN_NOT_PRESENT; + return (nss_dbm_db_t *)NULL; + } - rv->crustylock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError); - if( (NSSCKFWMutex *)NULL == rv->crustylock ) { - return (nss_dbm_db_t *)NULL; - } + rv->crustylock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError); + if ((NSSCKFWMutex *)NULL == rv->crustylock) { + return (nss_dbm_db_t *)NULL; + } - db_version = nss_dbm_db_get_format_version(rv); - if( db_version.major != nss_dbm_db_format_version.major ) { - nss_dbm_db_close(rv); - *pError = CKR_TOKEN_NOT_RECOGNIZED; - return (nss_dbm_db_t *)NULL; - } + db_version = nss_dbm_db_get_format_version(rv); + if (db_version.major != nss_dbm_db_format_version.major) { + nss_dbm_db_close(rv); + *pError = CKR_TOKEN_NOT_RECOGNIZED; + return (nss_dbm_db_t *)NULL; + } - return rv; + return rv; } NSS_IMPLEMENT void -nss_dbm_db_close -( - nss_dbm_db_t *db -) +nss_dbm_db_close( + nss_dbm_db_t *db) { - if( (NSSCKFWMutex *)NULL != db->crustylock ) { - (void)NSSCKFWMutex_Destroy(db->crustylock); - } + if ((NSSCKFWMutex *)NULL != db->crustylock) { + (void)NSSCKFWMutex_Destroy(db->crustylock); + } - if( (DB *)NULL != db->db ) { - (void)db->db->close(db->db); - } + if ((DB *)NULL != db->db) { + (void)db->db->close(db->db); + } - nss_ZFreeIf(db); + nss_ZFreeIf(db); } NSS_IMPLEMENT CK_VERSION -nss_dbm_db_get_format_version -( - nss_dbm_db_t *db -) +nss_dbm_db_get_format_version( + nss_dbm_db_t *db) { - CK_VERSION rv; - DBT k, v; - int dbrv; - char buffer[64]; + CK_VERSION rv; + DBT k, v; + int dbrv; + char buffer[64]; - rv.major = rv.minor = 0; + rv.major = rv.minor = 0; - k.data = PREFIX_METADATA "FormatVersion"; - k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL); - (void)memset(&v, 0, sizeof(v)); - - /* Locked region */ - { - if( CKR_OK != NSSCKFWMutex_Lock(db->crustylock) ) { - return rv; - } - - dbrv = db->db->get(db->db, &k, &v, 0); - if( dbrv == 0 ) { - CK_ULONG major = 0, minor = 0; - (void)PR_sscanf(v.data, "%ld.%ld", &major, &minor); - rv.major = major; - rv.minor = minor; - } else if( dbrv > 0 ) { - (void)PR_snprintf(buffer, sizeof(buffer), "%ld.%ld", nss_dbm_db_format_version.major, - nss_dbm_db_format_version.minor); - v.data = buffer; - v.size = nssUTF8_Size((NSSUTF8 *)v.data, (PRStatus *)NULL); - dbrv = db->db->put(db->db, &k, &v, 0); - (void)db->db->sync(db->db, 0); - rv = nss_dbm_db_format_version; - } else { - /* No error return.. */ - ; - } - - (void)NSSCKFWMutex_Unlock(db->crustylock); - } - - return rv; -} - -NSS_IMPLEMENT CK_RV -nss_dbm_db_set_label -( - nss_dbm_db_t *db, - NSSUTF8 *label -) -{ - CK_RV rv; - DBT k, v; - int dbrv; - - k.data = PREFIX_METADATA "Label"; - k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL); - v.data = label; - v.size = nssUTF8_Size((NSSUTF8 *)v.data, (PRStatus *)NULL); - - /* Locked region */ - { - rv = NSSCKFWMutex_Lock(db->crustylock); - if( CKR_OK != rv ) { - return rv; - } - - dbrv = db->db->put(db->db, &k, &v, 0); - if( 0 != dbrv ) { - rv = CKR_DEVICE_ERROR; - } - - dbrv = db->db->sync(db->db, 0); - if( 0 != dbrv ) { - rv = CKR_DEVICE_ERROR; - } - - (void)NSSCKFWMutex_Unlock(db->crustylock); - } - - return rv; -} - -NSS_IMPLEMENT NSSUTF8 * -nss_dbm_db_get_label -( - nss_dbm_db_t *db, - NSSArena *arena, - CK_RV *pError -) -{ - NSSUTF8 *rv = (NSSUTF8 *)NULL; - DBT k, v; - int dbrv; - - k.data = PREFIX_METADATA "Label"; - k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL); - - /* Locked region */ - { - if( CKR_OK != NSSCKFWMutex_Lock(db->crustylock) ) { - return rv; - } - - dbrv = db->db->get(db->db, &k, &v, 0); - if( 0 == dbrv ) { - rv = nssUTF8_Duplicate((NSSUTF8 *)v.data, arena); - if( (NSSUTF8 *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - } - } else if( dbrv > 0 ) { - /* Just return null */ - ; - } else { - *pError = CKR_DEVICE_ERROR; - ; - } - - - (void)NSSCKFWMutex_Unlock(db->crustylock); - } - - return rv; -} - -NSS_IMPLEMENT CK_RV -nss_dbm_db_delete_object -( - nss_dbm_dbt_t *dbt -) -{ - CK_RV rv; - int dbrv; - - /* Locked region */ - { - rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); - if( CKR_OK != rv ) { - return rv; - } - - dbrv = dbt->my_db->db->del(dbt->my_db->db, &dbt->dbt, 0); - if( 0 != dbrv ) { - rv = CKR_DEVICE_ERROR; - goto done; - } - - dbrv = dbt->my_db->db->sync(dbt->my_db->db, 0); - if( 0 != dbrv ) { - rv = CKR_DEVICE_ERROR; - goto done; - } - - done: - (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); - } - - return rv; -} - -static CK_ULONG -nss_dbm_db_new_handle -( - nss_dbm_db_t *db, - DBT *dbt, /* pre-allocated */ - CK_RV *pError -) -{ - CK_ULONG rv; - DBT k, v; - CK_ULONG align = 0, id, myid; - struct handle *hp; - - if( sizeof(struct handle) != dbt->size ) { - return EINVAL; - } - - /* Locked region */ - { - *pError = NSSCKFWMutex_Lock(db->crustylock); - if( CKR_OK != *pError ) { - return EINVAL; - } - - k.data = PREFIX_METADATA "LastID"; + k.data = PREFIX_METADATA "FormatVersion"; k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL); (void)memset(&v, 0, sizeof(v)); - rv = db->db->get(db->db, &k, &v, 0); - if( 0 == rv ) { - (void)memcpy(&align, v.data, sizeof(CK_ULONG)); - id = ntohl(align); - } else if( rv > 0 ) { - id = 0; - } else { - goto done; + /* Locked region */ + { + if (CKR_OK != NSSCKFWMutex_Lock(db->crustylock)) { + return rv; + } + + dbrv = db->db->get(db->db, &k, &v, 0); + if (dbrv == 0) { + CK_ULONG major = 0, minor = 0; + (void)PR_sscanf(v.data, "%ld.%ld", &major, &minor); + rv.major = major; + rv.minor = minor; + } + else if (dbrv > 0) { + (void)PR_snprintf(buffer, sizeof(buffer), "%ld.%ld", nss_dbm_db_format_version.major, + nss_dbm_db_format_version.minor); + v.data = buffer; + v.size = nssUTF8_Size((NSSUTF8 *)v.data, (PRStatus *)NULL); + dbrv = db->db->put(db->db, &k, &v, 0); + (void)db->db->sync(db->db, 0); + rv = nss_dbm_db_format_version; + } + else { + /* No error return.. */ + ; + } + + (void)NSSCKFWMutex_Unlock(db->crustylock); } - myid = id; - id++; - align = htonl(id); - v.data = &align; - v.size = sizeof(CK_ULONG); - - rv = db->db->put(db->db, &k, &v, 0); - if( 0 != rv ) { - goto done; - } - - rv = db->db->sync(db->db, 0); - if( 0 != rv ) { - goto done; - } - - done: - (void)NSSCKFWMutex_Unlock(db->crustylock); - } - - if( 0 != rv ) { return rv; - } +} - hp = (struct handle *)dbt->data; - (void)memcpy(&hp->prefix[0], PREFIX_OBJECT, 4); - hp->id = myid; +NSS_IMPLEMENT CK_RV +nss_dbm_db_set_label( + nss_dbm_db_t *db, + NSSUTF8 *label) +{ + CK_RV rv; + DBT k, v; + int dbrv; - return 0; + k.data = PREFIX_METADATA "Label"; + k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL); + v.data = label; + v.size = nssUTF8_Size((NSSUTF8 *)v.data, (PRStatus *)NULL); + + /* Locked region */ + { + rv = NSSCKFWMutex_Lock(db->crustylock); + if (CKR_OK != rv) { + return rv; + } + + dbrv = db->db->put(db->db, &k, &v, 0); + if (0 != dbrv) { + rv = CKR_DEVICE_ERROR; + } + + dbrv = db->db->sync(db->db, 0); + if (0 != dbrv) { + rv = CKR_DEVICE_ERROR; + } + + (void)NSSCKFWMutex_Unlock(db->crustylock); + } + + return rv; +} + +NSS_IMPLEMENT NSSUTF8 * +nss_dbm_db_get_label( + nss_dbm_db_t *db, + NSSArena *arena, + CK_RV *pError) +{ + NSSUTF8 *rv = (NSSUTF8 *)NULL; + DBT k, v; + int dbrv; + + k.data = PREFIX_METADATA "Label"; + k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL); + + /* Locked region */ + { + if (CKR_OK != NSSCKFWMutex_Lock(db->crustylock)) { + return rv; + } + + dbrv = db->db->get(db->db, &k, &v, 0); + if (0 == dbrv) { + rv = nssUTF8_Duplicate((NSSUTF8 *)v.data, arena); + if ((NSSUTF8 *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + } + } + else if (dbrv > 0) { + /* Just return null */ + ; + } + else { + *pError = CKR_DEVICE_ERROR; + ; + } + + (void)NSSCKFWMutex_Unlock(db->crustylock); + } + + return rv; +} + +NSS_IMPLEMENT CK_RV +nss_dbm_db_delete_object( + nss_dbm_dbt_t *dbt) +{ + CK_RV rv; + int dbrv; + + /* Locked region */ + { + rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); + if (CKR_OK != rv) { + return rv; + } + + dbrv = dbt->my_db->db->del(dbt->my_db->db, &dbt->dbt, 0); + if (0 != dbrv) { + rv = CKR_DEVICE_ERROR; + goto done; + } + + dbrv = dbt->my_db->db->sync(dbt->my_db->db, 0); + if (0 != dbrv) { + rv = CKR_DEVICE_ERROR; + goto done; + } + + done: + (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); + } + + return rv; +} + +static CK_ULONG +nss_dbm_db_new_handle( + nss_dbm_db_t *db, + DBT *dbt, /* pre-allocated */ + CK_RV *pError) +{ + CK_ULONG rv; + DBT k, v; + CK_ULONG align = 0, id, myid; + struct handle *hp; + + if (sizeof(struct handle) != dbt->size) { + return EINVAL; + } + + /* Locked region */ + { + *pError = NSSCKFWMutex_Lock(db->crustylock); + if (CKR_OK != *pError) { + return EINVAL; + } + + k.data = PREFIX_METADATA "LastID"; + k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL); + (void)memset(&v, 0, sizeof(v)); + + rv = db->db->get(db->db, &k, &v, 0); + if (0 == rv) { + (void)memcpy(&align, v.data, sizeof(CK_ULONG)); + id = ntohl(align); + } + else if (rv > 0) { + id = 0; + } + else { + goto done; + } + + myid = id; + id++; + align = htonl(id); + v.data = &align; + v.size = sizeof(CK_ULONG); + + rv = db->db->put(db->db, &k, &v, 0); + if (0 != rv) { + goto done; + } + + rv = db->db->sync(db->db, 0); + if (0 != rv) { + goto done; + } + + done: + (void)NSSCKFWMutex_Unlock(db->crustylock); + } + + if (0 != rv) { + return rv; + } + + hp = (struct handle *)dbt->data; + (void)memcpy(&hp->prefix[0], PREFIX_OBJECT, 4); + hp->id = myid; + + return 0; } /* @@ -311,723 +302,786 @@ nss_dbm_db_new_handle * will have to be augmentable or overridable by a Module. */ -enum swap_type { type_byte, type_short, type_long, type_opaque }; +enum swap_type { type_byte, + type_short, + type_long, + type_opaque }; static enum swap_type -nss_dbm_db_swap_type -( - CK_ATTRIBUTE_TYPE type -) +nss_dbm_db_swap_type( + CK_ATTRIBUTE_TYPE type) { - switch( type ) { - case CKA_CLASS: return type_long; - case CKA_TOKEN: return type_byte; - case CKA_PRIVATE: return type_byte; - case CKA_LABEL: return type_opaque; - case CKA_APPLICATION: return type_opaque; - case CKA_VALUE: return type_opaque; - case CKA_CERTIFICATE_TYPE: return type_long; - case CKA_ISSUER: return type_opaque; - case CKA_SERIAL_NUMBER: return type_opaque; - case CKA_KEY_TYPE: return type_long; - case CKA_SUBJECT: return type_opaque; - case CKA_ID: return type_opaque; - case CKA_SENSITIVE: return type_byte; - case CKA_ENCRYPT: return type_byte; - case CKA_DECRYPT: return type_byte; - case CKA_WRAP: return type_byte; - case CKA_UNWRAP: return type_byte; - case CKA_SIGN: return type_byte; - case CKA_SIGN_RECOVER: return type_byte; - case CKA_VERIFY: return type_byte; - case CKA_VERIFY_RECOVER: return type_byte; - case CKA_DERIVE: return type_byte; - case CKA_START_DATE: return type_opaque; - case CKA_END_DATE: return type_opaque; - case CKA_MODULUS: return type_opaque; - case CKA_MODULUS_BITS: return type_long; - case CKA_PUBLIC_EXPONENT: return type_opaque; - case CKA_PRIVATE_EXPONENT: return type_opaque; - case CKA_PRIME_1: return type_opaque; - case CKA_PRIME_2: return type_opaque; - case CKA_EXPONENT_1: return type_opaque; - case CKA_EXPONENT_2: return type_opaque; - case CKA_COEFFICIENT: return type_opaque; - case CKA_PRIME: return type_opaque; - case CKA_SUBPRIME: return type_opaque; - case CKA_BASE: return type_opaque; - case CKA_VALUE_BITS: return type_long; - case CKA_VALUE_LEN: return type_long; - case CKA_EXTRACTABLE: return type_byte; - case CKA_LOCAL: return type_byte; - case CKA_NEVER_EXTRACTABLE: return type_byte; - case CKA_ALWAYS_SENSITIVE: return type_byte; - case CKA_MODIFIABLE: return type_byte; - case CKA_NETSCAPE_URL: return type_opaque; - case CKA_NETSCAPE_EMAIL: return type_opaque; - case CKA_NETSCAPE_SMIME_INFO: return type_opaque; - case CKA_NETSCAPE_SMIME_TIMESTAMP: return type_opaque; - case CKA_NETSCAPE_PKCS8_SALT: return type_opaque; - case CKA_NETSCAPE_PASSWORD_CHECK: return type_opaque; - case CKA_NETSCAPE_EXPIRES: return type_opaque; - case CKA_TRUST_DIGITAL_SIGNATURE: return type_long; - case CKA_TRUST_NON_REPUDIATION: return type_long; - case CKA_TRUST_KEY_ENCIPHERMENT: return type_long; - case CKA_TRUST_DATA_ENCIPHERMENT: return type_long; - case CKA_TRUST_KEY_AGREEMENT: return type_long; - case CKA_TRUST_KEY_CERT_SIGN: return type_long; - case CKA_TRUST_CRL_SIGN: return type_long; - case CKA_TRUST_SERVER_AUTH: return type_long; - case CKA_TRUST_CLIENT_AUTH: return type_long; - case CKA_TRUST_CODE_SIGNING: return type_long; - case CKA_TRUST_EMAIL_PROTECTION: return type_long; - case CKA_TRUST_IPSEC_END_SYSTEM: return type_long; - case CKA_TRUST_IPSEC_TUNNEL: return type_long; - case CKA_TRUST_IPSEC_USER: return type_long; - case CKA_TRUST_TIME_STAMPING: return type_long; - case CKA_NETSCAPE_DB: return type_opaque; - case CKA_NETSCAPE_TRUST: return type_opaque; - default: return type_opaque; - } + switch (type) { + case CKA_CLASS: + return type_long; + case CKA_TOKEN: + return type_byte; + case CKA_PRIVATE: + return type_byte; + case CKA_LABEL: + return type_opaque; + case CKA_APPLICATION: + return type_opaque; + case CKA_VALUE: + return type_opaque; + case CKA_CERTIFICATE_TYPE: + return type_long; + case CKA_ISSUER: + return type_opaque; + case CKA_SERIAL_NUMBER: + return type_opaque; + case CKA_KEY_TYPE: + return type_long; + case CKA_SUBJECT: + return type_opaque; + case CKA_ID: + return type_opaque; + case CKA_SENSITIVE: + return type_byte; + case CKA_ENCRYPT: + return type_byte; + case CKA_DECRYPT: + return type_byte; + case CKA_WRAP: + return type_byte; + case CKA_UNWRAP: + return type_byte; + case CKA_SIGN: + return type_byte; + case CKA_SIGN_RECOVER: + return type_byte; + case CKA_VERIFY: + return type_byte; + case CKA_VERIFY_RECOVER: + return type_byte; + case CKA_DERIVE: + return type_byte; + case CKA_START_DATE: + return type_opaque; + case CKA_END_DATE: + return type_opaque; + case CKA_MODULUS: + return type_opaque; + case CKA_MODULUS_BITS: + return type_long; + case CKA_PUBLIC_EXPONENT: + return type_opaque; + case CKA_PRIVATE_EXPONENT: + return type_opaque; + case CKA_PRIME_1: + return type_opaque; + case CKA_PRIME_2: + return type_opaque; + case CKA_EXPONENT_1: + return type_opaque; + case CKA_EXPONENT_2: + return type_opaque; + case CKA_COEFFICIENT: + return type_opaque; + case CKA_PRIME: + return type_opaque; + case CKA_SUBPRIME: + return type_opaque; + case CKA_BASE: + return type_opaque; + case CKA_VALUE_BITS: + return type_long; + case CKA_VALUE_LEN: + return type_long; + case CKA_EXTRACTABLE: + return type_byte; + case CKA_LOCAL: + return type_byte; + case CKA_NEVER_EXTRACTABLE: + return type_byte; + case CKA_ALWAYS_SENSITIVE: + return type_byte; + case CKA_MODIFIABLE: + return type_byte; + case CKA_NETSCAPE_URL: + return type_opaque; + case CKA_NETSCAPE_EMAIL: + return type_opaque; + case CKA_NETSCAPE_SMIME_INFO: + return type_opaque; + case CKA_NETSCAPE_SMIME_TIMESTAMP: + return type_opaque; + case CKA_NETSCAPE_PKCS8_SALT: + return type_opaque; + case CKA_NETSCAPE_PASSWORD_CHECK: + return type_opaque; + case CKA_NETSCAPE_EXPIRES: + return type_opaque; + case CKA_TRUST_DIGITAL_SIGNATURE: + return type_long; + case CKA_TRUST_NON_REPUDIATION: + return type_long; + case CKA_TRUST_KEY_ENCIPHERMENT: + return type_long; + case CKA_TRUST_DATA_ENCIPHERMENT: + return type_long; + case CKA_TRUST_KEY_AGREEMENT: + return type_long; + case CKA_TRUST_KEY_CERT_SIGN: + return type_long; + case CKA_TRUST_CRL_SIGN: + return type_long; + case CKA_TRUST_SERVER_AUTH: + return type_long; + case CKA_TRUST_CLIENT_AUTH: + return type_long; + case CKA_TRUST_CODE_SIGNING: + return type_long; + case CKA_TRUST_EMAIL_PROTECTION: + return type_long; + case CKA_TRUST_IPSEC_END_SYSTEM: + return type_long; + case CKA_TRUST_IPSEC_TUNNEL: + return type_long; + case CKA_TRUST_IPSEC_USER: + return type_long; + case CKA_TRUST_TIME_STAMPING: + return type_long; + case CKA_NETSCAPE_DB: + return type_opaque; + case CKA_NETSCAPE_TRUST: + return type_opaque; + default: + return type_opaque; + } } static void -nss_dbm_db_swap_copy -( - CK_ATTRIBUTE_TYPE type, - void *dest, - void *src, - CK_ULONG len -) +nss_dbm_db_swap_copy( + CK_ATTRIBUTE_TYPE type, + void *dest, + void *src, + CK_ULONG len) { - switch( nss_dbm_db_swap_type(type) ) { - case type_byte: - case type_opaque: - (void)memcpy(dest, src, len); - break; - case type_short: - { - CK_USHORT s, d; - (void)memcpy(&s, src, sizeof(CK_USHORT)); - d = htons(s); - (void)memcpy(dest, &d, sizeof(CK_USHORT)); - break; + switch (nss_dbm_db_swap_type(type)) { + case type_byte: + case type_opaque: + (void)memcpy(dest, src, len); + break; + case type_short: { + CK_USHORT s, d; + (void)memcpy(&s, src, sizeof(CK_USHORT)); + d = htons(s); + (void)memcpy(dest, &d, sizeof(CK_USHORT)); + break; + } + case type_long: { + CK_ULONG s, d; + (void)memcpy(&s, src, sizeof(CK_ULONG)); + d = htonl(s); + (void)memcpy(dest, &d, sizeof(CK_ULONG)); + break; + } } - case type_long: - { - CK_ULONG s, d; - (void)memcpy(&s, src, sizeof(CK_ULONG)); - d = htonl(s); - (void)memcpy(dest, &d, sizeof(CK_ULONG)); - break; - } - } } static CK_RV -nss_dbm_db_wrap_object -( - NSSArena *arena, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - DBT *object -) +nss_dbm_db_wrap_object( + NSSArena *arena, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + DBT *object) { - CK_ULONG object_size; - CK_ULONG i; - CK_ULONG *pulData; - char *pcData; - CK_ULONG offset; - - object_size = (1 + ulAttributeCount*3) * sizeof(CK_ULONG); - offset = object_size; - for( i = 0; i < ulAttributeCount; i++ ) { - object_size += pTemplate[i].ulValueLen; - } - - object->size = object_size; - object->data = nss_ZAlloc(arena, object_size); - if( (void *)NULL == object->data ) { - return CKR_HOST_MEMORY; - } - - pulData = (CK_ULONG *)object->data; - pcData = (char *)object->data; - - pulData[0] = htonl(ulAttributeCount); - for( i = 0; i < ulAttributeCount; i++ ) { - CK_ULONG len = pTemplate[i].ulValueLen; - pulData[1 + i*3] = htonl(pTemplate[i].type); - pulData[2 + i*3] = htonl(len); - pulData[3 + i*3] = htonl(offset); - nss_dbm_db_swap_copy(pTemplate[i].type, &pcData[offset], pTemplate[i].pValue, len); - offset += len; - } - - return CKR_OK; -} - -static CK_RV -nss_dbm_db_unwrap_object -( - NSSArena *arena, - DBT *object, - CK_ATTRIBUTE_PTR *ppTemplate, - CK_ULONG *pulAttributeCount -) -{ - CK_ULONG *pulData; - char *pcData; - CK_ULONG n, i; - CK_ATTRIBUTE_PTR pTemplate; - - pulData = (CK_ULONG *)object->data; - pcData = (char *)object->data; - - n = ntohl(pulData[0]); - *pulAttributeCount = n; - pTemplate = nss_ZNEWARRAY(arena, CK_ATTRIBUTE, n); - if( (CK_ATTRIBUTE_PTR)NULL == pTemplate ) { - return CKR_HOST_MEMORY; - } - - for( i = 0; i < n; i++ ) { - CK_ULONG len; + CK_ULONG object_size; + CK_ULONG i; + CK_ULONG *pulData; + char *pcData; CK_ULONG offset; - void *p; - pTemplate[i].type = ntohl(pulData[1 + i*3]); - len = ntohl(pulData[2 + i*3]); - offset = ntohl(pulData[3 + i*3]); - - p = nss_ZAlloc(arena, len); - if( (void *)NULL == p ) { - return CKR_HOST_MEMORY; + object_size = (1 + ulAttributeCount * 3) * sizeof(CK_ULONG); + offset = object_size; + for (i = 0; i < ulAttributeCount; i++) { + object_size += pTemplate[i].ulValueLen; } - - nss_dbm_db_swap_copy(pTemplate[i].type, p, &pcData[offset], len); - pTemplate[i].ulValueLen = len; - pTemplate[i].pValue = p; - } - *ppTemplate = pTemplate; - return CKR_OK; + object->size = object_size; + object->data = nss_ZAlloc(arena, object_size); + if ((void *)NULL == object->data) { + return CKR_HOST_MEMORY; + } + + pulData = (CK_ULONG *)object->data; + pcData = (char *)object->data; + + pulData[0] = htonl(ulAttributeCount); + for (i = 0; i < ulAttributeCount; i++) { + CK_ULONG len = pTemplate[i].ulValueLen; + pulData[1 + i * 3] = htonl(pTemplate[i].type); + pulData[2 + i * 3] = htonl(len); + pulData[3 + i * 3] = htonl(offset); + nss_dbm_db_swap_copy(pTemplate[i].type, &pcData[offset], pTemplate[i].pValue, len); + offset += len; + } + + return CKR_OK; } +static CK_RV +nss_dbm_db_unwrap_object( + NSSArena *arena, + DBT *object, + CK_ATTRIBUTE_PTR *ppTemplate, + CK_ULONG *pulAttributeCount) +{ + CK_ULONG *pulData; + char *pcData; + CK_ULONG n, i; + CK_ATTRIBUTE_PTR pTemplate; + + pulData = (CK_ULONG *)object->data; + pcData = (char *)object->data; + + n = ntohl(pulData[0]); + *pulAttributeCount = n; + pTemplate = nss_ZNEWARRAY(arena, CK_ATTRIBUTE, n); + if ((CK_ATTRIBUTE_PTR)NULL == pTemplate) { + return CKR_HOST_MEMORY; + } + + for (i = 0; i < n; i++) { + CK_ULONG len; + CK_ULONG offset; + void *p; + + pTemplate[i].type = ntohl(pulData[1 + i * 3]); + len = ntohl(pulData[2 + i * 3]); + offset = ntohl(pulData[3 + i * 3]); + + p = nss_ZAlloc(arena, len); + if ((void *)NULL == p) { + return CKR_HOST_MEMORY; + } + + nss_dbm_db_swap_copy(pTemplate[i].type, p, &pcData[offset], len); + pTemplate[i].ulValueLen = len; + pTemplate[i].pValue = p; + } + + *ppTemplate = pTemplate; + return CKR_OK; +} NSS_IMPLEMENT nss_dbm_dbt_t * -nss_dbm_db_create_object -( - NSSArena *arena, - nss_dbm_db_t *db, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError, - CK_ULONG *pdbrv -) +nss_dbm_db_create_object( + NSSArena *arena, + nss_dbm_db_t *db, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError, + CK_ULONG *pdbrv) { - NSSArena *tmparena = (NSSArena *)NULL; - nss_dbm_dbt_t *rv = (nss_dbm_dbt_t *)NULL; - DBT object; + NSSArena *tmparena = (NSSArena *)NULL; + nss_dbm_dbt_t *rv = (nss_dbm_dbt_t *)NULL; + DBT object; - rv = nss_ZNEW(arena, nss_dbm_dbt_t); - if( (nss_dbm_dbt_t *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (nss_dbm_dbt_t *)NULL; - } - - rv->my_db = db; - rv->dbt.size = sizeof(struct handle); - rv->dbt.data = nss_ZAlloc(arena, rv->dbt.size); - if( (void *)NULL == rv->dbt.data ) { - *pError = CKR_HOST_MEMORY; - return (nss_dbm_dbt_t *)NULL; - } - - *pdbrv = nss_dbm_db_new_handle(db, &rv->dbt, pError); - if( 0 != *pdbrv ) { - return (nss_dbm_dbt_t *)NULL; - } - - tmparena = NSSArena_Create(); - if( (NSSArena *)NULL == tmparena ) { - *pError = CKR_HOST_MEMORY; - return (nss_dbm_dbt_t *)NULL; - } - - *pError = nss_dbm_db_wrap_object(tmparena, pTemplate, ulAttributeCount, &object); - if( CKR_OK != *pError ) { - return (nss_dbm_dbt_t *)NULL; - } - - /* Locked region */ - { - *pError = NSSCKFWMutex_Lock(db->crustylock); - if( CKR_OK != *pError ) { - goto loser; + rv = nss_ZNEW(arena, nss_dbm_dbt_t); + if ((nss_dbm_dbt_t *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (nss_dbm_dbt_t *)NULL; } - *pdbrv = db->db->put(db->db, &rv->dbt, &object, 0); - if( 0 != *pdbrv ) { - *pError = CKR_DEVICE_ERROR; + rv->my_db = db; + rv->dbt.size = sizeof(struct handle); + rv->dbt.data = nss_ZAlloc(arena, rv->dbt.size); + if ((void *)NULL == rv->dbt.data) { + *pError = CKR_HOST_MEMORY; + return (nss_dbm_dbt_t *)NULL; } - (void)db->db->sync(db->db, 0); + *pdbrv = nss_dbm_db_new_handle(db, &rv->dbt, pError); + if (0 != *pdbrv) { + return (nss_dbm_dbt_t *)NULL; + } - (void)NSSCKFWMutex_Unlock(db->crustylock); - } + tmparena = NSSArena_Create(); + if ((NSSArena *)NULL == tmparena) { + *pError = CKR_HOST_MEMORY; + return (nss_dbm_dbt_t *)NULL; + } - loser: - if( (NSSArena *)NULL != tmparena ) { - (void)NSSArena_Destroy(tmparena); - } + *pError = nss_dbm_db_wrap_object(tmparena, pTemplate, ulAttributeCount, &object); + if (CKR_OK != *pError) { + return (nss_dbm_dbt_t *)NULL; + } - return rv; + /* Locked region */ + { + *pError = NSSCKFWMutex_Lock(db->crustylock); + if (CKR_OK != *pError) { + goto loser; + } + + *pdbrv = db->db->put(db->db, &rv->dbt, &object, 0); + if (0 != *pdbrv) { + *pError = CKR_DEVICE_ERROR; + } + + (void)db->db->sync(db->db, 0); + + (void)NSSCKFWMutex_Unlock(db->crustylock); + } + +loser: + if ((NSSArena *)NULL != tmparena) { + (void)NSSArena_Destroy(tmparena); + } + + return rv; } - NSS_IMPLEMENT CK_RV -nss_dbm_db_find_objects -( - nss_dbm_find_t *find, - nss_dbm_db_t *db, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_ULONG *pdbrv -) +nss_dbm_db_find_objects( + nss_dbm_find_t *find, + nss_dbm_db_t *db, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_ULONG *pdbrv) { - CK_RV rv = CKR_OK; + CK_RV rv = CKR_OK; - if( (nss_dbm_db_t *)NULL != db ) { - DBT k, v; + if ((nss_dbm_db_t *)NULL != db) { + DBT k, v; - rv = NSSCKFWMutex_Lock(db->crustylock); - if( CKR_OK != rv ) { - return rv; - } + rv = NSSCKFWMutex_Lock(db->crustylock); + if (CKR_OK != rv) { + return rv; + } - *pdbrv = db->db->seq(db->db, &k, &v, R_FIRST); - while( 0 == *pdbrv ) { - CK_ULONG i, j; - NSSArena *tmparena = (NSSArena *)NULL; - CK_ULONG ulac; - CK_ATTRIBUTE_PTR pt; + *pdbrv = db->db->seq(db->db, &k, &v, R_FIRST); + while (0 == *pdbrv) { + CK_ULONG i, j; + NSSArena *tmparena = (NSSArena *)NULL; + CK_ULONG ulac; + CK_ATTRIBUTE_PTR pt; - if( (k.size < 4) || (0 != memcmp(k.data, PREFIX_OBJECT, 4)) ) { - goto nomatch; - } - - tmparena = NSSArena_Create(); - - rv = nss_dbm_db_unwrap_object(tmparena, &v, &pt, &ulac); - if( CKR_OK != rv ) { - goto loser; - } - - for( i = 0; i < ulAttributeCount; i++ ) { - for( j = 0; j < ulac; j++ ) { - if( pTemplate[i].type == pt[j].type ) { - if( pTemplate[i].ulValueLen != pt[j].ulValueLen ) { - goto nomatch; + if ((k.size < 4) || (0 != memcmp(k.data, PREFIX_OBJECT, 4))) { + goto nomatch; } - if( 0 != memcmp(pTemplate[i].pValue, pt[j].pValue, pt[j].ulValueLen) ) { - goto nomatch; + + tmparena = NSSArena_Create(); + + rv = nss_dbm_db_unwrap_object(tmparena, &v, &pt, &ulac); + if (CKR_OK != rv) { + goto loser; } - break; - } - } - if( j == ulac ) { - goto nomatch; - } - } - /* entire template matches */ - { - struct nss_dbm_dbt_node *node; + for (i = 0; i < ulAttributeCount; i++) { + for (j = 0; j < ulac; j++) { + if (pTemplate[i].type == + pt[j].type) { + if (pTemplate[i].ulValueLen != + pt[j].ulValueLen) { + goto nomatch; + } + if (0 != + memcmp(pTemplate[i].pValue, pt[j].pValue, pt[j].ulValueLen)) { + goto nomatch; + } + break; + } + } + if (j == ulac) { + goto nomatch; + } + } - node = nss_ZNEW(find->arena, struct nss_dbm_dbt_node); - if( (struct nss_dbm_dbt_node *)NULL == node ) { - rv = CKR_HOST_MEMORY; - goto loser; + /* entire template matches */ + { + struct nss_dbm_dbt_node *node; + + node = nss_ZNEW(find->arena, struct nss_dbm_dbt_node); + if ((struct nss_dbm_dbt_node *)NULL == node) { + rv = + CKR_HOST_MEMORY; + goto loser; + } + + node->dbt = nss_ZNEW(find->arena, nss_dbm_dbt_t); + if ((nss_dbm_dbt_t *)NULL == node->dbt) { + rv = + CKR_HOST_MEMORY; + goto loser; + } + + node->dbt->dbt.size = k.size; + node->dbt->dbt.data = nss_ZAlloc(find->arena, k.size); + if ((void *)NULL == node->dbt->dbt.data) { + rv = + CKR_HOST_MEMORY; + goto loser; + } + + (void)memcpy(node->dbt->dbt.data, k.data, k.size); + + node->dbt->my_db = db; + + node->next = find->found; + find->found = node; + } + + nomatch: + if ((NSSArena *)NULL != tmparena) { + (void)NSSArena_Destroy(tmparena); + } + *pdbrv = db->db->seq(db->db, &k, &v, R_NEXT); } - node->dbt = nss_ZNEW(find->arena, nss_dbm_dbt_t); - if( (nss_dbm_dbt_t *)NULL == node->dbt ) { - rv = CKR_HOST_MEMORY; - goto loser; - } - - node->dbt->dbt.size = k.size; - node->dbt->dbt.data = nss_ZAlloc(find->arena, k.size); - if( (void *)NULL == node->dbt->dbt.data ) { - rv = CKR_HOST_MEMORY; - goto loser; + if (*pdbrv < 0) { + rv = CKR_DEVICE_ERROR; + goto loser; } - (void)memcpy(node->dbt->dbt.data, k.data, k.size); + rv = CKR_OK; - node->dbt->my_db = db; - - node->next = find->found; - find->found = node; - } - - nomatch: - if( (NSSArena *)NULL != tmparena ) { - (void)NSSArena_Destroy(tmparena); - } - *pdbrv = db->db->seq(db->db, &k, &v, R_NEXT); + loser: + (void)NSSCKFWMutex_Unlock(db->crustylock); } - if( *pdbrv < 0 ) { - rv = CKR_DEVICE_ERROR; - goto loser; - } - - rv = CKR_OK; - - loser: - (void)NSSCKFWMutex_Unlock(db->crustylock); - } - - return rv; + return rv; } NSS_IMPLEMENT CK_BBOOL -nss_dbm_db_object_still_exists -( - nss_dbm_dbt_t *dbt -) +nss_dbm_db_object_still_exists( + nss_dbm_dbt_t *dbt) { - CK_BBOOL rv; - CK_RV ckrv; - int dbrv; - DBT object; + CK_BBOOL rv; + CK_RV ckrv; + int dbrv; + DBT object; - ckrv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); - if( CKR_OK != ckrv ) { - return CK_FALSE; - } + ckrv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); + if (CKR_OK != ckrv) { + return CK_FALSE; + } - dbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); - if( 0 == dbrv ) { - rv = CK_TRUE; - } else { - rv = CK_FALSE; - } + dbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); + if (0 == dbrv) { + rv = CK_TRUE; + } + else { + rv = CK_FALSE; + } - (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); + (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); - return rv; + return rv; } NSS_IMPLEMENT CK_ULONG -nss_dbm_db_get_object_attribute_count -( - nss_dbm_dbt_t *dbt, - CK_RV *pError, - CK_ULONG *pdbrv -) +nss_dbm_db_get_object_attribute_count( + nss_dbm_dbt_t *dbt, + CK_RV *pError, + CK_ULONG *pdbrv) { - CK_ULONG rv = 0; - DBT object; - CK_ULONG *pulData; + CK_ULONG rv = 0; + DBT object; + CK_ULONG *pulData; - /* Locked region */ - { - *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock); - if( CKR_OK != *pError ) { - return rv; + /* Locked region */ + { + *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock); + if (CKR_OK != *pError) { + return rv; + } + + *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); + if (0 == *pdbrv) { + ; + } + else if (*pdbrv > 0) { + *pError = CKR_OBJECT_HANDLE_INVALID; + goto done; + } + else { + *pError = CKR_DEVICE_ERROR; + goto done; + } + + pulData = (CK_ULONG *)object.data; + rv = ntohl(pulData[0]); + + done: + (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); } - *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); - if( 0 == *pdbrv ) { - ; - } else if( *pdbrv > 0 ) { - *pError = CKR_OBJECT_HANDLE_INVALID; - goto done; - } else { - *pError = CKR_DEVICE_ERROR; - goto done; - } - - pulData = (CK_ULONG *)object.data; - rv = ntohl(pulData[0]); - - done: - (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); - } - - return rv; + return rv; } NSS_IMPLEMENT CK_RV -nss_dbm_db_get_object_attribute_types -( - nss_dbm_dbt_t *dbt, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount, - CK_ULONG *pdbrv -) +nss_dbm_db_get_object_attribute_types( + nss_dbm_dbt_t *dbt, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount, + CK_ULONG *pdbrv) { - CK_RV rv = CKR_OK; - DBT object; - CK_ULONG *pulData; - CK_ULONG n, i; + CK_RV rv = CKR_OK; + DBT object; + CK_ULONG *pulData; + CK_ULONG n, i; - /* Locked region */ - { - rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); - if( CKR_OK != rv ) { - return rv; + /* Locked region */ + { + rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); + if (CKR_OK != rv) { + return rv; + } + + *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); + if (0 == *pdbrv) { + ; + } + else if (*pdbrv > 0) { + rv = CKR_OBJECT_HANDLE_INVALID; + goto done; + } + else { + rv = CKR_DEVICE_ERROR; + goto done; + } + + pulData = (CK_ULONG *)object.data; + n = ntohl(pulData[0]); + + if (ulCount < n) { + rv = CKR_BUFFER_TOO_SMALL; + goto done; + } + + for (i = 0; i < n; i++) { + typeArray[i] = ntohl(pulData[1 + i * 3]); + } + + done: + (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); } - *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); - if( 0 == *pdbrv ) { - ; - } else if( *pdbrv > 0 ) { - rv = CKR_OBJECT_HANDLE_INVALID; - goto done; - } else { - rv = CKR_DEVICE_ERROR; - goto done; - } - - pulData = (CK_ULONG *)object.data; - n = ntohl(pulData[0]); - - if( ulCount < n ) { - rv = CKR_BUFFER_TOO_SMALL; - goto done; - } - - for( i = 0; i < n; i++ ) { - typeArray[i] = ntohl(pulData[1 + i*3]); - } - - done: - (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); - } - - return rv; + return rv; } NSS_IMPLEMENT CK_ULONG -nss_dbm_db_get_object_attribute_size -( - nss_dbm_dbt_t *dbt, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError, - CK_ULONG *pdbrv -) +nss_dbm_db_get_object_attribute_size( + nss_dbm_dbt_t *dbt, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError, + CK_ULONG *pdbrv) { - CK_ULONG rv = 0; - DBT object; - CK_ULONG *pulData; - CK_ULONG n, i; + CK_ULONG rv = 0; + DBT object; + CK_ULONG *pulData; + CK_ULONG n, i; - /* Locked region */ - { - *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock); - if( CKR_OK != *pError ) { - return rv; + /* Locked region */ + { + *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock); + if (CKR_OK != *pError) { + return rv; + } + + *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); + if (0 == *pdbrv) { + ; + } + else if (*pdbrv > 0) { + *pError = CKR_OBJECT_HANDLE_INVALID; + goto done; + } + else { + *pError = CKR_DEVICE_ERROR; + goto done; + } + + pulData = (CK_ULONG *)object.data; + n = ntohl(pulData[0]); + + for (i = 0; i < n; i++) { + if (type == ntohl(pulData[1 + i * 3])) { + rv = ntohl(pulData[2 + i * + 3]); + } + } + + if (i == n) { + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + goto done; + } + + done: + (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); } - *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); - if( 0 == *pdbrv ) { - ; - } else if( *pdbrv > 0 ) { - *pError = CKR_OBJECT_HANDLE_INVALID; - goto done; - } else { - *pError = CKR_DEVICE_ERROR; - goto done; - } - - pulData = (CK_ULONG *)object.data; - n = ntohl(pulData[0]); - - for( i = 0; i < n; i++ ) { - if( type == ntohl(pulData[1 + i*3]) ) { - rv = ntohl(pulData[2 + i*3]); - } - } - - if( i == n ) { - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - goto done; - } - - done: - (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); - } - - return rv; + return rv; } NSS_IMPLEMENT NSSItem * -nss_dbm_db_get_object_attribute -( - nss_dbm_dbt_t *dbt, - NSSArena *arena, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError, - CK_ULONG *pdbrv -) +nss_dbm_db_get_object_attribute( + nss_dbm_dbt_t *dbt, + NSSArena *arena, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError, + CK_ULONG *pdbrv) { - NSSItem *rv = (NSSItem *)NULL; - DBT object; - CK_ULONG i; - NSSArena *tmp = NSSArena_Create(); - CK_ATTRIBUTE_PTR pTemplate; - CK_ULONG ulAttributeCount; + NSSItem *rv = (NSSItem *)NULL; + DBT object; + CK_ULONG i; + NSSArena *tmp = NSSArena_Create(); + CK_ATTRIBUTE_PTR pTemplate; + CK_ULONG ulAttributeCount; - /* Locked region */ - { - *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock); - if( CKR_OK != *pError ) { - goto loser; - } - - *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); - if( 0 == *pdbrv ) { - ; - } else if( *pdbrv > 0 ) { - *pError = CKR_OBJECT_HANDLE_INVALID; - goto done; - } else { - *pError = CKR_DEVICE_ERROR; - goto done; - } - - *pError = nss_dbm_db_unwrap_object(tmp, &object, &pTemplate, &ulAttributeCount); - if( CKR_OK != *pError ) { - goto done; - } - - for( i = 0; i < ulAttributeCount; i++ ) { - if( type == pTemplate[i].type ) { - rv = nss_ZNEW(arena, NSSItem); - if( (NSSItem *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - goto done; + /* Locked region */ + { + *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock); + if (CKR_OK != *pError) { + goto loser; } - rv->size = pTemplate[i].ulValueLen; - rv->data = nss_ZAlloc(arena, rv->size); - if( (void *)NULL == rv->data ) { - *pError = CKR_HOST_MEMORY; - goto done; + + *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); + if (0 == *pdbrv) { + ; } - (void)memcpy(rv->data, pTemplate[i].pValue, rv->size); - break; - } - } - if( ulAttributeCount == i ) { - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - goto done; + else if (*pdbrv > 0) { + *pError = CKR_OBJECT_HANDLE_INVALID; + goto done; + } + else { + *pError = CKR_DEVICE_ERROR; + goto done; + } + + *pError = nss_dbm_db_unwrap_object(tmp, &object, &pTemplate, &ulAttributeCount); + if (CKR_OK != *pError) { + goto done; + } + + for (i = 0; i < ulAttributeCount; i++) { + if (type == pTemplate[i].type) { + rv = nss_ZNEW(arena, NSSItem); + if ((NSSItem *)NULL == rv) { + *pError = + CKR_HOST_MEMORY; + goto done; + } + rv->size = pTemplate[i].ulValueLen; + rv->data = nss_ZAlloc(arena, rv->size); + if ((void *)NULL == rv->data) { + *pError = + CKR_HOST_MEMORY; + goto done; + } + (void)memcpy(rv->data, pTemplate[i].pValue, rv->size); + break; + } + } + if (ulAttributeCount == i) { + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + goto done; + } + + done: + (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); } - done: - (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); - } +loser: + if ((NSSArena *)NULL != tmp) { + NSSArena_Destroy(tmp); + } - loser: - if( (NSSArena *)NULL != tmp ) { - NSSArena_Destroy(tmp); - } - - return rv; + return rv; } NSS_IMPLEMENT CK_RV -nss_dbm_db_set_object_attribute -( - nss_dbm_dbt_t *dbt, - CK_ATTRIBUTE_TYPE type, - NSSItem *value, - CK_ULONG *pdbrv -) +nss_dbm_db_set_object_attribute( + nss_dbm_dbt_t *dbt, + CK_ATTRIBUTE_TYPE type, + NSSItem *value, + CK_ULONG *pdbrv) { - CK_RV rv = CKR_OK; - DBT object; - CK_ULONG i; - NSSArena *tmp = NSSArena_Create(); - CK_ATTRIBUTE_PTR pTemplate; - CK_ULONG ulAttributeCount; + CK_RV rv = CKR_OK; + DBT object; + CK_ULONG i; + NSSArena *tmp = NSSArena_Create(); + CK_ATTRIBUTE_PTR pTemplate; + CK_ULONG ulAttributeCount; - /* Locked region */ - { - rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); - if( CKR_OK != rv ) { - goto loser; + /* Locked region */ + { + rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock); + if (CKR_OK != rv) { + goto loser; + } + + *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); + if (0 == *pdbrv) { + ; + } + else if (*pdbrv > 0) { + rv = CKR_OBJECT_HANDLE_INVALID; + goto done; + } + else { + rv = CKR_DEVICE_ERROR; + goto done; + } + + rv = nss_dbm_db_unwrap_object(tmp, &object, &pTemplate, &ulAttributeCount); + if (CKR_OK != rv) { + goto done; + } + + for (i = 0; i < ulAttributeCount; i++) { + if (type == pTemplate[i].type) { + /* Replacing an existing attribute */ + pTemplate[i].ulValueLen = value->size; + pTemplate[i].pValue = value->data; + break; + } + } + + if (i == ulAttributeCount) { + /* Adding a new attribute */ + CK_ATTRIBUTE_PTR npt = nss_ZNEWARRAY(tmp, CK_ATTRIBUTE, ulAttributeCount + 1); + if ((CK_ATTRIBUTE_PTR)NULL == npt) { + rv = CKR_DEVICE_ERROR; + goto done; + } + + for (i = 0; i < ulAttributeCount; i++) { + npt[i] = pTemplate[i]; + } + + npt[ulAttributeCount].type = type; + npt[ulAttributeCount].ulValueLen = value->size; + npt[ulAttributeCount].pValue = value->data; + + pTemplate = npt; + ulAttributeCount++; + } + + rv = nss_dbm_db_wrap_object(tmp, pTemplate, ulAttributeCount, &object); + if (CKR_OK != rv) { + goto done; + } + + *pdbrv = dbt->my_db->db->put(dbt->my_db->db, &dbt->dbt, &object, 0); + if (0 != *pdbrv) { + rv = CKR_DEVICE_ERROR; + goto done; + } + + (void)dbt->my_db->db->sync(dbt->my_db->db, 0); + + done: + (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); } - *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0); - if( 0 == *pdbrv ) { - ; - } else if( *pdbrv > 0 ) { - rv = CKR_OBJECT_HANDLE_INVALID; - goto done; - } else { - rv = CKR_DEVICE_ERROR; - goto done; +loser: + if ((NSSArena *)NULL != tmp) { + NSSArena_Destroy(tmp); } - rv = nss_dbm_db_unwrap_object(tmp, &object, &pTemplate, &ulAttributeCount); - if( CKR_OK != rv ) { - goto done; - } - - for( i = 0; i < ulAttributeCount; i++ ) { - if( type == pTemplate[i].type ) { - /* Replacing an existing attribute */ - pTemplate[i].ulValueLen = value->size; - pTemplate[i].pValue = value->data; - break; - } - } - - if( i == ulAttributeCount ) { - /* Adding a new attribute */ - CK_ATTRIBUTE_PTR npt = nss_ZNEWARRAY(tmp, CK_ATTRIBUTE, ulAttributeCount+1); - if( (CK_ATTRIBUTE_PTR)NULL == npt ) { - rv = CKR_DEVICE_ERROR; - goto done; - } - - for( i = 0; i < ulAttributeCount; i++ ) { - npt[i] = pTemplate[i]; - } - - npt[ulAttributeCount].type = type; - npt[ulAttributeCount].ulValueLen = value->size; - npt[ulAttributeCount].pValue = value->data; - - pTemplate = npt; - ulAttributeCount++; - } - - rv = nss_dbm_db_wrap_object(tmp, pTemplate, ulAttributeCount, &object); - if( CKR_OK != rv ) { - goto done; - } - - *pdbrv = dbt->my_db->db->put(dbt->my_db->db, &dbt->dbt, &object, 0); - if( 0 != *pdbrv ) { - rv = CKR_DEVICE_ERROR; - goto done; - } - - (void)dbt->my_db->db->sync(dbt->my_db->db, 0); - - done: - (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock); - } - - loser: - if( (NSSArena *)NULL != tmp ) { - NSSArena_Destroy(tmp); - } - - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/dbm/find.c b/security/nss/lib/ckfw/dbm/find.c index 575c0ad5ac75..8a03855c3f3f 100644 --- a/security/nss/lib/ckfw/dbm/find.c +++ b/security/nss/lib/ckfw/dbm/find.c @@ -5,129 +5,122 @@ #include "ckdbm.h" static void -nss_dbm_mdFindObjects_Final -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdFindObjects_Final( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_find_t *find = (nss_dbm_find_t *)mdFindObjects->etc; + nss_dbm_find_t *find = (nss_dbm_find_t *)mdFindObjects->etc; - /* Locks might have system resources associated */ - (void)NSSCKFWMutex_Destroy(find->list_lock); - (void)NSSArena_Destroy(find->arena); + /* Locks might have system resources associated */ + (void)NSSCKFWMutex_Destroy(find->list_lock); + (void)NSSArena_Destroy(find->arena); } - static NSSCKMDObject * -nss_dbm_mdFindObjects_Next -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +nss_dbm_mdFindObjects_Next( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { - nss_dbm_find_t *find = (nss_dbm_find_t *)mdFindObjects->etc; - struct nss_dbm_dbt_node *node; - nss_dbm_object_t *object; - NSSCKMDObject *rv; + nss_dbm_find_t *find = (nss_dbm_find_t *)mdFindObjects->etc; + struct nss_dbm_dbt_node *node; + nss_dbm_object_t *object; + NSSCKMDObject *rv; - while(1) { - /* Lock */ - { - *pError = NSSCKFWMutex_Lock(find->list_lock); - if( CKR_OK != *pError ) { + while (1) { + /* Lock */ + { + *pError = NSSCKFWMutex_Lock(find->list_lock); + if (CKR_OK != *pError) { + return (NSSCKMDObject *)NULL; + } + + node = find->found; + if ((struct nss_dbm_dbt_node *)NULL != node) { + find->found = node->next; + } + + *pError = NSSCKFWMutex_Unlock(find->list_lock); + if (CKR_OK != *pError) { + /* screwed now */ + return (NSSCKMDObject *)NULL; + } + } + + if ((struct nss_dbm_dbt_node *)NULL == node) { + break; + } + + if (nss_dbm_db_object_still_exists(node->dbt)) { + break; + } + } + + if ((struct nss_dbm_dbt_node *)NULL == node) { + *pError = CKR_OK; return (NSSCKMDObject *)NULL; - } - - node = find->found; - if( (struct nss_dbm_dbt_node *)NULL != node ) { - find->found = node->next; - } - - *pError = NSSCKFWMutex_Unlock(find->list_lock); - if( CKR_OK != *pError ) { - /* screwed now */ + } + + object = nss_ZNEW(arena, nss_dbm_object_t); + if ((nss_dbm_object_t *)NULL == object) { + *pError = CKR_HOST_MEMORY; return (NSSCKMDObject *)NULL; - } } - if( (struct nss_dbm_dbt_node *)NULL == node ) { - break; + object->arena = arena; + object->handle = nss_ZNEW(arena, nss_dbm_dbt_t); + if ((nss_dbm_dbt_t *)NULL == object->handle) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDObject *)NULL; } - if( nss_dbm_db_object_still_exists(node->dbt) ) { - break; + object->handle->my_db = node->dbt->my_db; + object->handle->dbt.size = node->dbt->dbt.size; + object->handle->dbt.data = nss_ZAlloc(arena, node->dbt->dbt.size); + if ((void *)NULL == object->handle->dbt.data) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDObject *)NULL; } - } - if( (struct nss_dbm_dbt_node *)NULL == node ) { - *pError = CKR_OK; - return (NSSCKMDObject *)NULL; - } + (void)memcpy(object->handle->dbt.data, node->dbt->dbt.data, node->dbt->dbt.size); - object = nss_ZNEW(arena, nss_dbm_object_t); - if( (nss_dbm_object_t *)NULL == object ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDObject *)NULL; - } + rv = nss_dbm_mdObject_factory(object, pError); + if ((NSSCKMDObject *)NULL == rv) { + return (NSSCKMDObject *)NULL; + } - object->arena = arena; - object->handle = nss_ZNEW(arena, nss_dbm_dbt_t); - if( (nss_dbm_dbt_t *)NULL == object->handle ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDObject *)NULL; - } - - object->handle->my_db = node->dbt->my_db; - object->handle->dbt.size = node->dbt->dbt.size; - object->handle->dbt.data = nss_ZAlloc(arena, node->dbt->dbt.size); - if( (void *)NULL == object->handle->dbt.data ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDObject *)NULL; - } - - (void)memcpy(object->handle->dbt.data, node->dbt->dbt.data, node->dbt->dbt.size); - - rv = nss_dbm_mdObject_factory(object, pError); - if( (NSSCKMDObject *)NULL == rv ) { - return (NSSCKMDObject *)NULL; - } - - return rv; + return rv; } NSS_IMPLEMENT NSSCKMDFindObjects * -nss_dbm_mdFindObjects_factory -( - nss_dbm_find_t *find, - CK_RV *pError -) +nss_dbm_mdFindObjects_factory( + nss_dbm_find_t *find, + CK_RV *pError) { - NSSCKMDFindObjects *rv; + NSSCKMDFindObjects *rv; - rv = nss_ZNEW(find->arena, NSSCKMDFindObjects); - if( (NSSCKMDFindObjects *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDFindObjects *)NULL; - } + rv = nss_ZNEW(find->arena, NSSCKMDFindObjects); + if ((NSSCKMDFindObjects *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDFindObjects *)NULL; + } - rv->etc = (void *)find; - rv->Final = nss_dbm_mdFindObjects_Final; - rv->Next = nss_dbm_mdFindObjects_Next; + rv->etc = (void *)find; + rv->Final = nss_dbm_mdFindObjects_Final; + rv->Next = nss_dbm_mdFindObjects_Next; - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/dbm/instance.c b/security/nss/lib/ckfw/dbm/instance.c index 14f7af827d1b..fbb11722dfaf 100644 --- a/security/nss/lib/ckfw/dbm/instance.c +++ b/security/nss/lib/ckfw/dbm/instance.c @@ -5,159 +5,143 @@ #include "ckdbm.h" static CK_RV -nss_dbm_mdInstance_Initialize -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSUTF8 *configurationData -) +nss_dbm_mdInstance_Initialize( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSUTF8 *configurationData) { - CK_RV rv = CKR_OK; - NSSArena *arena; - nss_dbm_instance_t *instance; + CK_RV rv = CKR_OK; + NSSArena *arena; + nss_dbm_instance_t *instance; - arena = NSSCKFWInstance_GetArena(fwInstance, &rv); - if( ((NSSArena *)NULL == arena) && (CKR_OK != rv) ) { - return rv; - } + arena = NSSCKFWInstance_GetArena(fwInstance, &rv); + if (((NSSArena *)NULL == arena) && (CKR_OK != rv)) { + return rv; + } - instance = nss_ZNEW(arena, nss_dbm_instance_t); - if( (nss_dbm_instance_t *)NULL == instance ) { - return CKR_HOST_MEMORY; - } + instance = nss_ZNEW(arena, nss_dbm_instance_t); + if ((nss_dbm_instance_t *)NULL == instance) { + return CKR_HOST_MEMORY; + } - instance->arena = arena; + instance->arena = arena; - /* - * This should parse the configuration data for information on - * number and locations of databases, modes (e.g. readonly), etc. - * But for now, we'll have one slot with a creatable read-write - * database called "cert8.db." - */ + /* + * This should parse the configuration data for information on + * number and locations of databases, modes (e.g. readonly), etc. + * But for now, we'll have one slot with a creatable read-write + * database called "cert8.db." + */ - instance->nSlots = 1; - instance->filenames = nss_ZNEWARRAY(arena, char *, instance->nSlots); - if( (char **)NULL == instance->filenames ) { - return CKR_HOST_MEMORY; - } + instance->nSlots = 1; + instance->filenames = nss_ZNEWARRAY(arena, char *, instance->nSlots); + if ((char **)NULL == instance->filenames) { + return CKR_HOST_MEMORY; + } - instance->flags = nss_ZNEWARRAY(arena, int, instance->nSlots); - if( (int *)NULL == instance->flags ) { - return CKR_HOST_MEMORY; - } + instance->flags = nss_ZNEWARRAY(arena, int, instance->nSlots); + if ((int *)NULL == instance->flags) { + return CKR_HOST_MEMORY; + } - instance->filenames[0] = "cert8.db"; - instance->flags[0] = O_RDWR|O_CREAT; + instance->filenames[0] = "cert8.db"; + instance->flags[0] = O_RDWR | O_CREAT; - mdInstance->etc = (void *)instance; - return CKR_OK; + mdInstance->etc = (void *)instance; + return CKR_OK; } /* nss_dbm_mdInstance_Finalize is not required */ static CK_ULONG -nss_dbm_mdInstance_GetNSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdInstance_GetNSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; - return instance->nSlots; + nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; + return instance->nSlots; } static CK_VERSION -nss_dbm_mdInstance_GetCryptokiVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdInstance_GetCryptokiVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - static CK_VERSION rv = { 2, 1 }; - return rv; + static CK_VERSION rv = { 2, 1 }; + return rv; } static NSSUTF8 * -nss_dbm_mdInstance_GetManufacturerID -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdInstance_GetManufacturerID( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return "Mozilla Foundation"; + return "Mozilla Foundation"; } static NSSUTF8 * -nss_dbm_mdInstance_GetLibraryDescription -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdInstance_GetLibraryDescription( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return "Berkeley Database Module"; + return "Berkeley Database Module"; } static CK_VERSION -nss_dbm_mdInstance_GetLibraryVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdInstance_GetLibraryVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - static CK_VERSION rv = { 1, 0 }; /* My own version number */ - return rv; + static CK_VERSION rv = { 1, 0 }; /* My own version number */ + return rv; } static CK_BBOOL -nss_dbm_mdInstance_ModuleHandlesSessionObjects -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdInstance_ModuleHandlesSessionObjects( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_TRUE; + return CK_TRUE; } static CK_RV -nss_dbm_mdInstance_GetSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDSlot *slots[] -) +nss_dbm_mdInstance_GetSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDSlot *slots[]) { - nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; - CK_ULONG i; - CK_RV rv = CKR_OK; + nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; + CK_ULONG i; + CK_RV rv = CKR_OK; - for( i = 0; i < instance->nSlots; i++ ) { - slots[i] = nss_dbm_mdSlot_factory(instance, instance->filenames[i], - instance->flags[i], &rv); - if( (NSSCKMDSlot *)NULL == slots[i] ) { - return rv; + for (i = 0; i < instance->nSlots; i++) { + slots[i] = nss_dbm_mdSlot_factory(instance, instance->filenames[i], + instance->flags[i], &rv); + if ((NSSCKMDSlot *)NULL == slots[i]) { + return rv; + } } - } - return rv; + return rv; } /* nss_dbm_mdInstance_WaitForSlotEvent is not relevant */ -NSS_IMPLEMENT_DATA NSSCKMDInstance -nss_dbm_mdInstance = { - NULL, /* etc; filled in later */ - nss_dbm_mdInstance_Initialize, - NULL, /* nss_dbm_mdInstance_Finalize */ - nss_dbm_mdInstance_GetNSlots, - nss_dbm_mdInstance_GetCryptokiVersion, - nss_dbm_mdInstance_GetManufacturerID, - nss_dbm_mdInstance_GetLibraryDescription, - nss_dbm_mdInstance_GetLibraryVersion, - nss_dbm_mdInstance_ModuleHandlesSessionObjects, - nss_dbm_mdInstance_GetSlots, - NULL, /* nss_dbm_mdInstance_WaitForSlotEvent */ - NULL /* terminator */ -}; +NSS_IMPLEMENT_DATA NSSCKMDInstance + nss_dbm_mdInstance = { + NULL, /* etc; filled in later */ + nss_dbm_mdInstance_Initialize, + NULL, /* nss_dbm_mdInstance_Finalize */ + nss_dbm_mdInstance_GetNSlots, + nss_dbm_mdInstance_GetCryptokiVersion, + nss_dbm_mdInstance_GetManufacturerID, + nss_dbm_mdInstance_GetLibraryDescription, + nss_dbm_mdInstance_GetLibraryVersion, + nss_dbm_mdInstance_ModuleHandlesSessionObjects, + nss_dbm_mdInstance_GetSlots, + NULL, /* nss_dbm_mdInstance_WaitForSlotEvent */ + NULL /* terminator */ + }; diff --git a/security/nss/lib/ckfw/dbm/object.c b/security/nss/lib/ckfw/dbm/object.c index 0649d40c0cdf..4f6e4d409ce4 100644 --- a/security/nss/lib/ckfw/dbm/object.c +++ b/security/nss/lib/ckfw/dbm/object.c @@ -5,167 +5,151 @@ #include "ckdbm.h" static void -nss_dbm_mdObject_Finalize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdObject_Finalize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - ; + ; } static CK_RV -nss_dbm_mdObject_Destroy -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdObject_Destroy( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; - return nss_dbm_db_delete_object(object->handle); + nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; + return nss_dbm_db_delete_object(object->handle); } static CK_ULONG -nss_dbm_mdObject_GetAttributeCount -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdObject_GetAttributeCount( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - return nss_dbm_db_get_object_attribute_count(object->handle, pError, - &session->deviceError); + nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + return nss_dbm_db_get_object_attribute_count(object->handle, pError, + &session->deviceError); } static CK_RV -nss_dbm_mdObject_GetAttributeTypes -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -) +nss_dbm_mdObject_GetAttributeTypes( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount) { - nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - return nss_dbm_db_get_object_attribute_types(object->handle, typeArray, - ulCount, &session->deviceError); + nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + return nss_dbm_db_get_object_attribute_types(object->handle, typeArray, + ulCount, &session->deviceError); } static CK_ULONG -nss_dbm_mdObject_GetAttributeSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +nss_dbm_mdObject_GetAttributeSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - return nss_dbm_db_get_object_attribute_size(object->handle, attribute, pError, - &session->deviceError); + nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + return nss_dbm_db_get_object_attribute_size(object->handle, attribute, pError, + &session->deviceError); } static NSSItem * -nss_dbm_mdObject_GetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +nss_dbm_mdObject_GetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - return nss_dbm_db_get_object_attribute(object->handle, object->arena, attribute, - pError, &session->deviceError); + nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + return nss_dbm_db_get_object_attribute(object->handle, object->arena, attribute, + pError, &session->deviceError); } static CK_RV -nss_dbm_mdObject_SetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value -) +nss_dbm_mdObject_SetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value) { - nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - return nss_dbm_db_set_object_attribute(object->handle, attribute, value, - &session->deviceError); + nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + return nss_dbm_db_set_object_attribute(object->handle, attribute, value, + &session->deviceError); } NSS_IMPLEMENT NSSCKMDObject * -nss_dbm_mdObject_factory -( - nss_dbm_object_t *object, - CK_RV *pError -) +nss_dbm_mdObject_factory( + nss_dbm_object_t *object, + CK_RV *pError) { - NSSCKMDObject *rv; + NSSCKMDObject *rv; - rv = nss_ZNEW(object->arena, NSSCKMDObject); - if( (NSSCKMDObject *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDObject *)NULL; - } + rv = nss_ZNEW(object->arena, NSSCKMDObject); + if ((NSSCKMDObject *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDObject *)NULL; + } - rv->etc = (void *)object; - rv->Finalize = nss_dbm_mdObject_Finalize; - rv->Destroy = nss_dbm_mdObject_Destroy; - /* IsTokenObject can be deferred */ - rv->GetAttributeCount = nss_dbm_mdObject_GetAttributeCount; - rv->GetAttributeTypes = nss_dbm_mdObject_GetAttributeTypes; - rv->GetAttributeSize = nss_dbm_mdObject_GetAttributeSize; - rv->GetAttribute = nss_dbm_mdObject_GetAttribute; - rv->SetAttribute = nss_dbm_mdObject_SetAttribute; - /* GetObjectSize can be deferred */ + rv->etc = (void *)object; + rv->Finalize = nss_dbm_mdObject_Finalize; + rv->Destroy = nss_dbm_mdObject_Destroy; + /* IsTokenObject can be deferred */ + rv->GetAttributeCount = nss_dbm_mdObject_GetAttributeCount; + rv->GetAttributeTypes = nss_dbm_mdObject_GetAttributeTypes; + rv->GetAttributeSize = nss_dbm_mdObject_GetAttributeSize; + rv->GetAttribute = nss_dbm_mdObject_GetAttribute; + rv->SetAttribute = nss_dbm_mdObject_SetAttribute; + /* GetObjectSize can be deferred */ - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/dbm/session.c b/security/nss/lib/ckfw/dbm/session.c index 6101c06a7373..a1c2ee5faa04 100644 --- a/security/nss/lib/ckfw/dbm/session.c +++ b/security/nss/lib/ckfw/dbm/session.c @@ -5,50 +5,46 @@ #include "ckdbm.h" static void -nss_dbm_mdSession_Close -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdSession_Close( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - struct nss_dbm_dbt_node *w; + struct nss_dbm_dbt_node *w; - /* Lock */ - { - if( CKR_OK != NSSCKFWMutex_Lock(session->list_lock) ) { - return; + /* Lock */ + { + if (CKR_OK != NSSCKFWMutex_Lock(session->list_lock)) { + return; + } + + w = session->session_objects; + session->session_objects = (struct nss_dbm_dbt_node *)NULL; /* sanity */ + + (void)NSSCKFWMutex_Unlock(session->list_lock); } - w = session->session_objects; - session->session_objects = (struct nss_dbm_dbt_node *)NULL; /* sanity */ - - (void)NSSCKFWMutex_Unlock(session->list_lock); - } - - for( ; (struct nss_dbm_dbt_node *)NULL != w; w = w->next ) { - (void)nss_dbm_db_delete_object(w->dbt); - } + for (; (struct nss_dbm_dbt_node *)NULL != w; w = w->next) { + (void)nss_dbm_db_delete_object(w->dbt); + } } static CK_ULONG -nss_dbm_mdSession_GetDeviceError -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdSession_GetDeviceError( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - return session->deviceError; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + return session->deviceError; } /* Login isn't needed */ @@ -60,206 +56,200 @@ nss_dbm_mdSession_GetDeviceError /* SetOperationState is irrelevant */ static NSSCKMDObject * -nss_dbm_mdSession_CreateObject -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *handyArenaPointer, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_dbm_mdSession_CreateObject( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *handyArenaPointer, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - CK_ULONG i; - CK_BBOOL isToken = CK_FALSE; /* defaults to false */ - NSSCKMDObject *rv; - struct nss_dbm_dbt_node *node = (struct nss_dbm_dbt_node *)NULL; - nss_dbm_object_t *object; - nss_dbm_db_t *which_db; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + CK_ULONG i; + CK_BBOOL isToken = CK_FALSE; /* defaults to false */ + NSSCKMDObject *rv; + struct nss_dbm_dbt_node *node = (struct nss_dbm_dbt_node *)NULL; + nss_dbm_object_t *object; + nss_dbm_db_t *which_db; - /* This framework should really pass this to me */ - for( i = 0; i < ulAttributeCount; i++ ) { - if( CKA_TOKEN == pTemplate[i].type ) { - isToken = *(CK_BBOOL *)pTemplate[i].pValue; - break; + /* This framework should really pass this to me */ + for (i = 0; i < ulAttributeCount; i++) { + if (CKA_TOKEN == pTemplate[i].type) { + isToken = *(CK_BBOOL *)pTemplate[i].pValue; + break; + } } - } - object = nss_ZNEW(handyArenaPointer, nss_dbm_object_t); - if( (nss_dbm_object_t *)NULL == object ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDObject *)NULL; - } - - object->arena = handyArenaPointer; - which_db = isToken ? token->slot->token_db : token->session_db; - - /* Do this before the actual database call; it's easier to recover from */ - rv = nss_dbm_mdObject_factory(object, pError); - if( (NSSCKMDObject *)NULL == rv ) { - return (NSSCKMDObject *)NULL; - } - - if( CK_FALSE == isToken ) { - node = nss_ZNEW(session->arena, struct nss_dbm_dbt_node); - if( (struct nss_dbm_dbt_node *)NULL == node ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDObject *)NULL; - } - } - - object->handle = nss_dbm_db_create_object(handyArenaPointer, which_db, - pTemplate, ulAttributeCount, - pError, &session->deviceError); - if( (nss_dbm_dbt_t *)NULL == object->handle ) { - return (NSSCKMDObject *)NULL; - } - - if( CK_FALSE == isToken ) { - node->dbt = object->handle; - /* Lock */ - { - *pError = NSSCKFWMutex_Lock(session->list_lock); - if( CKR_OK != *pError ) { - (void)nss_dbm_db_delete_object(object->handle); + object = nss_ZNEW(handyArenaPointer, nss_dbm_object_t); + if ((nss_dbm_object_t *)NULL == object) { + *pError = CKR_HOST_MEMORY; return (NSSCKMDObject *)NULL; - } - - node->next = session->session_objects; - session->session_objects = node; - - *pError = NSSCKFWMutex_Unlock(session->list_lock); } - } - return rv; + object->arena = handyArenaPointer; + which_db = isToken ? token->slot->token_db : token->session_db; + + /* Do this before the actual database call; it's easier to recover from */ + rv = nss_dbm_mdObject_factory(object, pError); + if ((NSSCKMDObject *)NULL == rv) { + return (NSSCKMDObject *)NULL; + } + + if (CK_FALSE == isToken) { + node = nss_ZNEW(session->arena, struct nss_dbm_dbt_node); + if ((struct nss_dbm_dbt_node *)NULL == node) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDObject *)NULL; + } + } + + object->handle = nss_dbm_db_create_object(handyArenaPointer, which_db, + pTemplate, ulAttributeCount, + pError, &session->deviceError); + if ((nss_dbm_dbt_t *)NULL == object->handle) { + return (NSSCKMDObject *)NULL; + } + + if (CK_FALSE == isToken) { + node->dbt = object->handle; + /* Lock */ + { + *pError = NSSCKFWMutex_Lock(session->list_lock); + if (CKR_OK != *pError) { + (void)nss_dbm_db_delete_object(object->handle); + return (NSSCKMDObject *)NULL; + } + + node->next = session->session_objects; + session->session_objects = node; + + *pError = NSSCKFWMutex_Unlock(session->list_lock); + } + } + + return rv; } /* CopyObject isn't needed; the framework will use CreateObject */ static NSSCKMDFindObjects * -nss_dbm_mdSession_FindObjectsInit -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_dbm_mdSession_FindObjectsInit( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - NSSArena *arena; - nss_dbm_find_t *find; - NSSCKMDFindObjects *rv; + nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc; + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + NSSArena *arena; + nss_dbm_find_t *find; + NSSCKMDFindObjects *rv; - arena = NSSArena_Create(); - if( (NSSArena *)NULL == arena ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + arena = NSSArena_Create(); + if ((NSSArena *)NULL == arena) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - find = nss_ZNEW(arena, nss_dbm_find_t); - if( (nss_dbm_find_t *)NULL == find ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + find = nss_ZNEW(arena, nss_dbm_find_t); + if ((nss_dbm_find_t *)NULL == find) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - find->arena = arena; - find->list_lock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError); - if( (NSSCKFWMutex *)NULL == find->list_lock ) { - goto loser; - } + find->arena = arena; + find->list_lock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError); + if ((NSSCKFWMutex *)NULL == find->list_lock) { + goto loser; + } - *pError = nss_dbm_db_find_objects(find, token->slot->token_db, pTemplate, - ulAttributeCount, &session->deviceError); - if( CKR_OK != *pError ) { - goto loser; - } + *pError = nss_dbm_db_find_objects(find, token->slot->token_db, pTemplate, + ulAttributeCount, &session->deviceError); + if (CKR_OK != *pError) { + goto loser; + } - *pError = nss_dbm_db_find_objects(find, token->session_db, pTemplate, - ulAttributeCount, &session->deviceError); - if( CKR_OK != *pError ) { - goto loser; - } + *pError = nss_dbm_db_find_objects(find, token->session_db, pTemplate, + ulAttributeCount, &session->deviceError); + if (CKR_OK != *pError) { + goto loser; + } - rv = nss_dbm_mdFindObjects_factory(find, pError); - if( (NSSCKMDFindObjects *)NULL == rv ) { - goto loser; - } + rv = nss_dbm_mdFindObjects_factory(find, pError); + if ((NSSCKMDFindObjects *)NULL == rv) { + goto loser; + } - return rv; + return rv; - loser: - if( (NSSArena *)NULL != arena ) { - (void)NSSArena_Destroy(arena); - } +loser: + if ((NSSArena *)NULL != arena) { + (void)NSSArena_Destroy(arena); + } - return (NSSCKMDFindObjects *)NULL; + return (NSSCKMDFindObjects *)NULL; } /* SeedRandom is irrelevant */ /* GetRandom is irrelevant */ NSS_IMPLEMENT NSSCKMDSession * -nss_dbm_mdSession_factory -( - nss_dbm_token_t *token, - NSSCKFWSession *fwSession, - NSSCKFWInstance *fwInstance, - CK_BBOOL rw, - CK_RV *pError -) +nss_dbm_mdSession_factory( + nss_dbm_token_t *token, + NSSCKFWSession *fwSession, + NSSCKFWInstance *fwInstance, + CK_BBOOL rw, + CK_RV *pError) { - NSSArena *arena; - nss_dbm_session_t *session; - NSSCKMDSession *rv; + NSSArena *arena; + nss_dbm_session_t *session; + NSSCKMDSession *rv; - arena = NSSCKFWSession_GetArena(fwSession, pError); + arena = NSSCKFWSession_GetArena(fwSession, pError); - session = nss_ZNEW(arena, nss_dbm_session_t); - if( (nss_dbm_session_t *)NULL == session ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDSession *)NULL; - } + session = nss_ZNEW(arena, nss_dbm_session_t); + if ((nss_dbm_session_t *)NULL == session) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDSession *)NULL; + } - rv = nss_ZNEW(arena, NSSCKMDSession); - if( (NSSCKMDSession *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDSession *)NULL; - } + rv = nss_ZNEW(arena, NSSCKMDSession); + if ((NSSCKMDSession *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDSession *)NULL; + } - session->arena = arena; - session->token = token; - session->list_lock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError); - if( (NSSCKFWMutex *)NULL == session->list_lock ) { - return (NSSCKMDSession *)NULL; - } + session->arena = arena; + session->token = token; + session->list_lock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError); + if ((NSSCKFWMutex *)NULL == session->list_lock) { + return (NSSCKMDSession *)NULL; + } - rv->etc = (void *)session; - rv->Close = nss_dbm_mdSession_Close; - rv->GetDeviceError = nss_dbm_mdSession_GetDeviceError; - /* Login isn't needed */ - /* Logout isn't needed */ - /* InitPIN is irrelevant */ - /* SetPIN is irrelevant */ - /* GetOperationStateLen is irrelevant */ - /* GetOperationState is irrelevant */ - /* SetOperationState is irrelevant */ - rv->CreateObject = nss_dbm_mdSession_CreateObject; - /* CopyObject isn't needed; the framework will use CreateObject */ - rv->FindObjectsInit = nss_dbm_mdSession_FindObjectsInit; - rv->null = NULL; + rv->etc = (void *)session; + rv->Close = nss_dbm_mdSession_Close; + rv->GetDeviceError = nss_dbm_mdSession_GetDeviceError; + /* Login isn't needed */ + /* Logout isn't needed */ + /* InitPIN is irrelevant */ + /* SetPIN is irrelevant */ + /* GetOperationStateLen is irrelevant */ + /* GetOperationState is irrelevant */ + /* SetOperationState is irrelevant */ + rv->CreateObject = nss_dbm_mdSession_CreateObject; + /* CopyObject isn't needed; the framework will use CreateObject */ + rv->FindObjectsInit = nss_dbm_mdSession_FindObjectsInit; + rv->null = NULL; - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/dbm/slot.c b/security/nss/lib/ckfw/dbm/slot.c index 0b7e645dff60..827b4ca8a6a0 100644 --- a/security/nss/lib/ckfw/dbm/slot.c +++ b/security/nss/lib/ckfw/dbm/slot.c @@ -5,113 +5,102 @@ #include "ckdbm.h" static CK_RV -nss_dbm_mdSlot_Initialize -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdSlot_Initialize( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; - nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; - CK_RV rv = CKR_OK; + nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; + nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; + CK_RV rv = CKR_OK; - slot->token_db = nss_dbm_db_open(instance->arena, fwInstance, slot->filename, - slot->flags, &rv); - if( (nss_dbm_db_t *)NULL == slot->token_db ) { - if( CKR_TOKEN_NOT_PRESENT == rv ) { - /* This is not an error-- just means "the token isn't there" */ - rv = CKR_OK; + slot->token_db = nss_dbm_db_open(instance->arena, fwInstance, slot->filename, + slot->flags, &rv); + if ((nss_dbm_db_t *)NULL == slot->token_db) { + if (CKR_TOKEN_NOT_PRESENT == rv) { + /* This is not an error-- just means "the token isn't there" */ + rv = CKR_OK; + } } - } - return rv; + return rv; } static void -nss_dbm_mdSlot_Destroy -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdSlot_Destroy( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; + nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; - if( (nss_dbm_db_t *)NULL != slot->token_db ) { - nss_dbm_db_close(slot->token_db); - slot->token_db = (nss_dbm_db_t *)NULL; - } + if ((nss_dbm_db_t *)NULL != slot->token_db) { + nss_dbm_db_close(slot->token_db); + slot->token_db = (nss_dbm_db_t *)NULL; + } } static NSSUTF8 * -nss_dbm_mdSlot_GetSlotDescription -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdSlot_GetSlotDescription( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return "Database"; + return "Database"; } static NSSUTF8 * -nss_dbm_mdSlot_GetManufacturerID -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdSlot_GetManufacturerID( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return "Berkeley"; + return "Berkeley"; } static CK_BBOOL -nss_dbm_mdSlot_GetTokenPresent -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdSlot_GetTokenPresent( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; + nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; + + if ((nss_dbm_db_t *)NULL == slot->token_db) { + return CK_FALSE; + } + else { + return CK_TRUE; + } +} + +static CK_BBOOL +nss_dbm_mdSlot_GetRemovableDevice( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) +{ + /* + * Well, this supports "tokens" (databases) that aren't there, so in + * that sense they're removable. It'd be nice to handle databases + * that suddenly disappear (NFS-mounted home directories and network + * errors, for instance) but that's a harder problem. We'll say + * we support removable devices, badly. + */ - if( (nss_dbm_db_t *)NULL == slot->token_db ) { - return CK_FALSE; - } else { return CK_TRUE; - } -} - -static CK_BBOOL -nss_dbm_mdSlot_GetRemovableDevice -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) -{ - /* - * Well, this supports "tokens" (databases) that aren't there, so in - * that sense they're removable. It'd be nice to handle databases - * that suddenly disappear (NFS-mounted home directories and network - * errors, for instance) but that's a harder problem. We'll say - * we support removable devices, badly. - */ - - return CK_TRUE; } /* nss_dbm_mdSlot_GetHardwareSlot defaults to CK_FALSE */ -/* +/* * nss_dbm_mdSlot_GetHardwareVersion * nss_dbm_mdSlot_GetFirmwareVersion * @@ -122,60 +111,56 @@ nss_dbm_mdSlot_GetRemovableDevice */ static NSSCKMDToken * -nss_dbm_mdSlot_GetToken -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdSlot_GetToken( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; - return nss_dbm_mdToken_factory(slot, pError); + nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc; + return nss_dbm_mdToken_factory(slot, pError); } NSS_IMPLEMENT NSSCKMDSlot * -nss_dbm_mdSlot_factory -( - nss_dbm_instance_t *instance, - char *filename, - int flags, - CK_RV *pError -) +nss_dbm_mdSlot_factory( + nss_dbm_instance_t *instance, + char *filename, + int flags, + CK_RV *pError) { - nss_dbm_slot_t *slot; - NSSCKMDSlot *rv; + nss_dbm_slot_t *slot; + NSSCKMDSlot *rv; - slot = nss_ZNEW(instance->arena, nss_dbm_slot_t); - if( (nss_dbm_slot_t *)NULL == slot ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDSlot *)NULL; - } + slot = nss_ZNEW(instance->arena, nss_dbm_slot_t); + if ((nss_dbm_slot_t *)NULL == slot) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDSlot *)NULL; + } - slot->instance = instance; - slot->filename = filename; - slot->flags = flags; - slot->token_db = (nss_dbm_db_t *)NULL; + slot->instance = instance; + slot->filename = filename; + slot->flags = flags; + slot->token_db = (nss_dbm_db_t *)NULL; - rv = nss_ZNEW(instance->arena, NSSCKMDSlot); - if( (NSSCKMDSlot *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDSlot *)NULL; - } + rv = nss_ZNEW(instance->arena, NSSCKMDSlot); + if ((NSSCKMDSlot *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDSlot *)NULL; + } - rv->etc = (void *)slot; - rv->Initialize = nss_dbm_mdSlot_Initialize; - rv->Destroy = nss_dbm_mdSlot_Destroy; - rv->GetSlotDescription = nss_dbm_mdSlot_GetSlotDescription; - rv->GetManufacturerID = nss_dbm_mdSlot_GetManufacturerID; - rv->GetTokenPresent = nss_dbm_mdSlot_GetTokenPresent; - rv->GetRemovableDevice = nss_dbm_mdSlot_GetRemovableDevice; - /* GetHardwareSlot */ - /* GetHardwareVersion */ - /* GetFirmwareVersion */ - rv->GetToken = nss_dbm_mdSlot_GetToken; - rv->null = (void *)NULL; + rv->etc = (void *)slot; + rv->Initialize = nss_dbm_mdSlot_Initialize; + rv->Destroy = nss_dbm_mdSlot_Destroy; + rv->GetSlotDescription = nss_dbm_mdSlot_GetSlotDescription; + rv->GetManufacturerID = nss_dbm_mdSlot_GetManufacturerID; + rv->GetTokenPresent = nss_dbm_mdSlot_GetTokenPresent; + rv->GetRemovableDevice = nss_dbm_mdSlot_GetRemovableDevice; + /* GetHardwareSlot */ + /* GetHardwareVersion */ + /* GetFirmwareVersion */ + rv->GetToken = nss_dbm_mdSlot_GetToken; + rv->null = (void *)NULL; - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/dbm/token.c b/security/nss/lib/ckfw/dbm/token.c index e033e150480d..4648b8bef10e 100644 --- a/security/nss/lib/ckfw/dbm/token.c +++ b/security/nss/lib/ckfw/dbm/token.c @@ -5,168 +5,155 @@ #include "ckdbm.h" static CK_RV -nss_dbm_mdToken_Setup -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdToken_Setup( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - CK_RV rv = CKR_OK; + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + CK_RV rv = CKR_OK; - token->arena = NSSCKFWToken_GetArena(fwToken, &rv); - token->session_db = nss_dbm_db_open(token->arena, fwInstance, (char *)NULL, - O_RDWR|O_CREAT, &rv); - if( (nss_dbm_db_t *)NULL == token->session_db ) { - return rv; - } + token->arena = NSSCKFWToken_GetArena(fwToken, &rv); + token->session_db = nss_dbm_db_open(token->arena, fwInstance, (char *)NULL, + O_RDWR | O_CREAT, &rv); + if ((nss_dbm_db_t *)NULL == token->session_db) { + return rv; + } - /* Add a label record if there isn't one? */ + /* Add a label record if there isn't one? */ - return CKR_OK; + return CKR_OK; } static void -nss_dbm_mdToken_Invalidate -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdToken_Invalidate( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - if( (nss_dbm_db_t *)NULL != token->session_db ) { - nss_dbm_db_close(token->session_db); - token->session_db = (nss_dbm_db_t *)NULL; - } + if ((nss_dbm_db_t *)NULL != token->session_db) { + nss_dbm_db_close(token->session_db); + token->session_db = (nss_dbm_db_t *)NULL; + } } static CK_RV -nss_dbm_mdToken_InitToken -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *pin, - NSSUTF8 *label -) +nss_dbm_mdToken_InitToken( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *pin, + NSSUTF8 *label) { - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; - CK_RV rv; + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc; + CK_RV rv; - /* Wipe the session object data */ - - if( (nss_dbm_db_t *)NULL != token->session_db ) { - nss_dbm_db_close(token->session_db); - } + /* Wipe the session object data */ - token->session_db = nss_dbm_db_open(token->arena, fwInstance, (char *)NULL, - O_RDWR|O_CREAT, &rv); - if( (nss_dbm_db_t *)NULL == token->session_db ) { - return rv; - } - - /* Wipe the token object data */ - - if( token->slot->flags & O_RDWR ) { - if( (nss_dbm_db_t *)NULL != token->slot->token_db ) { - nss_dbm_db_close(token->slot->token_db); + if ((nss_dbm_db_t *)NULL != token->session_db) { + nss_dbm_db_close(token->session_db); } - token->slot->token_db = nss_dbm_db_open(instance->arena, fwInstance, - token->slot->filename, - token->slot->flags | O_CREAT | O_TRUNC, - &rv); - if( (nss_dbm_db_t *)NULL == token->slot->token_db ) { - return rv; + token->session_db = nss_dbm_db_open(token->arena, fwInstance, (char *)NULL, + O_RDWR | O_CREAT, &rv); + if ((nss_dbm_db_t *)NULL == token->session_db) { + return rv; } - /* PIN is irrelevant */ + /* Wipe the token object data */ - rv = nss_dbm_db_set_label(token->slot->token_db, label); - if( CKR_OK != rv ) { - return rv; + if (token->slot->flags & O_RDWR) { + if ((nss_dbm_db_t *)NULL != token->slot->token_db) { + nss_dbm_db_close(token->slot->token_db); + } + + token->slot->token_db = nss_dbm_db_open(instance->arena, fwInstance, + token->slot->filename, + token->slot->flags | O_CREAT | O_TRUNC, + &rv); + if ((nss_dbm_db_t *)NULL == token->slot->token_db) { + return rv; + } + + /* PIN is irrelevant */ + + rv = nss_dbm_db_set_label(token->slot->token_db, label); + if (CKR_OK != rv) { + return rv; + } } - } - return CKR_OK; + return CKR_OK; } static NSSUTF8 * -nss_dbm_mdToken_GetLabel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdToken_GetLabel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - if( (NSSUTF8 *)NULL == token->label ) { - token->label = nss_dbm_db_get_label(token->slot->token_db, token->arena, pError); - } + if ((NSSUTF8 *)NULL == token->label) { + token->label = nss_dbm_db_get_label(token->slot->token_db, token->arena, pError); + } - /* If no label has been set, return *something* */ - if( (NSSUTF8 *)NULL == token->label ) { - return token->slot->filename; - } + /* If no label has been set, return *something* */ + if ((NSSUTF8 *)NULL == token->label) { + return token->slot->filename; + } - return token->label; + return token->label; } static NSSUTF8 * -nss_dbm_mdToken_GetManufacturerID -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdToken_GetManufacturerID( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return "mozilla.org NSS"; + return "mozilla.org NSS"; } static NSSUTF8 * -nss_dbm_mdToken_GetModel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_dbm_mdToken_GetModel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return "dbm"; + return "dbm"; } /* GetSerialNumber is irrelevant */ /* GetHasRNG defaults to CK_FALSE */ static CK_BBOOL -nss_dbm_mdToken_GetIsWriteProtected -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdToken_GetIsWriteProtected( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - if( token->slot->flags & O_RDWR ) { - return CK_FALSE; - } else { - return CK_TRUE; - } + if (token->slot->flags & O_RDWR) { + return CK_FALSE; + } + else { + return CK_TRUE; + } } /* GetLoginRequired defaults to CK_FALSE */ @@ -177,47 +164,41 @@ nss_dbm_mdToken_GetIsWriteProtected /* GetSupportsDualCryptoOperations is irrelevant */ static CK_ULONG -nss_dbm_mdToken_effectively_infinite -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdToken_effectively_infinite( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_EFFECTIVELY_INFINITE; + return CK_EFFECTIVELY_INFINITE; } static CK_VERSION -nss_dbm_mdToken_GetHardwareVersion -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_dbm_mdToken_GetHardwareVersion( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - return nss_dbm_db_get_format_version(token->slot->token_db); + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + return nss_dbm_db_get_format_version(token->slot->token_db); } /* GetFirmwareVersion is irrelevant */ /* GetUTCTime is irrelevant */ static NSSCKMDSession * -nss_dbm_mdToken_OpenSession -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession, - CK_BBOOL rw, - CK_RV *pError -) +nss_dbm_mdToken_OpenSession( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession, + CK_BBOOL rw, + CK_RV *pError) { - nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; - return nss_dbm_mdSession_factory(token, fwSession, fwInstance, rw, pError); + nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc; + return nss_dbm_mdSession_factory(token, fwSession, fwInstance, rw, pError); } /* GetMechanismCount defaults to zero */ @@ -225,58 +206,56 @@ nss_dbm_mdToken_OpenSession /* GetMechanism is irrelevant */ NSS_IMPLEMENT NSSCKMDToken * -nss_dbm_mdToken_factory -( - nss_dbm_slot_t *slot, - CK_RV *pError -) +nss_dbm_mdToken_factory( + nss_dbm_slot_t *slot, + CK_RV *pError) { - nss_dbm_token_t *token; - NSSCKMDToken *rv; + nss_dbm_token_t *token; + NSSCKMDToken *rv; - token = nss_ZNEW(slot->instance->arena, nss_dbm_token_t); - if( (nss_dbm_token_t *)NULL == token ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDToken *)NULL; - } + token = nss_ZNEW(slot->instance->arena, nss_dbm_token_t); + if ((nss_dbm_token_t *)NULL == token) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDToken *)NULL; + } - rv = nss_ZNEW(slot->instance->arena, NSSCKMDToken); - if( (NSSCKMDToken *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDToken *)NULL; - } + rv = nss_ZNEW(slot->instance->arena, NSSCKMDToken); + if ((NSSCKMDToken *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDToken *)NULL; + } - token->slot = slot; + token->slot = slot; - rv->etc = (void *)token; - rv->Setup = nss_dbm_mdToken_Setup; - rv->Invalidate = nss_dbm_mdToken_Invalidate; - rv->InitToken = nss_dbm_mdToken_InitToken; - rv->GetLabel = nss_dbm_mdToken_GetLabel; - rv->GetManufacturerID = nss_dbm_mdToken_GetManufacturerID; - rv->GetModel = nss_dbm_mdToken_GetModel; - /* GetSerialNumber is irrelevant */ - /* GetHasRNG defaults to CK_FALSE */ - rv->GetIsWriteProtected = nss_dbm_mdToken_GetIsWriteProtected; - /* GetLoginRequired defaults to CK_FALSE */ - /* GetUserPinInitialized defaults to CK_FALSE */ - /* GetRestoreKeyNotNeeded is irrelevant */ - /* GetHasClockOnToken defaults to CK_FALSE */ - /* GetHasProtectedAuthenticationPath defaults to CK_FALSE */ - /* GetSupportsDualCryptoOperations is irrelevant */ - rv->GetMaxSessionCount = nss_dbm_mdToken_effectively_infinite; - rv->GetMaxRwSessionCount = nss_dbm_mdToken_effectively_infinite; - /* GetMaxPinLen is irrelevant */ - /* GetMinPinLen is irrelevant */ - /* GetTotalPublicMemory defaults to CK_UNAVAILABLE_INFORMATION */ - /* GetFreePublicMemory defaults to CK_UNAVAILABLE_INFORMATION */ - /* GetTotalPrivateMemory defaults to CK_UNAVAILABLE_INFORMATION */ - /* GetFreePrivateMemory defaults to CK_UNAVAILABLE_INFORMATION */ - rv->GetHardwareVersion = nss_dbm_mdToken_GetHardwareVersion; - /* GetFirmwareVersion is irrelevant */ - /* GetUTCTime is irrelevant */ - rv->OpenSession = nss_dbm_mdToken_OpenSession; - rv->null = NULL; + rv->etc = (void *)token; + rv->Setup = nss_dbm_mdToken_Setup; + rv->Invalidate = nss_dbm_mdToken_Invalidate; + rv->InitToken = nss_dbm_mdToken_InitToken; + rv->GetLabel = nss_dbm_mdToken_GetLabel; + rv->GetManufacturerID = nss_dbm_mdToken_GetManufacturerID; + rv->GetModel = nss_dbm_mdToken_GetModel; + /* GetSerialNumber is irrelevant */ + /* GetHasRNG defaults to CK_FALSE */ + rv->GetIsWriteProtected = nss_dbm_mdToken_GetIsWriteProtected; + /* GetLoginRequired defaults to CK_FALSE */ + /* GetUserPinInitialized defaults to CK_FALSE */ + /* GetRestoreKeyNotNeeded is irrelevant */ + /* GetHasClockOnToken defaults to CK_FALSE */ + /* GetHasProtectedAuthenticationPath defaults to CK_FALSE */ + /* GetSupportsDualCryptoOperations is irrelevant */ + rv->GetMaxSessionCount = nss_dbm_mdToken_effectively_infinite; + rv->GetMaxRwSessionCount = nss_dbm_mdToken_effectively_infinite; + /* GetMaxPinLen is irrelevant */ + /* GetMinPinLen is irrelevant */ + /* GetTotalPublicMemory defaults to CK_UNAVAILABLE_INFORMATION */ + /* GetFreePublicMemory defaults to CK_UNAVAILABLE_INFORMATION */ + /* GetTotalPrivateMemory defaults to CK_UNAVAILABLE_INFORMATION */ + /* GetFreePrivateMemory defaults to CK_UNAVAILABLE_INFORMATION */ + rv->GetHardwareVersion = nss_dbm_mdToken_GetHardwareVersion; + /* GetFirmwareVersion is irrelevant */ + /* GetUTCTime is irrelevant */ + rv->OpenSession = nss_dbm_mdToken_OpenSession; + rv->null = NULL; - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/find.c b/security/nss/lib/ckfw/find.c index 8a8a5415dd06..798a20b2f42d 100644 --- a/security/nss/lib/ckfw/find.c +++ b/security/nss/lib/ckfw/find.c @@ -21,7 +21,7 @@ * * -- public accessors -- * NSSCKFWFindObjects_GetMDFindObjects - * + * * -- implement public accessors -- * nssCKFWFindObjects_GetMDFindObjects * @@ -32,17 +32,17 @@ */ struct NSSCKFWFindObjectsStr { - NSSCKFWMutex *mutex; /* merely to serialise the MDObject calls */ - NSSCKMDFindObjects *mdfo1; - NSSCKMDFindObjects *mdfo2; - NSSCKFWSession *fwSession; - NSSCKMDSession *mdSession; - NSSCKFWToken *fwToken; - NSSCKMDToken *mdToken; - NSSCKFWInstance *fwInstance; - NSSCKMDInstance *mdInstance; + NSSCKFWMutex *mutex; /* merely to serialise the MDObject calls */ + NSSCKMDFindObjects *mdfo1; + NSSCKMDFindObjects *mdfo2; + NSSCKFWSession *fwSession; + NSSCKMDSession *mdSession; + NSSCKFWToken *fwToken; + NSSCKMDToken *mdToken; + NSSCKFWInstance *fwInstance; + NSSCKMDInstance *mdInstance; - NSSCKMDFindObjects *mdFindObjects; /* varies */ + NSSCKMDFindObjects *mdFindObjects; /* varies */ }; #ifdef DEBUG @@ -58,30 +58,24 @@ struct NSSCKFWFindObjectsStr { */ static CK_RV -findObjects_add_pointer -( - const NSSCKFWFindObjects *fwFindObjects -) +findObjects_add_pointer( + const NSSCKFWFindObjects *fwFindObjects) { - return CKR_OK; + return CKR_OK; } static CK_RV -findObjects_remove_pointer -( - const NSSCKFWFindObjects *fwFindObjects -) +findObjects_remove_pointer( + const NSSCKFWFindObjects *fwFindObjects) { - return CKR_OK; + return CKR_OK; } NSS_IMPLEMENT CK_RV -nssCKFWFindObjects_verifyPointer -( - const NSSCKFWFindObjects *fwFindObjects -) +nssCKFWFindObjects_verifyPointer( + const NSSCKFWFindObjects *fwFindObjects) { - return CKR_OK; + return CKR_OK; } #endif /* DEBUG */ @@ -91,128 +85,123 @@ nssCKFWFindObjects_verifyPointer * */ NSS_EXTERN NSSCKFWFindObjects * -nssCKFWFindObjects_Create -( - NSSCKFWSession *fwSession, - NSSCKFWToken *fwToken, - NSSCKFWInstance *fwInstance, - NSSCKMDFindObjects *mdFindObjects1, - NSSCKMDFindObjects *mdFindObjects2, - CK_RV *pError -) +nssCKFWFindObjects_Create( + NSSCKFWSession *fwSession, + NSSCKFWToken *fwToken, + NSSCKFWInstance *fwInstance, + NSSCKMDFindObjects *mdFindObjects1, + NSSCKMDFindObjects *mdFindObjects2, + CK_RV *pError) { - NSSCKFWFindObjects *fwFindObjects = NULL; - NSSCKMDSession *mdSession; - NSSCKMDToken *mdToken; - NSSCKMDInstance *mdInstance; + NSSCKFWFindObjects *fwFindObjects = NULL; + NSSCKMDSession *mdSession; + NSSCKMDToken *mdToken; + NSSCKMDInstance *mdInstance; - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdToken = nssCKFWToken_GetMDToken(fwToken); - mdInstance = nssCKFWInstance_GetMDInstance(fwInstance); + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdToken = nssCKFWToken_GetMDToken(fwToken); + mdInstance = nssCKFWInstance_GetMDInstance(fwInstance); - fwFindObjects = nss_ZNEW(NULL, NSSCKFWFindObjects); - if (!fwFindObjects) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + fwFindObjects = nss_ZNEW(NULL, NSSCKFWFindObjects); + if (!fwFindObjects) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - fwFindObjects->mdfo1 = mdFindObjects1; - fwFindObjects->mdfo2 = mdFindObjects2; - fwFindObjects->fwSession = fwSession; - fwFindObjects->mdSession = mdSession; - fwFindObjects->fwToken = fwToken; - fwFindObjects->mdToken = mdToken; - fwFindObjects->fwInstance = fwInstance; - fwFindObjects->mdInstance = mdInstance; + fwFindObjects->mdfo1 = mdFindObjects1; + fwFindObjects->mdfo2 = mdFindObjects2; + fwFindObjects->fwSession = fwSession; + fwFindObjects->mdSession = mdSession; + fwFindObjects->fwToken = fwToken; + fwFindObjects->mdToken = mdToken; + fwFindObjects->fwInstance = fwInstance; + fwFindObjects->mdInstance = mdInstance; - fwFindObjects->mutex = nssCKFWInstance_CreateMutex(fwInstance, NULL, pError); - if (!fwFindObjects->mutex) { - goto loser; - } + fwFindObjects->mutex = nssCKFWInstance_CreateMutex(fwInstance, NULL, pError); + if (!fwFindObjects->mutex) { + goto loser; + } #ifdef DEBUG - *pError = findObjects_add_pointer(fwFindObjects); - if( CKR_OK != *pError ) { - goto loser; - } + *pError = findObjects_add_pointer(fwFindObjects); + if (CKR_OK != *pError) { + goto loser; + } #endif /* DEBUG */ - return fwFindObjects; + return fwFindObjects; - loser: - if( fwFindObjects ) { - if( NULL != mdFindObjects1 ) { - if( NULL != mdFindObjects1->Final ) { - fwFindObjects->mdFindObjects = mdFindObjects1; - mdFindObjects1->Final(mdFindObjects1, fwFindObjects, mdSession, - fwSession, mdToken, fwToken, mdInstance, fwInstance); - } +loser: + if (fwFindObjects) { + if (NULL != mdFindObjects1) { + if (NULL != mdFindObjects1->Final) { + fwFindObjects->mdFindObjects = mdFindObjects1; + mdFindObjects1->Final(mdFindObjects1, fwFindObjects, mdSession, + fwSession, mdToken, fwToken, mdInstance, fwInstance); + } + } + + if (NULL != mdFindObjects2) { + if (NULL != mdFindObjects2->Final) { + fwFindObjects->mdFindObjects = mdFindObjects2; + mdFindObjects2->Final(mdFindObjects2, fwFindObjects, mdSession, + fwSession, mdToken, fwToken, mdInstance, fwInstance); + } + } + + nss_ZFreeIf(fwFindObjects); } - if( NULL != mdFindObjects2 ) { - if( NULL != mdFindObjects2->Final ) { - fwFindObjects->mdFindObjects = mdFindObjects2; - mdFindObjects2->Final(mdFindObjects2, fwFindObjects, mdSession, - fwSession, mdToken, fwToken, mdInstance, fwInstance); - } + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; } - nss_ZFreeIf(fwFindObjects); - } - - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - - return (NSSCKFWFindObjects *)NULL; + return (NSSCKFWFindObjects *)NULL; } - /* * nssCKFWFindObjects_Destroy * */ NSS_EXTERN void -nssCKFWFindObjects_Destroy -( - NSSCKFWFindObjects *fwFindObjects -) +nssCKFWFindObjects_Destroy( + NSSCKFWFindObjects *fwFindObjects) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWFindObjects_verifyPointer(fwFindObjects) ) { - return; - } + if (CKR_OK != nssCKFWFindObjects_verifyPointer(fwFindObjects)) { + return; + } #endif /* NSSDEBUG */ - (void)nssCKFWMutex_Destroy(fwFindObjects->mutex); + (void)nssCKFWMutex_Destroy(fwFindObjects->mutex); - if (fwFindObjects->mdfo1) { - if (fwFindObjects->mdfo1->Final) { - fwFindObjects->mdFindObjects = fwFindObjects->mdfo1; - fwFindObjects->mdfo1->Final(fwFindObjects->mdfo1, fwFindObjects, - fwFindObjects->mdSession, fwFindObjects->fwSession, - fwFindObjects->mdToken, fwFindObjects->fwToken, - fwFindObjects->mdInstance, fwFindObjects->fwInstance); + if (fwFindObjects->mdfo1) { + if (fwFindObjects->mdfo1->Final) { + fwFindObjects->mdFindObjects = fwFindObjects->mdfo1; + fwFindObjects->mdfo1->Final(fwFindObjects->mdfo1, fwFindObjects, + fwFindObjects->mdSession, fwFindObjects->fwSession, + fwFindObjects->mdToken, fwFindObjects->fwToken, + fwFindObjects->mdInstance, fwFindObjects->fwInstance); + } } - } - if (fwFindObjects->mdfo2) { - if (fwFindObjects->mdfo2->Final) { - fwFindObjects->mdFindObjects = fwFindObjects->mdfo2; - fwFindObjects->mdfo2->Final(fwFindObjects->mdfo2, fwFindObjects, - fwFindObjects->mdSession, fwFindObjects->fwSession, - fwFindObjects->mdToken, fwFindObjects->fwToken, - fwFindObjects->mdInstance, fwFindObjects->fwInstance); + if (fwFindObjects->mdfo2) { + if (fwFindObjects->mdfo2->Final) { + fwFindObjects->mdFindObjects = fwFindObjects->mdfo2; + fwFindObjects->mdfo2->Final(fwFindObjects->mdfo2, fwFindObjects, + fwFindObjects->mdSession, fwFindObjects->fwSession, + fwFindObjects->mdToken, fwFindObjects->fwToken, + fwFindObjects->mdInstance, fwFindObjects->fwInstance); + } } - } - nss_ZFreeIf(fwFindObjects); + nss_ZFreeIf(fwFindObjects); #ifdef DEBUG - (void)findObjects_remove_pointer(fwFindObjects); + (void)findObjects_remove_pointer(fwFindObjects); #endif /* DEBUG */ - return; + return; } /* @@ -220,18 +209,16 @@ nssCKFWFindObjects_Destroy * */ NSS_EXTERN NSSCKMDFindObjects * -nssCKFWFindObjects_GetMDFindObjects -( - NSSCKFWFindObjects *fwFindObjects -) +nssCKFWFindObjects_GetMDFindObjects( + NSSCKFWFindObjects *fwFindObjects) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWFindObjects_verifyPointer(fwFindObjects) ) { - return (NSSCKMDFindObjects *)NULL; - } + if (CKR_OK != nssCKFWFindObjects_verifyPointer(fwFindObjects)) { + return (NSSCKMDFindObjects *)NULL; + } #endif /* NSSDEBUG */ - return fwFindObjects->mdFindObjects; + return fwFindObjects->mdFindObjects; } /* @@ -239,89 +226,89 @@ nssCKFWFindObjects_GetMDFindObjects * */ NSS_EXTERN NSSCKFWObject * -nssCKFWFindObjects_Next -( - NSSCKFWFindObjects *fwFindObjects, - NSSArena *arenaOpt, - CK_RV *pError -) +nssCKFWFindObjects_Next( + NSSCKFWFindObjects *fwFindObjects, + NSSArena *arenaOpt, + CK_RV *pError) { - NSSCKMDObject *mdObject; - NSSCKFWObject *fwObject = (NSSCKFWObject *)NULL; - NSSArena *objArena; + NSSCKMDObject *mdObject; + NSSCKFWObject *fwObject = (NSSCKFWObject *)NULL; + NSSArena *objArena; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWObject *)NULL; - } + if (!pError) { + return (NSSCKFWObject *)NULL; + } - *pError = nssCKFWFindObjects_verifyPointer(fwFindObjects); - if( CKR_OK != *pError ) { - return (NSSCKFWObject *)NULL; - } + *pError = nssCKFWFindObjects_verifyPointer(fwFindObjects); + if (CKR_OK != *pError) { + return (NSSCKFWObject *)NULL; + } #endif /* NSSDEBUG */ - *pError = nssCKFWMutex_Lock(fwFindObjects->mutex); - if( CKR_OK != *pError ) { - return (NSSCKFWObject *)NULL; - } - - if (fwFindObjects->mdfo1) { - if (fwFindObjects->mdfo1->Next) { - fwFindObjects->mdFindObjects = fwFindObjects->mdfo1; - mdObject = fwFindObjects->mdfo1->Next(fwFindObjects->mdfo1, - fwFindObjects, fwFindObjects->mdSession, fwFindObjects->fwSession, - fwFindObjects->mdToken, fwFindObjects->fwToken, - fwFindObjects->mdInstance, fwFindObjects->fwInstance, - arenaOpt, pError); - if (!mdObject) { - if( CKR_OK != *pError ) { - goto done; - } - - /* All done. */ - fwFindObjects->mdfo1->Final(fwFindObjects->mdfo1, fwFindObjects, - fwFindObjects->mdSession, fwFindObjects->fwSession, - fwFindObjects->mdToken, fwFindObjects->fwToken, - fwFindObjects->mdInstance, fwFindObjects->fwInstance); - fwFindObjects->mdfo1 = (NSSCKMDFindObjects *)NULL; - } else { - goto wrap; - } + *pError = nssCKFWMutex_Lock(fwFindObjects->mutex); + if (CKR_OK != *pError) { + return (NSSCKFWObject *)NULL; } - } - if (fwFindObjects->mdfo2) { - if (fwFindObjects->mdfo2->Next) { - fwFindObjects->mdFindObjects = fwFindObjects->mdfo2; - mdObject = fwFindObjects->mdfo2->Next(fwFindObjects->mdfo2, - fwFindObjects, fwFindObjects->mdSession, fwFindObjects->fwSession, - fwFindObjects->mdToken, fwFindObjects->fwToken, - fwFindObjects->mdInstance, fwFindObjects->fwInstance, - arenaOpt, pError); - if (!mdObject) { - if( CKR_OK != *pError ) { - goto done; + if (fwFindObjects->mdfo1) { + if (fwFindObjects->mdfo1->Next) { + fwFindObjects->mdFindObjects = fwFindObjects->mdfo1; + mdObject = fwFindObjects->mdfo1->Next(fwFindObjects->mdfo1, + fwFindObjects, fwFindObjects->mdSession, fwFindObjects->fwSession, + fwFindObjects->mdToken, fwFindObjects->fwToken, + fwFindObjects->mdInstance, fwFindObjects->fwInstance, + arenaOpt, pError); + if (!mdObject) { + if (CKR_OK != *pError) { + goto done; + } + + /* All done. */ + fwFindObjects->mdfo1->Final(fwFindObjects->mdfo1, fwFindObjects, + fwFindObjects->mdSession, fwFindObjects->fwSession, + fwFindObjects->mdToken, fwFindObjects->fwToken, + fwFindObjects->mdInstance, fwFindObjects->fwInstance); + fwFindObjects->mdfo1 = (NSSCKMDFindObjects *)NULL; + } + else { + goto wrap; + } } - - /* All done. */ - fwFindObjects->mdfo2->Final(fwFindObjects->mdfo2, fwFindObjects, - fwFindObjects->mdSession, fwFindObjects->fwSession, - fwFindObjects->mdToken, fwFindObjects->fwToken, - fwFindObjects->mdInstance, fwFindObjects->fwInstance); - fwFindObjects->mdfo2 = (NSSCKMDFindObjects *)NULL; - } else { - goto wrap; - } } - } - - /* No more objects */ - *pError = CKR_OK; - goto done; - wrap: - /* + if (fwFindObjects->mdfo2) { + if (fwFindObjects->mdfo2->Next) { + fwFindObjects->mdFindObjects = fwFindObjects->mdfo2; + mdObject = fwFindObjects->mdfo2->Next(fwFindObjects->mdfo2, + fwFindObjects, fwFindObjects->mdSession, fwFindObjects->fwSession, + fwFindObjects->mdToken, fwFindObjects->fwToken, + fwFindObjects->mdInstance, fwFindObjects->fwInstance, + arenaOpt, pError); + if (!mdObject) { + if (CKR_OK != *pError) { + goto done; + } + + /* All done. */ + fwFindObjects->mdfo2->Final(fwFindObjects->mdfo2, fwFindObjects, + fwFindObjects->mdSession, fwFindObjects->fwSession, + fwFindObjects->mdToken, fwFindObjects->fwToken, + fwFindObjects->mdInstance, fwFindObjects->fwInstance); + fwFindObjects->mdfo2 = (NSSCKMDFindObjects *)NULL; + } + else { + goto wrap; + } + } + } + + /* No more objects */ + *pError = CKR_OK; + goto done; + +wrap: + /* * This seems is less than ideal-- we should determine if it's a token * object or a session object, and use the appropriate arena. * But that duplicates logic in nssCKFWObject_IsTokenObject. @@ -336,26 +323,26 @@ nssCKFWFindObjects_Next * exist in the cache from their initial creation). So this code is correct, * but it depends on nssCKFWObject_Create caching all objects. */ - objArena = nssCKFWToken_GetArena(fwFindObjects->fwToken, pError); - if (!objArena) { - if( CKR_OK == *pError ) { - *pError = CKR_HOST_MEMORY; + objArena = nssCKFWToken_GetArena(fwFindObjects->fwToken, pError); + if (!objArena) { + if (CKR_OK == *pError) { + *pError = CKR_HOST_MEMORY; + } + goto done; } - goto done; - } - fwObject = nssCKFWObject_Create(objArena, mdObject, - NULL, fwFindObjects->fwToken, - fwFindObjects->fwInstance, pError); - if (!fwObject) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + fwObject = nssCKFWObject_Create(objArena, mdObject, + NULL, fwFindObjects->fwToken, + fwFindObjects->fwInstance, pError); + if (!fwObject) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } } - } - done: - (void)nssCKFWMutex_Unlock(fwFindObjects->mutex); - return fwObject; +done: + (void)nssCKFWMutex_Unlock(fwFindObjects->mutex); + return fwObject; } /* @@ -364,16 +351,14 @@ nssCKFWFindObjects_Next */ NSS_EXTERN NSSCKMDFindObjects * -NSSCKFWFindObjects_GetMDFindObjects -( - NSSCKFWFindObjects *fwFindObjects -) +NSSCKFWFindObjects_GetMDFindObjects( + NSSCKFWFindObjects *fwFindObjects) { #ifdef DEBUG - if( CKR_OK != nssCKFWFindObjects_verifyPointer(fwFindObjects) ) { - return (NSSCKMDFindObjects *)NULL; - } + if (CKR_OK != nssCKFWFindObjects_verifyPointer(fwFindObjects)) { + return (NSSCKMDFindObjects *)NULL; + } #endif /* DEBUG */ - return nssCKFWFindObjects_GetMDFindObjects(fwFindObjects); + return nssCKFWFindObjects_GetMDFindObjects(fwFindObjects); } diff --git a/security/nss/lib/ckfw/hash.c b/security/nss/lib/ckfw/hash.c index 7d21084bd630..eb0d4066b4c3 100644 --- a/security/nss/lib/ckfw/hash.c +++ b/security/nss/lib/ckfw/hash.c @@ -31,24 +31,22 @@ */ struct nssCKFWHashStr { - NSSCKFWMutex *mutex; + NSSCKFWMutex *mutex; - /* - * The invariant that mutex protects is: - * The count accurately reflects the hashtable state. - */ + /* + * The invariant that mutex protects is: + * The count accurately reflects the hashtable state. + */ - PLHashTable *plHashTable; - CK_ULONG count; + PLHashTable *plHashTable; + CK_ULONG count; }; static PLHashNumber -nss_ckfw_identity_hash -( - const void *key -) +nss_ckfw_identity_hash( + const void *key) { - return (PLHashNumber)((char *)key - (char *)NULL); + return (PLHashNumber)((char *)key - (char *)NULL); } /* @@ -56,53 +54,51 @@ nss_ckfw_identity_hash * */ NSS_IMPLEMENT nssCKFWHash * -nssCKFWHash_Create -( - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +nssCKFWHash_Create( + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { - nssCKFWHash *rv; + nssCKFWHash *rv; #ifdef NSSDEBUG - if (!pError) { - return (nssCKFWHash *)NULL; - } + if (!pError) { + return (nssCKFWHash *)NULL; + } - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - *pError = CKR_ARGUMENTS_BAD; - return (nssCKFWHash *)NULL; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + *pError = CKR_ARGUMENTS_BAD; + return (nssCKFWHash *)NULL; + } #endif /* NSSDEBUG */ - rv = nss_ZNEW(arena, nssCKFWHash); - if (!rv) { - *pError = CKR_HOST_MEMORY; - return (nssCKFWHash *)NULL; - } - - rv->mutex = nssCKFWInstance_CreateMutex(fwInstance, arena, pError); - if (!rv->mutex) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + rv = nss_ZNEW(arena, nssCKFWHash); + if (!rv) { + *pError = CKR_HOST_MEMORY; + return (nssCKFWHash *)NULL; } - (void)nss_ZFreeIf(rv); - return (nssCKFWHash *)NULL; - } - rv->plHashTable = PL_NewHashTable(0, nss_ckfw_identity_hash, - PL_CompareValues, PL_CompareValues, &nssArenaHashAllocOps, arena); - if (!rv->plHashTable) { - (void)nssCKFWMutex_Destroy(rv->mutex); - (void)nss_ZFreeIf(rv); - *pError = CKR_HOST_MEMORY; - return (nssCKFWHash *)NULL; - } + rv->mutex = nssCKFWInstance_CreateMutex(fwInstance, arena, pError); + if (!rv->mutex) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + (void)nss_ZFreeIf(rv); + return (nssCKFWHash *)NULL; + } - rv->count = 0; + rv->plHashTable = PL_NewHashTable(0, nss_ckfw_identity_hash, + PL_CompareValues, PL_CompareValues, &nssArenaHashAllocOps, arena); + if (!rv->plHashTable) { + (void)nssCKFWMutex_Destroy(rv->mutex); + (void)nss_ZFreeIf(rv); + *pError = CKR_HOST_MEMORY; + return (nssCKFWHash *)NULL; + } - return rv; + rv->count = 0; + + return rv; } /* @@ -110,14 +106,12 @@ nssCKFWHash_Create * */ NSS_IMPLEMENT void -nssCKFWHash_Destroy -( - nssCKFWHash *hash -) +nssCKFWHash_Destroy( + nssCKFWHash *hash) { - (void)nssCKFWMutex_Destroy(hash->mutex); - PL_HashTableDestroy(hash->plHashTable); - (void)nss_ZFreeIf(hash); + (void)nssCKFWMutex_Destroy(hash->mutex); + PL_HashTableDestroy(hash->plHashTable); + (void)nss_ZFreeIf(hash); } /* @@ -125,31 +119,30 @@ nssCKFWHash_Destroy * */ NSS_IMPLEMENT CK_RV -nssCKFWHash_Add -( - nssCKFWHash *hash, - const void *key, - const void *value -) +nssCKFWHash_Add( + nssCKFWHash *hash, + const void *key, + const void *value) { - CK_RV error = CKR_OK; - PLHashEntry *he; + CK_RV error = CKR_OK; + PLHashEntry *he; + + error = nssCKFWMutex_Lock(hash->mutex); + if (CKR_OK != error) { + return error; + } + + he = PL_HashTableAdd(hash->plHashTable, key, (void *)value); + if (!he) { + error = CKR_HOST_MEMORY; + } + else { + hash->count++; + } + + (void)nssCKFWMutex_Unlock(hash->mutex); - error = nssCKFWMutex_Lock(hash->mutex); - if( CKR_OK != error ) { return error; - } - - he = PL_HashTableAdd(hash->plHashTable, key, (void *)value); - if (!he) { - error = CKR_HOST_MEMORY; - } else { - hash->count++; - } - - (void)nssCKFWMutex_Unlock(hash->mutex); - - return error; } /* @@ -157,25 +150,23 @@ nssCKFWHash_Add * */ NSS_IMPLEMENT void -nssCKFWHash_Remove -( - nssCKFWHash *hash, - const void *it -) +nssCKFWHash_Remove( + nssCKFWHash *hash, + const void *it) { - PRBool found; + PRBool found; - if( CKR_OK != nssCKFWMutex_Lock(hash->mutex) ) { + if (CKR_OK != nssCKFWMutex_Lock(hash->mutex)) { + return; + } + + found = PL_HashTableRemove(hash->plHashTable, it); + if (found) { + hash->count--; + } + + (void)nssCKFWMutex_Unlock(hash->mutex); return; - } - - found = PL_HashTableRemove(hash->plHashTable, it); - if( found ) { - hash->count--; - } - - (void)nssCKFWMutex_Unlock(hash->mutex); - return; } /* @@ -183,22 +174,20 @@ nssCKFWHash_Remove * */ NSS_IMPLEMENT CK_ULONG -nssCKFWHash_Count -( - nssCKFWHash *hash -) +nssCKFWHash_Count( + nssCKFWHash *hash) { - CK_ULONG count; + CK_ULONG count; - if( CKR_OK != nssCKFWMutex_Lock(hash->mutex) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWMutex_Lock(hash->mutex)) { + return (CK_ULONG)0; + } - count = hash->count; + count = hash->count; - (void)nssCKFWMutex_Unlock(hash->mutex); + (void)nssCKFWMutex_Unlock(hash->mutex); - return count; + return count; } /* @@ -206,27 +195,26 @@ nssCKFWHash_Count * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWHash_Exists -( - nssCKFWHash *hash, - const void *it -) +nssCKFWHash_Exists( + nssCKFWHash *hash, + const void *it) { - void *value; + void *value; - if( CKR_OK != nssCKFWMutex_Lock(hash->mutex) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWMutex_Lock(hash->mutex)) { + return CK_FALSE; + } - value = PL_HashTableLookup(hash->plHashTable, it); + value = PL_HashTableLookup(hash->plHashTable, it); - (void)nssCKFWMutex_Unlock(hash->mutex); + (void)nssCKFWMutex_Unlock(hash->mutex); - if (!value) { - return CK_FALSE; - } else { - return CK_TRUE; - } + if (!value) { + return CK_FALSE; + } + else { + return CK_TRUE; + } } /* @@ -234,41 +222,37 @@ nssCKFWHash_Exists * */ NSS_IMPLEMENT void * -nssCKFWHash_Lookup -( - nssCKFWHash *hash, - const void *it -) +nssCKFWHash_Lookup( + nssCKFWHash *hash, + const void *it) { - void *rv; + void *rv; - if( CKR_OK != nssCKFWMutex_Lock(hash->mutex) ) { - return (void *)NULL; - } + if (CKR_OK != nssCKFWMutex_Lock(hash->mutex)) { + return (void *)NULL; + } - rv = PL_HashTableLookup(hash->plHashTable, it); + rv = PL_HashTableLookup(hash->plHashTable, it); - (void)nssCKFWMutex_Unlock(hash->mutex); + (void)nssCKFWMutex_Unlock(hash->mutex); - return rv; + return rv; } struct arg_str { - nssCKFWHashIterator fcn; - void *closure; + nssCKFWHashIterator fcn; + void *closure; }; static PRIntn -nss_ckfwhash_enumerator -( - PLHashEntry *he, - PRIntn index, - void *arg -) +nss_ckfwhash_enumerator( + PLHashEntry *he, + PRIntn index, + void *arg) { - struct arg_str *as = (struct arg_str *)arg; - as->fcn(he->key, he->value, as->closure); - return HT_ENUMERATE_NEXT; + struct arg_str *as = (struct arg_str *)arg; + as->fcn(he->key, he->value, as->closure); + return HT_ENUMERATE_NEXT; } /* @@ -277,24 +261,22 @@ nss_ckfwhash_enumerator * NOTE that the iteration function will be called with the hashtable locked. */ NSS_IMPLEMENT void -nssCKFWHash_Iterate -( - nssCKFWHash *hash, - nssCKFWHashIterator fcn, - void *closure -) +nssCKFWHash_Iterate( + nssCKFWHash *hash, + nssCKFWHashIterator fcn, + void *closure) { - struct arg_str as; - as.fcn = fcn; - as.closure = closure; + struct arg_str as; + as.fcn = fcn; + as.closure = closure; + + if (CKR_OK != nssCKFWMutex_Lock(hash->mutex)) { + return; + } + + PL_HashTableEnumerateEntries(hash->plHashTable, nss_ckfwhash_enumerator, &as); + + (void)nssCKFWMutex_Unlock(hash->mutex); - if( CKR_OK != nssCKFWMutex_Lock(hash->mutex) ) { return; - } - - PL_HashTableEnumerateEntries(hash->plHashTable, nss_ckfwhash_enumerator, &as); - - (void)nssCKFWMutex_Unlock(hash->mutex); - - return; } diff --git a/security/nss/lib/ckfw/instance.c b/security/nss/lib/ckfw/instance.c index b8a5b25e17a3..3ef3fea155aa 100644 --- a/security/nss/lib/ckfw/instance.c +++ b/security/nss/lib/ckfw/instance.c @@ -33,7 +33,7 @@ * nssCKFWInstance_MayCreatePthreads * nssCKFWInstance_CreateMutex * nssCKFWInstance_GetConfigurationData - * nssCKFWInstance_GetInitArgs + * nssCKFWInstance_GetInitArgs * * -- private accessors -- * nssCKFWInstance_CreateSessionHandle @@ -60,52 +60,52 @@ */ struct NSSCKFWInstanceStr { - NSSCKFWMutex *mutex; - NSSArena *arena; - NSSCKMDInstance *mdInstance; - CK_C_INITIALIZE_ARGS_PTR pInitArgs; - CK_C_INITIALIZE_ARGS initArgs; - CryptokiLockingState LockingState; - CK_BBOOL mayCreatePthreads; - NSSUTF8 *configurationData; - CK_ULONG nSlots; - NSSCKFWSlot **fwSlotList; - NSSCKMDSlot **mdSlotList; - CK_BBOOL moduleHandlesSessionObjects; + NSSCKFWMutex *mutex; + NSSArena *arena; + NSSCKMDInstance *mdInstance; + CK_C_INITIALIZE_ARGS_PTR pInitArgs; + CK_C_INITIALIZE_ARGS initArgs; + CryptokiLockingState LockingState; + CK_BBOOL mayCreatePthreads; + NSSUTF8 *configurationData; + CK_ULONG nSlots; + NSSCKFWSlot **fwSlotList; + NSSCKMDSlot **mdSlotList; + CK_BBOOL moduleHandlesSessionObjects; - /* - * Everything above is set at creation time, and then not modified. - * The invariants the mutex protects are: - * - * 1) Each of the cached descriptions (versions, etc.) are in an - * internally consistant state. - * - * 2) The session handle hashes and count are consistant - * - * 3) The object handle hashes and count are consistant. - * - * I could use multiple locks, but let's wait to see if that's - * really necessary. - * - * Note that the calls accessing the cached descriptions will - * call the NSSCKMDInstance methods with the mutex locked. Those - * methods may then call the public NSSCKFWInstance routines. - * Those public routines only access the constant data above, so - * there's no problem. But be careful if you add to this object; - * mutexes are in general not reentrant, so don't create deadlock - * situations. - */ + /* + * Everything above is set at creation time, and then not modified. + * The invariants the mutex protects are: + * + * 1) Each of the cached descriptions (versions, etc.) are in an + * internally consistant state. + * + * 2) The session handle hashes and count are consistant + * + * 3) The object handle hashes and count are consistant. + * + * I could use multiple locks, but let's wait to see if that's + * really necessary. + * + * Note that the calls accessing the cached descriptions will + * call the NSSCKMDInstance methods with the mutex locked. Those + * methods may then call the public NSSCKFWInstance routines. + * Those public routines only access the constant data above, so + * there's no problem. But be careful if you add to this object; + * mutexes are in general not reentrant, so don't create deadlock + * situations. + */ - CK_VERSION cryptokiVersion; - NSSUTF8 *manufacturerID; - NSSUTF8 *libraryDescription; - CK_VERSION libraryVersion; + CK_VERSION cryptokiVersion; + NSSUTF8 *manufacturerID; + NSSUTF8 *libraryDescription; + CK_VERSION libraryVersion; - CK_ULONG lastSessionHandle; - nssCKFWHash *sessionHandleHash; + CK_ULONG lastSessionHandle; + nssCKFWHash *sessionHandleHash; - CK_ULONG lastObjectHandle; - nssCKFWHash *objectHandleHash; + CK_ULONG lastObjectHandle; + nssCKFWHash *objectHandleHash; }; #ifdef DEBUG @@ -121,30 +121,24 @@ struct NSSCKFWInstanceStr { */ static CK_RV -instance_add_pointer -( - const NSSCKFWInstance *fwInstance -) +instance_add_pointer( + const NSSCKFWInstance *fwInstance) { - return CKR_OK; + return CKR_OK; } static CK_RV -instance_remove_pointer -( - const NSSCKFWInstance *fwInstance -) +instance_remove_pointer( + const NSSCKFWInstance *fwInstance) { - return CKR_OK; + return CKR_OK; } NSS_IMPLEMENT CK_RV -nssCKFWInstance_verifyPointer -( - const NSSCKFWInstance *fwInstance -) +nssCKFWInstance_verifyPointer( + const NSSCKFWInstance *fwInstance) { - return CKR_OK; + return CKR_OK; } #endif /* DEBUG */ @@ -154,191 +148,192 @@ nssCKFWInstance_verifyPointer * */ NSS_IMPLEMENT NSSCKFWInstance * -nssCKFWInstance_Create -( - CK_C_INITIALIZE_ARGS_PTR pInitArgs, - CryptokiLockingState LockingState, - NSSCKMDInstance *mdInstance, - CK_RV *pError -) +nssCKFWInstance_Create( + CK_C_INITIALIZE_ARGS_PTR pInitArgs, + CryptokiLockingState LockingState, + NSSCKMDInstance *mdInstance, + CK_RV *pError) { - NSSCKFWInstance *fwInstance; - NSSArena *arena = (NSSArena *)NULL; - CK_ULONG i; - CK_BBOOL called_Initialize = CK_FALSE; + NSSCKFWInstance *fwInstance; + NSSArena *arena = (NSSArena *)NULL; + CK_ULONG i; + CK_BBOOL called_Initialize = CK_FALSE; #ifdef NSSDEBUG - if( (CK_RV)NULL == pError ) { - return (NSSCKFWInstance *)NULL; - } + if ((CK_RV)NULL == pError) { + return (NSSCKFWInstance *)NULL; + } - if (!mdInstance) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWInstance *)NULL; - } + if (!mdInstance) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWInstance *)NULL; + } #endif /* NSSDEBUG */ - arena = NSSArena_Create(); - if (!arena) { - *pError = CKR_HOST_MEMORY; - return (NSSCKFWInstance *)NULL; - } - - fwInstance = nss_ZNEW(arena, NSSCKFWInstance); - if (!fwInstance) { - goto nomem; - } - - fwInstance->arena = arena; - fwInstance->mdInstance = mdInstance; - - fwInstance->LockingState = LockingState; - if( (CK_C_INITIALIZE_ARGS_PTR)NULL != pInitArgs ) { - fwInstance->initArgs = *pInitArgs; - fwInstance->pInitArgs = &fwInstance->initArgs; - if( pInitArgs->flags & CKF_LIBRARY_CANT_CREATE_OS_THREADS ) { - fwInstance->mayCreatePthreads = CK_FALSE; - } else { - fwInstance->mayCreatePthreads = CK_TRUE; - } - fwInstance->configurationData = (NSSUTF8 *)(pInitArgs->pReserved); - } else { - fwInstance->mayCreatePthreads = CK_TRUE; - } - - fwInstance->mutex = nssCKFWMutex_Create(pInitArgs, LockingState, arena, - pError); - if (!fwInstance->mutex) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - goto loser; - } - - if (mdInstance->Initialize) { - *pError = mdInstance->Initialize(mdInstance, fwInstance, fwInstance->configurationData); - if( CKR_OK != *pError ) { - goto loser; + arena = NSSArena_Create(); + if (!arena) { + *pError = CKR_HOST_MEMORY; + return (NSSCKFWInstance *)NULL; } - called_Initialize = CK_TRUE; - } - - if (mdInstance->ModuleHandlesSessionObjects) { - fwInstance->moduleHandlesSessionObjects = - mdInstance->ModuleHandlesSessionObjects(mdInstance, fwInstance); - } else { - fwInstance->moduleHandlesSessionObjects = CK_FALSE; - } - - if (!mdInstance->GetNSlots) { - /* That routine is required */ - *pError = CKR_GENERAL_ERROR; - goto loser; - } - - fwInstance->nSlots = mdInstance->GetNSlots(mdInstance, fwInstance, pError); - if( (CK_ULONG)0 == fwInstance->nSlots ) { - if( CKR_OK == *pError ) { - /* Zero is not a legitimate answer */ - *pError = CKR_GENERAL_ERROR; - } - goto loser; - } - - fwInstance->fwSlotList = nss_ZNEWARRAY(arena, NSSCKFWSlot *, fwInstance->nSlots); - if( (NSSCKFWSlot **)NULL == fwInstance->fwSlotList ) { - goto nomem; - } - - fwInstance->mdSlotList = nss_ZNEWARRAY(arena, NSSCKMDSlot *, fwInstance->nSlots); - if( (NSSCKMDSlot **)NULL == fwInstance->mdSlotList ) { - goto nomem; - } - - fwInstance->sessionHandleHash = nssCKFWHash_Create(fwInstance, - fwInstance->arena, pError); - if (!fwInstance->sessionHandleHash) { - goto loser; - } - - fwInstance->objectHandleHash = nssCKFWHash_Create(fwInstance, - fwInstance->arena, pError); - if (!fwInstance->objectHandleHash) { - goto loser; - } - - if (!mdInstance->GetSlots) { - /* That routine is required */ - *pError = CKR_GENERAL_ERROR; - goto loser; - } - - *pError = mdInstance->GetSlots(mdInstance, fwInstance, fwInstance->mdSlotList); - if( CKR_OK != *pError ) { - goto loser; - } - - for( i = 0; i < fwInstance->nSlots; i++ ) { - NSSCKMDSlot *mdSlot = fwInstance->mdSlotList[i]; - - if (!mdSlot) { - *pError = CKR_GENERAL_ERROR; - goto loser; + fwInstance = nss_ZNEW(arena, NSSCKFWInstance); + if (!fwInstance) { + goto nomem; } - fwInstance->fwSlotList[i] = nssCKFWSlot_Create(fwInstance, mdSlot, i, pError); - if( CKR_OK != *pError ) { - CK_ULONG j; + fwInstance->arena = arena; + fwInstance->mdInstance = mdInstance; - for( j = 0; j < i; j++ ) { - (void)nssCKFWSlot_Destroy(fwInstance->fwSlotList[j]); - } - - for( j = i; j < fwInstance->nSlots; j++ ) { - NSSCKMDSlot *mds = fwInstance->mdSlotList[j]; - if (mds->Destroy) { - mds->Destroy(mds, (NSSCKFWSlot *)NULL, mdInstance, fwInstance); + fwInstance->LockingState = LockingState; + if ((CK_C_INITIALIZE_ARGS_PTR)NULL != pInitArgs) { + fwInstance->initArgs = *pInitArgs; + fwInstance->pInitArgs = &fwInstance->initArgs; + if (pInitArgs->flags & CKF_LIBRARY_CANT_CREATE_OS_THREADS) { + fwInstance->mayCreatePthreads = CK_FALSE; + } + else { + fwInstance->mayCreatePthreads = CK_TRUE; + } + fwInstance->configurationData = (NSSUTF8 *)(pInitArgs->pReserved); + } + else { + fwInstance->mayCreatePthreads = CK_TRUE; + } + + fwInstance->mutex = nssCKFWMutex_Create(pInitArgs, LockingState, arena, + pError); + if (!fwInstance->mutex) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto loser; + } + + if (mdInstance->Initialize) { + *pError = mdInstance->Initialize(mdInstance, fwInstance, fwInstance->configurationData); + if (CKR_OK != *pError) { + goto loser; + } + + called_Initialize = CK_TRUE; + } + + if (mdInstance->ModuleHandlesSessionObjects) { + fwInstance->moduleHandlesSessionObjects = + mdInstance->ModuleHandlesSessionObjects(mdInstance, fwInstance); + } + else { + fwInstance->moduleHandlesSessionObjects = CK_FALSE; + } + + if (!mdInstance->GetNSlots) { + /* That routine is required */ + *pError = CKR_GENERAL_ERROR; + goto loser; + } + + fwInstance->nSlots = mdInstance->GetNSlots(mdInstance, fwInstance, pError); + if ((CK_ULONG)0 == fwInstance->nSlots) { + if (CKR_OK == *pError) { + /* Zero is not a legitimate answer */ + *pError = CKR_GENERAL_ERROR; + } + goto loser; + } + + fwInstance->fwSlotList = nss_ZNEWARRAY(arena, NSSCKFWSlot *, fwInstance->nSlots); + if ((NSSCKFWSlot **)NULL == fwInstance->fwSlotList) { + goto nomem; + } + + fwInstance->mdSlotList = nss_ZNEWARRAY(arena, NSSCKMDSlot *, fwInstance->nSlots); + if ((NSSCKMDSlot **)NULL == fwInstance->mdSlotList) { + goto nomem; + } + + fwInstance->sessionHandleHash = nssCKFWHash_Create(fwInstance, + fwInstance->arena, pError); + if (!fwInstance->sessionHandleHash) { + goto loser; + } + + fwInstance->objectHandleHash = nssCKFWHash_Create(fwInstance, + fwInstance->arena, pError); + if (!fwInstance->objectHandleHash) { + goto loser; + } + + if (!mdInstance->GetSlots) { + /* That routine is required */ + *pError = CKR_GENERAL_ERROR; + goto loser; + } + + *pError = mdInstance->GetSlots(mdInstance, fwInstance, fwInstance->mdSlotList); + if (CKR_OK != *pError) { + goto loser; + } + + for (i = 0; i < fwInstance->nSlots; i++) { + NSSCKMDSlot *mdSlot = fwInstance->mdSlotList[i]; + + if (!mdSlot) { + *pError = CKR_GENERAL_ERROR; + goto loser; + } + + fwInstance->fwSlotList[i] = nssCKFWSlot_Create(fwInstance, mdSlot, i, pError); + if (CKR_OK != *pError) { + CK_ULONG j; + + for (j = 0; j < i; j++) { + (void)nssCKFWSlot_Destroy(fwInstance->fwSlotList[j]); + } + + for (j = i; j < fwInstance->nSlots; j++) { + NSSCKMDSlot *mds = fwInstance->mdSlotList[j]; + if (mds->Destroy) { + mds->Destroy(mds, (NSSCKFWSlot *)NULL, mdInstance, fwInstance); + } + } + + goto loser; } - } - - goto loser; } - } #ifdef DEBUG - *pError = instance_add_pointer(fwInstance); - if( CKR_OK != *pError ) { - for( i = 0; i < fwInstance->nSlots; i++ ) { - (void)nssCKFWSlot_Destroy(fwInstance->fwSlotList[i]); + *pError = instance_add_pointer(fwInstance); + if (CKR_OK != *pError) { + for (i = 0; i < fwInstance->nSlots; i++) { + (void)nssCKFWSlot_Destroy(fwInstance->fwSlotList[i]); + } + + goto loser; } - - goto loser; - } #endif /* DEBUG */ - *pError = CKR_OK; - return fwInstance; + *pError = CKR_OK; + return fwInstance; - nomem: - *pError = CKR_HOST_MEMORY; - /*FALLTHROUGH*/ - loser: +nomem: + *pError = CKR_HOST_MEMORY; + /*FALLTHROUGH*/ +loser: - if( CK_TRUE == called_Initialize ) { - if (mdInstance->Finalize) { - mdInstance->Finalize(mdInstance, fwInstance); + if (CK_TRUE == called_Initialize) { + if (mdInstance->Finalize) { + mdInstance->Finalize(mdInstance, fwInstance); + } } - } - if (fwInstance && fwInstance->mutex) { - nssCKFWMutex_Destroy(fwInstance->mutex); - } + if (fwInstance && fwInstance->mutex) { + nssCKFWMutex_Destroy(fwInstance->mutex); + } - if (arena) { - (void)NSSArena_Destroy(arena); - } - return (NSSCKFWInstance *)NULL; + if (arena) { + (void)NSSArena_Destroy(arena); + } + return (NSSCKFWInstance *)NULL; } /* @@ -346,47 +341,45 @@ nssCKFWInstance_Create * */ NSS_IMPLEMENT CK_RV -nssCKFWInstance_Destroy -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_Destroy( + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #endif /* NSSDEBUG */ - CK_ULONG i; + CK_ULONG i; #ifdef NSSDEBUG - error = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - nssCKFWMutex_Destroy(fwInstance->mutex); + nssCKFWMutex_Destroy(fwInstance->mutex); - for( i = 0; i < fwInstance->nSlots; i++ ) { - (void)nssCKFWSlot_Destroy(fwInstance->fwSlotList[i]); - } + for (i = 0; i < fwInstance->nSlots; i++) { + (void)nssCKFWSlot_Destroy(fwInstance->fwSlotList[i]); + } - if (fwInstance->mdInstance->Finalize) { - fwInstance->mdInstance->Finalize(fwInstance->mdInstance, fwInstance); - } + if (fwInstance->mdInstance->Finalize) { + fwInstance->mdInstance->Finalize(fwInstance->mdInstance, fwInstance); + } - if (fwInstance->sessionHandleHash) { - nssCKFWHash_Destroy(fwInstance->sessionHandleHash); - } + if (fwInstance->sessionHandleHash) { + nssCKFWHash_Destroy(fwInstance->sessionHandleHash); + } - if (fwInstance->objectHandleHash) { - nssCKFWHash_Destroy(fwInstance->objectHandleHash); - } + if (fwInstance->objectHandleHash) { + nssCKFWHash_Destroy(fwInstance->objectHandleHash); + } #ifdef DEBUG - (void)instance_remove_pointer(fwInstance); + (void)instance_remove_pointer(fwInstance); #endif /* DEBUG */ - (void)NSSArena_Destroy(fwInstance->arena); - return CKR_OK; + (void)NSSArena_Destroy(fwInstance->arena); + return CKR_OK; } /* @@ -394,18 +387,16 @@ nssCKFWInstance_Destroy * */ NSS_IMPLEMENT NSSCKMDInstance * -nssCKFWInstance_GetMDInstance -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_GetMDInstance( + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (NSSCKMDInstance *)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (NSSCKMDInstance *)NULL; + } #endif /* NSSDEBUG */ - return fwInstance->mdInstance; + return fwInstance->mdInstance; } /* @@ -413,25 +404,23 @@ nssCKFWInstance_GetMDInstance * */ NSS_IMPLEMENT NSSArena * -nssCKFWInstance_GetArena -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nssCKFWInstance_GetArena( + NSSCKFWInstance *fwInstance, + CK_RV *pError) { #ifdef NSSDEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (NSSArena *)NULL; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (NSSArena *)NULL; + } #endif /* NSSDEBUG */ - *pError = CKR_OK; - return fwInstance->arena; + *pError = CKR_OK; + return fwInstance->arena; } /* @@ -439,18 +428,16 @@ nssCKFWInstance_GetArena * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWInstance_MayCreatePthreads -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_MayCreatePthreads( + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - return fwInstance->mayCreatePthreads; + return fwInstance->mayCreatePthreads; } /* @@ -458,37 +445,35 @@ nssCKFWInstance_MayCreatePthreads * */ NSS_IMPLEMENT NSSCKFWMutex * -nssCKFWInstance_CreateMutex -( - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +nssCKFWInstance_CreateMutex( + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { - NSSCKFWMutex *mutex; + NSSCKFWMutex *mutex; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWMutex *)NULL; - } - - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (NSSCKFWMutex *)NULL; - } -#endif /* NSSDEBUG */ - - mutex = nssCKFWMutex_Create(fwInstance->pInitArgs, fwInstance->LockingState, - arena, pError); - if (!mutex) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + if (!pError) { + return (NSSCKFWMutex *)NULL; } - return (NSSCKFWMutex *)NULL; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (NSSCKFWMutex *)NULL; + } +#endif /* NSSDEBUG */ - return mutex; + mutex = nssCKFWMutex_Create(fwInstance->pInitArgs, fwInstance->LockingState, + arena, pError); + if (!mutex) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + + return (NSSCKFWMutex *)NULL; + } + + return mutex; } /* @@ -496,18 +481,16 @@ nssCKFWInstance_CreateMutex * */ NSS_IMPLEMENT NSSUTF8 * -nssCKFWInstance_GetConfigurationData -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_GetConfigurationData( + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (NSSUTF8 *)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (NSSUTF8 *)NULL; + } #endif /* NSSDEBUG */ - return fwInstance->configurationData; + return fwInstance->configurationData; } /* @@ -515,15 +498,13 @@ nssCKFWInstance_GetConfigurationData * */ CK_C_INITIALIZE_ARGS_PTR -nssCKFWInstance_GetInitArgs -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_GetInitArgs( + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (CK_C_INITIALIZE_ARGS_PTR)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (CK_C_INITIALIZE_ARGS_PTR)NULL; + } #endif /* NSSDEBUG */ return fwInstance->pInitArgs; @@ -534,50 +515,48 @@ nssCKFWInstance_GetInitArgs * */ NSS_IMPLEMENT CK_SESSION_HANDLE -nssCKFWInstance_CreateSessionHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession, - CK_RV *pError -) +nssCKFWInstance_CreateSessionHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession, + CK_RV *pError) { - CK_SESSION_HANDLE hSession; + CK_SESSION_HANDLE hSession; #ifdef NSSDEBUG - if (!pError) { - return (CK_SESSION_HANDLE)0; - } + if (!pError) { + return (CK_SESSION_HANDLE)0; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (CK_SESSION_HANDLE)0; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (CK_SESSION_HANDLE)0; + } #endif /* NSSDEBUG */ - *pError = nssCKFWMutex_Lock(fwInstance->mutex); - if( CKR_OK != *pError ) { - return (CK_SESSION_HANDLE)0; - } + *pError = nssCKFWMutex_Lock(fwInstance->mutex); + if (CKR_OK != *pError) { + return (CK_SESSION_HANDLE)0; + } - hSession = ++(fwInstance->lastSessionHandle); + hSession = ++(fwInstance->lastSessionHandle); - /* Alan would say I should unlock for this call. */ - - *pError = nssCKFWSession_SetHandle(fwSession, hSession); - if( CKR_OK != *pError ) { - goto done; - } + /* Alan would say I should unlock for this call. */ - *pError = nssCKFWHash_Add(fwInstance->sessionHandleHash, - (const void *)hSession, (const void *)fwSession); - if( CKR_OK != *pError ) { - hSession = (CK_SESSION_HANDLE)0; - goto done; - } + *pError = nssCKFWSession_SetHandle(fwSession, hSession); + if (CKR_OK != *pError) { + goto done; + } - done: - nssCKFWMutex_Unlock(fwInstance->mutex); - return hSession; + *pError = nssCKFWHash_Add(fwInstance->sessionHandleHash, + (const void *)hSession, (const void *)fwSession); + if (CKR_OK != *pError) { + hSession = (CK_SESSION_HANDLE)0; + goto done; + } + +done: + nssCKFWMutex_Unlock(fwInstance->mutex); + return hSession; } /* @@ -585,32 +564,30 @@ nssCKFWInstance_CreateSessionHandle * */ NSS_IMPLEMENT NSSCKFWSession * -nssCKFWInstance_ResolveSessionHandle -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -) +nssCKFWInstance_ResolveSessionHandle( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession) { - NSSCKFWSession *fwSession; + NSSCKFWSession *fwSession; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (NSSCKFWSession *)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (NSSCKFWSession *)NULL; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex) ) { - return (NSSCKFWSession *)NULL; - } + if (CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex)) { + return (NSSCKFWSession *)NULL; + } - fwSession = (NSSCKFWSession *)nssCKFWHash_Lookup( - fwInstance->sessionHandleHash, (const void *)hSession); + fwSession = (NSSCKFWSession *)nssCKFWHash_Lookup( + fwInstance->sessionHandleHash, (const void *)hSession); - /* Assert(hSession == nssCKFWSession_GetHandle(fwSession)) */ + /* Assert(hSession == nssCKFWSession_GetHandle(fwSession)) */ - (void)nssCKFWMutex_Unlock(fwInstance->mutex); + (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return fwSession; + return fwSession; } /* @@ -618,34 +595,32 @@ nssCKFWInstance_ResolveSessionHandle * */ NSS_IMPLEMENT void -nssCKFWInstance_DestroySessionHandle -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -) +nssCKFWInstance_DestroySessionHandle( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession) { - NSSCKFWSession *fwSession; + NSSCKFWSession *fwSession; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex) ) { + if (CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex)) { + return; + } + + fwSession = (NSSCKFWSession *)nssCKFWHash_Lookup( + fwInstance->sessionHandleHash, (const void *)hSession); + if (fwSession) { + nssCKFWHash_Remove(fwInstance->sessionHandleHash, (const void *)hSession); + nssCKFWSession_SetHandle(fwSession, (CK_SESSION_HANDLE)0); + } + + (void)nssCKFWMutex_Unlock(fwInstance->mutex); + return; - } - - fwSession = (NSSCKFWSession *)nssCKFWHash_Lookup( - fwInstance->sessionHandleHash, (const void *)hSession); - if (fwSession) { - nssCKFWHash_Remove(fwInstance->sessionHandleHash, (const void *)hSession); - nssCKFWSession_SetHandle(fwSession, (CK_SESSION_HANDLE)0); - } - - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - - return; } /* @@ -653,24 +628,22 @@ nssCKFWInstance_DestroySessionHandle * */ NSS_IMPLEMENT CK_SESSION_HANDLE -nssCKFWInstance_FindSessionHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession -) +nssCKFWInstance_FindSessionHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (CK_SESSION_HANDLE)0; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (CK_SESSION_HANDLE)0; + } - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return (CK_SESSION_HANDLE)0; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return (CK_SESSION_HANDLE)0; + } #endif /* NSSDEBUG */ - return nssCKFWSession_GetHandle(fwSession); - /* look it up and assert? */ + return nssCKFWSession_GetHandle(fwSession); + /* look it up and assert? */ } /* @@ -678,49 +651,47 @@ nssCKFWInstance_FindSessionHandle * */ NSS_IMPLEMENT CK_OBJECT_HANDLE -nssCKFWInstance_CreateObjectHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWObject *fwObject, - CK_RV *pError -) +nssCKFWInstance_CreateObjectHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWObject *fwObject, + CK_RV *pError) { - CK_OBJECT_HANDLE hObject; + CK_OBJECT_HANDLE hObject; #ifdef NSSDEBUG - if (!pError) { - return (CK_OBJECT_HANDLE)0; - } + if (!pError) { + return (CK_OBJECT_HANDLE)0; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (CK_OBJECT_HANDLE)0; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (CK_OBJECT_HANDLE)0; + } #endif /* NSSDEBUG */ - *pError = nssCKFWMutex_Lock(fwInstance->mutex); - if( CKR_OK != *pError ) { - return (CK_OBJECT_HANDLE)0; - } + *pError = nssCKFWMutex_Lock(fwInstance->mutex); + if (CKR_OK != *pError) { + return (CK_OBJECT_HANDLE)0; + } - hObject = ++(fwInstance->lastObjectHandle); + hObject = ++(fwInstance->lastObjectHandle); - *pError = nssCKFWObject_SetHandle(fwObject, hObject); - if( CKR_OK != *pError ) { - hObject = (CK_OBJECT_HANDLE)0; - goto done; - } + *pError = nssCKFWObject_SetHandle(fwObject, hObject); + if (CKR_OK != *pError) { + hObject = (CK_OBJECT_HANDLE)0; + goto done; + } - *pError = nssCKFWHash_Add(fwInstance->objectHandleHash, - (const void *)hObject, (const void *)fwObject); - if( CKR_OK != *pError ) { - hObject = (CK_OBJECT_HANDLE)0; - goto done; - } + *pError = nssCKFWHash_Add(fwInstance->objectHandleHash, + (const void *)hObject, (const void *)fwObject); + if (CKR_OK != *pError) { + hObject = (CK_OBJECT_HANDLE)0; + goto done; + } - done: - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return hObject; +done: + (void)nssCKFWMutex_Unlock(fwInstance->mutex); + return hObject; } /* @@ -728,31 +699,29 @@ nssCKFWInstance_CreateObjectHandle * */ NSS_IMPLEMENT NSSCKFWObject * -nssCKFWInstance_ResolveObjectHandle -( - NSSCKFWInstance *fwInstance, - CK_OBJECT_HANDLE hObject -) +nssCKFWInstance_ResolveObjectHandle( + NSSCKFWInstance *fwInstance, + CK_OBJECT_HANDLE hObject) { - NSSCKFWObject *fwObject; + NSSCKFWObject *fwObject; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (NSSCKFWObject *)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (NSSCKFWObject *)NULL; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex) ) { - return (NSSCKFWObject *)NULL; - } + if (CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex)) { + return (NSSCKFWObject *)NULL; + } - fwObject = (NSSCKFWObject *)nssCKFWHash_Lookup( - fwInstance->objectHandleHash, (const void *)hObject); + fwObject = (NSSCKFWObject *)nssCKFWHash_Lookup( + fwInstance->objectHandleHash, (const void *)hObject); - /* Assert(hObject == nssCKFWObject_GetHandle(fwObject)) */ + /* Assert(hObject == nssCKFWObject_GetHandle(fwObject)) */ - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return fwObject; + (void)nssCKFWMutex_Unlock(fwInstance->mutex); + return fwObject; } /* @@ -760,46 +729,44 @@ nssCKFWInstance_ResolveObjectHandle * */ NSS_IMPLEMENT CK_RV -nssCKFWInstance_ReassignObjectHandle -( - NSSCKFWInstance *fwInstance, - CK_OBJECT_HANDLE hObject, - NSSCKFWObject *fwObject -) +nssCKFWInstance_ReassignObjectHandle( + NSSCKFWInstance *fwInstance, + CK_OBJECT_HANDLE hObject, + NSSCKFWObject *fwObject) { - CK_RV error = CKR_OK; - NSSCKFWObject *oldObject; + CK_RV error = CKR_OK; + NSSCKFWObject *oldObject; #ifdef NSSDEBUG - error = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwInstance->mutex); - if( CKR_OK != error ) { + error = nssCKFWMutex_Lock(fwInstance->mutex); + if (CKR_OK != error) { + return error; + } + + oldObject = (NSSCKFWObject *)nssCKFWHash_Lookup( + fwInstance->objectHandleHash, (const void *)hObject); + if (oldObject) { + /* Assert(hObject == nssCKFWObject_GetHandle(oldObject) */ + (void)nssCKFWObject_SetHandle(oldObject, (CK_SESSION_HANDLE)0); + nssCKFWHash_Remove(fwInstance->objectHandleHash, (const void *)hObject); + } + + error = nssCKFWObject_SetHandle(fwObject, hObject); + if (CKR_OK != error) { + goto done; + } + error = nssCKFWHash_Add(fwInstance->objectHandleHash, + (const void *)hObject, (const void *)fwObject); + +done: + (void)nssCKFWMutex_Unlock(fwInstance->mutex); return error; - } - - oldObject = (NSSCKFWObject *)nssCKFWHash_Lookup( - fwInstance->objectHandleHash, (const void *)hObject); - if(oldObject) { - /* Assert(hObject == nssCKFWObject_GetHandle(oldObject) */ - (void)nssCKFWObject_SetHandle(oldObject, (CK_SESSION_HANDLE)0); - nssCKFWHash_Remove(fwInstance->objectHandleHash, (const void *)hObject); - } - - error = nssCKFWObject_SetHandle(fwObject, hObject); - if( CKR_OK != error ) { - goto done; - } - error = nssCKFWHash_Add(fwInstance->objectHandleHash, - (const void *)hObject, (const void *)fwObject); - - done: - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return error; } /* @@ -807,34 +774,32 @@ nssCKFWInstance_ReassignObjectHandle * */ NSS_IMPLEMENT void -nssCKFWInstance_DestroyObjectHandle -( - NSSCKFWInstance *fwInstance, - CK_OBJECT_HANDLE hObject -) +nssCKFWInstance_DestroyObjectHandle( + NSSCKFWInstance *fwInstance, + CK_OBJECT_HANDLE hObject) { - NSSCKFWObject *fwObject; + NSSCKFWObject *fwObject; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex) ) { + if (CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex)) { + return; + } + + fwObject = (NSSCKFWObject *)nssCKFWHash_Lookup( + fwInstance->objectHandleHash, (const void *)hObject); + if (fwObject) { + /* Assert(hObject = nssCKFWObject_GetHandle(fwObject)) */ + nssCKFWHash_Remove(fwInstance->objectHandleHash, (const void *)hObject); + (void)nssCKFWObject_SetHandle(fwObject, (CK_SESSION_HANDLE)0); + } + + (void)nssCKFWMutex_Unlock(fwInstance->mutex); return; - } - - fwObject = (NSSCKFWObject *)nssCKFWHash_Lookup( - fwInstance->objectHandleHash, (const void *)hObject); - if (fwObject) { - /* Assert(hObject = nssCKFWObject_GetHandle(fwObject)) */ - nssCKFWHash_Remove(fwInstance->objectHandleHash, (const void *)hObject); - (void)nssCKFWObject_SetHandle(fwObject, (CK_SESSION_HANDLE)0); - } - - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return; } /* @@ -842,23 +807,21 @@ nssCKFWInstance_DestroyObjectHandle * */ NSS_IMPLEMENT CK_OBJECT_HANDLE -nssCKFWInstance_FindObjectHandle -( - NSSCKFWInstance *fwInstance, - NSSCKFWObject *fwObject -) +nssCKFWInstance_FindObjectHandle( + NSSCKFWInstance *fwInstance, + NSSCKFWObject *fwObject) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (CK_OBJECT_HANDLE)0; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (CK_OBJECT_HANDLE)0; + } - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return (CK_OBJECT_HANDLE)0; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return (CK_OBJECT_HANDLE)0; + } #endif /* NSSDEBUG */ - - return nssCKFWObject_GetHandle(fwObject); + + return nssCKFWObject_GetHandle(fwObject); } /* @@ -866,70 +829,67 @@ nssCKFWInstance_FindObjectHandle * */ NSS_IMPLEMENT CK_ULONG -nssCKFWInstance_GetNSlots -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nssCKFWInstance_GetNSlots( + NSSCKFWInstance *fwInstance, + CK_RV *pError) { #ifdef NSSDEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - *pError = CKR_OK; - return fwInstance->nSlots; -} + *pError = CKR_OK; + return fwInstance->nSlots; +} /* * nssCKFWInstance_GetCryptokiVersion * */ NSS_IMPLEMENT CK_VERSION -nssCKFWInstance_GetCryptokiVersion -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_GetCryptokiVersion( + NSSCKFWInstance *fwInstance) { - CK_VERSION rv; + CK_VERSION rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + rv.major = rv.minor = 0; + return rv; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex)) { + rv.major = rv.minor = 0; + return rv; + } + + if ((0 != fwInstance->cryptokiVersion.major) || + (0 != fwInstance->cryptokiVersion.minor)) { + rv = fwInstance->cryptokiVersion; + goto done; + } + + if (fwInstance->mdInstance->GetCryptokiVersion) { + fwInstance->cryptokiVersion = fwInstance->mdInstance->GetCryptokiVersion( + fwInstance->mdInstance, fwInstance); + } + else { + fwInstance->cryptokiVersion.major = 2; + fwInstance->cryptokiVersion.minor = 1; + } - if( (0 != fwInstance->cryptokiVersion.major) || - (0 != fwInstance->cryptokiVersion.minor) ) { rv = fwInstance->cryptokiVersion; - goto done; - } - if (fwInstance->mdInstance->GetCryptokiVersion) { - fwInstance->cryptokiVersion = fwInstance->mdInstance->GetCryptokiVersion( - fwInstance->mdInstance, fwInstance); - } else { - fwInstance->cryptokiVersion.major = 2; - fwInstance->cryptokiVersion.minor = 1; - } - - rv = fwInstance->cryptokiVersion; - - done: - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return rv; +done: + (void)nssCKFWMutex_Unlock(fwInstance->mutex); + return rv; } /* @@ -937,48 +897,47 @@ nssCKFWInstance_GetCryptokiVersion * */ NSS_IMPLEMENT CK_RV -nssCKFWInstance_GetManufacturerID -( - NSSCKFWInstance *fwInstance, - CK_CHAR manufacturerID[32] -) +nssCKFWInstance_GetManufacturerID( + NSSCKFWInstance *fwInstance, + CK_CHAR manufacturerID[32]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == manufacturerID ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == manufacturerID) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwInstance->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwInstance->manufacturerID) { - if (fwInstance->mdInstance->GetManufacturerID) { - fwInstance->manufacturerID = fwInstance->mdInstance->GetManufacturerID( - fwInstance->mdInstance, fwInstance, &error); - if ((!fwInstance->manufacturerID) && (CKR_OK != error)) { - goto done; - } - } else { - fwInstance->manufacturerID = (NSSUTF8 *) ""; + error = nssCKFWMutex_Lock(fwInstance->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwInstance->manufacturerID, (char *)manufacturerID, 32, ' '); - error = CKR_OK; + if (!fwInstance->manufacturerID) { + if (fwInstance->mdInstance->GetManufacturerID) { + fwInstance->manufacturerID = fwInstance->mdInstance->GetManufacturerID( + fwInstance->mdInstance, fwInstance, &error); + if ((!fwInstance->manufacturerID) && (CKR_OK != error)) { + goto done; + } + } + else { + fwInstance->manufacturerID = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwInstance->manufacturerID, (char *)manufacturerID, 32, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwInstance->mutex); + return error; } /* @@ -986,19 +945,17 @@ nssCKFWInstance_GetManufacturerID * */ NSS_IMPLEMENT CK_ULONG -nssCKFWInstance_GetFlags -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_GetFlags( + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - /* No "instance flags" are yet defined by Cryptoki. */ - return (CK_ULONG)0; + /* No "instance flags" are yet defined by Cryptoki. */ + return (CK_ULONG)0; } /* @@ -1006,48 +963,47 @@ nssCKFWInstance_GetFlags * */ NSS_IMPLEMENT CK_RV -nssCKFWInstance_GetLibraryDescription -( - NSSCKFWInstance *fwInstance, - CK_CHAR libraryDescription[32] -) +nssCKFWInstance_GetLibraryDescription( + NSSCKFWInstance *fwInstance, + CK_CHAR libraryDescription[32]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == libraryDescription ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == libraryDescription) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwInstance->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwInstance->libraryDescription) { - if (fwInstance->mdInstance->GetLibraryDescription) { - fwInstance->libraryDescription = fwInstance->mdInstance->GetLibraryDescription( - fwInstance->mdInstance, fwInstance, &error); - if ((!fwInstance->libraryDescription) && (CKR_OK != error)) { - goto done; - } - } else { - fwInstance->libraryDescription = (NSSUTF8 *) ""; + error = nssCKFWMutex_Lock(fwInstance->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwInstance->libraryDescription, (char *)libraryDescription, 32, ' '); - error = CKR_OK; + if (!fwInstance->libraryDescription) { + if (fwInstance->mdInstance->GetLibraryDescription) { + fwInstance->libraryDescription = fwInstance->mdInstance->GetLibraryDescription( + fwInstance->mdInstance, fwInstance, &error); + if ((!fwInstance->libraryDescription) && (CKR_OK != error)) { + goto done; + } + } + else { + fwInstance->libraryDescription = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwInstance->libraryDescription, (char *)libraryDescription, 32, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwInstance->mutex); + return error; } /* @@ -1055,43 +1011,42 @@ nssCKFWInstance_GetLibraryDescription * */ NSS_IMPLEMENT CK_VERSION -nssCKFWInstance_GetLibraryVersion -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_GetLibraryVersion( + NSSCKFWInstance *fwInstance) { - CK_VERSION rv; + CK_VERSION rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + rv.major = rv.minor = 0; + return rv; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWMutex_Lock(fwInstance->mutex)) { + rv.major = rv.minor = 0; + return rv; + } + + if ((0 != fwInstance->libraryVersion.major) || + (0 != fwInstance->libraryVersion.minor)) { + rv = fwInstance->libraryVersion; + goto done; + } + + if (fwInstance->mdInstance->GetLibraryVersion) { + fwInstance->libraryVersion = fwInstance->mdInstance->GetLibraryVersion( + fwInstance->mdInstance, fwInstance); + } + else { + fwInstance->libraryVersion.major = 0; + fwInstance->libraryVersion.minor = 3; + } - if( (0 != fwInstance->libraryVersion.major) || - (0 != fwInstance->libraryVersion.minor) ) { rv = fwInstance->libraryVersion; - goto done; - } - - if (fwInstance->mdInstance->GetLibraryVersion) { - fwInstance->libraryVersion = fwInstance->mdInstance->GetLibraryVersion( - fwInstance->mdInstance, fwInstance); - } else { - fwInstance->libraryVersion.major = 0; - fwInstance->libraryVersion.minor = 3; - } - - rv = fwInstance->libraryVersion; - done: - (void)nssCKFWMutex_Unlock(fwInstance->mutex); - return rv; +done: + (void)nssCKFWMutex_Unlock(fwInstance->mutex); + return rv; } /* @@ -1099,18 +1054,16 @@ nssCKFWInstance_GetLibraryVersion * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWInstance_GetModuleHandlesSessionObjects -( - NSSCKFWInstance *fwInstance -) +nssCKFWInstance_GetModuleHandlesSessionObjects( + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - return fwInstance->moduleHandlesSessionObjects; + return fwInstance->moduleHandlesSessionObjects; } /* @@ -1118,24 +1071,22 @@ nssCKFWInstance_GetModuleHandlesSessionObjects * */ NSS_IMPLEMENT NSSCKFWSlot ** -nssCKFWInstance_GetSlots -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nssCKFWInstance_GetSlots( + NSSCKFWInstance *fwInstance, + CK_RV *pError) { #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWSlot **)NULL; - } + if (!pError) { + return (NSSCKFWSlot **)NULL; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (NSSCKFWSlot **)NULL; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (NSSCKFWSlot **)NULL; + } #endif /* NSSDEBUG */ - return fwInstance->fwSlotList; + return fwInstance->fwSlotList; } /* @@ -1143,72 +1094,69 @@ nssCKFWInstance_GetSlots * */ NSS_IMPLEMENT NSSCKFWSlot * -nssCKFWInstance_WaitForSlotEvent -( - NSSCKFWInstance *fwInstance, - CK_BBOOL block, - CK_RV *pError -) +nssCKFWInstance_WaitForSlotEvent( + NSSCKFWInstance *fwInstance, + CK_BBOOL block, + CK_RV *pError) { - NSSCKFWSlot *fwSlot = (NSSCKFWSlot *)NULL; - NSSCKMDSlot *mdSlot; - CK_ULONG i, n; + NSSCKFWSlot *fwSlot = (NSSCKFWSlot *)NULL; + NSSCKMDSlot *mdSlot; + CK_ULONG i, n; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWSlot *)NULL; - } + if (!pError) { + return (NSSCKFWSlot *)NULL; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (NSSCKFWSlot *)NULL; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (NSSCKFWSlot *)NULL; + } - switch( block ) { - case CK_TRUE: - case CK_FALSE: - break; - default: - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWSlot *)NULL; - } + switch (block) { + case CK_TRUE: + case CK_FALSE: + break; + default: + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWSlot *)NULL; + } #endif /* NSSDEBUG */ - if (!fwInstance->mdInstance->WaitForSlotEvent) { - *pError = CKR_NO_EVENT; - return (NSSCKFWSlot *)NULL; - } - - mdSlot = fwInstance->mdInstance->WaitForSlotEvent( - fwInstance->mdInstance, - fwInstance, - block, - pError - ); - - if (!mdSlot) { - return (NSSCKFWSlot *)NULL; - } - - n = nssCKFWInstance_GetNSlots(fwInstance, pError); - if( ((CK_ULONG)0 == n) && (CKR_OK != *pError) ) { - return (NSSCKFWSlot *)NULL; - } - - for( i = 0; i < n; i++ ) { - if( fwInstance->mdSlotList[i] == mdSlot ) { - fwSlot = fwInstance->fwSlotList[i]; - break; + if (!fwInstance->mdInstance->WaitForSlotEvent) { + *pError = CKR_NO_EVENT; + return (NSSCKFWSlot *)NULL; } - } - if (!fwSlot) { - /* Internal error */ - *pError = CKR_GENERAL_ERROR; - return (NSSCKFWSlot *)NULL; - } + mdSlot = fwInstance->mdInstance->WaitForSlotEvent( + fwInstance->mdInstance, + fwInstance, + block, + pError); - return fwSlot; + if (!mdSlot) { + return (NSSCKFWSlot *)NULL; + } + + n = nssCKFWInstance_GetNSlots(fwInstance, pError); + if (((CK_ULONG)0 == n) && (CKR_OK != *pError)) { + return (NSSCKFWSlot *)NULL; + } + + for (i = 0; i < n; i++) { + if (fwInstance->mdSlotList[i] == mdSlot) { + fwSlot = fwInstance->fwSlotList[i]; + break; + } + } + + if (!fwSlot) { + /* Internal error */ + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWSlot *)NULL; + } + + return fwSlot; } /* @@ -1216,18 +1164,16 @@ nssCKFWInstance_WaitForSlotEvent * */ NSS_IMPLEMENT NSSCKMDInstance * -NSSCKFWInstance_GetMDInstance -( - NSSCKFWInstance *fwInstance -) +NSSCKFWInstance_GetMDInstance( + NSSCKFWInstance *fwInstance) { #ifdef DEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (NSSCKMDInstance *)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (NSSCKMDInstance *)NULL; + } #endif /* DEBUG */ - return nssCKFWInstance_GetMDInstance(fwInstance); + return nssCKFWInstance_GetMDInstance(fwInstance); } /* @@ -1235,24 +1181,22 @@ NSSCKFWInstance_GetMDInstance * */ NSS_IMPLEMENT NSSArena * -NSSCKFWInstance_GetArena -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +NSSCKFWInstance_GetArena( + NSSCKFWInstance *fwInstance, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (NSSArena *)NULL; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (NSSArena *)NULL; + } #endif /* DEBUG */ - return nssCKFWInstance_GetArena(fwInstance, pError); + return nssCKFWInstance_GetArena(fwInstance, pError); } /* @@ -1260,18 +1204,16 @@ NSSCKFWInstance_GetArena * */ NSS_IMPLEMENT CK_BBOOL -NSSCKFWInstance_MayCreatePthreads -( - NSSCKFWInstance *fwInstance -) +NSSCKFWInstance_MayCreatePthreads( + NSSCKFWInstance *fwInstance) { #ifdef DEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return CK_FALSE; + } #endif /* DEBUG */ - return nssCKFWInstance_MayCreatePthreads(fwInstance); + return nssCKFWInstance_MayCreatePthreads(fwInstance); } /* @@ -1279,25 +1221,23 @@ NSSCKFWInstance_MayCreatePthreads * */ NSS_IMPLEMENT NSSCKFWMutex * -NSSCKFWInstance_CreateMutex -( - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +NSSCKFWInstance_CreateMutex( + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (NSSCKFWMutex *)NULL; - } + if (!pError) { + return (NSSCKFWMutex *)NULL; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (NSSCKFWMutex *)NULL; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (NSSCKFWMutex *)NULL; + } #endif /* DEBUG */ - return nssCKFWInstance_CreateMutex(fwInstance, arena, pError); + return nssCKFWInstance_CreateMutex(fwInstance, arena, pError); } /* @@ -1305,18 +1245,16 @@ NSSCKFWInstance_CreateMutex * */ NSS_IMPLEMENT NSSUTF8 * -NSSCKFWInstance_GetConfigurationData -( - NSSCKFWInstance *fwInstance -) +NSSCKFWInstance_GetConfigurationData( + NSSCKFWInstance *fwInstance) { #ifdef DEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (NSSUTF8 *)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (NSSUTF8 *)NULL; + } #endif /* DEBUG */ - return nssCKFWInstance_GetConfigurationData(fwInstance); + return nssCKFWInstance_GetConfigurationData(fwInstance); } /* @@ -1324,17 +1262,14 @@ NSSCKFWInstance_GetConfigurationData * */ NSS_IMPLEMENT CK_C_INITIALIZE_ARGS_PTR -NSSCKFWInstance_GetInitArgs -( - NSSCKFWInstance *fwInstance -) +NSSCKFWInstance_GetInitArgs( + NSSCKFWInstance *fwInstance) { #ifdef DEBUG - if( CKR_OK != nssCKFWInstance_verifyPointer(fwInstance) ) { - return (CK_C_INITIALIZE_ARGS_PTR)NULL; - } + if (CKR_OK != nssCKFWInstance_verifyPointer(fwInstance)) { + return (CK_C_INITIALIZE_ARGS_PTR)NULL; + } #endif /* DEBUG */ - return nssCKFWInstance_GetInitArgs(fwInstance); + return nssCKFWInstance_GetInitArgs(fwInstance); } - diff --git a/security/nss/lib/ckfw/mechanism.c b/security/nss/lib/ckfw/mechanism.c index 14baf02c585f..47e5ac69f3e5 100644 --- a/security/nss/lib/ckfw/mechanism.c +++ b/security/nss/lib/ckfw/mechanism.c @@ -55,13 +55,12 @@ * nssCKFWMechanism_DeriveKey */ - struct NSSCKFWMechanismStr { - NSSCKMDMechanism *mdMechanism; - NSSCKMDToken *mdToken; - NSSCKFWToken *fwToken; - NSSCKMDInstance *mdInstance; - NSSCKFWInstance *fwInstance; + NSSCKMDMechanism *mdMechanism; + NSSCKMDToken *mdToken; + NSSCKFWToken *fwToken; + NSSCKMDInstance *mdInstance; + NSSCKFWInstance *fwInstance; }; /* @@ -69,28 +68,25 @@ struct NSSCKFWMechanismStr { * */ NSS_IMPLEMENT NSSCKFWMechanism * -nssCKFWMechanism_Create -( - NSSCKMDMechanism *mdMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nssCKFWMechanism_Create( + NSSCKMDMechanism *mdMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - NSSCKFWMechanism *fwMechanism; + NSSCKFWMechanism *fwMechanism; - - fwMechanism = nss_ZNEW(NULL, NSSCKFWMechanism); - if (!fwMechanism) { - return (NSSCKFWMechanism *)NULL; - } - fwMechanism->mdMechanism = mdMechanism; - fwMechanism->mdToken = mdToken; - fwMechanism->fwToken = fwToken; - fwMechanism->mdInstance = mdInstance; - fwMechanism->fwInstance = fwInstance; - return fwMechanism; + fwMechanism = nss_ZNEW(NULL, NSSCKFWMechanism); + if (!fwMechanism) { + return (NSSCKFWMechanism *)NULL; + } + fwMechanism->mdMechanism = mdMechanism; + fwMechanism->mdToken = mdToken; + fwMechanism->fwToken = fwToken; + fwMechanism->mdInstance = mdInstance; + fwMechanism->fwInstance = fwInstance; + return fwMechanism; } /* @@ -98,24 +94,22 @@ nssCKFWMechanism_Create * */ NSS_IMPLEMENT void -nssCKFWMechanism_Destroy -( - NSSCKFWMechanism *fwMechanism -) +nssCKFWMechanism_Destroy( + NSSCKFWMechanism *fwMechanism) { - /* destroy any fw resources held by nssCKFWMechanism (currently none) */ + /* destroy any fw resources held by nssCKFWMechanism (currently none) */ - if (!fwMechanism->mdMechanism->Destroy) { - /* destroys it's parent as well */ - fwMechanism->mdMechanism->Destroy( - fwMechanism->mdMechanism, - fwMechanism, - fwMechanism->mdInstance, - fwMechanism->fwInstance); - } - /* if the Destroy function wasn't supplied, then the mechanism is 'static', - * and there is nothing to destroy */ - return; + if (!fwMechanism->mdMechanism->Destroy) { + /* destroys it's parent as well */ + fwMechanism->mdMechanism->Destroy( + fwMechanism->mdMechanism, + fwMechanism, + fwMechanism->mdInstance, + fwMechanism->fwInstance); + } + /* if the Destroy function wasn't supplied, then the mechanism is 'static', + * and there is nothing to destroy */ + return; } /* @@ -123,12 +117,10 @@ nssCKFWMechanism_Destroy * */ NSS_IMPLEMENT NSSCKMDMechanism * -nssCKFWMechanism_GetMDMechanism -( - NSSCKFWMechanism *fwMechanism -) +nssCKFWMechanism_GetMDMechanism( + NSSCKFWMechanism *fwMechanism) { - return fwMechanism->mdMechanism; + return fwMechanism->mdMechanism; } /* @@ -136,19 +128,17 @@ nssCKFWMechanism_GetMDMechanism * */ NSS_IMPLEMENT CK_ULONG -nssCKFWMechanism_GetMinKeySize -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetMinKeySize( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->GetMinKeySize) { - return 0; - } + if (!fwMechanism->mdMechanism->GetMinKeySize) { + return 0; + } - return fwMechanism->mdMechanism->GetMinKeySize(fwMechanism->mdMechanism, - fwMechanism, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, pError); + return fwMechanism->mdMechanism->GetMinKeySize(fwMechanism->mdMechanism, + fwMechanism, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, pError); } /* @@ -156,19 +146,17 @@ nssCKFWMechanism_GetMinKeySize * */ NSS_IMPLEMENT CK_ULONG -nssCKFWMechanism_GetMaxKeySize -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetMaxKeySize( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->GetMaxKeySize) { - return 0; - } + if (!fwMechanism->mdMechanism->GetMaxKeySize) { + return 0; + } - return fwMechanism->mdMechanism->GetMaxKeySize(fwMechanism->mdMechanism, - fwMechanism, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, pError); + return fwMechanism->mdMechanism->GetMaxKeySize(fwMechanism->mdMechanism, + fwMechanism, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, pError); } /* @@ -176,22 +164,19 @@ nssCKFWMechanism_GetMaxKeySize * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWMechanism_GetInHardware -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetInHardware( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->GetInHardware) { - return CK_FALSE; - } + if (!fwMechanism->mdMechanism->GetInHardware) { + return CK_FALSE; + } - return fwMechanism->mdMechanism->GetInHardware(fwMechanism->mdMechanism, - fwMechanism, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, pError); + return fwMechanism->mdMechanism->GetInHardware(fwMechanism->mdMechanism, + fwMechanism, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, pError); } - /* * the following are determined automatically by which of the cryptographic * functions are defined for this mechanism. @@ -201,16 +186,14 @@ nssCKFWMechanism_GetInHardware * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanEncrypt -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanEncrypt( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->EncryptInit) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->EncryptInit) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -218,16 +201,14 @@ nssCKFWMechanism_GetCanEncrypt * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanDecrypt -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanDecrypt( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->DecryptInit) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->DecryptInit) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -235,16 +216,14 @@ nssCKFWMechanism_GetCanDecrypt * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanDigest -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanDigest( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->DigestInit) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->DigestInit) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -252,16 +231,14 @@ nssCKFWMechanism_GetCanDigest * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanSign -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanSign( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->SignInit) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->SignInit) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -269,16 +246,14 @@ nssCKFWMechanism_GetCanSign * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanSignRecover -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanSignRecover( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->SignRecoverInit) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->SignRecoverInit) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -286,16 +261,14 @@ nssCKFWMechanism_GetCanSignRecover * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanVerify -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanVerify( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->VerifyInit) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->VerifyInit) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -303,16 +276,14 @@ nssCKFWMechanism_GetCanVerify * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanVerifyRecover -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanVerifyRecover( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->VerifyRecoverInit) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->VerifyRecoverInit) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -320,16 +291,14 @@ nssCKFWMechanism_GetCanVerifyRecover * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanGenerate -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanGenerate( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->GenerateKey) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->GenerateKey) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -337,16 +306,14 @@ nssCKFWMechanism_GetCanGenerate * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanGenerateKeyPair -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanGenerateKeyPair( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->GenerateKeyPair) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->GenerateKeyPair) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -354,16 +321,14 @@ nssCKFWMechanism_GetCanGenerateKeyPair * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanUnwrap -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanUnwrap( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->UnwrapKey) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->UnwrapKey) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -371,16 +336,14 @@ nssCKFWMechanism_GetCanUnwrap * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanWrap -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanWrap( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->WrapKey) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->WrapKey) { + return CK_FALSE; + } + return CK_TRUE; } /* @@ -388,55 +351,50 @@ nssCKFWMechanism_GetCanWrap * */ NSS_EXTERN CK_BBOOL -nssCKFWMechanism_GetCanDerive -( - NSSCKFWMechanism *fwMechanism, - CK_RV *pError -) +nssCKFWMechanism_GetCanDerive( + NSSCKFWMechanism *fwMechanism, + CK_RV *pError) { - if (!fwMechanism->mdMechanism->DeriveKey) { - return CK_FALSE; - } - return CK_TRUE; + if (!fwMechanism->mdMechanism->DeriveKey) { + return CK_FALSE; + } + return CK_TRUE; } /* * These are the actual crypto operations */ -/* +/* * nssCKFWMechanism_EncryptInit * Start an encryption session. */ NSS_EXTERN CK_RV -nssCKFWMechanism_EncryptInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWMechanism_EncryptInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { - NSSCKFWCryptoOperation *fwOperation; - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + CK_RV error = CKR_OK; + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_EncryptDecrypt); + if (fwOperation) { + return CKR_OPERATION_ACTIVE; + } - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_EncryptDecrypt); - if (fwOperation) { - return CKR_OPERATION_ACTIVE; - } + if (!fwMechanism->mdMechanism->EncryptInit) { + return CKR_FUNCTION_FAILED; + } - if (!fwMechanism->mdMechanism->EncryptInit) { - return CKR_FUNCTION_FAILED; - } - - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdObject = nssCKFWObject_GetMDObject(fwObject); - mdOperation = fwMechanism->mdMechanism->EncryptInit( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdObject = nssCKFWObject_GetMDObject(fwObject); + mdOperation = fwMechanism->mdMechanism->EncryptInit( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -448,58 +406,54 @@ nssCKFWMechanism_EncryptInit fwMechanism->fwInstance, mdObject, fwObject, - &error - ); - if (!mdOperation) { - goto loser; - } + &error); + if (!mdOperation) { + goto loser; + } - fwOperation = nssCKFWCryptoOperation_Create(mdOperation, - mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, - NSSCKFWCryptoOperationType_Encrypt, &error); - if (fwOperation) { - nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, - NSSCKFWCryptoOperationState_EncryptDecrypt); - } + fwOperation = nssCKFWCryptoOperation_Create(mdOperation, + mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, + NSSCKFWCryptoOperationType_Encrypt, &error); + if (fwOperation) { + nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, + NSSCKFWCryptoOperationState_EncryptDecrypt); + } loser: - return error; + return error; } -/* +/* * nssCKFWMechanism_DecryptInit * Start an encryption session. */ NSS_EXTERN CK_RV -nssCKFWMechanism_DecryptInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWMechanism_DecryptInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { - NSSCKFWCryptoOperation *fwOperation; - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + CK_RV error = CKR_OK; + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_EncryptDecrypt); + if (fwOperation) { + return CKR_OPERATION_ACTIVE; + } - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_EncryptDecrypt); - if (fwOperation) { - return CKR_OPERATION_ACTIVE; - } + if (!fwMechanism->mdMechanism->DecryptInit) { + return CKR_FUNCTION_FAILED; + } - if (!fwMechanism->mdMechanism->DecryptInit) { - return CKR_FUNCTION_FAILED; - } - - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdObject = nssCKFWObject_GetMDObject(fwObject); - mdOperation = fwMechanism->mdMechanism->DecryptInit( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdObject = nssCKFWObject_GetMDObject(fwObject); + mdOperation = fwMechanism->mdMechanism->DecryptInit( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -511,55 +465,51 @@ nssCKFWMechanism_DecryptInit fwMechanism->fwInstance, mdObject, fwObject, - &error - ); - if (!mdOperation) { - goto loser; - } + &error); + if (!mdOperation) { + goto loser; + } - fwOperation = nssCKFWCryptoOperation_Create(mdOperation, - mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, - NSSCKFWCryptoOperationType_Decrypt, &error); - if (fwOperation) { - nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, - NSSCKFWCryptoOperationState_EncryptDecrypt); - } + fwOperation = nssCKFWCryptoOperation_Create(mdOperation, + mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, + NSSCKFWCryptoOperationType_Decrypt, &error); + if (fwOperation) { + nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, + NSSCKFWCryptoOperationState_EncryptDecrypt); + } loser: - return error; + return error; } -/* +/* * nssCKFWMechanism_DigestInit * Start an encryption session. */ NSS_EXTERN CK_RV -nssCKFWMechanism_DigestInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession -) +nssCKFWMechanism_DigestInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession) { - NSSCKFWCryptoOperation *fwOperation; - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + CK_RV error = CKR_OK; + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_Digest); + if (fwOperation) { + return CKR_OPERATION_ACTIVE; + } - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_Digest); - if (fwOperation) { - return CKR_OPERATION_ACTIVE; - } + if (!fwMechanism->mdMechanism->DigestInit) { + return CKR_FUNCTION_FAILED; + } - if (!fwMechanism->mdMechanism->DigestInit) { - return CKR_FUNCTION_FAILED; - } - - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdOperation = fwMechanism->mdMechanism->DigestInit( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdOperation = fwMechanism->mdMechanism->DigestInit( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -569,58 +519,54 @@ nssCKFWMechanism_DigestInit fwMechanism->fwToken, fwMechanism->mdInstance, fwMechanism->fwInstance, - &error - ); - if (!mdOperation) { - goto loser; - } + &error); + if (!mdOperation) { + goto loser; + } - fwOperation = nssCKFWCryptoOperation_Create(mdOperation, - mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, - NSSCKFWCryptoOperationType_Digest, &error); - if (fwOperation) { - nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, - NSSCKFWCryptoOperationState_Digest); - } + fwOperation = nssCKFWCryptoOperation_Create(mdOperation, + mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, + NSSCKFWCryptoOperationType_Digest, &error); + if (fwOperation) { + nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, + NSSCKFWCryptoOperationState_Digest); + } loser: - return error; + return error; } -/* +/* * nssCKFWMechanism_SignInit * Start an encryption session. */ NSS_EXTERN CK_RV -nssCKFWMechanism_SignInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWMechanism_SignInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { - NSSCKFWCryptoOperation *fwOperation; - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + CK_RV error = CKR_OK; + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_SignVerify); + if (fwOperation) { + return CKR_OPERATION_ACTIVE; + } - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_SignVerify); - if (fwOperation) { - return CKR_OPERATION_ACTIVE; - } + if (!fwMechanism->mdMechanism->SignInit) { + return CKR_FUNCTION_FAILED; + } - if (!fwMechanism->mdMechanism->SignInit) { - return CKR_FUNCTION_FAILED; - } - - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdObject = nssCKFWObject_GetMDObject(fwObject); - mdOperation = fwMechanism->mdMechanism->SignInit( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdObject = nssCKFWObject_GetMDObject(fwObject); + mdOperation = fwMechanism->mdMechanism->SignInit( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -632,58 +578,54 @@ nssCKFWMechanism_SignInit fwMechanism->fwInstance, mdObject, fwObject, - &error - ); - if (!mdOperation) { - goto loser; - } + &error); + if (!mdOperation) { + goto loser; + } - fwOperation = nssCKFWCryptoOperation_Create(mdOperation, - mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, - NSSCKFWCryptoOperationType_Sign, &error); - if (fwOperation) { - nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, - NSSCKFWCryptoOperationState_SignVerify); - } + fwOperation = nssCKFWCryptoOperation_Create(mdOperation, + mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, + NSSCKFWCryptoOperationType_Sign, &error); + if (fwOperation) { + nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, + NSSCKFWCryptoOperationState_SignVerify); + } loser: - return error; + return error; } -/* +/* * nssCKFWMechanism_VerifyInit * Start an encryption session. */ NSS_EXTERN CK_RV -nssCKFWMechanism_VerifyInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWMechanism_VerifyInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { - NSSCKFWCryptoOperation *fwOperation; - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + CK_RV error = CKR_OK; + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_SignVerify); + if (fwOperation) { + return CKR_OPERATION_ACTIVE; + } - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_SignVerify); - if (fwOperation) { - return CKR_OPERATION_ACTIVE; - } + if (!fwMechanism->mdMechanism->VerifyInit) { + return CKR_FUNCTION_FAILED; + } - if (!fwMechanism->mdMechanism->VerifyInit) { - return CKR_FUNCTION_FAILED; - } - - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdObject = nssCKFWObject_GetMDObject(fwObject); - mdOperation = fwMechanism->mdMechanism->VerifyInit( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdObject = nssCKFWObject_GetMDObject(fwObject); + mdOperation = fwMechanism->mdMechanism->VerifyInit( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -695,58 +637,54 @@ nssCKFWMechanism_VerifyInit fwMechanism->fwInstance, mdObject, fwObject, - &error - ); - if (!mdOperation) { - goto loser; - } + &error); + if (!mdOperation) { + goto loser; + } - fwOperation = nssCKFWCryptoOperation_Create(mdOperation, - mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, - NSSCKFWCryptoOperationType_Verify, &error); - if (fwOperation) { - nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, - NSSCKFWCryptoOperationState_SignVerify); - } + fwOperation = nssCKFWCryptoOperation_Create(mdOperation, + mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, + NSSCKFWCryptoOperationType_Verify, &error); + if (fwOperation) { + nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, + NSSCKFWCryptoOperationState_SignVerify); + } loser: - return error; + return error; } -/* +/* * nssCKFWMechanism_SignRecoverInit * Start an encryption session. */ NSS_EXTERN CK_RV -nssCKFWMechanism_SignRecoverInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWMechanism_SignRecoverInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { - NSSCKFWCryptoOperation *fwOperation; - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + CK_RV error = CKR_OK; + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_SignVerify); + if (fwOperation) { + return CKR_OPERATION_ACTIVE; + } - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_SignVerify); - if (fwOperation) { - return CKR_OPERATION_ACTIVE; - } + if (!fwMechanism->mdMechanism->SignRecoverInit) { + return CKR_FUNCTION_FAILED; + } - if (!fwMechanism->mdMechanism->SignRecoverInit) { - return CKR_FUNCTION_FAILED; - } - - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdObject = nssCKFWObject_GetMDObject(fwObject); - mdOperation = fwMechanism->mdMechanism->SignRecoverInit( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdObject = nssCKFWObject_GetMDObject(fwObject); + mdOperation = fwMechanism->mdMechanism->SignRecoverInit( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -758,58 +696,54 @@ nssCKFWMechanism_SignRecoverInit fwMechanism->fwInstance, mdObject, fwObject, - &error - ); - if (!mdOperation) { - goto loser; - } + &error); + if (!mdOperation) { + goto loser; + } - fwOperation = nssCKFWCryptoOperation_Create(mdOperation, - mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, - NSSCKFWCryptoOperationType_SignRecover, &error); - if (fwOperation) { - nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, - NSSCKFWCryptoOperationState_SignVerify); - } + fwOperation = nssCKFWCryptoOperation_Create(mdOperation, + mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, + NSSCKFWCryptoOperationType_SignRecover, &error); + if (fwOperation) { + nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, + NSSCKFWCryptoOperationState_SignVerify); + } loser: - return error; + return error; } -/* +/* * nssCKFWMechanism_VerifyRecoverInit * Start an encryption session. */ NSS_EXTERN CK_RV -nssCKFWMechanism_VerifyRecoverInit -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWMechanism_VerifyRecoverInit( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { - NSSCKFWCryptoOperation *fwOperation; - NSSCKMDCryptoOperation *mdOperation; - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSCKMDCryptoOperation *mdOperation; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + CK_RV error = CKR_OK; + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_SignVerify); + if (fwOperation) { + return CKR_OPERATION_ACTIVE; + } - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_SignVerify); - if (fwOperation) { - return CKR_OPERATION_ACTIVE; - } + if (!fwMechanism->mdMechanism->VerifyRecoverInit) { + return CKR_FUNCTION_FAILED; + } - if (!fwMechanism->mdMechanism->VerifyRecoverInit) { - return CKR_FUNCTION_FAILED; - } - - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdObject = nssCKFWObject_GetMDObject(fwObject); - mdOperation = fwMechanism->mdMechanism->VerifyRecoverInit( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdObject = nssCKFWObject_GetMDObject(fwObject); + mdOperation = fwMechanism->mdMechanism->VerifyRecoverInit( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -821,59 +755,56 @@ nssCKFWMechanism_VerifyRecoverInit fwMechanism->fwInstance, mdObject, fwObject, - &error - ); - if (!mdOperation) { - goto loser; - } + &error); + if (!mdOperation) { + goto loser; + } - fwOperation = nssCKFWCryptoOperation_Create(mdOperation, - mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, - fwMechanism->mdInstance, fwMechanism->fwInstance, - NSSCKFWCryptoOperationType_VerifyRecover, &error); - if (fwOperation) { - nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, - NSSCKFWCryptoOperationState_SignVerify); - } + fwOperation = nssCKFWCryptoOperation_Create(mdOperation, + mdSession, fwSession, fwMechanism->mdToken, fwMechanism->fwToken, + fwMechanism->mdInstance, fwMechanism->fwInstance, + NSSCKFWCryptoOperationType_VerifyRecover, &error); + if (fwOperation) { + nssCKFWSession_SetCurrentCryptoOperation(fwSession, fwOperation, + NSSCKFWCryptoOperationState_SignVerify); + } loser: - return error; + return error; } /* * nssCKFWMechanism_GenerateKey */ NSS_EXTERN NSSCKFWObject * -nssCKFWMechanism_GenerateKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nssCKFWMechanism_GenerateKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - NSSCKFWObject *fwObject = NULL; - NSSArena *arena; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + NSSCKFWObject *fwObject = NULL; + NSSArena *arena; - if (!fwMechanism->mdMechanism->GenerateKey) { - *pError = CKR_FUNCTION_FAILED; - return (NSSCKFWObject *)NULL; - } - - arena = nssCKFWToken_GetArena(fwMechanism->fwToken, pError); - if (!arena) { - if (CKR_OK == *pError) { - *pError = CKR_GENERAL_ERROR; + if (!fwMechanism->mdMechanism->GenerateKey) { + *pError = CKR_FUNCTION_FAILED; + return (NSSCKFWObject *)NULL; } - return (NSSCKFWObject *)NULL; - } - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdObject = fwMechanism->mdMechanism->GenerateKey( + arena = nssCKFWToken_GetArena(fwMechanism->fwToken, pError); + if (!arena) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWObject *)NULL; + } + + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdObject = fwMechanism->mdMechanism->GenerateKey( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -887,53 +818,51 @@ nssCKFWMechanism_GenerateKey ulAttributeCount, pError); - if (!mdObject) { - return (NSSCKFWObject *)NULL; - } + if (!mdObject) { + return (NSSCKFWObject *)NULL; + } - fwObject = nssCKFWObject_Create(arena, mdObject, - fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, pError); + fwObject = nssCKFWObject_Create(arena, mdObject, + fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, pError); - return fwObject; + return fwObject; } /* * nssCKFWMechanism_GenerateKeyPair */ NSS_EXTERN CK_RV -nssCKFWMechanism_GenerateKeyPair -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG ulPublicKeyAttributeCount, - CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG ulPrivateKeyAttributeCount, - NSSCKFWObject **fwPublicKeyObject, - NSSCKFWObject **fwPrivateKeyObject -) +nssCKFWMechanism_GenerateKeyPair( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG ulPublicKeyAttributeCount, + CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG ulPrivateKeyAttributeCount, + NSSCKFWObject **fwPublicKeyObject, + NSSCKFWObject **fwPrivateKeyObject) { - NSSCKMDSession *mdSession; - NSSCKMDObject *mdPublicKeyObject; - NSSCKMDObject *mdPrivateKeyObject; - NSSArena *arena; - CK_RV error = CKR_OK; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdPublicKeyObject; + NSSCKMDObject *mdPrivateKeyObject; + NSSArena *arena; + CK_RV error = CKR_OK; - if (!fwMechanism->mdMechanism->GenerateKeyPair) { - return CKR_FUNCTION_FAILED; - } - - arena = nssCKFWToken_GetArena(fwMechanism->fwToken, &error); - if (!arena) { - if (CKR_OK == error) { - error = CKR_GENERAL_ERROR; + if (!fwMechanism->mdMechanism->GenerateKeyPair) { + return CKR_FUNCTION_FAILED; } - return error; - } - mdSession = nssCKFWSession_GetMDSession(fwSession); - error = fwMechanism->mdMechanism->GenerateKeyPair( + arena = nssCKFWToken_GetArena(fwMechanism->fwToken, &error); + if (!arena) { + if (CKR_OK == error) { + error = CKR_GENERAL_ERROR; + } + return error; + } + + mdSession = nssCKFWSession_GetMDSession(fwSession); + error = fwMechanism->mdMechanism->GenerateKeyPair( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -950,48 +879,46 @@ nssCKFWMechanism_GenerateKeyPair &mdPublicKeyObject, &mdPrivateKeyObject); - if (CKR_OK != error) { - return error; - } + if (CKR_OK != error) { + return error; + } - *fwPublicKeyObject = nssCKFWObject_Create(arena, mdPublicKeyObject, - fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, &error); - if (!*fwPublicKeyObject) { - return error; - } - *fwPrivateKeyObject = nssCKFWObject_Create(arena, mdPrivateKeyObject, - fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, &error); + *fwPublicKeyObject = nssCKFWObject_Create(arena, mdPublicKeyObject, + fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, &error); + if (!*fwPublicKeyObject) { + return error; + } + *fwPrivateKeyObject = nssCKFWObject_Create(arena, mdPrivateKeyObject, + fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, &error); - return error; + return error; } /* * nssCKFWMechanism_GetWrapKeyLength */ NSS_EXTERN CK_ULONG -nssCKFWMechanism_GetWrapKeyLength -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwWrappingKeyObject, - NSSCKFWObject *fwKeyObject, - CK_RV *pError -) +nssCKFWMechanism_GetWrapKeyLength( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwWrappingKeyObject, + NSSCKFWObject *fwKeyObject, + CK_RV *pError) { - NSSCKMDSession *mdSession; - NSSCKMDObject *mdWrappingKeyObject; - NSSCKMDObject *mdKeyObject; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdWrappingKeyObject; + NSSCKMDObject *mdKeyObject; - if (!fwMechanism->mdMechanism->WrapKey) { - *pError = CKR_FUNCTION_FAILED; - return (CK_ULONG) 0; - } + if (!fwMechanism->mdMechanism->WrapKey) { + *pError = CKR_FUNCTION_FAILED; + return (CK_ULONG)0; + } - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdWrappingKeyObject = nssCKFWObject_GetMDObject(fwWrappingKeyObject); - mdKeyObject = nssCKFWObject_GetMDObject(fwKeyObject); - return fwMechanism->mdMechanism->GetWrapKeyLength( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdWrappingKeyObject = nssCKFWObject_GetMDObject(fwWrappingKeyObject); + mdKeyObject = nssCKFWObject_GetMDObject(fwKeyObject); + return fwMechanism->mdMechanism->GetWrapKeyLength( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -1012,28 +939,26 @@ nssCKFWMechanism_GetWrapKeyLength * nssCKFWMechanism_WrapKey */ NSS_EXTERN CK_RV -nssCKFWMechanism_WrapKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwWrappingKeyObject, - NSSCKFWObject *fwKeyObject, - NSSItem *wrappedKey -) +nssCKFWMechanism_WrapKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwWrappingKeyObject, + NSSCKFWObject *fwKeyObject, + NSSItem *wrappedKey) { - NSSCKMDSession *mdSession; - NSSCKMDObject *mdWrappingKeyObject; - NSSCKMDObject *mdKeyObject; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdWrappingKeyObject; + NSSCKMDObject *mdKeyObject; - if (!fwMechanism->mdMechanism->WrapKey) { - return CKR_FUNCTION_FAILED; - } + if (!fwMechanism->mdMechanism->WrapKey) { + return CKR_FUNCTION_FAILED; + } - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdWrappingKeyObject = nssCKFWObject_GetMDObject(fwWrappingKeyObject); - mdKeyObject = nssCKFWObject_GetMDObject(fwKeyObject); - return fwMechanism->mdMechanism->WrapKey( + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdWrappingKeyObject = nssCKFWObject_GetMDObject(fwWrappingKeyObject); + mdKeyObject = nssCKFWObject_GetMDObject(fwKeyObject); + return fwMechanism->mdMechanism->WrapKey( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -1054,44 +979,42 @@ nssCKFWMechanism_WrapKey * nssCKFWMechanism_UnwrapKey */ NSS_EXTERN NSSCKFWObject * -nssCKFWMechanism_UnwrapKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwWrappingKeyObject, - NSSItem *wrappedKey, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nssCKFWMechanism_UnwrapKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwWrappingKeyObject, + NSSItem *wrappedKey, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - NSSCKMDObject *mdWrappingKeyObject; - NSSCKFWObject *fwObject = NULL; - NSSArena *arena; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + NSSCKMDObject *mdWrappingKeyObject; + NSSCKFWObject *fwObject = NULL; + NSSArena *arena; - if (!fwMechanism->mdMechanism->UnwrapKey) { - /* we could simulate UnwrapKey using Decrypt and Create object, but + if (!fwMechanism->mdMechanism->UnwrapKey) { + /* we could simulate UnwrapKey using Decrypt and Create object, but * 1) it's not clear that would work well, and 2) the low level token * may want to restrict unwrap key for a reason, so just fail it it * can't be done */ - *pError = CKR_FUNCTION_FAILED; - return (NSSCKFWObject *)NULL; - } - - arena = nssCKFWToken_GetArena(fwMechanism->fwToken, pError); - if (!arena) { - if (CKR_OK == *pError) { - *pError = CKR_GENERAL_ERROR; + *pError = CKR_FUNCTION_FAILED; + return (NSSCKFWObject *)NULL; } - return (NSSCKFWObject *)NULL; - } - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdWrappingKeyObject = nssCKFWObject_GetMDObject(fwWrappingKeyObject); - mdObject = fwMechanism->mdMechanism->UnwrapKey( + arena = nssCKFWToken_GetArena(fwMechanism->fwToken, pError); + if (!arena) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWObject *)NULL; + } + + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdWrappingKeyObject = nssCKFWObject_GetMDObject(fwWrappingKeyObject); + mdObject = fwMechanism->mdMechanism->UnwrapKey( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -1108,53 +1031,51 @@ nssCKFWMechanism_UnwrapKey ulAttributeCount, pError); - if (!mdObject) { - return (NSSCKFWObject *)NULL; - } + if (!mdObject) { + return (NSSCKFWObject *)NULL; + } - fwObject = nssCKFWObject_Create(arena, mdObject, - fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, pError); + fwObject = nssCKFWObject_Create(arena, mdObject, + fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, pError); - return fwObject; + return fwObject; } -/* +/* * nssCKFWMechanism_DeriveKey */ NSS_EXTERN NSSCKFWObject * -nssCKFWMechanism_DeriveKey -( - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKFWSession *fwSession, - NSSCKFWObject *fwBaseKeyObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nssCKFWMechanism_DeriveKey( + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKFWSession *fwSession, + NSSCKFWObject *fwBaseKeyObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSCKMDSession *mdSession; - NSSCKMDObject *mdObject; - NSSCKMDObject *mdBaseKeyObject; - NSSCKFWObject *fwObject = NULL; - NSSArena *arena; + NSSCKMDSession *mdSession; + NSSCKMDObject *mdObject; + NSSCKMDObject *mdBaseKeyObject; + NSSCKFWObject *fwObject = NULL; + NSSArena *arena; - if (!fwMechanism->mdMechanism->DeriveKey) { - *pError = CKR_FUNCTION_FAILED; - return (NSSCKFWObject *)NULL; - } - - arena = nssCKFWToken_GetArena(fwMechanism->fwToken, pError); - if (!arena) { - if (CKR_OK == *pError) { - *pError = CKR_GENERAL_ERROR; + if (!fwMechanism->mdMechanism->DeriveKey) { + *pError = CKR_FUNCTION_FAILED; + return (NSSCKFWObject *)NULL; } - return (NSSCKFWObject *)NULL; - } - mdSession = nssCKFWSession_GetMDSession(fwSession); - mdBaseKeyObject = nssCKFWObject_GetMDObject(fwBaseKeyObject); - mdObject = fwMechanism->mdMechanism->DeriveKey( + arena = nssCKFWToken_GetArena(fwMechanism->fwToken, pError); + if (!arena) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWObject *)NULL; + } + + mdSession = nssCKFWSession_GetMDSession(fwSession); + mdBaseKeyObject = nssCKFWObject_GetMDObject(fwBaseKeyObject); + mdObject = fwMechanism->mdMechanism->DeriveKey( fwMechanism->mdMechanism, fwMechanism, pMechanism, @@ -1170,13 +1091,12 @@ nssCKFWMechanism_DeriveKey ulAttributeCount, pError); - if (!mdObject) { - return (NSSCKFWObject *)NULL; - } + if (!mdObject) { + return (NSSCKFWObject *)NULL; + } - fwObject = nssCKFWObject_Create(arena, mdObject, - fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, pError); + fwObject = nssCKFWObject_Create(arena, mdObject, + fwSession, fwMechanism->fwToken, fwMechanism->fwInstance, pError); - return fwObject; + return fwObject; } - diff --git a/security/nss/lib/ckfw/mutex.c b/security/nss/lib/ckfw/mutex.c index 0d74cf133c58..be569e196a64 100644 --- a/security/nss/lib/ckfw/mutex.c +++ b/security/nss/lib/ckfw/mutex.c @@ -31,7 +31,7 @@ */ struct NSSCKFWMutexStr { - PRLock *lock; + PRLock *lock; }; #ifdef DEBUG @@ -47,30 +47,24 @@ struct NSSCKFWMutexStr { */ static CK_RV -mutex_add_pointer -( - const NSSCKFWMutex *fwMutex -) +mutex_add_pointer( + const NSSCKFWMutex *fwMutex) { - return CKR_OK; + return CKR_OK; } static CK_RV -mutex_remove_pointer -( - const NSSCKFWMutex *fwMutex -) +mutex_remove_pointer( + const NSSCKFWMutex *fwMutex) { - return CKR_OK; + return CKR_OK; } NSS_IMPLEMENT CK_RV -nssCKFWMutex_verifyPointer -( - const NSSCKFWMutex *fwMutex -) +nssCKFWMutex_verifyPointer( + const NSSCKFWMutex *fwMutex) { - return CKR_OK; + return CKR_OK; } #endif /* DEBUG */ @@ -80,78 +74,74 @@ nssCKFWMutex_verifyPointer * */ NSS_EXTERN NSSCKFWMutex * -nssCKFWMutex_Create -( - CK_C_INITIALIZE_ARGS_PTR pInitArgs, - CryptokiLockingState LockingState, - NSSArena *arena, - CK_RV *pError -) +nssCKFWMutex_Create( + CK_C_INITIALIZE_ARGS_PTR pInitArgs, + CryptokiLockingState LockingState, + NSSArena *arena, + CK_RV *pError) { - NSSCKFWMutex *mutex; - - mutex = nss_ZNEW(arena, NSSCKFWMutex); - if (!mutex) { - *pError = CKR_HOST_MEMORY; - return (NSSCKFWMutex *)NULL; - } - *pError = CKR_OK; - mutex->lock = NULL; - if (LockingState == MultiThreaded) { - mutex->lock = PR_NewLock(); - if (!mutex->lock) { - *pError = CKR_HOST_MEMORY; /* we couldn't get the resource */ + NSSCKFWMutex *mutex; + + mutex = nss_ZNEW(arena, NSSCKFWMutex); + if (!mutex) { + *pError = CKR_HOST_MEMORY; + return (NSSCKFWMutex *)NULL; + } + *pError = CKR_OK; + mutex->lock = NULL; + if (LockingState == MultiThreaded) { + mutex->lock = PR_NewLock(); + if (!mutex->lock) { + *pError = CKR_HOST_MEMORY; /* we couldn't get the resource */ + } + } + + if (CKR_OK != *pError) { + (void)nss_ZFreeIf(mutex); + return (NSSCKFWMutex *)NULL; } - } - - if( CKR_OK != *pError ) { - (void)nss_ZFreeIf(mutex); - return (NSSCKFWMutex *)NULL; - } #ifdef DEBUG - *pError = mutex_add_pointer(mutex); - if( CKR_OK != *pError ) { - if (mutex->lock) { - PR_DestroyLock(mutex->lock); + *pError = mutex_add_pointer(mutex); + if (CKR_OK != *pError) { + if (mutex->lock) { + PR_DestroyLock(mutex->lock); + } + (void)nss_ZFreeIf(mutex); + return (NSSCKFWMutex *)NULL; } - (void)nss_ZFreeIf(mutex); - return (NSSCKFWMutex *)NULL; - } #endif /* DEBUG */ - return mutex; -} + return mutex; +} /* * nssCKFWMutex_Destroy * */ NSS_EXTERN CK_RV -nssCKFWMutex_Destroy -( - NSSCKFWMutex *mutex -) +nssCKFWMutex_Destroy( + NSSCKFWMutex *mutex) { - CK_RV rv = CKR_OK; + CK_RV rv = CKR_OK; #ifdef NSSDEBUG - rv = nssCKFWMutex_verifyPointer(mutex); - if( CKR_OK != rv ) { - return rv; - } + rv = nssCKFWMutex_verifyPointer(mutex); + if (CKR_OK != rv) { + return rv; + } #endif /* NSSDEBUG */ - - if (mutex->lock) { - PR_DestroyLock(mutex->lock); - } + + if (mutex->lock) { + PR_DestroyLock(mutex->lock); + } #ifdef DEBUG - (void)mutex_remove_pointer(mutex); + (void)mutex_remove_pointer(mutex); #endif /* DEBUG */ - (void)nss_ZFreeIf(mutex); - return rv; + (void)nss_ZFreeIf(mutex); + return rv; } /* @@ -159,22 +149,20 @@ nssCKFWMutex_Destroy * */ NSS_EXTERN CK_RV -nssCKFWMutex_Lock -( - NSSCKFWMutex *mutex -) +nssCKFWMutex_Lock( + NSSCKFWMutex *mutex) { #ifdef NSSDEBUG - CK_RV rv = nssCKFWMutex_verifyPointer(mutex); - if( CKR_OK != rv ) { - return rv; - } + CK_RV rv = nssCKFWMutex_verifyPointer(mutex); + if (CKR_OK != rv) { + return rv; + } #endif /* NSSDEBUG */ - if (mutex->lock) { - PR_Lock(mutex->lock); - } - - return CKR_OK; + if (mutex->lock) { + PR_Lock(mutex->lock); + } + + return CKR_OK; } /* @@ -182,29 +170,27 @@ nssCKFWMutex_Lock * */ NSS_EXTERN CK_RV -nssCKFWMutex_Unlock -( - NSSCKFWMutex *mutex -) +nssCKFWMutex_Unlock( + NSSCKFWMutex *mutex) { - PRStatus nrv; + PRStatus nrv; #ifdef NSSDEBUG - CK_RV rv = nssCKFWMutex_verifyPointer(mutex); + CK_RV rv = nssCKFWMutex_verifyPointer(mutex); - if( CKR_OK != rv ) { - return rv; - } + if (CKR_OK != rv) { + return rv; + } #endif /* NSSDEBUG */ - if (!mutex->lock) - return CKR_OK; + if (!mutex->lock) + return CKR_OK; - nrv = PR_Unlock(mutex->lock); + nrv = PR_Unlock(mutex->lock); - /* if unlock fails, either we have a programming error, or we have - * some sort of hardware failure... in either case return CKR_DEVICE_ERROR. - */ - return nrv == PR_SUCCESS ? CKR_OK : CKR_DEVICE_ERROR; + /* if unlock fails, either we have a programming error, or we have + * some sort of hardware failure... in either case return CKR_DEVICE_ERROR. + */ + return nrv == PR_SUCCESS ? CKR_OK : CKR_DEVICE_ERROR; } /* @@ -212,19 +198,17 @@ nssCKFWMutex_Unlock * */ NSS_EXTERN CK_RV -NSSCKFWMutex_Destroy -( - NSSCKFWMutex *mutex -) +NSSCKFWMutex_Destroy( + NSSCKFWMutex *mutex) { #ifdef DEBUG - CK_RV rv = nssCKFWMutex_verifyPointer(mutex); - if( CKR_OK != rv ) { - return rv; - } + CK_RV rv = nssCKFWMutex_verifyPointer(mutex); + if (CKR_OK != rv) { + return rv; + } #endif /* DEBUG */ - - return nssCKFWMutex_Destroy(mutex); + + return nssCKFWMutex_Destroy(mutex); } /* @@ -232,19 +216,17 @@ NSSCKFWMutex_Destroy * */ NSS_EXTERN CK_RV -NSSCKFWMutex_Lock -( - NSSCKFWMutex *mutex -) +NSSCKFWMutex_Lock( + NSSCKFWMutex *mutex) { #ifdef DEBUG - CK_RV rv = nssCKFWMutex_verifyPointer(mutex); - if( CKR_OK != rv ) { - return rv; - } + CK_RV rv = nssCKFWMutex_verifyPointer(mutex); + if (CKR_OK != rv) { + return rv; + } #endif /* DEBUG */ - - return nssCKFWMutex_Lock(mutex); + + return nssCKFWMutex_Lock(mutex); } /* @@ -252,18 +234,15 @@ NSSCKFWMutex_Lock * */ NSS_EXTERN CK_RV -NSSCKFWMutex_Unlock -( - NSSCKFWMutex *mutex -) +NSSCKFWMutex_Unlock( + NSSCKFWMutex *mutex) { #ifdef DEBUG - CK_RV rv = nssCKFWMutex_verifyPointer(mutex); - if( CKR_OK != rv ) { - return rv; - } + CK_RV rv = nssCKFWMutex_verifyPointer(mutex); + if (CKR_OK != rv) { + return rv; + } #endif /* DEBUG */ - return nssCKFWMutex_Unlock(mutex); + return nssCKFWMutex_Unlock(mutex); } - diff --git a/security/nss/lib/ckfw/nssckfw.h b/security/nss/lib/ckfw/nssckfw.h index 4343eab6ae0e..8807ac85d73a 100644 --- a/security/nss/lib/ckfw/nssckfw.h +++ b/security/nss/lib/ckfw/nssckfw.h @@ -8,7 +8,7 @@ /* * nssckfw.h * - * This file prototypes the publicly available calls of the + * This file prototypes the publicly available calls of the * NSS Cryptoki Framework. */ @@ -40,10 +40,8 @@ */ NSS_EXTERN NSSCKMDInstance * -NSSCKFWInstance_GetMDInstance -( - NSSCKFWInstance *fwInstance -); +NSSCKFWInstance_GetMDInstance( + NSSCKFWInstance *fwInstance); /* * NSSCKFWInstance_GetArena @@ -51,11 +49,9 @@ NSSCKFWInstance_GetMDInstance */ NSS_EXTERN NSSArena * -NSSCKFWInstance_GetArena -( - NSSCKFWInstance *fwInstance, - CK_RV *pError -); +NSSCKFWInstance_GetArena( + NSSCKFWInstance *fwInstance, + CK_RV *pError); /* * NSSCKFWInstance_MayCreatePthreads @@ -63,10 +59,8 @@ NSSCKFWInstance_GetArena */ NSS_EXTERN CK_BBOOL -NSSCKFWInstance_MayCreatePthreads -( - NSSCKFWInstance *fwInstance -); +NSSCKFWInstance_MayCreatePthreads( + NSSCKFWInstance *fwInstance); /* * NSSCKFWInstance_CreateMutex @@ -74,12 +68,10 @@ NSSCKFWInstance_MayCreatePthreads */ NSS_EXTERN NSSCKFWMutex * -NSSCKFWInstance_CreateMutex -( - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -); +NSSCKFWInstance_CreateMutex( + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError); /* * NSSCKFWInstance_GetConfigurationData @@ -87,10 +79,8 @@ NSSCKFWInstance_CreateMutex */ NSS_EXTERN NSSUTF8 * -NSSCKFWInstance_GetConfigurationData -( - NSSCKFWInstance *fwInstance -); +NSSCKFWInstance_GetConfigurationData( + NSSCKFWInstance *fwInstance); /* * NSSCKFWInstance_GetInitArgs @@ -98,10 +88,8 @@ NSSCKFWInstance_GetConfigurationData */ NSS_EXTERN CK_C_INITIALIZE_ARGS_PTR -NSSCKFWInstance_GetInitArgs -( - NSSCKFWInstance *fwInstance -); +NSSCKFWInstance_GetInitArgs( + NSSCKFWInstance *fwInstance); /* * NSSCKFWSlot @@ -118,10 +106,8 @@ NSSCKFWInstance_GetInitArgs */ NSS_EXTERN NSSCKMDSlot * -NSSCKFWSlot_GetMDSlot -( - NSSCKFWSlot *fwSlot -); +NSSCKFWSlot_GetMDSlot( + NSSCKFWSlot *fwSlot); /* * NSSCKFWSlot_GetFWInstance @@ -129,10 +115,8 @@ NSSCKFWSlot_GetMDSlot */ NSS_EXTERN NSSCKFWInstance * -NSSCKFWSlot_GetFWInstance -( - NSSCKFWSlot *fwSlot -); +NSSCKFWSlot_GetFWInstance( + NSSCKFWSlot *fwSlot); /* * NSSCKFWSlot_GetMDInstance @@ -140,10 +124,8 @@ NSSCKFWSlot_GetFWInstance */ NSS_EXTERN NSSCKMDInstance * -NSSCKFWSlot_GetMDInstance -( - NSSCKFWSlot *fwSlot -); +NSSCKFWSlot_GetMDInstance( + NSSCKFWSlot *fwSlot); /* * NSSCKFWToken @@ -161,10 +143,8 @@ NSSCKFWSlot_GetMDInstance */ NSS_EXTERN NSSCKMDToken * -NSSCKFWToken_GetMDToken -( - NSSCKFWToken *fwToken -); +NSSCKFWToken_GetMDToken( + NSSCKFWToken *fwToken); /* * NSSCKFWToken_GetArena @@ -172,11 +152,9 @@ NSSCKFWToken_GetMDToken */ NSS_EXTERN NSSArena * -NSSCKFWToken_GetArena -( - NSSCKFWToken *fwToken, - CK_RV *pError -); +NSSCKFWToken_GetArena( + NSSCKFWToken *fwToken, + CK_RV *pError); /* * NSSCKFWToken_GetFWSlot @@ -184,10 +162,8 @@ NSSCKFWToken_GetArena */ NSS_EXTERN NSSCKFWSlot * -NSSCKFWToken_GetFWSlot -( - NSSCKFWToken *fwToken -); +NSSCKFWToken_GetFWSlot( + NSSCKFWToken *fwToken); /* * NSSCKFWToken_GetMDSlot @@ -195,10 +171,8 @@ NSSCKFWToken_GetFWSlot */ NSS_EXTERN NSSCKMDSlot * -NSSCKFWToken_GetMDSlot -( - NSSCKFWToken *fwToken -); +NSSCKFWToken_GetMDSlot( + NSSCKFWToken *fwToken); /* * NSSCKFWToken_GetSessionState @@ -206,10 +180,8 @@ NSSCKFWToken_GetMDSlot */ NSS_EXTERN CK_STATE -NSSCKFWToken_GetSessionState -( - NSSCKFWToken *fwToken -); +NSSCKFWToken_GetSessionState( + NSSCKFWToken *fwToken); /* * NSSCKFWMechanism @@ -225,10 +197,8 @@ NSSCKFWToken_GetSessionState */ NSS_EXTERN NSSCKMDMechanism * -NSSCKFWMechanism_GetMDMechanism -( - NSSCKFWMechanism *fwMechanism -); +NSSCKFWMechanism_GetMDMechanism( + NSSCKFWMechanism *fwMechanism); /* * NSSCKFWMechanism_GetParameter @@ -236,10 +206,8 @@ NSSCKFWMechanism_GetMDMechanism */ NSS_EXTERN NSSItem * -NSSCKFWMechanism_GetParameter -( - NSSCKFWMechanism *fwMechanism -); +NSSCKFWMechanism_GetParameter( + NSSCKFWMechanism *fwMechanism); /* * NSSCKFWSession @@ -259,10 +227,8 @@ NSSCKFWMechanism_GetParameter */ NSS_EXTERN NSSCKMDSession * -NSSCKFWSession_GetMDSession -( - NSSCKFWSession *fwSession -); +NSSCKFWSession_GetMDSession( + NSSCKFWSession *fwSession); /* * NSSCKFWSession_GetArena @@ -270,11 +236,9 @@ NSSCKFWSession_GetMDSession */ NSS_EXTERN NSSArena * -NSSCKFWSession_GetArena -( - NSSCKFWSession *fwSession, - CK_RV *pError -); +NSSCKFWSession_GetArena( + NSSCKFWSession *fwSession, + CK_RV *pError); /* * NSSCKFWSession_CallNotification @@ -282,11 +246,9 @@ NSSCKFWSession_GetArena */ NSS_EXTERN CK_RV -NSSCKFWSession_CallNotification -( - NSSCKFWSession *fwSession, - CK_NOTIFICATION event -); +NSSCKFWSession_CallNotification( + NSSCKFWSession *fwSession, + CK_NOTIFICATION event); /* * NSSCKFWSession_IsRWSession @@ -294,10 +256,8 @@ NSSCKFWSession_CallNotification */ NSS_EXTERN CK_BBOOL -NSSCKFWSession_IsRWSession -( - NSSCKFWSession *fwSession -); +NSSCKFWSession_IsRWSession( + NSSCKFWSession *fwSession); /* * NSSCKFWSession_IsSO @@ -305,10 +265,8 @@ NSSCKFWSession_IsRWSession */ NSS_EXTERN CK_BBOOL -NSSCKFWSession_IsSO -( - NSSCKFWSession *fwSession -); +NSSCKFWSession_IsSO( + NSSCKFWSession *fwSession); /* * NSSCKFWSession_GetCurrentCryptoOperation @@ -316,11 +274,9 @@ NSSCKFWSession_IsSO */ NSS_EXTERN NSSCKFWCryptoOperation * -NSSCKFWSession_GetCurrentCryptoOperation -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationState state -); +NSSCKFWSession_GetCurrentCryptoOperation( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationState state); /* * NSSCKFWObject @@ -340,91 +296,75 @@ NSSCKFWSession_GetCurrentCryptoOperation * */ NSS_EXTERN NSSCKMDObject * -NSSCKFWObject_GetMDObject -( - NSSCKFWObject *fwObject -); +NSSCKFWObject_GetMDObject( + NSSCKFWObject *fwObject); /* * NSSCKFWObject_GetArena * */ NSS_EXTERN NSSArena * -NSSCKFWObject_GetArena -( - NSSCKFWObject *fwObject, - CK_RV *pError -); +NSSCKFWObject_GetArena( + NSSCKFWObject *fwObject, + CK_RV *pError); /* * NSSCKFWObject_IsTokenObject * */ NSS_EXTERN CK_BBOOL -NSSCKFWObject_IsTokenObject -( - NSSCKFWObject *fwObject -); +NSSCKFWObject_IsTokenObject( + NSSCKFWObject *fwObject); /* * NSSCKFWObject_GetAttributeCount * */ NSS_EXTERN CK_ULONG -NSSCKFWObject_GetAttributeCount -( - NSSCKFWObject *fwObject, - CK_RV *pError -); +NSSCKFWObject_GetAttributeCount( + NSSCKFWObject *fwObject, + CK_RV *pError); /* * NSSCKFWObject_GetAttributeTypes * */ NSS_EXTERN CK_RV -NSSCKFWObject_GetAttributeTypes -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -); +NSSCKFWObject_GetAttributeTypes( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount); /* * NSSCKFWObject_GetAttributeSize * */ NSS_EXTERN CK_ULONG -NSSCKFWObject_GetAttributeSize -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -); +NSSCKFWObject_GetAttributeSize( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError); /* * NSSCKFWObject_GetAttribute * */ NSS_EXTERN NSSItem * -NSSCKFWObject_GetAttribute -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *itemOpt, - NSSArena *arenaOpt, - CK_RV *pError -); +NSSCKFWObject_GetAttribute( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *itemOpt, + NSSArena *arenaOpt, + CK_RV *pError); /* * NSSCKFWObject_GetObjectSize * */ NSS_EXTERN CK_ULONG -NSSCKFWObject_GetObjectSize -( - NSSCKFWObject *fwObject, - CK_RV *pError -); +NSSCKFWObject_GetObjectSize( + NSSCKFWObject *fwObject, + CK_RV *pError); /* * NSSCKFWFindObjects @@ -439,10 +379,8 @@ NSSCKFWObject_GetObjectSize */ NSS_EXTERN NSSCKMDFindObjects * -NSSCKFWFindObjects_GetMDFindObjects -( - NSSCKFWFindObjects * -); +NSSCKFWFindObjects_GetMDFindObjects( + NSSCKFWFindObjects *); /* * NSSCKFWMutex @@ -459,10 +397,8 @@ NSSCKFWFindObjects_GetMDFindObjects */ NSS_EXTERN CK_RV -NSSCKFWMutex_Destroy -( - NSSCKFWMutex *mutex -); +NSSCKFWMutex_Destroy( + NSSCKFWMutex *mutex); /* * NSSCKFWMutex_Lock @@ -470,10 +406,8 @@ NSSCKFWMutex_Destroy */ NSS_EXTERN CK_RV -NSSCKFWMutex_Lock -( - NSSCKFWMutex *mutex -); +NSSCKFWMutex_Lock( + NSSCKFWMutex *mutex); /* * NSSCKFWMutex_Unlock @@ -481,10 +415,7 @@ NSSCKFWMutex_Lock */ NSS_EXTERN CK_RV -NSSCKFWMutex_Unlock -( - NSSCKFWMutex *mutex -); +NSSCKFWMutex_Unlock( + NSSCKFWMutex *mutex); #endif /* NSSCKFW_H */ - diff --git a/security/nss/lib/ckfw/nssckfwc.h b/security/nss/lib/ckfw/nssckfwc.h index 3c11e96c7c95..734a67cf8749 100644 --- a/security/nss/lib/ckfw/nssckfwc.h +++ b/security/nss/lib/ckfw/nssckfwc.h @@ -8,7 +8,7 @@ /* * nssckfwc.h * - * This file prototypes all of the NSS Cryptoki Framework "wrapper" + * This file prototypes all of the NSS Cryptoki Framework "wrapper" * which implement the PKCS#11 API. Technically, these are public * routines (with capital "NSS" prefixes), since they are called * from (generated) code within a Module using the Framework. @@ -104,34 +104,28 @@ * */ NSS_EXTERN CK_RV -NSSCKFWC_Initialize -( - NSSCKFWInstance **pFwInstance, - NSSCKMDInstance *mdInstance, - CK_VOID_PTR pInitArgs -); +NSSCKFWC_Initialize( + NSSCKFWInstance **pFwInstance, + NSSCKMDInstance *mdInstance, + CK_VOID_PTR pInitArgs); /* * NSSCKFWC_Finalize * */ NSS_EXTERN CK_RV -NSSCKFWC_Finalize -( - NSSCKFWInstance **pFwInstance -); +NSSCKFWC_Finalize( + NSSCKFWInstance **pFwInstance); /* * NSSCKFWC_GetInfo * */ NSS_EXTERN CK_RV -NSSCKFWC_GetInfo -( - NSSCKFWInstance *fwInstance, - CK_INFO_PTR pInfo -); - +NSSCKFWC_GetInfo( + NSSCKFWInstance *fwInstance, + CK_INFO_PTR pInfo); + /* * C_GetFunctionList is implemented entirely in the Module's file which * includes the Framework API insert file. It requires no "actual" @@ -143,871 +137,743 @@ NSSCKFWC_GetInfo * */ NSS_EXTERN CK_RV -NSSCKFWC_GetSlotList -( - NSSCKFWInstance *fwInstance, - CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, - CK_ULONG_PTR pulCount -); - +NSSCKFWC_GetSlotList( + NSSCKFWInstance *fwInstance, + CK_BBOOL tokenPresent, + CK_SLOT_ID_PTR pSlotList, + CK_ULONG_PTR pulCount); + /* * NSSCKFWC_GetSlotInfo * */ NSS_EXTERN CK_RV -NSSCKFWC_GetSlotInfo -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_SLOT_INFO_PTR pInfo -); +NSSCKFWC_GetSlotInfo( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_SLOT_INFO_PTR pInfo); /* * NSSCKFWC_GetTokenInfo * */ NSS_EXTERN CK_RV -NSSCKFWC_GetTokenInfo -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_TOKEN_INFO_PTR pInfo -); +NSSCKFWC_GetTokenInfo( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_TOKEN_INFO_PTR pInfo); /* * NSSCKFWC_WaitForSlotEvent * */ NSS_EXTERN CK_RV -NSSCKFWC_WaitForSlotEvent -( - NSSCKFWInstance *fwInstance, - CK_FLAGS flags, - CK_SLOT_ID_PTR pSlot, - CK_VOID_PTR pReserved -); +NSSCKFWC_WaitForSlotEvent( + NSSCKFWInstance *fwInstance, + CK_FLAGS flags, + CK_SLOT_ID_PTR pSlot, + CK_VOID_PTR pReserved); /* * NSSCKFWC_GetMechanismList * */ NSS_EXTERN CK_RV -NSSCKFWC_GetMechanismList -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_MECHANISM_TYPE_PTR pMechanismList, - CK_ULONG_PTR pulCount -); +NSSCKFWC_GetMechanismList( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_MECHANISM_TYPE_PTR pMechanismList, + CK_ULONG_PTR pulCount); /* * NSSCKFWC_GetMechanismInfo * */ NSS_EXTERN CK_RV -NSSCKFWC_GetMechanismInfo -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_MECHANISM_TYPE type, - CK_MECHANISM_INFO_PTR pInfo -); +NSSCKFWC_GetMechanismInfo( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_MECHANISM_TYPE type, + CK_MECHANISM_INFO_PTR pInfo); /* * NSSCKFWC_InitToken * */ NSS_EXTERN CK_RV -NSSCKFWC_InitToken -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_CHAR_PTR pPin, - CK_ULONG ulPinLen, - CK_CHAR_PTR pLabel -); +NSSCKFWC_InitToken( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_CHAR_PTR pPin, + CK_ULONG ulPinLen, + CK_CHAR_PTR pLabel); /* * NSSCKFWC_InitPIN * */ NSS_EXTERN CK_RV -NSSCKFWC_InitPIN -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pPin, - CK_ULONG ulPinLen -); +NSSCKFWC_InitPIN( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_CHAR_PTR pPin, + CK_ULONG ulPinLen); /* * NSSCKFWC_SetPIN * */ NSS_EXTERN CK_RV -NSSCKFWC_SetPIN -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pOldPin, - CK_ULONG ulOldLen, - CK_CHAR_PTR pNewPin, - CK_ULONG ulNewLen -); +NSSCKFWC_SetPIN( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_CHAR_PTR pOldPin, + CK_ULONG ulOldLen, + CK_CHAR_PTR pNewPin, + CK_ULONG ulNewLen); /* * NSSCKFWC_OpenSession * */ NSS_EXTERN CK_RV -NSSCKFWC_OpenSession -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_FLAGS flags, - CK_VOID_PTR pApplication, - CK_NOTIFY Notify, - CK_SESSION_HANDLE_PTR phSession -); +NSSCKFWC_OpenSession( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_FLAGS flags, + CK_VOID_PTR pApplication, + CK_NOTIFY Notify, + CK_SESSION_HANDLE_PTR phSession); /* * NSSCKFWC_CloseSession * */ NSS_EXTERN CK_RV -NSSCKFWC_CloseSession -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -); +NSSCKFWC_CloseSession( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession); /* * NSSCKFWC_CloseAllSessions * */ NSS_EXTERN CK_RV -NSSCKFWC_CloseAllSessions -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID -); +NSSCKFWC_CloseAllSessions( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID); /* * NSSCKFWC_GetSessionInfo * */ NSS_EXTERN CK_RV -NSSCKFWC_GetSessionInfo -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_SESSION_INFO_PTR pInfo -); +NSSCKFWC_GetSessionInfo( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_SESSION_INFO_PTR pInfo); /* * NSSCKFWC_GetOperationState * */ NSS_EXTERN CK_RV -NSSCKFWC_GetOperationState -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, - CK_ULONG_PTR pulOperationStateLen -); +NSSCKFWC_GetOperationState( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, + CK_ULONG_PTR pulOperationStateLen); /* * NSSCKFWC_SetOperationState * */ NSS_EXTERN CK_RV -NSSCKFWC_SetOperationState -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, - CK_ULONG ulOperationStateLen, - CK_OBJECT_HANDLE hEncryptionKey, - CK_OBJECT_HANDLE hAuthenticationKey -); +NSSCKFWC_SetOperationState( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, + CK_ULONG ulOperationStateLen, + CK_OBJECT_HANDLE hEncryptionKey, + CK_OBJECT_HANDLE hAuthenticationKey); /* * NSSCKFWC_Login * */ NSS_EXTERN CK_RV -NSSCKFWC_Login -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_USER_TYPE userType, - CK_CHAR_PTR pPin, - CK_ULONG ulPinLen -); +NSSCKFWC_Login( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_USER_TYPE userType, + CK_CHAR_PTR pPin, + CK_ULONG ulPinLen); /* * NSSCKFWC_Logout * */ NSS_EXTERN CK_RV -NSSCKFWC_Logout -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -); +NSSCKFWC_Logout( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession); /* * NSSCKFWC_CreateObject * */ NSS_EXTERN CK_RV -NSSCKFWC_CreateObject -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject -); +NSSCKFWC_CreateObject( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phObject); /* * NSSCKFWC_CopyObject * */ NSS_EXTERN CK_RV -NSSCKFWC_CopyObject -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phNewObject -); +NSSCKFWC_CopyObject( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phNewObject); /* * NSSCKFWC_DestroyObject * */ NSS_EXTERN CK_RV -NSSCKFWC_DestroyObject -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject -); +NSSCKFWC_DestroyObject( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject); /* * NSSCKFWC_GetObjectSize * */ NSS_EXTERN CK_RV -NSSCKFWC_GetObjectSize -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ULONG_PTR pulSize -); +NSSCKFWC_GetObjectSize( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ULONG_PTR pulSize); /* * NSSCKFWC_GetAttributeValue * */ NSS_EXTERN CK_RV -NSSCKFWC_GetAttributeValue -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount -); - +NSSCKFWC_GetAttributeValue( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount); + /* * NSSCKFWC_SetAttributeValue * */ NSS_EXTERN CK_RV -NSSCKFWC_SetAttributeValue -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount -); +NSSCKFWC_SetAttributeValue( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount); /* * NSSCKFWC_FindObjectsInit * */ NSS_EXTERN CK_RV -NSSCKFWC_FindObjectsInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount -); +NSSCKFWC_FindObjectsInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount); /* * NSSCKFWC_FindObjects * */ NSS_EXTERN CK_RV -NSSCKFWC_FindObjects -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE_PTR phObject, - CK_ULONG ulMaxObjectCount, - CK_ULONG_PTR pulObjectCount -); +NSSCKFWC_FindObjects( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE_PTR phObject, + CK_ULONG ulMaxObjectCount, + CK_ULONG_PTR pulObjectCount); /* * NSSCKFWC_FindObjectsFinal * */ NSS_EXTERN CK_RV -NSSCKFWC_FindObjectsFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -); +NSSCKFWC_FindObjectsFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession); /* * NSSCKFWC_EncryptInit * */ NSS_EXTERN CK_RV -NSSCKFWC_EncryptInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -); +NSSCKFWC_EncryptInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey); /* * NSSCKFWC_Encrypt * */ NSS_EXTERN CK_RV -NSSCKFWC_Encrypt -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pEncryptedData, - CK_ULONG_PTR pulEncryptedDataLen -); +NSSCKFWC_Encrypt( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pEncryptedData, + CK_ULONG_PTR pulEncryptedDataLen); /* * NSSCKFWC_EncryptUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_EncryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen -); +NSSCKFWC_EncryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen); /* * NSSCKFWC_EncryptFinal * */ NSS_EXTERN CK_RV -NSSCKFWC_EncryptFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastEncryptedPart, - CK_ULONG_PTR pulLastEncryptedPartLen -); +NSSCKFWC_EncryptFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastEncryptedPart, + CK_ULONG_PTR pulLastEncryptedPartLen); /* * NSSCKFWC_DecryptInit * */ NSS_EXTERN CK_RV -NSSCKFWC_DecryptInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -); +NSSCKFWC_DecryptInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey); /* * NSSCKFWC_Decrypt * */ NSS_EXTERN CK_RV -NSSCKFWC_Decrypt -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData, - CK_ULONG ulEncryptedDataLen, - CK_BYTE_PTR pData, - CK_ULONG_PTR pulDataLen -); +NSSCKFWC_Decrypt( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedData, + CK_ULONG ulEncryptedDataLen, + CK_BYTE_PTR pData, + CK_ULONG_PTR pulDataLen); /* * NSSCKFWC_DecryptUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_DecryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, - CK_ULONG_PTR pulPartLen -); +NSSCKFWC_DecryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, + CK_ULONG_PTR pulPartLen); /* * NSSCKFWC_DecryptFinal * */ NSS_EXTERN CK_RV -NSSCKFWC_DecryptFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastPart, - CK_ULONG_PTR pulLastPartLen -); +NSSCKFWC_DecryptFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastPart, + CK_ULONG_PTR pulLastPartLen); /* * NSSCKFWC_DigestInit * */ NSS_EXTERN CK_RV -NSSCKFWC_DigestInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism -); +NSSCKFWC_DigestInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism); /* * NSSCKFWC_Digest * */ NSS_EXTERN CK_RV -NSSCKFWC_Digest -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen -); +NSSCKFWC_Digest( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pDigest, + CK_ULONG_PTR pulDigestLen); /* * NSSCKFWC_DigestUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_DigestUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen -); +NSSCKFWC_DigestUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen); /* * NSSCKFWC_DigestKey * */ NSS_EXTERN CK_RV -NSSCKFWC_DigestKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hKey -); +NSSCKFWC_DigestKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hKey); /* * NSSCKFWC_DigestFinal * */ NSS_EXTERN CK_RV -NSSCKFWC_DigestFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen -); +NSSCKFWC_DigestFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pDigest, + CK_ULONG_PTR pulDigestLen); /* * NSSCKFWC_SignInit * */ NSS_EXTERN CK_RV -NSSCKFWC_SignInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -); +NSSCKFWC_SignInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey); /* * NSSCKFWC_Sign * */ NSS_EXTERN CK_RV -NSSCKFWC_Sign -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen -); +NSSCKFWC_Sign( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen); /* * NSSCKFWC_SignUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_SignUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen -); +NSSCKFWC_SignUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen); /* * NSSCKFWC_SignFinal * */ NSS_EXTERN CK_RV -NSSCKFWC_SignFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen -); +NSSCKFWC_SignFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen); /* * NSSCKFWC_SignRecoverInit * */ NSS_EXTERN CK_RV -NSSCKFWC_SignRecoverInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -); +NSSCKFWC_SignRecoverInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey); /* * NSSCKFWC_SignRecover * */ NSS_EXTERN CK_RV -NSSCKFWC_SignRecover -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen -); +NSSCKFWC_SignRecover( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen); /* * NSSCKFWC_VerifyInit * */ NSS_EXTERN CK_RV -NSSCKFWC_VerifyInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -); +NSSCKFWC_VerifyInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey); /* * NSSCKFWC_Verify * */ NSS_EXTERN CK_RV -NSSCKFWC_Verify -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pSignature, - CK_ULONG ulSignatureLen -); +NSSCKFWC_Verify( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pSignature, + CK_ULONG ulSignatureLen); /* * NSSCKFWC_VerifyUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_VerifyUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen -); +NSSCKFWC_VerifyUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen); /* * NSSCKFWC_VerifyFinal * */ NSS_EXTERN CK_RV -NSSCKFWC_VerifyFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature, - CK_ULONG ulSignatureLen -); +NSSCKFWC_VerifyFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, + CK_ULONG ulSignatureLen); /* * NSSCKFWC_VerifyRecoverInit * */ NSS_EXTERN CK_RV -NSSCKFWC_VerifyRecoverInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -); +NSSCKFWC_VerifyRecoverInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey); /* * NSSCKFWC_VerifyRecover * */ NSS_EXTERN CK_RV -NSSCKFWC_VerifyRecover -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature, - CK_ULONG ulSignatureLen, - CK_BYTE_PTR pData, - CK_ULONG_PTR pulDataLen -); +NSSCKFWC_VerifyRecover( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, + CK_ULONG ulSignatureLen, + CK_BYTE_PTR pData, + CK_ULONG_PTR pulDataLen); /* * NSSCKFWC_DigestEncryptUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_DigestEncryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen -); +NSSCKFWC_DigestEncryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen); /* * NSSCKFWC_DecryptDigestUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_DecryptDigestUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, - CK_ULONG_PTR pulPartLen -); +NSSCKFWC_DecryptDigestUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, + CK_ULONG_PTR pulPartLen); /* * NSSCKFWC_SignEncryptUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_SignEncryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen -); +NSSCKFWC_SignEncryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen); /* * NSSCKFWC_DecryptVerifyUpdate * */ NSS_EXTERN CK_RV -NSSCKFWC_DecryptVerifyUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, - CK_ULONG_PTR pulPartLen -); +NSSCKFWC_DecryptVerifyUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, + CK_ULONG_PTR pulPartLen); /* * NSSCKFWC_GenerateKey * */ NSS_EXTERN CK_RV -NSSCKFWC_GenerateKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phKey -); +NSSCKFWC_GenerateKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phKey); /* * NSSCKFWC_GenerateKeyPair * */ NSS_EXTERN CK_RV -NSSCKFWC_GenerateKeyPair -( - NSSCKFWInstance *fwInstance, - 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 -); +NSSCKFWC_GenerateKeyPair( + NSSCKFWInstance *fwInstance, + 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); /* * NSSCKFWC_WrapKey * */ NSS_EXTERN CK_RV -NSSCKFWC_WrapKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hWrappingKey, - CK_OBJECT_HANDLE hKey, - CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pulWrappedKeyLen -); +NSSCKFWC_WrapKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hWrappingKey, + CK_OBJECT_HANDLE hKey, + CK_BYTE_PTR pWrappedKey, + CK_ULONG_PTR pulWrappedKeyLen); /* * NSSCKFWC_UnwrapKey * */ NSS_EXTERN CK_RV -NSSCKFWC_UnwrapKey -( - NSSCKFWInstance *fwInstance, - 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 -); +NSSCKFWC_UnwrapKey( + NSSCKFWInstance *fwInstance, + 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); /* * NSSCKFWC_DeriveKey * */ NSS_EXTERN CK_RV -NSSCKFWC_DeriveKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey -); +NSSCKFWC_DeriveKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hBaseKey, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey); /* * NSSCKFWC_SeedRandom * */ NSS_EXTERN CK_RV -NSSCKFWC_SeedRandom -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSeed, - CK_ULONG ulSeedLen -); +NSSCKFWC_SeedRandom( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSeed, + CK_ULONG ulSeedLen); /* * NSSCKFWC_GenerateRandom * */ NSS_EXTERN CK_RV -NSSCKFWC_GenerateRandom -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pRandomData, - CK_ULONG ulRandomLen -); +NSSCKFWC_GenerateRandom( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pRandomData, + CK_ULONG ulRandomLen); /* * NSSCKFWC_GetFunctionStatus * */ NSS_EXTERN CK_RV -NSSCKFWC_GetFunctionStatus -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -); +NSSCKFWC_GetFunctionStatus( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession); /* * NSSCKFWC_CancelFunction * */ NSS_EXTERN CK_RV -NSSCKFWC_CancelFunction -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -); +NSSCKFWC_CancelFunction( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession); #endif /* NSSCKFWC_H */ diff --git a/security/nss/lib/ckfw/nssckfwt.h b/security/nss/lib/ckfw/nssckfwt.h index 4c4fad2d5c8e..cd015d515360 100644 --- a/security/nss/lib/ckfw/nssckfwt.h +++ b/security/nss/lib/ckfw/nssckfwt.h @@ -51,7 +51,6 @@ typedef struct NSSCKFWMechanismStr NSSCKFWMechanism; struct NSSCKFWCryptoOperationStr; typedef struct NSSCKFWCryptoOperationStr NSSCKFWCryptoOperation; - /* * NSSCKFWSession * @@ -87,7 +86,7 @@ typedef struct NSSCKFWMutexStr NSSCKFWMutex; typedef enum { SingleThreaded, MultiThreaded -} CryptokiLockingState ; +} CryptokiLockingState; /* used as an index into an array, make sure it starts at '0' */ typedef enum { diff --git a/security/nss/lib/ckfw/nssckmdt.h b/security/nss/lib/ckfw/nssckmdt.h index 2c3aa2e2d533..d98f9b02aa05 100644 --- a/security/nss/lib/ckfw/nssckmdt.h +++ b/security/nss/lib/ckfw/nssckmdt.h @@ -44,9 +44,9 @@ typedef struct NSSCKMDObjectStr NSSCKMDObject; */ typedef struct { - PRBool needsFreeing; - NSSItem* item; -} NSSCKFWItem ; + PRBool needsFreeing; + NSSItem *item; +} NSSCKFWItem; /* * NSSCKMDInstance @@ -61,152 +61,147 @@ typedef struct { */ struct NSSCKMDInstanceStr { - /* - * The Module may use this pointer for its own purposes. - */ - void *etc; + /* + * The Module may use this pointer for its own purposes. + */ + void *etc; - /* - * This routine is called by the Framework to initialize - * the Module. This routine is optional; if unimplemented, - * it won't be called. If this routine returns an error, - * then the initialization will fail. - */ - CK_RV (PR_CALLBACK *Initialize)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSUTF8 *configurationData - ); + /* + * This routine is called by the Framework to initialize + * the Module. This routine is optional; if unimplemented, + * it won't be called. If this routine returns an error, + * then the initialization will fail. + */ + CK_RV(PR_CALLBACK *Initialize) + ( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSUTF8 *configurationData); - /* - * This routine is called when the Framework is finalizing - * the PKCS#11 Module. It is the last thing called before - * the NSSCKFWInstance's NSSArena is destroyed. This routine - * is optional; if unimplemented, it merely won't be called. - */ - void (PR_CALLBACK *Finalize)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called when the Framework is finalizing + * the PKCS#11 Module. It is the last thing called before + * the NSSCKFWInstance's NSSArena is destroyed. This routine + * is optional; if unimplemented, it merely won't be called. + */ + void(PR_CALLBACK *Finalize)( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* + /* * This routine gets the number of slots. This value must - * never change, once the instance is initialized. This + * never change, once the instance is initialized. This * routine must be implemented. It may return zero on error. */ - CK_ULONG (PR_CALLBACK *GetNSlots)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + CK_ULONG(PR_CALLBACK *GetNSlots) + ( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns the version of the Cryptoki standard - * to which this Module conforms. This routine is optional; - * if unimplemented, the Framework uses the version to which - * ~it~ was implemented. - */ - CK_VERSION (PR_CALLBACK *GetCryptokiVersion)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the version of the Cryptoki standard + * to which this Module conforms. This routine is optional; + * if unimplemented, the Framework uses the version to which + * ~it~ was implemented. + */ + CK_VERSION(PR_CALLBACK *GetCryptokiVersion) + ( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing the manufacturer ID for this Module. Only - * the characters completely encoded in the first thirty- - * two bytes are significant. This routine is optional. - * The string returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetManufacturerID)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing the manufacturer ID for this Module. Only + * the characters completely encoded in the first thirty- + * two bytes are significant. This routine is optional. + * The string returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetManufacturerID)( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing a description of this Module library. Only - * the characters completely encoded in the first thirty- - * two bytes are significant. This routine is optional. - * The string returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetLibraryDescription)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing a description of this Module library. Only + * the characters completely encoded in the first thirty- + * two bytes are significant. This routine is optional. + * The string returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetLibraryDescription)( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns the version of this Module library. - * This routine is optional; if unimplemented, the Framework - * will assume a Module library version of 0.1. - */ - CK_VERSION (PR_CALLBACK *GetLibraryVersion)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the version of this Module library. + * This routine is optional; if unimplemented, the Framework + * will assume a Module library version of 0.1. + */ + CK_VERSION(PR_CALLBACK *GetLibraryVersion) + ( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if the Module wishes to - * handle session objects. This routine is optional. - * If this routine is NULL, or if it exists but returns - * CK_FALSE, the Framework will assume responsibility - * for managing session objects. - */ - CK_BBOOL (PR_CALLBACK *ModuleHandlesSessionObjects)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if the Module wishes to + * handle session objects. This routine is optional. + * If this routine is NULL, or if it exists but returns + * CK_FALSE, the Framework will assume responsibility + * for managing session objects. + */ + CK_BBOOL(PR_CALLBACK *ModuleHandlesSessionObjects) + ( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine stuffs pointers to NSSCKMDSlot objects into - * the specified array; one for each slot supported by this - * instance. The Framework will determine the size needed - * for the array by calling GetNSlots. This routine is - * required. - */ - CK_RV (PR_CALLBACK *GetSlots)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDSlot *slots[] - ); + /* + * This routine stuffs pointers to NSSCKMDSlot objects into + * the specified array; one for each slot supported by this + * instance. The Framework will determine the size needed + * for the array by calling GetNSlots. This routine is + * required. + */ + CK_RV(PR_CALLBACK *GetSlots) + ( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDSlot *slots[]); - /* - * This call returns a pointer to the slot in which an event - * has occurred. If the block argument is CK_TRUE, the call - * should block until a slot event occurs; if CK_FALSE, it - * should check to see if an event has occurred, occurred, - * but return NULL (and set *pError to CK_NO_EVENT) if one - * hasn't. This routine is optional; if unimplemented, the - * Framework will assume that no event has happened. This - * routine may return NULL upon error. - */ - NSSCKMDSlot *(PR_CALLBACK *WaitForSlotEvent)( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_BBOOL block, - CK_RV *pError - ); + /* + * This call returns a pointer to the slot in which an event + * has occurred. If the block argument is CK_TRUE, the call + * should block until a slot event occurs; if CK_FALSE, it + * should check to see if an event has occurred, occurred, + * but return NULL (and set *pError to CK_NO_EVENT) if one + * hasn't. This routine is optional; if unimplemented, the + * Framework will assume that no event has happened. This + * routine may return NULL upon error. + */ + NSSCKMDSlot *(PR_CALLBACK *WaitForSlotEvent)( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_BBOOL block, + CK_RV *pError); - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; - /* * NSSCKMDSlot * @@ -220,165 +215,161 @@ struct NSSCKMDInstanceStr { */ struct NSSCKMDSlotStr { - /* - * The Module may use this pointer for its own purposes. - */ - void *etc; + /* + * The Module may use this pointer for its own purposes. + */ + void *etc; - /* - * This routine is called during the Framework initialization - * step, after the Framework Instance has obtained the list - * of slots (by calling NSSCKMDInstance->GetSlots). Any slot- - * specific initialization can be done here. This routine is - * optional; if unimplemented, it won't be called. Note that - * if this routine returns an error, the entire Framework - * initialization for this Module will fail. - */ - CK_RV (PR_CALLBACK *Initialize)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called during the Framework initialization + * step, after the Framework Instance has obtained the list + * of slots (by calling NSSCKMDInstance->GetSlots). Any slot- + * specific initialization can be done here. This routine is + * optional; if unimplemented, it won't be called. Note that + * if this routine returns an error, the entire Framework + * initialization for this Module will fail. + */ + CK_RV(PR_CALLBACK *Initialize) + ( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine is called when the Framework is finalizing - * the PKCS#11 Module. This call (for each of the slots) - * is the last thing called before NSSCKMDInstance->Finalize. - * This routine is optional; if unimplemented, it merely - * won't be called. Note: In the rare circumstance that - * the Framework initialization cannot complete (due to, - * for example, memory limitations), this can be called with - * a NULL value for fwSlot. - */ - void (PR_CALLBACK *Destroy)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called when the Framework is finalizing + * the PKCS#11 Module. This call (for each of the slots) + * is the last thing called before NSSCKMDInstance->Finalize. + * This routine is optional; if unimplemented, it merely + * won't be called. Note: In the rare circumstance that + * the Framework initialization cannot complete (due to, + * for example, memory limitations), this can be called with + * a NULL value for fwSlot. + */ + void(PR_CALLBACK *Destroy)( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing a description of this slot. Only the characters - * completely encoded in the first sixty-four bytes are - * significant. This routine is optional. The string - * returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetSlotDescription)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing a description of this slot. Only the characters + * completely encoded in the first sixty-four bytes are + * significant. This routine is optional. The string + * returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetSlotDescription)( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing a description of the manufacturer of this slot. - * Only the characters completely encoded in the first thirty- - * two bytes are significant. This routine is optional. - * The string returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetManufacturerID)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing a description of the manufacturer of this slot. + * Only the characters completely encoded in the first thirty- + * two bytes are significant. This routine is optional. + * The string returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetManufacturerID)( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns CK_TRUE if a token is present in this - * slot. This routine is optional; if unimplemented, CK_TRUE - * is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetTokenPresent)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if a token is present in this + * slot. This routine is optional; if unimplemented, CK_TRUE + * is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetTokenPresent) + ( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if the slot supports removable - * tokens. This routine is optional; if unimplemented, CK_FALSE - * is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetRemovableDevice)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if the slot supports removable + * tokens. This routine is optional; if unimplemented, CK_FALSE + * is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetRemovableDevice) + ( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if this slot is a hardware - * device, or CK_FALSE if this slot is a software device. This - * routine is optional; if unimplemented, CK_FALSE is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetHardwareSlot)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if this slot is a hardware + * device, or CK_FALSE if this slot is a software device. This + * routine is optional; if unimplemented, CK_FALSE is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetHardwareSlot) + ( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the version of this slot's hardware. - * This routine is optional; if unimplemented, the Framework - * will assume a hardware version of 0.1. - */ - CK_VERSION (PR_CALLBACK *GetHardwareVersion)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the version of this slot's hardware. + * This routine is optional; if unimplemented, the Framework + * will assume a hardware version of 0.1. + */ + CK_VERSION(PR_CALLBACK *GetHardwareVersion) + ( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the version of this slot's firmware. - * This routine is optional; if unimplemented, the Framework - * will assume a hardware version of 0.1. - */ - CK_VERSION (PR_CALLBACK *GetFirmwareVersion)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the version of this slot's firmware. + * This routine is optional; if unimplemented, the Framework + * will assume a hardware version of 0.1. + */ + CK_VERSION(PR_CALLBACK *GetFirmwareVersion) + ( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine should return a pointer to an NSSCKMDToken - * object corresponding to the token in the specified slot. - * The NSSCKFWToken object passed in has an NSSArena - * available which is dedicated for this token. This routine - * must be implemented. This routine may return NULL upon - * error. - */ - NSSCKMDToken *(PR_CALLBACK *GetToken)( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine should return a pointer to an NSSCKMDToken + * object corresponding to the token in the specified slot. + * The NSSCKFWToken object passed in has an NSSArena + * available which is dedicated for this token. This routine + * must be implemented. This routine may return NULL upon + * error. + */ + NSSCKMDToken *(PR_CALLBACK *GetToken)( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; /* @@ -394,444 +385,437 @@ struct NSSCKMDSlotStr { */ struct NSSCKMDTokenStr { - /* - * The Module may use this pointer for its own purposes. - */ - void *etc; + /* + * The Module may use this pointer for its own purposes. + */ + void *etc; - /* - * This routine is used to prepare a Module token object for - * use. It is called after the NSSCKMDToken object is obtained - * from NSSCKMDSlot->GetToken. It is named "Setup" here because - * Cryptoki already defines "InitToken" to do the process of - * wiping out any existing state on a token and preparing it for - * a new use. This routine is optional; if unimplemented, it - * merely won't be called. - */ - CK_RV (PR_CALLBACK *Setup)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is used to prepare a Module token object for + * use. It is called after the NSSCKMDToken object is obtained + * from NSSCKMDSlot->GetToken. It is named "Setup" here because + * Cryptoki already defines "InitToken" to do the process of + * wiping out any existing state on a token and preparing it for + * a new use. This routine is optional; if unimplemented, it + * merely won't be called. + */ + CK_RV(PR_CALLBACK *Setup) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine is called by the Framework whenever it notices - * that the token object is invalid. (Typically this is when a - * routine indicates an error such as CKR_DEVICE_REMOVED). This - * call is the last thing called before the NSSArena in the - * corresponding NSSCKFWToken is destroyed. This routine is - * optional; if unimplemented, it merely won't be called. - */ - void (PR_CALLBACK *Invalidate)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called by the Framework whenever it notices + * that the token object is invalid. (Typically this is when a + * routine indicates an error such as CKR_DEVICE_REMOVED). This + * call is the last thing called before the NSSArena in the + * corresponding NSSCKFWToken is destroyed. This routine is + * optional; if unimplemented, it merely won't be called. + */ + void(PR_CALLBACK *Invalidate)( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine initialises the token in the specified slot. - * This routine is optional; if unimplemented, the Framework - * will fail this operation with an error of CKR_DEVICE_ERROR. - */ + /* + * This routine initialises the token in the specified slot. + * This routine is optional; if unimplemented, the Framework + * will fail this operation with an error of CKR_DEVICE_ERROR. + */ - CK_RV (PR_CALLBACK *InitToken)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *pin, - NSSUTF8 *label - ); + CK_RV(PR_CALLBACK *InitToken) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *pin, + NSSUTF8 *label); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing this token's label. Only the characters - * completely encoded in the first thirty-two bytes are - * significant. This routine is optional. The string - * returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetLabel)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing this token's label. Only the characters + * completely encoded in the first thirty-two bytes are + * significant. This routine is optional. The string + * returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetLabel)( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing this token's manufacturer ID. Only the characters - * completely encoded in the first thirty-two bytes are - * significant. This routine is optional. The string - * returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetManufacturerID)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing this token's manufacturer ID. Only the characters + * completely encoded in the first thirty-two bytes are + * significant. This routine is optional. The string + * returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetManufacturerID)( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing this token's model name. Only the characters - * completely encoded in the first thirty-two bytes are - * significant. This routine is optional. The string - * returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetModel)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing this token's model name. Only the characters + * completely encoded in the first thirty-two bytes are + * significant. This routine is optional. The string + * returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetModel)( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns a pointer to a UTF8-encoded string - * containing this token's serial number. Only the characters - * completely encoded in the first thirty-two bytes are - * significant. This routine is optional. The string - * returned is never freed; if dynamically generated, - * the space for it should be allocated from the NSSArena - * that may be obtained from the NSSCKFWInstance. This - * routine may return NULL upon error; however if *pError - * is CKR_OK, the NULL will be considered the valid response. - */ - NSSUTF8 *(PR_CALLBACK *GetSerialNumber)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns a pointer to a UTF8-encoded string + * containing this token's serial number. Only the characters + * completely encoded in the first thirty-two bytes are + * significant. This routine is optional. The string + * returned is never freed; if dynamically generated, + * the space for it should be allocated from the NSSArena + * that may be obtained from the NSSCKFWInstance. This + * routine may return NULL upon error; however if *pError + * is CKR_OK, the NULL will be considered the valid response. + */ + NSSUTF8 *(PR_CALLBACK *GetSerialNumber)( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns CK_TRUE if the token has its own - * random number generator. This routine is optional; if - * unimplemented, CK_FALSE is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetHasRNG)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if the token has its own + * random number generator. This routine is optional; if + * unimplemented, CK_FALSE is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetHasRNG) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if this token is write-protected. - * This routine is optional; if unimplemented, CK_FALSE is - * assumed. - */ - CK_BBOOL (PR_CALLBACK *GetIsWriteProtected)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if this token is write-protected. + * This routine is optional; if unimplemented, CK_FALSE is + * assumed. + */ + CK_BBOOL(PR_CALLBACK *GetIsWriteProtected) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if this token requires a login. - * This routine is optional; if unimplemented, CK_FALSE is - * assumed. - */ - CK_BBOOL (PR_CALLBACK *GetLoginRequired)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if this token requires a login. + * This routine is optional; if unimplemented, CK_FALSE is + * assumed. + */ + CK_BBOOL(PR_CALLBACK *GetLoginRequired) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if the normal user's PIN on this - * token has been initialised. This routine is optional; if - * unimplemented, CK_FALSE is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetUserPinInitialized)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if the normal user's PIN on this + * token has been initialised. This routine is optional; if + * unimplemented, CK_FALSE is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetUserPinInitialized) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if a successful save of a - * session's cryptographic operations state ~always~ contains - * all keys needed to restore the state of the session. This - * routine is optional; if unimplemented, CK_FALSE is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetRestoreKeyNotNeeded)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if a successful save of a + * session's cryptographic operations state ~always~ contains + * all keys needed to restore the state of the session. This + * routine is optional; if unimplemented, CK_FALSE is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetRestoreKeyNotNeeded) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if the token has its own - * hardware clock. This routine is optional; if unimplemented, - * CK_FALSE is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetHasClockOnToken)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if the token has its own + * hardware clock. This routine is optional; if unimplemented, + * CK_FALSE is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetHasClockOnToken) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if the token has a protected - * authentication path. This routine is optional; if - * unimplemented, CK_FALSE is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetHasProtectedAuthenticationPath)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if the token has a protected + * authentication path. This routine is optional; if + * unimplemented, CK_FALSE is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetHasProtectedAuthenticationPath) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns CK_TRUE if the token supports dual - * cryptographic operations within a single session. This - * routine is optional; if unimplemented, CK_FALSE is assumed. - */ - CK_BBOOL (PR_CALLBACK *GetSupportsDualCryptoOperations)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns CK_TRUE if the token supports dual + * cryptographic operations within a single session. This + * routine is optional; if unimplemented, CK_FALSE is assumed. + */ + CK_BBOOL(PR_CALLBACK *GetSupportsDualCryptoOperations) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * XXX fgmr-- should we have a call to return all the flags - * at once, for folks who already know about Cryptoki? - */ + /* + * XXX fgmr-- should we have a call to return all the flags + * at once, for folks who already know about Cryptoki? + */ - /* - * This routine returns the maximum number of sessions that - * may be opened on this token. This routine is optional; - * if unimplemented, the special value CK_UNAVAILABLE_INFORMATION - * is assumed. XXX fgmr-- or CK_EFFECTIVELY_INFINITE? - */ - CK_ULONG (PR_CALLBACK *GetMaxSessionCount)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the maximum number of sessions that + * may be opened on this token. This routine is optional; + * if unimplemented, the special value CK_UNAVAILABLE_INFORMATION + * is assumed. XXX fgmr-- or CK_EFFECTIVELY_INFINITE? + */ + CK_ULONG(PR_CALLBACK *GetMaxSessionCount) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the maximum number of read/write - * sesisons that may be opened on this token. This routine - * is optional; if unimplemented, the special value - * CK_UNAVAILABLE_INFORMATION is assumed. XXX fgmr-- or - * CK_EFFECTIVELY_INFINITE? - */ - CK_ULONG (PR_CALLBACK *GetMaxRwSessionCount)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the maximum number of read/write + * sesisons that may be opened on this token. This routine + * is optional; if unimplemented, the special value + * CK_UNAVAILABLE_INFORMATION is assumed. XXX fgmr-- or + * CK_EFFECTIVELY_INFINITE? + */ + CK_ULONG(PR_CALLBACK *GetMaxRwSessionCount) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the maximum PIN code length that is - * supported on this token. This routine is optional; - * if unimplemented, the special value CK_UNAVAILABLE_INFORMATION - * is assumed. - */ - CK_ULONG (PR_CALLBACK *GetMaxPinLen)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the maximum PIN code length that is + * supported on this token. This routine is optional; + * if unimplemented, the special value CK_UNAVAILABLE_INFORMATION + * is assumed. + */ + CK_ULONG(PR_CALLBACK *GetMaxPinLen) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the minimum PIN code length that is - * supported on this token. This routine is optional; if - * unimplemented, the special value CK_UNAVAILABLE_INFORMATION - * is assumed. XXX fgmr-- or 0? - */ - CK_ULONG (PR_CALLBACK *GetMinPinLen)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the minimum PIN code length that is + * supported on this token. This routine is optional; if + * unimplemented, the special value CK_UNAVAILABLE_INFORMATION + * is assumed. XXX fgmr-- or 0? + */ + CK_ULONG(PR_CALLBACK *GetMinPinLen) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the total amount of memory on the token - * in which public objects may be stored. This routine is - * optional; if unimplemented, the special value - * CK_UNAVAILABLE_INFORMATION is assumed. - */ - CK_ULONG (PR_CALLBACK *GetTotalPublicMemory)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the total amount of memory on the token + * in which public objects may be stored. This routine is + * optional; if unimplemented, the special value + * CK_UNAVAILABLE_INFORMATION is assumed. + */ + CK_ULONG(PR_CALLBACK *GetTotalPublicMemory) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the amount of unused memory on the - * token in which public objects may be stored. This routine - * is optional; if unimplemented, the special value - * CK_UNAVAILABLE_INFORMATION is assumed. - */ - CK_ULONG (PR_CALLBACK *GetFreePublicMemory)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the amount of unused memory on the + * token in which public objects may be stored. This routine + * is optional; if unimplemented, the special value + * CK_UNAVAILABLE_INFORMATION is assumed. + */ + CK_ULONG(PR_CALLBACK *GetFreePublicMemory) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the total amount of memory on the token - * in which private objects may be stored. This routine is - * optional; if unimplemented, the special value - * CK_UNAVAILABLE_INFORMATION is assumed. - */ - CK_ULONG (PR_CALLBACK *GetTotalPrivateMemory)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the total amount of memory on the token + * in which private objects may be stored. This routine is + * optional; if unimplemented, the special value + * CK_UNAVAILABLE_INFORMATION is assumed. + */ + CK_ULONG(PR_CALLBACK *GetTotalPrivateMemory) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the amount of unused memory on the - * token in which private objects may be stored. This routine - * is optional; if unimplemented, the special value - * CK_UNAVAILABLE_INFORMATION is assumed. - */ - CK_ULONG (PR_CALLBACK *GetFreePrivateMemory)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the amount of unused memory on the + * token in which private objects may be stored. This routine + * is optional; if unimplemented, the special value + * CK_UNAVAILABLE_INFORMATION is assumed. + */ + CK_ULONG(PR_CALLBACK *GetFreePrivateMemory) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the version number of this token's - * hardware. This routine is optional; if unimplemented, - * the value 0.1 is assumed. - */ - CK_VERSION (PR_CALLBACK *GetHardwareVersion)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the version number of this token's + * hardware. This routine is optional; if unimplemented, + * the value 0.1 is assumed. + */ + CK_VERSION(PR_CALLBACK *GetHardwareVersion) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the version number of this token's - * firmware. This routine is optional; if unimplemented, - * the value 0.1 is assumed. - */ - CK_VERSION (PR_CALLBACK *GetFirmwareVersion)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the version number of this token's + * firmware. This routine is optional; if unimplemented, + * the value 0.1 is assumed. + */ + CK_VERSION(PR_CALLBACK *GetFirmwareVersion) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine stuffs the current UTC time, as obtained from - * the token, into the sixteen-byte buffer in the form - * YYYYMMDDhhmmss00. This routine need only be implemented - * by token which indicate that they have a real-time clock. - * XXX fgmr-- think about time formats. - */ - CK_RV (PR_CALLBACK *GetUTCTime)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_CHAR utcTime[16] - ); + /* + * This routine stuffs the current UTC time, as obtained from + * the token, into the sixteen-byte buffer in the form + * YYYYMMDDhhmmss00. This routine need only be implemented + * by token which indicate that they have a real-time clock. + * XXX fgmr-- think about time formats. + */ + CK_RV(PR_CALLBACK *GetUTCTime) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_CHAR utcTime[16]); - /* - * This routine creates a session on the token, and returns - * the corresponding NSSCKMDSession object. The value of - * rw will be CK_TRUE if the session is to be a read/write - * session, or CK_FALSE otherwise. An NSSArena dedicated to - * the new session is available from the specified NSSCKFWSession. - * This routine may return NULL upon error. - */ - NSSCKMDSession *(PR_CALLBACK *OpenSession)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession, - CK_BBOOL rw, - CK_RV *pError - ); + /* + * This routine creates a session on the token, and returns + * the corresponding NSSCKMDSession object. The value of + * rw will be CK_TRUE if the session is to be a read/write + * session, or CK_FALSE otherwise. An NSSArena dedicated to + * the new session is available from the specified NSSCKFWSession. + * This routine may return NULL upon error. + */ + NSSCKMDSession *(PR_CALLBACK *OpenSession)( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession, + CK_BBOOL rw, + CK_RV *pError); - /* - * This routine returns the number of PKCS#11 Mechanisms - * supported by this token. This routine is optional; if - * unimplemented, zero is assumed. - */ - CK_ULONG (PR_CALLBACK *GetMechanismCount)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine returns the number of PKCS#11 Mechanisms + * supported by this token. This routine is optional; if + * unimplemented, zero is assumed. + */ + CK_ULONG(PR_CALLBACK *GetMechanismCount) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine stuffs into the specified array the types - * of the mechanisms supported by this token. The Framework - * determines the size of the array by calling GetMechanismCount. - */ - CK_RV (PR_CALLBACK *GetMechanismTypes)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_MECHANISM_TYPE types[] - ); + /* + * This routine stuffs into the specified array the types + * of the mechanisms supported by this token. The Framework + * determines the size of the array by calling GetMechanismCount. + */ + CK_RV(PR_CALLBACK *GetMechanismTypes) + ( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_MECHANISM_TYPE types[]); - /* - * This routine returns a pointer to a Module mechanism - * object corresponding to a specified type. This routine - * need only exist for tokens implementing at least one - * mechanism. - */ - NSSCKMDMechanism *(PR_CALLBACK *GetMechanism)( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_MECHANISM_TYPE which, - CK_RV *pError - ); + /* + * This routine returns a pointer to a Module mechanism + * object corresponding to a specified type. This routine + * need only exist for tokens implementing at least one + * mechanism. + */ + NSSCKMDMechanism *(PR_CALLBACK *GetMechanism)( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_MECHANISM_TYPE which, + CK_RV *pError); - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; /* @@ -847,279 +831,275 @@ struct NSSCKMDTokenStr { */ struct NSSCKMDSessionStr { - /* - * The Module may use this pointer for its own purposes. - */ - void *etc; + /* + * The Module may use this pointer for its own purposes. + */ + void *etc; - /* - * This routine is called by the Framework when a session is - * closed. This call is the last thing called before the - * NSSArena in the correspoinding NSSCKFWSession is destroyed. - * This routine is optional; if unimplemented, it merely won't - * be called. - */ - void (PR_CALLBACK *Close)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called by the Framework when a session is + * closed. This call is the last thing called before the + * NSSArena in the correspoinding NSSCKFWSession is destroyed. + * This routine is optional; if unimplemented, it merely won't + * be called. + */ + void(PR_CALLBACK *Close)( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine is used to get any device-specific error. - * This routine is optional. - */ - CK_ULONG (PR_CALLBACK *GetDeviceError)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is used to get any device-specific error. + * This routine is optional. + */ + CK_ULONG(PR_CALLBACK *GetDeviceError) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine is used to log in a user to the token. This - * routine is optional, since the Framework's NSSCKFWSession - * object keeps track of the login state. - */ - CK_RV (PR_CALLBACK *Login)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_USER_TYPE userType, - NSSItem *pin, - CK_STATE oldState, - CK_STATE newState - ); + /* + * This routine is used to log in a user to the token. This + * routine is optional, since the Framework's NSSCKFWSession + * object keeps track of the login state. + */ + CK_RV(PR_CALLBACK *Login) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_USER_TYPE userType, + NSSItem *pin, + CK_STATE oldState, + CK_STATE newState); - /* - * This routine is used to log out a user from the token. This - * routine is optional, since the Framework's NSSCKFWSession - * object keeps track of the login state. - */ - CK_RV (PR_CALLBACK *Logout)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_STATE oldState, - CK_STATE newState - ); + /* + * This routine is used to log out a user from the token. This + * routine is optional, since the Framework's NSSCKFWSession + * object keeps track of the login state. + */ + CK_RV(PR_CALLBACK *Logout) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_STATE oldState, + CK_STATE newState); - /* - * This routine is used to initialize the normal user's PIN or - * password. This will only be called in the "read/write - * security officer functions" state. If this token has a - * protected authentication path, then the pin argument will - * be NULL. This routine is optional; if unimplemented, the - * Framework will return the error CKR_TOKEN_WRITE_PROTECTED. - */ - CK_RV (PR_CALLBACK *InitPIN)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *pin - ); + /* + * This routine is used to initialize the normal user's PIN or + * password. This will only be called in the "read/write + * security officer functions" state. If this token has a + * protected authentication path, then the pin argument will + * be NULL. This routine is optional; if unimplemented, the + * Framework will return the error CKR_TOKEN_WRITE_PROTECTED. + */ + CK_RV(PR_CALLBACK *InitPIN) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *pin); - /* - * This routine is used to modify a user's PIN or password. This - * routine will only be called in the "read/write security officer - * functions" or "read/write user functions" state. If this token - * has a protected authentication path, then the pin arguments - * will be NULL. This routine is optional; if unimplemented, the - * Framework will return the error CKR_TOKEN_WRITE_PROTECTED. - */ - CK_RV (PR_CALLBACK *SetPIN)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *oldPin, - NSSItem *newPin - ); + /* + * This routine is used to modify a user's PIN or password. This + * routine will only be called in the "read/write security officer + * functions" or "read/write user functions" state. If this token + * has a protected authentication path, then the pin arguments + * will be NULL. This routine is optional; if unimplemented, the + * Framework will return the error CKR_TOKEN_WRITE_PROTECTED. + */ + CK_RV(PR_CALLBACK *SetPIN) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *oldPin, + NSSItem *newPin); - /* - * This routine is used to find out how much space would be required - * to save the current operational state. This routine is optional; - * if unimplemented, the Framework will reject any attempts to save - * the operational state with the error CKR_STATE_UNSAVEABLE. This - * routine may return zero on error. - */ - CK_ULONG (PR_CALLBACK *GetOperationStateLen)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine is used to find out how much space would be required + * to save the current operational state. This routine is optional; + * if unimplemented, the Framework will reject any attempts to save + * the operational state with the error CKR_STATE_UNSAVEABLE. This + * routine may return zero on error. + */ + CK_ULONG(PR_CALLBACK *GetOperationStateLen) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine is used to store the current operational state. This - * routine is only required if GetOperationStateLen is implemented - * and can return a nonzero value. The buffer in the specified item - * will be pre-allocated, and the length will specify the amount of - * space available (which may be more than GetOperationStateLen - * asked for, but which will not be smaller). - */ - CK_RV (PR_CALLBACK *GetOperationState)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *buffer - ); + /* + * This routine is used to store the current operational state. This + * routine is only required if GetOperationStateLen is implemented + * and can return a nonzero value. The buffer in the specified item + * will be pre-allocated, and the length will specify the amount of + * space available (which may be more than GetOperationStateLen + * asked for, but which will not be smaller). + */ + CK_RV(PR_CALLBACK *GetOperationState) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *buffer); - /* - * This routine is used to restore an operational state previously - * obtained with GetOperationState. The Framework will take pains - * to be sure that the state is (or was at one point) valid; if the - * Module notices that the state is invalid, it should return an - * error, but it is not required to be paranoid about the issue. - * [XXX fgmr-- should (can?) the framework verify the keys match up?] - * This routine is required only if GetOperationState is implemented. - */ - CK_RV (PR_CALLBACK *SetOperationState)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *state, - NSSCKMDObject *mdEncryptionKey, - NSSCKFWObject *fwEncryptionKey, - NSSCKMDObject *mdAuthenticationKey, - NSSCKFWObject *fwAuthenticationKey - ); + /* + * This routine is used to restore an operational state previously + * obtained with GetOperationState. The Framework will take pains + * to be sure that the state is (or was at one point) valid; if the + * Module notices that the state is invalid, it should return an + * error, but it is not required to be paranoid about the issue. + * [XXX fgmr-- should (can?) the framework verify the keys match up?] + * This routine is required only if GetOperationState is implemented. + */ + CK_RV(PR_CALLBACK *SetOperationState) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *state, + NSSCKMDObject *mdEncryptionKey, + NSSCKFWObject *fwEncryptionKey, + NSSCKMDObject *mdAuthenticationKey, + NSSCKFWObject *fwAuthenticationKey); - /* - * This routine is used to create an object. The specified template - * will only specify a session object if the Module has indicated - * that it wishes to handle its own session objects. This routine - * is optional; if unimplemented, the Framework will reject the - * operation with the error CKR_TOKEN_WRITE_PROTECTED. Space for - * token objects should come from the NSSArena available from the - * NSSCKFWToken object; space for session objects (if supported) - * should come from the NSSArena available from the NSSCKFWSession - * object. The appropriate NSSArena pointer will, as a convenience, - * be passed as the handyArenaPointer argument. This routine may - * return NULL upon error. - */ - NSSCKMDObject *(PR_CALLBACK *CreateObject)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *handyArenaPointer, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError - ); + /* + * This routine is used to create an object. The specified template + * will only specify a session object if the Module has indicated + * that it wishes to handle its own session objects. This routine + * is optional; if unimplemented, the Framework will reject the + * operation with the error CKR_TOKEN_WRITE_PROTECTED. Space for + * token objects should come from the NSSArena available from the + * NSSCKFWToken object; space for session objects (if supported) + * should come from the NSSArena available from the NSSCKFWSession + * object. The appropriate NSSArena pointer will, as a convenience, + * be passed as the handyArenaPointer argument. This routine may + * return NULL upon error. + */ + NSSCKMDObject *(PR_CALLBACK *CreateObject)( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *handyArenaPointer, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); - /* - * This routine is used to make a copy of an object. It is entirely - * optional; if unimplemented, the Framework will try to use - * CreateObject instead. If the Module has indicated that it does - * not wish to handle session objects, then this routine will only - * be called to copy a token object to another token object. - * Otherwise, either the original object or the new may be of - * either the token or session variety. As with CreateObject, the - * handyArenaPointer will point to the appropriate arena for the - * new object. This routine may return NULL upon error. - */ - NSSCKMDObject *(PR_CALLBACK *CopyObject)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdOldObject, - NSSCKFWObject *fwOldObject, - NSSArena *handyArenaPointer, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError - ); + /* + * This routine is used to make a copy of an object. It is entirely + * optional; if unimplemented, the Framework will try to use + * CreateObject instead. If the Module has indicated that it does + * not wish to handle session objects, then this routine will only + * be called to copy a token object to another token object. + * Otherwise, either the original object or the new may be of + * either the token or session variety. As with CreateObject, the + * handyArenaPointer will point to the appropriate arena for the + * new object. This routine may return NULL upon error. + */ + NSSCKMDObject *(PR_CALLBACK *CopyObject)( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdOldObject, + NSSCKFWObject *fwOldObject, + NSSArena *handyArenaPointer, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); - /* - * This routine is used to begin an object search. This routine may - * be unimplemented only if the Module does not handle session - * objects, and if none of its tokens have token objects. The - * NSSCKFWFindObjects pointer has an NSSArena that may be used for - * storage for the life of this "find" operation. This routine may - * return NULL upon error. If the Module can determine immediately - * that the search will not find any matching objects, it may return - * NULL, and specify CKR_OK as the error. - */ - NSSCKMDFindObjects *(PR_CALLBACK *FindObjectsInit)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError - ); + /* + * This routine is used to begin an object search. This routine may + * be unimplemented only if the Module does not handle session + * objects, and if none of its tokens have token objects. The + * NSSCKFWFindObjects pointer has an NSSArena that may be used for + * storage for the life of this "find" operation. This routine may + * return NULL upon error. If the Module can determine immediately + * that the search will not find any matching objects, it may return + * NULL, and specify CKR_OK as the error. + */ + NSSCKMDFindObjects *(PR_CALLBACK *FindObjectsInit)( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); - /* - * This routine seeds the random-number generator. It is - * optional, even if GetRandom is implemented. If unimplemented, - * the Framework will issue the error CKR_RANDOM_SEED_NOT_SUPPORTED. - */ - CK_RV (PR_CALLBACK *SeedRandom)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *seed - ); + /* + * This routine seeds the random-number generator. It is + * optional, even if GetRandom is implemented. If unimplemented, + * the Framework will issue the error CKR_RANDOM_SEED_NOT_SUPPORTED. + */ + CK_RV(PR_CALLBACK *SeedRandom) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *seed); - /* - * This routine gets random data. It is optional. If unimplemented, - * the Framework will issue the error CKR_RANDOM_NO_RNG. - */ - CK_RV (PR_CALLBACK *GetRandom)( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *buffer - ); + /* + * This routine gets random data. It is optional. If unimplemented, + * the Framework will issue the error CKR_RANDOM_NO_RNG. + */ + CK_RV(PR_CALLBACK *GetRandom) + ( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *buffer); - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; /* @@ -1135,54 +1115,52 @@ struct NSSCKMDSessionStr { */ struct NSSCKMDFindObjectsStr { - /* - * The Module may use this pointer for its own purposes. - */ - void *etc; + /* + * The Module may use this pointer for its own purposes. + */ + void *etc; - /* - * This routine is called by the Framework to finish a - * search operation. Note that the Framework may finish - * a search before it has completed. This routine is - * optional; if unimplemented, it merely won't be called. - */ - void (PR_CALLBACK *Final)( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called by the Framework to finish a + * search operation. Note that the Framework may finish + * a search before it has completed. This routine is + * optional; if unimplemented, it merely won't be called. + */ + void(PR_CALLBACK *Final)( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine is used to obtain another pointer to an - * object matching the search criteria. This routine is - * required. If no (more) objects match the search, it - * should return NULL and set the error to CKR_OK. - */ - NSSCKMDObject *(PR_CALLBACK *Next)( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError - ); + /* + * This routine is used to obtain another pointer to an + * object matching the search criteria. This routine is + * required. If no (more) objects match the search, it + * should return NULL and set the error to CKR_OK. + */ + NSSCKMDObject *(PR_CALLBACK *Next)( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError); - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; /* @@ -1199,182 +1177,179 @@ struct NSSCKMDFindObjectsStr { */ struct NSSCKMDCryptoOperationStr { - /* - * The Module may use this pointer for its own purposes. - */ - void *etc; + /* + * The Module may use this pointer for its own purposes. + */ + void *etc; - /* - * This routine is called by the Framework clean up the mdCryptoOperation - * structure. - * This routine is optional; if unimplemented, it will be ignored. - */ - void (PR_CALLBACK *Destroy)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called by the Framework clean up the mdCryptoOperation + * structure. + * This routine is optional; if unimplemented, it will be ignored. + */ + void(PR_CALLBACK *Destroy)( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); + /* + * how many bytes do we need to finish this buffer? + * must be implemented if Final is implemented. + */ + CK_ULONG(PR_CALLBACK *GetFinalLength) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * how many bytes do we need to finish this buffer? - * must be implemented if Final is implemented. - */ - CK_ULONG (PR_CALLBACK *GetFinalLength)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * how many bytes do we need to complete the next operation. + * used in both Update and UpdateFinal. + */ + CK_ULONG(PR_CALLBACK *GetOperationLength) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *inputBuffer, + CK_RV *pError); - /* - * how many bytes do we need to complete the next operation. - * used in both Update and UpdateFinal. - */ - CK_ULONG (PR_CALLBACK *GetOperationLength)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *inputBuffer, - CK_RV *pError - ); + /* + * This routine is called by the Framework to finish a + * search operation. Note that the Framework may finish + * a search before it has completed. This routine is + * optional; if unimplemented, it merely won't be called. + * The respective final call with fail with CKR_FUNCTION_FAILED + * Final should not free the mdCryptoOperation. + */ + CK_RV(PR_CALLBACK *Final) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSItem *outputBuffer); - /* - * This routine is called by the Framework to finish a - * search operation. Note that the Framework may finish - * a search before it has completed. This routine is - * optional; if unimplemented, it merely won't be called. - * The respective final call with fail with CKR_FUNCTION_FAILED - * Final should not free the mdCryptoOperation. - */ - CK_RV(PR_CALLBACK *Final)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSItem *outputBuffer - ); + /* + * This routine is called by the Framework to complete the + * next step in an encryption/decryption operation. + * This routine is optional; if unimplemented, the respective + * update call with fail with CKR_FUNCTION_FAILED. + * Update should not be implemented for signing/verification/digest + * mechanisms. + */ + CK_RV(PR_CALLBACK *Update) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *inputBuffer, + NSSItem *outputBuffer); + /* + * This routine is called by the Framework to complete the + * next step in a signing/verification/digest operation. + * This routine is optional; if unimplemented, the respective + * update call with fail with CKR_FUNCTION_FAILED + * Update should not be implemented for encryption/decryption + * mechanisms. + */ + CK_RV(PR_CALLBACK *DigestUpdate) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *inputBuffer); - /* - * This routine is called by the Framework to complete the - * next step in an encryption/decryption operation. - * This routine is optional; if unimplemented, the respective - * update call with fail with CKR_FUNCTION_FAILED. - * Update should not be implemented for signing/verification/digest - * mechanisms. - */ - CK_RV(PR_CALLBACK *Update)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *inputBuffer, - NSSItem *outputBuffer - ); + /* + * This routine is called by the Framework to complete a + * single step operation. This routine is optional; if unimplemented, + * the framework will use the Update and Final functions to complete + * the operation. + */ + CK_RV(PR_CALLBACK *UpdateFinal) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *inputBuffer, + NSSItem *outputBuffer); - /* - * This routine is called by the Framework to complete the - * next step in a signing/verification/digest operation. - * This routine is optional; if unimplemented, the respective - * update call with fail with CKR_FUNCTION_FAILED - * Update should not be implemented for encryption/decryption - * mechanisms. - */ - CK_RV(PR_CALLBACK *DigestUpdate)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *inputBuffer - ); + /* + * This routine is called by the Framework to complete next + * step in a combined operation. The Decrypt/Encrypt mechanism + * should define and drive the combo step. + * This routine is optional; if unimplemented, + * the framework will use the appropriate Update functions to complete + * the operation. + */ + CK_RV(PR_CALLBACK *UpdateCombo) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDCryptoOperation *mdPeerCryptoOperation, + NSSCKFWCryptoOperation *fwPeerCryptoOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *inputBuffer, + NSSItem *outputBuffer); - /* - * This routine is called by the Framework to complete a - * single step operation. This routine is optional; if unimplemented, - * the framework will use the Update and Final functions to complete - * the operation. - */ - CK_RV(PR_CALLBACK *UpdateFinal)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *inputBuffer, - NSSItem *outputBuffer - ); + /* + * Hash a key directly into the digest + */ + CK_RV(PR_CALLBACK *DigestKey) + ( + NSSCKMDCryptoOperation *mdCryptoOperation, + NSSCKFWCryptoOperation *fwCryptoOperation, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey); - /* - * This routine is called by the Framework to complete next - * step in a combined operation. The Decrypt/Encrypt mechanism - * should define and drive the combo step. - * This routine is optional; if unimplemented, - * the framework will use the appropriate Update functions to complete - * the operation. - */ - CK_RV(PR_CALLBACK *UpdateCombo)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDCryptoOperation *mdPeerCryptoOperation, - NSSCKFWCryptoOperation *fwPeerCryptoOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *inputBuffer, - NSSItem *outputBuffer - ); - - /* - * Hash a key directly into the digest - */ - CK_RV(PR_CALLBACK *DigestKey)( - NSSCKMDCryptoOperation *mdCryptoOperation, - NSSCKFWCryptoOperation *fwCryptoOperation, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey - ); - - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; /* @@ -1383,365 +1358,352 @@ struct NSSCKMDCryptoOperationStr { */ struct NSSCKMDMechanismStr { - /* - * The Module may use this pointer for its own purposes. - */ - void *etc; + /* + * The Module may use this pointer for its own purposes. + */ + void *etc; - /* - * This also frees the fwMechanism if appropriate. - * If it is not supplied, the Framework will assume that the Token - * Manages a static list of mechanisms and the function will not be called. - */ - void (PR_CALLBACK *Destroy)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This also frees the fwMechanism if appropriate. + * If it is not supplied, the Framework will assume that the Token + * Manages a static list of mechanisms and the function will not be called. + */ + void(PR_CALLBACK *Destroy)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); + /* + * This routine returns the minimum key size allowed for + * this mechanism. This routine is optional; if unimplemented, + * zero will be assumed. This routine may return zero on + * error; if the error is CKR_OK, zero will be accepted as + * a valid response. + */ + CK_ULONG(PR_CALLBACK *GetMinKeySize) + ( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns the minimum key size allowed for - * this mechanism. This routine is optional; if unimplemented, - * zero will be assumed. This routine may return zero on - * error; if the error is CKR_OK, zero will be accepted as - * a valid response. - */ - CK_ULONG (PR_CALLBACK *GetMinKeySize)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns the maximum key size allowed for + * this mechanism. This routine is optional; if unimplemented, + * zero will be assumed. This routine may return zero on + * error; if the error is CKR_OK, zero will be accepted as + * a valid response. + */ + CK_ULONG(PR_CALLBACK *GetMaxKeySize) + ( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine returns the maximum key size allowed for - * this mechanism. This routine is optional; if unimplemented, - * zero will be assumed. This routine may return zero on - * error; if the error is CKR_OK, zero will be accepted as - * a valid response. - */ - CK_ULONG (PR_CALLBACK *GetMaxKeySize)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine is called to determine if the mechanism is + * implemented in hardware or software. It returns CK_TRUE + * if it is done in hardware. + */ + CK_BBOOL(PR_CALLBACK *GetInHardware) + ( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine is called to determine if the mechanism is - * implemented in hardware or software. It returns CK_TRUE - * if it is done in hardware. - */ - CK_BBOOL (PR_CALLBACK *GetInHardware)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * The crypto routines themselves. Most crypto operations may + * be performed in two ways, streaming and single-part. The + * streaming operations involve the use of (typically) three + * calls-- an Init method to set up the operation, an Update + * method to feed data to the operation, and a Final method to + * obtain the final result. Single-part operations involve + * one method, to perform the crypto operation all at once. + * + * The NSS Cryptoki Framework can implement the single-part + * operations in terms of the streaming operations on behalf + * of the Module. There are a few variances. + * + * Only the Init Functions are defined by the mechanism. Each + * init function will return a NSSCKFWCryptoOperation which + * can supply update, final, the single part updateFinal, and + * the combo updateCombo functions. + * + * For simplicity, the routines are listed in summary here: + * + * EncryptInit, + * DecryptInit, + * DigestInit, + * SignInit, + * SignRecoverInit; + * VerifyInit, + * VerifyRecoverInit; + * + * The key-management routines are + * + * GenerateKey + * GenerateKeyPair + * WrapKey + * UnwrapKey + * DeriveKey + * + * All of these routines based on the Cryptoki API; + * see PKCS#11 for further information. + */ - /* - * The crypto routines themselves. Most crypto operations may - * be performed in two ways, streaming and single-part. The - * streaming operations involve the use of (typically) three - * calls-- an Init method to set up the operation, an Update - * method to feed data to the operation, and a Final method to - * obtain the final result. Single-part operations involve - * one method, to perform the crypto operation all at once. - * - * The NSS Cryptoki Framework can implement the single-part - * operations in terms of the streaming operations on behalf - * of the Module. There are a few variances. - * - * Only the Init Functions are defined by the mechanism. Each - * init function will return a NSSCKFWCryptoOperation which - * can supply update, final, the single part updateFinal, and - * the combo updateCombo functions. - * - * For simplicity, the routines are listed in summary here: - * - * EncryptInit, - * DecryptInit, - * DigestInit, - * SignInit, - * SignRecoverInit; - * VerifyInit, - * VerifyRecoverInit; - * - * The key-management routines are - * - * GenerateKey - * GenerateKeyPair - * WrapKey - * UnwrapKey - * DeriveKey - * - * All of these routines based on the Cryptoki API; - * see PKCS#11 for further information. - */ + /* + */ + NSSCKMDCryptoOperation *(PR_CALLBACK *EncryptInit)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError); - /* - */ - NSSCKMDCryptoOperation * (PR_CALLBACK *EncryptInit)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError - ); + /* + */ + NSSCKMDCryptoOperation *(PR_CALLBACK *DecryptInit)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError); - /* - */ - NSSCKMDCryptoOperation * (PR_CALLBACK *DecryptInit)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError - ); + /* + */ + NSSCKMDCryptoOperation *(PR_CALLBACK *DigestInit)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - */ - NSSCKMDCryptoOperation * (PR_CALLBACK *DigestInit)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + */ + NSSCKMDCryptoOperation *(PR_CALLBACK *SignInit)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError); + /* + */ + NSSCKMDCryptoOperation *(PR_CALLBACK *VerifyInit)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError); - /* - */ - NSSCKMDCryptoOperation * (PR_CALLBACK *SignInit)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError - ); + /* + */ + NSSCKMDCryptoOperation *(PR_CALLBACK *SignRecoverInit)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError); - /* - */ - NSSCKMDCryptoOperation * (PR_CALLBACK *VerifyInit)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError - ); + /* + */ + NSSCKMDCryptoOperation *(PR_CALLBACK *VerifyRecoverInit)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError); - /* - */ - NSSCKMDCryptoOperation * (PR_CALLBACK *SignRecoverInit)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError - ); + /* + * Key management operations. + */ - /* - */ - NSSCKMDCryptoOperation * (PR_CALLBACK *VerifyRecoverInit)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError - ); + /* + * This routine generates a key. This routine may return NULL + * upon error. + */ + NSSCKMDObject *(PR_CALLBACK *GenerateKey)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); - /* - * Key management operations. - */ + /* + * This routine generates a key pair. + */ + CK_RV(PR_CALLBACK *GenerateKeyPair) + ( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG ulPublicKeyAttributeCount, + CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG ulPrivateKeyAttributeCount, + NSSCKMDObject **pPublicKey, + NSSCKMDObject **pPrivateKey); - /* - * This routine generates a key. This routine may return NULL - * upon error. - */ - NSSCKMDObject *(PR_CALLBACK *GenerateKey)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError - ); + /* + * This routine wraps a key. + */ + CK_ULONG(PR_CALLBACK *GetWrapKeyLength) + ( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdWrappingKey, + NSSCKFWObject *fwWrappingKey, + NSSCKMDObject *mdWrappedKey, + NSSCKFWObject *fwWrappedKey, + CK_RV *pError); - /* - * This routine generates a key pair. - */ - CK_RV (PR_CALLBACK *GenerateKeyPair)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG ulPublicKeyAttributeCount, - CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG ulPrivateKeyAttributeCount, - NSSCKMDObject **pPublicKey, - NSSCKMDObject **pPrivateKey - ); + /* + * This routine wraps a key. + */ + CK_RV(PR_CALLBACK *WrapKey) + ( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdWrappingKey, + NSSCKFWObject *fwWrappingKey, + NSSCKMDObject *mdKeyObject, + NSSCKFWObject *fwKeyObject, + NSSItem *wrappedKey); - /* - * This routine wraps a key. - */ - CK_ULONG (PR_CALLBACK *GetWrapKeyLength)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdWrappingKey, - NSSCKFWObject *fwWrappingKey, - NSSCKMDObject *mdWrappedKey, - NSSCKFWObject *fwWrappedKey, - CK_RV *pError - ); + /* + * This routine unwraps a key. This routine may return NULL + * upon error. + */ + NSSCKMDObject *(PR_CALLBACK *UnwrapKey)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdWrappingKey, + NSSCKFWObject *fwWrappingKey, + NSSItem *wrappedKey, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); - /* - * This routine wraps a key. - */ - CK_RV (PR_CALLBACK *WrapKey)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdWrappingKey, - NSSCKFWObject *fwWrappingKey, - NSSCKMDObject *mdKeyObject, - NSSCKFWObject *fwKeyObject, - NSSItem *wrappedKey - ); + /* + * This routine derives a key. This routine may return NULL + * upon error. + */ + NSSCKMDObject *(PR_CALLBACK *DeriveKey)( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM_PTR pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdBaseKey, + NSSCKFWObject *fwBaseKey, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); - /* - * This routine unwraps a key. This routine may return NULL - * upon error. - */ - NSSCKMDObject *(PR_CALLBACK *UnwrapKey)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdWrappingKey, - NSSCKFWObject *fwWrappingKey, - NSSItem *wrappedKey, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError - ); - - /* - * This routine derives a key. This routine may return NULL - * upon error. - */ - NSSCKMDObject *(PR_CALLBACK *DeriveKey)( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM_PTR pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdBaseKey, - NSSCKFWObject *fwBaseKey, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError - ); - - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; /* @@ -1756,190 +1718,187 @@ struct NSSCKMDMechanismStr { */ struct NSSCKMDObjectStr { - /* - * The implementation my use this pointer for its own purposes. - */ - void *etc; + /* + * The implementation my use this pointer for its own purposes. + */ + void *etc; - /* - * This routine is called by the Framework when it is letting - * go of an object handle. It can be used by the Module to - * free any resources tied up by an object "in use." It is - * optional. - */ - void (PR_CALLBACK *Finalize)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is called by the Framework when it is letting + * go of an object handle. It can be used by the Module to + * free any resources tied up by an object "in use." It is + * optional. + */ + void(PR_CALLBACK *Finalize)( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine is used to completely destroy an object. - * It is optional. The parameter fwObject might be NULL - * if the framework runs out of memory at the wrong moment. - */ - CK_RV (PR_CALLBACK *Destroy)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This routine is used to completely destroy an object. + * It is optional. The parameter fwObject might be NULL + * if the framework runs out of memory at the wrong moment. + */ + CK_RV(PR_CALLBACK *Destroy) + ( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This helper routine is used by the Framework, and is especially - * useful when it is managing session objects on behalf of the - * Module. This routine is optional; if unimplemented, the - * Framework will actually look up the CKA_TOKEN attribute. In the - * event of an error, just make something up-- the Framework will - * find out soon enough anyway. - */ - CK_BBOOL (PR_CALLBACK *IsTokenObject)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance - ); + /* + * This helper routine is used by the Framework, and is especially + * useful when it is managing session objects on behalf of the + * Module. This routine is optional; if unimplemented, the + * Framework will actually look up the CKA_TOKEN attribute. In the + * event of an error, just make something up-- the Framework will + * find out soon enough anyway. + */ + CK_BBOOL(PR_CALLBACK *IsTokenObject) + ( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); - /* - * This routine returns the number of attributes of which this - * object consists. It is mandatory. It can return zero on - * error. - */ - CK_ULONG (PR_CALLBACK *GetAttributeCount)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns the number of attributes of which this + * object consists. It is mandatory. It can return zero on + * error. + */ + CK_ULONG(PR_CALLBACK *GetAttributeCount) + ( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This routine stuffs the attribute types into the provided array. - * The array size (as obtained from GetAttributeCount) is passed in - * as a check; return CKR_BUFFER_TOO_SMALL if the count is wrong - * (either too big or too small). - */ - CK_RV (PR_CALLBACK *GetAttributeTypes)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount - ); + /* + * This routine stuffs the attribute types into the provided array. + * The array size (as obtained from GetAttributeCount) is passed in + * as a check; return CKR_BUFFER_TOO_SMALL if the count is wrong + * (either too big or too small). + */ + CK_RV(PR_CALLBACK *GetAttributeTypes) + ( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount); - /* - * This routine returns the size (in bytes) of the specified - * attribute. It can return zero on error. - */ - CK_ULONG (PR_CALLBACK *GetAttributeSize)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError - ); + /* + * This routine returns the size (in bytes) of the specified + * attribute. It can return zero on error. + */ + CK_ULONG(PR_CALLBACK *GetAttributeSize) + ( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError); - /* - * This routine returns an NSSCKFWItem structure. - * The item pointer points to an NSSItem containing the attribute value. - * The needsFreeing bit tells the framework whether to call the - * FreeAttribute function . Upon error, an NSSCKFWItem structure - * with a NULL NSSItem item pointer will be returned - */ - NSSCKFWItem (PR_CALLBACK *GetAttribute)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError - ); + /* + * This routine returns an NSSCKFWItem structure. + * The item pointer points to an NSSItem containing the attribute value. + * The needsFreeing bit tells the framework whether to call the + * FreeAttribute function . Upon error, an NSSCKFWItem structure + * with a NULL NSSItem item pointer will be returned + */ + NSSCKFWItem(PR_CALLBACK *GetAttribute)( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError); - /* - * This routine returns CKR_OK if the attribute could be freed. - */ - CK_RV (PR_CALLBACK *FreeAttribute)( - NSSCKFWItem * item - ); + /* + * This routine returns CKR_OK if the attribute could be freed. + */ + CK_RV(PR_CALLBACK *FreeAttribute) + ( + NSSCKFWItem *item); - /* - * This routine changes the specified attribute. If unimplemented, - * the object will be considered read-only. - */ - CK_RV (PR_CALLBACK *SetAttribute)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value - ); + /* + * This routine changes the specified attribute. If unimplemented, + * the object will be considered read-only. + */ + CK_RV(PR_CALLBACK *SetAttribute) + ( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value); - /* - * This routine returns the storage requirements of this object, - * in bytes. Cryptoki doesn't strictly define the definition, - * but it should relate to the values returned by the "Get Memory" - * routines of the NSSCKMDToken. This routine is optional; if - * unimplemented, the Framework will consider this information - * sensitive. This routine may return zero on error. If the - * specified error is CKR_OK, zero will be accepted as a valid - * response. - */ - CK_ULONG (PR_CALLBACK *GetObjectSize)( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError - ); + /* + * This routine returns the storage requirements of this object, + * in bytes. Cryptoki doesn't strictly define the definition, + * but it should relate to the values returned by the "Get Memory" + * routines of the NSSCKMDToken. This routine is optional; if + * unimplemented, the Framework will consider this information + * sensitive. This routine may return zero on error. If the + * specified error is CKR_OK, zero will be accepted as a valid + * response. + */ + CK_ULONG(PR_CALLBACK *GetObjectSize) + ( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); - /* - * This object may be extended in future versions of the - * NSS Cryptoki Framework. To allow for some flexibility - * in the area of binary compatibility, this field should - * be NULL. - */ - void *null; + /* + * This object may be extended in future versions of the + * NSS Cryptoki Framework. To allow for some flexibility + * in the area of binary compatibility, this field should + * be NULL. + */ + void *null; }; - #endif /* NSSCKMDT_H */ diff --git a/security/nss/lib/ckfw/nssckt.h b/security/nss/lib/ckfw/nssckt.h index 5ed534c2532f..b50a88f7b394 100644 --- a/security/nss/lib/ckfw/nssckt.h +++ b/security/nss/lib/ckfw/nssckt.h @@ -10,4 +10,3 @@ typedef CK_ATTRIBUTE_TYPE CK_PTR CK_ATTRIBUTE_TYPE_PTR; #define CK_ENTRY #endif /* _NSSCKT_H_ */ - diff --git a/security/nss/lib/ckfw/nssmkey/ckmk.h b/security/nss/lib/ckfw/nssmkey/ckmk.h index 9d8202f6ab31..4f3ab82d7224 100644 --- a/security/nss/lib/ckfw/nssmkey/ckmk.h +++ b/security/nss/lib/ckfw/nssmkey/ckmk.h @@ -36,9 +36,9 @@ * to this PKCS #11 module. */ struct ckmkRawObjectStr { - CK_ULONG n; - const CK_ATTRIBUTE_TYPE *types; - const NSSItem *items; + CK_ULONG n; + const CK_ATTRIBUTE_TYPE *types; + const NSSItem *items; }; typedef struct ckmkRawObjectStr ckmkRawObject; @@ -46,40 +46,40 @@ typedef struct ckmkRawObjectStr ckmkRawObject; * Key/Cert Items */ struct ckmkItemObjectStr { - SecKeychainItemRef itemRef; - SecItemClass itemClass; - PRBool hasID; - NSSItem modify; - NSSItem private; - NSSItem encrypt; - NSSItem decrypt; - NSSItem derive; - NSSItem sign; - NSSItem signRecover; - NSSItem verify; - NSSItem verifyRecover; - NSSItem wrap; - NSSItem unwrap; - NSSItem label; - NSSItem subject; - NSSItem issuer; - NSSItem serial; - NSSItem derCert; - NSSItem id; - NSSItem modulus; - NSSItem exponent; - NSSItem privateExponent; - NSSItem prime1; - NSSItem prime2; - NSSItem exponent1; - NSSItem exponent2; - NSSItem coefficient; + SecKeychainItemRef itemRef; + SecItemClass itemClass; + PRBool hasID; + NSSItem modify; + NSSItem private; + NSSItem encrypt; + NSSItem decrypt; + NSSItem derive; + NSSItem sign; + NSSItem signRecover; + NSSItem verify; + NSSItem verifyRecover; + NSSItem wrap; + NSSItem unwrap; + NSSItem label; + NSSItem subject; + NSSItem issuer; + NSSItem serial; + NSSItem derCert; + NSSItem id; + NSSItem modulus; + NSSItem exponent; + NSSItem privateExponent; + NSSItem prime1; + NSSItem prime2; + NSSItem exponent1; + NSSItem exponent2; + NSSItem coefficient; }; typedef struct ckmkItemObjectStr ckmkItemObject; typedef enum { - ckmkRaw, - ckmkItem, + ckmkRaw, + ckmkItem, } ckmkObjectType; /* @@ -87,112 +87,96 @@ typedef enum { * cfind as ckmkInternalObjects. */ struct ckmkInternalObjectStr { - ckmkObjectType type; - union { - ckmkRawObject raw; - ckmkItemObject item; - } u; - CK_OBJECT_CLASS objClass; - NSSItem hashKey; - unsigned char hashKeyData[128]; - NSSCKMDObject mdObject; + ckmkObjectType type; + union { + ckmkRawObject raw; + ckmkItemObject item; + } u; + CK_OBJECT_CLASS objClass; + NSSItem hashKey; + unsigned char hashKeyData[128]; + NSSCKMDObject mdObject; }; typedef struct ckmkInternalObjectStr ckmkInternalObject; /* our raw object data array */ NSS_EXTERN_DATA ckmkInternalObject nss_ckmk_data[]; -NSS_EXTERN_DATA const PRUint32 nss_ckmk_nObjects; +NSS_EXTERN_DATA const PRUint32 nss_ckmk_nObjects; -NSS_EXTERN_DATA const CK_VERSION nss_ckmk_CryptokiVersion; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckmk_ManufacturerID; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckmk_LibraryDescription; -NSS_EXTERN_DATA const CK_VERSION nss_ckmk_LibraryVersion; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckmk_SlotDescription; -NSS_EXTERN_DATA const CK_VERSION nss_ckmk_HardwareVersion; -NSS_EXTERN_DATA const CK_VERSION nss_ckmk_FirmwareVersion; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckmk_TokenLabel; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckmk_TokenModel; -NSS_EXTERN_DATA const NSSUTF8 * nss_ckmk_TokenSerialNumber; +NSS_EXTERN_DATA const CK_VERSION nss_ckmk_CryptokiVersion; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckmk_ManufacturerID; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckmk_LibraryDescription; +NSS_EXTERN_DATA const CK_VERSION nss_ckmk_LibraryVersion; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckmk_SlotDescription; +NSS_EXTERN_DATA const CK_VERSION nss_ckmk_HardwareVersion; +NSS_EXTERN_DATA const CK_VERSION nss_ckmk_FirmwareVersion; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckmk_TokenLabel; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckmk_TokenModel; +NSS_EXTERN_DATA const NSSUTF8 *nss_ckmk_TokenSerialNumber; -NSS_EXTERN_DATA const NSSCKMDInstance nss_ckmk_mdInstance; -NSS_EXTERN_DATA const NSSCKMDSlot nss_ckmk_mdSlot; -NSS_EXTERN_DATA const NSSCKMDToken nss_ckmk_mdToken; +NSS_EXTERN_DATA const NSSCKMDInstance nss_ckmk_mdInstance; +NSS_EXTERN_DATA const NSSCKMDSlot nss_ckmk_mdSlot; +NSS_EXTERN_DATA const NSSCKMDToken nss_ckmk_mdToken; NSS_EXTERN_DATA const NSSCKMDMechanism nss_ckmk_mdMechanismRSA; NSS_EXTERN NSSCKMDSession * -nss_ckmk_CreateSession -( - NSSCKFWSession *fwSession, - CK_RV *pError -); +nss_ckmk_CreateSession( + NSSCKFWSession *fwSession, + CK_RV *pError); NSS_EXTERN NSSCKMDFindObjects * -nss_ckmk_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nss_ckmk_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); /* * Object Utilities */ NSS_EXTERN NSSCKMDObject * -nss_ckmk_CreateMDObject -( - NSSArena *arena, - ckmkInternalObject *io, - CK_RV *pError -); +nss_ckmk_CreateMDObject( + NSSArena *arena, + ckmkInternalObject *io, + CK_RV *pError); NSS_EXTERN NSSCKMDObject * -nss_ckmk_CreateObject -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -); +nss_ckmk_CreateObject( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError); NSS_EXTERN const NSSItem * -nss_ckmk_FetchAttribute -( - ckmkInternalObject *io, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError -); +nss_ckmk_FetchAttribute( + ckmkInternalObject *io, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError); NSS_EXTERN void -nss_ckmk_DestroyInternalObject -( - ckmkInternalObject *io -); +nss_ckmk_DestroyInternalObject( + ckmkInternalObject *io); unsigned char * -nss_ckmk_DERUnwrap -( - unsigned char *src, - int size, - int *outSize, - unsigned char **next -); +nss_ckmk_DERUnwrap( + unsigned char *src, + int size, + int *outSize, + unsigned char **next); CK_ULONG -nss_ckmk_GetULongAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - CK_RV *pError -); +nss_ckmk_GetULongAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + CK_RV *pError); -#define NSS_CKMK_ARRAY_SIZE(x) ((sizeof (x))/(sizeof ((x)[0]))) +#define NSS_CKMK_ARRAY_SIZE(x) ((sizeof(x)) / (sizeof((x)[0]))) #ifdef DEBUG -#define CKMK_MACERR(str,err) cssmPerror(str,err) +#define CKMK_MACERR(str, err) cssmPerror(str, err) #else -#define CKMK_MACERR(str,err) +#define CKMK_MACERR(str, err) #endif - + #endif diff --git a/security/nss/lib/ckfw/nssmkey/ckmkver.c b/security/nss/lib/ckfw/nssmkey/ckmkver.c index 0f6897634e00..2b99f1e22807 100644 --- a/security/nss/lib/ckfw/nssmkey/ckmkver.c +++ b/security/nss/lib/ckfw/nssmkey/ckmkver.c @@ -14,5 +14,4 @@ /* * Version information */ -const char __nss_ckmk_version[] = "Version: NSS Access to the MAC OS X Key Ring " - NSS_CKMK_LIBRARY_VERSION _DEBUG_STRING; +const char __nss_ckmk_version[] = "Version: NSS Access to the MAC OS X Key Ring " NSS_CKMK_LIBRARY_VERSION _DEBUG_STRING; diff --git a/security/nss/lib/ckfw/nssmkey/manchor.c b/security/nss/lib/ckfw/nssmkey/manchor.c index 1b4d70bcd33d..6261eff951bd 100644 --- a/security/nss/lib/ckfw/nssmkey/manchor.c +++ b/security/nss/lib/ckfw/nssmkey/manchor.c @@ -6,12 +6,12 @@ * nssmkey/manchor.c * * This file "anchors" the actual cryptoki entry points in this module's - * shared library, which is required for dynamic loading. See the + * shared library, which is required for dynamic loading. See the * comments in nssck.api for more information. */ #include "ckmk.h" #define MODULE_NAME ckmk -#define INSTANCE_NAME (NSSCKMDInstance *)&nss_ckmk_mdInstance +#define INSTANCE_NAME (NSSCKMDInstance *) & nss_ckmk_mdInstance #include "nssck.api" diff --git a/security/nss/lib/ckfw/nssmkey/mconstants.c b/security/nss/lib/ckfw/nssmkey/mconstants.c index 89df4f25a561..c26298ada374 100644 --- a/security/nss/lib/ckfw/nssmkey/mconstants.c +++ b/security/nss/lib/ckfw/nssmkey/mconstants.c @@ -19,40 +19,43 @@ #include "nssmkey.h" NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckmk_CryptokiVersion = { - NSS_CKMK_CRYPTOKI_VERSION_MAJOR, - NSS_CKMK_CRYPTOKI_VERSION_MINOR }; + nss_ckmk_CryptokiVersion = { + NSS_CKMK_CRYPTOKI_VERSION_MAJOR, + NSS_CKMK_CRYPTOKI_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckmk_ManufacturerID = (NSSUTF8 *) "Mozilla Foundation"; + nss_ckmk_ManufacturerID = (NSSUTF8 *)"Mozilla Foundation"; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckmk_LibraryDescription = (NSSUTF8 *) "NSS Access to Mac OS X Key Ring"; + nss_ckmk_LibraryDescription = (NSSUTF8 *)"NSS Access to Mac OS X Key Ring"; NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckmk_LibraryVersion = { - NSS_CKMK_LIBRARY_VERSION_MAJOR, - NSS_CKMK_LIBRARY_VERSION_MINOR}; + nss_ckmk_LibraryVersion = { + NSS_CKMK_LIBRARY_VERSION_MAJOR, + NSS_CKMK_LIBRARY_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckmk_SlotDescription = (NSSUTF8 *) "Mac OS X Key Ring"; + nss_ckmk_SlotDescription = (NSSUTF8 *)"Mac OS X Key Ring"; NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckmk_HardwareVersion = { - NSS_CKMK_HARDWARE_VERSION_MAJOR, - NSS_CKMK_HARDWARE_VERSION_MINOR }; + nss_ckmk_HardwareVersion = { + NSS_CKMK_HARDWARE_VERSION_MAJOR, + NSS_CKMK_HARDWARE_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const CK_VERSION -nss_ckmk_FirmwareVersion = { - NSS_CKMK_FIRMWARE_VERSION_MAJOR, - NSS_CKMK_FIRMWARE_VERSION_MINOR }; + nss_ckmk_FirmwareVersion = { + NSS_CKMK_FIRMWARE_VERSION_MAJOR, + NSS_CKMK_FIRMWARE_VERSION_MINOR + }; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckmk_TokenLabel = (NSSUTF8 *) "Mac OS X Key Ring"; + nss_ckmk_TokenLabel = (NSSUTF8 *)"Mac OS X Key Ring"; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckmk_TokenModel = (NSSUTF8 *) "1"; + nss_ckmk_TokenModel = (NSSUTF8 *)"1"; NSS_IMPLEMENT_DATA const NSSUTF8 * -nss_ckmk_TokenSerialNumber = (NSSUTF8 *) "1"; - + nss_ckmk_TokenSerialNumber = (NSSUTF8 *)"1"; diff --git a/security/nss/lib/ckfw/nssmkey/mfind.c b/security/nss/lib/ckfw/nssmkey/mfind.c index 8f22bdac86c7..41deef5e97f6 100644 --- a/security/nss/lib/ckfw/nssmkey/mfind.c +++ b/security/nss/lib/ckfw/nssmkey/mfind.c @@ -14,354 +14,343 @@ */ struct ckmkFOStr { - NSSArena *arena; - CK_ULONG n; - CK_ULONG i; - ckmkInternalObject **objs; + NSSArena *arena; + CK_ULONG n; + CK_ULONG i; + ckmkInternalObject **objs; }; static void -ckmk_mdFindObjects_Final -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdFindObjects_Final( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - struct ckmkFOStr *fo = (struct ckmkFOStr *)mdFindObjects->etc; - NSSArena *arena = fo->arena; - PRUint32 i; + struct ckmkFOStr *fo = (struct ckmkFOStr *)mdFindObjects->etc; + NSSArena *arena = fo->arena; + PRUint32 i; - /* walk down an free the unused 'objs' */ - for (i=fo->i; i < fo->n ; i++) { - nss_ckmk_DestroyInternalObject(fo->objs[i]); - } + /* walk down an free the unused 'objs' */ + for (i = fo->i; i < fo->n; i++) { + nss_ckmk_DestroyInternalObject(fo->objs[i]); + } - nss_ZFreeIf(fo->objs); - nss_ZFreeIf(fo); - nss_ZFreeIf(mdFindObjects); - if ((NSSArena *)NULL != arena) { - NSSArena_Destroy(arena); - } + nss_ZFreeIf(fo->objs); + nss_ZFreeIf(fo); + nss_ZFreeIf(mdFindObjects); + if ((NSSArena *)NULL != arena) { + NSSArena_Destroy(arena); + } - return; + return; } static NSSCKMDObject * -ckmk_mdFindObjects_Next -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +ckmk_mdFindObjects_Next( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { - struct ckmkFOStr *fo = (struct ckmkFOStr *)mdFindObjects->etc; - ckmkInternalObject *io; + struct ckmkFOStr *fo = (struct ckmkFOStr *)mdFindObjects->etc; + ckmkInternalObject *io; - if( fo->i == fo->n ) { - *pError = CKR_OK; - return (NSSCKMDObject *)NULL; - } + if (fo->i == fo->n) { + *pError = CKR_OK; + return (NSSCKMDObject *)NULL; + } - io = fo->objs[ fo->i ]; - fo->i++; + io = fo->objs[fo->i]; + fo->i++; - return nss_ckmk_CreateMDObject(arena, io, pError); + return nss_ckmk_CreateMDObject(arena, io, pError); } static CK_BBOOL -ckmk_attrmatch -( - CK_ATTRIBUTE_PTR a, - ckmkInternalObject *o -) +ckmk_attrmatch( + CK_ATTRIBUTE_PTR a, + ckmkInternalObject *o) { - PRBool prb; - const NSSItem *b; - CK_RV error; + PRBool prb; + const NSSItem *b; + CK_RV error; - b = nss_ckmk_FetchAttribute(o, a->type, &error); - if (b == NULL) { - return CK_FALSE; - } - - if( a->ulValueLen != b->size ) { - /* match a decoded serial number */ - if ((a->type == CKA_SERIAL_NUMBER) && (a->ulValueLen < b->size)) { - int len; - unsigned char *data; - - data = nss_ckmk_DERUnwrap(b->data, b->size, &len, NULL); - if ((len == a->ulValueLen) && - nsslibc_memequal(a->pValue, data, len, (PRStatus *)NULL)) { - return CK_TRUE; - } + b = nss_ckmk_FetchAttribute(o, a->type, &error); + if (b == NULL) { + return CK_FALSE; } - return CK_FALSE; - } - prb = nsslibc_memequal(a->pValue, b->data, b->size, (PRStatus *)NULL); + if (a->ulValueLen != b->size) { + /* match a decoded serial number */ + if ((a->type == CKA_SERIAL_NUMBER) && (a->ulValueLen < b->size)) { + int len; + unsigned char *data; - if( PR_TRUE == prb ) { + data = nss_ckmk_DERUnwrap(b->data, b->size, &len, NULL); + if ((len == a->ulValueLen) && + nsslibc_memequal(a->pValue, data, len, (PRStatus *)NULL)) { + return CK_TRUE; + } + } + return CK_FALSE; + } + + prb = nsslibc_memequal(a->pValue, b->data, b->size, (PRStatus *)NULL); + + if (PR_TRUE == prb) { + return CK_TRUE; + } + else { + return CK_FALSE; + } +} + +static CK_BBOOL +ckmk_match( + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckmkInternalObject *o) +{ + CK_ULONG i; + + for (i = 0; i < ulAttributeCount; i++) { + if (CK_FALSE == ckmk_attrmatch(&pTemplate[i], o)) { + return CK_FALSE; + } + } + + /* Every attribute passed */ return CK_TRUE; - } else { - return CK_FALSE; - } } +#define CKMK_ITEM_CHUNK 20 -static CK_BBOOL -ckmk_match -( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckmkInternalObject *o -) -{ - CK_ULONG i; - - for( i = 0; i < ulAttributeCount; i++ ) { - if (CK_FALSE == ckmk_attrmatch(&pTemplate[i], o)) { - return CK_FALSE; +#define PUT_OBJECT(obj, err, size, count, list) \ + { \ + if (count >= size) { \ + (list) = (list) ? \ + nss_ZREALLOCARRAY(list, ckmkInternalObject *, \ + ((size) + \ + CKMK_ITEM_CHUNK)) \ + : \ + nss_ZNEWARRAY(NULL, ckmkInternalObject *, \ + ((size) + \ + CKMK_ITEM_CHUNK)); \ + if ((ckmkInternalObject **)NULL == list) { \ + err = CKR_HOST_MEMORY; \ + goto loser; \ + } \ + (size) += CKMK_ITEM_CHUNK; \ + } \ + (list)[count] = (obj); \ + count++; \ } - } - - /* Every attribute passed */ - return CK_TRUE; -} - -#define CKMK_ITEM_CHUNK 20 - -#define PUT_OBJECT(obj, err, size, count, list) \ - { \ - if (count >= size) { \ - (list) = (list) ? \ - nss_ZREALLOCARRAY(list, ckmkInternalObject *, \ - ((size)+CKMK_ITEM_CHUNK) ) : \ - nss_ZNEWARRAY(NULL, ckmkInternalObject *, \ - ((size)+CKMK_ITEM_CHUNK) ) ; \ - if ((ckmkInternalObject **)NULL == list) { \ - err = CKR_HOST_MEMORY; \ - goto loser; \ - } \ - (size) += CKMK_ITEM_CHUNK; \ - } \ - (list)[ count ] = (obj); \ - count++; \ - } - /* find all the certs that represent the appropriate object (cert, priv key, or * pub key) in the cert store. */ static PRUint32 collect_class( - CK_OBJECT_CLASS objClass, - SecItemClass itemClass, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckmkInternalObject ***listp, - PRUint32 *sizep, - PRUint32 count, - CK_RV *pError -) + CK_OBJECT_CLASS objClass, + SecItemClass itemClass, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckmkInternalObject ***listp, + PRUint32 *sizep, + PRUint32 count, + CK_RV *pError) { - ckmkInternalObject *next = NULL; - SecKeychainSearchRef searchRef = 0; - SecKeychainItemRef itemRef = 0; - OSStatus error; + ckmkInternalObject *next = NULL; + SecKeychainSearchRef searchRef = 0; + SecKeychainItemRef itemRef = 0; + OSStatus error; - /* future, build the attribute list based on the template - * so we can refine the search */ - error = SecKeychainSearchCreateFromAttributes( - NULL, itemClass, NULL, &searchRef); + /* future, build the attribute list based on the template + * so we can refine the search */ + error = SecKeychainSearchCreateFromAttributes( + NULL, itemClass, NULL, &searchRef); - while (noErr == SecKeychainSearchCopyNext(searchRef, &itemRef)) { - /* if we don't have an internal object structure, get one */ - if ((ckmkInternalObject *)NULL == next) { - next = nss_ZNEW(NULL, ckmkInternalObject); - if ((ckmkInternalObject *)NULL == next) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + while (noErr == SecKeychainSearchCopyNext(searchRef, &itemRef)) { + /* if we don't have an internal object structure, get one */ + if ((ckmkInternalObject *)NULL == next) { + next = nss_ZNEW(NULL, ckmkInternalObject); + if ((ckmkInternalObject *)NULL == next) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + } + /* fill in the relevant object data */ + next->type = ckmkItem; + next->objClass = objClass; + next->u.item.itemRef = itemRef; + next->u.item.itemClass = itemClass; + + /* see if this is one of the objects we are looking for */ + if (CK_TRUE == ckmk_match(pTemplate, ulAttributeCount, next)) { + /* yes, put it on the list */ + PUT_OBJECT(next, *pError, *sizep, count, *listp); + next = NULL; /* this one is on the list, need to allocate a new one now */ + } + else { + /* no , release the current item and clear out the structure for reuse */ + CFRelease(itemRef); + /* don't cache the values we just loaded */ + nsslibc_memset(next, 0, sizeof(*next)); + } } - /* fill in the relevant object data */ - next->type = ckmkItem; - next->objClass = objClass; - next->u.item.itemRef = itemRef; - next->u.item.itemClass = itemClass; - - /* see if this is one of the objects we are looking for */ - if( CK_TRUE == ckmk_match(pTemplate, ulAttributeCount, next) ) { - /* yes, put it on the list */ - PUT_OBJECT(next, *pError, *sizep, count, *listp); - next = NULL; /* this one is on the list, need to allocate a new one now */ - } else { - /* no , release the current item and clear out the structure for reuse */ - CFRelease(itemRef); - /* don't cache the values we just loaded */ - nsslibc_memset(next, 0, sizeof(*next)); - } - } loser: - if (searchRef) { - CFRelease(searchRef); - } - nss_ZFreeIf(next); - return count; + if (searchRef) { + CFRelease(searchRef); + } + nss_ZFreeIf(next); + return count; } static PRUint32 collect_objects( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - ckmkInternalObject ***listp, - CK_RV *pError -) + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + ckmkInternalObject ***listp, + CK_RV *pError) { - PRUint32 i; - PRUint32 count = 0; - PRUint32 size = 0; - CK_OBJECT_CLASS objClass; + PRUint32 i; + PRUint32 count = 0; + PRUint32 size = 0; + CK_OBJECT_CLASS objClass; - /* - * first handle the static build in objects (if any) - */ - for( i = 0; i < nss_ckmk_nObjects; i++ ) { - ckmkInternalObject *o = (ckmkInternalObject *)&nss_ckmk_data[i]; + /* + * first handle the static build in objects (if any) + */ + for (i = 0; i < nss_ckmk_nObjects; i++) { + ckmkInternalObject *o = (ckmkInternalObject *)&nss_ckmk_data[i]; - if( CK_TRUE == ckmk_match(pTemplate, ulAttributeCount, o) ) { - PUT_OBJECT(o, *pError, size, count, *listp); + if (CK_TRUE == ckmk_match(pTemplate, ulAttributeCount, o)) { + PUT_OBJECT(o, *pError, size, count, *listp); + } } - } - /* - * now handle the various object types - */ - objClass = nss_ckmk_GetULongAttribute(CKA_CLASS, - pTemplate, ulAttributeCount, pError); - if (CKR_OK != *pError) { - objClass = CK_INVALID_HANDLE; - } - *pError = CKR_OK; - switch (objClass) { - case CKO_CERTIFICATE: - count = collect_class(objClass, kSecCertificateItemClass, - pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - case CKO_PUBLIC_KEY: - count = collect_class(objClass, CSSM_DL_DB_RECORD_PUBLIC_KEY, - pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - case CKO_PRIVATE_KEY: - count = collect_class(objClass, CSSM_DL_DB_RECORD_PRIVATE_KEY, - pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - /* all of them */ - case CK_INVALID_HANDLE: - count = collect_class(CKO_CERTIFICATE, kSecCertificateItemClass, - pTemplate, ulAttributeCount, listp, - &size, count, pError); - count = collect_class(CKO_PUBLIC_KEY, CSSM_DL_DB_RECORD_PUBLIC_KEY, - pTemplate, ulAttributeCount, listp, - &size, count, pError); - count = collect_class(CKO_PUBLIC_KEY, CSSM_DL_DB_RECORD_PRIVATE_KEY, - pTemplate, ulAttributeCount, listp, - &size, count, pError); - break; - default: - break; - } - if (CKR_OK != *pError) { - goto loser; - } + /* + * now handle the various object types + */ + objClass = nss_ckmk_GetULongAttribute(CKA_CLASS, + pTemplate, ulAttributeCount, pError); + if (CKR_OK != *pError) { + objClass = CK_INVALID_HANDLE; + } + *pError = CKR_OK; + switch (objClass) { + case CKO_CERTIFICATE: + count = collect_class(objClass, kSecCertificateItemClass, + pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + case CKO_PUBLIC_KEY: + count = collect_class(objClass, CSSM_DL_DB_RECORD_PUBLIC_KEY, + pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + case CKO_PRIVATE_KEY: + count = collect_class(objClass, CSSM_DL_DB_RECORD_PRIVATE_KEY, + pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + /* all of them */ + case CK_INVALID_HANDLE: + count = collect_class(CKO_CERTIFICATE, kSecCertificateItemClass, + pTemplate, ulAttributeCount, listp, + &size, count, pError); + count = collect_class(CKO_PUBLIC_KEY, CSSM_DL_DB_RECORD_PUBLIC_KEY, + pTemplate, ulAttributeCount, listp, + &size, count, pError); + count = collect_class(CKO_PUBLIC_KEY, CSSM_DL_DB_RECORD_PRIVATE_KEY, + pTemplate, ulAttributeCount, listp, + &size, count, pError); + break; + default: + break; + } + if (CKR_OK != *pError) { + goto loser; + } - return count; + return count; loser: - nss_ZFreeIf(*listp); - return 0; + nss_ZFreeIf(*listp); + return 0; } - NSS_IMPLEMENT NSSCKMDFindObjects * -nss_ckmk_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckmk_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - /* This could be made more efficient. I'm rather rushed. */ - NSSArena *arena; - NSSCKMDFindObjects *rv = (NSSCKMDFindObjects *)NULL; - struct ckmkFOStr *fo = (struct ckmkFOStr *)NULL; - ckmkInternalObject **temp = (ckmkInternalObject **)NULL; + /* This could be made more efficient. I'm rather rushed. */ + NSSArena *arena; + NSSCKMDFindObjects *rv = (NSSCKMDFindObjects *)NULL; + struct ckmkFOStr *fo = (struct ckmkFOStr *)NULL; + ckmkInternalObject **temp = (ckmkInternalObject **)NULL; - arena = NSSArena_Create(); - if( (NSSArena *)NULL == arena ) { - goto loser; - } + arena = NSSArena_Create(); + if ((NSSArena *)NULL == arena) { + goto loser; + } - rv = nss_ZNEW(arena, NSSCKMDFindObjects); - if( (NSSCKMDFindObjects *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + rv = nss_ZNEW(arena, NSSCKMDFindObjects); + if ((NSSCKMDFindObjects *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - fo = nss_ZNEW(arena, struct ckmkFOStr); - if( (struct ckmkFOStr *)NULL == fo ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + fo = nss_ZNEW(arena, struct ckmkFOStr); + if ((struct ckmkFOStr *)NULL == fo) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - fo->arena = arena; - /* fo->n and fo->i are already zero */ + fo->arena = arena; + /* fo->n and fo->i are already zero */ - rv->etc = (void *)fo; - rv->Final = ckmk_mdFindObjects_Final; - rv->Next = ckmk_mdFindObjects_Next; - rv->null = (void *)NULL; + rv->etc = (void *)fo; + rv->Final = ckmk_mdFindObjects_Final; + rv->Next = ckmk_mdFindObjects_Next; + rv->null = (void *)NULL; - fo->n = collect_objects(pTemplate, ulAttributeCount, &temp, pError); - if (*pError != CKR_OK) { - goto loser; - } + fo->n = collect_objects(pTemplate, ulAttributeCount, &temp, pError); + if (*pError != CKR_OK) { + goto loser; + } - fo->objs = nss_ZNEWARRAY(arena, ckmkInternalObject *, fo->n); - if( (ckmkInternalObject **)NULL == fo->objs ) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + fo->objs = nss_ZNEWARRAY(arena, ckmkInternalObject *, fo->n); + if ((ckmkInternalObject **)NULL == fo->objs) { + *pError = CKR_HOST_MEMORY; + goto loser; + } - (void)nsslibc_memcpy(fo->objs, temp, sizeof(ckmkInternalObject *) * fo->n); - nss_ZFreeIf(temp); - temp = (ckmkInternalObject **)NULL; + (void)nsslibc_memcpy(fo->objs, temp, sizeof(ckmkInternalObject *) * fo->n); + nss_ZFreeIf(temp); + temp = (ckmkInternalObject **)NULL; - return rv; + return rv; - loser: - nss_ZFreeIf(temp); - nss_ZFreeIf(fo); - nss_ZFreeIf(rv); - if ((NSSArena *)NULL != arena) { - NSSArena_Destroy(arena); - } - return (NSSCKMDFindObjects *)NULL; +loser: + nss_ZFreeIf(temp); + nss_ZFreeIf(fo); + nss_ZFreeIf(rv); + if ((NSSArena *)NULL != arena) { + NSSArena_Destroy(arena); + } + return (NSSCKMDFindObjects *)NULL; } - diff --git a/security/nss/lib/ckfw/nssmkey/minst.c b/security/nss/lib/ckfw/nssmkey/minst.c index 923ba105cda5..fcb96c6527fc 100644 --- a/security/nss/lib/ckfw/nssmkey/minst.c +++ b/security/nss/lib/ckfw/nssmkey/minst.c @@ -7,7 +7,7 @@ /* * nssmkey/minstance.c * - * This file implements the NSSCKMDInstance object for the + * This file implements the NSSCKMDInstance object for the * "nssmkey" cryptoki module. */ @@ -16,96 +16,82 @@ */ static CK_ULONG -ckmk_mdInstance_GetNSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdInstance_GetNSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (CK_ULONG)1; + return (CK_ULONG)1; } static CK_VERSION -ckmk_mdInstance_GetCryptokiVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdInstance_GetCryptokiVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckmk_CryptokiVersion; + return nss_ckmk_CryptokiVersion; } static NSSUTF8 * -ckmk_mdInstance_GetManufacturerID -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdInstance_GetManufacturerID( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_ManufacturerID; + return (NSSUTF8 *)nss_ckmk_ManufacturerID; } static NSSUTF8 * -ckmk_mdInstance_GetLibraryDescription -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdInstance_GetLibraryDescription( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_LibraryDescription; + return (NSSUTF8 *)nss_ckmk_LibraryDescription; } static CK_VERSION -ckmk_mdInstance_GetLibraryVersion -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdInstance_GetLibraryVersion( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckmk_LibraryVersion; + return nss_ckmk_LibraryVersion; } static CK_RV -ckmk_mdInstance_GetSlots -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDSlot *slots[] -) +ckmk_mdInstance_GetSlots( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDSlot *slots[]) { - slots[0] = (NSSCKMDSlot *)&nss_ckmk_mdSlot; - return CKR_OK; + slots[0] = (NSSCKMDSlot *)&nss_ckmk_mdSlot; + return CKR_OK; } static CK_BBOOL -ckmk_mdInstance_ModuleHandlesSessionObjects -( - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdInstance_ModuleHandlesSessionObjects( + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - /* we don't want to allow any session object creation, at least - * until we can investigate whether or not we can use those objects - */ - return CK_TRUE; + /* we don't want to allow any session object creation, at least + * until we can investigate whether or not we can use those objects + */ + return CK_TRUE; } NSS_IMPLEMENT_DATA const NSSCKMDInstance -nss_ckmk_mdInstance = { - (void *)NULL, /* etc */ - NULL, /* Initialize */ - NULL, /* Finalize */ - ckmk_mdInstance_GetNSlots, - ckmk_mdInstance_GetCryptokiVersion, - ckmk_mdInstance_GetManufacturerID, - ckmk_mdInstance_GetLibraryDescription, - ckmk_mdInstance_GetLibraryVersion, - ckmk_mdInstance_ModuleHandlesSessionObjects, - /*NULL, /* HandleSessionObjects */ - ckmk_mdInstance_GetSlots, - NULL, /* WaitForSlotEvent */ - (void *)NULL /* null terminator */ -}; + nss_ckmk_mdInstance = { + (void *)NULL, /* etc */ + NULL, /* Initialize */ + NULL, /* Finalize */ + ckmk_mdInstance_GetNSlots, + ckmk_mdInstance_GetCryptokiVersion, + ckmk_mdInstance_GetManufacturerID, + ckmk_mdInstance_GetLibraryDescription, + ckmk_mdInstance_GetLibraryVersion, + ckmk_mdInstance_ModuleHandlesSessionObjects, + /*NULL, /* HandleSessionObjects */ + ckmk_mdInstance_GetSlots, + NULL, /* WaitForSlotEvent */ + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/nssmkey/mobject.c b/security/nss/lib/ckfw/nssmkey/mobject.c index 2013e7e99149..0b5f0a4851cc 100644 --- a/security/nss/lib/ckfw/nssmkey/mobject.c +++ b/security/nss/lib/ckfw/nssmkey/mobject.c @@ -90,37 +90,45 @@ static const CK_KEY_TYPE ckk_rsa = CKK_RSA; static const CK_OBJECT_CLASS cko_certificate = CKO_CERTIFICATE; static const CK_OBJECT_CLASS cko_private_key = CKO_PRIVATE_KEY; static const CK_OBJECT_CLASS cko_public_key = CKO_PUBLIC_KEY; -static const NSSItem ckmk_trueItem = { - (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) }; -static const NSSItem ckmk_falseItem = { - (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }; -static const NSSItem ckmk_x509Item = { - (void *)&ckc_x509, (PRUint32)sizeof(CK_CERTIFICATE_TYPE) }; -static const NSSItem ckmk_rsaItem = { - (void *)&ckk_rsa, (PRUint32)sizeof(CK_KEY_TYPE) }; -static const NSSItem ckmk_certClassItem = { - (void *)&cko_certificate, (PRUint32)sizeof(CK_OBJECT_CLASS) }; +static const NSSItem ckmk_trueItem = { + (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) +}; +static const NSSItem ckmk_falseItem = { + (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) +}; +static const NSSItem ckmk_x509Item = { + (void *)&ckc_x509, (PRUint32)sizeof(CK_CERTIFICATE_TYPE) +}; +static const NSSItem ckmk_rsaItem = { + (void *)&ckk_rsa, (PRUint32)sizeof(CK_KEY_TYPE) +}; +static const NSSItem ckmk_certClassItem = { + (void *)&cko_certificate, (PRUint32)sizeof(CK_OBJECT_CLASS) +}; static const NSSItem ckmk_privKeyClassItem = { - (void *)&cko_private_key, (PRUint32)sizeof(CK_OBJECT_CLASS) }; + (void *)&cko_private_key, (PRUint32)sizeof(CK_OBJECT_CLASS) +}; static const NSSItem ckmk_pubKeyClassItem = { - (void *)&cko_public_key, (PRUint32)sizeof(CK_OBJECT_CLASS) }; -static const NSSItem ckmk_emptyItem = { - (void *)&ck_true, 0}; + (void *)&cko_public_key, (PRUint32)sizeof(CK_OBJECT_CLASS) +}; +static const NSSItem ckmk_emptyItem = { + (void *)&ck_true, 0 +}; /* * these are utilities. The chould be moved to a new utilities file. */ #ifdef DEBUG static void -itemdump(char *str, void *data, int size, CK_RV error) +itemdump(char *str, void *data, int size, CK_RV error) { - unsigned char *ptr = (unsigned char *)data; - int i; - fprintf(stderr,str); - for (i=0; i < size; i++) { - fprintf(stderr,"%02x ",(unsigned int) ptr[i]); - } - fprintf(stderr," (error = %d)\n", (int ) error); + unsigned char *ptr = (unsigned char *)data; + int i; + fprintf(stderr, str); + for (i = 0; i < size; i++) { + fprintf(stderr, "%02x ", (unsigned int)ptr[i]); + } + fprintf(stderr, " (error = %d)\n", (int)error); } #endif @@ -130,48 +138,46 @@ itemdump(char *str, void *data, int size, CK_RV error) * the ANS1_Decoder for this work... */ unsigned char * -nss_ckmk_DERUnwrap -( - unsigned char *src, - int size, - int *outSize, - unsigned char **next -) +nss_ckmk_DERUnwrap( + unsigned char *src, + int size, + int *outSize, + unsigned char **next) { - unsigned char *start = src; - unsigned int len = 0; + unsigned char *start = src; + unsigned int len = 0; - /* initialize error condition return values */ - *outSize = 0; - if (next) { - *next = src; - } - - if (size < 2) { - return start; - } - src ++ ; /* skip the tag -- should check it against an expected value! */ - len = (unsigned) *src++; - if (len & 0x80) { - int count = len & 0x7f; - len =0; - - if (count+2 > size) { - return start; + /* initialize error condition return values */ + *outSize = 0; + if (next) { + *next = src; } - while (count-- > 0) { - len = (len << 8) | (unsigned) *src++; - } - } - if (len + (src-start) > (unsigned int)size) { - return start; - } - if (next) { - *next = src+len; - } - *outSize = len; - return src; + if (size < 2) { + return start; + } + src++; /* skip the tag -- should check it against an expected value! */ + len = (unsigned)*src++; + if (len & 0x80) { + int count = len & 0x7f; + len = 0; + + if (count + 2 > size) { + return start; + } + while (count-- > 0) { + len = (len << 8) | (unsigned)*src++; + } + } + if (len + (src - start) > (unsigned int)size) { + return start; + } + if (next) { + *next = src + len; + } + *outSize = len; + + return src; } /* @@ -179,74 +185,68 @@ nss_ckmk_DERUnwrap * data for the item is owned by the template. */ CK_RV -nss_ckmk_GetAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - NSSItem *item -) +nss_ckmk_GetAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + NSSItem *item) { - CK_ULONG i; + CK_ULONG i; - for (i=0; i < templateSize; i++) { - if (template[i].type == type) { - item->data = template[i].pValue; - item->size = template[i].ulValueLen; - return CKR_OK; + for (i = 0; i < templateSize; i++) { + if (template[i].type == type) { + item->data = template[i].pValue; + item->size = template[i].ulValueLen; + return CKR_OK; + } } - } - return CKR_TEMPLATE_INCOMPLETE; + return CKR_TEMPLATE_INCOMPLETE; } /* * get an attribute which is type CK_ULONG. */ CK_ULONG -nss_ckmk_GetULongAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - CK_RV *pError -) +nss_ckmk_GetULongAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + CK_RV *pError) { - NSSItem item; + NSSItem item; - *pError = nss_ckmk_GetAttribute(type, template, templateSize, &item); - if (CKR_OK != *pError) { - return (CK_ULONG) 0; - } - if (item.size != sizeof(CK_ULONG)) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (CK_ULONG) 0; - } - return *(CK_ULONG *)item.data; + *pError = nss_ckmk_GetAttribute(type, template, templateSize, &item); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } + if (item.size != sizeof(CK_ULONG)) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + return (CK_ULONG)0; + } + return *(CK_ULONG *)item.data; } /* * get an attribute which is type CK_BBOOL. */ CK_BBOOL -nss_ckmk_GetBoolAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - CK_BBOOL defaultBool -) +nss_ckmk_GetBoolAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + CK_BBOOL defaultBool) { - NSSItem item; - CK_RV error; + NSSItem item; + CK_RV error; - error = nss_ckmk_GetAttribute(type, template, templateSize, &item); - if (CKR_OK != error) { - return defaultBool; - } - if (item.size != sizeof(CK_BBOOL)) { - return defaultBool; - } - return *(CK_BBOOL *)item.data; + error = nss_ckmk_GetAttribute(type, template, templateSize, &item); + if (CKR_OK != error) { + return defaultBool; + } + if (item.size != sizeof(CK_BBOOL)) { + return defaultBool; + } + return *(CK_BBOOL *)item.data; } /* @@ -254,33 +254,31 @@ nss_ckmk_GetBoolAttribute * free the string. */ char * -nss_ckmk_GetStringAttribute -( - CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *template, - CK_ULONG templateSize, - CK_RV *pError -) +nss_ckmk_GetStringAttribute( + CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *template, + CK_ULONG templateSize, + CK_RV *pError) { - NSSItem item; - char *str; + NSSItem item; + char *str; - /* get the attribute */ - *pError = nss_ckmk_GetAttribute(type, template, templateSize, &item); - if (CKR_OK != *pError) { - return (char *)NULL; - } - /* make sure it is null terminated */ - str = nss_ZNEWARRAY(NULL, char, item.size+1); - if ((char *)NULL == str) { - *pError = CKR_HOST_MEMORY; - return (char *)NULL; - } + /* get the attribute */ + *pError = nss_ckmk_GetAttribute(type, template, templateSize, &item); + if (CKR_OK != *pError) { + return (char *)NULL; + } + /* make sure it is null terminated */ + str = nss_ZNEWARRAY(NULL, char, item.size + 1); + if ((char *)NULL == str) { + *pError = CKR_HOST_MEMORY; + return (char *)NULL; + } - nsslibc_memcpy(str, item.data, item.size); - str[item.size] = 0; + nsslibc_memcpy(str, item.data, item.size); + str[item.size] = 0; - return str; + return str; } /* @@ -291,230 +289,225 @@ nss_ckmk_GetStringAttribute */ static CK_RV ckmk_encodeInt(NSSItem *dest, void *src, int srcLen) -{ - int dataLen = srcLen; - int lenLen = 1; - int encLen; - int isSigned = 0; - int offset = 0; - unsigned char *data = NULL; - int i; +{ + int dataLen = srcLen; + int lenLen = 1; + int encLen; + int isSigned = 0; + int offset = 0; + unsigned char *data = NULL; + int i; - if (*(unsigned char *)src & 0x80) { - dataLen++; - isSigned = 1; - } - - /* calculate the length of the length specifier */ - /* (NOTE: destroys dataLen value) */ - if (dataLen > 0x7f) { - do { - lenLen++; - dataLen >>= 8; - } while (dataLen); - } - - /* calculate our total length */ - dataLen = isSigned + srcLen; - encLen = 1 + lenLen + dataLen; - data = nss_ZNEWARRAY(NULL, unsigned char, encLen); - if ((unsigned char *)NULL == data) { - return CKR_HOST_MEMORY; - } - data[0] = DER_INTEGER; - if (1 == lenLen) { - data[1] = dataLen; - } else { - data[1] = 0x80 + lenLen; - for (i=0; i < lenLen; i++) { - data[i+1] = ((dataLen >> ((lenLen-i-1)*8)) & 0xff); + if (*(unsigned char *)src & 0x80) { + dataLen++; + isSigned = 1; } - } - offset = lenLen+1; - if (isSigned) { - data[offset++] = 0; - } - nsslibc_memcpy(&data[offset], src, srcLen); - dest->data = data; - dest->size = encLen; - return CKR_OK; + /* calculate the length of the length specifier */ + /* (NOTE: destroys dataLen value) */ + if (dataLen > 0x7f) { + do { + lenLen++; + dataLen >>= 8; + } while (dataLen); + } + + /* calculate our total length */ + dataLen = isSigned + srcLen; + encLen = 1 + lenLen + dataLen; + data = nss_ZNEWARRAY(NULL, unsigned char, encLen); + if ((unsigned char *)NULL == data) { + return CKR_HOST_MEMORY; + } + data[0] = DER_INTEGER; + if (1 == lenLen) { + data[1] = dataLen; + } + else { + data[1] = 0x80 + lenLen; + for (i = 0; i < lenLen; i++) { + data[i + 1] = ((dataLen >> ((lenLen - + i - 1) * + 8)) & + 0xff); + } + } + offset = lenLen + 1; + + if (isSigned) { + data[offset++] = 0; + } + nsslibc_memcpy(&data[offset], src, srcLen); + dest->data = data; + dest->size = encLen; + return CKR_OK; } - /* * Get a Keyring attribute. If content is set to true, then we get the * content, not the attribute. */ static CK_RV -ckmk_GetCommonAttribute -( - ckmkInternalObject *io, - SecItemAttr itemAttr, - PRBool content, - NSSItem *item, - char *dbString -) +ckmk_GetCommonAttribute( + ckmkInternalObject *io, + SecItemAttr itemAttr, + PRBool content, + NSSItem *item, + char *dbString) { - SecKeychainAttributeList *attrList = NULL; - SecKeychainAttributeInfo attrInfo; - PRUint32 len = 0; - PRUint32 dataLen = 0; - PRUint32 attrFormat = 0; - void *dataVal = 0; - void *out = NULL; - CK_RV error = CKR_OK; - OSStatus macErr; + SecKeychainAttributeList *attrList = NULL; + SecKeychainAttributeInfo attrInfo; + PRUint32 len = 0; + PRUint32 dataLen = 0; + PRUint32 attrFormat = 0; + void *dataVal = 0; + void *out = NULL; + CK_RV error = CKR_OK; + OSStatus macErr; - attrInfo.count = 1; - attrInfo.tag = &itemAttr; - attrInfo.format = &attrFormat; + attrInfo.count = 1; + attrInfo.tag = &itemAttr; + attrInfo.format = &attrFormat; - macErr = SecKeychainItemCopyAttributesAndData(io->u.item.itemRef, - &attrInfo, NULL, &attrList, &len, &out); - if (noErr != macErr) { - CKMK_MACERR(dbString, macErr); - return CKR_ATTRIBUTE_TYPE_INVALID; - } - dataLen = content ? len : attrList->attr->length; - dataVal = content ? out : attrList->attr->data; + macErr = SecKeychainItemCopyAttributesAndData(io->u.item.itemRef, + &attrInfo, NULL, &attrList, &len, &out); + if (noErr != macErr) { + CKMK_MACERR(dbString, macErr); + return CKR_ATTRIBUTE_TYPE_INVALID; + } + dataLen = content ? len : attrList->attr->length; + dataVal = content ? out : attrList->attr->data; - /* Apple's documentation says this value is DER Encoded, but it clearly isn't - * der encode it before we ship it back off to NSS - */ - if ( kSecSerialNumberItemAttr == itemAttr ) { - error = ckmk_encodeInt(item, dataVal, dataLen); - goto loser; /* logically 'done' if error == CKR_OK */ - } - item->data = nss_ZNEWARRAY(NULL, char, dataLen); - if (NULL == item->data) { - error = CKR_HOST_MEMORY; - goto loser; - } - nsslibc_memcpy(item->data, dataVal, dataLen); - item->size = dataLen; + /* Apple's documentation says this value is DER Encoded, but it clearly isn't + * der encode it before we ship it back off to NSS + */ + if (kSecSerialNumberItemAttr == itemAttr) { + error = ckmk_encodeInt(item, dataVal, dataLen); + goto loser; /* logically 'done' if error == CKR_OK */ + } + item->data = nss_ZNEWARRAY(NULL, char, dataLen); + if (NULL == item->data) { + error = CKR_HOST_MEMORY; + goto loser; + } + nsslibc_memcpy(item->data, dataVal, dataLen); + item->size = dataLen; loser: - SecKeychainItemFreeAttributesAndData(attrList, out); - return error; + SecKeychainItemFreeAttributesAndData(attrList, out); + return error; } /* * change an attribute (does not operate on the content). */ static CK_RV -ckmk_updateAttribute -( - SecKeychainItemRef itemRef, - SecItemAttr itemAttr, - void *data, - PRUint32 len, - char *dbString -) +ckmk_updateAttribute( + SecKeychainItemRef itemRef, + SecItemAttr itemAttr, + void *data, + PRUint32 len, + char *dbString) { - SecKeychainAttributeList attrList; - SecKeychainAttribute attrAttr; - OSStatus macErr; - CK_RV error = CKR_OK; + SecKeychainAttributeList attrList; + SecKeychainAttribute attrAttr; + OSStatus macErr; + CK_RV error = CKR_OK; - attrList.count = 1; - attrList.attr = &attrAttr; - attrAttr.tag = itemAttr; - attrAttr.data = data; - attrAttr.length = len; - macErr = SecKeychainItemModifyAttributesAndData(itemRef, &attrList, 0, NULL); - if (noErr != macErr) { - CKMK_MACERR(dbString, macErr); - error = CKR_ATTRIBUTE_TYPE_INVALID; - } - return error; + attrList.count = 1; + attrList.attr = &attrAttr; + attrAttr.tag = itemAttr; + attrAttr.data = data; + attrAttr.length = len; + macErr = SecKeychainItemModifyAttributesAndData(itemRef, &attrList, 0, NULL); + if (noErr != macErr) { + CKMK_MACERR(dbString, macErr); + error = CKR_ATTRIBUTE_TYPE_INVALID; + } + return error; } /* * get an attribute (does not operate on the content) */ static CK_RV -ckmk_GetDataAttribute -( - ckmkInternalObject *io, - SecItemAttr itemAttr, - NSSItem *item, - char *dbString -) +ckmk_GetDataAttribute( + ckmkInternalObject *io, + SecItemAttr itemAttr, + NSSItem *item, + char *dbString) { - return ckmk_GetCommonAttribute(io, itemAttr, PR_FALSE, item, dbString); + return ckmk_GetCommonAttribute(io, itemAttr, PR_FALSE, item, dbString); } /* * get an attribute we know is a BOOL. */ static CK_RV -ckmk_GetBoolAttribute -( - ckmkInternalObject *io, - SecItemAttr itemAttr, - NSSItem *item, - char *dbString -) +ckmk_GetBoolAttribute( + ckmkInternalObject *io, + SecItemAttr itemAttr, + NSSItem *item, + char *dbString) { - SecKeychainAttribute attr; - SecKeychainAttributeList attrList; - CK_BBOOL *boolp = NULL; - PRUint32 len = 0;; - void *out = NULL; - CK_RV error = CKR_OK; - OSStatus macErr; + SecKeychainAttribute attr; + SecKeychainAttributeList attrList; + CK_BBOOL *boolp = NULL; + PRUint32 len = 0; + ; + void *out = NULL; + CK_RV error = CKR_OK; + OSStatus macErr; - attr.tag = itemAttr; - attr.length = 0; - attr.data = NULL; - attrList.count = 1; - attrList.attr = &attr; + attr.tag = itemAttr; + attr.length = 0; + attr.data = NULL; + attrList.count = 1; + attrList.attr = &attr; - boolp = nss_ZNEW(NULL, CK_BBOOL); - if ((CK_BBOOL *)NULL == boolp) { - error = CKR_HOST_MEMORY; - goto loser; - } + boolp = nss_ZNEW(NULL, CK_BBOOL); + if ((CK_BBOOL *)NULL == boolp) { + error = CKR_HOST_MEMORY; + goto loser; + } - macErr = SecKeychainItemCopyContent(io->u.item.itemRef, NULL, - &attrList, &len, &out); - if (noErr != macErr) { - CKMK_MACERR(dbString, macErr); - error = CKR_ATTRIBUTE_TYPE_INVALID; - goto loser; - } - if (sizeof(PRUint32) != attr.length) { - error = CKR_ATTRIBUTE_TYPE_INVALID; - goto loser; - } - *boolp = *(PRUint32 *)attr.data ? 1 : 0; - item->data = boolp; - boolp = NULL; - item->size = sizeof(CK_BBOOL); + macErr = SecKeychainItemCopyContent(io->u.item.itemRef, NULL, + &attrList, &len, &out); + if (noErr != macErr) { + CKMK_MACERR(dbString, macErr); + error = CKR_ATTRIBUTE_TYPE_INVALID; + goto loser; + } + if (sizeof(PRUint32) != attr.length) { + error = CKR_ATTRIBUTE_TYPE_INVALID; + goto loser; + } + *boolp = *(PRUint32 *)attr.data ? 1 : 0; + item->data = boolp; + boolp = NULL; + item->size = sizeof(CK_BBOOL); loser: - nss_ZFreeIf(boolp); - SecKeychainItemFreeContent(&attrList, out); - return error; + nss_ZFreeIf(boolp); + SecKeychainItemFreeContent(&attrList, out); + return error; } - /* * macros for fetching attributes into a cache and returning the * appropriate value. These operate inside switch statements */ #define CKMK_HANDLE_ITEM(func, io, type, loc, item, error, str) \ - if (0 == (item)->loc.size) { \ - error = func(io, type, &(item)->loc, str); \ - } \ + if (0 == (item)->loc.size) { \ + error = func(io, type, &(item)->loc, str); \ + } \ return (CKR_OK == (error)) ? &(item)->loc : NULL; #define CKMK_HANDLE_OPT_ITEM(func, io, type, loc, item, error, str) \ - if (0 == (item)->loc.size) { \ - (void) func(io, type, &(item)->loc, str); \ - } \ - return &(item)->loc ; + if (0 == (item)->loc.size) { \ + (void) func(io, type, &(item)->loc, str); \ + } \ + return &(item)->loc; #define CKMK_HANDLE_BOOL_ITEM(io, type, loc, item, error, str) \ CKMK_HANDLE_ITEM(ckmk_GetBoolAttribute, io, type, loc, item, error, str) @@ -527,379 +520,364 @@ loser: * fetch the unique identifier for each object type. */ static void -ckmk_FetchHashKey -( - ckmkInternalObject *io -) +ckmk_FetchHashKey( + ckmkInternalObject *io) { - NSSItem *key = &io->hashKey; + NSSItem *key = &io->hashKey; - if (io->objClass == CKO_CERTIFICATE) { - ckmk_GetCommonAttribute(io, kSecCertEncodingItemAttr, - PR_TRUE, key, "Fetching HashKey (cert)"); - } else { - ckmk_GetCommonAttribute(io, kSecKeyLabel, - PR_FALSE, key, "Fetching HashKey (key)"); - } + if (io->objClass == CKO_CERTIFICATE) { + ckmk_GetCommonAttribute(io, kSecCertEncodingItemAttr, + PR_TRUE, key, "Fetching HashKey (cert)"); + } + else { + ckmk_GetCommonAttribute(io, kSecKeyLabel, + PR_FALSE, key, "Fetching HashKey (key)"); + } } /* * Apple mucks with the actual subject and issuer, so go fetch * the real ones ourselves. */ -static void -ckmk_fetchCert -( - ckmkInternalObject *io -) +static void +ckmk_fetchCert( + ckmkInternalObject *io) { - CK_RV error; - unsigned char * cert, *next; - int certSize, thisEntrySize; + CK_RV error; + unsigned char *cert, *next; + int certSize, thisEntrySize; - error = ckmk_GetCommonAttribute(io, kSecCertEncodingItemAttr, PR_TRUE, - &io->u.item.derCert, "Fetching Value (cert)"); - if (CKR_OK != error) { - return; - } - /* unwrap the cert bundle */ - cert = nss_ckmk_DERUnwrap((unsigned char *)io->u.item.derCert.data, - io->u.item.derCert.size, - &certSize, NULL); - /* unwrap the cert itself */ - /* cert == certdata */ - cert = nss_ckmk_DERUnwrap(cert, certSize, &certSize, NULL); + error = ckmk_GetCommonAttribute(io, kSecCertEncodingItemAttr, PR_TRUE, + &io->u.item.derCert, "Fetching Value (cert)"); + if (CKR_OK != error) { + return; + } + /* unwrap the cert bundle */ + cert = nss_ckmk_DERUnwrap((unsigned char *)io->u.item.derCert.data, + io->u.item.derCert.size, + &certSize, NULL); + /* unwrap the cert itself */ + /* cert == certdata */ + cert = nss_ckmk_DERUnwrap(cert, certSize, &certSize, NULL); - /* skip the optional version */ - if ((cert[0] & 0xa0) == 0xa0) { + /* skip the optional version */ + if ((cert[0] & 0xa0) == 0xa0) { + nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); + certSize -= next - cert; + cert = next; + } + /* skip the serial number */ nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); certSize -= next - cert; cert = next; - } - /* skip the serial number */ - nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); - certSize -= next - cert; - cert = next; - /* skip the OID */ - nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); - certSize -= next - cert; - cert = next; + /* skip the OID */ + nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); + certSize -= next - cert; + cert = next; - /* save the (wrapped) issuer */ - io->u.item.issuer.data = cert; - nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); - io->u.item.issuer.size = next - cert; - certSize -= io->u.item.issuer.size; - cert = next; + /* save the (wrapped) issuer */ + io->u.item.issuer.data = cert; + nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); + io->u.item.issuer.size = next - cert; + certSize -= io->u.item.issuer.size; + cert = next; - /* skip the OID */ - nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); - certSize -= next - cert; - cert = next; + /* skip the OID */ + nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); + certSize -= next - cert; + cert = next; - /* save the (wrapped) subject */ - io->u.item.subject.data = cert; - nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); - io->u.item.subject.size = next - cert; - certSize -= io->u.item.subject.size; - cert = next; + /* save the (wrapped) subject */ + io->u.item.subject.data = cert; + nss_ckmk_DERUnwrap(cert, certSize, &thisEntrySize, &next); + io->u.item.subject.size = next - cert; + certSize -= io->u.item.subject.size; + cert = next; } -static void -ckmk_fetchModulus -( - ckmkInternalObject *io -) +static void +ckmk_fetchModulus( + ckmkInternalObject *io) { - NSSItem item; - PRInt32 modLen; - CK_RV error; + NSSItem item; + PRInt32 modLen; + CK_RV error; - /* we can't reliably get the modulus for private keys through CSSM (sigh). - * For NSS this is OK because we really only use this to get the modulus - * length (unless we are trying to get a public key from a private keys, - * something CSSM ALSO does not do!). - */ - error = ckmk_GetDataAttribute(io, kSecKeyKeySizeInBits, &item, - "Key Fetch Modulus"); - if (CKR_OK != error) { - return; - } + /* we can't reliably get the modulus for private keys through CSSM (sigh). + * For NSS this is OK because we really only use this to get the modulus + * length (unless we are trying to get a public key from a private keys, + * something CSSM ALSO does not do!). + */ + error = ckmk_GetDataAttribute(io, kSecKeyKeySizeInBits, &item, + "Key Fetch Modulus"); + if (CKR_OK != error) { + return; + } - modLen = *(PRInt32 *)item.data; - modLen = modLen/8; /* convert from bits to bytes */ + modLen = *(PRInt32 *)item.data; + modLen = modLen / 8; /* convert from bits to bytes */ - nss_ZFreeIf(item.data); - io->u.item.modulus.data = nss_ZNEWARRAY(NULL, char, modLen); - if (NULL == io->u.item.modulus.data) { - return; - } - *(char *)io->u.item.modulus.data = 0x80; /* fake NSS out or it will + nss_ZFreeIf(item.data); + io->u.item.modulus.data = nss_ZNEWARRAY(NULL, char, modLen); + if (NULL == io->u.item.modulus.data) { + return; + } + *(char *)io->u.item.modulus.data = 0x80; /* fake NSS out or it will * drop the first byte */ - io->u.item.modulus.size = modLen; - return; + io->u.item.modulus.size = modLen; + return; } const NSSItem * -ckmk_FetchCertAttribute -( - ckmkInternalObject *io, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError -) +ckmk_FetchCertAttribute( + ckmkInternalObject *io, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError) { - ckmkItemObject *item = &io->u.item; - *pError = CKR_OK; - switch(type) { - case CKA_CLASS: - return &ckmk_certClassItem; - case CKA_TOKEN: - case CKA_MODIFIABLE: - return &ckmk_trueItem; - case CKA_PRIVATE: - return &ckmk_falseItem; - case CKA_CERTIFICATE_TYPE: - return &ckmk_x509Item; - case CKA_LABEL: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecLabelItemAttr, label, item, *pError, - "Cert:Label attr") - case CKA_SUBJECT: - /* OK, well apple does provide an subject and issuer attribute, but they - * decided to cannonicalize that value. Probably a good move for them, - * but makes it useless for most users of PKCS #11.. Get the real subject - * from the certificate */ - if (0 == item->derCert.size) { - ckmk_fetchCert(io); + ckmkItemObject *item = &io->u.item; + *pError = CKR_OK; + switch (type) { + case CKA_CLASS: + return &ckmk_certClassItem; + case CKA_TOKEN: + case CKA_MODIFIABLE: + return &ckmk_trueItem; + case CKA_PRIVATE: + return &ckmk_falseItem; + case CKA_CERTIFICATE_TYPE: + return &ckmk_x509Item; + case CKA_LABEL: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecLabelItemAttr, label, item, *pError, + "Cert:Label attr") + case CKA_SUBJECT: + /* OK, well apple does provide an subject and issuer attribute, but they + * decided to cannonicalize that value. Probably a good move for them, + * but makes it useless for most users of PKCS #11.. Get the real subject + * from the certificate */ + if (0 == item->derCert.size) { + ckmk_fetchCert(io); + } + return &item->subject; + case CKA_ISSUER: + if (0 == item->derCert.size) { + ckmk_fetchCert(io); + } + return &item->issuer; + case CKA_SERIAL_NUMBER: + CKMK_HANDLE_DATA_ITEM(io, kSecSerialNumberItemAttr, serial, item, *pError, + "Cert:Serial Number attr") + case CKA_VALUE: + if (0 == item->derCert.size) { + ckmk_fetchCert(io); + } + return &item->derCert; + case CKA_ID: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecPublicKeyHashItemAttr, id, item, *pError, + "Cert:ID attr") + default: + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + break; } - return &item->subject; - case CKA_ISSUER: - if (0 == item->derCert.size) { - ckmk_fetchCert(io); - } - return &item->issuer; - case CKA_SERIAL_NUMBER: - CKMK_HANDLE_DATA_ITEM(io, kSecSerialNumberItemAttr, serial, item, *pError, - "Cert:Serial Number attr") - case CKA_VALUE: - if (0 == item->derCert.size) { - ckmk_fetchCert(io); - } - return &item->derCert; - case CKA_ID: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecPublicKeyHashItemAttr, id, item, *pError, - "Cert:ID attr") - default: - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - break; - } - return NULL; + return NULL; } const NSSItem * -ckmk_FetchPubKeyAttribute -( - ckmkInternalObject *io, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError -) +ckmk_FetchPubKeyAttribute( + ckmkInternalObject *io, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError) { - ckmkItemObject *item = &io->u.item; - *pError = CKR_OK; - - switch(type) { - case CKA_CLASS: - return &ckmk_pubKeyClassItem; - case CKA_TOKEN: - case CKA_LOCAL: - return &ckmk_trueItem; - case CKA_KEY_TYPE: - return &ckmk_rsaItem; - case CKA_LABEL: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyPrintName, label, item, *pError, - "PubKey:Label attr") - case CKA_ENCRYPT: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyEncrypt, encrypt, item, *pError, - "PubKey:Encrypt attr") - case CKA_VERIFY: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyVerify, verify, item, *pError, - "PubKey:Verify attr") - case CKA_VERIFY_RECOVER: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyVerifyRecover, verifyRecover, - item, *pError, "PubKey:VerifyRecover attr") - case CKA_PRIVATE: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyPrivate, private, item, *pError, - "PubKey:Private attr") - case CKA_MODIFIABLE: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyModifiable, modify, item, *pError, - "PubKey:Modify attr") - case CKA_DERIVE: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyDerive, derive, item, *pError, - "PubKey:Derive attr") - case CKA_WRAP: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyWrap, wrap, item, *pError, - "PubKey:Wrap attr") - case CKA_SUBJECT: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecSubjectItemAttr, subject, item, *pError, - "PubKey:Subect attr") - case CKA_MODULUS: - return &ckmk_emptyItem; - case CKA_PUBLIC_EXPONENT: - return &ckmk_emptyItem; - case CKA_ID: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyLabel, id, item, *pError, - "PubKey:ID attr") - default: - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - break; - } - return NULL; + ckmkItemObject *item = &io->u.item; + *pError = CKR_OK; + + switch (type) { + case CKA_CLASS: + return &ckmk_pubKeyClassItem; + case CKA_TOKEN: + case CKA_LOCAL: + return &ckmk_trueItem; + case CKA_KEY_TYPE: + return &ckmk_rsaItem; + case CKA_LABEL: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyPrintName, label, item, *pError, + "PubKey:Label attr") + case CKA_ENCRYPT: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyEncrypt, encrypt, item, *pError, + "PubKey:Encrypt attr") + case CKA_VERIFY: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyVerify, verify, item, *pError, + "PubKey:Verify attr") + case CKA_VERIFY_RECOVER: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyVerifyRecover, verifyRecover, + item, *pError, "PubKey:VerifyRecover attr") + case CKA_PRIVATE: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyPrivate, private, item, *pError, + "PubKey:Private attr") + case CKA_MODIFIABLE: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyModifiable, modify, item, *pError, + "PubKey:Modify attr") + case CKA_DERIVE: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyDerive, derive, item, *pError, + "PubKey:Derive attr") + case CKA_WRAP: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyWrap, wrap, item, *pError, + "PubKey:Wrap attr") + case CKA_SUBJECT: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecSubjectItemAttr, subject, item, *pError, + "PubKey:Subect attr") + case CKA_MODULUS: + return &ckmk_emptyItem; + case CKA_PUBLIC_EXPONENT: + return &ckmk_emptyItem; + case CKA_ID: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyLabel, id, item, *pError, + "PubKey:ID attr") + default: + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + break; + } + return NULL; } const NSSItem * -ckmk_FetchPrivKeyAttribute -( - ckmkInternalObject *io, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError -) +ckmk_FetchPrivKeyAttribute( + ckmkInternalObject *io, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError) { - ckmkItemObject *item = &io->u.item; - *pError = CKR_OK; + ckmkItemObject *item = &io->u.item; + *pError = CKR_OK; - switch(type) { - case CKA_CLASS: - return &ckmk_privKeyClassItem; - case CKA_TOKEN: - case CKA_LOCAL: - return &ckmk_trueItem; - case CKA_SENSITIVE: - case CKA_EXTRACTABLE: /* will probably move in the future */ - case CKA_ALWAYS_SENSITIVE: - case CKA_NEVER_EXTRACTABLE: - return &ckmk_falseItem; - case CKA_KEY_TYPE: - return &ckmk_rsaItem; - case CKA_LABEL: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyPrintName, label, item, *pError, - "PrivateKey:Label attr") - case CKA_DECRYPT: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyDecrypt, decrypt, item, *pError, - "PrivateKey:Decrypt attr") - case CKA_SIGN: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeySign, sign, item, *pError, - "PrivateKey:Sign attr") - case CKA_SIGN_RECOVER: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeySignRecover, signRecover, item, *pError, - "PrivateKey:Sign Recover attr") - case CKA_PRIVATE: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyPrivate, private, item, *pError, - "PrivateKey:Private attr") - case CKA_MODIFIABLE: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyModifiable, modify, item, *pError, - "PrivateKey:Modify attr") - case CKA_DERIVE: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyDerive, derive, item, *pError, - "PrivateKey:Derive attr") - case CKA_UNWRAP: - CKMK_HANDLE_BOOL_ITEM(io, kSecKeyUnwrap, unwrap, item, *pError, - "PrivateKey:Unwrap attr") - case CKA_SUBJECT: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecSubjectItemAttr, subject, item, *pError, - "PrivateKey:Subject attr") - case CKA_MODULUS: - if (0 == item->modulus.size) { - ckmk_fetchModulus(io); - } - return &item->modulus; - case CKA_PUBLIC_EXPONENT: - return &ckmk_emptyItem; + switch (type) { + case CKA_CLASS: + return &ckmk_privKeyClassItem; + case CKA_TOKEN: + case CKA_LOCAL: + return &ckmk_trueItem; + case CKA_SENSITIVE: + case CKA_EXTRACTABLE: /* will probably move in the future */ + case CKA_ALWAYS_SENSITIVE: + case CKA_NEVER_EXTRACTABLE: + return &ckmk_falseItem; + case CKA_KEY_TYPE: + return &ckmk_rsaItem; + case CKA_LABEL: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyPrintName, label, item, *pError, + "PrivateKey:Label attr") + case CKA_DECRYPT: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyDecrypt, decrypt, item, *pError, + "PrivateKey:Decrypt attr") + case CKA_SIGN: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeySign, sign, item, *pError, + "PrivateKey:Sign attr") + case CKA_SIGN_RECOVER: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeySignRecover, signRecover, item, *pError, + "PrivateKey:Sign Recover attr") + case CKA_PRIVATE: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyPrivate, private, item, *pError, + "PrivateKey:Private attr") + case CKA_MODIFIABLE: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyModifiable, modify, item, *pError, + "PrivateKey:Modify attr") + case CKA_DERIVE: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyDerive, derive, item, *pError, + "PrivateKey:Derive attr") + case CKA_UNWRAP: + CKMK_HANDLE_BOOL_ITEM(io, kSecKeyUnwrap, unwrap, item, *pError, + "PrivateKey:Unwrap attr") + case CKA_SUBJECT: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecSubjectItemAttr, subject, item, *pError, + "PrivateKey:Subject attr") + case CKA_MODULUS: + if (0 == item->modulus.size) { + ckmk_fetchModulus(io); + } + return &item->modulus; + case CKA_PUBLIC_EXPONENT: + return &ckmk_emptyItem; #ifdef notdef - /* the following are sensitive attributes. We could implement them for - * sensitive keys using the key export function, but it's better to - * just support wrap through this token. That will more reliably allow us - * to export any private key that is truly exportable. - */ - case CKA_PRIVATE_EXPONENT: - CKMK_HANDLE_DATA_ITEM(io, kSecPrivateExponentItemAttr, privateExponent, - item, *pError) - case CKA_PRIME_1: - CKMK_HANDLE_DATA_ITEM(io, kSecPrime1ItemAttr, prime1, item, *pError) - case CKA_PRIME_2: - CKMK_HANDLE_DATA_ITEM(io, kSecPrime2ItemAttr, prime2, item, *pError) - case CKA_EXPONENT_1: - CKMK_HANDLE_DATA_ITEM(io, kSecExponent1ItemAttr, exponent1, item, *pError) - case CKA_EXPONENT_2: - CKMK_HANDLE_DATA_ITEM(io, kSecExponent2ItemAttr, exponent2, item, *pError) - case CKA_COEFFICIENT: - CKMK_HANDLE_DATA_ITEM(io, kSecCoefficientItemAttr, coefficient, - item, *pError) + /* the following are sensitive attributes. We could implement them for + * sensitive keys using the key export function, but it's better to + * just support wrap through this token. That will more reliably allow us + * to export any private key that is truly exportable. + */ + case CKA_PRIVATE_EXPONENT: + CKMK_HANDLE_DATA_ITEM(io, kSecPrivateExponentItemAttr, privateExponent, + item, *pError) + case CKA_PRIME_1: + CKMK_HANDLE_DATA_ITEM(io, kSecPrime1ItemAttr, prime1, item, *pError) + case CKA_PRIME_2: + CKMK_HANDLE_DATA_ITEM(io, kSecPrime2ItemAttr, prime2, item, *pError) + case CKA_EXPONENT_1: + CKMK_HANDLE_DATA_ITEM(io, kSecExponent1ItemAttr, exponent1, item, *pError) + case CKA_EXPONENT_2: + CKMK_HANDLE_DATA_ITEM(io, kSecExponent2ItemAttr, exponent2, item, *pError) + case CKA_COEFFICIENT: + CKMK_HANDLE_DATA_ITEM(io, kSecCoefficientItemAttr, coefficient, + item, *pError) #endif - case CKA_ID: - CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyLabel, id, item, *pError, - "PrivateKey:ID attr") - default: - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - return NULL; - } + case CKA_ID: + CKMK_HANDLE_OPT_DATA_ITEM(io, kSecKeyLabel, id, item, *pError, + "PrivateKey:ID attr") + default: + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + return NULL; + } } const NSSItem * -nss_ckmk_FetchAttribute -( - ckmkInternalObject *io, - CK_ATTRIBUTE_TYPE type, - CK_RV *pError -) +nss_ckmk_FetchAttribute( + ckmkInternalObject *io, + CK_ATTRIBUTE_TYPE type, + CK_RV *pError) { - CK_ULONG i; - const NSSItem * value = NULL; + CK_ULONG i; + const NSSItem *value = NULL; - if (io->type == ckmkRaw) { - for( i = 0; i < io->u.raw.n; i++ ) { - if( type == io->u.raw.types[i] ) { - return &io->u.raw.items[i]; - } + if (io->type == ckmkRaw) { + for (i = 0; i < io->u.raw.n; i++) { + if (type == io->u.raw.types[i]) { + return &io->u.raw.items[i]; + } + } + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + return NULL; + } + /* deal with the common attributes */ + switch (io->objClass) { + case CKO_CERTIFICATE: + value = ckmk_FetchCertAttribute(io, type, pError); + break; + case CKO_PRIVATE_KEY: + value = ckmk_FetchPrivKeyAttribute(io, type, pError); + break; + case CKO_PUBLIC_KEY: + value = ckmk_FetchPubKeyAttribute(io, type, pError); + break; + default: + *pError = CKR_OBJECT_HANDLE_INVALID; + return NULL; } - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - return NULL; - } - /* deal with the common attributes */ - switch (io->objClass) { - case CKO_CERTIFICATE: - value = ckmk_FetchCertAttribute(io, type, pError); - break; - case CKO_PRIVATE_KEY: - value = ckmk_FetchPrivKeyAttribute(io, type, pError); - break; - case CKO_PUBLIC_KEY: - value = ckmk_FetchPubKeyAttribute(io, type, pError); - break; - default: - *pError = CKR_OBJECT_HANDLE_INVALID; - return NULL; - } #ifdef DEBUG - if (CKA_ID == type) { - itemdump("id: ", value->data, value->size, *pError); - } + if (CKA_ID == type) { + itemdump("id: ", value->data, value->size, *pError); + } #endif - return value; + return value; } -static void -ckmk_removeObjectFromHash -( - ckmkInternalObject *io -); +static void +ckmk_removeObjectFromHash( + ckmkInternalObject *io); /* * * These are the MSObject functions we need to implement * * Finalize - unneeded (actually we should clean up the hashtables) - * Destroy + * Destroy * IsTokenObject - CK_TRUE * GetAttributeCount * GetAttributeTypes @@ -910,541 +888,516 @@ ckmk_removeObjectFromHash */ static CK_RV -ckmk_mdObject_Destroy -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdObject_Destroy( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; - OSStatus macErr; + ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; + OSStatus macErr; - if (ckmkRaw == io->type) { - /* there is not 'object write protected' error, use the next best thing */ - return CKR_TOKEN_WRITE_PROTECTED; - } + if (ckmkRaw == io->type) { + /* there is not 'object write protected' error, use the next best thing */ + return CKR_TOKEN_WRITE_PROTECTED; + } - /* This API is done well. The following 4 lines are the complete apple - * specific part of this implementation */ - macErr = SecKeychainItemDelete(io->u.item.itemRef); - if (noErr != macErr) { - CKMK_MACERR("Delete object", macErr); - } + /* This API is done well. The following 4 lines are the complete apple + * specific part of this implementation */ + macErr = SecKeychainItemDelete(io->u.item.itemRef); + if (noErr != macErr) { + CKMK_MACERR("Delete object", macErr); + } - /* remove it from the hash */ - ckmk_removeObjectFromHash(io); + /* remove it from the hash */ + ckmk_removeObjectFromHash(io); - /* free the puppy.. */ - nss_ckmk_DestroyInternalObject(io); + /* free the puppy.. */ + nss_ckmk_DestroyInternalObject(io); - return CKR_OK; + return CKR_OK; } static CK_BBOOL -ckmk_mdObject_IsTokenObject -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdObject_IsTokenObject( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_TRUE; + return CK_TRUE; } static CK_ULONG -ckmk_mdObject_GetAttributeCount -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdObject_GetAttributeCount( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; + ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; - if (ckmkRaw == io->type) { - return io->u.raw.n; - } - switch (io->objClass) { - case CKO_CERTIFICATE: - return certAttrsCount; - case CKO_PUBLIC_KEY: - return pubKeyAttrsCount; - case CKO_PRIVATE_KEY: - return privKeyAttrsCount; - default: - break; - } - return 0; -} - -static CK_RV -ckmk_mdObject_GetAttributeTypes -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -) -{ - ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; - CK_ULONG i; - CK_RV error = CKR_OK; - const CK_ATTRIBUTE_TYPE *attrs = NULL; - CK_ULONG size = ckmk_mdObject_GetAttributeCount( - mdObject, fwObject, mdSession, fwSession, - mdToken, fwToken, mdInstance, fwInstance, &error); - - if( size != ulCount ) { - return CKR_BUFFER_TOO_SMALL; - } - if (io->type == ckmkRaw) { - attrs = io->u.raw.types; - } else switch(io->objClass) { - case CKO_CERTIFICATE: - attrs = certAttrs; - break; - case CKO_PUBLIC_KEY: - attrs = pubKeyAttrs; - break; - case CKO_PRIVATE_KEY: - attrs = privKeyAttrs; - break; - default: - return CKR_OK; - } - - for( i = 0; i < size; i++) { - typeArray[i] = attrs[i]; - } - - return CKR_OK; -} - -static CK_ULONG -ckmk_mdObject_GetAttributeSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) -{ - ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; - - const NSSItem *b; - - b = nss_ckmk_FetchAttribute(io, attribute, pError); - - if ((const NSSItem *)NULL == b) { + if (ckmkRaw == io->type) { + return io->u.raw.n; + } + switch (io->objClass) { + case CKO_CERTIFICATE: + return certAttrsCount; + case CKO_PUBLIC_KEY: + return pubKeyAttrsCount; + case CKO_PRIVATE_KEY: + return privKeyAttrsCount; + default: + break; + } return 0; - } - return b->size; } static CK_RV -ckmk_mdObject_SetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value -) +ckmk_mdObject_GetAttributeTypes( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount) { - ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; - SecKeychainItemRef itemRef; + ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; + CK_ULONG i; + CK_RV error = CKR_OK; + const CK_ATTRIBUTE_TYPE *attrs = NULL; + CK_ULONG size = ckmk_mdObject_GetAttributeCount( + mdObject, fwObject, mdSession, fwSession, + mdToken, fwToken, mdInstance, fwInstance, &error); - if (io->type == ckmkRaw) { - return CKR_TOKEN_WRITE_PROTECTED; - } - itemRef = io->u.item.itemRef; + if (size != ulCount) { + return CKR_BUFFER_TOO_SMALL; + } + if (io->type == ckmkRaw) { + attrs = io->u.raw.types; + } + else + switch (io->objClass) { + case CKO_CERTIFICATE: + attrs = + certAttrs; + break; + case CKO_PUBLIC_KEY: + attrs = + pubKeyAttrs; + break; + case CKO_PRIVATE_KEY: + attrs = + privKeyAttrs; + break; + default: + return CKR_OK; + } - switch (io->objClass) { - case CKO_PRIVATE_KEY: - case CKO_PUBLIC_KEY: - switch (attribute) { - case CKA_ID: - ckmk_updateAttribute(itemRef, kSecKeyLabel, - value->data, value->size, "Set Attr Key ID"); + for (i = 0; i < size; i++) { + typeArray[i] = attrs[i]; + } + + return CKR_OK; +} + +static CK_ULONG +ckmk_mdObject_GetAttributeSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) +{ + ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; + + const NSSItem *b; + + b = nss_ckmk_FetchAttribute(io, attribute, pError); + + if ((const NSSItem *)NULL == b) { + return 0; + } + return b->size; +} + +static CK_RV +ckmk_mdObject_SetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value) +{ + ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; + SecKeychainItemRef itemRef; + + if (io->type == ckmkRaw) { + return CKR_TOKEN_WRITE_PROTECTED; + } + itemRef = io->u.item.itemRef; + + switch (io->objClass) { + case CKO_PRIVATE_KEY: + case CKO_PUBLIC_KEY: + switch (attribute) { + case CKA_ID: + ckmk_updateAttribute(itemRef, kSecKeyLabel, + value->data, value->size, "Set Attr Key ID"); #ifdef DEBUG - itemdump("key id: ", value->data, value->size, CKR_OK); + itemdump("key id: ", value->data, value->size, CKR_OK); #endif - break; - case CKA_LABEL: - ckmk_updateAttribute(itemRef, kSecKeyPrintName, value->data, - value->size, "Set Attr Key Label"); - break; - default: - break; - } - break; + break; + case CKA_LABEL: + ckmk_updateAttribute(itemRef, kSecKeyPrintName, value->data, + value->size, "Set Attr Key Label"); + break; + default: + break; + } + break; - case CKO_CERTIFICATE: - switch (attribute) { - case CKA_ID: - ckmk_updateAttribute(itemRef, kSecPublicKeyHashItemAttr, - value->data, value->size, "Set Attr Cert ID"); - break; - case CKA_LABEL: - ckmk_updateAttribute(itemRef, kSecLabelItemAttr, value->data, - value->size, "Set Attr Cert Label"); - break; - default: - break; - } - break; + case CKO_CERTIFICATE: + switch (attribute) { + case CKA_ID: + ckmk_updateAttribute(itemRef, kSecPublicKeyHashItemAttr, + value->data, value->size, "Set Attr Cert ID"); + break; + case CKA_LABEL: + ckmk_updateAttribute(itemRef, kSecLabelItemAttr, value->data, + value->size, "Set Attr Cert Label"); + break; + default: + break; + } + break; - default: - break; - } - return CKR_OK; + default: + break; + } + return CKR_OK; } static NSSCKFWItem -ckmk_mdObject_GetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +ckmk_mdObject_GetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - NSSCKFWItem mdItem; - ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; + NSSCKFWItem mdItem; + ckmkInternalObject *io = (ckmkInternalObject *)mdObject->etc; - mdItem.needsFreeing = PR_FALSE; - mdItem.item = (NSSItem*)nss_ckmk_FetchAttribute(io, attribute, pError); + mdItem.needsFreeing = PR_FALSE; + mdItem.item = (NSSItem *)nss_ckmk_FetchAttribute(io, attribute, pError); - - return mdItem; + return mdItem; } static CK_ULONG -ckmk_mdObject_GetObjectSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdObject_GetObjectSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - CK_ULONG rv = 1; + CK_ULONG rv = 1; - /* size is irrelevant to this token */ - return rv; + /* size is irrelevant to this token */ + return rv; } static const NSSCKMDObject -ckmk_prototype_mdObject = { - (void *)NULL, /* etc */ - NULL, /* Finalize */ - ckmk_mdObject_Destroy, - ckmk_mdObject_IsTokenObject, - ckmk_mdObject_GetAttributeCount, - ckmk_mdObject_GetAttributeTypes, - ckmk_mdObject_GetAttributeSize, - ckmk_mdObject_GetAttribute, - NULL, /* FreeAttribute */ - ckmk_mdObject_SetAttribute, - ckmk_mdObject_GetObjectSize, - (void *)NULL /* null terminator */ -}; + ckmk_prototype_mdObject = { + (void *)NULL, /* etc */ + NULL, /* Finalize */ + ckmk_mdObject_Destroy, + ckmk_mdObject_IsTokenObject, + ckmk_mdObject_GetAttributeCount, + ckmk_mdObject_GetAttributeTypes, + ckmk_mdObject_GetAttributeSize, + ckmk_mdObject_GetAttribute, + NULL, /* FreeAttribute */ + ckmk_mdObject_SetAttribute, + ckmk_mdObject_GetObjectSize, + (void *)NULL /* null terminator */ + }; static nssHash *ckmkInternalObjectHash = NULL; NSS_IMPLEMENT NSSCKMDObject * -nss_ckmk_CreateMDObject -( - NSSArena *arena, - ckmkInternalObject *io, - CK_RV *pError -) +nss_ckmk_CreateMDObject( + NSSArena *arena, + ckmkInternalObject *io, + CK_RV *pError) { - if ((nssHash *)NULL == ckmkInternalObjectHash) { - ckmkInternalObjectHash = nssHash_CreateItem(NULL, 10); - } - if (ckmkItem == io->type) { - /* the hash key, not a cryptographic key */ - NSSItem *key = &io->hashKey; - ckmkInternalObject *old_o = NULL; + if ((nssHash *)NULL == ckmkInternalObjectHash) { + ckmkInternalObjectHash = nssHash_CreateItem(NULL, 10); + } + if (ckmkItem == io->type) { + /* the hash key, not a cryptographic key */ + NSSItem *key = &io->hashKey; + ckmkInternalObject *old_o = NULL; - if (key->size == 0) { - ckmk_FetchHashKey(io); + if (key->size == 0) { + ckmk_FetchHashKey(io); + } + old_o = (ckmkInternalObject *) + nssHash_Lookup(ckmkInternalObjectHash, key); + if (!old_o) { + nssHash_Add(ckmkInternalObjectHash, key, io); + } + else if (old_o != io) { + nss_ckmk_DestroyInternalObject(io); + io = old_o; + } } - old_o = (ckmkInternalObject *) - nssHash_Lookup(ckmkInternalObjectHash, key); - if (!old_o) { - nssHash_Add(ckmkInternalObjectHash, key, io); - } else if (old_o != io) { - nss_ckmk_DestroyInternalObject(io); - io = old_o; + + if ((void *)NULL == io->mdObject.etc) { + (void)nsslibc_memcpy(&io->mdObject, &ckmk_prototype_mdObject, + sizeof(ckmk_prototype_mdObject)); + io->mdObject.etc = (void *)io; } - } - - if ( (void*)NULL == io->mdObject.etc) { - (void) nsslibc_memcpy(&io->mdObject,&ckmk_prototype_mdObject, - sizeof(ckmk_prototype_mdObject)); - io->mdObject.etc = (void *)io; - } - return &io->mdObject; + return &io->mdObject; } static void -ckmk_removeObjectFromHash -( - ckmkInternalObject *io -) +ckmk_removeObjectFromHash( + ckmkInternalObject *io) { - NSSItem *key = &io->hashKey; + NSSItem *key = &io->hashKey; - if ((nssHash *)NULL == ckmkInternalObjectHash) { + if ((nssHash *)NULL == ckmkInternalObjectHash) { + return; + } + if (key->size == 0) { + ckmk_FetchHashKey(io); + } + nssHash_Remove(ckmkInternalObjectHash, key); return; - } - if (key->size == 0) { - ckmk_FetchHashKey(io); - } - nssHash_Remove(ckmkInternalObjectHash, key); - return; } - void -nss_ckmk_DestroyInternalObject -( - ckmkInternalObject *io -) +nss_ckmk_DestroyInternalObject( + ckmkInternalObject *io) { - switch (io->type) { - case ckmkRaw: + switch (io->type) { + case ckmkRaw: + return; + case ckmkItem: + nss_ZFreeIf(io->u.item.modify.data); + nss_ZFreeIf(io->u.item.private.data); + nss_ZFreeIf(io->u.item.encrypt.data); + nss_ZFreeIf(io->u.item.decrypt.data); + nss_ZFreeIf(io->u.item.derive.data); + nss_ZFreeIf(io->u.item.sign.data); + nss_ZFreeIf(io->u.item.signRecover.data); + nss_ZFreeIf(io->u.item.verify.data); + nss_ZFreeIf(io->u.item.verifyRecover.data); + nss_ZFreeIf(io->u.item.wrap.data); + nss_ZFreeIf(io->u.item.unwrap.data); + nss_ZFreeIf(io->u.item.label.data); + /*nss_ZFreeIf(io->u.item.subject.data); */ + /*nss_ZFreeIf(io->u.item.issuer.data); */ + nss_ZFreeIf(io->u.item.serial.data); + nss_ZFreeIf(io->u.item.modulus.data); + nss_ZFreeIf(io->u.item.exponent.data); + nss_ZFreeIf(io->u.item.privateExponent.data); + nss_ZFreeIf(io->u.item.prime1.data); + nss_ZFreeIf(io->u.item.prime2.data); + nss_ZFreeIf(io->u.item.exponent1.data); + nss_ZFreeIf(io->u.item.exponent2.data); + nss_ZFreeIf(io->u.item.coefficient.data); + break; + } + nss_ZFreeIf(io); return; - case ckmkItem: - nss_ZFreeIf(io->u.item.modify.data); - nss_ZFreeIf(io->u.item.private.data); - nss_ZFreeIf(io->u.item.encrypt.data); - nss_ZFreeIf(io->u.item.decrypt.data); - nss_ZFreeIf(io->u.item.derive.data); - nss_ZFreeIf(io->u.item.sign.data); - nss_ZFreeIf(io->u.item.signRecover.data); - nss_ZFreeIf(io->u.item.verify.data); - nss_ZFreeIf(io->u.item.verifyRecover.data); - nss_ZFreeIf(io->u.item.wrap.data); - nss_ZFreeIf(io->u.item.unwrap.data); - nss_ZFreeIf(io->u.item.label.data); - /*nss_ZFreeIf(io->u.item.subject.data); */ - /*nss_ZFreeIf(io->u.item.issuer.data); */ - nss_ZFreeIf(io->u.item.serial.data); - nss_ZFreeIf(io->u.item.modulus.data); - nss_ZFreeIf(io->u.item.exponent.data); - nss_ZFreeIf(io->u.item.privateExponent.data); - nss_ZFreeIf(io->u.item.prime1.data); - nss_ZFreeIf(io->u.item.prime2.data); - nss_ZFreeIf(io->u.item.exponent1.data); - nss_ZFreeIf(io->u.item.exponent2.data); - nss_ZFreeIf(io->u.item.coefficient.data); - break; - } - nss_ZFreeIf(io); - return; } - static ckmkInternalObject * -nss_ckmk_NewInternalObject -( - CK_OBJECT_CLASS objClass, - SecKeychainItemRef itemRef, - SecItemClass itemClass, - CK_RV *pError -) +nss_ckmk_NewInternalObject( + CK_OBJECT_CLASS objClass, + SecKeychainItemRef itemRef, + SecItemClass itemClass, + CK_RV *pError) { - ckmkInternalObject *io = nss_ZNEW(NULL, ckmkInternalObject); + ckmkInternalObject *io = nss_ZNEW(NULL, ckmkInternalObject); - if ((ckmkInternalObject *)NULL == io) { - *pError = CKR_HOST_MEMORY; + if ((ckmkInternalObject *)NULL == io) { + *pError = CKR_HOST_MEMORY; + return io; + } + io->type = ckmkItem; + io->objClass = objClass; + io->u.item.itemRef = itemRef; + io->u.item.itemClass = itemClass; return io; - } - io->type = ckmkItem; - io->objClass = objClass; - io->u.item.itemRef = itemRef; - io->u.item.itemClass = itemClass; - return io; } /* - * Apple doesn't alway have a default keyChain set by the OS, use the + * Apple doesn't alway have a default keyChain set by the OS, use the * SearchList to try to find one. */ static CK_RV -ckmk_GetSafeDefaultKeychain -( - SecKeychainRef *keychainRef -) +ckmk_GetSafeDefaultKeychain( + SecKeychainRef *keychainRef) { - OSStatus macErr; - CFArrayRef searchList = 0; - CK_RV error = CKR_OK; + OSStatus macErr; + CFArrayRef searchList = 0; + CK_RV error = CKR_OK; - macErr = SecKeychainCopyDefault(keychainRef); - if (noErr != macErr) { - int searchCount = 0; - if (errSecNoDefaultKeychain != macErr) { - CKMK_MACERR("Getting default key chain", macErr); - error = CKR_GENERAL_ERROR; - goto loser; - } - /* ok, we don't have a default key chain, find one */ - macErr = SecKeychainCopySearchList(&searchList); + macErr = SecKeychainCopyDefault(keychainRef); if (noErr != macErr) { - CKMK_MACERR("failed to find a keyring searchList", macErr); - error = CKR_DEVICE_REMOVED; - goto loser; + int searchCount = 0; + if (errSecNoDefaultKeychain != macErr) { + CKMK_MACERR("Getting default key chain", macErr); + error = CKR_GENERAL_ERROR; + goto loser; + } + /* ok, we don't have a default key chain, find one */ + macErr = SecKeychainCopySearchList(&searchList); + if (noErr != macErr) { + CKMK_MACERR("failed to find a keyring searchList", macErr); + error = CKR_DEVICE_REMOVED; + goto loser; + } + searchCount = CFArrayGetCount(searchList); + if (searchCount < 1) { + error = CKR_DEVICE_REMOVED; + goto loser; + } + *keychainRef = + (SecKeychainRef)CFRetain(CFArrayGetValueAtIndex(searchList, 0)); + if (0 == *keychainRef) { + error = CKR_DEVICE_REMOVED; + goto loser; + } + /* should we set it as default? */ } - searchCount = CFArrayGetCount(searchList); - if (searchCount < 1) { - error = CKR_DEVICE_REMOVED; - goto loser; - } - *keychainRef = - (SecKeychainRef)CFRetain(CFArrayGetValueAtIndex(searchList, 0)); - if (0 == *keychainRef) { - error = CKR_DEVICE_REMOVED; - goto loser; - } - /* should we set it as default? */ - } loser: - if (0 != searchList) { - CFRelease(searchList); - } - return error; + if (0 != searchList) { + CFRelease(searchList); + } + return error; } static ckmkInternalObject * -nss_ckmk_CreateCertificate -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckmk_CreateCertificate( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSItem value; - ckmkInternalObject *io = NULL; - OSStatus macErr; - SecCertificateRef certRef; - SecKeychainItemRef itemRef; - SecKeychainRef keychainRef; - CSSM_DATA certData; + NSSItem value; + ckmkInternalObject *io = NULL; + OSStatus macErr; + SecCertificateRef certRef; + SecKeychainItemRef itemRef; + SecKeychainRef keychainRef; + CSSM_DATA certData; - *pError = nss_ckmk_GetAttribute(CKA_VALUE, pTemplate, - ulAttributeCount, &value); - if (CKR_OK != *pError) { - goto loser; - } - - certData.Data = value.data; - certData.Length = value.size; - macErr = SecCertificateCreateFromData(&certData, CSSM_CERT_X_509v3, - CSSM_CERT_ENCODING_BER, &certRef); - if (noErr != macErr) { - CKMK_MACERR("Create cert from data Failed", macErr); - *pError = CKR_GENERAL_ERROR; /* need to map macErr */ - goto loser; - } - - *pError = ckmk_GetSafeDefaultKeychain(&keychainRef); - if (CKR_OK != *pError) { - goto loser; - } - - macErr = SecCertificateAddToKeychain( certRef, keychainRef); - itemRef = (SecKeychainItemRef) certRef; - if (errSecDuplicateItem != macErr) { - NSSItem keyID = { NULL, 0 }; - char *nickname = NULL; - CK_RV dummy; + *pError = nss_ckmk_GetAttribute(CKA_VALUE, pTemplate, + ulAttributeCount, &value); + if (CKR_OK != *pError) { + goto loser; + } + certData.Data = value.data; + certData.Length = value.size; + macErr = SecCertificateCreateFromData(&certData, CSSM_CERT_X_509v3, + CSSM_CERT_ENCODING_BER, &certRef); if (noErr != macErr) { - CKMK_MACERR("Add cert to keychain Failed", macErr); - *pError = CKR_GENERAL_ERROR; /* need to map macErr */ - goto loser; + CKMK_MACERR("Create cert from data Failed", macErr); + *pError = CKR_GENERAL_ERROR; /* need to map macErr */ + goto loser; } - /* these two are optional */ - nickname = nss_ckmk_GetStringAttribute(CKA_LABEL, pTemplate, - ulAttributeCount, &dummy); - /* we've added a new one, update the attributes in the key ring */ - if (nickname) { - ckmk_updateAttribute(itemRef, kSecLabelItemAttr, nickname, - strlen(nickname)+1, "Modify Cert Label"); - nss_ZFreeIf(nickname); - } - dummy = nss_ckmk_GetAttribute(CKA_ID, pTemplate, - ulAttributeCount, &keyID); - if (CKR_OK == dummy) { - dummy = ckmk_updateAttribute(itemRef, kSecPublicKeyHashItemAttr, - keyID.data, keyID.size, "Modify Cert ID"); - } - } - io = nss_ckmk_NewInternalObject(CKO_CERTIFICATE, itemRef, - kSecCertificateItemClass, pError); - if ((ckmkInternalObject *)NULL != io) { - itemRef = 0; - } + *pError = ckmk_GetSafeDefaultKeychain(&keychainRef); + if (CKR_OK != *pError) { + goto loser; + } + + macErr = SecCertificateAddToKeychain(certRef, keychainRef); + itemRef = (SecKeychainItemRef)certRef; + if (errSecDuplicateItem != macErr) { + NSSItem keyID = { NULL, 0 }; + char *nickname = NULL; + CK_RV dummy; + + if (noErr != macErr) { + CKMK_MACERR("Add cert to keychain Failed", macErr); + *pError = CKR_GENERAL_ERROR; /* need to map macErr */ + goto loser; + } + /* these two are optional */ + nickname = nss_ckmk_GetStringAttribute(CKA_LABEL, pTemplate, + ulAttributeCount, &dummy); + /* we've added a new one, update the attributes in the key ring */ + if (nickname) { + ckmk_updateAttribute(itemRef, kSecLabelItemAttr, nickname, + strlen(nickname) + 1, "Modify Cert Label"); + nss_ZFreeIf(nickname); + } + dummy = nss_ckmk_GetAttribute(CKA_ID, pTemplate, + ulAttributeCount, &keyID); + if (CKR_OK == dummy) { + dummy = ckmk_updateAttribute(itemRef, kSecPublicKeyHashItemAttr, + keyID.data, keyID.size, "Modify Cert ID"); + } + } + + io = nss_ckmk_NewInternalObject(CKO_CERTIFICATE, itemRef, + kSecCertificateItemClass, pError); + if ((ckmkInternalObject *)NULL != io) { + itemRef = 0; + } loser: - if (0 != itemRef) { - CFRelease(itemRef); - } - if (0 != keychainRef) { - CFRelease(keychainRef); - } + if (0 != itemRef) { + CFRelease(itemRef); + } + if (0 != keychainRef) { + CFRelease(keychainRef); + } - return io; + return io; } /* @@ -1457,8 +1410,8 @@ struct ckmk_AttributeStr { typedef struct ckmk_AttributeStr ckmk_Attribute; /* -** A PKCS#8 private key info object -*/ + ** A PKCS#8 private key info object + */ struct PrivateKeyInfoStr { PLArenaPool *arena; SECItem version; @@ -1470,23 +1423,23 @@ typedef struct PrivateKeyInfoStr PrivateKeyInfo; const SEC_ASN1Template ckmk_RSAPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RSAPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,version) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,modulus) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,publicExponent) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,privateExponent) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,prime1) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,prime2) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,exponent1) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,exponent2) }, - { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey,coefficient) }, - { 0 } -}; + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, version) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, modulus) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, publicExponent) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, privateExponent) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime1) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime2) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent1) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent2) }, + { SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, coefficient) }, + { 0 } +}; const SEC_ASN1Template ckmk_AttributeTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(ckmk_Attribute) }, { SEC_ASN1_OBJECT_ID, offsetof(ckmk_Attribute, attrType) }, - { SEC_ASN1_SET_OF, offsetof(ckmk_Attribute, attrValue), - SEC_AnyTemplate }, + { SEC_ASN1_SET_OF, offsetof(ckmk_Attribute, attrValue), + SEC_AnyTemplate }, { 0 } }; @@ -1499,91 +1452,89 @@ SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) /* ASN1 Templates for new decoder/encoder */ const SEC_ASN1Template ckmk_PrivateKeyInfoTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PrivateKeyInfo) }, - { SEC_ASN1_INTEGER, offsetof(PrivateKeyInfo,version) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(PrivateKeyInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_OCTET_STRING, offsetof(PrivateKeyInfo,privateKey) }, + { SEC_ASN1_INTEGER, offsetof(PrivateKeyInfo, version) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(PrivateKeyInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_OCTET_STRING, offsetof(PrivateKeyInfo, privateKey) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(PrivateKeyInfo, attributes), ckmk_SetOfAttributeTemplate }, + offsetof(PrivateKeyInfo, attributes), ckmk_SetOfAttributeTemplate }, { 0 } }; #define CKMK_PRIVATE_KEY_INFO_VERSION 0 static CK_RV -ckmk_CreateRSAKeyBlob -( - RSAPrivateKey *lk, - NSSItem *keyBlob -) +ckmk_CreateRSAKeyBlob( + RSAPrivateKey *lk, + NSSItem *keyBlob) { - PrivateKeyInfo *pki = NULL; - PLArenaPool *arena = NULL; - SECOidTag algorithm = SEC_OID_UNKNOWN; - void *dummy; - SECStatus rv; - SECItem *encodedKey = NULL; - CK_RV error = CKR_OK; + PrivateKeyInfo *pki = NULL; + PLArenaPool *arena = NULL; + SECOidTag algorithm = SEC_OID_UNKNOWN; + void *dummy; + SECStatus rv; + SECItem *encodedKey = NULL; + CK_RV error = CKR_OK; - arena = PORT_NewArena(2048); /* XXX different size? */ - if(!arena) { - error = CKR_HOST_MEMORY; - goto loser; - } + arena = PORT_NewArena(2048); /* XXX different size? */ + if (!arena) { + error = CKR_HOST_MEMORY; + goto loser; + } - pki = (PrivateKeyInfo*)PORT_ArenaZAlloc(arena, sizeof(PrivateKeyInfo)); - if(!pki) { - error = CKR_HOST_MEMORY; - goto loser; - } - pki->arena = arena; + pki = (PrivateKeyInfo *)PORT_ArenaZAlloc(arena, sizeof(PrivateKeyInfo)); + if (!pki) { + error = CKR_HOST_MEMORY; + goto loser; + } + pki->arena = arena; - dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, - ckmk_RSAPrivateKeyTemplate); - algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION; - - if (!dummy) { - error = CKR_DEVICE_ERROR; /* should map NSS SECError */ - goto loser; - } - - rv = SECOID_SetAlgorithmID(arena, &pki->algorithm, algorithm, - (SECItem*)NULL); - if (rv != SECSuccess) { - error = CKR_DEVICE_ERROR; /* should map NSS SECError */ - goto loser; - } + dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, + ckmk_RSAPrivateKeyTemplate); + algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION; - dummy = SEC_ASN1EncodeInteger(arena, &pki->version, - CKMK_PRIVATE_KEY_INFO_VERSION); - if (!dummy) { - error = CKR_DEVICE_ERROR; /* should map NSS SECError */ - goto loser; - } + if (!dummy) { + error = CKR_DEVICE_ERROR; /* should map NSS SECError */ + goto loser; + } - encodedKey = SEC_ASN1EncodeItem(NULL, NULL, pki, - ckmk_PrivateKeyInfoTemplate); - if (!encodedKey) { - error = CKR_DEVICE_ERROR; - goto loser; - } + rv = SECOID_SetAlgorithmID(arena, &pki->algorithm, algorithm, + (SECItem *)NULL); + if (rv != SECSuccess) { + error = CKR_DEVICE_ERROR; /* should map NSS SECError */ + goto loser; + } - keyBlob->data = nss_ZNEWARRAY(NULL, char, encodedKey->len); - if (NULL == keyBlob->data) { - error = CKR_HOST_MEMORY; - goto loser; - } - nsslibc_memcpy(keyBlob->data, encodedKey->data, encodedKey->len); - keyBlob->size = encodedKey->len; + dummy = SEC_ASN1EncodeInteger(arena, &pki->version, + CKMK_PRIVATE_KEY_INFO_VERSION); + if (!dummy) { + error = CKR_DEVICE_ERROR; /* should map NSS SECError */ + goto loser; + } + + encodedKey = SEC_ASN1EncodeItem(NULL, NULL, pki, + ckmk_PrivateKeyInfoTemplate); + if (!encodedKey) { + error = CKR_DEVICE_ERROR; + goto loser; + } + + keyBlob->data = nss_ZNEWARRAY(NULL, char, encodedKey->len); + if (NULL == keyBlob->data) { + error = CKR_HOST_MEMORY; + goto loser; + } + nsslibc_memcpy(keyBlob->data, encodedKey->data, encodedKey->len); + keyBlob->size = encodedKey->len; loser: - if(arena) { - PORT_FreeArena(arena, PR_TRUE); - } - if (encodedKey) { - SECITEM_FreeItem(encodedKey, PR_TRUE); - } - - return error; + if (arena) { + PORT_FreeArena(arena, PR_TRUE); + } + if (encodedKey) { + SECITEM_FreeItem(encodedKey, PR_TRUE); + } + + return error; } /* * There MUST be a better way to do this. For now, find the key based on the @@ -1591,334 +1542,327 @@ loser: */ #define IMPORTED_NAME "Imported Private Key" static CK_RV -ckmk_FindImportedKey -( - SecKeychainRef keychainRef, - SecItemClass itemClass, - SecKeychainItemRef *outItemRef -) +ckmk_FindImportedKey( + SecKeychainRef keychainRef, + SecItemClass itemClass, + SecKeychainItemRef *outItemRef) { - OSStatus macErr; - SecKeychainSearchRef searchRef = 0; - SecKeychainItemRef newItemRef; - - macErr = SecKeychainSearchCreateFromAttributes(keychainRef, itemClass, - NULL, &searchRef); - if (noErr != macErr) { - CKMK_MACERR("Can't search for Key", macErr); - return CKR_GENERAL_ERROR; - } - while (noErr == SecKeychainSearchCopyNext(searchRef, &newItemRef)) { - SecKeychainAttributeList *attrList = NULL; - SecKeychainAttributeInfo attrInfo; - SecItemAttr itemAttr = kSecKeyPrintName; - PRUint32 attrFormat = 0; OSStatus macErr; + SecKeychainSearchRef searchRef = 0; + SecKeychainItemRef newItemRef; - attrInfo.count = 1; - attrInfo.tag = &itemAttr; - attrInfo.format = &attrFormat; - - macErr = SecKeychainItemCopyAttributesAndData(newItemRef, - &attrInfo, NULL, &attrList, NULL, NULL); - if (noErr == macErr) { - if (nsslibc_memcmp(attrList->attr->data, IMPORTED_NAME, - attrList->attr->length, NULL) == 0) { - *outItemRef = newItemRef; - CFRelease (searchRef); - SecKeychainItemFreeAttributesAndData(attrList, NULL); - return CKR_OK; - } - SecKeychainItemFreeAttributesAndData(attrList, NULL); + macErr = SecKeychainSearchCreateFromAttributes(keychainRef, itemClass, + NULL, &searchRef); + if (noErr != macErr) { + CKMK_MACERR("Can't search for Key", macErr); + return CKR_GENERAL_ERROR; } - CFRelease(newItemRef); - } - CFRelease (searchRef); - return CKR_GENERAL_ERROR; /* we can come up with something better! */ + while (noErr == SecKeychainSearchCopyNext(searchRef, &newItemRef)) { + SecKeychainAttributeList *attrList = NULL; + SecKeychainAttributeInfo attrInfo; + SecItemAttr itemAttr = kSecKeyPrintName; + PRUint32 attrFormat = 0; + OSStatus macErr; + + attrInfo.count = 1; + attrInfo.tag = &itemAttr; + attrInfo.format = &attrFormat; + + macErr = SecKeychainItemCopyAttributesAndData(newItemRef, + &attrInfo, NULL, &attrList, NULL, NULL); + if (noErr == macErr) { + if (nsslibc_memcmp(attrList->attr->data, IMPORTED_NAME, + attrList->attr->length, NULL) == 0) { + *outItemRef = newItemRef; + CFRelease(searchRef); + SecKeychainItemFreeAttributesAndData(attrList, NULL); + return CKR_OK; + } + SecKeychainItemFreeAttributesAndData(attrList, NULL); + } + CFRelease(newItemRef); + } + CFRelease(searchRef); + return CKR_GENERAL_ERROR; /* we can come up with something better! */ } static ckmkInternalObject * -nss_ckmk_CreatePrivateKey -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckmk_CreatePrivateKey( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSItem attribute; - RSAPrivateKey lk; - NSSItem keyID; - char *nickname = NULL; - ckmkInternalObject *io = NULL; - CK_KEY_TYPE keyType; - OSStatus macErr; - SecKeychainItemRef itemRef = 0; - NSSItem keyBlob = { NULL, 0 }; - CFDataRef dataRef = 0; - SecExternalFormat inputFormat = kSecFormatBSAFE; - /*SecExternalFormat inputFormat = kSecFormatOpenSSL; */ - SecExternalItemType itemType = kSecItemTypePrivateKey; - SecKeyImportExportParameters keyParams ; - SecKeychainRef targetKeychain = 0; - unsigned char zero = 0; - CK_RV error; - - keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; - keyParams.flags = 0; - keyParams.passphrase = 0; - keyParams.alertTitle = 0; - keyParams.alertPrompt = 0; - keyParams.accessRef = 0; /* default */ - keyParams.keyUsage = 0; /* will get filled in */ - keyParams.keyAttributes = CSSM_KEYATTR_PERMANENT; /* will get filled in */ - keyType = nss_ckmk_GetULongAttribute - (CKA_KEY_TYPE, pTemplate, ulAttributeCount, pError); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - if (CKK_RSA != keyType) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (ckmkInternalObject *)NULL; - } - if (nss_ckmk_GetBoolAttribute(CKA_DECRYPT, - pTemplate, ulAttributeCount, CK_TRUE)) { - keyParams.keyUsage |= CSSM_KEYUSE_DECRYPT; - } - if (nss_ckmk_GetBoolAttribute(CKA_UNWRAP, - pTemplate, ulAttributeCount, CK_TRUE)) { - keyParams.keyUsage |= CSSM_KEYUSE_UNWRAP; - } - if (nss_ckmk_GetBoolAttribute(CKA_SIGN, - pTemplate, ulAttributeCount, CK_TRUE)) { - keyParams.keyUsage |= CSSM_KEYUSE_SIGN; - } - if (nss_ckmk_GetBoolAttribute(CKA_DERIVE, - pTemplate, ulAttributeCount, CK_FALSE)) { - keyParams.keyUsage |= CSSM_KEYUSE_DERIVE; - } - if (nss_ckmk_GetBoolAttribute(CKA_SENSITIVE, - pTemplate, ulAttributeCount, CK_TRUE)) { - keyParams.keyAttributes |= CSSM_KEYATTR_SENSITIVE; - } - if (nss_ckmk_GetBoolAttribute(CKA_EXTRACTABLE, - pTemplate, ulAttributeCount, CK_TRUE)) { - keyParams.keyAttributes |= CSSM_KEYATTR_EXTRACTABLE; - } + NSSItem attribute; + RSAPrivateKey lk; + NSSItem keyID; + char *nickname = NULL; + ckmkInternalObject *io = NULL; + CK_KEY_TYPE keyType; + OSStatus macErr; + SecKeychainItemRef itemRef = 0; + NSSItem keyBlob = { NULL, 0 }; + CFDataRef dataRef = 0; + SecExternalFormat inputFormat = kSecFormatBSAFE; + /*SecExternalFormat inputFormat = kSecFormatOpenSSL; */ + SecExternalItemType itemType = kSecItemTypePrivateKey; + SecKeyImportExportParameters keyParams; + SecKeychainRef targetKeychain = 0; + unsigned char zero = 0; + CK_RV error; - lk.version.type = siUnsignedInteger; - lk.version.data = &zero; - lk.version.len = 1; + keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; + keyParams.flags = 0; + keyParams.passphrase = 0; + keyParams.alertTitle = 0; + keyParams.alertPrompt = 0; + keyParams.accessRef = 0; /* default */ + keyParams.keyUsage = 0; /* will get filled in */ + keyParams.keyAttributes = CSSM_KEYATTR_PERMANENT; /* will get filled in */ + keyType = nss_ckmk_GetULongAttribute(CKA_KEY_TYPE, pTemplate, ulAttributeCount, pError); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + if (CKK_RSA != keyType) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + return (ckmkInternalObject *)NULL; + } + if (nss_ckmk_GetBoolAttribute(CKA_DECRYPT, + pTemplate, ulAttributeCount, CK_TRUE)) { + keyParams.keyUsage |= CSSM_KEYUSE_DECRYPT; + } + if (nss_ckmk_GetBoolAttribute(CKA_UNWRAP, + pTemplate, ulAttributeCount, CK_TRUE)) { + keyParams.keyUsage |= CSSM_KEYUSE_UNWRAP; + } + if (nss_ckmk_GetBoolAttribute(CKA_SIGN, + pTemplate, ulAttributeCount, CK_TRUE)) { + keyParams.keyUsage |= CSSM_KEYUSE_SIGN; + } + if (nss_ckmk_GetBoolAttribute(CKA_DERIVE, + pTemplate, ulAttributeCount, CK_FALSE)) { + keyParams.keyUsage |= CSSM_KEYUSE_DERIVE; + } + if (nss_ckmk_GetBoolAttribute(CKA_SENSITIVE, + pTemplate, ulAttributeCount, CK_TRUE)) { + keyParams.keyAttributes |= CSSM_KEYATTR_SENSITIVE; + } + if (nss_ckmk_GetBoolAttribute(CKA_EXTRACTABLE, + pTemplate, ulAttributeCount, CK_TRUE)) { + keyParams.keyAttributes |= CSSM_KEYATTR_EXTRACTABLE; + } - *pError = nss_ckmk_GetAttribute(CKA_MODULUS, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.modulus.type = siUnsignedInteger; - lk.modulus.data = attribute.data; - lk.modulus.len = attribute.size; + lk.version.type = siUnsignedInteger; + lk.version.data = &zero; + lk.version.len = 1; - *pError = nss_ckmk_GetAttribute(CKA_PUBLIC_EXPONENT, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.publicExponent.type = siUnsignedInteger; - lk.publicExponent.data = attribute.data; - lk.publicExponent.len = attribute.size; + *pError = nss_ckmk_GetAttribute(CKA_MODULUS, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.modulus.type = siUnsignedInteger; + lk.modulus.data = attribute.data; + lk.modulus.len = attribute.size; - *pError = nss_ckmk_GetAttribute(CKA_PRIVATE_EXPONENT, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.privateExponent.type = siUnsignedInteger; - lk.privateExponent.data = attribute.data; - lk.privateExponent.len = attribute.size; + *pError = nss_ckmk_GetAttribute(CKA_PUBLIC_EXPONENT, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.publicExponent.type = siUnsignedInteger; + lk.publicExponent.data = attribute.data; + lk.publicExponent.len = attribute.size; - *pError = nss_ckmk_GetAttribute(CKA_PRIME_1, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.prime1.type = siUnsignedInteger; - lk.prime1.data = attribute.data; - lk.prime1.len = attribute.size; + *pError = nss_ckmk_GetAttribute(CKA_PRIVATE_EXPONENT, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.privateExponent.type = siUnsignedInteger; + lk.privateExponent.data = attribute.data; + lk.privateExponent.len = attribute.size; - *pError = nss_ckmk_GetAttribute(CKA_PRIME_2, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.prime2.type = siUnsignedInteger; - lk.prime2.data = attribute.data; - lk.prime2.len = attribute.size; + *pError = nss_ckmk_GetAttribute(CKA_PRIME_1, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.prime1.type = siUnsignedInteger; + lk.prime1.data = attribute.data; + lk.prime1.len = attribute.size; - *pError = nss_ckmk_GetAttribute(CKA_EXPONENT_1, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.exponent1.type = siUnsignedInteger; - lk.exponent1.data = attribute.data; - lk.exponent1.len = attribute.size; + *pError = nss_ckmk_GetAttribute(CKA_PRIME_2, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.prime2.type = siUnsignedInteger; + lk.prime2.data = attribute.data; + lk.prime2.len = attribute.size; - *pError = nss_ckmk_GetAttribute(CKA_EXPONENT_2, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.exponent2.type = siUnsignedInteger; - lk.exponent2.data = attribute.data; - lk.exponent2.len = attribute.size; + *pError = nss_ckmk_GetAttribute(CKA_EXPONENT_1, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.exponent1.type = siUnsignedInteger; + lk.exponent1.data = attribute.data; + lk.exponent1.len = attribute.size; - *pError = nss_ckmk_GetAttribute(CKA_COEFFICIENT, pTemplate, - ulAttributeCount, &attribute); - if (CKR_OK != *pError) { - return (ckmkInternalObject *)NULL; - } - lk.coefficient.type = siUnsignedInteger; - lk.coefficient.data = attribute.data; - lk.coefficient.len = attribute.size; + *pError = nss_ckmk_GetAttribute(CKA_EXPONENT_2, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.exponent2.type = siUnsignedInteger; + lk.exponent2.data = attribute.data; + lk.exponent2.len = attribute.size; - /* ASN1 Encode the pkcs8 structure... look at softoken to see how this - * is done... */ - error = ckmk_CreateRSAKeyBlob(&lk, &keyBlob); - if (CKR_OK != error) { - goto loser; - } + *pError = nss_ckmk_GetAttribute(CKA_COEFFICIENT, pTemplate, + ulAttributeCount, &attribute); + if (CKR_OK != *pError) { + return (ckmkInternalObject *)NULL; + } + lk.coefficient.type = siUnsignedInteger; + lk.coefficient.data = attribute.data; + lk.coefficient.len = attribute.size; - dataRef = CFDataCreate(NULL, (UInt8 *)keyBlob.data, keyBlob.size); - if (0 == dataRef) { - *pError = CKR_HOST_MEMORY; - goto loser; - } + /* ASN1 Encode the pkcs8 structure... look at softoken to see how this + * is done... */ + error = ckmk_CreateRSAKeyBlob(&lk, &keyBlob); + if (CKR_OK != error) { + goto loser; + } - *pError == ckmk_GetSafeDefaultKeychain(&targetKeychain); - if (CKR_OK != *pError) { - goto loser; - } + dataRef = CFDataCreate(NULL, (UInt8 *)keyBlob.data, keyBlob.size); + if (0 == dataRef) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + *pError == ckmk_GetSafeDefaultKeychain(&targetKeychain); + if (CKR_OK != *pError) { + goto loser; + } - /* the itemArray that is returned is useless. the item does not - * is 'not on the key chain' so none of the modify calls work on it. - * It also has a key that isn't the same key as the one in the actual - * key chain. In short it isn't the item we want, and it gives us zero - * information about the item we want, so don't even bother with it... - */ - macErr = SecKeychainItemImport(dataRef, NULL, &inputFormat, &itemType, 0, - &keyParams, targetKeychain, NULL); - if (noErr != macErr) { - CKMK_MACERR("Import Private Key", macErr); - *pError = CKR_GENERAL_ERROR; - goto loser; - } + /* the itemArray that is returned is useless. the item does not + * is 'not on the key chain' so none of the modify calls work on it. + * It also has a key that isn't the same key as the one in the actual + * key chain. In short it isn't the item we want, and it gives us zero + * information about the item we want, so don't even bother with it... + */ + macErr = SecKeychainItemImport(dataRef, NULL, &inputFormat, &itemType, 0, + &keyParams, targetKeychain, NULL); + if (noErr != macErr) { + CKMK_MACERR("Import Private Key", macErr); + *pError = CKR_GENERAL_ERROR; + goto loser; + } - *pError = ckmk_FindImportedKey(targetKeychain, - CSSM_DL_DB_RECORD_PRIVATE_KEY, - &itemRef); - if (CKR_OK != *pError) { + *pError = ckmk_FindImportedKey(targetKeychain, + CSSM_DL_DB_RECORD_PRIVATE_KEY, + &itemRef); + if (CKR_OK != *pError) { #ifdef DEBUG - fprintf(stderr,"couldn't find key in keychain \n"); + fprintf(stderr, "couldn't find key in keychain \n"); #endif - goto loser; - } + goto loser; + } - - /* set the CKA_ID and the CKA_LABEL */ - error = nss_ckmk_GetAttribute(CKA_ID, pTemplate, + /* set the CKA_ID and the CKA_LABEL */ + error = nss_ckmk_GetAttribute(CKA_ID, pTemplate, ulAttributeCount, &keyID); - if (CKR_OK == error) { - error = ckmk_updateAttribute(itemRef, kSecKeyLabel, - keyID.data, keyID.size, "Modify Key ID"); + if (CKR_OK == error) { + error = ckmk_updateAttribute(itemRef, kSecKeyLabel, + keyID.data, keyID.size, "Modify Key ID"); #ifdef DEBUG - itemdump("key id: ", keyID.data, keyID.size, error); + itemdump("key id: ", keyID.data, keyID.size, error); #endif - } - nickname = nss_ckmk_GetStringAttribute(CKA_LABEL, pTemplate, - ulAttributeCount, &error); - if (nickname) { - ckmk_updateAttribute(itemRef, kSecKeyPrintName, nickname, - strlen(nickname)+1, "Modify Key Label"); - } else { + } + nickname = nss_ckmk_GetStringAttribute(CKA_LABEL, pTemplate, + ulAttributeCount, &error); + if (nickname) { + ckmk_updateAttribute(itemRef, kSecKeyPrintName, nickname, + strlen(nickname) + 1, "Modify Key Label"); + } + else { #define DEFAULT_NICKNAME "NSS Imported Key" - ckmk_updateAttribute(itemRef, kSecKeyPrintName, DEFAULT_NICKNAME, - sizeof(DEFAULT_NICKNAME), "Modify Key Label"); - } + ckmk_updateAttribute(itemRef, kSecKeyPrintName, DEFAULT_NICKNAME, + sizeof(DEFAULT_NICKNAME), "Modify Key Label"); + } - io = nss_ckmk_NewInternalObject(CKO_PRIVATE_KEY, itemRef, - CSSM_DL_DB_RECORD_PRIVATE_KEY, pError); - if ((ckmkInternalObject *)NULL == io) { - CFRelease(itemRef); - } + io = nss_ckmk_NewInternalObject(CKO_PRIVATE_KEY, itemRef, + CSSM_DL_DB_RECORD_PRIVATE_KEY, pError); + if ((ckmkInternalObject *)NULL == io) { + CFRelease(itemRef); + } - return io; + return io; loser: - /* free the key blob */ - if (keyBlob.data) { - nss_ZFreeIf(keyBlob.data); - } - if (0 != targetKeychain) { - CFRelease(targetKeychain); - } - if (0 != dataRef) { - CFRelease(dataRef); - } - return io; + /* free the key blob */ + if (keyBlob.data) { + nss_ZFreeIf(keyBlob.data); + } + if (0 != targetKeychain) { + CFRelease(targetKeychain); + } + if (0 != dataRef) { + CFRelease(dataRef); + } + return io; } - NSS_EXTERN NSSCKMDObject * -nss_ckmk_CreateObject -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nss_ckmk_CreateObject( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - CK_OBJECT_CLASS objClass; - ckmkInternalObject *io = NULL; - CK_BBOOL isToken; + CK_OBJECT_CLASS objClass; + ckmkInternalObject *io = NULL; + CK_BBOOL isToken; - /* - * only create token objects - */ - isToken = nss_ckmk_GetBoolAttribute(CKA_TOKEN, pTemplate, - ulAttributeCount, CK_FALSE); - if (!isToken) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (NSSCKMDObject *) NULL; - } + /* + * only create token objects + */ + isToken = nss_ckmk_GetBoolAttribute(CKA_TOKEN, pTemplate, + ulAttributeCount, CK_FALSE); + if (!isToken) { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + return (NSSCKMDObject *)NULL; + } - /* - * only create keys and certs. - */ - objClass = nss_ckmk_GetULongAttribute(CKA_CLASS, pTemplate, - ulAttributeCount, pError); - if (CKR_OK != *pError) { - return (NSSCKMDObject *) NULL; - } + /* + * only create keys and certs. + */ + objClass = nss_ckmk_GetULongAttribute(CKA_CLASS, pTemplate, + ulAttributeCount, pError); + if (CKR_OK != *pError) { + return (NSSCKMDObject *)NULL; + } #ifdef notdef - if (objClass == CKO_PUBLIC_KEY) { - return CKR_OK; /* fake public key creation, happens as a side effect of - * private key creation */ - } + if (objClass == CKO_PUBLIC_KEY) { + return CKR_OK; /* fake public key creation, happens as a side effect of + * private key creation */ + } #endif - if (objClass == CKO_CERTIFICATE) { - io = nss_ckmk_CreateCertificate(fwSession, pTemplate, - ulAttributeCount, pError); - } else if (objClass == CKO_PRIVATE_KEY) { - io = nss_ckmk_CreatePrivateKey(fwSession, pTemplate, - ulAttributeCount, pError); - } else { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - } + if (objClass == CKO_CERTIFICATE) { + io = nss_ckmk_CreateCertificate(fwSession, pTemplate, + ulAttributeCount, pError); + } + else if (objClass == CKO_PRIVATE_KEY) { + io = nss_ckmk_CreatePrivateKey(fwSession, pTemplate, + ulAttributeCount, pError); + } + else { + *pError = CKR_ATTRIBUTE_VALUE_INVALID; + } - if ((ckmkInternalObject *)NULL == io) { - return (NSSCKMDObject *) NULL; - } - return nss_ckmk_CreateMDObject(NULL, io, pError); + if ((ckmkInternalObject *)NULL == io) { + return (NSSCKMDObject *)NULL; + } + return nss_ckmk_CreateMDObject(NULL, io, pError); } diff --git a/security/nss/lib/ckfw/nssmkey/mrsa.c b/security/nss/lib/ckfw/nssmkey/mrsa.c index 8cf46adbc8b1..00175b47a816 100644 --- a/security/nss/lib/ckfw/nssmkey/mrsa.c +++ b/security/nss/lib/ckfw/nssmkey/mrsa.c @@ -9,196 +9,183 @@ * to NSS's S/MIME code. The following two functions currently are not * part of the SecKey.h interface. */ -OSStatus -SecKeyGetCredentials -( - SecKeyRef keyRef, - CSSM_ACL_AUTHORIZATION_TAG authTag, - int type, - const CSSM_ACCESS_CREDENTIALS **creds -); +OSStatus +SecKeyGetCredentials( + SecKeyRef keyRef, + CSSM_ACL_AUTHORIZATION_TAG authTag, + int type, + const CSSM_ACCESS_CREDENTIALS **creds); /* this function could be implemented using 'SecKeychainItemCopyKeychain' and * 'SecKeychainGetCSPHandle' */ -OSStatus -SecKeyGetCSPHandle -( - SecKeyRef keyRef, - CSSM_CSP_HANDLE *cspHandle -); +OSStatus +SecKeyGetCSPHandle( + SecKeyRef keyRef, + CSSM_CSP_HANDLE *cspHandle); - -typedef struct ckmkInternalCryptoOperationRSAPrivStr - ckmkInternalCryptoOperationRSAPriv; -struct ckmkInternalCryptoOperationRSAPrivStr -{ - NSSCKMDCryptoOperation mdOperation; - NSSCKMDMechanism *mdMechanism; - ckmkInternalObject *iKey; - NSSItem *buffer; - CSSM_CC_HANDLE cssmContext; +typedef struct ckmkInternalCryptoOperationRSAPrivStr + ckmkInternalCryptoOperationRSAPriv; +struct ckmkInternalCryptoOperationRSAPrivStr { + NSSCKMDCryptoOperation mdOperation; + NSSCKMDMechanism *mdMechanism; + ckmkInternalObject *iKey; + NSSItem *buffer; + CSSM_CC_HANDLE cssmContext; }; typedef enum { - CKMK_DECRYPT, - CKMK_SIGN + CKMK_DECRYPT, + CKMK_SIGN } ckmkRSAOpType; /* * ckmk_mdCryptoOperationRSAPriv_Create */ static NSSCKMDCryptoOperation * -ckmk_mdCryptoOperationRSAPriv_Create -( - const NSSCKMDCryptoOperation *proto, - NSSCKMDMechanism *mdMechanism, - NSSCKMDObject *mdKey, - ckmkRSAOpType type, - CK_RV *pError -) +ckmk_mdCryptoOperationRSAPriv_Create( + const NSSCKMDCryptoOperation *proto, + NSSCKMDMechanism *mdMechanism, + NSSCKMDObject *mdKey, + ckmkRSAOpType type, + CK_RV *pError) { - ckmkInternalObject *iKey = (ckmkInternalObject *)mdKey->etc; - const NSSItem *classItem = nss_ckmk_FetchAttribute(iKey, CKA_CLASS, pError); - const NSSItem *keyType = nss_ckmk_FetchAttribute(iKey, CKA_KEY_TYPE, pError); - ckmkInternalCryptoOperationRSAPriv *iOperation; - SecKeyRef privateKey; - OSStatus macErr; - CSSM_RETURN cssmErr; - const CSSM_KEY *cssmKey; - CSSM_CSP_HANDLE cspHandle; - const CSSM_ACCESS_CREDENTIALS *creds = NULL; - CSSM_CC_HANDLE cssmContext; - CSSM_ACL_AUTHORIZATION_TAG authType; + ckmkInternalObject *iKey = (ckmkInternalObject *)mdKey->etc; + const NSSItem *classItem = nss_ckmk_FetchAttribute(iKey, CKA_CLASS, pError); + const NSSItem *keyType = nss_ckmk_FetchAttribute(iKey, CKA_KEY_TYPE, pError); + ckmkInternalCryptoOperationRSAPriv *iOperation; + SecKeyRef privateKey; + OSStatus macErr; + CSSM_RETURN cssmErr; + const CSSM_KEY *cssmKey; + CSSM_CSP_HANDLE cspHandle; + const CSSM_ACCESS_CREDENTIALS *creds = NULL; + CSSM_CC_HANDLE cssmContext; + CSSM_ACL_AUTHORIZATION_TAG authType; - /* make sure we have the right objects */ - if (((const NSSItem *)NULL == classItem) || - (sizeof(CK_OBJECT_CLASS) != classItem->size) || - (CKO_PRIVATE_KEY != *(CK_OBJECT_CLASS *)classItem->data) || - ((const NSSItem *)NULL == keyType) || - (sizeof(CK_KEY_TYPE) != keyType->size) || - (CKK_RSA != *(CK_KEY_TYPE *)keyType->data)) { - *pError = CKR_KEY_TYPE_INCONSISTENT; - return (NSSCKMDCryptoOperation *)NULL; - } + /* make sure we have the right objects */ + if (((const NSSItem *)NULL == classItem) || + (sizeof(CK_OBJECT_CLASS) != classItem->size) || + (CKO_PRIVATE_KEY != *(CK_OBJECT_CLASS *)classItem->data) || + ((const NSSItem *)NULL == keyType) || + (sizeof(CK_KEY_TYPE) != keyType->size) || + (CKK_RSA != *(CK_KEY_TYPE *)keyType->data)) { + *pError = CKR_KEY_TYPE_INCONSISTENT; + return (NSSCKMDCryptoOperation *)NULL; + } - privateKey = (SecKeyRef) iKey->u.item.itemRef; - macErr = SecKeyGetCSSMKey(privateKey, &cssmKey); - if (noErr != macErr) { - CKMK_MACERR("Getting CSSM Key", macErr); - *pError = CKR_KEY_HANDLE_INVALID; - return (NSSCKMDCryptoOperation *)NULL; - } - macErr = SecKeyGetCSPHandle(privateKey, &cspHandle); - if (noErr != macErr) { - CKMK_MACERR("Getting CSP for Key", macErr); - *pError = CKR_KEY_HANDLE_INVALID; - return (NSSCKMDCryptoOperation *)NULL; - } - switch (type) { - case CKMK_DECRYPT: - authType = CSSM_ACL_AUTHORIZATION_DECRYPT; - break; - case CKMK_SIGN: - authType = CSSM_ACL_AUTHORIZATION_SIGN; - break; - default: - *pError = CKR_GENERAL_ERROR; + privateKey = (SecKeyRef)iKey->u.item.itemRef; + macErr = SecKeyGetCSSMKey(privateKey, &cssmKey); + if (noErr != macErr) { + CKMK_MACERR("Getting CSSM Key", macErr); + *pError = CKR_KEY_HANDLE_INVALID; + return (NSSCKMDCryptoOperation *)NULL; + } + macErr = SecKeyGetCSPHandle(privateKey, &cspHandle); + if (noErr != macErr) { + CKMK_MACERR("Getting CSP for Key", macErr); + *pError = CKR_KEY_HANDLE_INVALID; + return (NSSCKMDCryptoOperation *)NULL; + } + switch (type) { + case CKMK_DECRYPT: + authType = CSSM_ACL_AUTHORIZATION_DECRYPT; + break; + case CKMK_SIGN: + authType = CSSM_ACL_AUTHORIZATION_SIGN; + break; + default: + *pError = CKR_GENERAL_ERROR; #ifdef DEBUG - fprintf(stderr,"RSAPriv_Create: bad type = %d\n", type); + fprintf(stderr, "RSAPriv_Create: bad type = %d\n", type); #endif - return (NSSCKMDCryptoOperation *)NULL; - } + return (NSSCKMDCryptoOperation *)NULL; + } - macErr = SecKeyGetCredentials(privateKey, authType, 0, &creds); - if (noErr != macErr) { - CKMK_MACERR("Getting Credentials for Key", macErr); - *pError = CKR_KEY_HANDLE_INVALID; - return (NSSCKMDCryptoOperation *)NULL; - } - - switch (type) { - case CKMK_DECRYPT: - cssmErr = CSSM_CSP_CreateAsymmetricContext(cspHandle, CSSM_ALGID_RSA, - creds, cssmKey, CSSM_PADDING_PKCS1, &cssmContext); - break; - case CKMK_SIGN: - cssmErr = CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_RSA, - creds, cssmKey, &cssmContext); - break; - default: - *pError = CKR_GENERAL_ERROR; + macErr = SecKeyGetCredentials(privateKey, authType, 0, &creds); + if (noErr != macErr) { + CKMK_MACERR("Getting Credentials for Key", macErr); + *pError = CKR_KEY_HANDLE_INVALID; + return (NSSCKMDCryptoOperation *)NULL; + } + + switch (type) { + case CKMK_DECRYPT: + cssmErr = CSSM_CSP_CreateAsymmetricContext(cspHandle, CSSM_ALGID_RSA, + creds, cssmKey, CSSM_PADDING_PKCS1, &cssmContext); + break; + case CKMK_SIGN: + cssmErr = CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_RSA, + creds, cssmKey, &cssmContext); + break; + default: + *pError = CKR_GENERAL_ERROR; #ifdef DEBUG - fprintf(stderr,"RSAPriv_Create: bad type = %d\n", type); + fprintf(stderr, "RSAPriv_Create: bad type = %d\n", type); #endif - return (NSSCKMDCryptoOperation *)NULL; - } - if (noErr != cssmErr) { - CKMK_MACERR("Getting Context for Key", cssmErr); - *pError = CKR_GENERAL_ERROR; - return (NSSCKMDCryptoOperation *)NULL; - } + return (NSSCKMDCryptoOperation *)NULL; + } + if (noErr != cssmErr) { + CKMK_MACERR("Getting Context for Key", cssmErr); + *pError = CKR_GENERAL_ERROR; + return (NSSCKMDCryptoOperation *)NULL; + } - iOperation = nss_ZNEW(NULL, ckmkInternalCryptoOperationRSAPriv); - if ((ckmkInternalCryptoOperationRSAPriv *)NULL == iOperation) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDCryptoOperation *)NULL; - } - iOperation->mdMechanism = mdMechanism; - iOperation->iKey = iKey; - iOperation->cssmContext = cssmContext; + iOperation = nss_ZNEW(NULL, ckmkInternalCryptoOperationRSAPriv); + if ((ckmkInternalCryptoOperationRSAPriv *)NULL == iOperation) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDCryptoOperation *)NULL; + } + iOperation->mdMechanism = mdMechanism; + iOperation->iKey = iKey; + iOperation->cssmContext = cssmContext; - nsslibc_memcpy(&iOperation->mdOperation, - proto, sizeof(NSSCKMDCryptoOperation)); - iOperation->mdOperation.etc = iOperation; + nsslibc_memcpy(&iOperation->mdOperation, + proto, sizeof(NSSCKMDCryptoOperation)); + iOperation->mdOperation.etc = iOperation; - return &iOperation->mdOperation; + return &iOperation->mdOperation; } static void -ckmk_mdCryptoOperationRSAPriv_Destroy -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdCryptoOperationRSAPriv_Destroy( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - ckmkInternalCryptoOperationRSAPriv *iOperation = - (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; + ckmkInternalCryptoOperationRSAPriv *iOperation = + (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; - if (iOperation->buffer) { - nssItem_Destroy(iOperation->buffer); - } - if (iOperation->cssmContext) { - CSSM_DeleteContext(iOperation->cssmContext); - } - nss_ZFreeIf(iOperation); - return; + if (iOperation->buffer) { + nssItem_Destroy(iOperation->buffer); + } + if (iOperation->cssmContext) { + CSSM_DeleteContext(iOperation->cssmContext); + } + nss_ZFreeIf(iOperation); + return; } static CK_ULONG -ckmk_mdCryptoOperationRSA_GetFinalLength -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdCryptoOperationRSA_GetFinalLength( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - ckmkInternalCryptoOperationRSAPriv *iOperation = - (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; - const NSSItem *modulus = - nss_ckmk_FetchAttribute(iOperation->iKey, CKA_MODULUS, pError); + ckmkInternalCryptoOperationRSAPriv *iOperation = + (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; + const NSSItem *modulus = + nss_ckmk_FetchAttribute(iOperation->iKey, CKA_MODULUS, pError); - return modulus->size; + return modulus->size; } - /* * ckmk_mdCryptoOperationRSADecrypt_GetOperationLength * we won't know the length until we actually decrypt the @@ -206,105 +193,101 @@ ckmk_mdCryptoOperationRSA_GetFinalLength * the block, we'll save if for when the block is asked for */ static CK_ULONG -ckmk_mdCryptoOperationRSADecrypt_GetOperationLength -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *input, - CK_RV *pError -) +ckmk_mdCryptoOperationRSADecrypt_GetOperationLength( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *input, + CK_RV *pError) { - ckmkInternalCryptoOperationRSAPriv *iOperation = - (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; - CSSM_DATA cssmInput; - CSSM_DATA cssmOutput = { 0, NULL }; - PRUint32 bytesDecrypted; - CSSM_DATA remainder = { 0, NULL }; - NSSItem output; - CSSM_RETURN cssmErr; + ckmkInternalCryptoOperationRSAPriv *iOperation = + (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; + CSSM_DATA cssmInput; + CSSM_DATA cssmOutput = { 0, NULL }; + PRUint32 bytesDecrypted; + CSSM_DATA remainder = { 0, NULL }; + NSSItem output; + CSSM_RETURN cssmErr; + + if (iOperation->buffer) { + return iOperation->buffer->size; + } + + cssmInput.Data = input->data; + cssmInput.Length = input->size; + + cssmErr = CSSM_DecryptData(iOperation->cssmContext, + &cssmInput, 1, &cssmOutput, 1, + &bytesDecrypted, &remainder); + if (CSSM_OK != cssmErr) { + CKMK_MACERR("Decrypt Failed", cssmErr); + *pError = CKR_DATA_INVALID; + return 0; + } + /* we didn't suppy any buffers, so it should all be in remainder */ + output.data = nss_ZNEWARRAY(NULL, char, bytesDecrypted + remainder.Length); + if (NULL == output.data) { + free(cssmOutput.Data); + free(remainder.Data); + *pError = CKR_HOST_MEMORY; + return 0; + } + output.size = bytesDecrypted + remainder.Length; + + if (0 != bytesDecrypted) { + nsslibc_memcpy(output.data, cssmOutput.Data, bytesDecrypted); + free(cssmOutput.Data); + } + if (0 != remainder.Length) { + nsslibc_memcpy(((char *)output.data) + bytesDecrypted, + remainder.Data, remainder.Length); + free(remainder.Data); + } + + iOperation->buffer = nssItem_Duplicate(&output, NULL, NULL); + nss_ZFreeIf(output.data); + if ((NSSItem *)NULL == iOperation->buffer) { + *pError = CKR_HOST_MEMORY; + return 0; + } - if (iOperation->buffer) { return iOperation->buffer->size; - } - - cssmInput.Data = input->data; - cssmInput.Length = input->size; - - cssmErr = CSSM_DecryptData(iOperation->cssmContext, - &cssmInput, 1, &cssmOutput, 1, - &bytesDecrypted, &remainder); - if (CSSM_OK != cssmErr) { - CKMK_MACERR("Decrypt Failed", cssmErr); - *pError = CKR_DATA_INVALID; - return 0; - } - /* we didn't suppy any buffers, so it should all be in remainder */ - output.data = nss_ZNEWARRAY(NULL, char, bytesDecrypted + remainder.Length); - if (NULL == output.data) { - free(cssmOutput.Data); - free(remainder.Data); - *pError = CKR_HOST_MEMORY; - return 0; - } - output.size = bytesDecrypted + remainder.Length; - - if (0 != bytesDecrypted) { - nsslibc_memcpy(output.data, cssmOutput.Data, bytesDecrypted); - free(cssmOutput.Data); - } - if (0 != remainder.Length) { - nsslibc_memcpy(((char *)output.data)+bytesDecrypted, - remainder.Data, remainder.Length); - free(remainder.Data); - } - - iOperation->buffer = nssItem_Duplicate(&output, NULL, NULL); - nss_ZFreeIf(output.data); - if ((NSSItem *) NULL == iOperation->buffer) { - *pError = CKR_HOST_MEMORY; - return 0; - } - - return iOperation->buffer->size; } /* * ckmk_mdCryptoOperationRSADecrypt_UpdateFinal * - * NOTE: ckmk_mdCryptoOperationRSADecrypt_GetOperationLength is presumed to + * NOTE: ckmk_mdCryptoOperationRSADecrypt_GetOperationLength is presumed to * have been called previously. */ static CK_RV -ckmk_mdCryptoOperationRSADecrypt_UpdateFinal -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *input, - NSSItem *output -) +ckmk_mdCryptoOperationRSADecrypt_UpdateFinal( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *input, + NSSItem *output) { - ckmkInternalCryptoOperationRSAPriv *iOperation = - (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; - NSSItem *buffer = iOperation->buffer; + ckmkInternalCryptoOperationRSAPriv *iOperation = + (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; + NSSItem *buffer = iOperation->buffer; - if ((NSSItem *)NULL == buffer) { - return CKR_GENERAL_ERROR; - } - nsslibc_memcpy(output->data, buffer->data, buffer->size); - output->size = buffer->size; - return CKR_OK; + if ((NSSItem *)NULL == buffer) { + return CKR_GENERAL_ERROR; + } + nsslibc_memcpy(output->data, buffer->data, buffer->size); + output->size = buffer->size; + return CKR_OK; } /* @@ -312,199 +295,185 @@ ckmk_mdCryptoOperationRSADecrypt_UpdateFinal * */ static CK_RV -ckmk_mdCryptoOperationRSASign_UpdateFinal -( - NSSCKMDCryptoOperation *mdOperation, - NSSCKFWCryptoOperation *fwOperation, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - const NSSItem *input, - NSSItem *output -) +ckmk_mdCryptoOperationRSASign_UpdateFinal( + NSSCKMDCryptoOperation *mdOperation, + NSSCKFWCryptoOperation *fwOperation, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + const NSSItem *input, + NSSItem *output) { - ckmkInternalCryptoOperationRSAPriv *iOperation = - (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; - CSSM_DATA cssmInput; - CSSM_DATA cssmOutput = { 0, NULL }; - CSSM_RETURN cssmErr; + ckmkInternalCryptoOperationRSAPriv *iOperation = + (ckmkInternalCryptoOperationRSAPriv *)mdOperation->etc; + CSSM_DATA cssmInput; + CSSM_DATA cssmOutput = { 0, NULL }; + CSSM_RETURN cssmErr; - cssmInput.Data = input->data; - cssmInput.Length = input->size; + cssmInput.Data = input->data; + cssmInput.Length = input->size; - cssmErr = CSSM_SignData(iOperation->cssmContext, &cssmInput, 1, - CSSM_ALGID_NONE, &cssmOutput); - if (CSSM_OK != cssmErr) { - CKMK_MACERR("Signed Failed", cssmErr); - return CKR_FUNCTION_FAILED; - } - if (cssmOutput.Length > output->size) { + cssmErr = CSSM_SignData(iOperation->cssmContext, &cssmInput, 1, + CSSM_ALGID_NONE, &cssmOutput); + if (CSSM_OK != cssmErr) { + CKMK_MACERR("Signed Failed", cssmErr); + return CKR_FUNCTION_FAILED; + } + if (cssmOutput.Length > output->size) { + free(cssmOutput.Data); + return CKR_BUFFER_TOO_SMALL; + } + nsslibc_memcpy(output->data, cssmOutput.Data, cssmOutput.Length); free(cssmOutput.Data); - return CKR_BUFFER_TOO_SMALL; - } - nsslibc_memcpy(output->data, cssmOutput.Data, cssmOutput.Length); - free(cssmOutput.Data); - output->size = cssmOutput.Length; + output->size = cssmOutput.Length; - return CKR_OK; + return CKR_OK; } - NSS_IMPLEMENT_DATA const NSSCKMDCryptoOperation -ckmk_mdCryptoOperationRSADecrypt_proto = { - NULL, /* etc */ - ckmk_mdCryptoOperationRSAPriv_Destroy, - NULL, /* GetFinalLengh - not needed for one shot Decrypt/Encrypt */ - ckmk_mdCryptoOperationRSADecrypt_GetOperationLength, - NULL, /* Final - not needed for one shot operation */ - NULL, /* Update - not needed for one shot operation */ - NULL, /* DigetUpdate - not needed for one shot operation */ - ckmk_mdCryptoOperationRSADecrypt_UpdateFinal, - NULL, /* UpdateCombo - not needed for one shot operation */ - NULL, /* DigetKey - not needed for one shot operation */ - (void *)NULL /* null terminator */ -}; + ckmk_mdCryptoOperationRSADecrypt_proto = { + NULL, /* etc */ + ckmk_mdCryptoOperationRSAPriv_Destroy, + NULL, /* GetFinalLengh - not needed for one shot Decrypt/Encrypt */ + ckmk_mdCryptoOperationRSADecrypt_GetOperationLength, + NULL, /* Final - not needed for one shot operation */ + NULL, /* Update - not needed for one shot operation */ + NULL, /* DigetUpdate - not needed for one shot operation */ + ckmk_mdCryptoOperationRSADecrypt_UpdateFinal, + NULL, /* UpdateCombo - not needed for one shot operation */ + NULL, /* DigetKey - not needed for one shot operation */ + (void *)NULL /* null terminator */ + }; NSS_IMPLEMENT_DATA const NSSCKMDCryptoOperation -ckmk_mdCryptoOperationRSASign_proto = { - NULL, /* etc */ - ckmk_mdCryptoOperationRSAPriv_Destroy, - ckmk_mdCryptoOperationRSA_GetFinalLength, - NULL, /* GetOperationLengh - not needed for one shot Sign/Verify */ - NULL, /* Final - not needed for one shot operation */ - NULL, /* Update - not needed for one shot operation */ - NULL, /* DigetUpdate - not needed for one shot operation */ - ckmk_mdCryptoOperationRSASign_UpdateFinal, - NULL, /* UpdateCombo - not needed for one shot operation */ - NULL, /* DigetKey - not needed for one shot operation */ - (void *)NULL /* null terminator */ -}; + ckmk_mdCryptoOperationRSASign_proto = { + NULL, /* etc */ + ckmk_mdCryptoOperationRSAPriv_Destroy, + ckmk_mdCryptoOperationRSA_GetFinalLength, + NULL, /* GetOperationLengh - not needed for one shot Sign/Verify */ + NULL, /* Final - not needed for one shot operation */ + NULL, /* Update - not needed for one shot operation */ + NULL, /* DigetUpdate - not needed for one shot operation */ + ckmk_mdCryptoOperationRSASign_UpdateFinal, + NULL, /* UpdateCombo - not needed for one shot operation */ + NULL, /* DigetKey - not needed for one shot operation */ + (void *)NULL /* null terminator */ + }; /********** NSSCKMDMechansim functions ***********************/ /* * ckmk_mdMechanismRSA_Destroy */ static void -ckmk_mdMechanismRSA_Destroy -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdMechanismRSA_Destroy( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nss_ZFreeIf(fwMechanism); + nss_ZFreeIf(fwMechanism); } /* * ckmk_mdMechanismRSA_GetMinKeySize */ static CK_ULONG -ckmk_mdMechanismRSA_GetMinKeySize -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdMechanismRSA_GetMinKeySize( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return 384; + return 384; } /* * ckmk_mdMechanismRSA_GetMaxKeySize */ static CK_ULONG -ckmk_mdMechanismRSA_GetMaxKeySize -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdMechanismRSA_GetMaxKeySize( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return 16384; + return 16384; } /* * ckmk_mdMechanismRSA_DecryptInit */ -static NSSCKMDCryptoOperation * -ckmk_mdMechanismRSA_DecryptInit -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError -) +static NSSCKMDCryptoOperation * +ckmk_mdMechanismRSA_DecryptInit( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError) { - return ckmk_mdCryptoOperationRSAPriv_Create( - &ckmk_mdCryptoOperationRSADecrypt_proto, - mdMechanism, mdKey, CKMK_DECRYPT, pError); + return ckmk_mdCryptoOperationRSAPriv_Create( + &ckmk_mdCryptoOperationRSADecrypt_proto, + mdMechanism, mdKey, CKMK_DECRYPT, pError); } /* * ckmk_mdMechanismRSA_SignInit */ -static NSSCKMDCryptoOperation * -ckmk_mdMechanismRSA_SignInit -( - NSSCKMDMechanism *mdMechanism, - NSSCKFWMechanism *fwMechanism, - CK_MECHANISM *pMechanism, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKMDObject *mdKey, - NSSCKFWObject *fwKey, - CK_RV *pError -) +static NSSCKMDCryptoOperation * +ckmk_mdMechanismRSA_SignInit( + NSSCKMDMechanism *mdMechanism, + NSSCKFWMechanism *fwMechanism, + CK_MECHANISM *pMechanism, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKMDObject *mdKey, + NSSCKFWObject *fwKey, + CK_RV *pError) { - return ckmk_mdCryptoOperationRSAPriv_Create( - &ckmk_mdCryptoOperationRSASign_proto, - mdMechanism, mdKey, CKMK_SIGN, pError); + return ckmk_mdCryptoOperationRSAPriv_Create( + &ckmk_mdCryptoOperationRSASign_proto, + mdMechanism, mdKey, CKMK_SIGN, pError); } - NSS_IMPLEMENT_DATA const NSSCKMDMechanism -nss_ckmk_mdMechanismRSA = { - (void *)NULL, /* etc */ - ckmk_mdMechanismRSA_Destroy, - ckmk_mdMechanismRSA_GetMinKeySize, - ckmk_mdMechanismRSA_GetMaxKeySize, - NULL, /* GetInHardware - default false */ - NULL, /* EncryptInit - default errs */ - ckmk_mdMechanismRSA_DecryptInit, - NULL, /* DigestInit - default errs*/ - ckmk_mdMechanismRSA_SignInit, - NULL, /* VerifyInit - default errs */ - ckmk_mdMechanismRSA_SignInit, /* SignRecoverInit */ - NULL, /* VerifyRecoverInit - default errs */ - NULL, /* GenerateKey - default errs */ - NULL, /* GenerateKeyPair - default errs */ - NULL, /* GetWrapKeyLength - default errs */ - NULL, /* WrapKey - default errs */ - NULL, /* UnwrapKey - default errs */ - NULL, /* DeriveKey - default errs */ - (void *)NULL /* null terminator */ -}; + nss_ckmk_mdMechanismRSA = { + (void *)NULL, /* etc */ + ckmk_mdMechanismRSA_Destroy, + ckmk_mdMechanismRSA_GetMinKeySize, + ckmk_mdMechanismRSA_GetMaxKeySize, + NULL, /* GetInHardware - default false */ + NULL, /* EncryptInit - default errs */ + ckmk_mdMechanismRSA_DecryptInit, + NULL, /* DigestInit - default errs*/ + ckmk_mdMechanismRSA_SignInit, + NULL, /* VerifyInit - default errs */ + ckmk_mdMechanismRSA_SignInit, /* SignRecoverInit */ + NULL, /* VerifyRecoverInit - default errs */ + NULL, /* GenerateKey - default errs */ + NULL, /* GenerateKeyPair - default errs */ + NULL, /* GetWrapKeyLength - default errs */ + NULL, /* WrapKey - default errs */ + NULL, /* UnwrapKey - default errs */ + NULL, /* DeriveKey - default errs */ + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/nssmkey/msession.c b/security/nss/lib/ckfw/nssmkey/msession.c index 6e1e1954ea19..e6a29244a1ad 100644 --- a/security/nss/lib/ckfw/nssmkey/msession.c +++ b/security/nss/lib/ckfw/nssmkey/msession.c @@ -7,87 +7,81 @@ /* * nssmkey/msession.c * - * This file implements the NSSCKMDSession object for the + * This file implements the NSSCKMDSession object for the * "nssmkey" cryptoki module. */ static NSSCKMDFindObjects * -ckmk_mdSession_FindObjectsInit -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +ckmk_mdSession_FindObjectsInit( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - return nss_ckmk_FindObjectsInit(fwSession, pTemplate, ulAttributeCount, pError); + return nss_ckmk_FindObjectsInit(fwSession, pTemplate, ulAttributeCount, pError); } static NSSCKMDObject * -ckmk_mdSession_CreateObject -( - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +ckmk_mdSession_CreateObject( + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - return nss_ckmk_CreateObject(fwSession, pTemplate, ulAttributeCount, pError); + return nss_ckmk_CreateObject(fwSession, pTemplate, ulAttributeCount, pError); } NSS_IMPLEMENT NSSCKMDSession * -nss_ckmk_CreateSession -( - NSSCKFWSession *fwSession, - CK_RV *pError -) +nss_ckmk_CreateSession( + NSSCKFWSession *fwSession, + CK_RV *pError) { - NSSArena *arena; - NSSCKMDSession *rv; + NSSArena *arena; + NSSCKMDSession *rv; - arena = NSSCKFWSession_GetArena(fwSession, pError); - if( (NSSArena *)NULL == arena ) { - return (NSSCKMDSession *)NULL; - } + arena = NSSCKFWSession_GetArena(fwSession, pError); + if ((NSSArena *)NULL == arena) { + return (NSSCKMDSession *)NULL; + } - rv = nss_ZNEW(arena, NSSCKMDSession); - if( (NSSCKMDSession *)NULL == rv ) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDSession *)NULL; - } + rv = nss_ZNEW(arena, NSSCKMDSession); + if ((NSSCKMDSession *)NULL == rv) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDSession *)NULL; + } - /* - * rv was zeroed when allocated, so we only - * need to set the non-zero members. - */ + /* + * rv was zeroed when allocated, so we only + * need to set the non-zero members. + */ - rv->etc = (void *)fwSession; - /* rv->Close */ - /* rv->GetDeviceError */ - /* rv->Login */ - /* rv->Logout */ - /* rv->InitPIN */ - /* rv->SetPIN */ - /* rv->GetOperationStateLen */ - /* rv->GetOperationState */ - /* rv->SetOperationState */ - rv->CreateObject = ckmk_mdSession_CreateObject; - /* rv->CopyObject */ - rv->FindObjectsInit = ckmk_mdSession_FindObjectsInit; - /* rv->SeedRandom */ - /* rv->GetRandom */ - /* rv->null */ + rv->etc = (void *)fwSession; + /* rv->Close */ + /* rv->GetDeviceError */ + /* rv->Login */ + /* rv->Logout */ + /* rv->InitPIN */ + /* rv->SetPIN */ + /* rv->GetOperationStateLen */ + /* rv->GetOperationState */ + /* rv->SetOperationState */ + rv->CreateObject = ckmk_mdSession_CreateObject; + /* rv->CopyObject */ + rv->FindObjectsInit = ckmk_mdSession_FindObjectsInit; + /* rv->SeedRandom */ + /* rv->GetRandom */ + /* rv->null */ - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/nssmkey/mslot.c b/security/nss/lib/ckfw/nssmkey/mslot.c index 7a432124d9fb..b2747ff7b2a6 100644 --- a/security/nss/lib/ckfw/nssmkey/mslot.c +++ b/security/nss/lib/ckfw/nssmkey/mslot.c @@ -12,80 +12,70 @@ */ static NSSUTF8 * -ckmk_mdSlot_GetSlotDescription -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdSlot_GetSlotDescription( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_SlotDescription; + return (NSSUTF8 *)nss_ckmk_SlotDescription; } static NSSUTF8 * -ckmk_mdSlot_GetManufacturerID -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdSlot_GetManufacturerID( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_ManufacturerID; + return (NSSUTF8 *)nss_ckmk_ManufacturerID; } static CK_VERSION -ckmk_mdSlot_GetHardwareVersion -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdSlot_GetHardwareVersion( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckmk_HardwareVersion; + return nss_ckmk_HardwareVersion; } static CK_VERSION -ckmk_mdSlot_GetFirmwareVersion -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdSlot_GetFirmwareVersion( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckmk_FirmwareVersion; + return nss_ckmk_FirmwareVersion; } static NSSCKMDToken * -ckmk_mdSlot_GetToken -( - NSSCKMDSlot *mdSlot, - NSSCKFWSlot *fwSlot, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdSlot_GetToken( + NSSCKMDSlot *mdSlot, + NSSCKFWSlot *fwSlot, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSCKMDToken *)&nss_ckmk_mdToken; + return (NSSCKMDToken *)&nss_ckmk_mdToken; } NSS_IMPLEMENT_DATA const NSSCKMDSlot -nss_ckmk_mdSlot = { - (void *)NULL, /* etc */ - NULL, /* Initialize */ - NULL, /* Destroy */ - ckmk_mdSlot_GetSlotDescription, - ckmk_mdSlot_GetManufacturerID, - NULL, /* GetTokenPresent -- defaults to true */ - NULL, /* GetRemovableDevice -- defaults to false */ - NULL, /* GetHardwareSlot -- defaults to false */ - ckmk_mdSlot_GetHardwareVersion, - ckmk_mdSlot_GetFirmwareVersion, - ckmk_mdSlot_GetToken, - (void *)NULL /* null terminator */ -}; + nss_ckmk_mdSlot = { + (void *)NULL, /* etc */ + NULL, /* Initialize */ + NULL, /* Destroy */ + ckmk_mdSlot_GetSlotDescription, + ckmk_mdSlot_GetManufacturerID, + NULL, /* GetTokenPresent -- defaults to true */ + NULL, /* GetRemovableDevice -- defaults to false */ + NULL, /* GetHardwareSlot -- defaults to false */ + ckmk_mdSlot_GetHardwareVersion, + ckmk_mdSlot_GetFirmwareVersion, + ckmk_mdSlot_GetToken, + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/nssmkey/mtoken.c b/security/nss/lib/ckfw/nssmkey/mtoken.c index a0278072c730..e18d612405ad 100644 --- a/security/nss/lib/ckfw/nssmkey/mtoken.c +++ b/security/nss/lib/ckfw/nssmkey/mtoken.c @@ -12,197 +12,173 @@ */ static NSSUTF8 * -ckmk_mdToken_GetLabel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdToken_GetLabel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_TokenLabel; + return (NSSUTF8 *)nss_ckmk_TokenLabel; } static NSSUTF8 * -ckmk_mdToken_GetManufacturerID -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdToken_GetManufacturerID( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_ManufacturerID; + return (NSSUTF8 *)nss_ckmk_ManufacturerID; } static NSSUTF8 * -ckmk_mdToken_GetModel -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdToken_GetModel( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_TokenModel; + return (NSSUTF8 *)nss_ckmk_TokenModel; } static NSSUTF8 * -ckmk_mdToken_GetSerialNumber -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +ckmk_mdToken_GetSerialNumber( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - return (NSSUTF8 *)nss_ckmk_TokenSerialNumber; + return (NSSUTF8 *)nss_ckmk_TokenSerialNumber; } static CK_BBOOL -ckmk_mdToken_GetIsWriteProtected -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdToken_GetIsWriteProtected( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_FALSE; + return CK_FALSE; } /* fake out Mozilla so we don't try to initialize the token */ static CK_BBOOL -ckmk_mdToken_GetUserPinInitialized -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdToken_GetUserPinInitialized( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return CK_TRUE; + return CK_TRUE; } static CK_VERSION -ckmk_mdToken_GetHardwareVersion -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdToken_GetHardwareVersion( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckmk_HardwareVersion; + return nss_ckmk_HardwareVersion; } static CK_VERSION -ckmk_mdToken_GetFirmwareVersion -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdToken_GetFirmwareVersion( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return nss_ckmk_FirmwareVersion; + return nss_ckmk_FirmwareVersion; } static NSSCKMDSession * -ckmk_mdToken_OpenSession -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSCKFWSession *fwSession, - CK_BBOOL rw, - CK_RV *pError -) +ckmk_mdToken_OpenSession( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSCKFWSession *fwSession, + CK_BBOOL rw, + CK_RV *pError) { - return nss_ckmk_CreateSession(fwSession, pError); + return nss_ckmk_CreateSession(fwSession, pError); } static CK_ULONG -ckmk_mdToken_GetMechanismCount -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +ckmk_mdToken_GetMechanismCount( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - return (CK_ULONG)1; + return (CK_ULONG)1; } static CK_RV -ckmk_mdToken_GetMechanismTypes -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_MECHANISM_TYPE types[] -) +ckmk_mdToken_GetMechanismTypes( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_MECHANISM_TYPE types[]) { - types[0] = CKM_RSA_PKCS; - return CKR_OK; + types[0] = CKM_RSA_PKCS; + return CKR_OK; } static NSSCKMDMechanism * -ckmk_mdToken_GetMechanism -( - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_MECHANISM_TYPE which, - CK_RV *pError -) +ckmk_mdToken_GetMechanism( + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_MECHANISM_TYPE which, + CK_RV *pError) { - if (which != CKM_RSA_PKCS) { - *pError = CKR_MECHANISM_INVALID; - return (NSSCKMDMechanism *)NULL; - } - return (NSSCKMDMechanism *)&nss_ckmk_mdMechanismRSA; + if (which != CKM_RSA_PKCS) { + *pError = CKR_MECHANISM_INVALID; + return (NSSCKMDMechanism *)NULL; + } + return (NSSCKMDMechanism *)&nss_ckmk_mdMechanismRSA; } NSS_IMPLEMENT_DATA const NSSCKMDToken -nss_ckmk_mdToken = { - (void *)NULL, /* etc */ - NULL, /* Setup */ - NULL, /* Invalidate */ - NULL, /* InitToken -- default errs */ - ckmk_mdToken_GetLabel, - ckmk_mdToken_GetManufacturerID, - ckmk_mdToken_GetModel, - ckmk_mdToken_GetSerialNumber, - NULL, /* GetHasRNG -- default is false */ - ckmk_mdToken_GetIsWriteProtected, - NULL, /* GetLoginRequired -- default is false */ - ckmk_mdToken_GetUserPinInitialized, - NULL, /* GetRestoreKeyNotNeeded -- irrelevant */ - NULL, /* GetHasClockOnToken -- default is false */ - NULL, /* GetHasProtectedAuthenticationPath -- default is false */ - NULL, /* GetSupportsDualCryptoOperations -- default is false */ - NULL, /* GetMaxSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetMaxRwSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetMaxPinLen -- irrelevant */ - NULL, /* GetMinPinLen -- irrelevant */ - NULL, /* GetTotalPublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetFreePublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetTotalPrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ - NULL, /* GetFreePrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ - ckmk_mdToken_GetHardwareVersion, - ckmk_mdToken_GetFirmwareVersion, - NULL, /* GetUTCTime -- no clock */ - ckmk_mdToken_OpenSession, - ckmk_mdToken_GetMechanismCount, - ckmk_mdToken_GetMechanismTypes, - ckmk_mdToken_GetMechanism, - (void *)NULL /* null terminator */ -}; + nss_ckmk_mdToken = { + (void *)NULL, /* etc */ + NULL, /* Setup */ + NULL, /* Invalidate */ + NULL, /* InitToken -- default errs */ + ckmk_mdToken_GetLabel, + ckmk_mdToken_GetManufacturerID, + ckmk_mdToken_GetModel, + ckmk_mdToken_GetSerialNumber, + NULL, /* GetHasRNG -- default is false */ + ckmk_mdToken_GetIsWriteProtected, + NULL, /* GetLoginRequired -- default is false */ + ckmk_mdToken_GetUserPinInitialized, + NULL, /* GetRestoreKeyNotNeeded -- irrelevant */ + NULL, /* GetHasClockOnToken -- default is false */ + NULL, /* GetHasProtectedAuthenticationPath -- default is false */ + NULL, /* GetSupportsDualCryptoOperations -- default is false */ + NULL, /* GetMaxSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetMaxRwSessionCount -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetMaxPinLen -- irrelevant */ + NULL, /* GetMinPinLen -- irrelevant */ + NULL, /* GetTotalPublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetFreePublicMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetTotalPrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ + NULL, /* GetFreePrivateMemory -- default is CK_UNAVAILABLE_INFORMATION */ + ckmk_mdToken_GetHardwareVersion, + ckmk_mdToken_GetFirmwareVersion, + NULL, /* GetUTCTime -- no clock */ + ckmk_mdToken_OpenSession, + ckmk_mdToken_GetMechanismCount, + ckmk_mdToken_GetMechanismTypes, + ckmk_mdToken_GetMechanism, + (void *)NULL /* null terminator */ + }; diff --git a/security/nss/lib/ckfw/nssmkey/nssmkey.h b/security/nss/lib/ckfw/nssmkey/nssmkey.h index bce77bf132b7..ba58233e6284 100644 --- a/security/nss/lib/ckfw/nssmkey/nssmkey.h +++ b/security/nss/lib/ckfw/nssmkey/nssmkey.h @@ -18,7 +18,7 @@ #define NSS_CKMK_CRYPTOKI_VERSION_MAJOR 2 #define NSS_CKMK_CRYPTOKI_VERSION_MINOR 20 -/* These version numbers detail the changes +/* These version numbers detail the changes * to the list of trusted certificates. * * NSS_CKMK_LIBRARY_VERSION_MINOR is a CK_BYTE. It's not clear @@ -33,7 +33,7 @@ #define NSS_CKMK_HARDWARE_VERSION_MAJOR 1 #define NSS_CKMK_HARDWARE_VERSION_MINOR 0 -/* These version numbers detail the semantic changes to ckbi itself +/* These version numbers detail the semantic changes to ckbi itself * (new PKCS #11 objects), etc. */ #define NSS_CKMK_FIRMWARE_VERSION_MAJOR 1 #define NSS_CKMK_FIRMWARE_VERSION_MINOR 0 diff --git a/security/nss/lib/ckfw/nssmkey/staticobj.c b/security/nss/lib/ckfw/nssmkey/staticobj.c index 0ccc86141697..5f3bb7c720a0 100644 --- a/security/nss/lib/ckfw/nssmkey/staticobj.c +++ b/security/nss/lib/ckfw/nssmkey/staticobj.c @@ -17,20 +17,20 @@ static const CK_BBOOL ck_false = CK_FALSE; static const CK_OBJECT_CLASS cko_netscape_builtin_root_list = CKO_NETSCAPE_BUILTIN_ROOT_LIST; /* example of a static object */ -static const CK_ATTRIBUTE_TYPE nss_ckmk_types_1 [] = { - CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_MODIFIABLE, CKA_LABEL +static const CK_ATTRIBUTE_TYPE nss_ckmk_types_1[] = { + CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_MODIFIABLE, CKA_LABEL }; -static const NSSItem nss_ckmk_items_1 [] = { - { (void *)&cko_data, (PRUint32)sizeof(CK_OBJECT_CLASS) }, - { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) }, - { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, - { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, - { (void *)"Mozilla Mac Key Ring Access", (PRUint32)28 } +static const NSSItem nss_ckmk_items_1[] = { + { (void *)&cko_data, (PRUint32)sizeof(CK_OBJECT_CLASS) }, + { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) }, + { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, + { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }, + { (void *)"Mozilla Mac Key Ring Access", (PRUint32)28 } }; ckmkInternalObject nss_ckmk_data[] = { - { ckmkRaw, {{ 5, nss_ckmk_types_1, nss_ckmk_items_1}} , CKO_DATA, {NULL} }, + { ckmkRaw, { { 5, nss_ckmk_types_1, nss_ckmk_items_1 } }, CKO_DATA, { NULL } }, }; const PRUint32 nss_ckmk_nObjects = 1; diff --git a/security/nss/lib/ckfw/object.c b/security/nss/lib/ckfw/object.c index 661977e6dba9..bb2663aa299c 100644 --- a/security/nss/lib/ckfw/object.c +++ b/security/nss/lib/ckfw/object.c @@ -50,16 +50,16 @@ */ struct NSSCKFWObjectStr { - NSSCKFWMutex *mutex; /* merely to serialise the MDObject calls */ - NSSArena *arena; - NSSCKMDObject *mdObject; - NSSCKMDSession *mdSession; - NSSCKFWSession *fwSession; - NSSCKMDToken *mdToken; - NSSCKFWToken *fwToken; - NSSCKMDInstance *mdInstance; - NSSCKFWInstance *fwInstance; - CK_OBJECT_HANDLE hObject; + NSSCKFWMutex *mutex; /* merely to serialise the MDObject calls */ + NSSArena *arena; + NSSCKMDObject *mdObject; + NSSCKMDSession *mdSession; + NSSCKFWSession *fwSession; + NSSCKMDToken *mdToken; + NSSCKFWToken *fwToken; + NSSCKMDInstance *mdInstance; + NSSCKFWInstance *fwInstance; + CK_OBJECT_HANDLE hObject; }; #ifdef DEBUG @@ -75,123 +75,114 @@ struct NSSCKFWObjectStr { */ static CK_RV -object_add_pointer -( - const NSSCKFWObject *fwObject -) +object_add_pointer( + const NSSCKFWObject *fwObject) { - return CKR_OK; + return CKR_OK; } static CK_RV -object_remove_pointer -( - const NSSCKFWObject *fwObject -) +object_remove_pointer( + const NSSCKFWObject *fwObject) { - return CKR_OK; + return CKR_OK; } NSS_IMPLEMENT CK_RV -nssCKFWObject_verifyPointer -( - const NSSCKFWObject *fwObject -) +nssCKFWObject_verifyPointer( + const NSSCKFWObject *fwObject) { - return CKR_OK; + return CKR_OK; } #endif /* DEBUG */ - /* * nssCKFWObject_Create * */ NSS_IMPLEMENT NSSCKFWObject * -nssCKFWObject_Create -( - NSSArena *arena, - NSSCKMDObject *mdObject, - NSSCKFWSession *fwSession, - NSSCKFWToken *fwToken, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nssCKFWObject_Create( + NSSArena *arena, + NSSCKMDObject *mdObject, + NSSCKFWSession *fwSession, + NSSCKFWToken *fwToken, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - NSSCKFWObject *fwObject; - nssCKFWHash *mdObjectHash; + NSSCKFWObject *fwObject; + nssCKFWHash *mdObjectHash; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWObject *)NULL; - } + if (!pError) { + return (NSSCKFWObject *)NULL; + } - if( PR_SUCCESS != nssArena_verifyPointer(arena) ) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWObject *)NULL; - } + if (PR_SUCCESS != nssArena_verifyPointer(arena)) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWObject *)NULL; + } #endif /* NSSDEBUG */ - if (!fwToken) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWObject *)NULL; - } - mdObjectHash = nssCKFWToken_GetMDObjectHash(fwToken); - if (!mdObjectHash) { - *pError = CKR_GENERAL_ERROR; - return (NSSCKFWObject *)NULL; - } - - if( nssCKFWHash_Exists(mdObjectHash, mdObject) ) { - fwObject = nssCKFWHash_Lookup(mdObjectHash, mdObject); - return fwObject; - } - - fwObject = nss_ZNEW(arena, NSSCKFWObject); - if (!fwObject) { - *pError = CKR_HOST_MEMORY; - return (NSSCKFWObject *)NULL; - } - - fwObject->arena = arena; - fwObject->mdObject = mdObject; - fwObject->fwSession = fwSession; - - if (fwSession) { - fwObject->mdSession = nssCKFWSession_GetMDSession(fwSession); - } - - fwObject->fwToken = fwToken; - fwObject->mdToken = nssCKFWToken_GetMDToken(fwToken); - fwObject->fwInstance = fwInstance; - fwObject->mdInstance = nssCKFWInstance_GetMDInstance(fwInstance); - fwObject->mutex = nssCKFWInstance_CreateMutex(fwInstance, arena, pError); - if (!fwObject->mutex) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + if (!fwToken) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWObject *)NULL; + } + mdObjectHash = nssCKFWToken_GetMDObjectHash(fwToken); + if (!mdObjectHash) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWObject *)NULL; } - nss_ZFreeIf(fwObject); - return (NSSCKFWObject *)NULL; - } - *pError = nssCKFWHash_Add(mdObjectHash, mdObject, fwObject); - if( CKR_OK != *pError ) { - nss_ZFreeIf(fwObject); - return (NSSCKFWObject *)NULL; - } + if (nssCKFWHash_Exists(mdObjectHash, mdObject)) { + fwObject = nssCKFWHash_Lookup(mdObjectHash, mdObject); + return fwObject; + } + + fwObject = nss_ZNEW(arena, NSSCKFWObject); + if (!fwObject) { + *pError = CKR_HOST_MEMORY; + return (NSSCKFWObject *)NULL; + } + + fwObject->arena = arena; + fwObject->mdObject = mdObject; + fwObject->fwSession = fwSession; + + if (fwSession) { + fwObject->mdSession = nssCKFWSession_GetMDSession(fwSession); + } + + fwObject->fwToken = fwToken; + fwObject->mdToken = nssCKFWToken_GetMDToken(fwToken); + fwObject->fwInstance = fwInstance; + fwObject->mdInstance = nssCKFWInstance_GetMDInstance(fwInstance); + fwObject->mutex = nssCKFWInstance_CreateMutex(fwInstance, arena, pError); + if (!fwObject->mutex) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + nss_ZFreeIf(fwObject); + return (NSSCKFWObject *)NULL; + } + + *pError = nssCKFWHash_Add(mdObjectHash, mdObject, fwObject); + if (CKR_OK != *pError) { + nss_ZFreeIf(fwObject); + return (NSSCKFWObject *)NULL; + } #ifdef DEBUG - *pError = object_add_pointer(fwObject); - if( CKR_OK != *pError ) { - nssCKFWHash_Remove(mdObjectHash, mdObject); - nss_ZFreeIf(fwObject); - return (NSSCKFWObject *)NULL; - } + *pError = object_add_pointer(fwObject); + if (CKR_OK != *pError) { + nssCKFWHash_Remove(mdObjectHash, mdObject); + nss_ZFreeIf(fwObject); + return (NSSCKFWObject *)NULL; + } #endif /* DEBUG */ - *pError = CKR_OK; - return fwObject; + *pError = CKR_OK; + return fwObject; } /* @@ -199,45 +190,43 @@ nssCKFWObject_Create * */ NSS_IMPLEMENT void -nssCKFWObject_Finalize -( - NSSCKFWObject *fwObject, - PRBool removeFromHash -) +nssCKFWObject_Finalize( + NSSCKFWObject *fwObject, + PRBool removeFromHash) { - nssCKFWHash *mdObjectHash; + nssCKFWHash *mdObjectHash; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return; + } #endif /* NSSDEBUG */ - (void)nssCKFWMutex_Destroy(fwObject->mutex); + (void)nssCKFWMutex_Destroy(fwObject->mutex); - if (fwObject->mdObject->Finalize) { - fwObject->mdObject->Finalize(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance); - } - - if (removeFromHash) { - mdObjectHash = nssCKFWToken_GetMDObjectHash(fwObject->fwToken); - if (mdObjectHash) { - nssCKFWHash_Remove(mdObjectHash, fwObject->mdObject); + if (fwObject->mdObject->Finalize) { + fwObject->mdObject->Finalize(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance); } - } - if (fwObject->fwSession) { - nssCKFWSession_DeregisterSessionObject(fwObject->fwSession, fwObject); - } - nss_ZFreeIf(fwObject); + if (removeFromHash) { + mdObjectHash = nssCKFWToken_GetMDObjectHash(fwObject->fwToken); + if (mdObjectHash) { + nssCKFWHash_Remove(mdObjectHash, fwObject->mdObject); + } + } + + if (fwObject->fwSession) { + nssCKFWSession_DeregisterSessionObject(fwObject->fwSession, fwObject); + } + nss_ZFreeIf(fwObject); #ifdef DEBUG - (void)object_remove_pointer(fwObject); + (void)object_remove_pointer(fwObject); #endif /* DEBUG */ - return; + return; } /* @@ -245,42 +234,40 @@ nssCKFWObject_Finalize * */ NSS_IMPLEMENT void -nssCKFWObject_Destroy -( - NSSCKFWObject *fwObject -) +nssCKFWObject_Destroy( + NSSCKFWObject *fwObject) { - nssCKFWHash *mdObjectHash; + nssCKFWHash *mdObjectHash; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return; + } #endif /* NSSDEBUG */ - (void)nssCKFWMutex_Destroy(fwObject->mutex); + (void)nssCKFWMutex_Destroy(fwObject->mutex); - if (fwObject->mdObject->Destroy) { - fwObject->mdObject->Destroy(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance); - } + if (fwObject->mdObject->Destroy) { + fwObject->mdObject->Destroy(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance); + } - mdObjectHash = nssCKFWToken_GetMDObjectHash(fwObject->fwToken); - if (mdObjectHash) { - nssCKFWHash_Remove(mdObjectHash, fwObject->mdObject); - } + mdObjectHash = nssCKFWToken_GetMDObjectHash(fwObject->fwToken); + if (mdObjectHash) { + nssCKFWHash_Remove(mdObjectHash, fwObject->mdObject); + } - if (fwObject->fwSession) { - nssCKFWSession_DeregisterSessionObject(fwObject->fwSession, fwObject); - } - nss_ZFreeIf(fwObject); + if (fwObject->fwSession) { + nssCKFWSession_DeregisterSessionObject(fwObject->fwSession, fwObject); + } + nss_ZFreeIf(fwObject); #ifdef DEBUG - (void)object_remove_pointer(fwObject); + (void)object_remove_pointer(fwObject); #endif /* DEBUG */ - return; + return; } /* @@ -288,18 +275,16 @@ nssCKFWObject_Destroy * */ NSS_IMPLEMENT NSSCKMDObject * -nssCKFWObject_GetMDObject -( - NSSCKFWObject *fwObject -) +nssCKFWObject_GetMDObject( + NSSCKFWObject *fwObject) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return (NSSCKMDObject *)NULL; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return (NSSCKMDObject *)NULL; + } #endif /* NSSDEBUG */ - return fwObject->mdObject; + return fwObject->mdObject; } /* @@ -307,24 +292,22 @@ nssCKFWObject_GetMDObject * */ NSS_IMPLEMENT NSSArena * -nssCKFWObject_GetArena -( - NSSCKFWObject *fwObject, - CK_RV *pError -) +nssCKFWObject_GetArena( + NSSCKFWObject *fwObject, + CK_RV *pError) { #ifdef NSSDEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (NSSArena *)NULL; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (NSSArena *)NULL; + } #endif /* NSSDEBUG */ - return fwObject->arena; + return fwObject->arena; } /* @@ -332,30 +315,28 @@ nssCKFWObject_GetArena * */ NSS_IMPLEMENT CK_RV -nssCKFWObject_SetHandle -( - NSSCKFWObject *fwObject, - CK_OBJECT_HANDLE hObject -) +nssCKFWObject_SetHandle( + NSSCKFWObject *fwObject, + CK_OBJECT_HANDLE hObject) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #endif /* NSSDEBUG */ #ifdef NSSDEBUG - error = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - if( (CK_OBJECT_HANDLE)0 != fwObject->hObject ) { - return CKR_GENERAL_ERROR; - } + if ((CK_OBJECT_HANDLE)0 != fwObject->hObject) { + return CKR_GENERAL_ERROR; + } - fwObject->hObject = hObject; + fwObject->hObject = hObject; - return CKR_OK; + return CKR_OK; } /* @@ -363,18 +344,16 @@ nssCKFWObject_SetHandle * */ NSS_IMPLEMENT CK_OBJECT_HANDLE -nssCKFWObject_GetHandle -( - NSSCKFWObject *fwObject -) +nssCKFWObject_GetHandle( + NSSCKFWObject *fwObject) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return (CK_OBJECT_HANDLE)0; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return (CK_OBJECT_HANDLE)0; + } #endif /* NSSDEBUG */ - return fwObject->hObject; + return fwObject->hObject; } /* @@ -382,44 +361,42 @@ nssCKFWObject_GetHandle * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWObject_IsTokenObject -( - NSSCKFWObject *fwObject -) +nssCKFWObject_IsTokenObject( + NSSCKFWObject *fwObject) { - CK_BBOOL b = CK_FALSE; + CK_BBOOL b = CK_FALSE; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwObject->mdObject->IsTokenObject) { - NSSItem item; - NSSItem *pItem; - CK_RV rv = CKR_OK; + if (!fwObject->mdObject->IsTokenObject) { + NSSItem item; + NSSItem *pItem; + CK_RV rv = CKR_OK; - item.data = (void *)&b; - item.size = sizeof(b); + item.data = (void *)&b; + item.size = sizeof(b); - pItem = nssCKFWObject_GetAttribute(fwObject, CKA_TOKEN, &item, - (NSSArena *)NULL, &rv); - if (!pItem) { - /* Error of some type */ - b = CK_FALSE; - goto done; + pItem = nssCKFWObject_GetAttribute(fwObject, CKA_TOKEN, &item, + (NSSArena *)NULL, &rv); + if (!pItem) { + /* Error of some type */ + b = CK_FALSE; + goto done; + } + + goto done; } - goto done; - } + b = fwObject->mdObject->IsTokenObject(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance); - b = fwObject->mdObject->IsTokenObject(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance); - - done: - return b; +done: + return b; } /* @@ -427,42 +404,40 @@ nssCKFWObject_IsTokenObject * */ NSS_IMPLEMENT CK_ULONG -nssCKFWObject_GetAttributeCount -( - NSSCKFWObject *fwObject, - CK_RV *pError -) +nssCKFWObject_GetAttributeCount( + NSSCKFWObject *fwObject, + CK_RV *pError) { - CK_ULONG rv; + CK_ULONG rv; #ifdef NSSDEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if (!fwObject->mdObject->GetAttributeCount) { - *pError = CKR_GENERAL_ERROR; - return (CK_ULONG)0; - } + if (!fwObject->mdObject->GetAttributeCount) { + *pError = CKR_GENERAL_ERROR; + return (CK_ULONG)0; + } - *pError = nssCKFWMutex_Lock(fwObject->mutex); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWMutex_Lock(fwObject->mutex); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } - rv = fwObject->mdObject->GetAttributeCount(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, - pError); + rv = fwObject->mdObject->GetAttributeCount(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, + pError); - (void)nssCKFWMutex_Unlock(fwObject->mutex); - return rv; + (void)nssCKFWMutex_Unlock(fwObject->mutex); + return rv; } /* @@ -470,42 +445,40 @@ nssCKFWObject_GetAttributeCount * */ NSS_IMPLEMENT CK_RV -nssCKFWObject_GetAttributeTypes -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -) +nssCKFWObject_GetAttributeTypes( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != error) { + return error; + } - if( (CK_ATTRIBUTE_TYPE_PTR)NULL == typeArray ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_ATTRIBUTE_TYPE_PTR)NULL == typeArray) { + return CKR_ARGUMENTS_BAD; + } #endif /* NSSDEBUG */ - if (!fwObject->mdObject->GetAttributeTypes) { - return CKR_GENERAL_ERROR; - } + if (!fwObject->mdObject->GetAttributeTypes) { + return CKR_GENERAL_ERROR; + } - error = nssCKFWMutex_Lock(fwObject->mutex); - if( CKR_OK != error ) { + error = nssCKFWMutex_Lock(fwObject->mutex); + if (CKR_OK != error) { + return error; + } + + error = fwObject->mdObject->GetAttributeTypes(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, + typeArray, ulCount); + + (void)nssCKFWMutex_Unlock(fwObject->mutex); return error; - } - - error = fwObject->mdObject->GetAttributeTypes(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, - typeArray, ulCount); - - (void)nssCKFWMutex_Unlock(fwObject->mutex); - return error; } /* @@ -513,43 +486,41 @@ nssCKFWObject_GetAttributeTypes * */ NSS_IMPLEMENT CK_ULONG -nssCKFWObject_GetAttributeSize -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +nssCKFWObject_GetAttributeSize( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - CK_ULONG rv; + CK_ULONG rv; #ifdef NSSDEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if (!fwObject->mdObject->GetAttributeSize) { - *pError = CKR_GENERAL_ERROR; - return (CK_ULONG )0; - } + if (!fwObject->mdObject->GetAttributeSize) { + *pError = CKR_GENERAL_ERROR; + return (CK_ULONG)0; + } - *pError = nssCKFWMutex_Lock(fwObject->mutex); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWMutex_Lock(fwObject->mutex); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } - rv = fwObject->mdObject->GetAttributeSize(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, - attribute, pError); + rv = fwObject->mdObject->GetAttributeSize(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, + attribute, pError); - (void)nssCKFWMutex_Unlock(fwObject->mutex); - return rv; + (void)nssCKFWMutex_Unlock(fwObject->mutex); + return rv; } /* @@ -563,97 +534,98 @@ nssCKFWObject_GetAttributeSize * specified. */ NSS_IMPLEMENT NSSItem * -nssCKFWObject_GetAttribute -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *itemOpt, - NSSArena *arenaOpt, - CK_RV *pError -) +nssCKFWObject_GetAttribute( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *itemOpt, + NSSArena *arenaOpt, + CK_RV *pError) { - NSSItem *rv = (NSSItem *)NULL; - NSSCKFWItem mdItem; + NSSItem *rv = (NSSItem *)NULL; + NSSCKFWItem mdItem; #ifdef NSSDEBUG - if (!pError) { - return (NSSItem *)NULL; - } + if (!pError) { + return (NSSItem *)NULL; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (NSSItem *)NULL; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (NSSItem *)NULL; + } #endif /* NSSDEBUG */ - if (!fwObject->mdObject->GetAttribute) { - *pError = CKR_GENERAL_ERROR; - return (NSSItem *)NULL; - } - - *pError = nssCKFWMutex_Lock(fwObject->mutex); - if( CKR_OK != *pError ) { - return (NSSItem *)NULL; - } - - mdItem = fwObject->mdObject->GetAttribute(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, - attribute, pError); - - if (!mdItem.item) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + if (!fwObject->mdObject->GetAttribute) { + *pError = CKR_GENERAL_ERROR; + return (NSSItem *)NULL; } - goto done; - } - - if (!itemOpt) { - rv = nss_ZNEW(arenaOpt, NSSItem); - if (!rv) { - *pError = CKR_HOST_MEMORY; - goto done; + *pError = nssCKFWMutex_Lock(fwObject->mutex); + if (CKR_OK != *pError) { + return (NSSItem *)NULL; + } + + mdItem = fwObject->mdObject->GetAttribute(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, + attribute, pError); + + if (!mdItem.item) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + + goto done; + } + + if (!itemOpt) { + rv = nss_ZNEW(arenaOpt, NSSItem); + if (!rv) { + *pError = CKR_HOST_MEMORY; + goto done; + } + } + else { + rv = itemOpt; } - } else { - rv = itemOpt; - } - if (!rv->data) { - rv->size = mdItem.item->size; - rv->data = nss_ZAlloc(arenaOpt, rv->size); if (!rv->data) { - *pError = CKR_HOST_MEMORY; - if (!itemOpt) { - nss_ZFreeIf(rv); - } - rv = (NSSItem *)NULL; - goto done; + rv->size = mdItem.item->size; + rv->data = nss_ZAlloc(arenaOpt, rv->size); + if (!rv->data) { + *pError = CKR_HOST_MEMORY; + if (!itemOpt) { + nss_ZFreeIf(rv); + } + rv = (NSSItem *)NULL; + goto done; + } } - } else { - if( rv->size >= mdItem.item->size ) { - rv->size = mdItem.item->size; - } else { - *pError = CKR_BUFFER_TOO_SMALL; - /* Should we set rv->size to mdItem->size? */ - /* rv can't have been allocated */ - rv = (NSSItem *)NULL; - goto done; + else { + if (rv->size >= mdItem.item->size) { + rv->size = mdItem.item->size; + } + else { + *pError = CKR_BUFFER_TOO_SMALL; + /* Should we set rv->size to mdItem->size? */ + /* rv can't have been allocated */ + rv = (NSSItem *)NULL; + goto done; + } } - } - (void)nsslibc_memcpy(rv->data, mdItem.item->data, rv->size); + (void)nsslibc_memcpy(rv->data, mdItem.item->data, rv->size); - if (PR_TRUE == mdItem.needsFreeing) { - PR_ASSERT(fwObject->mdObject->FreeAttribute); - if (fwObject->mdObject->FreeAttribute) { - *pError = fwObject->mdObject->FreeAttribute(&mdItem); + if (PR_TRUE == mdItem.needsFreeing) { + PR_ASSERT(fwObject->mdObject->FreeAttribute); + if (fwObject->mdObject->FreeAttribute) { + *pError = fwObject->mdObject->FreeAttribute(&mdItem); + } } - } - done: - (void)nssCKFWMutex_Unlock(fwObject->mutex); - return rv; +done: + (void)nssCKFWMutex_Unlock(fwObject->mutex); + return rv; } /* @@ -661,128 +633,128 @@ nssCKFWObject_GetAttribute * */ NSS_IMPLEMENT CK_RV -nssCKFWObject_SetAttribute -( - NSSCKFWObject *fwObject, - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value -) +nssCKFWObject_SetAttribute( + NSSCKFWObject *fwObject, + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - if( CKA_TOKEN == attribute ) { - /* - * We're changing from a session object to a token object or - * vice-versa. - */ + if (CKA_TOKEN == attribute) { + /* + * We're changing from a session object to a token object or + * vice-versa. + */ - CK_ATTRIBUTE a; - NSSCKFWObject *newFwObject; - NSSCKFWObject swab; + CK_ATTRIBUTE a; + NSSCKFWObject *newFwObject; + NSSCKFWObject swab; - a.type = CKA_TOKEN; - a.pValue = value->data; - a.ulValueLen = value->size; + a.type = CKA_TOKEN; + a.pValue = value->data; + a.ulValueLen = value->size; - newFwObject = nssCKFWSession_CopyObject(fwSession, fwObject, - &a, 1, &error); - if (!newFwObject) { - if( CKR_OK == error ) { - error = CKR_GENERAL_ERROR; - } - return error; + newFwObject = nssCKFWSession_CopyObject(fwSession, fwObject, + &a, 1, &error); + if (!newFwObject) { + if (CKR_OK == error) { + error = CKR_GENERAL_ERROR; + } + return error; + } + + /* + * Actually, I bet the locking is worse than this.. this part of + * the code could probably use some scrutiny and reworking. + */ + error = nssCKFWMutex_Lock(fwObject->mutex); + if (CKR_OK != error) { + nssCKFWObject_Destroy(newFwObject); + return error; + } + + error = nssCKFWMutex_Lock(newFwObject->mutex); + if (CKR_OK != error) { + nssCKFWMutex_Unlock(fwObject->mutex); + nssCKFWObject_Destroy(newFwObject); + return error; + } + + /* + * Now, we have our new object, but it has a new fwObject pointer, + * while we have to keep the existing one. So quick swap the contents. + */ + swab = *fwObject; + *fwObject = *newFwObject; + *newFwObject = swab; + + /* But keep the mutexes the same */ + swab.mutex = fwObject->mutex; + fwObject->mutex = newFwObject->mutex; + newFwObject->mutex = swab.mutex; + + (void)nssCKFWMutex_Unlock(newFwObject->mutex); + (void)nssCKFWMutex_Unlock(fwObject->mutex); + + /* + * Either remove or add this to the list of session objects + */ + + if (CK_FALSE == *(CK_BBOOL *)value->data) { + /* + * New one is a session object, except since we "stole" the fwObject, it's + * not in the list. Add it. + */ + nssCKFWSession_RegisterSessionObject(fwSession, fwObject); + } + else { + /* + * New one is a token object, except since we "stole" the fwObject, it's + * in the list. Remove it. + */ + if (fwObject->fwSession) { + nssCKFWSession_DeregisterSessionObject(fwObject->fwSession, fwObject); + } + } + + /* + * Now delete the old object. Remember the names have changed. + */ + nssCKFWObject_Destroy(newFwObject); + + return CKR_OK; } + else { + /* + * An "ordinary" change. + */ + if (!fwObject->mdObject->SetAttribute) { + /* We could fake it with copying, like above.. later */ + return CKR_ATTRIBUTE_READ_ONLY; + } - /* - * Actually, I bet the locking is worse than this.. this part of - * the code could probably use some scrutiny and reworking. - */ - error = nssCKFWMutex_Lock(fwObject->mutex); - if( CKR_OK != error ) { - nssCKFWObject_Destroy(newFwObject); - return error; + error = nssCKFWMutex_Lock(fwObject->mutex); + if (CKR_OK != error) { + return error; + } + + error = fwObject->mdObject->SetAttribute(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, + attribute, value); + + (void)nssCKFWMutex_Unlock(fwObject->mutex); + + return error; } - - error = nssCKFWMutex_Lock(newFwObject->mutex); - if( CKR_OK != error ) { - nssCKFWMutex_Unlock(fwObject->mutex); - nssCKFWObject_Destroy(newFwObject); - return error; - } - - /* - * Now, we have our new object, but it has a new fwObject pointer, - * while we have to keep the existing one. So quick swap the contents. - */ - swab = *fwObject; - *fwObject = *newFwObject; - *newFwObject = swab; - - /* But keep the mutexes the same */ - swab.mutex = fwObject->mutex; - fwObject->mutex = newFwObject->mutex; - newFwObject->mutex = swab.mutex; - - (void)nssCKFWMutex_Unlock(newFwObject->mutex); - (void)nssCKFWMutex_Unlock(fwObject->mutex); - - /* - * Either remove or add this to the list of session objects - */ - - if( CK_FALSE == *(CK_BBOOL *)value->data ) { - /* - * New one is a session object, except since we "stole" the fwObject, it's - * not in the list. Add it. - */ - nssCKFWSession_RegisterSessionObject(fwSession, fwObject); - } else { - /* - * New one is a token object, except since we "stole" the fwObject, it's - * in the list. Remove it. - */ - if (fwObject->fwSession) { - nssCKFWSession_DeregisterSessionObject(fwObject->fwSession, fwObject); - } - } - - /* - * Now delete the old object. Remember the names have changed. - */ - nssCKFWObject_Destroy(newFwObject); - - return CKR_OK; - } else { - /* - * An "ordinary" change. - */ - if (!fwObject->mdObject->SetAttribute) { - /* We could fake it with copying, like above.. later */ - return CKR_ATTRIBUTE_READ_ONLY; - } - - error = nssCKFWMutex_Lock(fwObject->mutex); - if( CKR_OK != error ) { - return error; - } - - error = fwObject->mdObject->SetAttribute(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, - attribute, value); - - (void)nssCKFWMutex_Unlock(fwObject->mutex); - - return error; - } } /* @@ -790,42 +762,40 @@ nssCKFWObject_SetAttribute * */ NSS_IMPLEMENT CK_ULONG -nssCKFWObject_GetObjectSize -( - NSSCKFWObject *fwObject, - CK_RV *pError -) +nssCKFWObject_GetObjectSize( + NSSCKFWObject *fwObject, + CK_RV *pError) { - CK_ULONG rv; + CK_ULONG rv; #ifdef NSSDEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if (!fwObject->mdObject->GetObjectSize) { - *pError = CKR_INFORMATION_SENSITIVE; - return (CK_ULONG)0; - } + if (!fwObject->mdObject->GetObjectSize) { + *pError = CKR_INFORMATION_SENSITIVE; + return (CK_ULONG)0; + } - *pError = nssCKFWMutex_Lock(fwObject->mutex); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWMutex_Lock(fwObject->mutex); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } - rv = fwObject->mdObject->GetObjectSize(fwObject->mdObject, fwObject, - fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, - fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, - pError); + rv = fwObject->mdObject->GetObjectSize(fwObject->mdObject, fwObject, + fwObject->mdSession, fwObject->fwSession, fwObject->mdToken, + fwObject->fwToken, fwObject->mdInstance, fwObject->fwInstance, + pError); - (void)nssCKFWMutex_Unlock(fwObject->mutex); - return rv; + (void)nssCKFWMutex_Unlock(fwObject->mutex); + return rv; } /* @@ -833,18 +803,16 @@ nssCKFWObject_GetObjectSize * */ NSS_IMPLEMENT NSSCKMDObject * -NSSCKFWObject_GetMDObject -( - NSSCKFWObject *fwObject -) +NSSCKFWObject_GetMDObject( + NSSCKFWObject *fwObject) { #ifdef DEBUG - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return (NSSCKMDObject *)NULL; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return (NSSCKMDObject *)NULL; + } #endif /* DEBUG */ - return nssCKFWObject_GetMDObject(fwObject); + return nssCKFWObject_GetMDObject(fwObject); } /* @@ -852,24 +820,22 @@ NSSCKFWObject_GetMDObject * */ NSS_IMPLEMENT NSSArena * -NSSCKFWObject_GetArena -( - NSSCKFWObject *fwObject, - CK_RV *pError -) +NSSCKFWObject_GetArena( + NSSCKFWObject *fwObject, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (NSSArena *)NULL; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (NSSArena *)NULL; + } #endif /* DEBUG */ - return nssCKFWObject_GetArena(fwObject, pError); + return nssCKFWObject_GetArena(fwObject, pError); } /* @@ -877,18 +843,16 @@ NSSCKFWObject_GetArena * */ NSS_IMPLEMENT CK_BBOOL -NSSCKFWObject_IsTokenObject -( - NSSCKFWObject *fwObject -) +NSSCKFWObject_IsTokenObject( + NSSCKFWObject *fwObject) { #ifdef DEBUG - if( CKR_OK != nssCKFWObject_verifyPointer(fwObject) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWObject_verifyPointer(fwObject)) { + return CK_FALSE; + } #endif /* DEBUG */ - return nssCKFWObject_IsTokenObject(fwObject); + return nssCKFWObject_IsTokenObject(fwObject); } /* @@ -896,24 +860,22 @@ NSSCKFWObject_IsTokenObject * */ NSS_IMPLEMENT CK_ULONG -NSSCKFWObject_GetAttributeCount -( - NSSCKFWObject *fwObject, - CK_RV *pError -) +NSSCKFWObject_GetAttributeCount( + NSSCKFWObject *fwObject, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } #endif /* DEBUG */ - return nssCKFWObject_GetAttributeCount(fwObject, pError); + return nssCKFWObject_GetAttributeCount(fwObject, pError); } /* @@ -921,27 +883,25 @@ NSSCKFWObject_GetAttributeCount * */ NSS_IMPLEMENT CK_RV -NSSCKFWObject_GetAttributeTypes -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -) +NSSCKFWObject_GetAttributeTypes( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount) { #ifdef DEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; - error = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != error) { + return error; + } - if( (CK_ATTRIBUTE_TYPE_PTR)NULL == typeArray ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_ATTRIBUTE_TYPE_PTR)NULL == typeArray) { + return CKR_ARGUMENTS_BAD; + } #endif /* DEBUG */ - return nssCKFWObject_GetAttributeTypes(fwObject, typeArray, ulCount); + return nssCKFWObject_GetAttributeTypes(fwObject, typeArray, ulCount); } /* @@ -949,25 +909,23 @@ NSSCKFWObject_GetAttributeTypes * */ NSS_IMPLEMENT CK_ULONG -NSSCKFWObject_GetAttributeSize -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +NSSCKFWObject_GetAttributeSize( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } #endif /* DEBUG */ - return nssCKFWObject_GetAttributeSize(fwObject, attribute, pError); + return nssCKFWObject_GetAttributeSize(fwObject, attribute, pError); } /* @@ -975,27 +933,25 @@ NSSCKFWObject_GetAttributeSize * */ NSS_IMPLEMENT NSSItem * -NSSCKFWObject_GetAttribute -( - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *itemOpt, - NSSArena *arenaOpt, - CK_RV *pError -) +NSSCKFWObject_GetAttribute( + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *itemOpt, + NSSArena *arenaOpt, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (NSSItem *)NULL; - } + if (!pError) { + return (NSSItem *)NULL; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (NSSItem *)NULL; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (NSSItem *)NULL; + } #endif /* DEBUG */ - return nssCKFWObject_GetAttribute(fwObject, attribute, itemOpt, arenaOpt, pError); + return nssCKFWObject_GetAttribute(fwObject, attribute, itemOpt, arenaOpt, pError); } /* @@ -1003,22 +959,20 @@ NSSCKFWObject_GetAttribute * */ NSS_IMPLEMENT CK_ULONG -NSSCKFWObject_GetObjectSize -( - NSSCKFWObject *fwObject, - CK_RV *pError -) +NSSCKFWObject_GetObjectSize( + NSSCKFWObject *fwObject, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } #endif /* DEBUG */ - return nssCKFWObject_GetObjectSize(fwObject, pError); + return nssCKFWObject_GetObjectSize(fwObject, pError); } diff --git a/security/nss/lib/ckfw/session.c b/security/nss/lib/ckfw/session.c index 1d0526272ab6..39d7f4f894fe 100644 --- a/security/nss/lib/ckfw/session.c +++ b/security/nss/lib/ckfw/session.c @@ -61,26 +61,26 @@ */ struct NSSCKFWSessionStr { - NSSArena *arena; - NSSCKMDSession *mdSession; - NSSCKFWToken *fwToken; - NSSCKMDToken *mdToken; - NSSCKFWInstance *fwInstance; - NSSCKMDInstance *mdInstance; - CK_VOID_PTR pApplication; - CK_NOTIFY Notify; + NSSArena *arena; + NSSCKMDSession *mdSession; + NSSCKFWToken *fwToken; + NSSCKMDToken *mdToken; + NSSCKFWInstance *fwInstance; + NSSCKMDInstance *mdInstance; + CK_VOID_PTR pApplication; + CK_NOTIFY Notify; - /* - * Everything above is set at creation time, and then not modified. - * The items below are atomic. No locking required. If we fear - * about pointer-copies being nonatomic, we'll lock fwFindObjects. - */ + /* + * Everything above is set at creation time, and then not modified. + * The items below are atomic. No locking required. If we fear + * about pointer-copies being nonatomic, we'll lock fwFindObjects. + */ - CK_BBOOL rw; - NSSCKFWFindObjects *fwFindObjects; - NSSCKFWCryptoOperation *fwOperationArray[NSSCKFWCryptoOperationState_Max]; - nssCKFWHash *sessionObjectHash; - CK_SESSION_HANDLE hSession; + CK_BBOOL rw; + NSSCKFWFindObjects *fwFindObjects; + NSSCKFWCryptoOperation *fwOperationArray[NSSCKFWCryptoOperationState_Max]; + nssCKFWHash *sessionObjectHash; + CK_SESSION_HANDLE hSession; }; #ifdef DEBUG @@ -96,30 +96,24 @@ struct NSSCKFWSessionStr { */ static CK_RV -session_add_pointer -( - const NSSCKFWSession *fwSession -) +session_add_pointer( + const NSSCKFWSession *fwSession) { - return CKR_OK; + return CKR_OK; } static CK_RV -session_remove_pointer -( - const NSSCKFWSession *fwSession -) +session_remove_pointer( + const NSSCKFWSession *fwSession) { - return CKR_OK; + return CKR_OK; } NSS_IMPLEMENT CK_RV -nssCKFWSession_verifyPointer -( - const NSSCKFWSession *fwSession -) +nssCKFWSession_verifyPointer( + const NSSCKFWSession *fwSession) { - return CKR_OK; + return CKR_OK; } #endif /* DEBUG */ @@ -129,95 +123,91 @@ nssCKFWSession_verifyPointer * */ NSS_IMPLEMENT NSSCKFWSession * -nssCKFWSession_Create -( - NSSCKFWToken *fwToken, - CK_BBOOL rw, - CK_VOID_PTR pApplication, - CK_NOTIFY Notify, - CK_RV *pError -) +nssCKFWSession_Create( + NSSCKFWToken *fwToken, + CK_BBOOL rw, + CK_VOID_PTR pApplication, + CK_NOTIFY Notify, + CK_RV *pError) { - NSSArena *arena = (NSSArena *)NULL; - NSSCKFWSession *fwSession; - NSSCKFWSlot *fwSlot; + NSSArena *arena = (NSSArena *)NULL; + NSSCKFWSession *fwSession; + NSSCKFWSlot *fwSlot; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWSession *)NULL; - } + if (!pError) { + return (NSSCKFWSession *)NULL; + } - *pError = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != *pError ) { - return (NSSCKFWSession *)NULL; - } + *pError = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != *pError) { + return (NSSCKFWSession *)NULL; + } #endif /* NSSDEBUG */ - arena = NSSArena_Create(); - if (!arena) { - *pError = CKR_HOST_MEMORY; - return (NSSCKFWSession *)NULL; - } - - fwSession = nss_ZNEW(arena, NSSCKFWSession); - if (!fwSession) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - - fwSession->arena = arena; - fwSession->mdSession = (NSSCKMDSession *)NULL; /* set later */ - fwSession->fwToken = fwToken; - fwSession->mdToken = nssCKFWToken_GetMDToken(fwToken); - - fwSlot = nssCKFWToken_GetFWSlot(fwToken); - fwSession->fwInstance = nssCKFWSlot_GetFWInstance(fwSlot); - fwSession->mdInstance = nssCKFWSlot_GetMDInstance(fwSlot); - - fwSession->rw = rw; - fwSession->pApplication = pApplication; - fwSession->Notify = Notify; - - fwSession->fwFindObjects = (NSSCKFWFindObjects *)NULL; - - fwSession->sessionObjectHash = nssCKFWHash_Create(fwSession->fwInstance, arena, pError); - if (!fwSession->sessionObjectHash) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + arena = NSSArena_Create(); + if (!arena) { + *pError = CKR_HOST_MEMORY; + return (NSSCKFWSession *)NULL; + } + + fwSession = nss_ZNEW(arena, NSSCKFWSession); + if (!fwSession) { + *pError = CKR_HOST_MEMORY; + goto loser; + } + + fwSession->arena = arena; + fwSession->mdSession = (NSSCKMDSession *)NULL; /* set later */ + fwSession->fwToken = fwToken; + fwSession->mdToken = nssCKFWToken_GetMDToken(fwToken); + + fwSlot = nssCKFWToken_GetFWSlot(fwToken); + fwSession->fwInstance = nssCKFWSlot_GetFWInstance(fwSlot); + fwSession->mdInstance = nssCKFWSlot_GetMDInstance(fwSlot); + + fwSession->rw = rw; + fwSession->pApplication = pApplication; + fwSession->Notify = Notify; + + fwSession->fwFindObjects = (NSSCKFWFindObjects *)NULL; + + fwSession->sessionObjectHash = nssCKFWHash_Create(fwSession->fwInstance, arena, pError); + if (!fwSession->sessionObjectHash) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto loser; } - goto loser; - } #ifdef DEBUG - *pError = session_add_pointer(fwSession); - if( CKR_OK != *pError ) { - goto loser; - } + *pError = session_add_pointer(fwSession); + if (CKR_OK != *pError) { + goto loser; + } #endif /* DEBUG */ - return fwSession; + return fwSession; - loser: - if (arena) { - if (fwSession && fwSession->sessionObjectHash) { - (void)nssCKFWHash_Destroy(fwSession->sessionObjectHash); +loser: + if (arena) { + if (fwSession && fwSession->sessionObjectHash) { + (void)nssCKFWHash_Destroy(fwSession->sessionObjectHash); + } + NSSArena_Destroy(arena); } - NSSArena_Destroy(arena); - } - return (NSSCKFWSession *)NULL; + return (NSSCKFWSession *)NULL; } static void -nss_ckfw_session_object_destroy_iterator -( - const void *key, - void *value, - void *closure -) +nss_ckfw_session_object_destroy_iterator( + const void *key, + void *value, + void *closure) { - NSSCKFWObject *fwObject = (NSSCKFWObject *)value; - nssCKFWObject_Finalize(fwObject, PR_TRUE); + NSSCKFWObject *fwObject = (NSSCKFWObject *)value; + nssCKFWObject_Finalize(fwObject, PR_TRUE); } /* @@ -225,51 +215,49 @@ nss_ckfw_session_object_destroy_iterator * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_Destroy -( - NSSCKFWSession *fwSession, - CK_BBOOL removeFromTokenHash -) +nssCKFWSession_Destroy( + NSSCKFWSession *fwSession, + CK_BBOOL removeFromTokenHash) { - CK_RV error = CKR_OK; - nssCKFWHash *sessionObjectHash; - NSSCKFWCryptoOperationState i; + CK_RV error = CKR_OK; + nssCKFWHash *sessionObjectHash; + NSSCKFWCryptoOperationState i; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - if( removeFromTokenHash ) { - error = nssCKFWToken_RemoveSession(fwSession->fwToken, fwSession); - } - - /* - * Invalidate session objects - */ - - sessionObjectHash = fwSession->sessionObjectHash; - fwSession->sessionObjectHash = (nssCKFWHash *)NULL; - - nssCKFWHash_Iterate(sessionObjectHash, - nss_ckfw_session_object_destroy_iterator, - (void *)NULL); - - for (i=0; i < NSSCKFWCryptoOperationState_Max; i++) { - if (fwSession->fwOperationArray[i]) { - nssCKFWCryptoOperation_Destroy(fwSession->fwOperationArray[i]); + if (removeFromTokenHash) { + error = nssCKFWToken_RemoveSession(fwSession->fwToken, fwSession); + } + + /* + * Invalidate session objects + */ + + sessionObjectHash = fwSession->sessionObjectHash; + fwSession->sessionObjectHash = (nssCKFWHash *)NULL; + + nssCKFWHash_Iterate(sessionObjectHash, + nss_ckfw_session_object_destroy_iterator, + (void *)NULL); + + for (i = 0; i < NSSCKFWCryptoOperationState_Max; i++) { + if (fwSession->fwOperationArray[i]) { + nssCKFWCryptoOperation_Destroy(fwSession->fwOperationArray[i]); + } } - } #ifdef DEBUG - (void)session_remove_pointer(fwSession); + (void)session_remove_pointer(fwSession); #endif /* DEBUG */ - (void)nssCKFWHash_Destroy(sessionObjectHash); - NSSArena_Destroy(fwSession->arena); + (void)nssCKFWHash_Destroy(sessionObjectHash); + NSSArena_Destroy(fwSession->arena); - return error; + return error; } /* @@ -277,18 +265,16 @@ nssCKFWSession_Destroy * */ NSS_IMPLEMENT NSSCKMDSession * -nssCKFWSession_GetMDSession -( - NSSCKFWSession *fwSession -) +nssCKFWSession_GetMDSession( + NSSCKFWSession *fwSession) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return (NSSCKMDSession *)NULL; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return (NSSCKMDSession *)NULL; + } #endif /* NSSDEBUG */ - return fwSession->mdSession; + return fwSession->mdSession; } /* @@ -296,24 +282,22 @@ nssCKFWSession_GetMDSession * */ NSS_IMPLEMENT NSSArena * -nssCKFWSession_GetArena -( - NSSCKFWSession *fwSession, - CK_RV *pError -) +nssCKFWSession_GetArena( + NSSCKFWSession *fwSession, + CK_RV *pError) { #ifdef NSSDEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - *pError = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != *pError ) { - return (NSSArena *)NULL; - } + *pError = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != *pError) { + return (NSSArena *)NULL; + } #endif /* NSSDEBUG */ - return fwSession->arena; + return fwSession->arena; } /* @@ -321,34 +305,32 @@ nssCKFWSession_GetArena * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_CallNotification -( - NSSCKFWSession *fwSession, - CK_NOTIFICATION event -) +nssCKFWSession_CallNotification( + NSSCKFWSession *fwSession, + CK_NOTIFICATION event) { - CK_RV error = CKR_OK; - CK_SESSION_HANDLE handle; + CK_RV error = CKR_OK; + CK_SESSION_HANDLE handle; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - if( (CK_NOTIFY)NULL == fwSession->Notify ) { - return CKR_OK; - } + if ((CK_NOTIFY)NULL == fwSession->Notify) { + return CKR_OK; + } - handle = nssCKFWInstance_FindSessionHandle(fwSession->fwInstance, fwSession); - if( (CK_SESSION_HANDLE)0 == handle ) { - return CKR_GENERAL_ERROR; - } + handle = nssCKFWInstance_FindSessionHandle(fwSession->fwInstance, fwSession); + if ((CK_SESSION_HANDLE)0 == handle) { + return CKR_GENERAL_ERROR; + } - error = fwSession->Notify(handle, event, fwSession->pApplication); + error = fwSession->Notify(handle, event, fwSession->pApplication); - return error; + return error; } /* @@ -356,18 +338,16 @@ nssCKFWSession_CallNotification * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWSession_IsRWSession -( - NSSCKFWSession *fwSession -) +nssCKFWSession_IsRWSession( + NSSCKFWSession *fwSession) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - return fwSession->rw; + return fwSession->rw; } /* @@ -375,31 +355,29 @@ nssCKFWSession_IsRWSession * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWSession_IsSO -( - NSSCKFWSession *fwSession -) +nssCKFWSession_IsSO( + NSSCKFWSession *fwSession) { - CK_STATE state; + CK_STATE state; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - state = nssCKFWToken_GetSessionState(fwSession->fwToken); - switch( state ) { - case CKS_RO_PUBLIC_SESSION: - case CKS_RO_USER_FUNCTIONS: - case CKS_RW_PUBLIC_SESSION: - case CKS_RW_USER_FUNCTIONS: - return CK_FALSE; - case CKS_RW_SO_FUNCTIONS: - return CK_TRUE; - default: - return CK_FALSE; - } + state = nssCKFWToken_GetSessionState(fwSession->fwToken); + switch (state) { + case CKS_RO_PUBLIC_SESSION: + case CKS_RO_USER_FUNCTIONS: + case CKS_RW_PUBLIC_SESSION: + case CKS_RW_USER_FUNCTIONS: + return CK_FALSE; + case CKS_RW_SO_FUNCTIONS: + return CK_TRUE; + default: + return CK_FALSE; + } } /* @@ -407,18 +385,16 @@ nssCKFWSession_IsSO * */ NSS_IMPLEMENT NSSCKFWSlot * -nssCKFWSession_GetFWSlot -( - NSSCKFWSession *fwSession -) +nssCKFWSession_GetFWSlot( + NSSCKFWSession *fwSession) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return (NSSCKFWSlot *)NULL; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return (NSSCKFWSlot *)NULL; + } #endif /* NSSDEBUG */ - return nssCKFWToken_GetFWSlot(fwSession->fwToken); + return nssCKFWToken_GetFWSlot(fwSession->fwToken); } /* @@ -426,18 +402,16 @@ nssCKFWSession_GetFWSlot * */ NSS_IMPLEMENT CK_STATE -nssCKFWSession_GetSessionState -( - NSSCKFWSession *fwSession -) +nssCKFWSession_GetSessionState( + NSSCKFWSession *fwSession) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return CKS_RO_PUBLIC_SESSION; /* whatever */ - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return CKS_RO_PUBLIC_SESSION; /* whatever */ + } #endif /* NSSDEBUG */ - return nssCKFWToken_GetSessionState(fwSession->fwToken); + return nssCKFWToken_GetSessionState(fwSession->fwToken); } /* @@ -445,33 +419,31 @@ nssCKFWSession_GetSessionState * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_SetFWFindObjects -( - NSSCKFWSession *fwSession, - NSSCKFWFindObjects *fwFindObjects -) +nssCKFWSession_SetFWFindObjects( + NSSCKFWSession *fwSession, + NSSCKFWFindObjects *fwFindObjects) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #endif /* NSSDEBUG */ #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - /* fwFindObjects may be null */ +/* fwFindObjects may be null */ #endif /* NSSDEBUG */ - if ((fwSession->fwFindObjects) && - (fwFindObjects)) { - return CKR_OPERATION_ACTIVE; - } + if ((fwSession->fwFindObjects) && + (fwFindObjects)) { + return CKR_OPERATION_ACTIVE; + } - fwSession->fwFindObjects = fwFindObjects; + fwSession->fwFindObjects = fwFindObjects; - return CKR_OK; + return CKR_OK; } /* @@ -479,29 +451,27 @@ nssCKFWSession_SetFWFindObjects * */ NSS_IMPLEMENT NSSCKFWFindObjects * -nssCKFWSession_GetFWFindObjects -( - NSSCKFWSession *fwSession, - CK_RV *pError -) +nssCKFWSession_GetFWFindObjects( + NSSCKFWSession *fwSession, + CK_RV *pError) { #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWFindObjects *)NULL; - } + if (!pError) { + return (NSSCKFWFindObjects *)NULL; + } - *pError = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != *pError ) { - return (NSSCKFWFindObjects *)NULL; - } + *pError = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != *pError) { + return (NSSCKFWFindObjects *)NULL; + } #endif /* NSSDEBUG */ - if (!fwSession->fwFindObjects) { - *pError = CKR_OPERATION_NOT_INITIALIZED; - return (NSSCKFWFindObjects *)NULL; - } + if (!fwSession->fwFindObjects) { + *pError = CKR_OPERATION_NOT_INITIALIZED; + return (NSSCKFWFindObjects *)NULL; + } - return fwSession->fwFindObjects; + return fwSession->fwFindObjects; } /* @@ -509,34 +479,32 @@ nssCKFWSession_GetFWFindObjects * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_SetMDSession -( - NSSCKFWSession *fwSession, - NSSCKMDSession *mdSession -) +nssCKFWSession_SetMDSession( + NSSCKFWSession *fwSession, + NSSCKMDSession *mdSession) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #endif /* NSSDEBUG */ #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!mdSession) { - return CKR_ARGUMENTS_BAD; - } + if (!mdSession) { + return CKR_ARGUMENTS_BAD; + } #endif /* NSSDEBUG */ - if (fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } - fwSession->mdSession = mdSession; + fwSession->mdSession = mdSession; - return CKR_OK; + return CKR_OK; } /* @@ -544,30 +512,28 @@ nssCKFWSession_SetMDSession * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_SetHandle -( - NSSCKFWSession *fwSession, - CK_SESSION_HANDLE hSession -) +nssCKFWSession_SetHandle( + NSSCKFWSession *fwSession, + CK_SESSION_HANDLE hSession) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #endif /* NSSDEBUG */ #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - if( (CK_SESSION_HANDLE)0 != fwSession->hSession ) { - return CKR_GENERAL_ERROR; - } + if ((CK_SESSION_HANDLE)0 != fwSession->hSession) { + return CKR_GENERAL_ERROR; + } - fwSession->hSession = hSession; + fwSession->hSession = hSession; - return CKR_OK; + return CKR_OK; } /* @@ -575,18 +541,16 @@ nssCKFWSession_SetHandle * */ NSS_IMPLEMENT CK_SESSION_HANDLE -nssCKFWSession_GetHandle -( - NSSCKFWSession *fwSession -) +nssCKFWSession_GetHandle( + NSSCKFWSession *fwSession) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return NULL; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return NULL; + } #endif /* NSSDEBUG */ - return fwSession->hSession; + return fwSession->hSession; } /* @@ -594,25 +558,23 @@ nssCKFWSession_GetHandle * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_RegisterSessionObject -( - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWSession_RegisterSessionObject( + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { - CK_RV rv = CKR_OK; + CK_RV rv = CKR_OK; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return CKR_GENERAL_ERROR; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - if (fwSession->sessionObjectHash) { - rv = nssCKFWHash_Add(fwSession->sessionObjectHash, fwObject, fwObject); - } + if (fwSession->sessionObjectHash) { + rv = nssCKFWHash_Add(fwSession->sessionObjectHash, fwObject, fwObject); + } - return rv; + return rv; } /* @@ -620,23 +582,21 @@ nssCKFWSession_RegisterSessionObject * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_DeregisterSessionObject -( - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject -) +nssCKFWSession_DeregisterSessionObject( + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return CKR_GENERAL_ERROR; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - if (fwSession->sessionObjectHash) { - nssCKFWHash_Remove(fwSession->sessionObjectHash, fwObject); - } + if (fwSession->sessionObjectHash) { + nssCKFWHash_Remove(fwSession->sessionObjectHash, fwObject); + } - return CKR_OK; + return CKR_OK; } /* @@ -644,28 +604,26 @@ nssCKFWSession_DeregisterSessionObject * */ NSS_IMPLEMENT CK_ULONG -nssCKFWSession_GetDeviceError -( - NSSCKFWSession *fwSession -) +nssCKFWSession_GetDeviceError( + NSSCKFWSession *fwSession) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return (CK_ULONG)0; + } - if (!fwSession->mdSession) { - return (CK_ULONG)0; - } + if (!fwSession->mdSession) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if (!fwSession->mdSession->GetDeviceError) { - return (CK_ULONG)0; - } + if (!fwSession->mdSession->GetDeviceError) { + return (CK_ULONG)0; + } - return fwSession->mdSession->GetDeviceError(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance); + return fwSession->mdSession->GetDeviceError(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance); } /* @@ -673,116 +631,119 @@ nssCKFWSession_GetDeviceError * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_Login -( - NSSCKFWSession *fwSession, - CK_USER_TYPE userType, - NSSItem *pin -) +nssCKFWSession_Login( + NSSCKFWSession *fwSession, + CK_USER_TYPE userType, + NSSItem *pin) { - CK_RV error = CKR_OK; - CK_STATE oldState; - CK_STATE newState; + CK_RV error = CKR_OK; + CK_STATE oldState; + CK_STATE newState; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } - - switch( userType ) { - case CKU_SO: - case CKU_USER: - break; - default: - return CKR_USER_TYPE_INVALID; - } - - if (!pin) { - if( CK_TRUE != nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken) ) { - return CKR_ARGUMENTS_BAD; + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; } - } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + switch (userType) { + case CKU_SO: + case CKU_USER: + break; + default: + return CKR_USER_TYPE_INVALID; + } + + if (!pin) { + if (CK_TRUE != nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken)) { + return CKR_ARGUMENTS_BAD; + } + } + + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - oldState = nssCKFWToken_GetSessionState(fwSession->fwToken); + oldState = nssCKFWToken_GetSessionState(fwSession->fwToken); - /* - * It's not clear what happens when you're already logged in. - * I'll just fail; but if we decide to change, the logic is - * all right here. - */ - - if( CKU_SO == userType ) { - switch( oldState ) { - case CKS_RO_PUBLIC_SESSION: - /* - * There's no such thing as a read-only security officer - * session, so fail. The error should be CKR_SESSION_READ_ONLY, - * except that C_Login isn't defined to return that. So we'll - * do CKR_SESSION_READ_ONLY_EXISTS, which is what is documented. - */ - return CKR_SESSION_READ_ONLY_EXISTS; - case CKS_RO_USER_FUNCTIONS: - return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; - case CKS_RW_PUBLIC_SESSION: - newState = CKS_RW_SO_FUNCTIONS; - break; - case CKS_RW_USER_FUNCTIONS: - return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; - case CKS_RW_SO_FUNCTIONS: - return CKR_USER_ALREADY_LOGGED_IN; - default: - return CKR_GENERAL_ERROR; - } - } else /* CKU_USER == userType */ { - switch( oldState ) { - case CKS_RO_PUBLIC_SESSION: - newState = CKS_RO_USER_FUNCTIONS; - break; - case CKS_RO_USER_FUNCTIONS: - return CKR_USER_ALREADY_LOGGED_IN; - case CKS_RW_PUBLIC_SESSION: - newState = CKS_RW_USER_FUNCTIONS; - break; - case CKS_RW_USER_FUNCTIONS: - return CKR_USER_ALREADY_LOGGED_IN; - case CKS_RW_SO_FUNCTIONS: - return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; - default: - return CKR_GENERAL_ERROR; - } - } - - /* - * So now we're in one of three cases: - * - * Old == CKS_RW_PUBLIC_SESSION, New == CKS_RW_SO_FUNCTIONS; - * Old == CKS_RW_PUBLIC_SESSION, New == CKS_RW_USER_FUNCTIONS; - * Old == CKS_RO_PUBLIC_SESSION, New == CKS_RO_USER_FUNCTIONS; - */ - - if (!fwSession->mdSession->Login) { /* - * The Module doesn't want to be informed (or check the pin) - * it'll just rely on the Framework as needed. + * It's not clear what happens when you're already logged in. + * I'll just fail; but if we decide to change, the logic is + * all right here. */ - ; - } else { - error = fwSession->mdSession->Login(fwSession->mdSession, fwSession, - fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, userType, pin, oldState, newState); - if( CKR_OK != error ) { - return error; - } - } - (void)nssCKFWToken_SetSessionState(fwSession->fwToken, newState); - return CKR_OK; + if (CKU_SO == userType) { + switch (oldState) { + case CKS_RO_PUBLIC_SESSION: + /* + * There's no such thing as a read-only security officer + * session, so fail. The error should be CKR_SESSION_READ_ONLY, + * except that C_Login isn't defined to return that. So we'll + * do CKR_SESSION_READ_ONLY_EXISTS, which is what is documented. + */ + return CKR_SESSION_READ_ONLY_EXISTS; + case CKS_RO_USER_FUNCTIONS: + return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; + case CKS_RW_PUBLIC_SESSION: + newState = + CKS_RW_SO_FUNCTIONS; + break; + case CKS_RW_USER_FUNCTIONS: + return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; + case CKS_RW_SO_FUNCTIONS: + return CKR_USER_ALREADY_LOGGED_IN; + default: + return CKR_GENERAL_ERROR; + } + } + else /* CKU_USER == userType */ { + switch (oldState) { + case CKS_RO_PUBLIC_SESSION: + newState = + CKS_RO_USER_FUNCTIONS; + break; + case CKS_RO_USER_FUNCTIONS: + return CKR_USER_ALREADY_LOGGED_IN; + case CKS_RW_PUBLIC_SESSION: + newState = + CKS_RW_USER_FUNCTIONS; + break; + case CKS_RW_USER_FUNCTIONS: + return CKR_USER_ALREADY_LOGGED_IN; + case CKS_RW_SO_FUNCTIONS: + return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; + default: + return CKR_GENERAL_ERROR; + } + } + + /* + * So now we're in one of three cases: + * + * Old == CKS_RW_PUBLIC_SESSION, New == CKS_RW_SO_FUNCTIONS; + * Old == CKS_RW_PUBLIC_SESSION, New == CKS_RW_USER_FUNCTIONS; + * Old == CKS_RO_PUBLIC_SESSION, New == CKS_RO_USER_FUNCTIONS; + */ + + if (!fwSession->mdSession->Login) { + /* + * The Module doesn't want to be informed (or check the pin) + * it'll just rely on the Framework as needed. + */ + ; + } + else { + error = fwSession->mdSession->Login(fwSession->mdSession, fwSession, + fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, userType, pin, oldState, newState); + if (CKR_OK != error) { + return error; + } + } + + (void)nssCKFWToken_SetSessionState(fwSession->fwToken, newState); + return CKR_OK; } /* @@ -790,74 +751,73 @@ nssCKFWSession_Login * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_Logout -( - NSSCKFWSession *fwSession -) +nssCKFWSession_Logout( + NSSCKFWSession *fwSession) { - CK_RV error = CKR_OK; - CK_STATE oldState; - CK_STATE newState; + CK_RV error = CKR_OK; + CK_STATE oldState; + CK_STATE newState; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - oldState = nssCKFWToken_GetSessionState(fwSession->fwToken); + oldState = nssCKFWToken_GetSessionState(fwSession->fwToken); - switch( oldState ) { - case CKS_RO_PUBLIC_SESSION: - return CKR_USER_NOT_LOGGED_IN; - case CKS_RO_USER_FUNCTIONS: - newState = CKS_RO_PUBLIC_SESSION; - break; - case CKS_RW_PUBLIC_SESSION: - return CKR_USER_NOT_LOGGED_IN; - case CKS_RW_USER_FUNCTIONS: - newState = CKS_RW_PUBLIC_SESSION; - break; - case CKS_RW_SO_FUNCTIONS: - newState = CKS_RW_PUBLIC_SESSION; - break; - default: - return CKR_GENERAL_ERROR; - } - - /* - * So now we're in one of three cases: - * - * Old == CKS_RW_SO_FUNCTIONS, New == CKS_RW_PUBLIC_SESSION; - * Old == CKS_RW_USER_FUNCTIONS, New == CKS_RW_PUBLIC_SESSION; - * Old == CKS_RO_USER_FUNCTIONS, New == CKS_RO_PUBLIC_SESSION; - */ - - if (!fwSession->mdSession->Logout) { - /* - * The Module doesn't want to be informed. Okay. - */ - ; - } else { - error = fwSession->mdSession->Logout(fwSession->mdSession, fwSession, - fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, oldState, newState); - if( CKR_OK != error ) { - /* - * Now what?! A failure really should end up with the Framework - * considering it logged out, right? - */ - ; + switch (oldState) { + case CKS_RO_PUBLIC_SESSION: + return CKR_USER_NOT_LOGGED_IN; + case CKS_RO_USER_FUNCTIONS: + newState = CKS_RO_PUBLIC_SESSION; + break; + case CKS_RW_PUBLIC_SESSION: + return CKR_USER_NOT_LOGGED_IN; + case CKS_RW_USER_FUNCTIONS: + newState = CKS_RW_PUBLIC_SESSION; + break; + case CKS_RW_SO_FUNCTIONS: + newState = CKS_RW_PUBLIC_SESSION; + break; + default: + return CKR_GENERAL_ERROR; } - } - (void)nssCKFWToken_SetSessionState(fwSession->fwToken, newState); - return error; + /* + * So now we're in one of three cases: + * + * Old == CKS_RW_SO_FUNCTIONS, New == CKS_RW_PUBLIC_SESSION; + * Old == CKS_RW_USER_FUNCTIONS, New == CKS_RW_PUBLIC_SESSION; + * Old == CKS_RO_USER_FUNCTIONS, New == CKS_RO_PUBLIC_SESSION; + */ + + if (!fwSession->mdSession->Logout) { + /* + * The Module doesn't want to be informed. Okay. + */ + ; + } + else { + error = fwSession->mdSession->Logout(fwSession->mdSession, fwSession, + fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, oldState, newState); + if (CKR_OK != error) { + /* + * Now what?! A failure really should end up with the Framework + * considering it logged out, right? + */ + ; + } + } + + (void)nssCKFWToken_SetSessionState(fwSession->fwToken, newState); + return error; } /* @@ -865,47 +825,45 @@ nssCKFWSession_Logout * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_InitPIN -( - NSSCKFWSession *fwSession, - NSSItem *pin -) +nssCKFWSession_InitPIN( + NSSCKFWSession *fwSession, + NSSItem *pin) { - CK_RV error = CKR_OK; - CK_STATE state; + CK_RV error = CKR_OK; + CK_STATE state; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - state = nssCKFWToken_GetSessionState(fwSession->fwToken); - if( CKS_RW_SO_FUNCTIONS != state ) { - return CKR_USER_NOT_LOGGED_IN; - } - - if (!pin) { - CK_BBOOL has = nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken); - if( CK_TRUE != has ) { - return CKR_ARGUMENTS_BAD; + state = nssCKFWToken_GetSessionState(fwSession->fwToken); + if (CKS_RW_SO_FUNCTIONS != state) { + return CKR_USER_NOT_LOGGED_IN; } - } - if (!fwSession->mdSession->InitPIN) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (!pin) { + CK_BBOOL has = nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken); + if (CK_TRUE != has) { + return CKR_ARGUMENTS_BAD; + } + } - error = fwSession->mdSession->InitPIN(fwSession->mdSession, fwSession, - fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, pin); + if (!fwSession->mdSession->InitPIN) { + return CKR_TOKEN_WRITE_PROTECTED; + } - return error; + error = fwSession->mdSession->InitPIN(fwSession->mdSession, fwSession, + fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, pin); + + return error; } /* @@ -913,49 +871,47 @@ nssCKFWSession_InitPIN * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_SetPIN -( - NSSCKFWSession *fwSession, - NSSItem *newPin, - NSSItem *oldPin -) +nssCKFWSession_SetPIN( + NSSCKFWSession *fwSession, + NSSItem *oldPin, + NSSItem *newPin) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - if (!newPin) { - CK_BBOOL has = nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken); - if( CK_TRUE != has ) { - return CKR_ARGUMENTS_BAD; + if (!newPin) { + CK_BBOOL has = nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken); + if (CK_TRUE != has) { + return CKR_ARGUMENTS_BAD; + } } - } - if (!oldPin) { - CK_BBOOL has = nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken); - if( CK_TRUE != has ) { - return CKR_ARGUMENTS_BAD; + if (!oldPin) { + CK_BBOOL has = nssCKFWToken_GetHasProtectedAuthenticationPath(fwSession->fwToken); + if (CK_TRUE != has) { + return CKR_ARGUMENTS_BAD; + } } - } - if (!fwSession->mdSession->SetPIN) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (!fwSession->mdSession->SetPIN) { + return CKR_TOKEN_WRITE_PROTECTED; + } - error = fwSession->mdSession->SetPIN(fwSession->mdSession, fwSession, - fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, newPin, oldPin); + error = fwSession->mdSession->SetPIN(fwSession->mdSession, fwSession, + fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, oldPin, newPin); - return error; + return error; } /* @@ -963,54 +919,52 @@ nssCKFWSession_SetPIN * */ NSS_IMPLEMENT CK_ULONG -nssCKFWSession_GetOperationStateLen -( - NSSCKFWSession *fwSession, - CK_RV *pError -) +nssCKFWSession_GetOperationStateLen( + NSSCKFWSession *fwSession, + CK_RV *pError) { - CK_ULONG mdAmt; - CK_ULONG fwAmt; + CK_ULONG mdAmt; + CK_ULONG fwAmt; #ifdef NSSDEBUG - if (!pError) { - return (CK_ULONG)0; - } + if (!pError) { + return (CK_ULONG)0; + } - *pError = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != *pError ) { - return (CK_ULONG)0; - } + *pError = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != *pError) { + return (CK_ULONG)0; + } - if (!fwSession->mdSession) { - *pError = CKR_GENERAL_ERROR; - return (CK_ULONG)0; - } + if (!fwSession->mdSession) { + *pError = CKR_GENERAL_ERROR; + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if (!fwSession->mdSession->GetOperationStateLen) { - *pError = CKR_STATE_UNSAVEABLE; - return (CK_ULONG)0; - } + if (!fwSession->mdSession->GetOperationStateLen) { + *pError = CKR_STATE_UNSAVEABLE; + return (CK_ULONG)0; + } - /* - * We could check that the session is actually in some state.. - */ + /* + * We could check that the session is actually in some state.. + */ - mdAmt = fwSession->mdSession->GetOperationStateLen(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, pError); + mdAmt = fwSession->mdSession->GetOperationStateLen(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, pError); - if( ((CK_ULONG)0 == mdAmt) && (CKR_OK != *pError) ) { - return (CK_ULONG)0; - } + if (((CK_ULONG)0 == mdAmt) && (CKR_OK != *pError)) { + return (CK_ULONG)0; + } - /* - * Add a bit of sanity-checking - */ - fwAmt = mdAmt + 2*sizeof(CK_ULONG); + /* + * Add a bit of sanity-checking + */ + fwAmt = mdAmt + 2 * sizeof(CK_ULONG); - return fwAmt; + return fwAmt; } /* @@ -1018,82 +972,80 @@ nssCKFWSession_GetOperationStateLen * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_GetOperationState -( - NSSCKFWSession *fwSession, - NSSItem *buffer -) +nssCKFWSession_GetOperationState( + NSSCKFWSession *fwSession, + NSSItem *buffer) { - CK_RV error = CKR_OK; - CK_ULONG fwAmt; - CK_ULONG *ulBuffer; - NSSItem i2; - CK_ULONG n, i; + CK_RV error = CKR_OK; + CK_ULONG fwAmt; + CK_ULONG *ulBuffer; + NSSItem i2; + CK_ULONG n, i; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!buffer) { - return CKR_ARGUMENTS_BAD; - } + if (!buffer) { + return CKR_ARGUMENTS_BAD; + } - if (!buffer->data) { - return CKR_ARGUMENTS_BAD; - } + if (!buffer->data) { + return CKR_ARGUMENTS_BAD; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - if (!fwSession->mdSession->GetOperationState) { - return CKR_STATE_UNSAVEABLE; - } + if (!fwSession->mdSession->GetOperationState) { + return CKR_STATE_UNSAVEABLE; + } - /* - * Sanity-check the caller's buffer. - */ + /* + * Sanity-check the caller's buffer. + */ - error = CKR_OK; - fwAmt = nssCKFWSession_GetOperationStateLen(fwSession, &error); - if( ((CK_ULONG)0 == fwAmt) && (CKR_OK != error) ) { - return error; - } + error = CKR_OK; + fwAmt = nssCKFWSession_GetOperationStateLen(fwSession, &error); + if (((CK_ULONG)0 == fwAmt) && (CKR_OK != error)) { + return error; + } - if( buffer->size < fwAmt ) { - return CKR_BUFFER_TOO_SMALL; - } + if (buffer->size < fwAmt) { + return CKR_BUFFER_TOO_SMALL; + } - ulBuffer = (CK_ULONG *)buffer->data; + ulBuffer = (CK_ULONG *)buffer->data; - i2.size = buffer->size - 2*sizeof(CK_ULONG); - i2.data = (void *)&ulBuffer[2]; + i2.size = buffer->size - 2 * sizeof(CK_ULONG); + i2.data = (void *)&ulBuffer[2]; - error = fwSession->mdSession->GetOperationState(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance, &i2); + error = fwSession->mdSession->GetOperationState(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance, &i2); - if( CKR_OK != error ) { - return error; - } + if (CKR_OK != error) { + return error; + } - /* - * Add a little integrety/identity check. - * NOTE: right now, it's pretty stupid. - * A CRC or something would be better. - */ + /* + * Add a little integrety/identity check. + * NOTE: right now, it's pretty stupid. + * A CRC or something would be better. + */ - ulBuffer[0] = 0x434b4657; /* CKFW */ - ulBuffer[1] = 0; - n = i2.size/sizeof(CK_ULONG); - for( i = 0; i < n; i++ ) { - ulBuffer[1] ^= ulBuffer[2+i]; - } + ulBuffer[0] = 0x434b4657; /* CKFW */ + ulBuffer[1] = 0; + n = i2.size / sizeof(CK_ULONG); + for (i = 0; i < n; i++) { + ulBuffer[1] ^= ulBuffer[2 + i]; + } - return CKR_OK; + return CKR_OK; } /* @@ -1101,126 +1053,125 @@ nssCKFWSession_GetOperationState * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_SetOperationState -( - NSSCKFWSession *fwSession, - NSSItem *state, - NSSCKFWObject *encryptionKey, - NSSCKFWObject *authenticationKey -) +nssCKFWSession_SetOperationState( + NSSCKFWSession *fwSession, + NSSItem *state, + NSSCKFWObject *encryptionKey, + NSSCKFWObject *authenticationKey) { - CK_RV error = CKR_OK; - CK_ULONG *ulBuffer; - CK_ULONG n, i; - CK_ULONG x; - NSSItem s; - NSSCKMDObject *mdek; - NSSCKMDObject *mdak; + CK_RV error = CKR_OK; + CK_ULONG *ulBuffer; + CK_ULONG n, i; + CK_ULONG x; + NSSItem s; + NSSCKMDObject *mdek; + NSSCKMDObject *mdak; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } - - if (!state) { - return CKR_ARGUMENTS_BAD; - } - - if (!state->data) { - return CKR_ARGUMENTS_BAD; - } - - if (encryptionKey) { - error = nssCKFWObject_verifyPointer(encryptionKey); - if( CKR_OK != error ) { - return error; + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; } - } - if (authenticationKey) { - error = nssCKFWObject_verifyPointer(authenticationKey); - if( CKR_OK != error ) { - return error; + if (!state) { + return CKR_ARGUMENTS_BAD; } - } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!state->data) { + return CKR_ARGUMENTS_BAD; + } + + if (encryptionKey) { + error = nssCKFWObject_verifyPointer(encryptionKey); + if (CKR_OK != error) { + return error; + } + } + + if (authenticationKey) { + error = nssCKFWObject_verifyPointer(authenticationKey); + if (CKR_OK != error) { + return error; + } + } + + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - ulBuffer = (CK_ULONG *)state->data; - if( 0x43b4657 != ulBuffer[0] ) { - return CKR_SAVED_STATE_INVALID; - } - n = (state->size / sizeof(CK_ULONG)) - 2; - x = (CK_ULONG)0; - for( i = 0; i < n; i++ ) { - x ^= ulBuffer[2+i]; - } + ulBuffer = (CK_ULONG *)state->data; + if (0x43b4657 != ulBuffer[0]) { + return CKR_SAVED_STATE_INVALID; + } + n = (state->size / sizeof(CK_ULONG)) - 2; + x = (CK_ULONG)0; + for (i = 0; i < n; i++) { + x ^= ulBuffer[2 + i]; + } - if( x != ulBuffer[1] ) { - return CKR_SAVED_STATE_INVALID; - } + if (x != ulBuffer[1]) { + return CKR_SAVED_STATE_INVALID; + } - if (!fwSession->mdSession->SetOperationState) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession->SetOperationState) { + return CKR_GENERAL_ERROR; + } - s.size = state->size - 2*sizeof(CK_ULONG); - s.data = (void *)&ulBuffer[2]; + s.size = state->size - 2 * sizeof(CK_ULONG); + s.data = (void *)&ulBuffer[2]; - if (encryptionKey) { - mdek = nssCKFWObject_GetMDObject(encryptionKey); - } else { - mdek = (NSSCKMDObject *)NULL; - } + if (encryptionKey) { + mdek = nssCKFWObject_GetMDObject(encryptionKey); + } + else { + mdek = (NSSCKMDObject *)NULL; + } - if (authenticationKey) { - mdak = nssCKFWObject_GetMDObject(authenticationKey); - } else { - mdak = (NSSCKMDObject *)NULL; - } + if (authenticationKey) { + mdak = nssCKFWObject_GetMDObject(authenticationKey); + } + else { + mdak = (NSSCKMDObject *)NULL; + } - error = fwSession->mdSession->SetOperationState(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, &s, mdek, encryptionKey, mdak, authenticationKey); + error = fwSession->mdSession->SetOperationState(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, &s, mdek, encryptionKey, mdak, authenticationKey); - if( CKR_OK != error ) { - return error; - } + if (CKR_OK != error) { + return error; + } - /* - * Here'd we restore any session data - */ - - return CKR_OK; + /* + * Here'd we restore any session data + */ + + return CKR_OK; } static CK_BBOOL -nss_attributes_form_token_object -( - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount -) +nss_attributes_form_token_object( + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount) { - CK_ULONG i; - CK_BBOOL rv; + CK_ULONG i; + CK_BBOOL rv; - for( i = 0; i < ulAttributeCount; i++ ) { - if( CKA_TOKEN == pTemplate[i].type ) { - /* If we sanity-check, we can remove this sizeof check */ - if( sizeof(CK_BBOOL) == pTemplate[i].ulValueLen ) { - (void)nsslibc_memcpy(&rv, pTemplate[i].pValue, sizeof(CK_BBOOL)); - return rv; - } else { - return CK_FALSE; - } + for (i = 0; i < ulAttributeCount; i++) { + if (CKA_TOKEN == pTemplate[i].type) { + /* If we sanity-check, we can remove this sizeof check */ + if (sizeof(CK_BBOOL) == pTemplate[i].ulValueLen) { + (void)nsslibc_memcpy(&rv, pTemplate[i].pValue, sizeof(CK_BBOOL)); + return rv; + } + else { + return CK_FALSE; + } + } } - } - return CK_FALSE; + return CK_FALSE; } /* @@ -1228,133 +1179,136 @@ nss_attributes_form_token_object * */ NSS_IMPLEMENT NSSCKFWObject * -nssCKFWSession_CreateObject -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nssCKFWSession_CreateObject( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSArena *arena; - NSSCKMDObject *mdObject; - NSSCKFWObject *fwObject; - CK_BBOOL isTokenObject; + NSSArena *arena; + NSSCKMDObject *mdObject; + NSSCKFWObject *fwObject; + CK_BBOOL isTokenObject; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWObject *)NULL; - } + if (!pError) { + return (NSSCKFWObject *)NULL; + } - *pError = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != pError ) { - return (NSSCKFWObject *)NULL; - } + *pError = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != pError) { + return (NSSCKFWObject *)NULL; + } - if( (CK_ATTRIBUTE_PTR)NULL == pTemplate ) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWObject *)NULL; - } + if ((CK_ATTRIBUTE_PTR)NULL == pTemplate) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWObject *)NULL; + } - if (!fwSession->mdSession) { - *pError = CKR_GENERAL_ERROR; - return (NSSCKFWObject *)NULL; - } + if (!fwSession->mdSession) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWObject *)NULL; + } #endif /* NSSDEBUG */ - /* - * Here would be an excellent place to sanity-check the object. - */ + /* + * Here would be an excellent place to sanity-check the object. + */ - isTokenObject = nss_attributes_form_token_object(pTemplate, ulAttributeCount); - if( CK_TRUE == isTokenObject ) { - /* === TOKEN OBJECT === */ + isTokenObject = nss_attributes_form_token_object(pTemplate, ulAttributeCount); + if (CK_TRUE == isTokenObject) { + /* === TOKEN OBJECT === */ - if (!fwSession->mdSession->CreateObject) { - *pError = CKR_TOKEN_WRITE_PROTECTED; - return (NSSCKFWObject *)NULL; + if (!fwSession->mdSession->CreateObject) { + *pError = CKR_TOKEN_WRITE_PROTECTED; + return (NSSCKFWObject *)NULL; + } + + arena = nssCKFWToken_GetArena(fwSession->fwToken, pError); + if (!arena) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWObject *)NULL; + } + + goto callmdcreateobject; + } + else { + /* === SESSION OBJECT === */ + + arena = nssCKFWSession_GetArena(fwSession, pError); + if (!arena) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWObject *)NULL; + } + + if (CK_TRUE == nssCKFWInstance_GetModuleHandlesSessionObjects( + fwSession->fwInstance)) { + /* --- module handles the session object -- */ + + if (!fwSession->mdSession->CreateObject) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWObject *)NULL; + } + + goto callmdcreateobject; + } + else { + /* --- framework handles the session object -- */ + mdObject = nssCKMDSessionObject_Create(fwSession->fwToken, + arena, pTemplate, ulAttributeCount, pError); + goto gotmdobject; + } } - arena = nssCKFWToken_GetArena(fwSession->fwToken, pError); - if (!arena) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWObject *)NULL; - } +callmdcreateobject: + mdObject = fwSession->mdSession->CreateObject(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance, arena, pTemplate, + ulAttributeCount, pError); - goto callmdcreateobject; - } else { - /* === SESSION OBJECT === */ - - arena = nssCKFWSession_GetArena(fwSession, pError); - if (!arena) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWObject *)NULL; - } - - if( CK_TRUE == nssCKFWInstance_GetModuleHandlesSessionObjects( - fwSession->fwInstance) ) { - /* --- module handles the session object -- */ - - if (!fwSession->mdSession->CreateObject) { - *pError = CKR_GENERAL_ERROR; +gotmdobject: + if (!mdObject) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } return (NSSCKFWObject *)NULL; - } - - goto callmdcreateobject; - } else { - /* --- framework handles the session object -- */ - mdObject = nssCKMDSessionObject_Create(fwSession->fwToken, - arena, pTemplate, ulAttributeCount, pError); - goto gotmdobject; } - } - callmdcreateobject: - mdObject = fwSession->mdSession->CreateObject(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance, arena, pTemplate, - ulAttributeCount, pError); + fwObject = nssCKFWObject_Create(arena, mdObject, + isTokenObject ? + NULL + : + fwSession, + fwSession->fwToken, fwSession->fwInstance, pError); + if (!fwObject) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } - gotmdobject: - if (!mdObject) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWObject *)NULL; - } + if (mdObject->Destroy) { + (void)mdObject->Destroy(mdObject, (NSSCKFWObject *)NULL, + fwSession->mdSession, fwSession, fwSession->mdToken, + fwSession->fwToken, fwSession->mdInstance, fwSession->fwInstance); + } - fwObject = nssCKFWObject_Create(arena, mdObject, - isTokenObject ? NULL : fwSession, - fwSession->fwToken, fwSession->fwInstance, pError); - if (!fwObject) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - - if (mdObject->Destroy) { - (void)mdObject->Destroy(mdObject, (NSSCKFWObject *)NULL, - fwSession->mdSession, fwSession, fwSession->mdToken, - fwSession->fwToken, fwSession->mdInstance, fwSession->fwInstance); - } - - return (NSSCKFWObject *)NULL; - } - - if( CK_FALSE == isTokenObject ) { - if( CK_FALSE == nssCKFWHash_Exists(fwSession->sessionObjectHash, fwObject) ) { - *pError = nssCKFWHash_Add(fwSession->sessionObjectHash, fwObject, fwObject); - if( CKR_OK != *pError ) { - nssCKFWObject_Finalize(fwObject, PR_TRUE); return (NSSCKFWObject *)NULL; - } } - } - - return fwObject; + + if (CK_FALSE == isTokenObject) { + if (CK_FALSE == nssCKFWHash_Exists(fwSession->sessionObjectHash, fwObject)) { + *pError = nssCKFWHash_Add(fwSession->sessionObjectHash, fwObject, fwObject); + if (CKR_OK != *pError) { + nssCKFWObject_Finalize(fwObject, PR_TRUE); + return (NSSCKFWObject *)NULL; + } + } + } + + return fwObject; } /* @@ -1362,222 +1316,233 @@ nssCKFWSession_CreateObject * */ NSS_IMPLEMENT NSSCKFWObject * -nssCKFWSession_CopyObject -( - NSSCKFWSession *fwSession, - NSSCKFWObject *fwObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nssCKFWSession_CopyObject( + NSSCKFWSession *fwSession, + NSSCKFWObject *fwObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - CK_BBOOL oldIsToken; - CK_BBOOL newIsToken; - CK_ULONG i; - NSSCKFWObject *rv; + CK_BBOOL oldIsToken; + CK_BBOOL newIsToken; + CK_ULONG i; + NSSCKFWObject *rv; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWObject *)NULL; - } + if (!pError) { + return (NSSCKFWObject *)NULL; + } - *pError = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != *pError ) { - return (NSSCKFWObject *)NULL; - } + *pError = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != *pError) { + return (NSSCKFWObject *)NULL; + } - *pError = nssCKFWObject_verifyPointer(fwObject); - if( CKR_OK != *pError ) { - return (NSSCKFWObject *)NULL; - } + *pError = nssCKFWObject_verifyPointer(fwObject); + if (CKR_OK != *pError) { + return (NSSCKFWObject *)NULL; + } - if (!fwSession->mdSession) { - *pError = CKR_GENERAL_ERROR; - return (NSSCKFWObject *)NULL; - } + if (!fwSession->mdSession) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWObject *)NULL; + } #endif /* NSSDEBUG */ - /* - * Sanity-check object - */ + /* + * Sanity-check object + */ - if (!fwObject) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWObject *)NULL; - } - - oldIsToken = nssCKFWObject_IsTokenObject(fwObject); - - newIsToken = oldIsToken; - for( i = 0; i < ulAttributeCount; i++ ) { - if( CKA_TOKEN == pTemplate[i].type ) { - /* Since we sanity-checked the object, we know this is the right size. */ - (void)nsslibc_memcpy(&newIsToken, pTemplate[i].pValue, sizeof(CK_BBOOL)); - break; - } - } - - /* - * If the Module handles its session objects, or if both the new - * and old object are token objects, use CopyObject if it exists. - */ - - if ((fwSession->mdSession->CopyObject) && - (((CK_TRUE == oldIsToken) && (CK_TRUE == newIsToken)) || - (CK_TRUE == nssCKFWInstance_GetModuleHandlesSessionObjects( - fwSession->fwInstance))) ) { - /* use copy object */ - NSSArena *arena; - NSSCKMDObject *mdOldObject; - NSSCKMDObject *mdObject; - - mdOldObject = nssCKFWObject_GetMDObject(fwObject); - - if( CK_TRUE == newIsToken ) { - arena = nssCKFWToken_GetArena(fwSession->fwToken, pError); - } else { - arena = nssCKFWSession_GetArena(fwSession, pError); - } - if (!arena) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWObject *)NULL; + if (!fwObject) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWObject *)NULL; } - mdObject = fwSession->mdSession->CopyObject(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance, mdOldObject, - fwObject, arena, pTemplate, ulAttributeCount, pError); - if (!mdObject) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWObject *)NULL; - } + oldIsToken = nssCKFWObject_IsTokenObject(fwObject); - rv = nssCKFWObject_Create(arena, mdObject, - newIsToken ? NULL : fwSession, - fwSession->fwToken, fwSession->fwInstance, pError); - - if( CK_FALSE == newIsToken ) { - if( CK_FALSE == nssCKFWHash_Exists(fwSession->sessionObjectHash, rv) ) { - *pError = nssCKFWHash_Add(fwSession->sessionObjectHash, rv, rv); - if( CKR_OK != *pError ) { - nssCKFWObject_Finalize(rv, PR_TRUE); - return (NSSCKFWObject *)NULL; + newIsToken = oldIsToken; + for (i = 0; i < ulAttributeCount; i++) { + if (CKA_TOKEN == pTemplate[i].type) { + /* Since we sanity-checked the object, we know this is the right size. */ + (void)nsslibc_memcpy(&newIsToken, pTemplate[i].pValue, sizeof(CK_BBOOL)); + break; } - } } - return rv; - } else { - /* use create object */ - NSSArena *tmpArena; - CK_ATTRIBUTE_PTR newTemplate; - CK_ULONG i, j, n, newLength, k; - CK_ATTRIBUTE_TYPE_PTR oldTypes; - NSSCKFWObject *rv; - - n = nssCKFWObject_GetAttributeCount(fwObject, pError); - if( (0 == n) && (CKR_OK != *pError) ) { - return (NSSCKFWObject *)NULL; - } + /* + * If the Module handles its session objects, or if both the new + * and old object are token objects, use CopyObject if it exists. + */ - tmpArena = NSSArena_Create(); - if (!tmpArena) { - *pError = CKR_HOST_MEMORY; - return (NSSCKFWObject *)NULL; - } + if ((fwSession->mdSession->CopyObject) && + (((CK_TRUE == oldIsToken) && (CK_TRUE == newIsToken)) || + (CK_TRUE == nssCKFWInstance_GetModuleHandlesSessionObjects( + fwSession->fwInstance)))) { + /* use copy object */ + NSSArena *arena; + NSSCKMDObject *mdOldObject; + NSSCKMDObject *mdObject; - oldTypes = nss_ZNEWARRAY(tmpArena, CK_ATTRIBUTE_TYPE, n); - if( (CK_ATTRIBUTE_TYPE_PTR)NULL == oldTypes ) { - NSSArena_Destroy(tmpArena); - *pError = CKR_HOST_MEMORY; - return (NSSCKFWObject *)NULL; - } + mdOldObject = nssCKFWObject_GetMDObject(fwObject); - *pError = nssCKFWObject_GetAttributeTypes(fwObject, oldTypes, n); - if( CKR_OK != *pError ) { - NSSArena_Destroy(tmpArena); - return (NSSCKFWObject *)NULL; - } - - newLength = n; - for( i = 0; i < ulAttributeCount; i++ ) { - for( j = 0; j < n; j++ ) { - if( oldTypes[j] == pTemplate[i].type ) { - if( (CK_VOID_PTR)NULL == pTemplate[i].pValue ) { - /* Removing the attribute */ - newLength--; - } - break; + if (CK_TRUE == newIsToken) { + arena = nssCKFWToken_GetArena(fwSession->fwToken, pError); } - } - if( j == n ) { - /* Not found */ - newLength++; - } - } - - newTemplate = nss_ZNEWARRAY(tmpArena, CK_ATTRIBUTE, newLength); - if( (CK_ATTRIBUTE_PTR)NULL == newTemplate ) { - NSSArena_Destroy(tmpArena); - *pError = CKR_HOST_MEMORY; - return (NSSCKFWObject *)NULL; - } - - k = 0; - for( j = 0; j < n; j++ ) { - for( i = 0; i < ulAttributeCount; i++ ) { - if( oldTypes[j] == pTemplate[i].type ) { - if( (CK_VOID_PTR)NULL == pTemplate[i].pValue ) { - /* This attribute is being deleted */ - ; - } else { - /* This attribute is being replaced */ - newTemplate[k].type = pTemplate[i].type; - newTemplate[k].pValue = pTemplate[i].pValue; - newTemplate[k].ulValueLen = pTemplate[i].ulValueLen; - k++; - } - break; + else { + arena = nssCKFWSession_GetArena(fwSession, pError); } - } - if( i == ulAttributeCount ) { - /* This attribute is being copied over from the old object */ - NSSItem item, *it; - item.size = 0; - item.data = (void *)NULL; - it = nssCKFWObject_GetAttribute(fwObject, oldTypes[j], - &item, tmpArena, pError); - if (!it) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - NSSArena_Destroy(tmpArena); - return (NSSCKFWObject *)NULL; + if (!arena) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWObject *)NULL; } - newTemplate[k].type = oldTypes[j]; - newTemplate[k].pValue = it->data; - newTemplate[k].ulValueLen = it->size; - k++; - } - } - /* assert that k == newLength */ - rv = nssCKFWSession_CreateObject(fwSession, newTemplate, newLength, pError); - if (!rv) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - NSSArena_Destroy(tmpArena); - return (NSSCKFWObject *)NULL; - } + mdObject = fwSession->mdSession->CopyObject(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance, mdOldObject, + fwObject, arena, pTemplate, ulAttributeCount, pError); + if (!mdObject) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWObject *)NULL; + } - NSSArena_Destroy(tmpArena); - return rv; - } + rv = nssCKFWObject_Create(arena, mdObject, + newIsToken ? + NULL + : + fwSession, + fwSession->fwToken, fwSession->fwInstance, pError); + + if (CK_FALSE == newIsToken) { + if (CK_FALSE == nssCKFWHash_Exists(fwSession->sessionObjectHash, rv)) { + *pError = nssCKFWHash_Add(fwSession->sessionObjectHash, rv, rv); + if (CKR_OK != *pError) { + nssCKFWObject_Finalize(rv, PR_TRUE); + return (NSSCKFWObject *)NULL; + } + } + } + + return rv; + } + else { + /* use create object */ + NSSArena *tmpArena; + CK_ATTRIBUTE_PTR newTemplate; + CK_ULONG i, j, n, newLength, k; + CK_ATTRIBUTE_TYPE_PTR oldTypes; + NSSCKFWObject *rv; + + n = nssCKFWObject_GetAttributeCount(fwObject, pError); + if ((0 == n) && (CKR_OK != *pError)) { + return (NSSCKFWObject *)NULL; + } + + tmpArena = NSSArena_Create(); + if (!tmpArena) { + *pError = CKR_HOST_MEMORY; + return (NSSCKFWObject *)NULL; + } + + oldTypes = nss_ZNEWARRAY(tmpArena, CK_ATTRIBUTE_TYPE, n); + if ((CK_ATTRIBUTE_TYPE_PTR)NULL == oldTypes) { + NSSArena_Destroy(tmpArena); + *pError = CKR_HOST_MEMORY; + return (NSSCKFWObject *)NULL; + } + + *pError = nssCKFWObject_GetAttributeTypes(fwObject, oldTypes, n); + if (CKR_OK != *pError) { + NSSArena_Destroy(tmpArena); + return (NSSCKFWObject *)NULL; + } + + newLength = n; + for (i = 0; i < ulAttributeCount; i++) { + for (j = 0; j < n; j++) { + if (oldTypes[j] == pTemplate[i].type) { + if ((CK_VOID_PTR)NULL == + pTemplate[i].pValue) { + /* Removing the attribute */ + newLength--; + } + break; + } + } + if (j == n) { + /* Not found */ + newLength++; + } + } + + newTemplate = nss_ZNEWARRAY(tmpArena, CK_ATTRIBUTE, newLength); + if ((CK_ATTRIBUTE_PTR)NULL == newTemplate) { + NSSArena_Destroy(tmpArena); + *pError = CKR_HOST_MEMORY; + return (NSSCKFWObject *)NULL; + } + + k = 0; + for (j = 0; j < n; j++) { + for (i = 0; i < ulAttributeCount; i++) { + if (oldTypes[j] == pTemplate[i].type) { + if ((CK_VOID_PTR)NULL == + pTemplate[i].pValue) { + /* This attribute is being deleted */ + ; + } + else { + /* This attribute is being replaced */ + newTemplate[k].type = + pTemplate[i].type; + newTemplate[k].pValue = + pTemplate[i].pValue; + newTemplate[k].ulValueLen = + pTemplate[i].ulValueLen; + k++; + } + break; + } + } + if (i == ulAttributeCount) { + /* This attribute is being copied over from the old object */ + NSSItem item, *it; + item.size = 0; + item.data = (void *)NULL; + it = nssCKFWObject_GetAttribute(fwObject, oldTypes[j], + &item, tmpArena, pError); + if (!it) { + if (CKR_OK == + *pError) { + *pError = + CKR_GENERAL_ERROR; + } + NSSArena_Destroy(tmpArena); + return (NSSCKFWObject *)NULL; + } + newTemplate[k].type = oldTypes[j]; + newTemplate[k].pValue = it->data; + newTemplate[k].ulValueLen = it->size; + k++; + } + } + /* assert that k == newLength */ + + rv = nssCKFWSession_CreateObject(fwSession, newTemplate, newLength, pError); + if (!rv) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + NSSArena_Destroy(tmpArena); + return (NSSCKFWObject *)NULL; + } + + NSSArena_Destroy(tmpArena); + return rv; + } } /* @@ -1585,135 +1550,142 @@ nssCKFWSession_CopyObject * */ NSS_IMPLEMENT NSSCKFWFindObjects * -nssCKFWSession_FindObjectsInit -( - NSSCKFWSession *fwSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_RV *pError -) +nssCKFWSession_FindObjectsInit( + NSSCKFWSession *fwSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_RV *pError) { - NSSCKMDFindObjects *mdfo1 = (NSSCKMDFindObjects *)NULL; - NSSCKMDFindObjects *mdfo2 = (NSSCKMDFindObjects *)NULL; + NSSCKMDFindObjects *mdfo1 = (NSSCKMDFindObjects *)NULL; + NSSCKMDFindObjects *mdfo2 = (NSSCKMDFindObjects *)NULL; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWFindObjects *)NULL; - } + if (!pError) { + return (NSSCKFWFindObjects *)NULL; + } - *pError = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != *pError ) { - return (NSSCKFWFindObjects *)NULL; - } + *pError = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != *pError) { + return (NSSCKFWFindObjects *)NULL; + } - if( ((CK_ATTRIBUTE_PTR)NULL == pTemplate) && (ulAttributeCount != 0) ) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWFindObjects *)NULL; - } + if (((CK_ATTRIBUTE_PTR)NULL == pTemplate) && (ulAttributeCount != 0)) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWFindObjects *)NULL; + } - if (!fwSession->mdSession) { - *pError = CKR_GENERAL_ERROR; - return (NSSCKFWFindObjects *)NULL; - } + if (!fwSession->mdSession) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWFindObjects *)NULL; + } #endif /* NSSDEBUG */ - if( CK_TRUE != nssCKFWInstance_GetModuleHandlesSessionObjects( - fwSession->fwInstance) ) { - CK_ULONG i; + if (CK_TRUE != nssCKFWInstance_GetModuleHandlesSessionObjects( + fwSession->fwInstance)) { + CK_ULONG i; - /* - * Does the search criteria restrict us to token or session - * objects? - */ + /* + * Does the search criteria restrict us to token or session + * objects? + */ - for( i = 0; i < ulAttributeCount; i++ ) { - if( CKA_TOKEN == pTemplate[i].type ) { - /* Yes, it does. */ - CK_BBOOL isToken; - if( sizeof(CK_BBOOL) != pTemplate[i].ulValueLen ) { - *pError = CKR_ATTRIBUTE_VALUE_INVALID; - return (NSSCKFWFindObjects *)NULL; + for (i = 0; i < ulAttributeCount; i++) { + if (CKA_TOKEN == pTemplate[i].type) { + /* Yes, it does. */ + CK_BBOOL isToken; + if (sizeof(CK_BBOOL) != pTemplate[i].ulValueLen) { + *pError = + CKR_ATTRIBUTE_VALUE_INVALID; + return (NSSCKFWFindObjects *)NULL; + } + (void)nsslibc_memcpy(&isToken, pTemplate[i].pValue, sizeof(CK_BBOOL)); + + if (CK_TRUE == isToken) { + /* Pass it on to the module's search routine */ + if (!fwSession->mdSession->FindObjectsInit) { + goto wrap; + } + + mdfo1 = + fwSession->mdSession->FindObjectsInit(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance, + pTemplate, ulAttributeCount, pError); + } + else { + /* Do the search ourselves */ + mdfo1 = + nssCKMDFindSessionObjects_Create(fwSession->fwToken, + pTemplate, ulAttributeCount, pError); + } + + if (!mdfo1) { + if (CKR_OK == + *pError) { + *pError = + CKR_GENERAL_ERROR; + } + return (NSSCKFWFindObjects *)NULL; + } + + goto wrap; + } } - (void)nsslibc_memcpy(&isToken, pTemplate[i].pValue, sizeof(CK_BBOOL)); - if( CK_TRUE == isToken ) { - /* Pass it on to the module's search routine */ - if (!fwSession->mdSession->FindObjectsInit) { + if (i == ulAttributeCount) { + /* No, it doesn't. Do a hybrid search. */ + mdfo1 = fwSession->mdSession->FindObjectsInit(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance, + pTemplate, ulAttributeCount, pError); + + if (!mdfo1) { + if (CKR_OK == *pError) { + *pError = + CKR_GENERAL_ERROR; + } + return (NSSCKFWFindObjects *)NULL; + } + + mdfo2 = nssCKMDFindSessionObjects_Create(fwSession->fwToken, + pTemplate, ulAttributeCount, pError); + if (!mdfo2) { + if (CKR_OK == *pError) { + *pError = + CKR_GENERAL_ERROR; + } + if (mdfo1->Final) { + mdfo1->Final(mdfo1, (NSSCKFWFindObjects *)NULL, fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance); + } + return (NSSCKFWFindObjects *)NULL; + } + goto wrap; - } - - mdfo1 = fwSession->mdSession->FindObjectsInit(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance, - pTemplate, ulAttributeCount, pError); - } else { - /* Do the search ourselves */ - mdfo1 = nssCKMDFindSessionObjects_Create(fwSession->fwToken, - pTemplate, ulAttributeCount, pError); } + /*NOTREACHED*/ + } + else { + /* Module handles all its own objects. Pass on to module's search */ + mdfo1 = fwSession->mdSession->FindObjectsInit(fwSession->mdSession, + fwSession, fwSession->mdToken, fwSession->fwToken, + fwSession->mdInstance, fwSession->fwInstance, + pTemplate, ulAttributeCount, pError); if (!mdfo1) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWFindObjects *)NULL; + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWFindObjects *)NULL; } - + goto wrap; - } } - if( i == ulAttributeCount ) { - /* No, it doesn't. Do a hybrid search. */ - mdfo1 = fwSession->mdSession->FindObjectsInit(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance, - pTemplate, ulAttributeCount, pError); - - if (!mdfo1) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWFindObjects *)NULL; - } - - mdfo2 = nssCKMDFindSessionObjects_Create(fwSession->fwToken, - pTemplate, ulAttributeCount, pError); - if (!mdfo2) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - if (mdfo1->Final) { - mdfo1->Final(mdfo1, (NSSCKFWFindObjects *)NULL, fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance); - } - return (NSSCKFWFindObjects *)NULL; - } - - goto wrap; - } - /*NOTREACHED*/ - } else { - /* Module handles all its own objects. Pass on to module's search */ - mdfo1 = fwSession->mdSession->FindObjectsInit(fwSession->mdSession, - fwSession, fwSession->mdToken, fwSession->fwToken, - fwSession->mdInstance, fwSession->fwInstance, - pTemplate, ulAttributeCount, pError); - - if (!mdfo1) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWFindObjects *)NULL; - } - - goto wrap; - } - - wrap: - return nssCKFWFindObjects_Create(fwSession, fwSession->fwToken, - fwSession->fwInstance, mdfo1, mdfo2, pError); +wrap: + return nssCKFWFindObjects_Create(fwSession, fwSession->fwToken, + fwSession->fwInstance, mdfo1, mdfo2, pError); } /* @@ -1721,46 +1693,44 @@ nssCKFWSession_FindObjectsInit * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_SeedRandom -( - NSSCKFWSession *fwSession, - NSSItem *seed -) +nssCKFWSession_SeedRandom( + NSSCKFWSession *fwSession, + NSSItem *seed) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!seed) { - return CKR_ARGUMENTS_BAD; - } + if (!seed) { + return CKR_ARGUMENTS_BAD; + } - if (!seed->data) { - return CKR_ARGUMENTS_BAD; - } + if (!seed->data) { + return CKR_ARGUMENTS_BAD; + } - if( 0 == seed->size ) { - return CKR_ARGUMENTS_BAD; - } + if (0 == seed->size) { + return CKR_ARGUMENTS_BAD; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - if (!fwSession->mdSession->SeedRandom) { - return CKR_RANDOM_SEED_NOT_SUPPORTED; - } + if (!fwSession->mdSession->SeedRandom) { + return CKR_RANDOM_SEED_NOT_SUPPORTED; + } - error = fwSession->mdSession->SeedRandom(fwSession->mdSession, fwSession, - fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, seed); + error = fwSession->mdSession->SeedRandom(fwSession->mdSession, fwSession, + fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, seed); - return error; + return error; } /* @@ -1768,584 +1738,565 @@ nssCKFWSession_SeedRandom * */ NSS_IMPLEMENT CK_RV -nssCKFWSession_GetRandom -( - NSSCKFWSession *fwSession, - NSSItem *buffer -) +nssCKFWSession_GetRandom( + NSSCKFWSession *fwSession, + NSSItem *buffer) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!buffer) { - return CKR_ARGUMENTS_BAD; - } + if (!buffer) { + return CKR_ARGUMENTS_BAD; + } - if (!buffer->data) { - return CKR_ARGUMENTS_BAD; - } + if (!buffer->data) { + return CKR_ARGUMENTS_BAD; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - if (!fwSession->mdSession->GetRandom) { - if( CK_TRUE == nssCKFWToken_GetHasRNG(fwSession->fwToken) ) { - return CKR_GENERAL_ERROR; - } else { - return CKR_RANDOM_NO_RNG; + if (!fwSession->mdSession->GetRandom) { + if (CK_TRUE == nssCKFWToken_GetHasRNG(fwSession->fwToken)) { + return CKR_GENERAL_ERROR; + } + else { + return CKR_RANDOM_NO_RNG; + } } - } - if( 0 == buffer->size ) { - return CKR_OK; - } + if (0 == buffer->size) { + return CKR_OK; + } - error = fwSession->mdSession->GetRandom(fwSession->mdSession, fwSession, - fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, - fwSession->fwInstance, buffer); + error = fwSession->mdSession->GetRandom(fwSession->mdSession, fwSession, + fwSession->mdToken, fwSession->fwToken, fwSession->mdInstance, + fwSession->fwInstance, buffer); - return error; + return error; } - /* * nssCKFWSession_SetCurrentCryptoOperation */ NSS_IMPLEMENT void -nssCKFWSession_SetCurrentCryptoOperation -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperation * fwOperation, - NSSCKFWCryptoOperationState state -) +nssCKFWSession_SetCurrentCryptoOperation( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperation *fwOperation, + NSSCKFWCryptoOperationState state) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return; - } + CK_RV error = CKR_OK; + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return; + } - if ( state >= NSSCKFWCryptoOperationState_Max) { - return; - } + if (state >= NSSCKFWCryptoOperationState_Max) { + return; + } - if (!fwSession->mdSession) { - return; - } + if (!fwSession->mdSession) { + return; + } #endif /* NSSDEBUG */ - fwSession->fwOperationArray[state] = fwOperation; - return; + fwSession->fwOperationArray[state] = fwOperation; + return; } /* * nssCKFWSession_GetCurrentCryptoOperation */ NSS_IMPLEMENT NSSCKFWCryptoOperation * -nssCKFWSession_GetCurrentCryptoOperation -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationState state -) +nssCKFWSession_GetCurrentCryptoOperation( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationState state) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return (NSSCKFWCryptoOperation *)NULL; - } + CK_RV error = CKR_OK; + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return (NSSCKFWCryptoOperation *)NULL; + } - if ( state >= NSSCKFWCryptoOperationState_Max) { - return (NSSCKFWCryptoOperation *)NULL; - } + if (state >= NSSCKFWCryptoOperationState_Max) { + return (NSSCKFWCryptoOperation *)NULL; + } - if (!fwSession->mdSession) { - return (NSSCKFWCryptoOperation *)NULL; - } + if (!fwSession->mdSession) { + return (NSSCKFWCryptoOperation *)NULL; + } #endif /* NSSDEBUG */ - return fwSession->fwOperationArray[state]; + return fwSession->fwOperationArray[state]; } /* * nssCKFWSession_Final */ NSS_IMPLEMENT CK_RV -nssCKFWSession_Final -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -) +nssCKFWSession_Final( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen) { - NSSCKFWCryptoOperation *fwOperation; - NSSItem outputBuffer; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSItem outputBuffer; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - /* make sure we have a valid operation initialized */ - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); - if (!fwOperation) { - return CKR_OPERATION_NOT_INITIALIZED; - } - - /* make sure it's the correct type */ - if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { - return CKR_OPERATION_NOT_INITIALIZED; - } - - /* handle buffer issues, note for Verify, the type is an input buffer. */ - if (NSSCKFWCryptoOperationType_Verify == type) { - if ((CK_BYTE_PTR)NULL == outBuf) { - error = CKR_ARGUMENTS_BAD; - goto done; - } - } else { - CK_ULONG len = nssCKFWCryptoOperation_GetFinalLength(fwOperation, &error); - CK_ULONG maxBufLen = *outBufLen; - - if (CKR_OK != error) { - goto done; - } - *outBufLen = len; - if ((CK_BYTE_PTR)NULL == outBuf) { - return CKR_OK; + /* make sure we have a valid operation initialized */ + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); + if (!fwOperation) { + return CKR_OPERATION_NOT_INITIALIZED; } - if (len > maxBufLen) { - return CKR_BUFFER_TOO_SMALL; + /* make sure it's the correct type */ + if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { + return CKR_OPERATION_NOT_INITIALIZED; } - } - outputBuffer.data = outBuf; - outputBuffer.size = *outBufLen; - error = nssCKFWCryptoOperation_Final(fwOperation, &outputBuffer); + /* handle buffer issues, note for Verify, the type is an input buffer. */ + if (NSSCKFWCryptoOperationType_Verify == type) { + if ((CK_BYTE_PTR)NULL == outBuf) { + error = CKR_ARGUMENTS_BAD; + goto done; + } + } + else { + CK_ULONG len = nssCKFWCryptoOperation_GetFinalLength(fwOperation, &error); + CK_ULONG maxBufLen = *outBufLen; + + if (CKR_OK != error) { + goto done; + } + *outBufLen = len; + if ((CK_BYTE_PTR)NULL == outBuf) { + return CKR_OK; + } + + if (len > maxBufLen) { + return CKR_BUFFER_TOO_SMALL; + } + } + outputBuffer.data = outBuf; + outputBuffer.size = *outBufLen; + + error = nssCKFWCryptoOperation_Final(fwOperation, &outputBuffer); done: - if (CKR_BUFFER_TOO_SMALL == error) { + if (CKR_BUFFER_TOO_SMALL == error) { + return error; + } + /* clean up our state */ + nssCKFWCryptoOperation_Destroy(fwOperation); + nssCKFWSession_SetCurrentCryptoOperation(fwSession, NULL, state); return error; - } - /* clean up our state */ - nssCKFWCryptoOperation_Destroy(fwOperation); - nssCKFWSession_SetCurrentCryptoOperation(fwSession, NULL, state); - return error; } /* * nssCKFWSession_Update */ NSS_IMPLEMENT CK_RV -nssCKFWSession_Update -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -) +nssCKFWSession_Update( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen) { - NSSCKFWCryptoOperation *fwOperation; - NSSItem inputBuffer; - NSSItem outputBuffer; - CK_ULONG len; - CK_ULONG maxBufLen; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSItem inputBuffer; + NSSItem outputBuffer; + CK_ULONG len; + CK_ULONG maxBufLen; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - /* make sure we have a valid operation initialized */ - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); - if (!fwOperation) { - return CKR_OPERATION_NOT_INITIALIZED; - } + /* make sure we have a valid operation initialized */ + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); + if (!fwOperation) { + return CKR_OPERATION_NOT_INITIALIZED; + } - /* make sure it's the correct type */ - if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { - return CKR_OPERATION_NOT_INITIALIZED; - } + /* make sure it's the correct type */ + if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { + return CKR_OPERATION_NOT_INITIALIZED; + } - inputBuffer.data = inBuf; - inputBuffer.size = inBufLen; + inputBuffer.data = inBuf; + inputBuffer.size = inBufLen; - /* handle buffer issues, note for Verify, the type is an input buffer. */ - len = nssCKFWCryptoOperation_GetOperationLength(fwOperation, &inputBuffer, - &error); - if (CKR_OK != error) { - return error; - } - maxBufLen = *outBufLen; + /* handle buffer issues, note for Verify, the type is an input buffer. */ + len = nssCKFWCryptoOperation_GetOperationLength(fwOperation, &inputBuffer, + &error); + if (CKR_OK != error) { + return error; + } + maxBufLen = *outBufLen; - *outBufLen = len; - if ((CK_BYTE_PTR)NULL == outBuf) { - return CKR_OK; - } + *outBufLen = len; + if ((CK_BYTE_PTR)NULL == outBuf) { + return CKR_OK; + } - if (len > maxBufLen) { - return CKR_BUFFER_TOO_SMALL; - } - outputBuffer.data = outBuf; - outputBuffer.size = *outBufLen; + if (len > maxBufLen) { + return CKR_BUFFER_TOO_SMALL; + } + outputBuffer.data = outBuf; + outputBuffer.size = *outBufLen; - return nssCKFWCryptoOperation_Update(fwOperation, - &inputBuffer, &outputBuffer); + return nssCKFWCryptoOperation_Update(fwOperation, + &inputBuffer, &outputBuffer); } /* * nssCKFWSession_DigestUpdate */ NSS_IMPLEMENT CK_RV -nssCKFWSession_DigestUpdate -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen -) +nssCKFWSession_DigestUpdate( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen) { - NSSCKFWCryptoOperation *fwOperation; - NSSItem inputBuffer; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSItem inputBuffer; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - /* make sure we have a valid operation initialized */ - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); - if (!fwOperation) { - return CKR_OPERATION_NOT_INITIALIZED; - } + /* make sure we have a valid operation initialized */ + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); + if (!fwOperation) { + return CKR_OPERATION_NOT_INITIALIZED; + } - /* make sure it's the correct type */ - if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { - return CKR_OPERATION_NOT_INITIALIZED; - } + /* make sure it's the correct type */ + if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { + return CKR_OPERATION_NOT_INITIALIZED; + } - inputBuffer.data = inBuf; - inputBuffer.size = inBufLen; + inputBuffer.data = inBuf; + inputBuffer.size = inBufLen; - - error = nssCKFWCryptoOperation_DigestUpdate(fwOperation, &inputBuffer); - return error; + error = nssCKFWCryptoOperation_DigestUpdate(fwOperation, &inputBuffer); + return error; } /* * nssCKFWSession_DigestUpdate */ NSS_IMPLEMENT CK_RV -nssCKFWSession_DigestKey -( - NSSCKFWSession *fwSession, - NSSCKFWObject *fwKey -) +nssCKFWSession_DigestKey( + NSSCKFWSession *fwSession, + NSSCKFWObject *fwKey) { - NSSCKFWCryptoOperation *fwOperation; - NSSItem *inputBuffer; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSItem *inputBuffer; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - /* make sure we have a valid operation initialized */ - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_Digest); - if (!fwOperation) { - return CKR_OPERATION_NOT_INITIALIZED; - } + /* make sure we have a valid operation initialized */ + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_Digest); + if (!fwOperation) { + return CKR_OPERATION_NOT_INITIALIZED; + } - /* make sure it's the correct type */ - if (NSSCKFWCryptoOperationType_Digest != - nssCKFWCryptoOperation_GetType(fwOperation)) { - return CKR_OPERATION_NOT_INITIALIZED; - } + /* make sure it's the correct type */ + if (NSSCKFWCryptoOperationType_Digest != + nssCKFWCryptoOperation_GetType(fwOperation)) { + return CKR_OPERATION_NOT_INITIALIZED; + } - error = nssCKFWCryptoOperation_DigestKey(fwOperation, fwKey); - if (CKR_FUNCTION_FAILED != error) { + error = nssCKFWCryptoOperation_DigestKey(fwOperation, fwKey); + if (CKR_FUNCTION_FAILED != error) { + return error; + } + + /* no machine depended way for this to happen, do it by hand */ + inputBuffer = nssCKFWObject_GetAttribute(fwKey, CKA_VALUE, NULL, NULL, &error); + if (!inputBuffer) { + /* couldn't get the value, just fail then */ + return error; + } + error = nssCKFWCryptoOperation_DigestUpdate(fwOperation, inputBuffer); + nssItem_Destroy(inputBuffer); return error; - } - - /* no machine depended way for this to happen, do it by hand */ - inputBuffer=nssCKFWObject_GetAttribute(fwKey, CKA_VALUE, NULL, NULL, &error); - if (!inputBuffer) { - /* couldn't get the value, just fail then */ - return error; - } - error = nssCKFWCryptoOperation_DigestUpdate(fwOperation, inputBuffer); - nssItem_Destroy(inputBuffer); - return error; } /* * nssCKFWSession_UpdateFinal */ NSS_IMPLEMENT CK_RV -nssCKFWSession_UpdateFinal -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType type, - NSSCKFWCryptoOperationState state, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -) +nssCKFWSession_UpdateFinal( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType type, + NSSCKFWCryptoOperationState state, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen) { - NSSCKFWCryptoOperation *fwOperation; - NSSItem inputBuffer; - NSSItem outputBuffer; - PRBool isEncryptDecrypt; - CK_RV error = CKR_OK; + NSSCKFWCryptoOperation *fwOperation; + NSSItem inputBuffer; + NSSItem outputBuffer; + PRBool isEncryptDecrypt; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } #endif /* NSSDEBUG */ - /* make sure we have a valid operation initialized */ - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); - if (!fwOperation) { - return CKR_OPERATION_NOT_INITIALIZED; - } - - /* make sure it's the correct type */ - if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { - return CKR_OPERATION_NOT_INITIALIZED; - } - - inputBuffer.data = inBuf; - inputBuffer.size = inBufLen; - isEncryptDecrypt = (PRBool) ((NSSCKFWCryptoOperationType_Encrypt == type) || - (NSSCKFWCryptoOperationType_Decrypt == type)) ; - - /* handle buffer issues, note for Verify, the type is an input buffer. */ - if (NSSCKFWCryptoOperationType_Verify == type) { - if ((CK_BYTE_PTR)NULL == outBuf) { - error = CKR_ARGUMENTS_BAD; - goto done; + /* make sure we have a valid operation initialized */ + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); + if (!fwOperation) { + return CKR_OPERATION_NOT_INITIALIZED; } - } else { + + /* make sure it's the correct type */ + if (type != nssCKFWCryptoOperation_GetType(fwOperation)) { + return CKR_OPERATION_NOT_INITIALIZED; + } + + inputBuffer.data = inBuf; + inputBuffer.size = inBufLen; + isEncryptDecrypt = (PRBool)((NSSCKFWCryptoOperationType_Encrypt == type) || + (NSSCKFWCryptoOperationType_Decrypt == type)); + + /* handle buffer issues, note for Verify, the type is an input buffer. */ + if (NSSCKFWCryptoOperationType_Verify == type) { + if ((CK_BYTE_PTR)NULL == outBuf) { + error = CKR_ARGUMENTS_BAD; + goto done; + } + } + else { + CK_ULONG maxBufLen = *outBufLen; + CK_ULONG len; + + len = (isEncryptDecrypt) ? + nssCKFWCryptoOperation_GetOperationLength(fwOperation, + &inputBuffer, &error) + : + nssCKFWCryptoOperation_GetFinalLength(fwOperation, &error); + + if (CKR_OK != error) { + goto done; + } + + *outBufLen = len; + if ((CK_BYTE_PTR)NULL == outBuf) { + return CKR_OK; + } + + if (len > maxBufLen) { + return CKR_BUFFER_TOO_SMALL; + } + } + outputBuffer.data = outBuf; + outputBuffer.size = *outBufLen; + + error = nssCKFWCryptoOperation_UpdateFinal(fwOperation, + &inputBuffer, &outputBuffer); + + /* UpdateFinal isn't support, manually use Update and Final */ + if (CKR_FUNCTION_FAILED == error) { + error = isEncryptDecrypt ? + nssCKFWCryptoOperation_Update(fwOperation, &inputBuffer, &outputBuffer) + : + nssCKFWCryptoOperation_DigestUpdate(fwOperation, &inputBuffer); + + if (CKR_OK == error) { + error = nssCKFWCryptoOperation_Final(fwOperation, &outputBuffer); + } + } + +done: + if (CKR_BUFFER_TOO_SMALL == error) { + /* if we return CKR_BUFFER_TOO_SMALL, we the caller is not expecting. + * the crypto state to be freed */ + return error; + } + + /* clean up our state */ + nssCKFWCryptoOperation_Destroy(fwOperation); + nssCKFWSession_SetCurrentCryptoOperation(fwSession, NULL, state); + return error; +} + +NSS_IMPLEMENT CK_RV +nssCKFWSession_UpdateCombo( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationType encryptType, + NSSCKFWCryptoOperationType digestType, + NSSCKFWCryptoOperationState digestState, + CK_BYTE_PTR inBuf, + CK_ULONG inBufLen, + CK_BYTE_PTR outBuf, + CK_ULONG_PTR outBufLen) +{ + NSSCKFWCryptoOperation *fwOperation; + NSSCKFWCryptoOperation *fwPeerOperation; + NSSItem inputBuffer; + NSSItem outputBuffer; CK_ULONG maxBufLen = *outBufLen; CK_ULONG len; + CK_RV error = CKR_OK; - len = (isEncryptDecrypt) ? - nssCKFWCryptoOperation_GetOperationLength(fwOperation, - &inputBuffer, &error) : - nssCKFWCryptoOperation_GetFinalLength(fwOperation, &error); - +#ifdef NSSDEBUG + error = nssCKFWSession_verifyPointer(fwSession); if (CKR_OK != error) { - goto done; + return error; + } + + if (!fwSession->mdSession) { + return CKR_GENERAL_ERROR; + } +#endif /* NSSDEBUG */ + + /* make sure we have a valid operation initialized */ + fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + NSSCKFWCryptoOperationState_EncryptDecrypt); + if (!fwOperation) { + return CKR_OPERATION_NOT_INITIALIZED; + } + + /* make sure it's the correct type */ + if (encryptType != nssCKFWCryptoOperation_GetType(fwOperation)) { + return CKR_OPERATION_NOT_INITIALIZED; + } + /* make sure we have a valid operation initialized */ + fwPeerOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, + digestState); + if (!fwPeerOperation) { + return CKR_OPERATION_NOT_INITIALIZED; + } + + /* make sure it's the correct type */ + if (digestType != nssCKFWCryptoOperation_GetType(fwOperation)) { + return CKR_OPERATION_NOT_INITIALIZED; + } + + inputBuffer.data = inBuf; + inputBuffer.size = inBufLen; + len = nssCKFWCryptoOperation_GetOperationLength(fwOperation, + &inputBuffer, &error); + if (CKR_OK != error) { + return error; } *outBufLen = len; if ((CK_BYTE_PTR)NULL == outBuf) { - return CKR_OK; + return CKR_OK; } if (len > maxBufLen) { - return CKR_BUFFER_TOO_SMALL; + return CKR_BUFFER_TOO_SMALL; } - } - outputBuffer.data = outBuf; - outputBuffer.size = *outBufLen; - error = nssCKFWCryptoOperation_UpdateFinal(fwOperation, - &inputBuffer, &outputBuffer); + outputBuffer.data = outBuf; + outputBuffer.size = *outBufLen; - /* UpdateFinal isn't support, manually use Update and Final */ - if (CKR_FUNCTION_FAILED == error) { - error = isEncryptDecrypt ? - nssCKFWCryptoOperation_Update(fwOperation, &inputBuffer, &outputBuffer) : - nssCKFWCryptoOperation_DigestUpdate(fwOperation, &inputBuffer); + error = nssCKFWCryptoOperation_UpdateCombo(fwOperation, fwPeerOperation, + &inputBuffer, &outputBuffer); + if (CKR_FUNCTION_FAILED == error) { + PRBool isEncrypt = + (PRBool)(NSSCKFWCryptoOperationType_Encrypt == encryptType); - if (CKR_OK == error) { - error = nssCKFWCryptoOperation_Final(fwOperation, &outputBuffer); + if (isEncrypt) { + error = nssCKFWCryptoOperation_DigestUpdate(fwPeerOperation, + &inputBuffer); + if (CKR_OK != error) { + return error; + } + } + error = nssCKFWCryptoOperation_Update(fwOperation, + &inputBuffer, &outputBuffer); + if (CKR_OK != error) { + return error; + } + if (!isEncrypt) { + error = nssCKFWCryptoOperation_DigestUpdate(fwPeerOperation, + &outputBuffer); + } } - } - - -done: - if (CKR_BUFFER_TOO_SMALL == error) { - /* if we return CKR_BUFFER_TOO_SMALL, we the caller is not expecting. - * the crypto state to be freed */ return error; - } - - /* clean up our state */ - nssCKFWCryptoOperation_Destroy(fwOperation); - nssCKFWSession_SetCurrentCryptoOperation(fwSession, NULL, state); - return error; } -NSS_IMPLEMENT CK_RV -nssCKFWSession_UpdateCombo -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationType encryptType, - NSSCKFWCryptoOperationType digestType, - NSSCKFWCryptoOperationState digestState, - CK_BYTE_PTR inBuf, - CK_ULONG inBufLen, - CK_BYTE_PTR outBuf, - CK_ULONG_PTR outBufLen -) -{ - NSSCKFWCryptoOperation *fwOperation; - NSSCKFWCryptoOperation *fwPeerOperation; - NSSItem inputBuffer; - NSSItem outputBuffer; - CK_ULONG maxBufLen = *outBufLen; - CK_ULONG len; - CK_RV error = CKR_OK; - -#ifdef NSSDEBUG - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } - - if (!fwSession->mdSession) { - return CKR_GENERAL_ERROR; - } -#endif /* NSSDEBUG */ - - /* make sure we have a valid operation initialized */ - fwOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - NSSCKFWCryptoOperationState_EncryptDecrypt); - if (!fwOperation) { - return CKR_OPERATION_NOT_INITIALIZED; - } - - /* make sure it's the correct type */ - if (encryptType != nssCKFWCryptoOperation_GetType(fwOperation)) { - return CKR_OPERATION_NOT_INITIALIZED; - } - /* make sure we have a valid operation initialized */ - fwPeerOperation = nssCKFWSession_GetCurrentCryptoOperation(fwSession, - digestState); - if (!fwPeerOperation) { - return CKR_OPERATION_NOT_INITIALIZED; - } - - /* make sure it's the correct type */ - if (digestType != nssCKFWCryptoOperation_GetType(fwOperation)) { - return CKR_OPERATION_NOT_INITIALIZED; - } - - inputBuffer.data = inBuf; - inputBuffer.size = inBufLen; - len = nssCKFWCryptoOperation_GetOperationLength(fwOperation, - &inputBuffer, &error); - if (CKR_OK != error) { - return error; - } - - *outBufLen = len; - if ((CK_BYTE_PTR)NULL == outBuf) { - return CKR_OK; - } - - if (len > maxBufLen) { - return CKR_BUFFER_TOO_SMALL; - } - - outputBuffer.data = outBuf; - outputBuffer.size = *outBufLen; - - error = nssCKFWCryptoOperation_UpdateCombo(fwOperation, fwPeerOperation, - &inputBuffer, &outputBuffer); - if (CKR_FUNCTION_FAILED == error) { - PRBool isEncrypt = - (PRBool) (NSSCKFWCryptoOperationType_Encrypt == encryptType); - - if (isEncrypt) { - error = nssCKFWCryptoOperation_DigestUpdate(fwPeerOperation, - &inputBuffer); - if (CKR_OK != error) { - return error; - } - } - error = nssCKFWCryptoOperation_Update(fwOperation, - &inputBuffer, &outputBuffer); - if (CKR_OK != error) { - return error; - } - if (!isEncrypt) { - error = nssCKFWCryptoOperation_DigestUpdate(fwPeerOperation, - &outputBuffer); - } - } - return error; -} - - /* * NSSCKFWSession_GetMDSession * */ NSS_IMPLEMENT NSSCKMDSession * -NSSCKFWSession_GetMDSession -( - NSSCKFWSession *fwSession -) +NSSCKFWSession_GetMDSession( + NSSCKFWSession *fwSession) { #ifdef DEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return (NSSCKMDSession *)NULL; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return (NSSCKMDSession *)NULL; + } #endif /* DEBUG */ - return nssCKFWSession_GetMDSession(fwSession); + return nssCKFWSession_GetMDSession(fwSession); } /* @@ -2354,24 +2305,22 @@ NSSCKFWSession_GetMDSession */ NSS_IMPLEMENT NSSArena * -NSSCKFWSession_GetArena -( - NSSCKFWSession *fwSession, - CK_RV *pError -) +NSSCKFWSession_GetArena( + NSSCKFWSession *fwSession, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - *pError = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != *pError ) { - return (NSSArena *)NULL; - } + *pError = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != *pError) { + return (NSSArena *)NULL; + } #endif /* DEBUG */ - return nssCKFWSession_GetArena(fwSession, pError); + return nssCKFWSession_GetArena(fwSession, pError); } /* @@ -2380,22 +2329,20 @@ NSSCKFWSession_GetArena */ NSS_IMPLEMENT CK_RV -NSSCKFWSession_CallNotification -( - NSSCKFWSession *fwSession, - CK_NOTIFICATION event -) +NSSCKFWSession_CallNotification( + NSSCKFWSession *fwSession, + CK_NOTIFICATION event) { #ifdef DEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } #endif /* DEBUG */ - return nssCKFWSession_CallNotification(fwSession, event); + return nssCKFWSession_CallNotification(fwSession, event); } /* @@ -2404,18 +2351,16 @@ NSSCKFWSession_CallNotification */ NSS_IMPLEMENT CK_BBOOL -NSSCKFWSession_IsRWSession -( - NSSCKFWSession *fwSession -) +NSSCKFWSession_IsRWSession( + NSSCKFWSession *fwSession) { #ifdef DEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return CK_FALSE; + } #endif /* DEBUG */ - return nssCKFWSession_IsRWSession(fwSession); + return nssCKFWSession_IsRWSession(fwSession); } /* @@ -2424,37 +2369,33 @@ NSSCKFWSession_IsRWSession */ NSS_IMPLEMENT CK_BBOOL -NSSCKFWSession_IsSO -( - NSSCKFWSession *fwSession -) +NSSCKFWSession_IsSO( + NSSCKFWSession *fwSession) { #ifdef DEBUG - if( CKR_OK != nssCKFWSession_verifyPointer(fwSession) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWSession_verifyPointer(fwSession)) { + return CK_FALSE; + } #endif /* DEBUG */ - return nssCKFWSession_IsSO(fwSession); + return nssCKFWSession_IsSO(fwSession); } NSS_IMPLEMENT NSSCKFWCryptoOperation * -NSSCKFWSession_GetCurrentCryptoOperation -( - NSSCKFWSession *fwSession, - NSSCKFWCryptoOperationState state -) +NSSCKFWSession_GetCurrentCryptoOperation( + NSSCKFWSession *fwSession, + NSSCKFWCryptoOperationState state) { #ifdef DEBUG - CK_RV error = CKR_OK; - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return (NSSCKFWCryptoOperation *)NULL; - } + CK_RV error = CKR_OK; + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return (NSSCKFWCryptoOperation *)NULL; + } - if ( state >= NSSCKFWCryptoOperationState_Max) { - return (NSSCKFWCryptoOperation *)NULL; - } + if (state >= NSSCKFWCryptoOperationState_Max) { + return (NSSCKFWCryptoOperation *)NULL; + } #endif /* DEBUG */ - return nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); + return nssCKFWSession_GetCurrentCryptoOperation(fwSession, state); } diff --git a/security/nss/lib/ckfw/sessobj.c b/security/nss/lib/ckfw/sessobj.c index 113b0f45d753..a144de288a6c 100644 --- a/security/nss/lib/ckfw/sessobj.c +++ b/security/nss/lib/ckfw/sessobj.c @@ -5,7 +5,7 @@ /* * sessobj.c * - * This file contains an NSSCKMDObject implementation for session + * This file contains an NSSCKMDObject implementation for session * objects. The framework uses this implementation to manage * session objects when a Module doesn't wish to be bothered. */ @@ -32,11 +32,11 @@ */ struct nssCKMDSessionObjectStr { - CK_ULONG n; - NSSArena *arena; - NSSItem *attributes; - CK_ATTRIBUTE_TYPE_PTR types; - nssCKFWHash *hash; + CK_ULONG n; + NSSArena *arena; + NSSItem *attributes; + CK_ATTRIBUTE_TYPE_PTR types; + nssCKFWHash *hash; }; typedef struct nssCKMDSessionObjectStr nssCKMDSessionObject; @@ -53,31 +53,25 @@ typedef struct nssCKMDSessionObjectStr nssCKMDSessionObject; */ static CK_RV -nss_ckmdSessionObject_add_pointer -( - const NSSCKMDObject *mdObject -) +nss_ckmdSessionObject_add_pointer( + const NSSCKMDObject *mdObject) { - return CKR_OK; + return CKR_OK; } static CK_RV -nss_ckmdSessionObject_remove_pointer -( - const NSSCKMDObject *mdObject -) +nss_ckmdSessionObject_remove_pointer( + const NSSCKMDObject *mdObject) { - return CKR_OK; + return CKR_OK; } #ifdef NSS_DEBUG static CK_RV -nss_ckmdSessionObject_verifyPointer -( - const NSSCKMDObject *mdObject -) +nss_ckmdSessionObject_verifyPointer( + const NSSCKMDObject *mdObject) { - return CKR_OK; + return CKR_OK; } #endif @@ -87,234 +81,214 @@ nss_ckmdSessionObject_verifyPointer * We must forward-declare these routines */ static void -nss_ckmdSessionObject_Finalize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -); +nss_ckmdSessionObject_Finalize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); static CK_RV -nss_ckmdSessionObject_Destroy -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -); +nss_ckmdSessionObject_Destroy( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); static CK_BBOOL -nss_ckmdSessionObject_IsTokenObject -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -); +nss_ckmdSessionObject_IsTokenObject( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); static CK_ULONG -nss_ckmdSessionObject_GetAttributeCount -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -); +nss_ckmdSessionObject_GetAttributeCount( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); static CK_RV -nss_ckmdSessionObject_GetAttributeTypes -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -); +nss_ckmdSessionObject_GetAttributeTypes( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount); static CK_ULONG -nss_ckmdSessionObject_GetAttributeSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -); +nss_ckmdSessionObject_GetAttributeSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError); static NSSCKFWItem -nss_ckmdSessionObject_GetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -); +nss_ckmdSessionObject_GetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError); static CK_RV -nss_ckmdSessionObject_SetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value -); +nss_ckmdSessionObject_SetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value); static CK_ULONG -nss_ckmdSessionObject_GetObjectSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -); +nss_ckmdSessionObject_GetObjectSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError); /* * nssCKMDSessionObject_Create * */ NSS_IMPLEMENT NSSCKMDObject * -nssCKMDSessionObject_Create -( - NSSCKFWToken *fwToken, - NSSArena *arena, - CK_ATTRIBUTE_PTR attributes, - CK_ULONG ulCount, - CK_RV *pError -) +nssCKMDSessionObject_Create( + NSSCKFWToken *fwToken, + NSSArena *arena, + CK_ATTRIBUTE_PTR attributes, + CK_ULONG ulCount, + CK_RV *pError) { - NSSCKMDObject *mdObject = (NSSCKMDObject *)NULL; - nssCKMDSessionObject *mdso = (nssCKMDSessionObject *)NULL; - CK_ULONG i; - nssCKFWHash *hash; + NSSCKMDObject *mdObject = (NSSCKMDObject *)NULL; + nssCKMDSessionObject *mdso = (nssCKMDSessionObject *)NULL; + CK_ULONG i; + nssCKFWHash *hash; - *pError = CKR_OK; + *pError = CKR_OK; - mdso = nss_ZNEW(arena, nssCKMDSessionObject); - if (!mdso) { - goto loser; - } - - mdso->arena = arena; - mdso->n = ulCount; - mdso->attributes = nss_ZNEWARRAY(arena, NSSItem, ulCount); - if (!mdso->attributes) { - goto loser; - } - - mdso->types = nss_ZNEWARRAY(arena, CK_ATTRIBUTE_TYPE, ulCount); - if (!mdso->types) { - goto loser; - } - for( i = 0; i < ulCount; i++ ) { - mdso->types[i] = attributes[i].type; - mdso->attributes[i].size = attributes[i].ulValueLen; - mdso->attributes[i].data = nss_ZAlloc(arena, attributes[i].ulValueLen); - if (!mdso->attributes[i].data) { - goto loser; + mdso = nss_ZNEW(arena, nssCKMDSessionObject); + if (!mdso) { + goto loser; } - (void)nsslibc_memcpy(mdso->attributes[i].data, attributes[i].pValue, - attributes[i].ulValueLen); - } - mdObject = nss_ZNEW(arena, NSSCKMDObject); - if (!mdObject) { - goto loser; - } + mdso->arena = arena; + mdso->n = ulCount; + mdso->attributes = nss_ZNEWARRAY(arena, NSSItem, ulCount); + if (!mdso->attributes) { + goto loser; + } - mdObject->etc = (void *)mdso; - mdObject->Finalize = nss_ckmdSessionObject_Finalize; - mdObject->Destroy = nss_ckmdSessionObject_Destroy; - mdObject->IsTokenObject = nss_ckmdSessionObject_IsTokenObject; - mdObject->GetAttributeCount = nss_ckmdSessionObject_GetAttributeCount; - mdObject->GetAttributeTypes = nss_ckmdSessionObject_GetAttributeTypes; - mdObject->GetAttributeSize = nss_ckmdSessionObject_GetAttributeSize; - mdObject->GetAttribute = nss_ckmdSessionObject_GetAttribute; - mdObject->SetAttribute = nss_ckmdSessionObject_SetAttribute; - mdObject->GetObjectSize = nss_ckmdSessionObject_GetObjectSize; + mdso->types = nss_ZNEWARRAY(arena, CK_ATTRIBUTE_TYPE, ulCount); + if (!mdso->types) { + goto loser; + } + for (i = 0; i < ulCount; i++) { + mdso->types[i] = attributes[i].type; + mdso->attributes[i].size = attributes[i].ulValueLen; + mdso->attributes[i].data = nss_ZAlloc(arena, attributes[i].ulValueLen); + if (!mdso->attributes[i].data) { + goto loser; + } + (void)nsslibc_memcpy(mdso->attributes[i].data, attributes[i].pValue, + attributes[i].ulValueLen); + } - hash = nssCKFWToken_GetSessionObjectHash(fwToken); - if (!hash) { - *pError = CKR_GENERAL_ERROR; - goto loser; - } + mdObject = nss_ZNEW(arena, NSSCKMDObject); + if (!mdObject) { + goto loser; + } - mdso->hash = hash; + mdObject->etc = (void *)mdso; + mdObject->Finalize = nss_ckmdSessionObject_Finalize; + mdObject->Destroy = nss_ckmdSessionObject_Destroy; + mdObject->IsTokenObject = nss_ckmdSessionObject_IsTokenObject; + mdObject->GetAttributeCount = nss_ckmdSessionObject_GetAttributeCount; + mdObject->GetAttributeTypes = nss_ckmdSessionObject_GetAttributeTypes; + mdObject->GetAttributeSize = nss_ckmdSessionObject_GetAttributeSize; + mdObject->GetAttribute = nss_ckmdSessionObject_GetAttribute; + mdObject->SetAttribute = nss_ckmdSessionObject_SetAttribute; + mdObject->GetObjectSize = nss_ckmdSessionObject_GetObjectSize; - *pError = nssCKFWHash_Add(hash, mdObject, mdObject); - if( CKR_OK != *pError ) { - goto loser; - } + hash = nssCKFWToken_GetSessionObjectHash(fwToken); + if (!hash) { + *pError = CKR_GENERAL_ERROR; + goto loser; + } + + mdso->hash = hash; + + *pError = nssCKFWHash_Add(hash, mdObject, mdObject); + if (CKR_OK != *pError) { + goto loser; + } #ifdef DEBUG - if(( *pError = nss_ckmdSessionObject_add_pointer(mdObject)) != CKR_OK ) { - goto loser; - } + if ((*pError = nss_ckmdSessionObject_add_pointer(mdObject)) != CKR_OK) { + goto loser; + } #endif /* DEBUG */ - return mdObject; + return mdObject; - loser: - if (mdso) { - if (mdso->attributes) { - for( i = 0; i < ulCount; i++ ) { - nss_ZFreeIf(mdso->attributes[i].data); - } - nss_ZFreeIf(mdso->attributes); +loser: + if (mdso) { + if (mdso->attributes) { + for (i = 0; i < ulCount; i++) { + nss_ZFreeIf(mdso->attributes[i].data); + } + nss_ZFreeIf(mdso->attributes); + } + nss_ZFreeIf(mdso->types); + nss_ZFreeIf(mdso); } - nss_ZFreeIf(mdso->types); - nss_ZFreeIf(mdso); - } - nss_ZFreeIf(mdObject); - if (*pError == CKR_OK) { - *pError = CKR_HOST_MEMORY; - } - return (NSSCKMDObject *)NULL; + nss_ZFreeIf(mdObject); + if (*pError == CKR_OK) { + *pError = CKR_HOST_MEMORY; + } + return (NSSCKMDObject *)NULL; } /* @@ -322,20 +296,18 @@ nssCKMDSessionObject_Create * */ static void -nss_ckmdSessionObject_Finalize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_ckmdSessionObject_Finalize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - /* This shouldn't ever be called */ - return; + /* This shouldn't ever be called */ + return; } /* @@ -344,48 +316,46 @@ nss_ckmdSessionObject_Finalize */ static CK_RV -nss_ckmdSessionObject_Destroy -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_ckmdSessionObject_Destroy( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #endif /* NSSDEBUG */ - nssCKMDSessionObject *mdso; - CK_ULONG i; + nssCKMDSessionObject *mdso; + CK_ULONG i; #ifdef NSSDEBUG - error = nss_ckmdSessionObject_verifyPointer(mdObject); - if( CKR_OK != error ) { - return error; - } + error = nss_ckmdSessionObject_verifyPointer(mdObject); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - mdso = (nssCKMDSessionObject *)mdObject->etc; + mdso = (nssCKMDSessionObject *)mdObject->etc; - nssCKFWHash_Remove(mdso->hash, mdObject); + nssCKFWHash_Remove(mdso->hash, mdObject); - for( i = 0; i < mdso->n; i++ ) { - nss_ZFreeIf(mdso->attributes[i].data); - } - nss_ZFreeIf(mdso->attributes); - nss_ZFreeIf(mdso->types); - nss_ZFreeIf(mdso); - nss_ZFreeIf(mdObject); + for (i = 0; i < mdso->n; i++) { + nss_ZFreeIf(mdso->attributes[i].data); + } + nss_ZFreeIf(mdso->attributes); + nss_ZFreeIf(mdso->types); + nss_ZFreeIf(mdso); + nss_ZFreeIf(mdObject); #ifdef DEBUG - (void)nss_ckmdSessionObject_remove_pointer(mdObject); + (void)nss_ckmdSessionObject_remove_pointer(mdObject); #endif /* DEBUG */ - return CKR_OK; + return CKR_OK; } /* @@ -394,28 +364,26 @@ nss_ckmdSessionObject_Destroy */ static CK_BBOOL -nss_ckmdSessionObject_IsTokenObject -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_ckmdSessionObject_IsTokenObject( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { #ifdef NSSDEBUG - if( CKR_OK != nss_ckmdSessionObject_verifyPointer(mdObject) ) { - return CK_FALSE; - } + if (CKR_OK != nss_ckmdSessionObject_verifyPointer(mdObject)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - /* - * This implementation is only ever used for session objects. - */ - return CK_FALSE; + /* + * This implementation is only ever used for session objects. + */ + return CK_FALSE; } /* @@ -423,37 +391,35 @@ nss_ckmdSessionObject_IsTokenObject * */ static CK_ULONG -nss_ckmdSessionObject_GetAttributeCount -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_ckmdSessionObject_GetAttributeCount( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - nssCKMDSessionObject *obj; + nssCKMDSessionObject *obj; #ifdef NSSDEBUG - if (!pError) { - return 0; - } + if (!pError) { + return 0; + } - *pError = nss_ckmdSessionObject_verifyPointer(mdObject); - if( CKR_OK != *pError ) { - return 0; - } + *pError = nss_ckmdSessionObject_verifyPointer(mdObject); + if (CKR_OK != *pError) { + return 0; + } - /* We could even check all the other arguments, for sanity. */ +/* We could even check all the other arguments, for sanity. */ #endif /* NSSDEBUG */ - obj = (nssCKMDSessionObject *)mdObject->etc; + obj = (nssCKMDSessionObject *)mdObject->etc; - return obj->n; + return obj->n; } /* @@ -461,44 +427,43 @@ nss_ckmdSessionObject_GetAttributeCount * */ static CK_RV -nss_ckmdSessionObject_GetAttributeTypes -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE_PTR typeArray, - CK_ULONG ulCount -) +nss_ckmdSessionObject_GetAttributeTypes( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE_PTR typeArray, + CK_ULONG ulCount) { #ifdef NSSDEBUG - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #endif /* NSSDEBUG */ - nssCKMDSessionObject *obj; + nssCKMDSessionObject *obj; #ifdef NSSDEBUG - error = nss_ckmdSessionObject_verifyPointer(mdObject); - if( CKR_OK != error ) { - return error; - } + error = nss_ckmdSessionObject_verifyPointer(mdObject); + if (CKR_OK != error) { + return error; + } - /* We could even check all the other arguments, for sanity. */ +/* We could even check all the other arguments, for sanity. */ #endif /* NSSDEBUG */ - obj = (nssCKMDSessionObject *)mdObject->etc; + obj = (nssCKMDSessionObject *)mdObject->etc; - if( ulCount < obj->n ) { - return CKR_BUFFER_TOO_SMALL; - } + if (ulCount < obj->n) { + return CKR_BUFFER_TOO_SMALL; + } - (void)nsslibc_memcpy(typeArray, obj->types, - sizeof(CK_ATTRIBUTE_TYPE) * obj->n); + (void)nsslibc_memcpy(typeArray, obj->types, + sizeof(CK_ATTRIBUTE_TYPE) * + obj->n); - return CKR_OK; + return CKR_OK; } /* @@ -506,46 +471,44 @@ nss_ckmdSessionObject_GetAttributeTypes * */ static CK_ULONG -nss_ckmdSessionObject_GetAttributeSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +nss_ckmdSessionObject_GetAttributeSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - nssCKMDSessionObject *obj; - CK_ULONG i; + nssCKMDSessionObject *obj; + CK_ULONG i; #ifdef NSSDEBUG - if (!pError) { - return 0; - } + if (!pError) { + return 0; + } - *pError = nss_ckmdSessionObject_verifyPointer(mdObject); - if( CKR_OK != *pError ) { - return 0; - } + *pError = nss_ckmdSessionObject_verifyPointer(mdObject); + if (CKR_OK != *pError) { + return 0; + } - /* We could even check all the other arguments, for sanity. */ +/* We could even check all the other arguments, for sanity. */ #endif /* NSSDEBUG */ - obj = (nssCKMDSessionObject *)mdObject->etc; + obj = (nssCKMDSessionObject *)mdObject->etc; - for( i = 0; i < obj->n; i++ ) { - if( attribute == obj->types[i] ) { - return (CK_ULONG)(obj->attributes[i].size); + for (i = 0; i < obj->n; i++) { + if (attribute == obj->types[i]) { + return (CK_ULONG)(obj->attributes[i].size); + } } - } - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - return 0; + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + return 0; } /* @@ -553,50 +516,48 @@ nss_ckmdSessionObject_GetAttributeSize * */ static NSSCKFWItem -nss_ckmdSessionObject_GetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - CK_RV *pError -) +nss_ckmdSessionObject_GetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + CK_RV *pError) { - NSSCKFWItem item; - nssCKMDSessionObject *obj; - CK_ULONG i; + NSSCKFWItem item; + nssCKMDSessionObject *obj; + CK_ULONG i; - item.needsFreeing = PR_FALSE; - item.item = NULL; + item.needsFreeing = PR_FALSE; + item.item = NULL; #ifdef NSSDEBUG - if (!pError) { - return item; - } + if (!pError) { + return item; + } - *pError = nss_ckmdSessionObject_verifyPointer(mdObject); - if( CKR_OK != *pError ) { - return item; - } + *pError = nss_ckmdSessionObject_verifyPointer(mdObject); + if (CKR_OK != *pError) { + return item; + } - /* We could even check all the other arguments, for sanity. */ +/* We could even check all the other arguments, for sanity. */ #endif /* NSSDEBUG */ - obj = (nssCKMDSessionObject *)mdObject->etc; + obj = (nssCKMDSessionObject *)mdObject->etc; - for( i = 0; i < obj->n; i++ ) { - if( attribute == obj->types[i] ) { - item.item = &obj->attributes[i]; - return item; + for (i = 0; i < obj->n; i++) { + if (attribute == obj->types[i]) { + item.item = &obj->attributes[i]; + return item; + } } - } - *pError = CKR_ATTRIBUTE_TYPE_INVALID; - return item; + *pError = CKR_ATTRIBUTE_TYPE_INVALID; + return item; } /* @@ -612,79 +573,77 @@ nss_ckmdSessionObject_GetAttribute * more easily. Do this later. */ static CK_RV -nss_ckmdSessionObject_SetAttribute -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_ATTRIBUTE_TYPE attribute, - NSSItem *value -) +nss_ckmdSessionObject_SetAttribute( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_ATTRIBUTE_TYPE attribute, + NSSItem *value) { - nssCKMDSessionObject *obj; - CK_ULONG i; - NSSItem n; - NSSItem *ra; - CK_ATTRIBUTE_TYPE_PTR rt; + nssCKMDSessionObject *obj; + CK_ULONG i; + NSSItem n; + NSSItem *ra; + CK_ATTRIBUTE_TYPE_PTR rt; #ifdef NSSDEBUG - CK_RV error; + CK_RV error; #endif /* NSSDEBUG */ #ifdef NSSDEBUG - error = nss_ckmdSessionObject_verifyPointer(mdObject); - if( CKR_OK != error ) { - return 0; - } - - /* We could even check all the other arguments, for sanity. */ -#endif /* NSSDEBUG */ - - obj = (nssCKMDSessionObject *)mdObject->etc; - - n.size = value->size; - n.data = nss_ZAlloc(obj->arena, n.size); - if (!n.data) { - return CKR_HOST_MEMORY; - } - (void)nsslibc_memcpy(n.data, value->data, n.size); - - for( i = 0; i < obj->n; i++ ) { - if( attribute == obj->types[i] ) { - nss_ZFreeIf(obj->attributes[i].data); - obj->attributes[i] = n; - return CKR_OK; + error = nss_ckmdSessionObject_verifyPointer(mdObject); + if (CKR_OK != error) { + return 0; } - } - /* - * It's new. - */ +/* We could even check all the other arguments, for sanity. */ +#endif /* NSSDEBUG */ - ra = (NSSItem *)nss_ZRealloc(obj->attributes, sizeof(NSSItem) * (obj->n + 1)); - if (!ra) { - nss_ZFreeIf(n.data); - return CKR_HOST_MEMORY; - } - obj->attributes = ra; + obj = (nssCKMDSessionObject *)mdObject->etc; - rt = (CK_ATTRIBUTE_TYPE_PTR)nss_ZRealloc(obj->types, - sizeof(CK_ATTRIBUTE_TYPE) * (obj->n + 1)); - if (!rt) { - nss_ZFreeIf(n.data); - return CKR_HOST_MEMORY; - } + n.size = value->size; + n.data = nss_ZAlloc(obj->arena, n.size); + if (!n.data) { + return CKR_HOST_MEMORY; + } + (void)nsslibc_memcpy(n.data, value->data, n.size); - obj->types = rt; - obj->attributes[obj->n] = n; - obj->types[obj->n] = attribute; - obj->n++; + for (i = 0; i < obj->n; i++) { + if (attribute == obj->types[i]) { + nss_ZFreeIf(obj->attributes[i].data); + obj->attributes[i] = n; + return CKR_OK; + } + } - return CKR_OK; + /* + * It's new. + */ + + ra = (NSSItem *)nss_ZRealloc(obj->attributes, sizeof(NSSItem) * (obj->n + 1)); + if (!ra) { + nss_ZFreeIf(n.data); + return CKR_HOST_MEMORY; + } + obj->attributes = ra; + + rt = (CK_ATTRIBUTE_TYPE_PTR)nss_ZRealloc(obj->types, + sizeof(CK_ATTRIBUTE_TYPE) * (obj->n + 1)); + if (!rt) { + nss_ZFreeIf(n.data); + return CKR_HOST_MEMORY; + } + + obj->types = rt; + obj->attributes[obj->n] = n; + obj->types[obj->n] = attribute; + obj->n++; + + return CKR_OK; } /* @@ -692,47 +651,45 @@ nss_ckmdSessionObject_SetAttribute * */ static CK_ULONG -nss_ckmdSessionObject_GetObjectSize -( - NSSCKMDObject *mdObject, - NSSCKFWObject *fwObject, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - CK_RV *pError -) +nss_ckmdSessionObject_GetObjectSize( + NSSCKMDObject *mdObject, + NSSCKFWObject *fwObject, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + CK_RV *pError) { - nssCKMDSessionObject *obj; - CK_ULONG i; - CK_ULONG rv = (CK_ULONG)0; + nssCKMDSessionObject *obj; + CK_ULONG i; + CK_ULONG rv = (CK_ULONG)0; #ifdef NSSDEBUG - if (!pError) { - return 0; - } + if (!pError) { + return 0; + } - *pError = nss_ckmdSessionObject_verifyPointer(mdObject); - if( CKR_OK != *pError ) { - return 0; - } + *pError = nss_ckmdSessionObject_verifyPointer(mdObject); + if (CKR_OK != *pError) { + return 0; + } - /* We could even check all the other arguments, for sanity. */ +/* We could even check all the other arguments, for sanity. */ #endif /* NSSDEBUG */ - obj = (nssCKMDSessionObject *)mdObject->etc; + obj = (nssCKMDSessionObject *)mdObject->etc; - for( i = 0; i < obj->n; i++ ) { - rv += obj->attributes[i].size; - } + for (i = 0; i < obj->n; i++) { + rv += obj->attributes[i].size; + } - rv += sizeof(NSSItem) * obj->n; - rv += sizeof(CK_ATTRIBUTE_TYPE) * obj->n; - rv += sizeof(nssCKMDSessionObject); + rv += sizeof(NSSItem) * obj->n; + rv += sizeof(CK_ATTRIBUTE_TYPE) * obj->n; + rv += sizeof(nssCKMDSessionObject); - return rv; + return rv; } /* @@ -747,18 +704,17 @@ nss_ckmdSessionObject_GetObjectSize */ struct nodeStr { - struct nodeStr *next; - NSSCKMDObject *mdObject; + struct nodeStr *next; + NSSCKMDObject *mdObject; }; struct nssCKMDFindSessionObjectsStr { - NSSArena *arena; - CK_RV error; - CK_ATTRIBUTE_PTR pTemplate; - CK_ULONG ulCount; - struct nodeStr *list; - nssCKFWHash *hash; - + NSSArena *arena; + CK_RV error; + CK_ATTRIBUTE_PTR pTemplate; + CK_ULONG ulCount; + struct nodeStr *list; + nssCKFWHash *hash; }; typedef struct nssCKMDFindSessionObjectsStr nssCKMDFindSessionObjects; @@ -775,31 +731,25 @@ typedef struct nssCKMDFindSessionObjectsStr nssCKMDFindSessionObjects; */ static CK_RV -nss_ckmdFindSessionObjects_add_pointer -( - const NSSCKMDFindObjects *mdFindObjects -) +nss_ckmdFindSessionObjects_add_pointer( + const NSSCKMDFindObjects *mdFindObjects) { - return CKR_OK; + return CKR_OK; } static CK_RV -nss_ckmdFindSessionObjects_remove_pointer -( - const NSSCKMDFindObjects *mdFindObjects -) +nss_ckmdFindSessionObjects_remove_pointer( + const NSSCKMDFindObjects *mdFindObjects) { - return CKR_OK; + return CKR_OK; } #ifdef NSS_DEBUG static CK_RV -nss_ckmdFindSessionObjects_verifyPointer -( - const NSSCKMDFindObjects *mdFindObjects -) +nss_ckmdFindSessionObjects_verifyPointer( + const NSSCKMDFindObjects *mdFindObjects) { - return CKR_OK; + return CKR_OK; } #endif @@ -809,104 +759,98 @@ nss_ckmdFindSessionObjects_verifyPointer * We must forward-declare these routines. */ static void -nss_ckmdFindSessionObjects_Final -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -); +nss_ckmdFindSessionObjects_Final( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance); static NSSCKMDObject * -nss_ckmdFindSessionObjects_Next -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -); +nss_ckmdFindSessionObjects_Next( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError); static CK_BBOOL -items_match -( - NSSItem *a, - CK_VOID_PTR pValue, - CK_ULONG ulValueLen -) +items_match( + NSSItem *a, + CK_VOID_PTR pValue, + CK_ULONG ulValueLen) { - if( a->size != ulValueLen ) { - return CK_FALSE; - } + if (a->size != ulValueLen) { + return CK_FALSE; + } - if( PR_TRUE == nsslibc_memequal(a->data, pValue, ulValueLen, (PRStatus *)NULL) ) { - return CK_TRUE; - } else { - return CK_FALSE; - } + if (PR_TRUE == nsslibc_memequal(a->data, pValue, ulValueLen, (PRStatus *)NULL)) { + return CK_TRUE; + } + else { + return CK_FALSE; + } } /* * Our hashtable iterator */ static void -findfcn -( - const void *key, - void *value, - void *closure -) +findfcn( + const void *key, + void *value, + void *closure) { - NSSCKMDObject *mdObject = (NSSCKMDObject *)value; - nssCKMDSessionObject *mdso = (nssCKMDSessionObject *)mdObject->etc; - nssCKMDFindSessionObjects *mdfso = (nssCKMDFindSessionObjects *)closure; - CK_ULONG i, j; - struct nodeStr *node; + NSSCKMDObject *mdObject = (NSSCKMDObject *)value; + nssCKMDSessionObject *mdso = (nssCKMDSessionObject *)mdObject->etc; + nssCKMDFindSessionObjects *mdfso = (nssCKMDFindSessionObjects *)closure; + CK_ULONG i, j; + struct nodeStr *node; - if( CKR_OK != mdfso->error ) { - return; - } + if (CKR_OK != mdfso->error) { + return; + } - for( i = 0; i < mdfso->ulCount; i++ ) { - CK_ATTRIBUTE_PTR p = &mdfso->pTemplate[i]; + for (i = 0; i < mdfso->ulCount; i++) { + CK_ATTRIBUTE_PTR p = &mdfso->pTemplate[i]; - for( j = 0; j < mdso->n; j++ ) { - if( mdso->types[j] == p->type ) { - if( !items_match(&mdso->attributes[j], p->pValue, p->ulValueLen) ) { - return; - } else { - break; + for (j = 0; j < mdso->n; j++) { + if (mdso->types[j] == p->type) { + if (!items_match(&mdso->attributes[j], p->pValue, p->ulValueLen)) { + return; + } + else { + break; + } + } + } + + if (j == mdso->n) { + /* Attribute not found */ + return; } - } } - if( j == mdso->n ) { - /* Attribute not found */ - return; + /* Matches */ + node = nss_ZNEW(mdfso->arena, struct nodeStr); + if ((struct nodeStr *)NULL == node) { + mdfso->error = CKR_HOST_MEMORY; + return; } - } - /* Matches */ - node = nss_ZNEW(mdfso->arena, struct nodeStr); - if( (struct nodeStr *)NULL == node ) { - mdfso->error = CKR_HOST_MEMORY; + node->mdObject = mdObject; + node->next = mdfso->list; + mdfso->list = node; + return; - } - - node->mdObject = mdObject; - node->next = mdfso->list; - mdfso->list = node; - - return; } /* @@ -914,162 +858,157 @@ findfcn * */ NSS_IMPLEMENT NSSCKMDFindObjects * -nssCKMDFindSessionObjects_Create -( - NSSCKFWToken *fwToken, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_RV *pError -) +nssCKMDFindSessionObjects_Create( + NSSCKFWToken *fwToken, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_RV *pError) { - NSSArena *arena; - nssCKMDFindSessionObjects *mdfso; - nssCKFWHash *hash; - NSSCKMDFindObjects *rv; + NSSArena *arena; + nssCKMDFindSessionObjects *mdfso; + nssCKFWHash *hash; + NSSCKMDFindObjects *rv; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKMDFindObjects *)NULL; - } + if (!pError) { + return (NSSCKMDFindObjects *)NULL; + } - *pError = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != *pError ) { - return (NSSCKMDFindObjects *)NULL; - } + *pError = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != *pError) { + return (NSSCKMDFindObjects *)NULL; + } - if( (CK_ATTRIBUTE_PTR)NULL == pTemplate ) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKMDFindObjects *)NULL; - } + if ((CK_ATTRIBUTE_PTR)NULL == pTemplate) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKMDFindObjects *)NULL; + } #endif /* NSSDEBUG */ - *pError = CKR_OK; + *pError = CKR_OK; - hash = nssCKFWToken_GetSessionObjectHash(fwToken); - if (!hash) { - *pError= CKR_GENERAL_ERROR; - return (NSSCKMDFindObjects *)NULL; - } + hash = nssCKFWToken_GetSessionObjectHash(fwToken); + if (!hash) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKMDFindObjects *)NULL; + } - arena = NSSArena_Create(); - if (!arena) { - *pError = CKR_HOST_MEMORY; - return (NSSCKMDFindObjects *)NULL; - } + arena = NSSArena_Create(); + if (!arena) { + *pError = CKR_HOST_MEMORY; + return (NSSCKMDFindObjects *)NULL; + } - mdfso = nss_ZNEW(arena, nssCKMDFindSessionObjects); - if (!mdfso) { - goto loser; - } + mdfso = nss_ZNEW(arena, nssCKMDFindSessionObjects); + if (!mdfso) { + goto loser; + } - rv = nss_ZNEW(arena, NSSCKMDFindObjects); - if(rv == NULL) { - goto loser; - } + rv = nss_ZNEW(arena, NSSCKMDFindObjects); + if (rv == NULL) { + goto loser; + } - mdfso->error = CKR_OK; - mdfso->pTemplate = pTemplate; - mdfso->ulCount = ulCount; - mdfso->hash = hash; + mdfso->error = CKR_OK; + mdfso->pTemplate = pTemplate; + mdfso->ulCount = ulCount; + mdfso->hash = hash; - nssCKFWHash_Iterate(hash, findfcn, mdfso); + nssCKFWHash_Iterate(hash, findfcn, mdfso); - if( CKR_OK != mdfso->error ) { - goto loser; - } + if (CKR_OK != mdfso->error) { + goto loser; + } - rv->etc = (void *)mdfso; - rv->Final = nss_ckmdFindSessionObjects_Final; - rv->Next = nss_ckmdFindSessionObjects_Next; + rv->etc = (void *)mdfso; + rv->Final = nss_ckmdFindSessionObjects_Final; + rv->Next = nss_ckmdFindSessionObjects_Next; #ifdef DEBUG - if( (*pError = nss_ckmdFindSessionObjects_add_pointer(rv)) != CKR_OK ) { - goto loser; - } -#endif /* DEBUG */ - mdfso->arena = arena; + if ((*pError = nss_ckmdFindSessionObjects_add_pointer(rv)) != CKR_OK) { + goto loser; + } +#endif /* DEBUG */ + mdfso->arena = arena; - return rv; + return rv; loser: - if (arena) { - NSSArena_Destroy(arena); - } - if (*pError == CKR_OK) { - *pError = CKR_HOST_MEMORY; - } - return NULL; + if (arena) { + NSSArena_Destroy(arena); + } + if (*pError == CKR_OK) { + *pError = CKR_HOST_MEMORY; + } + return NULL; } static void -nss_ckmdFindSessionObjects_Final -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance -) +nss_ckmdFindSessionObjects_Final( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance) { - nssCKMDFindSessionObjects *mdfso; + nssCKMDFindSessionObjects *mdfso; #ifdef NSSDEBUG - if( CKR_OK != nss_ckmdFindSessionObjects_verifyPointer(mdFindObjects) ) { - return; - } + if (CKR_OK != nss_ckmdFindSessionObjects_verifyPointer(mdFindObjects)) { + return; + } #endif /* NSSDEBUG */ - mdfso = (nssCKMDFindSessionObjects *)mdFindObjects->etc; - if (mdfso->arena) NSSArena_Destroy(mdfso->arena); + mdfso = (nssCKMDFindSessionObjects *)mdFindObjects->etc; + if (mdfso->arena) + NSSArena_Destroy(mdfso->arena); #ifdef DEBUG - (void)nss_ckmdFindSessionObjects_remove_pointer(mdFindObjects); + (void)nss_ckmdFindSessionObjects_remove_pointer(mdFindObjects); #endif /* DEBUG */ - return; + return; } static NSSCKMDObject * -nss_ckmdFindSessionObjects_Next -( - NSSCKMDFindObjects *mdFindObjects, - NSSCKFWFindObjects *fwFindObjects, - NSSCKMDSession *mdSession, - NSSCKFWSession *fwSession, - NSSCKMDToken *mdToken, - NSSCKFWToken *fwToken, - NSSCKMDInstance *mdInstance, - NSSCKFWInstance *fwInstance, - NSSArena *arena, - CK_RV *pError -) +nss_ckmdFindSessionObjects_Next( + NSSCKMDFindObjects *mdFindObjects, + NSSCKFWFindObjects *fwFindObjects, + NSSCKMDSession *mdSession, + NSSCKFWSession *fwSession, + NSSCKMDToken *mdToken, + NSSCKFWToken *fwToken, + NSSCKMDInstance *mdInstance, + NSSCKFWInstance *fwInstance, + NSSArena *arena, + CK_RV *pError) { - nssCKMDFindSessionObjects *mdfso; - NSSCKMDObject *rv = (NSSCKMDObject *)NULL; + nssCKMDFindSessionObjects *mdfso; + NSSCKMDObject *rv = (NSSCKMDObject *)NULL; #ifdef NSSDEBUG - if( CKR_OK != nss_ckmdFindSessionObjects_verifyPointer(mdFindObjects) ) { - return (NSSCKMDObject *)NULL; - } + if (CKR_OK != nss_ckmdFindSessionObjects_verifyPointer(mdFindObjects)) { + return (NSSCKMDObject *)NULL; + } #endif /* NSSDEBUG */ - mdfso = (nssCKMDFindSessionObjects *)mdFindObjects->etc; + mdfso = (nssCKMDFindSessionObjects *)mdFindObjects->etc; - while (!rv) { - if( (struct nodeStr *)NULL == mdfso->list ) { - *pError = CKR_OK; - return (NSSCKMDObject *)NULL; + while (!rv) { + if ((struct nodeStr *)NULL == mdfso->list) { + *pError = CKR_OK; + return (NSSCKMDObject *)NULL; + } + + if (nssCKFWHash_Exists(mdfso->hash, mdfso->list->mdObject)) { + rv = mdfso->list->mdObject; + } + + mdfso->list = mdfso->list->next; } - if( nssCKFWHash_Exists(mdfso->hash, mdfso->list->mdObject) ) { - rv = mdfso->list->mdObject; - } - - mdfso->list = mdfso->list->next; - } - - return rv; + return rv; } diff --git a/security/nss/lib/ckfw/slot.c b/security/nss/lib/ckfw/slot.c index 658aedb652d9..fa3ffbced832 100644 --- a/security/nss/lib/ckfw/slot.c +++ b/security/nss/lib/ckfw/slot.c @@ -46,35 +46,35 @@ */ struct NSSCKFWSlotStr { - NSSCKFWMutex *mutex; - NSSCKMDSlot *mdSlot; - NSSCKFWInstance *fwInstance; - NSSCKMDInstance *mdInstance; - CK_SLOT_ID slotID; + NSSCKFWMutex *mutex; + NSSCKMDSlot *mdSlot; + NSSCKFWInstance *fwInstance; + NSSCKMDInstance *mdInstance; + CK_SLOT_ID slotID; - /* - * Everything above is set at creation time, and then not modified. - * The invariants the mutex protects are: - * - * 1) Each of the cached descriptions (versions, etc.) are in an - * internally consistant state. - * - * 2) The fwToken points to the token currently in the slot, and - * it is in a consistant state. - * - * Note that the calls accessing the cached descriptions will - * call the NSSCKMDSlot methods with the mutex locked. Those - * methods may then call the public NSSCKFWSlot routines. Those - * public routines only access the constant data above, so there's - * no problem. But be careful if you add to this object; mutexes - * are in general not reentrant, so don't create deadlock situations. - */ + /* + * Everything above is set at creation time, and then not modified. + * The invariants the mutex protects are: + * + * 1) Each of the cached descriptions (versions, etc.) are in an + * internally consistant state. + * + * 2) The fwToken points to the token currently in the slot, and + * it is in a consistant state. + * + * Note that the calls accessing the cached descriptions will + * call the NSSCKMDSlot methods with the mutex locked. Those + * methods may then call the public NSSCKFWSlot routines. Those + * public routines only access the constant data above, so there's + * no problem. But be careful if you add to this object; mutexes + * are in general not reentrant, so don't create deadlock situations. + */ - NSSUTF8 *slotDescription; - NSSUTF8 *manufacturerID; - CK_VERSION hardwareVersion; - CK_VERSION firmwareVersion; - NSSCKFWToken *fwToken; + NSSUTF8 *slotDescription; + NSSUTF8 *manufacturerID; + CK_VERSION hardwareVersion; + CK_VERSION firmwareVersion; + NSSCKFWToken *fwToken; }; #ifdef DEBUG @@ -90,30 +90,24 @@ struct NSSCKFWSlotStr { */ static CK_RV -slot_add_pointer -( - const NSSCKFWSlot *fwSlot -) +slot_add_pointer( + const NSSCKFWSlot *fwSlot) { - return CKR_OK; + return CKR_OK; } static CK_RV -slot_remove_pointer -( - const NSSCKFWSlot *fwSlot -) +slot_remove_pointer( + const NSSCKFWSlot *fwSlot) { - return CKR_OK; + return CKR_OK; } NSS_IMPLEMENT CK_RV -nssCKFWSlot_verifyPointer -( - const NSSCKFWSlot *fwSlot -) +nssCKFWSlot_verifyPointer( + const NSSCKFWSlot *fwSlot) { - return CKR_OK; + return CKR_OK; } #endif /* DEBUG */ @@ -123,86 +117,84 @@ nssCKFWSlot_verifyPointer * */ NSS_IMPLEMENT NSSCKFWSlot * -nssCKFWSlot_Create -( - NSSCKFWInstance *fwInstance, - NSSCKMDSlot *mdSlot, - CK_SLOT_ID slotID, - CK_RV *pError -) +nssCKFWSlot_Create( + NSSCKFWInstance *fwInstance, + NSSCKMDSlot *mdSlot, + CK_SLOT_ID slotID, + CK_RV *pError) { - NSSCKFWSlot *fwSlot; - NSSCKMDInstance *mdInstance; - NSSArena *arena; + NSSCKFWSlot *fwSlot; + NSSCKMDInstance *mdInstance; + NSSArena *arena; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWSlot *)NULL; - } + if (!pError) { + return (NSSCKFWSlot *)NULL; + } - *pError = nssCKFWInstance_verifyPointer(fwInstance); - if( CKR_OK != *pError ) { - return (NSSCKFWSlot *)NULL; - } + *pError = nssCKFWInstance_verifyPointer(fwInstance); + if (CKR_OK != *pError) { + return (NSSCKFWSlot *)NULL; + } #endif /* NSSDEBUG */ - mdInstance = nssCKFWInstance_GetMDInstance(fwInstance); - if (!mdInstance) { - *pError = CKR_GENERAL_ERROR; - return (NSSCKFWSlot *)NULL; - } - - arena = nssCKFWInstance_GetArena(fwInstance, pError); - if (!arena) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + mdInstance = nssCKFWInstance_GetMDInstance(fwInstance); + if (!mdInstance) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWSlot *)NULL; } - } - fwSlot = nss_ZNEW(arena, NSSCKFWSlot); - if (!fwSlot) { - *pError = CKR_HOST_MEMORY; - return (NSSCKFWSlot *)NULL; - } - - fwSlot->mdSlot = mdSlot; - fwSlot->fwInstance = fwInstance; - fwSlot->mdInstance = mdInstance; - fwSlot->slotID = slotID; - - fwSlot->mutex = nssCKFWInstance_CreateMutex(fwInstance, arena, pError); - if (!fwSlot->mutex) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + arena = nssCKFWInstance_GetArena(fwInstance, pError); + if (!arena) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } } - (void)nss_ZFreeIf(fwSlot); - return (NSSCKFWSlot *)NULL; - } - if (mdSlot->Initialize) { - *pError = CKR_OK; - *pError = mdSlot->Initialize(mdSlot, fwSlot, mdInstance, fwInstance); - if( CKR_OK != *pError ) { - (void)nssCKFWMutex_Destroy(fwSlot->mutex); - (void)nss_ZFreeIf(fwSlot); - return (NSSCKFWSlot *)NULL; + fwSlot = nss_ZNEW(arena, NSSCKFWSlot); + if (!fwSlot) { + *pError = CKR_HOST_MEMORY; + return (NSSCKFWSlot *)NULL; + } + + fwSlot->mdSlot = mdSlot; + fwSlot->fwInstance = fwInstance; + fwSlot->mdInstance = mdInstance; + fwSlot->slotID = slotID; + + fwSlot->mutex = nssCKFWInstance_CreateMutex(fwInstance, arena, pError); + if (!fwSlot->mutex) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + (void)nss_ZFreeIf(fwSlot); + return (NSSCKFWSlot *)NULL; + } + + if (mdSlot->Initialize) { + *pError = CKR_OK; + *pError = mdSlot->Initialize(mdSlot, fwSlot, mdInstance, fwInstance); + if (CKR_OK != *pError) { + (void)nssCKFWMutex_Destroy(fwSlot->mutex); + (void)nss_ZFreeIf(fwSlot); + return (NSSCKFWSlot *)NULL; + } } - } #ifdef DEBUG - *pError = slot_add_pointer(fwSlot); - if( CKR_OK != *pError ) { - if (mdSlot->Destroy) { - mdSlot->Destroy(mdSlot, fwSlot, mdInstance, fwInstance); - } + *pError = slot_add_pointer(fwSlot); + if (CKR_OK != *pError) { + if (mdSlot->Destroy) { + mdSlot->Destroy(mdSlot, fwSlot, mdInstance, fwInstance); + } - (void)nssCKFWMutex_Destroy(fwSlot->mutex); - (void)nss_ZFreeIf(fwSlot); - return (NSSCKFWSlot *)NULL; - } + (void)nssCKFWMutex_Destroy(fwSlot->mutex); + (void)nss_ZFreeIf(fwSlot); + return (NSSCKFWSlot *)NULL; + } #endif /* DEBUG */ - return fwSlot; + return fwSlot; } /* @@ -210,35 +202,33 @@ nssCKFWSlot_Create * */ NSS_IMPLEMENT CK_RV -nssCKFWSlot_Destroy -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_Destroy( + NSSCKFWSlot *fwSlot) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWSlot_verifyPointer(fwSlot); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSlot_verifyPointer(fwSlot); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - if (fwSlot->fwToken) { - nssCKFWToken_Destroy(fwSlot->fwToken); - } + if (fwSlot->fwToken) { + nssCKFWToken_Destroy(fwSlot->fwToken); + } - (void)nssCKFWMutex_Destroy(fwSlot->mutex); + (void)nssCKFWMutex_Destroy(fwSlot->mutex); - if (fwSlot->mdSlot->Destroy) { - fwSlot->mdSlot->Destroy(fwSlot->mdSlot, fwSlot, - fwSlot->mdInstance, fwSlot->fwInstance); - } + if (fwSlot->mdSlot->Destroy) { + fwSlot->mdSlot->Destroy(fwSlot->mdSlot, fwSlot, + fwSlot->mdInstance, fwSlot->fwInstance); + } #ifdef DEBUG - error = slot_remove_pointer(fwSlot); + error = slot_remove_pointer(fwSlot); #endif /* DEBUG */ - (void)nss_ZFreeIf(fwSlot); - return error; + (void)nss_ZFreeIf(fwSlot); + return error; } /* @@ -246,18 +236,16 @@ nssCKFWSlot_Destroy * */ NSS_IMPLEMENT NSSCKMDSlot * -nssCKFWSlot_GetMDSlot -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetMDSlot( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return (NSSCKMDSlot *)NULL; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return (NSSCKMDSlot *)NULL; + } #endif /* NSSDEBUG */ - return fwSlot->mdSlot; + return fwSlot->mdSlot; } /* @@ -266,18 +254,16 @@ nssCKFWSlot_GetMDSlot */ NSS_IMPLEMENT NSSCKFWInstance * -nssCKFWSlot_GetFWInstance -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetFWInstance( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return (NSSCKFWInstance *)NULL; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return (NSSCKFWInstance *)NULL; + } #endif /* NSSDEBUG */ - return fwSlot->fwInstance; + return fwSlot->fwInstance; } /* @@ -286,18 +272,16 @@ nssCKFWSlot_GetFWInstance */ NSS_IMPLEMENT NSSCKMDInstance * -nssCKFWSlot_GetMDInstance -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetMDInstance( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return (NSSCKMDInstance *)NULL; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return (NSSCKMDInstance *)NULL; + } #endif /* NSSDEBUG */ - return fwSlot->mdInstance; + return fwSlot->mdInstance; } /* @@ -305,18 +289,16 @@ nssCKFWSlot_GetMDInstance * */ NSS_IMPLEMENT CK_SLOT_ID -nssCKFWSlot_GetSlotID -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetSlotID( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return (CK_SLOT_ID)0; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return (CK_SLOT_ID)0; + } #endif /* NSSDEBUG */ - return fwSlot->slotID; + return fwSlot->slotID; } /* @@ -324,49 +306,48 @@ nssCKFWSlot_GetSlotID * */ NSS_IMPLEMENT CK_RV -nssCKFWSlot_GetSlotDescription -( - NSSCKFWSlot *fwSlot, - CK_CHAR slotDescription[64] -) +nssCKFWSlot_GetSlotDescription( + NSSCKFWSlot *fwSlot, + CK_CHAR slotDescription[64]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == slotDescription ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == slotDescription) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWSlot_verifyPointer(fwSlot); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSlot_verifyPointer(fwSlot); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwSlot->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwSlot->slotDescription) { - if (fwSlot->mdSlot->GetSlotDescription) { - fwSlot->slotDescription = fwSlot->mdSlot->GetSlotDescription( - fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, - fwSlot->fwInstance, &error); - if ((!fwSlot->slotDescription) && (CKR_OK != error)) { - goto done; - } - } else { - fwSlot->slotDescription = (NSSUTF8 *) ""; + error = nssCKFWMutex_Lock(fwSlot->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwSlot->slotDescription, (char *)slotDescription, 64, ' '); - error = CKR_OK; + if (!fwSlot->slotDescription) { + if (fwSlot->mdSlot->GetSlotDescription) { + fwSlot->slotDescription = fwSlot->mdSlot->GetSlotDescription( + fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, + fwSlot->fwInstance, &error); + if ((!fwSlot->slotDescription) && (CKR_OK != error)) { + goto done; + } + } + else { + fwSlot->slotDescription = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwSlot->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwSlot->slotDescription, (char *)slotDescription, 64, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwSlot->mutex); + return error; } /* @@ -374,49 +355,48 @@ nssCKFWSlot_GetSlotDescription * */ NSS_IMPLEMENT CK_RV -nssCKFWSlot_GetManufacturerID -( - NSSCKFWSlot *fwSlot, - CK_CHAR manufacturerID[32] -) +nssCKFWSlot_GetManufacturerID( + NSSCKFWSlot *fwSlot, + CK_CHAR manufacturerID[32]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == manufacturerID ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == manufacturerID) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWSlot_verifyPointer(fwSlot); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSlot_verifyPointer(fwSlot); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwSlot->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwSlot->manufacturerID) { - if (fwSlot->mdSlot->GetManufacturerID) { - fwSlot->manufacturerID = fwSlot->mdSlot->GetManufacturerID( - fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, - fwSlot->fwInstance, &error); - if ((!fwSlot->manufacturerID) && (CKR_OK != error)) { - goto done; - } - } else { - fwSlot->manufacturerID = (NSSUTF8 *) ""; + error = nssCKFWMutex_Lock(fwSlot->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwSlot->manufacturerID, (char *)manufacturerID, 32, ' '); - error = CKR_OK; + if (!fwSlot->manufacturerID) { + if (fwSlot->mdSlot->GetManufacturerID) { + fwSlot->manufacturerID = fwSlot->mdSlot->GetManufacturerID( + fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, + fwSlot->fwInstance, &error); + if ((!fwSlot->manufacturerID) && (CKR_OK != error)) { + goto done; + } + } + else { + fwSlot->manufacturerID = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwSlot->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwSlot->manufacturerID, (char *)manufacturerID, 32, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwSlot->mutex); + return error; } /* @@ -424,23 +404,21 @@ nssCKFWSlot_GetManufacturerID * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWSlot_GetTokenPresent -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetTokenPresent( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwSlot->mdSlot->GetTokenPresent) { - return CK_TRUE; - } + if (!fwSlot->mdSlot->GetTokenPresent) { + return CK_TRUE; + } - return fwSlot->mdSlot->GetTokenPresent(fwSlot->mdSlot, fwSlot, - fwSlot->mdInstance, fwSlot->fwInstance); + return fwSlot->mdSlot->GetTokenPresent(fwSlot->mdSlot, fwSlot, + fwSlot->mdInstance, fwSlot->fwInstance); } /* @@ -448,23 +426,21 @@ nssCKFWSlot_GetTokenPresent * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWSlot_GetRemovableDevice -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetRemovableDevice( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwSlot->mdSlot->GetRemovableDevice) { - return CK_FALSE; - } + if (!fwSlot->mdSlot->GetRemovableDevice) { + return CK_FALSE; + } - return fwSlot->mdSlot->GetRemovableDevice(fwSlot->mdSlot, fwSlot, - fwSlot->mdInstance, fwSlot->fwInstance); + return fwSlot->mdSlot->GetRemovableDevice(fwSlot->mdSlot, fwSlot, + fwSlot->mdInstance, fwSlot->fwInstance); } /* @@ -472,23 +448,21 @@ nssCKFWSlot_GetRemovableDevice * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWSlot_GetHardwareSlot -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetHardwareSlot( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwSlot->mdSlot->GetHardwareSlot) { - return CK_FALSE; - } + if (!fwSlot->mdSlot->GetHardwareSlot) { + return CK_FALSE; + } - return fwSlot->mdSlot->GetHardwareSlot(fwSlot->mdSlot, fwSlot, - fwSlot->mdInstance, fwSlot->fwInstance); + return fwSlot->mdSlot->GetHardwareSlot(fwSlot->mdSlot, fwSlot, + fwSlot->mdInstance, fwSlot->fwInstance); } /* @@ -496,43 +470,42 @@ nssCKFWSlot_GetHardwareSlot * */ NSS_IMPLEMENT CK_VERSION -nssCKFWSlot_GetHardwareVersion -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetHardwareVersion( + NSSCKFWSlot *fwSlot) { - CK_VERSION rv; + CK_VERSION rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + rv.major = rv.minor = 0; + return rv; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwSlot->mutex) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWMutex_Lock(fwSlot->mutex)) { + rv.major = rv.minor = 0; + return rv; + } + + if ((0 != fwSlot->hardwareVersion.major) || + (0 != fwSlot->hardwareVersion.minor)) { + rv = fwSlot->hardwareVersion; + goto done; + } + + if (fwSlot->mdSlot->GetHardwareVersion) { + fwSlot->hardwareVersion = fwSlot->mdSlot->GetHardwareVersion( + fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, fwSlot->fwInstance); + } + else { + fwSlot->hardwareVersion.major = 0; + fwSlot->hardwareVersion.minor = 1; + } - if( (0 != fwSlot->hardwareVersion.major) || - (0 != fwSlot->hardwareVersion.minor) ) { rv = fwSlot->hardwareVersion; - goto done; - } - - if (fwSlot->mdSlot->GetHardwareVersion) { - fwSlot->hardwareVersion = fwSlot->mdSlot->GetHardwareVersion( - fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, fwSlot->fwInstance); - } else { - fwSlot->hardwareVersion.major = 0; - fwSlot->hardwareVersion.minor = 1; - } - - rv = fwSlot->hardwareVersion; - done: - (void)nssCKFWMutex_Unlock(fwSlot->mutex); - return rv; +done: + (void)nssCKFWMutex_Unlock(fwSlot->mutex); + return rv; } /* @@ -540,100 +513,98 @@ nssCKFWSlot_GetHardwareVersion * */ NSS_IMPLEMENT CK_VERSION -nssCKFWSlot_GetFirmwareVersion -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_GetFirmwareVersion( + NSSCKFWSlot *fwSlot) { - CK_VERSION rv; + CK_VERSION rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + rv.major = rv.minor = 0; + return rv; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwSlot->mutex) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWMutex_Lock(fwSlot->mutex)) { + rv.major = rv.minor = 0; + return rv; + } + + if ((0 != fwSlot->firmwareVersion.major) || + (0 != fwSlot->firmwareVersion.minor)) { + rv = fwSlot->firmwareVersion; + goto done; + } + + if (fwSlot->mdSlot->GetFirmwareVersion) { + fwSlot->firmwareVersion = fwSlot->mdSlot->GetFirmwareVersion( + fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, fwSlot->fwInstance); + } + else { + fwSlot->firmwareVersion.major = 0; + fwSlot->firmwareVersion.minor = 1; + } - if( (0 != fwSlot->firmwareVersion.major) || - (0 != fwSlot->firmwareVersion.minor) ) { rv = fwSlot->firmwareVersion; - goto done; - } - - if (fwSlot->mdSlot->GetFirmwareVersion) { - fwSlot->firmwareVersion = fwSlot->mdSlot->GetFirmwareVersion( - fwSlot->mdSlot, fwSlot, fwSlot->mdInstance, fwSlot->fwInstance); - } else { - fwSlot->firmwareVersion.major = 0; - fwSlot->firmwareVersion.minor = 1; - } - - rv = fwSlot->firmwareVersion; - done: - (void)nssCKFWMutex_Unlock(fwSlot->mutex); - return rv; +done: + (void)nssCKFWMutex_Unlock(fwSlot->mutex); + return rv; } /* * nssCKFWSlot_GetToken - * + * */ NSS_IMPLEMENT NSSCKFWToken * -nssCKFWSlot_GetToken -( - NSSCKFWSlot *fwSlot, - CK_RV *pError -) +nssCKFWSlot_GetToken( + NSSCKFWSlot *fwSlot, + CK_RV *pError) { - NSSCKMDToken *mdToken; - NSSCKFWToken *fwToken; + NSSCKMDToken *mdToken; + NSSCKFWToken *fwToken; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWToken *)NULL; - } + if (!pError) { + return (NSSCKFWToken *)NULL; + } - *pError = nssCKFWSlot_verifyPointer(fwSlot); - if( CKR_OK != *pError ) { - return (NSSCKFWToken *)NULL; - } + *pError = nssCKFWSlot_verifyPointer(fwSlot); + if (CKR_OK != *pError) { + return (NSSCKFWToken *)NULL; + } #endif /* NSSDEBUG */ - *pError = nssCKFWMutex_Lock(fwSlot->mutex); - if( CKR_OK != *pError ) { - return (NSSCKFWToken *)NULL; - } - - if (!fwSlot->fwToken) { - if (!fwSlot->mdSlot->GetToken) { - *pError = CKR_GENERAL_ERROR; - fwToken = (NSSCKFWToken *)NULL; - goto done; + *pError = nssCKFWMutex_Lock(fwSlot->mutex); + if (CKR_OK != *pError) { + return (NSSCKFWToken *)NULL; } - mdToken = fwSlot->mdSlot->GetToken(fwSlot->mdSlot, fwSlot, - fwSlot->mdInstance, fwSlot->fwInstance, pError); - if (!mdToken) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - return (NSSCKFWToken *)NULL; + if (!fwSlot->fwToken) { + if (!fwSlot->mdSlot->GetToken) { + *pError = CKR_GENERAL_ERROR; + fwToken = (NSSCKFWToken *)NULL; + goto done; + } + + mdToken = fwSlot->mdSlot->GetToken(fwSlot->mdSlot, fwSlot, + fwSlot->mdInstance, fwSlot->fwInstance, pError); + if (!mdToken) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + return (NSSCKFWToken *)NULL; + } + + fwToken = nssCKFWToken_Create(fwSlot, mdToken, pError); + fwSlot->fwToken = fwToken; + } + else { + fwToken = fwSlot->fwToken; } - fwToken = nssCKFWToken_Create(fwSlot, mdToken, pError); - fwSlot->fwToken = fwToken; - } else { - fwToken = fwSlot->fwToken; - } - - done: - (void)nssCKFWMutex_Unlock(fwSlot->mutex); - return fwToken; +done: + (void)nssCKFWMutex_Unlock(fwSlot->mutex); + return fwToken; } /* @@ -641,25 +612,23 @@ nssCKFWSlot_GetToken * */ NSS_IMPLEMENT void -nssCKFWSlot_ClearToken -( - NSSCKFWSlot *fwSlot -) +nssCKFWSlot_ClearToken( + NSSCKFWSlot *fwSlot) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwSlot->mutex) ) { - /* Now what? */ - return; - } + if (CKR_OK != nssCKFWMutex_Lock(fwSlot->mutex)) { + /* Now what? */ + return; + } - fwSlot->fwToken = (NSSCKFWToken *)NULL; - (void)nssCKFWMutex_Unlock(fwSlot->mutex); - return; + fwSlot->fwToken = (NSSCKFWToken *)NULL; + (void)nssCKFWMutex_Unlock(fwSlot->mutex); + return; } /* @@ -668,18 +637,16 @@ nssCKFWSlot_ClearToken */ NSS_IMPLEMENT NSSCKMDSlot * -NSSCKFWSlot_GetMDSlot -( - NSSCKFWSlot *fwSlot -) +NSSCKFWSlot_GetMDSlot( + NSSCKFWSlot *fwSlot) { #ifdef DEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return (NSSCKMDSlot *)NULL; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return (NSSCKMDSlot *)NULL; + } #endif /* DEBUG */ - return nssCKFWSlot_GetMDSlot(fwSlot); + return nssCKFWSlot_GetMDSlot(fwSlot); } /* @@ -688,18 +655,16 @@ NSSCKFWSlot_GetMDSlot */ NSS_IMPLEMENT NSSCKFWInstance * -NSSCKFWSlot_GetFWInstance -( - NSSCKFWSlot *fwSlot -) +NSSCKFWSlot_GetFWInstance( + NSSCKFWSlot *fwSlot) { #ifdef DEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return (NSSCKFWInstance *)NULL; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return (NSSCKFWInstance *)NULL; + } #endif /* DEBUG */ - return nssCKFWSlot_GetFWInstance(fwSlot); + return nssCKFWSlot_GetFWInstance(fwSlot); } /* @@ -708,16 +673,14 @@ NSSCKFWSlot_GetFWInstance */ NSS_IMPLEMENT NSSCKMDInstance * -NSSCKFWSlot_GetMDInstance -( - NSSCKFWSlot *fwSlot -) +NSSCKFWSlot_GetMDInstance( + NSSCKFWSlot *fwSlot) { #ifdef DEBUG - if( CKR_OK != nssCKFWSlot_verifyPointer(fwSlot) ) { - return (NSSCKMDInstance *)NULL; - } + if (CKR_OK != nssCKFWSlot_verifyPointer(fwSlot)) { + return (NSSCKMDInstance *)NULL; + } #endif /* DEBUG */ - return nssCKFWSlot_GetMDInstance(fwSlot); + return nssCKFWSlot_GetMDInstance(fwSlot); } diff --git a/security/nss/lib/ckfw/token.c b/security/nss/lib/ckfw/token.c index 4a9757643414..d8d37fc8d22f 100644 --- a/security/nss/lib/ckfw/token.c +++ b/security/nss/lib/ckfw/token.c @@ -75,49 +75,49 @@ */ struct NSSCKFWTokenStr { - NSSCKFWMutex *mutex; - NSSArena *arena; - NSSCKMDToken *mdToken; - NSSCKFWSlot *fwSlot; - NSSCKMDSlot *mdSlot; - NSSCKFWInstance *fwInstance; - NSSCKMDInstance *mdInstance; + NSSCKFWMutex *mutex; + NSSArena *arena; + NSSCKMDToken *mdToken; + NSSCKFWSlot *fwSlot; + NSSCKMDSlot *mdSlot; + NSSCKFWInstance *fwInstance; + NSSCKMDInstance *mdInstance; - /* - * Everything above is set at creation time, and then not modified. - * The invariants the mutex protects are: - * - * 1) Each of the cached descriptions (versions, etc.) are in an - * internally consistant state. - * - * 2) The session counts and hashes are consistant. - * - * 3) The object hashes are consistant. - * - * Note that the calls accessing the cached descriptions will call - * the NSSCKMDToken methods with the mutex locked. Those methods - * may then call the public NSSCKFWToken routines. Those public - * routines only access the constant data above and the atomic - * CK_STATE session state variable below, so there's no problem. - * But be careful if you add to this object; mutexes are in - * general not reentrant, so don't create deadlock situations. - */ + /* + * Everything above is set at creation time, and then not modified. + * The invariants the mutex protects are: + * + * 1) Each of the cached descriptions (versions, etc.) are in an + * internally consistant state. + * + * 2) The session counts and hashes are consistant. + * + * 3) The object hashes are consistant. + * + * Note that the calls accessing the cached descriptions will call + * the NSSCKMDToken methods with the mutex locked. Those methods + * may then call the public NSSCKFWToken routines. Those public + * routines only access the constant data above and the atomic + * CK_STATE session state variable below, so there's no problem. + * But be careful if you add to this object; mutexes are in + * general not reentrant, so don't create deadlock situations. + */ - NSSUTF8 *label; - NSSUTF8 *manufacturerID; - NSSUTF8 *model; - NSSUTF8 *serialNumber; - CK_VERSION hardwareVersion; - CK_VERSION firmwareVersion; + NSSUTF8 *label; + NSSUTF8 *manufacturerID; + NSSUTF8 *model; + NSSUTF8 *serialNumber; + CK_VERSION hardwareVersion; + CK_VERSION firmwareVersion; - CK_ULONG sessionCount; - CK_ULONG rwSessionCount; - nssCKFWHash *sessions; - nssCKFWHash *sessionObjectHash; - nssCKFWHash *mdObjectHash; - nssCKFWHash *mdMechanismHash; + CK_ULONG sessionCount; + CK_ULONG rwSessionCount; + nssCKFWHash *sessions; + nssCKFWHash *sessionObjectHash; + nssCKFWHash *mdObjectHash; + nssCKFWHash *mdMechanismHash; - CK_STATE state; + CK_STATE state; }; #ifdef DEBUG @@ -133,30 +133,24 @@ struct NSSCKFWTokenStr { */ static CK_RV -token_add_pointer -( - const NSSCKFWToken *fwToken -) +token_add_pointer( + const NSSCKFWToken *fwToken) { - return CKR_OK; + return CKR_OK; } static CK_RV -token_remove_pointer -( - const NSSCKFWToken *fwToken -) +token_remove_pointer( + const NSSCKFWToken *fwToken) { - return CKR_OK; + return CKR_OK; } NSS_IMPLEMENT CK_RV -nssCKFWToken_verifyPointer -( - const NSSCKFWToken *fwToken -) +nssCKFWToken_verifyPointer( + const NSSCKFWToken *fwToken) { - return CKR_OK; + return CKR_OK; } #endif /* DEBUG */ @@ -166,154 +160,148 @@ nssCKFWToken_verifyPointer * */ NSS_IMPLEMENT NSSCKFWToken * -nssCKFWToken_Create -( - NSSCKFWSlot *fwSlot, - NSSCKMDToken *mdToken, - CK_RV *pError -) +nssCKFWToken_Create( + NSSCKFWSlot *fwSlot, + NSSCKMDToken *mdToken, + CK_RV *pError) { - NSSArena *arena = (NSSArena *)NULL; - NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; - CK_BBOOL called_setup = CK_FALSE; + NSSArena *arena = (NSSArena *)NULL; + NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; + CK_BBOOL called_setup = CK_FALSE; - /* - * We have already verified the arguments in nssCKFWSlot_GetToken. - */ + /* + * We have already verified the arguments in nssCKFWSlot_GetToken. + */ - arena = NSSArena_Create(); - if (!arena) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - - fwToken = nss_ZNEW(arena, NSSCKFWToken); - if (!fwToken) { - *pError = CKR_HOST_MEMORY; - goto loser; - } - - fwToken->arena = arena; - fwToken->mdToken = mdToken; - fwToken->fwSlot = fwSlot; - fwToken->fwInstance = nssCKFWSlot_GetFWInstance(fwSlot); - fwToken->mdInstance = nssCKFWSlot_GetMDInstance(fwSlot); - fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */ - fwToken->sessionCount = 0; - fwToken->rwSessionCount = 0; - - fwToken->mutex = nssCKFWInstance_CreateMutex(fwToken->fwInstance, arena, pError); - if (!fwToken->mutex) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + arena = NSSArena_Create(); + if (!arena) { + *pError = CKR_HOST_MEMORY; + goto loser; } - goto loser; - } - fwToken->sessions = nssCKFWHash_Create(fwToken->fwInstance, arena, pError); - if (!fwToken->sessions) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + fwToken = nss_ZNEW(arena, NSSCKFWToken); + if (!fwToken) { + *pError = CKR_HOST_MEMORY; + goto loser; } - goto loser; - } - if( CK_TRUE != nssCKFWInstance_GetModuleHandlesSessionObjects( - fwToken->fwInstance) ) { - fwToken->sessionObjectHash = nssCKFWHash_Create(fwToken->fwInstance, - arena, pError); - if (!fwToken->sessionObjectHash) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; - } - goto loser; + fwToken->arena = arena; + fwToken->mdToken = mdToken; + fwToken->fwSlot = fwSlot; + fwToken->fwInstance = nssCKFWSlot_GetFWInstance(fwSlot); + fwToken->mdInstance = nssCKFWSlot_GetMDInstance(fwSlot); + fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */ + fwToken->sessionCount = 0; + fwToken->rwSessionCount = 0; + + fwToken->mutex = nssCKFWInstance_CreateMutex(fwToken->fwInstance, arena, pError); + if (!fwToken->mutex) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto loser; } - } - fwToken->mdObjectHash = nssCKFWHash_Create(fwToken->fwInstance, - arena, pError); - if (!fwToken->mdObjectHash) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + fwToken->sessions = nssCKFWHash_Create(fwToken->fwInstance, arena, pError); + if (!fwToken->sessions) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto loser; } - goto loser; - } - fwToken->mdMechanismHash = nssCKFWHash_Create(fwToken->fwInstance, - arena, pError); - if (!fwToken->mdMechanismHash) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + if (CK_TRUE != nssCKFWInstance_GetModuleHandlesSessionObjects( + fwToken->fwInstance)) { + fwToken->sessionObjectHash = nssCKFWHash_Create(fwToken->fwInstance, + arena, pError); + if (!fwToken->sessionObjectHash) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto loser; + } } - goto loser; - } - /* More here */ - - if (mdToken->Setup) { - *pError = mdToken->Setup(mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); - if( CKR_OK != *pError ) { - goto loser; + fwToken->mdObjectHash = nssCKFWHash_Create(fwToken->fwInstance, + arena, pError); + if (!fwToken->mdObjectHash) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto loser; } - } - called_setup = CK_TRUE; + fwToken->mdMechanismHash = nssCKFWHash_Create(fwToken->fwInstance, + arena, pError); + if (!fwToken->mdMechanismHash) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto loser; + } + + /* More here */ + + if (mdToken->Setup) { + *pError = mdToken->Setup(mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); + if (CKR_OK != *pError) { + goto loser; + } + } + + called_setup = CK_TRUE; #ifdef DEBUG - *pError = token_add_pointer(fwToken); - if( CKR_OK != *pError ) { - goto loser; - } + *pError = token_add_pointer(fwToken); + if (CKR_OK != *pError) { + goto loser; + } #endif /* DEBUG */ - *pError = CKR_OK; - return fwToken; + *pError = CKR_OK; + return fwToken; - loser: +loser: - if( CK_TRUE == called_setup ) { - if (mdToken->Invalidate) { - mdToken->Invalidate(mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); + if (CK_TRUE == called_setup) { + if (mdToken->Invalidate) { + mdToken->Invalidate(mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); + } } - } - if (arena) { - (void)NSSArena_Destroy(arena); - } + if (arena) { + (void)NSSArena_Destroy(arena); + } - return (NSSCKFWToken *)NULL; + return (NSSCKFWToken *)NULL; } static void -nss_ckfwtoken_session_iterator -( - const void *key, - void *value, - void *closure -) +nss_ckfwtoken_session_iterator( + const void *key, + void *value, + void *closure) { - /* - * Remember that the fwToken->mutex is locked - */ - NSSCKFWSession *fwSession = (NSSCKFWSession *)value; - (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); - return; + /* + * Remember that the fwToken->mutex is locked + */ + NSSCKFWSession *fwSession = (NSSCKFWSession *)value; + (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); + return; } static void -nss_ckfwtoken_object_iterator -( - const void *key, - void *value, - void *closure -) +nss_ckfwtoken_object_iterator( + const void *key, + void *value, + void *closure) { - /* - * Remember that the fwToken->mutex is locked - */ - NSSCKFWObject *fwObject = (NSSCKFWObject *)value; - (void)nssCKFWObject_Finalize(fwObject, CK_FALSE); - return; + /* + * Remember that the fwToken->mutex is locked + */ + NSSCKFWObject *fwObject = (NSSCKFWObject *)value; + (void)nssCKFWObject_Finalize(fwObject, CK_FALSE); + return; } /* @@ -321,56 +309,54 @@ nss_ckfwtoken_object_iterator * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_Destroy -( - NSSCKFWToken *fwToken -) +nssCKFWToken_Destroy( + NSSCKFWToken *fwToken) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - (void)nssCKFWMutex_Destroy(fwToken->mutex); - - if (fwToken->mdToken->Invalidate) { - fwToken->mdToken->Invalidate(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); - } - /* we can destroy the list without locking now because no one else is - * referencing us (or _Destroy was invalidly called!) - */ - nssCKFWHash_Iterate(fwToken->sessions, nss_ckfwtoken_session_iterator, - (void *)NULL); - nssCKFWHash_Destroy(fwToken->sessions); + (void)nssCKFWMutex_Destroy(fwToken->mutex); - /* session objects go away when their sessions are removed */ - if (fwToken->sessionObjectHash) { - nssCKFWHash_Destroy(fwToken->sessionObjectHash); - } + if (fwToken->mdToken->Invalidate) { + fwToken->mdToken->Invalidate(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); + } + /* we can destroy the list without locking now because no one else is + * referencing us (or _Destroy was invalidly called!) + */ + nssCKFWHash_Iterate(fwToken->sessions, nss_ckfwtoken_session_iterator, + (void *)NULL); + nssCKFWHash_Destroy(fwToken->sessions); - /* free up the token objects */ - if (fwToken->mdObjectHash) { - nssCKFWHash_Iterate(fwToken->mdObjectHash, nss_ckfwtoken_object_iterator, - (void *)NULL); - nssCKFWHash_Destroy(fwToken->mdObjectHash); - } - if (fwToken->mdMechanismHash) { - nssCKFWHash_Destroy(fwToken->mdMechanismHash); - } + /* session objects go away when their sessions are removed */ + if (fwToken->sessionObjectHash) { + nssCKFWHash_Destroy(fwToken->sessionObjectHash); + } + + /* free up the token objects */ + if (fwToken->mdObjectHash) { + nssCKFWHash_Iterate(fwToken->mdObjectHash, nss_ckfwtoken_object_iterator, + (void *)NULL); + nssCKFWHash_Destroy(fwToken->mdObjectHash); + } + if (fwToken->mdMechanismHash) { + nssCKFWHash_Destroy(fwToken->mdMechanismHash); + } + + nssCKFWSlot_ClearToken(fwToken->fwSlot); - nssCKFWSlot_ClearToken(fwToken->fwSlot); - #ifdef DEBUG - error = token_remove_pointer(fwToken); + error = token_remove_pointer(fwToken); #endif /* DEBUG */ - (void)NSSArena_Destroy(fwToken->arena); - return error; + (void)NSSArena_Destroy(fwToken->arena); + return error; } /* @@ -378,18 +364,16 @@ nssCKFWToken_Destroy * */ NSS_IMPLEMENT NSSCKMDToken * -nssCKFWToken_GetMDToken -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMDToken( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (NSSCKMDToken *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (NSSCKMDToken *)NULL; + } #endif /* NSSDEBUG */ - return fwToken->mdToken; + return fwToken->mdToken; } /* @@ -397,24 +381,22 @@ nssCKFWToken_GetMDToken * */ NSS_IMPLEMENT NSSArena * -nssCKFWToken_GetArena -( - NSSCKFWToken *fwToken, - CK_RV *pError -) +nssCKFWToken_GetArena( + NSSCKFWToken *fwToken, + CK_RV *pError) { #ifdef NSSDEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - *pError = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != *pError ) { - return (NSSArena *)NULL; - } + *pError = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != *pError) { + return (NSSArena *)NULL; + } #endif /* NSSDEBUG */ - return fwToken->arena; + return fwToken->arena; } /* @@ -422,18 +404,16 @@ nssCKFWToken_GetArena * */ NSS_IMPLEMENT NSSCKFWSlot * -nssCKFWToken_GetFWSlot -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetFWSlot( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (NSSCKFWSlot *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (NSSCKFWSlot *)NULL; + } #endif /* NSSDEBUG */ - return fwToken->fwSlot; + return fwToken->fwSlot; } /* @@ -441,18 +421,16 @@ nssCKFWToken_GetFWSlot * */ NSS_IMPLEMENT NSSCKMDSlot * -nssCKFWToken_GetMDSlot -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMDSlot( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (NSSCKMDSlot *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (NSSCKMDSlot *)NULL; + } #endif /* NSSDEBUG */ - return fwToken->mdSlot; + return fwToken->mdSlot; } /* @@ -460,29 +438,27 @@ nssCKFWToken_GetMDSlot * */ NSS_IMPLEMENT CK_STATE -nssCKFWToken_GetSessionState -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetSessionState( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CKS_RO_PUBLIC_SESSION; /* whatever */ - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CKS_RO_PUBLIC_SESSION; /* whatever */ + } #endif /* NSSDEBUG */ - /* - * BTW, do not lock the token in this method. - */ + /* + * BTW, do not lock the token in this method. + */ - /* - * Theoretically, there is no state if there aren't any - * sessions open. But then we'd need to worry about - * reporting an error, etc. What the heck-- let's just - * revert to CKR_RO_PUBLIC_SESSION as the "default." - */ + /* + * Theoretically, there is no state if there aren't any + * sessions open. But then we'd need to worry about + * reporting an error, etc. What the heck-- let's just + * revert to CKR_RO_PUBLIC_SESSION as the "default." + */ - return fwToken->state; + return fwToken->state; } /* @@ -490,56 +466,55 @@ nssCKFWToken_GetSessionState * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_InitToken -( - NSSCKFWToken *fwToken, - NSSItem *pin, - NSSUTF8 *label -) +nssCKFWToken_InitToken( + NSSCKFWToken *fwToken, + NSSItem *pin, + NSSUTF8 *label) { - CK_RV error; + CK_RV error; #ifdef NSSDEBUG - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return CKR_ARGUMENTS_BAD; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return CKR_ARGUMENTS_BAD; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { - return error; - } - - if( fwToken->sessionCount > 0 ) { - error = CKR_SESSION_EXISTS; - goto done; - } - - if (!fwToken->mdToken->InitToken) { - error = CKR_DEVICE_ERROR; - goto done; - } - - if (!pin) { - if( nssCKFWToken_GetHasProtectedAuthenticationPath(fwToken) ) { - ; /* okay */ - } else { - error = CKR_PIN_INCORRECT; - goto done; + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; } - } - if (!label) { - label = (NSSUTF8 *) ""; - } + if (fwToken->sessionCount > 0) { + error = CKR_SESSION_EXISTS; + goto done; + } - error = fwToken->mdToken->InitToken(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance, pin, label); + if (!fwToken->mdToken->InitToken) { + error = CKR_DEVICE_ERROR; + goto done; + } - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return error; + if (!pin) { + if (nssCKFWToken_GetHasProtectedAuthenticationPath(fwToken)) { + ; /* okay */ + } + else { + error = CKR_PIN_INCORRECT; + goto done; + } + } + + if (!label) { + label = (NSSUTF8 *)""; + } + + error = fwToken->mdToken->InitToken(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance, pin, label); + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return error; } /* @@ -547,48 +522,47 @@ nssCKFWToken_InitToken * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_GetLabel -( - NSSCKFWToken *fwToken, - CK_CHAR label[32] -) +nssCKFWToken_GetLabel( + NSSCKFWToken *fwToken, + CK_CHAR label[32]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == label ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == label) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwToken->label) { - if (fwToken->mdToken->GetLabel) { - fwToken->label = fwToken->mdToken->GetLabel(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance, &error); - if ((!fwToken->label) && (CKR_OK != error)) { - goto done; - } - } else { - fwToken->label = (NSSUTF8 *) ""; + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwToken->label, (char *)label, 32, ' '); - error = CKR_OK; + if (!fwToken->label) { + if (fwToken->mdToken->GetLabel) { + fwToken->label = fwToken->mdToken->GetLabel(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance, &error); + if ((!fwToken->label) && (CKR_OK != error)) { + goto done; + } + } + else { + fwToken->label = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwToken->label, (char *)label, 32, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return error; } /* @@ -596,48 +570,47 @@ nssCKFWToken_GetLabel * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_GetManufacturerID -( - NSSCKFWToken *fwToken, - CK_CHAR manufacturerID[32] -) +nssCKFWToken_GetManufacturerID( + NSSCKFWToken *fwToken, + CK_CHAR manufacturerID[32]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == manufacturerID ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == manufacturerID) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwToken->manufacturerID) { - if (fwToken->mdToken->GetManufacturerID) { - fwToken->manufacturerID = fwToken->mdToken->GetManufacturerID(fwToken->mdToken, - fwToken, fwToken->mdInstance, fwToken->fwInstance, &error); - if ((!fwToken->manufacturerID) && (CKR_OK != error)) { - goto done; - } - } else { - fwToken->manufacturerID = (NSSUTF8 *)""; + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwToken->manufacturerID, (char *)manufacturerID, 32, ' '); - error = CKR_OK; + if (!fwToken->manufacturerID) { + if (fwToken->mdToken->GetManufacturerID) { + fwToken->manufacturerID = fwToken->mdToken->GetManufacturerID(fwToken->mdToken, + fwToken, fwToken->mdInstance, fwToken->fwInstance, &error); + if ((!fwToken->manufacturerID) && (CKR_OK != error)) { + goto done; + } + } + else { + fwToken->manufacturerID = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwToken->manufacturerID, (char *)manufacturerID, 32, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return error; } /* @@ -645,48 +618,47 @@ nssCKFWToken_GetManufacturerID * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_GetModel -( - NSSCKFWToken *fwToken, - CK_CHAR model[16] -) +nssCKFWToken_GetModel( + NSSCKFWToken *fwToken, + CK_CHAR model[16]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == model ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == model) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwToken->model) { - if (fwToken->mdToken->GetModel) { - fwToken->model = fwToken->mdToken->GetModel(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance, &error); - if ((!fwToken->model) && (CKR_OK != error)) { - goto done; - } - } else { - fwToken->model = (NSSUTF8 *)""; + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwToken->model, (char *)model, 16, ' '); - error = CKR_OK; + if (!fwToken->model) { + if (fwToken->mdToken->GetModel) { + fwToken->model = fwToken->mdToken->GetModel(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance, &error); + if ((!fwToken->model) && (CKR_OK != error)) { + goto done; + } + } + else { + fwToken->model = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwToken->model, (char *)model, 16, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return error; } /* @@ -694,73 +666,69 @@ nssCKFWToken_GetModel * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_GetSerialNumber -( - NSSCKFWToken *fwToken, - CK_CHAR serialNumber[16] -) +nssCKFWToken_GetSerialNumber( + NSSCKFWToken *fwToken, + CK_CHAR serialNumber[16]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - if( (CK_CHAR_PTR)NULL == serialNumber ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == serialNumber) { + return CKR_ARGUMENTS_BAD; + } - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { - return error; - } - - if (!fwToken->serialNumber) { - if (fwToken->mdToken->GetSerialNumber) { - fwToken->serialNumber = fwToken->mdToken->GetSerialNumber(fwToken->mdToken, - fwToken, fwToken->mdInstance, fwToken->fwInstance, &error); - if ((!fwToken->serialNumber) && (CKR_OK != error)) { - goto done; - } - } else { - fwToken->serialNumber = (NSSUTF8 *)""; + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; } - } - (void)nssUTF8_CopyIntoFixedBuffer(fwToken->serialNumber, (char *)serialNumber, 16, ' '); - error = CKR_OK; + if (!fwToken->serialNumber) { + if (fwToken->mdToken->GetSerialNumber) { + fwToken->serialNumber = fwToken->mdToken->GetSerialNumber(fwToken->mdToken, + fwToken, fwToken->mdInstance, fwToken->fwInstance, &error); + if ((!fwToken->serialNumber) && (CKR_OK != error)) { + goto done; + } + } + else { + fwToken->serialNumber = (NSSUTF8 *)""; + } + } - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return error; + (void)nssUTF8_CopyIntoFixedBuffer(fwToken->serialNumber, (char *)serialNumber, 16, ' '); + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return error; } - /* * nssCKFWToken_GetHasRNG * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetHasRNG -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetHasRNG( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetHasRNG) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetHasRNG) { + return CK_FALSE; + } - return fwToken->mdToken->GetHasRNG(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetHasRNG(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -768,23 +736,21 @@ nssCKFWToken_GetHasRNG * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetIsWriteProtected -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetIsWriteProtected( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetIsWriteProtected) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetIsWriteProtected) { + return CK_FALSE; + } - return fwToken->mdToken->GetIsWriteProtected(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetIsWriteProtected(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -792,23 +758,21 @@ nssCKFWToken_GetIsWriteProtected * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetLoginRequired -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetLoginRequired( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetLoginRequired) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetLoginRequired) { + return CK_FALSE; + } - return fwToken->mdToken->GetLoginRequired(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetLoginRequired(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -816,23 +780,21 @@ nssCKFWToken_GetLoginRequired * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetUserPinInitialized -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetUserPinInitialized( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetUserPinInitialized) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetUserPinInitialized) { + return CK_FALSE; + } - return fwToken->mdToken->GetUserPinInitialized(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetUserPinInitialized(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -840,23 +802,21 @@ nssCKFWToken_GetUserPinInitialized * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetRestoreKeyNotNeeded -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetRestoreKeyNotNeeded( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetRestoreKeyNotNeeded) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetRestoreKeyNotNeeded) { + return CK_FALSE; + } - return fwToken->mdToken->GetRestoreKeyNotNeeded(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetRestoreKeyNotNeeded(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -864,23 +824,21 @@ nssCKFWToken_GetRestoreKeyNotNeeded * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetHasClockOnToken -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetHasClockOnToken( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetHasClockOnToken) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetHasClockOnToken) { + return CK_FALSE; + } - return fwToken->mdToken->GetHasClockOnToken(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetHasClockOnToken(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -888,23 +846,21 @@ nssCKFWToken_GetHasClockOnToken * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetHasProtectedAuthenticationPath -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetHasProtectedAuthenticationPath( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetHasProtectedAuthenticationPath) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetHasProtectedAuthenticationPath) { + return CK_FALSE; + } - return fwToken->mdToken->GetHasProtectedAuthenticationPath(fwToken->mdToken, - fwToken, fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetHasProtectedAuthenticationPath(fwToken->mdToken, + fwToken, fwToken->mdInstance, fwToken->fwInstance); } /* @@ -912,23 +868,21 @@ nssCKFWToken_GetHasProtectedAuthenticationPath * */ NSS_IMPLEMENT CK_BBOOL -nssCKFWToken_GetSupportsDualCryptoOperations -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetSupportsDualCryptoOperations( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_FALSE; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_FALSE; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetSupportsDualCryptoOperations) { - return CK_FALSE; - } + if (!fwToken->mdToken->GetSupportsDualCryptoOperations) { + return CK_FALSE; + } - return fwToken->mdToken->GetSupportsDualCryptoOperations(fwToken->mdToken, - fwToken, fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetSupportsDualCryptoOperations(fwToken->mdToken, + fwToken, fwToken->mdInstance, fwToken->fwInstance); } /* @@ -936,23 +890,21 @@ nssCKFWToken_GetSupportsDualCryptoOperations * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetMaxSessionCount -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMaxSessionCount( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetMaxSessionCount) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetMaxSessionCount) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetMaxSessionCount(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetMaxSessionCount(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -960,23 +912,21 @@ nssCKFWToken_GetMaxSessionCount * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetMaxRwSessionCount -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMaxRwSessionCount( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetMaxRwSessionCount) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetMaxRwSessionCount) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetMaxRwSessionCount(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetMaxRwSessionCount(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -984,23 +934,21 @@ nssCKFWToken_GetMaxRwSessionCount * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetMaxPinLen -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMaxPinLen( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetMaxPinLen) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetMaxPinLen) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetMaxPinLen(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetMaxPinLen(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -1008,23 +956,21 @@ nssCKFWToken_GetMaxPinLen * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetMinPinLen -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMinPinLen( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetMinPinLen) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetMinPinLen) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetMinPinLen(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetMinPinLen(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -1032,23 +978,21 @@ nssCKFWToken_GetMinPinLen * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetTotalPublicMemory -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetTotalPublicMemory( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetTotalPublicMemory) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetTotalPublicMemory) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetTotalPublicMemory(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetTotalPublicMemory(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -1056,23 +1000,21 @@ nssCKFWToken_GetTotalPublicMemory * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetFreePublicMemory -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetFreePublicMemory( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetFreePublicMemory) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetFreePublicMemory) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetFreePublicMemory(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetFreePublicMemory(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -1080,23 +1022,21 @@ nssCKFWToken_GetFreePublicMemory * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetTotalPrivateMemory -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetTotalPrivateMemory( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetTotalPrivateMemory) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetTotalPrivateMemory) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetTotalPrivateMemory(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetTotalPrivateMemory(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -1104,23 +1044,21 @@ nssCKFWToken_GetTotalPrivateMemory * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetFreePrivateMemory -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetFreePrivateMemory( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CK_UNAVAILABLE_INFORMATION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CK_UNAVAILABLE_INFORMATION; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetFreePrivateMemory) { - return CK_UNAVAILABLE_INFORMATION; - } + if (!fwToken->mdToken->GetFreePrivateMemory) { + return CK_UNAVAILABLE_INFORMATION; + } - return fwToken->mdToken->GetFreePrivateMemory(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetFreePrivateMemory(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -1128,44 +1066,43 @@ nssCKFWToken_GetFreePrivateMemory * */ NSS_IMPLEMENT CK_VERSION -nssCKFWToken_GetHardwareVersion -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetHardwareVersion( + NSSCKFWToken *fwToken) { - CK_VERSION rv; + CK_VERSION rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + rv.major = rv.minor = 0; + return rv; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWMutex_Lock(fwToken->mutex)) { + rv.major = rv.minor = 0; + return rv; + } + + if ((0 != fwToken->hardwareVersion.major) || + (0 != fwToken->hardwareVersion.minor)) { + rv = fwToken->hardwareVersion; + goto done; + } + + if (fwToken->mdToken->GetHardwareVersion) { + fwToken->hardwareVersion = fwToken->mdToken->GetHardwareVersion( + fwToken->mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); + } + else { + fwToken->hardwareVersion.major = 0; + fwToken->hardwareVersion.minor = 1; + } - if( (0 != fwToken->hardwareVersion.major) || - (0 != fwToken->hardwareVersion.minor) ) { rv = fwToken->hardwareVersion; - goto done; - } - if (fwToken->mdToken->GetHardwareVersion) { - fwToken->hardwareVersion = fwToken->mdToken->GetHardwareVersion( - fwToken->mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); - } else { - fwToken->hardwareVersion.major = 0; - fwToken->hardwareVersion.minor = 1; - } - - rv = fwToken->hardwareVersion; - - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return rv; +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return rv; } /* @@ -1173,44 +1110,43 @@ nssCKFWToken_GetHardwareVersion * */ NSS_IMPLEMENT CK_VERSION -nssCKFWToken_GetFirmwareVersion -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetFirmwareVersion( + NSSCKFWToken *fwToken) { - CK_VERSION rv; + CK_VERSION rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + rv.major = rv.minor = 0; + return rv; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) { - rv.major = rv.minor = 0; - return rv; - } + if (CKR_OK != nssCKFWMutex_Lock(fwToken->mutex)) { + rv.major = rv.minor = 0; + return rv; + } + + if ((0 != fwToken->firmwareVersion.major) || + (0 != fwToken->firmwareVersion.minor)) { + rv = fwToken->firmwareVersion; + goto done; + } + + if (fwToken->mdToken->GetFirmwareVersion) { + fwToken->firmwareVersion = fwToken->mdToken->GetFirmwareVersion( + fwToken->mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); + } + else { + fwToken->firmwareVersion.major = 0; + fwToken->firmwareVersion.minor = 1; + } - if( (0 != fwToken->firmwareVersion.major) || - (0 != fwToken->firmwareVersion.minor) ) { rv = fwToken->firmwareVersion; - goto done; - } - if (fwToken->mdToken->GetFirmwareVersion) { - fwToken->firmwareVersion = fwToken->mdToken->GetFirmwareVersion( - fwToken->mdToken, fwToken, fwToken->mdInstance, fwToken->fwInstance); - } else { - fwToken->firmwareVersion.major = 0; - fwToken->firmwareVersion.minor = 1; - } - - rv = fwToken->firmwareVersion; - - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return rv; +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return rv; } /* @@ -1218,86 +1154,96 @@ nssCKFWToken_GetFirmwareVersion * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_GetUTCTime -( - NSSCKFWToken *fwToken, - CK_CHAR utcTime[16] -) +nssCKFWToken_GetUTCTime( + NSSCKFWToken *fwToken, + CK_CHAR utcTime[16]) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } - if( (CK_CHAR_PTR)NULL == utcTime ) { - return CKR_ARGUMENTS_BAD; - } + if ((CK_CHAR_PTR)NULL == utcTime) { + return CKR_ARGUMENTS_BAD; + } #endif /* DEBUG */ - if( CK_TRUE != nssCKFWToken_GetHasClockOnToken(fwToken) ) { - /* return CKR_DEVICE_ERROR; */ - (void)nssUTF8_CopyIntoFixedBuffer((NSSUTF8 *)NULL, (char *)utcTime, 16, ' '); + if (CK_TRUE != nssCKFWToken_GetHasClockOnToken(fwToken)) { + /* return CKR_DEVICE_ERROR; */ + (void)nssUTF8_CopyIntoFixedBuffer((NSSUTF8 *)NULL, (char *)utcTime, 16, ' '); + return CKR_OK; + } + + if (!fwToken->mdToken->GetUTCTime) { + /* It said it had one! */ + return CKR_GENERAL_ERROR; + } + + error = fwToken->mdToken->GetUTCTime(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance, utcTime); + if (CKR_OK != error) { + return error; + } + + /* Sanity-check the data */ + { + /* Format is YYYYMMDDhhmmss00 */ + int i; + int Y, M, D, h, m, s; + static int dims[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + + for (i = 0; i < 16; i++) { + if ((utcTime[i] < '0') || (utcTime[i] > '9')) { + goto badtime; + } + } + + Y = ((utcTime[0] - '0') * 1000) + ((utcTime[1] - '0') * 100) + + ((utcTime[2] - '0') * 10) + (utcTime[3] - '0'); + M = ((utcTime[4] - '0') * 10) + (utcTime[5] - '0'); + D = ((utcTime[6] - '0') * 10) + (utcTime[7] - '0'); + h = ((utcTime[8] - '0') * 10) + (utcTime[9] - '0'); + m = ((utcTime[10] - '0') * 10) + (utcTime[11] - '0'); + s = ((utcTime[12] - '0') * 10) + (utcTime[13] - '0'); + + if ((Y < 1990) || (Y > 3000)) + goto badtime; /* Y3K problem. heh heh heh */ + if ((M < 1) || (M > 12)) + goto badtime; + if ((D < 1) || (D > 31)) + goto badtime; + + if (D > dims[M - 1]) + goto badtime; /* per-month check */ + if ((2 == M) && (((Y % 4) || !(Y % + 100)) && + (Y % 400)) && + (D > 28)) + goto badtime; /* leap years */ + + if ((h < 0) || (h > 23)) + goto badtime; + if ((m < 0) || (m > 60)) + goto badtime; + if ((s < 0) || (s > 61)) + goto badtime; + + /* 60m and 60 or 61s is only allowed for leap seconds. */ + if ((60 == m) || (s >= 60)) { + if ((23 != h) || (60 != m) || (s < 60)) + goto badtime; + /* leap seconds can only happen on June 30 or Dec 31.. I think */ + /* if( ((6 != M) || (30 != D)) && ((12 != M) || (31 != D)) ) goto badtime; */ + } + } + return CKR_OK; - } - if (!fwToken->mdToken->GetUTCTime) { - /* It said it had one! */ +badtime: return CKR_GENERAL_ERROR; - } - - error = fwToken->mdToken->GetUTCTime(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance, utcTime); - if( CKR_OK != error ) { - return error; - } - - /* Sanity-check the data */ - { - /* Format is YYYYMMDDhhmmss00 */ - int i; - int Y, M, D, h, m, s; - static int dims[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - - for( i = 0; i < 16; i++ ) { - if( (utcTime[i] < '0') || (utcTime[i] > '9') ) { - goto badtime; - } - } - - Y = ((utcTime[ 0] - '0') * 1000) + ((utcTime[1] - '0') * 100) + - ((utcTime[ 2] - '0') * 10) + (utcTime[ 3] - '0'); - M = ((utcTime[ 4] - '0') * 10) + (utcTime[ 5] - '0'); - D = ((utcTime[ 6] - '0') * 10) + (utcTime[ 7] - '0'); - h = ((utcTime[ 8] - '0') * 10) + (utcTime[ 9] - '0'); - m = ((utcTime[10] - '0') * 10) + (utcTime[11] - '0'); - s = ((utcTime[12] - '0') * 10) + (utcTime[13] - '0'); - - if( (Y < 1990) || (Y > 3000) ) goto badtime; /* Y3K problem. heh heh heh */ - if( (M < 1) || (M > 12) ) goto badtime; - if( (D < 1) || (D > 31) ) goto badtime; - - if( D > dims[M-1] ) goto badtime; /* per-month check */ - if( (2 == M) && (((Y%4)||!(Y%100))&&(Y%400)) && (D > 28) ) goto badtime; /* leap years */ - - if( (h < 0) || (h > 23) ) goto badtime; - if( (m < 0) || (m > 60) ) goto badtime; - if( (s < 0) || (s > 61) ) goto badtime; - - /* 60m and 60 or 61s is only allowed for leap seconds. */ - if( (60 == m) || (s >= 60) ) { - if( (23 != h) || (60 != m) || (s < 60) ) goto badtime; - /* leap seconds can only happen on June 30 or Dec 31.. I think */ - /* if( ((6 != M) || (30 != D)) && ((12 != M) || (31 != D)) ) goto badtime; */ - } - } - - return CKR_OK; - - badtime: - return CKR_GENERAL_ERROR; } /* @@ -1305,108 +1251,107 @@ nssCKFWToken_GetUTCTime * */ NSS_IMPLEMENT NSSCKFWSession * -nssCKFWToken_OpenSession -( - NSSCKFWToken *fwToken, - CK_BBOOL rw, - CK_VOID_PTR pApplication, - CK_NOTIFY Notify, - CK_RV *pError -) +nssCKFWToken_OpenSession( + NSSCKFWToken *fwToken, + CK_BBOOL rw, + CK_VOID_PTR pApplication, + CK_NOTIFY Notify, + CK_RV *pError) { - NSSCKFWSession *fwSession = (NSSCKFWSession *)NULL; - NSSCKMDSession *mdSession; + NSSCKFWSession *fwSession = (NSSCKFWSession *)NULL; + NSSCKMDSession *mdSession; #ifdef NSSDEBUG - if (!pError) { - return (NSSCKFWSession *)NULL; - } + if (!pError) { + return (NSSCKFWSession *)NULL; + } - *pError = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != *pError ) { - return (NSSCKFWSession *)NULL; - } + *pError = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != *pError) { + return (NSSCKFWSession *)NULL; + } - switch( rw ) { - case CK_TRUE: - case CK_FALSE: - break; - default: - *pError = CKR_ARGUMENTS_BAD; - return (NSSCKFWSession *)NULL; - } + switch (rw) { + case CK_TRUE: + case CK_FALSE: + break; + default: + *pError = CKR_ARGUMENTS_BAD; + return (NSSCKFWSession *)NULL; + } #endif /* NSSDEBUG */ - *pError = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != *pError ) { - return (NSSCKFWSession *)NULL; - } - - if( CK_TRUE == rw ) { - /* Read-write session desired */ - if( CK_TRUE == nssCKFWToken_GetIsWriteProtected(fwToken) ) { - *pError = CKR_TOKEN_WRITE_PROTECTED; - goto done; + *pError = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != *pError) { + return (NSSCKFWSession *)NULL; } - } else { - /* Read-only session desired */ - if( CKS_RW_SO_FUNCTIONS == nssCKFWToken_GetSessionState(fwToken) ) { - *pError = CKR_SESSION_READ_WRITE_SO_EXISTS; - goto done; + + if (CK_TRUE == rw) { + /* Read-write session desired */ + if (CK_TRUE == nssCKFWToken_GetIsWriteProtected(fwToken)) { + *pError = CKR_TOKEN_WRITE_PROTECTED; + goto done; + } } - } - - /* We could compare sesion counts to any limits we know of, I guess.. */ - - if (!fwToken->mdToken->OpenSession) { - /* - * I'm not sure that the Module actually needs to implement - * mdSessions -- the Framework can keep track of everything - * needed, really. But I'll sort out that detail later.. - */ - *pError = CKR_GENERAL_ERROR; - goto done; - } - - fwSession = nssCKFWSession_Create(fwToken, rw, pApplication, Notify, pError); - if (!fwSession) { - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + else { + /* Read-only session desired */ + if (CKS_RW_SO_FUNCTIONS == nssCKFWToken_GetSessionState(fwToken)) { + *pError = CKR_SESSION_READ_WRITE_SO_EXISTS; + goto done; + } } - goto done; - } - mdSession = fwToken->mdToken->OpenSession(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance, fwSession, - rw, pError); - if (!mdSession) { - (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); - if( CKR_OK == *pError ) { - *pError = CKR_GENERAL_ERROR; + /* We could compare sesion counts to any limits we know of, I guess.. */ + + if (!fwToken->mdToken->OpenSession) { + /* + * I'm not sure that the Module actually needs to implement + * mdSessions -- the Framework can keep track of everything + * needed, really. But I'll sort out that detail later.. + */ + *pError = CKR_GENERAL_ERROR; + goto done; } - goto done; - } - *pError = nssCKFWSession_SetMDSession(fwSession, mdSession); - if( CKR_OK != *pError ) { - if (mdSession->Close) { - mdSession->Close(mdSession, fwSession, fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + fwSession = nssCKFWSession_Create(fwToken, rw, pApplication, Notify, pError); + if (!fwSession) { + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto done; } - (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); - goto done; - } - *pError = nssCKFWHash_Add(fwToken->sessions, fwSession, fwSession); - if( CKR_OK != *pError ) { - (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); - fwSession = (NSSCKFWSession *)NULL; - goto done; - } + mdSession = fwToken->mdToken->OpenSession(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance, fwSession, + rw, pError); + if (!mdSession) { + (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); + if (CKR_OK == *pError) { + *pError = CKR_GENERAL_ERROR; + } + goto done; + } - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return fwSession; + *pError = nssCKFWSession_SetMDSession(fwSession, mdSession); + if (CKR_OK != *pError) { + if (mdSession->Close) { + mdSession->Close(mdSession, fwSession, fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); + } + (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); + goto done; + } + + *pError = nssCKFWHash_Add(fwToken->sessions, fwSession, fwSession); + if (CKR_OK != *pError) { + (void)nssCKFWSession_Destroy(fwSession, CK_FALSE); + fwSession = (NSSCKFWSession *)NULL; + goto done; + } + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return fwSession; } /* @@ -1414,23 +1359,21 @@ nssCKFWToken_OpenSession * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetMechanismCount -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMechanismCount( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return 0; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return 0; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetMechanismCount) { - return 0; - } + if (!fwToken->mdToken->GetMechanismCount) { + return 0; + } - return fwToken->mdToken->GetMechanismCount(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + return fwToken->mdToken->GetMechanismCount(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } /* @@ -1438,110 +1381,103 @@ nssCKFWToken_GetMechanismCount * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_GetMechanismTypes -( - NSSCKFWToken *fwToken, - CK_MECHANISM_TYPE types[] -) +nssCKFWToken_GetMechanismTypes( + NSSCKFWToken *fwToken, + CK_MECHANISM_TYPE types[]) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CKR_ARGUMENTS_BAD; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CKR_ARGUMENTS_BAD; + } - if (!types) { - return CKR_ARGUMENTS_BAD; - } + if (!types) { + return CKR_ARGUMENTS_BAD; + } #endif /* NSSDEBUG */ - if (!fwToken->mdToken->GetMechanismTypes) { - /* - * This should only be called with a sufficiently-large - * "types" array, which can only be done if GetMechanismCount - * is implemented. If that's implemented (and returns nonzero), - * then this should be too. So return an error. - */ - return CKR_GENERAL_ERROR; - } + if (!fwToken->mdToken->GetMechanismTypes) { + /* + * This should only be called with a sufficiently-large + * "types" array, which can only be done if GetMechanismCount + * is implemented. If that's implemented (and returns nonzero), + * then this should be too. So return an error. + */ + return CKR_GENERAL_ERROR; + } - return fwToken->mdToken->GetMechanismTypes(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance, types); + return fwToken->mdToken->GetMechanismTypes(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance, types); } - /* * nssCKFWToken_GetMechanism * */ NSS_IMPLEMENT NSSCKFWMechanism * -nssCKFWToken_GetMechanism -( - NSSCKFWToken *fwToken, - CK_MECHANISM_TYPE which, - CK_RV *pError -) +nssCKFWToken_GetMechanism( + NSSCKFWToken *fwToken, + CK_MECHANISM_TYPE which, + CK_RV *pError) { - NSSCKMDMechanism *mdMechanism; - if (!fwToken->mdMechanismHash) { - *pError = CKR_GENERAL_ERROR; - return (NSSCKFWMechanism *)NULL; - } - - if (!fwToken->mdToken->GetMechanism) { - /* - * If we don't implement any GetMechanism function, then we must - * not support any. - */ - *pError = CKR_MECHANISM_INVALID; - return (NSSCKFWMechanism *)NULL; - } + NSSCKMDMechanism *mdMechanism; + if (!fwToken->mdMechanismHash) { + *pError = CKR_GENERAL_ERROR; + return (NSSCKFWMechanism *)NULL; + } - /* lookup in hash table */ - mdMechanism = fwToken->mdToken->GetMechanism(fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance, which, pError); - if (!mdMechanism) { - return (NSSCKFWMechanism *) NULL; - } - /* store in hash table */ - return nssCKFWMechanism_Create(mdMechanism, fwToken->mdToken, fwToken, - fwToken->mdInstance, fwToken->fwInstance); + if (!fwToken->mdToken->GetMechanism) { + /* + * If we don't implement any GetMechanism function, then we must + * not support any. + */ + *pError = CKR_MECHANISM_INVALID; + return (NSSCKFWMechanism *)NULL; + } + + /* lookup in hash table */ + mdMechanism = fwToken->mdToken->GetMechanism(fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance, which, pError); + if (!mdMechanism) { + return (NSSCKFWMechanism *)NULL; + } + /* store in hash table */ + return nssCKFWMechanism_Create(mdMechanism, fwToken->mdToken, fwToken, + fwToken->mdInstance, fwToken->fwInstance); } NSS_IMPLEMENT CK_RV -nssCKFWToken_SetSessionState -( - NSSCKFWToken *fwToken, - CK_STATE newState -) +nssCKFWToken_SetSessionState( + NSSCKFWToken *fwToken, + CK_STATE newState) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } - switch( newState ) { - case CKS_RO_PUBLIC_SESSION: - case CKS_RO_USER_FUNCTIONS: - case CKS_RW_PUBLIC_SESSION: - case CKS_RW_USER_FUNCTIONS: - case CKS_RW_SO_FUNCTIONS: - break; - default: - return CKR_ARGUMENTS_BAD; - } + switch (newState) { + case CKS_RO_PUBLIC_SESSION: + case CKS_RO_USER_FUNCTIONS: + case CKS_RW_PUBLIC_SESSION: + case CKS_RW_USER_FUNCTIONS: + case CKS_RW_SO_FUNCTIONS: + break; + default: + return CKR_ARGUMENTS_BAD; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; + } - fwToken->state = newState; - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return CKR_OK; + fwToken->state = newState; + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return CKR_OK; } /* @@ -1549,101 +1485,96 @@ nssCKFWToken_SetSessionState * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_RemoveSession -( - NSSCKFWToken *fwToken, - NSSCKFWSession *fwSession -) +nssCKFWToken_RemoveSession( + NSSCKFWToken *fwToken, + NSSCKFWSession *fwSession) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } - error = nssCKFWSession_verifyPointer(fwSession); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWSession_verifyPointer(fwSession); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; + } + + if (CK_TRUE != nssCKFWHash_Exists(fwToken->sessions, fwSession)) { + error = CKR_SESSION_HANDLE_INVALID; + goto done; + } + + nssCKFWHash_Remove(fwToken->sessions, fwSession); + fwToken->sessionCount--; + + if (nssCKFWSession_IsRWSession(fwSession)) { + fwToken->rwSessionCount--; + } + + if (0 == fwToken->sessionCount) { + fwToken->rwSessionCount = 0; /* sanity */ + fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */ + } + + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); return error; - } - - if( CK_TRUE != nssCKFWHash_Exists(fwToken->sessions, fwSession) ) { - error = CKR_SESSION_HANDLE_INVALID; - goto done; - } - - nssCKFWHash_Remove(fwToken->sessions, fwSession); - fwToken->sessionCount--; - - if( nssCKFWSession_IsRWSession(fwSession) ) { - fwToken->rwSessionCount--; - } - - if( 0 == fwToken->sessionCount ) { - fwToken->rwSessionCount = 0; /* sanity */ - fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */ - } - - error = CKR_OK; - - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return error; } - /* * nssCKFWToken_CloseAllSessions * */ NSS_IMPLEMENT CK_RV -nssCKFWToken_CloseAllSessions -( - NSSCKFWToken *fwToken -) +nssCKFWToken_CloseAllSessions( + NSSCKFWToken *fwToken) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; #ifdef NSSDEBUG - error = nssCKFWToken_verifyPointer(fwToken); - if( CKR_OK != error ) { - return error; - } + error = nssCKFWToken_verifyPointer(fwToken); + if (CKR_OK != error) { + return error; + } #endif /* NSSDEBUG */ - error = nssCKFWMutex_Lock(fwToken->mutex); - if( CKR_OK != error ) { - return error; - } - - nssCKFWHash_Iterate(fwToken->sessions, nss_ckfwtoken_session_iterator, (void *)NULL); - - nssCKFWHash_Destroy(fwToken->sessions); - - fwToken->sessions = nssCKFWHash_Create(fwToken->fwInstance, fwToken->arena, &error); - if (!fwToken->sessions) { - if( CKR_OK == error ) { - error = CKR_GENERAL_ERROR; + error = nssCKFWMutex_Lock(fwToken->mutex); + if (CKR_OK != error) { + return error; } - goto done; - } - fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */ - fwToken->sessionCount = 0; - fwToken->rwSessionCount = 0; + nssCKFWHash_Iterate(fwToken->sessions, nss_ckfwtoken_session_iterator, (void *)NULL); - error = CKR_OK; + nssCKFWHash_Destroy(fwToken->sessions); - done: - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return error; + fwToken->sessions = nssCKFWHash_Create(fwToken->fwInstance, fwToken->arena, &error); + if (!fwToken->sessions) { + if (CKR_OK == error) { + error = CKR_GENERAL_ERROR; + } + goto done; + } + + fwToken->state = CKS_RO_PUBLIC_SESSION; /* some default */ + fwToken->sessionCount = 0; + fwToken->rwSessionCount = 0; + + error = CKR_OK; + +done: + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return error; } /* @@ -1651,26 +1582,24 @@ nssCKFWToken_CloseAllSessions * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetSessionCount -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetSessionCount( + NSSCKFWToken *fwToken) { - CK_ULONG rv; + CK_ULONG rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWMutex_Lock(fwToken->mutex)) { + return (CK_ULONG)0; + } - rv = fwToken->sessionCount; - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return rv; + rv = fwToken->sessionCount; + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return rv; } /* @@ -1678,26 +1607,24 @@ nssCKFWToken_GetSessionCount * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetRwSessionCount -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetRwSessionCount( + NSSCKFWToken *fwToken) { - CK_ULONG rv; + CK_ULONG rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWMutex_Lock(fwToken->mutex)) { + return (CK_ULONG)0; + } - rv = fwToken->rwSessionCount; - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return rv; + rv = fwToken->rwSessionCount; + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return rv; } /* @@ -1705,26 +1632,24 @@ nssCKFWToken_GetRwSessionCount * */ NSS_IMPLEMENT CK_ULONG -nssCKFWToken_GetRoSessionCount -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetRoSessionCount( + NSSCKFWToken *fwToken) { - CK_ULONG rv; + CK_ULONG rv; #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (CK_ULONG)0; + } #endif /* NSSDEBUG */ - if( CKR_OK != nssCKFWMutex_Lock(fwToken->mutex) ) { - return (CK_ULONG)0; - } + if (CKR_OK != nssCKFWMutex_Lock(fwToken->mutex)) { + return (CK_ULONG)0; + } - rv = fwToken->sessionCount - fwToken->rwSessionCount; - (void)nssCKFWMutex_Unlock(fwToken->mutex); - return rv; + rv = fwToken->sessionCount - fwToken->rwSessionCount; + (void)nssCKFWMutex_Unlock(fwToken->mutex); + return rv; } /* @@ -1732,18 +1657,16 @@ nssCKFWToken_GetRoSessionCount * */ NSS_IMPLEMENT nssCKFWHash * -nssCKFWToken_GetSessionObjectHash -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetSessionObjectHash( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (nssCKFWHash *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (nssCKFWHash *)NULL; + } #endif /* NSSDEBUG */ - return fwToken->sessionObjectHash; + return fwToken->sessionObjectHash; } /* @@ -1751,18 +1674,16 @@ nssCKFWToken_GetSessionObjectHash * */ NSS_IMPLEMENT nssCKFWHash * -nssCKFWToken_GetMDObjectHash -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetMDObjectHash( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (nssCKFWHash *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (nssCKFWHash *)NULL; + } #endif /* NSSDEBUG */ - return fwToken->mdObjectHash; + return fwToken->mdObjectHash; } /* @@ -1770,18 +1691,16 @@ nssCKFWToken_GetMDObjectHash * */ NSS_IMPLEMENT nssCKFWHash * -nssCKFWToken_GetObjectHandleHash -( - NSSCKFWToken *fwToken -) +nssCKFWToken_GetObjectHandleHash( + NSSCKFWToken *fwToken) { #ifdef NSSDEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (nssCKFWHash *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (nssCKFWHash *)NULL; + } #endif /* NSSDEBUG */ - return fwToken->mdObjectHash; + return fwToken->mdObjectHash; } /* @@ -1790,18 +1709,16 @@ nssCKFWToken_GetObjectHandleHash */ NSS_IMPLEMENT NSSCKMDToken * -NSSCKFWToken_GetMDToken -( - NSSCKFWToken *fwToken -) +NSSCKFWToken_GetMDToken( + NSSCKFWToken *fwToken) { #ifdef DEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (NSSCKMDToken *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (NSSCKMDToken *)NULL; + } #endif /* DEBUG */ - return nssCKFWToken_GetMDToken(fwToken); + return nssCKFWToken_GetMDToken(fwToken); } /* @@ -1810,24 +1727,22 @@ NSSCKFWToken_GetMDToken */ NSS_IMPLEMENT NSSArena * -NSSCKFWToken_GetArena -( - NSSCKFWToken *fwToken, - CK_RV *pError -) +NSSCKFWToken_GetArena( + NSSCKFWToken *fwToken, + CK_RV *pError) { #ifdef DEBUG - if (!pError) { - return (NSSArena *)NULL; - } + if (!pError) { + return (NSSArena *)NULL; + } - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - *pError = CKR_ARGUMENTS_BAD; - return (NSSArena *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + *pError = CKR_ARGUMENTS_BAD; + return (NSSArena *)NULL; + } #endif /* DEBUG */ - return nssCKFWToken_GetArena(fwToken, pError); + return nssCKFWToken_GetArena(fwToken, pError); } /* @@ -1836,18 +1751,16 @@ NSSCKFWToken_GetArena */ NSS_IMPLEMENT NSSCKFWSlot * -NSSCKFWToken_GetFWSlot -( - NSSCKFWToken *fwToken -) +NSSCKFWToken_GetFWSlot( + NSSCKFWToken *fwToken) { #ifdef DEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (NSSCKFWSlot *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (NSSCKFWSlot *)NULL; + } #endif /* DEBUG */ - return nssCKFWToken_GetFWSlot(fwToken); + return nssCKFWToken_GetFWSlot(fwToken); } /* @@ -1856,18 +1769,16 @@ NSSCKFWToken_GetFWSlot */ NSS_IMPLEMENT NSSCKMDSlot * -NSSCKFWToken_GetMDSlot -( - NSSCKFWToken *fwToken -) +NSSCKFWToken_GetMDSlot( + NSSCKFWToken *fwToken) { #ifdef DEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return (NSSCKMDSlot *)NULL; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return (NSSCKMDSlot *)NULL; + } #endif /* DEBUG */ - return nssCKFWToken_GetMDSlot(fwToken); + return nssCKFWToken_GetMDSlot(fwToken); } /* @@ -1876,16 +1787,14 @@ NSSCKFWToken_GetMDSlot */ NSS_IMPLEMENT CK_STATE -NSSCKFWSession_GetSessionState -( - NSSCKFWToken *fwToken -) +NSSCKFWSession_GetSessionState( + NSSCKFWToken *fwToken) { #ifdef DEBUG - if( CKR_OK != nssCKFWToken_verifyPointer(fwToken) ) { - return CKS_RO_PUBLIC_SESSION; - } + if (CKR_OK != nssCKFWToken_verifyPointer(fwToken)) { + return CKS_RO_PUBLIC_SESSION; + } #endif /* DEBUG */ - return nssCKFWToken_GetSessionState(fwToken); + return nssCKFWToken_GetSessionState(fwToken); } diff --git a/security/nss/lib/ckfw/wrap.c b/security/nss/lib/ckfw/wrap.c index 3a0b0df21ff1..7a8d42f8e9f0 100644 --- a/security/nss/lib/ckfw/wrap.c +++ b/security/nss/lib/ckfw/wrap.c @@ -92,41 +92,46 @@ /* figure out out locking semantics */ static CK_RV nssCKFW_GetThreadSafeState(CK_C_INITIALIZE_ARGS_PTR pInitArgs, - CryptokiLockingState *pLocking_state) { - int functionCount = 0; + CryptokiLockingState *pLocking_state) +{ + int functionCount = 0; - /* parsed according to (PKCS #11 Section 11.4) */ - /* no args, the degenerate version of case 1 */ - if (!pInitArgs) { - *pLocking_state = SingleThreaded; - return CKR_OK; - } + /* parsed according to (PKCS #11 Section 11.4) */ + /* no args, the degenerate version of case 1 */ + if (!pInitArgs) { + *pLocking_state = SingleThreaded; + return CKR_OK; + } - /* CKF_OS_LOCKING_OK set, Cases 2 and 4 */ - if (pInitArgs->flags & CKF_OS_LOCKING_OK) { - *pLocking_state = MultiThreaded; - return CKR_OK; - } - if ((CK_CREATEMUTEX) NULL != pInitArgs->CreateMutex) functionCount++; - if ((CK_DESTROYMUTEX) NULL != pInitArgs->DestroyMutex) functionCount++; - if ((CK_LOCKMUTEX) NULL != pInitArgs->LockMutex) functionCount++; - if ((CK_UNLOCKMUTEX) NULL != pInitArgs->UnlockMutex) functionCount++; + /* CKF_OS_LOCKING_OK set, Cases 2 and 4 */ + if (pInitArgs->flags & CKF_OS_LOCKING_OK) { + *pLocking_state = MultiThreaded; + return CKR_OK; + } + if ((CK_CREATEMUTEX)NULL != pInitArgs->CreateMutex) + functionCount++; + if ((CK_DESTROYMUTEX)NULL != pInitArgs->DestroyMutex) + functionCount++; + if ((CK_LOCKMUTEX)NULL != pInitArgs->LockMutex) + functionCount++; + if ((CK_UNLOCKMUTEX)NULL != pInitArgs->UnlockMutex) + functionCount++; - /* CKF_OS_LOCKING_OK is not set, and not functions supplied, - * explicit case 1 */ - if (0 == functionCount) { - *pLocking_state = SingleThreaded; - return CKR_OK; - } + /* CKF_OS_LOCKING_OK is not set, and not functions supplied, + * explicit case 1 */ + if (0 == functionCount) { + *pLocking_state = SingleThreaded; + return CKR_OK; + } - /* OS_LOCKING_OK is not set and functions have been supplied. Since - * ckfw uses nssbase library which explicitly calls NSPR, and since - * there is no way to reliably override these explicit calls to NSPR, - * therefore we can't support applications which have their own threading - * module. Return CKR_CANT_LOCK if they supplied the correct number of - * arguments, or CKR_ARGUMENTS_BAD if they did not in either case we will - * fail the initialize */ - return (4 == functionCount) ? CKR_CANT_LOCK : CKR_ARGUMENTS_BAD; + /* OS_LOCKING_OK is not set and functions have been supplied. Since + * ckfw uses nssbase library which explicitly calls NSPR, and since + * there is no way to reliably override these explicit calls to NSPR, + * therefore we can't support applications which have their own threading + * module. Return CKR_CANT_LOCK if they supplied the correct number of + * arguments, or CKR_ARGUMENTS_BAD if they did not in either case we will + * fail the initialize */ + return (4 == functionCount) ? CKR_CANT_LOCK : CKR_ARGUMENTS_BAD; } static PRInt32 liveInstances; @@ -136,60 +141,58 @@ static PRInt32 liveInstances; * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Initialize -( - NSSCKFWInstance **pFwInstance, - NSSCKMDInstance *mdInstance, - CK_VOID_PTR pInitArgs -) +NSSCKFWC_Initialize( + NSSCKFWInstance **pFwInstance, + NSSCKMDInstance *mdInstance, + CK_VOID_PTR pInitArgs) { - CK_RV error = CKR_OK; - CryptokiLockingState locking_state; + CK_RV error = CKR_OK; + CryptokiLockingState locking_state; - if( (NSSCKFWInstance **)NULL == pFwInstance ) { - error = CKR_GENERAL_ERROR; - goto loser; - } + if ((NSSCKFWInstance **)NULL == pFwInstance) { + error = CKR_GENERAL_ERROR; + goto loser; + } - if (*pFwInstance) { - error = CKR_CRYPTOKI_ALREADY_INITIALIZED; - goto loser; - } + if (*pFwInstance) { + error = CKR_CRYPTOKI_ALREADY_INITIALIZED; + goto loser; + } - if (!mdInstance) { - error = CKR_GENERAL_ERROR; - goto loser; - } + if (!mdInstance) { + error = CKR_GENERAL_ERROR; + goto loser; + } - error = nssCKFW_GetThreadSafeState(pInitArgs,&locking_state); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFW_GetThreadSafeState(pInitArgs, &locking_state); + if (CKR_OK != error) { + goto loser; + } - *pFwInstance = nssCKFWInstance_Create(pInitArgs, locking_state, mdInstance, &error); - if (!*pFwInstance) { - goto loser; - } - PR_ATOMIC_INCREMENT(&liveInstances); - return CKR_OK; + *pFwInstance = nssCKFWInstance_Create(pInitArgs, locking_state, mdInstance, &error); + if (!*pFwInstance) { + goto loser; + } + PR_ATOMIC_INCREMENT(&liveInstances); + return CKR_OK; - loser: - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CANT_LOCK: - case CKR_CRYPTOKI_ALREADY_INITIALIZED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_NEED_TO_CREATE_THREADS: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CANT_LOCK: + case CKR_CRYPTOKI_ALREADY_INITIALIZED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_NEED_TO_CREATE_THREADS: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -197,59 +200,57 @@ NSSCKFWC_Initialize * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Finalize -( - NSSCKFWInstance **pFwInstance -) +NSSCKFWC_Finalize( + NSSCKFWInstance **pFwInstance) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; - if( (NSSCKFWInstance **)NULL == pFwInstance ) { - error = CKR_GENERAL_ERROR; - goto loser; - } - - if (!*pFwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - error = nssCKFWInstance_Destroy(*pFwInstance); - - /* In any case */ - *pFwInstance = (NSSCKFWInstance *)NULL; - - loser: - switch( error ) { - PRInt32 remainingInstances; - case CKR_OK: - remainingInstances = PR_ATOMIC_DECREMENT(&liveInstances); - if (!remainingInstances) { - nssArena_Shutdown(); + if ((NSSCKFWInstance **)NULL == pFwInstance) { + error = CKR_GENERAL_ERROR; + goto loser; } - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - break; - default: - error = CKR_GENERAL_ERROR; - break; - } - /* - * A thread's error stack is automatically destroyed when the thread - * terminates or, for the primordial thread, by PR_Cleanup. On - * Windows with MinGW, the thread private data destructor PR_Free - * registered by this module is actually a thunk for PR_Free defined - * in this module. When the thread that unloads this module terminates - * or calls PR_Cleanup, the thunk for PR_Free is already gone with the - * module. Therefore we need to destroy the error stack before the - * module is unloaded. - */ - nss_DestroyErrorStack(); - return error; + if (!*pFwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } + + error = nssCKFWInstance_Destroy(*pFwInstance); + + /* In any case */ + *pFwInstance = (NSSCKFWInstance *)NULL; + +loser: + switch (error) { + PRInt32 remainingInstances; + case CKR_OK: + remainingInstances = PR_ATOMIC_DECREMENT(&liveInstances); + if (!remainingInstances) { + nssArena_Shutdown(); + } + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + break; + default: + error = CKR_GENERAL_ERROR; + break; + } + + /* + * A thread's error stack is automatically destroyed when the thread + * terminates or, for the primordial thread, by PR_Cleanup. On + * Windows with MinGW, the thread private data destructor PR_Free + * registered by this module is actually a thunk for PR_Free defined + * in this module. When the thread that unloads this module terminates + * or calls PR_Cleanup, the thunk for PR_Free is already gone with the + * module. Therefore we need to destroy the error stack before the + * module is unloaded. + */ + nss_DestroyErrorStack(); + return error; } /* @@ -257,57 +258,55 @@ NSSCKFWC_Finalize * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetInfo -( - NSSCKFWInstance *fwInstance, - CK_INFO_PTR pInfo -) +NSSCKFWC_GetInfo( + NSSCKFWInstance *fwInstance, + CK_INFO_PTR pInfo) { - CK_RV error = CKR_OK; + CK_RV error = CKR_OK; - if( (CK_INFO_PTR)CK_NULL_PTR == pInfo ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_INFO_PTR)CK_NULL_PTR == pInfo) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* - * A purify error here means a caller error - */ - (void)nsslibc_memset(pInfo, 0, sizeof(CK_INFO)); + /* + * A purify error here means a caller error + */ + (void)nsslibc_memset(pInfo, 0, sizeof(CK_INFO)); - pInfo->cryptokiVersion = nssCKFWInstance_GetCryptokiVersion(fwInstance); + pInfo->cryptokiVersion = nssCKFWInstance_GetCryptokiVersion(fwInstance); - error = nssCKFWInstance_GetManufacturerID(fwInstance, pInfo->manufacturerID); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWInstance_GetManufacturerID(fwInstance, pInfo->manufacturerID); + if (CKR_OK != error) { + goto loser; + } - pInfo->flags = nssCKFWInstance_GetFlags(fwInstance); + pInfo->flags = nssCKFWInstance_GetFlags(fwInstance); - error = nssCKFWInstance_GetLibraryDescription(fwInstance, pInfo->libraryDescription); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWInstance_GetLibraryDescription(fwInstance, pInfo->libraryDescription); + if (CKR_OK != error) { + goto loser; + } - pInfo->libraryVersion = nssCKFWInstance_GetLibraryVersion(fwInstance); + pInfo->libraryVersion = nssCKFWInstance_GetLibraryVersion(fwInstance); - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - break; - default: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + break; + default: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } - + /* * C_GetFunctionList is implemented entirely in the Module's file which * includes the Framework API insert file. It requires no "actual" @@ -319,179 +318,176 @@ NSSCKFWC_GetInfo * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetSlotList -( - NSSCKFWInstance *fwInstance, - CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, - CK_ULONG_PTR pulCount -) +NSSCKFWC_GetSlotList( + NSSCKFWInstance *fwInstance, + CK_BBOOL tokenPresent, + CK_SLOT_ID_PTR pSlotList, + CK_ULONG_PTR pulCount) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; + CK_RV error = CKR_OK; + CK_ULONG nSlots; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - switch( tokenPresent ) { - case CK_TRUE: - case CK_FALSE: - break; - default: - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - if( (CK_ULONG_PTR)CK_NULL_PTR == pulCount ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } - - if( (CK_SLOT_ID_PTR)CK_NULL_PTR == pSlotList ) { - *pulCount = nSlots; - return CKR_OK; - } - - /* - * A purify error here indicates caller error. - */ - (void)nsslibc_memset(pSlotList, 0, *pulCount * sizeof(CK_SLOT_ID)); - - if( *pulCount < nSlots ) { - *pulCount = nSlots; - error = CKR_BUFFER_TOO_SMALL; - goto loser; - } else { - CK_ULONG i; - *pulCount = nSlots; - - /* - * Our secret "mapping": CK_SLOT_IDs are integers [1,N], and we - * just index one when we need it. - */ - - for( i = 0; i < nSlots; i++ ) { - pSlotList[i] = i+1; + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; } - return CKR_OK; - } + switch (tokenPresent) { + case CK_TRUE: + case CK_FALSE: + break; + default: + error = CKR_ARGUMENTS_BAD; + goto loser; + } - loser: - switch( error ) { - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + if ((CK_ULONG_PTR)CK_NULL_PTR == pulCount) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - return error; + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } + + if ((CK_SLOT_ID_PTR)CK_NULL_PTR == pSlotList) { + *pulCount = nSlots; + return CKR_OK; + } + + /* + * A purify error here indicates caller error. + */ + (void)nsslibc_memset(pSlotList, 0, *pulCount * sizeof(CK_SLOT_ID)); + + if (*pulCount < nSlots) { + *pulCount = nSlots; + error = CKR_BUFFER_TOO_SMALL; + goto loser; + } + else { + CK_ULONG i; + *pulCount = nSlots; + + /* + * Our secret "mapping": CK_SLOT_IDs are integers [1,N], and we + * just index one when we need it. + */ + + for (i = 0; i < nSlots; i++) { + pSlotList[i] = i + 1; + } + + return CKR_OK; + } + +loser: + switch (error) { + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } - + /* * NSSCKFWC_GetSlotInfo * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetSlotInfo -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_SLOT_INFO_PTR pInfo -) +NSSCKFWC_GetSlotInfo( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_SLOT_INFO_PTR pInfo) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } - if( (slotID < 1) || (slotID > nSlots) ) { - error = CKR_SLOT_ID_INVALID; - goto loser; - } + if ((slotID < 1) || (slotID > nSlots)) { + error = CKR_SLOT_ID_INVALID; + goto loser; + } - if( (CK_SLOT_INFO_PTR)CK_NULL_PTR == pInfo ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_SLOT_INFO_PTR)CK_NULL_PTR == pInfo) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - (void)nsslibc_memset(pInfo, 0, sizeof(CK_SLOT_INFO)); + /* + * A purify error here indicates caller error. + */ + (void)nsslibc_memset(pInfo, 0, sizeof(CK_SLOT_INFO)); - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } - fwSlot = slots[ slotID-1 ]; + fwSlot = slots[slotID - 1]; - error = nssCKFWSlot_GetSlotDescription(fwSlot, pInfo->slotDescription); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWSlot_GetSlotDescription(fwSlot, pInfo->slotDescription); + if (CKR_OK != error) { + goto loser; + } - error = nssCKFWSlot_GetManufacturerID(fwSlot, pInfo->manufacturerID); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWSlot_GetManufacturerID(fwSlot, pInfo->manufacturerID); + if (CKR_OK != error) { + goto loser; + } - if( nssCKFWSlot_GetTokenPresent(fwSlot) ) { - pInfo->flags |= CKF_TOKEN_PRESENT; - } + if (nssCKFWSlot_GetTokenPresent(fwSlot)) { + pInfo->flags |= CKF_TOKEN_PRESENT; + } - if( nssCKFWSlot_GetRemovableDevice(fwSlot) ) { - pInfo->flags |= CKF_REMOVABLE_DEVICE; - } + if (nssCKFWSlot_GetRemovableDevice(fwSlot)) { + pInfo->flags |= CKF_REMOVABLE_DEVICE; + } - if( nssCKFWSlot_GetHardwareSlot(fwSlot) ) { - pInfo->flags |= CKF_HW_SLOT; - } + if (nssCKFWSlot_GetHardwareSlot(fwSlot)) { + pInfo->flags |= CKF_HW_SLOT; + } - pInfo->hardwareVersion = nssCKFWSlot_GetHardwareVersion(fwSlot); - pInfo->firmwareVersion = nssCKFWSlot_GetFirmwareVersion(fwSlot); + pInfo->hardwareVersion = nssCKFWSlot_GetHardwareVersion(fwSlot); + pInfo->firmwareVersion = nssCKFWSlot_GetFirmwareVersion(fwSlot); - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SLOT_ID_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - } +loser: + switch (error) { + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SLOT_ID_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + } - return error; + return error; } /* @@ -499,156 +495,154 @@ NSSCKFWC_GetSlotInfo * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetTokenInfo -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_TOKEN_INFO_PTR pInfo -) +NSSCKFWC_GetTokenInfo( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_TOKEN_INFO_PTR pInfo) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } - if( (slotID < 1) || (slotID > nSlots) ) { - error = CKR_SLOT_ID_INVALID; - goto loser; - } + if ((slotID < 1) || (slotID > nSlots)) { + error = CKR_SLOT_ID_INVALID; + goto loser; + } - if( (CK_TOKEN_INFO_PTR)CK_NULL_PTR == pInfo ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_TOKEN_INFO_PTR)CK_NULL_PTR == pInfo) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - (void)nsslibc_memset(pInfo, 0, sizeof(CK_TOKEN_INFO)); + /* + * A purify error here indicates caller error. + */ + (void)nsslibc_memset(pInfo, 0, sizeof(CK_TOKEN_INFO)); - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } - fwSlot = slots[ slotID-1 ]; + fwSlot = slots[slotID - 1]; - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWToken_GetLabel(fwToken, pInfo->label); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWToken_GetLabel(fwToken, pInfo->label); + if (CKR_OK != error) { + goto loser; + } - error = nssCKFWToken_GetManufacturerID(fwToken, pInfo->manufacturerID); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWToken_GetManufacturerID(fwToken, pInfo->manufacturerID); + if (CKR_OK != error) { + goto loser; + } - error = nssCKFWToken_GetModel(fwToken, pInfo->model); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWToken_GetModel(fwToken, pInfo->model); + if (CKR_OK != error) { + goto loser; + } - error = nssCKFWToken_GetSerialNumber(fwToken, pInfo->serialNumber); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWToken_GetSerialNumber(fwToken, pInfo->serialNumber); + if (CKR_OK != error) { + goto loser; + } - if( nssCKFWToken_GetHasRNG(fwToken) ) { - pInfo->flags |= CKF_RNG; - } + if (nssCKFWToken_GetHasRNG(fwToken)) { + pInfo->flags |= CKF_RNG; + } - if( nssCKFWToken_GetIsWriteProtected(fwToken) ) { - pInfo->flags |= CKF_WRITE_PROTECTED; - } + if (nssCKFWToken_GetIsWriteProtected(fwToken)) { + pInfo->flags |= CKF_WRITE_PROTECTED; + } - if( nssCKFWToken_GetLoginRequired(fwToken) ) { - pInfo->flags |= CKF_LOGIN_REQUIRED; - } + if (nssCKFWToken_GetLoginRequired(fwToken)) { + pInfo->flags |= CKF_LOGIN_REQUIRED; + } - if( nssCKFWToken_GetUserPinInitialized(fwToken) ) { - pInfo->flags |= CKF_USER_PIN_INITIALIZED; - } + if (nssCKFWToken_GetUserPinInitialized(fwToken)) { + pInfo->flags |= CKF_USER_PIN_INITIALIZED; + } - if( nssCKFWToken_GetRestoreKeyNotNeeded(fwToken) ) { - pInfo->flags |= CKF_RESTORE_KEY_NOT_NEEDED; - } + if (nssCKFWToken_GetRestoreKeyNotNeeded(fwToken)) { + pInfo->flags |= CKF_RESTORE_KEY_NOT_NEEDED; + } - if( nssCKFWToken_GetHasClockOnToken(fwToken) ) { - pInfo->flags |= CKF_CLOCK_ON_TOKEN; - } + if (nssCKFWToken_GetHasClockOnToken(fwToken)) { + pInfo->flags |= CKF_CLOCK_ON_TOKEN; + } - if( nssCKFWToken_GetHasProtectedAuthenticationPath(fwToken) ) { - pInfo->flags |= CKF_PROTECTED_AUTHENTICATION_PATH; - } + if (nssCKFWToken_GetHasProtectedAuthenticationPath(fwToken)) { + pInfo->flags |= CKF_PROTECTED_AUTHENTICATION_PATH; + } - if( nssCKFWToken_GetSupportsDualCryptoOperations(fwToken) ) { - pInfo->flags |= CKF_DUAL_CRYPTO_OPERATIONS; - } + if (nssCKFWToken_GetSupportsDualCryptoOperations(fwToken)) { + pInfo->flags |= CKF_DUAL_CRYPTO_OPERATIONS; + } - pInfo->ulMaxSessionCount = nssCKFWToken_GetMaxSessionCount(fwToken); - pInfo->ulSessionCount = nssCKFWToken_GetSessionCount(fwToken); - pInfo->ulMaxRwSessionCount = nssCKFWToken_GetMaxRwSessionCount(fwToken); - pInfo->ulRwSessionCount= nssCKFWToken_GetRwSessionCount(fwToken); - pInfo->ulMaxPinLen = nssCKFWToken_GetMaxPinLen(fwToken); - pInfo->ulMinPinLen = nssCKFWToken_GetMinPinLen(fwToken); - pInfo->ulTotalPublicMemory = nssCKFWToken_GetTotalPublicMemory(fwToken); - pInfo->ulFreePublicMemory = nssCKFWToken_GetFreePublicMemory(fwToken); - pInfo->ulTotalPrivateMemory = nssCKFWToken_GetTotalPrivateMemory(fwToken); - pInfo->ulFreePrivateMemory = nssCKFWToken_GetFreePrivateMemory(fwToken); - pInfo->hardwareVersion = nssCKFWToken_GetHardwareVersion(fwToken); - pInfo->firmwareVersion = nssCKFWToken_GetFirmwareVersion(fwToken); - - error = nssCKFWToken_GetUTCTime(fwToken, pInfo->utcTime); - if( CKR_OK != error ) { - goto loser; - } + pInfo->ulMaxSessionCount = nssCKFWToken_GetMaxSessionCount(fwToken); + pInfo->ulSessionCount = nssCKFWToken_GetSessionCount(fwToken); + pInfo->ulMaxRwSessionCount = nssCKFWToken_GetMaxRwSessionCount(fwToken); + pInfo->ulRwSessionCount = nssCKFWToken_GetRwSessionCount(fwToken); + pInfo->ulMaxPinLen = nssCKFWToken_GetMaxPinLen(fwToken); + pInfo->ulMinPinLen = nssCKFWToken_GetMinPinLen(fwToken); + pInfo->ulTotalPublicMemory = nssCKFWToken_GetTotalPublicMemory(fwToken); + pInfo->ulFreePublicMemory = nssCKFWToken_GetFreePublicMemory(fwToken); + pInfo->ulTotalPrivateMemory = nssCKFWToken_GetTotalPrivateMemory(fwToken); + pInfo->ulFreePrivateMemory = nssCKFWToken_GetFreePrivateMemory(fwToken); + pInfo->hardwareVersion = nssCKFWToken_GetHardwareVersion(fwToken); + pInfo->firmwareVersion = nssCKFWToken_GetFirmwareVersion(fwToken); - return CKR_OK; + error = nssCKFWToken_GetUTCTime(fwToken, pInfo->utcTime); + if (CKR_OK != error) { + goto loser; + } - loser: - switch( error ) { - case CKR_DEVICE_REMOVED: - case CKR_TOKEN_NOT_PRESENT: - if (fwToken) - nssCKFWToken_Destroy(fwToken); - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SLOT_ID_INVALID: - case CKR_TOKEN_NOT_RECOGNIZED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_DEVICE_REMOVED: + case CKR_TOKEN_NOT_PRESENT: + if (fwToken) + nssCKFWToken_Destroy(fwToken); + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SLOT_ID_INVALID: + case CKR_TOKEN_NOT_RECOGNIZED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -656,82 +650,80 @@ NSSCKFWC_GetTokenInfo * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_WaitForSlotEvent -( - NSSCKFWInstance *fwInstance, - CK_FLAGS flags, - CK_SLOT_ID_PTR pSlot, - CK_VOID_PTR pReserved -) +NSSCKFWC_WaitForSlotEvent( + NSSCKFWInstance *fwInstance, + CK_FLAGS flags, + CK_SLOT_ID_PTR pSlot, + CK_VOID_PTR pReserved) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - CK_BBOOL block; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; - CK_ULONG i; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + CK_BBOOL block; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; + CK_ULONG i; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - if( flags & ~CKF_DONT_BLOCK ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - block = (flags & CKF_DONT_BLOCK) ? CK_TRUE : CK_FALSE; - - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } - - if( (CK_SLOT_ID_PTR)CK_NULL_PTR == pSlot ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - if( (CK_VOID_PTR)CK_NULL_PTR != pReserved ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } - - fwSlot = nssCKFWInstance_WaitForSlotEvent(fwInstance, block, &error); - if (!fwSlot) { - goto loser; - } - - for( i = 0; i < nSlots; i++ ) { - if( fwSlot == slots[i] ) { - *pSlot = (CK_SLOT_ID)(CK_ULONG)(i+1); - return CKR_OK; + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; } - } - error = CKR_GENERAL_ERROR; /* returned something not in the slot list */ + if (flags & ~CKF_DONT_BLOCK) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - loser: - switch( error ) { - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_NO_EVENT: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + block = (flags & CKF_DONT_BLOCK) ? CK_TRUE : CK_FALSE; - return error; + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } + + if ((CK_SLOT_ID_PTR)CK_NULL_PTR == pSlot) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } + + if ((CK_VOID_PTR)CK_NULL_PTR != pReserved) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } + + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } + + fwSlot = nssCKFWInstance_WaitForSlotEvent(fwInstance, block, &error); + if (!fwSlot) { + goto loser; + } + + for (i = 0; i < nSlots; i++) { + if (fwSlot == slots[i]) { + *pSlot = (CK_SLOT_ID)(CK_ULONG)(i + 1); + return CKR_OK; + } + } + + error = CKR_GENERAL_ERROR; /* returned something not in the slot list */ + +loser: + switch (error) { + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_NO_EVENT: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -739,113 +731,112 @@ NSSCKFWC_WaitForSlotEvent * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetMechanismList -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_MECHANISM_TYPE_PTR pMechanismList, - CK_ULONG_PTR pulCount -) +NSSCKFWC_GetMechanismList( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_MECHANISM_TYPE_PTR pMechanismList, + CK_ULONG_PTR pulCount) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; - CK_ULONG count; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; + CK_ULONG count; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } - if( (slotID < 1) || (slotID > nSlots) ) { - error = CKR_SLOT_ID_INVALID; - goto loser; - } + if ((slotID < 1) || (slotID > nSlots)) { + error = CKR_SLOT_ID_INVALID; + goto loser; + } - if( (CK_ULONG_PTR)CK_NULL_PTR == pulCount ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_ULONG_PTR)CK_NULL_PTR == pulCount) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } - fwSlot = slots[ slotID-1 ]; + fwSlot = slots[slotID - 1]; - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - count = nssCKFWToken_GetMechanismCount(fwToken); + count = nssCKFWToken_GetMechanismCount(fwToken); + + if ((CK_MECHANISM_TYPE_PTR)CK_NULL_PTR == pMechanismList) { + *pulCount = count; + return CKR_OK; + } + + if (*pulCount < count) { + *pulCount = count; + error = CKR_BUFFER_TOO_SMALL; + goto loser; + } + + /* + * A purify error here indicates caller error. + */ + (void)nsslibc_memset(pMechanismList, 0, *pulCount * sizeof(CK_MECHANISM_TYPE)); - if( (CK_MECHANISM_TYPE_PTR)CK_NULL_PTR == pMechanismList ) { *pulCount = count; - return CKR_OK; - } - if( *pulCount < count ) { - *pulCount = count; - error = CKR_BUFFER_TOO_SMALL; - goto loser; - } + if (0 != count) { + error = nssCKFWToken_GetMechanismTypes(fwToken, pMechanismList); + } + else { + error = CKR_OK; + } - /* - * A purify error here indicates caller error. - */ - (void)nsslibc_memset(pMechanismList, 0, *pulCount * sizeof(CK_MECHANISM_TYPE)); + if (CKR_OK == error) { + return CKR_OK; + } - *pulCount = count; +loser: + switch (error) { + case CKR_DEVICE_REMOVED: + case CKR_TOKEN_NOT_PRESENT: + if (fwToken) + nssCKFWToken_Destroy(fwToken); + break; + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SLOT_ID_INVALID: + case CKR_TOKEN_NOT_RECOGNIZED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - if( 0 != count ) { - error = nssCKFWToken_GetMechanismTypes(fwToken, pMechanismList); - } else { - error = CKR_OK; - } - - if( CKR_OK == error ) { - return CKR_OK; - } - - loser: - switch( error ) { - case CKR_DEVICE_REMOVED: - case CKR_TOKEN_NOT_PRESENT: - if (fwToken) - nssCKFWToken_Destroy(fwToken); - break; - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SLOT_ID_INVALID: - case CKR_TOKEN_NOT_RECOGNIZED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - - return error; + return error; } /* @@ -853,139 +844,137 @@ NSSCKFWC_GetMechanismList * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetMechanismInfo -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_MECHANISM_TYPE type, - CK_MECHANISM_INFO_PTR pInfo -) +NSSCKFWC_GetMechanismInfo( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_MECHANISM_TYPE type, + CK_MECHANISM_INFO_PTR pInfo) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } - if( (slotID < 1) || (slotID > nSlots) ) { - error = CKR_SLOT_ID_INVALID; - goto loser; - } + if ((slotID < 1) || (slotID > nSlots)) { + error = CKR_SLOT_ID_INVALID; + goto loser; + } - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } - fwSlot = slots[ slotID-1 ]; + fwSlot = slots[slotID - 1]; - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - if( (CK_MECHANISM_INFO_PTR)CK_NULL_PTR == pInfo ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_MECHANISM_INFO_PTR)CK_NULL_PTR == pInfo) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - (void)nsslibc_memset(pInfo, 0, sizeof(CK_MECHANISM_INFO)); + /* + * A purify error here indicates caller error. + */ + (void)nsslibc_memset(pInfo, 0, sizeof(CK_MECHANISM_INFO)); - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, type, &error); - if (!fwMechanism) { - goto loser; - } + fwMechanism = nssCKFWToken_GetMechanism(fwToken, type, &error); + if (!fwMechanism) { + goto loser; + } - pInfo->ulMinKeySize = nssCKFWMechanism_GetMinKeySize(fwMechanism, &error); - pInfo->ulMaxKeySize = nssCKFWMechanism_GetMaxKeySize(fwMechanism, &error); + pInfo->ulMinKeySize = nssCKFWMechanism_GetMinKeySize(fwMechanism, &error); + pInfo->ulMaxKeySize = nssCKFWMechanism_GetMaxKeySize(fwMechanism, &error); - if( nssCKFWMechanism_GetInHardware(fwMechanism, &error) ) { - pInfo->flags |= CKF_HW; - } - if( nssCKFWMechanism_GetCanEncrypt(fwMechanism, &error) ) { - pInfo->flags |= CKF_ENCRYPT; - } - if( nssCKFWMechanism_GetCanDecrypt(fwMechanism, &error) ) { - pInfo->flags |= CKF_DECRYPT; - } - if( nssCKFWMechanism_GetCanDigest(fwMechanism, &error) ) { - pInfo->flags |= CKF_DIGEST; - } - if( nssCKFWMechanism_GetCanSign(fwMechanism, &error) ) { - pInfo->flags |= CKF_SIGN; - } - if( nssCKFWMechanism_GetCanSignRecover(fwMechanism, &error) ) { - pInfo->flags |= CKF_SIGN_RECOVER; - } - if( nssCKFWMechanism_GetCanVerify(fwMechanism, &error) ) { - pInfo->flags |= CKF_VERIFY; - } - if( nssCKFWMechanism_GetCanVerifyRecover(fwMechanism, &error) ) { - pInfo->flags |= CKF_VERIFY_RECOVER; - } - if( nssCKFWMechanism_GetCanGenerate(fwMechanism, &error) ) { - pInfo->flags |= CKF_GENERATE; - } - if( nssCKFWMechanism_GetCanGenerateKeyPair(fwMechanism, &error) ) { - pInfo->flags |= CKF_GENERATE_KEY_PAIR; - } - if( nssCKFWMechanism_GetCanWrap(fwMechanism, &error) ) { - pInfo->flags |= CKF_WRAP; - } - if( nssCKFWMechanism_GetCanUnwrap(fwMechanism, &error) ) { - pInfo->flags |= CKF_UNWRAP; - } - if( nssCKFWMechanism_GetCanDerive(fwMechanism, &error) ) { - pInfo->flags |= CKF_DERIVE; - } - nssCKFWMechanism_Destroy(fwMechanism); + if (nssCKFWMechanism_GetInHardware(fwMechanism, &error)) { + pInfo->flags |= CKF_HW; + } + if (nssCKFWMechanism_GetCanEncrypt(fwMechanism, &error)) { + pInfo->flags |= CKF_ENCRYPT; + } + if (nssCKFWMechanism_GetCanDecrypt(fwMechanism, &error)) { + pInfo->flags |= CKF_DECRYPT; + } + if (nssCKFWMechanism_GetCanDigest(fwMechanism, &error)) { + pInfo->flags |= CKF_DIGEST; + } + if (nssCKFWMechanism_GetCanSign(fwMechanism, &error)) { + pInfo->flags |= CKF_SIGN; + } + if (nssCKFWMechanism_GetCanSignRecover(fwMechanism, &error)) { + pInfo->flags |= CKF_SIGN_RECOVER; + } + if (nssCKFWMechanism_GetCanVerify(fwMechanism, &error)) { + pInfo->flags |= CKF_VERIFY; + } + if (nssCKFWMechanism_GetCanVerifyRecover(fwMechanism, &error)) { + pInfo->flags |= CKF_VERIFY_RECOVER; + } + if (nssCKFWMechanism_GetCanGenerate(fwMechanism, &error)) { + pInfo->flags |= CKF_GENERATE; + } + if (nssCKFWMechanism_GetCanGenerateKeyPair(fwMechanism, &error)) { + pInfo->flags |= CKF_GENERATE_KEY_PAIR; + } + if (nssCKFWMechanism_GetCanWrap(fwMechanism, &error)) { + pInfo->flags |= CKF_WRAP; + } + if (nssCKFWMechanism_GetCanUnwrap(fwMechanism, &error)) { + pInfo->flags |= CKF_UNWRAP; + } + if (nssCKFWMechanism_GetCanDerive(fwMechanism, &error)) { + pInfo->flags |= CKF_DERIVE; + } + nssCKFWMechanism_Destroy(fwMechanism); - return error; + return error; - loser: - switch( error ) { - case CKR_DEVICE_REMOVED: - case CKR_TOKEN_NOT_PRESENT: - if (fwToken) - nssCKFWToken_Destroy(fwToken); - break; - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_MECHANISM_INVALID: - case CKR_SLOT_ID_INVALID: - case CKR_TOKEN_NOT_RECOGNIZED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_DEVICE_REMOVED: + case CKR_TOKEN_NOT_PRESENT: + if (fwToken) + nssCKFWToken_Destroy(fwToken); + break; + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_MECHANISM_INVALID: + case CKR_SLOT_ID_INVALID: + case CKR_TOKEN_NOT_RECOGNIZED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -993,94 +982,92 @@ NSSCKFWC_GetMechanismInfo * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_InitToken -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_CHAR_PTR pPin, - CK_ULONG ulPinLen, - CK_CHAR_PTR pLabel -) +NSSCKFWC_InitToken( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_CHAR_PTR pPin, + CK_ULONG ulPinLen, + CK_CHAR_PTR pLabel) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; - NSSItem pin; - NSSUTF8 *label; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; + NSSItem pin; + NSSUTF8 *label; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } - if( (slotID < 1) || (slotID > nSlots) ) { - error = CKR_SLOT_ID_INVALID; - goto loser; - } + if ((slotID < 1) || (slotID > nSlots)) { + error = CKR_SLOT_ID_INVALID; + goto loser; + } - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } - fwSlot = slots[ slotID-1 ]; + fwSlot = slots[slotID - 1]; - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - pin.size = (PRUint32)ulPinLen; - pin.data = (void *)pPin; - label = (NSSUTF8 *)pLabel; /* identity conversion */ + pin.size = (PRUint32)ulPinLen; + pin.data = (void *)pPin; + label = (NSSUTF8 *)pLabel; /* identity conversion */ - error = nssCKFWToken_InitToken(fwToken, &pin, label); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWToken_InitToken(fwToken, &pin, label); + if (CKR_OK != error) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_DEVICE_REMOVED: - case CKR_TOKEN_NOT_PRESENT: - if (fwToken) - nssCKFWToken_Destroy(fwToken); - break; - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_PIN_INCORRECT: - case CKR_PIN_LOCKED: - case CKR_SESSION_EXISTS: - case CKR_SLOT_ID_INVALID: - case CKR_TOKEN_NOT_RECOGNIZED: - case CKR_TOKEN_WRITE_PROTECTED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_DEVICE_REMOVED: + case CKR_TOKEN_NOT_PRESENT: + if (fwToken) + nssCKFWToken_Destroy(fwToken); + break; + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_PIN_INCORRECT: + case CKR_PIN_LOCKED: + case CKR_SESSION_EXISTS: + case CKR_SLOT_ID_INVALID: + case CKR_TOKEN_NOT_RECOGNIZED: + case CKR_TOKEN_WRITE_PROTECTED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -1088,73 +1075,72 @@ NSSCKFWC_InitToken * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_InitPIN -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pPin, - CK_ULONG ulPinLen -) +NSSCKFWC_InitPIN( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_CHAR_PTR pPin, + CK_ULONG ulPinLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSItem pin, *arg; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSItem pin, *arg; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( (CK_CHAR_PTR)CK_NULL_PTR == pPin ) { - arg = (NSSItem *)NULL; - } else { - arg = &pin; - pin.size = (PRUint32)ulPinLen; - pin.data = (void *)pPin; - } + if ((CK_CHAR_PTR)CK_NULL_PTR == pPin) { + arg = (NSSItem *)NULL; + } + else { + arg = &pin; + pin.size = (PRUint32)ulPinLen; + pin.data = (void *)pPin; + } - error = nssCKFWSession_InitPIN(fwSession, arg); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWSession_InitPIN(fwSession, arg); + if (CKR_OK != error) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_PIN_INVALID: - case CKR_PIN_LEN_RANGE: - case CKR_SESSION_READ_ONLY: - case CKR_SESSION_HANDLE_INVALID: - case CKR_TOKEN_WRITE_PROTECTED: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_PIN_INVALID: + case CKR_PIN_LEN_RANGE: + case CKR_SESSION_READ_ONLY: + case CKR_SESSION_HANDLE_INVALID: + case CKR_TOKEN_WRITE_PROTECTED: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -1162,84 +1148,84 @@ NSSCKFWC_InitPIN * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SetPIN -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pOldPin, - CK_ULONG ulOldLen, - CK_CHAR_PTR pNewPin, - CK_ULONG ulNewLen -) +NSSCKFWC_SetPIN( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_CHAR_PTR pOldPin, + CK_ULONG ulOldLen, + CK_CHAR_PTR pNewPin, + CK_ULONG ulNewLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSItem oldPin, newPin, *oldArg, *newArg; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSItem oldPin, newPin, *oldArg, *newArg; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( (CK_CHAR_PTR)CK_NULL_PTR == pOldPin ) { - oldArg = (NSSItem *)NULL; - } else { - oldArg = &oldPin; - oldPin.size = (PRUint32)ulOldLen; - oldPin.data = (void *)pOldPin; - } + if ((CK_CHAR_PTR)CK_NULL_PTR == pOldPin) { + oldArg = (NSSItem *)NULL; + } + else { + oldArg = &oldPin; + oldPin.size = (PRUint32)ulOldLen; + oldPin.data = (void *)pOldPin; + } - if( (CK_CHAR_PTR)CK_NULL_PTR == pNewPin ) { - newArg = (NSSItem *)NULL; - } else { - newArg = &newPin; - newPin.size = (PRUint32)ulNewLen; - newPin.data = (void *)pNewPin; - } + if ((CK_CHAR_PTR)CK_NULL_PTR == pNewPin) { + newArg = (NSSItem *)NULL; + } + else { + newArg = &newPin; + newPin.size = (PRUint32)ulNewLen; + newPin.data = (void *)pNewPin; + } - error = nssCKFWSession_SetPIN(fwSession, oldArg, newArg); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWSession_SetPIN(fwSession, oldArg, newArg); + if (CKR_OK != error) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_PIN_INCORRECT: - case CKR_PIN_INVALID: - case CKR_PIN_LEN_RANGE: - case CKR_PIN_LOCKED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TOKEN_WRITE_PROTECTED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_PIN_INCORRECT: + case CKR_PIN_INVALID: + case CKR_PIN_LEN_RANGE: + case CKR_PIN_LOCKED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TOKEN_WRITE_PROTECTED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -1247,128 +1233,128 @@ NSSCKFWC_SetPIN * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_OpenSession -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID, - CK_FLAGS flags, - CK_VOID_PTR pApplication, - CK_NOTIFY Notify, - CK_SESSION_HANDLE_PTR phSession -) +NSSCKFWC_OpenSession( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID, + CK_FLAGS flags, + CK_VOID_PTR pApplication, + CK_NOTIFY Notify, + CK_SESSION_HANDLE_PTR phSession) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; - NSSCKFWSession *fwSession; - CK_BBOOL rw; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; + NSSCKFWSession *fwSession; + CK_BBOOL rw; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } - if( (slotID < 1) || (slotID > nSlots) ) { - error = CKR_SLOT_ID_INVALID; - goto loser; - } + if ((slotID < 1) || (slotID > nSlots)) { + error = CKR_SLOT_ID_INVALID; + goto loser; + } - if( flags & CKF_RW_SESSION ) { - rw = CK_TRUE; - } else { - rw = CK_FALSE; - } + if (flags & CKF_RW_SESSION) { + rw = CK_TRUE; + } + else { + rw = CK_FALSE; + } - if( flags & CKF_SERIAL_SESSION ) { - ; - } else { - error = CKR_SESSION_PARALLEL_NOT_SUPPORTED; - goto loser; - } + if (flags & CKF_SERIAL_SESSION) { + ; + } + else { + error = CKR_SESSION_PARALLEL_NOT_SUPPORTED; + goto loser; + } - if( flags & ~(CKF_RW_SESSION|CKF_SERIAL_SESSION) ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if (flags & ~(CKF_RW_SESSION | CKF_SERIAL_SESSION)) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - if( (CK_SESSION_HANDLE_PTR)CK_NULL_PTR == phSession ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_SESSION_HANDLE_PTR)CK_NULL_PTR == phSession) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - *phSession = (CK_SESSION_HANDLE)0; + /* + * A purify error here indicates caller error. + */ + *phSession = (CK_SESSION_HANDLE)0; - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } - fwSlot = slots[ slotID-1 ]; + fwSlot = slots[slotID - 1]; - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - fwSession = nssCKFWToken_OpenSession(fwToken, rw, pApplication, - Notify, &error); - if (!fwSession) { - goto loser; - } + fwSession = nssCKFWToken_OpenSession(fwToken, rw, pApplication, + Notify, &error); + if (!fwSession) { + goto loser; + } - *phSession = nssCKFWInstance_CreateSessionHandle(fwInstance, - fwSession, &error); - if( (CK_SESSION_HANDLE)0 == *phSession ) { - goto loser; - } + *phSession = nssCKFWInstance_CreateSessionHandle(fwInstance, + fwSession, &error); + if ((CK_SESSION_HANDLE)0 == *phSession) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SESSION_COUNT: - case CKR_SESSION_EXISTS: - case CKR_SESSION_PARALLEL_NOT_SUPPORTED: - case CKR_SESSION_READ_WRITE_SO_EXISTS: - case CKR_SLOT_ID_INVALID: - case CKR_TOKEN_NOT_PRESENT: - case CKR_TOKEN_NOT_RECOGNIZED: - case CKR_TOKEN_WRITE_PROTECTED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SESSION_COUNT: + case CKR_SESSION_EXISTS: + case CKR_SESSION_PARALLEL_NOT_SUPPORTED: + case CKR_SESSION_READ_WRITE_SO_EXISTS: + case CKR_SLOT_ID_INVALID: + case CKR_TOKEN_NOT_PRESENT: + case CKR_TOKEN_NOT_RECOGNIZED: + case CKR_TOKEN_WRITE_PROTECTED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -1376,58 +1362,56 @@ NSSCKFWC_OpenSession * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_CloseSession -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -) +NSSCKFWC_CloseSession( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - nssCKFWInstance_DestroySessionHandle(fwInstance, hSession); - error = nssCKFWSession_Destroy(fwSession, CK_TRUE); + nssCKFWInstance_DestroySessionHandle(fwInstance, hSession); + error = nssCKFWSession_Destroy(fwSession, CK_TRUE); - if( CKR_OK != error ) { - goto loser; - } + if (CKR_OK != error) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -1435,78 +1419,76 @@ NSSCKFWC_CloseSession * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_CloseAllSessions -( - NSSCKFWInstance *fwInstance, - CK_SLOT_ID slotID -) +NSSCKFWC_CloseAllSessions( + NSSCKFWInstance *fwInstance, + CK_SLOT_ID slotID) { - CK_RV error = CKR_OK; - CK_ULONG nSlots; - NSSCKFWSlot **slots; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; + CK_RV error = CKR_OK; + CK_ULONG nSlots; + NSSCKFWSlot **slots; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken = (NSSCKFWToken *)NULL; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); - if( (CK_ULONG)0 == nSlots ) { - goto loser; - } + nSlots = nssCKFWInstance_GetNSlots(fwInstance, &error); + if ((CK_ULONG)0 == nSlots) { + goto loser; + } - if( (slotID < 1) || (slotID > nSlots) ) { - error = CKR_SLOT_ID_INVALID; - goto loser; - } + if ((slotID < 1) || (slotID > nSlots)) { + error = CKR_SLOT_ID_INVALID; + goto loser; + } - slots = nssCKFWInstance_GetSlots(fwInstance, &error); - if( (NSSCKFWSlot **)NULL == slots ) { - goto loser; - } + slots = nssCKFWInstance_GetSlots(fwInstance, &error); + if ((NSSCKFWSlot **)NULL == slots) { + goto loser; + } - fwSlot = slots[ slotID-1 ]; + fwSlot = slots[slotID - 1]; - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWToken_CloseAllSessions(fwToken); - if( CKR_OK != error ) { - goto loser; - } + error = nssCKFWToken_CloseAllSessions(fwToken); + if (CKR_OK != error) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SLOT_ID_INVALID: - case CKR_TOKEN_NOT_PRESENT: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SLOT_ID_INVALID: + case CKR_TOKEN_NOT_PRESENT: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -1514,80 +1496,78 @@ NSSCKFWC_CloseAllSessions * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetSessionInfo -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_SESSION_INFO_PTR pInfo -) +NSSCKFWC_GetSessionInfo( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_SESSION_INFO_PTR pInfo) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWSlot *fwSlot; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWSlot *fwSlot; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( (CK_SESSION_INFO_PTR)CK_NULL_PTR == pInfo ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_SESSION_INFO_PTR)CK_NULL_PTR == pInfo) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - (void)nsslibc_memset(pInfo, 0, sizeof(CK_SESSION_INFO)); + /* + * A purify error here indicates caller error. + */ + (void)nsslibc_memset(pInfo, 0, sizeof(CK_SESSION_INFO)); - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; + goto loser; + } - pInfo->slotID = nssCKFWSlot_GetSlotID(fwSlot); - pInfo->state = nssCKFWSession_GetSessionState(fwSession); + pInfo->slotID = nssCKFWSlot_GetSlotID(fwSlot); + pInfo->state = nssCKFWSession_GetSessionState(fwSession); - if( CK_TRUE == nssCKFWSession_IsRWSession(fwSession) ) { - pInfo->flags |= CKF_RW_SESSION; - } + if (CK_TRUE == nssCKFWSession_IsRWSession(fwSession)) { + pInfo->flags |= CKF_RW_SESSION; + } - pInfo->flags |= CKF_SERIAL_SESSION; /* Always true */ + pInfo->flags |= CKF_SERIAL_SESSION; /* Always true */ - pInfo->ulDeviceError = nssCKFWSession_GetDeviceError(fwSession); + pInfo->ulDeviceError = nssCKFWSession_GetDeviceError(fwSession); - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -1595,88 +1575,86 @@ NSSCKFWC_GetSessionInfo * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetOperationState -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, - CK_ULONG_PTR pulOperationStateLen -) +NSSCKFWC_GetOperationState( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, + CK_ULONG_PTR pulOperationStateLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - CK_ULONG len; - NSSItem buf; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + CK_ULONG len; + NSSItem buf; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( (CK_ULONG_PTR)CK_NULL_PTR == pulOperationStateLen ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_ULONG_PTR)CK_NULL_PTR == pulOperationStateLen) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - len = nssCKFWSession_GetOperationStateLen(fwSession, &error); - if( ((CK_ULONG)0 == len) && (CKR_OK != error) ) { - goto loser; - } + len = nssCKFWSession_GetOperationStateLen(fwSession, &error); + if (((CK_ULONG)0 == len) && (CKR_OK != error)) { + goto loser; + } - if( (CK_BYTE_PTR)CK_NULL_PTR == pOperationState ) { + if ((CK_BYTE_PTR)CK_NULL_PTR == pOperationState) { + *pulOperationStateLen = len; + return CKR_OK; + } + + if (*pulOperationStateLen < len) { + *pulOperationStateLen = len; + error = CKR_BUFFER_TOO_SMALL; + goto loser; + } + + buf.size = (PRUint32)*pulOperationStateLen; + buf.data = (void *)pOperationState; *pulOperationStateLen = len; + error = nssCKFWSession_GetOperationState(fwSession, &buf); + + if (CKR_OK != error) { + goto loser; + } + return CKR_OK; - } - if( *pulOperationStateLen < len ) { - *pulOperationStateLen = len; - error = CKR_BUFFER_TOO_SMALL; - goto loser; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_STATE_UNSAVEABLE: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - buf.size = (PRUint32)*pulOperationStateLen; - buf.data = (void *)pOperationState; - *pulOperationStateLen = len; - error = nssCKFWSession_GetOperationState(fwSession, &buf); - - if( CKR_OK != error ) { - goto loser; - } - - return CKR_OK; - - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_STATE_UNSAVEABLE: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - - return error; + return error; } /* @@ -1684,100 +1662,100 @@ NSSCKFWC_GetOperationState * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SetOperationState -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, - CK_ULONG ulOperationStateLen, - CK_OBJECT_HANDLE hEncryptionKey, - CK_OBJECT_HANDLE hAuthenticationKey -) +NSSCKFWC_SetOperationState( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, + CK_ULONG ulOperationStateLen, + CK_OBJECT_HANDLE hEncryptionKey, + CK_OBJECT_HANDLE hAuthenticationKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *eKey; - NSSCKFWObject *aKey; - NSSItem state; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *eKey; + NSSCKFWObject *aKey; + NSSItem state; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - if( (CK_BYTE_PTR)CK_NULL_PTR == pOperationState ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - /* - * We could loop through the buffer, to catch any purify errors - * in a place with a "user error" note. - */ - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } - - if( (CK_OBJECT_HANDLE)0 == hEncryptionKey ) { - eKey = (NSSCKFWObject *)NULL; - } else { - eKey = nssCKFWInstance_ResolveObjectHandle(fwInstance, hEncryptionKey); - if (!eKey) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; } - } - if( (CK_OBJECT_HANDLE)0 == hAuthenticationKey ) { - aKey = (NSSCKFWObject *)NULL; - } else { - aKey = nssCKFWInstance_ResolveObjectHandle(fwInstance, hAuthenticationKey); - if (!aKey) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; + if ((CK_BYTE_PTR)CK_NULL_PTR == pOperationState) { + error = CKR_ARGUMENTS_BAD; + goto loser; } - } - state.data = pOperationState; - state.size = ulOperationStateLen; + /* + * We could loop through the buffer, to catch any purify errors + * in a place with a "user error" note. + */ - error = nssCKFWSession_SetOperationState(fwSession, &state, eKey, aKey); - if( CKR_OK != error ) { - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - return CKR_OK; + if ((CK_OBJECT_HANDLE)0 == hEncryptionKey) { + eKey = (NSSCKFWObject *)NULL; + } + else { + eKey = nssCKFWInstance_ResolveObjectHandle(fwInstance, hEncryptionKey); + if (!eKey) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_CHANGED: - case CKR_KEY_NEEDED: - case CKR_KEY_NOT_NEEDED: - case CKR_SAVED_STATE_INVALID: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + if ((CK_OBJECT_HANDLE)0 == hAuthenticationKey) { + aKey = (NSSCKFWObject *)NULL; + } + else { + aKey = nssCKFWInstance_ResolveObjectHandle(fwInstance, hAuthenticationKey); + if (!aKey) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } + } - return error; + state.data = pOperationState; + state.size = ulOperationStateLen; + + error = nssCKFWSession_SetOperationState(fwSession, &state, eKey, aKey); + if (CKR_OK != error) { + goto loser; + } + + return CKR_OK; + +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_CHANGED: + case CKR_KEY_NEEDED: + case CKR_KEY_NOT_NEEDED: + case CKR_SAVED_STATE_INVALID: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -1785,77 +1763,76 @@ NSSCKFWC_SetOperationState * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Login -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_USER_TYPE userType, - CK_CHAR_PTR pPin, - CK_ULONG ulPinLen -) +NSSCKFWC_Login( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_USER_TYPE userType, + CK_CHAR_PTR pPin, + CK_ULONG ulPinLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSItem pin, *arg; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSItem pin, *arg; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - if( (CK_CHAR_PTR)CK_NULL_PTR == pPin ) { - arg = (NSSItem *)NULL; - } else { - arg = &pin; - pin.size = (PRUint32)ulPinLen; - pin.data = (void *)pPin; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - error = nssCKFWSession_Login(fwSession, userType, arg); - if( CKR_OK != error ) { - goto loser; - } + if ((CK_CHAR_PTR)CK_NULL_PTR == pPin) { + arg = (NSSItem *)NULL; + } + else { + arg = &pin; + pin.size = (PRUint32)ulPinLen; + pin.data = (void *)pPin; + } - return CKR_OK; + error = nssCKFWSession_Login(fwSession, userType, arg); + if (CKR_OK != error) { + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_PIN_EXPIRED: - case CKR_PIN_INCORRECT: - case CKR_PIN_LOCKED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY_EXISTS: - case CKR_USER_ALREADY_LOGGED_IN: - case CKR_USER_ANOTHER_ALREADY_LOGGED_IN: - case CKR_USER_PIN_NOT_INITIALIZED: - case CKR_USER_TOO_MANY_TYPES: - case CKR_USER_TYPE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_PIN_EXPIRED: + case CKR_PIN_INCORRECT: + case CKR_PIN_LOCKED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY_EXISTS: + case CKR_USER_ALREADY_LOGGED_IN: + case CKR_USER_ANOTHER_ALREADY_LOGGED_IN: + case CKR_USER_PIN_NOT_INITIALIZED: + case CKR_USER_TOO_MANY_TYPES: + case CKR_USER_TYPE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -1863,57 +1840,55 @@ NSSCKFWC_Login * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Logout -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -) +NSSCKFWC_Logout( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Logout(fwSession); - if( CKR_OK != error ) { - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - return CKR_OK; + error = nssCKFWSession_Logout(fwSession); + if (CKR_OK != error) { + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -1921,85 +1896,83 @@ NSSCKFWC_Logout * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_CreateObject -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject -) +NSSCKFWC_CreateObject( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phObject) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - if( (CK_OBJECT_HANDLE_PTR)CK_NULL_PTR == phObject ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - *phObject = (CK_OBJECT_HANDLE)0; + if ((CK_OBJECT_HANDLE_PTR)CK_NULL_PTR == phObject) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - fwObject = nssCKFWSession_CreateObject(fwSession, pTemplate, - ulCount, &error); - if (!fwObject) { - goto loser; - } + /* + * A purify error here indicates caller error. + */ + *phObject = (CK_OBJECT_HANDLE)0; - *phObject = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); - if( (CK_OBJECT_HANDLE)0 == *phObject ) { - nssCKFWObject_Destroy(fwObject); - goto loser; - } + fwObject = nssCKFWSession_CreateObject(fwSession, pTemplate, + ulCount, &error); + if (!fwObject) { + goto loser; + } - return CKR_OK; + *phObject = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + if ((CK_OBJECT_HANDLE)0 == *phObject) { + nssCKFWObject_Destroy(fwObject); + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ATTRIBUTE_READ_ONLY: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TEMPLATE_INCOMPLETE: - case CKR_TEMPLATE_INCONSISTENT: - case CKR_TOKEN_WRITE_PROTECTED: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ATTRIBUTE_READ_ONLY: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TEMPLATE_INCOMPLETE: + case CKR_TEMPLATE_INCONSISTENT: + case CKR_TOKEN_WRITE_PROTECTED: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2007,94 +1980,92 @@ NSSCKFWC_CreateObject * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_CopyObject -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phNewObject -) +NSSCKFWC_CopyObject( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phNewObject) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWObject *fwNewObject; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWObject *fwNewObject; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - if( (CK_OBJECT_HANDLE_PTR)CK_NULL_PTR == phNewObject ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - *phNewObject = (CK_OBJECT_HANDLE)0; + if ((CK_OBJECT_HANDLE_PTR)CK_NULL_PTR == phNewObject) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); - if (!fwObject) { - error = CKR_OBJECT_HANDLE_INVALID; - goto loser; - } + /* + * A purify error here indicates caller error. + */ + *phNewObject = (CK_OBJECT_HANDLE)0; - fwNewObject = nssCKFWSession_CopyObject(fwSession, fwObject, - pTemplate, ulCount, &error); - if (!fwNewObject) { - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); + if (!fwObject) { + error = CKR_OBJECT_HANDLE_INVALID; + goto loser; + } - *phNewObject = nssCKFWInstance_CreateObjectHandle(fwInstance, - fwNewObject, &error); - if( (CK_OBJECT_HANDLE)0 == *phNewObject ) { - nssCKFWObject_Destroy(fwNewObject); - goto loser; - } + fwNewObject = nssCKFWSession_CopyObject(fwSession, fwObject, + pTemplate, ulCount, &error); + if (!fwNewObject) { + goto loser; + } - return CKR_OK; + *phNewObject = nssCKFWInstance_CreateObjectHandle(fwInstance, + fwNewObject, &error); + if ((CK_OBJECT_HANDLE)0 == *phNewObject) { + nssCKFWObject_Destroy(fwNewObject); + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ATTRIBUTE_READ_ONLY: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OBJECT_HANDLE_INVALID: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TEMPLATE_INCONSISTENT: - case CKR_TOKEN_WRITE_PROTECTED: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ATTRIBUTE_READ_ONLY: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OBJECT_HANDLE_INVALID: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TEMPLATE_INCONSISTENT: + case CKR_TOKEN_WRITE_PROTECTED: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2102,65 +2073,63 @@ NSSCKFWC_CopyObject * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DestroyObject -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject -) +NSSCKFWC_DestroyObject( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); - if (!fwObject) { - error = CKR_OBJECT_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - nssCKFWInstance_DestroyObjectHandle(fwInstance, hObject); - nssCKFWObject_Destroy(fwObject); + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); + if (!fwObject) { + error = CKR_OBJECT_HANDLE_INVALID; + goto loser; + } - return CKR_OK; + nssCKFWInstance_DestroyObjectHandle(fwInstance, hObject); + nssCKFWObject_Destroy(fwObject); - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OBJECT_HANDLE_INVALID: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TOKEN_WRITE_PROTECTED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OBJECT_HANDLE_INVALID: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TOKEN_WRITE_PROTECTED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2168,77 +2137,75 @@ NSSCKFWC_DestroyObject * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetObjectSize -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ULONG_PTR pulSize -) +NSSCKFWC_GetObjectSize( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ULONG_PTR pulSize) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); - if (!fwObject) { - error = CKR_OBJECT_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( (CK_ULONG_PTR)CK_NULL_PTR == pulSize ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); + if (!fwObject) { + error = CKR_OBJECT_HANDLE_INVALID; + goto loser; + } - /* - * A purify error here indicates caller error. - */ - *pulSize = (CK_ULONG)0; + if ((CK_ULONG_PTR)CK_NULL_PTR == pulSize) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - *pulSize = nssCKFWObject_GetObjectSize(fwObject, &error); - if( ((CK_ULONG)0 == *pulSize) && (CKR_OK != error) ) { - goto loser; - } + /* + * A purify error here indicates caller error. + */ + *pulSize = (CK_ULONG)0; - return CKR_OK; + *pulSize = nssCKFWObject_GetObjectSize(fwObject, &error); + if (((CK_ULONG)0 == *pulSize) && (CKR_OK != error)) { + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_INFORMATION_SENSITIVE: - case CKR_OBJECT_HANDLE_INVALID: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_INFORMATION_SENSITIVE: + case CKR_OBJECT_HANDLE_INVALID: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2246,229 +2213,236 @@ NSSCKFWC_GetObjectSize * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetAttributeValue -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount -) +NSSCKFWC_GetAttributeValue( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - CK_BBOOL sensitive = CK_FALSE; - CK_BBOOL invalid = CK_FALSE; - CK_BBOOL tooSmall = CK_FALSE; - CK_ULONG i; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + CK_BBOOL sensitive = CK_FALSE; + CK_BBOOL invalid = CK_FALSE; + CK_BBOOL tooSmall = CK_FALSE; + CK_ULONG i; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } - - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); - if (!fwObject) { - error = CKR_OBJECT_HANDLE_INVALID; - goto loser; - } - - if( (CK_ATTRIBUTE_PTR)CK_NULL_PTR == pTemplate ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - for( i = 0; i < ulCount; i++ ) { - CK_ULONG size = nssCKFWObject_GetAttributeSize(fwObject, - pTemplate[i].type, &error); - if( (CK_ULONG)0 == size ) { - switch( error ) { - case CKR_ATTRIBUTE_SENSITIVE: - case CKR_INFORMATION_SENSITIVE: - sensitive = CK_TRUE; - pTemplate[i].ulValueLen = (CK_ULONG)(-1); - continue; - case CKR_ATTRIBUTE_TYPE_INVALID: - invalid = CK_TRUE; - pTemplate[i].ulValueLen = (CK_ULONG)(-1); - continue; - case CKR_OK: - break; - default: + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; goto loser; - } } - if( (CK_VOID_PTR)CK_NULL_PTR == pTemplate[i].pValue ) { - pTemplate[i].ulValueLen = size; - } else { - NSSItem it, *p; + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( pTemplate[i].ulValueLen < size ) { - tooSmall = CK_TRUE; - continue; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); + if (!fwObject) { + error = CKR_OBJECT_HANDLE_INVALID; + goto loser; + } - it.size = (PRUint32)pTemplate[i].ulValueLen; - it.data = (void *)pTemplate[i].pValue; - p = nssCKFWObject_GetAttribute(fwObject, pTemplate[i].type, &it, - (NSSArena *)NULL, &error); - if (!p) { - switch( error ) { - case CKR_ATTRIBUTE_SENSITIVE: - case CKR_INFORMATION_SENSITIVE: - sensitive = CK_TRUE; - pTemplate[i].ulValueLen = (CK_ULONG)(-1); - continue; - case CKR_ATTRIBUTE_TYPE_INVALID: - invalid = CK_TRUE; - pTemplate[i].ulValueLen = (CK_ULONG)(-1); - continue; - default: - goto loser; + if ((CK_ATTRIBUTE_PTR)CK_NULL_PTR == pTemplate) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } + + for (i = 0; i < ulCount; i++) { + CK_ULONG size = nssCKFWObject_GetAttributeSize(fwObject, + pTemplate[i].type, &error); + if ((CK_ULONG)0 == size) { + switch (error) { + case CKR_ATTRIBUTE_SENSITIVE: + case CKR_INFORMATION_SENSITIVE: + sensitive = + CK_TRUE; + pTemplate[i].ulValueLen = + (CK_ULONG)(-1); + continue; + case CKR_ATTRIBUTE_TYPE_INVALID: + invalid = + CK_TRUE; + pTemplate[i].ulValueLen = + (CK_ULONG)(-1); + continue; + case CKR_OK: + break; + default: + goto loser; + } } - } - pTemplate[i].ulValueLen = size; + if ((CK_VOID_PTR)CK_NULL_PTR == pTemplate[i].pValue) { + pTemplate[i].ulValueLen = size; + } + else { + NSSItem it, *p; + + if (pTemplate[i].ulValueLen < size) { + tooSmall = CK_TRUE; + continue; + } + + it.size = (PRUint32)pTemplate[i].ulValueLen; + it.data = (void *)pTemplate[i].pValue; + p = nssCKFWObject_GetAttribute(fwObject, pTemplate[i].type, &it, + (NSSArena *)NULL, &error); + if (!p) { + switch (error) { + case CKR_ATTRIBUTE_SENSITIVE: + case CKR_INFORMATION_SENSITIVE: + sensitive = + CK_TRUE; + pTemplate[i].ulValueLen = + (CK_ULONG)(-1); + continue; + case CKR_ATTRIBUTE_TYPE_INVALID: + invalid = + CK_TRUE; + pTemplate[i].ulValueLen = + (CK_ULONG)(-1); + continue; + default: + goto loser; + } + } + + pTemplate[i].ulValueLen = size; + } } - } - if( sensitive ) { - error = CKR_ATTRIBUTE_SENSITIVE; - goto loser; - } else if( invalid ) { - error = CKR_ATTRIBUTE_TYPE_INVALID; - goto loser; - } else if( tooSmall ) { - error = CKR_BUFFER_TOO_SMALL; - goto loser; - } + if (sensitive) { + error = CKR_ATTRIBUTE_SENSITIVE; + goto loser; + } + else if (invalid) { + error = CKR_ATTRIBUTE_TYPE_INVALID; + goto loser; + } + else if (tooSmall) { + error = CKR_BUFFER_TOO_SMALL; + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ATTRIBUTE_SENSITIVE: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OBJECT_HANDLE_INVALID: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ATTRIBUTE_SENSITIVE: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OBJECT_HANDLE_INVALID: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } - + /* * NSSCKFWC_SetAttributeValue * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SetAttributeValue -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount -) +NSSCKFWC_SetAttributeValue( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - CK_ULONG i; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + CK_ULONG i; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } - - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); - if (!fwObject) { - error = CKR_OBJECT_HANDLE_INVALID; - goto loser; - } - - if( (CK_ATTRIBUTE_PTR)CK_NULL_PTR == pTemplate ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - for (i=0; i < ulCount; i++) { - NSSItem value; - - value.data = pTemplate[i].pValue; - value.size = pTemplate[i].ulValueLen; - - error = nssCKFWObject_SetAttribute(fwObject, fwSession, - pTemplate[i].type, &value); - - if( CKR_OK != error ) { - goto loser; + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; } - } - return CKR_OK; + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ATTRIBUTE_READ_ONLY: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OBJECT_HANDLE_INVALID: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TEMPLATE_INCONSISTENT: - case CKR_TOKEN_WRITE_PROTECTED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hObject); + if (!fwObject) { + error = CKR_OBJECT_HANDLE_INVALID; + goto loser; + } - return error; + if ((CK_ATTRIBUTE_PTR)CK_NULL_PTR == pTemplate) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } + + for (i = 0; i < ulCount; i++) { + NSSItem value; + + value.data = pTemplate[i].pValue; + value.size = pTemplate[i].ulValueLen; + + error = nssCKFWObject_SetAttribute(fwObject, fwSession, + pTemplate[i].type, &value); + + if (CKR_OK != error) { + goto loser; + } + } + + return CKR_OK; + +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ATTRIBUTE_READ_ONLY: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OBJECT_HANDLE_INVALID: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TEMPLATE_INCONSISTENT: + case CKR_TOKEN_WRITE_PROTECTED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2476,85 +2450,83 @@ NSSCKFWC_SetAttributeValue * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_FindObjectsInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount -) +NSSCKFWC_FindObjectsInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWFindObjects *fwFindObjects; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWFindObjects *fwFindObjects; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - if( ((CK_ATTRIBUTE_PTR)CK_NULL_PTR == pTemplate) && (ulCount != 0) ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwFindObjects = nssCKFWSession_GetFWFindObjects(fwSession, &error); - if (fwFindObjects) { - error = CKR_OPERATION_ACTIVE; - goto loser; - } + if (((CK_ATTRIBUTE_PTR)CK_NULL_PTR == pTemplate) && (ulCount != 0)) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - if( CKR_OPERATION_NOT_INITIALIZED != error ) { - goto loser; - } + fwFindObjects = nssCKFWSession_GetFWFindObjects(fwSession, &error); + if (fwFindObjects) { + error = CKR_OPERATION_ACTIVE; + goto loser; + } - fwFindObjects = nssCKFWSession_FindObjectsInit(fwSession, - pTemplate, ulCount, &error); - if (!fwFindObjects) { - goto loser; - } + if (CKR_OPERATION_NOT_INITIALIZED != error) { + goto loser; + } - error = nssCKFWSession_SetFWFindObjects(fwSession, fwFindObjects); + fwFindObjects = nssCKFWSession_FindObjectsInit(fwSession, + pTemplate, ulCount, &error); + if (!fwFindObjects) { + goto loser; + } - if( CKR_OK != error ) { - nssCKFWFindObjects_Destroy(fwFindObjects); - goto loser; - } + error = nssCKFWSession_SetFWFindObjects(fwSession, fwFindObjects); - return CKR_OK; + if (CKR_OK != error) { + nssCKFWFindObjects_Destroy(fwFindObjects); + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_ACTIVE: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + return CKR_OK; - return error; +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_ACTIVE: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2562,93 +2534,91 @@ NSSCKFWC_FindObjectsInit * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_FindObjects -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE_PTR phObject, - CK_ULONG ulMaxObjectCount, - CK_ULONG_PTR pulObjectCount -) +NSSCKFWC_FindObjects( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE_PTR phObject, + CK_ULONG ulMaxObjectCount, + CK_ULONG_PTR pulObjectCount) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWFindObjects *fwFindObjects; - CK_ULONG i; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWFindObjects *fwFindObjects; + CK_ULONG i; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } - - if( (CK_OBJECT_HANDLE_PTR)CK_NULL_PTR == phObject ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } - - /* - * A purify error here indicates caller error. - */ - (void)nsslibc_memset(phObject, 0, sizeof(CK_OBJECT_HANDLE) * ulMaxObjectCount); - *pulObjectCount = (CK_ULONG)0; - - fwFindObjects = nssCKFWSession_GetFWFindObjects(fwSession, &error); - if (!fwFindObjects) { - goto loser; - } - - for( i = 0; i < ulMaxObjectCount; i++ ) { - NSSCKFWObject *fwObject = nssCKFWFindObjects_Next(fwFindObjects, - NULL, &error); - if (!fwObject) { - break; + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; } - phObject[i] = nssCKFWInstance_FindObjectHandle(fwInstance, fwObject); - if( (CK_OBJECT_HANDLE)0 == phObject[i] ) { - phObject[i] = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; } - if( (CK_OBJECT_HANDLE)0 == phObject[i] ) { - /* This isn't right either, is it? */ - nssCKFWObject_Destroy(fwObject); - goto loser; + + if ((CK_OBJECT_HANDLE_PTR)CK_NULL_PTR == phObject) { + error = CKR_ARGUMENTS_BAD; + goto loser; } - } - *pulObjectCount = i; + /* + * A purify error here indicates caller error. + */ + (void)nsslibc_memset(phObject, 0, sizeof(CK_OBJECT_HANDLE) * ulMaxObjectCount); + *pulObjectCount = (CK_ULONG)0; - return CKR_OK; + fwFindObjects = nssCKFWSession_GetFWFindObjects(fwSession, &error); + if (!fwFindObjects) { + goto loser; + } - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + for (i = 0; i < ulMaxObjectCount; i++) { + NSSCKFWObject *fwObject = nssCKFWFindObjects_Next(fwFindObjects, + NULL, &error); + if (!fwObject) { + break; + } - return error; + phObject[i] = nssCKFWInstance_FindObjectHandle(fwInstance, fwObject); + if ((CK_OBJECT_HANDLE)0 == phObject[i]) { + phObject[i] = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + } + if ((CK_OBJECT_HANDLE)0 == phObject[i]) { + /* This isn't right either, is it? */ + nssCKFWObject_Destroy(fwObject); + goto loser; + } + } + + *pulObjectCount = i; + + return CKR_OK; + +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2656,67 +2626,65 @@ NSSCKFWC_FindObjects * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_FindObjectsFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -) +NSSCKFWC_FindObjectsFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWFindObjects *fwFindObjects; - - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWFindObjects *fwFindObjects; - fwFindObjects = nssCKFWSession_GetFWFindObjects(fwSession, &error); - if (!fwFindObjects) { - error = CKR_OPERATION_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - nssCKFWFindObjects_Destroy(fwFindObjects); - error = nssCKFWSession_SetFWFindObjects(fwSession, - (NSSCKFWFindObjects *)NULL); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( CKR_OK != error ) { - goto loser; - } + fwFindObjects = nssCKFWSession_GetFWFindObjects(fwSession, &error); + if (!fwFindObjects) { + error = CKR_OPERATION_NOT_INITIALIZED; + goto loser; + } - return CKR_OK; + nssCKFWFindObjects_Destroy(fwFindObjects); + error = nssCKFWSession_SetFWFindObjects(fwSession, + (NSSCKFWFindObjects *)NULL); - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } + if (CKR_OK != error) { + goto loser; + } - return error; + return CKR_OK; + +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + + return error; } /* @@ -2724,97 +2692,95 @@ NSSCKFWC_FindObjectsFinal * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_EncryptInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -) +NSSCKFWC_EncryptInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWMechanism_EncryptInit(fwMechanism, pMechanism, - fwSession, fwObject); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); + error = nssCKFWMechanism_EncryptInit(fwMechanism, pMechanism, + fwSession, fwObject); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_FUNCTION_NOT_PERMITTED: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_TYPE_INCONSISTENT: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_FUNCTION_NOT_PERMITTED: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_TYPE_INCONSISTENT: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -2822,64 +2788,62 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Encrypt -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pEncryptedData, - CK_ULONG_PTR pulEncryptedDataLen -) +NSSCKFWC_Encrypt( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pEncryptedData, + CK_ULONG_PTR pulEncryptedDataLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateFinal(fwSession, - NSSCKFWCryptoOperationType_Encrypt, - NSSCKFWCryptoOperationState_EncryptDecrypt, - pData, ulDataLen, pEncryptedData, pulEncryptedDataLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateFinal(fwSession, + NSSCKFWCryptoOperationType_Encrypt, + NSSCKFWCryptoOperationState_EncryptDecrypt, + pData, ulDataLen, pEncryptedData, pulEncryptedDataLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_INVALID: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_CLOSED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_INVALID: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_CLOSED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -2887,63 +2851,61 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_EncryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen -) +NSSCKFWC_EncryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Update(fwSession, - NSSCKFWCryptoOperationType_Encrypt, - NSSCKFWCryptoOperationState_EncryptDecrypt, - pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_Update(fwSession, + NSSCKFWCryptoOperationType_Encrypt, + NSSCKFWCryptoOperationState_EncryptDecrypt, + pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -2951,61 +2913,59 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_EncryptFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastEncryptedPart, - CK_ULONG_PTR pulLastEncryptedPartLen -) +NSSCKFWC_EncryptFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastEncryptedPart, + CK_ULONG_PTR pulLastEncryptedPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Final(fwSession, - NSSCKFWCryptoOperationType_Encrypt, - NSSCKFWCryptoOperationState_EncryptDecrypt, - pLastEncryptedPart, pulLastEncryptedPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_Final(fwSession, + NSSCKFWCryptoOperationType_Encrypt, + NSSCKFWCryptoOperationState_EncryptDecrypt, + pLastEncryptedPart, pulLastEncryptedPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3013,97 +2973,95 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DecryptInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -) +NSSCKFWC_DecryptInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWMechanism_DecryptInit(fwMechanism, pMechanism, - fwSession, fwObject); - nssCKFWMechanism_Destroy(fwMechanism); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWMechanism_DecryptInit(fwMechanism, pMechanism, + fwSession, fwObject); + nssCKFWMechanism_Destroy(fwMechanism); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_FUNCTION_NOT_PERMITTED: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_TYPE_INCONSISTENT: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_FUNCTION_NOT_PERMITTED: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_TYPE_INCONSISTENT: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3111,71 +3069,69 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Decrypt -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData, - CK_ULONG ulEncryptedDataLen, - CK_BYTE_PTR pData, - CK_ULONG_PTR pulDataLen -) +NSSCKFWC_Decrypt( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedData, + CK_ULONG ulEncryptedDataLen, + CK_BYTE_PTR pData, + CK_ULONG_PTR pulDataLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateFinal(fwSession, - NSSCKFWCryptoOperationType_Decrypt, - NSSCKFWCryptoOperationState_EncryptDecrypt, - pEncryptedData, ulEncryptedDataLen, pData, pulDataLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateFinal(fwSession, + NSSCKFWCryptoOperationType_Decrypt, + NSSCKFWCryptoOperationState_EncryptDecrypt, + pEncryptedData, ulEncryptedDataLen, pData, pulDataLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_ENCRYPTED_DATA_INVALID: - case CKR_ENCRYPTED_DATA_LEN_RANGE: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - case CKR_DATA_LEN_RANGE: - error = CKR_ENCRYPTED_DATA_LEN_RANGE; - break; - case CKR_DATA_INVALID: - error = CKR_ENCRYPTED_DATA_INVALID; - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_ENCRYPTED_DATA_INVALID: + case CKR_ENCRYPTED_DATA_LEN_RANGE: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + case CKR_DATA_LEN_RANGE: + error = CKR_ENCRYPTED_DATA_LEN_RANGE; + break; + case CKR_DATA_INVALID: + error = CKR_ENCRYPTED_DATA_INVALID; + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3183,71 +3139,69 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DecryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, - CK_ULONG_PTR pulPartLen -) +NSSCKFWC_DecryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, + CK_ULONG_PTR pulPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Update(fwSession, - NSSCKFWCryptoOperationType_Decrypt, - NSSCKFWCryptoOperationState_EncryptDecrypt, - pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_Update(fwSession, + NSSCKFWCryptoOperationType_Decrypt, + NSSCKFWCryptoOperationState_EncryptDecrypt, + pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_ENCRYPTED_DATA_INVALID: - case CKR_ENCRYPTED_DATA_LEN_RANGE: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - case CKR_DATA_LEN_RANGE: - error = CKR_ENCRYPTED_DATA_LEN_RANGE; - break; - case CKR_DATA_INVALID: - error = CKR_ENCRYPTED_DATA_INVALID; - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_ENCRYPTED_DATA_INVALID: + case CKR_ENCRYPTED_DATA_LEN_RANGE: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + case CKR_DATA_LEN_RANGE: + error = CKR_ENCRYPTED_DATA_LEN_RANGE; + break; + case CKR_DATA_INVALID: + error = CKR_ENCRYPTED_DATA_INVALID; + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3255,69 +3209,67 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DecryptFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastPart, - CK_ULONG_PTR pulLastPartLen -) +NSSCKFWC_DecryptFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastPart, + CK_ULONG_PTR pulLastPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Final(fwSession, - NSSCKFWCryptoOperationType_Decrypt, - NSSCKFWCryptoOperationState_EncryptDecrypt, - pLastPart, pulLastPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_Final(fwSession, + NSSCKFWCryptoOperationType_Decrypt, + NSSCKFWCryptoOperationState_EncryptDecrypt, + pLastPart, pulLastPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_FAILED: - case CKR_FUNCTION_CANCELED: - case CKR_ENCRYPTED_DATA_INVALID: - case CKR_ENCRYPTED_DATA_LEN_RANGE: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - case CKR_DATA_LEN_RANGE: - error = CKR_ENCRYPTED_DATA_LEN_RANGE; - break; - case CKR_DATA_INVALID: - error = CKR_ENCRYPTED_DATA_INVALID; - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_FAILED: + case CKR_FUNCTION_CANCELED: + case CKR_ENCRYPTED_DATA_INVALID: + case CKR_ENCRYPTED_DATA_LEN_RANGE: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + case CKR_DATA_LEN_RANGE: + error = CKR_ENCRYPTED_DATA_LEN_RANGE; + break; + case CKR_DATA_INVALID: + error = CKR_ENCRYPTED_DATA_INVALID; + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3325,85 +3277,83 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DigestInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism -) +NSSCKFWC_DigestInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWMechanism_DigestInit(fwMechanism, pMechanism, fwSession); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); + error = nssCKFWMechanism_DigestInit(fwMechanism, pMechanism, fwSession); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3411,62 +3361,60 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Digest -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen -) +NSSCKFWC_Digest( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pDigest, + CK_ULONG_PTR pulDigestLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateFinal(fwSession, - NSSCKFWCryptoOperationType_Digest, - NSSCKFWCryptoOperationState_Digest, - pData, ulDataLen, pDigest, pulDigestLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateFinal(fwSession, + NSSCKFWCryptoOperationType_Digest, + NSSCKFWCryptoOperationState_Digest, + pData, ulDataLen, pDigest, pulDigestLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3474,59 +3422,57 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DigestUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen -) +NSSCKFWC_DigestUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_DigestUpdate(fwSession, - NSSCKFWCryptoOperationType_Digest, - NSSCKFWCryptoOperationState_Digest, - pData, ulDataLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_DigestUpdate(fwSession, + NSSCKFWCryptoOperationType_Digest, + NSSCKFWCryptoOperationState_Digest, + pData, ulDataLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3534,64 +3480,62 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DigestKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hKey -) +NSSCKFWC_DigestKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - error = nssCKFWSession_DigestKey(fwSession, fwObject); + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_DigestKey(fwSession, fwObject); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_INDIGESTIBLE: - case CKR_KEY_SIZE_RANGE: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_INDIGESTIBLE: + case CKR_KEY_SIZE_RANGE: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3599,60 +3543,58 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DigestFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen -) +NSSCKFWC_DigestFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pDigest, + CK_ULONG_PTR pulDigestLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Final(fwSession, - NSSCKFWCryptoOperationType_Digest, - NSSCKFWCryptoOperationState_Digest, - pDigest, pulDigestLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_Final(fwSession, + NSSCKFWCryptoOperationType_Digest, + NSSCKFWCryptoOperationState_Digest, + pDigest, pulDigestLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3660,98 +3602,96 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SignInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -) +NSSCKFWC_SignInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWMechanism_SignInit(fwMechanism, pMechanism, fwSession, - fwObject); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); + error = nssCKFWMechanism_SignInit(fwMechanism, pMechanism, fwSession, + fwObject); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_FUNCTION_NOT_PERMITTED: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_TYPE_INCONSISTENT: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_FUNCTION_NOT_PERMITTED: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_TYPE_INCONSISTENT: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3759,66 +3699,64 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Sign -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen -) +NSSCKFWC_Sign( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateFinal(fwSession, - NSSCKFWCryptoOperationType_Sign, - NSSCKFWCryptoOperationState_SignVerify, - pData, ulDataLen, pSignature, pulSignatureLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateFinal(fwSession, + NSSCKFWCryptoOperationType_Sign, + NSSCKFWCryptoOperationState_SignVerify, + pData, ulDataLen, pSignature, pulSignatureLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_INVALID: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - case CKR_FUNCTION_REJECTED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_INVALID: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + case CKR_FUNCTION_REJECTED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3826,61 +3764,59 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SignUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen -) +NSSCKFWC_SignUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_DigestUpdate(fwSession, - NSSCKFWCryptoOperationType_Sign, - NSSCKFWCryptoOperationState_SignVerify, - pPart, ulPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_DigestUpdate(fwSession, + NSSCKFWCryptoOperationType_Sign, + NSSCKFWCryptoOperationState_SignVerify, + pPart, ulPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3888,63 +3824,61 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SignFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen -) +NSSCKFWC_SignFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Final(fwSession, - NSSCKFWCryptoOperationType_Sign, - NSSCKFWCryptoOperationState_SignVerify, - pSignature, pulSignatureLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_Final(fwSession, + NSSCKFWCryptoOperationType_Sign, + NSSCKFWCryptoOperationState_SignVerify, + pSignature, pulSignatureLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - case CKR_FUNCTION_REJECTED: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + case CKR_FUNCTION_REJECTED: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -3952,98 +3886,96 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SignRecoverInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -) +NSSCKFWC_SignRecoverInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWMechanism_SignRecoverInit(fwMechanism, pMechanism, fwSession, - fwObject); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); + error = nssCKFWMechanism_SignRecoverInit(fwMechanism, pMechanism, fwSession, + fwObject); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_FUNCTION_NOT_PERMITTED: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_TYPE_INCONSISTENT: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_FUNCTION_NOT_PERMITTED: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_TYPE_INCONSISTENT: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4051,65 +3983,63 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SignRecover -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen -) +NSSCKFWC_SignRecover( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateFinal(fwSession, - NSSCKFWCryptoOperationType_SignRecover, - NSSCKFWCryptoOperationState_SignVerify, - pData, ulDataLen, pSignature, pulSignatureLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateFinal(fwSession, + NSSCKFWCryptoOperationType_SignRecover, + NSSCKFWCryptoOperationState_SignVerify, + pData, ulDataLen, pSignature, pulSignatureLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_INVALID: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_INVALID: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4117,98 +4047,96 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_VerifyInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -) +NSSCKFWC_VerifyInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWMechanism_VerifyInit(fwMechanism, pMechanism, fwSession, - fwObject); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); + error = nssCKFWMechanism_VerifyInit(fwMechanism, pMechanism, fwSession, + fwObject); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_FUNCTION_NOT_PERMITTED: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_TYPE_INCONSISTENT: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_FUNCTION_NOT_PERMITTED: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_TYPE_INCONSISTENT: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4216,65 +4144,63 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_Verify -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, - CK_ULONG ulDataLen, - CK_BYTE_PTR pSignature, - CK_ULONG ulSignatureLen -) +NSSCKFWC_Verify( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, + CK_ULONG ulDataLen, + CK_BYTE_PTR pSignature, + CK_ULONG ulSignatureLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateFinal(fwSession, - NSSCKFWCryptoOperationType_Verify, - NSSCKFWCryptoOperationState_SignVerify, - pData, ulDataLen, pSignature, &ulSignatureLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateFinal(fwSession, + NSSCKFWCryptoOperationType_Verify, + NSSCKFWCryptoOperationState_SignVerify, + pData, ulDataLen, pSignature, &ulSignatureLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_INVALID: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SIGNATURE_INVALID: - case CKR_SIGNATURE_LEN_RANGE: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_INVALID: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SIGNATURE_INVALID: + case CKR_SIGNATURE_LEN_RANGE: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4282,60 +4208,58 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_VerifyUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen -) +NSSCKFWC_VerifyUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_DigestUpdate(fwSession, - NSSCKFWCryptoOperationType_Verify, - NSSCKFWCryptoOperationState_SignVerify, - pPart, ulPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_DigestUpdate(fwSession, + NSSCKFWCryptoOperationType_Verify, + NSSCKFWCryptoOperationState_SignVerify, + pPart, ulPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4343,62 +4267,60 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_VerifyFinal -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature, - CK_ULONG ulSignatureLen -) +NSSCKFWC_VerifyFinal( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, + CK_ULONG ulSignatureLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_Final(fwSession, - NSSCKFWCryptoOperationType_Verify, - NSSCKFWCryptoOperationState_SignVerify, - pSignature, &ulSignatureLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_Final(fwSession, + NSSCKFWCryptoOperationType_Verify, + NSSCKFWCryptoOperationState_SignVerify, + pSignature, &ulSignatureLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SIGNATURE_INVALID: - case CKR_SIGNATURE_LEN_RANGE: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SIGNATURE_INVALID: + case CKR_SIGNATURE_LEN_RANGE: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4406,98 +4328,96 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_VerifyRecoverInit -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey -) +NSSCKFWC_VerifyRecoverInit( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error = nssCKFWMechanism_VerifyRecoverInit(fwMechanism, pMechanism, - fwSession, fwObject); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); + error = nssCKFWMechanism_VerifyRecoverInit(fwMechanism, pMechanism, + fwSession, fwObject); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_FUNCTION_NOT_PERMITTED: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_TYPE_INCONSISTENT: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_CLOSED: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_FUNCTION_NOT_PERMITTED: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_TYPE_INCONSISTENT: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_CLOSED: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4505,64 +4425,62 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_VerifyRecover -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature, - CK_ULONG ulSignatureLen, - CK_BYTE_PTR pData, - CK_ULONG_PTR pulDataLen -) +NSSCKFWC_VerifyRecover( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, + CK_ULONG ulSignatureLen, + CK_BYTE_PTR pData, + CK_ULONG_PTR pulDataLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateFinal(fwSession, - NSSCKFWCryptoOperationType_VerifyRecover, - NSSCKFWCryptoOperationState_SignVerify, - pSignature, ulSignatureLen, pData, pulDataLen); - if (CKR_OK == error) { - return CKR_OK; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } + + error = nssCKFWSession_UpdateFinal(fwSession, + NSSCKFWCryptoOperationType_VerifyRecover, + NSSCKFWCryptoOperationState_SignVerify, + pSignature, ulSignatureLen, pData, pulDataLen); + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_INVALID: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SIGNATURE_INVALID: - case CKR_SIGNATURE_LEN_RANGE: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_INVALID: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SIGNATURE_INVALID: + case CKR_SIGNATURE_LEN_RANGE: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4570,64 +4488,62 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DigestEncryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen -) +NSSCKFWC_DigestEncryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateCombo(fwSession, - NSSCKFWCryptoOperationType_Encrypt, - NSSCKFWCryptoOperationType_Digest, - NSSCKFWCryptoOperationState_Digest, - pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateCombo(fwSession, + NSSCKFWCryptoOperationType_Encrypt, + NSSCKFWCryptoOperationType_Digest, + NSSCKFWCryptoOperationState_Digest, + pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4635,71 +4551,69 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DecryptDigestUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, - CK_ULONG_PTR pulPartLen -) +NSSCKFWC_DecryptDigestUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, + CK_ULONG_PTR pulPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateCombo(fwSession, - NSSCKFWCryptoOperationType_Decrypt, - NSSCKFWCryptoOperationType_Digest, - NSSCKFWCryptoOperationState_Digest, - pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateCombo(fwSession, + NSSCKFWCryptoOperationType_Decrypt, + NSSCKFWCryptoOperationType_Digest, + NSSCKFWCryptoOperationState_Digest, + pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_ENCRYPTED_DATA_INVALID: - case CKR_ENCRYPTED_DATA_LEN_RANGE: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - case CKR_DATA_INVALID: - error = CKR_ENCRYPTED_DATA_INVALID; - break; - case CKR_DATA_LEN_RANGE: - error = CKR_ENCRYPTED_DATA_LEN_RANGE; - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_ENCRYPTED_DATA_INVALID: + case CKR_ENCRYPTED_DATA_LEN_RANGE: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + case CKR_DATA_INVALID: + error = CKR_ENCRYPTED_DATA_INVALID; + break; + case CKR_DATA_LEN_RANGE: + error = CKR_ENCRYPTED_DATA_LEN_RANGE; + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4707,65 +4621,63 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SignEncryptUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen -) +NSSCKFWC_SignEncryptUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateCombo(fwSession, - NSSCKFWCryptoOperationType_Encrypt, - NSSCKFWCryptoOperationType_Sign, - NSSCKFWCryptoOperationState_SignVerify, - pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateCombo(fwSession, + NSSCKFWCryptoOperationType_Encrypt, + NSSCKFWCryptoOperationType_Sign, + NSSCKFWCryptoOperationState_SignVerify, + pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4773,69 +4685,67 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DecryptVerifyUpdate -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, - CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, - CK_ULONG_PTR pulPartLen -) +NSSCKFWC_DecryptVerifyUpdate( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, + CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, + CK_ULONG_PTR pulPartLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - error = nssCKFWSession_UpdateCombo(fwSession, - NSSCKFWCryptoOperationType_Decrypt, - NSSCKFWCryptoOperationType_Verify, - NSSCKFWCryptoOperationState_SignVerify, - pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen); + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWSession_UpdateCombo(fwSession, + NSSCKFWCryptoOperationType_Decrypt, + NSSCKFWCryptoOperationType_Verify, + NSSCKFWCryptoOperationState_SignVerify, + pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DATA_LEN_RANGE: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_ENCRYPTED_DATA_INVALID: - case CKR_ENCRYPTED_DATA_LEN_RANGE: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_NOT_INITIALIZED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - break; - case CKR_DATA_INVALID: - error = CKR_ENCRYPTED_DATA_INVALID; - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DATA_LEN_RANGE: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_ENCRYPTED_DATA_INVALID: + case CKR_ENCRYPTED_DATA_LEN_RANGE: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_NOT_INITIALIZED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + break; + case CKR_DATA_INVALID: + error = CKR_ENCRYPTED_DATA_INVALID; + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4843,106 +4753,104 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GenerateKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phKey -) +NSSCKFWC_GenerateKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - fwObject = nssCKFWMechanism_GenerateKey( - fwMechanism, - pMechanism, - fwSession, - pTemplate, - ulCount, - &error); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); - if (!fwObject) { - goto loser; - } - *phKey= nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + fwObject = nssCKFWMechanism_GenerateKey( + fwMechanism, + pMechanism, + fwSession, + pTemplate, + ulCount, + &error); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + if (!fwObject) { + goto loser; + } + *phKey = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_ATTRIBUTE_READ_ONLY: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TEMPLATE_INCOMPLETE: - case CKR_TEMPLATE_INCONSISTENT: - case CKR_TOKEN_WRITE_PROTECTED: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_ATTRIBUTE_READ_ONLY: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TEMPLATE_INCOMPLETE: + case CKR_TEMPLATE_INCONSISTENT: + case CKR_TOKEN_WRITE_PROTECTED: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -4950,121 +4858,119 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GenerateKeyPair -( - NSSCKFWInstance *fwInstance, - 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 -) +NSSCKFWC_GenerateKeyPair( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG ulPublicKeyAttributeCount, + CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG ulPrivateKeyAttributeCount, + CK_OBJECT_HANDLE_PTR phPublicKey, + CK_OBJECT_HANDLE_PTR phPrivateKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwPrivateKeyObject; - NSSCKFWObject *fwPublicKeyObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwPrivateKeyObject; + NSSCKFWObject *fwPublicKeyObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - error= nssCKFWMechanism_GenerateKeyPair( - fwMechanism, - pMechanism, - fwSession, - pPublicKeyTemplate, - ulPublicKeyAttributeCount, - pPublicKeyTemplate, - ulPublicKeyAttributeCount, - &fwPublicKeyObject, - &fwPrivateKeyObject); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); - if (CKR_OK != error) { - goto loser; - } - *phPublicKey = nssCKFWInstance_CreateObjectHandle(fwInstance, - fwPublicKeyObject, - &error); - if (CKR_OK != error) { - goto loser; - } - *phPrivateKey = nssCKFWInstance_CreateObjectHandle(fwInstance, - fwPrivateKeyObject, - &error); - if (CKR_OK == error) { - return CKR_OK; - } + error = nssCKFWMechanism_GenerateKeyPair( + fwMechanism, + pMechanism, + fwSession, + pPublicKeyTemplate, + ulPublicKeyAttributeCount, + pPublicKeyTemplate, + ulPublicKeyAttributeCount, + &fwPublicKeyObject, + &fwPrivateKeyObject); + + nssCKFWMechanism_Destroy(fwMechanism); + if (CKR_OK != error) { + goto loser; + } + *phPublicKey = nssCKFWInstance_CreateObjectHandle(fwInstance, + fwPublicKeyObject, + &error); + if (CKR_OK != error) { + goto loser; + } + *phPrivateKey = nssCKFWInstance_CreateObjectHandle(fwInstance, + fwPrivateKeyObject, + &error); + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_ATTRIBUTE_READ_ONLY: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_DOMAIN_PARAMS_INVALID: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TEMPLATE_INCOMPLETE: - case CKR_TEMPLATE_INCONSISTENT: - case CKR_TOKEN_WRITE_PROTECTED: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_ATTRIBUTE_READ_ONLY: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_DOMAIN_PARAMS_INVALID: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TEMPLATE_INCOMPLETE: + case CKR_TEMPLATE_INCONSISTENT: + case CKR_TOKEN_WRITE_PROTECTED: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -5072,153 +4978,150 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_WrapKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hWrappingKey, - CK_OBJECT_HANDLE hKey, - CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pulWrappedKeyLen -) +NSSCKFWC_WrapKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hWrappingKey, + CK_OBJECT_HANDLE hKey, + CK_BYTE_PTR pWrappedKey, + CK_ULONG_PTR pulWrappedKeyLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwKeyObject; - NSSCKFWObject *fwWrappingKeyObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; - NSSItem wrappedKey; - CK_ULONG wrappedKeyLength = 0; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwKeyObject; + NSSCKFWObject *fwWrappingKeyObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; + NSSItem wrappedKey; + CK_ULONG wrappedKeyLength = 0; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwWrappingKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, - hWrappingKey); - if (!fwWrappingKeyObject) { - error = CKR_WRAPPING_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); - if (!fwKeyObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwWrappingKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, + hWrappingKey); + if (!fwWrappingKeyObject) { + error = CKR_WRAPPING_KEY_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hKey); + if (!fwKeyObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - /* + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } + + /* * first get the length... */ - wrappedKeyLength = nssCKFWMechanism_GetWrapKeyLength( - fwMechanism, - pMechanism, - fwSession, - fwWrappingKeyObject, - fwKeyObject, - &error); - if ((CK_ULONG) 0 == wrappedKeyLength) { + wrappedKeyLength = nssCKFWMechanism_GetWrapKeyLength( + fwMechanism, + pMechanism, + fwSession, + fwWrappingKeyObject, + fwKeyObject, + &error); + if ((CK_ULONG)0 == wrappedKeyLength) { + nssCKFWMechanism_Destroy(fwMechanism); + goto loser; + } + if ((CK_BYTE_PTR)NULL == pWrappedKey) { + *pulWrappedKeyLen = wrappedKeyLength; + nssCKFWMechanism_Destroy(fwMechanism); + return CKR_OK; + } + if (wrappedKeyLength > *pulWrappedKeyLen) { + *pulWrappedKeyLen = wrappedKeyLength; + nssCKFWMechanism_Destroy(fwMechanism); + error = CKR_BUFFER_TOO_SMALL; + goto loser; + } + + wrappedKey.data = pWrappedKey; + wrappedKey.size = wrappedKeyLength; + + error = nssCKFWMechanism_WrapKey( + fwMechanism, + pMechanism, + fwSession, + fwWrappingKeyObject, + fwKeyObject, + &wrappedKey); + nssCKFWMechanism_Destroy(fwMechanism); - goto loser; - } - if ((CK_BYTE_PTR)NULL == pWrappedKey) { - *pulWrappedKeyLen = wrappedKeyLength; - nssCKFWMechanism_Destroy(fwMechanism); - return CKR_OK; - } - if (wrappedKeyLength > *pulWrappedKeyLen) { - *pulWrappedKeyLen = wrappedKeyLength; - nssCKFWMechanism_Destroy(fwMechanism); - error = CKR_BUFFER_TOO_SMALL; - goto loser; - } - + *pulWrappedKeyLen = wrappedKey.size; - wrappedKey.data = pWrappedKey; - wrappedKey.size = wrappedKeyLength; - - error = nssCKFWMechanism_WrapKey( - fwMechanism, - pMechanism, - fwSession, - fwWrappingKeyObject, - fwKeyObject, - &wrappedKey); - - nssCKFWMechanism_Destroy(fwMechanism); - *pulWrappedKeyLen = wrappedKey.size; - - if (CKR_OK == error) { - return CKR_OK; - } + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_NOT_WRAPPABLE: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_UNEXTRACTABLE: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_WRAPPING_KEY_HANDLE_INVALID: - case CKR_WRAPPING_KEY_SIZE_RANGE: - case CKR_WRAPPING_KEY_TYPE_INCONSISTENT: - break; - case CKR_KEY_TYPE_INCONSISTENT: - error = CKR_WRAPPING_KEY_TYPE_INCONSISTENT; - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_NOT_WRAPPABLE: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_UNEXTRACTABLE: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_WRAPPING_KEY_HANDLE_INVALID: + case CKR_WRAPPING_KEY_SIZE_RANGE: + case CKR_WRAPPING_KEY_TYPE_INCONSISTENT: + break; + case CKR_KEY_TYPE_INCONSISTENT: + error = CKR_WRAPPING_KEY_TYPE_INCONSISTENT; + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -5226,145 +5129,143 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_UnwrapKey -( - NSSCKFWInstance *fwInstance, - 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 -) +NSSCKFWC_UnwrapKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hUnwrappingKey, + CK_BYTE_PTR pWrappedKey, + CK_ULONG ulWrappedKeyLen, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWObject *fwWrappingKeyObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; - NSSItem wrappedKey; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWObject *fwWrappingKeyObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; + NSSItem wrappedKey; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwWrappingKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, - hUnwrappingKey); - if (!fwWrappingKeyObject) { - error = CKR_WRAPPING_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwWrappingKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, + hUnwrappingKey); + if (!fwWrappingKeyObject) { + error = CKR_WRAPPING_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - wrappedKey.data = pWrappedKey; - wrappedKey.size = ulWrappedKeyLen; + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - fwObject = nssCKFWMechanism_UnwrapKey( - fwMechanism, - pMechanism, - fwSession, - fwWrappingKeyObject, - &wrappedKey, - pTemplate, - ulAttributeCount, - &error); + wrappedKey.data = pWrappedKey; + wrappedKey.size = ulWrappedKeyLen; - nssCKFWMechanism_Destroy(fwMechanism); - if (!fwObject) { - goto loser; - } - *phKey = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + fwObject = nssCKFWMechanism_UnwrapKey( + fwMechanism, + pMechanism, + fwSession, + fwWrappingKeyObject, + &wrappedKey, + pTemplate, + ulAttributeCount, + &error); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + if (!fwObject) { + goto loser; + } + *phKey = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_ATTRIBUTE_READ_ONLY: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_BUFFER_TOO_SMALL: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_DOMAIN_PARAMS_INVALID: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TEMPLATE_INCOMPLETE: - case CKR_TEMPLATE_INCONSISTENT: - case CKR_TOKEN_WRITE_PROTECTED: - case CKR_UNWRAPPING_KEY_HANDLE_INVALID: - case CKR_UNWRAPPING_KEY_SIZE_RANGE: - case CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: - case CKR_USER_NOT_LOGGED_IN: - case CKR_WRAPPED_KEY_INVALID: - case CKR_WRAPPED_KEY_LEN_RANGE: - break; - case CKR_KEY_HANDLE_INVALID: - error = CKR_UNWRAPPING_KEY_HANDLE_INVALID; - break; - case CKR_KEY_SIZE_RANGE: - error = CKR_UNWRAPPING_KEY_SIZE_RANGE; - break; - case CKR_KEY_TYPE_INCONSISTENT: - error = CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; - break; - case CKR_ENCRYPTED_DATA_INVALID: - error = CKR_WRAPPED_KEY_INVALID; - break; - case CKR_ENCRYPTED_DATA_LEN_RANGE: - error = CKR_WRAPPED_KEY_LEN_RANGE; - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_ATTRIBUTE_READ_ONLY: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_BUFFER_TOO_SMALL: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_DOMAIN_PARAMS_INVALID: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TEMPLATE_INCOMPLETE: + case CKR_TEMPLATE_INCONSISTENT: + case CKR_TOKEN_WRITE_PROTECTED: + case CKR_UNWRAPPING_KEY_HANDLE_INVALID: + case CKR_UNWRAPPING_KEY_SIZE_RANGE: + case CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: + case CKR_USER_NOT_LOGGED_IN: + case CKR_WRAPPED_KEY_INVALID: + case CKR_WRAPPED_KEY_LEN_RANGE: + break; + case CKR_KEY_HANDLE_INVALID: + error = CKR_UNWRAPPING_KEY_HANDLE_INVALID; + break; + case CKR_KEY_SIZE_RANGE: + error = CKR_UNWRAPPING_KEY_SIZE_RANGE; + break; + case CKR_KEY_TYPE_INCONSISTENT: + error = CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; + break; + case CKR_ENCRYPTED_DATA_INVALID: + error = CKR_WRAPPED_KEY_INVALID; + break; + case CKR_ENCRYPTED_DATA_LEN_RANGE: + error = CKR_WRAPPED_KEY_LEN_RANGE; + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -5372,119 +5273,117 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_DeriveKey -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey -) +NSSCKFWC_DeriveKey( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hBaseKey, + CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSCKFWObject *fwObject; - NSSCKFWObject *fwBaseKeyObject; - NSSCKFWSlot *fwSlot; - NSSCKFWToken *fwToken; - NSSCKFWMechanism *fwMechanism; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSCKFWObject *fwObject; + NSSCKFWObject *fwBaseKeyObject; + NSSCKFWSlot *fwSlot; + NSSCKFWToken *fwToken; + NSSCKFWMechanism *fwMechanism; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } - - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwBaseKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hBaseKey); - if (!fwBaseKeyObject) { - error = CKR_KEY_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - fwSlot = nssCKFWSession_GetFWSlot(fwSession); - if (!fwSlot) { - error = CKR_GENERAL_ERROR; /* should never happen! */ - goto loser; - } + fwBaseKeyObject = nssCKFWInstance_ResolveObjectHandle(fwInstance, hBaseKey); + if (!fwBaseKeyObject) { + error = CKR_KEY_HANDLE_INVALID; + goto loser; + } - if( CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot) ) { - error = CKR_TOKEN_NOT_PRESENT; - goto loser; - } + fwSlot = nssCKFWSession_GetFWSlot(fwSession); + if (!fwSlot) { + error = CKR_GENERAL_ERROR; /* should never happen! */ + goto loser; + } - fwToken = nssCKFWSlot_GetToken(fwSlot, &error); - if (!fwToken) { - goto loser; - } + if (CK_TRUE != nssCKFWSlot_GetTokenPresent(fwSlot)) { + error = CKR_TOKEN_NOT_PRESENT; + goto loser; + } - fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); - if (!fwMechanism) { - goto loser; - } + fwToken = nssCKFWSlot_GetToken(fwSlot, &error); + if (!fwToken) { + goto loser; + } - fwObject = nssCKFWMechanism_DeriveKey( - fwMechanism, - pMechanism, - fwSession, - fwBaseKeyObject, - pTemplate, - ulAttributeCount, - &error); + fwMechanism = nssCKFWToken_GetMechanism(fwToken, pMechanism->mechanism, &error); + if (!fwMechanism) { + goto loser; + } - nssCKFWMechanism_Destroy(fwMechanism); - if (!fwObject) { - goto loser; - } - *phKey = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + fwObject = nssCKFWMechanism_DeriveKey( + fwMechanism, + pMechanism, + fwSession, + fwBaseKeyObject, + pTemplate, + ulAttributeCount, + &error); - if (CKR_OK == error) { - return CKR_OK; - } + nssCKFWMechanism_Destroy(fwMechanism); + if (!fwObject) { + goto loser; + } + *phKey = nssCKFWInstance_CreateObjectHandle(fwInstance, fwObject, &error); + + if (CKR_OK == error) { + return CKR_OK; + } loser: - /* verify error */ - switch( error ) { - case CKR_ARGUMENTS_BAD: - case CKR_ATTRIBUTE_READ_ONLY: - case CKR_ATTRIBUTE_TYPE_INVALID: - case CKR_ATTRIBUTE_VALUE_INVALID: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_DEVICE_REMOVED: - case CKR_DOMAIN_PARAMS_INVALID: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_KEY_HANDLE_INVALID: - case CKR_KEY_SIZE_RANGE: - case CKR_KEY_TYPE_INCONSISTENT: - case CKR_MECHANISM_INVALID: - case CKR_MECHANISM_PARAM_INVALID: - case CKR_OPERATION_ACTIVE: - case CKR_PIN_EXPIRED: - case CKR_SESSION_CLOSED: - case CKR_SESSION_HANDLE_INVALID: - case CKR_SESSION_READ_ONLY: - case CKR_TEMPLATE_INCOMPLETE: - case CKR_TEMPLATE_INCONSISTENT: - case CKR_TOKEN_WRITE_PROTECTED: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } - return error; + /* verify error */ + switch (error) { + case CKR_ARGUMENTS_BAD: + case CKR_ATTRIBUTE_READ_ONLY: + case CKR_ATTRIBUTE_TYPE_INVALID: + case CKR_ATTRIBUTE_VALUE_INVALID: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_DEVICE_REMOVED: + case CKR_DOMAIN_PARAMS_INVALID: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_KEY_HANDLE_INVALID: + case CKR_KEY_SIZE_RANGE: + case CKR_KEY_TYPE_INCONSISTENT: + case CKR_MECHANISM_INVALID: + case CKR_MECHANISM_PARAM_INVALID: + case CKR_OPERATION_ACTIVE: + case CKR_PIN_EXPIRED: + case CKR_SESSION_CLOSED: + case CKR_SESSION_HANDLE_INVALID: + case CKR_SESSION_READ_ONLY: + case CKR_TEMPLATE_INCOMPLETE: + case CKR_TEMPLATE_INCONSISTENT: + case CKR_TOKEN_WRITE_PROTECTED: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } + return error; } /* @@ -5492,76 +5391,74 @@ loser: * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_SeedRandom -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSeed, - CK_ULONG ulSeedLen -) +NSSCKFWC_SeedRandom( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSeed, + CK_ULONG ulSeedLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSItem seed; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSItem seed; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( (CK_BYTE_PTR)CK_NULL_PTR == pSeed ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_BYTE_PTR)CK_NULL_PTR == pSeed) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* We could read through the buffer in a Purify trap */ + /* We could read through the buffer in a Purify trap */ - seed.size = (PRUint32)ulSeedLen; - seed.data = (void *)pSeed; + seed.size = (PRUint32)ulSeedLen; + seed.data = (void *)pSeed; - error = nssCKFWSession_SeedRandom(fwSession, &seed); + error = nssCKFWSession_SeedRandom(fwSession, &seed); - if( CKR_OK != error ) { - goto loser; - } + if (CKR_OK != error) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_ACTIVE: - case CKR_RANDOM_SEED_NOT_SUPPORTED: - case CKR_RANDOM_NO_RNG: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_ACTIVE: + case CKR_RANDOM_SEED_NOT_SUPPORTED: + case CKR_RANDOM_NO_RNG: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -5569,78 +5466,76 @@ NSSCKFWC_SeedRandom * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GenerateRandom -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pRandomData, - CK_ULONG ulRandomLen -) +NSSCKFWC_GenerateRandom( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pRandomData, + CK_ULONG ulRandomLen) { - CK_RV error = CKR_OK; - NSSCKFWSession *fwSession; - NSSItem buffer; + CK_RV error = CKR_OK; + NSSCKFWSession *fwSession; + NSSItem buffer; - if (!fwInstance) { - error = CKR_CRYPTOKI_NOT_INITIALIZED; - goto loser; - } + if (!fwInstance) { + error = CKR_CRYPTOKI_NOT_INITIALIZED; + goto loser; + } - fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); - if (!fwSession) { - error = CKR_SESSION_HANDLE_INVALID; - goto loser; - } + fwSession = nssCKFWInstance_ResolveSessionHandle(fwInstance, hSession); + if (!fwSession) { + error = CKR_SESSION_HANDLE_INVALID; + goto loser; + } - if( (CK_BYTE_PTR)CK_NULL_PTR == pRandomData ) { - error = CKR_ARGUMENTS_BAD; - goto loser; - } + if ((CK_BYTE_PTR)CK_NULL_PTR == pRandomData) { + error = CKR_ARGUMENTS_BAD; + goto loser; + } - /* + /* * A purify error here indicates caller error. */ - (void)nsslibc_memset(pRandomData, 0, ulRandomLen); + (void)nsslibc_memset(pRandomData, 0, ulRandomLen); - buffer.size = (PRUint32)ulRandomLen; - buffer.data = (void *)pRandomData; + buffer.size = (PRUint32)ulRandomLen; + buffer.data = (void *)pRandomData; - error = nssCKFWSession_GetRandom(fwSession, &buffer); + error = nssCKFWSession_GetRandom(fwSession, &buffer); - if( CKR_OK != error ) { - goto loser; - } + if (CKR_OK != error) { + goto loser; + } - return CKR_OK; + return CKR_OK; - loser: - switch( error ) { - case CKR_SESSION_CLOSED: - /* destroy session? */ - break; - case CKR_DEVICE_REMOVED: - /* (void)nssCKFWToken_Destroy(fwToken); */ - break; - case CKR_ARGUMENTS_BAD: - case CKR_CRYPTOKI_NOT_INITIALIZED: - case CKR_DEVICE_ERROR: - case CKR_DEVICE_MEMORY: - case CKR_FUNCTION_CANCELED: - case CKR_FUNCTION_FAILED: - case CKR_GENERAL_ERROR: - case CKR_HOST_MEMORY: - case CKR_OPERATION_ACTIVE: - case CKR_RANDOM_NO_RNG: - case CKR_SESSION_HANDLE_INVALID: - case CKR_USER_NOT_LOGGED_IN: - break; - default: - case CKR_OK: - error = CKR_GENERAL_ERROR; - break; - } +loser: + switch (error) { + case CKR_SESSION_CLOSED: + /* destroy session? */ + break; + case CKR_DEVICE_REMOVED: + /* (void)nssCKFWToken_Destroy(fwToken); */ + break; + case CKR_ARGUMENTS_BAD: + case CKR_CRYPTOKI_NOT_INITIALIZED: + case CKR_DEVICE_ERROR: + case CKR_DEVICE_MEMORY: + case CKR_FUNCTION_CANCELED: + case CKR_FUNCTION_FAILED: + case CKR_GENERAL_ERROR: + case CKR_HOST_MEMORY: + case CKR_OPERATION_ACTIVE: + case CKR_RANDOM_NO_RNG: + case CKR_SESSION_HANDLE_INVALID: + case CKR_USER_NOT_LOGGED_IN: + break; + default: + case CKR_OK: + error = CKR_GENERAL_ERROR; + break; + } - return error; + return error; } /* @@ -5648,13 +5543,11 @@ NSSCKFWC_GenerateRandom * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_GetFunctionStatus -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -) +NSSCKFWC_GetFunctionStatus( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession) { - return CKR_FUNCTION_NOT_PARALLEL; + return CKR_FUNCTION_NOT_PARALLEL; } /* @@ -5662,11 +5555,9 @@ NSSCKFWC_GetFunctionStatus * */ NSS_IMPLEMENT CK_RV -NSSCKFWC_CancelFunction -( - NSSCKFWInstance *fwInstance, - CK_SESSION_HANDLE hSession -) +NSSCKFWC_CancelFunction( + NSSCKFWInstance *fwInstance, + CK_SESSION_HANDLE hSession) { - return CKR_FUNCTION_NOT_PARALLEL; + return CKR_FUNCTION_NOT_PARALLEL; } diff --git a/security/nss/lib/crmf/asn1cmn.c b/security/nss/lib/crmf/asn1cmn.c index af86670663d9..6cf469fb4cda 100644 --- a/security/nss/lib/crmf/asn1cmn.c +++ b/security/nss/lib/crmf/asn1cmn.c @@ -11,94 +11,94 @@ SEC_ASN1_MKSUB(SEC_IntegerTemplate) SEC_ASN1_MKSUB(SEC_SignedCertificateTemplate) static const SEC_ASN1Template CMMFCertResponseTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFCertResponse)}, - { SEC_ASN1_INTEGER, offsetof(CMMFCertResponse, certReqId)}, - { SEC_ASN1_INLINE, offsetof(CMMFCertResponse, status), - CMMFPKIStatusInfoTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_POINTER, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFCertResponse) }, + { SEC_ASN1_INTEGER, offsetof(CMMFCertResponse, certReqId) }, + { SEC_ASN1_INLINE, offsetof(CMMFCertResponse, status), + CMMFPKIStatusInfoTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_POINTER, offsetof(CMMFCertResponse, certifiedKeyPair), - CMMFCertifiedKeyPairTemplate}, + CMMFCertifiedKeyPairTemplate }, { 0 } }; static const SEC_ASN1Template CMMFCertOrEncCertTemplate[] = { - { SEC_ASN1_ANY, offsetof(CMMFCertOrEncCert, derValue), NULL, - sizeof(CMMFCertOrEncCert)}, + { SEC_ASN1_ANY, offsetof(CMMFCertOrEncCert, derValue), NULL, + sizeof(CMMFCertOrEncCert) }, { 0 } }; const SEC_ASN1Template CMMFCertifiedKeyPairTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFCertifiedKeyPair)}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFCertifiedKeyPair) }, { SEC_ASN1_INLINE, offsetof(CMMFCertifiedKeyPair, certOrEncCert), CMMFCertOrEncCertTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | 0, offsetof(CMMFCertifiedKeyPair, privateKey), - CRMFEncryptedValueTemplate}, - { SEC_ASN1_NO_STREAM | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 1, - offsetof (CMMFCertifiedKeyPair, derPublicationInfo), + CRMFEncryptedValueTemplate }, + { SEC_ASN1_NO_STREAM | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_XTRN | 1, + offsetof(CMMFCertifiedKeyPair, derPublicationInfo), SEC_ASN1_SUB(SEC_AnyTemplate) }, { 0 } }; const SEC_ASN1Template CMMFPKIStatusInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFPKIStatusInfo)}, - { SEC_ASN1_INTEGER, offsetof(CMMFPKIStatusInfo, status)}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_UTF8_STRING, - offsetof(CMMFPKIStatusInfo, statusString)}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_BIT_STRING, - offsetof(CMMFPKIStatusInfo, failInfo)}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFPKIStatusInfo) }, + { SEC_ASN1_INTEGER, offsetof(CMMFPKIStatusInfo, status) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_UTF8_STRING, + offsetof(CMMFPKIStatusInfo, statusString) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_BIT_STRING, + offsetof(CMMFPKIStatusInfo, failInfo) }, { 0 } }; const SEC_ASN1Template CMMFSequenceOfCertsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF| SEC_ASN1_XTRN, 0, - SEC_ASN1_SUB(SEC_SignedCertificateTemplate)} + { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN, 0, + SEC_ASN1_SUB(SEC_SignedCertificateTemplate) } }; const SEC_ASN1Template CMMFRandTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFRand)}, - { SEC_ASN1_INTEGER, offsetof(CMMFRand, integer)}, - { SEC_ASN1_OCTET_STRING, offsetof(CMMFRand, senderHash)}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFRand) }, + { SEC_ASN1_INTEGER, offsetof(CMMFRand, integer) }, + { SEC_ASN1_OCTET_STRING, offsetof(CMMFRand, senderHash) }, { 0 } }; const SEC_ASN1Template CMMFPOPODecKeyRespContentTemplate[] = { - { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN, + { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_XTRN, offsetof(CMMFPOPODecKeyRespContent, responses), - SEC_ASN1_SUB(SEC_IntegerTemplate), - sizeof(CMMFPOPODecKeyRespContent)}, + SEC_ASN1_SUB(SEC_IntegerTemplate), + sizeof(CMMFPOPODecKeyRespContent) }, { 0 } }; const SEC_ASN1Template CMMFCertOrEncCertEncryptedCertTemplate[] = { { SEC_ASN1_CONTEXT_SPECIFIC | 1, 0, - CRMFEncryptedValueTemplate}, + CRMFEncryptedValueTemplate }, { 0 } }; const SEC_ASN1Template CMMFCertOrEncCertCertificateTemplate[] = { { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, 0, - SEC_ASN1_SUB(SEC_SignedCertificateTemplate)}, + SEC_ASN1_SUB(SEC_SignedCertificateTemplate) }, { 0 } }; const SEC_ASN1Template CMMFCertRepContentTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFCertRepContent)}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFCertRepContent) }, { SEC_ASN1_CONSTRUCTED | SEC_ASN1_OPTIONAL | - SEC_ASN1_CONTEXT_SPECIFIC | 1, + SEC_ASN1_CONTEXT_SPECIFIC | 1, offsetof(CMMFCertRepContent, caPubs), CMMFSequenceOfCertsTemplate }, { SEC_ASN1_SEQUENCE_OF, offsetof(CMMFCertRepContent, response), - CMMFCertResponseTemplate}, + CMMFCertResponseTemplate }, { 0 } }; static const SEC_ASN1Template CMMFChallengeTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFChallenge)}, - { SEC_ASN1_POINTER | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFChallenge) }, + { SEC_ASN1_POINTER | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN, offsetof(CMMFChallenge, owf), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_OCTET_STRING, offsetof(CMMFChallenge, witness) }, @@ -109,27 +109,27 @@ static const SEC_ASN1Template CMMFChallengeTemplate[] = { }; const SEC_ASN1Template CMMFPOPODecKeyChallContentTemplate[] = { - { SEC_ASN1_SEQUENCE_OF,offsetof(CMMFPOPODecKeyChallContent, challenges), + { SEC_ASN1_SEQUENCE_OF, offsetof(CMMFPOPODecKeyChallContent, challenges), CMMFChallengeTemplate, sizeof(CMMFPOPODecKeyChallContent) }, { 0 } }; SECStatus -cmmf_decode_process_cert_response(PLArenaPool *poolp, - CERTCertDBHandle *db, - CMMFCertResponse *inCertResp) +cmmf_decode_process_cert_response(PLArenaPool *poolp, + CERTCertDBHandle *db, + CMMFCertResponse *inCertResp) { SECStatus rv = SECSuccess; - + if (inCertResp->certifiedKeyPair != NULL) { - rv = cmmf_decode_process_certified_key_pair(poolp, - db, - inCertResp->certifiedKeyPair); + rv = cmmf_decode_process_certified_key_pair(poolp, + db, + inCertResp->certifiedKeyPair); } return rv; } -static CERTCertificate* +static CERTCertificate * cmmf_DecodeDERCertificate(CERTCertDBHandle *db, SECItem *derCert) { CERTCertificate *newCert; @@ -141,80 +141,76 @@ cmmf_DecodeDERCertificate(CERTCertDBHandle *db, SECItem *derCert) static CMMFCertOrEncCertChoice cmmf_get_certorenccertchoice_from_der(SECItem *der) { - CMMFCertOrEncCertChoice retChoice; + CMMFCertOrEncCertChoice retChoice; - switch(der->data[0] & 0x0f) { - case 0: - retChoice = cmmfCertificate; - break; - case 1: - retChoice = cmmfEncryptedCert; - break; - default: - retChoice = cmmfNoCertOrEncCert; - break; + switch (der->data[0] & 0x0f) { + case 0: + retChoice = cmmfCertificate; + break; + case 1: + retChoice = cmmfEncryptedCert; + break; + default: + retChoice = cmmfNoCertOrEncCert; + break; } return retChoice; } static SECStatus -cmmf_decode_process_certorenccert(PLArenaPool *poolp, - CERTCertDBHandle *db, - CMMFCertOrEncCert *inCertOrEncCert) +cmmf_decode_process_certorenccert(PLArenaPool *poolp, + CERTCertDBHandle *db, + CMMFCertOrEncCert *inCertOrEncCert) { SECStatus rv = SECSuccess; - inCertOrEncCert->choice = + inCertOrEncCert->choice = cmmf_get_certorenccertchoice_from_der(&inCertOrEncCert->derValue); switch (inCertOrEncCert->choice) { - case cmmfCertificate: - { - /* The DER has implicit tagging, so we gotta switch it to - * un-tagged in order for the ASN1 parser to understand it. - * Saving the bits that were changed. - */ - inCertOrEncCert->derValue.data[0] = 0x30; - inCertOrEncCert->cert.certificate = - cmmf_DecodeDERCertificate(db, &inCertOrEncCert->derValue); - if (inCertOrEncCert->cert.certificate == NULL) { - rv = SECFailure; - } - - } - break; - case cmmfEncryptedCert: - PORT_Assert(poolp); - if (!poolp) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - break; - } - inCertOrEncCert->cert.encryptedCert = - PORT_ArenaZNew(poolp, CRMFEncryptedValue); - if (inCertOrEncCert->cert.encryptedCert == NULL) { - rv = SECFailure; - break; - } - rv = SEC_ASN1Decode(poolp, inCertOrEncCert->cert.encryptedCert, - CMMFCertOrEncCertEncryptedCertTemplate, - (const char*)inCertOrEncCert->derValue.data, - inCertOrEncCert->derValue.len); - break; - default: - rv = SECFailure; + case cmmfCertificate: { + /* The DER has implicit tagging, so we gotta switch it to + * un-tagged in order for the ASN1 parser to understand it. + * Saving the bits that were changed. + */ + inCertOrEncCert->derValue.data[0] = 0x30; + inCertOrEncCert->cert.certificate = + cmmf_DecodeDERCertificate(db, &inCertOrEncCert->derValue); + if (inCertOrEncCert->cert.certificate == NULL) { + rv = SECFailure; + } + + } break; + case cmmfEncryptedCert: + PORT_Assert(poolp); + if (!poolp) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + break; + } + inCertOrEncCert->cert.encryptedCert = + PORT_ArenaZNew(poolp, CRMFEncryptedValue); + if (inCertOrEncCert->cert.encryptedCert == NULL) { + rv = SECFailure; + break; + } + rv = SEC_ASN1Decode(poolp, inCertOrEncCert->cert.encryptedCert, + CMMFCertOrEncCertEncryptedCertTemplate, + (const char *)inCertOrEncCert->derValue.data, + inCertOrEncCert->derValue.len); + break; + default: + rv = SECFailure; } return rv; } -SECStatus -cmmf_decode_process_certified_key_pair(PLArenaPool *poolp, - CERTCertDBHandle *db, - CMMFCertifiedKeyPair *inCertKeyPair) +SECStatus +cmmf_decode_process_certified_key_pair(PLArenaPool *poolp, + CERTCertDBHandle *db, + CMMFCertifiedKeyPair *inCertKeyPair) { - return cmmf_decode_process_certorenccert (poolp, - db, - &inCertKeyPair->certOrEncCert); + return cmmf_decode_process_certorenccert(poolp, + db, + &inCertKeyPair->certOrEncCert); } - - diff --git a/security/nss/lib/crmf/challcli.c b/security/nss/lib/crmf/challcli.c index eaff34958394..f2e68594af71 100644 --- a/security/nss/lib/crmf/challcli.c +++ b/security/nss/lib/crmf/challcli.c @@ -10,12 +10,12 @@ #include "secder.h" #include "sechash.h" -CMMFPOPODecKeyChallContent* +CMMFPOPODecKeyChallContent * CMMF_CreatePOPODecKeyChallContentFromDER(const char *buf, long len) { - PLArenaPool *poolp; + PLArenaPool *poolp; CMMFPOPODecKeyChallContent *challContent; - SECStatus rv; + SECStatus rv; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { @@ -26,19 +26,19 @@ CMMF_CreatePOPODecKeyChallContentFromDER(const char *buf, long len) goto loser; } challContent->poolp = poolp; - rv = SEC_ASN1Decode(poolp, challContent, - CMMFPOPODecKeyChallContentTemplate, buf, len); + rv = SEC_ASN1Decode(poolp, challContent, + CMMFPOPODecKeyChallContentTemplate, buf, len); if (rv != SECSuccess) { goto loser; } if (challContent->challenges) { - while (challContent->challenges[challContent->numChallenges] != NULL) { - challContent->numChallenges++; - } - challContent->numAllocated = challContent->numChallenges; + while (challContent->challenges[challContent->numChallenges] != NULL) { + challContent->numChallenges++; + } + challContent->numAllocated = challContent->numChallenges; } return challContent; - loser: +loser: if (poolp != NULL) { PORT_FreeArena(poolp, PR_FALSE); } @@ -46,8 +46,7 @@ CMMF_CreatePOPODecKeyChallContentFromDER(const char *buf, long len) } int -CMMF_POPODecKeyChallContentGetNumChallenges - (CMMFPOPODecKeyChallContent *inKeyChallCont) +CMMF_POPODecKeyChallContentGetNumChallenges(CMMFPOPODecKeyChallContent *inKeyChallCont) { PORT_Assert(inKeyChallCont != NULL); if (inKeyChallCont == NULL) { @@ -56,51 +55,50 @@ CMMF_POPODecKeyChallContentGetNumChallenges return inKeyChallCont->numChallenges; } -SECItem* -CMMF_POPODecKeyChallContentGetPublicValue - (CMMFPOPODecKeyChallContent *inKeyChallCont, - int inIndex) +SECItem * +CMMF_POPODecKeyChallContentGetPublicValue(CMMFPOPODecKeyChallContent *inKeyChallCont, + int inIndex) { PORT_Assert(inKeyChallCont != NULL); - if (inKeyChallCont == NULL || (inIndex > inKeyChallCont->numChallenges-1)|| - inIndex < 0) { + if (inKeyChallCont == NULL || (inIndex > inKeyChallCont->numChallenges - 1) || + inIndex < 0) { return NULL; } return SECITEM_DupItem(&inKeyChallCont->challenges[inIndex]->key); } -static SECAlgorithmID* -cmmf_get_owf(CMMFPOPODecKeyChallContent *inChalCont, - int inIndex) +static SECAlgorithmID * +cmmf_get_owf(CMMFPOPODecKeyChallContent *inChalCont, + int inIndex) { - int i; - - for (i=inIndex; i >= 0; i--) { - if (inChalCont->challenges[i]->owf != NULL) { - return inChalCont->challenges[i]->owf; - } - } - return NULL; + int i; + + for (i = inIndex; i >= 0; i--) { + if (inChalCont->challenges[i]->owf != NULL) { + return inChalCont->challenges[i]->owf; + } + } + return NULL; } -SECStatus +SECStatus CMMF_POPODecKeyChallContDecryptChallenge(CMMFPOPODecKeyChallContent *inChalCont, - int inIndex, - SECKEYPrivateKey *inPrivKey) + int inIndex, + SECKEYPrivateKey *inPrivKey) { - CMMFChallenge *challenge; - SECItem *decryptedRand=NULL; - PLArenaPool *poolp = NULL; + CMMFChallenge *challenge; + SECItem *decryptedRand = NULL; + PLArenaPool *poolp = NULL; SECAlgorithmID *owf; - SECStatus rv = SECFailure; - SECOidTag tag; - CMMFRand randStr; - SECItem hashItem; - unsigned char hash[HASH_LENGTH_MAX]; + SECStatus rv = SECFailure; + SECOidTag tag; + CMMFRand randStr; + SECItem hashItem; + unsigned char hash[HASH_LENGTH_MAX]; PORT_Assert(inChalCont != NULL && inPrivKey != NULL); - if (inChalCont == NULL || inIndex <0 || inIndex > inChalCont->numChallenges - || inPrivKey == NULL){ + if (inChalCont == NULL || inIndex < 0 || inIndex > inChalCont->numChallenges || + inPrivKey == NULL) { return SECFailure; } @@ -114,21 +112,21 @@ CMMF_POPODecKeyChallContDecryptChallenge(CMMFPOPODecKeyChallContent *inChalCont, if (decryptedRand == NULL) { goto loser; } - rv = PK11_PrivDecryptPKCS1(inPrivKey, decryptedRand->data, - &decryptedRand->len, decryptedRand->len, - challenge->challenge.data, challenge->challenge.len); + rv = PK11_PrivDecryptPKCS1(inPrivKey, decryptedRand->data, + &decryptedRand->len, decryptedRand->len, + challenge->challenge.data, challenge->challenge.len); if (rv != SECSuccess) { goto loser; } rv = SEC_ASN1DecodeItem(poolp, &randStr, CMMFRandTemplate, - decryptedRand); + decryptedRand); if (rv != SECSuccess) { goto loser; } rv = SECFailure; /* Just so that when we do go to loser, - * I won't have to set it again. - */ + * I won't have to set it again. + */ owf = cmmf_get_owf(inChalCont, inIndex); if (owf == NULL) { /* No hashing algorithm came with the challenges. Can't verify */ @@ -138,7 +136,7 @@ CMMF_POPODecKeyChallContDecryptChallenge(CMMFPOPODecKeyChallContent *inChalCont, tag = SECOID_FindOIDTag(&owf->algorithm); hashItem.len = HASH_ResultLenByOidTag(tag); if (!hashItem.len) - goto loser; /* error code has been set */ + goto loser; /* error code has been set */ rv = PK11_HashBuf(tag, hash, randStr.integer.data, randStr.integer.len); if (rv != SECSuccess) { @@ -147,46 +145,45 @@ CMMF_POPODecKeyChallContDecryptChallenge(CMMFPOPODecKeyChallContent *inChalCont, hashItem.data = hash; if (SECITEM_CompareItem(&hashItem, &challenge->witness) != SECEqual) { /* The hash for the data we decrypted doesn't match the hash provided - * in the challenge. Bail out. - */ - PORT_SetError(SEC_ERROR_BAD_DATA); + * in the challenge. Bail out. + */ + PORT_SetError(SEC_ERROR_BAD_DATA); rv = SECFailure; - goto loser; + goto loser; } - rv = PK11_HashBuf(tag, hash, challenge->senderDER.data, - challenge->senderDER.len); + rv = PK11_HashBuf(tag, hash, challenge->senderDER.data, + challenge->senderDER.len); if (rv != SECSuccess) { goto loser; } if (SECITEM_CompareItem(&hashItem, &randStr.senderHash) != SECEqual) { /* The hash for the data we decrypted doesn't match the hash provided - * in the challenge. Bail out. - */ - PORT_SetError(SEC_ERROR_BAD_DATA); + * in the challenge. Bail out. + */ + PORT_SetError(SEC_ERROR_BAD_DATA); rv = SECFailure; - goto loser; + goto loser; } /* All of the hashes have verified, so we can now store the integer away.*/ rv = SECITEM_CopyItem(inChalCont->poolp, &challenge->randomNumber, - &randStr.integer); - loser: + &randStr.integer); +loser: if (poolp) { - PORT_FreeArena(poolp, PR_FALSE); + PORT_FreeArena(poolp, PR_FALSE); } return rv; } SECStatus -CMMF_POPODecKeyChallContentGetRandomNumber - (CMMFPOPODecKeyChallContent *inKeyChallCont, - int inIndex, - long *inDest) +CMMF_POPODecKeyChallContentGetRandomNumber(CMMFPOPODecKeyChallContent *inKeyChallCont, + int inIndex, + long *inDest) { CMMFChallenge *challenge; - + PORT_Assert(inKeyChallCont != NULL); - if (inKeyChallCont == NULL || inIndex > 0 || inIndex >= - inKeyChallCont->numChallenges) { + if (inKeyChallCont == NULL || inIndex > 0 || inIndex >= + inKeyChallCont->numChallenges) { return SECFailure; } challenge = inKeyChallCont->challenges[inIndex]; @@ -198,16 +195,16 @@ CMMF_POPODecKeyChallContentGetRandomNumber return (*inDest == -1) ? SECFailure : SECSuccess; } -SECStatus -CMMF_EncodePOPODecKeyRespContent(long *inDecodedRand, - int inNumRand, - CRMFEncoderOutputCallback inCallback, - void *inArg) +SECStatus +CMMF_EncodePOPODecKeyRespContent(long *inDecodedRand, + int inNumRand, + CRMFEncoderOutputCallback inCallback, + void *inArg) { PLArenaPool *poolp; CMMFPOPODecKeyRespContent *response; SECItem *currItem; - SECStatus rv=SECFailure; + SECStatus rv = SECFailure; int i; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); @@ -218,23 +215,23 @@ CMMF_EncodePOPODecKeyRespContent(long *inDecodedRand, if (response == NULL) { goto loser; } - response->responses = PORT_ArenaZNewArray(poolp, SECItem*, inNumRand+1); + response->responses = PORT_ArenaZNewArray(poolp, SECItem *, inNumRand + 1); if (response->responses == NULL) { goto loser; } - for (i=0; iresponses[i] = PORT_ArenaZNew(poolp,SECItem); - if (currItem == NULL) { - goto loser; - } - currItem = SEC_ASN1EncodeInteger(poolp, currItem, inDecodedRand[i]); - if (currItem == NULL) { - goto loser; - } + for (i = 0; i < inNumRand; i++) { + currItem = response->responses[i] = PORT_ArenaZNew(poolp, SECItem); + if (currItem == NULL) { + goto loser; + } + currItem = SEC_ASN1EncodeInteger(poolp, currItem, inDecodedRand[i]); + if (currItem == NULL) { + goto loser; + } } rv = cmmf_user_encode(response, inCallback, inArg, - CMMFPOPODecKeyRespContentTemplate); - loser: + CMMFPOPODecKeyRespContentTemplate); +loser: if (poolp != NULL) { PORT_FreeArena(poolp, PR_FALSE); } diff --git a/security/nss/lib/crmf/cmmf.h b/security/nss/lib/crmf/cmmf.h index b5b29a6974e9..1e39a8d2d245 100644 --- a/security/nss/lib/crmf/cmmf.h +++ b/security/nss/lib/crmf/cmmf.h @@ -6,7 +6,7 @@ #ifndef _CMMF_H_ #define _CMMF_H_ /* - * These are the functions exported by the security library for + * These are the functions exported by the security library for * implementing Certificate Management Message Formats (CMMF). * * This API is designed against July 1998 CMMF draft. Please read this @@ -25,20 +25,20 @@ SEC_BEGIN_PROTOS * INPUTS: * NONE * NOTES: - * This function will create an empty CMMFCertRepContent Structure. + * This function will create an empty CMMFCertRepContent Structure. * The client of the library must set the CMMFCertResponses. * Call CMMF_CertRepContentSetCertResponse to accomplish this task. - * If the client of the library also wants to include the chain of - * CA certs required to make the certificates in CMMFCertResponse valid, + * If the client of the library also wants to include the chain of + * CA certs required to make the certificates in CMMFCertResponse valid, * then the user must also set the caPubs field of CMMFCertRepContent. * Call CMMF_CertRepContentSetCAPubs to accomplish this. After setting - * the desired fields, the user can then call CMMF_EncodeCertRepContent + * the desired fields, the user can then call CMMF_EncodeCertRepContent * to DER-encode the CertRepContent. * RETURN: - * A pointer to the CMMFCertRepContent. A NULL return value indicates + * A pointer to the CMMFCertRepContent. A NULL return value indicates * an error in allocating memory or failure to initialize the structure. */ -extern CMMFCertRepContent* CMMF_CreateCertRepContent(void); +extern CMMFCertRepContent *CMMF_CreateCertRepContent(void); /* * FUNCTION: CMMF_CreateCertRepContentFromDER @@ -46,24 +46,24 @@ extern CMMFCertRepContent* CMMF_CreateCertRepContent(void); * db * The certificate database where the certificates will be placed. * The certificates will be placed in the temporary database associated - * with the handle. + * with the handle. * buf * A buffer to the DER-encoded CMMFCertRepContent * len * The length in bytes of the buffer 'buf' * NOTES: * This function passes the buffer to the ASN1 decoder and creates a - * CMMFCertRepContent structure. The user must call + * CMMFCertRepContent structure. The user must call * CMMF_DestroyCertRepContent after the return value is no longer needed. * * RETURN: * A pointer to the CMMFCertRepContent structure. A NULL return * value indicates the library was unable to parse the DER. */ -extern CMMFCertRepContent* - CMMF_CreateCertRepContentFromDER(CERTCertDBHandle *db, - const char *buf, - long len); +extern CMMFCertRepContent * +CMMF_CreateCertRepContentFromDER(CERTCertDBHandle *db, + const char *buf, + long len); /* * FUNCTION: CMMF_CreateCertResponse @@ -73,17 +73,17 @@ extern CMMFCertRepContent* * NOTES: * This creates a CMMFCertResponse. This response should correspond * to a request that was received via CRMF. From the CRMF message you - * can get the Request Id to pass in as inCertReqId, in essence binding + * can get the Request Id to pass in as inCertReqId, in essence binding * a CMRFCertRequest message to the CMMFCertResponse created by this * function. If no requuest id is associated with the response to create * then the user should pass in -1 for 'inCertReqId'. * * RETURN: - * A pointer to the new CMMFCertResponse corresponding to the request id - * passed in. A NULL return value indicates an error while trying to + * A pointer to the new CMMFCertResponse corresponding to the request id + * passed in. A NULL return value indicates an error while trying to * create the CMMFCertResponse. */ -extern CMMFCertResponse* CMMF_CreateCertResponse(long inCertReqId); +extern CMMFCertResponse *CMMF_CreateCertResponse(long inCertReqId); /* * FUNCTION: CMMF_CreateKeyRecRepContent @@ -91,7 +91,7 @@ extern CMMFCertResponse* CMMF_CreateCertResponse(long inCertReqId); * NONE * NOTES: * This function creates a new empty CMMFKeyRecRepContent structure. - * At the very minimum, the user must call + * At the very minimum, the user must call * CMMF_KeyRecRepContentSetPKIStatusInfoStatus field to have an * encodable structure. Depending on what the response is, the user may * have to set other fields as well to properly build up the structure so @@ -111,26 +111,26 @@ extern CMMFKeyRecRepContent *CMMF_CreateKeyRecRepContent(void); * FUNCTION: CMMF_CreateKeyRecRepContentFromDER * INPUTS: * db - * The handle for the certificate database where the decoded + * The handle for the certificate database where the decoded * certificates will be placed. The decoded certificates will - * be placed in the temporary database associated with the + * be placed in the temporary database associated with the * handle. * buf * A buffer contatining the DER-encoded CMMFKeyRecRepContent * len * The length in bytes of the buffer 'buf' * NOTES - * This function passes the buffer to the ASN1 decoder and creates a + * This function passes the buffer to the ASN1 decoder and creates a * CMMFKeyRecRepContent structure. * * RETURN: * A pointer to the CMMFKeyRecRepContent structure. A NULL return * value indicates the library was unable to parse the DER. */ -extern CMMFKeyRecRepContent* - CMMF_CreateKeyRecRepContentFromDER(CERTCertDBHandle *db, - const char *buf, - long len); +extern CMMFKeyRecRepContent * +CMMF_CreateKeyRecRepContentFromDER(CERTCertDBHandle *db, + const char *buf, + long len); /* * FUNCTION: CMMF_CreatePOPODecKeyChallContent @@ -139,18 +139,18 @@ extern CMMFKeyRecRepContent* * NOTES: * This function creates an empty CMMFPOPODecKeyChallContent. The user * must add the challenges individually specifying the random number to - * be used and the public key to be used when creating each individual - * challenge. User can accomplish this by calling the function + * be used and the public key to be used when creating each individual + * challenge. User can accomplish this by calling the function * CMMF_POPODecKeyChallContentSetNextChallenge. * RETURN: * A pointer to a CMMFPOPODecKeyChallContent structure. Ther user can * then call CMMF_EncodePOPODecKeyChallContent passing in the return - * value from this function after setting all of the challenges. A - * return value of NULL indicates an error while creating the + * value from this function after setting all of the challenges. A + * return value of NULL indicates an error while creating the * CMMFPOPODecKeyChallContent structure. */ -extern CMMFPOPODecKeyChallContent* - CMMF_CreatePOPODecKeyChallContent(void); +extern CMMFPOPODecKeyChallContent * +CMMF_CreatePOPODecKeyChallContent(void); /* * FUNCTION: CMMF_CreatePOPODecKeyChallContentFromDER @@ -161,14 +161,14 @@ extern CMMFPOPODecKeyChallContent* * The length in bytes of the buffer 'buf' * NOTES: * This function passes the buffer to the ASN1 decoder and creates a - * CMMFPOPODecKeyChallContent structure. + * CMMFPOPODecKeyChallContent structure. * * RETURN: * A pointer to the CMMFPOPODecKeyChallContent structure. A NULL return * value indicates the library was unable to parse the DER. */ -extern CMMFPOPODecKeyChallContent* - CMMF_CreatePOPODecKeyChallContentFromDER(const char *buf, long len); +extern CMMFPOPODecKeyChallContent * +CMMF_CreatePOPODecKeyChallContentFromDER(const char *buf, long len); /* * FUNCTION: CMMF_CreatePOPODecKeyRespContentFromDER @@ -178,15 +178,15 @@ extern CMMFPOPODecKeyChallContent* * len * The length in bytes of the buffer 'buf' * NOTES - * This function passes the buffer to the ASN1 decoder and creates a + * This function passes the buffer to the ASN1 decoder and creates a * CMMFPOPODecKeyRespContent structure. * * RETURN: * A pointer to the CMMFPOPODecKeyRespContent structure. A NULL return * value indicates the library was unable to parse the DER. */ -extern CMMFPOPODecKeyRespContent* - CMMF_CreatePOPODecKeyRespContentFromDER(const char *buf, long len); +extern CMMFPOPODecKeyRespContent * +CMMF_CreatePOPODecKeyRespContentFromDER(const char *buf, long len); /************************** Set Functions *************************/ @@ -196,16 +196,16 @@ extern CMMFPOPODecKeyRespContent* * inCertRepContent * The CMMFCertRepContent to operate on. * inCertResponses - * An array of pointers to CMMFCertResponse structures to + * An array of pointers to CMMFCertResponse structures to * add to the CMMFCertRepContent structure. * inNumResponses * The length of the array 'inCertResponses' * NOTES: - * This function will add the CMMFCertResponse structure to the - * CMMFCertRepContent passed in. The CMMFCertResponse field of + * This function will add the CMMFCertResponse structure to the + * CMMFCertRepContent passed in. The CMMFCertResponse field of * CMMFCertRepContent is required, so the client must call this function - * before calling CMMF_EncodeCertRepContent. If the user calls - * CMMF_EncodeCertRepContent before calling this function, + * before calling CMMF_EncodeCertRepContent. If the user calls + * CMMF_EncodeCertRepContent before calling this function, * CMMF_EncodeCertRepContent will fail. * * RETURN: @@ -213,10 +213,10 @@ extern CMMFPOPODecKeyRespContent* * structure was successful. Any other return value indicates an error * while trying to add the CMMFCertResponses. */ -extern SECStatus - CMMF_CertRepContentSetCertResponses(CMMFCertRepContent *inCertRepContent, - CMMFCertResponse **inCertResponses, - int inNumResponses); +extern SECStatus +CMMF_CertRepContentSetCertResponses(CMMFCertRepContent *inCertRepContent, + CMMFCertResponse **inCertResponses, + int inNumResponses); /* * FUNCTION: CMMF_CertRepContentSetCAPubs @@ -228,19 +228,19 @@ extern SECStatus * required to make the issued cert valid. * NOTES: * This function will set the the certificates in the CA chain as part - * of the CMMFCertRepContent. This field is an optional member of the + * of the CMMFCertRepContent. This field is an optional member of the * CMMFCertRepContent structure, so the client is not required to call * this function before calling CMMF_EncodeCertRepContent. * * RETURN: * SECSuccess if adding the 'inCAPubs' to the CERTRepContent was successful. - * Any other return value indicates an error while adding 'inCAPubs' to the + * Any other return value indicates an error while adding 'inCAPubs' to the * CMMFCertRepContent structure. - * + * */ -extern SECStatus - CMMF_CertRepContentSetCAPubs (CMMFCertRepContent *inCertRepContent, - CERTCertList *inCAPubs); +extern SECStatus +CMMF_CertRepContentSetCAPubs(CMMFCertRepContent *inCertRepContent, + CERTCertList *inCAPubs); /* * FUNCTION: CMMF_CertResponseSetPKIStatusInfoStatus @@ -250,7 +250,7 @@ extern SECStatus * inPKIStatus * The value to set for the PKIStatusInfo.status field. * NOTES: - * This function will set the CertResponse.status.status field of + * This function will set the CertResponse.status.status field of * the CMMFCertResponse structure. (View the definition of CertResponse * in the CMMF draft to see exactly which value this talks about.) This * field is a required member of the structure, so the user must call this @@ -260,9 +260,9 @@ extern SECStatus * SECSuccess if setting the field with the passed in value was successful. * Any other return value indicates an error while trying to set the field. */ -extern SECStatus - CMMF_CertResponseSetPKIStatusInfoStatus (CMMFCertResponse *inCertResp, - CMMFPKIStatus inPKIStatus); +extern SECStatus +CMMF_CertResponseSetPKIStatusInfoStatus(CMMFCertResponse *inCertResp, + CMMFPKIStatus inPKIStatus); /* * FUNCTION: CMMF_CertResponseSetCertificate @@ -270,7 +270,7 @@ extern SECStatus * inCertResp * The CMMFCertResponse to operate on. * inCertificate - * The certificate to add to the + * The certificate to add to the * CertResponse.CertifiedKeyPair.certOrEncCert.certificate field. * NOTES: * This function will take the certificate and make it a member of the @@ -282,13 +282,13 @@ extern SECStatus * Any other return value indicates an error in adding the certificate to * the CertResponse. */ -extern SECStatus - CMMF_CertResponseSetCertificate (CMMFCertResponse *inCertResp, - CERTCertificate *inCertificate); +extern SECStatus +CMMF_CertResponseSetCertificate(CMMFCertResponse *inCertResp, + CERTCertificate *inCertificate); /* * FUNCTION: CMMF_KeyRecRepContentSetPKIStatusInfoStatus - * INPUTS: + * INPUTS: * inKeyRecRep * The CMMFKeyRecRepContent to operate on. * inPKIStatus @@ -296,17 +296,17 @@ extern SECStatus * NOTES: * This function sets the only required field for the KeyRecRepContent. * In most cases, the user will set this field and other fields of the - * structure to properly create the CMMFKeyRecRepContent structure. + * structure to properly create the CMMFKeyRecRepContent structure. * Refer to the CMMF draft to see which fields need to be set in order * to create the desired CMMFKeyRecRepContent. - * + * * RETURN: * SECSuccess if setting the PKIStatusInfo.status field was successful. * Any other return value indicates an error in setting the field. */ -extern SECStatus +extern SECStatus CMMF_KeyRecRepContentSetPKIStatusInfoStatus(CMMFKeyRecRepContent *inKeyRecRep, - CMMFPKIStatus inPKIStatus); + CMMFPKIStatus inPKIStatus); /* * FUNCTION: CMMF_KeyRecRepContentSetNewSignCert @@ -320,13 +320,13 @@ CMMF_KeyRecRepContentSetPKIStatusInfoStatus(CMMFKeyRecRepContent *inKeyRecRep, * structure. * * RETURN: - * SECSuccess if setting the new signing cert was successful. Any other + * SECSuccess if setting the new signing cert was successful. Any other * return value indicates an error occurred while trying to add the * new signing certificate. */ -extern SECStatus - CMMF_KeyRecRepContentSetNewSignCert(CMMFKeyRecRepContent *inKeyRecRep, - CERTCertificate *inNewSignCert); +extern SECStatus +CMMF_KeyRecRepContentSetNewSignCert(CMMFKeyRecRepContent *inKeyRecRep, + CERTCertificate *inNewSignCert); /* * FUNCTION: CMMF_KeyRecRepContentSetCACerts @@ -334,21 +334,21 @@ extern SECStatus * inKeyRecRep * The CMMFKeyRecRepContent to operate on. * inCACerts - * The list of CA certificates required to construct a valid + * The list of CA certificates required to construct a valid * certificate chain with the certificates that will be returned * to the end user via this KeyRecRepContent. * NOTES: * This function sets the caCerts that are required to form a chain with the - * end entity certificates that are being re-issued in this + * end entity certificates that are being re-issued in this * CMMFKeyRecRepContent structure. * * RETURN: * SECSuccess if adding the caCerts was successful. Any other return value * indicates an error while tring to add the caCerts. */ -extern SECStatus - CMMF_KeyRecRepContentSetCACerts(CMMFKeyRecRepContent *inKeyRecRep, - CERTCertList *inCACerts); +extern SECStatus +CMMF_KeyRecRepContentSetCACerts(CMMFKeyRecRepContent *inKeyRecRep, + CERTCertList *inCACerts); /* * FUNCTION: CMMF_KeyRecRepContentSetCertifiedKeyPair @@ -362,21 +362,21 @@ extern SECStatus * inPubKey * The public key to use for wrapping the private key. * NOTES: - * This function adds another certificate-key pair to the - * CMMFKeyRecRepcontent structure. There may be more than one - * certificate-key pair in the structure, so the user must call this + * This function adds another certificate-key pair to the + * CMMFKeyRecRepcontent structure. There may be more than one + * certificate-key pair in the structure, so the user must call this * function multiple times to add more than one cert-key pair. * * RETURN: * SECSuccess if adding the certified key pair was successful. Any other - * return value indicates an error in adding certified key pair to + * return value indicates an error in adding certified key pair to * CMMFKeyRecRepContent structure. */ -extern SECStatus - CMMF_KeyRecRepContentSetCertifiedKeyPair(CMMFKeyRecRepContent *inKeyRecRep, - CERTCertificate *inCert, - SECKEYPrivateKey *inPrivKey, - SECKEYPublicKey *inPubKey); +extern SECStatus +CMMF_KeyRecRepContentSetCertifiedKeyPair(CMMFKeyRecRepContent *inKeyRecRep, + CERTCertificate *inCert, + SECKEYPrivateKey *inPrivKey, + SECKEYPublicKey *inPubKey); /* * FUNCTION: CMMF_POPODecKeyChallContentSetNextChallenge @@ -392,15 +392,15 @@ extern SECStatus * passwdArg * This value will be passed to the function used for getting a * password. The password for getting a password should be registered - * by calling PK11_SetPasswordFunc before this function is called. - * If no password callback is registered and the library needs to + * by calling PK11_SetPasswordFunc before this function is called. + * If no password callback is registered and the library needs to * authenticate to the slot for any reason, this function will fail. * NOTES: * This function adds a challenge to the end of the list of challenges * contained by 'inDecKeyChall'. Refer to the CMMF draft on how the * the random number passed in and the sender's GeneralName are used * to generate the challenge and witness fields of the challenge. This - * library will use SHA1 as the one-way function for generating the + * library will use SHA1 as the one-way function for generating the * witess field of the challenge. * * RETURN: @@ -409,13 +409,11 @@ extern SECStatus * while trying to generate the challenge. */ extern SECStatus -CMMF_POPODecKeyChallContentSetNextChallenge - (CMMFPOPODecKeyChallContent *inDecKeyChall, - long inRandom, - CERTGeneralName *inSender, - SECKEYPublicKey *inPubKey, - void *passwdArg); - +CMMF_POPODecKeyChallContentSetNextChallenge(CMMFPOPODecKeyChallContent *inDecKeyChall, + long inRandom, + CERTGeneralName *inSender, + SECKEYPublicKey *inPubKey, + void *passwdArg); /************************** Encoding Functions *************************/ @@ -425,30 +423,30 @@ CMMF_POPODecKeyChallContentSetNextChallenge * inCertRepContent * The CMMFCertRepContent to DER-encode. * inCallback - * A callback function that the ASN1 encoder will call whenever it - * wants to write out DER-encoded bytes. Look at the defintion of + * A callback function that the ASN1 encoder will call whenever it + * wants to write out DER-encoded bytes. Look at the defintion of * CRMFEncoderOutputCallback in crmft.h for a description of the * parameters to the function. * inArg * An opaque pointer to a user-supplied argument that will be passed * to the callback funtion whenever the function is called. * NOTES: - * The CMMF library will use the same DER-encoding scheme as the CRMF + * The CMMF library will use the same DER-encoding scheme as the CRMF * library. In other words, when reading CRMF comments that pertain to - * encoding, those comments apply to the CMMF libray as well. + * encoding, those comments apply to the CMMF libray as well. * The callback function will be called multiple times, each time supplying - * the next chunk of DER-encoded bytes. The user must concatenate the + * the next chunk of DER-encoded bytes. The user must concatenate the * output of each successive call to the callback in order to get the * entire DER-encoded CMMFCertRepContent structure. * * RETURN: - * SECSuccess if encoding the CMMFCertRepContent was successful. Any + * SECSuccess if encoding the CMMFCertRepContent was successful. Any * other return value indicates an error while decoding the structure. */ -extern SECStatus - CMMF_EncodeCertRepContent (CMMFCertRepContent *inCertRepContent, - CRMFEncoderOutputCallback inCallback, - void *inArg); +extern SECStatus +CMMF_EncodeCertRepContent(CMMFCertRepContent *inCertRepContent, + CRMFEncoderOutputCallback inCallback, + void *inArg); /* * FUNCTION: CMMF_EncodeKeyRecRepContent @@ -456,30 +454,30 @@ extern SECStatus * inKeyRecRep * The CMMFKeyRepContent to DER-encode. * inCallback - * A callback function that the ASN1 encoder will call whenever it - * wants to write out DER-encoded bytes. Look at the defintion of + * A callback function that the ASN1 encoder will call whenever it + * wants to write out DER-encoded bytes. Look at the defintion of * CRMFEncoderOutputCallback in crmft.h for a description of the * parameters to the function. * inArg * An opaque pointer to a user-supplied argument that will be passed * to the callback funtion whenever the function is called. * NOTES: - * The CMMF library will use the same DER-encoding scheme as the CRMF + * The CMMF library will use the same DER-encoding scheme as the CRMF * library. In other words, when reading CRMF comments that pertain to - * encoding, those comments apply to the CMMF libray as well. + * encoding, those comments apply to the CMMF libray as well. * The callback function will be called multiple times, each time supplying - * the next chunk of DER-encoded bytes. The user must concatenate the + * the next chunk of DER-encoded bytes. The user must concatenate the * output of each successive call to the callback in order to get the * entire DER-encoded CMMFCertRepContent structure. * * RETURN: - * SECSuccess if encoding the CMMFKeyRecRepContent was successful. Any + * SECSuccess if encoding the CMMFKeyRecRepContent was successful. Any * other return value indicates an error while decoding the structure. */ extern SECStatus - CMMF_EncodeKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep, - CRMFEncoderOutputCallback inCallback, - void *inArg); +CMMF_EncodeKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep, + CRMFEncoderOutputCallback inCallback, + void *inArg); /* * FUNCTION: CMMF_EncodePOPODecKeyChallContent @@ -487,19 +485,19 @@ extern SECStatus * inDecKeyChall * The CMMFDecKeyChallContent to operate on. * inCallback - * A callback function that the ASN1 encoder will call whenever it - * wants to write out DER-encoded bytes. Look at the defintion of + * A callback function that the ASN1 encoder will call whenever it + * wants to write out DER-encoded bytes. Look at the defintion of * CRMFEncoderOutputCallback in crmft.h for a description of the * parameters to the function. * inArg * An opaque pointer to a user-supplied argument that will be passed * to the callback function whenever the function is called. * NOTES: - * The CMMF library will use the same DER-encoding scheme as the CRMF + * The CMMF library will use the same DER-encoding scheme as the CRMF * library. In other words, when reading CRMF comments that pertain to - * encoding, those comments apply to the CMMF libray as well. + * encoding, those comments apply to the CMMF libray as well. * The callback function will be called multiple times, each time supplying - * the next chunk of DER-encoded bytes. The user must concatenate the + * the next chunk of DER-encoded bytes. The user must concatenate the * output of each successive call to the callback in order to get the * entire DER-encoded CMMFCertRepContent structure. * The DER will be an encoding of the type POPODecKeyChallContents, which @@ -509,34 +507,34 @@ extern SECStatus * SECSuccess if encoding was successful. Any other return value indicates * an error in trying to encode the Challenges. */ -extern SECStatus +extern SECStatus CMMF_EncodePOPODecKeyChallContent(CMMFPOPODecKeyChallContent *inDecKeyChall, - CRMFEncoderOutputCallback inCallback, - void *inArg); + CRMFEncoderOutputCallback inCallback, + void *inArg); /* * FUNCTION: CMMF_EncodePOPODecKeyRespContent * INPUTS: * inDecodedRand - * An array of integers to encode as the responses to + * An array of integers to encode as the responses to * CMMFPOPODecKeyChallContent. The integers must be in the same order * as the challenges extracted from CMMFPOPODecKeyChallContent. * inNumRand * The number of random integers contained in the array 'inDecodedRand' * inCallback - * A callback function that the ASN1 encoder will call whenever it - * wants to write out DER-encoded bytes. Look at the defintion of + * A callback function that the ASN1 encoder will call whenever it + * wants to write out DER-encoded bytes. Look at the defintion of * CRMFEncoderOutputCallback in crmft.h for a description of the * parameters to the function. * inArg * An opaque pointer to a user-supplied argument that will be passed * to the callback funtion whenever the function is called. * NOTES: - * The CMMF library will use the same DER-encoding scheme as the CRMF + * The CMMF library will use the same DER-encoding scheme as the CRMF * library. In other words, when reading CRMF comments that pertain to - * encoding, those comments apply to the CMMF libray as well. + * encoding, those comments apply to the CMMF libray as well. * The callback function will be called multiple times, each time supplying - * the next chunk of DER-encoded bytes. The user must concatenate the + * the next chunk of DER-encoded bytes. The user must concatenate the * output of each successive call to the callback in order to get the * entire DER-encoded POPODecKeyRespContent. * @@ -544,11 +542,11 @@ CMMF_EncodePOPODecKeyChallContent(CMMFPOPODecKeyChallContent *inDecKeyChall, * SECSuccess if encoding was successful. Any other return value indicates * an error in trying to encode the Challenges. */ -extern SECStatus - CMMF_EncodePOPODecKeyRespContent(long *inDecodedRand, - int inNumRand, - CRMFEncoderOutputCallback inCallback, - void *inArg); +extern SECStatus +CMMF_EncodePOPODecKeyRespContent(long *inDecodedRand, + int inNumRand, + CRMFEncoderOutputCallback inCallback, + void *inArg); /*************** Accessor function ***********************************/ @@ -560,27 +558,26 @@ extern SECStatus * NOTES: * This function will return a copy of the list of certificates that * make up the chain of CA's required to make the cert issued valid. - * The user must call CERT_DestroyCertList on the return value when - * done using the return value. + * The user must call CERT_DestroyCertList on the return value when + * done using the return value. * * Only call this function on a CertRepContent that has been decoded. * The client must call CERT_DestroyCertList when the certificate list - * is no longer needed. + * is no longer needed. * * The certs in the list will not be in the temporary database. In order * to make these certificates a part of the permanent CA internal database, - * the user must collect the der for all of these certs and call + * the user must collect the der for all of these certs and call * CERT_ImportCAChain. Afterwards the certs will be part of the permanent * database. - * + * * RETURN: - * A pointer to the CERTCertList representing the CA chain associated + * A pointer to the CERTCertList representing the CA chain associated * with the issued cert. A NULL return value indicates that no CA Pubs - * were available in the CMMFCertRepContent structure. + * were available in the CMMFCertRepContent structure. */ -extern CERTCertList* - CMMF_CertRepContentGetCAPubs (CMMFCertRepContent *inCertRepContent); - +extern CERTCertList * +CMMF_CertRepContentGetCAPubs(CMMFCertRepContent *inCertRepContent); /* * FUNCTION: CMMF_CertRepContentGetNumResponses @@ -590,12 +587,12 @@ extern CERTCertList* * NOTES: * This function will return the number of CertResponses that are contained * by the CMMFCertRepContent passed in. - * + * * RETURN: * The number of CMMFCertResponses contained in the structure passed in. */ -extern int - CMMF_CertRepContentGetNumResponses (CMMFCertRepContent *inCertRepContent); +extern int +CMMF_CertRepContentGetNumResponses(CMMFCertRepContent *inCertRepContent); /* * FUNCTION: CMMF_CertRepContentGetResponseAtIndex @@ -605,20 +602,20 @@ extern int * inIndex * The index of the CMMFCertResponse the user wants a copy of. * NOTES: - * This function creates a copy of the CMMFCertResponse at the index + * This function creates a copy of the CMMFCertResponse at the index * corresponding to the parameter 'inIndex'. Indexing is done like a * traditional C array, ie the valid indexes are (0...numResponses-1). - * The user must call CMMF_DestroyCertResponse after the return value is + * The user must call CMMF_DestroyCertResponse after the return value is * no longer needed. * * RETURN: - * A pointer to the CMMFCertResponse at the index corresponding to - * 'inIndex'. A return value of NULL indicates an error in copying + * A pointer to the CMMFCertResponse at the index corresponding to + * 'inIndex'. A return value of NULL indicates an error in copying * the CMMFCertResponse. */ -extern CMMFCertResponse* -CMMF_CertRepContentGetResponseAtIndex (CMMFCertRepContent *inCertRepContent, - int inIndex); +extern CMMFCertResponse * +CMMF_CertRepContentGetResponseAtIndex(CMMFCertRepContent *inCertRepContent, + int inIndex); /* * FUNCTION: CMMF_CertResponseGetCertReqId @@ -626,11 +623,11 @@ CMMF_CertRepContentGetResponseAtIndex (CMMFCertRepContent *inCertRepContent, * inCertResp * The CMMFCertResponse to operate on. * NOTES: - * This function returns the CertResponse.certReqId from the + * This function returns the CertResponse.certReqId from the * CMMFCertResponse structure passed in. If the return value is -1, that * means there is no associated certificate request with the CertResponse. * RETURN: - * A long representing the id of the certificate request this + * A long representing the id of the certificate request this * CMMFCertResponse corresponds to. A return value of -1 indicates an * error in extracting the value of the integer. */ @@ -642,7 +639,7 @@ extern long CMMF_CertResponseGetCertReqId(CMMFCertResponse *inCertResp); * inCertResp * The CMMFCertResponse to operate on. * NOTES: - * This function returns the CertResponse.status.status field of the + * This function returns the CertResponse.status.status field of the * CMMFCertResponse structure. * * RETURN: @@ -650,8 +647,8 @@ extern long CMMF_CertResponseGetCertReqId(CMMFCertResponse *inCertResp); * draft. See the CMMF draft for the definition of PKIStatus. See crmft.h * for the definition of CMMFPKIStatus. */ -extern CMMFPKIStatus - CMMF_CertResponseGetPKIStatusInfoStatus(CMMFCertResponse *inCertResp); +extern CMMFPKIStatus +CMMF_CertResponseGetPKIStatusInfoStatus(CMMFCertResponse *inCertResp); /* * FUNCTION: CMMF_CertResponseGetCertificate @@ -664,18 +661,18 @@ extern CMMFPKIStatus * NOTES: * This function retrieves the CertResponse.certifiedKeyPair.certificate * from the CMMFCertResponse. The user will get a copy of that certificate - * so the user must call CERT_DestroyCertificate when the return value is - * no longer needed. The certificate returned will be in the temporary + * so the user must call CERT_DestroyCertificate when the return value is + * no longer needed. The certificate returned will be in the temporary * certificate database. * * RETURN: - * A pointer to a copy of the certificate contained within the + * A pointer to a copy of the certificate contained within the * CMMFCertResponse. A return value of NULL indicates an error while trying * to make a copy of the certificate. */ -extern CERTCertificate* - CMMF_CertResponseGetCertificate(CMMFCertResponse *inCertResp, - CERTCertDBHandle *inCertdb); +extern CERTCertificate * +CMMF_CertResponseGetCertificate(CMMFCertResponse *inCertResp, + CERTCertDBHandle *inCertdb); /* * FUNCTION: CMMF_KeyRecRepContentGetPKIStatusInfoStatus @@ -683,13 +680,13 @@ extern CERTCertificate* * inKeyRecRep * The CMMFKeyRecRepContent structure to operate on. * NOTES: - * This function retrieves the KeyRecRepContent.status.status field of + * This function retrieves the KeyRecRepContent.status.status field of * the CMMFKeyRecRepContent structure. * RETURN: - * The CMMFPKIStatus corresponding to the value held in the + * The CMMFPKIStatus corresponding to the value held in the * CMMFKeyRecRepContent structure. */ -extern CMMFPKIStatus +extern CMMFPKIStatus CMMF_KeyRecRepContentGetPKIStatusInfoStatus(CMMFKeyRecRepContent *inKeyRecRep); /* @@ -699,15 +696,15 @@ CMMF_KeyRecRepContentGetPKIStatusInfoStatus(CMMFKeyRecRepContent *inKeyRecRep); * The CMMFKeyRecRepContent to operate on. * NOTES: * This function retrieves the KeyRecRepContent.newSignCert field of the - * CMMFKeyRecRepContent structure. The user must call + * CMMFKeyRecRepContent structure. The user must call * CERT_DestroyCertificate when the return value is no longer needed. The - * returned certificate will be in the temporary database. The user + * returned certificate will be in the temporary database. The user * must then place the certificate permanently in whatever token the * user determines is the proper destination. A return value of NULL * indicates the newSigCert field was not present. */ -extern CERTCertificate* - CMMF_KeyRecRepContentGetNewSignCert(CMMFKeyRecRepContent *inKeyRecRep); +extern CERTCertificate * +CMMF_KeyRecRepContentGetNewSignCert(CMMFKeyRecRepContent *inKeyRecRep); /* * FUNCTION: CMMF_KeyRecRepContentGetCACerts @@ -715,22 +712,22 @@ extern CERTCertificate* * inKeyRecRep * The CMMFKeyRecRepContent to operate on. * NOTES: - * This function returns a CERTCertList which contains all of the + * This function returns a CERTCertList which contains all of the * certficates that are in the sequence KeyRecRepContent.caCerts - * User must call CERT_DestroyCertList when the return value is no longer + * User must call CERT_DestroyCertList when the return value is no longer * needed. All of these certificates will be placed in the tempoaray * database. * * RETURN: * A pointer to the list of caCerts contained in the CMMFKeyRecRepContent - * structure. A return value of NULL indicates the library was not able to + * structure. A return value of NULL indicates the library was not able to * make a copy of the certifcates. This may be because there are no caCerts * included in the CMMFKeyRecRepContent strucure or an internal error. Call - * CMMF_KeyRecRepContentHasCACerts to find out if there are any caCerts + * CMMF_KeyRecRepContentHasCACerts to find out if there are any caCerts * included in 'inKeyRecRep'. */ -extern CERTCertList* - CMMF_KeyRecRepContentGetCACerts(CMMFKeyRecRepContent *inKeyRecRep); +extern CERTCertList * +CMMF_KeyRecRepContentGetCACerts(CMMFKeyRecRepContent *inKeyRecRep); /* * FUNCTION: CMMF_KeyRecRepContentGetNumKeyPairs @@ -741,8 +738,8 @@ extern CERTCertList* * This function returns the number of CMMFCertifiedKeyPair structures that * that are stored in the KeyRecRepContent structure. */ -extern int - CMMF_KeyRecRepContentGetNumKeyPairs(CMMFKeyRecRepContent *inKeyRecRep); +extern int +CMMF_KeyRecRepContentGetNumKeyPairs(CMMFKeyRecRepContent *inKeyRecRep); /* * FUNCTION: CMMF_KeyRecRepContentGetCertKeyAtIndex @@ -753,17 +750,17 @@ extern int * The index of the desired CMMFCertifiedKeyPair * NOTES: * This function retrieves the CMMFCertifiedKeyPair structure at the index - * 'inIndex'. Valid indexes are 0...(numKeyPairs-1) The user must call + * 'inIndex'. Valid indexes are 0...(numKeyPairs-1) The user must call * CMMF_DestroyCertifiedKeyPair when the return value is no longer needed. * * RETURN: * A pointer to the Certified Key Pair at the desired index. A return value - * of NULL indicates an error in extracting the Certified Key Pair at the + * of NULL indicates an error in extracting the Certified Key Pair at the * desired index. */ -extern CMMFCertifiedKeyPair* - CMMF_KeyRecRepContentGetCertKeyAtIndex(CMMFKeyRecRepContent *inKeyRecRep, - int inIndex); +extern CMMFCertifiedKeyPair * +CMMF_KeyRecRepContentGetCertKeyAtIndex(CMMFKeyRecRepContent *inKeyRecRep, + int inIndex); /* * FUNCTION: CMMF_CertifiedKeyPairGetCertificate @@ -774,21 +771,21 @@ extern CMMFCertifiedKeyPair* * The database handle for the database you want this certificate * to wind up in. * NOTES: - * This function retrieves the certificate at + * This function retrieves the certificate at * CertifiedKeyPair.certOrEncCert.certificate * The user must call CERT_DestroyCertificate when the return value is no * longer needed. The user must import this certificate as a token object * onto PKCS#11 slot in order to make it a permanent object. The returned * certificate will be in the temporary database. - * + * * RETURN: * A pointer to the certificate contained within the certified key pair. - * A return value of NULL indicates an error in creating the copy of the + * A return value of NULL indicates an error in creating the copy of the * certificate. */ -extern CERTCertificate* - CMMF_CertifiedKeyPairGetCertificate(CMMFCertifiedKeyPair *inCertKeyPair, - CERTCertDBHandle *inCertdb); +extern CERTCertificate * +CMMF_CertifiedKeyPairGetCertificate(CMMFCertifiedKeyPair *inCertKeyPair, + CERTCertDBHandle *inCertdb); /* * FUNCTION: CMMF_POPODecKeyChallContentGetNumChallenges @@ -796,11 +793,10 @@ extern CERTCertificate* * inKeyChallCont * The CMMFPOPODecKeyChallContent to operate on. * RETURN: - * This function returns the number of CMMFChallenges are contained in + * This function returns the number of CMMFChallenges are contained in * the CMMFPOPODecKeyChallContent structure. */ -extern int CMMF_POPODecKeyChallContentGetNumChallenges - (CMMFPOPODecKeyChallContent *inKeyChallCont); +extern int CMMF_POPODecKeyChallContentGetNumChallenges(CMMFPOPODecKeyChallContent *inKeyChallCont); /* * FUNCTION: CMMF_POPODecKeyChallContentGetPublicValue @@ -816,14 +812,12 @@ extern int CMMF_POPODecKeyChallContentGetNumChallenges * This function retrieves the public value stored away in the Challenge at * index inIndex of inKeyChallCont. * RETURN: - * A pointer to a SECItem containing the public value. User must call + * A pointer to a SECItem containing the public value. User must call * SECITEM_FreeItem on the return value when the value is no longer necessary. * A return value of NULL indicates an error while retrieving the public value. */ -extern SECItem* CMMF_POPODecKeyChallContentGetPublicValue - (CMMFPOPODecKeyChallContent *inKeyChallCont, - int inIndex); - +extern SECItem *CMMF_POPODecKeyChallContentGetPublicValue(CMMFPOPODecKeyChallContent *inKeyChallCont, + int inIndex); /* * FUNCTION: CMMF_POPODecKeyChallContentGetRandomNumber @@ -839,9 +833,9 @@ extern SECItem* CMMF_POPODecKeyChallContentGetPublicValue * challenge. * NOTES: * This function returns the value held in the decrypted Rand structure - * corresponding to the random integer. The user must call - * CMMF_POPODecKeyChallContentDecryptChallenge before calling this function. Call - * CMMF_ChallengeIsDecrypted to find out if the challenge has been + * corresponding to the random integer. The user must call + * CMMF_POPODecKeyChallContentDecryptChallenge before calling this function. Call + * CMMF_ChallengeIsDecrypted to find out if the challenge has been * decrypted. * * RETURN: @@ -850,10 +844,9 @@ extern SECItem* CMMF_POPODecKeyChallContentGetPublicValue * Any other return value indicates an error and that the value at *inDest * is not a valid value. */ -extern SECStatus CMMF_POPODecKeyChallContentGetRandomNumber - (CMMFPOPODecKeyChallContent *inKeyChallCont, - int inIndex, - long *inDest); +extern SECStatus CMMF_POPODecKeyChallContentGetRandomNumber(CMMFPOPODecKeyChallContent *inKeyChallCont, + int inIndex, + long *inDest); /* * FUNCTION: CMMF_POPODecKeyRespContentGetNumResponses @@ -863,8 +856,8 @@ extern SECStatus CMMF_POPODecKeyChallContentGetRandomNumber * RETURN: * This function returns the number of responses contained in inRespContent. */ -extern int - CMMF_POPODecKeyRespContentGetNumResponses(CMMFPOPODecKeyRespContent *inRespCont); +extern int +CMMF_POPODecKeyRespContentGetNumResponses(CMMFPOPODecKeyRespContent *inRespCont); /* * FUNCTION: CMMF_POPODecKeyRespContentGetResponse @@ -876,22 +869,22 @@ extern int * The Nth response is at index N-1, ie the 1st response is at index 0, * the 2nd response is at index 1, and so on. * inDest - * A pointer to a pre-allocated buffer where the library can put the + * A pointer to a pre-allocated buffer where the library can put the * value of the response located at inIndex. * NOTES: - * The function returns the response contained at index inIndex. - * CMMFPOPODecKeyRespContent is a structure that the server will generally + * The function returns the response contained at index inIndex. + * CMMFPOPODecKeyRespContent is a structure that the server will generally * get in response to a CMMFPOPODecKeyChallContent. The server will expect - * to see the responses in the same order as it constructed them in + * to see the responses in the same order as it constructed them in * the CMMFPOPODecKeyChallContent structure. * RETURN: * SECSuccess if getting the response at the desired index was successful. Any * other return value indicates an errror. */ extern SECStatus - CMMF_POPODecKeyRespContentGetResponse (CMMFPOPODecKeyRespContent *inRespCont, - int inIndex, - long *inDest); +CMMF_POPODecKeyRespContentGetResponse(CMMFPOPODecKeyRespContent *inRespCont, + int inIndex, + long *inDest); /************************* Destructor Functions ******************************/ @@ -918,12 +911,12 @@ extern SECStatus CMMF_DestroyCertResponse(CMMFCertResponse *inCertResp); * This function frees the memory associated with the CMMFCertRepContent * passed in. * RETURN: - * SECSuccess if freeing all the memory associated with the - * CMMFCertRepContent passed in is successful. Any other return value + * SECSuccess if freeing all the memory associated with the + * CMMFCertRepContent passed in is successful. Any other return value * indicates an error while freeing the memory. */ -extern SECStatus - CMMF_DestroyCertRepContent (CMMFCertRepContent *inCertRepContent); +extern SECStatus +CMMF_DestroyCertRepContent(CMMFCertRepContent *inCertRepContent); /* * FUNCTION: CMMF_DestroyKeyRecRepContent @@ -931,22 +924,22 @@ extern SECStatus * inKeyRecRep * The CMMFKeyRecRepContent to destroy. * NOTES: - * This function destroys all the memory associated with the + * This function destroys all the memory associated with the * CMMFKeyRecRepContent passed in. * * RETURN: - * SECSuccess if freeing all the memory is successful. Any other return + * SECSuccess if freeing all the memory is successful. Any other return * value indicates an error in freeing the memory. */ -extern SECStatus - CMMF_DestroyKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep); +extern SECStatus +CMMF_DestroyKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep); /* * FUNCTION: CMMF_DestroyCertifiedKeyPair * INPUTS: * inCertKeyPair * The CMMFCertifiedKeyPair to operate on. - * NOTES: + * NOTES: * This function frees up all the memory associated with 'inCertKeyPair' * * RETURN: @@ -954,8 +947,8 @@ extern SECStatus * is successful. Any other return value indicates an error while trying * to free the memory. */ -extern SECStatus - CMMF_DestroyCertifiedKeyPair(CMMFCertifiedKeyPair *inCertKeyPair); +extern SECStatus +CMMF_DestroyCertifiedKeyPair(CMMFCertifiedKeyPair *inCertKeyPair); /* * FUNCTION: CMMF_DestroyPOPODecKeyRespContent @@ -963,7 +956,7 @@ extern SECStatus * inDecKeyResp * The CMMFPOPODecKeyRespContent structure to free. * NOTES: - * This function frees up all the memory associate with the + * This function frees up all the memory associate with the * CMMFPOPODecKeyRespContent. * * RETURN: @@ -972,11 +965,10 @@ extern SECStatus * return value indicates an error while freeing the memory. */ extern SECStatus - CMMF_DestroyPOPODecKeyRespContent(CMMFPOPODecKeyRespContent *inDecKeyResp); - +CMMF_DestroyPOPODecKeyRespContent(CMMFPOPODecKeyRespContent *inDecKeyResp); /************************** Miscellaneous Functions *************************/ - + /* * FUNCTION: CMMF_CertifiedKeyPairUnwrapPrivKey * INPUTS: @@ -997,25 +989,25 @@ extern SECStatus * wincx * An opaque pointer that the library will use in a callback function * to get the password if necessary. - * + * * NOTES: * This function uses the private key passed in to unwrap the private key - * contained within the CMMFCertifiedKeyPair structure. After this + * contained within the CMMFCertifiedKeyPair structure. After this * function successfully returns, the private key has been unwrapped and - * placed in the specified slot. + * placed in the specified slot. * * RETURN: - * SECSuccess if unwrapping the private key was successful. Any other + * SECSuccess if unwrapping the private key was successful. Any other * return value indicates an error while trying to un-wrap the private key. */ -extern SECStatus - CMMF_CertifiedKeyPairUnwrapPrivKey(CMMFCertifiedKeyPair *inKeyPair, - SECKEYPrivateKey *inPrivKey, - SECItem *inNickName, - PK11SlotInfo *inSlot, - CERTCertDBHandle *inCertdb, - SECKEYPrivateKey **destPrivKey, - void *wincx); +extern SECStatus +CMMF_CertifiedKeyPairUnwrapPrivKey(CMMFCertifiedKeyPair *inKeyPair, + SECKEYPrivateKey *inPrivKey, + SECItem *inNickName, + PK11SlotInfo *inSlot, + CERTCertDBHandle *inCertdb, + SECKEYPrivateKey **destPrivKey, + void *wincx); /* * FUNCTION: CMMF_KeyRecRepContentHasCACerts @@ -1023,13 +1015,13 @@ extern SECStatus * inKeyRecRecp * The CMMFKeyRecRepContent to operate on. * RETURN: - * This function returns PR_TRUE if there are one or more certificates in + * This function returns PR_TRUE if there are one or more certificates in * the sequence KeyRecRepContent.caCerts within the CMMFKeyRecRepContent * structure. The function will return PR_FALSE if there are 0 certificate * in the above mentioned sequence. */ -extern PRBool - CMMF_KeyRecRepContentHasCACerts(CMMFKeyRecRepContent *inKeyRecRep); +extern PRBool +CMMF_KeyRecRepContentHasCACerts(CMMFKeyRecRepContent *inKeyRecRep); /* * FUNCTION: CMMF_POPODecKeyChallContDecryptChallenge @@ -1043,12 +1035,12 @@ extern PRBool * The private key to use to decrypt the witness field. * NOTES: * This function uses the private key to decrypt the challenge field - * contained in the appropriate challenge. Make sure the private key matches - * the public key that was used to encrypt the witness. Use + * contained in the appropriate challenge. Make sure the private key matches + * the public key that was used to encrypt the witness. Use * CMMF_POPODecKeyChallContentGetPublicValue to get the public value of * the key used to encrypt the witness and then use that to determine the * appropriate private key. This can be done by calling PK11_MakeIDFromPubKey - * and then passing that return value to PK11_FindKeyByKeyID. The creator of + * and then passing that return value to PK11_FindKeyByKeyID. The creator of * the challenge will most likely be an RA that has the public key * from a Cert request. So the private key should be the private key * associated with public key in that request. This function will also @@ -1057,17 +1049,17 @@ extern PRBool * * RETURN: * SECSuccess if decrypting the witness field was successful. This does - * not indicate that the decrypted data is valid, since the private key - * passed in may not be the actual key needed to properly decrypt the + * not indicate that the decrypted data is valid, since the private key + * passed in may not be the actual key needed to properly decrypt the * witness field. Meaning that there is a decrypted structure now, but * may be garbage because the private key was incorrect. * Any other return value indicates the function could not complete the * decryption process. */ -extern SECStatus - CMMF_POPODecKeyChallContDecryptChallenge(CMMFPOPODecKeyChallContent *inChalCont, - int inIndex, - SECKEYPrivateKey *inPrivKey); +extern SECStatus +CMMF_POPODecKeyChallContDecryptChallenge(CMMFPOPODecKeyChallContent *inChalCont, + int inIndex, + SECKEYPrivateKey *inPrivKey); /* * FUNCTION: CMMF_DestroyPOPODecKeyChallContent @@ -1075,16 +1067,16 @@ extern SECStatus * inDecKeyCont * The CMMFPOPODecKeyChallContent to free * NOTES: - * This function frees up all the memory associated with the - * CMMFPOPODecKeyChallContent + * This function frees up all the memory associated with the + * CMMFPOPODecKeyChallContent * RETURN: - * SECSuccess if freeing up all the memory associatd with the + * SECSuccess if freeing up all the memory associatd with the * CMMFPOPODecKeyChallContent is successful. Any other return value * indicates an error while freeing the memory. * */ -extern SECStatus - CMMF_DestroyPOPODecKeyChallContent (CMMFPOPODecKeyChallContent *inDecKeyCont); +extern SECStatus +CMMF_DestroyPOPODecKeyChallContent(CMMFPOPODecKeyChallContent *inDecKeyCont); SEC_END_PROTOS #endif /* _CMMF_H_ */ diff --git a/security/nss/lib/crmf/cmmfasn1.c b/security/nss/lib/crmf/cmmfasn1.c index 711d4ab15f9a..64915b33920b 100644 --- a/security/nss/lib/crmf/cmmfasn1.c +++ b/security/nss/lib/crmf/cmmfasn1.c @@ -11,50 +11,50 @@ SEC_ASN1_MKSUB(SEC_SignedCertificateTemplate) static const SEC_ASN1Template CMMFSequenceOfCertifiedKeyPairsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, CMMFCertifiedKeyPairTemplate} + { SEC_ASN1_SEQUENCE_OF, 0, CMMFCertifiedKeyPairTemplate } }; static const SEC_ASN1Template CMMFKeyRecRepContentTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFKeyRecRepContent)}, - { SEC_ASN1_INLINE, offsetof(CMMFKeyRecRepContent, status), - CMMFPKIStatusInfoTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | - SEC_ASN1_XTRN | 0, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CMMFKeyRecRepContent) }, + { SEC_ASN1_INLINE, offsetof(CMMFKeyRecRepContent, status), + CMMFPKIStatusInfoTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | + SEC_ASN1_XTRN | 0, offsetof(CMMFKeyRecRepContent, newSigCert), - SEC_ASN1_SUB(SEC_SignedCertificateTemplate)}, + SEC_ASN1_SUB(SEC_SignedCertificateTemplate) }, { SEC_ASN1_CONSTRUCTED | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | 1, offsetof(CMMFKeyRecRepContent, caCerts), - CMMFSequenceOfCertsTemplate}, + CMMFSequenceOfCertsTemplate }, { SEC_ASN1_CONSTRUCTED | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | 2, offsetof(CMMFKeyRecRepContent, keyPairHist), - CMMFSequenceOfCertifiedKeyPairsTemplate}, + CMMFSequenceOfCertifiedKeyPairsTemplate }, { 0 } }; SECStatus -CMMF_EncodeCertRepContent (CMMFCertRepContent *inCertRepContent, - CRMFEncoderOutputCallback inCallback, - void *inArg) +CMMF_EncodeCertRepContent(CMMFCertRepContent *inCertRepContent, + CRMFEncoderOutputCallback inCallback, + void *inArg) { return cmmf_user_encode(inCertRepContent, inCallback, inArg, - CMMFCertRepContentTemplate); + CMMFCertRepContentTemplate); } SECStatus CMMF_EncodePOPODecKeyChallContent(CMMFPOPODecKeyChallContent *inDecKeyChall, - CRMFEncoderOutputCallback inCallback, - void *inArg) + CRMFEncoderOutputCallback inCallback, + void *inArg) { return cmmf_user_encode(inDecKeyChall, inCallback, inArg, - CMMFPOPODecKeyChallContentTemplate); + CMMFPOPODecKeyChallContentTemplate); } -CMMFPOPODecKeyRespContent* +CMMFPOPODecKeyRespContent * CMMF_CreatePOPODecKeyRespContentFromDER(const char *buf, long len) { - PLArenaPool *poolp; + PLArenaPool *poolp; CMMFPOPODecKeyRespContent *decKeyResp; - SECStatus rv; + SECStatus rv; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { @@ -66,13 +66,13 @@ CMMF_CreatePOPODecKeyRespContentFromDER(const char *buf, long len) } decKeyResp->poolp = poolp; rv = SEC_ASN1Decode(poolp, decKeyResp, CMMFPOPODecKeyRespContentTemplate, - buf, len); + buf, len); if (rv != SECSuccess) { goto loser; } return decKeyResp; - - loser: + +loser: if (poolp != NULL) { PORT_FreeArena(poolp, PR_FALSE); } @@ -80,21 +80,21 @@ CMMF_CreatePOPODecKeyRespContentFromDER(const char *buf, long len) } SECStatus -CMMF_EncodeKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep, - CRMFEncoderOutputCallback inCallback, - void *inArg) +CMMF_EncodeKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep, + CRMFEncoderOutputCallback inCallback, + void *inArg) { return cmmf_user_encode(inKeyRecRep, inCallback, inArg, - CMMFKeyRecRepContentTemplate); + CMMFKeyRecRepContentTemplate); } -CMMFKeyRecRepContent* -CMMF_CreateKeyRecRepContentFromDER(CERTCertDBHandle *db, const char *buf, - long len) +CMMFKeyRecRepContent * +CMMF_CreateKeyRecRepContentFromDER(CERTCertDBHandle *db, const char *buf, + long len) { - PLArenaPool *poolp; + PLArenaPool *poolp; CMMFKeyRecRepContent *keyRecContent; - SECStatus rv; + SECStatus rv; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { @@ -106,27 +106,26 @@ CMMF_CreateKeyRecRepContentFromDER(CERTCertDBHandle *db, const char *buf, } keyRecContent->poolp = poolp; rv = SEC_ASN1Decode(poolp, keyRecContent, CMMFKeyRecRepContentTemplate, - buf, len); + buf, len); if (rv != SECSuccess) { goto loser; } if (keyRecContent->keyPairHist != NULL) { - while(keyRecContent->keyPairHist[keyRecContent->numKeyPairs] != NULL) { - rv = cmmf_decode_process_certified_key_pair(poolp, db, - keyRecContent->keyPairHist[keyRecContent->numKeyPairs]); - if (rv != SECSuccess) { - goto loser; - } - keyRecContent->numKeyPairs++; - } - keyRecContent->allocKeyPairs = keyRecContent->numKeyPairs; + while (keyRecContent->keyPairHist[keyRecContent->numKeyPairs] != NULL) { + rv = cmmf_decode_process_certified_key_pair(poolp, db, + keyRecContent->keyPairHist[keyRecContent->numKeyPairs]); + if (rv != SECSuccess) { + goto loser; + } + keyRecContent->numKeyPairs++; + } + keyRecContent->allocKeyPairs = keyRecContent->numKeyPairs; } keyRecContent->isDecoded = PR_TRUE; return keyRecContent; - loser: +loser: if (poolp != NULL) { PORT_FreeArena(poolp, PR_FALSE); } return NULL; } - diff --git a/security/nss/lib/crmf/cmmfchal.c b/security/nss/lib/crmf/cmmfchal.c index bf0b7ba377c2..b2d33b9d72e7 100644 --- a/security/nss/lib/crmf/cmmfchal.c +++ b/security/nss/lib/crmf/cmmfchal.c @@ -14,51 +14,50 @@ #include "keyhi.h" static int -cmmf_create_witness_and_challenge(PLArenaPool *poolp, - CMMFChallenge *challenge, - long inRandom, - SECItem *senderDER, - SECKEYPublicKey *inPubKey, - void *passwdArg) +cmmf_create_witness_and_challenge(PLArenaPool *poolp, + CMMFChallenge *challenge, + long inRandom, + SECItem *senderDER, + SECKEYPublicKey *inPubKey, + void *passwdArg) { - SECItem *encodedRandNum; - SECItem encodedRandStr = {siBuffer, NULL, 0}; - SECItem *dummy; - unsigned char *randHash, *senderHash, *encChal=NULL; - unsigned modulusLen = 0; - SECStatus rv = SECFailure; - CMMFRand randStr= { {siBuffer, NULL, 0}, {siBuffer, NULL, 0}}; - PK11SlotInfo *slot; - PK11SymKey *symKey = NULL; + SECItem *encodedRandNum; + SECItem encodedRandStr = { siBuffer, NULL, 0 }; + SECItem *dummy; + unsigned char *randHash, *senderHash, *encChal = NULL; + unsigned modulusLen = 0; + SECStatus rv = SECFailure; + CMMFRand randStr = { { siBuffer, NULL, 0 }, { siBuffer, NULL, 0 } }; + PK11SlotInfo *slot; + PK11SymKey *symKey = NULL; CERTSubjectPublicKeyInfo *spki = NULL; - encodedRandNum = SEC_ASN1EncodeInteger(poolp, &challenge->randomNumber, - inRandom); + inRandom); encodedRandNum = &challenge->randomNumber; - randHash = PORT_ArenaNewArray(poolp, unsigned char, SHA1_LENGTH); + randHash = PORT_ArenaNewArray(poolp, unsigned char, SHA1_LENGTH); senderHash = PORT_ArenaNewArray(poolp, unsigned char, SHA1_LENGTH); if (randHash == NULL) { goto loser; } - rv = PK11_HashBuf(SEC_OID_SHA1, randHash, encodedRandNum->data, - (PRUint32)encodedRandNum->len); + rv = PK11_HashBuf(SEC_OID_SHA1, randHash, encodedRandNum->data, + (PRUint32)encodedRandNum->len); if (rv != SECSuccess) { goto loser; } rv = PK11_HashBuf(SEC_OID_SHA1, senderHash, senderDER->data, - (PRUint32)senderDER->len); + (PRUint32)senderDER->len); if (rv != SECSuccess) { goto loser; } challenge->witness.data = randHash; - challenge->witness.len = SHA1_LENGTH; + challenge->witness.len = SHA1_LENGTH; - randStr.integer = *encodedRandNum; + randStr.integer = *encodedRandNum; randStr.senderHash.data = senderHash; - randStr.senderHash.len = SHA1_LENGTH; - dummy = SEC_ASN1EncodeItem(NULL, &encodedRandStr, &randStr, - CMMFRandTemplate); + randStr.senderHash.len = SHA1_LENGTH; + dummy = SEC_ASN1EncodeItem(NULL, &encodedRandStr, &randStr, + CMMFRandTemplate); if (dummy != &encodedRandStr) { rv = SECFailure; goto loser; @@ -70,7 +69,7 @@ cmmf_create_witness_and_challenge(PLArenaPool *poolp, rv = SECFailure; goto loser; } - slot =PK11_GetBestSlotWithAttributes(CKM_RSA_PKCS, CKF_WRAP, 0, passwdArg); + slot = PK11_GetBestSlotWithAttributes(CKM_RSA_PKCS, CKF_WRAP, 0, passwdArg); if (slot == NULL) { rv = SECFailure; goto loser; @@ -83,23 +82,23 @@ cmmf_create_witness_and_challenge(PLArenaPool *poolp, * the PK11 libraries depend on. */ symKey = PK11_ImportSymKey(slot, CKM_RSA_PKCS, PK11_OriginGenerated, - CKA_VALUE, &encodedRandStr, passwdArg); + CKA_VALUE, &encodedRandStr, passwdArg); if (symKey == NULL) { rv = SECFailure; - goto loser; + goto loser; } challenge->challenge.data = encChal; - challenge->challenge.len = modulusLen; - rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, inPubKey, symKey, - &challenge->challenge); + challenge->challenge.len = modulusLen; + rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, inPubKey, symKey, + &challenge->challenge); PK11_FreeSlot(slot); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SECITEM_CopyItem(poolp, &challenge->senderDER, senderDER); crmf_get_public_value(inPubKey, &challenge->key); /* Fall through */ - loser: +loser: if (spki != NULL) { SECKEY_DestroySubjectPublicKeyInfo(spki); } @@ -116,17 +115,17 @@ cmmf_create_witness_and_challenge(PLArenaPool *poolp, } static SECStatus -cmmf_create_first_challenge(CMMFPOPODecKeyChallContent *challContent, - long inRandom, - SECItem *senderDER, - SECKEYPublicKey *inPubKey, - void *passwdArg) +cmmf_create_first_challenge(CMMFPOPODecKeyChallContent *challContent, + long inRandom, + SECItem *senderDER, + SECKEYPublicKey *inPubKey, + void *passwdArg) { - SECOidData *oidData; - CMMFChallenge *challenge; + SECOidData *oidData; + CMMFChallenge *challenge; SECAlgorithmID *algId; - PLArenaPool *poolp; - SECStatus rv; + PLArenaPool *poolp; + SECStatus rv; oidData = SECOID_FindOIDByTag(SEC_OID_SHA1); if (oidData == NULL) { @@ -145,15 +144,15 @@ cmmf_create_first_challenge(CMMFPOPODecKeyChallContent *challContent, if (rv != SECSuccess) { return SECFailure; } - rv = cmmf_create_witness_and_challenge(poolp, challenge, inRandom, - senderDER, inPubKey, passwdArg); + rv = cmmf_create_witness_and_challenge(poolp, challenge, inRandom, + senderDER, inPubKey, passwdArg); challContent->challenges[0] = (rv == SECSuccess) ? challenge : NULL; challContent->numChallenges++; - return rv ; + return rv; } -CMMFPOPODecKeyChallContent* -CMMF_CreatePOPODecKeyChallContent (void) +CMMFPOPODecKeyChallContent * +CMMF_CreatePOPODecKeyChallContent(void) { PLArenaPool *poolp; CMMFPOPODecKeyChallContent *challContent; @@ -165,32 +164,31 @@ CMMF_CreatePOPODecKeyChallContent (void) challContent = PORT_ArenaZNew(poolp, CMMFPOPODecKeyChallContent); if (challContent == NULL) { PORT_FreeArena(poolp, PR_FALSE); - return NULL; + return NULL; } challContent->poolp = poolp; return challContent; } SECStatus -CMMF_POPODecKeyChallContentSetNextChallenge - (CMMFPOPODecKeyChallContent *inDecKeyChall, - long inRandom, - CERTGeneralName *inSender, - SECKEYPublicKey *inPubKey, - void *passwdArg) +CMMF_POPODecKeyChallContentSetNextChallenge(CMMFPOPODecKeyChallContent *inDecKeyChall, + long inRandom, + CERTGeneralName *inSender, + SECKEYPublicKey *inPubKey, + void *passwdArg) { - CMMFChallenge *curChallenge; - PLArenaPool *genNamePool = NULL, *poolp; - SECStatus rv; - SECItem *genNameDER; - void *mark; + CMMFChallenge *curChallenge; + PLArenaPool *genNamePool = NULL, *poolp; + SECStatus rv; + SECItem *genNameDER; + void *mark; - PORT_Assert (inDecKeyChall != NULL && - inSender != NULL && - inPubKey != NULL); + PORT_Assert(inDecKeyChall != NULL && + inSender != NULL && + inPubKey != NULL); - if (inDecKeyChall == NULL || - inSender == NULL || inPubKey == NULL) { + if (inDecKeyChall == NULL || + inSender == NULL || inPubKey == NULL) { return SECFailure; } poolp = inDecKeyChall->poolp; @@ -204,8 +202,8 @@ CMMF_POPODecKeyChallContentSetNextChallenge } if (inDecKeyChall->challenges == NULL) { inDecKeyChall->challenges = - PORT_ArenaZNewArray(poolp, CMMFChallenge*,(CMMF_MAX_CHALLENGES+1)); - inDecKeyChall->numAllocated = CMMF_MAX_CHALLENGES; + PORT_ArenaZNewArray(poolp, CMMFChallenge *, (CMMF_MAX_CHALLENGES + 1)); + inDecKeyChall->numAllocated = CMMF_MAX_CHALLENGES; } if (inDecKeyChall->numChallenges >= inDecKeyChall->numAllocated) { @@ -214,22 +212,23 @@ CMMF_POPODecKeyChallContentSetNextChallenge } if (inDecKeyChall->numChallenges == 0) { - rv = cmmf_create_first_challenge(inDecKeyChall, inRandom, - genNameDER, inPubKey, passwdArg); - } else { + rv = cmmf_create_first_challenge(inDecKeyChall, inRandom, + genNameDER, inPubKey, passwdArg); + } + else { curChallenge = PORT_ArenaZNew(poolp, CMMFChallenge); - if (curChallenge == NULL) { - rv = SECFailure; - goto loser; - } - rv = cmmf_create_witness_and_challenge(poolp, curChallenge, inRandom, - genNameDER, inPubKey, - passwdArg); - if (rv == SECSuccess) { - inDecKeyChall->challenges[inDecKeyChall->numChallenges] = - curChallenge; - inDecKeyChall->numChallenges++; - } + if (curChallenge == NULL) { + rv = SECFailure; + goto loser; + } + rv = cmmf_create_witness_and_challenge(poolp, curChallenge, inRandom, + genNameDER, inPubKey, + passwdArg); + if (rv == SECSuccess) { + inDecKeyChall->challenges[inDecKeyChall->numChallenges] = + curChallenge; + inDecKeyChall->numChallenges++; + } } if (rv != SECSuccess) { goto loser; @@ -238,7 +237,7 @@ CMMF_POPODecKeyChallContentSetNextChallenge PORT_FreeArena(genNamePool, PR_FALSE); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); if (genNamePool != NULL) { PORT_FreeArena(genNamePool, PR_FALSE); @@ -257,7 +256,7 @@ CMMF_DestroyPOPODecKeyRespContent(CMMFPOPODecKeyRespContent *inDecKeyResp) return SECSuccess; } -int +int CMMF_POPODecKeyRespContentGetNumResponses(CMMFPOPODecKeyRespContent *inRespCont) { int numResponses = 0; @@ -268,20 +267,20 @@ CMMF_POPODecKeyRespContentGetNumResponses(CMMFPOPODecKeyRespContent *inRespCont) } while (inRespCont->responses[numResponses] != NULL) { - numResponses ++; + numResponses++; } return numResponses; } SECStatus -CMMF_POPODecKeyRespContentGetResponse (CMMFPOPODecKeyRespContent *inRespCont, - int inIndex, - long *inDest) +CMMF_POPODecKeyRespContentGetResponse(CMMFPOPODecKeyRespContent *inRespCont, + int inIndex, + long *inDest) { PORT_Assert(inRespCont != NULL); - - if (inRespCont == NULL || inIndex < 0 || - inIndex >= CMMF_POPODecKeyRespContentGetNumResponses(inRespCont)) { + + if (inRespCont == NULL || inIndex < 0 || + inIndex >= CMMF_POPODecKeyRespContentGetNumResponses(inRespCont)) { return SECFailure; } *inDest = DER_GetInteger(inRespCont->responses[inIndex]); diff --git a/security/nss/lib/crmf/cmmfi.h b/security/nss/lib/crmf/cmmfi.h index bfe3cb02bce6..9336ccfc2387 100644 --- a/security/nss/lib/crmf/cmmfi.h +++ b/security/nss/lib/crmf/cmmfi.h @@ -14,7 +14,7 @@ #include "crmfi.h" #define CMMF_MAX_CHALLENGES 10 -#define CMMF_MAX_KEY_PAIRS 50 +#define CMMF_MAX_KEY_PAIRS 50 /* * Some templates that the code will need to implement CMMF. @@ -27,72 +27,66 @@ extern const SEC_ASN1Template CMMFSequenceOfCertsTemplate[]; extern const SEC_ASN1Template CMMFPKIStatusInfoTemplate[]; extern const SEC_ASN1Template CMMFCertifiedKeyPairTemplate[]; - /* - * Some utility functions that are shared by multiple files in this + * Some utility functions that are shared by multiple files in this * implementation. */ -extern SECStatus cmmf_CopyCertResponse (PLArenaPool *poolp, - CMMFCertResponse *dest, - CMMFCertResponse *src); +extern SECStatus cmmf_CopyCertResponse(PLArenaPool *poolp, + CMMFCertResponse *dest, + CMMFCertResponse *src); -extern SECStatus cmmf_CopyPKIStatusInfo (PLArenaPool *poolp, - CMMFPKIStatusInfo *dest, - CMMFPKIStatusInfo *src); +extern SECStatus cmmf_CopyPKIStatusInfo(PLArenaPool *poolp, + CMMFPKIStatusInfo *dest, + CMMFPKIStatusInfo *src); -extern SECStatus cmmf_CopyCertifiedKeyPair(PLArenaPool *poolp, - CMMFCertifiedKeyPair *dest, - CMMFCertifiedKeyPair *src); +extern SECStatus cmmf_CopyCertifiedKeyPair(PLArenaPool *poolp, + CMMFCertifiedKeyPair *dest, + CMMFCertifiedKeyPair *src); -extern SECStatus cmmf_DestroyPKIStatusInfo(CMMFPKIStatusInfo *info, - PRBool freeit); +extern SECStatus cmmf_DestroyPKIStatusInfo(CMMFPKIStatusInfo *info, + PRBool freeit); -extern SECStatus cmmf_DestroyCertOrEncCert(CMMFCertOrEncCert *certOrEncCert, - PRBool freeit); +extern SECStatus cmmf_DestroyCertOrEncCert(CMMFCertOrEncCert *certOrEncCert, + PRBool freeit); -extern SECStatus cmmf_PKIStatusInfoSetStatus(CMMFPKIStatusInfo *statusInfo, - PLArenaPool *poolp, - CMMFPKIStatus inStatus); +extern SECStatus cmmf_PKIStatusInfoSetStatus(CMMFPKIStatusInfo *statusInfo, + PLArenaPool *poolp, + CMMFPKIStatus inStatus); -extern SECStatus cmmf_ExtractCertsFromList(CERTCertList *inCertList, - PLArenaPool *poolp, - CERTCertificate ***certArray); +extern SECStatus cmmf_ExtractCertsFromList(CERTCertList *inCertList, + PLArenaPool *poolp, + CERTCertificate ***certArray); -extern SECStatus - cmmf_CertOrEncCertSetCertificate(CMMFCertOrEncCert *certOrEncCert, - PLArenaPool *poolp, - CERTCertificate *inCert); +extern SECStatus +cmmf_CertOrEncCertSetCertificate(CMMFCertOrEncCert *certOrEncCert, + PLArenaPool *poolp, + CERTCertificate *inCert); -extern CMMFPKIStatus - cmmf_PKIStatusInfoGetStatus(CMMFPKIStatusInfo *inStatus); +extern CMMFPKIStatus +cmmf_PKIStatusInfoGetStatus(CMMFPKIStatusInfo *inStatus); -extern CERTCertList* - cmmf_MakeCertList(CERTCertificate **inCerts); +extern CERTCertList * +cmmf_MakeCertList(CERTCertificate **inCerts); -extern CERTCertificate* +extern CERTCertificate * cmmf_CertOrEncCertGetCertificate(CMMFCertOrEncCert *certOrEncCert, - CERTCertDBHandle *certdb); + CERTCertDBHandle *certdb); extern SECStatus -cmmf_decode_process_cert_response(PLArenaPool *poolp, - CERTCertDBHandle *db, - CMMFCertResponse *inCertResp); +cmmf_decode_process_cert_response(PLArenaPool *poolp, + CERTCertDBHandle *db, + CMMFCertResponse *inCertResp); extern SECStatus -cmmf_decode_process_certified_key_pair(PLArenaPool *poolp, - CERTCertDBHandle *db, - CMMFCertifiedKeyPair *inCertKeyPair); +cmmf_decode_process_certified_key_pair(PLArenaPool *poolp, + CERTCertDBHandle *db, + CMMFCertifiedKeyPair *inCertKeyPair); extern SECStatus cmmf_user_encode(void *src, CRMFEncoderOutputCallback inCallback, void *inArg, - const SEC_ASN1Template *inTemplate); + const SEC_ASN1Template *inTemplate); extern SECStatus -cmmf_copy_secitem (PLArenaPool *poolp, SECItem *dest, SECItem *src); +cmmf_copy_secitem(PLArenaPool *poolp, SECItem *dest, SECItem *src); #endif /*_CMMFI_H_*/ - - - - - diff --git a/security/nss/lib/crmf/cmmfit.h b/security/nss/lib/crmf/cmmfit.h index 84f81c3d61b0..014413f07578 100644 --- a/security/nss/lib/crmf/cmmfit.h +++ b/security/nss/lib/crmf/cmmfit.h @@ -14,23 +14,23 @@ * ------------- ------- * 0 granted- got exactly what you asked for. * - * 1 grantedWithMods-got something like what you asked + * 1 grantedWithMods-got something like what you asked * for;requester is responsible for ascertainging the * differences. * - * 2 rejection-you don't get what you asked for; more + * 2 rejection-you don't get what you asked for; more * information elsewhere in the message * - * 3 waiting-the request body part has not yet been + * 3 waiting-the request body part has not yet been * processed, expect to hear more later. * - * 4 revocationWarning-this message contains a warning + * 4 revocationWarning-this message contains a warning * that a revocation is imminent. * - * 5 revocationNotification-notification that a + * 5 revocationNotification-notification that a * revocation has occurred. * - * 6 keyUpdateWarning-update already done for the + * 6 keyUpdateWarning-update already done for the * oldCertId specified in FullCertTemplate. */ @@ -41,76 +41,75 @@ struct CMMFPKIStatusInfoStr { }; struct CMMFCertOrEncCertStr { - union { - CERTCertificate *certificate; + union { + CERTCertificate *certificate; CRMFEncryptedValue *encryptedCert; } cert; CMMFCertOrEncCertChoice choice; - SECItem derValue; + SECItem derValue; }; struct CMMFCertifiedKeyPairStr { - CMMFCertOrEncCert certOrEncCert; + CMMFCertOrEncCert certOrEncCert; CRMFEncryptedValue *privateKey; - SECItem derPublicationInfo; /* We aren't creating - * PKIPublicationInfo's, so - * we'll store away the der - * here if we decode one that - * does have pubInfo. - */ + SECItem derPublicationInfo; /* We aren't creating + * PKIPublicationInfo's, so + * we'll store away the der + * here if we decode one that + * does have pubInfo. + */ SECItem unwrappedPrivKey; }; struct CMMFCertResponseStr { - SECItem certReqId; - CMMFPKIStatusInfo status; /*PKIStatusInfo*/ + SECItem certReqId; + CMMFPKIStatusInfo status; /*PKIStatusInfo*/ CMMFCertifiedKeyPair *certifiedKeyPair; }; struct CMMFCertRepContentStr { - CERTCertificate **caPubs; + CERTCertificate **caPubs; CMMFCertResponse **response; - PLArenaPool *poolp; - PRBool isDecoded; + PLArenaPool *poolp; + PRBool isDecoded; }; struct CMMFChallengeStr { - SECAlgorithmID *owf; - SECItem witness; - SECItem senderDER; - SECItem key; - SECItem challenge; - SECItem randomNumber; + SECAlgorithmID *owf; + SECItem witness; + SECItem senderDER; + SECItem key; + SECItem challenge; + SECItem randomNumber; }; struct CMMFRandStr { - SECItem integer; - SECItem senderHash; + SECItem integer; + SECItem senderHash; CERTGeneralName *sender; }; struct CMMFPOPODecKeyChallContentStr { CMMFChallenge **challenges; - PLArenaPool *poolp; - int numChallenges; - int numAllocated; + PLArenaPool *poolp; + int numChallenges; + int numAllocated; }; struct CMMFPOPODecKeyRespContentStr { - SECItem **responses; - PLArenaPool *poolp; + SECItem **responses; + PLArenaPool *poolp; }; struct CMMFKeyRecRepContentStr { - CMMFPKIStatusInfo status; /* PKIStatusInfo */ - CERTCertificate *newSigCert; - CERTCertificate **caCerts; + CMMFPKIStatusInfo status; /* PKIStatusInfo */ + CERTCertificate *newSigCert; + CERTCertificate **caCerts; CMMFCertifiedKeyPair **keyPairHist; - PLArenaPool *poolp; - int numKeyPairs; - int allocKeyPairs; - PRBool isDecoded; + PLArenaPool *poolp; + int numKeyPairs; + int allocKeyPairs; + PRBool isDecoded; }; #endif /* _CMMFIT_H_ */ - diff --git a/security/nss/lib/crmf/cmmfrec.c b/security/nss/lib/crmf/cmmfrec.c index 880e846f0507..068a0d84d5ed 100644 --- a/security/nss/lib/crmf/cmmfrec.c +++ b/security/nss/lib/crmf/cmmfrec.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * This file will implement the functions related to key recovery in + * This file will implement the functions related to key recovery in * CMMF */ @@ -13,10 +13,10 @@ #include "secitem.h" #include "keyhi.h" -CMMFKeyRecRepContent* +CMMFKeyRecRepContent * CMMF_CreateKeyRecRepContent(void) { - PLArenaPool *poolp; + PLArenaPool *poolp; CMMFKeyRecRepContent *keyRecContent; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); @@ -26,7 +26,7 @@ CMMF_CreateKeyRecRepContent(void) keyRecContent = PORT_ArenaZNew(poolp, CMMFKeyRecRepContent); if (keyRecContent == NULL) { PORT_FreeArena(poolp, PR_FALSE); - return NULL; + return NULL; } keyRecContent->poolp = poolp; return keyRecContent; @@ -37,25 +37,24 @@ CMMF_DestroyKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep) { PORT_Assert(inKeyRecRep != NULL); if (inKeyRecRep != NULL && inKeyRecRep->poolp != NULL) { - int i; + int i; - if (!inKeyRecRep->isDecoded && inKeyRecRep->newSigCert != NULL) { - CERT_DestroyCertificate(inKeyRecRep->newSigCert); - } - if (inKeyRecRep->caCerts != NULL) { - for (i=0; inKeyRecRep->caCerts[i] != NULL; i++) { - CERT_DestroyCertificate(inKeyRecRep->caCerts[i]); - } - } - if (inKeyRecRep->keyPairHist != NULL) { - for (i=0; inKeyRecRep->keyPairHist[i] != NULL; i++) { - if (inKeyRecRep->keyPairHist[i]->certOrEncCert.choice == - cmmfCertificate) { - CERT_DestroyCertificate(inKeyRecRep->keyPairHist[i]-> - certOrEncCert.cert.certificate); - } - } - } + if (!inKeyRecRep->isDecoded && inKeyRecRep->newSigCert != NULL) { + CERT_DestroyCertificate(inKeyRecRep->newSigCert); + } + if (inKeyRecRep->caCerts != NULL) { + for (i = 0; inKeyRecRep->caCerts[i] != NULL; i++) { + CERT_DestroyCertificate(inKeyRecRep->caCerts[i]); + } + } + if (inKeyRecRep->keyPairHist != NULL) { + for (i = 0; inKeyRecRep->keyPairHist[i] != NULL; i++) { + if (inKeyRecRep->keyPairHist[i]->certOrEncCert.choice == + cmmfCertificate) { + CERT_DestroyCertificate(inKeyRecRep->keyPairHist[i]->certOrEncCert.cert.certificate); + } + } + } PORT_FreeArena(inKeyRecRep->poolp, PR_TRUE); } return SECSuccess; @@ -63,52 +62,53 @@ CMMF_DestroyKeyRecRepContent(CMMFKeyRecRepContent *inKeyRecRep) SECStatus CMMF_KeyRecRepContentSetPKIStatusInfoStatus(CMMFKeyRecRepContent *inKeyRecRep, - CMMFPKIStatus inPKIStatus) + CMMFPKIStatus inPKIStatus) { PORT_Assert(inKeyRecRep != NULL && inPKIStatus >= cmmfGranted && - inPKIStatus < cmmfNumPKIStatus); + inPKIStatus < cmmfNumPKIStatus); if (inKeyRecRep == NULL) { return SECFailure; } - - return cmmf_PKIStatusInfoSetStatus(&inKeyRecRep->status, - inKeyRecRep->poolp, - inPKIStatus); + + return cmmf_PKIStatusInfoSetStatus(&inKeyRecRep->status, + inKeyRecRep->poolp, + inPKIStatus); } SECStatus CMMF_KeyRecRepContentSetNewSignCert(CMMFKeyRecRepContent *inKeyRecRep, - CERTCertificate *inNewSignCert) + CERTCertificate *inNewSignCert) { - PORT_Assert (inKeyRecRep != NULL && inNewSignCert != NULL); + PORT_Assert(inKeyRecRep != NULL && inNewSignCert != NULL); if (inKeyRecRep == NULL || inNewSignCert == NULL) { return SECFailure; } if (!inKeyRecRep->isDecoded && inKeyRecRep->newSigCert) { - CERT_DestroyCertificate(inKeyRecRep->newSigCert); + CERT_DestroyCertificate(inKeyRecRep->newSigCert); } inKeyRecRep->isDecoded = PR_FALSE; inKeyRecRep->newSigCert = CERT_DupCertificate(inNewSignCert); - return (inKeyRecRep->newSigCert == NULL) ? SECFailure : SECSuccess; + return (inKeyRecRep->newSigCert == NULL) ? SECFailure : SECSuccess; } SECStatus CMMF_KeyRecRepContentSetCACerts(CMMFKeyRecRepContent *inKeyRecRep, - CERTCertList *inCACerts) + CERTCertList *inCACerts) { SECStatus rv; void *mark; - PORT_Assert (inKeyRecRep != NULL && inCACerts != NULL); + PORT_Assert(inKeyRecRep != NULL && inCACerts != NULL); if (inKeyRecRep == NULL || inCACerts == NULL) { return SECFailure; } mark = PORT_ArenaMark(inKeyRecRep->poolp); rv = cmmf_ExtractCertsFromList(inCACerts, inKeyRecRep->poolp, - &inKeyRecRep->caCerts); + &inKeyRecRep->caCerts); if (rv != SECSuccess) { PORT_ArenaRelease(inKeyRecRep->poolp, mark); - } else { + } + else { PORT_ArenaUnmark(inKeyRecRep->poolp, mark); } return rv; @@ -116,49 +116,49 @@ CMMF_KeyRecRepContentSetCACerts(CMMFKeyRecRepContent *inKeyRecRep, SECStatus CMMF_KeyRecRepContentSetCertifiedKeyPair(CMMFKeyRecRepContent *inKeyRecRep, - CERTCertificate *inCert, - SECKEYPrivateKey *inPrivKey, - SECKEYPublicKey *inPubKey) + CERTCertificate *inCert, + SECKEYPrivateKey *inPrivKey, + SECKEYPublicKey *inPubKey) { CMMFCertifiedKeyPair *keyPair; - CRMFEncryptedValue *dummy; - PLArenaPool *poolp; - void *mark; - SECStatus rv; + CRMFEncryptedValue *dummy; + PLArenaPool *poolp; + void *mark; + SECStatus rv; - PORT_Assert (inKeyRecRep != NULL && - inCert != NULL && - inPrivKey != NULL && - inPubKey != NULL); + PORT_Assert(inKeyRecRep != NULL && + inCert != NULL && + inPrivKey != NULL && + inPubKey != NULL); if (inKeyRecRep == NULL || - inCert == NULL || - inPrivKey == NULL || - inPubKey == NULL) { + inCert == NULL || + inPrivKey == NULL || + inPubKey == NULL) { return SECFailure; } poolp = inKeyRecRep->poolp; mark = PORT_ArenaMark(poolp); if (inKeyRecRep->keyPairHist == NULL) { - inKeyRecRep->keyPairHist = PORT_ArenaNewArray(poolp, - CMMFCertifiedKeyPair*, - (CMMF_MAX_KEY_PAIRS+1)); - if (inKeyRecRep->keyPairHist == NULL) { - goto loser; - } - inKeyRecRep->allocKeyPairs = CMMF_MAX_KEY_PAIRS; - inKeyRecRep->numKeyPairs = 0; + inKeyRecRep->keyPairHist = PORT_ArenaNewArray(poolp, + CMMFCertifiedKeyPair *, + (CMMF_MAX_KEY_PAIRS + 1)); + if (inKeyRecRep->keyPairHist == NULL) { + goto loser; + } + inKeyRecRep->allocKeyPairs = CMMF_MAX_KEY_PAIRS; + inKeyRecRep->numKeyPairs = 0; } if (inKeyRecRep->allocKeyPairs == inKeyRecRep->numKeyPairs) { goto loser; } - + keyPair = PORT_ArenaZNew(poolp, CMMFCertifiedKeyPair); if (keyPair == NULL) { goto loser; } rv = cmmf_CertOrEncCertSetCertificate(&keyPair->certOrEncCert, - poolp, inCert); + poolp, inCert); if (rv != SECSuccess) { goto loser; } @@ -166,12 +166,12 @@ CMMF_KeyRecRepContentSetCertifiedKeyPair(CMMFKeyRecRepContent *inKeyRecRep, if (keyPair->privateKey == NULL) { goto loser; } - dummy = crmf_create_encrypted_value_wrapped_privkey(inPrivKey, inPubKey, - keyPair->privateKey); + dummy = crmf_create_encrypted_value_wrapped_privkey(inPrivKey, inPubKey, + keyPair->privateKey); PORT_Assert(dummy == keyPair->privateKey); if (dummy != keyPair->privateKey) { crmf_destroy_encrypted_value(dummy, PR_TRUE); - goto loser; + goto loser; } inKeyRecRep->keyPairHist[inKeyRecRep->numKeyPairs] = keyPair; inKeyRecRep->numKeyPairs++; @@ -179,7 +179,7 @@ CMMF_KeyRecRepContentSetCertifiedKeyPair(CMMFKeyRecRepContent *inKeyRecRep, PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); return SECFailure; } @@ -194,12 +194,12 @@ CMMF_KeyRecRepContentGetPKIStatusInfoStatus(CMMFKeyRecRepContent *inKeyRecRep) return cmmf_PKIStatusInfoGetStatus(&inKeyRecRep->status); } -CERTCertificate* +CERTCertificate * CMMF_KeyRecRepContentGetNewSignCert(CMMFKeyRecRepContent *inKeyRecRep) { PORT_Assert(inKeyRecRep != NULL); - if (inKeyRecRep == NULL || - inKeyRecRep->newSigCert == NULL) { + if (inKeyRecRep == NULL || + inKeyRecRep->newSigCert == NULL) { return NULL; } /* newSigCert may not be a real certificate, it may be a hand decoded @@ -208,12 +208,12 @@ CMMF_KeyRecRepContentGetNewSignCert(CMMFKeyRecRepContent *inKeyRecRep) * portion so that we never wind up with a half formed CERTCertificate * here. In this case the call would be to CERT_DupCertificate. */ - return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), - &inKeyRecRep->newSigCert->signatureWrap.data, - NULL, PR_FALSE, PR_TRUE); + return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), + &inKeyRecRep->newSigCert->signatureWrap.data, + NULL, PR_FALSE, PR_TRUE); } -CERTCertList* +CERTCertList * CMMF_KeyRecRepContentGetCACerts(CMMFKeyRecRepContent *inKeyRecRep) { PORT_Assert(inKeyRecRep != NULL); @@ -223,7 +223,7 @@ CMMF_KeyRecRepContentGetCACerts(CMMFKeyRecRepContent *inKeyRecRep) return cmmf_MakeCertList(inKeyRecRep->caCerts); } -int +int CMMF_KeyRecRepContentGetNumKeyPairs(CMMFKeyRecRepContent *inKeyRecRep) { PORT_Assert(inKeyRecRep != NULL); @@ -232,87 +232,86 @@ CMMF_KeyRecRepContentGetNumKeyPairs(CMMFKeyRecRepContent *inKeyRecRep) PRBool cmmf_KeyRecRepContentIsValidIndex(CMMFKeyRecRepContent *inKeyRecRep, - int inIndex) + int inIndex) { int numKeyPairs = CMMF_KeyRecRepContentGetNumKeyPairs(inKeyRecRep); - + return (PRBool)(inIndex >= 0 && inIndex < numKeyPairs); } -CMMFCertifiedKeyPair* +CMMFCertifiedKeyPair * CMMF_KeyRecRepContentGetCertKeyAtIndex(CMMFKeyRecRepContent *inKeyRecRep, - int inIndex) + int inIndex) { CMMFCertifiedKeyPair *newKeyPair; - SECStatus rv; + SECStatus rv; PORT_Assert(inKeyRecRep != NULL && - cmmf_KeyRecRepContentIsValidIndex(inKeyRecRep, inIndex)); + cmmf_KeyRecRepContentIsValidIndex(inKeyRecRep, inIndex)); if (inKeyRecRep == NULL || - !cmmf_KeyRecRepContentIsValidIndex(inKeyRecRep, inIndex)) { + !cmmf_KeyRecRepContentIsValidIndex(inKeyRecRep, inIndex)) { return NULL; } newKeyPair = PORT_ZNew(CMMFCertifiedKeyPair); if (newKeyPair == NULL) { return NULL; } - rv = cmmf_CopyCertifiedKeyPair(NULL, newKeyPair, - inKeyRecRep->keyPairHist[inIndex]); + rv = cmmf_CopyCertifiedKeyPair(NULL, newKeyPair, + inKeyRecRep->keyPairHist[inIndex]); if (rv != SECSuccess) { CMMF_DestroyCertifiedKeyPair(newKeyPair); - newKeyPair = NULL; + newKeyPair = NULL; } return newKeyPair; } -SECStatus +SECStatus CMMF_CertifiedKeyPairUnwrapPrivKey(CMMFCertifiedKeyPair *inKeyPair, - SECKEYPrivateKey *inPrivKey, - SECItem *inNickName, - PK11SlotInfo *inSlot, - CERTCertDBHandle *inCertdb, - SECKEYPrivateKey **destPrivKey, - void *wincx) + SECKEYPrivateKey *inPrivKey, + SECItem *inNickName, + PK11SlotInfo *inSlot, + CERTCertDBHandle *inCertdb, + SECKEYPrivateKey **destPrivKey, + void *wincx) { CERTCertificate *cert; - SECItem keyUsageValue = {siBuffer, NULL, 0}; + SECItem keyUsageValue = { siBuffer, NULL, 0 }; unsigned char keyUsage = 0x0; SECKEYPublicKey *pubKey; SECStatus rv; PORT_Assert(inKeyPair != NULL && - inPrivKey != NULL && inCertdb != NULL); - if (inKeyPair == NULL || - inPrivKey == NULL || - inKeyPair->privateKey == NULL || - inCertdb == NULL) { + inPrivKey != NULL && inCertdb != NULL); + if (inKeyPair == NULL || + inPrivKey == NULL || + inKeyPair->privateKey == NULL || + inCertdb == NULL) { return SECFailure; } - + cert = CMMF_CertifiedKeyPairGetCertificate(inKeyPair, inCertdb); CERT_FindKeyUsageExtension(cert, &keyUsageValue); if (keyUsageValue.data != NULL) { keyUsage = keyUsageValue.data[3]; - PORT_Free(keyUsageValue.data); + PORT_Free(keyUsageValue.data); } pubKey = CERT_ExtractPublicKey(cert); rv = crmf_encrypted_value_unwrap_priv_key(NULL, inKeyPair->privateKey, - inPrivKey, pubKey, - inNickName, inSlot, keyUsage, - destPrivKey, wincx); + inPrivKey, pubKey, + inNickName, inSlot, keyUsage, + destPrivKey, wincx); SECKEY_DestroyPublicKey(pubKey); CERT_DestroyCertificate(cert); return rv; } - -PRBool +PRBool CMMF_KeyRecRepContentHasCACerts(CMMFKeyRecRepContent *inKeyRecRep) { PORT_Assert(inKeyRecRep != NULL); if (inKeyRecRep == NULL) { return PR_FALSE; } - return (PRBool)(inKeyRecRep->caCerts != NULL && - inKeyRecRep->caCerts[0] != NULL); + return (PRBool)(inKeyRecRep->caCerts != NULL && + inKeyRecRep->caCerts[0] != NULL); } diff --git a/security/nss/lib/crmf/cmmfresp.c b/security/nss/lib/crmf/cmmfresp.c index 420bbe4db82f..1be8c47f344e 100644 --- a/security/nss/lib/crmf/cmmfresp.c +++ b/security/nss/lib/crmf/cmmfresp.c @@ -4,7 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * This file will contain all routines dealing with creating a + * This file will contain all routines dealing with creating a * CMMFCertRepContent structure through Create/Set functions. */ @@ -15,11 +15,11 @@ #include "secitem.h" #include "secder.h" -CMMFCertRepContent* +CMMFCertRepContent * CMMF_CreateCertRepContent(void) { CMMFCertRepContent *retCertRep; - PLArenaPool *poolp; + PLArenaPool *poolp; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { @@ -31,47 +31,49 @@ CMMF_CreateCertRepContent(void) } retCertRep->poolp = poolp; return retCertRep; - loser: +loser: if (poolp != NULL) { PORT_FreeArena(poolp, PR_FALSE); } return NULL; } -SECStatus +SECStatus cmmf_CertOrEncCertSetCertificate(CMMFCertOrEncCert *certOrEncCert, - PLArenaPool *poolp, - CERTCertificate *inCert) + PLArenaPool *poolp, + CERTCertificate *inCert) { - SECItem *derDest = NULL; - SECStatus rv = SECFailure; + SECItem *derDest = NULL; + SECStatus rv = SECFailure; if (inCert->derCert.data == NULL) { - derDest = SEC_ASN1EncodeItem(NULL, NULL, inCert, - CMMFCertOrEncCertCertificateTemplate); - if (derDest == NULL) { - goto loser; - } - } else { + derDest = SEC_ASN1EncodeItem(NULL, NULL, inCert, + CMMFCertOrEncCertCertificateTemplate); + if (derDest == NULL) { + goto loser; + } + } + else { derDest = SECITEM_DupItem(&inCert->derCert); - if (derDest == NULL) { - goto loser; - } + if (derDest == NULL) { + goto loser; + } } PORT_Assert(certOrEncCert->cert.certificate == NULL); certOrEncCert->cert.certificate = CERT_DupCertificate(inCert); certOrEncCert->choice = cmmfCertificate; if (poolp != NULL) { rv = SECITEM_CopyItem(poolp, &certOrEncCert->derValue, derDest); - if (rv != SECSuccess) { - goto loser; - } - } else { + if (rv != SECSuccess) { + goto loser; + } + } + else { certOrEncCert->derValue = *derDest; } PORT_Free(derDest); return SECSuccess; - loser: +loser: if (derDest != NULL) { SECITEM_FreeItem(derDest, PR_TRUE); } @@ -79,41 +81,41 @@ cmmf_CertOrEncCertSetCertificate(CMMFCertOrEncCert *certOrEncCert, } SECStatus -cmmf_ExtractCertsFromList(CERTCertList *inCertList, - PLArenaPool *poolp, - CERTCertificate ***certArray) +cmmf_ExtractCertsFromList(CERTCertList *inCertList, + PLArenaPool *poolp, + CERTCertificate ***certArray) { - CERTCertificate **arrayLocalCopy; - CERTCertListNode *node; - int numNodes = 0, i; + CERTCertificate **arrayLocalCopy; + CERTCertListNode *node; + int numNodes = 0, i; for (node = CERT_LIST_HEAD(inCertList); !CERT_LIST_END(node, inCertList); - node = CERT_LIST_NEXT(node)) { + node = CERT_LIST_NEXT(node)) { numNodes++; } arrayLocalCopy = *certArray = (poolp == NULL) ? - PORT_NewArray(CERTCertificate*, (numNodes+1)) : - PORT_ArenaNewArray(poolp, CERTCertificate*, (numNodes+1)); + PORT_NewArray(CERTCertificate *, (numNodes + 1)) : + PORT_ArenaNewArray(poolp, CERTCertificate *, (numNodes + 1)); if (arrayLocalCopy == NULL) { return SECFailure; } - for (node = CERT_LIST_HEAD(inCertList), i=0; - !CERT_LIST_END(node, inCertList); - node = CERT_LIST_NEXT(node), i++) { + for (node = CERT_LIST_HEAD(inCertList), i = 0; + !CERT_LIST_END(node, inCertList); + node = CERT_LIST_NEXT(node), i++) { arrayLocalCopy[i] = CERT_DupCertificate(node->cert); - if (arrayLocalCopy[i] == NULL) { - int j; - - for (j=0; j 0); + PORT_Assert(inCertRepContent != NULL && + inCertResponses != NULL && + inNumResponses > 0); if (inCertRepContent == NULL || - inCertResponses == NULL || - inCertRepContent->response != NULL) { + inCertResponses == NULL || + inCertRepContent->response != NULL) { return SECFailure; } poolp = inCertRepContent->poolp; mark = PORT_ArenaMark(poolp); - respArr = inCertRepContent->response = - PORT_ArenaZNewArray(poolp, CMMFCertResponse*, (inNumResponses+1)); + respArr = inCertRepContent->response = + PORT_ArenaZNewArray(poolp, CMMFCertResponse *, (inNumResponses + 1)); if (respArr == NULL) { goto loser; } - for (i=0; i= cmmfGranted - && inPKIStatus < cmmfNumPKIStatus); + PORT_Assert(inCertResp != NULL && inPKIStatus >= cmmfGranted && + inPKIStatus < cmmfNumPKIStatus); - if (inCertResp == NULL) { + if (inCertResp == NULL) { return SECFailure; } return cmmf_PKIStatusInfoSetStatus(&inCertResp->status, NULL, - inPKIStatus); + inPKIStatus); } SECStatus -CMMF_CertResponseSetCertificate (CMMFCertResponse *inCertResp, - CERTCertificate *inCertificate) +CMMF_CertResponseSetCertificate(CMMFCertResponse *inCertResp, + CERTCertificate *inCertificate) { CMMFCertifiedKeyPair *keyPair = NULL; - SECStatus rv = SECFailure; + SECStatus rv = SECFailure; PORT_Assert(inCertResp != NULL && inCertificate != NULL); if (inCertResp == NULL || inCertificate == NULL) { return SECFailure; } if (inCertResp->certifiedKeyPair == NULL) { - keyPair = inCertResp->certifiedKeyPair = - PORT_ZNew(CMMFCertifiedKeyPair); - } else { + keyPair = inCertResp->certifiedKeyPair = + PORT_ZNew(CMMFCertifiedKeyPair); + } + else { keyPair = inCertResp->certifiedKeyPair; } if (keyPair == NULL) { goto loser; } rv = cmmf_CertOrEncCertSetCertificate(&keyPair->certOrEncCert, NULL, - inCertificate); + inCertificate); if (rv != SECSuccess) { goto loser; } return SECSuccess; - loser: +loser: if (keyPair) { if (keyPair->certOrEncCert.derValue.data) { - PORT_Free(keyPair->certOrEncCert.derValue.data); - } - PORT_Free(keyPair); + PORT_Free(keyPair->certOrEncCert.derValue.data); + } + PORT_Free(keyPair); } return rv; } - SECStatus CMMF_CertRepContentSetCAPubs(CMMFCertRepContent *inCertRepContent, - CERTCertList *inCAPubs) + CERTCertList *inCAPubs) { - PLArenaPool *poolp; - void *mark; - SECStatus rv; + PLArenaPool *poolp; + void *mark; + SECStatus rv; PORT_Assert(inCertRepContent != NULL && - inCAPubs != NULL && - inCertRepContent->caPubs == NULL); - + inCAPubs != NULL && + inCertRepContent->caPubs == NULL); + if (inCertRepContent == NULL || - inCAPubs == NULL || inCertRepContent == NULL) { + inCAPubs == NULL || inCertRepContent == NULL) { return SECFailure; } @@ -260,24 +262,25 @@ CMMF_CertRepContentSetCAPubs(CMMFCertRepContent *inCertRepContent, mark = PORT_ArenaMark(poolp); rv = cmmf_ExtractCertsFromList(inCAPubs, poolp, - &inCertRepContent->caPubs); + &inCertRepContent->caPubs); if (rv != SECSuccess) { PORT_ArenaRelease(poolp, mark); - } else { + } + else { PORT_ArenaUnmark(poolp, mark); } return rv; } -CERTCertificate* +CERTCertificate * CMMF_CertifiedKeyPairGetCertificate(CMMFCertifiedKeyPair *inCertKeyPair, - CERTCertDBHandle *inCertdb) + CERTCertDBHandle *inCertdb) { PORT_Assert(inCertKeyPair != NULL); if (inCertKeyPair == NULL) { return NULL; } return cmmf_CertOrEncCertGetCertificate(&inCertKeyPair->certOrEncCert, - inCertdb); + inCertdb); } diff --git a/security/nss/lib/crmf/cmmft.h b/security/nss/lib/crmf/cmmft.h index aea64b0f46d1..e39f19ed3a60 100644 --- a/security/nss/lib/crmf/cmmft.h +++ b/security/nss/lib/crmf/cmmft.h @@ -19,7 +19,7 @@ typedef enum { } CMMFCertOrEncCertChoice; /* - * This is the enumeration and the corresponding values used to + * This is the enumeration and the corresponding values used to * represent the CMMF type PKIStatus */ typedef enum { @@ -51,19 +51,19 @@ typedef enum { cmmfNoFailureInfo = 9 } CMMFPKIFailureInfo; -typedef struct CMMFPKIStatusInfoStr CMMFPKIStatusInfo; -typedef struct CMMFCertOrEncCertStr CMMFCertOrEncCert; -typedef struct CMMFCertifiedKeyPairStr CMMFCertifiedKeyPair; -typedef struct CMMFCertResponseStr CMMFCertResponse; -typedef struct CMMFCertResponseSeqStr CMMFCertResponseSeq; +typedef struct CMMFPKIStatusInfoStr CMMFPKIStatusInfo; +typedef struct CMMFCertOrEncCertStr CMMFCertOrEncCert; +typedef struct CMMFCertifiedKeyPairStr CMMFCertifiedKeyPair; +typedef struct CMMFCertResponseStr CMMFCertResponse; +typedef struct CMMFCertResponseSeqStr CMMFCertResponseSeq; typedef struct CMMFPOPODecKeyChallContentStr CMMFPOPODecKeyChallContent; -typedef struct CMMFChallengeStr CMMFChallenge; -typedef struct CMMFRandStr CMMFRand; -typedef struct CMMFPOPODecKeyRespContentStr CMMFPOPODecKeyRespContent; -typedef struct CMMFKeyRecRepContentStr CMMFKeyRecRepContent; -typedef struct CMMFCertRepContentStr CMMFCertRepContent; +typedef struct CMMFChallengeStr CMMFChallenge; +typedef struct CMMFRandStr CMMFRand; +typedef struct CMMFPOPODecKeyRespContentStr CMMFPOPODecKeyRespContent; +typedef struct CMMFKeyRecRepContentStr CMMFKeyRecRepContent; +typedef struct CMMFCertRepContentStr CMMFCertRepContent; -/* Export this so people can call SEC_ASN1EncodeItem instead of having to +/* Export this so people can call SEC_ASN1EncodeItem instead of having to * write callbacks that are passed in to the high level encode function * for CMMFCertRepContent. */ diff --git a/security/nss/lib/crmf/crmf.h b/security/nss/lib/crmf/crmf.h index 9f36c2884596..c56e28913b10 100644 --- a/security/nss/lib/crmf/crmf.h +++ b/security/nss/lib/crmf/crmf.h @@ -3,7 +3,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #ifndef _CRMF_H_ #define _CRMF_H_ @@ -27,16 +26,16 @@ SEC_BEGIN_PROTOS * An opaque pointer that gets passed to the function fn * OUTPUT: * The function fn will be called multiple times. Look at the - * comments in crmft.h where the CRMFEncoderOutputCallback type is + * comments in crmft.h where the CRMFEncoderOutputCallback type is * defined for information on proper behavior of the function fn. * RETURN: * SECSuccess if encoding was successful. Any other return value * indicates an error occurred during encoding. */ -extern SECStatus - CRMF_EncodeCertReqMsg (CRMFCertReqMsg *inCertReqMsg, - CRMFEncoderOutputCallback fn, - void *arg); +extern SECStatus +CRMF_EncodeCertReqMsg(CRMFCertReqMsg *inCertReqMsg, + CRMFEncoderOutputCallback fn, + void *arg); /* * FUNCTION: CRMF_EncoderCertRequest @@ -49,17 +48,17 @@ extern SECStatus * arg * An opaque pointer that gets passed to the function fn. * OUTPUT: - * The function fn will be called, probably multiple times whenever - * the ASN1 encoder wants to write out DER-encoded bytes. Look at the + * The function fn will be called, probably multiple times whenever + * the ASN1 encoder wants to write out DER-encoded bytes. Look at the * comments in crmft.h where the CRMFEncoderOutputCallback type is * defined for information on proper behavior of the function fn. * RETURN: - * SECSuccess if encoding was successful. Any other return value + * SECSuccess if encoding was successful. Any other return value * indicates an error occurred during encoding. */ -extern SECStatus CRMF_EncodeCertRequest (CRMFCertRequest *inCertReq, - CRMFEncoderOutputCallback fn, - void *arg); +extern SECStatus CRMF_EncodeCertRequest(CRMFCertRequest *inCertReq, + CRMFEncoderOutputCallback fn, + void *arg); /* * FUNCTION: CRMF_EncodeCertReqMessages * INPUTS: @@ -77,25 +76,24 @@ extern SECStatus CRMF_EncodeCertRequest (CRMFCertRequest *inCertReq, * * NOTES: * The parameter inCertReqMsgs needs to be an array with a NULL pointer - * to signal the end of messages. An array in the form of + * to signal the end of messages. An array in the form of * {m1, m2, m3, NULL, m4, ...} will only encode the messages m1, m2, and * m3. All messages from m4 on will not be looked at by the library. * * OUTPUT: - * The function fn will be called, probably multiple times. Look at the + * The function fn will be called, probably multiple times. Look at the * comments in crmft.h where the CRMFEncoderOutputCallback type is * defined for information on proper behavior of the function fn. * * RETURN: - * SECSuccess if encoding the Certificate Request Messages was successful. + * SECSuccess if encoding the Certificate Request Messages was successful. * Any other return value indicates an error occurred while encoding the * certificate request messages. */ -extern SECStatus - CRMF_EncodeCertReqMessages(CRMFCertReqMsg **inCertReqMsgs, - CRMFEncoderOutputCallback fn, - void *arg); - +extern SECStatus +CRMF_EncodeCertReqMessages(CRMFCertReqMsg **inCertReqMsgs, + CRMFEncoderOutputCallback fn, + void *arg); /* * FUNCTION: CRMF_CreateCertReqMsg @@ -104,19 +102,19 @@ extern SECStatus * OUTPUT: * An empty CRMF Certificate Request Message. * Before encoding this message, the user must set - * the ProofOfPossession field and the certificate + * the ProofOfPossession field and the certificate * request which are necessary for the full message. * After the user no longer needs this CertReqMsg, * the user must call CRMF_DestroyCertReqMsg to free * all memory associated with the Certificate Request * Message. * RETURN: - * A pointer to a Certificate Request Message. The user - * must pass the return value of this function to + * A pointer to a Certificate Request Message. The user + * must pass the return value of this function to * CRMF_DestroyCertReqMsg after the Certificate Request * Message is no longer necessary. */ -extern CRMFCertReqMsg* CRMF_CreateCertReqMsg(void); +extern CRMFCertReqMsg *CRMF_CreateCertReqMsg(void); /* * FUNCTION: CRMF_DestroyCertReqMsg @@ -127,12 +125,12 @@ extern CRMFCertReqMsg* CRMF_CreateCertReqMsg(void); * This function frees all the memory used for the Certificate * Request Message and all the memory used in making copies of * fields of elelments of the message, eg. the Proof Of Possession - * filed and the Cetificate Request. + * filed and the Cetificate Request. * RETURN: * SECSuccess if destruction was successful. Any other return value * indicates an error while trying to free the memory associated * with inCertReqMsg. - * + * */ extern SECStatus CRMF_DestroyCertReqMsg(CRMFCertReqMsg *inCertReqMsg); @@ -151,14 +149,14 @@ extern SECStatus CRMF_DestroyCertReqMsg(CRMFCertReqMsg *inCertReqMsg); * the user must not call this function until the Certificate Request * has been fully built and is ready to be encoded. * RETURN: - * SECSuccess + * SECSuccess * If copying the Certificate as a member of the Certificate * request message was successful. * Any other return value indicates a failure to copy the Certificate * Request and make it a part of the Certificate Request Message. */ -extern SECStatus CRMF_CertReqMsgSetCertRequest(CRMFCertReqMsg *inCertReqMsg, - CRMFCertRequest *inCertReq); +extern SECStatus CRMF_CertReqMsgSetCertRequest(CRMFCertReqMsg *inCertReqMsg, + CRMFCertRequest *inCertReq); /* * FUNCTION: CRMF_CreateCertRequest @@ -176,7 +174,7 @@ extern SECStatus CRMF_CertReqMsgSetCertRequest(CRMFCertReqMsg *inCertReqMsg, * A pointer to the new Certificate Request. A NULL return value * indicates an error in creating the Certificate Request. */ -extern CRMFCertRequest *CRMF_CreateCertRequest (PRUint32 inRequestID); +extern CRMFCertRequest *CRMF_CreateCertRequest(PRUint32 inRequestID); /* * FUNCTION: CRMF_DestroyCertRequest @@ -185,12 +183,12 @@ extern CRMFCertRequest *CRMF_CreateCertRequest (PRUint32 inRequestID); * The Certificate Request that will be destroyed. * RETURN: * SECSuccess - * If freeing the memory associated with the certificate request + * If freeing the memory associated with the certificate request * was successful. - * Any other return value indicates an error while trying to free the + * Any other return value indicates an error while trying to free the * memory. */ -extern SECStatus CRMF_DestroyCertRequest (CRMFCertRequest *inCertReq); +extern SECStatus CRMF_DestroyCertRequest(CRMFCertRequest *inCertReq); /* * FUNCTION: CRMF_CreateCertExtension @@ -201,16 +199,16 @@ extern SECStatus CRMF_DestroyCertRequest (CRMFCertRequest *inCertReq); * will fail. * isCritical * A boolean value stating if the extension value is crtical. PR_TRUE - * means the value is crtical. PR_FALSE indicates the value is not + * means the value is crtical. PR_FALSE indicates the value is not * critical. * data * This is the data associated with the extension. The user of the * library is responsible for making sure the value passed in is a * valid interpretation of the certificate extension. * NOTES: - * Use this function to create CRMFCertExtension Structures which will - * then be passed to CRMF_AddFieldToCertTemplate as part of the - * CRMFCertCreationInfo.extensions The user must call + * Use this function to create CRMFCertExtension Structures which will + * then be passed to CRMF_AddFieldToCertTemplate as part of the + * CRMFCertCreationInfo.extensions The user must call * CRMF_DestroyCertExtension after the extension has been added to a certifcate * and the extension is no longer needed. * @@ -218,9 +216,9 @@ extern SECStatus CRMF_DestroyCertRequest (CRMFCertRequest *inCertReq); * A pointer to a newly created CertExtension. A return value of NULL * indicates the id passed in was an invalid certificate extension. */ -extern CRMFCertExtension *CRMF_CreateCertExtension(SECOidTag id, - PRBool isCritical, - SECItem *data); +extern CRMFCertExtension *CRMF_CreateCertExtension(SECOidTag id, + PRBool isCritical, + SECItem *data); /* * FUNCTION: CMRF_DestroyCertExtension @@ -232,12 +230,12 @@ extern CRMFCertExtension *CRMF_CreateCertExtension(SECOidTag id, * * RETURN: * SECSuccess if freeing the memory associated with the certificate extension - * was successful. Any other error indicates an error while freeing the + * was successful. Any other error indicates an error while freeing the * memory. */ extern SECStatus CRMF_DestroyCertExtension(CRMFCertExtension *inExtension); -/* +/* * FUNCTION: CRMF_CertRequestSetTemplateField * INPUTS: * inCertReq @@ -255,7 +253,7 @@ extern SECStatus CRMF_DestroyCertExtension(CRMFCertExtension *inExtension); * depending on the template field one wants to set. * * Look in crmft.h for the definition of CRMFCertTemplateField. - * + * * In all cases, the library makes copies of the data passed in. * * CRMFCertTemplateField Type of data What data means @@ -267,23 +265,23 @@ extern SECStatus CRMF_DestroyCertExtension(CRMFCertExtension *inExtension); * crmfSerialNumber long * The serial number * for the cert to be * created. - * + * * crmfSigningAlg SECAlgorithm * The ASN.1 object ID for * the algorithm used in encoding * the certificate. * - * crmfIssuer CERTName * Certificate Library + * crmfIssuer CERTName * Certificate Library * representation of the ASN1 type * Name from X.509 * * crmfValidity CRMFValidityCreationInfo * At least one of the two * fields in the structure must - * be present. A NULL pointer + * be present. A NULL pointer * in the structure indicates - * that member should not be + * that member should not be * added. * - * crmfSubject CERTName * Certificate Library + * crmfSubject CERTName * Certificate Library * representation of the ASN1 type * Name from X.509 * @@ -301,23 +299,23 @@ extern SECStatus CRMF_DestroyCertExtension(CRMFCertExtension *inExtension); * and not the number of bytes. * * crmfExtension CRMFCertExtCreationInfo * A pointer to the structure - * populated with an array of + * populated with an array of * of certificate extensions * and an integer that tells * how many elements are in the * array. Look in crmft.h for - * the definition of + * the definition of * CRMFCertExtCreationInfo * RETURN: * SECSuccess if adding the desired field to the template was successful. - * Any other return value indicates failure when trying to add the field + * Any other return value indicates failure when trying to add the field * to the template. - * + * */ extern SECStatus - CRMF_CertRequestSetTemplateField(CRMFCertRequest *inCertReq, - CRMFCertTemplateField inTemplateField, - void *data); +CRMF_CertRequestSetTemplateField(CRMFCertRequest *inCertReq, + CRMFCertTemplateField inTemplateField, + void *data); /* * FUNCTION: CRMF_CertRequestIsFieldPresent @@ -337,8 +335,8 @@ extern SECStatus * the function returns PR_FALSE. */ extern PRBool - CRMF_CertRequestIsFieldPresent(CRMFCertRequest *inCertReq, - CRMFCertTemplateField inTemplateField); +CRMF_CertRequestIsFieldPresent(CRMFCertRequest *inCertReq, + CRMFCertTemplateField inTemplateField); /* * FUNCTION: CRMF_CertRequestIsControlPresent @@ -363,9 +361,8 @@ extern PRBool * does not exist, the function will return PR_FALSE. */ extern PRBool - CRMF_CertRequestIsControlPresent(CRMFCertRequest *inCertReq, - CRMFControlType inControlType); - +CRMF_CertRequestIsControlPresent(CRMFCertRequest *inCertReq, + CRMFControlType inControlType); /* * FUNCTION: CRMF_CertRequestSetRegTokenControl @@ -376,7 +373,7 @@ extern PRBool * The UTF8 value which will be the Registration Token Control * for this Certificate Request. * NOTES: - * The library does no verification that the value passed in is + * The library does no verification that the value passed in is * a valid UTF8 value. The caller must make sure of this in order * to get an encoding that is valid. The library will ultimately * encode this value as it was passed in. @@ -387,7 +384,7 @@ extern PRBool * */ extern SECStatus CRMF_CertRequestSetRegTokenControl(CRMFCertRequest *inCertReq, - SECItem *value); + SECItem *value); /* * FUNCTION: CRMF_CertRequestSetAuthenticatorControl @@ -398,7 +395,7 @@ extern SECStatus CRMF_CertRequestSetRegTokenControl(CRMFCertRequest *inCertReq, * The UTF8 value that will become the Authenticator Control * for the passed in Certificate Request. * NOTES: - * The library does no verification that the value passed in is + * The library does no verification that the value passed in is * a valid UTF8 value. The caller must make sure of this in order * to get an encoding that is valid. The library will ultimately * encode this value as it was passed in. @@ -407,31 +404,31 @@ extern SECStatus CRMF_CertRequestSetRegTokenControl(CRMFCertRequest *inCertReq, * Any other return value indicates an unsuccessful attempt to add the * control. */ -extern SECStatus - CRMF_CertRequestSetAuthenticatorControl (CRMFCertRequest *inCertReq, - SECItem *value); +extern SECStatus +CRMF_CertRequestSetAuthenticatorControl(CRMFCertRequest *inCertReq, + SECItem *value); /* * FUNCTION: CRMF_CreateEncryptedKeyWithencryptedValue * INPUTS: * inPrivKey * This is the private key associated with a certificate that is - * being requested. This structure will eventually wind up as - * a part of the PKIArchiveOptions Control. + * being requested. This structure will eventually wind up as + * a part of the PKIArchiveOptions Control. * inCACert - * This is the certificate for the CA that will be receiving the + * This is the certificate for the CA that will be receiving the * certificate request for the private key passed in. * OUTPUT: - * A CRMFEncryptedKey that can ultimately be used as part of the + * A CRMFEncryptedKey that can ultimately be used as part of the * PKIArchiveOptions Control. * * RETURN: * A pointer to a CRMFEncyptedKey. A NULL return value indicates an erro * during the creation of the encrypted key. */ -extern CRMFEncryptedKey* - CRMF_CreateEncryptedKeyWithEncryptedValue(SECKEYPrivateKey *inPrivKey, - CERTCertificate *inCACert); +extern CRMFEncryptedKey * +CRMF_CreateEncryptedKeyWithEncryptedValue(SECKEYPrivateKey *inPrivKey, + CERTCertificate *inCACert); /* * FUNCTION: CRMF_DestroyEncryptedKey @@ -445,12 +442,12 @@ extern CRMFEncryptedKey* * value indicates an error while freeig the memroy. */ extern SECStatus CRMF_DestroyEncryptedKey(CRMFEncryptedKey *inEncrKey); - + /* * FUNCTION: CRMF_CreatePKIArchiveOptions * INPUTS: * inType - * An enumeration value indicating which option for + * An enumeration value indicating which option for * PKIArchiveOptions to use. * data * A pointer that will be type-cast and de-referenced according @@ -470,9 +467,9 @@ extern SECStatus CRMF_DestroyEncryptedKey(CRMFEncryptedKey *inEncrKey); * Request. A NULL pointer indicates an error occurred while creating * the CRMFPKIArchiveOptions Structure. */ -extern CRMFPKIArchiveOptions* - CRMF_CreatePKIArchiveOptions(CRMFPKIArchiveOptionsType inType, - void *data); +extern CRMFPKIArchiveOptions * +CRMF_CreatePKIArchiveOptions(CRMFPKIArchiveOptionsType inType, + void *data); /* * FUNCTION: CRMF_DestroyPKIArchiveOptions * INPUTS: @@ -484,8 +481,8 @@ extern CRMFPKIArchiveOptions* * SECSuccess if successful in freeing the memory used by 'inArchOpt' * Any other return value indicates an error while freeing the memory. */ -extern SECStatus - CRMF_DestroyPKIArchiveOptions(CRMFPKIArchiveOptions *inArchOpt); +extern SECStatus +CRMF_DestroyPKIArchiveOptions(CRMFPKIArchiveOptions *inArchOpt); /* * FUNCTION: CRMF_CertRequestSetPKIArchiveOptions @@ -503,9 +500,9 @@ extern SECStatus * request. Any other return value indicates an error when trying to add * the Archive Options to the Certificate Request. */ -extern SECStatus - CRMF_CertRequestSetPKIArchiveOptions(CRMFCertRequest *inCertReq, - CRMFPKIArchiveOptions *inOptions); +extern SECStatus +CRMF_CertRequestSetPKIArchiveOptions(CRMFCertRequest *inCertReq, + CRMFPKIArchiveOptions *inOptions); /* * FUNCTION: CRMF_CertReqMsgGetPOPType @@ -530,11 +527,11 @@ extern CRMFPOPChoice CRMF_CertReqMsgGetPOPType(CRMFCertReqMsg *inCertReqMsg); * InCertReqMsg * The Certificate Request Message to operate on. * NOTES: - * This function will set the method of Proof Of Possession to - * crmfRAVerified which means the RA has already verified the + * This function will set the method of Proof Of Possession to + * crmfRAVerified which means the RA has already verified the * requester does possess the private key. * RETURN: - * SECSuccess if adding RAVerified to the message is successful. + * SECSuccess if adding RAVerified to the message is successful. * Any other message indicates an error while trying to add RAVerified * as the Proof of Possession. */ @@ -551,7 +548,7 @@ extern SECStatus CRMF_CertReqMsgSetRAVerifiedPOP(CRMFCertReqMsg *inCertReqMsg); * inPubKey * The Public Key which corresponds to the Private Key passed in. * inCertForInput - * A Certificate that in the future may be used to create + * A Certificate that in the future may be used to create * POPOSigningKeyInput. * fn * A callback for retrieving a password which may be used in the @@ -560,13 +557,13 @@ extern SECStatus CRMF_CertReqMsgSetRAVerifiedPOP(CRMFCertReqMsg *inCertReqMsg); * An opaque pointer that would be passed to fn whenever it is * called. * NOTES: - * Adds Proof Of Possession to the CertRequest using the signature field - * of the ProofOfPossession field. NOTE: In order to use this option, + * Adds Proof Of Possession to the CertRequest using the signature field + * of the ProofOfPossession field. NOTE: In order to use this option, * the certificate template must contain the publicKey at the very minimum. - * + * * If you don't want the function to generate POPOSigningKeyInput, then * make sure the cert template already contains the subject and public key - * values. Currently creating POPOSigningKeyInput is not supported, so + * values. Currently creating POPOSigningKeyInput is not supported, so * a Message passed to this function must have the publicKey and the subject * as part of the template * @@ -583,8 +580,8 @@ extern SECStatus CRMF_CertReqMsgSetRAVerifiedPOP(CRMFCertReqMsg *inCertReqMsg); * If passed in, this certificate needs to be a valid certificate. * * The last 3 arguments are for future compatibility in case we ever want to - * support generating POPOSigningKeyInput. Pass in NULL for all 3 if you - * definitely don't want the function to even try to generate + * support generating POPOSigningKeyInput. Pass in NULL for all 3 if you + * definitely don't want the function to even try to generate * POPOSigningKeyInput. If you try to use POPOSigningKeyInput, the function * will fail. * @@ -593,13 +590,13 @@ extern SECStatus CRMF_CertReqMsgSetRAVerifiedPOP(CRMFCertReqMsg *inCertReqMsg); * Any other return value indicates an error in trying to add * the Signature Proof Of Possession. */ -extern SECStatus - CRMF_CertReqMsgSetSignaturePOP(CRMFCertReqMsg *inCertReqMsg, - SECKEYPrivateKey *inPrivKey, - SECKEYPublicKey *inPubKey, - CERTCertificate *inCertForInput, - CRMFMACPasswordCallback fn, - void *arg); +extern SECStatus +CRMF_CertReqMsgSetSignaturePOP(CRMFCertReqMsg *inCertReqMsg, + SECKEYPrivateKey *inPrivKey, + SECKEYPublicKey *inPubKey, + CERTCertificate *inCertForInput, + CRMFMACPasswordCallback fn, + void *arg); /* * FUNCTION: CRMF_CertReqMsgSetKeyEnciphermentPOP @@ -610,7 +607,7 @@ extern SECStatus * An enumeration indicating which POPOPrivKey Choice to use * in constructing the KeyEnciphermentPOP. * subseqMess - * This parameter must be provided iff inKeyChoice is + * This parameter must be provided iff inKeyChoice is * crmfSubsequentMessage. This details how the RA is to respond * in order to perform Proof Of Possession. Look in crmft.h under * the definition of CRMFSubseqMessOptions for possible values. @@ -618,7 +615,7 @@ extern SECStatus * This parameter only needs to be provided if inKeyChoice is * crmfThisMessage. The item should contain the encrypted private * key. - * + * * NOTES: * Adds Proof Of Possession using the keyEncipherment field of * ProofOfPossession. @@ -651,11 +648,11 @@ extern SECStatus * SECSuccess if adding KeyEnciphermentPOP was successful. Any other return * value indicates an error in adding KeyEnciphermentPOP. */ -extern SECStatus - CRMF_CertReqMsgSetKeyEnciphermentPOP(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKeyChoice inKeyChoice, - CRMFSubseqMessOptions subseqMess, - SECItem *encPrivKey); +extern SECStatus +CRMF_CertReqMsgSetKeyEnciphermentPOP(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKeyChoice inKeyChoice, + CRMFSubseqMessOptions subseqMess, + SECItem *encPrivKey); /* * FUNCTION: CRMF_CertReqMsgSetKeyAgreementPOP @@ -666,7 +663,7 @@ extern SECStatus * An enumeration indicating which POPOPrivKey Choice to use * in constructing the KeyAgreementPOP. * subseqMess - * This parameter must be provided iff inKeyChoice is + * This parameter must be provided iff inKeyChoice is * crmfSubsequentMessage. This details how the RA is to respond * in order to perform Proof Of Possession. Look in crmft.h under * the definition of CRMFSubseqMessOptions for possible values. @@ -700,11 +697,11 @@ extern SECStatus * * crmfDHMAC This option is not supported. */ -extern SECStatus - CRMF_CertReqMsgSetKeyAgreementPOP(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKeyChoice inKeyChoice, - CRMFSubseqMessOptions subseqMess, - SECItem *encPrivKey); +extern SECStatus +CRMF_CertReqMsgSetKeyAgreementPOP(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKeyChoice inKeyChoice, + CRMFSubseqMessOptions subseqMess, + SECItem *encPrivKey); /* * FUNCTION: CRMF_CreateCertReqMsgFromDER @@ -714,16 +711,16 @@ extern SECStatus * len * The length in bytes of the buffer 'buf' * NOTES: - * This function passes the buffer to the ASN1 decoder and creates a + * This function passes the buffer to the ASN1 decoder and creates a * CRMFCertReqMsg structure. Do not try adding any fields to a message - * returned from this function. Specifically adding more Controls or + * returned from this function. Specifically adding more Controls or * Extensions may cause your program to crash. * * RETURN: * A pointer to the Certificate Request Message structure. A NULL return * value indicates the library was unable to parse the DER. */ -extern CRMFCertReqMsg* CRMF_CreateCertReqMsgFromDER(const char *buf, long len); +extern CRMFCertReqMsg *CRMF_CreateCertReqMsgFromDER(const char *buf, long len); /* * FUNCTION: CRMF_CreateCertReqMessagesFromDER @@ -733,19 +730,19 @@ extern CRMFCertReqMsg* CRMF_CreateCertReqMsgFromDER(const char *buf, long len); * len * The length in bytes of buf * NOTES: - * This function passes the buffer to the ASN1 decoder and creates a + * This function passes the buffer to the ASN1 decoder and creates a * CRMFCertReqMessages structure. Do not try adding any fields to a message - * derived from this function. Specifically adding more Controls or + * derived from this function. Specifically adding more Controls or * Extensions may cause your program to crash. - * The user must call CRMF_DestroyCertReqMessages after the return value is + * The user must call CRMF_DestroyCertReqMessages after the return value is * no longer needed, ie when all individual messages have been extracted. - * + * * RETURN: * A pointer to the Certificate Request Messages structure. A NULL return * value indicates the library was unable to parse the DER. - */ -extern CRMFCertReqMessages* - CRMF_CreateCertReqMessagesFromDER(const char *buf, long len); + */ +extern CRMFCertReqMessages * +CRMF_CreateCertReqMessagesFromDER(const char *buf, long len); /* * FUNCTION: CRMF_DestroyCertReqMessages @@ -755,9 +752,9 @@ extern CRMFCertReqMessages* * RETURN: * SECSuccess if freeing the memory was done successfully. Any other * return value indicates an error in freeing up memory. - */ -extern SECStatus - CRMF_DestroyCertReqMessages(CRMFCertReqMessages *inCertReqMsgs); + */ +extern SECStatus +CRMF_DestroyCertReqMessages(CRMFCertReqMessages *inCertReqMsgs); /* * FUNCTION: CRMF_CertReqMessagesGetNumMessages @@ -765,11 +762,11 @@ extern SECStatus * inCertReqMsgs * The Request Messages to operate on. * RETURN: - * The number of messages contained in the in the Request Messages + * The number of messages contained in the in the Request Messages * strucure. */ -extern int - CRMF_CertReqMessagesGetNumMessages(CRMFCertReqMessages *inCertReqMsgs); +extern int +CRMF_CertReqMessagesGetNumMessages(CRMFCertReqMessages *inCertReqMsgs); /* * FUNCTION: CRMF_CertReqMessagesGetCertReqMsgAtIndex @@ -779,9 +776,9 @@ extern int * index * The index of the single message the user wants a copy of. * NOTES: - * This function returns a copy of the request messages stored at the + * This function returns a copy of the request messages stored at the * index corresponding to the parameter 'index'. Indexing of the messages - * is done in the same manner as a C array. Meaning the valid index are + * is done in the same manner as a C array. Meaning the valid index are * 0...numMessages-1. User must call CRMF_DestroyCertReqMsg when done using * the return value of this function. * @@ -790,10 +787,9 @@ extern int * Any other return value indicates an invalid index or error while copying * the single request message. */ -extern CRMFCertReqMsg* - CRMF_CertReqMessagesGetCertReqMsgAtIndex(CRMFCertReqMessages *inReqMsgs, - int index); - +extern CRMFCertReqMsg * +CRMF_CertReqMessagesGetCertReqMsgAtIndex(CRMFCertReqMessages *inReqMsgs, + int index); /* * FUNCTION: CRMF_CertReqMsgGetID @@ -805,12 +801,12 @@ extern CRMFCertReqMsg* * RETURN: * SECSuccess if the function was able to retrieve the ID and place it * at *destID. Any other return value indicates an error meaning the value - * in *destId is un-reliable and should not be used by the caller of this + * in *destId is un-reliable and should not be used by the caller of this * function. - * + * */ -extern SECStatus CRMF_CertReqMsgGetID(CRMFCertReqMsg *inCertReqMsg, - long *destID); +extern SECStatus CRMF_CertReqMsgGetID(CRMFCertReqMsg *inCertReqMsg, + long *destID); /* * FUNCTION: CRMF_DoesRequestHaveField @@ -823,7 +819,7 @@ extern SECStatus CRMF_CertReqMsgGetID(CRMFCertReqMsg *inCertReqMsg, * NOTES: * All the fields in a certificate template are optional. This function * checks to see if the requested field is present. Look in crmft.h at the - * definition of CRMFCertTemplateField for possible values for possible + * definition of CRMFCertTemplateField for possible values for possible * querying. * * RETURN: @@ -831,10 +827,10 @@ extern SECStatus CRMF_CertReqMsgGetID(CRMFCertReqMsg *inCertReqMsg, * of 'inCertReq' * PR_FALSE iff the field corresponding to 'inField' has not been speicified * as part of 'inCertReq' - * + * */ -extern PRBool CRMF_DoesRequestHaveField(CRMFCertRequest *inCertReq, - CRMFCertTemplateField inField); +extern PRBool CRMF_DoesRequestHaveField(CRMFCertRequest *inCertReq, + CRMFCertTemplateField inField); /* * FUNCTION: CRMF_CertReqMsgGetCertRequest @@ -849,11 +845,11 @@ extern PRBool CRMF_DoesRequestHaveField(CRMFCertRequest *inCertReq, * pass it the request returned by this function. * RETURN: * A pointer to a copy of the certificate request contained by the message. - * A NULL return value indicates an error occurred while copying the + * A NULL return value indicates an error occurred while copying the * certificate request. */ extern CRMFCertRequest * - CRMF_CertReqMsgGetCertRequest(CRMFCertReqMsg *inCertReqMsg); +CRMF_CertReqMsgGetCertRequest(CRMFCertReqMsg *inCertReqMsg); /* * FUNCTION: CRMF_CertRequestGetCertTemplateVersion @@ -864,15 +860,15 @@ extern CRMFCertRequest * * A pointer to where the library can store the version contatined * in the certificate template within the certifcate request. * RETURN: - * SECSuccess if the Certificate template contains the version field. In - * this case, *version will hold the value of the certificate template + * SECSuccess if the Certificate template contains the version field. In + * this case, *version will hold the value of the certificate template * version. * SECFailure indicates that version field was not present as part of * of the certificate template. */ -extern SECStatus - CRMF_CertRequestGetCertTemplateVersion(CRMFCertRequest *inCertReq, - long *version); +extern SECStatus +CRMF_CertRequestGetCertTemplateVersion(CRMFCertRequest *inCertReq, + long *version); /* * FUNCTION: CRMF_CertRequestGetCertTemplateSerialNumber @@ -883,15 +879,15 @@ extern SECStatus * A pointer where the library can put the serial number contained * in the certificate request's certificate template. * RETURN: - * If a serial number exists in the CertTemplate of the request, the function - * returns SECSuccess and the value at *serialNumber contains the serial + * If a serial number exists in the CertTemplate of the request, the function + * returns SECSuccess and the value at *serialNumber contains the serial * number. * If no serial number is present, then the function returns SECFailure and * the value at *serialNumber is un-changed. */ -extern SECStatus - CRMF_CertRequestGetCertTemplateSerialNumber(CRMFCertRequest *inCertReq, - long *serialNumber); +extern SECStatus +CRMF_CertRequestGetCertTemplateSerialNumber(CRMFCertRequest *inCertReq, + long *serialNumber); /* * FUNCTION: CRMF_CertRequestGetCertTemplateSigningAlg @@ -903,14 +899,14 @@ extern SECStatus * used in the cert request's cert template. * RETURN: * If the signingAlg is present in the CertRequest's CertTemplate, then - * the function returns SECSuccess and places a copy of sigingAlg in + * the function returns SECSuccess and places a copy of sigingAlg in * *destAlg. * If no signingAlg is present, then the function returns SECFailure and * the value at *destAlg is un-changed */ -extern SECStatus - CRMF_CertRequestGetCertTemplateSigningAlg(CRMFCertRequest *inCertReq, - SECAlgorithmID *destAlg); +extern SECStatus +CRMF_CertRequestGetCertTemplateSigningAlg(CRMFCertRequest *inCertReq, + SECAlgorithmID *destAlg); /* * FUNCTION: CRMF_CertRequestGetCertTemplateIssuer * INPUTS: @@ -920,14 +916,14 @@ extern SECStatus * A pointer to where the library can place a copy of the cert * request's cert template issuer field. * RETURN: - * If the issuer is present in the cert request cert template, the function + * If the issuer is present in the cert request cert template, the function * returns SECSuccess and places a copy of the issuer in *destIssuer. * If there is no issuer present, the function returns SECFailure and the * value at *destIssuer is unchanged. */ -extern SECStatus - CRMF_CertRequestGetCertTemplateIssuer(CRMFCertRequest *inCertReq, - CERTName *destIssuer); +extern SECStatus +CRMF_CertRequestGetCertTemplateIssuer(CRMFCertRequest *inCertReq, + CERTName *destIssuer); /* * FUNCTION: CRMF_CertRequestGetCertTemplateValidity @@ -938,28 +934,28 @@ extern SECStatus * A pointer to where the library can place a copy of the validity * info in the cert request cert template. * NOTES: - * Pass the pointer to - * RETURN: + * Pass the pointer to + * RETURN: * If there is an OptionalValidity field, the function will return SECSuccess - * and place the appropriate values in *destValidity->notBefore and + * and place the appropriate values in *destValidity->notBefore and * *destValidity->notAfter. (Each field is optional, but at least one will * be present if the function returns SECSuccess) * * If there is no OptionalValidity field, the function will return SECFailure * and the values at *destValidity will be un-changed. */ -extern SECStatus - CRMF_CertRequestGetCertTemplateValidity(CRMFCertRequest *inCertReq, - CRMFGetValidity *destValidity); +extern SECStatus +CRMF_CertRequestGetCertTemplateValidity(CRMFCertRequest *inCertReq, + CRMFGetValidity *destValidity); /* * FUNCTION: CRMF_DestroyGetValidity * INPUTS: * inValidity * A pointer to the memroy to be freed. * NOTES: - * The function will free the memory allocated by the function + * The function will free the memory allocated by the function * CRMF_CertRequestGetCertTemplateValidity. That means only memory pointed - * to within the CRMFGetValidity structure. Since + * to within the CRMFGetValidity structure. Since * CRMF_CertRequestGetCertTemplateValidity does not allocate memory for the * structure passed into it, it will not free it. Meaning this function will * free the memory at inValidity->notBefore and inValidity->notAfter, but not @@ -969,8 +965,8 @@ extern SECStatus * SECSuccess if freeing the memory was successful. Any other return value * indicates an error while freeing the memory. */ -extern SECStatus - CRMF_DestroyGetValidity(CRMFGetValidity *inValidity); +extern SECStatus +CRMF_DestroyGetValidity(CRMFGetValidity *inValidity); /* * FUNCTION: CRMF_CertRequestGetCertTemplateSubject @@ -981,15 +977,15 @@ extern SECStatus * A pointer to where the library can place a copy of the subject * contained in the request's cert template. * RETURN: - * If there is a subject in the CertTemplate, then the function returns + * If there is a subject in the CertTemplate, then the function returns * SECSuccess and a copy of the subject is placed in *destSubject. * * If there is no subject, the function returns SECFailure and the values at * *destSubject is unchanged. */ -extern SECStatus - CRMF_CertRequestGetCertTemplateSubject (CRMFCertRequest *inCertReq, - CERTName *destSubject); +extern SECStatus +CRMF_CertRequestGetCertTemplateSubject(CRMFCertRequest *inCertReq, + CERTName *destSubject); /* * FUNCTION: CRMF_CertRequestGetCertTemplatePublicKey @@ -1006,9 +1002,9 @@ extern SECStatus * If there is no publicKey, the function returns SECFailure and the value * at *destPublicKey is un-changed. */ -extern SECStatus - CRMF_CertRequestGetCertTemplatePublicKey(CRMFCertRequest *inCertReq, - CERTSubjectPublicKeyInfo *destPublicKey); +extern SECStatus +CRMF_CertRequestGetCertTemplatePublicKey(CRMFCertRequest *inCertReq, + CERTSubjectPublicKeyInfo *destPublicKey); /* * FUNCTION: CRMF_CertRequestGetCertTemplateIssuerUID @@ -1019,7 +1015,7 @@ extern SECStatus * A pointer to where the library can store a copy of the request's * cert template destIssuerUID. * - * NOTES: + * NOTES: * destIssuerUID is a bit string and will be returned in a SECItem as * a bit string. Meaning the len field contains the number of valid bits as * opposed to the number of bytes allocated. @@ -1031,9 +1027,9 @@ extern SECStatus * If there is no issuerUID, the function returns SECFailure and the value * *destIssuerUID is unchanged. */ -extern SECStatus - CRMF_CertRequestGetCertTemplateIssuerUID(CRMFCertRequest *inCertReq, - SECItem *destIssuerUID); +extern SECStatus +CRMF_CertRequestGetCertTemplateIssuerUID(CRMFCertRequest *inCertReq, + SECItem *destIssuerUID); /* * FUNCTION: CRMF_CertRequestGetCertTemplateSubjectUID @@ -1043,7 +1039,7 @@ extern SECStatus * A pointer to where the library can store a copy of the request's * cert template destIssuerUID. * - * NOTES: + * NOTES: * destSubjectUID is a bit string and will be returned in a SECItem as * a bit string. Meaning the len field contains the number of valid bits as * opposed to the number of bytes allocated. @@ -1056,7 +1052,7 @@ extern SECStatus * *destIssuerUID is unchanged. */ extern SECStatus CRMF_GetCertTemplateSubjectUID(CRMFCertRequest *inCertReq, - SECItem *destSubjectUID); + SECItem *destSubjectUID); /* * FUNCTION: CRMF_CertRequestGetNumberOfExtensions @@ -1076,20 +1072,20 @@ extern int CRMF_CertRequestGetNumberOfExtensions(CRMFCertRequest *inCertReq); * index * The index of the extension array whihc the user wants to access. * NOTES: - * This function retrieves the extension at the index corresponding to the - * parameter "index" indicates. Indexing is done like a C array. + * This function retrieves the extension at the index corresponding to the + * parameter "index" indicates. Indexing is done like a C array. * (0 ... numElements-1) * * Call CRMF_DestroyCertExtension when done using the return value. * * RETURN: - * A pointer to a copy of the extension at the desired index. A NULL - * return value indicates an invalid index or an error while copying + * A pointer to a copy of the extension at the desired index. A NULL + * return value indicates an invalid index or an error while copying * the extension. */ extern CRMFCertExtension * - CRMF_CertRequestGetExtensionAtIndex(CRMFCertRequest *inCertReq, - int index); +CRMF_CertRequestGetExtensionAtIndex(CRMFCertRequest *inCertReq, + int index); /* * FUNCTION: CRMF_CertExtensionGetOidTag * INPUTS: @@ -1112,7 +1108,7 @@ extern SECOidTag CRMF_CertExtensionGetOidTag(CRMFCertExtension *inExtension); * PR_FALSE if the extension is not critical. */ extern PRBool CRMF_CertExtensionGetIsCritical(CRMFCertExtension *inExt); - + /* * FUNCTION: CRMF_CertExtensionGetValue * INPUT: @@ -1127,7 +1123,7 @@ extern PRBool CRMF_CertExtensionGetIsCritical(CRMFCertExtension *inExt); * A pointer to an item containig the value for the certificate extension. * A NULL return value indicates an error in copying the information. */ -extern SECItem* CRMF_CertExtensionGetValue(CRMFCertExtension *inExtension); +extern SECItem *CRMF_CertExtensionGetValue(CRMFCertExtension *inExtension); /* * FUNCTION: CRMF_CertReqMsgGetPOPOSigningKey @@ -1136,20 +1132,20 @@ extern SECItem* CRMF_CertExtensionGetValue(CRMFCertExtension *inExtension); * The certificate request message to operate on. * destKey * A pointer to where the library can place a pointer to - * a copy of the Proof Of Possession Signing Key used + * a copy of the Proof Of Possession Signing Key used * by the message. * * RETURN: - * Get the POPOSigningKey associated with this CRMFCertReqMsg. + * Get the POPOSigningKey associated with this CRMFCertReqMsg. * If the CertReqMsg does not have a pop, the function returns * SECFailure and the value at *destKey is un-changed.. * - * If the CertReqMsg does have a pop, then the CertReqMsg's + * If the CertReqMsg does have a pop, then the CertReqMsg's * POPOSigningKey will be placed at *destKey. */ -extern SECStatus - CRMF_CertReqMsgGetPOPOSigningKey(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOSigningKey **destKey); +extern SECStatus +CRMF_CertReqMsgGetPOPOSigningKey(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOSigningKey **destKey); /* * FUNCTION: CRMF_DestroyPOPOSigningKey @@ -1161,7 +1157,7 @@ extern SECStatus * SECSuccess if freeing the memory was successful. Any other return value * indicates an error while freeing memory. */ -extern SECStatus CRMF_DestroyPOPOSigningKey (CRMFPOPOSigningKey *inKey); +extern SECStatus CRMF_DestroyPOPOSigningKey(CRMFPOPOSigningKey *inKey); /* * FUNCTION: CRMF_POPOSigningKeyGetAlgID @@ -1173,8 +1169,8 @@ extern SECStatus CRMF_DestroyPOPOSigningKey (CRMFPOPOSigningKey *inKey); * call SECOID_DestroyAlgorithmID(destID, PR_TRUE) when done using the * return value. */ -extern SECAlgorithmID* - CRMF_POPOSigningKeyGetAlgID(CRMFPOPOSigningKey *inSignKey); +extern SECAlgorithmID * +CRMF_POPOSigningKeyGetAlgID(CRMFPOPOSigningKey *inSignKey); /* * FUNCTION: CRMF_POPOSigningKeyGetSignature @@ -1182,13 +1178,13 @@ extern SECAlgorithmID* * inSignKey * The Signing Key to operate on. * - * RETURN: + * RETURN: * Get the actual signature stored away in the CRMFPOPOSigningKey. SECItem * returned is a BIT STRING, so the len field is the number of bits as opposed - * to the total number of bytes allocatd. User must call + * to the total number of bytes allocatd. User must call * SECITEM_FreeItem(retVal,PR_TRUE) when done using the return value. */ -extern SECItem* CRMF_POPOSigningKeyGetSignature(CRMFPOPOSigningKey *inSignKey); +extern SECItem *CRMF_POPOSigningKeyGetSignature(CRMFPOPOSigningKey *inSignKey); /* * FUNCTION: CRMF_POPOSigningKeyGetInput @@ -1196,7 +1192,7 @@ extern SECItem* CRMF_POPOSigningKeyGetSignature(CRMFPOPOSigningKey *inSignKey); * inSignKey * The Signing Key to operate on. * NOTES: - * This function will return the der encoded input that was read in while + * This function will return the der encoded input that was read in while * decoding. The API does not support this option when creating, so you * cannot add this field. * @@ -1208,7 +1204,7 @@ extern SECItem* CRMF_POPOSigningKeyGetSignature(CRMFPOPOSigningKey *inSignKey); * If the optional field is part of the POPOSingingKey, the function will * return a copy of the der encoded poposkInput. */ -extern SECItem* CRMF_POPOSigningKeyGetInput(CRMFPOPOSigningKey *inSignKey); +extern SECItem *CRMF_POPOSigningKeyGetInput(CRMFPOPOSigningKey *inSignKey); /* * FUNCTION: CRMF_CertReqMsgGetPOPKeyEncipherment @@ -1216,12 +1212,12 @@ extern SECItem* CRMF_POPOSigningKeyGetInput(CRMFPOPOSigningKey *inSignKey); * inCertReqMsg * The certificate request message to operate on. * destKey - * A pointer to where the library can place a pointer to a - * copy of the POPOPrivKey representing Key Encipherment + * A pointer to where the library can place a pointer to a + * copy of the POPOPrivKey representing Key Encipherment * Proof of Possession. *NOTES: - * This function gets the POPOPrivKey associated with this CRMFCertReqMsg - * for Key Encipherment. + * This function gets the POPOPrivKey associated with this CRMFCertReqMsg + * for Key Encipherment. * * RETURN: * If the CertReqMsg did not use Key Encipherment for Proof Of Possession, the @@ -1231,9 +1227,9 @@ extern SECItem* CRMF_POPOSigningKeyGetInput(CRMFPOPOSigningKey *inSignKey); * function returns SECSuccess and places the POPOPrivKey representing the * Key Encipherment Proof Of Possessin at *destKey. */ -extern SECStatus - CRMF_CertReqMsgGetPOPKeyEncipherment(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKey **destKey); +extern SECStatus +CRMF_CertReqMsgGetPOPKeyEncipherment(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKey **destKey); /* * FUNCTION: CRMF_CertReqMsgGetPOPKeyAgreement @@ -1241,12 +1237,12 @@ extern SECStatus * inCertReqMsg * The certificate request message to operate on. * destKey - * A pointer to where the library can place a pointer to a - * copy of the POPOPrivKey representing Key Agreement + * A pointer to where the library can place a pointer to a + * copy of the POPOPrivKey representing Key Agreement * Proof of Possession. * NOTES: - * This function gets the POPOPrivKey associated with this CRMFCertReqMsg for - * Key Agreement. + * This function gets the POPOPrivKey associated with this CRMFCertReqMsg for + * Key Agreement. * * RETURN: * If the CertReqMsg used Key Agreement for Proof Of Possession, the @@ -1256,11 +1252,11 @@ extern SECStatus * If the CertReqMsg did not use Key Agreement for Proof Of Possession, the * function return SECFailure and the value at *destKey is unchanged. */ -extern SECStatus - CRMF_CertReqMsgGetPOPKeyAgreement(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKey **destKey); +extern SECStatus +CRMF_CertReqMsgGetPOPKeyAgreement(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKey **destKey); -/* +/* * FUNCTION: CRMF_DestroyPOPOPrivKey * INPUTS: * inPrivKey @@ -1271,12 +1267,12 @@ extern SECStatus * * RETURN: * SECSuccess on successful destruction of the POPOPrivKey. - * Any other return value indicates an error in freeing the + * Any other return value indicates an error in freeing the * memory. */ extern SECStatus CRMF_DestroyPOPOPrivKey(CRMFPOPOPrivKey *inPrivKey); -/* +/* * FUNCTION: CRMF_POPOPrivKeyGetChoice * INPUT: * inKey @@ -1298,7 +1294,7 @@ extern CRMFPOPOPrivKeyChoice CRMF_POPOPrivKeyGetChoice(CRMFPOPOPrivKey *inKey); * field stored in the POPOPrivKey * * RETURN: - * Returns the field thisMessage from the POPOPrivKey. + * Returns the field thisMessage from the POPOPrivKey. * If the POPOPrivKey did not use the field thisMessage, the function * returns SECFailure and the value at *destString is unchanged. * @@ -1307,8 +1303,8 @@ extern CRMFPOPOPrivKeyChoice CRMF_POPOPrivKeyGetChoice(CRMFPOPOPrivKey *inKey); * at *destString. BIT STRING representation means the len field is the * number of valid bits as opposed to the total number of bytes. */ -extern SECStatus CRMF_POPOPrivKeyGetThisMessage(CRMFPOPOPrivKey *inKey, - SECItem *destString); +extern SECStatus CRMF_POPOPrivKeyGetThisMessage(CRMFPOPOPrivKey *inKey, + SECItem *destString); /* * FUNCTION: CRMF_POPOPrivKeyGetSubseqMess @@ -1316,20 +1312,20 @@ extern SECStatus CRMF_POPOPrivKeyGetThisMessage(CRMFPOPOPrivKey *inKey, * inKey * The POPOPrivKey to operate on. * destOpt - * A pointer to where the library can place the value of the + * A pointer to where the library can place the value of the * Subsequent Message option used by POPOPrivKey. * * RETURN: - * Retrieves the field subsequentMessage from the POPOPrivKey. - * If the POPOPrivKey used the subsequentMessage option, the function + * Retrieves the field subsequentMessage from the POPOPrivKey. + * If the POPOPrivKey used the subsequentMessage option, the function * returns SECSuccess and places the appropriate enumerated value at * *destMessageOption. * * If the POPOPrivKey did not use the subsequenMessage option, the function * returns SECFailure and the value at *destOpt is un-changed. */ -extern SECStatus CRMF_POPOPrivKeyGetSubseqMess(CRMFPOPOPrivKey *inKey, - CRMFSubseqMessOptions *destOpt); +extern SECStatus CRMF_POPOPrivKeyGetSubseqMess(CRMFPOPOPrivKey *inKey, + CRMFSubseqMessOptions *destOpt); /* * FUNCTION: CRMF_POPOPrivKeyGetDHMAC @@ -1339,9 +1335,9 @@ extern SECStatus CRMF_POPOPrivKeyGetSubseqMess(CRMFPOPOPrivKey *inKey, * destMAC * A pointer to where the library can place a copy of the dhMAC * field of the POPOPrivKey. - * + * * NOTES: - * Returns the field dhMAC from the POPOPrivKey. The populated SECItem + * Returns the field dhMAC from the POPOPrivKey. The populated SECItem * is in BIT STRING format. * * RETURN: @@ -1352,20 +1348,20 @@ extern SECStatus CRMF_POPOPrivKeyGetSubseqMess(CRMFPOPOPrivKey *inKey, * * If the POPOPrivKey did not use the dhMAC option, the function returns * SECFailure and the value at *destMAC is unchanged. - * + * */ extern SECStatus CRMF_POPOPrivKeyGetDHMAC(CRMFPOPOPrivKey *inKey, - SECItem *destMAC); + SECItem *destMAC); /* * FUNCTION: CRMF_CertRequestGetNumControls - * INPUTS: + * INPUTS: * inCertReq * The Certificate Request to operate on. * RETURN: * Returns the number of Controls registered with this CertRequest. */ -extern int CRMF_CertRequestGetNumControls (CRMFCertRequest *inCertReq); +extern int CRMF_CertRequestGetNumControls(CRMFCertRequest *inCertReq); /* * FUNCTION: CRMF_CertRequestGetControlAtIndex @@ -1375,18 +1371,18 @@ extern int CRMF_CertRequestGetNumControls (CRMFCertRequest *inCertReq); * index * The index of the control the user wants a copy of. * NOTES: - * Function retrieves the Control at located at index. The Controls + * Function retrieves the Control at located at index. The Controls * are numbered like a traditional C array (0 ... numElements-1) * * RETURN: * Returns a copy of the control at the index specified. This is a copy - * so the user must call CRMF_DestroyControl after the return value is no + * so the user must call CRMF_DestroyControl after the return value is no * longer needed. A return value of NULL indicates an error while copying * the control or that the index was invalid. */ -extern CRMFControl* - CRMF_CertRequestGetControlAtIndex(CRMFCertRequest *inCertReq, - int index); +extern CRMFControl * +CRMF_CertRequestGetControlAtIndex(CRMFCertRequest *inCertReq, + int index); /* * FUNCTION: CRMF_DestroyControl @@ -1431,11 +1427,11 @@ extern CRMFControlType CRMF_ControlGetControlType(CRMFControl *inControl); * The SECItem returned should be in UTF8 format. A NULL * return value indicates there was no Registration Control associated * with the Control. - * (This library will not verify format. It assumes the client properly - * formatted the strings when adding it or the message decoded was properly + * (This library will not verify format. It assumes the client properly + * formatted the strings when adding it or the message decoded was properly * formatted. The library will just give back the bytes it was given.) */ -extern SECItem* CRMF_ControlGetRegTokenControlValue(CRMFControl *inControl); +extern SECItem *CRMF_ControlGetRegTokenControlValue(CRMFControl *inControl); /* * FUNCTION: CRMF_ControlGetAuthenticatorControlValue @@ -1451,11 +1447,11 @@ extern SECItem* CRMF_ControlGetRegTokenControlValue(CRMFControl *inControl); * The SECItem returned should be in UTF8 format. A NULL * return value indicates there was no Authenticator Control associated * with the CRMFControl.. - * (This library will not verify format. It assumes the client properly - * formatted the strings when adding it or the message decoded was properly + * (This library will not verify format. It assumes the client properly + * formatted the strings when adding it or the message decoded was properly * formatted. The library will just give back the bytes it was given.) */ -extern SECItem* CRMF_ControlGetAuthicatorControlValue(CRMFControl *inControl); +extern SECItem *CRMF_ControlGetAuthicatorControlValue(CRMFControl *inControl); /* * FUNCTION: CRMF_ControlGetPKIArchiveOptions @@ -1468,12 +1464,12 @@ extern SECItem* CRMF_ControlGetAuthicatorControlValue(CRMFControl *inControl); * * RETURN: * Get the PKIArchiveOptions associated with the Control. A return - * value of NULL indicates the Control was not a PKIArchiveOptions + * value of NULL indicates the Control was not a PKIArchiveOptions * Control. */ -extern CRMFPKIArchiveOptions* - CRMF_ControlGetPKIArchiveOptions(CRMFControl *inControl); - +extern CRMFPKIArchiveOptions * +CRMF_ControlGetPKIArchiveOptions(CRMFControl *inControl); + /* * FUNCTION: CMRF_DestroyPKIArchiveOptions * INPUTS: @@ -1483,12 +1479,12 @@ extern CRMFPKIArchiveOptions* * Destroy the CRMFPKIArchiveOptions structure. * * RETURN: - * SECSuccess if successful in freeing all the memory associated with + * SECSuccess if successful in freeing all the memory associated with * the PKIArchiveOptions. Any other return value indicates an error while * freeing the PKIArchiveOptions. */ -extern SECStatus - CRMF_DestroyPKIArchiveOptions(CRMFPKIArchiveOptions *inOptions); +extern SECStatus +CRMF_DestroyPKIArchiveOptions(CRMFPKIArchiveOptions *inOptions); /* * FUNCTION: CRMF_PKIArchiveOptionsGetOptionType @@ -1500,14 +1496,14 @@ extern SECStatus * of CRMFPKIArchiveOptionsType in crmft.h for possible return values. */ extern CRMFPKIArchiveOptionsType - CRMF_PKIArchiveOptionsGetOptionType(CRMFPKIArchiveOptions *inOptions); +CRMF_PKIArchiveOptionsGetOptionType(CRMFPKIArchiveOptions *inOptions); /* * FUNCTION: CRMF_PKIArchiveOptionsGetEncryptedPrivKey * INPUTS: * inOpts * The PKIArchiveOptions to operate on. - * + * * NOTES: * The user must call CRMF_DestroyEncryptedKey when done using this return * value. @@ -1517,8 +1513,8 @@ extern CRMFPKIArchiveOptionsType * A return value of NULL indicates that encryptedPrivKey was not used as * the choice for this PKIArchiveOptions. */ -extern CRMFEncryptedKey* - CRMF_PKIArchiveOptionsGetEncryptedPrivKey(CRMFPKIArchiveOptions *inOpts); +extern CRMFEncryptedKey * +CRMF_PKIArchiveOptionsGetEncryptedPrivKey(CRMFPKIArchiveOptions *inOpts); /* * FUNCTION: CRMF_EncryptedKeyGetChoice @@ -1530,13 +1526,12 @@ extern CRMFEncryptedKey* * Get the choice used for representing the EncryptedKey. * * RETURN: - * Returns the Choice used in representing the EncryptedKey. Look in + * Returns the Choice used in representing the EncryptedKey. Look in * crmft.h at the definition of CRMFEncryptedKeyChoice for possible return * values. */ -extern CRMFEncryptedKeyChoice - CRMF_EncryptedKeyGetChoice(CRMFEncryptedKey *inEncrKey); - +extern CRMFEncryptedKeyChoice +CRMF_EncryptedKeyGetChoice(CRMFEncryptedKey *inEncrKey); /* * FUNCTION: CRMF_EncryptedKeyGetEncryptedValue @@ -1545,15 +1540,15 @@ extern CRMFEncryptedKeyChoice * The EncryptedKey to operate on. * * NOTES: - * The user must call CRMF_DestroyEncryptedValue passing in + * The user must call CRMF_DestroyEncryptedValue passing in * CRMF_GetEncryptedValue's return value. * * RETURN: * A pointer to a copy of the EncryptedValue contained as a member of * the EncryptedKey. */ -extern CRMFEncryptedValue* - CRMF_EncryptedKeyGetEncryptedValue(CRMFEncryptedKey *inKey); +extern CRMFEncryptedValue * +CRMF_EncryptedKeyGetEncryptedValue(CRMFEncryptedKey *inKey); /* * FUNCTION: CRMF_DestroyEncryptedValue @@ -1586,7 +1581,7 @@ extern SECStatus CRMF_DestroyEncryptedValue(CRMFEncryptedValue *inEncrValue); * as opposed to the allocated number of bytes. * ANULL return value indicates an error in copying the encValue field. */ -extern SECItem* CRMF_EncryptedValueGetEncValue(CRMFEncryptedValue *inEncValue); +extern SECItem *CRMF_EncryptedValueGetEncValue(CRMFEncryptedValue *inEncValue); /* * FUNCTION: CRMF_EncryptedValueGetIntendedAlg @@ -1603,9 +1598,8 @@ extern SECItem* CRMF_EncryptedValueGetEncValue(CRMFEncryptedValue *inEncValue); * A Copy of the intendedAlg field. A NULL return value indicates the * optional field was not present in the structure. */ -extern SECAlgorithmID* - CRMF_EncryptedValueGetIntendedAlg(CRMFEncryptedValue *inEncValue); - +extern SECAlgorithmID * +CRMF_EncryptedValueGetIntendedAlg(CRMFEncryptedValue *inEncValue); /* * FUNCTION: CRMF_EncryptedValueGetSymmAlg @@ -1622,9 +1616,8 @@ extern SECAlgorithmID* * A Copy of the symmAlg field. A NULL return value indicates the * optional field was not present in the structure. */ -extern SECAlgorithmID* - CRMF_EncryptedValueGetSymmAlg(CRMFEncryptedValue *inEncValue); - +extern SECAlgorithmID * +CRMF_EncryptedValueGetSymmAlg(CRMFEncryptedValue *inEncValue); /* * FUNCTION: CRMF_EncryptedValueGetKeyAlg @@ -1641,8 +1634,8 @@ extern SECAlgorithmID* * A Copy of the keyAlg field. A NULL return value indicates the * optional field was not present in the structure. */ -extern SECAlgorithmID* - CRMF_EncryptedValueGetKeyAlg(CRMFEncryptedValue *inEncValue); +extern SECAlgorithmID * +CRMF_EncryptedValueGetKeyAlg(CRMFEncryptedValue *inEncValue); /* * FUNCTION: CRMF_EncryptedValueGetValueHint @@ -1662,12 +1655,12 @@ extern SECAlgorithmID* * value indicates the optional valueHint field is not present in the * EncryptedValue. */ -extern SECItem* - CRMF_EncryptedValueGetValueHint(CRMFEncryptedValue *inEncValue); +extern SECItem * +CRMF_EncryptedValueGetValueHint(CRMFEncryptedValue *inEncValue); /* * FUNCTION: CRMF_EncrypteValueGetEncSymmKey - * INPUTS: + * INPUTS: * inEncValue * The EncryptedValue to operate on. * @@ -1676,19 +1669,19 @@ extern SECItem* * symmetric key that the client uses in doing Public Key wrap of a private * key. When present, this is the symmetric key that was used to wrap the * private key. (The encrypted private key will be stored in encValue - * of the same EncryptedValue structure.) The user must call + * of the same EncryptedValue structure.) The user must call * SECITEM_FreeItem(retVal, PR_TRUE) when the return value is no longer * needed. * * RETURN: * A copy of the optional encSymmKey field of the EncryptedValue structure. * The return value will be in BIT STRING format, meaning the len field will - * be the number of valid bits as opposed to the number of bytes. A return + * be the number of valid bits as opposed to the number of bytes. A return * value of NULL means the optional encSymmKey field was not present in * the EncryptedValue structure. */ -extern SECItem* - CRMF_EncryptedValueGetEncSymmKey(CRMFEncryptedValue *inEncValue); +extern SECItem * +CRMF_EncryptedValueGetEncSymmKey(CRMFEncryptedValue *inEncValue); /* * FUNCTION: CRMF_PKIArchiveOptionsGetKeyGenParameters @@ -1697,19 +1690,19 @@ extern SECItem* * The PKiArchiveOptions to operate on. * * NOTES: - * User must call SECITEM_FreeItem(retVal, PR_TRUE) after the return + * User must call SECITEM_FreeItem(retVal, PR_TRUE) after the return * value is no longer needed. * * RETURN: * Get the keyGenParameters field of the PKIArchiveOptions. - * A NULL return value indicates that keyGenParameters was not + * A NULL return value indicates that keyGenParameters was not * used as the choice for this PKIArchiveOptions. * * The SECItem returned is in BIT STRING format (ie, the len field indicates * number of valid bits as opposed to allocated number of bytes.) */ -extern SECItem* - CRMF_PKIArchiveOptionsGetKeyGenParameters(CRMFPKIArchiveOptions *inOptions); +extern SECItem * +CRMF_PKIArchiveOptionsGetKeyGenParameters(CRMFPKIArchiveOptions *inOptions); /* * FUNCTION: CRMF_PKIArchiveOptionsGetArchiveRemGenPrivKey @@ -1717,34 +1710,32 @@ extern SECItem* * inOpt * The PKIArchiveOptions to operate on. * destVal - * A pointer to where the library can place the value for + * A pointer to where the library can place the value for * arciveRemGenPrivKey * RETURN: * If the PKIArchiveOptions used the archiveRemGenPrivKey field, the * function returns SECSuccess and fills the value at *destValue with either - * PR_TRUE or PR_FALSE, depending on what the PKIArchiveOptions has as a - * value. + * PR_TRUE or PR_FALSE, depending on what the PKIArchiveOptions has as a + * value. * * If the PKIArchiveOptions does not use the archiveRemGenPrivKey field, the * function returns SECFailure and the value at *destValue is unchanged. */ -extern SECStatus - CRMF_PKIArchiveOptionsGetArchiveRemGenPrivKey(CRMFPKIArchiveOptions *inOpt, - PRBool *destVal); +extern SECStatus +CRMF_PKIArchiveOptionsGetArchiveRemGenPrivKey(CRMFPKIArchiveOptions *inOpt, + PRBool *destVal); /* Helper functions that can be used by other libraries. */ /* * A quick helper function to get the best wrap mechanism. */ -extern CK_MECHANISM_TYPE CRMF_GetBestWrapPadMechanism(PK11SlotInfo *slot); +extern CK_MECHANISM_TYPE CRMF_GetBestWrapPadMechanism(PK11SlotInfo *slot); /* - * A helper function to get a randomly generated IV from a mechanism + * A helper function to get a randomly generated IV from a mechanism * type. */ -extern SECItem* CRMF_GetIVFromMechanism(CK_MECHANISM_TYPE mechType); - +extern SECItem *CRMF_GetIVFromMechanism(CK_MECHANISM_TYPE mechType); + SEC_END_PROTOS #endif /*_CRMF_H_*/ - - diff --git a/security/nss/lib/crmf/crmfcont.c b/security/nss/lib/crmf/crmfcont.c index 4e274d32c820..6c7c10580a4c 100644 --- a/security/nss/lib/crmf/crmfcont.c +++ b/security/nss/lib/crmf/crmfcont.c @@ -10,32 +10,33 @@ #include "secoid.h" static SECStatus -crmf_modify_control_array (CRMFCertRequest *inCertReq, int count) +crmf_modify_control_array(CRMFCertRequest *inCertReq, int count) { if (count > 0) { - void *dummy = PORT_Realloc(inCertReq->controls, - sizeof(CRMFControl*)*(count+2)); - if (dummy == NULL) { - return SECFailure; - } - inCertReq->controls = dummy; - } else { - inCertReq->controls = PORT_ZNewArray(CRMFControl*, 2); + void *dummy = PORT_Realloc(inCertReq->controls, + sizeof(CRMFControl *) * (count + 2)); + if (dummy == NULL) { + return SECFailure; + } + inCertReq->controls = dummy; } - return (inCertReq->controls == NULL) ? SECFailure : SECSuccess ; + else { + inCertReq->controls = PORT_ZNewArray(CRMFControl *, 2); + } + return (inCertReq->controls == NULL) ? SECFailure : SECSuccess; } static SECStatus -crmf_add_new_control(CRMFCertRequest *inCertReq,SECOidTag inTag, - CRMFControl **destControl) +crmf_add_new_control(CRMFCertRequest *inCertReq, SECOidTag inTag, + CRMFControl **destControl) { - SECOidData *oidData; - SECStatus rv; + SECOidData *oidData; + SECStatus rv; PLArenaPool *poolp; - int numControls = 0; + int numControls = 0; CRMFControl *newControl; CRMFControl **controls; - void *mark; + void *mark; poolp = inCertReq->poolp; if (poolp == NULL) { @@ -44,7 +45,7 @@ crmf_add_new_control(CRMFCertRequest *inCertReq,SECOidTag inTag, mark = PORT_ArenaMark(poolp); if (inCertReq->controls != NULL) { while (inCertReq->controls[numControls] != NULL) - numControls++; + numControls++; } rv = crmf_modify_control_array(inCertReq, numControls); if (rv != SECSuccess) { @@ -52,7 +53,7 @@ crmf_add_new_control(CRMFCertRequest *inCertReq,SECOidTag inTag, } controls = inCertReq->controls; oidData = SECOID_FindOIDByTag(inTag); - newControl = *destControl = PORT_ArenaZNew(poolp,CRMFControl); + newControl = *destControl = PORT_ArenaZNew(poolp, CRMFControl); if (newControl == NULL) { goto loser; } @@ -62,24 +63,23 @@ crmf_add_new_control(CRMFCertRequest *inCertReq,SECOidTag inTag, } newControl->tag = inTag; controls[numControls] = newControl; - controls[numControls+1] = NULL; + controls[numControls + 1] = NULL; PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); *destControl = NULL; return SECFailure; - } static SECStatus crmf_add_secitem_control(CRMFCertRequest *inCertReq, SECItem *value, - SECOidTag inTag) + SECOidTag inTag) { - SECStatus rv; + SECStatus rv; CRMFControl *newControl; - void *mark; + void *mark; rv = crmf_add_new_control(inCertReq, inTag, &newControl); if (rv != SECSuccess) { @@ -89,7 +89,7 @@ crmf_add_secitem_control(CRMFCertRequest *inCertReq, SECItem *value, rv = SECITEM_CopyItem(inCertReq->poolp, &newControl->derValue, value); if (rv != SECSuccess) { PORT_ArenaRelease(inCertReq->poolp, mark); - return rv; + return rv; } PORT_ArenaUnmark(inCertReq->poolp, mark); return SECSuccess; @@ -98,16 +98,16 @@ crmf_add_secitem_control(CRMFCertRequest *inCertReq, SECItem *value, SECStatus CRMF_CertRequestSetRegTokenControl(CRMFCertRequest *inCertReq, SECItem *value) { - return crmf_add_secitem_control(inCertReq, value, - SEC_OID_PKIX_REGCTRL_REGTOKEN); + return crmf_add_secitem_control(inCertReq, value, + SEC_OID_PKIX_REGCTRL_REGTOKEN); } SECStatus -CRMF_CertRequestSetAuthenticatorControl (CRMFCertRequest *inCertReq, - SECItem *value) +CRMF_CertRequestSetAuthenticatorControl(CRMFCertRequest *inCertReq, + SECItem *value) { - return crmf_add_secitem_control(inCertReq, value, - SEC_OID_PKIX_REGCTRL_AUTHENTICATOR); + return crmf_add_secitem_control(inCertReq, value, + SEC_OID_PKIX_REGCTRL_AUTHENTICATOR); } SECStatus @@ -115,32 +115,32 @@ crmf_destroy_encrypted_value(CRMFEncryptedValue *inEncrValue, PRBool freeit) { if (inEncrValue != NULL) { if (inEncrValue->intendedAlg) { - SECOID_DestroyAlgorithmID(inEncrValue->intendedAlg, PR_TRUE); - inEncrValue->intendedAlg = NULL; - } - if (inEncrValue->symmAlg) { - SECOID_DestroyAlgorithmID(inEncrValue->symmAlg, PR_TRUE); - inEncrValue->symmAlg = NULL; - } + SECOID_DestroyAlgorithmID(inEncrValue->intendedAlg, PR_TRUE); + inEncrValue->intendedAlg = NULL; + } + if (inEncrValue->symmAlg) { + SECOID_DestroyAlgorithmID(inEncrValue->symmAlg, PR_TRUE); + inEncrValue->symmAlg = NULL; + } if (inEncrValue->encSymmKey.data) { - PORT_Free(inEncrValue->encSymmKey.data); - inEncrValue->encSymmKey.data = NULL; - } - if (inEncrValue->keyAlg) { - SECOID_DestroyAlgorithmID(inEncrValue->keyAlg, PR_TRUE); - inEncrValue->keyAlg = NULL; - } - if (inEncrValue->valueHint.data) { - PORT_Free(inEncrValue->valueHint.data); - inEncrValue->valueHint.data = NULL; - } + PORT_Free(inEncrValue->encSymmKey.data); + inEncrValue->encSymmKey.data = NULL; + } + if (inEncrValue->keyAlg) { + SECOID_DestroyAlgorithmID(inEncrValue->keyAlg, PR_TRUE); + inEncrValue->keyAlg = NULL; + } + if (inEncrValue->valueHint.data) { + PORT_Free(inEncrValue->valueHint.data); + inEncrValue->valueHint.data = NULL; + } if (inEncrValue->encValue.data) { - PORT_Free(inEncrValue->encValue.data); - inEncrValue->encValue.data = NULL; - } - if (freeit) { - PORT_Free(inEncrValue); - } + PORT_Free(inEncrValue->encValue.data); + inEncrValue->encValue.data = NULL; + } + if (freeit) { + PORT_Free(inEncrValue); + } } return SECSuccess; } @@ -152,19 +152,19 @@ CRMF_DestroyEncryptedValue(CRMFEncryptedValue *inEncrValue) } SECStatus -crmf_copy_encryptedvalue_secalg(PLArenaPool *poolp, - SECAlgorithmID *srcAlgId, - SECAlgorithmID **destAlgId) +crmf_copy_encryptedvalue_secalg(PLArenaPool *poolp, + SECAlgorithmID *srcAlgId, + SECAlgorithmID **destAlgId) { SECAlgorithmID *newAlgId; SECStatus rv; newAlgId = (poolp != NULL) ? PORT_ArenaZNew(poolp, SECAlgorithmID) : - PORT_ZNew(SECAlgorithmID); + PORT_ZNew(SECAlgorithmID); if (newAlgId == NULL) { return SECFailure; } - + rv = SECOID_CopyAlgorithmID(poolp, newAlgId, srcAlgId); if (rv != SECSuccess) { if (!poolp) { @@ -173,121 +173,121 @@ crmf_copy_encryptedvalue_secalg(PLArenaPool *poolp, return rv; } *destAlgId = newAlgId; - + return rv; } SECStatus -crmf_copy_encryptedvalue(PLArenaPool *poolp, - CRMFEncryptedValue *srcValue, - CRMFEncryptedValue *destValue) +crmf_copy_encryptedvalue(PLArenaPool *poolp, + CRMFEncryptedValue *srcValue, + CRMFEncryptedValue *destValue) { - SECStatus rv; + SECStatus rv; if (srcValue->intendedAlg != NULL) { rv = crmf_copy_encryptedvalue_secalg(poolp, - srcValue->intendedAlg, - &destValue->intendedAlg); - if (rv != SECSuccess) { - goto loser; - } + srcValue->intendedAlg, + &destValue->intendedAlg); + if (rv != SECSuccess) { + goto loser; + } } if (srcValue->symmAlg != NULL) { - rv = crmf_copy_encryptedvalue_secalg(poolp, - srcValue->symmAlg, - &destValue->symmAlg); - if (rv != SECSuccess) { - goto loser; - } + rv = crmf_copy_encryptedvalue_secalg(poolp, + srcValue->symmAlg, + &destValue->symmAlg); + if (rv != SECSuccess) { + goto loser; + } } if (srcValue->encSymmKey.data != NULL) { - rv = crmf_make_bitstring_copy(poolp, - &destValue->encSymmKey, - &srcValue->encSymmKey); - if (rv != SECSuccess) { - goto loser; - } + rv = crmf_make_bitstring_copy(poolp, + &destValue->encSymmKey, + &srcValue->encSymmKey); + if (rv != SECSuccess) { + goto loser; + } } if (srcValue->keyAlg != NULL) { rv = crmf_copy_encryptedvalue_secalg(poolp, - srcValue->keyAlg, - &destValue->keyAlg); - if (rv != SECSuccess) { - goto loser; - } + srcValue->keyAlg, + &destValue->keyAlg); + if (rv != SECSuccess) { + goto loser; + } } if (srcValue->valueHint.data != NULL) { - rv = SECITEM_CopyItem(poolp, - &destValue->valueHint, - &srcValue->valueHint); - if (rv != SECSuccess) { - goto loser; - } + rv = SECITEM_CopyItem(poolp, + &destValue->valueHint, + &srcValue->valueHint); + if (rv != SECSuccess) { + goto loser; + } } if (srcValue->encValue.data != NULL) { rv = crmf_make_bitstring_copy(poolp, - &destValue->encValue, - &srcValue->encValue); - if (rv != SECSuccess) { - goto loser; - } + &destValue->encValue, + &srcValue->encValue); + if (rv != SECSuccess) { + goto loser; + } } return SECSuccess; - loser: +loser: if (poolp == NULL && destValue != NULL) { crmf_destroy_encrypted_value(destValue, PR_FALSE); } return SECFailure; } -SECStatus -crmf_copy_encryptedkey(PLArenaPool *poolp, - CRMFEncryptedKey *srcEncrKey, - CRMFEncryptedKey *destEncrKey) +SECStatus +crmf_copy_encryptedkey(PLArenaPool *poolp, + CRMFEncryptedKey *srcEncrKey, + CRMFEncryptedKey *destEncrKey) { - SECStatus rv; - void *mark = NULL; + SECStatus rv; + void *mark = NULL; if (poolp != NULL) { mark = PORT_ArenaMark(poolp); } switch (srcEncrKey->encKeyChoice) { - case crmfEncryptedValueChoice: - rv = crmf_copy_encryptedvalue(poolp, - &srcEncrKey->value.encryptedValue, - &destEncrKey->value.encryptedValue); - break; - case crmfEnvelopedDataChoice: - destEncrKey->value.envelopedData = - SEC_PKCS7CopyContentInfo(srcEncrKey->value.envelopedData); - rv = (destEncrKey->value.envelopedData != NULL) ? SECSuccess: - SECFailure; - break; - default: - rv = SECFailure; + case crmfEncryptedValueChoice: + rv = crmf_copy_encryptedvalue(poolp, + &srcEncrKey->value.encryptedValue, + &destEncrKey->value.encryptedValue); + break; + case crmfEnvelopedDataChoice: + destEncrKey->value.envelopedData = + SEC_PKCS7CopyContentInfo(srcEncrKey->value.envelopedData); + rv = (destEncrKey->value.envelopedData != NULL) ? SECSuccess : + SECFailure; + break; + default: + rv = SECFailure; } if (rv != SECSuccess) { goto loser; } destEncrKey->encKeyChoice = srcEncrKey->encKeyChoice; if (mark) { - PORT_ArenaUnmark(poolp, mark); + PORT_ArenaUnmark(poolp, mark); } return SECSuccess; - loser: +loser: if (mark) { PORT_ArenaRelease(poolp, mark); } return SECFailure; } -static CRMFPKIArchiveOptions* +static CRMFPKIArchiveOptions * crmf_create_encr_pivkey_option(CRMFEncryptedKey *inEncryptedKey) { CRMFPKIArchiveOptions *newArchOpt; - SECStatus rv; + SECStatus rv; newArchOpt = PORT_ZNew(CRMFPKIArchiveOptions); if (newArchOpt == NULL) { @@ -295,25 +295,25 @@ crmf_create_encr_pivkey_option(CRMFEncryptedKey *inEncryptedKey) } rv = crmf_copy_encryptedkey(NULL, inEncryptedKey, - &newArchOpt->option.encryptedKey); - + &newArchOpt->option.encryptedKey); + if (rv != SECSuccess) { - goto loser; + goto loser; } newArchOpt->archOption = crmfEncryptedPrivateKey; return newArchOpt; - loser: +loser: if (newArchOpt != NULL) { CRMF_DestroyPKIArchiveOptions(newArchOpt); } return NULL; } -static CRMFPKIArchiveOptions* +static CRMFPKIArchiveOptions * crmf_create_keygen_param_option(SECItem *inKeyGenParams) { CRMFPKIArchiveOptions *newArchOptions; - SECStatus rv; + SECStatus rv; newArchOptions = PORT_ZNew(CRMFPKIArchiveOptions); if (newArchOptions == NULL) { @@ -321,23 +321,23 @@ crmf_create_keygen_param_option(SECItem *inKeyGenParams) } newArchOptions->archOption = crmfKeyGenParameters; rv = SECITEM_CopyItem(NULL, &newArchOptions->option.keyGenParameters, - inKeyGenParams); + inKeyGenParams); if (rv != SECSuccess) { goto loser; } return newArchOptions; - loser: +loser: if (newArchOptions != NULL) { CRMF_DestroyPKIArchiveOptions(newArchOptions); } return NULL; } -static CRMFPKIArchiveOptions* +static CRMFPKIArchiveOptions * crmf_create_arch_rem_gen_privkey(PRBool archiveRemGenPrivKey) { - unsigned char value; - SECItem *dummy; + unsigned char value; + SECItem *dummy; CRMFPKIArchiveOptions *newArchOptions; value = (archiveRemGenPrivKey) ? hexTrue : hexFalse; @@ -345,63 +345,63 @@ crmf_create_arch_rem_gen_privkey(PRBool archiveRemGenPrivKey) if (newArchOptions == NULL) { goto loser; } - dummy = SEC_ASN1EncodeItem(NULL, - &newArchOptions->option.archiveRemGenPrivKey, - &value, SEC_ASN1_GET(SEC_BooleanTemplate)); - PORT_Assert (dummy == &newArchOptions->option.archiveRemGenPrivKey); + dummy = SEC_ASN1EncodeItem(NULL, + &newArchOptions->option.archiveRemGenPrivKey, + &value, SEC_ASN1_GET(SEC_BooleanTemplate)); + PORT_Assert(dummy == &newArchOptions->option.archiveRemGenPrivKey); if (dummy != &newArchOptions->option.archiveRemGenPrivKey) { - SECITEM_FreeItem (dummy, PR_TRUE); - goto loser; + SECITEM_FreeItem(dummy, PR_TRUE); + goto loser; } newArchOptions->archOption = crmfArchiveRemGenPrivKey; return newArchOptions; - loser: +loser: if (newArchOptions != NULL) { CRMF_DestroyPKIArchiveOptions(newArchOptions); } return NULL; } -CRMFPKIArchiveOptions* +CRMFPKIArchiveOptions * CRMF_CreatePKIArchiveOptions(CRMFPKIArchiveOptionsType inType, void *data) { - CRMFPKIArchiveOptions* retOptions; + CRMFPKIArchiveOptions *retOptions; PORT_Assert(data != NULL); if (data == NULL) { return NULL; } - switch(inType) { - case crmfEncryptedPrivateKey: - retOptions = crmf_create_encr_pivkey_option((CRMFEncryptedKey*)data); - break; - case crmfKeyGenParameters: - retOptions = crmf_create_keygen_param_option((SECItem*)data); - break; - case crmfArchiveRemGenPrivKey: - retOptions = crmf_create_arch_rem_gen_privkey(*(PRBool*)data); - break; - default: - retOptions = NULL; + switch (inType) { + case crmfEncryptedPrivateKey: + retOptions = crmf_create_encr_pivkey_option((CRMFEncryptedKey *)data); + break; + case crmfKeyGenParameters: + retOptions = crmf_create_keygen_param_option((SECItem *)data); + break; + case crmfArchiveRemGenPrivKey: + retOptions = crmf_create_arch_rem_gen_privkey(*(PRBool *)data); + break; + default: + retOptions = NULL; } return retOptions; } static SECStatus crmf_destroy_encrypted_key(CRMFEncryptedKey *inEncrKey, PRBool freeit) -{ +{ PORT_Assert(inEncrKey != NULL); if (inEncrKey != NULL) { - switch (inEncrKey->encKeyChoice){ - case crmfEncryptedValueChoice: - crmf_destroy_encrypted_value(&inEncrKey->value.encryptedValue, - PR_FALSE); - break; - case crmfEnvelopedDataChoice: - SEC_PKCS7DestroyContentInfo(inEncrKey->value.envelopedData); - break; - default: - break; + switch (inEncrKey->encKeyChoice) { + case crmfEncryptedValueChoice: + crmf_destroy_encrypted_value(&inEncrKey->value.encryptedValue, + PR_FALSE); + break; + case crmfEnvelopedDataChoice: + SEC_PKCS7DestroyContentInfo(inEncrKey->value.envelopedData); + break; + default: + break; } if (freeit) { PORT_Free(inEncrKey); @@ -410,37 +410,37 @@ crmf_destroy_encrypted_key(CRMFEncryptedKey *inEncrKey, PRBool freeit) return SECSuccess; } -SECStatus -crmf_destroy_pkiarchiveoptions(CRMFPKIArchiveOptions *inArchOptions, - PRBool freeit) +SECStatus +crmf_destroy_pkiarchiveoptions(CRMFPKIArchiveOptions *inArchOptions, + PRBool freeit) { PORT_Assert(inArchOptions != NULL); if (inArchOptions != NULL) { switch (inArchOptions->archOption) { - case crmfEncryptedPrivateKey: - crmf_destroy_encrypted_key(&inArchOptions->option.encryptedKey, - PR_FALSE); - break; - case crmfKeyGenParameters: - case crmfArchiveRemGenPrivKey: - /* This is a union, so having a pointer to one is like - * having a pointer to both. - */ - SECITEM_FreeItem(&inArchOptions->option.keyGenParameters, - PR_FALSE); - break; - case crmfNoArchiveOptions: - break; - } - if (freeit) { - PORT_Free(inArchOptions); - } + case crmfEncryptedPrivateKey: + crmf_destroy_encrypted_key(&inArchOptions->option.encryptedKey, + PR_FALSE); + break; + case crmfKeyGenParameters: + case crmfArchiveRemGenPrivKey: + /* This is a union, so having a pointer to one is like + * having a pointer to both. + */ + SECITEM_FreeItem(&inArchOptions->option.keyGenParameters, + PR_FALSE); + break; + case crmfNoArchiveOptions: + break; + } + if (freeit) { + PORT_Free(inArchOptions); + } } return SECSuccess; } SECStatus -CRMF_DestroyPKIArchiveOptions(CRMFPKIArchiveOptions *inArchOptions) +CRMF_DestroyPKIArchiveOptions(CRMFPKIArchiveOptions *inArchOptions) { return crmf_destroy_pkiarchiveoptions(inArchOptions, PR_TRUE); } @@ -449,24 +449,24 @@ static CK_MECHANISM_TYPE crmf_get_non_pad_mechanism(CK_MECHANISM_TYPE type) { switch (type) { - case CKM_DES3_CBC_PAD: - return CKM_DES3_CBC; - case CKM_CAST5_CBC_PAD: - return CKM_CAST5_CBC; - case CKM_DES_CBC_PAD: - return CKM_DES_CBC; - case CKM_IDEA_CBC_PAD: - return CKM_IDEA_CBC; - case CKM_CAST3_CBC_PAD: - return CKM_CAST3_CBC; - case CKM_CAST_CBC_PAD: - return CKM_CAST_CBC; - case CKM_RC5_CBC_PAD: - return CKM_RC5_CBC; - case CKM_RC2_CBC_PAD: - return CKM_RC2_CBC; - case CKM_CDMF_CBC_PAD: - return CKM_CDMF_CBC; + case CKM_DES3_CBC_PAD: + return CKM_DES3_CBC; + case CKM_CAST5_CBC_PAD: + return CKM_CAST5_CBC; + case CKM_DES_CBC_PAD: + return CKM_DES_CBC; + case CKM_IDEA_CBC_PAD: + return CKM_IDEA_CBC; + case CKM_CAST3_CBC_PAD: + return CKM_CAST3_CBC; + case CKM_CAST_CBC_PAD: + return CKM_CAST_CBC; + case CKM_RC5_CBC_PAD: + return CKM_RC5_CBC; + case CKM_RC2_CBC_PAD: + return CKM_RC2_CBC; + case CKM_CDMF_CBC_PAD: + return CKM_CDMF_CBC; } return type; } @@ -474,8 +474,8 @@ crmf_get_non_pad_mechanism(CK_MECHANISM_TYPE type) static CK_MECHANISM_TYPE crmf_get_pad_mech_from_tag(SECOidTag oidTag) { - CK_MECHANISM_TYPE mechType; - SECOidData *oidData; + CK_MECHANISM_TYPE mechType; + SECOidData *oidData; oidData = SECOID_FindOIDByTag(oidTag); mechType = (CK_MECHANISM_TYPE)oidData->mechanism; @@ -483,24 +483,24 @@ crmf_get_pad_mech_from_tag(SECOidTag oidTag) } static CK_MECHANISM_TYPE -crmf_get_best_privkey_wrap_mechanism(PK11SlotInfo *slot) +crmf_get_best_privkey_wrap_mechanism(PK11SlotInfo *slot) { CK_MECHANISM_TYPE privKeyPadMechs[] = { CKM_DES3_CBC_PAD, - CKM_CAST5_CBC_PAD, - CKM_DES_CBC_PAD, - CKM_IDEA_CBC_PAD, - CKM_CAST3_CBC_PAD, - CKM_CAST_CBC_PAD, - CKM_RC5_CBC_PAD, - CKM_RC2_CBC_PAD, - CKM_CDMF_CBC_PAD }; - int mechCount = sizeof(privKeyPadMechs)/sizeof(privKeyPadMechs[0]); + CKM_CAST5_CBC_PAD, + CKM_DES_CBC_PAD, + CKM_IDEA_CBC_PAD, + CKM_CAST3_CBC_PAD, + CKM_CAST_CBC_PAD, + CKM_RC5_CBC_PAD, + CKM_RC2_CBC_PAD, + CKM_CDMF_CBC_PAD }; + int mechCount = sizeof(privKeyPadMechs) / sizeof(privKeyPadMechs[0]); int i; - for (i=0; i < mechCount; i++) { + for (i = 0; i < mechCount; i++) { if (PK11_DoesMechanism(slot, privKeyPadMechs[i])) { - return privKeyPadMechs[i]; - } + return privKeyPadMechs[i]; + } } return CKM_INVALID_MECHANISM; } @@ -511,12 +511,12 @@ CRMF_GetBestWrapPadMechanism(PK11SlotInfo *slot) return crmf_get_best_privkey_wrap_mechanism(slot); } -static SECItem* +static SECItem * crmf_get_iv(CK_MECHANISM_TYPE mechType) { - int iv_size = PK11_GetIVLength(mechType); - SECItem *iv; - SECStatus rv; + int iv_size = PK11_GetIVLength(mechType); + SECItem *iv; + SECStatus rv; iv = PORT_ZNew(SECItem); if (iv == NULL) { @@ -524,25 +524,25 @@ crmf_get_iv(CK_MECHANISM_TYPE mechType) } if (iv_size == 0) { iv->data = NULL; - iv->len = 0; - return iv; + iv->len = 0; + return iv; } iv->data = PORT_NewArray(unsigned char, iv_size); if (iv->data == NULL) { iv->len = 0; - return iv; + return iv; } iv->len = iv_size; rv = PK11_GenerateRandom(iv->data, iv->len); if (rv != SECSuccess) { PORT_Free(iv->data); - iv->data = NULL; - iv->len = 0; + iv->data = NULL; + iv->len = 0; } return iv; } -SECItem* +SECItem * CRMF_GetIVFromMechanism(CK_MECHANISM_TYPE mechType) { return crmf_get_iv(mechType); @@ -552,8 +552,7 @@ CK_MECHANISM_TYPE crmf_get_mechanism_from_public_key(SECKEYPublicKey *inPubKey) { CERTSubjectPublicKeyInfo *spki = NULL; - SECOidTag tag; - + SECOidTag tag; spki = SECKEY_CreateSubjectPublicKeyInfo(inPubKey); if (spki == NULL) { @@ -565,58 +564,59 @@ crmf_get_mechanism_from_public_key(SECKEYPublicKey *inPubKey) return PK11_AlgtagToMechanism(tag); } -SECItem* +SECItem * crmf_get_public_value(SECKEYPublicKey *pubKey, SECItem *dest) { SECItem *src; - switch(pubKey->keyType) { - case dsaKey: - src = &pubKey->u.dsa.publicValue; - break; - case rsaKey: - src = &pubKey->u.rsa.modulus; - break; - case dhKey: - src = &pubKey->u.dh.publicValue; - break; - default: - src = NULL; - break; + switch (pubKey->keyType) { + case dsaKey: + src = &pubKey->u.dsa.publicValue; + break; + case rsaKey: + src = &pubKey->u.rsa.modulus; + break; + case dhKey: + src = &pubKey->u.dh.publicValue; + break; + default: + src = NULL; + break; } if (!src) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } if (dest != NULL) { - SECStatus rv = SECITEM_CopyItem(NULL, dest, src); - if (rv != SECSuccess) { - dest = NULL; - } - } else { + SECStatus rv = SECITEM_CopyItem(NULL, dest, src); + if (rv != SECSuccess) { + dest = NULL; + } + } + else { dest = SECITEM_ArenaDupItem(NULL, src); } return dest; } -static SECItem* +static SECItem * crmf_decode_params(SECItem *inParams) { - SECItem *params; - SECStatus rv = SECFailure; + SECItem *params; + SECStatus rv = SECFailure; PLArenaPool *poolp; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { return NULL; } - + params = PORT_ArenaZNew(poolp, SECItem); if (params) { - rv = SEC_ASN1DecodeItem(poolp, params, - SEC_ASN1_GET(SEC_OctetStringTemplate), - inParams); + rv = SEC_ASN1DecodeItem(poolp, params, + SEC_ASN1_GET(SEC_OctetStringTemplate), + inParams); } params = (rv == SECSuccess) ? SECITEM_ArenaDupItem(NULL, params) : NULL; PORT_FreeArena(poolp, PR_FALSE); @@ -629,37 +629,38 @@ crmf_get_key_size_from_mech(CK_MECHANISM_TYPE mechType) CK_MECHANISM_TYPE keyGen = PK11_GetKeyGen(mechType); switch (keyGen) { - case CKM_CDMF_KEY_GEN: - case CKM_DES_KEY_GEN: - return 8; - case CKM_DES2_KEY_GEN: - return 16; - case CKM_DES3_KEY_GEN: - return 24; + case CKM_CDMF_KEY_GEN: + case CKM_DES_KEY_GEN: + return 8; + case CKM_DES2_KEY_GEN: + return 16; + case CKM_DES3_KEY_GEN: + return 24; } return 0; } SECStatus -crmf_encrypted_value_unwrap_priv_key(PLArenaPool *poolp, - CRMFEncryptedValue *encValue, - SECKEYPrivateKey *privKey, - SECKEYPublicKey *newPubKey, - SECItem *nickname, - PK11SlotInfo *slot, - unsigned char keyUsage, - SECKEYPrivateKey **unWrappedKey, - void *wincx) +crmf_encrypted_value_unwrap_priv_key(PLArenaPool *poolp, + CRMFEncryptedValue *encValue, + SECKEYPrivateKey *privKey, + SECKEYPublicKey *newPubKey, + SECItem *nickname, + PK11SlotInfo *slot, + unsigned char keyUsage, + SECKEYPrivateKey **unWrappedKey, + void *wincx) { - PK11SymKey *wrappingKey = NULL; - CK_MECHANISM_TYPE wrapMechType; - SECOidTag oidTag; - SECItem *params = NULL, *publicValue = NULL; - int keySize, origLen; - CK_KEY_TYPE keyType; + PK11SymKey *wrappingKey = NULL; + CK_MECHANISM_TYPE wrapMechType; + SECOidTag oidTag; + SECItem *params = NULL, *publicValue = NULL; + int keySize, origLen; + CK_KEY_TYPE keyType; CK_ATTRIBUTE_TYPE *usage = NULL; CK_ATTRIBUTE_TYPE rsaUsage[] = { - CKA_UNWRAP, CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER }; + CKA_UNWRAP, CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER + }; CK_ATTRIBUTE_TYPE dsaUsage[] = { CKA_SIGN }; CK_ATTRIBUTE_TYPE dhUsage[] = { CKA_DERIVE }; int usageCount = 0; @@ -667,108 +668,110 @@ crmf_encrypted_value_unwrap_priv_key(PLArenaPool *poolp, oidTag = SECOID_GetAlgorithmTag(encValue->symmAlg); wrapMechType = crmf_get_pad_mech_from_tag(oidTag); keySize = crmf_get_key_size_from_mech(wrapMechType); - wrappingKey = PK11_PubUnwrapSymKey(privKey, &encValue->encSymmKey, - wrapMechType, CKA_UNWRAP, keySize); + wrappingKey = PK11_PubUnwrapSymKey(privKey, &encValue->encSymmKey, + wrapMechType, CKA_UNWRAP, keySize); if (wrappingKey == NULL) { goto loser; - }/* Make the length a byte length instead of bit length*/ - params = (encValue->symmAlg != NULL) ? - crmf_decode_params(&encValue->symmAlg->parameters) : NULL; + } /* Make the length a byte length instead of bit length*/ + params = (encValue->symmAlg != NULL) ? + crmf_decode_params(&encValue->symmAlg->parameters) + : NULL; origLen = encValue->encValue.len; encValue->encValue.len = CRMF_BITS_TO_BYTES(origLen); publicValue = crmf_get_public_value(newPubKey, NULL); - switch(newPubKey->keyType) { - default: - case rsaKey: - keyType = CKK_RSA; - switch (keyUsage & (KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE)) { - case KU_KEY_ENCIPHERMENT: - usage = rsaUsage; - usageCount = 2; + switch (newPubKey->keyType) { + default: + case rsaKey: + keyType = CKK_RSA; + switch (keyUsage & (KU_KEY_ENCIPHERMENT | KU_DIGITAL_SIGNATURE)) { + case KU_KEY_ENCIPHERMENT: + usage = rsaUsage; + usageCount = 2; + break; + case KU_DIGITAL_SIGNATURE: + usage = &rsaUsage[2]; + usageCount = 2; + break; + case KU_KEY_ENCIPHERMENT | + KU_DIGITAL_SIGNATURE: + case 0: /* default to everything */ + usage = rsaUsage; + usageCount = 4; + break; + } break; - case KU_DIGITAL_SIGNATURE: - usage = &rsaUsage[2]; - usageCount = 2; + case dhKey: + keyType = CKK_DH; + usage = dhUsage; + usageCount = sizeof(dhUsage) / sizeof(dhUsage[0]); break; - case KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE: - case 0: /* default to everything */ - usage = rsaUsage; - usageCount = 4; + case dsaKey: + keyType = CKK_DSA; + usage = dsaUsage; + usageCount = sizeof(dsaUsage) / sizeof(dsaUsage[0]); break; - } - break; - case dhKey: - keyType = CKK_DH; - usage = dhUsage; - usageCount = sizeof(dhUsage)/sizeof(dhUsage[0]); - break; - case dsaKey: - keyType = CKK_DSA; - usage = dsaUsage; - usageCount = sizeof(dsaUsage)/sizeof(dsaUsage[0]); - break; } PORT_Assert(usage != NULL); PORT_Assert(usageCount != 0); *unWrappedKey = PK11_UnwrapPrivKey(slot, wrappingKey, wrapMechType, params, - &encValue->encValue, nickname, - publicValue, PR_TRUE,PR_TRUE, - keyType, usage, usageCount, wincx); + &encValue->encValue, nickname, + publicValue, PR_TRUE, PR_TRUE, + keyType, usage, usageCount, wincx); encValue->encValue.len = origLen; if (*unWrappedKey == NULL) { goto loser; } - SECITEM_FreeItem (publicValue, PR_TRUE); - if (params!= NULL) { + SECITEM_FreeItem(publicValue, PR_TRUE); + if (params != NULL) { SECITEM_FreeItem(params, PR_TRUE); - } + } PK11_FreeSymKey(wrappingKey); return SECSuccess; - loser: +loser: *unWrappedKey = NULL; return SECFailure; } CRMFEncryptedValue * -crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, - SECKEYPublicKey *inCAKey, - CRMFEncryptedValue *destValue) +crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, + SECKEYPublicKey *inCAKey, + CRMFEncryptedValue *destValue) { - SECItem wrappedPrivKey, wrappedSymKey; - SECItem encodedParam, *dummy; - SECStatus rv; - CK_MECHANISM_TYPE pubMechType, symKeyType; - unsigned char *wrappedSymKeyBits; - unsigned char *wrappedPrivKeyBits; - SECItem *iv = NULL; - SECOidTag tag; - PK11SymKey *symKey; - PK11SlotInfo *slot; - SECAlgorithmID *symmAlg; - CRMFEncryptedValue *myEncrValue = NULL; + SECItem wrappedPrivKey, wrappedSymKey; + SECItem encodedParam, *dummy; + SECStatus rv; + CK_MECHANISM_TYPE pubMechType, symKeyType; + unsigned char *wrappedSymKeyBits; + unsigned char *wrappedPrivKeyBits; + SECItem *iv = NULL; + SECOidTag tag; + PK11SymKey *symKey; + PK11SlotInfo *slot; + SECAlgorithmID *symmAlg; + CRMFEncryptedValue *myEncrValue = NULL; encodedParam.data = NULL; - wrappedSymKeyBits = PORT_NewArray(unsigned char, MAX_WRAPPED_KEY_LEN); + wrappedSymKeyBits = PORT_NewArray(unsigned char, MAX_WRAPPED_KEY_LEN); wrappedPrivKeyBits = PORT_NewArray(unsigned char, MAX_WRAPPED_KEY_LEN); if (wrappedSymKeyBits == NULL || wrappedPrivKeyBits == NULL) { goto loser; } if (destValue == NULL) { myEncrValue = destValue = PORT_ZNew(CRMFEncryptedValue); - if (destValue == NULL) { - goto loser; - } + if (destValue == NULL) { + goto loser; + } } pubMechType = crmf_get_mechanism_from_public_key(inCAKey); if (pubMechType == CKM_INVALID_MECHANISM) { - /* XXX I should probably do something here for non-RSA - * keys that are in certs. (ie DSA) - * XXX or at least SET AN ERROR CODE. - */ + /* XXX I should probably do something here for non-RSA + * keys that are in certs. (ie DSA) + * XXX or at least SET AN ERROR CODE. + */ goto loser; } - slot = inPrivKey->pkcs11Slot; + slot = inPrivKey->pkcs11Slot; PORT_Assert(slot != NULL); symKeyType = crmf_get_best_privkey_wrap_mechanism(slot); symKey = PK11_KeyGen(slot, symKeyType, NULL, 0, NULL); @@ -777,7 +780,7 @@ crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, } wrappedSymKey.data = wrappedSymKeyBits; - wrappedSymKey.len = MAX_WRAPPED_KEY_LEN; + wrappedSymKey.len = MAX_WRAPPED_KEY_LEN; rv = PK11_PubWrapSymKey(pubMechType, inCAKey, symKey, &wrappedSymKey); if (rv != SECSuccess) { goto loser; @@ -786,26 +789,26 @@ crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, wrappedSymKey.len <<= 3; wrappedPrivKey.data = wrappedPrivKeyBits; - wrappedPrivKey.len = MAX_WRAPPED_KEY_LEN; + wrappedPrivKey.len = MAX_WRAPPED_KEY_LEN; iv = crmf_get_iv(symKeyType); - rv = PK11_WrapPrivKey(slot, symKey, inPrivKey, symKeyType, iv, - &wrappedPrivKey, NULL); + rv = PK11_WrapPrivKey(slot, symKey, inPrivKey, symKeyType, iv, + &wrappedPrivKey, NULL); PK11_FreeSymKey(symKey); if (rv != SECSuccess) { goto loser; } /* Make the length of the result a Bit String length. */ wrappedPrivKey.len <<= 3; - rv = crmf_make_bitstring_copy(NULL, - &destValue->encValue, - &wrappedPrivKey); + rv = crmf_make_bitstring_copy(NULL, + &destValue->encValue, + &wrappedPrivKey); if (rv != SECSuccess) { goto loser; } rv = crmf_make_bitstring_copy(NULL, - &destValue->encSymmKey, - &wrappedSymKey); + &destValue->encSymmKey, + &wrappedSymKey); if (rv != SECSuccess) { goto loser; } @@ -814,11 +817,11 @@ crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, goto loser; } - dummy = SEC_ASN1EncodeItem(NULL, &encodedParam, iv, + dummy = SEC_ASN1EncodeItem(NULL, &encodedParam, iv, SEC_ASN1_GET(SEC_OctetStringTemplate)); if (dummy != &encodedParam) { SECITEM_FreeItem(dummy, PR_TRUE); - goto loser; + goto loser; } symKeyType = crmf_get_non_pad_mechanism(symKeyType); @@ -832,9 +835,9 @@ crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, PORT_Free(wrappedSymKeyBits); SECITEM_FreeItem(iv, PR_TRUE); return destValue; - loser: +loser: if (iv != NULL) { - SECITEM_FreeItem(iv, PR_TRUE); + SECITEM_FreeItem(iv, PR_TRUE); } if (myEncrValue != NULL) { crmf_destroy_encrypted_value(myEncrValue, PR_TRUE); @@ -846,17 +849,17 @@ crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, PORT_Free(wrappedPrivKeyBits); } if (encodedParam.data != NULL) { - SECITEM_FreeItem(&encodedParam, PR_FALSE); + SECITEM_FreeItem(&encodedParam, PR_FALSE); } return NULL; } -CRMFEncryptedKey* -CRMF_CreateEncryptedKeyWithEncryptedValue (SECKEYPrivateKey *inPrivKey, - CERTCertificate *inCACert) +CRMFEncryptedKey * +CRMF_CreateEncryptedKeyWithEncryptedValue(SECKEYPrivateKey *inPrivKey, + CERTCertificate *inCACert) { - SECKEYPublicKey *caPubKey = NULL; - CRMFEncryptedKey *encKey = NULL; + SECKEYPublicKey *caPubKey = NULL; + CRMFEncryptedKey *encKey = NULL; PORT_Assert(inPrivKey != NULL && inCACert != NULL); if (inPrivKey == NULL || inCACert == NULL) { @@ -883,13 +886,13 @@ CRMF_CreateEncryptedKeyWithEncryptedValue (SECKEYPrivateKey *inPrivKey, crmf_create_encrypted_value_wrapped_privkey( inPrivKey, caPubKey, &encKey->value.encryptedValue); #endif - /* We won't add the der value here, but rather when it + /* We won't add the der value here, but rather when it * becomes part of a certificate request. */ SECKEY_DestroyPublicKey(caPubKey); encKey->encKeyChoice = crmfEncryptedValueChoice; return encKey; - loser: +loser: if (encKey != NULL) { CRMF_DestroyEncryptedKey(encKey); } @@ -906,29 +909,29 @@ CRMF_DestroyEncryptedKey(CRMFEncryptedKey *inEncrKey) } SECStatus -crmf_copy_pkiarchiveoptions(PLArenaPool *poolp, - CRMFPKIArchiveOptions *destOpt, - CRMFPKIArchiveOptions *srcOpt) +crmf_copy_pkiarchiveoptions(PLArenaPool *poolp, + CRMFPKIArchiveOptions *destOpt, + CRMFPKIArchiveOptions *srcOpt) { SECStatus rv; destOpt->archOption = srcOpt->archOption; switch (srcOpt->archOption) { - case crmfEncryptedPrivateKey: - rv = crmf_copy_encryptedkey(poolp, - &srcOpt->option.encryptedKey, - &destOpt->option.encryptedKey); - break; - case crmfKeyGenParameters: - case crmfArchiveRemGenPrivKey: - /* We've got a union, so having a pointer to one is just - * like having a pointer to the other one. - */ - rv = SECITEM_CopyItem(poolp, - &destOpt->option.keyGenParameters, - &srcOpt->option.keyGenParameters); - break; - default: - rv = SECFailure; + case crmfEncryptedPrivateKey: + rv = crmf_copy_encryptedkey(poolp, + &srcOpt->option.encryptedKey, + &destOpt->option.encryptedKey); + break; + case crmfKeyGenParameters: + case crmfArchiveRemGenPrivKey: + /* We've got a union, so having a pointer to one is just + * like having a pointer to the other one. + */ + rv = SECITEM_CopyItem(poolp, + &destOpt->option.keyGenParameters, + &srcOpt->option.keyGenParameters); + break; + default: + rv = SECFailure; } return rv; } @@ -940,23 +943,23 @@ crmf_check_and_adjust_archoption(CRMFControl *inControl) options = &inControl->value.archiveOptions; if (options->archOption == crmfNoArchiveOptions) { - /* It hasn't been set, so figure it out from the - * der. - */ + /* It hasn't been set, so figure it out from the + * der. + */ switch (inControl->derValue.data[0] & 0x0f) { - case 0: - options->archOption = crmfEncryptedPrivateKey; - break; - case 1: - options->archOption = crmfKeyGenParameters; - break; - case 2: - options->archOption = crmfArchiveRemGenPrivKey; - break; - default: - /* We've got bad DER. Return an error. */ - return SECFailure; - } + case 0: + options->archOption = crmfEncryptedPrivateKey; + break; + case 1: + options->archOption = crmfKeyGenParameters; + break; + case 2: + options->archOption = crmfArchiveRemGenPrivKey; + break; + default: + /* We've got bad DER. Return an error. */ + return SECFailure; + } } return SECSuccess; } @@ -965,10 +968,10 @@ static const SEC_ASN1Template * crmf_get_pkiarchive_subtemplate(CRMFControl *inControl) { const SEC_ASN1Template *retTemplate; - SECStatus rv; + SECStatus rv; /* * We could be in the process of decoding, in which case the - * archOption field will not be set. Let's check it and set + * archOption field will not be set. Let's check it and set * it accordingly. */ @@ -978,38 +981,38 @@ crmf_get_pkiarchive_subtemplate(CRMFControl *inControl) } switch (inControl->value.archiveOptions.archOption) { - case crmfEncryptedPrivateKey: - retTemplate = CRMFEncryptedKeyWithEncryptedValueTemplate; - inControl->value.archiveOptions.option.encryptedKey.encKeyChoice = - crmfEncryptedValueChoice; - break; - default: - retTemplate = NULL; + case crmfEncryptedPrivateKey: + retTemplate = CRMFEncryptedKeyWithEncryptedValueTemplate; + inControl->value.archiveOptions.option.encryptedKey.encKeyChoice = + crmfEncryptedValueChoice; + break; + default: + retTemplate = NULL; } return retTemplate; } -const SEC_ASN1Template* +const SEC_ASN1Template * crmf_get_pkiarchiveoptions_subtemplate(CRMFControl *inControl) { const SEC_ASN1Template *retTemplate; switch (inControl->tag) { - case SEC_OID_PKIX_REGCTRL_REGTOKEN: - case SEC_OID_PKIX_REGCTRL_AUTHENTICATOR: - retTemplate = SEC_ASN1_GET(SEC_UTF8StringTemplate); - break; - case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: - retTemplate = crmf_get_pkiarchive_subtemplate(inControl); - break; - case SEC_OID_PKIX_REGCTRL_PKIPUBINFO: - case SEC_OID_PKIX_REGCTRL_OLD_CERT_ID: - case SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY: - /* We don't support these controls, so we fail for now.*/ - retTemplate = NULL; - break; - default: - retTemplate = NULL; + case SEC_OID_PKIX_REGCTRL_REGTOKEN: + case SEC_OID_PKIX_REGCTRL_AUTHENTICATOR: + retTemplate = SEC_ASN1_GET(SEC_UTF8StringTemplate); + break; + case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: + retTemplate = crmf_get_pkiarchive_subtemplate(inControl); + break; + case SEC_OID_PKIX_REGCTRL_PKIPUBINFO: + case SEC_OID_PKIX_REGCTRL_OLD_CERT_ID: + case SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY: + /* We don't support these controls, so we fail for now.*/ + retTemplate = NULL; + break; + default: + retTemplate = NULL; } return retTemplate; } @@ -1020,7 +1023,7 @@ crmf_encode_pkiarchiveoptions(PLArenaPool *poolp, CRMFControl *inControl) const SEC_ASN1Template *asn1Template; asn1Template = crmf_get_pkiarchiveoptions_subtemplate(inControl); - /* We've got a union, so passing a pointer to one element of the + /* We've got a union, so passing a pointer to one element of the * union, is the same as passing a pointer to any of the other * members of the union. */ @@ -1031,46 +1034,46 @@ crmf_encode_pkiarchiveoptions(PLArenaPool *poolp, CRMFControl *inControl) goto loser; } return SECSuccess; - loser: +loser: return SECFailure; } SECStatus -CRMF_CertRequestSetPKIArchiveOptions(CRMFCertRequest *inCertReq, - CRMFPKIArchiveOptions *inOptions) +CRMF_CertRequestSetPKIArchiveOptions(CRMFCertRequest *inCertReq, + CRMFPKIArchiveOptions *inOptions) { CRMFControl *newControl; PLArenaPool *poolp; - SECStatus rv; - void *mark; - + SECStatus rv; + void *mark; + PORT_Assert(inCertReq != NULL && inOptions != NULL); if (inCertReq == NULL || inOptions == NULL) { return SECFailure; } poolp = inCertReq->poolp; mark = PORT_ArenaMark(poolp); - rv = crmf_add_new_control(inCertReq, - SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS, - &newControl); + rv = crmf_add_new_control(inCertReq, + SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS, + &newControl); if (rv != SECSuccess) { goto loser; } - rv = crmf_copy_pkiarchiveoptions(poolp, - &newControl->value.archiveOptions, - inOptions); + rv = crmf_copy_pkiarchiveoptions(poolp, + &newControl->value.archiveOptions, + inOptions); if (rv != SECSuccess) { goto loser; } - rv = crmf_encode_pkiarchiveoptions(poolp, newControl); + rv = crmf_encode_pkiarchiveoptions(poolp, newControl); if (rv != SECSuccess) { goto loser; } PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); return SECFailure; } @@ -1082,25 +1085,25 @@ crmf_destroy_control(CRMFControl *inControl, PRBool freeit) if (inControl != NULL) { SECITEM_FreeItem(&inControl->derTag, PR_FALSE); SECITEM_FreeItem(&inControl->derValue, PR_FALSE); - /* None of the other tags require special processing at - * the moment when freeing because they are not supported, - * but if/when they are, add the necessary routines here. - * If all controls are supported, then every member of the - * union inControl->value will have a case that deals with - * it in the following switch statement. - */ - switch (inControl->tag) { - case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: - crmf_destroy_pkiarchiveoptions(&inControl->value.archiveOptions, - PR_FALSE); - break; - default: - /* Put this here to get rid of all those annoying warnings.*/ - break; - } - if (freeit) { - PORT_Free(inControl); - } + /* None of the other tags require special processing at + * the moment when freeing because they are not supported, + * but if/when they are, add the necessary routines here. + * If all controls are supported, then every member of the + * union inControl->value will have a case that deals with + * it in the following switch statement. + */ + switch (inControl->tag) { + case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: + crmf_destroy_pkiarchiveoptions(&inControl->value.archiveOptions, + PR_FALSE); + break; + default: + /* Put this here to get rid of all those annoying warnings.*/ + break; + } + if (freeit) { + PORT_Free(inControl); + } } return SECSuccess; } @@ -1116,49 +1119,48 @@ crmf_controltype_to_tag(CRMFControlType inControlType) { SECOidTag retVal; - switch(inControlType) { - case crmfRegTokenControl: - retVal = SEC_OID_PKIX_REGCTRL_REGTOKEN; - break; - case crmfAuthenticatorControl: - retVal = SEC_OID_PKIX_REGCTRL_AUTHENTICATOR; - break; - case crmfPKIPublicationInfoControl: - retVal = SEC_OID_PKIX_REGCTRL_PKIPUBINFO; - break; - case crmfPKIArchiveOptionsControl: - retVal = SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS; - break; - case crmfOldCertIDControl: - retVal = SEC_OID_PKIX_REGCTRL_OLD_CERT_ID; - break; - case crmfProtocolEncrKeyControl: - retVal = SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY; - break; - default: - retVal = SEC_OID_UNKNOWN; - break; + switch (inControlType) { + case crmfRegTokenControl: + retVal = SEC_OID_PKIX_REGCTRL_REGTOKEN; + break; + case crmfAuthenticatorControl: + retVal = SEC_OID_PKIX_REGCTRL_AUTHENTICATOR; + break; + case crmfPKIPublicationInfoControl: + retVal = SEC_OID_PKIX_REGCTRL_PKIPUBINFO; + break; + case crmfPKIArchiveOptionsControl: + retVal = SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS; + break; + case crmfOldCertIDControl: + retVal = SEC_OID_PKIX_REGCTRL_OLD_CERT_ID; + break; + case crmfProtocolEncrKeyControl: + retVal = SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY; + break; + default: + retVal = SEC_OID_UNKNOWN; + break; } return retVal; } PRBool CRMF_CertRequestIsControlPresent(CRMFCertRequest *inCertReq, - CRMFControlType inControlType) + CRMFControlType inControlType) { SECOidTag controlTag; - int i; + int i; PORT_Assert(inCertReq != NULL); if (inCertReq == NULL || inCertReq->controls == NULL) { return PR_FALSE; } controlTag = crmf_controltype_to_tag(inControlType); - for (i=0; inCertReq->controls[i] != NULL; i++) { + for (i = 0; inCertReq->controls[i] != NULL; i++) { if (inCertReq->controls[i]->tag == controlTag) { - return PR_TRUE; - } + return PR_TRUE; + } } return PR_FALSE; } - diff --git a/security/nss/lib/crmf/crmfdec.c b/security/nss/lib/crmf/crmfdec.c index 6be165fa722f..ac6e8726864b 100644 --- a/security/nss/lib/crmf/crmfdec.c +++ b/security/nss/lib/crmf/crmfdec.c @@ -3,7 +3,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #include "crmf.h" #include "crmfi.h" #include "secitem.h" @@ -14,35 +13,35 @@ crmf_get_popchoice_from_der(SECItem *derPOP) CRMFPOPChoice retChoice; switch (derPOP->data[0] & 0x0f) { - case 0: - retChoice = crmfRAVerified; - break; - case 1: - retChoice = crmfSignature; - break; - case 2: - retChoice = crmfKeyEncipherment; - break; - case 3: - retChoice = crmfKeyAgreement; - break; - default: - retChoice = crmfNoPOPChoice; - break; + case 0: + retChoice = crmfRAVerified; + break; + case 1: + retChoice = crmfSignature; + break; + case 2: + retChoice = crmfKeyEncipherment; + break; + case 3: + retChoice = crmfKeyAgreement; + break; + default: + retChoice = crmfNoPOPChoice; + break; } return retChoice; } static SECStatus crmf_decode_process_raverified(CRMFCertReqMsg *inCertReqMsg) -{ +{ CRMFProofOfPossession *pop; /* Just set up the structure so that the message structure * looks like one that was created using the API */ pop = inCertReqMsg->pop; pop->popChoice.raVerified.data = NULL; - pop->popChoice.raVerified.len = 0; + pop->popChoice.raVerified.len = 0; return SECSuccess; } @@ -51,14 +50,14 @@ crmf_decode_process_signature(CRMFCertReqMsg *inCertReqMsg) { PORT_Assert(inCertReqMsg->poolp); if (!inCertReqMsg->poolp) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } return SEC_ASN1Decode(inCertReqMsg->poolp, - &inCertReqMsg->pop->popChoice.signature, - CRMFPOPOSigningKeyTemplate, - (const char*)inCertReqMsg->derPOP.data, - inCertReqMsg->derPOP.len); + &inCertReqMsg->pop->popChoice.signature, + CRMFPOPOSigningKeyTemplate, + (const char *)inCertReqMsg->derPOP.data, + inCertReqMsg->derPOP.len); } static CRMFPOPOPrivKeyChoice @@ -67,17 +66,17 @@ crmf_get_messagechoice_from_der(SECItem *derPOP) CRMFPOPOPrivKeyChoice retChoice; switch (derPOP->data[2] & 0x0f) { - case 0: - retChoice = crmfThisMessage; - break; - case 1: - retChoice = crmfSubsequentMessage; - break; - case 2: - retChoice = crmfDHMAC; - break; - default: - retChoice = crmfNoMessage; + case 0: + retChoice = crmfThisMessage; + break; + case 1: + retChoice = crmfSubsequentMessage; + break; + case 2: + retChoice = crmfDHMAC; + break; + default: + retChoice = crmfNoMessage; } return retChoice; } @@ -86,13 +85,13 @@ static SECStatus crmf_decode_process_popoprivkey(CRMFCertReqMsg *inCertReqMsg) { /* We've got a union, so a pointer to one POPOPrivKey - * struct is the same as having a pointer to the other + * struct is the same as having a pointer to the other * one. */ - CRMFPOPOPrivKey *popoPrivKey = - &inCertReqMsg->pop->popChoice.keyEncipherment; - SECItem *derPOP, privKeyDer; - SECStatus rv; + CRMFPOPOPrivKey *popoPrivKey = + &inCertReqMsg->pop->popChoice.keyEncipherment; + SECItem *derPOP, privKeyDer; + SECStatus rv; derPOP = &inCertReqMsg->derPOP; popoPrivKey->messageChoice = crmf_get_messagechoice_from_der(derPOP); @@ -101,37 +100,36 @@ crmf_decode_process_popoprivkey(CRMFCertReqMsg *inCertReqMsg) } /* If we ever encounter BER encodings of this, we'll get in trouble*/ switch (popoPrivKey->messageChoice) { - case crmfThisMessage: - case crmfDHMAC: - privKeyDer.type = derPOP->type; - privKeyDer.data = &derPOP->data[5]; - privKeyDer.len = derPOP->len - 5; - break; - case crmfSubsequentMessage: - privKeyDer.type = derPOP->type; - privKeyDer.data = &derPOP->data[4]; - privKeyDer.len = derPOP->len - 4; - break; - default: - return SECFailure; + case crmfThisMessage: + case crmfDHMAC: + privKeyDer.type = derPOP->type; + privKeyDer.data = &derPOP->data[5]; + privKeyDer.len = derPOP->len - 5; + break; + case crmfSubsequentMessage: + privKeyDer.type = derPOP->type; + privKeyDer.data = &derPOP->data[4]; + privKeyDer.len = derPOP->len - 4; + break; + default: + return SECFailure; } - rv = SECITEM_CopyItem(inCertReqMsg->poolp, - &popoPrivKey->message.subsequentMessage, - &privKeyDer); + rv = SECITEM_CopyItem(inCertReqMsg->poolp, + &popoPrivKey->message.subsequentMessage, + &privKeyDer); if (rv != SECSuccess) { return rv; } if (popoPrivKey->messageChoice == crmfThisMessage || - popoPrivKey->messageChoice == crmfDHMAC) { + popoPrivKey->messageChoice == crmfDHMAC) { - popoPrivKey->message.thisMessage.len = - CRMF_BYTES_TO_BITS(privKeyDer.len) - (int)derPOP->data[4]; - + popoPrivKey->message.thisMessage.len = + CRMF_BYTES_TO_BITS(privKeyDer.len) - (int)derPOP->data[4]; } - return SECSuccess; + return SECSuccess; } static SECStatus @@ -149,11 +147,11 @@ crmf_decode_process_keyencipherment(CRMFCertReqMsg *inCertReqMsg) if (rv != SECSuccess) { return rv; } - if (inCertReqMsg->pop->popChoice.keyEncipherment.messageChoice == - crmfDHMAC) { + if (inCertReqMsg->pop->popChoice.keyEncipherment.messageChoice == + crmfDHMAC) { /* Key Encipherment can not use the dhMAC option for - * POPOPrivKey. - */ + * POPOPrivKey. + */ return SECFailure; } return SECSuccess; @@ -162,100 +160,99 @@ crmf_decode_process_keyencipherment(CRMFCertReqMsg *inCertReqMsg) static SECStatus crmf_decode_process_pop(CRMFCertReqMsg *inCertReqMsg) { - SECItem *derPOP; - PLArenaPool *poolp; - CRMFProofOfPossession *pop; - void *mark; - SECStatus rv; + SECItem *derPOP; + PLArenaPool *poolp; + CRMFProofOfPossession *pop; + void *mark; + SECStatus rv; - derPOP = &inCertReqMsg->derPOP; - poolp = inCertReqMsg->poolp; - if (derPOP->data == NULL) { - /* There is no Proof of Possession field in this message. */ - return SECSuccess; - } - mark = PORT_ArenaMark(poolp); - pop = PORT_ArenaZNew(poolp, CRMFProofOfPossession); - if (pop == NULL) { - goto loser; - } - pop->popUsed = crmf_get_popchoice_from_der(derPOP); - if (pop->popUsed == crmfNoPOPChoice) { - /* A bad encoding of CRMF. Not a valid tag was given to the - * Proof Of Possession field. - */ - goto loser; - } - inCertReqMsg->pop = pop; - switch (pop->popUsed) { - case crmfRAVerified: - rv = crmf_decode_process_raverified(inCertReqMsg); - break; - case crmfSignature: - rv = crmf_decode_process_signature(inCertReqMsg); - break; - case crmfKeyEncipherment: - rv = crmf_decode_process_keyencipherment(inCertReqMsg); - break; - case crmfKeyAgreement: - rv = crmf_decode_process_keyagreement(inCertReqMsg); - break; - default: - rv = SECFailure; - } - if (rv != SECSuccess) { - goto loser; - } - PORT_ArenaUnmark(poolp, mark); - return SECSuccess; + derPOP = &inCertReqMsg->derPOP; + poolp = inCertReqMsg->poolp; + if (derPOP->data == NULL) { + /* There is no Proof of Possession field in this message. */ + return SECSuccess; + } + mark = PORT_ArenaMark(poolp); + pop = PORT_ArenaZNew(poolp, CRMFProofOfPossession); + if (pop == NULL) { + goto loser; + } + pop->popUsed = crmf_get_popchoice_from_der(derPOP); + if (pop->popUsed == crmfNoPOPChoice) { + /* A bad encoding of CRMF. Not a valid tag was given to the + * Proof Of Possession field. + */ + goto loser; + } + inCertReqMsg->pop = pop; + switch (pop->popUsed) { + case crmfRAVerified: + rv = crmf_decode_process_raverified(inCertReqMsg); + break; + case crmfSignature: + rv = crmf_decode_process_signature(inCertReqMsg); + break; + case crmfKeyEncipherment: + rv = crmf_decode_process_keyencipherment(inCertReqMsg); + break; + case crmfKeyAgreement: + rv = crmf_decode_process_keyagreement(inCertReqMsg); + break; + default: + rv = SECFailure; + } + if (rv != SECSuccess) { + goto loser; + } + PORT_ArenaUnmark(poolp, mark); + return SECSuccess; - loser: - PORT_ArenaRelease(poolp, mark); - inCertReqMsg->pop = NULL; - return SECFailure; - +loser: + PORT_ArenaRelease(poolp, mark); + inCertReqMsg->pop = NULL; + return SECFailure; } static SECStatus crmf_decode_process_single_control(PLArenaPool *poolp, - CRMFControl *inControl) + CRMFControl *inControl) { const SEC_ASN1Template *asn1Template = NULL; inControl->tag = SECOID_FindOIDTag(&inControl->derTag); asn1Template = crmf_get_pkiarchiveoptions_subtemplate(inControl); - PORT_Assert (asn1Template != NULL); - PORT_Assert (poolp != NULL); + PORT_Assert(asn1Template != NULL); + PORT_Assert(poolp != NULL); if (!asn1Template || !poolp) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } /* We've got a union, so passing a pointer to one element of the * union is the same as passing a pointer to any of the other * members of the union. */ - return SEC_ASN1Decode(poolp, &inControl->value.archiveOptions, - asn1Template, (const char*)inControl->derValue.data, - inControl->derValue.len); + return SEC_ASN1Decode(poolp, &inControl->value.archiveOptions, + asn1Template, (const char *)inControl->derValue.data, + inControl->derValue.len); } -static SECStatus +static SECStatus crmf_decode_process_controls(CRMFCertReqMsg *inCertReqMsg) { - int i, numControls; - SECStatus rv; - PLArenaPool *poolp; + int i, numControls; + SECStatus rv; + PLArenaPool *poolp; CRMFControl **controls; - + numControls = CRMF_CertRequestGetNumControls(inCertReqMsg->certReq); controls = inCertReqMsg->certReq->controls; - poolp = inCertReqMsg->poolp; - for (i=0; i < numControls; i++) { + poolp = inCertReqMsg->poolp; + for (i = 0; i < numControls; i++) { rv = crmf_decode_process_single_control(poolp, controls[i]); - if (rv != SECSuccess) { - return SECFailure; - } + if (rv != SECSuccess) { + return SECFailure; + } } return SECSuccess; } @@ -274,26 +271,26 @@ crmf_decode_process_single_reqmsg(CRMFCertReqMsg *inCertReqMsg) if (rv != SECSuccess) { goto loser; } - inCertReqMsg->certReq->certTemplate.numExtensions = + inCertReqMsg->certReq->certTemplate.numExtensions = CRMF_CertRequestGetNumberOfExtensions(inCertReqMsg->certReq); inCertReqMsg->isDecoded = PR_TRUE; rv = SECSuccess; - loser: +loser: return rv; } -CRMFCertReqMsg* -CRMF_CreateCertReqMsgFromDER (const char * buf, long len) +CRMFCertReqMsg * +CRMF_CreateCertReqMsgFromDER(const char *buf, long len) { - PLArenaPool *poolp; + PLArenaPool *poolp; CRMFCertReqMsg *certReqMsg; - SECStatus rv; + SECStatus rv; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { goto loser; } - certReqMsg = PORT_ArenaZNew (poolp, CRMFCertReqMsg); + certReqMsg = PORT_ArenaZNew(poolp, CRMFCertReqMsg); if (certReqMsg == NULL) { goto loser; } @@ -309,27 +306,27 @@ CRMF_CreateCertReqMsgFromDER (const char * buf, long len) } return certReqMsg; - loser: +loser: if (poolp != NULL) { PORT_FreeArena(poolp, PR_FALSE); } return NULL; } -CRMFCertReqMessages* +CRMFCertReqMessages * CRMF_CreateCertReqMessagesFromDER(const char *buf, long len) { - long arenaSize; - int i; - SECStatus rv; - PLArenaPool *poolp; + long arenaSize; + int i; + SECStatus rv; + PLArenaPool *poolp; CRMFCertReqMessages *certReqMsgs; - PORT_Assert (buf != NULL); + PORT_Assert(buf != NULL); /* Wanna make sure the arena is big enough to store all of the requests * coming in. We'll guestimate according to the length of the buffer. */ - arenaSize = len + len/2; + arenaSize = len + len / 2; poolp = PORT_NewArena(arenaSize); if (poolp == NULL) { return NULL; @@ -340,24 +337,24 @@ CRMF_CreateCertReqMessagesFromDER(const char *buf, long len) } certReqMsgs->poolp = poolp; rv = SEC_ASN1Decode(poolp, certReqMsgs, CRMFCertReqMessagesTemplate, - buf, len); + buf, len); if (rv != SECSuccess) { goto loser; } - for (i=0; certReqMsgs->messages[i] != NULL; i++) { - /* The sub-routines expect the individual messages to have - * an arena. We'll give them one temporarily. - */ + for (i = 0; certReqMsgs->messages[i] != NULL; i++) { + /* The sub-routines expect the individual messages to have + * an arena. We'll give them one temporarily. + */ certReqMsgs->messages[i]->poolp = poolp; rv = crmf_decode_process_single_reqmsg(certReqMsgs->messages[i]); - if (rv != SECSuccess) { - goto loser; - } + if (rv != SECSuccess) { + goto loser; + } certReqMsgs->messages[i]->poolp = NULL; } return certReqMsgs; - loser: +loser: PORT_FreeArena(poolp, PR_FALSE); return NULL; } diff --git a/security/nss/lib/crmf/crmfenc.c b/security/nss/lib/crmf/crmfenc.c index bf360183638a..6d01a45cea26 100644 --- a/security/nss/lib/crmf/crmfenc.c +++ b/security/nss/lib/crmf/crmfenc.c @@ -3,53 +3,46 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #include "crmf.h" #include "crmfi.h" -SECStatus -CRMF_EncodeCertReqMsg(CRMFCertReqMsg *inCertReqMsg, - CRMFEncoderOutputCallback fn, - void *arg) +SECStatus +CRMF_EncodeCertReqMsg(CRMFCertReqMsg *inCertReqMsg, + CRMFEncoderOutputCallback fn, + void *arg) { struct crmfEncoderOutput output; - output.fn = fn; + output.fn = fn; output.outputArg = arg; - return SEC_ASN1Encode(inCertReqMsg,CRMFCertReqMsgTemplate, - crmf_encoder_out, &output); - + return SEC_ASN1Encode(inCertReqMsg, CRMFCertReqMsgTemplate, + crmf_encoder_out, &output); } - SECStatus -CRMF_EncodeCertRequest(CRMFCertRequest *inCertReq, - CRMFEncoderOutputCallback fn, - void *arg) +CRMF_EncodeCertRequest(CRMFCertRequest *inCertReq, + CRMFEncoderOutputCallback fn, + void *arg) { struct crmfEncoderOutput output; - output.fn = fn; + output.fn = fn; output.outputArg = arg; - return SEC_ASN1Encode(inCertReq, CRMFCertRequestTemplate, - crmf_encoder_out, &output); + return SEC_ASN1Encode(inCertReq, CRMFCertRequestTemplate, + crmf_encoder_out, &output); } SECStatus -CRMF_EncodeCertReqMessages(CRMFCertReqMsg **inCertReqMsgs, - CRMFEncoderOutputCallback fn, - void *arg) +CRMF_EncodeCertReqMessages(CRMFCertReqMsg **inCertReqMsgs, + CRMFEncoderOutputCallback fn, + void *arg) { struct crmfEncoderOutput output; CRMFCertReqMessages msgs; - - output.fn = fn; + + output.fn = fn; output.outputArg = arg; msgs.messages = inCertReqMsgs; return SEC_ASN1Encode(&msgs, CRMFCertReqMessagesTemplate, - crmf_encoder_out, &output); + crmf_encoder_out, &output); } - - - - diff --git a/security/nss/lib/crmf/crmffut.h b/security/nss/lib/crmf/crmffut.h index bde8241f0391..d6f9374384fd 100644 --- a/security/nss/lib/crmf/crmffut.h +++ b/security/nss/lib/crmf/crmffut.h @@ -8,112 +8,111 @@ */ /* - * Use this function to create the CRMFSinglePubInfo* variables that will + * Use this function to create the CRMFSinglePubInfo* variables that will * populate the inPubInfoArray parameter for the function * CRMF_CreatePKIPublicationInfo. * * "inPubMethod" specifies which publication method will be used - * "pubLocation" is a representation of the location where + * "pubLocation" is a representation of the location where */ -extern CRMFSinglePubInfo* - CRMF_CreateSinglePubInfo(CRMFPublicationMethod inPubMethod, - CRMFGeneralName *pubLocation); +extern CRMFSinglePubInfo * +CRMF_CreateSinglePubInfo(CRMFPublicationMethod inPubMethod, + CRMFGeneralName *pubLocation); /* * Create a PKIPublicationInfo that can later be passed to the function * CRMFAddPubInfoControl. */ extern CRMFPKIPublicationInfo * - CRMF_CreatePKIPublicationInfo(CRMFPublicationAction inAction, - CRMFSinglePubInfo **inPubInfoArray, - int numPubInfo); +CRMF_CreatePKIPublicationInfo(CRMFPublicationAction inAction, + CRMFSinglePubInfo **inPubInfoArray, + int numPubInfo); /* * Only call this function on a CRMFPublicationInfo that was created by * CRMF_CreatePKIPublicationInfo that was passed in NULL for arena. */ -extern SECStatus - CRMF_DestroyPKIPublicationInfo(CRMFPKIPublicationInfo *inPubInfo); +extern SECStatus +CRMF_DestroyPKIPublicationInfo(CRMFPKIPublicationInfo *inPubInfo); -extern SECStatus CRMF_AddPubInfoControl(CRMFCertRequest *inCertReq, - CRMFPKIPublicationInfo *inPubInfo); +extern SECStatus CRMF_AddPubInfoControl(CRMFCertRequest *inCertReq, + CRMFPKIPublicationInfo *inPubInfo); /* - * This is to create a Cert ID Control which can later be added to + * This is to create a Cert ID Control which can later be added to * a certificate request. */ -extern CRMFCertID* CRMF_CreateCertID(CRMFGeneralName *issuer, - long serialNumber); +extern CRMFCertID *CRMF_CreateCertID(CRMFGeneralName *issuer, + long serialNumber); -extern SECStatus CRMF_DestroyCertID(CRMFCertID* certID); +extern SECStatus CRMF_DestroyCertID(CRMFCertID *certID); extern SECStatus CRMF_AddCertIDControl(CRMFCertRequest *inCertReq, - CRMFCertID *certID); + CRMFCertID *certID); -extern SECStatus - CRMF_AddProtocolEncryptioKeyControl(CRMFCertRequest *inCertReq, - CERTSubjectPublicKeyInfo *spki); +extern SECStatus +CRMF_AddProtocolEncryptioKeyControl(CRMFCertRequest *inCertReq, + CERTSubjectPublicKeyInfo *spki); /* * Add the ASCII Pairs Registration Info to the Certificate Request. * The SECItem must be an OCTET string representation. */ extern SECStatus - CRMF_AddUTF8PairsRegInfo(CRMFCertRequest *inCertReq, - SECItem *asciiPairs); +CRMF_AddUTF8PairsRegInfo(CRMFCertRequest *inCertReq, + SECItem *asciiPairs); /* - * This takes a CertRequest and adds it to another CertRequest. + * This takes a CertRequest and adds it to another CertRequest. */ extern SECStatus - CRMF_AddCertReqToRegInfo(CRMFCertRequest *certReqToAddTo, - CRMFCertRequest *certReqBeingAdded); +CRMF_AddCertReqToRegInfo(CRMFCertRequest *certReqToAddTo, + CRMFCertRequest *certReqBeingAdded); /* * Returns which option was used for the authInfo field of POPOSigningKeyInput */ -extern CRMFPOPOSkiInputAuthChoice - CRMF_GetSignKeyInputAuthChoice(CRMFPOPOSigningKeyInput *inKeyInput); +extern CRMFPOPOSkiInputAuthChoice +CRMF_GetSignKeyInputAuthChoice(CRMFPOPOSigningKeyInput *inKeyInput); /* * Gets the PKMACValue associated with the POPOSigningKeyInput. - * If the POPOSigningKeyInput did not use authInfo.publicKeyMAC + * If the POPOSigningKeyInput did not use authInfo.publicKeyMAC * the function returns SECFailure and the value at *destValue is unchanged. * * If the POPOSigningKeyInput did use authInfo.publicKeyMAC, the function * returns SECSuccess and places the PKMACValue at *destValue. */ -extern SECStatus - CRMF_GetSignKeyInputPKMACValue(CRMFPOPOSigningKeyInput *inKeyInput, - CRMFPKMACValue **destValue); +extern SECStatus +CRMF_GetSignKeyInputPKMACValue(CRMFPOPOSigningKeyInput *inKeyInput, + CRMFPKMACValue **destValue); /* * Gets the SubjectPublicKeyInfo from the POPOSigningKeyInput */ extern CERTSubjectPublicKeyInfo * - CRMF_GetSignKeyInputPublicKey(CRMFPOPOSigningKeyInput *inKeyInput); - +CRMF_GetSignKeyInputPublicKey(CRMFPOPOSigningKeyInput *inKeyInput); /* * Return the value for the PKIPublicationInfo Control. - * A return value of NULL indicates that the Control was - * not a PKIPublicationInfo Control. Call + * A return value of NULL indicates that the Control was + * not a PKIPublicationInfo Control. Call * CRMF_DestroyPKIPublicationInfo on the return value when done * using the pointer. */ -extern CRMFPKIPublicationInfo* CRMF_GetPKIPubInfo(CRMFControl *inControl); +extern CRMFPKIPublicationInfo *CRMF_GetPKIPubInfo(CRMFControl *inControl); /* * Free up a CRMFPKIPublicationInfo structure. */ -extern SECStatus - CRMF_DestroyPKIPublicationInfo(CRMFPKIPublicationInfo *inPubInfo); +extern SECStatus +CRMF_DestroyPKIPublicationInfo(CRMFPKIPublicationInfo *inPubInfo); /* * Get the choice used for action in this PKIPublicationInfo. */ -extern CRMFPublicationAction - CRMF_GetPublicationAction(CRMFPKIPublicationInfo *inPubInfo); +extern CRMFPublicationAction +CRMF_GetPublicationAction(CRMFPKIPublicationInfo *inPubInfo); /* * Get the number of pubInfos are stored in the PKIPubicationInfo. @@ -124,9 +123,9 @@ extern int CRMF_GetNumPubInfos(CRMFPKIPublicationInfo *inPubInfo); * Get the pubInfo at index for the given PKIPubicationInfo. * Indexing is done like a traditional C Array. (0 .. numElements-1) */ -extern CRMFSinglePubInfo* - CRMF_GetPubInfoAtIndex(CRMFPKIPublicationInfo *inPubInfo, - int index); +extern CRMFSinglePubInfo * +CRMF_GetPubInfoAtIndex(CRMFPKIPublicationInfo *inPubInfo, + int index); /* * Destroy the CRMFSinglePubInfo. @@ -136,15 +135,15 @@ extern SECStatus CRMF_DestroySinglePubInfo(CRMFSinglePubInfo *inPubInfo); /* * Get the pubMethod used by the SinglePubInfo. */ -extern CRMFPublicationMethod - CRMF_GetPublicationMethod(CRMFSinglePubInfo *inPubInfo); +extern CRMFPublicationMethod +CRMF_GetPublicationMethod(CRMFSinglePubInfo *inPubInfo); /* * Get the pubLocation associated with the SinglePubInfo. * A NULL return value indicates there was no pubLocation associated * with the SinglePuInfo. */ -extern CRMFGeneralName* CRMF_GetPubLocation(CRMFSinglePubInfo *inPubInfo); +extern CRMFGeneralName *CRMF_GetPubLocation(CRMFSinglePubInfo *inPubInfo); /* * Get the authInfo.sender field out of the POPOSigningKeyInput. @@ -155,7 +154,7 @@ extern CRMFGeneralName* CRMF_GetPubLocation(CRMFSinglePubInfo *inPubInfo); * SECSuccess and puts the authInfo.sender at *destName/ */ extern SECStatus CRMF_GetSignKeyInputSender(CRMFPOPOSigningKeyInput *keyInput, - CRMFGeneralName **destName); + CRMFGeneralName **destName); /**************** CMMF Functions that need to be added. **********************/ @@ -175,7 +174,7 @@ extern SECStatus CRMF_GetSignKeyInputSender(CRMFPOPOSigningKeyInput *keyInput, * contained by 'inDecKeyChall'. Refer to the CMMF draft on how the * the random number passed in and the sender's GeneralName are used * to generate the challenge and witness fields of the challenge. This - * library will use SHA1 as the one-way function for generating the + * library will use SHA1 as the one-way function for generating the * witess field of the challenge. * * RETURN: @@ -184,11 +183,10 @@ extern SECStatus CRMF_GetSignKeyInputSender(CRMFPOPOSigningKeyInput *keyInput, * while trying to generate the challenge. */ extern SECStatus -CMMF_POPODecKeyChallContentSetNextChallenge - (CMMFPOPODecKeyChallContent *inDecKeyChall, - long inRandom, - CERTGeneralName *inSender, - SECKEYPublicKey *inPubKey); +CMMF_POPODecKeyChallContentSetNextChallenge(CMMFPOPODecKeyChallContent *inDecKeyChall, + long inRandom, + CERTGeneralName *inSender, + SECKEYPublicKey *inPubKey); /* * FUNCTION: CMMF_POPODecKeyChallContentGetNumChallenges @@ -196,11 +194,10 @@ CMMF_POPODecKeyChallContentSetNextChallenge * inKeyChallCont * The CMMFPOPODecKeyChallContent to operate on. * RETURN: - * This function returns the number of CMMFChallenges are contained in + * This function returns the number of CMMFChallenges are contained in * the CMMFPOPODecKeyChallContent structure. */ -extern int CMMF_POPODecKeyChallContentGetNumChallenges - (CMMFPOPODecKeyChallContent *inKeyChallCont); +extern int CMMF_POPODecKeyChallContentGetNumChallenges(CMMFPOPODecKeyChallContent *inKeyChallCont); /* * FUNCTION: CMMF_ChallengeGetRandomNumber @@ -213,9 +210,9 @@ extern int CMMF_POPODecKeyChallContentGetNumChallenges * challenge. * NOTES: * This function returns the value held in the decrypted Rand structure - * corresponding to the random integer. The user must call - * CMMF_ChallengeDecryptWitness before calling this function. Call - * CMMF_ChallengeIsDecrypted to find out if the challenge has been + * corresponding to the random integer. The user must call + * CMMF_ChallengeDecryptWitness before calling this function. Call + * CMMF_ChallengeIsDecrypted to find out if the challenge has been * decrypted. * * RETURN: @@ -225,7 +222,7 @@ extern int CMMF_POPODecKeyChallContentGetNumChallenges * is not a valid value. */ extern SECStatus CMMF_ChallengeGetRandomNumber(CMMFChallenge *inChallenge, - long *inDest); + long *inDest); /* * FUNCTION: CMMF_ChallengeGetSender @@ -234,8 +231,8 @@ extern SECStatus CMMF_ChallengeGetRandomNumber(CMMFChallenge *inChallenge, * the CMMFChallenge to operate on. * NOTES: * This function returns the value held in the decrypted Rand structure - * corresponding to the sender. The user must call - * CMMF_ChallengeDecryptWitness before calling this function. Call + * corresponding to the sender. The user must call + * CMMF_ChallengeDecryptWitness before calling this function. Call * CMMF_ChallengeIsDecrypted to find out if the witness field has been * decrypted. The user must call CERT_DestroyGeneralName after the return * value is no longer needed. @@ -245,7 +242,7 @@ extern SECStatus CMMF_ChallengeGetRandomNumber(CMMFChallenge *inChallenge, * NULL indicates an error in trying to copy the information or that the * witness field has not been decrypted. */ -extern CERTGeneralName* CMMF_ChallengeGetSender(CMMFChallenge *inChallenge); +extern CERTGeneralName *CMMF_ChallengeGetSender(CMMFChallenge *inChallenge); /* * FUNCTION: CMMF_ChallengeGetAlgId @@ -256,19 +253,19 @@ extern CERTGeneralName* CMMF_ChallengeGetSender(CMMFChallenge *inChallenge); * A pointer to memory where a pointer to a copy of the algorithm * id can be placed. * NOTES: - * This function retrieves the one way function algorithm identifier + * This function retrieves the one way function algorithm identifier * contained within the CMMFChallenge if the optional field is present. * * RETURN: * SECSucces indicates the function was able to place a pointer to a copy of - * the alogrithm id at *inAlgId. If the value at *inDestAlgId is NULL, - * that means there was no algorithm identifier present in the - * CMMFChallenge. Any other return value indicates the function was not - * able to make a copy of the algorithm identifier. In this case the value + * the alogrithm id at *inAlgId. If the value at *inDestAlgId is NULL, + * that means there was no algorithm identifier present in the + * CMMFChallenge. Any other return value indicates the function was not + * able to make a copy of the algorithm identifier. In this case the value * at *inDestAlgId is not valid. */ -extern SECStatus CMMF_ChallengeGetAlgId(CMMFChallenge *inChallenge, - SECAlgorithmID *inAlgId); +extern SECStatus CMMF_ChallengeGetAlgId(CMMFChallenge *inChallenge, + SECAlgorithmID *inAlgId); /* * FUNCTION: CMMF_DestroyChallenge @@ -276,14 +273,14 @@ extern SECStatus CMMF_ChallengeGetAlgId(CMMFChallenge *inChallenge, * inChallenge * The CMMFChallenge to free up. * NOTES: - * This function frees up all the memory associated with the CMMFChallenge + * This function frees up all the memory associated with the CMMFChallenge * passed in. * RETURN: * SECSuccess if freeing all the memory associated with the CMMFChallenge - * passed in is successful. Any other return value indicates an error + * passed in is successful. Any other return value indicates an error * while freeing the memory. */ -extern SECStatus CMMF_DestroyChallenge (CMMFChallenge *inChallenge); +extern SECStatus CMMF_DestroyChallenge(CMMFChallenge *inChallenge); /* * FUNCTION: CMMF_DestroyPOPODecKeyRespContent @@ -291,7 +288,7 @@ extern SECStatus CMMF_DestroyChallenge (CMMFChallenge *inChallenge); * inDecKeyResp * The CMMFPOPODecKeyRespContent structure to free. * NOTES: - * This function frees up all the memory associate with the + * This function frees up all the memory associate with the * CMMFPOPODecKeyRespContent. * * RETURN: @@ -300,7 +297,7 @@ extern SECStatus CMMF_DestroyChallenge (CMMFChallenge *inChallenge); * return value indicates an error while freeing the memory. */ extern SECStatus - CMMF_DestroyPOPODecKeyRespContent(CMMFPOPODecKeyRespContent *inDecKeyResp); +CMMF_DestroyPOPODecKeyRespContent(CMMFPOPODecKeyRespContent *inDecKeyResp); /* * FUNCTION: CMMF_ChallengeDecryptWitness @@ -312,7 +309,7 @@ extern SECStatus * NOTES: * This function uses the private key to decrypt the challenge field * contained in the CMMFChallenge. Make sure the private key matches the - * public key that was used to encrypt the witness. The creator of + * public key that was used to encrypt the witness. The creator of * the challenge will most likely be an RA that has the public key * from a Cert request. So the private key should be the private key * associated with public key in that request. This function will also @@ -320,15 +317,15 @@ extern SECStatus * * RETURN: * SECSuccess if decrypting the witness field was successful. This does - * not indicate that the decrypted data is valid, since the private key - * passed in may not be the actual key needed to properly decrypt the + * not indicate that the decrypted data is valid, since the private key + * passed in may not be the actual key needed to properly decrypt the * witness field. Meaning that there is a decrypted structure now, but * may be garbage because the private key was incorrect. * Any other return value indicates the function could not complete the * decryption process. */ -extern SECStatus CMMF_ChallengeDecryptWitness(CMMFChallenge *inChallenge, - SECKEYPrivateKey *inPrivKey); +extern SECStatus CMMF_ChallengeDecryptWitness(CMMFChallenge *inChallenge, + SECKEYPrivateKey *inPrivKey); /* * FUNCTION: CMMF_ChallengeIsDecrypted @@ -336,8 +333,8 @@ extern SECStatus CMMF_ChallengeDecryptWitness(CMMFChallenge *inChallenge, * inChallenge * The CMMFChallenge to operate on. * RETURN: - * This is a predicate function that returns PR_TRUE if the decryption - * process has already been performed. The function return PR_FALSE if + * This is a predicate function that returns PR_TRUE if the decryption + * process has already been performed. The function return PR_FALSE if * the decryption process has not been performed yet. */ extern PRBool CMMF_ChallengeIsDecrypted(CMMFChallenge *inChallenge); @@ -348,14 +345,13 @@ extern PRBool CMMF_ChallengeIsDecrypted(CMMFChallenge *inChallenge); * inDecKeyCont * The CMMFPOPODecKeyChallContent to free * NOTES: - * This function frees up all the memory associated with the - * CMMFPOPODecKeyChallContent + * This function frees up all the memory associated with the + * CMMFPOPODecKeyChallContent * RETURN: - * SECSuccess if freeing up all the memory associatd with the + * SECSuccess if freeing up all the memory associatd with the * CMMFPOPODecKeyChallContent is successful. Any other return value * indicates an error while freeing the memory. * */ -extern SECStatus - CMMF_DestroyPOPODecKeyChallContent (CMMFPOPODecKeyChallContent *inDecKeyCont); - +extern SECStatus +CMMF_DestroyPOPODecKeyChallContent(CMMFPOPODecKeyChallContent *inDecKeyCont); diff --git a/security/nss/lib/crmf/crmfget.c b/security/nss/lib/crmf/crmfget.c index 4886cda9b390..86514a7ac070 100644 --- a/security/nss/lib/crmf/crmfget.c +++ b/security/nss/lib/crmf/crmfget.c @@ -8,7 +8,6 @@ #include "keyhi.h" #include "secder.h" - CRMFPOPChoice CRMF_CertReqMsgGetPOPType(CRMFCertReqMsg *inCertReqMsg) { @@ -22,50 +21,51 @@ CRMF_CertReqMsgGetPOPType(CRMFCertReqMsg *inCertReqMsg) static SECStatus crmf_destroy_validity(CRMFOptionalValidity *inValidity, PRBool freeit) { - if (inValidity != NULL){ + if (inValidity != NULL) { if (inValidity->notBefore.data != NULL) { - PORT_Free(inValidity->notBefore.data); - } - if (inValidity->notAfter.data != NULL) { - PORT_Free(inValidity->notAfter.data); - } - if (freeit) { - PORT_Free(inValidity); - } + PORT_Free(inValidity->notBefore.data); + } + if (inValidity->notAfter.data != NULL) { + PORT_Free(inValidity->notAfter.data); + } + if (freeit) { + PORT_Free(inValidity); + } } return SECSuccess; } -static SECStatus -crmf_copy_cert_request_validity(PLArenaPool *poolp, - CRMFOptionalValidity **destValidity, - CRMFOptionalValidity *srcValidity) +static SECStatus +crmf_copy_cert_request_validity(PLArenaPool *poolp, + CRMFOptionalValidity **destValidity, + CRMFOptionalValidity *srcValidity) { CRMFOptionalValidity *myValidity = NULL; - SECStatus rv; + SECStatus rv; *destValidity = myValidity = (poolp == NULL) ? - PORT_ZNew(CRMFOptionalValidity) : - PORT_ArenaZNew(poolp, CRMFOptionalValidity); + PORT_ZNew(CRMFOptionalValidity) + : + PORT_ArenaZNew(poolp, CRMFOptionalValidity); if (myValidity == NULL) { goto loser; } if (srcValidity->notBefore.data != NULL) { - rv = SECITEM_CopyItem(poolp, &myValidity->notBefore, - &srcValidity->notBefore); - if (rv != SECSuccess) { - goto loser; - } + rv = SECITEM_CopyItem(poolp, &myValidity->notBefore, + &srcValidity->notBefore); + if (rv != SECSuccess) { + goto loser; + } } if (srcValidity->notAfter.data != NULL) { - rv = SECITEM_CopyItem(poolp, &myValidity->notAfter, - &srcValidity->notAfter); - if (rv != SECSuccess) { - goto loser; - } + rv = SECITEM_CopyItem(poolp, &myValidity->notAfter, + &srcValidity->notAfter); + if (rv != SECSuccess) { + goto loser; + } } return SECSuccess; - loser: +loser: if (myValidity != NULL && poolp == NULL) { crmf_destroy_validity(myValidity, PR_TRUE); } @@ -73,11 +73,11 @@ crmf_copy_cert_request_validity(PLArenaPool *poolp, } static SECStatus -crmf_copy_extensions(PLArenaPool *poolp, - CRMFCertTemplate *destTemplate, - CRMFCertExtension **srcExt) +crmf_copy_extensions(PLArenaPool *poolp, + CRMFCertTemplate *destTemplate, + CRMFCertExtension **srcExt) { - int numExt = 0, i; + int numExt = 0, i; CRMFCertExtension **myExtArray = NULL; while (srcExt[numExt] != NULL) { @@ -86,32 +86,32 @@ crmf_copy_extensions(PLArenaPool *poolp, if (numExt == 0) { /*No extensions to copy.*/ destTemplate->extensions = NULL; - destTemplate->numExtensions = 0; + destTemplate->numExtensions = 0; return SECSuccess; } - destTemplate->extensions = myExtArray = - PORT_NewArray(CRMFCertExtension*, numExt+1); + destTemplate->extensions = myExtArray = + PORT_NewArray(CRMFCertExtension *, numExt + 1); if (myExtArray == NULL) { goto loser; } - - for (i=0; inumExtensions = numExt; myExtArray[numExt] = NULL; return SECSuccess; - loser: +loser: if (myExtArray != NULL) { if (poolp == NULL) { - for (i=0; myExtArray[i] != NULL; i++) { - CRMF_DestroyCertExtension(myExtArray[i]); - } - } - PORT_Free(myExtArray); + for (i = 0; myExtArray[i] != NULL; i++) { + CRMF_DestroyCertExtension(myExtArray[i]); + } + } + PORT_Free(myExtArray); } destTemplate->extensions = NULL; destTemplate->numExtensions = 0; @@ -119,95 +119,95 @@ crmf_copy_extensions(PLArenaPool *poolp, } static SECStatus -crmf_copy_cert_request_template(PLArenaPool *poolp, - CRMFCertTemplate *destTemplate, - CRMFCertTemplate *srcTemplate) +crmf_copy_cert_request_template(PLArenaPool *poolp, + CRMFCertTemplate *destTemplate, + CRMFCertTemplate *srcTemplate) { SECStatus rv; if (srcTemplate->version.data != NULL) { - rv = SECITEM_CopyItem(poolp, &destTemplate->version, - &srcTemplate->version); - if (rv != SECSuccess) { - goto loser; - } + rv = SECITEM_CopyItem(poolp, &destTemplate->version, + &srcTemplate->version); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->serialNumber.data != NULL) { rv = SECITEM_CopyItem(poolp, &destTemplate->serialNumber, - &srcTemplate->serialNumber); - if (rv != SECSuccess) { - goto loser; - } + &srcTemplate->serialNumber); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->signingAlg != NULL) { rv = crmf_template_copy_secalg(poolp, &destTemplate->signingAlg, - srcTemplate->signingAlg); - if (rv != SECSuccess) { - goto loser; - } + srcTemplate->signingAlg); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->issuer != NULL) { rv = crmf_copy_cert_name(poolp, &destTemplate->issuer, - srcTemplate->issuer); - if (rv != SECSuccess) { - goto loser; - } + srcTemplate->issuer); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->validity != NULL) { rv = crmf_copy_cert_request_validity(poolp, &destTemplate->validity, - srcTemplate->validity); - if (rv != SECSuccess) { - goto loser; - } + srcTemplate->validity); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->subject != NULL) { - rv = crmf_copy_cert_name(poolp, &destTemplate->subject, - srcTemplate->subject); - if (rv != SECSuccess) { - goto loser; - } + rv = crmf_copy_cert_name(poolp, &destTemplate->subject, + srcTemplate->subject); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->publicKey != NULL) { rv = crmf_template_add_public_key(poolp, &destTemplate->publicKey, - srcTemplate->publicKey); - if (rv != SECSuccess) { - goto loser; - } + srcTemplate->publicKey); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->issuerUID.data != NULL) { rv = crmf_make_bitstring_copy(poolp, &destTemplate->issuerUID, - &srcTemplate->issuerUID); - if (rv != SECSuccess) { - goto loser; - } + &srcTemplate->issuerUID); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->subjectUID.data != NULL) { rv = crmf_make_bitstring_copy(poolp, &destTemplate->subjectUID, - &srcTemplate->subjectUID); - if (rv != SECSuccess) { - goto loser; - } + &srcTemplate->subjectUID); + if (rv != SECSuccess) { + goto loser; + } } if (srcTemplate->extensions != NULL) { rv = crmf_copy_extensions(poolp, destTemplate, - srcTemplate->extensions); - if (rv != SECSuccess) { - goto loser; - } + srcTemplate->extensions); + if (rv != SECSuccess) { + goto loser; + } } return SECSuccess; - loser: +loser: return SECFailure; } -static CRMFControl* +static CRMFControl * crmf_copy_control(PLArenaPool *poolp, CRMFControl *srcControl) { CRMFControl *newControl; - SECStatus rv; + SECStatus rv; newControl = (poolp == NULL) ? PORT_ZNew(CRMFControl) : - PORT_ArenaZNew(poolp, CRMFControl); + PORT_ArenaZNew(poolp, CRMFControl); if (newControl == NULL) { goto loser; } @@ -225,20 +225,20 @@ crmf_copy_control(PLArenaPool *poolp, CRMFControl *srcControl) * then they need to be handled here as well. */ switch (newControl->tag) { - case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: - rv = crmf_copy_pkiarchiveoptions(poolp, - &newControl->value.archiveOptions, - &srcControl->value.archiveOptions); - break; - default: - rv = SECSuccess; + case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: + rv = crmf_copy_pkiarchiveoptions(poolp, + &newControl->value.archiveOptions, + &srcControl->value.archiveOptions); + break; + default: + rv = SECSuccess; } if (rv != SECSuccess) { goto loser; } return newControl; - loser: +loser: if (poolp == NULL && newControl != NULL) { CRMF_DestroyControl(newControl); } @@ -246,11 +246,11 @@ crmf_copy_control(PLArenaPool *poolp, CRMFControl *srcControl) } static SECStatus -crmf_copy_cert_request_controls(PLArenaPool *poolp, - CRMFCertRequest *destReq, - CRMFCertRequest *srcReq) +crmf_copy_cert_request_controls(PLArenaPool *poolp, + CRMFCertRequest *destReq, + CRMFCertRequest *srcReq) { - int numControls, i; + int numControls, i; CRMFControl **myControls = NULL; numControls = CRMF_CertRequestGetNumControls(srcReq); @@ -258,43 +258,42 @@ crmf_copy_cert_request_controls(PLArenaPool *poolp, /* No Controls To Copy*/ return SECSuccess; } - myControls = destReq->controls = PORT_NewArray(CRMFControl*, - numControls+1); + myControls = destReq->controls = PORT_NewArray(CRMFControl *, + numControls + 1); if (myControls == NULL) { goto loser; } - for (i=0; icontrols[i]); - if (myControls[i] == NULL) { - goto loser; - } + if (myControls[i] == NULL) { + goto loser; + } } myControls[numControls] = NULL; return SECSuccess; - loser: +loser: if (myControls != NULL) { if (poolp == NULL) { - for (i=0; myControls[i] != NULL; i++) { - CRMF_DestroyControl(myControls[i]); - } - } - PORT_Free(myControls); + for (i = 0; myControls[i] != NULL; i++) { + CRMF_DestroyControl(myControls[i]); + } + } + PORT_Free(myControls); } return SECFailure; } - -CRMFCertRequest* +CRMFCertRequest * crmf_copy_cert_request(PLArenaPool *poolp, CRMFCertRequest *srcReq) { CRMFCertRequest *newReq = NULL; - SECStatus rv; + SECStatus rv; if (srcReq == NULL) { return NULL; } newReq = (poolp == NULL) ? PORT_ZNew(CRMFCertRequest) : - PORT_ArenaZNew(poolp, CRMFCertRequest); + PORT_ArenaZNew(poolp, CRMFCertRequest); if (newReq == NULL) { goto loser; } @@ -302,8 +301,8 @@ crmf_copy_cert_request(PLArenaPool *poolp, CRMFCertRequest *srcReq) if (rv != SECSuccess) { goto loser; } - rv = crmf_copy_cert_request_template(poolp, &newReq->certTemplate, - &srcReq->certTemplate); + rv = crmf_copy_cert_request_template(poolp, &newReq->certTemplate, + &srcReq->certTemplate); if (rv != SECSuccess) { goto loser; } @@ -312,7 +311,7 @@ crmf_copy_cert_request(PLArenaPool *poolp, CRMFCertRequest *srcReq) goto loser; } return newReq; - loser: +loser: if (newReq != NULL && poolp == NULL) { CRMF_DestroyCertRequest(newReq); PORT_Free(newReq); @@ -320,19 +319,19 @@ crmf_copy_cert_request(PLArenaPool *poolp, CRMFCertRequest *srcReq) return NULL; } -SECStatus +SECStatus CRMF_DestroyGetValidity(CRMFGetValidity *inValidity) { PORT_Assert(inValidity != NULL); if (inValidity != NULL) { if (inValidity->notAfter) { - PORT_Free(inValidity->notAfter); - inValidity->notAfter = NULL; - } - if (inValidity->notBefore) { - PORT_Free(inValidity->notBefore); - inValidity->notBefore = NULL; - } + PORT_Free(inValidity->notAfter); + inValidity->notAfter = NULL; + } + if (inValidity->notBefore) { + PORT_Free(inValidity->notBefore); + inValidity->notBefore = NULL; + } } return SECSuccess; } @@ -346,7 +345,7 @@ crmf_make_bitstring_copy(PLArenaPool *arena, SECItem *dest, SECItem *src) origLenBits = src->len; bytesToCopy = CRMF_BITS_TO_BYTES(origLenBits); - src->len = bytesToCopy; + src->len = bytesToCopy; rv = SECITEM_CopyItem(arena, dest, src); src->len = origLenBits; if (rv != SECSuccess) { @@ -361,11 +360,11 @@ CRMF_CertRequestGetNumberOfExtensions(CRMFCertRequest *inCertReq) { CRMFCertTemplate *certTemplate; int count = 0; - + certTemplate = &inCertReq->certTemplate; if (certTemplate->extensions) { while (certTemplate->extensions[count] != NULL) - count++; + count++; } return count; } @@ -390,17 +389,16 @@ CRMF_CertExtensionGetIsCritical(CRMFCertExtension *inExt) return inExt->critical.data != NULL; } -SECItem* +SECItem * CRMF_CertExtensionGetValue(CRMFCertExtension *inExtension) { PORT_Assert(inExtension != NULL); if (inExtension == NULL) { return NULL; } - + return SECITEM_DupItem(&inExtension->value); } - SECStatus CRMF_DestroyPOPOSigningKey(CRMFPOPOSigningKey *inKey) @@ -408,15 +406,15 @@ CRMF_DestroyPOPOSigningKey(CRMFPOPOSigningKey *inKey) PORT_Assert(inKey != NULL); if (inKey != NULL) { if (inKey->derInput.data != NULL) { - SECITEM_FreeItem(&inKey->derInput, PR_FALSE); - } - if (inKey->algorithmIdentifier != NULL) { - SECOID_DestroyAlgorithmID(inKey->algorithmIdentifier, PR_TRUE); - } - if (inKey->signature.data != NULL) { - SECITEM_FreeItem(&inKey->signature, PR_FALSE); - } - PORT_Free(inKey); + SECITEM_FreeItem(&inKey->derInput, PR_FALSE); + } + if (inKey->algorithmIdentifier != NULL) { + SECOID_DestroyAlgorithmID(inKey->algorithmIdentifier, PR_TRUE); + } + if (inKey->signature.data != NULL) { + SECITEM_FreeItem(&inKey->signature, PR_FALSE); + } + PORT_Free(inKey); } return SECSuccess; } @@ -427,7 +425,7 @@ CRMF_DestroyPOPOPrivKey(CRMFPOPOPrivKey *inPrivKey) PORT_Assert(inPrivKey != NULL); if (inPrivKey != NULL) { SECITEM_FreeItem(&inPrivKey->message.thisMessage, PR_FALSE); - PORT_Free(inPrivKey); + PORT_Free(inPrivKey); } return SECSuccess; } @@ -435,7 +433,7 @@ CRMF_DestroyPOPOPrivKey(CRMFPOPOPrivKey *inPrivKey) int CRMF_CertRequestGetNumControls(CRMFCertRequest *inCertReq) { - int count = 0; + int count = 0; PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { @@ -443,8 +441,7 @@ CRMF_CertRequestGetNumControls(CRMFCertRequest *inCertReq) } if (inCertReq->controls) { while (inCertReq->controls[count] != NULL) - count++; + count++; } return count; } - diff --git a/security/nss/lib/crmf/crmfi.h b/security/nss/lib/crmf/crmfi.h index fd27a9b9a129..badfd2b053d8 100644 --- a/security/nss/lib/crmf/crmfi.h +++ b/security/nss/lib/crmf/crmfi.h @@ -3,11 +3,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #ifndef _CRMFI_H_ #define _CRMFI_H_ -/* This file will contain all declarations common to both - * encoding and decoding of CRMF Cert Requests. This header +/* This file will contain all declarations common to both + * encoding and decoding of CRMF Cert Requests. This header * file should only be included internally by CRMF implementation * files. */ @@ -16,38 +15,38 @@ #include "secerr.h" #include "blapit.h" -#define CRMF_DEFAULT_ARENA_SIZE 1024 +#define CRMF_DEFAULT_ARENA_SIZE 1024 /* * Explanation for the definition of MAX_WRAPPED_KEY_LEN: - * + * * It's used for internal buffers to transport a wrapped private key. * The value is in BYTES. * We want to define a reasonable upper bound for this value. * Ideally this could be calculated, but in order to simplify the code * we want to estimate the maximum requires size. * See also bug 655850 for the full explanation. - * + * * We know the largest wrapped keys are RSA keys. * We'll estimate the maximum size needed for wrapped RSA keys, * and assume it's sufficient for wrapped keys of any type we support. - * + * * The maximum size of RSA keys in bits is defined elsewhere as * RSA_MAX_MODULUS_BITS - * + * * The idea is to define MAX_WRAPPED_KEY_LEN based on the above. - * + * * A wrapped RSA key requires about * ( ( RSA_MAX_MODULUS_BITS / 8 ) * 5.5) + 65 * bytes. - * + * * Therefore, a safe upper bound is: * ( ( RSA_MAX_MODULUS_BITS / 8 ) *8 ) = RSA_MAX_MODULUS_BITS - * + * */ -#define MAX_WRAPPED_KEY_LEN RSA_MAX_MODULUS_BITS +#define MAX_WRAPPED_KEY_LEN RSA_MAX_MODULUS_BITS -#define CRMF_BITS_TO_BYTES(bits) (((bits)+7)/8) +#define CRMF_BITS_TO_BYTES(bits) (((bits) + 7) / 8) #define CRMF_BYTES_TO_BITS(bytes) ((bytes)*8) struct crmfEncoderArg { @@ -61,30 +60,30 @@ struct crmfEncoderOutput { }; /* - * This function is used by the API for encoding functions that are + * This function is used by the API for encoding functions that are * exposed through the API, ie all of the CMMF_Encode* and CRMF_Encode* * functions. */ extern void - crmf_encoder_out(void *arg, const char *buf, unsigned long len, - int depth, SEC_ASN1EncodingPart data_kind); +crmf_encoder_out(void *arg, const char *buf, unsigned long len, + int depth, SEC_ASN1EncodingPart data_kind); /* * This function is used when we want to encode something locally within * the library, ie the CertRequest so that we can produce its signature. */ -extern SECStatus - crmf_init_encoder_callback_arg (struct crmfEncoderArg *encoderArg, - SECItem *derDest); +extern SECStatus +crmf_init_encoder_callback_arg(struct crmfEncoderArg *encoderArg, + SECItem *derDest); /* * This is the callback function we feed to the ASN1 encoder when doing - * internal DER-encodings. ie, encoding the cert request so we can + * internal DER-encodings. ie, encoding the cert request so we can * produce a signature. */ extern void -crmf_generic_encoder_callback(void *arg, const char* buf, unsigned long len, - int depth, SEC_ASN1EncodingPart data_kind); +crmf_generic_encoder_callback(void *arg, const char *buf, unsigned long len, + int depth, SEC_ASN1EncodingPart data_kind); /* The ASN1 templates that need to be seen by internal files * in order to implement CRMF. @@ -109,76 +108,76 @@ extern const unsigned char hexFalse; * Prototypes for helper routines used internally by multiple files. */ extern SECStatus crmf_encode_integer(PLArenaPool *poolp, SECItem *dest, - long value); + long value); extern SECStatus crmf_make_bitstring_copy(PLArenaPool *arena, SECItem *dest, - SECItem *src); + SECItem *src); -extern SECStatus crmf_copy_pkiarchiveoptions(PLArenaPool *poolp, - CRMFPKIArchiveOptions *destOpt, - CRMFPKIArchiveOptions *srcOpt); -extern SECStatus - crmf_destroy_pkiarchiveoptions(CRMFPKIArchiveOptions *inArchOptions, - PRBool freeit); -extern const SEC_ASN1Template* - crmf_get_pkiarchiveoptions_subtemplate(CRMFControl *inControl); - -extern SECStatus crmf_copy_encryptedkey(PLArenaPool *poolp, - CRMFEncryptedKey *srcEncrKey, - CRMFEncryptedKey *destEncrKey); +extern SECStatus crmf_copy_pkiarchiveoptions(PLArenaPool *poolp, + CRMFPKIArchiveOptions *destOpt, + CRMFPKIArchiveOptions *srcOpt); extern SECStatus -crmf_copy_encryptedvalue(PLArenaPool *poolp, - CRMFEncryptedValue *srcValue, - CRMFEncryptedValue *destValue); +crmf_destroy_pkiarchiveoptions(CRMFPKIArchiveOptions *inArchOptions, + PRBool freeit); +extern const SEC_ASN1Template * +crmf_get_pkiarchiveoptions_subtemplate(CRMFControl *inControl); + +extern SECStatus crmf_copy_encryptedkey(PLArenaPool *poolp, + CRMFEncryptedKey *srcEncrKey, + CRMFEncryptedKey *destEncrKey); +extern SECStatus +crmf_copy_encryptedvalue(PLArenaPool *poolp, + CRMFEncryptedValue *srcValue, + CRMFEncryptedValue *destValue); extern SECStatus -crmf_copy_encryptedvalue_secalg(PLArenaPool *poolp, - SECAlgorithmID *srcAlgId, - SECAlgorithmID **destAlgId); +crmf_copy_encryptedvalue_secalg(PLArenaPool *poolp, + SECAlgorithmID *srcAlgId, + SECAlgorithmID **destAlgId); extern SECStatus crmf_template_copy_secalg(PLArenaPool *poolp, - SECAlgorithmID **dest, - SECAlgorithmID *src); + SECAlgorithmID **dest, + SECAlgorithmID *src); extern SECStatus crmf_copy_cert_name(PLArenaPool *poolp, CERTName **dest, - CERTName *src); + CERTName *src); -extern SECStatus crmf_template_add_public_key(PLArenaPool *poolp, - CERTSubjectPublicKeyInfo **dest, - CERTSubjectPublicKeyInfo *pubKey); +extern SECStatus crmf_template_add_public_key(PLArenaPool *poolp, + CERTSubjectPublicKeyInfo **dest, + CERTSubjectPublicKeyInfo *pubKey); -extern CRMFCertExtension* crmf_create_cert_extension(PLArenaPool *poolp, - SECOidTag tag, - PRBool isCritical, - SECItem *data); -extern CRMFCertRequest* +extern CRMFCertExtension *crmf_create_cert_extension(PLArenaPool *poolp, + SECOidTag tag, + PRBool isCritical, + SECItem *data); +extern CRMFCertRequest * crmf_copy_cert_request(PLArenaPool *poolp, CRMFCertRequest *srcReq); -extern SECStatus crmf_destroy_encrypted_value(CRMFEncryptedValue *inEncrValue, - PRBool freeit); +extern SECStatus crmf_destroy_encrypted_value(CRMFEncryptedValue *inEncrValue, + PRBool freeit); extern CRMFEncryptedValue * -crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, - SECKEYPublicKey *inPubKey, - CRMFEncryptedValue *destValue); +crmf_create_encrypted_value_wrapped_privkey(SECKEYPrivateKey *inPrivKey, + SECKEYPublicKey *inPubKey, + CRMFEncryptedValue *destValue); -extern CK_MECHANISM_TYPE - crmf_get_mechanism_from_public_key(SECKEYPublicKey *inPubKey); +extern CK_MECHANISM_TYPE +crmf_get_mechanism_from_public_key(SECKEYPublicKey *inPubKey); extern SECStatus -crmf_encrypted_value_unwrap_priv_key(PLArenaPool *poolp, - CRMFEncryptedValue *encValue, - SECKEYPrivateKey *privKey, - SECKEYPublicKey *newPubKey, - SECItem *nickname, - PK11SlotInfo *slot, - unsigned char keyUsage, - SECKEYPrivateKey **unWrappedKey, - void *wincx); +crmf_encrypted_value_unwrap_priv_key(PLArenaPool *poolp, + CRMFEncryptedValue *encValue, + SECKEYPrivateKey *privKey, + SECKEYPublicKey *newPubKey, + SECItem *nickname, + PK11SlotInfo *slot, + unsigned char keyUsage, + SECKEYPrivateKey **unWrappedKey, + void *wincx); -extern SECItem* +extern SECItem * crmf_get_public_value(SECKEYPublicKey *pubKey, SECItem *dest); -extern CRMFCertExtension* +extern CRMFCertExtension * crmf_copy_cert_extension(PLArenaPool *poolp, CRMFCertExtension *inExtension); extern SECStatus diff --git a/security/nss/lib/crmf/crmfit.h b/security/nss/lib/crmf/crmfit.h index a8defcd49dce..c5c4b96e9070 100644 --- a/security/nss/lib/crmf/crmfit.h +++ b/security/nss/lib/crmf/crmfit.h @@ -3,13 +3,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #ifndef _CRMFIT_H_ #define _CRMFIT_H_ struct CRMFCertReqMessagesStr { CRMFCertReqMsg **messages; - PLArenaPool *poolp; + PLArenaPool *poolp; }; struct CRMFCertExtensionStr { @@ -18,49 +17,48 @@ struct CRMFCertExtensionStr { SECItem value; }; - struct CRMFOptionalValidityStr { - SECItem notBefore; + SECItem notBefore; SECItem notAfter; }; struct CRMFCertTemplateStr { - SECItem version; - SECItem serialNumber; - SECAlgorithmID *signingAlg; - CERTName *issuer; - CRMFOptionalValidity *validity; - CERTName *subject; + SECItem version; + SECItem serialNumber; + SECAlgorithmID *signingAlg; + CERTName *issuer; + CRMFOptionalValidity *validity; + CERTName *subject; CERTSubjectPublicKeyInfo *publicKey; - SECItem issuerUID; - SECItem subjectUID; - CRMFCertExtension **extensions; - int numExtensions; + SECItem issuerUID; + SECItem subjectUID; + CRMFCertExtension **extensions; + int numExtensions; }; struct CRMFCertIDStr { - SECItem issuer; /* General Name */ + SECItem issuer; /* General Name */ SECItem serialNumber; /*INTEGER*/ }; struct CRMFEncryptedValueStr { SECAlgorithmID *intendedAlg; SECAlgorithmID *symmAlg; - SECItem encSymmKey; /*BIT STRING */ + SECItem encSymmKey; /*BIT STRING */ SECAlgorithmID *keyAlg; - SECItem valueHint; /*OCTET STRING */ - SECItem encValue; /*BIT STRING */ + SECItem valueHint; /*OCTET STRING */ + SECItem encValue; /*BIT STRING */ }; /* * The field derValue will contain the actual der * to include in the encoding or that was read in - * from a der blob. + * from a der blob. */ struct CRMFEncryptedKeyStr { union { - SEC_PKCS7ContentInfo *envelopedData; - CRMFEncryptedValue encryptedValue; + SEC_PKCS7ContentInfo *envelopedData; + CRMFEncryptedValue encryptedValue; } value; CRMFEncryptedKeyChoice encKeyChoice; SECItem derValue; @@ -69,9 +67,9 @@ struct CRMFEncryptedKeyStr { /* ASN1 must only have one of the following 3 options. */ struct CRMFPKIArchiveOptionsStr { union { - CRMFEncryptedKey encryptedKey; - SECItem keyGenParameters; - SECItem archiveRemGenPrivKey; /* BOOLEAN */ + CRMFEncryptedKey encryptedKey; + SECItem keyGenParameters; + SECItem archiveRemGenPrivKey; /* BOOLEAN */ } option; CRMFPKIArchiveOptionsType archOption; }; @@ -79,39 +77,39 @@ struct CRMFPKIArchiveOptionsStr { struct CRMFPKIPublicationInfoStr { SECItem action; /* Possible values */ /* dontPublish (0), pleasePublish (1) */ - CRMFSinglePubInfo **pubInfos; + CRMFSinglePubInfo **pubInfos; }; struct CRMFControlStr { - SECOidTag tag; - SECItem derTag; - SECItem derValue; - /* These will be C structures used to represent the various + SECOidTag tag; + SECItem derTag; + SECItem derValue; + /* These will be C structures used to represent the various * options. Values that can't be stored as der right away. * After creating these structures, we'll place their der * encoding in derValue so the encoder knows how to get to * it. */ union { - CRMFCertID oldCertId; - CRMFPKIArchiveOptions archiveOptions; - CRMFPKIPublicationInfo pubInfo; - CRMFProtocolEncrKey protEncrKey; + CRMFCertID oldCertId; + CRMFPKIArchiveOptions archiveOptions; + CRMFPKIPublicationInfo pubInfo; + CRMFProtocolEncrKey protEncrKey; } value; }; struct CRMFCertRequestStr { - SECItem certReqId; - CRMFCertTemplate certTemplate; - CRMFControl **controls; + SECItem certReqId; + CRMFCertTemplate certTemplate; + CRMFControl **controls; /* The following members are used by the internal implementation, but * are not part of the encoding. */ PLArenaPool *poolp; - PRUint32 requestID; /* This is the value that will be encoded into - * the certReqId field. - */ -}; + PRUint32 requestID; /* This is the value that will be encoded into + * the certReqId field. + */ +}; struct CRMFAttributeStr { SECItem derTag; @@ -119,41 +117,41 @@ struct CRMFAttributeStr { }; struct CRMFCertReqMsgStr { - CRMFCertRequest *certReq; - CRMFProofOfPossession *pop; - CRMFAttribute **regInfo; - SECItem derPOP; + CRMFCertRequest *certReq; + CRMFProofOfPossession *pop; + CRMFAttribute **regInfo; + SECItem derPOP; /* This arena will be used for allocating memory when decoding. */ PLArenaPool *poolp; - PRBool isDecoded; + PRBool isDecoded; }; struct CRMFPOPOSigningKeyInputStr { /* ASN1 must have only one of the next 2 options */ union { - SECItem sender; /*General Name*/ - CRMFPKMACValue *publicKeyMAC; - }authInfo; + SECItem sender; /*General Name*/ + CRMFPKMACValue *publicKeyMAC; + } authInfo; CERTSubjectPublicKeyInfo publicKey; }; struct CRMFPOPOSigningKeyStr { - SECItem derInput; /*If in the future we support - *POPOSigningKeyInput, this will - *a C structure representation - *instead. - */ - SECAlgorithmID *algorithmIdentifier; - SECItem signature; /* This is a BIT STRING. Remember */ -}; /* that when interpreting. */ + SECItem derInput; /*If in the future we support + *POPOSigningKeyInput, this will + *a C structure representation + *instead. + */ + SECAlgorithmID *algorithmIdentifier; + SECItem signature; /* This is a BIT STRING. Remember */ +}; /* that when interpreting. */ /* ASN1 must only choose one of these members */ struct CRMFPOPOPrivKeyStr { union { - SECItem thisMessage; /* BIT STRING */ - SECItem subsequentMessage; /*INTEGER*/ - SECItem dhMAC; /*BIT STRING*/ + SECItem thisMessage; /* BIT STRING */ + SECItem subsequentMessage; /*INTEGER*/ + SECItem dhMAC; /*BIT STRING*/ } message; CRMFPOPOPrivKeyChoice messageChoice; }; @@ -161,26 +159,26 @@ struct CRMFPOPOPrivKeyStr { /* ASN1 must only have one of these options. */ struct CRMFProofOfPossessionStr { union { - SECItem raVerified; - CRMFPOPOSigningKey signature; - CRMFPOPOPrivKey keyEncipherment; - CRMFPOPOPrivKey keyAgreement; + SECItem raVerified; + CRMFPOPOSigningKey signature; + CRMFPOPOPrivKey keyEncipherment; + CRMFPOPOPrivKey keyAgreement; } popChoice; - CRMFPOPChoice popUsed; /*Not part of encoding*/ + CRMFPOPChoice popUsed; /*Not part of encoding*/ }; struct CRMFPKMACValueStr { SECAlgorithmID algID; - SECItem value; /*BIT STRING*/ + SECItem value; /*BIT STRING*/ }; struct CRMFSinglePubInfoStr { - SECItem pubMethod; /* Possible Values: - * dontCare (0) - * x500 (1) - * web (2) - * ldap (3) - */ + SECItem pubMethod; /* Possible Values: + * dontCare (0) + * x500 (1) + * web (2) + * ldap (3) + */ CERTGeneralName *pubLocation; /* General Name */ }; diff --git a/security/nss/lib/crmf/crmfpop.c b/security/nss/lib/crmf/crmfpop.c index 2d4e32699f30..019875616e83 100644 --- a/security/nss/lib/crmf/crmfpop.c +++ b/security/nss/lib/crmf/crmfpop.c @@ -3,7 +3,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #include "crmf.h" #include "crmfi.h" #include "secasn1.h" @@ -13,8 +12,8 @@ #define CRMF_DEFAULT_ALLOC_SIZE 1024U SECStatus -crmf_init_encoder_callback_arg (struct crmfEncoderArg *encoderArg, - SECItem *derDest) +crmf_init_encoder_callback_arg(struct crmfEncoderArg *encoderArg, + SECItem *derDest) { derDest->data = PORT_ZNewArray(unsigned char, CRMF_DEFAULT_ALLOC_SIZE); if (derDest->data == NULL) { @@ -24,18 +23,17 @@ crmf_init_encoder_callback_arg (struct crmfEncoderArg *encoderArg, encoderArg->allocatedLen = CRMF_DEFAULT_ALLOC_SIZE; encoderArg->buffer = derDest; return SECSuccess; - } /* Caller should release or unmark the pool, instead of doing it here. ** But there are NO callers of this function at present... */ -SECStatus +SECStatus CRMF_CertReqMsgSetRAVerifiedPOP(CRMFCertReqMsg *inCertReqMsg) { CRMFProofOfPossession *pop; - PLArenaPool *poolp; - void *mark; + PLArenaPool *poolp; + void *mark; PORT_Assert(inCertReqMsg != NULL && inCertReqMsg->pop == NULL); poolp = inCertReqMsg->poolp; @@ -49,13 +47,13 @@ CRMF_CertReqMsgSetRAVerifiedPOP(CRMFCertReqMsg *inCertReqMsg) } pop->popUsed = crmfRAVerified; pop->popChoice.raVerified.data = NULL; - pop->popChoice.raVerified.len = 0; + pop->popChoice.raVerified.len = 0; inCertReqMsg->pop = pop; (void)SEC_ASN1EncodeItem(poolp, &(inCertReqMsg->derPOP), &(pop->popChoice.raVerified), CRMFRAVerifiedTemplate); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); return SECFailure; } @@ -71,14 +69,14 @@ crmf_get_key_sign_tag(SECKEYPublicKey *inPubKey) return SEC_GetSignatureAlgorithmOidTag(inPubKey->keyType, SEC_OID_UNKNOWN); } -static SECAlgorithmID* -crmf_create_poposignkey_algid(PLArenaPool *poolp, - SECKEYPublicKey *inPubKey) +static SECAlgorithmID * +crmf_create_poposignkey_algid(PLArenaPool *poolp, + SECKEYPublicKey *inPubKey) { SECAlgorithmID *algID; - SECOidTag tag; - SECStatus rv; - void *mark; + SECOidTag tag; + SECStatus rv; + void *mark; mark = PORT_ArenaMark(poolp); algID = PORT_ArenaZNew(poolp, SECAlgorithmID); @@ -95,83 +93,83 @@ crmf_create_poposignkey_algid(PLArenaPool *poolp, } PORT_ArenaUnmark(poolp, mark); return algID; - loser: +loser: PORT_ArenaRelease(poolp, mark); return NULL; } -static CRMFPOPOSigningKeyInput* +static CRMFPOPOSigningKeyInput * crmf_create_poposigningkeyinput(PLArenaPool *poolp, CERTCertificate *inCert, - CRMFMACPasswordCallback fn, void *arg) + CRMFMACPasswordCallback fn, void *arg) { - /* PSM isn't going to do this, so we'll fail here for now.*/ - return NULL; + /* PSM isn't going to do this, so we'll fail here for now.*/ + return NULL; } void -crmf_generic_encoder_callback(void *arg, const char* buf, unsigned long len, - int depth, SEC_ASN1EncodingPart data_kind) +crmf_generic_encoder_callback(void *arg, const char *buf, unsigned long len, + int depth, SEC_ASN1EncodingPart data_kind) { - struct crmfEncoderArg *encoderArg = (struct crmfEncoderArg*)arg; + struct crmfEncoderArg *encoderArg = (struct crmfEncoderArg *)arg; unsigned char *cursor; - - if (encoderArg->buffer->len + len > encoderArg->allocatedLen) { - int newSize = encoderArg->buffer->len+CRMF_DEFAULT_ALLOC_SIZE; + + if (encoderArg->buffer->len + len > encoderArg->allocatedLen) { + int newSize = encoderArg->buffer->len + CRMF_DEFAULT_ALLOC_SIZE; void *dummy = PORT_Realloc(encoderArg->buffer->data, newSize); - if (dummy == NULL) { - /* I really want to return an error code here */ - PORT_Assert(0); - return; - } - encoderArg->buffer->data = dummy; - encoderArg->allocatedLen = newSize; + if (dummy == NULL) { + /* I really want to return an error code here */ + PORT_Assert(0); + return; + } + encoderArg->buffer->data = dummy; + encoderArg->allocatedLen = newSize; } cursor = &(encoderArg->buffer->data[encoderArg->buffer->len]); - PORT_Memcpy (cursor, buf, len); - encoderArg->buffer->len += len; + PORT_Memcpy(cursor, buf, len); + encoderArg->buffer->len += len; } static SECStatus crmf_encode_certreq(CRMFCertRequest *inCertReq, SECItem *derDest) { struct crmfEncoderArg encoderArg; - SECStatus rv; - - rv = crmf_init_encoder_callback_arg (&encoderArg, derDest); + SECStatus rv; + + rv = crmf_init_encoder_callback_arg(&encoderArg, derDest); if (rv != SECSuccess) { return SECFailure; } - return SEC_ASN1Encode(inCertReq, CRMFCertRequestTemplate, - crmf_generic_encoder_callback, &encoderArg); + return SEC_ASN1Encode(inCertReq, CRMFCertRequestTemplate, + crmf_generic_encoder_callback, &encoderArg); } static SECStatus -crmf_sign_certreq(PLArenaPool *poolp, - CRMFPOPOSigningKey *crmfSignKey, - CRMFCertRequest *certReq, - SECKEYPrivateKey *inKey, - SECAlgorithmID *inAlgId) +crmf_sign_certreq(PLArenaPool *poolp, + CRMFPOPOSigningKey *crmfSignKey, + CRMFCertRequest *certReq, + SECKEYPrivateKey *inKey, + SECAlgorithmID *inAlgId) { - SECItem derCertReq = { siBuffer, NULL, 0 }; - SECItem certReqSig = { siBuffer, NULL, 0 }; - SECStatus rv = SECSuccess; + SECItem derCertReq = { siBuffer, NULL, 0 }; + SECItem certReqSig = { siBuffer, NULL, 0 }; + SECStatus rv = SECSuccess; rv = crmf_encode_certreq(certReq, &derCertReq); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SEC_SignData(&certReqSig, derCertReq.data, derCertReq.len, - inKey,SECOID_GetAlgorithmTag(inAlgId)); + inKey, SECOID_GetAlgorithmTag(inAlgId)); if (rv != SECSuccess) { goto loser; } - + /* Now make it a part of the POPOSigningKey */ rv = SECITEM_CopyItem(poolp, &(crmfSignKey->signature), &certReqSig); /* Convert this length to number of bits */ - crmfSignKey->signature.len <<= 3; - - loser: + crmfSignKey->signature.len <<= 3; + +loser: if (derCertReq.data != NULL) { PORT_Free(derCertReq.data); } @@ -182,87 +180,88 @@ crmf_sign_certreq(PLArenaPool *poolp, } static SECStatus -crmf_create_poposignkey(PLArenaPool *poolp, - CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOSigningKeyInput *signKeyInput, - SECKEYPrivateKey *inPrivKey, - SECAlgorithmID *inAlgID, - CRMFPOPOSigningKey *signKey) +crmf_create_poposignkey(PLArenaPool *poolp, + CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOSigningKeyInput *signKeyInput, + SECKEYPrivateKey *inPrivKey, + SECAlgorithmID *inAlgID, + CRMFPOPOSigningKey *signKey) { - CRMFCertRequest *certReq; - void *mark; - PRBool useSignKeyInput; - SECStatus rv; - + CRMFCertRequest *certReq; + void *mark; + PRBool useSignKeyInput; + SECStatus rv; + PORT_Assert(inCertReqMsg != NULL && inCertReqMsg->certReq != NULL); mark = PORT_ArenaMark(poolp); if (signKey == NULL) { goto loser; } certReq = inCertReqMsg->certReq; - useSignKeyInput = !(CRMF_DoesRequestHaveField(certReq,crmfSubject) && - CRMF_DoesRequestHaveField(certReq,crmfPublicKey)); + useSignKeyInput = !(CRMF_DoesRequestHaveField(certReq, crmfSubject) && + CRMF_DoesRequestHaveField(certReq, crmfPublicKey)); if (useSignKeyInput) { - goto loser; - } else { - rv = crmf_sign_certreq(poolp, signKey, certReq,inPrivKey, inAlgID); - if (rv != SECSuccess) { - goto loser; - } + goto loser; } - PORT_ArenaUnmark(poolp,mark); + else { + rv = crmf_sign_certreq(poolp, signKey, certReq, inPrivKey, inAlgID); + if (rv != SECSuccess) { + goto loser; + } + } + PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: - PORT_ArenaRelease(poolp,mark); +loser: + PORT_ArenaRelease(poolp, mark); return SECFailure; } SECStatus -CRMF_CertReqMsgSetSignaturePOP(CRMFCertReqMsg *inCertReqMsg, - SECKEYPrivateKey *inPrivKey, - SECKEYPublicKey *inPubKey, - CERTCertificate *inCertForInput, - CRMFMACPasswordCallback fn, - void *arg) +CRMF_CertReqMsgSetSignaturePOP(CRMFCertReqMsg *inCertReqMsg, + SECKEYPrivateKey *inPrivKey, + SECKEYPublicKey *inPubKey, + CERTCertificate *inCertForInput, + CRMFMACPasswordCallback fn, + void *arg) { - SECAlgorithmID *algID; - PLArenaPool *poolp; - SECItem derTemp = {siBuffer, NULL, 0}; - void *mark; - SECStatus rv; + SECAlgorithmID *algID; + PLArenaPool *poolp; + SECItem derTemp = { siBuffer, NULL, 0 }; + void *mark; + SECStatus rv; CRMFPOPOSigningKeyInput *signKeyInput = NULL; - CRMFCertRequest *certReq; - CRMFProofOfPossession *pop; - struct crmfEncoderArg encoderArg; + CRMFCertRequest *certReq; + CRMFProofOfPossession *pop; + struct crmfEncoderArg encoderArg; PORT_Assert(inCertReqMsg != NULL && inCertReqMsg->certReq != NULL && - inCertReqMsg->pop == NULL); + inCertReqMsg->pop == NULL); certReq = inCertReqMsg->certReq; - if (CRMF_CertReqMsgGetPOPType(inCertReqMsg) != crmfNoPOPChoice || - !CRMF_DoesRequestHaveField(certReq, crmfPublicKey)) { + if (CRMF_CertReqMsgGetPOPType(inCertReqMsg) != crmfNoPOPChoice || + !CRMF_DoesRequestHaveField(certReq, crmfPublicKey)) { return SECFailure; - } + } poolp = inCertReqMsg->poolp; mark = PORT_ArenaMark(poolp); algID = crmf_create_poposignkey_algid(poolp, inPubKey); - if(!CRMF_DoesRequestHaveField(certReq,crmfSubject)) { + if (!CRMF_DoesRequestHaveField(certReq, crmfSubject)) { signKeyInput = crmf_create_poposigningkeyinput(poolp, inCertForInput, - fn, arg); - if (signKeyInput == NULL) { - goto loser; - } + fn, arg); + if (signKeyInput == NULL) { + goto loser; + } } pop = PORT_ArenaZNew(poolp, CRMFProofOfPossession); if (pop == NULL) { goto loser; } - - rv = crmf_create_poposignkey(poolp, inCertReqMsg, - signKeyInput, inPrivKey, algID, - &(pop->popChoice.signature)); + + rv = crmf_create_poposignkey(poolp, inCertReqMsg, + signKeyInput, inPrivKey, algID, + &(pop->popChoice.signature)); if (rv != SECSuccess) { goto loser; } @@ -270,14 +269,14 @@ CRMF_CertReqMsgSetSignaturePOP(CRMFCertReqMsg *inCertReqMsg, pop->popUsed = crmfSignature; pop->popChoice.signature.algorithmIdentifier = algID; inCertReqMsg->pop = pop; - - rv = crmf_init_encoder_callback_arg (&encoderArg, &derTemp); + + rv = crmf_init_encoder_callback_arg(&encoderArg, &derTemp); if (rv != SECSuccess) { goto loser; } - rv = SEC_ASN1Encode(&pop->popChoice.signature, - CRMFPOPOSigningKeyTemplate, - crmf_generic_encoder_callback, &encoderArg); + rv = SEC_ASN1Encode(&pop->popChoice.signature, + CRMFPOPOSigningKeyTemplate, + crmf_generic_encoder_callback, &encoderArg); if (rv != SECSuccess) { goto loser; } @@ -285,49 +284,49 @@ CRMF_CertReqMsgSetSignaturePOP(CRMFCertReqMsg *inCertReqMsg, if (rv != SECSuccess) { goto loser; } - PORT_Free (derTemp.data); - PORT_ArenaUnmark(poolp,mark); + PORT_Free(derTemp.data); + PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: - PORT_ArenaRelease(poolp,mark); +loser: + PORT_ArenaRelease(poolp, mark); if (derTemp.data != NULL) { PORT_Free(derTemp.data); } return SECFailure; } -static const SEC_ASN1Template* -crmf_get_popoprivkey_subtemplate(CRMFPOPOPrivKey *inPrivKey) +static const SEC_ASN1Template * +crmf_get_popoprivkey_subtemplate(CRMFPOPOPrivKey *inPrivKey) { const SEC_ASN1Template *retTemplate = NULL; switch (inPrivKey->messageChoice) { - case crmfThisMessage: - retTemplate = CRMFThisMessageTemplate; - break; - case crmfSubsequentMessage: - retTemplate = CRMFSubsequentMessageTemplate; - break; - case crmfDHMAC: - retTemplate = CRMFDHMACTemplate; - break; - default: - retTemplate = NULL; + case crmfThisMessage: + retTemplate = CRMFThisMessageTemplate; + break; + case crmfSubsequentMessage: + retTemplate = CRMFSubsequentMessageTemplate; + break; + case crmfDHMAC: + retTemplate = CRMFDHMACTemplate; + break; + default: + retTemplate = NULL; } return retTemplate; } static SECStatus -crmf_encode_popoprivkey(PLArenaPool *poolp, - CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKey *popoPrivKey, - const SEC_ASN1Template *privKeyTemplate) +crmf_encode_popoprivkey(PLArenaPool *poolp, + CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKey *popoPrivKey, + const SEC_ASN1Template *privKeyTemplate) { - struct crmfEncoderArg encoderArg; - SECItem derTemp = { siBuffer, NULL, 0 }; - SECStatus rv; - void *mark; + struct crmfEncoderArg encoderArg; + SECItem derTemp = { siBuffer, NULL, 0 }; + SECStatus rv; + void *mark; const SEC_ASN1Template *subDerTemplate; mark = PORT_ArenaMark(poolp); @@ -336,21 +335,21 @@ crmf_encode_popoprivkey(PLArenaPool *poolp, goto loser; } subDerTemplate = crmf_get_popoprivkey_subtemplate(popoPrivKey); - /* We've got a union, so a pointer to one item is a pointer to + /* We've got a union, so a pointer to one item is a pointer to * all the items in the union. */ - rv = SEC_ASN1Encode(&popoPrivKey->message.thisMessage, - subDerTemplate, - crmf_generic_encoder_callback, &encoderArg); + rv = SEC_ASN1Encode(&popoPrivKey->message.thisMessage, + subDerTemplate, + crmf_generic_encoder_callback, &encoderArg); if (rv != SECSuccess) { goto loser; } - if (encoderArg.allocatedLen > derTemp.len+2) { - void *dummy = PORT_Realloc(derTemp.data, derTemp.len+2); - if (dummy == NULL) { - goto loser; - } - derTemp.data = dummy; + if (encoderArg.allocatedLen > derTemp.len + 2) { + void *dummy = PORT_Realloc(derTemp.data, derTemp.len + 2); + if (dummy == NULL) { + goto loser; + } + derTemp.data = dummy; } PORT_Memmove(&derTemp.data[2], &derTemp.data[0], derTemp.len); /* I couldn't figure out how to get the ASN1 encoder to implicitly @@ -367,7 +366,7 @@ crmf_encode_popoprivkey(PLArenaPool *poolp, PORT_Free(derTemp.data); PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); if (derTemp.data) { PORT_Free(derTemp.data); @@ -375,29 +374,29 @@ crmf_encode_popoprivkey(PLArenaPool *poolp, return SECFailure; } -static const SEC_ASN1Template* -crmf_get_template_for_privkey(CRMFPOPChoice inChoice) +static const SEC_ASN1Template * +crmf_get_template_for_privkey(CRMFPOPChoice inChoice) { switch (inChoice) { - case crmfKeyAgreement: - return CRMFPOPOKeyAgreementTemplate; - case crmfKeyEncipherment: - return CRMFPOPOKeyEnciphermentTemplate; - default: - break; + case crmfKeyAgreement: + return CRMFPOPOKeyAgreementTemplate; + case crmfKeyEncipherment: + return CRMFPOPOKeyEnciphermentTemplate; + default: + break; } return NULL; } static SECStatus crmf_add_privkey_thismessage(CRMFCertReqMsg *inCertReqMsg, SECItem *encPrivKey, - CRMFPOPChoice inChoice) + CRMFPOPChoice inChoice) { - PLArenaPool *poolp; - void *mark; - CRMFPOPOPrivKey *popoPrivKey; + PLArenaPool *poolp; + void *mark; + CRMFPOPOPrivKey *popoPrivKey; CRMFProofOfPossession *pop; - SECStatus rv; + SECStatus rv; PORT_Assert(inCertReqMsg != NULL && encPrivKey != NULL); poolp = inCertReqMsg->poolp; @@ -409,14 +408,14 @@ crmf_add_privkey_thismessage(CRMFCertReqMsg *inCertReqMsg, SECItem *encPrivKey, pop->popUsed = inChoice; /* popChoice is a union, so getting a pointer to one * field gives me a pointer to the other fields as - * well. This in essence points to both + * well. This in essence points to both * pop->popChoice.keyEncipherment and * pop->popChoice.keyAgreement */ popoPrivKey = &pop->popChoice.keyEncipherment; rv = SECITEM_CopyItem(poolp, &(popoPrivKey->message.thisMessage), - encPrivKey); + encPrivKey); if (rv != SECSuccess) { goto loser; } @@ -424,27 +423,27 @@ crmf_add_privkey_thismessage(CRMFCertReqMsg *inCertReqMsg, SECItem *encPrivKey, popoPrivKey->messageChoice = crmfThisMessage; inCertReqMsg->pop = pop; rv = crmf_encode_popoprivkey(poolp, inCertReqMsg, popoPrivKey, - crmf_get_template_for_privkey(inChoice)); + crmf_get_template_for_privkey(inChoice)); if (rv != SECSuccess) { goto loser; } PORT_ArenaUnmark(poolp, mark); return SECSuccess; - - loser: + +loser: PORT_ArenaRelease(poolp, mark); return SECFailure; } static SECStatus crmf_add_privkey_dhmac(CRMFCertReqMsg *inCertReqMsg, SECItem *dhmac, - CRMFPOPChoice inChoice) + CRMFPOPChoice inChoice) { - PLArenaPool *poolp; - void *mark; - CRMFPOPOPrivKey *popoPrivKey; + PLArenaPool *poolp; + void *mark; + CRMFPOPOPrivKey *popoPrivKey; CRMFProofOfPossession *pop; - SECStatus rv; + SECStatus rv; PORT_Assert(inCertReqMsg != NULL && dhmac != NULL); poolp = inCertReqMsg->poolp; @@ -471,22 +470,22 @@ crmf_add_privkey_dhmac(CRMFCertReqMsg *inCertReqMsg, SECItem *dhmac, } PORT_ArenaUnmark(poolp, mark); return SECSuccess; - - loser: + +loser: PORT_ArenaRelease(poolp, mark); return SECFailure; } static SECStatus -crmf_add_privkey_subseqmessage(CRMFCertReqMsg *inCertReqMsg, - CRMFSubseqMessOptions subsequentMessage, - CRMFPOPChoice inChoice) +crmf_add_privkey_subseqmessage(CRMFCertReqMsg *inCertReqMsg, + CRMFSubseqMessOptions subsequentMessage, + CRMFPOPChoice inChoice) { - void *mark; - PLArenaPool *poolp; + void *mark; + PLArenaPool *poolp; CRMFProofOfPossession *pop; - CRMFPOPOPrivKey *popoPrivKey; - SECStatus rv; + CRMFPOPOPrivKey *popoPrivKey; + SECStatus rv; const SEC_ASN1Template *privKeyTemplate; if (subsequentMessage == crmfNoSubseqMess) { @@ -500,25 +499,25 @@ crmf_add_privkey_subseqmessage(CRMFCertReqMsg *inCertReqMsg, } pop->popUsed = inChoice; - /* + /* * We have a union, so a pointer to one member of the union * is also a member to another member of that same union. */ popoPrivKey = &pop->popChoice.keyEncipherment; switch (subsequentMessage) { - case crmfEncrCert: - rv = crmf_encode_integer(poolp, - &(popoPrivKey->message.subsequentMessage), - 0); - break; - case crmfChallengeResp: - rv = crmf_encode_integer(poolp, - &(popoPrivKey->message.subsequentMessage), - 1); - break; - default: - goto loser; + case crmfEncrCert: + rv = crmf_encode_integer(poolp, + &(popoPrivKey->message.subsequentMessage), + 0); + break; + case crmfChallengeResp: + rv = crmf_encode_integer(poolp, + &(popoPrivKey->message.subsequentMessage), + 1); + break; + default: + goto loser; } if (rv != SECSuccess) { goto loser; @@ -527,23 +526,23 @@ crmf_add_privkey_subseqmessage(CRMFCertReqMsg *inCertReqMsg, privKeyTemplate = crmf_get_template_for_privkey(inChoice); inCertReqMsg->pop = pop; rv = crmf_encode_popoprivkey(poolp, inCertReqMsg, popoPrivKey, - privKeyTemplate); + privKeyTemplate); if (rv != SECSuccess) { goto loser; } PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); return SECFailure; } -SECStatus -CRMF_CertReqMsgSetKeyEnciphermentPOP(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKeyChoice inKeyChoice, - CRMFSubseqMessOptions subseqMess, - SECItem *encPrivKey) +SECStatus +CRMF_CertReqMsgSetKeyEnciphermentPOP(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKeyChoice inKeyChoice, + CRMFSubseqMessOptions subseqMess, + SECItem *encPrivKey) { SECStatus rv; @@ -551,49 +550,48 @@ CRMF_CertReqMsgSetKeyEnciphermentPOP(CRMFCertReqMsg *inCertReqMsg, if (CRMF_CertReqMsgGetPOPType(inCertReqMsg) != crmfNoPOPChoice) { return SECFailure; } - switch (inKeyChoice) { - case crmfThisMessage: - rv = crmf_add_privkey_thismessage(inCertReqMsg, encPrivKey, - crmfKeyEncipherment); - break; - case crmfSubsequentMessage: - rv = crmf_add_privkey_subseqmessage(inCertReqMsg, subseqMess, - crmfKeyEncipherment); - break; - case crmfDHMAC: - default: - rv = SECFailure; + switch (inKeyChoice) { + case crmfThisMessage: + rv = crmf_add_privkey_thismessage(inCertReqMsg, encPrivKey, + crmfKeyEncipherment); + break; + case crmfSubsequentMessage: + rv = crmf_add_privkey_subseqmessage(inCertReqMsg, subseqMess, + crmfKeyEncipherment); + break; + case crmfDHMAC: + default: + rv = SECFailure; } return rv; } -SECStatus -CRMF_CertReqMsgSetKeyAgreementPOP (CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKeyChoice inKeyChoice, - CRMFSubseqMessOptions subseqMess, - SECItem *encPrivKey) +SECStatus +CRMF_CertReqMsgSetKeyAgreementPOP(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKeyChoice inKeyChoice, + CRMFSubseqMessOptions subseqMess, + SECItem *encPrivKey) { SECStatus rv; PORT_Assert(inCertReqMsg != NULL && inCertReqMsg->pop == NULL); - switch (inKeyChoice) { - case crmfThisMessage: - rv = crmf_add_privkey_thismessage(inCertReqMsg, encPrivKey, - crmfKeyAgreement); - break; - case crmfSubsequentMessage: - rv = crmf_add_privkey_subseqmessage(inCertReqMsg, subseqMess, - crmfKeyAgreement); - break; - case crmfDHMAC: - /* In this case encPrivKey should be the calculated dhMac - * as specified in RFC 2511 */ - rv = crmf_add_privkey_dhmac(inCertReqMsg, encPrivKey, - crmfKeyAgreement); - break; - default: - rv = SECFailure; + switch (inKeyChoice) { + case crmfThisMessage: + rv = crmf_add_privkey_thismessage(inCertReqMsg, encPrivKey, + crmfKeyAgreement); + break; + case crmfSubsequentMessage: + rv = crmf_add_privkey_subseqmessage(inCertReqMsg, subseqMess, + crmfKeyAgreement); + break; + case crmfDHMAC: + /* In this case encPrivKey should be the calculated dhMac + * as specified in RFC 2511 */ + rv = crmf_add_privkey_dhmac(inCertReqMsg, encPrivKey, + crmfKeyAgreement); + break; + default: + rv = SECFailure; } return rv; } - diff --git a/security/nss/lib/crmf/crmfreq.c b/security/nss/lib/crmf/crmfreq.c index 7da81cdbf4aa..7dbf94c7c193 100644 --- a/security/nss/lib/crmf/crmfreq.c +++ b/security/nss/lib/crmf/crmfreq.c @@ -14,17 +14,16 @@ */ #define IS_NOT_NULL(ptr) ((ptr) == NULL) ? PR_FALSE : PR_TRUE -const unsigned char hexTrue = 0xff; +const unsigned char hexTrue = 0xff; const unsigned char hexFalse = 0x00; - SECStatus crmf_encode_integer(PLArenaPool *poolp, SECItem *dest, long value) { SECItem *dummy; dummy = SEC_ASN1EncodeInteger(poolp, dest, value); - PORT_Assert (dummy == dest); + PORT_Assert(dummy == dest); if (dummy == NULL) { return SECFailure; } @@ -33,12 +32,12 @@ crmf_encode_integer(PLArenaPool *poolp, SECItem *dest, long value) SECStatus crmf_encode_unsigned_integer(PLArenaPool *poolp, SECItem *dest, - unsigned long value) + unsigned long value) { SECItem *dummy; dummy = SEC_ASN1EncodeUnsignedInteger(poolp, dest, value); - PORT_Assert (dummy == dest); + PORT_Assert(dummy == dest); if (dummy != dest) { return SECFailure; } @@ -46,73 +45,73 @@ crmf_encode_unsigned_integer(PLArenaPool *poolp, SECItem *dest, } static SECStatus -crmf_copy_secitem (PLArenaPool *poolp, SECItem *dest, SECItem *src) +crmf_copy_secitem(PLArenaPool *poolp, SECItem *dest, SECItem *src) { - return SECITEM_CopyItem (poolp, dest, src); + return SECITEM_CopyItem(poolp, dest, src); } PRBool -CRMF_DoesRequestHaveField (CRMFCertRequest *inCertReq, - CRMFCertTemplateField inField) +CRMF_DoesRequestHaveField(CRMFCertRequest *inCertReq, + CRMFCertTemplateField inField) { - + PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return PR_FALSE; } switch (inField) { - case crmfVersion: - return inCertReq->certTemplate.version.data != NULL; - case crmfSerialNumber: - return inCertReq->certTemplate.serialNumber.data != NULL; - case crmfSigningAlg: - return inCertReq->certTemplate.signingAlg != NULL; - case crmfIssuer: - return inCertReq->certTemplate.issuer != NULL; - case crmfValidity: - return inCertReq->certTemplate.validity != NULL; - case crmfSubject: - return inCertReq->certTemplate.subject != NULL; - case crmfPublicKey: - return inCertReq->certTemplate.publicKey != NULL; - case crmfIssuerUID: - return inCertReq->certTemplate.issuerUID.data != NULL; - case crmfSubjectUID: - return inCertReq->certTemplate.subjectUID.data != NULL; - case crmfExtension: - return CRMF_CertRequestGetNumberOfExtensions(inCertReq) != 0; + case crmfVersion: + return inCertReq->certTemplate.version.data != NULL; + case crmfSerialNumber: + return inCertReq->certTemplate.serialNumber.data != NULL; + case crmfSigningAlg: + return inCertReq->certTemplate.signingAlg != NULL; + case crmfIssuer: + return inCertReq->certTemplate.issuer != NULL; + case crmfValidity: + return inCertReq->certTemplate.validity != NULL; + case crmfSubject: + return inCertReq->certTemplate.subject != NULL; + case crmfPublicKey: + return inCertReq->certTemplate.publicKey != NULL; + case crmfIssuerUID: + return inCertReq->certTemplate.issuerUID.data != NULL; + case crmfSubjectUID: + return inCertReq->certTemplate.subjectUID.data != NULL; + case crmfExtension: + return CRMF_CertRequestGetNumberOfExtensions(inCertReq) != 0; } return PR_FALSE; } CRMFCertRequest * -CRMF_CreateCertRequest (PRUint32 inRequestID) +CRMF_CreateCertRequest(PRUint32 inRequestID) { - PLArenaPool *poolp; + PLArenaPool *poolp; CRMFCertRequest *certReq; - SECStatus rv; - + SECStatus rv; + poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { goto loser; } - - certReq=PORT_ArenaZNew(poolp,CRMFCertRequest); + + certReq = PORT_ArenaZNew(poolp, CRMFCertRequest); if (certReq == NULL) { goto loser; } certReq->poolp = poolp; certReq->requestID = inRequestID; - - rv = crmf_encode_unsigned_integer(poolp, &(certReq->certReqId), + + rv = crmf_encode_unsigned_integer(poolp, &(certReq->certReqId), inRequestID); if (rv != SECSuccess) { goto loser; } return certReq; - loser: +loser: if (poolp) { PORT_FreeArena(poolp, PR_FALSE); } @@ -125,18 +124,18 @@ CRMF_DestroyCertRequest(CRMFCertRequest *inCertReq) PORT_Assert(inCertReq != NULL); if (inCertReq != NULL) { if (inCertReq->certTemplate.extensions) { - PORT_Free(inCertReq->certTemplate.extensions); - } - if (inCertReq->controls) { - /* Right now we don't support EnveloppedData option, - * so we won't go through and delete each occurrence of - * an EnveloppedData in the control. - */ - PORT_Free(inCertReq->controls); - } - if (inCertReq->poolp) { - PORT_FreeArena(inCertReq->poolp, PR_TRUE); - } + PORT_Free(inCertReq->certTemplate.extensions); + } + if (inCertReq->controls) { + /* Right now we don't support EnveloppedData option, + * so we won't go through and delete each occurrence of + * an EnveloppedData in the control. + */ + PORT_Free(inCertReq->controls); + } + if (inCertReq->poolp) { + PORT_FreeArena(inCertReq->poolp, PR_TRUE); + } } return SECSuccess; } @@ -154,12 +153,12 @@ crmf_template_add_serialnumber(PLArenaPool *poolp, SECItem *dest, long serial) } SECStatus -crmf_template_copy_secalg (PLArenaPool *poolp, SECAlgorithmID **dest, - SECAlgorithmID* src) +crmf_template_copy_secalg(PLArenaPool *poolp, SECAlgorithmID **dest, + SECAlgorithmID *src) { - SECStatus rv; - void *mark = NULL; - SECAlgorithmID *mySecAlg; + SECStatus rv; + void *mark = NULL; + SECAlgorithmID *mySecAlg; if (!poolp) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -180,7 +179,7 @@ crmf_template_copy_secalg (PLArenaPool *poolp, SECAlgorithmID **dest, } return SECSuccess; - loser: +loser: *dest = NULL; if (mark) { PORT_ArenaRelease(poolp, mark); @@ -190,11 +189,11 @@ crmf_template_copy_secalg (PLArenaPool *poolp, SECAlgorithmID **dest, SECStatus crmf_copy_cert_name(PLArenaPool *poolp, CERTName **dest, - CERTName *src) + CERTName *src) { CERTName *newName; SECStatus rv; - void *mark; + void *mark; mark = PORT_ArenaMark(poolp); *dest = newName = PORT_ArenaZNew(poolp, CERTName); @@ -204,91 +203,89 @@ crmf_copy_cert_name(PLArenaPool *poolp, CERTName **dest, rv = CERT_CopyName(poolp, newName, src); if (rv != SECSuccess) { - goto loser; + goto loser; } PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); *dest = NULL; return SECFailure; } static SECStatus -crmf_template_add_issuer (PLArenaPool *poolp, CERTName **dest, - CERTName* issuerName) +crmf_template_add_issuer(PLArenaPool *poolp, CERTName **dest, + CERTName *issuerName) { return crmf_copy_cert_name(poolp, dest, issuerName); } - static SECStatus -crmf_template_add_validity (PLArenaPool *poolp, CRMFOptionalValidity **dest, - CRMFValidityCreationInfo *info) +crmf_template_add_validity(PLArenaPool *poolp, CRMFOptionalValidity **dest, + CRMFValidityCreationInfo *info) { - SECStatus rv; - void *mark; + SECStatus rv; + void *mark; CRMFOptionalValidity *myValidity; /*First off, let's make sure at least one of the two fields is present*/ - if (!info || (!info->notBefore && !info->notAfter)) { + if (!info || (!info->notBefore && !info->notAfter)) { return SECFailure; } - mark = PORT_ArenaMark (poolp); + mark = PORT_ArenaMark(poolp); *dest = myValidity = PORT_ArenaZNew(poolp, CRMFOptionalValidity); if (myValidity == NULL) { goto loser; } if (info->notBefore) { - rv = DER_EncodeTimeChoice (poolp, &myValidity->notBefore, - *info->notBefore); - if (rv != SECSuccess) { - goto loser; - } + rv = DER_EncodeTimeChoice(poolp, &myValidity->notBefore, + *info->notBefore); + if (rv != SECSuccess) { + goto loser; + } } if (info->notAfter) { - rv = DER_EncodeTimeChoice (poolp, &myValidity->notAfter, - *info->notAfter); - if (rv != SECSuccess) { - goto loser; - } + rv = DER_EncodeTimeChoice(poolp, &myValidity->notAfter, + *info->notAfter); + if (rv != SECSuccess) { + goto loser; + } } PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser: +loser: PORT_ArenaRelease(poolp, mark); *dest = NULL; return SECFailure; } static SECStatus -crmf_template_add_subject (PLArenaPool *poolp, CERTName **dest, - CERTName *subject) +crmf_template_add_subject(PLArenaPool *poolp, CERTName **dest, + CERTName *subject) { return crmf_copy_cert_name(poolp, dest, subject); } SECStatus crmf_template_add_public_key(PLArenaPool *poolp, - CERTSubjectPublicKeyInfo **dest, - CERTSubjectPublicKeyInfo *pubKey) + CERTSubjectPublicKeyInfo **dest, + CERTSubjectPublicKeyInfo *pubKey) { CERTSubjectPublicKeyInfo *spki; SECStatus rv; - *dest = spki = (poolp == NULL) ? - PORT_ZNew(CERTSubjectPublicKeyInfo) : - PORT_ArenaZNew (poolp, CERTSubjectPublicKeyInfo); + *dest = spki = (poolp == NULL) ? PORT_ZNew(CERTSubjectPublicKeyInfo) : + PORT_ArenaZNew(poolp, CERTSubjectPublicKeyInfo); if (spki == NULL) { goto loser; } - rv = SECKEY_CopySubjectPublicKeyInfo (poolp, spki, pubKey); + rv = SECKEY_CopySubjectPublicKeyInfo(poolp, spki, pubKey); if (rv != SECSuccess) { goto loser; } return SECSuccess; - loser: +loser: if (poolp == NULL && spki != NULL) { SECKEY_DestroySubjectPublicKeyInfo(spki); } @@ -297,11 +294,11 @@ crmf_template_add_public_key(PLArenaPool *poolp, } static SECStatus -crmf_copy_bitstring (PLArenaPool *poolp, SECItem *dest, const SECItem *src) +crmf_copy_bitstring(PLArenaPool *poolp, SECItem *dest, const SECItem *src) { SECStatus rv; - SECItem byteSrc; - + SECItem byteSrc; + byteSrc = *src; byteSrc.len = CRMF_BITS_TO_BYTES(byteSrc.len); rv = crmf_copy_secitem(poolp, dest, &byteSrc); @@ -311,23 +308,23 @@ crmf_copy_bitstring (PLArenaPool *poolp, SECItem *dest, const SECItem *src) static SECStatus crmf_template_add_issuer_uid(PLArenaPool *poolp, SECItem *dest, - const SECItem *issuerUID) + const SECItem *issuerUID) { - return crmf_copy_bitstring (poolp, dest, issuerUID); + return crmf_copy_bitstring(poolp, dest, issuerUID); } static SECStatus crmf_template_add_subject_uid(PLArenaPool *poolp, SECItem *dest, - const SECItem *subjectUID) + const SECItem *subjectUID) { - return crmf_copy_bitstring (poolp, dest, subjectUID); + return crmf_copy_bitstring(poolp, dest, subjectUID); } static void -crmf_zeroize_new_extensions (CRMFCertExtension **extensions, - int numToZeroize) +crmf_zeroize_new_extensions(CRMFCertExtension **extensions, + int numToZeroize) { - PORT_Memset((void*)extensions, 0, sizeof(CERTCertExtension*)*numToZeroize); + PORT_Memset((void *)extensions, 0, sizeof(CERTCertExtension *) * numToZeroize); } /* @@ -342,72 +339,72 @@ crmf_zeroize_new_extensions (CRMFCertExtension **extensions, */ static SECStatus crmf_template_add_extensions(PLArenaPool *poolp, CRMFCertTemplate *inTemplate, - CRMFCertExtCreationInfo *extensions) + CRMFCertExtCreationInfo *extensions) { - void *mark; - int newSize, oldSize, i; - SECStatus rv; + void *mark; + int newSize, oldSize, i; + SECStatus rv; CRMFCertExtension **extArray; - CRMFCertExtension *newExt, *currExt; + CRMFCertExtension *newExt, *currExt; mark = PORT_ArenaMark(poolp); if (inTemplate->extensions == NULL) { newSize = extensions->numExtensions; - extArray = PORT_ZNewArray(CRMFCertExtension*,newSize+1); - } else { + extArray = PORT_ZNewArray(CRMFCertExtension *, newSize + 1); + } + else { newSize = inTemplate->numExtensions + extensions->numExtensions; - extArray = PORT_Realloc(inTemplate->extensions, - sizeof(CRMFCertExtension*)*(newSize+1)); + extArray = PORT_Realloc(inTemplate->extensions, + sizeof(CRMFCertExtension *) * (newSize + 1)); } if (extArray == NULL) { goto loser; } - oldSize = inTemplate->numExtensions; - inTemplate->extensions = extArray; + oldSize = inTemplate->numExtensions; + inTemplate->extensions = extArray; inTemplate->numExtensions = newSize; - for (i=oldSize; i < newSize; i++) { + for (i = oldSize; i < newSize; i++) { newExt = PORT_ArenaZNew(poolp, CRMFCertExtension); - if (newExt == NULL) { - goto loser2; - } - currExt = extensions->extensions[i-oldSize]; - rv = crmf_copy_secitem(poolp, &(newExt->id), &(currExt->id)); - if (rv != SECSuccess) { - goto loser2; - } - rv = crmf_copy_secitem(poolp, &(newExt->critical), - &(currExt->critical)); - if (rv != SECSuccess) { - goto loser2; - } - rv = crmf_copy_secitem(poolp, &(newExt->value), &(currExt->value)); - if (rv != SECSuccess) { - goto loser2; - } - extArray[i] = newExt; + if (newExt == NULL) { + goto loser2; + } + currExt = extensions->extensions[i - oldSize]; + rv = crmf_copy_secitem(poolp, &(newExt->id), &(currExt->id)); + if (rv != SECSuccess) { + goto loser2; + } + rv = crmf_copy_secitem(poolp, &(newExt->critical), + &(currExt->critical)); + if (rv != SECSuccess) { + goto loser2; + } + rv = crmf_copy_secitem(poolp, &(newExt->value), &(currExt->value)); + if (rv != SECSuccess) { + goto loser2; + } + extArray[i] = newExt; } extArray[newSize] = NULL; PORT_ArenaUnmark(poolp, mark); return SECSuccess; - loser2: - crmf_zeroize_new_extensions (&(inTemplate->extensions[oldSize]), - extensions->numExtensions); +loser2: + crmf_zeroize_new_extensions(&(inTemplate->extensions[oldSize]), + extensions->numExtensions); inTemplate->numExtensions = oldSize; - loser: +loser: PORT_ArenaRelease(poolp, mark); return SECFailure; } SECStatus -CRMF_CertRequestSetTemplateField(CRMFCertRequest *inCertReq, - CRMFCertTemplateField inTemplateField, - void *data) +CRMF_CertRequestSetTemplateField(CRMFCertRequest *inCertReq, + CRMFCertTemplateField inTemplateField, + void *data) { CRMFCertTemplate *certTemplate; - PLArenaPool *poolp; - SECStatus rv = SECFailure; - void *mark; - + PLArenaPool *poolp; + SECStatus rv = SECFailure; + void *mark; if (inCertReq == NULL) { return SECFailure; @@ -418,73 +415,74 @@ CRMF_CertRequestSetTemplateField(CRMFCertRequest *inCertReq, poolp = inCertReq->poolp; mark = PORT_ArenaMark(poolp); switch (inTemplateField) { - case crmfVersion: - rv = crmf_template_add_version(poolp,&(certTemplate->version), - *(long*)data); - break; - case crmfSerialNumber: - rv = crmf_template_add_serialnumber(poolp, - &(certTemplate->serialNumber), - *(long*)data); - break; - case crmfSigningAlg: - rv = crmf_template_copy_secalg (poolp, &(certTemplate->signingAlg), - (SECAlgorithmID*)data); - break; - case crmfIssuer: - rv = crmf_template_add_issuer (poolp, &(certTemplate->issuer), - (CERTName*)data); - break; - case crmfValidity: - rv = crmf_template_add_validity (poolp, &(certTemplate->validity), - (CRMFValidityCreationInfo*)data); - break; - case crmfSubject: - rv = crmf_template_add_subject (poolp, &(certTemplate->subject), - (CERTName*)data); - break; - case crmfPublicKey: - rv = crmf_template_add_public_key(poolp, &(certTemplate->publicKey), - (CERTSubjectPublicKeyInfo*)data); - break; - case crmfIssuerUID: - rv = crmf_template_add_issuer_uid(poolp, &(certTemplate->issuerUID), - (SECItem*)data); - break; - case crmfSubjectUID: - rv = crmf_template_add_subject_uid(poolp, &(certTemplate->subjectUID), - (SECItem*)data); - break; - case crmfExtension: - rv = crmf_template_add_extensions(poolp, certTemplate, - (CRMFCertExtCreationInfo*)data); - break; + case crmfVersion: + rv = crmf_template_add_version(poolp, &(certTemplate->version), + *(long *)data); + break; + case crmfSerialNumber: + rv = crmf_template_add_serialnumber(poolp, + &(certTemplate->serialNumber), + *(long *)data); + break; + case crmfSigningAlg: + rv = crmf_template_copy_secalg(poolp, &(certTemplate->signingAlg), + (SECAlgorithmID *)data); + break; + case crmfIssuer: + rv = crmf_template_add_issuer(poolp, &(certTemplate->issuer), + (CERTName *)data); + break; + case crmfValidity: + rv = crmf_template_add_validity(poolp, &(certTemplate->validity), + (CRMFValidityCreationInfo *)data); + break; + case crmfSubject: + rv = crmf_template_add_subject(poolp, &(certTemplate->subject), + (CERTName *)data); + break; + case crmfPublicKey: + rv = crmf_template_add_public_key(poolp, &(certTemplate->publicKey), + (CERTSubjectPublicKeyInfo *)data); + break; + case crmfIssuerUID: + rv = crmf_template_add_issuer_uid(poolp, &(certTemplate->issuerUID), + (SECItem *)data); + break; + case crmfSubjectUID: + rv = crmf_template_add_subject_uid(poolp, &(certTemplate->subjectUID), + (SECItem *)data); + break; + case crmfExtension: + rv = crmf_template_add_extensions(poolp, certTemplate, + (CRMFCertExtCreationInfo *)data); + break; } if (rv != SECSuccess) { PORT_ArenaRelease(poolp, mark); - } else { + } + else { PORT_ArenaUnmark(poolp, mark); } return rv; } SECStatus -CRMF_CertReqMsgSetCertRequest (CRMFCertReqMsg *inCertReqMsg, - CRMFCertRequest *inCertReq) +CRMF_CertReqMsgSetCertRequest(CRMFCertReqMsg *inCertReqMsg, + CRMFCertRequest *inCertReq) { - PORT_Assert (inCertReqMsg != NULL && inCertReq != NULL); + PORT_Assert(inCertReqMsg != NULL && inCertReq != NULL); if (inCertReqMsg == NULL || inCertReq == NULL) { return SECFailure; } inCertReqMsg->certReq = crmf_copy_cert_request(inCertReqMsg->poolp, - inCertReq); + inCertReq); return (inCertReqMsg->certReq == NULL) ? SECFailure : SECSuccess; } -CRMFCertReqMsg* +CRMFCertReqMsg * CRMF_CreateCertReqMsg(void) { - PLArenaPool *poolp; + PLArenaPool *poolp; CRMFCertReqMsg *reqMsg; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); @@ -497,49 +495,49 @@ CRMF_CreateCertReqMsg(void) } reqMsg->poolp = poolp; return reqMsg; - - loser: + +loser: if (poolp) { PORT_FreeArena(poolp, PR_FALSE); } return NULL; } -SECStatus +SECStatus CRMF_DestroyCertReqMsg(CRMFCertReqMsg *inCertReqMsg) { PORT_Assert(inCertReqMsg != NULL && inCertReqMsg->poolp != NULL); if (!inCertReqMsg->isDecoded) { if (inCertReqMsg->certReq->certTemplate.extensions != NULL) { - PORT_Free(inCertReqMsg->certReq->certTemplate.extensions); - } - if (inCertReqMsg->certReq->controls != NULL) { - PORT_Free(inCertReqMsg->certReq->controls); - } + PORT_Free(inCertReqMsg->certReq->certTemplate.extensions); + } + if (inCertReqMsg->certReq->controls != NULL) { + PORT_Free(inCertReqMsg->certReq->controls); + } } PORT_FreeArena(inCertReqMsg->poolp, PR_TRUE); return SECSuccess; } -CRMFCertExtension* +CRMFCertExtension * crmf_create_cert_extension(PLArenaPool *poolp, - SECOidTag id, - PRBool isCritical, - SECItem *data) + SECOidTag id, + PRBool isCritical, + SECItem *data) { CRMFCertExtension *newExt; - SECOidData *oidData; - SECStatus rv; + SECOidData *oidData; + SECStatus rv; newExt = (poolp == NULL) ? PORT_ZNew(CRMFCertExtension) : - PORT_ArenaZNew(poolp, CRMFCertExtension); + PORT_ArenaZNew(poolp, CRMFCertExtension); if (newExt == NULL) { goto loser; } oidData = SECOID_FindOIDByTag(id); - if (oidData == NULL || - oidData->supportedExtension != SUPPORTED_CERT_EXTENSION) { - goto loser; + if (oidData == NULL || + oidData->supportedExtension != SUPPORTED_CERT_EXTENSION) { + goto loser; } rv = SECITEM_CopyItem(poolp, &(newExt->id), &(oidData->oid)); @@ -553,17 +551,18 @@ crmf_create_cert_extension(PLArenaPool *poolp, } if (isCritical) { - newExt->critical.data = (poolp == NULL) ? - PORT_New(unsigned char) : - PORT_ArenaNew(poolp, unsigned char); - if (newExt->critical.data == NULL) { - goto loser; - } - newExt->critical.data[0] = hexTrue; - newExt->critical.len = 1; + newExt->critical.data = (poolp == NULL) ? + PORT_New(unsigned char) + : + PORT_ArenaNew(poolp, unsigned char); + if (newExt->critical.data == NULL) { + goto loser; + } + newExt->critical.data[0] = hexTrue; + newExt->critical.len = 1; } return newExt; - loser: +loser: if (newExt != NULL && poolp == NULL) { CRMF_DestroyCertExtension(newExt); } @@ -572,8 +571,8 @@ crmf_create_cert_extension(PLArenaPool *poolp, CRMFCertExtension * CRMF_CreateCertExtension(SECOidTag id, - PRBool isCritical, - SECItem *data) + PRBool isCritical, + SECItem *data) { return crmf_create_cert_extension(NULL, id, isCritical, data); } @@ -582,12 +581,12 @@ static SECStatus crmf_destroy_cert_extension(CRMFCertExtension *inExtension, PRBool freeit) { if (inExtension != NULL) { - SECITEM_FreeItem (&(inExtension->id), PR_FALSE); - SECITEM_FreeItem (&(inExtension->value), PR_FALSE); - SECITEM_FreeItem (&(inExtension->critical), PR_FALSE); - if (freeit) { - PORT_Free(inExtension); - } + SECITEM_FreeItem(&(inExtension->id), PR_FALSE); + SECITEM_FreeItem(&(inExtension->value), PR_FALSE); + SECITEM_FreeItem(&(inExtension->critical), PR_FALSE); + if (freeit) { + PORT_Free(inExtension); + } } return SECSuccess; } @@ -599,9 +598,9 @@ CRMF_DestroyCertExtension(CRMFCertExtension *inExtension) } SECStatus -CRMF_DestroyCertReqMessages(CRMFCertReqMessages *inCertReqMsgs) +CRMF_DestroyCertReqMessages(CRMFCertReqMessages *inCertReqMsgs) { - PORT_Assert (inCertReqMsgs != NULL); + PORT_Assert(inCertReqMsgs != NULL); if (inCertReqMsgs != NULL) { PORT_FreeArena(inCertReqMsgs->poolp, PR_TRUE); } @@ -618,53 +617,53 @@ crmf_item_has_data(SECItem *item) } PRBool -CRMF_CertRequestIsFieldPresent(CRMFCertRequest *inCertReq, - CRMFCertTemplateField inTemplateField) +CRMF_CertRequestIsFieldPresent(CRMFCertRequest *inCertReq, + CRMFCertTemplateField inTemplateField) { - PRBool retVal; + PRBool retVal; CRMFCertTemplate *certTemplate; PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { - /* This is probably some kind of error, but this is - * the safest return value for this function. - */ + /* This is probably some kind of error, but this is + * the safest return value for this function. + */ return PR_FALSE; } certTemplate = &inCertReq->certTemplate; switch (inTemplateField) { - case crmfVersion: - retVal = crmf_item_has_data(&certTemplate->version); - break; - case crmfSerialNumber: - retVal = crmf_item_has_data(&certTemplate->serialNumber); - break; - case crmfSigningAlg: - retVal = IS_NOT_NULL(certTemplate->signingAlg); - break; - case crmfIssuer: - retVal = IS_NOT_NULL(certTemplate->issuer); - break; - case crmfValidity: - retVal = IS_NOT_NULL(certTemplate->validity); - break; - case crmfSubject: - retVal = IS_NOT_NULL(certTemplate->subject); - break; - case crmfPublicKey: - retVal = IS_NOT_NULL(certTemplate->publicKey); - break; - case crmfIssuerUID: - retVal = crmf_item_has_data(&certTemplate->issuerUID); - break; - case crmfSubjectUID: - retVal = crmf_item_has_data(&certTemplate->subjectUID); - break; - case crmfExtension: - retVal = IS_NOT_NULL(certTemplate->extensions); - break; - default: - retVal = PR_FALSE; + case crmfVersion: + retVal = crmf_item_has_data(&certTemplate->version); + break; + case crmfSerialNumber: + retVal = crmf_item_has_data(&certTemplate->serialNumber); + break; + case crmfSigningAlg: + retVal = IS_NOT_NULL(certTemplate->signingAlg); + break; + case crmfIssuer: + retVal = IS_NOT_NULL(certTemplate->issuer); + break; + case crmfValidity: + retVal = IS_NOT_NULL(certTemplate->validity); + break; + case crmfSubject: + retVal = IS_NOT_NULL(certTemplate->subject); + break; + case crmfPublicKey: + retVal = IS_NOT_NULL(certTemplate->publicKey); + break; + case crmfIssuerUID: + retVal = crmf_item_has_data(&certTemplate->issuerUID); + break; + case crmfSubjectUID: + retVal = crmf_item_has_data(&certTemplate->subjectUID); + break; + case crmfExtension: + retVal = IS_NOT_NULL(certTemplate->extensions); + break; + default: + retVal = PR_FALSE; } return retVal; } diff --git a/security/nss/lib/crmf/crmft.h b/security/nss/lib/crmf/crmft.h index e12aa02c8922..8d83cf1e61bc 100644 --- a/security/nss/lib/crmf/crmft.h +++ b/security/nss/lib/crmf/crmft.h @@ -3,8 +3,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Header file with all of the structures and types that will be exported +/* Header file with all of the structures and types that will be exported * by the security library for implementation of CRMF. */ @@ -47,7 +46,7 @@ typedef enum { } CRMFPublicationAction; /* - * An enumeration for the possible for pubMethod which is a part of + * An enumeration for the possible for pubMethod which is a part of * the SinglePubInfo ASN1 type. */ typedef enum { @@ -79,7 +78,7 @@ typedef enum { } CRMFPOPChoice; /* - * An enumertion type for options for the authInfo field of the + * An enumertion type for options for the authInfo field of the * CRMFPOPOSigningKeyInput structure. */ typedef enum { @@ -132,41 +131,41 @@ typedef enum { * The number of DER encoded bytes to write out. * */ -typedef void (*CRMFEncoderOutputCallback) (void *arg, - const char *buf, - unsigned long len); +typedef void (*CRMFEncoderOutputCallback)(void *arg, + const char *buf, + unsigned long len); /* * Type for the function that gets a password. Just in case we ever * need to support publicKeyMAC for POPOSigningKeyInput */ -typedef SECItem* (*CRMFMACPasswordCallback) (void *arg); +typedef SECItem *(*CRMFMACPasswordCallback)(void *arg); -typedef struct CRMFOptionalValidityStr CRMFOptionalValidity; -typedef struct CRMFValidityCreationInfoStr CRMFGetValidity; -typedef struct CRMFCertTemplateStr CRMFCertTemplate; -typedef struct CRMFCertRequestStr CRMFCertRequest; -typedef struct CRMFCertReqMsgStr CRMFCertReqMsg; -typedef struct CRMFCertReqMessagesStr CRMFCertReqMessages; -typedef struct CRMFProofOfPossessionStr CRMFProofOfPossession; -typedef struct CRMFPOPOSigningKeyStr CRMFPOPOSigningKey; -typedef struct CRMFPOPOSigningKeyInputStr CRMFPOPOSigningKeyInput; -typedef struct CRMFPOPOPrivKeyStr CRMFPOPOPrivKey; -typedef struct CRMFPKIPublicationInfoStr CRMFPKIPublicationInfo; -typedef struct CRMFSinglePubInfoStr CRMFSinglePubInfo; -typedef struct CRMFPKIArchiveOptionsStr CRMFPKIArchiveOptions; -typedef struct CRMFEncryptedKeyStr CRMFEncryptedKey; -typedef struct CRMFEncryptedValueStr CRMFEncryptedValue; -typedef struct CRMFCertIDStr CRMFCertID; -typedef struct CRMFCertIDStr CRMFOldCertID; -typedef CERTSubjectPublicKeyInfo CRMFProtocolEncrKey; -typedef struct CRMFValidityCreationInfoStr CRMFValidityCreationInfo; -typedef struct CRMFCertExtCreationInfoStr CRMFCertExtCreationInfo; -typedef struct CRMFPKMACValueStr CRMFPKMACValue; -typedef struct CRMFAttributeStr CRMFAttribute; -typedef struct CRMFControlStr CRMFControl; -typedef CERTGeneralName CRMFGeneralName; -typedef struct CRMFCertExtensionStr CRMFCertExtension; +typedef struct CRMFOptionalValidityStr CRMFOptionalValidity; +typedef struct CRMFValidityCreationInfoStr CRMFGetValidity; +typedef struct CRMFCertTemplateStr CRMFCertTemplate; +typedef struct CRMFCertRequestStr CRMFCertRequest; +typedef struct CRMFCertReqMsgStr CRMFCertReqMsg; +typedef struct CRMFCertReqMessagesStr CRMFCertReqMessages; +typedef struct CRMFProofOfPossessionStr CRMFProofOfPossession; +typedef struct CRMFPOPOSigningKeyStr CRMFPOPOSigningKey; +typedef struct CRMFPOPOSigningKeyInputStr CRMFPOPOSigningKeyInput; +typedef struct CRMFPOPOPrivKeyStr CRMFPOPOPrivKey; +typedef struct CRMFPKIPublicationInfoStr CRMFPKIPublicationInfo; +typedef struct CRMFSinglePubInfoStr CRMFSinglePubInfo; +typedef struct CRMFPKIArchiveOptionsStr CRMFPKIArchiveOptions; +typedef struct CRMFEncryptedKeyStr CRMFEncryptedKey; +typedef struct CRMFEncryptedValueStr CRMFEncryptedValue; +typedef struct CRMFCertIDStr CRMFCertID; +typedef struct CRMFCertIDStr CRMFOldCertID; +typedef CERTSubjectPublicKeyInfo CRMFProtocolEncrKey; +typedef struct CRMFValidityCreationInfoStr CRMFValidityCreationInfo; +typedef struct CRMFCertExtCreationInfoStr CRMFCertExtCreationInfo; +typedef struct CRMFPKMACValueStr CRMFPKMACValue; +typedef struct CRMFAttributeStr CRMFAttribute; +typedef struct CRMFControlStr CRMFControl; +typedef CERTGeneralName CRMFGeneralName; +typedef struct CRMFCertExtensionStr CRMFCertExtension; struct CRMFValidityCreationInfoStr { PRTime *notBefore; @@ -184,5 +183,4 @@ struct CRMFCertExtCreationInfoStr { extern const SEC_ASN1Template CRMFCertReqMessagesTemplate[]; extern const SEC_ASN1Template CRMFCertRequestTemplate[]; - #endif /*_CRMFT_H_*/ diff --git a/security/nss/lib/crmf/crmftmpl.c b/security/nss/lib/crmf/crmftmpl.c index 320d524635f8..265a15dd5dde 100644 --- a/security/nss/lib/crmf/crmftmpl.c +++ b/security/nss/lib/crmf/crmftmpl.c @@ -18,27 +18,27 @@ SEC_ASN1_MKSUB(CERT_TimeChoiceTemplate) SEC_ASN1_MKSUB(CERT_SubjectPublicKeyInfoTemplate) SEC_ASN1_MKSUB(CERT_NameTemplate) -/* +/* * It's all implicit tagging. */ const SEC_ASN1Template CRMFControlTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFControl)}, - { SEC_ASN1_OBJECT_ID, offsetof(CRMFControl, derTag)}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFControl) }, + { SEC_ASN1_OBJECT_ID, offsetof(CRMFControl, derTag) }, { SEC_ASN1_ANY, offsetof(CRMFControl, derValue) }, { 0 } }; static const SEC_ASN1Template CRMFCertExtensionTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CRMFCertExtension) }, + 0, NULL, sizeof(CRMFCertExtension) }, { SEC_ASN1_OBJECT_ID, - offsetof(CRMFCertExtension,id) }, + offsetof(CRMFCertExtension, id) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, - offsetof(CRMFCertExtension,critical) }, + offsetof(CRMFCertExtension, critical) }, { SEC_ASN1_OCTET_STRING, - offsetof(CRMFCertExtension,value) }, - { 0, } + offsetof(CRMFCertExtension, value) }, + { 0 } }; static const SEC_ASN1Template CRMFSequenceOfCertExtensionTemplate[] = { @@ -46,78 +46,78 @@ static const SEC_ASN1Template CRMFSequenceOfCertExtensionTemplate[] = { }; static const SEC_ASN1Template CRMFOptionalValidityTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof (CRMFOptionalValidity) }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFOptionalValidity) }, { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_NO_STREAM | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN | 0, - offsetof (CRMFOptionalValidity, notBefore), + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN | 0, + offsetof(CRMFOptionalValidity, notBefore), SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_NO_STREAM | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN | 1, - offsetof (CRMFOptionalValidity, notAfter), + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN | 1, + offsetof(CRMFOptionalValidity, notAfter), SEC_ASN1_SUB(CERT_TimeChoiceTemplate) }, { 0 } }; static const SEC_ASN1Template crmfPointerToNameTemplate[] = { - { SEC_ASN1_POINTER | SEC_ASN1_XTRN, 0, SEC_ASN1_SUB(CERT_NameTemplate)}, + { SEC_ASN1_POINTER | SEC_ASN1_XTRN, 0, SEC_ASN1_SUB(CERT_NameTemplate) }, { 0 } }; static const SEC_ASN1Template CRMFCertTemplateTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFCertTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(CRMFCertTemplate, version), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN | 1 , - offsetof (CRMFCertTemplate, serialNumber), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | - SEC_ASN1_XTRN | 2, - offsetof (CRMFCertTemplate, signingAlg), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | 3, - offsetof (CRMFCertTemplate, issuer), crmfPointerToNameTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | 4, - offsetof (CRMFCertTemplate, validity), - CRMFOptionalValidityTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | 5, - offsetof (CRMFCertTemplate, subject), crmfPointerToNameTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | - SEC_ASN1_XTRN | 6, - offsetof (CRMFCertTemplate, publicKey), - SEC_ASN1_SUB(CERT_SubjectPublicKeyInfoTemplate) }, - { SEC_ASN1_NO_STREAM | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | - SEC_ASN1_XTRN | 7, - offsetof (CRMFCertTemplate, issuerUID), - SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { SEC_ASN1_NO_STREAM | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | - SEC_ASN1_XTRN | 8, - offsetof (CRMFCertTemplate, subjectUID), - SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { SEC_ASN1_CONSTRUCTED | SEC_ASN1_OPTIONAL | - SEC_ASN1_CONTEXT_SPECIFIC | 9, - offsetof (CRMFCertTemplate, extensions), - CRMFSequenceOfCertExtensionTemplate }, - { 0 } + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFCertTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(CRMFCertTemplate, version), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, + { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | SEC_ASN1_XTRN | 1, + offsetof(CRMFCertTemplate, serialNumber), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | + SEC_ASN1_XTRN | 2, + offsetof(CRMFCertTemplate, signingAlg), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | 3, + offsetof(CRMFCertTemplate, issuer), crmfPointerToNameTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | 4, + offsetof(CRMFCertTemplate, validity), + CRMFOptionalValidityTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | 5, + offsetof(CRMFCertTemplate, subject), crmfPointerToNameTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | + SEC_ASN1_XTRN | 6, + offsetof(CRMFCertTemplate, publicKey), + SEC_ASN1_SUB(CERT_SubjectPublicKeyInfoTemplate) }, + { SEC_ASN1_NO_STREAM | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | + SEC_ASN1_XTRN | 7, + offsetof(CRMFCertTemplate, issuerUID), + SEC_ASN1_SUB(SEC_BitStringTemplate) }, + { SEC_ASN1_NO_STREAM | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | + SEC_ASN1_XTRN | 8, + offsetof(CRMFCertTemplate, subjectUID), + SEC_ASN1_SUB(SEC_BitStringTemplate) }, + { SEC_ASN1_CONSTRUCTED | SEC_ASN1_OPTIONAL | + SEC_ASN1_CONTEXT_SPECIFIC | 9, + offsetof(CRMFCertTemplate, extensions), + CRMFSequenceOfCertExtensionTemplate }, + { 0 } }; static const SEC_ASN1Template CRMFAttributeTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFAttribute)}, - { SEC_ASN1_OBJECT_ID, offsetof(CRMFAttribute, derTag)}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFAttribute) }, + { SEC_ASN1_OBJECT_ID, offsetof(CRMFAttribute, derTag) }, { SEC_ASN1_ANY, offsetof(CRMFAttribute, derValue) }, { 0 } }; const SEC_ASN1Template CRMFCertRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof (CRMFCertRequest) }, - { SEC_ASN1_INTEGER, offsetof(CRMFCertRequest, certReqId)}, - { SEC_ASN1_INLINE, offsetof(CRMFCertRequest, certTemplate), - CRMFCertTemplateTemplate}, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFCertRequest) }, + { SEC_ASN1_INTEGER, offsetof(CRMFCertRequest, certReqId) }, + { SEC_ASN1_INLINE, offsetof(CRMFCertRequest, certTemplate), + CRMFCertTemplateTemplate }, { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, - offsetof(CRMFCertRequest,controls), - CRMFControlTemplate}, /* SEQUENCE SIZE (1...MAX)*/ + offsetof(CRMFCertRequest, controls), + CRMFControlTemplate }, /* SEQUENCE SIZE (1...MAX)*/ { 0 } }; @@ -128,35 +128,34 @@ const SEC_ASN1Template CRMFCertReqMsgTemplate[] = { { SEC_ASN1_ANY | SEC_ASN1_OPTIONAL, offsetof(CRMFCertReqMsg, derPOP) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, - offsetof(CRMFCertReqMsg, regInfo), - CRMFAttributeTemplate}, /* SEQUENCE SIZE (1...MAX)*/ + offsetof(CRMFCertReqMsg, regInfo), + CRMFAttributeTemplate }, /* SEQUENCE SIZE (1...MAX)*/ { 0 } }; const SEC_ASN1Template CRMFCertReqMessagesTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, offsetof(CRMFCertReqMessages, messages), - CRMFCertReqMsgTemplate, sizeof (CRMFCertReqMessages)} + { SEC_ASN1_SEQUENCE_OF, offsetof(CRMFCertReqMessages, messages), + CRMFCertReqMsgTemplate, sizeof(CRMFCertReqMessages) } }; const SEC_ASN1Template CRMFRAVerifiedTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | 0 | SEC_ASN1_XTRN, + { SEC_ASN1_CONTEXT_SPECIFIC | 0 | SEC_ASN1_XTRN, 0, SEC_ASN1_SUB(SEC_NullTemplate) }, { 0 } }; - /* This template will need to add POPOSigningKeyInput eventually, maybe*/ static const SEC_ASN1Template crmfPOPOSigningKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFPOPOSigningKey) }, - { SEC_ASN1_NO_STREAM | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 0, - offsetof(CRMFPOPOSigningKey, derInput), + { SEC_ASN1_NO_STREAM | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_XTRN | 0, + offsetof(CRMFPOPOSigningKey, derInput), SEC_ASN1_SUB(SEC_AnyTemplate) }, - { SEC_ASN1_POINTER | SEC_ASN1_XTRN, + { SEC_ASN1_POINTER | SEC_ASN1_XTRN, offsetof(CRMFPOPOSigningKey, algorithmIdentifier), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_BIT_STRING | SEC_ASN1_XTRN, + { SEC_ASN1_BIT_STRING | SEC_ASN1_XTRN, offsetof(CRMFPOPOSigningKey, signature), SEC_ASN1_SUB(SEC_BitStringTemplate) }, { 0 } @@ -165,7 +164,7 @@ static const SEC_ASN1Template crmfPOPOSigningKeyTemplate[] = { const SEC_ASN1Template CRMFPOPOSigningKeyTemplate[] = { { SEC_ASN1_CONTEXT_SPECIFIC | 1, 0, - crmfPOPOSigningKeyTemplate}, + crmfPOPOSigningKeyTemplate }, { 0 } }; @@ -178,7 +177,7 @@ const SEC_ASN1Template CRMFThisMessageTemplate[] = { const SEC_ASN1Template CRMFSubsequentMessageTemplate[] = { { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1, - 0, + 0, SEC_ASN1_SUB(SEC_IntegerTemplate) }, { 0 } }; @@ -191,51 +190,51 @@ const SEC_ASN1Template CRMFDHMACTemplate[] = { }; const SEC_ASN1Template CRMFPOPOKeyEnciphermentTemplate[] = { - { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, + { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2, 0, SEC_ASN1_SUB(SEC_AnyTemplate) }, { 0 } }; const SEC_ASN1Template CRMFPOPOKeyAgreementTemplate[] = { - { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 3, + { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 3, 0, - SEC_ASN1_SUB(SEC_AnyTemplate)}, + SEC_ASN1_SUB(SEC_AnyTemplate) }, { 0 } }; const SEC_ASN1Template CRMFEncryptedValueTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFEncryptedValue)}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | - SEC_ASN1_XTRN | 0, - offsetof(CRMFEncryptedValue, intendedAlg), + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRMFEncryptedValue) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | + SEC_ASN1_XTRN | 0, + offsetof(CRMFEncryptedValue, intendedAlg), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | - SEC_ASN1_XTRN | 1, - offsetof (CRMFEncryptedValue, symmAlg), + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | + SEC_ASN1_XTRN | 1, + offsetof(CRMFEncryptedValue, symmAlg), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_NO_STREAM | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | - SEC_ASN1_XTRN | 2, - offsetof(CRMFEncryptedValue, encSymmKey), + { SEC_ASN1_NO_STREAM | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | + SEC_ASN1_XTRN | 2, + offsetof(CRMFEncryptedValue, encSymmKey), SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | - SEC_ASN1_XTRN | 3, - offsetof(CRMFEncryptedValue, keyAlg), + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | + SEC_ASN1_XTRN | 3, + offsetof(CRMFEncryptedValue, keyAlg), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_NO_STREAM | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 4, + { SEC_ASN1_NO_STREAM | SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_XTRN | 4, offsetof(CRMFEncryptedValue, valueHint), SEC_ASN1_SUB(SEC_OctetStringTemplate) }, { SEC_ASN1_BIT_STRING, offsetof(CRMFEncryptedValue, encValue) }, { 0 } }; -const SEC_ASN1Template CRMFEncryptedKeyWithEncryptedValueTemplate [] = { - { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, +const SEC_ASN1Template CRMFEncryptedKeyWithEncryptedValueTemplate[] = { + { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | + SEC_ASN1_CONTEXT_SPECIFIC | 0, 0, - CRMFEncryptedValueTemplate}, + CRMFEncryptedValueTemplate }, { 0 } }; diff --git a/security/nss/lib/crmf/encutil.c b/security/nss/lib/crmf/encutil.c index ffa99edcc39f..8ca7007b6c43 100644 --- a/security/nss/lib/crmf/encutil.c +++ b/security/nss/lib/crmf/encutil.c @@ -9,17 +9,17 @@ void crmf_encoder_out(void *arg, const char *buf, unsigned long len, - int depth, SEC_ASN1EncodingPart data_kind) + int depth, SEC_ASN1EncodingPart data_kind) { struct crmfEncoderOutput *output; - output = (struct crmfEncoderOutput*) arg; - output->fn (output->outputArg, buf, len); + output = (struct crmfEncoderOutput *)arg; + output->fn(output->outputArg, buf, len); } SECStatus cmmf_user_encode(void *src, CRMFEncoderOutputCallback inCallback, void *inArg, - const SEC_ASN1Template *inTemplate) + const SEC_ASN1Template *inTemplate) { struct crmfEncoderOutput output; @@ -27,8 +27,7 @@ cmmf_user_encode(void *src, CRMFEncoderOutputCallback inCallback, void *inArg, if (src == NULL) { return SECFailure; } - output.fn = inCallback; + output.fn = inCallback; output.outputArg = inArg; - return SEC_ASN1Encode(src, inTemplate, crmf_encoder_out, &output); + return SEC_ASN1Encode(src, inTemplate, crmf_encoder_out, &output); } - diff --git a/security/nss/lib/crmf/respcli.c b/security/nss/lib/crmf/respcli.c index 5525aaf262cb..aaec0136f1ff 100644 --- a/security/nss/lib/crmf/respcli.c +++ b/security/nss/lib/crmf/respcli.c @@ -3,9 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - /* - * This file will contain all routines needed by a client that has + * This file will contain all routines needed by a client that has * to parse a CMMFCertRepContent structure and retirieve the appropriate * data. */ @@ -18,14 +17,14 @@ #include "secder.h" #include "secasn1.h" -CMMFCertRepContent* -CMMF_CreateCertRepContentFromDER(CERTCertDBHandle *db, const char *buf, - long len) +CMMFCertRepContent * +CMMF_CreateCertRepContentFromDER(CERTCertDBHandle *db, const char *buf, + long len) { - PLArenaPool *poolp; + PLArenaPool *poolp; CMMFCertRepContent *certRepContent; - SECStatus rv; - int i; + SECStatus rv; + int i; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { @@ -37,22 +36,22 @@ CMMF_CreateCertRepContentFromDER(CERTCertDBHandle *db, const char *buf, } certRepContent->poolp = poolp; rv = SEC_ASN1Decode(poolp, certRepContent, CMMFCertRepContentTemplate, - buf, len); + buf, len); if (rv != SECSuccess) { goto loser; } if (certRepContent->response != NULL) { - for (i=0; certRepContent->response[i] != NULL; i++) { - rv = cmmf_decode_process_cert_response(poolp, db, - certRepContent->response[i]); - if (rv != SECSuccess) { - goto loser; - } - } + for (i = 0; certRepContent->response[i] != NULL; i++) { + rv = cmmf_decode_process_cert_response(poolp, db, + certRepContent->response[i]); + if (rv != SECSuccess) { + goto loser; + } + } } certRepContent->isDecoded = PR_TRUE; return certRepContent; - loser: +loser: PORT_FreeArena(poolp, PR_FALSE); return NULL; } @@ -69,7 +68,7 @@ CMMF_CertResponseGetCertReqId(CMMFCertResponse *inCertResp) PRBool cmmf_CertRepContentIsIndexValid(CMMFCertRepContent *inCertRepContent, - int inIndex) + int inIndex) { int numResponses; @@ -78,27 +77,27 @@ cmmf_CertRepContentIsIndexValid(CMMFCertRepContent *inCertRepContent, return (PRBool)(inIndex >= 0 && inIndex < numResponses); } -CMMFCertResponse* +CMMFCertResponse * CMMF_CertRepContentGetResponseAtIndex(CMMFCertRepContent *inCertRepContent, - int inIndex) + int inIndex) { CMMFCertResponse *certResponse; - SECStatus rv; + SECStatus rv; PORT_Assert(inCertRepContent != NULL && - cmmf_CertRepContentIsIndexValid(inCertRepContent, inIndex)); + cmmf_CertRepContentIsIndexValid(inCertRepContent, inIndex)); if (inCertRepContent == NULL || - !cmmf_CertRepContentIsIndexValid(inCertRepContent, inIndex)) { + !cmmf_CertRepContentIsIndexValid(inCertRepContent, inIndex)) { return NULL; } certResponse = PORT_ZNew(CMMFCertResponse); - if (certResponse){ - rv = cmmf_CopyCertResponse(NULL, certResponse, - inCertRepContent->response[inIndex]); - if (rv != SECSuccess) { - CMMF_DestroyCertResponse(certResponse); - certResponse = NULL; - } + if (certResponse) { + rv = cmmf_CopyCertResponse(NULL, certResponse, + inCertRepContent->response[inIndex]); + if (rv != SECSuccess) { + CMMF_DestroyCertResponse(certResponse); + certResponse = NULL; + } } return certResponse; } @@ -113,27 +112,25 @@ CMMF_CertResponseGetPKIStatusInfoStatus(CMMFCertResponse *inCertResp) return cmmf_PKIStatusInfoGetStatus(&inCertResp->status); } -CERTCertificate* +CERTCertificate * CMMF_CertResponseGetCertificate(CMMFCertResponse *inCertResp, - CERTCertDBHandle *inCertdb) + CERTCertDBHandle *inCertdb) { PORT_Assert(inCertResp != NULL); if (inCertResp == NULL || inCertResp->certifiedKeyPair == NULL) { return NULL; } - + return cmmf_CertOrEncCertGetCertificate( - &inCertResp->certifiedKeyPair->certOrEncCert, inCertdb); - + &inCertResp->certifiedKeyPair->certOrEncCert, inCertdb); } -CERTCertList* -CMMF_CertRepContentGetCAPubs (CMMFCertRepContent *inCertRepContent) +CERTCertList * +CMMF_CertRepContentGetCAPubs(CMMFCertRepContent *inCertRepContent) { - PORT_Assert (inCertRepContent != NULL); + PORT_Assert(inCertRepContent != NULL); if (inCertRepContent == NULL || inCertRepContent->caPubs == NULL) { return NULL; } return cmmf_MakeCertList(inCertRepContent->caPubs); } - diff --git a/security/nss/lib/crmf/respcmn.c b/security/nss/lib/crmf/respcmn.c index 1353d367ec15..3f5f15ace786 100644 --- a/security/nss/lib/crmf/respcmn.c +++ b/security/nss/lib/crmf/respcmn.c @@ -8,8 +8,8 @@ #include "secitem.h" #include "secder.h" -SECStatus -cmmf_DestroyPKIStatusInfo (CMMFPKIStatusInfo *info, PRBool freeit) +SECStatus +cmmf_DestroyPKIStatusInfo(CMMFPKIStatusInfo *info, PRBool freeit) { if (info->status.data != NULL) { PORT_Free(info->status.data); @@ -35,13 +35,13 @@ CMMF_DestroyCertResponse(CMMFCertResponse *inCertResp) PORT_Assert(inCertResp != NULL); if (inCertResp != NULL) { if (inCertResp->certReqId.data != NULL) { - PORT_Free(inCertResp->certReqId.data); - } - cmmf_DestroyPKIStatusInfo(&inCertResp->status, PR_FALSE); - if (inCertResp->certifiedKeyPair != NULL) { - CMMF_DestroyCertifiedKeyPair(inCertResp->certifiedKeyPair); - } - PORT_Free(inCertResp); + PORT_Free(inCertResp->certReqId.data); + } + cmmf_DestroyPKIStatusInfo(&inCertResp->status, PR_FALSE); + if (inCertResp->certifiedKeyPair != NULL) { + CMMF_DestroyCertifiedKeyPair(inCertResp->certifiedKeyPair); + } + PORT_Free(inCertResp); } return SECSuccess; } @@ -51,32 +51,31 @@ CMMF_DestroyCertRepContent(CMMFCertRepContent *inCertRepContent) { PORT_Assert(inCertRepContent != NULL); if (inCertRepContent != NULL) { - CMMFCertResponse **pResponse = inCertRepContent->response; + CMMFCertResponse **pResponse = inCertRepContent->response; if (pResponse != NULL) { for (; *pResponse != NULL; pResponse++) { - CMMFCertifiedKeyPair *certKeyPair = (*pResponse)->certifiedKeyPair; - /* XXX Why not call CMMF_DestroyCertifiedKeyPair or - ** XXX cmmf_DestroyCertOrEncCert ? - */ - if (certKeyPair != NULL && + CMMFCertifiedKeyPair *certKeyPair = (*pResponse)->certifiedKeyPair; + /* XXX Why not call CMMF_DestroyCertifiedKeyPair or + ** XXX cmmf_DestroyCertOrEncCert ? + */ + if (certKeyPair != NULL && certKeyPair->certOrEncCert.choice == cmmfCertificate && certKeyPair->certOrEncCert.cert.certificate != NULL) { - CERT_DestroyCertificate - (certKeyPair->certOrEncCert.cert.certificate); - certKeyPair->certOrEncCert.cert.certificate = NULL; + CERT_DestroyCertificate(certKeyPair->certOrEncCert.cert.certificate); + certKeyPair->certOrEncCert.cert.certificate = NULL; } } } - if (inCertRepContent->caPubs) { - CERTCertificate **caPubs = inCertRepContent->caPubs; - for (; *caPubs; ++caPubs) { - CERT_DestroyCertificate(*caPubs); - *caPubs = NULL; - } - } - if (inCertRepContent->poolp != NULL) { - PORT_FreeArena(inCertRepContent->poolp, PR_TRUE); - } + if (inCertRepContent->caPubs) { + CERTCertificate **caPubs = inCertRepContent->caPubs; + for (; *caPubs; ++caPubs) { + CERT_DestroyCertificate(*caPubs); + *caPubs = NULL; + } + } + if (inCertRepContent->poolp != NULL) { + PORT_FreeArena(inCertRepContent->poolp, PR_TRUE); + } } return SECSuccess; } @@ -94,73 +93,73 @@ CMMF_DestroyPOPODecKeyChallContent(CMMFPOPODecKeyChallContent *inDecKeyCont) SECStatus crmf_create_prtime(SECItem *src, PRTime **dest) { - *dest = PORT_ZNew(PRTime); + *dest = PORT_ZNew(PRTime); return DER_DecodeTimeChoice(*dest, src); } -CRMFCertExtension* +CRMFCertExtension * crmf_copy_cert_extension(PLArenaPool *poolp, CRMFCertExtension *inExtension) { - PRBool isCritical; - SECOidTag id; - SECItem *data; + PRBool isCritical; + SECOidTag id; + SECItem *data; CRMFCertExtension *newExt; PORT_Assert(inExtension != NULL); if (inExtension == NULL) { return NULL; } - id = CRMF_CertExtensionGetOidTag(inExtension); + id = CRMF_CertExtensionGetOidTag(inExtension); isCritical = CRMF_CertExtensionGetIsCritical(inExtension); - data = CRMF_CertExtensionGetValue(inExtension); - newExt = crmf_create_cert_extension(poolp, id, - isCritical, - data); + data = CRMF_CertExtensionGetValue(inExtension); + newExt = crmf_create_cert_extension(poolp, id, + isCritical, + data); SECITEM_FreeItem(data, PR_TRUE); - return newExt; + return newExt; } -static SECItem* +static SECItem * cmmf_encode_certificate(CERTCertificate *inCert) { - return SEC_ASN1EncodeItem(NULL, NULL, inCert, - SEC_ASN1_GET(SEC_SignedCertificateTemplate)); + return SEC_ASN1EncodeItem(NULL, NULL, inCert, + SEC_ASN1_GET(SEC_SignedCertificateTemplate)); } -CERTCertList* +CERTCertList * cmmf_MakeCertList(CERTCertificate **inCerts) { - CERTCertList *certList; + CERTCertList *certList; CERTCertificate *currCert; - SECItem *derCert, *freeCert = NULL; - SECStatus rv; - int i; + SECItem *derCert, *freeCert = NULL; + SECStatus rv; + int i; certList = CERT_NewCertList(); if (certList == NULL) { return NULL; } - for (i=0; inCerts[i] != NULL; i++) { + for (i = 0; inCerts[i] != NULL; i++) { derCert = &inCerts[i]->derCert; - if (derCert->data == NULL) { - derCert = freeCert = cmmf_encode_certificate(inCerts[i]); - } - currCert=CERT_NewTempCertificate(CERT_GetDefaultCertDB(), - derCert, NULL, PR_FALSE, PR_TRUE); - if (freeCert != NULL) { - SECITEM_FreeItem(freeCert, PR_TRUE); - freeCert = NULL; - } - if (currCert == NULL) { - goto loser; - } - rv = CERT_AddCertToListTail(certList, currCert); - if (rv != SECSuccess) { - goto loser; - } + if (derCert->data == NULL) { + derCert = freeCert = cmmf_encode_certificate(inCerts[i]); + } + currCert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), + derCert, NULL, PR_FALSE, PR_TRUE); + if (freeCert != NULL) { + SECITEM_FreeItem(freeCert, PR_TRUE); + freeCert = NULL; + } + if (currCert == NULL) { + goto loser; + } + rv = CERT_AddCertToListTail(certList, currCert); + if (rv != SECSuccess) { + goto loser; + } } return certList; - loser: +loser: CERT_DestroyCertList(certList); return NULL; } @@ -181,31 +180,30 @@ int CMMF_CertRepContentGetNumResponses(CMMFCertRepContent *inCertRepContent) { int numResponses = 0; - PORT_Assert (inCertRepContent != NULL); + PORT_Assert(inCertRepContent != NULL); if (inCertRepContent != NULL && inCertRepContent->response != NULL) { while (inCertRepContent->response[numResponses] != NULL) { - numResponses++; - } + numResponses++; + } } return numResponses; } - SECStatus cmmf_DestroyCertOrEncCert(CMMFCertOrEncCert *certOrEncCert, PRBool freeit) { switch (certOrEncCert->choice) { - case cmmfCertificate: - CERT_DestroyCertificate(certOrEncCert->cert.certificate); - certOrEncCert->cert.certificate = NULL; - break; - case cmmfEncryptedCert: - crmf_destroy_encrypted_value(certOrEncCert->cert.encryptedCert, - PR_TRUE); - certOrEncCert->cert.encryptedCert = NULL; - break; - default: - break; + case cmmfCertificate: + CERT_DestroyCertificate(certOrEncCert->cert.certificate); + certOrEncCert->cert.certificate = NULL; + break; + case cmmfEncryptedCert: + crmf_destroy_encrypted_value(certOrEncCert->cert.encryptedCert, + PR_TRUE); + certOrEncCert->cert.encryptedCert = NULL; + break; + default: + break; } if (freeit) { PORT_Free(certOrEncCert); @@ -214,16 +212,17 @@ cmmf_DestroyCertOrEncCert(CMMFCertOrEncCert *certOrEncCert, PRBool freeit) } SECStatus -cmmf_copy_secitem (PLArenaPool *poolp, SECItem *dest, SECItem *src) +cmmf_copy_secitem(PLArenaPool *poolp, SECItem *dest, SECItem *src) { SECStatus rv; if (src->data != NULL) { rv = SECITEM_CopyItem(poolp, dest, src); - } else { + } + else { dest->data = NULL; - dest->len = 0; - rv = SECSuccess; + dest->len = 0; + rv = SECSuccess; } return rv; } @@ -246,161 +245,159 @@ CMMF_DestroyCertifiedKeyPair(CMMFCertifiedKeyPair *inCertKeyPair) } SECStatus -cmmf_CopyCertResponse(PLArenaPool *poolp, - CMMFCertResponse *dest, - CMMFCertResponse *src) +cmmf_CopyCertResponse(PLArenaPool *poolp, + CMMFCertResponse *dest, + CMMFCertResponse *src) { SECStatus rv; if (src->certReqId.data != NULL) { rv = SECITEM_CopyItem(poolp, &dest->certReqId, &src->certReqId); - if (rv != SECSuccess) { - return rv; - } + if (rv != SECSuccess) { + return rv; + } } rv = cmmf_CopyPKIStatusInfo(poolp, &dest->status, &src->status); if (rv != SECSuccess) { return rv; } if (src->certifiedKeyPair != NULL) { - CMMFCertifiedKeyPair *destKeyPair; + CMMFCertifiedKeyPair *destKeyPair; - destKeyPair = (poolp == NULL) ? PORT_ZNew(CMMFCertifiedKeyPair) : - PORT_ArenaZNew(poolp, CMMFCertifiedKeyPair); - if (!destKeyPair) { - return SECFailure; - } - rv = cmmf_CopyCertifiedKeyPair(poolp, destKeyPair, - src->certifiedKeyPair); - if (rv != SECSuccess) { - if (!poolp) { - CMMF_DestroyCertifiedKeyPair(destKeyPair); - } - return rv; - } - dest->certifiedKeyPair = destKeyPair; + destKeyPair = (poolp == NULL) ? PORT_ZNew(CMMFCertifiedKeyPair) : + PORT_ArenaZNew(poolp, CMMFCertifiedKeyPair); + if (!destKeyPair) { + return SECFailure; + } + rv = cmmf_CopyCertifiedKeyPair(poolp, destKeyPair, + src->certifiedKeyPair); + if (rv != SECSuccess) { + if (!poolp) { + CMMF_DestroyCertifiedKeyPair(destKeyPair); + } + return rv; + } + dest->certifiedKeyPair = destKeyPair; } return SECSuccess; } static SECStatus cmmf_CopyCertOrEncCert(PLArenaPool *poolp, CMMFCertOrEncCert *dest, - CMMFCertOrEncCert *src) + CMMFCertOrEncCert *src) { - SECStatus rv = SECSuccess; + SECStatus rv = SECSuccess; CRMFEncryptedValue *encVal; dest->choice = src->choice; rv = cmmf_copy_secitem(poolp, &dest->derValue, &src->derValue); switch (src->choice) { - case cmmfCertificate: - dest->cert.certificate = CERT_DupCertificate(src->cert.certificate); - break; - case cmmfEncryptedCert: - encVal = (poolp == NULL) ? PORT_ZNew(CRMFEncryptedValue) : - PORT_ArenaZNew(poolp, CRMFEncryptedValue); - if (encVal == NULL) { - return SECFailure; - } - rv = crmf_copy_encryptedvalue(poolp, src->cert.encryptedCert, encVal); - if (rv != SECSuccess) { - if (!poolp) { - crmf_destroy_encrypted_value(encVal, PR_TRUE); - } - return rv; - } - dest->cert.encryptedCert = encVal; - break; - default: - rv = SECFailure; + case cmmfCertificate: + dest->cert.certificate = CERT_DupCertificate(src->cert.certificate); + break; + case cmmfEncryptedCert: + encVal = (poolp == NULL) ? PORT_ZNew(CRMFEncryptedValue) : + PORT_ArenaZNew(poolp, CRMFEncryptedValue); + if (encVal == NULL) { + return SECFailure; + } + rv = crmf_copy_encryptedvalue(poolp, src->cert.encryptedCert, encVal); + if (rv != SECSuccess) { + if (!poolp) { + crmf_destroy_encrypted_value(encVal, PR_TRUE); + } + return rv; + } + dest->cert.encryptedCert = encVal; + break; + default: + rv = SECFailure; } return rv; } SECStatus cmmf_CopyCertifiedKeyPair(PLArenaPool *poolp, CMMFCertifiedKeyPair *dest, - CMMFCertifiedKeyPair *src) + CMMFCertifiedKeyPair *src) { SECStatus rv; - rv = cmmf_CopyCertOrEncCert(poolp, &dest->certOrEncCert, - &src->certOrEncCert); + rv = cmmf_CopyCertOrEncCert(poolp, &dest->certOrEncCert, + &src->certOrEncCert); if (rv != SECSuccess) { return rv; } if (src->privateKey != NULL) { - CRMFEncryptedValue *encVal; + CRMFEncryptedValue *encVal; - encVal = (poolp == NULL) ? PORT_ZNew(CRMFEncryptedValue) : - PORT_ArenaZNew(poolp, CRMFEncryptedValue); - if (encVal == NULL) { - return SECFailure; - } - rv = crmf_copy_encryptedvalue(poolp, src->privateKey, - encVal); - if (rv != SECSuccess) { - if (!poolp) { - crmf_destroy_encrypted_value(encVal, PR_TRUE); - } - return rv; - } - dest->privateKey = encVal; + encVal = (poolp == NULL) ? PORT_ZNew(CRMFEncryptedValue) : + PORT_ArenaZNew(poolp, CRMFEncryptedValue); + if (encVal == NULL) { + return SECFailure; + } + rv = crmf_copy_encryptedvalue(poolp, src->privateKey, + encVal); + if (rv != SECSuccess) { + if (!poolp) { + crmf_destroy_encrypted_value(encVal, PR_TRUE); + } + return rv; + } + dest->privateKey = encVal; } - rv = cmmf_copy_secitem(poolp, &dest->derPublicationInfo, - &src->derPublicationInfo); + rv = cmmf_copy_secitem(poolp, &dest->derPublicationInfo, + &src->derPublicationInfo); return rv; } SECStatus cmmf_CopyPKIStatusInfo(PLArenaPool *poolp, CMMFPKIStatusInfo *dest, - CMMFPKIStatusInfo *src) + CMMFPKIStatusInfo *src) { SECStatus rv; - rv = cmmf_copy_secitem (poolp, &dest->status, &src->status); + rv = cmmf_copy_secitem(poolp, &dest->status, &src->status); if (rv != SECSuccess) { return rv; } - rv = cmmf_copy_secitem (poolp, &dest->statusString, &src->statusString); + rv = cmmf_copy_secitem(poolp, &dest->statusString, &src->statusString); if (rv != SECSuccess) { return rv; } - rv = cmmf_copy_secitem (poolp, &dest->failInfo, &src->failInfo); + rv = cmmf_copy_secitem(poolp, &dest->failInfo, &src->failInfo); return rv; } -CERTCertificate* +CERTCertificate * cmmf_CertOrEncCertGetCertificate(CMMFCertOrEncCert *certOrEncCert, - CERTCertDBHandle *certdb) + CERTCertDBHandle *certdb) { - if (certOrEncCert->choice != cmmfCertificate || - certOrEncCert->cert.certificate == NULL) { + if (certOrEncCert->choice != cmmfCertificate || + certOrEncCert->cert.certificate == NULL) { return NULL; } return CERT_NewTempCertificate(certdb, - &certOrEncCert->cert.certificate->derCert, - NULL, PR_FALSE, PR_TRUE); + &certOrEncCert->cert.certificate->derCert, + NULL, PR_FALSE, PR_TRUE); } -SECStatus -cmmf_PKIStatusInfoSetStatus(CMMFPKIStatusInfo *statusInfo, - PLArenaPool *poolp, - CMMFPKIStatus inStatus) +SECStatus +cmmf_PKIStatusInfoSetStatus(CMMFPKIStatusInfo *statusInfo, + PLArenaPool *poolp, + CMMFPKIStatus inStatus) { SECItem *dummy; - - if (inStatus = cmmfNumPKIStatus) { + + if (inStatus < cmmfGranted || inStatus >= cmmfNumPKIStatus) { return SECFailure; } - dummy = SEC_ASN1EncodeInteger(poolp, &statusInfo->status, inStatus); + dummy = SEC_ASN1EncodeInteger(poolp, &statusInfo->status, inStatus); PORT_Assert(dummy == &statusInfo->status); if (dummy != &statusInfo->status) { SECITEM_FreeItem(dummy, PR_TRUE); - return SECFailure; + return SECFailure; } return SECSuccess; } - - diff --git a/security/nss/lib/crmf/servget.c b/security/nss/lib/crmf/servget.c index d19c8290f5f1..c36abfe23828 100644 --- a/security/nss/lib/crmf/servget.c +++ b/security/nss/lib/crmf/servget.c @@ -3,7 +3,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - #include "cmmf.h" #include "cmmfi.h" #include "secitem.h" @@ -20,15 +19,15 @@ CRMF_EncryptedKeyGetChoice(CRMFEncryptedKey *inEncrKey) return inEncrKey->encKeyChoice; } -CRMFEncryptedValue* +CRMFEncryptedValue * CRMF_EncryptedKeyGetEncryptedValue(CRMFEncryptedKey *inEncrKey) { CRMFEncryptedValue *newEncrValue = NULL; - SECStatus rv; + SECStatus rv; PORT_Assert(inEncrKey != NULL); if (inEncrKey == NULL || - CRMF_EncryptedKeyGetChoice(inEncrKey) != crmfEncryptedValueChoice) { + CRMF_EncryptedKeyGetChoice(inEncrKey) != crmfEncryptedValueChoice) { goto loser; } newEncrValue = PORT_ZNew(CRMFEncryptedValue); @@ -36,24 +35,24 @@ CRMF_EncryptedKeyGetEncryptedValue(CRMFEncryptedKey *inEncrKey) goto loser; } rv = crmf_copy_encryptedvalue(NULL, &inEncrKey->value.encryptedValue, - newEncrValue); + newEncrValue); if (rv != SECSuccess) { goto loser; } return newEncrValue; - loser: +loser: if (newEncrValue != NULL) { CRMF_DestroyEncryptedValue(newEncrValue); } return NULL; } -static SECItem* +static SECItem * crmf_get_encvalue_bitstring(SECItem *srcItem) { - SECItem *newItem = NULL; + SECItem *newItem = NULL; SECStatus rv; - + if (srcItem->data == NULL) { return NULL; } @@ -66,14 +65,14 @@ crmf_get_encvalue_bitstring(SECItem *srcItem) goto loser; } return newItem; - loser: +loser: if (newItem != NULL) { SECITEM_FreeItem(newItem, PR_TRUE); } return NULL; } -SECItem* +SECItem * CRMF_EncryptedValueGetEncSymmKey(CRMFEncryptedValue *inEncValue) { if (inEncValue == NULL) { @@ -82,7 +81,7 @@ CRMF_EncryptedValueGetEncSymmKey(CRMFEncryptedValue *inEncValue) return crmf_get_encvalue_bitstring(&inEncValue->encSymmKey); } -SECItem* +SECItem * CRMF_EncryptedValueGetEncValue(CRMFEncryptedValue *inEncrValue) { if (inEncrValue == NULL || inEncrValue->encValue.data == NULL) { @@ -91,12 +90,12 @@ CRMF_EncryptedValueGetEncValue(CRMFEncryptedValue *inEncrValue) return crmf_get_encvalue_bitstring(&inEncrValue->encValue); } -static SECAlgorithmID* +static SECAlgorithmID * crmf_get_encvalue_algid(SECAlgorithmID *srcAlg) { - SECStatus rv; + SECStatus rv; SECAlgorithmID *newAlgID; - + if (srcAlg == NULL) { return NULL; } @@ -107,7 +106,7 @@ crmf_get_encvalue_algid(SECAlgorithmID *srcAlg) return newAlgID; } -SECAlgorithmID* +SECAlgorithmID * CRMF_EncryptedValueGetIntendedAlg(CRMFEncryptedValue *inEncValue) { if (inEncValue == NULL) { @@ -116,7 +115,7 @@ CRMF_EncryptedValueGetIntendedAlg(CRMFEncryptedValue *inEncValue) return crmf_get_encvalue_algid(inEncValue->intendedAlg); } -SECAlgorithmID* +SECAlgorithmID * CRMF_EncryptedValueGetKeyAlg(CRMFEncryptedValue *inEncValue) { if (inEncValue == NULL) { @@ -125,7 +124,7 @@ CRMF_EncryptedValueGetKeyAlg(CRMFEncryptedValue *inEncValue) return crmf_get_encvalue_algid(inEncValue->keyAlg); } -SECAlgorithmID* +SECAlgorithmID * CRMF_EncryptedValueGetSymmAlg(CRMFEncryptedValue *inEncValue) { if (inEncValue == NULL) { @@ -134,7 +133,7 @@ CRMF_EncryptedValueGetSymmAlg(CRMFEncryptedValue *inEncValue) return crmf_get_encvalue_algid(inEncValue->symmAlg); } -SECItem* +SECItem * CRMF_EncryptedValueGetValueHint(CRMFEncryptedValue *inEncValue) { if (inEncValue == NULL || inEncValue->valueHint.data == NULL) { @@ -144,28 +143,28 @@ CRMF_EncryptedValueGetValueHint(CRMFEncryptedValue *inEncValue) } SECStatus -CRMF_PKIArchiveOptionsGetArchiveRemGenPrivKey(CRMFPKIArchiveOptions *inOpt, - PRBool *destVal) +CRMF_PKIArchiveOptionsGetArchiveRemGenPrivKey(CRMFPKIArchiveOptions *inOpt, + PRBool *destVal) { if (inOpt == NULL || destVal == NULL || - CRMF_PKIArchiveOptionsGetOptionType(inOpt) != crmfArchiveRemGenPrivKey){ + CRMF_PKIArchiveOptionsGetOptionType(inOpt) != crmfArchiveRemGenPrivKey) { return SECFailure; } - *destVal = (inOpt->option.archiveRemGenPrivKey.data[0] == hexFalse) - ? PR_FALSE: - PR_TRUE; + *destVal = (inOpt->option.archiveRemGenPrivKey.data[0] == hexFalse) + ? PR_FALSE + : PR_TRUE; return SECSuccess; } - -CRMFEncryptedKey* + +CRMFEncryptedKey * CRMF_PKIArchiveOptionsGetEncryptedPrivKey(CRMFPKIArchiveOptions *inOpts) { CRMFEncryptedKey *newEncrKey = NULL; - SECStatus rv; + SECStatus rv; PORT_Assert(inOpts != NULL); if (inOpts == NULL || - CRMF_PKIArchiveOptionsGetOptionType(inOpts) != crmfEncryptedPrivateKey){ + CRMF_PKIArchiveOptionsGetOptionType(inOpts) != crmfEncryptedPrivateKey) { return NULL; } newEncrKey = PORT_ZNew(CRMFEncryptedKey); @@ -173,24 +172,24 @@ CRMF_PKIArchiveOptionsGetEncryptedPrivKey(CRMFPKIArchiveOptions *inOpts) goto loser; } rv = crmf_copy_encryptedkey(NULL, &inOpts->option.encryptedKey, - newEncrKey); + newEncrKey); if (rv != SECSuccess) { goto loser; } return newEncrKey; - loser: +loser: if (newEncrKey != NULL) { CRMF_DestroyEncryptedKey(newEncrKey); } return NULL; } -SECItem* +SECItem * CRMF_PKIArchiveOptionsGetKeyGenParameters(CRMFPKIArchiveOptions *inOptions) { if (inOptions == NULL || - CRMF_PKIArchiveOptionsGetOptionType(inOptions) != crmfKeyGenParameters || - inOptions->option.keyGenParameters.data == NULL) { + CRMF_PKIArchiveOptionsGetOptionType(inOptions) != crmfKeyGenParameters || + inOptions->option.keyGenParameters.data == NULL) { return NULL; } return SECITEM_DupItem(&inOptions->option.keyGenParameters); @@ -199,7 +198,7 @@ CRMF_PKIArchiveOptionsGetKeyGenParameters(CRMFPKIArchiveOptions *inOptions) CRMFPKIArchiveOptionsType CRMF_PKIArchiveOptionsGetOptionType(CRMFPKIArchiveOptions *inOptions) { - PORT_Assert (inOptions != NULL); + PORT_Assert(inOptions != NULL); if (inOptions == NULL) { return crmfNoArchiveOptions; } @@ -214,30 +213,30 @@ crmf_extract_long_from_item(SECItem *intItem, long *destLong) } SECStatus -CRMF_POPOPrivGetKeySubseqMess(CRMFPOPOPrivKey *inKey, - CRMFSubseqMessOptions *destOpt) +CRMF_POPOPrivGetKeySubseqMess(CRMFPOPOPrivKey *inKey, + CRMFSubseqMessOptions *destOpt) { - long value; + long value; SECStatus rv; PORT_Assert(inKey != NULL); if (inKey == NULL || - inKey->messageChoice != crmfSubsequentMessage) { + inKey->messageChoice != crmfSubsequentMessage) { return SECFailure; } - rv = crmf_extract_long_from_item(&inKey->message.subsequentMessage,&value); + rv = crmf_extract_long_from_item(&inKey->message.subsequentMessage, &value); if (rv != SECSuccess) { return SECFailure; } switch (value) { - case 0: - *destOpt = crmfEncrCert; - break; - case 1: - *destOpt = crmfChallengeResp; - break; - default: - rv = SECFailure; + case 0: + *destOpt = crmfEncrCert; + break; + case 1: + *destOpt = crmfChallengeResp; + break; + default: + rv = SECFailure; } if (rv != SECSuccess) { return rv; @@ -266,24 +265,24 @@ CRMF_POPOPrivKeyGetDHMAC(CRMFPOPOPrivKey *inKey, SECItem *destMAC) } SECStatus -CRMF_POPOPrivKeyGetThisMessage(CRMFPOPOPrivKey *inKey, - SECItem *destString) +CRMF_POPOPrivKeyGetThisMessage(CRMFPOPOPrivKey *inKey, + SECItem *destString) { PORT_Assert(inKey != NULL); - if (inKey == NULL || - inKey->messageChoice != crmfThisMessage) { + if (inKey == NULL || + inKey->messageChoice != crmfThisMessage) { return SECFailure; } - return crmf_make_bitstring_copy(NULL, destString, - &inKey->message.thisMessage); + return crmf_make_bitstring_copy(NULL, destString, + &inKey->message.thisMessage); } -SECAlgorithmID* +SECAlgorithmID * CRMF_POPOSigningKeyGetAlgID(CRMFPOPOSigningKey *inSignKey) { SECAlgorithmID *newAlgId = NULL; - SECStatus rv; + SECStatus rv; PORT_Assert(inSignKey != NULL); if (inSignKey == NULL) { @@ -293,21 +292,21 @@ CRMF_POPOSigningKeyGetAlgID(CRMFPOPOSigningKey *inSignKey) if (newAlgId == NULL) { goto loser; } - rv = SECOID_CopyAlgorithmID(NULL, newAlgId, - inSignKey->algorithmIdentifier); + rv = SECOID_CopyAlgorithmID(NULL, newAlgId, + inSignKey->algorithmIdentifier); if (rv != SECSuccess) { goto loser; } return newAlgId; - loser: +loser: if (newAlgId != NULL) { SECOID_DestroyAlgorithmID(newAlgId, PR_TRUE); } return NULL; } -SECItem* +SECItem * CRMF_POPOSigningKeyGetInput(CRMFPOPOSigningKey *inSignKey) { PORT_Assert(inSignKey != NULL); @@ -317,11 +316,11 @@ CRMF_POPOSigningKeyGetInput(CRMFPOPOSigningKey *inSignKey) return SECITEM_DupItem(&inSignKey->derInput); } -SECItem* +SECItem * CRMF_POPOSigningKeyGetSignature(CRMFPOPOSigningKey *inSignKey) { - SECItem *newSig = NULL; - SECStatus rv; + SECItem *newSig = NULL; + SECStatus rv; PORT_Assert(inSignKey != NULL); if (inSignKey == NULL) { @@ -336,47 +335,48 @@ CRMF_POPOSigningKeyGetSignature(CRMFPOPOSigningKey *inSignKey) goto loser; } return newSig; - loser: +loser: if (newSig != NULL) { SECITEM_FreeItem(newSig, PR_TRUE); } return NULL; } -static SECStatus -crmf_copy_poposigningkey(PLArenaPool *poolp, - CRMFPOPOSigningKey *inPopoSignKey, - CRMFPOPOSigningKey *destPopoSignKey) +static SECStatus +crmf_copy_poposigningkey(PLArenaPool *poolp, + CRMFPOPOSigningKey *inPopoSignKey, + CRMFPOPOSigningKey *destPopoSignKey) { SECStatus rv; - /* We don't support use of the POPOSigningKeyInput, so we'll only + /* We don't support use of the POPOSigningKeyInput, so we'll only * store away the DER encoding. */ if (inPopoSignKey->derInput.data != NULL) { - rv = SECITEM_CopyItem(poolp, &destPopoSignKey->derInput, - &inPopoSignKey->derInput); + rv = SECITEM_CopyItem(poolp, &destPopoSignKey->derInput, + &inPopoSignKey->derInput); } - destPopoSignKey->algorithmIdentifier = (poolp == NULL) ? - PORT_ZNew(SECAlgorithmID) : - PORT_ArenaZNew(poolp, SECAlgorithmID); + destPopoSignKey->algorithmIdentifier = (poolp == NULL) ? + PORT_ZNew(SECAlgorithmID) + : + PORT_ArenaZNew(poolp, SECAlgorithmID); if (destPopoSignKey->algorithmIdentifier == NULL) { goto loser; } rv = SECOID_CopyAlgorithmID(poolp, destPopoSignKey->algorithmIdentifier, - inPopoSignKey->algorithmIdentifier); + inPopoSignKey->algorithmIdentifier); if (rv != SECSuccess) { goto loser; } - - rv = crmf_make_bitstring_copy(poolp, &destPopoSignKey->signature, - &inPopoSignKey->signature); + + rv = crmf_make_bitstring_copy(poolp, &destPopoSignKey->signature, + &inPopoSignKey->signature); if (rv != SECSuccess) { goto loser; } return SECSuccess; - loser: +loser: if (poolp == NULL) { CRMF_DestroyPOPOSigningKey(destPopoSignKey); } @@ -384,28 +384,28 @@ crmf_copy_poposigningkey(PLArenaPool *poolp, } static SECStatus -crmf_copy_popoprivkey(PLArenaPool *poolp, - CRMFPOPOPrivKey *srcPrivKey, - CRMFPOPOPrivKey *destPrivKey) +crmf_copy_popoprivkey(PLArenaPool *poolp, + CRMFPOPOPrivKey *srcPrivKey, + CRMFPOPOPrivKey *destPrivKey) { - SECStatus rv; + SECStatus rv; destPrivKey->messageChoice = srcPrivKey->messageChoice; switch (destPrivKey->messageChoice) { - case crmfThisMessage: - case crmfDHMAC: - /* I've got a union, so taking the address of one, will also give - * me a pointer to the other (eg, message.dhMAC) - */ - rv = crmf_make_bitstring_copy(poolp, &destPrivKey->message.thisMessage, - &srcPrivKey->message.thisMessage); - break; - case crmfSubsequentMessage: - rv = SECITEM_CopyItem(poolp, &destPrivKey->message.subsequentMessage, - &srcPrivKey->message.subsequentMessage); - break; - default: - rv = SECFailure; + case crmfThisMessage: + case crmfDHMAC: + /* I've got a union, so taking the address of one, will also give + * me a pointer to the other (eg, message.dhMAC) + */ + rv = crmf_make_bitstring_copy(poolp, &destPrivKey->message.thisMessage, + &srcPrivKey->message.thisMessage); + break; + case crmfSubsequentMessage: + rv = SECITEM_CopyItem(poolp, &destPrivKey->message.subsequentMessage, + &srcPrivKey->message.subsequentMessage); + break; + default: + rv = SECFailure; } if (rv != SECSuccess && poolp == NULL) { @@ -414,13 +414,13 @@ crmf_copy_popoprivkey(PLArenaPool *poolp, return rv; } -static CRMFProofOfPossession* +static CRMFProofOfPossession * crmf_copy_pop(PLArenaPool *poolp, CRMFProofOfPossession *srcPOP) { CRMFProofOfPossession *newPOP; - SECStatus rv; + SECStatus rv; - /* + /* * Proof Of Possession structures are always part of the Request * message, so there will always be an arena for allocating memory. */ @@ -432,43 +432,43 @@ crmf_copy_pop(PLArenaPool *poolp, CRMFProofOfPossession *srcPOP) return NULL; } switch (srcPOP->popUsed) { - case crmfRAVerified: - newPOP->popChoice.raVerified.data = NULL; - newPOP->popChoice.raVerified.len = 0; - break; - case crmfSignature: - rv = crmf_copy_poposigningkey(poolp, &srcPOP->popChoice.signature, - &newPOP->popChoice.signature); - if (rv != SECSuccess) { - goto loser; - } - break; - case crmfKeyEncipherment: - case crmfKeyAgreement: - /* We've got a union, so a pointer to one, is a pointer to the - * other one. - */ - rv = crmf_copy_popoprivkey(poolp, &srcPOP->popChoice.keyEncipherment, - &newPOP->popChoice.keyEncipherment); - if (rv != SECSuccess) { - goto loser; - } - break; - default: - goto loser; + case crmfRAVerified: + newPOP->popChoice.raVerified.data = NULL; + newPOP->popChoice.raVerified.len = 0; + break; + case crmfSignature: + rv = crmf_copy_poposigningkey(poolp, &srcPOP->popChoice.signature, + &newPOP->popChoice.signature); + if (rv != SECSuccess) { + goto loser; + } + break; + case crmfKeyEncipherment: + case crmfKeyAgreement: + /* We've got a union, so a pointer to one, is a pointer to the + * other one. + */ + rv = crmf_copy_popoprivkey(poolp, &srcPOP->popChoice.keyEncipherment, + &newPOP->popChoice.keyEncipherment); + if (rv != SECSuccess) { + goto loser; + } + break; + default: + goto loser; } newPOP->popUsed = srcPOP->popUsed; return newPOP; - loser: +loser: return NULL; } -static CRMFCertReqMsg* +static CRMFCertReqMsg * crmf_copy_cert_req_msg(CRMFCertReqMsg *srcReqMsg) { CRMFCertReqMsg *newReqMsg; - PLArenaPool *poolp; + PLArenaPool *poolp; poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); if (poolp == NULL) { @@ -494,16 +494,16 @@ crmf_copy_cert_req_msg(CRMFCertReqMsg *srcReqMsg) */ return newReqMsg; - loser: +loser: if (newReqMsg != NULL) { CRMF_DestroyCertReqMsg(newReqMsg); } return NULL; } -CRMFCertReqMsg* +CRMFCertReqMsg * CRMF_CertReqMessagesGetCertReqMsgAtIndex(CRMFCertReqMessages *inReqMsgs, - int index) + int index) { int numMsgs; @@ -533,10 +533,10 @@ CRMF_CertReqMessagesGetNumMessages(CRMFCertReqMessages *inCertReqMsgs) return numMessages; } -CRMFCertRequest* +CRMFCertRequest * CRMF_CertReqMsgGetCertRequest(CRMFCertReqMsg *inCertReqMsg) { - PLArenaPool *poolp = NULL; + PLArenaPool *poolp = NULL; CRMFCertRequest *newCertReq = NULL; PORT_Assert(inCertReqMsg != NULL); @@ -551,7 +551,7 @@ CRMF_CertReqMsgGetCertRequest(CRMFCertReqMsg *inCertReqMsg) } newCertReq->poolp = poolp; return newCertReq; - loser: +loser: if (poolp != NULL) { PORT_FreeArena(poolp, PR_FALSE); } @@ -565,17 +565,17 @@ CRMF_CertReqMsgGetID(CRMFCertReqMsg *inCertReqMsg, long *destID) if (inCertReqMsg == NULL || inCertReqMsg->certReq == NULL) { return SECFailure; } - return crmf_extract_long_from_item(&inCertReqMsg->certReq->certReqId, - destID); + return crmf_extract_long_from_item(&inCertReqMsg->certReq->certReqId, + destID); } SECStatus -CRMF_CertReqMsgGetPOPKeyAgreement(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKey **destKey) +CRMF_CertReqMsgGetPOPKeyAgreement(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKey **destKey) { PORT_Assert(inCertReqMsg != NULL && destKey != NULL); if (inCertReqMsg == NULL || destKey == NULL || - CRMF_CertReqMsgGetPOPType(inCertReqMsg) != crmfKeyAgreement) { + CRMF_CertReqMsgGetPOPType(inCertReqMsg) != crmfKeyAgreement) { return SECFailure; } *destKey = PORT_ZNew(CRMFPOPOPrivKey); @@ -583,38 +583,39 @@ CRMF_CertReqMsgGetPOPKeyAgreement(CRMFCertReqMsg *inCertReqMsg, return SECFailure; } return crmf_copy_popoprivkey(NULL, - &inCertReqMsg->pop->popChoice.keyAgreement, - *destKey); + &inCertReqMsg->pop->popChoice.keyAgreement, + *destKey); } SECStatus -CRMF_CertReqMsgGetPOPKeyEncipherment(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOPrivKey **destKey) +CRMF_CertReqMsgGetPOPKeyEncipherment(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOPrivKey **destKey) { PORT_Assert(inCertReqMsg != NULL && destKey != NULL); if (inCertReqMsg == NULL || destKey == NULL || - CRMF_CertReqMsgGetPOPType(inCertReqMsg) != crmfKeyEncipherment) { + CRMF_CertReqMsgGetPOPType(inCertReqMsg) != crmfKeyEncipherment) { return SECFailure; } *destKey = PORT_ZNew(CRMFPOPOPrivKey); if (*destKey == NULL) { - return SECFailure; + return SECFailure; } return crmf_copy_popoprivkey(NULL, - &inCertReqMsg->pop->popChoice.keyEncipherment, - *destKey); + &inCertReqMsg->pop->popChoice.keyEncipherment, + *destKey); } SECStatus -CRMF_CertReqMsgGetPOPOSigningKey(CRMFCertReqMsg *inCertReqMsg, - CRMFPOPOSigningKey **destKey) +CRMF_CertReqMsgGetPOPOSigningKey(CRMFCertReqMsg *inCertReqMsg, + CRMFPOPOSigningKey **destKey) { CRMFProofOfPossession *pop; PORT_Assert(inCertReqMsg != NULL); - if (inCertReqMsg == NULL) { + if (inCertReqMsg == NULL) { return SECFailure; } - pop = inCertReqMsg->pop;; + pop = inCertReqMsg->pop; + ; if (pop->popUsed != crmfSignature) { return SECFailure; } @@ -622,50 +623,51 @@ CRMF_CertReqMsgGetPOPOSigningKey(CRMFCertReqMsg *inCertReqMsg, if (*destKey == NULL) { return SECFailure; } - return crmf_copy_poposigningkey(NULL,&pop->popChoice.signature, *destKey); + return crmf_copy_poposigningkey(NULL, &pop->popChoice.signature, *destKey); } static SECStatus crmf_copy_name(CERTName *destName, CERTName *srcName) { - PLArenaPool *poolp = NULL; - SECStatus rv; + PLArenaPool *poolp = NULL; + SECStatus rv; - if (destName->arena != NULL) { - poolp = destName->arena; - } else { - poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); - } - if (poolp == NULL) { - return SECFailure; - } - /* Need to do this so that CERT_CopyName doesn't free out - * the arena from underneath us. - */ - destName->arena = NULL; - rv = CERT_CopyName(poolp, destName, srcName); - destName->arena = poolp; - return rv; + if (destName->arena != NULL) { + poolp = destName->arena; + } + else { + poolp = PORT_NewArena(CRMF_DEFAULT_ARENA_SIZE); + } + if (poolp == NULL) { + return SECFailure; + } + /* Need to do this so that CERT_CopyName doesn't free out + * the arena from underneath us. + */ + destName->arena = NULL; + rv = CERT_CopyName(poolp, destName, srcName); + destName->arena = poolp; + return rv; } SECStatus CRMF_CertRequestGetCertTemplateIssuer(CRMFCertRequest *inCertReq, - CERTName *destIssuer) + CERTName *destIssuer) { PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return SECFailure; } if (CRMF_DoesRequestHaveField(inCertReq, crmfIssuer)) { - return crmf_copy_name(destIssuer, - inCertReq->certTemplate.issuer); + return crmf_copy_name(destIssuer, + inCertReq->certTemplate.issuer); } return SECFailure; } -SECStatus +SECStatus CRMF_CertRequestGetCertTemplateIssuerUID(CRMFCertRequest *inCertReq, - SECItem *destIssuerUID) + SECItem *destIssuerUID) { PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { @@ -673,146 +675,145 @@ CRMF_CertRequestGetCertTemplateIssuerUID(CRMFCertRequest *inCertReq, } if (CRMF_DoesRequestHaveField(inCertReq, crmfIssuerUID)) { return crmf_make_bitstring_copy(NULL, destIssuerUID, - &inCertReq->certTemplate.issuerUID); + &inCertReq->certTemplate.issuerUID); } return SECFailure; } SECStatus -CRMF_CertRequestGetCertTemplatePublicKey(CRMFCertRequest *inCertReq, - CERTSubjectPublicKeyInfo *destPublicKey) +CRMF_CertRequestGetCertTemplatePublicKey(CRMFCertRequest *inCertReq, + CERTSubjectPublicKeyInfo *destPublicKey) { - PORT_Assert (inCertReq != NULL); + PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return SECFailure; } if (CRMF_DoesRequestHaveField(inCertReq, crmfPublicKey)) { return SECKEY_CopySubjectPublicKeyInfo(NULL, destPublicKey, - inCertReq->certTemplate.publicKey); + inCertReq->certTemplate.publicKey); } return SECFailure; } SECStatus CRMF_CertRequestGetCertTemplateSerialNumber(CRMFCertRequest *inCertReq, - long *serialNumber) + long *serialNumber) { PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return SECFailure; } if (CRMF_DoesRequestHaveField(inCertReq, crmfSerialNumber)) { - return - crmf_extract_long_from_item(&inCertReq->certTemplate.serialNumber, - serialNumber); + return crmf_extract_long_from_item(&inCertReq->certTemplate.serialNumber, + serialNumber); } return SECFailure; } SECStatus CRMF_CertRequestGetCertTemplateSigningAlg(CRMFCertRequest *inCertReq, - SECAlgorithmID *destAlg) + SECAlgorithmID *destAlg) { PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return SECFailure; } if (CRMF_DoesRequestHaveField(inCertReq, crmfSigningAlg)) { - return SECOID_CopyAlgorithmID(NULL, destAlg, - inCertReq->certTemplate.signingAlg); + return SECOID_CopyAlgorithmID(NULL, destAlg, + inCertReq->certTemplate.signingAlg); } return SECFailure; } -SECStatus +SECStatus CRMF_CertRequestGetCertTemplateSubject(CRMFCertRequest *inCertReq, - CERTName *destSubject) + CERTName *destSubject) { - PORT_Assert(inCertReq != NULL); - if (inCertReq == NULL) { - return SECFailure; - } - if (CRMF_DoesRequestHaveField(inCertReq, crmfSubject)) { - return crmf_copy_name(destSubject, inCertReq->certTemplate.subject); - } - return SECFailure; + PORT_Assert(inCertReq != NULL); + if (inCertReq == NULL) { + return SECFailure; + } + if (CRMF_DoesRequestHaveField(inCertReq, crmfSubject)) { + return crmf_copy_name(destSubject, inCertReq->certTemplate.subject); + } + return SECFailure; } SECStatus CRMF_CertRequestGetCertTemplateSubjectUID(CRMFCertRequest *inCertReq, - SECItem *destSubjectUID) + SECItem *destSubjectUID) { PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return SECFailure; } if (CRMF_DoesRequestHaveField(inCertReq, crmfSubjectUID)) { - return crmf_make_bitstring_copy(NULL, destSubjectUID, - &inCertReq->certTemplate.subjectUID); + return crmf_make_bitstring_copy(NULL, destSubjectUID, + &inCertReq->certTemplate.subjectUID); } return SECFailure; } -SECStatus -CRMF_CertRequestGetCertTemplateVersion(CRMFCertRequest *inCertReq, - long *version) +SECStatus +CRMF_CertRequestGetCertTemplateVersion(CRMFCertRequest *inCertReq, + long *version) { - PORT_Assert (inCertReq != NULL); + PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return SECFailure; } if (CRMF_DoesRequestHaveField(inCertReq, crmfVersion)) { return crmf_extract_long_from_item(&inCertReq->certTemplate.version, - version); - } + version); + } return SECFailure; } static SECStatus -crmf_copy_validity(CRMFGetValidity *destValidity, - CRMFOptionalValidity *src) +crmf_copy_validity(CRMFGetValidity *destValidity, + CRMFOptionalValidity *src) { SECStatus rv; - + destValidity->notBefore = destValidity->notAfter = NULL; if (src->notBefore.data != NULL) { - rv = crmf_create_prtime(&src->notBefore, - &destValidity->notBefore); - if (rv != SECSuccess) { - return rv; - } + rv = crmf_create_prtime(&src->notBefore, + &destValidity->notBefore); + if (rv != SECSuccess) { + return rv; + } } if (src->notAfter.data != NULL) { rv = crmf_create_prtime(&src->notAfter, - &destValidity->notAfter); - if (rv != SECSuccess) { - return rv; - } + &destValidity->notAfter); + if (rv != SECSuccess) { + return rv; + } } return SECSuccess; } -SECStatus +SECStatus CRMF_CertRequestGetCertTemplateValidity(CRMFCertRequest *inCertReq, - CRMFGetValidity *destValidity) + CRMFGetValidity *destValidity) { PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { return SECFailure; } if (CRMF_DoesRequestHaveField(inCertReq, crmfValidity)) { - return crmf_copy_validity(destValidity, - inCertReq->certTemplate.validity); + return crmf_copy_validity(destValidity, + inCertReq->certTemplate.validity); } return SECFailure; } -CRMFControl* +CRMFControl * CRMF_CertRequestGetControlAtIndex(CRMFCertRequest *inCertReq, int index) { CRMFControl *newControl, *srcControl; - int numControls; - SECStatus rv; + int numControls; + SECStatus rv; PORT_Assert(inCertReq != NULL); if (inCertReq == NULL) { @@ -828,63 +829,63 @@ CRMF_CertRequestGetControlAtIndex(CRMFCertRequest *inCertReq, int index) } srcControl = inCertReq->controls[index]; newControl->tag = srcControl->tag; - rv = SECITEM_CopyItem (NULL, &newControl->derTag, &srcControl->derTag); + rv = SECITEM_CopyItem(NULL, &newControl->derTag, &srcControl->derTag); if (rv != SECSuccess) { goto loser; } - rv = SECITEM_CopyItem(NULL, &newControl->derValue, - &srcControl->derValue); + rv = SECITEM_CopyItem(NULL, &newControl->derValue, + &srcControl->derValue); if (rv != SECSuccess) { goto loser; } /* Copy over the PKIArchiveOptions stuff */ switch (srcControl->tag) { - case SEC_OID_PKIX_REGCTRL_REGTOKEN: - case SEC_OID_PKIX_REGCTRL_AUTHENTICATOR: - /* No further processing necessary for these types. */ - rv = SECSuccess; - break; - case SEC_OID_PKIX_REGCTRL_OLD_CERT_ID: - case SEC_OID_PKIX_REGCTRL_PKIPUBINFO: - case SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY: - /* These aren't supported yet, so no post-processing will - * be done at this time. But we don't want to fail in case - * we read in DER that has one of these options. - */ - rv = SECSuccess; - break; - case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: - rv = crmf_copy_pkiarchiveoptions(NULL, - &newControl->value.archiveOptions, - &srcControl->value.archiveOptions); - break; - default: - rv = SECFailure; + case SEC_OID_PKIX_REGCTRL_REGTOKEN: + case SEC_OID_PKIX_REGCTRL_AUTHENTICATOR: + /* No further processing necessary for these types. */ + rv = SECSuccess; + break; + case SEC_OID_PKIX_REGCTRL_OLD_CERT_ID: + case SEC_OID_PKIX_REGCTRL_PKIPUBINFO: + case SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY: + /* These aren't supported yet, so no post-processing will + * be done at this time. But we don't want to fail in case + * we read in DER that has one of these options. + */ + rv = SECSuccess; + break; + case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: + rv = crmf_copy_pkiarchiveoptions(NULL, + &newControl->value.archiveOptions, + &srcControl->value.archiveOptions); + break; + default: + rv = SECFailure; } if (rv != SECSuccess) { goto loser; } return newControl; - loser: +loser: if (newControl != NULL) { CRMF_DestroyControl(newControl); } return NULL; } -static SECItem* +static SECItem * crmf_copy_control_value(CRMFControl *inControl) { return SECITEM_DupItem(&inControl->derValue); } -SECItem* +SECItem * CRMF_ControlGetAuthenticatorControlValue(CRMFControl *inControl) { - PORT_Assert (inControl!= NULL); + PORT_Assert(inControl != NULL); if (inControl == NULL || - CRMF_ControlGetControlType(inControl) != crmfAuthenticatorControl) { + CRMF_ControlGetControlType(inControl) != crmfAuthenticatorControl) { return NULL; } return crmf_copy_control_value(inControl); @@ -897,31 +898,31 @@ CRMF_ControlGetControlType(CRMFControl *inControl) PORT_Assert(inControl != NULL); switch (inControl->tag) { - case SEC_OID_PKIX_REGCTRL_REGTOKEN: - retType = crmfRegTokenControl; - break; - case SEC_OID_PKIX_REGCTRL_AUTHENTICATOR: - retType = crmfAuthenticatorControl; - break; - case SEC_OID_PKIX_REGCTRL_PKIPUBINFO: - retType = crmfPKIPublicationInfoControl; - break; - case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: - retType = crmfPKIArchiveOptionsControl; - break; - case SEC_OID_PKIX_REGCTRL_OLD_CERT_ID: - retType = crmfOldCertIDControl; - break; - case SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY: - retType = crmfProtocolEncrKeyControl; - break; - default: - retType = crmfNoControl; + case SEC_OID_PKIX_REGCTRL_REGTOKEN: + retType = crmfRegTokenControl; + break; + case SEC_OID_PKIX_REGCTRL_AUTHENTICATOR: + retType = crmfAuthenticatorControl; + break; + case SEC_OID_PKIX_REGCTRL_PKIPUBINFO: + retType = crmfPKIPublicationInfoControl; + break; + case SEC_OID_PKIX_REGCTRL_PKI_ARCH_OPTIONS: + retType = crmfPKIArchiveOptionsControl; + break; + case SEC_OID_PKIX_REGCTRL_OLD_CERT_ID: + retType = crmfOldCertIDControl; + break; + case SEC_OID_PKIX_REGCTRL_PROTOCOL_ENC_KEY: + retType = crmfProtocolEncrKeyControl; + break; + default: + retType = crmfNoControl; } return retType; } -CRMFPKIArchiveOptions* +CRMFPKIArchiveOptions * CRMF_ControlGetPKIArchiveOptions(CRMFControl *inControl) { CRMFPKIArchiveOptions *newOpt = NULL; @@ -929,40 +930,41 @@ CRMF_ControlGetPKIArchiveOptions(CRMFControl *inControl) PORT_Assert(inControl != NULL); if (inControl == NULL || - CRMF_ControlGetControlType(inControl) != crmfPKIArchiveOptionsControl){ + CRMF_ControlGetControlType(inControl) != crmfPKIArchiveOptionsControl) { goto loser; } newOpt = PORT_ZNew(CRMFPKIArchiveOptions); if (newOpt == NULL) { goto loser; } - rv = crmf_copy_pkiarchiveoptions(NULL, newOpt, - &inControl->value.archiveOptions); + rv = crmf_copy_pkiarchiveoptions(NULL, newOpt, + &inControl->value.archiveOptions); if (rv != SECSuccess) { goto loser; } - loser: +loser: if (newOpt != NULL) { CRMF_DestroyPKIArchiveOptions(newOpt); } return NULL; } -SECItem* +SECItem * CRMF_ControlGetRegTokenControlValue(CRMFControl *inControl) { PORT_Assert(inControl != NULL); if (inControl == NULL || - CRMF_ControlGetControlType(inControl) != crmfRegTokenControl) { + CRMF_ControlGetControlType(inControl) != crmfRegTokenControl) { return NULL; } - return crmf_copy_control_value(inControl);; + return crmf_copy_control_value(inControl); + ; } -CRMFCertExtension* +CRMFCertExtension * CRMF_CertRequestGetExtensionAtIndex(CRMFCertRequest *inCertReq, - int index) + int index) { int numExtensions; @@ -971,8 +973,6 @@ CRMF_CertRequestGetExtensionAtIndex(CRMFCertRequest *inCertReq, if (index >= numExtensions || index < 0) { return NULL; } - return - crmf_copy_cert_extension(NULL, - inCertReq->certTemplate.extensions[index]); + return crmf_copy_cert_extension(NULL, + inCertReq->certTemplate.extensions[index]); } - diff --git a/security/nss/lib/cryptohi/cryptohi.h b/security/nss/lib/cryptohi/cryptohi.h index 6661b6644267..f658daa9eff9 100644 --- a/security/nss/lib/cryptohi/cryptohi.h +++ b/security/nss/lib/cryptohi/cryptohi.h @@ -17,10 +17,8 @@ #include "keyt.h" #include "certt.h" - SEC_BEGIN_PROTOS - /****************************************/ /* ** DER encode/decode (EC)DSA signatures @@ -39,14 +37,14 @@ extern SECItem *DSAU_DecodeDerSig(const SECItem *item); * on the size of q or the EC key used for signing. * * We can reuse the DSAU_EncodeDerSig interface to DER encode - * raw ECDSA signature keeping in mind that the length of r + * raw ECDSA signature keeping in mind that the length of r * is the same as that of s and exactly half of src->len. * * For decoding, we need to pass the length of the desired * raw signature (twice the key size) explicitly. */ -extern SECStatus DSAU_EncodeDerSigWithLen(SECItem *dest, SECItem *src, - unsigned int len); +extern SECStatus DSAU_EncodeDerSigWithLen(SECItem *dest, SECItem *src, + unsigned int len); extern SECItem *DSAU_DecodeDerSigToLen(const SECItem *item, unsigned int len); /****************************************/ @@ -81,7 +79,7 @@ extern SECStatus SGN_Begin(SGNContext *cx); ** "inputLen" the length of the input data */ extern SECStatus SGN_Update(SGNContext *cx, const unsigned char *input, - unsigned int inputLen); + unsigned int inputLen); /* ** Finish the signature process. Use either k0 or k1 to sign the data @@ -100,12 +98,12 @@ extern SECStatus SGN_End(SGNContext *cx, SECItem *result); ** "buf" the input data to sign ** "len" the amount of data to sign ** "pk" the private key to encrypt with -** "algid" the signature/hash algorithm to sign with +** "algid" the signature/hash algorithm to sign with ** (must be compatible with the key type). */ extern SECStatus SEC_SignData(SECItem *result, - const unsigned char *buf, int len, - SECKEYPrivateKey *pk, SECOidTag algid); + const unsigned char *buf, int len, + SECKEYPrivateKey *pk, SECOidTag algid); /* ** Sign a pre-digested block of data using private key encryption, encoding @@ -116,7 +114,7 @@ extern SECStatus SEC_SignData(SECItem *result, ** "algtag" The algorithm tag to encode (need for RSA only) */ extern SECStatus SGN_Digest(SECKEYPrivateKey *privKey, - SECOidTag algtag, SECItem *result, SECItem *digest); + SECOidTag algtag, SECItem *result, SECItem *digest); /* ** DER sign a single block of data using private key encryption and the @@ -130,8 +128,8 @@ extern SECStatus SGN_Digest(SECKEYPrivateKey *privKey, ** "pk" the private key to encrypt with */ extern SECStatus SEC_DerSignData(PLArenaPool *arena, SECItem *result, - const unsigned char *buf, int len, - SECKEYPrivateKey *pk, SECOidTag algid); + const unsigned char *buf, int len, + SECKEYPrivateKey *pk, SECOidTag algid); /* ** Destroy a signed-data object. @@ -155,18 +153,18 @@ extern SECOidTag SEC_GetSignatureAlgorithmOidTag(KeyType keyType, /* ** Create a signature verification context. This version is deprecated, -** This function is deprecated. Use VFY_CreateContextDirect or +** This function is deprecated. Use VFY_CreateContextDirect or ** VFY_CreateContextWithAlgorithmID instead. ** "key" the public key to verify with ** "sig" the encrypted signature data if sig is NULL then ** VFY_EndWithSignature must be called with the correct signature at ** the end of the processing. -** "sigAlg" specifies the signing algorithm to use (including the +** "sigAlg" specifies the signing algorithm to use (including the ** hash algorthim). This must match the key type. ** "wincx" void pointer to the window context */ extern VFYContext *VFY_CreateContext(SECKEYPublicKey *key, SECItem *sig, - SECOidTag sigAlg, void *wincx); + SECOidTag sigAlg, void *wincx); /* ** Create a signature verification context. ** "key" the public key to verify with @@ -174,9 +172,9 @@ extern VFYContext *VFY_CreateContext(SECKEYPublicKey *key, SECItem *sig, ** VFY_EndWithSignature must be called with the correct signature at ** the end of the processing. ** "pubkAlg" specifies the cryptographic signing algorithm to use (the -** raw algorithm without any hash specified. This must match the key +** raw algorithm without any hash specified. This must match the key ** type. -** "hashAlg" specifies the hashing algorithm used. If the key is an +** "hashAlg" specifies the hashing algorithm used. If the key is an ** RSA key, and sig is not NULL, then hashAlg can be SEC_OID_UNKNOWN. ** the hash is selected from data in the sig. ** "hash" optional pointer to return the actual hash algorithm used. @@ -186,10 +184,10 @@ extern VFYContext *VFY_CreateContext(SECKEYPublicKey *key, SECItem *sig, ** "wincx" void pointer to the window context */ extern VFYContext *VFY_CreateContextDirect(const SECKEYPublicKey *key, - const SECItem *sig, - SECOidTag pubkAlg, - SECOidTag hashAlg, - SECOidTag *hash, void *wincx); + const SECItem *sig, + SECOidTag pubkAlg, + SECOidTag hashAlg, + SECOidTag *hash, void *wincx); /* ** Create a signature verification context from a algorithm ID. ** "key" the public key to verify with @@ -198,15 +196,15 @@ extern VFYContext *VFY_CreateContextDirect(const SECKEYPublicKey *key, ** the end of the processing. ** "algid" specifies the signing algorithm and parameters to use. ** This must match the key type. -** "hash" optional pointer to return the oid of the actual hash used in +** "hash" optional pointer to return the oid of the actual hash used in ** the signature. If this value is NULL no, hash oid is returned. ** "wincx" void pointer to the window context */ -extern VFYContext *VFY_CreateContextWithAlgorithmID(const SECKEYPublicKey *key, - const SECItem *sig, - const SECAlgorithmID *algid, - SECOidTag *hash, - void *wincx); +extern VFYContext *VFY_CreateContextWithAlgorithmID(const SECKEYPublicKey *key, + const SECItem *sig, + const SECAlgorithmID *algid, + SECOidTag *hash, + void *wincx); /* ** Destroy a verification-context object. @@ -226,7 +224,7 @@ extern SECStatus VFY_Begin(VFYContext *cx); ** "inputLen" the amount of input data */ extern SECStatus VFY_Update(VFYContext *cx, const unsigned char *input, - unsigned int inputLen); + unsigned int inputLen); /* ** Finish the verification process. The return value is a status which @@ -243,19 +241,18 @@ extern SECStatus VFY_End(VFYContext *cx); ** returned. Otherwise, SECFailure is returned and the error code found ** using PORT_GetError() indicates what failure occurred. If signature is ** supplied the verification uses this signature to verify, otherwise the -** signature passed in VFY_CreateContext() is used. +** signature passed in VFY_CreateContext() is used. ** VFY_EndWithSignature(cx,NULL); is identical to VFY_End(cx);. ** "cx" the context ** "sig" the encrypted signature data */ extern SECStatus VFY_EndWithSignature(VFYContext *cx, SECItem *sig); - /* ** Verify the signature on a block of data for which we already have ** the digest. The signature data is an RSA private key encrypted ** block of data formatted according to PKCS#1. -** This function is deprecated. Use VFY_VerifyDigestDirect or +** This function is deprecated. Use VFY_VerifyDigestDirect or ** VFY_VerifyDigestWithAlgorithmID instead. ** "dig" the digest ** "key" the public key to check the signature with @@ -265,7 +262,7 @@ extern SECStatus VFY_EndWithSignature(VFYContext *cx, SECItem *sig); ** "wincx" void pointer to the window context **/ extern SECStatus VFY_VerifyDigest(SECItem *dig, SECKEYPublicKey *key, - SECItem *sig, SECOidTag sigAlg, void *wincx); + SECItem *sig, SECOidTag sigAlg, void *wincx); /* ** Verify the signature on a block of data for which we already have ** the digest. The signature data is an RSA private key encrypted @@ -274,15 +271,15 @@ extern SECStatus VFY_VerifyDigest(SECItem *dig, SECKEYPublicKey *key, ** "key" the public key to check the signature with ** "sig" the encrypted signature data ** "pubkAlg" specifies the cryptographic signing algorithm to use (the -** raw algorithm without any hash specified. This must match the key +** raw algorithm without any hash specified. This must match the key ** type. ** "hashAlg" specifies the hashing algorithm used. ** "wincx" void pointer to the window context **/ -extern SECStatus VFY_VerifyDigestDirect(const SECItem *dig, - const SECKEYPublicKey *key, - const SECItem *sig, SECOidTag pubkAlg, - SECOidTag hashAlg, void *wincx); +extern SECStatus VFY_VerifyDigestDirect(const SECItem *dig, + const SECKEYPublicKey *key, + const SECItem *sig, SECOidTag pubkAlg, + SECOidTag hashAlg, void *wincx); /* ** Verify the signature on a block of data for which we already have ** the digest. The signature data is an RSA private key encrypted @@ -297,15 +294,15 @@ extern SECStatus VFY_VerifyDigestDirect(const SECItem *dig, ** not set to SEC_OID_UNKNOWN, it must match the hash of the signature. ** "wincx" void pointer to the window context */ -extern SECStatus VFY_VerifyDigestWithAlgorithmID(const SECItem *dig, - const SECKEYPublicKey *key, const SECItem *sig, - const SECAlgorithmID *algid, SECOidTag hash, - void *wincx); +extern SECStatus VFY_VerifyDigestWithAlgorithmID(const SECItem *dig, + const SECKEYPublicKey *key, const SECItem *sig, + const SECAlgorithmID *algid, SECOidTag hash, + void *wincx); /* ** Verify the signature on a block of data. The signature data is an RSA ** private key encrypted block of data formatted according to PKCS#1. -** This function is deprecated. Use VFY_VerifyDataDirect or +** This function is deprecated. Use VFY_VerifyDataDirect or ** VFY_VerifyDataWithAlgorithmID instead. ** "buf" the input data ** "len" the length of the input data @@ -316,8 +313,8 @@ extern SECStatus VFY_VerifyDigestWithAlgorithmID(const SECItem *dig, ** "wincx" void pointer to the window context */ extern SECStatus VFY_VerifyData(const unsigned char *buf, int len, - const SECKEYPublicKey *key, const SECItem *sig, - SECOidTag sigAlg, void *wincx); + const SECKEYPublicKey *key, const SECItem *sig, + SECOidTag sigAlg, void *wincx); /* ** Verify the signature on a block of data. The signature data is an RSA ** private key encrypted block of data formatted according to PKCS#1. @@ -326,9 +323,9 @@ extern SECStatus VFY_VerifyData(const unsigned char *buf, int len, ** "key" the public key to check the signature with ** "sig" the encrypted signature data ** "pubkAlg" specifies the cryptographic signing algorithm to use (the -** raw algorithm without any hash specified. This must match the key +** raw algorithm without any hash specified. This must match the key ** type. -** "hashAlg" specifies the hashing algorithm used. If the key is an +** "hashAlg" specifies the hashing algorithm used. If the key is an ** RSA key, and sig is not NULL, then hashAlg can be SEC_OID_UNKNOWN. ** the hash is selected from data in the sig. ** "hash" optional pointer to return the actual hash algorithm used. @@ -338,10 +335,10 @@ extern SECStatus VFY_VerifyData(const unsigned char *buf, int len, ** "wincx" void pointer to the window context */ extern SECStatus VFY_VerifyDataDirect(const unsigned char *buf, int len, - const SECKEYPublicKey *key, - const SECItem *sig, - SECOidTag pubkAlg, SECOidTag hashAlg, - SECOidTag *hash, void *wincx); + const SECKEYPublicKey *key, + const SECItem *sig, + SECOidTag pubkAlg, SECOidTag hashAlg, + SECOidTag *hash, void *wincx); /* ** Verify the signature on a block of data. The signature data is an RSA @@ -352,16 +349,15 @@ extern SECStatus VFY_VerifyDataDirect(const unsigned char *buf, int len, ** "sig" the encrypted signature data ** "algid" specifies the signing algorithm and parameters to use. ** This must match the key type. -** "hash" optional pointer to return the oid of the actual hash used in +** "hash" optional pointer to return the oid of the actual hash used in ** the signature. If this value is NULL no, hash oid is returned. ** "wincx" void pointer to the window context */ -extern SECStatus VFY_VerifyDataWithAlgorithmID(const unsigned char *buf, - int len, const SECKEYPublicKey *key, - const SECItem *sig, - const SECAlgorithmID *algid, SECOidTag *hash, - void *wincx); - +extern SECStatus VFY_VerifyDataWithAlgorithmID(const unsigned char *buf, + int len, const SECKEYPublicKey *key, + const SECItem *sig, + const SECAlgorithmID *algid, SECOidTag *hash, + void *wincx); SEC_END_PROTOS diff --git a/security/nss/lib/cryptohi/cryptoht.h b/security/nss/lib/cryptohi/cryptoht.h index aca4899590c3..5780bf47ae6a 100644 --- a/security/nss/lib/cryptohi/cryptoht.h +++ b/security/nss/lib/cryptohi/cryptoht.h @@ -11,5 +11,4 @@ typedef struct SGNContextStr SGNContext; typedef struct VFYContextStr VFYContext; - #endif /* _CRYPTOHT_H_ */ diff --git a/security/nss/lib/cryptohi/dsautil.c b/security/nss/lib/cryptohi/dsautil.c index 5606379df4e4..db397dfd5f38 100644 --- a/security/nss/lib/cryptohi/dsautil.c +++ b/security/nss/lib/cryptohi/dsautil.c @@ -7,7 +7,7 @@ #include "prerr.h" #ifndef DSA1_SUBPRIME_LEN -#define DSA1_SUBPRIME_LEN 20 /* bytes */ +#define DSA1_SUBPRIME_LEN 20 /* bytes */ #endif typedef struct { @@ -16,16 +16,16 @@ typedef struct { } DSA_ASN1Signature; const SEC_ASN1Template DSA_SignatureTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(DSA_ASN1Signature) }, - { SEC_ASN1_INTEGER, offsetof(DSA_ASN1Signature,r) }, - { SEC_ASN1_INTEGER, offsetof(DSA_ASN1Signature,s) }, - { 0, } -}; + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(DSA_ASN1Signature) }, + { SEC_ASN1_INTEGER, offsetof(DSA_ASN1Signature, r) }, + { SEC_ASN1_INTEGER, offsetof(DSA_ASN1Signature, s) }, + { 0 } + }; /* Input is variable length multi-byte integer, MSB first (big endian). -** Most signficant bit of first byte is NOT treated as a sign bit. -** May be one or more leading bytes of zeros. +** Most signficant bit of first byte is NOT treated as a sign bit. +** May be one or more leading bytes of zeros. ** Output is variable length multi-byte integer, MSB first (big endian). ** Most significant bit of first byte will be zero (positive sign bit) ** No more than one leading zero byte. @@ -37,21 +37,21 @@ DSAU_ConvertUnsignedToSigned(SECItem *dest, SECItem *src) { unsigned char *pSrc = src->data; unsigned char *pDst = dest->data; - unsigned int cntSrc = src->len; + unsigned int cntSrc = src->len; /* skip any leading zeros. */ - while (cntSrc && !(*pSrc)) { - pSrc++; - cntSrc--; + while (cntSrc && !(*pSrc)) { + pSrc++; + cntSrc--; } if (!cntSrc) { - *pDst = 0; - dest->len = 1; - return; + *pDst = 0; + dest->len = 1; + return; } if (*pSrc & 0x80) - *pDst++ = 0; + *pDst++ = 0; PORT_Memcpy(pDst, pSrc, cntSrc); dest->len = (pDst - dest->data) + cntSrc; @@ -71,27 +71,27 @@ DSAU_ConvertSignedToFixedUnsigned(SECItem *dest, SECItem *src) { unsigned char *pSrc = src->data; unsigned char *pDst = dest->data; - unsigned int cntSrc = src->len; - unsigned int cntDst = dest->len; - int zCount = cntDst - cntSrc; + unsigned int cntSrc = src->len; + unsigned int cntDst = dest->len; + int zCount = cntDst - cntSrc; if (zCount > 0) { - PORT_Memset(pDst, 0, zCount); - PORT_Memcpy(pDst + zCount, pSrc, cntSrc); - return SECSuccess; + PORT_Memset(pDst, 0, zCount); + PORT_Memcpy(pDst + zCount, pSrc, cntSrc); + return SECSuccess; } if (zCount <= 0) { - /* Source is longer than destination. Check for leading zeros. */ - while (zCount++ < 0) { - if (*pSrc++ != 0) - goto loser; - } + /* Source is longer than destination. Check for leading zeros. */ + while (zCount++ < 0) { + if (*pSrc++ != 0) + goto loser; + } } PORT_Memcpy(pDst, pSrc, cntDst); return SECSuccess; loser: - PORT_SetError( PR_INVALID_ARGUMENT_ERROR ); + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; } @@ -101,52 +101,56 @@ loser: static SECStatus common_EncodeDerSig(SECItem *dest, SECItem *src) { - SECItem * item; - SECItem srcItem; + SECItem *item; + SECItem srcItem; DSA_ASN1Signature sig; - unsigned char *signedR; - unsigned char *signedS; + unsigned char *signedR; + unsigned char *signedS; unsigned int len; /* Allocate memory with room for an extra byte that * may be required if the top bit in the first byte * is already set. */ - len = src->len/2; - signedR = (unsigned char *) PORT_Alloc(len + 1); - if (!signedR) return SECFailure; - signedS = (unsigned char *) PORT_ZAlloc(len + 1); + len = src->len / 2; + signedR = (unsigned char *)PORT_Alloc(len + 1); + if (!signedR) + return SECFailure; + signedS = (unsigned char *)PORT_ZAlloc(len + 1); if (!signedS) { - if (signedR) PORT_Free(signedR); - return SECFailure; + if (signedR) + PORT_Free(signedR); + return SECFailure; } PORT_Memset(&sig, 0, sizeof(sig)); /* Must convert r and s from "unsigned" integers to "signed" integers. ** If the high order bit of the first byte (MSB) is 1, then must - ** prepend with leading zero. + ** prepend with leading zero. ** Must remove all but one leading zero byte from numbers. */ sig.r.type = siUnsignedInteger; sig.r.data = signedR; - sig.r.len = sizeof signedR; + sig.r.len = sizeof signedR; sig.s.type = siUnsignedInteger; sig.s.data = signedS; - sig.s.len = sizeof signedR; + sig.s.len = sizeof signedR; srcItem.data = src->data; - srcItem.len = len; + srcItem.len = len; DSAU_ConvertUnsignedToSigned(&sig.r, &srcItem); srcItem.data += len; DSAU_ConvertUnsignedToSigned(&sig.s, &srcItem); item = SEC_ASN1EncodeItem(NULL, dest, &sig, DSA_SignatureTemplate); - if (signedR) PORT_Free(signedR); - if (signedS) PORT_Free(signedS); + if (signedR) + PORT_Free(signedR); + if (signedS) + PORT_Free(signedS); if (item == NULL) - return SECFailure; + return SECFailure; /* XXX leak item? */ return SECSuccess; @@ -161,54 +165,54 @@ common_EncodeDerSig(SECItem *dest, SECItem *src) static SECItem * common_DecodeDerSig(const SECItem *item, unsigned int len) { - SECItem * result = NULL; - SECStatus status; + SECItem *result = NULL; + SECStatus status; DSA_ASN1Signature sig; - SECItem dst; + SECItem dst; PORT_Memset(&sig, 0, sizeof(sig)); result = PORT_ZNew(SECItem); if (result == NULL) - goto loser; + goto loser; - result->len = 2 * len; - result->data = (unsigned char*)PORT_Alloc(2 * len); + result->len = 2 * len; + result->data = (unsigned char *)PORT_Alloc(2 * len); if (result->data == NULL) - goto loser; + goto loser; sig.r.type = siUnsignedInteger; sig.s.type = siUnsignedInteger; status = SEC_ASN1DecodeItem(NULL, &sig, DSA_SignatureTemplate, item); if (status != SECSuccess) - goto loser; + goto loser; - /* Convert sig.r and sig.s from variable length signed integers to + /* Convert sig.r and sig.s from variable length signed integers to ** fixed length unsigned integers. */ dst.data = result->data; - dst.len = len; + dst.len = len; status = DSAU_ConvertSignedToFixedUnsigned(&dst, &sig.r); if (status != SECSuccess) - goto loser; + goto loser; dst.data += len; status = DSAU_ConvertSignedToFixedUnsigned(&dst, &sig.s); if (status != SECSuccess) - goto loser; + goto loser; done: if (sig.r.data != NULL) - PORT_Free(sig.r.data); + PORT_Free(sig.r.data); if (sig.s.data != NULL) - PORT_Free(sig.s.data); + PORT_Free(sig.s.data); return result; loser: if (result != NULL) { - SECITEM_FreeItem(result, PR_TRUE); - result = NULL; + SECITEM_FreeItem(result, PR_TRUE); + result = NULL; } goto done; } @@ -221,8 +225,8 @@ DSAU_EncodeDerSig(SECItem *dest, SECItem *src) { PORT_Assert(src->len == 2 * DSA1_SUBPRIME_LEN); if (src->len != 2 * DSA1_SUBPRIME_LEN) { - PORT_SetError( PR_INVALID_ARGUMENT_ERROR ); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } return common_EncodeDerSig(dest, src); @@ -237,8 +241,8 @@ DSAU_EncodeDerSigWithLen(SECItem *dest, SECItem *src, unsigned int len) PORT_Assert((src->len == len) && (len % 2 == 0)); if ((src->len != len) || (src->len % 2 != 0)) { - PORT_SetError( PR_INVALID_ARGUMENT_ERROR ); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } return common_EncodeDerSig(dest, src); @@ -263,5 +267,5 @@ DSAU_DecodeDerSig(const SECItem *item) SECItem * DSAU_DecodeDerSigToLen(const SECItem *item, unsigned int len) { - return common_DecodeDerSig(item, len/2); + return common_DecodeDerSig(item, len / 2); } diff --git a/security/nss/lib/cryptohi/keyhi.h b/security/nss/lib/cryptohi/keyhi.h index 0ed3698ebf2d..180990049ba0 100644 --- a/security/nss/lib/cryptohi/keyhi.h +++ b/security/nss/lib/cryptohi/keyhi.h @@ -16,7 +16,6 @@ SEC_BEGIN_PROTOS - /* ** Destroy a subject-public-key-info object. */ @@ -27,15 +26,15 @@ extern void SECKEY_DestroySubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki); ** appropriately (memory is allocated for each of the sub objects). */ extern SECStatus SECKEY_CopySubjectPublicKeyInfo(PLArenaPool *arena, - CERTSubjectPublicKeyInfo *dst, - CERTSubjectPublicKeyInfo *src); + CERTSubjectPublicKeyInfo *dst, + CERTSubjectPublicKeyInfo *src); /* ** Update the PQG parameters for a cert's public key. ** Only done for DSA certs */ extern SECStatus -SECKEY_UpdateCertPQG(CERTCertificate * subjectCert); +SECKEY_UpdateCertPQG(CERTCertificate *subjectCert); /* ** Return the number of bits in the provided big integer. This assumes that the @@ -77,19 +76,19 @@ extern SECKEYPublicKey *SECKEY_ConvertToPublicKey(SECKEYPrivateKey *privateKey); * create a new RSA key pair. The private Key is returned... */ SECKEYPrivateKey *SECKEY_CreateRSAPrivateKey(int keySizeInBits, - SECKEYPublicKey **pubk, void *cx); - + SECKEYPublicKey **pubk, void *cx); + /* * create a new DH key pair. The private Key is returned... */ SECKEYPrivateKey *SECKEY_CreateDHPrivateKey(SECKEYDHParams *param, - SECKEYPublicKey **pubk, void *cx); + SECKEYPublicKey **pubk, void *cx); /* * create a new EC key pair. The private Key is returned... */ SECKEYPrivateKey *SECKEY_CreateECPrivateKey(SECKEYECParams *param, - SECKEYPublicKey **pubk, void *cx); + SECKEYPublicKey **pubk, void *cx); /* ** Create a subject-public-key-info based on a public key. @@ -103,11 +102,11 @@ SECKEY_CreateSubjectPublicKeyInfo(const SECKEYPublicKey *k); */ extern CERTSubjectPublicKeyInfo * SECKEY_ConvertAndDecodePublicKeyAndChallenge(char *pkacstr, char *challenge, - void *cx); + void *cx); /* ** Encode a CERTSubjectPublicKeyInfo structure. into a -** DER encoded subject public key info. +** DER encoded subject public key info. */ SECItem * SECKEY_EncodeDERSubjectPublicKeyInfo(const SECKEYPublicKey *pubk); @@ -139,7 +138,6 @@ SECKEY_ExtractPublicKey(const CERTSubjectPublicKeyInfo *); */ extern void SECKEY_DestroyPrivateKey(SECKEYPrivateKey *key); - /* ** Destroy a public key object. ** "key" the object @@ -147,54 +145,54 @@ extern void SECKEY_DestroyPrivateKey(SECKEYPrivateKey *key); extern void SECKEY_DestroyPublicKey(SECKEYPublicKey *key); /* Destroy and zero out a private key info structure. for now this - * function zero's out memory allocated in an arena for the key - * since PORT_FreeArena does not currently do this. + * function zero's out memory allocated in an arena for the key + * since PORT_FreeArena does not currently do this. * - * NOTE -- If a private key info is allocated in an arena, one should - * not call this function with freeit = PR_FALSE. The function should - * destroy the arena. + * NOTE -- If a private key info is allocated in an arena, one should + * not call this function with freeit = PR_FALSE. The function should + * destroy the arena. */ extern void SECKEY_DestroyPrivateKeyInfo(SECKEYPrivateKeyInfo *pvk, PRBool freeit); /* Destroy and zero out an encrypted private key info. * - * NOTE -- If a encrypted private key info is allocated in an arena, one should - * not call this function with freeit = PR_FALSE. The function should - * destroy the arena. + * NOTE -- If a encrypted private key info is allocated in an arena, one should + * not call this function with freeit = PR_FALSE. The function should + * destroy the arena. */ extern void SECKEY_DestroyEncryptedPrivateKeyInfo(SECKEYEncryptedPrivateKeyInfo *epki, - PRBool freeit); + PRBool freeit); -/* Copy private key info structure. +/* Copy private key info structure. * poolp is the arena into which the contents of from is to be copied. * NULL is a valid entry. * to is the destination private key info * from is the source private key info - * if either from or to is NULL or an error occurs, SECFailure is + * if either from or to is NULL or an error occurs, SECFailure is * returned. otherwise, SECSuccess is returned. */ extern SECStatus SECKEY_CopyPrivateKeyInfo(PLArenaPool *poolp, - SECKEYPrivateKeyInfo *to, - const SECKEYPrivateKeyInfo *from); + SECKEYPrivateKeyInfo *to, + const SECKEYPrivateKeyInfo *from); extern SECStatus -SECKEY_CacheStaticFlags(SECKEYPrivateKey* key); +SECKEY_CacheStaticFlags(SECKEYPrivateKey *key); -/* Copy encrypted private key info structure. +/* Copy encrypted private key info structure. * poolp is the arena into which the contents of from is to be copied. * NULL is a valid entry. * to is the destination encrypted private key info * from is the source encrypted private key info - * if either from or to is NULL or an error occurs, SECFailure is + * if either from or to is NULL or an error occurs, SECFailure is * returned. otherwise, SECSuccess is returned. */ extern SECStatus SECKEY_CopyEncryptedPrivateKeyInfo(PLArenaPool *poolp, - SECKEYEncryptedPrivateKeyInfo *to, - const SECKEYEncryptedPrivateKeyInfo *from); + SECKEYEncryptedPrivateKeyInfo *to, + const SECKEYEncryptedPrivateKeyInfo *from); /* * Accessor functions for key type of public and private keys. */ @@ -205,10 +203,10 @@ KeyType SECKEY_GetPublicKeyType(const SECKEYPublicKey *pubKey); * Creates a PublicKey from its DER encoding. * Currently only supports RSA, DSA, and DH keys. */ -SECKEYPublicKey* +SECKEYPublicKey * SECKEY_ImportDERPublicKey(const SECItem *derKey, CK_KEY_TYPE type); -SECKEYPrivateKeyList* +SECKEYPrivateKeyList * SECKEY_NewPrivateKeyList(void); void @@ -218,14 +216,14 @@ void SECKEY_RemovePrivateKeyListNode(SECKEYPrivateKeyListNode *node); SECStatus -SECKEY_AddPrivateKeyToListTail( SECKEYPrivateKeyList *list, - SECKEYPrivateKey *key); +SECKEY_AddPrivateKeyToListTail(SECKEYPrivateKeyList *list, + SECKEYPrivateKey *key); -#define PRIVKEY_LIST_HEAD(l) ((SECKEYPrivateKeyListNode*)PR_LIST_HEAD(&l->list)) +#define PRIVKEY_LIST_HEAD(l) ((SECKEYPrivateKeyListNode *)PR_LIST_HEAD(&l->list)) #define PRIVKEY_LIST_NEXT(n) ((SECKEYPrivateKeyListNode *)n->links.next) -#define PRIVKEY_LIST_END(n,l) (((void *)n) == ((void *)&l->list)) +#define PRIVKEY_LIST_END(n, l) (((void *)n) == ((void *)&l->list)) -SECKEYPublicKeyList* +SECKEYPublicKeyList * SECKEY_NewPublicKeyList(void); void @@ -235,12 +233,12 @@ void SECKEY_RemovePublicKeyListNode(SECKEYPublicKeyListNode *node); SECStatus -SECKEY_AddPublicKeyToListTail( SECKEYPublicKeyList *list, - SECKEYPublicKey *key); +SECKEY_AddPublicKeyToListTail(SECKEYPublicKeyList *list, + SECKEYPublicKey *key); -#define PUBKEY_LIST_HEAD(l) ((SECKEYPublicKeyListNode*)PR_LIST_HEAD(&l->list)) +#define PUBKEY_LIST_HEAD(l) ((SECKEYPublicKeyListNode *)PR_LIST_HEAD(&l->list)) #define PUBKEY_LIST_NEXT(n) ((SECKEYPublicKeyListNode *)n->links.next) -#define PUBKEY_LIST_END(n,l) (((void *)n) == ((void *)&l->list)) +#define PUBKEY_LIST_END(n, l) (((void *)n) == ((void *)&l->list)) /* * Length in bits of the EC's field size. This is also the length of @@ -266,7 +264,7 @@ extern int SECKEY_ECParamsToBasePointOrderLen(const SECItem *params); * * Return 0 on failure (unknown EC domain parameters). */ -SECOidTag SECKEY_GetECCOid(const SECKEYECParams * params); +SECOidTag SECKEY_GetECCOid(const SECKEYECParams *params); SEC_END_PROTOS diff --git a/security/nss/lib/cryptohi/keyi.h b/security/nss/lib/cryptohi/keyi.h index 7d0304e8d1da..f8f5f7f7dae8 100644 --- a/security/nss/lib/cryptohi/keyi.h +++ b/security/nss/lib/cryptohi/keyi.h @@ -5,7 +5,6 @@ #ifndef _KEYI_H_ #define _KEYI_H_ - SEC_BEGIN_PROTOS /* NSS private functions */ /* map an oid to a keytype... actually this function and it's converse @@ -16,7 +15,7 @@ KeyType seckey_GetKeyType(SECOidTag pubKeyOid); * algorithm, key and parameters (parameters is the parameters field * of a algorithm ID structure (SECAlgorithmID)*/ SECStatus sec_DecodeSigAlg(const SECKEYPublicKey *key, SECOidTag sigAlg, - const SECItem *param, SECOidTag *encalg, SECOidTag *hashalg); + const SECItem *param, SECOidTag *encalg, SECOidTag *hashalg); SEC_END_PROTOS diff --git a/security/nss/lib/cryptohi/keythi.h b/security/nss/lib/cryptohi/keythi.h index 9b9a2785526a..e0a9215a00ae 100644 --- a/security/nss/lib/cryptohi/keythi.h +++ b/security/nss/lib/cryptohi/keythi.h @@ -21,14 +21,14 @@ ** ** rsaOaepKey maps to keys with SEC_OID_PKCS1_RSA_OAEP_ENCRYPTION and may only ** be used for encryption with OAEP padding (PKCS #1 v2.1). -*/ +*/ -typedef enum { - nullKey = 0, - rsaKey = 1, - dsaKey = 2, +typedef enum { + nullKey = 0, + rsaKey = 1, + dsaKey = 2, fortezzaKey = 3, /* deprecated */ - dhKey = 4, + dhKey = 4, keaKey = 5, /* deprecated */ ecKey = 6, rsaPssKey = 7, @@ -54,20 +54,19 @@ SEC_ASN1_CHOOSER_DECLARE(SECKEY_RSAPublicKeyTemplate) SEC_ASN1_CHOOSER_DECLARE(SECKEY_RSAPSSParamsTemplate) SEC_END_PROTOS - /* ** RSA Public Key structures -** member names from PKCS#1, section 7.1 +** member names from PKCS#1, section 7.1 */ struct SECKEYRSAPublicKeyStr { - PLArenaPool * arena; + PLArenaPool *arena; SECItem modulus; SECItem publicExponent; }; typedef struct SECKEYRSAPublicKeyStr SECKEYRSAPublicKey; -/* +/* ** RSA-PSS parameters */ struct SECKEYRSAPSSParamsStr { @@ -97,20 +96,19 @@ struct SECKEYDSAPublicKeyStr { }; typedef struct SECKEYDSAPublicKeyStr SECKEYDSAPublicKey; - /* ** Diffie-Hellman Public Key structure ** Structure member names suggested by PKCS#3. */ struct SECKEYDHParamsStr { - PLArenaPool * arena; + PLArenaPool *arena; SECItem prime; /* p */ - SECItem base; /* g */ + SECItem base; /* g */ }; typedef struct SECKEYDHParamsStr SECKEYDHParams; struct SECKEYDHPublicKeyStr { - PLArenaPool * arena; + PLArenaPool *arena; SECItem prime; SECItem base; SECItem publicValue; @@ -126,8 +124,8 @@ typedef SECItem SECKEYECParams; struct SECKEYECPublicKeyStr { SECKEYECParams DEREncodedParams; - int size; /* size in bits */ - SECItem publicValue; /* encoded point */ + int size; /* size in bits */ + SECItem publicValue; /* encoded point */ /* XXX Even though the PKCS#11 interface takes encoded parameters, * we may still wish to decode them above PKCS#11 for things like * printing key information. For named curves, which is what @@ -141,9 +139,9 @@ typedef struct SECKEYECPublicKeyStr SECKEYECPublicKey; ** FORTEZZA Public Key structures */ struct SECKEYFortezzaPublicKeyStr { - int KEAversion; - int DSSversion; - unsigned char KMID[8]; + int KEAversion; + int DSSversion; + unsigned char KMID[8]; SECItem clearance; SECItem KEApriviledge; SECItem DSSpriviledge; @@ -173,7 +171,7 @@ struct SECKEYKEAParamsStr { SECItem hash; }; typedef struct SECKEYKEAParamsStr SECKEYKEAParams; - + struct SECKEYKEAPublicKeyStr { SECKEYKEAParams params; SECItem publicValue; @@ -190,26 +188,26 @@ struct SECKEYPublicKeyStr { CK_OBJECT_HANDLE pkcs11ID; union { SECKEYRSAPublicKey rsa; - SECKEYDSAPublicKey dsa; - SECKEYDHPublicKey dh; + SECKEYDSAPublicKey dsa; + SECKEYDHPublicKey dh; SECKEYKEAPublicKey kea; SECKEYFortezzaPublicKey fortezza; - SECKEYECPublicKey ec; + SECKEYECPublicKey ec; } u; }; typedef struct SECKEYPublicKeyStr SECKEYPublicKey; /* bit flag definitions for staticflags */ -#define SECKEY_Attributes_Cached 0x1 /* bit 0 states - whether attributes are cached */ -#define SECKEY_CKA_PRIVATE (1U << 1) /* bit 1 is the value of CKA_PRIVATE */ -#define SECKEY_CKA_ALWAYS_AUTHENTICATE (1U << 2) +#define SECKEY_Attributes_Cached 0x1 /* bit 0 states \ + whether attributes are cached */ +#define SECKEY_CKA_PRIVATE (1U << 1) /* bit 1 is the value of CKA_PRIVATE */ +#define SECKEY_CKA_ALWAYS_AUTHENTICATE (1U << 2) #define SECKEY_ATTRIBUTES_CACHED(key) \ - (0 != (key->staticflags & SECKEY_Attributes_Cached)) + (0 != (key->staticflags & SECKEY_Attributes_Cached)) #define SECKEY_ATTRIBUTE_VALUE(key,attribute) \ - (0 != (key->staticflags & SECKEY_##attribute)) + (0 != (key->staticflags & SECKEY_##attribute)) #define SECKEY_HAS_ATTRIBUTE_SET(key,attribute) \ (0 != (key->staticflags & SECKEY_Attributes_Cached)) ? \ @@ -223,15 +221,15 @@ typedef struct SECKEYPublicKeyStr SECKEYPublicKey; /* ** A generic key structure -*/ +*/ struct SECKEYPrivateKeyStr { PLArenaPool *arena; KeyType keyType; - PK11SlotInfo *pkcs11Slot; /* pkcs11 slot this key lives in */ - CK_OBJECT_HANDLE pkcs11ID; /* ID of pkcs11 object */ - PRBool pkcs11IsTemp; /* temp pkcs11 object, delete it when done */ - void *wincx; /* context for errors and pw prompts */ - PRUint32 staticflags; /* bit flag of cached PKCS#11 attributes */ + PK11SlotInfo *pkcs11Slot; /* pkcs11 slot this key lives in */ + CK_OBJECT_HANDLE pkcs11ID; /* ID of pkcs11 object */ + PRBool pkcs11IsTemp; /* temp pkcs11 object, delete it when done */ + void *wincx; /* context for errors and pw prompts */ + PRUint32 staticflags; /* bit flag of cached PKCS#11 attributes */ }; typedef struct SECKEYPrivateKeyStr SECKEYPrivateKey; @@ -255,4 +253,3 @@ typedef struct { PLArenaPool *arena; } SECKEYPublicKeyList; #endif /* _KEYTHI_H_ */ - diff --git a/security/nss/lib/cryptohi/sechash.c b/security/nss/lib/cryptohi/sechash.c index b9476c478343..b12621100a21 100644 --- a/security/nss/lib/cryptohi/sechash.c +++ b/security/nss/lib/cryptohi/sechash.c @@ -5,7 +5,7 @@ #include "secoidt.h" #include "secerr.h" #include "blapi.h" -#include "pk11func.h" /* for the PK11_ calls below. */ +#include "pk11func.h" /* for the PK11_ calls below. */ static void * null_hash_new_context(void) @@ -32,7 +32,7 @@ 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) + unsigned int maxOut) { *outLen = 0; } @@ -43,134 +43,132 @@ null_hash_destroy_context(void *v, PRBool b) PORT_Assert(v == NULL); } - static void * -md2_NewContext(void) { - return (void *) PK11_CreateDigestContext(SEC_OID_MD2); +md2_NewContext(void) +{ + return (void *)PK11_CreateDigestContext(SEC_OID_MD2); } static void * -md5_NewContext(void) { - return (void *) PK11_CreateDigestContext(SEC_OID_MD5); +md5_NewContext(void) +{ + return (void *)PK11_CreateDigestContext(SEC_OID_MD5); } static void * -sha1_NewContext(void) { - return (void *) PK11_CreateDigestContext(SEC_OID_SHA1); +sha1_NewContext(void) +{ + return (void *)PK11_CreateDigestContext(SEC_OID_SHA1); } static void * -sha224_NewContext(void) { - return (void *) PK11_CreateDigestContext(SEC_OID_SHA224); +sha224_NewContext(void) +{ + return (void *)PK11_CreateDigestContext(SEC_OID_SHA224); } static void * -sha256_NewContext(void) { - return (void *) PK11_CreateDigestContext(SEC_OID_SHA256); +sha256_NewContext(void) +{ + return (void *)PK11_CreateDigestContext(SEC_OID_SHA256); } static void * -sha384_NewContext(void) { - return (void *) PK11_CreateDigestContext(SEC_OID_SHA384); +sha384_NewContext(void) +{ + return (void *)PK11_CreateDigestContext(SEC_OID_SHA384); } static void * -sha512_NewContext(void) { - return (void *) PK11_CreateDigestContext(SEC_OID_SHA512); +sha512_NewContext(void) +{ + return (void *)PK11_CreateDigestContext(SEC_OID_SHA512); } const SECHashObject SECHashObjects[] = { - { 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, - 0, - HASH_AlgNULL - }, - { MD2_LENGTH, - (void * (*)(void)) md2_NewContext, - (void * (*)(void *)) PK11_CloneContext, - (void (*)(void *, PRBool)) PK11_DestroyContext, - (void (*)(void *)) PK11_DigestBegin, - (void (*)(void *, const unsigned char *, unsigned int)) PK11_DigestOp, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) - PK11_DigestFinal, - MD2_BLOCK_LENGTH, - HASH_AlgMD2 - }, - { MD5_LENGTH, - (void * (*)(void)) md5_NewContext, - (void * (*)(void *)) PK11_CloneContext, - (void (*)(void *, PRBool)) PK11_DestroyContext, - (void (*)(void *)) PK11_DigestBegin, - (void (*)(void *, const unsigned char *, unsigned int)) PK11_DigestOp, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) - PK11_DigestFinal, - MD5_BLOCK_LENGTH, - HASH_AlgMD5 - }, - { SHA1_LENGTH, - (void * (*)(void)) sha1_NewContext, - (void * (*)(void *)) PK11_CloneContext, - (void (*)(void *, PRBool)) PK11_DestroyContext, - (void (*)(void *)) PK11_DigestBegin, - (void (*)(void *, const unsigned char *, unsigned int)) PK11_DigestOp, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) - PK11_DigestFinal, - SHA1_BLOCK_LENGTH, - HASH_AlgSHA1 - }, - { SHA256_LENGTH, - (void * (*)(void)) sha256_NewContext, - (void * (*)(void *)) PK11_CloneContext, - (void (*)(void *, PRBool)) PK11_DestroyContext, - (void (*)(void *)) PK11_DigestBegin, - (void (*)(void *, const unsigned char *, unsigned int)) PK11_DigestOp, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) - PK11_DigestFinal, - SHA256_BLOCK_LENGTH, - HASH_AlgSHA256 - }, - { SHA384_LENGTH, - (void * (*)(void)) sha384_NewContext, - (void * (*)(void *)) PK11_CloneContext, - (void (*)(void *, PRBool)) PK11_DestroyContext, - (void (*)(void *)) PK11_DigestBegin, - (void (*)(void *, const unsigned char *, unsigned int)) PK11_DigestOp, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) - PK11_DigestFinal, - SHA384_BLOCK_LENGTH, - HASH_AlgSHA384 - }, - { SHA512_LENGTH, - (void * (*)(void)) sha512_NewContext, - (void * (*)(void *)) PK11_CloneContext, - (void (*)(void *, PRBool)) PK11_DestroyContext, - (void (*)(void *)) PK11_DigestBegin, - (void (*)(void *, const unsigned char *, unsigned int)) PK11_DigestOp, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) - PK11_DigestFinal, - SHA512_BLOCK_LENGTH, - HASH_AlgSHA512 - }, - { SHA224_LENGTH, - (void * (*)(void)) sha224_NewContext, - (void * (*)(void *)) PK11_CloneContext, - (void (*)(void *, PRBool)) PK11_DestroyContext, - (void (*)(void *)) PK11_DigestBegin, - (void (*)(void *, const unsigned char *, unsigned int)) PK11_DigestOp, - (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) - PK11_DigestFinal, - SHA224_BLOCK_LENGTH, - HASH_AlgSHA224 - }, + { 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, + 0, + HASH_AlgNULL }, + { MD2_LENGTH, + (void *(*)(void))md2_NewContext, + (void *(*)(void *))PK11_CloneContext, + (void (*)(void *, PRBool))PK11_DestroyContext, + (void (*)(void *))PK11_DigestBegin, + (void (*)(void *, const unsigned char *, unsigned int))PK11_DigestOp, + (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) + PK11_DigestFinal, + MD2_BLOCK_LENGTH, + HASH_AlgMD2 }, + { MD5_LENGTH, + (void *(*)(void))md5_NewContext, + (void *(*)(void *))PK11_CloneContext, + (void (*)(void *, PRBool))PK11_DestroyContext, + (void (*)(void *))PK11_DigestBegin, + (void (*)(void *, const unsigned char *, unsigned int))PK11_DigestOp, + (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) + PK11_DigestFinal, + MD5_BLOCK_LENGTH, + HASH_AlgMD5 }, + { SHA1_LENGTH, + (void *(*)(void))sha1_NewContext, + (void *(*)(void *))PK11_CloneContext, + (void (*)(void *, PRBool))PK11_DestroyContext, + (void (*)(void *))PK11_DigestBegin, + (void (*)(void *, const unsigned char *, unsigned int))PK11_DigestOp, + (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) + PK11_DigestFinal, + SHA1_BLOCK_LENGTH, + HASH_AlgSHA1 }, + { SHA256_LENGTH, + (void *(*)(void))sha256_NewContext, + (void *(*)(void *))PK11_CloneContext, + (void (*)(void *, PRBool))PK11_DestroyContext, + (void (*)(void *))PK11_DigestBegin, + (void (*)(void *, const unsigned char *, unsigned int))PK11_DigestOp, + (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) + PK11_DigestFinal, + SHA256_BLOCK_LENGTH, + HASH_AlgSHA256 }, + { SHA384_LENGTH, + (void *(*)(void))sha384_NewContext, + (void *(*)(void *))PK11_CloneContext, + (void (*)(void *, PRBool))PK11_DestroyContext, + (void (*)(void *))PK11_DigestBegin, + (void (*)(void *, const unsigned char *, unsigned int))PK11_DigestOp, + (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) + PK11_DigestFinal, + SHA384_BLOCK_LENGTH, + HASH_AlgSHA384 }, + { SHA512_LENGTH, + (void *(*)(void))sha512_NewContext, + (void *(*)(void *))PK11_CloneContext, + (void (*)(void *, PRBool))PK11_DestroyContext, + (void (*)(void *))PK11_DigestBegin, + (void (*)(void *, const unsigned char *, unsigned int))PK11_DigestOp, + (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) + PK11_DigestFinal, + SHA512_BLOCK_LENGTH, + HASH_AlgSHA512 }, + { SHA224_LENGTH, + (void *(*)(void))sha224_NewContext, + (void *(*)(void *))PK11_CloneContext, + (void (*)(void *, PRBool))PK11_DestroyContext, + (void (*)(void *))PK11_DigestBegin, + (void (*)(void *, const unsigned char *, unsigned int))PK11_DigestOp, + (void (*)(void *, unsigned char *, unsigned int *, unsigned int)) + PK11_DigestFinal, + SHA224_BLOCK_LENGTH, + HASH_AlgSHA224 }, }; -const SECHashObject * +const SECHashObject * HASH_GetHashObject(HASH_HashType type) { return &SECHashObjects[type]; @@ -179,19 +177,34 @@ HASH_GetHashObject(HASH_HashType type) HASH_HashType HASH_GetHashTypeByOidTag(SECOidTag hashOid) { - HASH_HashType ht = HASH_AlgNULL; + HASH_HashType ht = HASH_AlgNULL; - switch(hashOid) { - case SEC_OID_MD2: ht = HASH_AlgMD2; break; - case SEC_OID_MD5: ht = HASH_AlgMD5; break; - case SEC_OID_SHA1: ht = HASH_AlgSHA1; break; - case SEC_OID_SHA224: ht = HASH_AlgSHA224; break; - case SEC_OID_SHA256: ht = HASH_AlgSHA256; break; - case SEC_OID_SHA384: ht = HASH_AlgSHA384; break; - case SEC_OID_SHA512: ht = HASH_AlgSHA512; break; - default: ht = HASH_AlgNULL; - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - break; + switch (hashOid) { + case SEC_OID_MD2: + ht = HASH_AlgMD2; + break; + case SEC_OID_MD5: + ht = HASH_AlgMD5; + break; + case SEC_OID_SHA1: + ht = HASH_AlgSHA1; + break; + case SEC_OID_SHA224: + ht = HASH_AlgSHA224; + break; + case SEC_OID_SHA256: + ht = HASH_AlgSHA256; + break; + case SEC_OID_SHA384: + ht = HASH_AlgSHA384; + break; + case SEC_OID_SHA512: + ht = HASH_AlgSHA512; + break; + default: + ht = HASH_AlgNULL; + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + break; } return ht; } @@ -201,17 +214,28 @@ HASH_GetHashOidTagByHMACOidTag(SECOidTag hmacOid) { SECOidTag hashOid = SEC_OID_UNKNOWN; - switch(hmacOid) { - /* no oid exists for HMAC_MD2 */ - /* NSS does not define a oid for HMAC_MD4 */ - case SEC_OID_HMAC_SHA1: hashOid = SEC_OID_SHA1; break; - case SEC_OID_HMAC_SHA224: hashOid = SEC_OID_SHA224; break; - case SEC_OID_HMAC_SHA256: hashOid = SEC_OID_SHA256; break; - case SEC_OID_HMAC_SHA384: hashOid = SEC_OID_SHA384; break; - case SEC_OID_HMAC_SHA512: hashOid = SEC_OID_SHA512; break; - default: hashOid = SEC_OID_UNKNOWN; - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - break; + switch (hmacOid) { + /* no oid exists for HMAC_MD2 */ + /* NSS does not define a oid for HMAC_MD4 */ + case SEC_OID_HMAC_SHA1: + hashOid = SEC_OID_SHA1; + break; + case SEC_OID_HMAC_SHA224: + hashOid = SEC_OID_SHA224; + break; + case SEC_OID_HMAC_SHA256: + hashOid = SEC_OID_SHA256; + break; + case SEC_OID_HMAC_SHA384: + hashOid = SEC_OID_SHA384; + break; + case SEC_OID_HMAC_SHA512: + hashOid = SEC_OID_SHA512; + break; + default: + hashOid = SEC_OID_UNKNOWN; + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + break; } return hashOid; } @@ -221,25 +245,36 @@ HASH_GetHMACOidTagByHashOidTag(SECOidTag hashOid) { SECOidTag hmacOid = SEC_OID_UNKNOWN; - switch(hashOid) { - /* no oid exists for HMAC_MD2 */ - /* NSS does not define a oid for HMAC_MD4 */ - case SEC_OID_SHA1: hmacOid = SEC_OID_HMAC_SHA1; break; - case SEC_OID_SHA224: hmacOid = SEC_OID_HMAC_SHA224; break; - case SEC_OID_SHA256: hmacOid = SEC_OID_HMAC_SHA256; break; - case SEC_OID_SHA384: hmacOid = SEC_OID_HMAC_SHA384; break; - case SEC_OID_SHA512: hmacOid = SEC_OID_HMAC_SHA512; break; - default: hmacOid = SEC_OID_UNKNOWN; - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - break; + switch (hashOid) { + /* no oid exists for HMAC_MD2 */ + /* NSS does not define a oid for HMAC_MD4 */ + case SEC_OID_SHA1: + hmacOid = SEC_OID_HMAC_SHA1; + break; + case SEC_OID_SHA224: + hmacOid = SEC_OID_HMAC_SHA224; + break; + case SEC_OID_SHA256: + hmacOid = SEC_OID_HMAC_SHA256; + break; + case SEC_OID_SHA384: + hmacOid = SEC_OID_HMAC_SHA384; + break; + case SEC_OID_SHA512: + hmacOid = SEC_OID_HMAC_SHA512; + break; + default: + hmacOid = SEC_OID_UNKNOWN; + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + break; } return hmacOid; } -const SECHashObject * +const SECHashObject * HASH_GetHashObjectByOidTag(SECOidTag hashOid) { - HASH_HashType ht = HASH_GetHashTypeByOidTag(hashOid); + HASH_HashType ht = HASH_GetHashTypeByOidTag(hashOid); return (ht == HASH_AlgNULL) ? NULL : &SECHashObjects[ht]; } @@ -248,11 +283,11 @@ HASH_GetHashObjectByOidTag(SECOidTag hashOid) unsigned int HASH_ResultLenByOidTag(SECOidTag hashOid) { - const SECHashObject * hashObject = HASH_GetHashObjectByOidTag(hashOid); - unsigned int resultLen = 0; + const SECHashObject *hashObject = HASH_GetHashObjectByOidTag(hashOid); + unsigned int resultLen = 0; if (hashObject) - resultLen = hashObject->length; + resultLen = hashObject->length; return resultLen; } @@ -260,45 +295,43 @@ HASH_ResultLenByOidTag(SECOidTag hashOid) unsigned int HASH_ResultLen(HASH_HashType type) { - if ( ( type < HASH_AlgNULL ) || ( type >= HASH_AlgTOTAL ) ) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return(0); + if ((type < HASH_AlgNULL) || (type >= HASH_AlgTOTAL)) { + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return (0); } - - return(SECHashObjects[type].length); + + return (SECHashObjects[type].length); } unsigned int HASH_ResultLenContext(HASHContext *context) { - return(context->hashobj->length); + return (context->hashobj->length); } - - SECStatus HASH_HashBuf(HASH_HashType type, - unsigned char *dest, - const unsigned char *src, - PRUint32 src_len) + unsigned char *dest, + const unsigned char *src, + PRUint32 src_len) { HASHContext *cx; unsigned int part; - - if ( ( type < HASH_AlgNULL ) || ( type >= HASH_AlgTOTAL ) ) { - return(SECFailure); + + if ((type < HASH_AlgNULL) || (type >= HASH_AlgTOTAL)) { + return (SECFailure); } - + cx = HASH_Create(type); - if ( cx == NULL ) { - return(SECFailure); + if (cx == NULL) { + return (SECFailure); } HASH_Begin(cx); HASH_Update(cx, src, src_len); HASH_End(cx, dest, &part, HASH_ResultLenContext(cx)); HASH_Destroy(cx); - return(SECSuccess); + return (SECSuccess); } HASHContext * @@ -306,104 +339,100 @@ HASH_Create(HASH_HashType type) { void *hash_context = NULL; HASHContext *ret = NULL; - - if ( ( type < HASH_AlgNULL ) || ( type >= HASH_AlgTOTAL ) ) { - return(NULL); + + if ((type < HASH_AlgNULL) || (type >= HASH_AlgTOTAL)) { + return (NULL); } - - hash_context = (* SECHashObjects[type].create)(); - if ( hash_context == NULL ) { - goto loser; + + hash_context = (*SECHashObjects[type].create)(); + if (hash_context == NULL) { + goto loser; } ret = (HASHContext *)PORT_Alloc(sizeof(HASHContext)); - if ( ret == NULL ) { - goto loser; + if (ret == NULL) { + goto loser; } ret->hash_context = hash_context; ret->hashobj = &SECHashObjects[type]; - - return(ret); - -loser: - if ( hash_context != NULL ) { - (* SECHashObjects[type].destroy)(hash_context, PR_TRUE); - } - - return(NULL); -} + return (ret); + +loser: + if (hash_context != NULL) { + (*SECHashObjects[type].destroy)(hash_context, PR_TRUE); + } + + return (NULL); +} HASHContext * HASH_Clone(HASHContext *context) { void *hash_context = NULL; HASHContext *ret = NULL; - - hash_context = (* context->hashobj->clone)(context->hash_context); - if ( hash_context == NULL ) { - goto loser; + + hash_context = (*context->hashobj->clone)(context->hash_context); + if (hash_context == NULL) { + goto loser; } ret = (HASHContext *)PORT_Alloc(sizeof(HASHContext)); - if ( ret == NULL ) { - goto loser; + if (ret == NULL) { + goto loser; } ret->hash_context = hash_context; ret->hashobj = context->hashobj; - - return(ret); - -loser: - if ( hash_context != NULL ) { - (* context->hashobj->destroy)(hash_context, PR_TRUE); - } - - return(NULL); + return (ret); + +loser: + if (hash_context != NULL) { + (*context->hashobj->destroy)(hash_context, PR_TRUE); + } + + return (NULL); } void HASH_Destroy(HASHContext *context) { - (* context->hashobj->destroy)(context->hash_context, PR_TRUE); + (*context->hashobj->destroy)(context->hash_context, PR_TRUE); PORT_Free(context); return; } - void HASH_Begin(HASHContext *context) { - (* context->hashobj->begin)(context->hash_context); + (*context->hashobj->begin)(context->hash_context); return; } - void HASH_Update(HASHContext *context, - const unsigned char *src, - unsigned int len) + const unsigned char *src, + unsigned int len) { - (* context->hashobj->update)(context->hash_context, src, len); + (*context->hashobj->update)(context->hash_context, src, len); return; } void HASH_End(HASHContext *context, - unsigned char *result, - unsigned int *result_len, - unsigned int max_result_len) + unsigned char *result, + unsigned int *result_len, + unsigned int max_result_len) { - (* context->hashobj->end)(context->hash_context, result, result_len, - max_result_len); + (*context->hashobj->end)(context->hash_context, result, result_len, + max_result_len); return; } HASH_HashType HASH_GetType(HASHContext *context) { - return(context->hashobj->type); + return (context->hashobj->type); } diff --git a/security/nss/lib/cryptohi/sechash.h b/security/nss/lib/cryptohi/sechash.h index 5c585511bffb..94ff7ed3d017 100644 --- a/security/nss/lib/cryptohi/sechash.h +++ b/security/nss/lib/cryptohi/sechash.h @@ -12,42 +12,42 @@ SEC_BEGIN_PROTOS /* -** Generic hash api. +** Generic hash api. */ -extern unsigned int HASH_ResultLen(HASH_HashType type); +extern unsigned int HASH_ResultLen(HASH_HashType type); -extern unsigned int HASH_ResultLenContext(HASHContext *context); +extern unsigned int HASH_ResultLenContext(HASHContext *context); -extern unsigned int HASH_ResultLenByOidTag(SECOidTag hashOid); +extern unsigned int HASH_ResultLenByOidTag(SECOidTag hashOid); -extern SECStatus HASH_HashBuf(HASH_HashType type, - unsigned char *dest, - const unsigned char *src, - PRUint32 src_len); +extern SECStatus HASH_HashBuf(HASH_HashType type, + unsigned char *dest, + const unsigned char *src, + PRUint32 src_len); -extern HASHContext * HASH_Create(HASH_HashType type); +extern HASHContext *HASH_Create(HASH_HashType type); -extern HASHContext * HASH_Clone(HASHContext *context); +extern HASHContext *HASH_Clone(HASHContext *context); -extern void HASH_Destroy(HASHContext *context); +extern void HASH_Destroy(HASHContext *context); -extern void HASH_Begin(HASHContext *context); +extern void HASH_Begin(HASHContext *context); -extern void HASH_Update(HASHContext *context, - const unsigned char *src, - unsigned int len); +extern void HASH_Update(HASHContext *context, + const unsigned char *src, + unsigned int len); + +extern void HASH_End(HASHContext *context, + unsigned char *result, + unsigned int *result_len, + unsigned int max_result_len); -extern void HASH_End(HASHContext *context, - unsigned char *result, - unsigned int *result_len, - unsigned int max_result_len); - extern HASH_HashType HASH_GetType(HASHContext *context); -extern const SECHashObject * HASH_GetHashObject(HASH_HashType type); +extern const SECHashObject *HASH_GetHashObject(HASH_HashType type); -extern const SECHashObject * HASH_GetHashObjectByOidTag(SECOidTag hashOid); +extern const SECHashObject *HASH_GetHashObjectByOidTag(SECOidTag hashOid); extern HASH_HashType HASH_GetHashTypeByOidTag(SECOidTag hashOid); extern SECOidTag HASH_GetHashOidTagByHMACOidTag(SECOidTag hmacOid); diff --git a/security/nss/lib/cryptohi/seckey.c b/security/nss/lib/cryptohi/seckey.c index 1fcd4087f0dd..f318678283f7 100644 --- a/security/nss/lib/cryptohi/seckey.c +++ b/security/nss/lib/cryptohi/seckey.c @@ -20,28 +20,28 @@ SEC_ASN1_MKSUB(SEC_IntegerTemplate) const SEC_ASN1Template CERT_SubjectPublicKeyInfoTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTSubjectPublicKeyInfo) }, + 0, NULL, sizeof(CERTSubjectPublicKeyInfo) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTSubjectPublicKeyInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(CERTSubjectPublicKeyInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_BIT_STRING, - offsetof(CERTSubjectPublicKeyInfo,subjectPublicKey), }, - { 0, } -}; - -const SEC_ASN1Template CERT_PublicKeyAndChallengeTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTPublicKeyAndChallenge) }, - { SEC_ASN1_ANY, offsetof(CERTPublicKeyAndChallenge,spki) }, - { SEC_ASN1_IA5_STRING, offsetof(CERTPublicKeyAndChallenge,challenge) }, + offsetof(CERTSubjectPublicKeyInfo, subjectPublicKey) }, { 0 } }; +const SEC_ASN1Template CERT_PublicKeyAndChallengeTemplate[] = + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CERTPublicKeyAndChallenge) }, + { SEC_ASN1_ANY, offsetof(CERTPublicKeyAndChallenge, spki) }, + { SEC_ASN1_IA5_STRING, offsetof(CERTPublicKeyAndChallenge, challenge) }, + { 0 } + }; + const SEC_ASN1Template SECKEY_RSAPublicKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYPublicKey) }, - { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.rsa.modulus), }, - { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.rsa.publicExponent), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey, u.rsa.modulus) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey, u.rsa.publicExponent) }, + { 0 } }; static const SEC_ASN1Template seckey_PointerToAlgorithmIDTemplate[] = { @@ -51,52 +51,52 @@ static const SEC_ASN1Template seckey_PointerToAlgorithmIDTemplate[] = { /* Parameters for SEC_OID_PKCS1_RSA_PSS_SIGNATURE */ const SEC_ASN1Template SECKEY_RSAPSSParamsTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYRSAPSSParams) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(SECKEYRSAPSSParams, hashAlg), - seckey_PointerToAlgorithmIDTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(SECKEYRSAPSSParams, maskAlg), - seckey_PointerToAlgorithmIDTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | - SEC_ASN1_XTRN | SEC_ASN1_CONTEXT_SPECIFIC | 2, - offsetof(SECKEYRSAPSSParams, saltLength), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | - SEC_ASN1_XTRN | SEC_ASN1_CONTEXT_SPECIFIC | 3, - offsetof(SECKEYRSAPSSParams, trailerField), - SEC_ASN1_SUB(SEC_IntegerTemplate) }, - { 0 } -}; + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYRSAPSSParams) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | + SEC_ASN1_CONTEXT_SPECIFIC | 0, + offsetof(SECKEYRSAPSSParams, hashAlg), + seckey_PointerToAlgorithmIDTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | + SEC_ASN1_CONTEXT_SPECIFIC | 1, + offsetof(SECKEYRSAPSSParams, maskAlg), + seckey_PointerToAlgorithmIDTemplate }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | + SEC_ASN1_XTRN | SEC_ASN1_CONTEXT_SPECIFIC | 2, + offsetof(SECKEYRSAPSSParams, saltLength), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, + { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | + SEC_ASN1_XTRN | SEC_ASN1_CONTEXT_SPECIFIC | 3, + offsetof(SECKEYRSAPSSParams, trailerField), + SEC_ASN1_SUB(SEC_IntegerTemplate) }, + { 0 } + }; const SEC_ASN1Template SECKEY_DSAPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dsa.publicValue), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey, u.dsa.publicValue) }, + { 0 } }; const SEC_ASN1Template SECKEY_PQGParamsTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYPQGParams) }, - { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,prime) }, - { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,subPrime) }, - { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams,base) }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams, prime) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams, subPrime) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams, base) }, + { 0 } }; const SEC_ASN1Template SECKEY_DHPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dh.publicValue), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey, u.dh.publicValue) }, + { 0 } }; const SEC_ASN1Template SECKEY_DHParamKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYPublicKey) }, - { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dh.prime), }, - { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey,u.dh.base), }, + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECKEYPublicKey) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey, u.dh.prime) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPublicKey, u.dh.base) }, /* XXX chrisk: this needs to be expanded for decoding of j and validationParms (RFC2459 7.3.2) */ { SEC_ASN1_SKIP_REST }, - { 0, } + { 0 } }; SEC_ASN1_CHOOSER_IMPLEMENT(SECKEY_DSAPublicKeyTemplate) @@ -142,33 +142,33 @@ prepare_dh_pub_key_for_asn1(SECKEYPublicKey *pubk) } /* Create an RSA key pair is any slot able to do so. -** The created keys are "session" (temporary), not "token" (permanent), +** The created keys are "session" (temporary), not "token" (permanent), ** and they are "sensitive", which makes them costly to move to another token. */ SECKEYPrivateKey * -SECKEY_CreateRSAPrivateKey(int keySizeInBits,SECKEYPublicKey **pubk, void *cx) +SECKEY_CreateRSAPrivateKey(int keySizeInBits, SECKEYPublicKey **pubk, void *cx) { SECKEYPrivateKey *privk; PK11RSAGenParams param; - PK11SlotInfo *slot = PK11_GetBestSlot(CKM_RSA_PKCS_KEY_PAIR_GEN,cx); + PK11SlotInfo *slot = PK11_GetBestSlot(CKM_RSA_PKCS_KEY_PAIR_GEN, cx); if (!slot) { - return NULL; + return NULL; } param.keySizeInBits = keySizeInBits; param.pe = 65537L; - - privk = PK11_GenerateKeyPair(slot,CKM_RSA_PKCS_KEY_PAIR_GEN,¶m,pubk, - PR_FALSE, PR_TRUE, cx); + + privk = PK11_GenerateKeyPair(slot, CKM_RSA_PKCS_KEY_PAIR_GEN, ¶m, pubk, + PR_FALSE, PR_TRUE, cx); PK11_FreeSlot(slot); - return(privk); + return (privk); } -/* Create a DH key pair in any slot able to do so, -** This is a "session" (temporary), not "token" (permanent) key. +/* Create a DH key pair in any slot able to do so, +** This is a "session" (temporary), not "token" (permanent) key. ** Because of the high probability that this key will need to be moved to ** another token, and the high cost of moving "sensitive" keys, we attempt -** to create this key pair without the "sensitive" attribute, but revert to +** to create this key pair without the "sensitive" attribute, but revert to ** creating a "sensitive" key if necessary. */ SECKEYPrivateKey * @@ -180,72 +180,77 @@ SECKEY_CreateDHPrivateKey(SECKEYDHParams *param, SECKEYPublicKey **pubk, void *c if (!param || !param->base.data || !param->prime.data || SECKEY_BigIntegerBitLength(¶m->prime) < DH_MIN_P_BITS || param->base.len == 0 || param->base.len > param->prime.len + 1 || - (param->base.len == 1 && param->base.data[0] == 0)) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + (param->base.len == 1 && param->base.data[0] == 0)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } - slot = PK11_GetBestSlot(CKM_DH_PKCS_KEY_PAIR_GEN,cx); + slot = PK11_GetBestSlot(CKM_DH_PKCS_KEY_PAIR_GEN, cx); if (!slot) { - return NULL; + return NULL; } - privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, + privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, pubk, PR_FALSE, PR_FALSE, cx); - if (!privk) - privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, - pubk, PR_FALSE, PR_TRUE, cx); + if (!privk) + privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, + pubk, PR_FALSE, PR_TRUE, cx); PK11_FreeSlot(slot); - return(privk); + return (privk); } -/* Create an EC key pair in any slot able to do so, -** This is a "session" (temporary), not "token" (permanent) key. +/* Create an EC key pair in any slot able to do so, +** This is a "session" (temporary), not "token" (permanent) key. ** Because of the high probability that this key will need to be moved to ** another token, and the high cost of moving "sensitive" keys, we attempt -** to create this key pair without the "sensitive" attribute, but revert to +** to create this key pair without the "sensitive" attribute, but revert to ** creating a "sensitive" key if necessary. */ SECKEYPrivateKey * SECKEY_CreateECPrivateKey(SECKEYECParams *param, SECKEYPublicKey **pubk, void *cx) { SECKEYPrivateKey *privk; - PK11SlotInfo *slot = PK11_GetBestSlot(CKM_EC_KEY_PAIR_GEN,cx); + PK11SlotInfo *slot = PK11_GetBestSlot(CKM_EC_KEY_PAIR_GEN, cx); if (!slot) { - return NULL; + return NULL; } - privk = PK11_GenerateKeyPairWithOpFlags(slot, CKM_EC_KEY_PAIR_GEN, - param, pubk, - PK11_ATTR_SESSION | PK11_ATTR_INSENSITIVE | - PK11_ATTR_PUBLIC, - CKF_DERIVE, CKF_DERIVE|CKF_SIGN,cx); - if (!privk) - privk = PK11_GenerateKeyPairWithOpFlags(slot, CKM_EC_KEY_PAIR_GEN, - param, pubk, - PK11_ATTR_SESSION | PK11_ATTR_SENSITIVE | - PK11_ATTR_PRIVATE, - CKF_DERIVE, CKF_DERIVE|CKF_SIGN,cx); + privk = PK11_GenerateKeyPairWithOpFlags(slot, CKM_EC_KEY_PAIR_GEN, + param, pubk, + PK11_ATTR_SESSION | + PK11_ATTR_INSENSITIVE | + PK11_ATTR_PUBLIC, + CKF_DERIVE, CKF_DERIVE | + CKF_SIGN, + cx); + if (!privk) + privk = PK11_GenerateKeyPairWithOpFlags(slot, CKM_EC_KEY_PAIR_GEN, + param, pubk, + PK11_ATTR_SESSION | + PK11_ATTR_SENSITIVE | + PK11_ATTR_PRIVATE, + CKF_DERIVE, CKF_DERIVE | + CKF_SIGN, + cx); PK11_FreeSlot(slot); - return(privk); + return (privk); } void SECKEY_DestroyPrivateKey(SECKEYPrivateKey *privk) { if (privk) { - if (privk->pkcs11Slot) { - if (privk->pkcs11IsTemp) { - PK11_DestroyObject(privk->pkcs11Slot,privk->pkcs11ID); - } - PK11_FreeSlot(privk->pkcs11Slot); - - } - if (privk->arena) { - PORT_FreeArena(privk->arena, PR_TRUE); - } + if (privk->pkcs11Slot) { + if (privk->pkcs11IsTemp) { + PK11_DestroyObject(privk->pkcs11Slot, privk->pkcs11ID); + } + PK11_FreeSlot(privk->pkcs11Slot); + } + if (privk->arena) { + PORT_FreeArena(privk->arena, PR_TRUE); + } } } @@ -253,39 +258,39 @@ void SECKEY_DestroyPublicKey(SECKEYPublicKey *pubk) { if (pubk) { - if (pubk->pkcs11Slot) { - if (!PK11_IsPermObject(pubk->pkcs11Slot,pubk->pkcs11ID)) { - PK11_DestroyObject(pubk->pkcs11Slot,pubk->pkcs11ID); - } - PK11_FreeSlot(pubk->pkcs11Slot); - } - if (pubk->arena) { - PORT_FreeArena(pubk->arena, PR_FALSE); - } + if (pubk->pkcs11Slot) { + if (!PK11_IsPermObject(pubk->pkcs11Slot, pubk->pkcs11ID)) { + PK11_DestroyObject(pubk->pkcs11Slot, pubk->pkcs11ID); + } + PK11_FreeSlot(pubk->pkcs11Slot); + } + if (pubk->arena) { + PORT_FreeArena(pubk->arena, PR_FALSE); + } } } SECStatus SECKEY_CopySubjectPublicKeyInfo(PLArenaPool *arena, - CERTSubjectPublicKeyInfo *to, - CERTSubjectPublicKeyInfo *from) + CERTSubjectPublicKeyInfo *to, + CERTSubjectPublicKeyInfo *from) { SECStatus rv; SECItem spk; rv = SECOID_CopyAlgorithmID(arena, &to->algorithm, &from->algorithm); if (rv == SECSuccess) { - /* - * subjectPublicKey is a bit string, whose length is in bits. - * Convert the length from bits to bytes for SECITEM_CopyItem. - */ - spk = from->subjectPublicKey; - DER_ConvertBitString(&spk); - rv = SECITEM_CopyItem(arena, &to->subjectPublicKey, &spk); - /* Set the length back to bits. */ - if (rv == SECSuccess) { - to->subjectPublicKey.len = from->subjectPublicKey.len; - } + /* + * subjectPublicKey is a bit string, whose length is in bits. + * Convert the length from bits to bytes for SECITEM_CopyItem. + */ + spk = from->subjectPublicKey; + DER_ConvertBitString(&spk); + rv = SECITEM_CopyItem(arena, &to->subjectPublicKey, &spk); + /* Set the length back to bits. */ + if (rv == SECSuccess) { + to->subjectPublicKey.len = from->subjectPublicKey.len; + } } return rv; @@ -301,13 +306,13 @@ SECKEY_CopySubjectPublicKeyInfo(PLArenaPool *arena, * pqg parameters that has a parent that is not a DSA cert. */ static SECStatus -seckey_UpdateCertPQGChain(CERTCertificate * subjectCert, int count) +seckey_UpdateCertPQGChain(CERTCertificate *subjectCert, int count) { SECStatus rv; - SECOidData *oid=NULL; + SECOidData *oid = NULL; int tag; - CERTSubjectPublicKeyInfo * subjectSpki=NULL; - CERTSubjectPublicKeyInfo * issuerSpki=NULL; + CERTSubjectPublicKeyInfo *subjectSpki = NULL; + CERTSubjectPublicKeyInfo *issuerSpki = NULL; CERTCertificate *issuerCert = NULL; rv = SECSuccess; @@ -317,39 +322,40 @@ seckey_UpdateCertPQGChain(CERTCertificate * subjectCert, int count) /* check if cert chain length exceeds the maximum length*/ if (count > CERT_MAX_CERT_CHAIN) { - return SECFailure; + return SECFailure; } - oid = SECOID_FindOID(&subjectCert->subjectPublicKeyInfo.algorithm.algorithm); - if (oid != NULL) { + oid = SECOID_FindOID(&subjectCert->subjectPublicKeyInfo.algorithm.algorithm); + if (oid != NULL) { tag = oid->offset; - + /* Check if cert has a DSA or EC public key. If not, return * success since no PQG params need to be updated. - * - * Question: do we really need to do this for EC keys. They don't have - * PQG parameters, but they do have parameters. The question is does - * the child cert inherit thost parameters for EC from the parent, or - * do we always include those parameters in each cert. - */ + * + * Question: do we really need to do this for EC keys. They don't have + * PQG parameters, but they do have parameters. The question is does + * the child cert inherit thost parameters for EC from the parent, or + * do we always include those parameters in each cert. + */ + + if ((tag != SEC_OID_ANSIX9_DSA_SIGNATURE) && + (tag != SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST) && + (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST) && + (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST) && + (tag != SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST) && + (tag != SEC_OID_SDN702_DSA_SIGNATURE) && + (tag != SEC_OID_ANSIX962_EC_PUBLIC_KEY)) { - if ( (tag != SEC_OID_ANSIX9_DSA_SIGNATURE) && - (tag != SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST) && - (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST) && - (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST) && - (tag != SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST) && - (tag != SEC_OID_SDN702_DSA_SIGNATURE) && - (tag != SEC_OID_ANSIX962_EC_PUBLIC_KEY) ) { - return SECSuccess; } - } else { - return SECFailure; /* return failure if oid is NULL */ + } + else { + return SECFailure; /* return failure if oid is NULL */ } /* if cert has PQG parameters, return success */ - subjectSpki=&subjectCert->subjectPublicKeyInfo; + subjectSpki = &subjectCert->subjectPublicKeyInfo; if (subjectSpki->algorithm.parameters.len != 0) { return SECSuccess; @@ -357,42 +363,42 @@ seckey_UpdateCertPQGChain(CERTCertificate * subjectCert, int count) /* check if the cert is self-signed */ if (subjectCert->isRoot) { - /* fail since cert is self-signed and has no pqg params. */ - return SECFailure; + /* fail since cert is self-signed and has no pqg params. */ + return SECFailure; } - + /* get issuer cert */ issuerCert = CERT_FindCertIssuer(subjectCert, PR_Now(), certUsageAnyCA); - if ( ! issuerCert ) { - return SECFailure; + if (!issuerCert) { + return SECFailure; } /* if parent is not DSA, return failure since we don't allow this case. */ oid = SECOID_FindOID(&issuerCert->subjectPublicKeyInfo.algorithm.algorithm); - if (oid != NULL) { + if (oid != NULL) { tag = oid->offset; - + /* Check if issuer cert has a DSA public key. If not, * return failure. */ - if ( (tag != SEC_OID_ANSIX9_DSA_SIGNATURE) && - (tag != SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST) && - (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST) && - (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST) && - (tag != SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST) && - (tag != SEC_OID_SDN702_DSA_SIGNATURE) && - (tag != SEC_OID_ANSIX962_EC_PUBLIC_KEY) ) { + if ((tag != SEC_OID_ANSIX9_DSA_SIGNATURE) && + (tag != SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST) && + (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST) && + (tag != SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST) && + (tag != SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST) && + (tag != SEC_OID_SDN702_DSA_SIGNATURE) && + (tag != SEC_OID_ANSIX962_EC_PUBLIC_KEY)) { rv = SECFailure; goto loser; } - } else { - rv = SECFailure; /* return failure if oid is NULL */ + } + else { + rv = SECFailure; /* return failure if oid is NULL */ goto loser; } - /* at this point the subject cert has no pqg parameters and the * issuer cert has a DSA public key. Update the issuer's * pqg parameters with a recursive call to this same function. */ @@ -405,9 +411,9 @@ seckey_UpdateCertPQGChain(CERTCertificate * subjectCert, int count) /* ensure issuer has pqg parameters */ - issuerSpki=&issuerCert->subjectPublicKeyInfo; + issuerSpki = &issuerCert->subjectPublicKeyInfo; if (issuerSpki->algorithm.parameters.len == 0) { - rv = SECFailure; + rv = SECFailure; } /* if update was successful and pqg params present, then copy the @@ -415,8 +421,8 @@ seckey_UpdateCertPQGChain(CERTCertificate * subjectCert, int count) if (rv == SECSuccess) { rv = SECITEM_CopyItem(subjectCert->arena, - &subjectSpki->algorithm.parameters, - &issuerSpki->algorithm.parameters); + &subjectSpki->algorithm.parameters, + &issuerSpki->algorithm.parameters); } loser: @@ -424,35 +430,35 @@ loser: CERT_DestroyCertificate(issuerCert); } return rv; - } - SECStatus -SECKEY_UpdateCertPQG(CERTCertificate * subjectCert) +SECKEY_UpdateCertPQG(CERTCertificate *subjectCert) { if (!subjectCert) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + return SECFailure; } - return seckey_UpdateCertPQGChain(subjectCert,0); + return seckey_UpdateCertPQGChain(subjectCert, 0); } - /* Decode the DSA PQG parameters. The params could be stored in two * possible formats, the old fortezza-only wrapped format or * the normal standard format. Store the decoded parameters in - * a V3 certificate data structure. */ + * a V3 certificate data structure. */ static SECStatus seckey_DSADecodePQG(PLArenaPool *arena, SECKEYPublicKey *pubk, - const SECItem *params) { + const SECItem *params) +{ SECStatus rv; SECItem newparams; - if (params == NULL) return SECFailure; - - if (params->data == NULL) return SECFailure; + if (params == NULL) + return SECFailure; + + if (params->data == NULL) + return SECFailure; PORT_Assert(arena); @@ -467,15 +473,16 @@ seckey_DSADecodePQG(PLArenaPool *arena, SECKEYPublicKey *pubk, if ((newparams.data[0] != 0xa1) && (newparams.data[0] != 0xa0)) { - + if (SECSuccess == rv) { - /* PQG params are in the standard format */ - prepare_pqg_params_for_asn1(&pubk->u.dsa.params); - rv = SEC_QuickDERDecodeItem(arena, &pubk->u.dsa.params, - SECKEY_PQGParamsTemplate, - &newparams); + /* PQG params are in the standard format */ + prepare_pqg_params_for_asn1(&pubk->u.dsa.params); + rv = SEC_QuickDERDecodeItem(arena, &pubk->u.dsa.params, + SECKEY_PQGParamsTemplate, + &newparams); } - } else { + } + else { if (SECSuccess == rv) { /* else the old fortezza-only wrapped format is used. */ @@ -486,61 +493,61 @@ seckey_DSADecodePQG(PLArenaPool *arena, SECKEYPublicKey *pubk, return rv; } - /* Function used to make an oid tag to a key type */ -KeyType -seckey_GetKeyType (SECOidTag tag) { +KeyType +seckey_GetKeyType(SECOidTag tag) +{ KeyType keyType; switch (tag) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - keyType = rsaKey; - break; - case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: - keyType = rsaPssKey; - break; - case SEC_OID_PKCS1_RSA_OAEP_ENCRYPTION: - keyType = rsaOaepKey; - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - keyType = dsaKey; - break; - case SEC_OID_MISSI_KEA_DSS_OLD: - case SEC_OID_MISSI_KEA_DSS: - case SEC_OID_MISSI_DSS_OLD: - case SEC_OID_MISSI_DSS: - keyType = fortezzaKey; - break; - case SEC_OID_MISSI_KEA: - case SEC_OID_MISSI_ALT_KEA: - keyType = keaKey; - break; - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - keyType = dhKey; - break; - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - keyType = ecKey; - break; - /* accommodate applications that hand us a signature type when they - * should be handing us a cipher type */ - case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: - keyType = rsaKey; - break; - default: - keyType = nullKey; + case SEC_OID_X500_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_ENCRYPTION: + keyType = rsaKey; + break; + case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: + keyType = rsaPssKey; + break; + case SEC_OID_PKCS1_RSA_OAEP_ENCRYPTION: + keyType = rsaOaepKey; + break; + case SEC_OID_ANSIX9_DSA_SIGNATURE: + keyType = dsaKey; + break; + case SEC_OID_MISSI_KEA_DSS_OLD: + case SEC_OID_MISSI_KEA_DSS: + case SEC_OID_MISSI_DSS_OLD: + case SEC_OID_MISSI_DSS: + keyType = fortezzaKey; + break; + case SEC_OID_MISSI_KEA: + case SEC_OID_MISSI_ALT_KEA: + keyType = keaKey; + break; + case SEC_OID_X942_DIFFIE_HELMAN_KEY: + keyType = dhKey; + break; + case SEC_OID_ANSIX962_EC_PUBLIC_KEY: + keyType = ecKey; + break; + /* accommodate applications that hand us a signature type when they + * should be handing us a cipher type */ + case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: + keyType = rsaKey; + break; + default: + keyType = nullKey; } return keyType; } /* Function used to determine what kind of cert we are dealing with. */ -KeyType -CERT_GetCertKeyType (const CERTSubjectPublicKeyInfo *spki) +KeyType +CERT_GetCertKeyType(const CERTSubjectPublicKeyInfo *spki) { return seckey_GetKeyType(SECOID_GetAlgorithmTag(&spki->algorithm)); } @@ -554,95 +561,98 @@ seckey_ExtractPublicKey(const CERTSubjectPublicKeyInfo *spki) PLArenaPool *arena; SECOidTag tag; - arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) - return NULL; + return NULL; - pubk = (SECKEYPublicKey *) PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey)); + pubk = (SECKEYPublicKey *)PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey)); if (pubk == NULL) { - PORT_FreeArena (arena, PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } pubk->arena = arena; pubk->pkcs11Slot = 0; pubk->pkcs11ID = CK_INVALID_HANDLE; - /* Convert bit string length from bits to bytes */ os = spki->subjectPublicKey; - DER_ConvertBitString (&os); + DER_ConvertBitString(&os); tag = SECOID_GetAlgorithmTag(&spki->algorithm); /* 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, &newOs, &os); - if ( rv == SECSuccess ) - switch ( tag ) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - pubk->keyType = rsaKey; - prepare_rsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_RSAPublicKeyTemplate, &newOs); - if (rv == SECSuccess) - return pubk; - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - case SEC_OID_SDN702_DSA_SIGNATURE: - pubk->keyType = dsaKey; - prepare_dsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DSAPublicKeyTemplate, &newOs); - if (rv != SECSuccess) break; + if (rv == SECSuccess) + switch (tag) { + case SEC_OID_X500_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_ENCRYPTION: + pubk->keyType = rsaKey; + prepare_rsa_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_RSAPublicKeyTemplate, &newOs); + if (rv == SECSuccess) + return pubk; + break; + case SEC_OID_ANSIX9_DSA_SIGNATURE: + case SEC_OID_SDN702_DSA_SIGNATURE: + pubk->keyType = dsaKey; + prepare_dsa_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DSAPublicKeyTemplate, &newOs); + if (rv != SECSuccess) + break; - rv = seckey_DSADecodePQG(arena, pubk, - &spki->algorithm.parameters); + rv = seckey_DSADecodePQG(arena, pubk, + &spki->algorithm.parameters); - if (rv == SECSuccess) return pubk; - break; - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - pubk->keyType = dhKey; - prepare_dh_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DHPublicKeyTemplate, &newOs); - if (rv != SECSuccess) break; + if (rv == SECSuccess) + return pubk; + break; + case SEC_OID_X942_DIFFIE_HELMAN_KEY: + pubk->keyType = dhKey; + prepare_dh_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DHPublicKeyTemplate, &newOs); + if (rv != SECSuccess) + break; - /* 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, &newParms, &spki->algorithm.parameters); - if ( rv != SECSuccess ) - break; + /* 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, &newParms, &spki->algorithm.parameters); + if (rv != SECSuccess) + break; - rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DHParamKeyTemplate, - &newParms); + rv = SEC_QuickDERDecodeItem(arena, pubk, SECKEY_DHParamKeyTemplate, + &newParms); - if (rv == SECSuccess) return pubk; - break; - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - pubk->keyType = ecKey; - pubk->u.ec.size = 0; + if (rv == SECSuccess) + return pubk; + break; + case SEC_OID_ANSIX962_EC_PUBLIC_KEY: + pubk->keyType = ecKey; + pubk->u.ec.size = 0; - /* 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.DEREncodedParams, - &spki->algorithm.parameters); - if ( rv != SECSuccess ) - break; - rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, &newOs); - if (rv == SECSuccess) return pubk; - break; + /* 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.DEREncodedParams, + &spki->algorithm.parameters); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, &newOs); + if (rv == SECSuccess) + return pubk; + break; - default: - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - rv = SECFailure; - break; - } + default: + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); + rv = SECFailure; + break; + } - SECKEY_DestroyPublicKey (pubk); + SECKEY_DestroyPublicKey(pubk); return NULL; } - /* required for JSS */ SECKEYPublicKey * SECKEY_ExtractPublicKey(const CERTSubjectPublicKeyInfo *spki) @@ -657,10 +667,11 @@ CERT_ExtractPublicKey(CERTCertificate *cert) if (!cert) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + return NULL; } rv = SECKEY_UpdateCertPQG(cert); - if (rv != SECSuccess) return NULL; + if (rv != SECSuccess) + return NULL; return seckey_ExtractPublicKey(&cert->subjectPublicKeyInfo); } @@ -669,128 +680,128 @@ int SECKEY_ECParamsToKeySize(const SECItem *encodedParams) { SECOidTag tag; - SECItem oid = { siBuffer, NULL, 0}; - + SECItem oid = { siBuffer, NULL, 0 }; + /* The encodedParams data contains 0x06 (SEC_ASN1_OBJECT_ID), * followed by the length of the curve oid and the curve oid. */ oid.len = encodedParams->data[1]; oid.data = encodedParams->data + 2; if ((tag = SECOID_FindOIDTag(&oid)) == SEC_OID_UNKNOWN) - return 0; + return 0; switch (tag) { - case SEC_OID_SECG_EC_SECP112R1: - case SEC_OID_SECG_EC_SECP112R2: - return 112; + case SEC_OID_SECG_EC_SECP112R1: + case SEC_OID_SECG_EC_SECP112R2: + return 112; - case SEC_OID_SECG_EC_SECT113R1: - case SEC_OID_SECG_EC_SECT113R2: - return 113; + case SEC_OID_SECG_EC_SECT113R1: + case SEC_OID_SECG_EC_SECT113R2: + return 113; - case SEC_OID_SECG_EC_SECP128R1: - case SEC_OID_SECG_EC_SECP128R2: - return 128; + case SEC_OID_SECG_EC_SECP128R1: + case SEC_OID_SECG_EC_SECP128R2: + return 128; - case SEC_OID_SECG_EC_SECT131R1: - case SEC_OID_SECG_EC_SECT131R2: - return 131; + case SEC_OID_SECG_EC_SECT131R1: + case SEC_OID_SECG_EC_SECT131R2: + return 131; - case SEC_OID_SECG_EC_SECP160K1: - case SEC_OID_SECG_EC_SECP160R1: - case SEC_OID_SECG_EC_SECP160R2: - return 160; + case SEC_OID_SECG_EC_SECP160K1: + case SEC_OID_SECG_EC_SECP160R1: + case SEC_OID_SECG_EC_SECP160R2: + return 160; - case SEC_OID_SECG_EC_SECT163K1: - case SEC_OID_SECG_EC_SECT163R1: - case SEC_OID_SECG_EC_SECT163R2: - case SEC_OID_ANSIX962_EC_C2PNB163V1: - case SEC_OID_ANSIX962_EC_C2PNB163V2: - case SEC_OID_ANSIX962_EC_C2PNB163V3: - return 163; + case SEC_OID_SECG_EC_SECT163K1: + case SEC_OID_SECG_EC_SECT163R1: + case SEC_OID_SECG_EC_SECT163R2: + case SEC_OID_ANSIX962_EC_C2PNB163V1: + case SEC_OID_ANSIX962_EC_C2PNB163V2: + case SEC_OID_ANSIX962_EC_C2PNB163V3: + return 163; - case SEC_OID_ANSIX962_EC_C2PNB176V1: - return 176; + case SEC_OID_ANSIX962_EC_C2PNB176V1: + return 176; - case SEC_OID_ANSIX962_EC_C2TNB191V1: - case SEC_OID_ANSIX962_EC_C2TNB191V2: - case SEC_OID_ANSIX962_EC_C2TNB191V3: - case SEC_OID_ANSIX962_EC_C2ONB191V4: - case SEC_OID_ANSIX962_EC_C2ONB191V5: - return 191; + case SEC_OID_ANSIX962_EC_C2TNB191V1: + case SEC_OID_ANSIX962_EC_C2TNB191V2: + case SEC_OID_ANSIX962_EC_C2TNB191V3: + case SEC_OID_ANSIX962_EC_C2ONB191V4: + case SEC_OID_ANSIX962_EC_C2ONB191V5: + return 191; - case SEC_OID_SECG_EC_SECP192K1: - case SEC_OID_ANSIX962_EC_PRIME192V1: - case SEC_OID_ANSIX962_EC_PRIME192V2: - case SEC_OID_ANSIX962_EC_PRIME192V3: - return 192; + case SEC_OID_SECG_EC_SECP192K1: + case SEC_OID_ANSIX962_EC_PRIME192V1: + case SEC_OID_ANSIX962_EC_PRIME192V2: + case SEC_OID_ANSIX962_EC_PRIME192V3: + return 192; - case SEC_OID_SECG_EC_SECT193R1: - case SEC_OID_SECG_EC_SECT193R2: - return 193; + case SEC_OID_SECG_EC_SECT193R1: + case SEC_OID_SECG_EC_SECT193R2: + return 193; - case SEC_OID_ANSIX962_EC_C2PNB208W1: - return 208; + case SEC_OID_ANSIX962_EC_C2PNB208W1: + return 208; - case SEC_OID_SECG_EC_SECP224K1: - case SEC_OID_SECG_EC_SECP224R1: - return 224; + case SEC_OID_SECG_EC_SECP224K1: + case SEC_OID_SECG_EC_SECP224R1: + return 224; - case SEC_OID_SECG_EC_SECT233K1: - case SEC_OID_SECG_EC_SECT233R1: - return 233; + case SEC_OID_SECG_EC_SECT233K1: + case SEC_OID_SECG_EC_SECT233R1: + return 233; - case SEC_OID_SECG_EC_SECT239K1: - case SEC_OID_ANSIX962_EC_C2TNB239V1: - case SEC_OID_ANSIX962_EC_C2TNB239V2: - case SEC_OID_ANSIX962_EC_C2TNB239V3: - case SEC_OID_ANSIX962_EC_C2ONB239V4: - case SEC_OID_ANSIX962_EC_C2ONB239V5: - case SEC_OID_ANSIX962_EC_PRIME239V1: - case SEC_OID_ANSIX962_EC_PRIME239V2: - case SEC_OID_ANSIX962_EC_PRIME239V3: - return 239; + case SEC_OID_SECG_EC_SECT239K1: + case SEC_OID_ANSIX962_EC_C2TNB239V1: + case SEC_OID_ANSIX962_EC_C2TNB239V2: + case SEC_OID_ANSIX962_EC_C2TNB239V3: + case SEC_OID_ANSIX962_EC_C2ONB239V4: + case SEC_OID_ANSIX962_EC_C2ONB239V5: + case SEC_OID_ANSIX962_EC_PRIME239V1: + case SEC_OID_ANSIX962_EC_PRIME239V2: + case SEC_OID_ANSIX962_EC_PRIME239V3: + return 239; - case SEC_OID_SECG_EC_SECP256K1: - case SEC_OID_ANSIX962_EC_PRIME256V1: - return 256; + case SEC_OID_SECG_EC_SECP256K1: + case SEC_OID_ANSIX962_EC_PRIME256V1: + return 256; - case SEC_OID_ANSIX962_EC_C2PNB272W1: - return 272; + case SEC_OID_ANSIX962_EC_C2PNB272W1: + return 272; - case SEC_OID_SECG_EC_SECT283K1: - case SEC_OID_SECG_EC_SECT283R1: - return 283; + case SEC_OID_SECG_EC_SECT283K1: + case SEC_OID_SECG_EC_SECT283R1: + return 283; - case SEC_OID_ANSIX962_EC_C2PNB304W1: - return 304; + case SEC_OID_ANSIX962_EC_C2PNB304W1: + return 304; - case SEC_OID_ANSIX962_EC_C2TNB359V1: - return 359; + case SEC_OID_ANSIX962_EC_C2TNB359V1: + return 359; - case SEC_OID_ANSIX962_EC_C2PNB368W1: - return 368; + case SEC_OID_ANSIX962_EC_C2PNB368W1: + return 368; - case SEC_OID_SECG_EC_SECP384R1: - return 384; + case SEC_OID_SECG_EC_SECP384R1: + return 384; - case SEC_OID_SECG_EC_SECT409K1: - case SEC_OID_SECG_EC_SECT409R1: - return 409; + case SEC_OID_SECG_EC_SECT409K1: + case SEC_OID_SECG_EC_SECT409R1: + return 409; - case SEC_OID_ANSIX962_EC_C2TNB431R1: - return 431; + case SEC_OID_ANSIX962_EC_C2TNB431R1: + return 431; - case SEC_OID_SECG_EC_SECP521R1: - return 521; + case SEC_OID_SECG_EC_SECP521R1: + return 521; - case SEC_OID_SECG_EC_SECT571K1: - case SEC_OID_SECG_EC_SECT571R1: - return 571; + case SEC_OID_SECG_EC_SECT571K1: + case SEC_OID_SECG_EC_SECT571R1: + return 571; - default: - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - return 0; + default: + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); + return 0; } } @@ -798,146 +809,146 @@ int SECKEY_ECParamsToBasePointOrderLen(const SECItem *encodedParams) { SECOidTag tag; - SECItem oid = { siBuffer, NULL, 0}; - + SECItem oid = { siBuffer, NULL, 0 }; + /* The encodedParams data contains 0x06 (SEC_ASN1_OBJECT_ID), * followed by the length of the curve oid and the curve oid. */ oid.len = encodedParams->data[1]; oid.data = encodedParams->data + 2; if ((tag = SECOID_FindOIDTag(&oid)) == SEC_OID_UNKNOWN) - return 0; + return 0; switch (tag) { - case SEC_OID_SECG_EC_SECP112R1: - return 112; - case SEC_OID_SECG_EC_SECP112R2: - return 110; + case SEC_OID_SECG_EC_SECP112R1: + return 112; + case SEC_OID_SECG_EC_SECP112R2: + return 110; - case SEC_OID_SECG_EC_SECT113R1: - case SEC_OID_SECG_EC_SECT113R2: - return 113; + case SEC_OID_SECG_EC_SECT113R1: + case SEC_OID_SECG_EC_SECT113R2: + return 113; - case SEC_OID_SECG_EC_SECP128R1: - return 128; - case SEC_OID_SECG_EC_SECP128R2: - return 126; + case SEC_OID_SECG_EC_SECP128R1: + return 128; + case SEC_OID_SECG_EC_SECP128R2: + return 126; - case SEC_OID_SECG_EC_SECT131R1: - case SEC_OID_SECG_EC_SECT131R2: - return 131; + case SEC_OID_SECG_EC_SECT131R1: + case SEC_OID_SECG_EC_SECT131R2: + return 131; - case SEC_OID_SECG_EC_SECP160K1: - case SEC_OID_SECG_EC_SECP160R1: - case SEC_OID_SECG_EC_SECP160R2: - return 161; + case SEC_OID_SECG_EC_SECP160K1: + case SEC_OID_SECG_EC_SECP160R1: + case SEC_OID_SECG_EC_SECP160R2: + return 161; - case SEC_OID_SECG_EC_SECT163K1: - return 163; - case SEC_OID_SECG_EC_SECT163R1: - return 162; - case SEC_OID_SECG_EC_SECT163R2: - case SEC_OID_ANSIX962_EC_C2PNB163V1: - return 163; - case SEC_OID_ANSIX962_EC_C2PNB163V2: - case SEC_OID_ANSIX962_EC_C2PNB163V3: - return 162; + case SEC_OID_SECG_EC_SECT163K1: + return 163; + case SEC_OID_SECG_EC_SECT163R1: + return 162; + case SEC_OID_SECG_EC_SECT163R2: + case SEC_OID_ANSIX962_EC_C2PNB163V1: + return 163; + case SEC_OID_ANSIX962_EC_C2PNB163V2: + case SEC_OID_ANSIX962_EC_C2PNB163V3: + return 162; - case SEC_OID_ANSIX962_EC_C2PNB176V1: - return 161; + case SEC_OID_ANSIX962_EC_C2PNB176V1: + return 161; - case SEC_OID_ANSIX962_EC_C2TNB191V1: - return 191; - case SEC_OID_ANSIX962_EC_C2TNB191V2: - return 190; - case SEC_OID_ANSIX962_EC_C2TNB191V3: - return 189; - case SEC_OID_ANSIX962_EC_C2ONB191V4: - return 191; - case SEC_OID_ANSIX962_EC_C2ONB191V5: - return 188; + case SEC_OID_ANSIX962_EC_C2TNB191V1: + return 191; + case SEC_OID_ANSIX962_EC_C2TNB191V2: + return 190; + case SEC_OID_ANSIX962_EC_C2TNB191V3: + return 189; + case SEC_OID_ANSIX962_EC_C2ONB191V4: + return 191; + case SEC_OID_ANSIX962_EC_C2ONB191V5: + return 188; - case SEC_OID_SECG_EC_SECP192K1: - case SEC_OID_ANSIX962_EC_PRIME192V1: - case SEC_OID_ANSIX962_EC_PRIME192V2: - case SEC_OID_ANSIX962_EC_PRIME192V3: - return 192; + case SEC_OID_SECG_EC_SECP192K1: + case SEC_OID_ANSIX962_EC_PRIME192V1: + case SEC_OID_ANSIX962_EC_PRIME192V2: + case SEC_OID_ANSIX962_EC_PRIME192V3: + return 192; - case SEC_OID_SECG_EC_SECT193R1: - case SEC_OID_SECG_EC_SECT193R2: - return 193; + case SEC_OID_SECG_EC_SECT193R1: + case SEC_OID_SECG_EC_SECT193R2: + return 193; - case SEC_OID_ANSIX962_EC_C2PNB208W1: - return 193; + case SEC_OID_ANSIX962_EC_C2PNB208W1: + return 193; - case SEC_OID_SECG_EC_SECP224K1: - return 225; - case SEC_OID_SECG_EC_SECP224R1: - return 224; + case SEC_OID_SECG_EC_SECP224K1: + return 225; + case SEC_OID_SECG_EC_SECP224R1: + return 224; - case SEC_OID_SECG_EC_SECT233K1: - return 232; - case SEC_OID_SECG_EC_SECT233R1: - return 233; + case SEC_OID_SECG_EC_SECT233K1: + return 232; + case SEC_OID_SECG_EC_SECT233R1: + return 233; - case SEC_OID_SECG_EC_SECT239K1: - case SEC_OID_ANSIX962_EC_C2TNB239V1: - return 238; - case SEC_OID_ANSIX962_EC_C2TNB239V2: - return 237; - case SEC_OID_ANSIX962_EC_C2TNB239V3: - return 236; - case SEC_OID_ANSIX962_EC_C2ONB239V4: - return 238; - case SEC_OID_ANSIX962_EC_C2ONB239V5: - return 237; - case SEC_OID_ANSIX962_EC_PRIME239V1: - case SEC_OID_ANSIX962_EC_PRIME239V2: - case SEC_OID_ANSIX962_EC_PRIME239V3: - return 239; + case SEC_OID_SECG_EC_SECT239K1: + case SEC_OID_ANSIX962_EC_C2TNB239V1: + return 238; + case SEC_OID_ANSIX962_EC_C2TNB239V2: + return 237; + case SEC_OID_ANSIX962_EC_C2TNB239V3: + return 236; + case SEC_OID_ANSIX962_EC_C2ONB239V4: + return 238; + case SEC_OID_ANSIX962_EC_C2ONB239V5: + return 237; + case SEC_OID_ANSIX962_EC_PRIME239V1: + case SEC_OID_ANSIX962_EC_PRIME239V2: + case SEC_OID_ANSIX962_EC_PRIME239V3: + return 239; - case SEC_OID_SECG_EC_SECP256K1: - case SEC_OID_ANSIX962_EC_PRIME256V1: - return 256; + case SEC_OID_SECG_EC_SECP256K1: + case SEC_OID_ANSIX962_EC_PRIME256V1: + return 256; - case SEC_OID_ANSIX962_EC_C2PNB272W1: - return 257; + case SEC_OID_ANSIX962_EC_C2PNB272W1: + return 257; - case SEC_OID_SECG_EC_SECT283K1: - return 281; - case SEC_OID_SECG_EC_SECT283R1: - return 282; + case SEC_OID_SECG_EC_SECT283K1: + return 281; + case SEC_OID_SECG_EC_SECT283R1: + return 282; - case SEC_OID_ANSIX962_EC_C2PNB304W1: - return 289; + case SEC_OID_ANSIX962_EC_C2PNB304W1: + return 289; - case SEC_OID_ANSIX962_EC_C2TNB359V1: - return 353; + case SEC_OID_ANSIX962_EC_C2TNB359V1: + return 353; - case SEC_OID_ANSIX962_EC_C2PNB368W1: - return 353; + case SEC_OID_ANSIX962_EC_C2PNB368W1: + return 353; - case SEC_OID_SECG_EC_SECP384R1: - return 384; + case SEC_OID_SECG_EC_SECP384R1: + return 384; - case SEC_OID_SECG_EC_SECT409K1: - return 407; - case SEC_OID_SECG_EC_SECT409R1: - return 409; + case SEC_OID_SECG_EC_SECT409K1: + return 407; + case SEC_OID_SECG_EC_SECT409R1: + return 409; - case SEC_OID_ANSIX962_EC_C2TNB431R1: - return 418; + case SEC_OID_ANSIX962_EC_C2TNB431R1: + return 418; - case SEC_OID_SECG_EC_SECP521R1: - return 521; + case SEC_OID_SECG_EC_SECP521R1: + return 521; - case SEC_OID_SECG_EC_SECT571K1: - case SEC_OID_SECG_EC_SECT571R1: - return 570; + case SEC_OID_SECG_EC_SECT571K1: + case SEC_OID_SECG_EC_SECT571R1: + return 570; - default: - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - return 0; + default: + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); + return 0; } } @@ -994,21 +1005,21 @@ SECKEY_PublicKeyStrengthInBits(const SECKEYPublicKey *pubk) /* interpret modulus length as key strength */ switch (pubk->keyType) { - case rsaKey: - bitSize = SECKEY_BigIntegerBitLength(&pubk->u.rsa.modulus); - break; - case dsaKey: - bitSize = SECKEY_BigIntegerBitLength(&pubk->u.dsa.publicValue); - break; - case dhKey: - bitSize = SECKEY_BigIntegerBitLength(&pubk->u.dh.publicValue); - break; - case ecKey: - bitSize = SECKEY_ECParamsToKeySize(&pubk->u.ec.DEREncodedParams); - break; - default: - PORT_SetError(SEC_ERROR_INVALID_KEY); - break; + case rsaKey: + bitSize = SECKEY_BigIntegerBitLength(&pubk->u.rsa.modulus); + break; + case dsaKey: + bitSize = SECKEY_BigIntegerBitLength(&pubk->u.dsa.params.prime); + break; + case dhKey: + bitSize = SECKEY_BigIntegerBitLength(&pubk->u.dh.prime); + break; + case ecKey: + bitSize = SECKEY_ECParamsToKeySize(&pubk->u.ec.DEREncodedParams); + break; + default: + PORT_SetError(SEC_ERROR_INVALID_KEY); + break; } return bitSize; } @@ -1021,18 +1032,18 @@ SECKEY_SignatureLen(const SECKEYPublicKey *pubk) unsigned size; switch (pubk->keyType) { - case rsaKey: - b0 = pubk->u.rsa.modulus.data[0]; - return b0 ? pubk->u.rsa.modulus.len : pubk->u.rsa.modulus.len - 1; - case dsaKey: - return pubk->u.dsa.params.subPrime.len * 2; - case ecKey: - /* Get the base point order length in bits and adjust */ - size = SECKEY_ECParamsToBasePointOrderLen( - &pubk->u.ec.DEREncodedParams); - return ((size + 7)/8) * 2; - default: - break; + case rsaKey: + b0 = pubk->u.rsa.modulus.data[0]; + return b0 ? pubk->u.rsa.modulus.len : pubk->u.rsa.modulus.len - 1; + case dsaKey: + return pubk->u.dsa.params.subPrime.len * 2; + case ecKey: + /* Get the base point order length in bits and adjust */ + size = SECKEY_ECParamsToBasePointOrderLen( + &pubk->u.ec.DEREncodedParams); + return ((size + 7) / 8) * 2; + default: + break; } PORT_SetError(SEC_ERROR_INVALID_KEY); return 0; @@ -1043,44 +1054,47 @@ SECKEY_CopyPrivateKey(const SECKEYPrivateKey *privk) { SECKEYPrivateKey *copyk; PLArenaPool *arena; - + if (!privk || !privk->pkcs11Slot) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return NULL; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return NULL; } - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - return NULL; + return NULL; } - copyk = (SECKEYPrivateKey *) PORT_ArenaZAlloc (arena, sizeof (SECKEYPrivateKey)); + copyk = (SECKEYPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(SECKEYPrivateKey)); if (copyk) { - copyk->arena = arena; - copyk->keyType = privk->keyType; + copyk->arena = arena; + copyk->keyType = privk->keyType; - /* copy the PKCS #11 parameters */ - copyk->pkcs11Slot = PK11_ReferenceSlot(privk->pkcs11Slot); - /* if the key we're referencing was a temparary key we have just - * created, that we want to go away when we're through, we need - * to make a copy of it */ - if (privk->pkcs11IsTemp) { - copyk->pkcs11ID = - PK11_CopyKey(privk->pkcs11Slot,privk->pkcs11ID); - if (copyk->pkcs11ID == CK_INVALID_HANDLE) goto fail; - } else { - copyk->pkcs11ID = privk->pkcs11ID; - } - copyk->pkcs11IsTemp = privk->pkcs11IsTemp; - copyk->wincx = privk->wincx; - copyk->staticflags = privk->staticflags; - return copyk; - } else { - PORT_SetError (SEC_ERROR_NO_MEMORY); + /* copy the PKCS #11 parameters */ + copyk->pkcs11Slot = PK11_ReferenceSlot(privk->pkcs11Slot); + /* if the key we're referencing was a temparary key we have just + * created, that we want to go away when we're through, we need + * to make a copy of it */ + if (privk->pkcs11IsTemp) { + copyk->pkcs11ID = + PK11_CopyKey(privk->pkcs11Slot, privk->pkcs11ID); + if (copyk->pkcs11ID == CK_INVALID_HANDLE) + goto fail; + } + else { + copyk->pkcs11ID = privk->pkcs11ID; + } + copyk->pkcs11IsTemp = privk->pkcs11IsTemp; + copyk->wincx = privk->wincx; + copyk->staticflags = privk->staticflags; + return copyk; + } + else { + PORT_SetError(SEC_ERROR_NO_MEMORY); } fail: - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return NULL; } @@ -1093,82 +1107,88 @@ SECKEY_CopyPublicKey(const SECKEYPublicKey *pubk) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return NULL; } - copyk = (SECKEYPublicKey *) PORT_ArenaZAlloc (arena, sizeof (SECKEYPublicKey)); + copyk = (SECKEYPublicKey *)PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey)); if (!copyk) { - PORT_FreeArena (arena, PR_FALSE); - PORT_SetError (SEC_ERROR_NO_MEMORY); + PORT_FreeArena(arena, PR_FALSE); + PORT_SetError(SEC_ERROR_NO_MEMORY); return NULL; } copyk->arena = arena; copyk->keyType = pubk->keyType; - if (pubk->pkcs11Slot && - PK11_IsPermObject(pubk->pkcs11Slot,pubk->pkcs11ID)) { + if (pubk->pkcs11Slot && + PK11_IsPermObject(pubk->pkcs11Slot, pubk->pkcs11ID)) { copyk->pkcs11Slot = PK11_ReferenceSlot(pubk->pkcs11Slot); copyk->pkcs11ID = pubk->pkcs11ID; - } else { - copyk->pkcs11Slot = NULL; /* go get own reference */ + } + else { + copyk->pkcs11Slot = NULL; /* go get own reference */ copyk->pkcs11ID = CK_INVALID_HANDLE; } switch (pubk->keyType) { - case rsaKey: - rv = SECITEM_CopyItem(arena, ©k->u.rsa.modulus, - &pubk->u.rsa.modulus); - if (rv == SECSuccess) { - rv = SECITEM_CopyItem (arena, ©k->u.rsa.publicExponent, - &pubk->u.rsa.publicExponent); - if (rv == SECSuccess) - return copyk; - } - break; - case dsaKey: - rv = SECITEM_CopyItem(arena, ©k->u.dsa.publicValue, - &pubk->u.dsa.publicValue); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, ©k->u.dsa.params.prime, - &pubk->u.dsa.params.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, ©k->u.dsa.params.subPrime, - &pubk->u.dsa.params.subPrime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, ©k->u.dsa.params.base, - &pubk->u.dsa.params.base); - break; - case dhKey: - rv = SECITEM_CopyItem(arena,©k->u.dh.prime,&pubk->u.dh.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena,©k->u.dh.base,&pubk->u.dh.base); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, ©k->u.dh.publicValue, - &pubk->u.dh.publicValue); - break; - case ecKey: - copyk->u.ec.size = pubk->u.ec.size; - rv = SECITEM_CopyItem(arena,©k->u.ec.DEREncodedParams, - &pubk->u.ec.DEREncodedParams); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena,©k->u.ec.publicValue, - &pubk->u.ec.publicValue); - break; - case nullKey: - return copyk; - default: - PORT_SetError(SEC_ERROR_INVALID_KEY); - rv = SECFailure; - break; + case rsaKey: + rv = SECITEM_CopyItem(arena, ©k->u.rsa.modulus, + &pubk->u.rsa.modulus); + if (rv == SECSuccess) { + rv = SECITEM_CopyItem(arena, ©k->u.rsa.publicExponent, + &pubk->u.rsa.publicExponent); + if (rv == SECSuccess) + return copyk; + } + break; + case dsaKey: + rv = SECITEM_CopyItem(arena, ©k->u.dsa.publicValue, + &pubk->u.dsa.publicValue); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, ©k->u.dsa.params.prime, + &pubk->u.dsa.params.prime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, ©k->u.dsa.params.subPrime, + &pubk->u.dsa.params.subPrime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, ©k->u.dsa.params.base, + &pubk->u.dsa.params.base); + break; + case dhKey: + rv = SECITEM_CopyItem(arena, ©k->u.dh.prime, &pubk->u.dh.prime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, ©k->u.dh.base, &pubk->u.dh.base); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, ©k->u.dh.publicValue, + &pubk->u.dh.publicValue); + break; + case ecKey: + copyk->u.ec.size = pubk->u.ec.size; + rv = SECITEM_CopyItem(arena, ©k->u.ec.DEREncodedParams, + &pubk->u.ec.DEREncodedParams); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, ©k->u.ec.publicValue, + &pubk->u.ec.publicValue); + break; + case nullKey: + return copyk; + default: + PORT_SetError(SEC_ERROR_INVALID_KEY); + rv = SECFailure; + break; } if (rv == SECSuccess) return copyk; - SECKEY_DestroyPublicKey (copyk); + SECKEY_DestroyPublicKey(copyk); return NULL; } - SECKEYPublicKey * SECKEY_ConvertToPublicKey(SECKEYPrivateKey *privk) { @@ -1182,49 +1202,51 @@ SECKEY_ConvertToPublicKey(SECKEYPrivateKey *privk) */ cert = PK11_GetCertFromPrivateKey(privk); if (cert) { - pubk = CERT_ExtractPublicKey(cert); - CERT_DestroyCertificate(cert); - return pubk; + pubk = CERT_ExtractPublicKey(cert); + CERT_DestroyCertificate(cert); + return pubk; } /* couldn't find the cert, build pub key by hand */ - arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return NULL; } pubk = (SECKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof (SECKEYPublicKey)); + sizeof(SECKEYPublicKey)); if (pubk == NULL) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } pubk->keyType = privk->keyType; pubk->pkcs11Slot = NULL; pubk->pkcs11ID = CK_INVALID_HANDLE; pubk->arena = arena; - switch(privk->keyType) { - case nullKey: - case dhKey: - case dsaKey: - /* Nothing to query, if the cert isn't there, we're done -- no way - * to get the public key */ - break; - case rsaKey: - rv = PK11_ReadAttribute(privk->pkcs11Slot,privk->pkcs11ID, - CKA_MODULUS,arena,&pubk->u.rsa.modulus); - if (rv != SECSuccess) break; - rv = PK11_ReadAttribute(privk->pkcs11Slot,privk->pkcs11ID, - CKA_PUBLIC_EXPONENT,arena,&pubk->u.rsa.publicExponent); - if (rv != SECSuccess) break; - return pubk; - break; - default: - break; + switch (privk->keyType) { + case nullKey: + case dhKey: + case dsaKey: + /* Nothing to query, if the cert isn't there, we're done -- no way + * to get the public key */ + break; + case rsaKey: + rv = PK11_ReadAttribute(privk->pkcs11Slot, privk->pkcs11ID, + CKA_MODULUS, arena, &pubk->u.rsa.modulus); + if (rv != SECSuccess) + break; + rv = PK11_ReadAttribute(privk->pkcs11Slot, privk->pkcs11ID, + CKA_PUBLIC_EXPONENT, arena, &pubk->u.rsa.publicExponent); + if (rv != SECSuccess) + break; + return pubk; + break; + default: + break; } - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return NULL; } @@ -1237,105 +1259,108 @@ seckey_CreateSubjectPublicKeyInfo_helper(SECKEYPublicKey *pubk) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return NULL; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return NULL; } - spki = (CERTSubjectPublicKeyInfo *) PORT_ArenaZAlloc(arena, sizeof (*spki)); + spki = (CERTSubjectPublicKeyInfo *)PORT_ArenaZAlloc(arena, sizeof(*spki)); if (spki != NULL) { - SECStatus rv; - SECItem *rv_item; - - spki->arena = arena; - switch(pubk->keyType) { - case rsaKey: - rv = SECOID_SetAlgorithmID(arena, &spki->algorithm, - SEC_OID_PKCS1_RSA_ENCRYPTION, 0); - if (rv == SECSuccess) { - /* - * DER encode the public key into the subjectPublicKeyInfo. - */ - prepare_rsa_pub_key_for_asn1(pubk); - rv_item = SEC_ASN1EncodeItem(arena, &spki->subjectPublicKey, - pubk, SECKEY_RSAPublicKeyTemplate); - if (rv_item != NULL) { - /* - * The stored value is supposed to be a BIT_STRING, - * so convert the length. - */ - spki->subjectPublicKey.len <<= 3; - /* - * We got a good one; return it. - */ - return spki; - } - } - break; - case dsaKey: - /* DER encode the params. */ - prepare_pqg_params_for_asn1(&pubk->u.dsa.params); - rv_item = SEC_ASN1EncodeItem(arena, ¶ms, &pubk->u.dsa.params, - SECKEY_PQGParamsTemplate); - if (rv_item != NULL) { - rv = SECOID_SetAlgorithmID(arena, &spki->algorithm, - SEC_OID_ANSIX9_DSA_SIGNATURE, - ¶ms); - if (rv == SECSuccess) { - /* - * DER encode the public key into the subjectPublicKeyInfo. - */ - prepare_dsa_pub_key_for_asn1(pubk); - rv_item = SEC_ASN1EncodeItem(arena, &spki->subjectPublicKey, - pubk, - SECKEY_DSAPublicKeyTemplate); - if (rv_item != NULL) { - /* - * The stored value is supposed to be a BIT_STRING, - * so convert the length. - */ - spki->subjectPublicKey.len <<= 3; - /* - * We got a good one; return it. - */ - return spki; - } - } - } - SECITEM_FreeItem(¶ms, PR_FALSE); - break; - case ecKey: - rv = SECITEM_CopyItem(arena, ¶ms, - &pubk->u.ec.DEREncodedParams); - if (rv != SECSuccess) break; + SECStatus rv; + SECItem *rv_item; - rv = SECOID_SetAlgorithmID(arena, &spki->algorithm, - SEC_OID_ANSIX962_EC_PUBLIC_KEY, - ¶ms); - if (rv != SECSuccess) break; + spki->arena = arena; + switch (pubk->keyType) { + case rsaKey: + rv = SECOID_SetAlgorithmID(arena, &spki->algorithm, + SEC_OID_PKCS1_RSA_ENCRYPTION, 0); + if (rv == SECSuccess) { + /* + * DER encode the public key into the subjectPublicKeyInfo. + */ + prepare_rsa_pub_key_for_asn1(pubk); + rv_item = SEC_ASN1EncodeItem(arena, &spki->subjectPublicKey, + pubk, SECKEY_RSAPublicKeyTemplate); + if (rv_item != NULL) { + /* + * The stored value is supposed to be a BIT_STRING, + * so convert the length. + */ + spki->subjectPublicKey.len <<= 3; + /* + * We got a good one; return it. + */ + return spki; + } + } + break; + case dsaKey: + /* DER encode the params. */ + prepare_pqg_params_for_asn1(&pubk->u.dsa.params); + rv_item = SEC_ASN1EncodeItem(arena, ¶ms, &pubk->u.dsa.params, + SECKEY_PQGParamsTemplate); + if (rv_item != NULL) { + rv = SECOID_SetAlgorithmID(arena, &spki->algorithm, + SEC_OID_ANSIX9_DSA_SIGNATURE, + ¶ms); + if (rv == SECSuccess) { + /* + * DER encode the public key into the subjectPublicKeyInfo. + */ + prepare_dsa_pub_key_for_asn1(pubk); + rv_item = SEC_ASN1EncodeItem(arena, &spki->subjectPublicKey, + pubk, + SECKEY_DSAPublicKeyTemplate); + if (rv_item != NULL) { + /* + * The stored value is supposed to be a BIT_STRING, + * so convert the length. + */ + spki->subjectPublicKey.len <<= 3; + /* + * We got a good one; return it. + */ + return spki; + } + } + } + SECITEM_FreeItem(¶ms, PR_FALSE); + break; + case ecKey: + rv = SECITEM_CopyItem(arena, ¶ms, + &pubk->u.ec.DEREncodedParams); + if (rv != SECSuccess) + break; - rv = SECITEM_CopyItem(arena, &spki->subjectPublicKey, - &pubk->u.ec.publicValue); + rv = SECOID_SetAlgorithmID(arena, &spki->algorithm, + SEC_OID_ANSIX962_EC_PUBLIC_KEY, + ¶ms); + if (rv != SECSuccess) + break; - if (rv == SECSuccess) { - /* - * The stored value is supposed to be a BIT_STRING, - * so convert the length. - */ - spki->subjectPublicKey.len <<= 3; - /* - * We got a good one; return it. - */ - return spki; - } - break; - case dhKey: /* later... */ + rv = SECITEM_CopyItem(arena, &spki->subjectPublicKey, + &pubk->u.ec.publicValue); - break; - default: - break; - } - } else { - PORT_SetError(SEC_ERROR_NO_MEMORY); + if (rv == SECSuccess) { + /* + * The stored value is supposed to be a BIT_STRING, + * so convert the length. + */ + spki->subjectPublicKey.len <<= 3; + /* + * We got a good one; return it. + */ + return spki; + } + break; + case dhKey: /* later... */ + + break; + default: + break; + } + } + else { + PORT_SetError(SEC_ERROR_NO_MEMORY); } PORT_FreeArena(arena, PR_FALSE); @@ -1366,25 +1391,25 @@ void SECKEY_DestroySubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki) { if (spki && spki->arena) { - PORT_FreeArena(spki->arena, PR_FALSE); + PORT_FreeArena(spki->arena, PR_FALSE); } } SECItem * SECKEY_EncodeDERSubjectPublicKeyInfo(const SECKEYPublicKey *pubk) { - CERTSubjectPublicKeyInfo *spki=NULL; - SECItem *spkiDER=NULL; + CERTSubjectPublicKeyInfo *spki = NULL; + SECItem *spkiDER = NULL; /* get the subjectpublickeyinfo */ spki = SECKEY_CreateSubjectPublicKeyInfo(pubk); - if( spki == NULL ) { - goto finish; + if (spki == NULL) { + goto finish; } /* DER-encode the subjectpublickeyinfo */ - spkiDER = SEC_ASN1EncodeItem(NULL /*arena*/, NULL/*dest*/, spki, - CERT_SubjectPublicKeyInfoTemplate); + spkiDER = SEC_ASN1EncodeItem(NULL /*arena*/, NULL /*dest*/, spki, + CERT_SubjectPublicKeyInfoTemplate); SECKEY_DestroySubjectPublicKeyInfo(spki); @@ -1392,7 +1417,6 @@ finish: return spkiDER; } - CERTSubjectPublicKeyInfo * SECKEY_DecodeDERSubjectPublicKeyInfo(const SECItem *spkider) { @@ -1403,26 +1427,27 @@ SECKEY_DecodeDERSubjectPublicKeyInfo(const SECItem *spkider) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return NULL; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return NULL; } spki = (CERTSubjectPublicKeyInfo *) - PORT_ArenaZAlloc(arena, sizeof (CERTSubjectPublicKeyInfo)); + PORT_ArenaZAlloc(arena, sizeof(CERTSubjectPublicKeyInfo)); if (spki != NULL) { - spki->arena = arena; + spki->arena = arena; /* 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, &newSpkider, spkider); - if ( rv == SECSuccess ) { - rv = SEC_QuickDERDecodeItem(arena,spki, - CERT_SubjectPublicKeyInfoTemplate, &newSpkider); + if (rv == SECSuccess) { + rv = SEC_QuickDERDecodeItem(arena, spki, + CERT_SubjectPublicKeyInfoTemplate, &newSpkider); } - if (rv == SECSuccess) - return spki; - } else { - PORT_SetError(SEC_ERROR_NO_MEMORY); + if (rv == SECSuccess) + return spki; + } + else { + PORT_SetError(SEC_ERROR_NO_MEMORY); } PORT_FreeArena(arena, PR_FALSE); @@ -1441,7 +1466,7 @@ SECKEY_ConvertAndDecodeSubjectPublicKeyInfo(const char *spkistr) rv = ATOB_ConvertAsciiToItem(&der, spkistr); if (rv != SECSuccess) - return NULL; + return NULL; spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&der); @@ -1455,7 +1480,7 @@ SECKEY_ConvertAndDecodeSubjectPublicKeyInfo(const char *spkistr) */ CERTSubjectPublicKeyInfo * SECKEY_ConvertAndDecodePublicKeyAndChallenge(char *pkacstr, char *challenge, - void *wincx) + void *wincx) { CERTSubjectPublicKeyInfo *spki = NULL; CERTPublicKeyAndChallenge pkac; @@ -1466,171 +1491,175 @@ SECKEY_ConvertAndDecodePublicKeyAndChallenge(char *pkacstr, char *challenge, SECItem sig; SECKEYPublicKey *pubKey = NULL; unsigned int len; - + signedItem.data = NULL; - + /* convert the base64 encoded data to binary */ rv = ATOB_ConvertAsciiToItem(&signedItem, pkacstr); if (rv != SECSuccess) { - goto loser; + goto loser; } /* create an arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - goto loser; + goto loser; } /* decode the outer wrapping of signed data */ PORT_Memset(&sd, 0, sizeof(CERTSignedData)); - rv = SEC_QuickDERDecodeItem(arena, &sd, CERT_SignedDataTemplate, &signedItem ); - if ( rv ) { - goto loser; + rv = SEC_QuickDERDecodeItem(arena, &sd, CERT_SignedDataTemplate, &signedItem); + if (rv) { + goto loser; } /* decode the public key and challenge wrapper */ PORT_Memset(&pkac, 0, sizeof(CERTPublicKeyAndChallenge)); - rv = SEC_QuickDERDecodeItem(arena, &pkac, CERT_PublicKeyAndChallengeTemplate, - &sd.data); - if ( rv ) { - goto loser; + rv = SEC_QuickDERDecodeItem(arena, &pkac, CERT_PublicKeyAndChallengeTemplate, + &sd.data); + if (rv) { + goto loser; } /* decode the subject public key info */ spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&pkac.spki); - if ( spki == NULL ) { - goto loser; + if (spki == NULL) { + goto loser; } - + /* get the public key */ pubKey = seckey_ExtractPublicKey(spki); - if ( pubKey == NULL ) { - goto loser; + if (pubKey == NULL) { + goto loser; } /* check the signature */ sig = sd.signature; DER_ConvertBitString(&sig); rv = VFY_VerifyDataWithAlgorithmID(sd.data.data, sd.data.len, pubKey, &sig, - &(sd.signatureAlgorithm), NULL, wincx); - if ( rv != SECSuccess ) { - goto loser; + &(sd.signatureAlgorithm), NULL, wincx); + if (rv != SECSuccess) { + goto loser; } - + /* check the challenge */ - if ( challenge ) { - len = PORT_Strlen(challenge); - /* length is right */ - if ( len != pkac.challenge.len ) { - goto loser; - } - /* actual data is right */ - if ( PORT_Memcmp(challenge, pkac.challenge.data, len) != 0 ) { - goto loser; - } + if (challenge) { + len = PORT_Strlen(challenge); + /* length is right */ + if (len != pkac.challenge.len) { + goto loser; + } + /* actual data is right */ + if (PORT_Memcmp(challenge, pkac.challenge.data, len) != 0) { + goto loser; + } } goto done; loser: /* make sure that we return null if we got an error */ - if ( spki ) { - SECKEY_DestroySubjectPublicKeyInfo(spki); + if (spki) { + SECKEY_DestroySubjectPublicKeyInfo(spki); } spki = NULL; - + done: - if ( signedItem.data ) { - PORT_Free(signedItem.data); + if (signedItem.data) { + PORT_Free(signedItem.data); } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - if ( pubKey ) { - SECKEY_DestroyPublicKey(pubKey); + if (pubKey) { + SECKEY_DestroyPublicKey(pubKey); } - + return spki; } void SECKEY_DestroyPrivateKeyInfo(SECKEYPrivateKeyInfo *pvk, - PRBool freeit) + PRBool freeit) { PLArenaPool *poolp; - if(pvk != NULL) { - if(pvk->arena) { - poolp = pvk->arena; - /* zero structure since PORT_FreeArena does not support - * this yet. - */ - PORT_Memset(pvk->privateKey.data, 0, pvk->privateKey.len); - PORT_Memset(pvk, 0, sizeof(*pvk)); - if(freeit == PR_TRUE) { - PORT_FreeArena(poolp, PR_TRUE); - } else { - pvk->arena = poolp; - } - } else { - SECITEM_ZfreeItem(&pvk->version, PR_FALSE); - SECITEM_ZfreeItem(&pvk->privateKey, PR_FALSE); - SECOID_DestroyAlgorithmID(&pvk->algorithm, PR_FALSE); - PORT_Memset(pvk, 0, sizeof(*pvk)); - if(freeit == PR_TRUE) { - PORT_Free(pvk); - } - } + if (pvk != NULL) { + if (pvk->arena) { + poolp = pvk->arena; + /* zero structure since PORT_FreeArena does not support + * this yet. + */ + PORT_Memset(pvk->privateKey.data, 0, pvk->privateKey.len); + PORT_Memset(pvk, 0, sizeof(*pvk)); + if (freeit == PR_TRUE) { + PORT_FreeArena(poolp, PR_TRUE); + } + else { + pvk->arena = poolp; + } + } + else { + SECITEM_ZfreeItem(&pvk->version, PR_FALSE); + SECITEM_ZfreeItem(&pvk->privateKey, PR_FALSE); + SECOID_DestroyAlgorithmID(&pvk->algorithm, PR_FALSE); + PORT_Memset(pvk, 0, sizeof(*pvk)); + if (freeit == PR_TRUE) { + PORT_Free(pvk); + } + } } } void SECKEY_DestroyEncryptedPrivateKeyInfo(SECKEYEncryptedPrivateKeyInfo *epki, - PRBool freeit) + PRBool freeit) { PLArenaPool *poolp; - if(epki != NULL) { - if(epki->arena) { - poolp = epki->arena; - /* zero structure since PORT_FreeArena does not support - * this yet. - */ - PORT_Memset(epki->encryptedData.data, 0, epki->encryptedData.len); - PORT_Memset(epki, 0, sizeof(*epki)); - if(freeit == PR_TRUE) { - PORT_FreeArena(poolp, PR_TRUE); - } else { - epki->arena = poolp; - } - } else { - SECITEM_ZfreeItem(&epki->encryptedData, PR_FALSE); - SECOID_DestroyAlgorithmID(&epki->algorithm, PR_FALSE); - PORT_Memset(epki, 0, sizeof(*epki)); - if(freeit == PR_TRUE) { - PORT_Free(epki); - } - } + if (epki != NULL) { + if (epki->arena) { + poolp = epki->arena; + /* zero structure since PORT_FreeArena does not support + * this yet. + */ + PORT_Memset(epki->encryptedData.data, 0, epki->encryptedData.len); + PORT_Memset(epki, 0, sizeof(*epki)); + if (freeit == PR_TRUE) { + PORT_FreeArena(poolp, PR_TRUE); + } + else { + epki->arena = poolp; + } + } + else { + SECITEM_ZfreeItem(&epki->encryptedData, PR_FALSE); + SECOID_DestroyAlgorithmID(&epki->algorithm, PR_FALSE); + PORT_Memset(epki, 0, sizeof(*epki)); + if (freeit == PR_TRUE) { + PORT_Free(epki); + } + } } } SECStatus SECKEY_CopyPrivateKeyInfo(PLArenaPool *poolp, - SECKEYPrivateKeyInfo *to, - const SECKEYPrivateKeyInfo *from) + SECKEYPrivateKeyInfo *to, + const SECKEYPrivateKeyInfo *from) { SECStatus rv = SECFailure; - if((to == NULL) || (from == NULL)) { - return SECFailure; + if ((to == NULL) || (from == NULL)) { + return SECFailure; } rv = SECOID_CopyAlgorithmID(poolp, &to->algorithm, &from->algorithm); - if(rv != SECSuccess) { - return SECFailure; + if (rv != SECSuccess) { + return SECFailure; } rv = SECITEM_CopyItem(poolp, &to->privateKey, &from->privateKey); - if(rv != SECSuccess) { - return SECFailure; + if (rv != SECSuccess) { + return SECFailure; } rv = SECITEM_CopyItem(poolp, &to->version, &from->version); @@ -1639,18 +1668,18 @@ SECKEY_CopyPrivateKeyInfo(PLArenaPool *poolp, SECStatus SECKEY_CopyEncryptedPrivateKeyInfo(PLArenaPool *poolp, - SECKEYEncryptedPrivateKeyInfo *to, - const SECKEYEncryptedPrivateKeyInfo *from) + SECKEYEncryptedPrivateKeyInfo *to, + const SECKEYEncryptedPrivateKeyInfo *from) { SECStatus rv = SECFailure; - if((to == NULL) || (from == NULL)) { - return SECFailure; + if ((to == NULL) || (from == NULL)) { + return SECFailure; } rv = SECOID_CopyAlgorithmID(poolp, &to->algorithm, &from->algorithm); - if(rv != SECSuccess) { - return SECFailure; + if (rv != SECSuccess) { + return SECFailure; } rv = SECITEM_CopyItem(poolp, &to->encryptedData, &from->encryptedData); @@ -1660,16 +1689,16 @@ SECKEY_CopyEncryptedPrivateKeyInfo(PLArenaPool *poolp, KeyType SECKEY_GetPrivateKeyType(const SECKEYPrivateKey *privKey) { - return privKey->keyType; + return privKey->keyType; } KeyType SECKEY_GetPublicKeyType(const SECKEYPublicKey *pubKey) { - return pubKey->keyType; + return pubKey->keyType; } -SECKEYPublicKey* +SECKEYPublicKey * SECKEY_ImportDERPublicKey(const SECItem *derKey, CK_KEY_TYPE type) { SECKEYPublicKey *pubk = NULL; @@ -1679,11 +1708,11 @@ SECKEY_ImportDERPublicKey(const SECItem *derKey, CK_KEY_TYPE type) if (!derKey) { return NULL; - } + } arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); + PORT_SetError(SEC_ERROR_NO_MEMORY); goto finish; } @@ -1701,25 +1730,25 @@ SECKEY_ImportDERPublicKey(const SECItem *derKey, CK_KEY_TYPE type) pubk->pkcs11Slot = NULL; pubk->pkcs11ID = CK_INVALID_HANDLE; - switch( type ) { - case CKK_RSA: - prepare_rsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_RSAPublicKeyTemplate, &newDerKey); - pubk->keyType = rsaKey; - break; - case CKK_DSA: - prepare_dsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_DSAPublicKeyTemplate, &newDerKey); - pubk->keyType = dsaKey; - break; - case CKK_DH: - prepare_dh_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_DHPublicKeyTemplate, &newDerKey); - pubk->keyType = dhKey; - break; - default: - rv = SECFailure; - break; + switch (type) { + case CKK_RSA: + prepare_rsa_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_RSAPublicKeyTemplate, &newDerKey); + pubk->keyType = rsaKey; + break; + case CKK_DSA: + prepare_dsa_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_DSAPublicKeyTemplate, &newDerKey); + pubk->keyType = dsaKey; + break; + case CKK_DH: + prepare_dh_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(pubk->arena, pubk, SECKEY_DHPublicKeyTemplate, &newDerKey); + pubk->keyType = dhKey; + break; + default: + rv = SECFailure; + break; } finish: @@ -1732,20 +1761,20 @@ finish: return pubk; } -SECKEYPrivateKeyList* +SECKEYPrivateKeyList * SECKEY_NewPrivateKeyList(void) { PLArenaPool *arena = NULL; SECKEYPrivateKeyList *ret = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { + if (arena == NULL) { goto loser; } ret = (SECKEYPrivateKeyList *)PORT_ArenaZAlloc(arena, - sizeof(SECKEYPrivateKeyList)); - if ( ret == NULL ) { + sizeof(SECKEYPrivateKeyList)); + if (ret == NULL) { goto loser; } @@ -1753,22 +1782,22 @@ SECKEY_NewPrivateKeyList(void) PR_INIT_CLIST(&ret->list); - return(ret); + return (ret); loser: - if ( arena != NULL ) { + if (arena != NULL) { PORT_FreeArena(arena, PR_FALSE); } - return(NULL); + return (NULL); } void SECKEY_DestroyPrivateKeyList(SECKEYPrivateKeyList *keys) { - while( !PR_CLIST_IS_EMPTY(&keys->list) ) { + while (!PR_CLIST_IS_EMPTY(&keys->list)) { SECKEY_RemovePrivateKeyListNode( - (SECKEYPrivateKeyListNode*)(PR_LIST_HEAD(&keys->list)) ); + (SECKEYPrivateKeyListNode *)(PR_LIST_HEAD(&keys->list))); } PORT_FreeArena(keys->arena, PR_FALSE); @@ -1776,7 +1805,6 @@ SECKEY_DestroyPrivateKeyList(SECKEYPrivateKeyList *keys) return; } - void SECKEY_RemovePrivateKeyListNode(SECKEYPrivateKeyListNode *node) { @@ -1785,44 +1813,42 @@ SECKEY_RemovePrivateKeyListNode(SECKEYPrivateKeyListNode *node) node->key = NULL; PR_REMOVE_LINK(&node->links); return; - } SECStatus -SECKEY_AddPrivateKeyToListTail( SECKEYPrivateKeyList *list, - SECKEYPrivateKey *key) +SECKEY_AddPrivateKeyToListTail(SECKEYPrivateKeyList *list, + SECKEYPrivateKey *key) { SECKEYPrivateKeyListNode *node; node = (SECKEYPrivateKeyListNode *)PORT_ArenaZAlloc(list->arena, - sizeof(SECKEYPrivateKeyListNode)); - if ( node == NULL ) { + sizeof(SECKEYPrivateKeyListNode)); + if (node == NULL) { goto loser; } PR_INSERT_BEFORE(&node->links, &list->list); node->key = key; - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } - -SECKEYPublicKeyList* +SECKEYPublicKeyList * SECKEY_NewPublicKeyList(void) { PLArenaPool *arena = NULL; SECKEYPublicKeyList *ret = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { + if (arena == NULL) { goto loser; } ret = (SECKEYPublicKeyList *)PORT_ArenaZAlloc(arena, - sizeof(SECKEYPublicKeyList)); - if ( ret == NULL ) { + sizeof(SECKEYPublicKeyList)); + if (ret == NULL) { goto loser; } @@ -1830,22 +1856,22 @@ SECKEY_NewPublicKeyList(void) PR_INIT_CLIST(&ret->list); - return(ret); + return (ret); loser: - if ( arena != NULL ) { + if (arena != NULL) { PORT_FreeArena(arena, PR_FALSE); } - return(NULL); + return (NULL); } void SECKEY_DestroyPublicKeyList(SECKEYPublicKeyList *keys) { - while( !PR_CLIST_IS_EMPTY(&keys->list) ) { + while (!PR_CLIST_IS_EMPTY(&keys->list)) { SECKEY_RemovePublicKeyListNode( - (SECKEYPublicKeyListNode*)(PR_LIST_HEAD(&keys->list)) ); + (SECKEYPublicKeyListNode *)(PR_LIST_HEAD(&keys->list))); } PORT_FreeArena(keys->arena, PR_FALSE); @@ -1853,7 +1879,6 @@ SECKEY_DestroyPublicKeyList(SECKEYPublicKeyList *keys) return; } - void SECKEY_RemovePublicKeyListNode(SECKEYPublicKeyListNode *node) { @@ -1862,38 +1887,38 @@ SECKEY_RemovePublicKeyListNode(SECKEYPublicKeyListNode *node) node->key = NULL; PR_REMOVE_LINK(&node->links); return; - } SECStatus -SECKEY_AddPublicKeyToListTail( SECKEYPublicKeyList *list, - SECKEYPublicKey *key) +SECKEY_AddPublicKeyToListTail(SECKEYPublicKeyList *list, + SECKEYPublicKey *key) { SECKEYPublicKeyListNode *node; node = (SECKEYPublicKeyListNode *)PORT_ArenaZAlloc(list->arena, - sizeof(SECKEYPublicKeyListNode)); - if ( node == NULL ) { + sizeof(SECKEYPublicKeyListNode)); + if (node == NULL) { goto loser; } PR_INSERT_BEFORE(&node->links, &list->list); node->key = key; - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } -#define SECKEY_CacheAttribute(key, attribute) \ +#define SECKEY_CacheAttribute(key, attribute) \ if (CK_TRUE == PK11_HasAttributeSet(key->pkcs11Slot, key->pkcs11ID, attribute, PR_FALSE)) { \ - key->staticflags |= SECKEY_##attribute; \ - } else { \ - key->staticflags &= (~SECKEY_##attribute); \ + key->staticflags |= SECKEY_##attribute; \ + } \ + else { \ + key->staticflags &= (~SECKEY_##attribute); \ } SECStatus -SECKEY_CacheStaticFlags(SECKEYPrivateKey* key) +SECKEY_CacheStaticFlags(SECKEYPrivateKey *key) { SECStatus rv = SECFailure; if (key && key->pkcs11Slot && key->pkcs11ID) { @@ -1906,20 +1931,22 @@ SECKEY_CacheStaticFlags(SECKEYPrivateKey* key) } SECOidTag -SECKEY_GetECCOid(const SECKEYECParams * params) +SECKEY_GetECCOid(const SECKEYECParams *params) { - SECItem oid = { siBuffer, NULL, 0}; + SECItem oid = { siBuffer, NULL, 0 }; SECOidData *oidData = NULL; - /* + /* * params->data needs to contain the ASN encoding of an object ID (OID) * representing a named curve. Here, we strip away everything * before the actual OID and use the OID to look up a named curve. */ - if (params->data[0] != SEC_ASN1_OBJECT_ID) return 0; + if (params->data[0] != SEC_ASN1_OBJECT_ID) + return 0; oid.len = params->len - 2; oid.data = params->data + 2; - if ((oidData = SECOID_FindOID(&oid)) == NULL) return 0; + if ((oidData = SECOID_FindOID(&oid)) == NULL) + return 0; return oidData->offset; } diff --git a/security/nss/lib/cryptohi/secsign.c b/security/nss/lib/cryptohi/secsign.c index fa4bf5fff47a..c59114c3626c 100644 --- a/security/nss/lib/cryptohi/secsign.c +++ b/security/nss/lib/cryptohi/secsign.c @@ -40,25 +40,25 @@ SGN_NewContext(SECOidTag alg, SECKEYPrivateKey *key) * it may just support CKM_SHA1_RSA_PKCS and/or CKM_MD5_RSA_PKCS. */ /* we have a private key, not a public key, so don't pass it in */ - rv = sec_DecodeSigAlg(NULL, alg, NULL, &signalg, &hashalg); + rv = sec_DecodeSigAlg(NULL, alg, NULL, &signalg, &hashalg); if (rv != SECSuccess) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return 0; + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return 0; } keyType = seckey_GetKeyType(signalg); /* verify our key type */ if (key->keyType != keyType && - !((key->keyType == dsaKey) && (keyType == fortezzaKey)) ) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return 0; + !((key->keyType == dsaKey) && (keyType == fortezzaKey))) { + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return 0; } - cx = (SGNContext*) PORT_ZAlloc(sizeof(SGNContext)); + cx = (SGNContext *)PORT_ZAlloc(sizeof(SGNContext)); if (cx) { - cx->hashalg = hashalg; - cx->signalg = signalg; - cx->key = key; + cx->hashalg = hashalg; + cx->signalg = signalg; + cx->key = key; } return cx; } @@ -67,13 +67,13 @@ void SGN_DestroyContext(SGNContext *cx, PRBool freeit) { if (cx) { - if (cx->hashcx != NULL) { - (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); - cx->hashcx = NULL; - } - if (freeit) { - PORT_ZFree(cx, sizeof(SGNContext)); - } + if (cx->hashcx != NULL) { + (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); + cx->hashcx = NULL; + } + if (freeit) { + PORT_ZFree(cx, sizeof(SGNContext)); + } } } @@ -81,17 +81,17 @@ SECStatus SGN_Begin(SGNContext *cx) { if (cx->hashcx != NULL) { - (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); - cx->hashcx = NULL; + (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); + cx->hashcx = NULL; } cx->hashobj = HASH_GetHashObjectByOidTag(cx->hashalg); if (!cx->hashobj) - return SECFailure; /* error code is already set */ + return SECFailure; /* error code is already set */ cx->hashcx = (*cx->hashobj->create)(); if (cx->hashcx == NULL) - return SECFailure; + return SECFailure; (*cx->hashobj->begin)(cx->hashcx); return SECSuccess; @@ -101,8 +101,8 @@ SECStatus SGN_Update(SGNContext *cx, const unsigned char *input, unsigned int inputLen) { if (cx->hashcx == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } (*cx->hashobj->update)(cx->hashcx, input, inputLen); return SECSuccess; @@ -111,12 +111,12 @@ SGN_Update(SGNContext *cx, const unsigned char *input, unsigned int inputLen) /* XXX Old template; want to expunge it eventually. */ static DERTemplate SECAlgorithmIDTemplate[] = { { DER_SEQUENCE, - 0, NULL, sizeof(SECAlgorithmID) }, + 0, NULL, sizeof(SECAlgorithmID) }, { DER_OBJECT_ID, - offsetof(SECAlgorithmID,algorithm), }, + offsetof(SECAlgorithmID, algorithm) }, { DER_OPTIONAL | DER_ANY, - offsetof(SECAlgorithmID,parameters), }, - { 0, } + offsetof(SECAlgorithmID, parameters) }, + { 0 } }; /* @@ -125,13 +125,13 @@ static DERTemplate SECAlgorithmIDTemplate[] = { */ static DERTemplate SGNDigestInfoTemplate[] = { { DER_SEQUENCE, - 0, NULL, sizeof(SGNDigestInfo) }, + 0, NULL, sizeof(SGNDigestInfo) }, { DER_INLINE, - offsetof(SGNDigestInfo,digestAlgorithm), - SECAlgorithmIDTemplate, }, + offsetof(SGNDigestInfo, digestAlgorithm), + SECAlgorithmIDTemplate }, { DER_OCTET_STRING, - offsetof(SGNDigestInfo,digest), }, - { 0, } + offsetof(SGNDigestInfo, digest) }, + { 0 } }; SECStatus @@ -151,36 +151,36 @@ SGN_End(SGNContext *cx, SECItem *result) /* Finish up digest function */ if (cx->hashcx == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } (*cx->hashobj->end)(cx->hashcx, digest, &part1, sizeof(digest)); - if (privKey->keyType == rsaKey) { - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - rv = SECFailure; - goto loser; - } - - /* Construct digest info */ - di = SGN_CreateDigestInfo(cx->hashalg, digest, part1); - if (!di) { - rv = SECFailure; - goto loser; - } + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (!arena) { + rv = SECFailure; + goto loser; + } - /* Der encode the digest as a DigestInfo */ + /* Construct digest info */ + di = SGN_CreateDigestInfo(cx->hashalg, digest, part1); + if (!di) { + rv = SECFailure; + goto loser; + } + + /* Der encode the digest as a DigestInfo */ rv = DER_Encode(arena, &digder, SGNDigestInfoTemplate, di); - if (rv != SECSuccess) { - goto loser; - } - } else { - digder.data = digest; - digder.len = part1; + if (rv != SECSuccess) { + goto loser; + } + } + else { + digder.data = digest; + digder.len = part1; } /* @@ -189,41 +189,42 @@ SGN_End(SGNContext *cx, SECItem *result) */ signatureLen = PK11_SignatureLen(privKey); if (signatureLen <= 0) { - PORT_SetError(SEC_ERROR_INVALID_KEY); - rv = SECFailure; - goto loser; + PORT_SetError(SEC_ERROR_INVALID_KEY); + rv = SECFailure; + goto loser; } sigitem.len = signatureLen; - sigitem.data = (unsigned char*) PORT_Alloc(signatureLen); + sigitem.data = (unsigned char *)PORT_Alloc(signatureLen); if (sigitem.data == NULL) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } rv = PK11_Sign(privKey, &sigitem, &digder); if (rv != SECSuccess) { - PORT_Free(sigitem.data); - sigitem.data = NULL; - goto loser; + PORT_Free(sigitem.data); + sigitem.data = NULL; + goto loser; } if ((cx->signalg == SEC_OID_ANSIX9_DSA_SIGNATURE) || (cx->signalg == SEC_OID_ANSIX962_EC_PUBLIC_KEY)) { /* DSAU_EncodeDerSigWithLen works for DSA and ECDSA */ - rv = DSAU_EncodeDerSigWithLen(result, &sigitem, sigitem.len); - PORT_Free(sigitem.data); - if (rv != SECSuccess) - goto loser; - } else { - result->len = sigitem.len; - result->data = sigitem.data; + rv = DSAU_EncodeDerSigWithLen(result, &sigitem, sigitem.len); + PORT_Free(sigitem.data); + if (rv != SECSuccess) + goto loser; + } + else { + result->len = sigitem.len; + result->data = sigitem.data; } - loser: +loser: SGN_DestroyDigestInfo(di); if (arena != NULL) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return rv; } @@ -236,71 +237,69 @@ SGN_End(SGNContext *cx, SECItem *result) */ SECStatus SEC_SignData(SECItem *res, const unsigned char *buf, int len, - SECKEYPrivateKey *pk, SECOidTag algid) + SECKEYPrivateKey *pk, SECOidTag algid) { SECStatus rv; SGNContext *sgn; - sgn = SGN_NewContext(algid, pk); if (sgn == NULL) - return SECFailure; + return SECFailure; rv = SGN_Begin(sgn); if (rv != SECSuccess) - goto loser; + goto loser; rv = SGN_Update(sgn, buf, len); if (rv != SECSuccess) - goto loser; + goto loser; rv = SGN_End(sgn, res); - loser: +loser: SGN_DestroyContext(sgn, PR_TRUE); return rv; } /************************************************************************/ - + DERTemplate CERTSignedDataTemplate[] = -{ - { DER_SEQUENCE, - 0, NULL, sizeof(CERTSignedData) }, - { DER_ANY, - offsetof(CERTSignedData,data), }, - { DER_INLINE, - offsetof(CERTSignedData,signatureAlgorithm), - SECAlgorithmIDTemplate, }, - { DER_BIT_STRING, - offsetof(CERTSignedData,signature), }, - { 0, } -}; + { + { DER_SEQUENCE, + 0, NULL, sizeof(CERTSignedData) }, + { DER_ANY, + offsetof(CERTSignedData, data) }, + { DER_INLINE, + offsetof(CERTSignedData, signatureAlgorithm), + SECAlgorithmIDTemplate }, + { DER_BIT_STRING, + offsetof(CERTSignedData, signature) }, + { 0 } + }; SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) const SEC_ASN1Template CERT_SignedDataTemplate[] = -{ - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CERTSignedData) }, - { SEC_ASN1_ANY, - offsetof(CERTSignedData,data), }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(CERTSignedData,signatureAlgorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate), }, - { SEC_ASN1_BIT_STRING, - offsetof(CERTSignedData,signature), }, - { 0, } -}; + { + { SEC_ASN1_SEQUENCE, + 0, NULL, sizeof(CERTSignedData) }, + { SEC_ASN1_ANY, + offsetof(CERTSignedData, data) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, + offsetof(CERTSignedData, signatureAlgorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + { SEC_ASN1_BIT_STRING, + offsetof(CERTSignedData, signature) }, + { 0 } + }; SEC_ASN1_CHOOSER_IMPLEMENT(CERT_SignedDataTemplate) - SECStatus SEC_DerSignData(PLArenaPool *arena, SECItem *result, - const unsigned char *buf, int len, SECKEYPrivateKey *pk, - SECOidTag algID) + const unsigned char *buf, int len, SECKEYPrivateKey *pk, + SECOidTag algID) { SECItem it; CERTSignedData sd; @@ -313,58 +312,60 @@ SEC_DerSignData(PLArenaPool *arena, SECItem *result, */ if (algID == SEC_OID_UNKNOWN) { - switch(pk->keyType) { - case rsaKey: - algID = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION; - break; - case dsaKey: - /* get Signature length (= q_len*2) and work from there */ - switch (PK11_SignatureLen(pk)) { - case 448: - algID = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST; - break; - case 512: - algID = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST; - break; - default: - algID = SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST; - break; - } - break; - case ecKey: - algID = SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST; - break; - default: - PORT_SetError(SEC_ERROR_INVALID_KEY); - return SECFailure; - } + switch (pk->keyType) { + case rsaKey: + algID = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION; + break; + case dsaKey: + /* get Signature length (= q_len*2) and work from there */ + switch (PK11_SignatureLen(pk)) { + case 448: + algID = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST; + break; + case 512: + algID = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST; + break; + default: + algID = SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST; + break; + } + break; + case ecKey: + algID = SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_KEY); + return SECFailure; + } } /* Sign input buffer */ rv = SEC_SignData(&it, buf, len, pk, algID); - if (rv) goto loser; + if (rv) + goto loser; /* Fill out SignedData object */ PORT_Memset(&sd, 0, sizeof(sd)); - sd.data.data = (unsigned char*) buf; + sd.data.data = (unsigned char *)buf; sd.data.len = len; sd.signature.data = it.data; - sd.signature.len = it.len << 3; /* convert to bit string */ + sd.signature.len = it.len << 3; /* convert to bit string */ rv = SECOID_SetAlgorithmID(arena, &sd.signatureAlgorithm, algID, 0); - if (rv) goto loser; + if (rv) + goto loser; /* DER encode the signed data object */ rv = DER_Encode(arena, result, CERTSignedDataTemplate, &sd); /* FALL THROUGH */ - loser: +loser: PORT_Free(it.data); return rv; } SECStatus SGN_Digest(SECKEYPrivateKey *privKey, - SECOidTag algtag, SECItem *result, SECItem *digest) + SECOidTag algtag, SECItem *result, SECItem *digest) { int modulusLen; SECStatus rv; @@ -372,33 +373,33 @@ SGN_Digest(SECKEYPrivateKey *privKey, PLArenaPool *arena = 0; SGNDigestInfo *di = 0; - result->data = 0; if (privKey->keyType == rsaKey) { - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - rv = SECFailure; - goto loser; - } - - /* Construct digest info */ - di = SGN_CreateDigestInfo(algtag, digest->data, digest->len); - if (!di) { - rv = SECFailure; - goto loser; - } + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (!arena) { + rv = SECFailure; + goto loser; + } - /* Der encode the digest as a DigestInfo */ + /* Construct digest info */ + di = SGN_CreateDigestInfo(algtag, digest->data, digest->len); + if (!di) { + rv = SECFailure; + goto loser; + } + + /* Der encode the digest as a DigestInfo */ rv = DER_Encode(arena, &digder, SGNDigestInfoTemplate, di); - if (rv != SECSuccess) { - goto loser; - } - } else { - digder.data = digest->data; - digder.len = digest->len; + if (rv != SECSuccess) { + goto loser; + } + } + else { + digder.data = digest->data; + digder.len = digest->len; } /* @@ -407,29 +408,29 @@ SGN_Digest(SECKEYPrivateKey *privKey, */ modulusLen = PK11_SignatureLen(privKey); if (modulusLen <= 0) { - PORT_SetError(SEC_ERROR_INVALID_KEY); - rv = SECFailure; - goto loser; + PORT_SetError(SEC_ERROR_INVALID_KEY); + rv = SECFailure; + goto loser; } result->len = modulusLen; - result->data = (unsigned char*) PORT_Alloc(modulusLen); + result->data = (unsigned char *)PORT_Alloc(modulusLen); result->type = siBuffer; if (result->data == NULL) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } rv = PK11_Sign(privKey, result, &digder); if (rv != SECSuccess) { - PORT_Free(result->data); - result->data = NULL; + PORT_Free(result->data); + result->data = NULL; } - loser: +loser: SGN_DestroyDigestInfo(di); if (arena != NULL) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return rv; } @@ -440,58 +441,73 @@ SEC_GetSignatureAlgorithmOidTag(KeyType keyType, SECOidTag hashAlgTag) SECOidTag sigTag = SEC_OID_UNKNOWN; switch (keyType) { - case rsaKey: - switch (hashAlgTag) { - case SEC_OID_MD2: - sigTag = SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION; break; - case SEC_OID_MD5: - sigTag = SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION; break; - case SEC_OID_SHA1: - sigTag = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION; break; - case SEC_OID_SHA224: - sigTag = SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION; break; - case SEC_OID_UNKNOWN: /* default for RSA if not specified */ - case SEC_OID_SHA256: - sigTag = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION; break; - case SEC_OID_SHA384: - sigTag = SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION; break; - case SEC_OID_SHA512: - sigTag = SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION; break; - default: - break; - } - break; - case dsaKey: - switch (hashAlgTag) { - case SEC_OID_UNKNOWN: /* default for DSA if not specified */ - case SEC_OID_SHA1: - sigTag = SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST; break; - case SEC_OID_SHA224: - sigTag = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST; break; - case SEC_OID_SHA256: - sigTag = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST; break; - default: - break; - } - break; - case ecKey: - switch (hashAlgTag) { - case SEC_OID_UNKNOWN: /* default for ECDSA if not specified */ - case SEC_OID_SHA1: - sigTag = SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE; break; - case SEC_OID_SHA224: - sigTag = SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE; break; - case SEC_OID_SHA256: - sigTag = SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE; break; - case SEC_OID_SHA384: - sigTag = SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE; break; - case SEC_OID_SHA512: - sigTag = SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE; break; - default: - break; - } - default: - break; + case rsaKey: + switch (hashAlgTag) { + case SEC_OID_MD2: + sigTag = SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION; + break; + case SEC_OID_MD5: + sigTag = SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION; + break; + case SEC_OID_SHA1: + sigTag = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION; + break; + case SEC_OID_SHA224: + sigTag = SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION; + break; + case SEC_OID_UNKNOWN: /* default for RSA if not specified */ + case SEC_OID_SHA256: + sigTag = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION; + break; + case SEC_OID_SHA384: + sigTag = SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION; + break; + case SEC_OID_SHA512: + sigTag = SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION; + break; + default: + break; + } + break; + case dsaKey: + switch (hashAlgTag) { + case SEC_OID_UNKNOWN: /* default for DSA if not specified */ + case SEC_OID_SHA1: + sigTag = SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST; + break; + case SEC_OID_SHA224: + sigTag = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST; + break; + case SEC_OID_SHA256: + sigTag = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST; + break; + default: + break; + } + break; + case ecKey: + switch (hashAlgTag) { + case SEC_OID_UNKNOWN: /* default for ECDSA if not specified */ + case SEC_OID_SHA1: + sigTag = SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE; + break; + case SEC_OID_SHA224: + sigTag = SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE; + break; + case SEC_OID_SHA256: + sigTag = SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE; + break; + case SEC_OID_SHA384: + sigTag = SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE; + break; + case SEC_OID_SHA512: + sigTag = SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE; + break; + default: + break; + } + default: + break; } return sigTag; } diff --git a/security/nss/lib/cryptohi/secvfy.c b/security/nss/lib/cryptohi/secvfy.c index c869167cd2c2..5090f1aeb234 100644 --- a/security/nss/lib/cryptohi/secvfy.c +++ b/security/nss/lib/cryptohi/secvfy.c @@ -35,13 +35,13 @@ */ static SECStatus recoverPKCS1DigestInfo(SECOidTag givenDigestAlg, - /*out*/ SECOidTag* digestAlgOut, - /*out*/ unsigned char** digestInfo, - /*out*/ unsigned int* digestInfoLen, - SECKEYPublicKey* key, - const SECItem* sig, void* wincx) + /*out*/ SECOidTag *digestAlgOut, + /*out*/ unsigned char **digestInfo, + /*out*/ unsigned int *digestInfoLen, + SECKEYPublicKey *key, + const SECItem *sig, void *wincx) { - SGNDigestInfo* di = NULL; + SGNDigestInfo *di = NULL; SECItem it; PRBool rv = SECSuccess; @@ -53,11 +53,11 @@ recoverPKCS1DigestInfo(SECOidTag givenDigestAlg, PORT_Assert(sig); it.data = NULL; - it.len = SECKEY_PublicKeyStrength(key); + it.len = SECKEY_PublicKeyStrength(key); if (it.len != 0) { it.data = (unsigned char *)PORT_Alloc(it.len); } - if (it.len == 0 || it.data == NULL ) { + if (it.len == 0 || it.data == NULL) { rv = SECFailure; } @@ -65,7 +65,7 @@ recoverPKCS1DigestInfo(SECOidTag givenDigestAlg, /* decrypt the block */ rv = PK11_VerifyRecover(key, sig, &it, wincx); } - + if (rv == SECSuccess) { if (givenDigestAlg != SEC_OID_UNKNOWN) { /* We don't need to parse the DigestInfo if the caller gave us the @@ -74,7 +74,7 @@ recoverPKCS1DigestInfo(SECOidTag givenDigestAlg, * that the DigestInfo is encoded absolutely correctly. */ *digestInfoLen = it.len; - *digestInfo = (unsigned char*)it.data; + *digestInfo = (unsigned char *)it.data; *digestAlgOut = givenDigestAlg; return SECSuccess; } @@ -104,8 +104,9 @@ recoverPKCS1DigestInfo(SECOidTag givenDigestAlg, if (rv == SECSuccess) { *digestInfoLen = it.len; - *digestInfo = (unsigned char*)it.data; - } else { + *digestInfo = (unsigned char *)it.data; + } + else { if (it.data) { PORT_Free(it.data); } @@ -118,7 +119,7 @@ recoverPKCS1DigestInfo(SECOidTag givenDigestAlg, } struct VFYContextStr { - SECOidTag hashAlg; /* the hash algorithm */ + SECOidTag hashAlg; /* the hash algorithm */ SECKEYPublicKey *key; /* * This buffer holds either the digest or the full signature @@ -130,35 +131,35 @@ struct VFYContextStr { * the size of the union or some other union member instead. */ union { - unsigned char buffer[1]; + unsigned char buffer[1]; - /* the full DSA signature... 40 bytes */ - unsigned char dsasig[DSA_MAX_SIGNATURE_LEN]; - /* the full ECDSA signature */ - unsigned char ecdsasig[2 * MAX_ECKEY_LEN]; + /* the full DSA signature... 40 bytes */ + unsigned char dsasig[DSA_MAX_SIGNATURE_LEN]; + /* the full ECDSA signature */ + unsigned char ecdsasig[2 * MAX_ECKEY_LEN]; } u; unsigned int pkcs1RSADigestInfoLen; /* the encoded DigestInfo from a RSA PKCS#1 signature */ unsigned char *pkcs1RSADigestInfo; - void * wincx; + void *wincx; void *hashcx; const SECHashObject *hashobj; - SECOidTag encAlg; /* enc alg */ - PRBool hasSignature; /* true if the signature was provided in the - * VFY_CreateContext call. If false, the - * signature must be provided with a - * VFY_EndWithSignature call. */ + SECOidTag encAlg; /* enc alg */ + PRBool hasSignature; /* true if the signature was provided in the + * VFY_CreateContext call. If false, the + * signature must be provided with a + * VFY_EndWithSignature call. */ }; static SECStatus -verifyPKCS1DigestInfo(const VFYContext* cx, const SECItem* digest) +verifyPKCS1DigestInfo(const VFYContext *cx, const SECItem *digest) { - SECItem pkcs1DigestInfo; - pkcs1DigestInfo.data = cx->pkcs1RSADigestInfo; - pkcs1DigestInfo.len = cx->pkcs1RSADigestInfoLen; - return _SGN_VerifyPKCS1DigestInfo( - cx->hashAlg, digest, &pkcs1DigestInfo, - PR_TRUE /*XXX: unsafeAllowMissingParameters*/); + SECItem pkcs1DigestInfo; + pkcs1DigestInfo.data = cx->pkcs1RSADigestInfo; + pkcs1DigestInfo.len = cx->pkcs1RSADigestInfoLen; + return _SGN_VerifyPKCS1DigestInfo( + cx->hashAlg, digest, &pkcs1DigestInfo, + PR_TRUE /*XXX: unsafeAllowMissingParameters*/); } /* @@ -168,47 +169,51 @@ verifyPKCS1DigestInfo(const VFYContext* cx, const SECItem* digest) */ static SECStatus decodeECorDSASignature(SECOidTag algid, const SECItem *sig, unsigned char *dsig, - unsigned int len) { + unsigned int len) +{ SECItem *dsasig = NULL; /* also used for ECDSA */ - SECStatus rv=SECSuccess; + SECStatus rv = SECSuccess; if ((algid != SEC_OID_ANSIX9_DSA_SIGNATURE) && - (algid != SEC_OID_ANSIX962_EC_PUBLIC_KEY) ) { + (algid != SEC_OID_ANSIX962_EC_PUBLIC_KEY)) { if (sig->len != len) { - PORT_SetError(SEC_ERROR_BAD_DER); - return SECFailure; - } + PORT_SetError(SEC_ERROR_BAD_DER); + return SECFailure; + } - PORT_Memcpy(dsig, sig->data, sig->len); - return SECSuccess; + PORT_Memcpy(dsig, sig->data, sig->len); + return SECSuccess; } - if (algid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) { - if (len > MAX_ECKEY_LEN * 2) { - PORT_SetError(SEC_ERROR_BAD_DER); - return SECFailure; - } + if (algid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) { + if (len > MAX_ECKEY_LEN * 2) { + PORT_SetError(SEC_ERROR_BAD_DER); + return SECFailure; + } } dsasig = DSAU_DecodeDerSigToLen((SECItem *)sig, len); if ((dsasig == NULL) || (dsasig->len != len)) { - rv = SECFailure; - } else { - PORT_Memcpy(dsig, dsasig->data, dsasig->len); + rv = SECFailure; + } + else { + PORT_Memcpy(dsig, dsasig->data, dsasig->len); } - if (dsasig != NULL) SECITEM_FreeItem(dsasig, PR_TRUE); - if (rv == SECFailure) PORT_SetError(SEC_ERROR_BAD_DER); + if (dsasig != NULL) + SECITEM_FreeItem(dsasig, PR_TRUE); + if (rv == SECFailure) + PORT_SetError(SEC_ERROR_BAD_DER); return rv; } const SEC_ASN1Template hashParameterTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECItem) }, - { SEC_ASN1_OBJECT_ID, 0 }, - { SEC_ASN1_SKIP_REST }, - { 0, } -}; + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECItem) }, + { SEC_ASN1_OBJECT_ID, 0 }, + { SEC_ASN1_SKIP_REST }, + { 0 } + }; /* * Pulls the hash algorithm, signing algorithm, and key type out of a @@ -222,160 +227,164 @@ const SEC_ASN1Template hashParameterTemplate[] = * algorithm was not found or was not a signing algorithm. */ SECStatus -sec_DecodeSigAlg(const SECKEYPublicKey *key, SECOidTag sigAlg, - const SECItem *param, SECOidTag *encalg, SECOidTag *hashalg) +sec_DecodeSigAlg(const SECKEYPublicKey *key, SECOidTag sigAlg, + const SECItem *param, SECOidTag *encalg, SECOidTag *hashalg) { int len; PLArenaPool *arena; SECStatus rv; SECItem oid; - PR_ASSERT(hashalg!=NULL); - PR_ASSERT(encalg!=NULL); + PR_ASSERT(hashalg != NULL); + PR_ASSERT(encalg != NULL); switch (sigAlg) { - /* We probably shouldn't be generating MD2 signatures either */ - case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION: - *hashalg = SEC_OID_MD2; - break; - case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: - *hashalg = SEC_OID_MD5; - break; - case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: - case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE: - case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE: - *hashalg = SEC_OID_SHA1; - break; - case SEC_OID_PKCS1_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: - *hashalg = SEC_OID_UNKNOWN; /* get it from the RSA signature */ - break; + /* We probably shouldn't be generating MD2 signatures either */ + case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION: + *hashalg = SEC_OID_MD2; + break; + case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: + *hashalg = SEC_OID_MD5; + break; + case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: + case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE: + case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE: + *hashalg = SEC_OID_SHA1; + break; + case SEC_OID_PKCS1_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: + *hashalg = SEC_OID_UNKNOWN; /* get it from the RSA signature */ + break; - case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: - case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: - case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST: - *hashalg = SEC_OID_SHA224; - break; - case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: - case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: - case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST: - *hashalg = SEC_OID_SHA256; - break; - case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: - case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: - *hashalg = SEC_OID_SHA384; - break; - case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: - case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: - *hashalg = SEC_OID_SHA512; - break; + case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: + case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: + case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST: + *hashalg = SEC_OID_SHA224; + break; + case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: + case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: + case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST: + *hashalg = SEC_OID_SHA256; + break; + case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: + case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: + *hashalg = SEC_OID_SHA384; + break; + case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: + case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: + *hashalg = SEC_OID_SHA512; + break; - /* what about normal DSA? */ - case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST: - case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST: - case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE: - *hashalg = SEC_OID_SHA1; - break; - case SEC_OID_MISSI_DSS: - case SEC_OID_MISSI_KEA_DSS: - case SEC_OID_MISSI_KEA_DSS_OLD: - case SEC_OID_MISSI_DSS_OLD: - *hashalg = SEC_OID_SHA1; - break; - case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST: - /* This is an EC algorithm. Recommended means the largest - * hash algorithm that is not reduced by the keysize of - * the EC algorithm. Note that key strength is in bytes and - * algorithms are specified in bits. Never use an algorithm - * weaker than sha1. */ - len = SECKEY_PublicKeyStrength(key); - if (len < 28) { /* 28 bytes == 224 bits */ - *hashalg = SEC_OID_SHA1; - } else if (len < 32) { /* 32 bytes == 256 bits */ - *hashalg = SEC_OID_SHA224; - } else if (len < 48) { /* 48 bytes == 384 bits */ - *hashalg = SEC_OID_SHA256; - } else if (len < 64) { /* 48 bytes == 512 bits */ - *hashalg = SEC_OID_SHA384; - } else { - /* use the largest in this case */ - *hashalg = SEC_OID_SHA512; - } - break; - case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST: - if (param == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; - } - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - return SECFailure; - } - rv = SEC_QuickDERDecodeItem(arena, &oid, hashParameterTemplate, param); - if (rv == SECSuccess) { - *hashalg = SECOID_FindOIDTag(&oid); - } - PORT_FreeArena(arena, PR_FALSE); - if (rv != SECSuccess) { - return rv; - } - /* only accept hash algorithms */ - if (HASH_GetHashTypeByOidTag(*hashalg) == HASH_AlgNULL) { - /* error set by HASH_GetHashTypeByOidTag */ - return SECFailure; - } - break; - /* we don't implement MD4 hashes */ - case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION: - default: - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; + /* what about normal DSA? */ + case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST: + case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST: + case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE: + *hashalg = SEC_OID_SHA1; + break; + case SEC_OID_MISSI_DSS: + case SEC_OID_MISSI_KEA_DSS: + case SEC_OID_MISSI_KEA_DSS_OLD: + case SEC_OID_MISSI_DSS_OLD: + *hashalg = SEC_OID_SHA1; + break; + case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST: + /* This is an EC algorithm. Recommended means the largest + * hash algorithm that is not reduced by the keysize of + * the EC algorithm. Note that key strength is in bytes and + * algorithms are specified in bits. Never use an algorithm + * weaker than sha1. */ + len = SECKEY_PublicKeyStrength(key); + if (len < 28) { /* 28 bytes == 224 bits */ + *hashalg = SEC_OID_SHA1; + } + else if (len < 32) { /* 32 bytes == 256 bits */ + *hashalg = SEC_OID_SHA224; + } + else if (len < 48) { /* 48 bytes == 384 bits */ + *hashalg = SEC_OID_SHA256; + } + else if (len < 64) { /* 48 bytes == 512 bits */ + *hashalg = SEC_OID_SHA384; + } + else { + /* use the largest in this case */ + *hashalg = SEC_OID_SHA512; + } + break; + case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST: + if (param == NULL) { + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return SECFailure; + } + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (arena == NULL) { + return SECFailure; + } + rv = SEC_QuickDERDecodeItem(arena, &oid, hashParameterTemplate, param); + if (rv == SECSuccess) { + *hashalg = SECOID_FindOIDTag(&oid); + } + PORT_FreeArena(arena, PR_FALSE); + if (rv != SECSuccess) { + return rv; + } + /* only accept hash algorithms */ + if (HASH_GetHashTypeByOidTag(*hashalg) == HASH_AlgNULL) { + /* error set by HASH_GetHashTypeByOidTag */ + return SECFailure; + } + break; + /* we don't implement MD4 hashes */ + case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION: + default: + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return SECFailure; } - /* get the "encryption" algorithm */ + /* get the "encryption" algorithm */ switch (sigAlg) { - case SEC_OID_PKCS1_RSA_ENCRYPTION: - case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: - case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE: - case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE: - case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: - *encalg = SEC_OID_PKCS1_RSA_ENCRYPTION; - break; - case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: - *encalg = SEC_OID_PKCS1_RSA_PSS_SIGNATURE; - break; + case SEC_OID_PKCS1_RSA_ENCRYPTION: + case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: + case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE: + case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE: + case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: + *encalg = SEC_OID_PKCS1_RSA_ENCRYPTION; + break; + case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: + *encalg = SEC_OID_PKCS1_RSA_PSS_SIGNATURE; + break; - /* what about normal DSA? */ - case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST: - case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST: - case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST: - case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST: - *encalg = SEC_OID_ANSIX9_DSA_SIGNATURE; - break; - case SEC_OID_MISSI_DSS: - case SEC_OID_MISSI_KEA_DSS: - case SEC_OID_MISSI_KEA_DSS_OLD: - case SEC_OID_MISSI_DSS_OLD: - *encalg = SEC_OID_MISSI_DSS; - break; - case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST: - case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST: - *encalg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; - break; - /* we don't implement MD4 hashes */ - case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION: - default: - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; + /* what about normal DSA? */ + case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST: + case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST: + case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST: + case SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST: + *encalg = SEC_OID_ANSIX9_DSA_SIGNATURE; + break; + case SEC_OID_MISSI_DSS: + case SEC_OID_MISSI_KEA_DSS: + case SEC_OID_MISSI_KEA_DSS_OLD: + case SEC_OID_MISSI_DSS_OLD: + *encalg = SEC_OID_MISSI_DSS; + break; + case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST: + case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST: + *encalg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; + break; + /* we don't implement MD4 hashes */ + case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION: + default: + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return SECFailure; } return SECSuccess; } @@ -388,13 +397,13 @@ sec_DecodeSigAlg(const SECKEYPublicKey *key, SECOidTag sigAlg, * our base vfyCreate function takes. * * There is one noteworthy corner case, if we are using an RSA key, and the - * signature block is provided, then the hashAlg can be specified as + * signature block is provided, then the hashAlg can be specified as * SEC_OID_UNKNOWN. In this case, verify will use the hash oid supplied * in the RSA signature block. */ static VFYContext * -vfy_CreateContext(const SECKEYPublicKey *key, const SECItem *sig, - SECOidTag encAlg, SECOidTag hashAlg, SECOidTag *hash, void *wincx) +vfy_CreateContext(const SECKEYPublicKey *key, const SECItem *sig, + SECOidTag encAlg, SECOidTag hashAlg, SECOidTag *hash, void *wincx) { VFYContext *cx; SECStatus rv; @@ -405,14 +414,14 @@ vfy_CreateContext(const SECKEYPublicKey *key, const SECItem *sig, /* RSA-PSS algorithm can be used with both rsaKey and rsaPssKey */ type = seckey_GetKeyType(encAlg); if ((key->keyType != type) && - ((key->keyType != rsaKey) || (type != rsaPssKey))) { - PORT_SetError(SEC_ERROR_PKCS7_KEYALG_MISMATCH); - return NULL; + ((key->keyType != rsaKey) || (type != rsaPssKey))) { + PORT_SetError(SEC_ERROR_PKCS7_KEYALG_MISMATCH); + return NULL; } - cx = (VFYContext*) PORT_ZAlloc(sizeof(VFYContext)); + cx = (VFYContext *)PORT_ZAlloc(sizeof(VFYContext)); if (cx == NULL) { - goto loser; + goto loser; } cx->wincx = wincx; @@ -423,81 +432,82 @@ vfy_CreateContext(const SECKEYPublicKey *key, const SECItem *sig, cx->pkcs1RSADigestInfo = NULL; rv = SECSuccess; if (sig) { - switch (type) { - case rsaKey: - rv = recoverPKCS1DigestInfo(hashAlg, &cx->hashAlg, - &cx->pkcs1RSADigestInfo, - &cx->pkcs1RSADigestInfoLen, - cx->key, - sig, wincx); - break; - case dsaKey: - case ecKey: - sigLen = SECKEY_SignatureLen(key); - if (sigLen == 0) { - /* error set by SECKEY_SignatureLen */ - rv = SECFailure; - break; - } - rv = decodeECorDSASignature(encAlg, sig, cx->u.buffer, sigLen); - break; - default: - rv = SECFailure; - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - break; - } + switch (type) { + case rsaKey: + rv = recoverPKCS1DigestInfo(hashAlg, &cx->hashAlg, + &cx->pkcs1RSADigestInfo, + &cx->pkcs1RSADigestInfoLen, + cx->key, + sig, wincx); + break; + case dsaKey: + case ecKey: + sigLen = SECKEY_SignatureLen(key); + if (sigLen == 0) { + /* error set by SECKEY_SignatureLen */ + rv = SECFailure; + break; + } + rv = decodeECorDSASignature(encAlg, sig, cx->u.buffer, sigLen); + break; + default: + rv = SECFailure; + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); + break; + } } - if (rv) goto loser; + if (rv) + goto loser; /* check hash alg again, RSA may have changed it.*/ if (HASH_GetHashTypeByOidTag(cx->hashAlg) == HASH_AlgNULL) { - /* error set by HASH_GetHashTypeByOidTag */ - goto loser; + /* error set by HASH_GetHashTypeByOidTag */ + goto loser; } if (hash) { - *hash = cx->hashAlg; + *hash = cx->hashAlg; } return cx; - loser: +loser: if (cx) { - VFY_DestroyContext(cx, PR_TRUE); + VFY_DestroyContext(cx, PR_TRUE); } return 0; } VFYContext * VFY_CreateContext(SECKEYPublicKey *key, SECItem *sig, SECOidTag sigAlg, - void *wincx) + void *wincx) { SECOidTag encAlg, hashAlg; SECStatus rv = sec_DecodeSigAlg(key, sigAlg, NULL, &encAlg, &hashAlg); if (rv != SECSuccess) { - return NULL; + return NULL; } return vfy_CreateContext(key, sig, encAlg, hashAlg, NULL, wincx); } VFYContext * -VFY_CreateContextDirect(const SECKEYPublicKey *key, const SECItem *sig, - SECOidTag encAlg, SECOidTag hashAlg, - SECOidTag *hash, void *wincx) +VFY_CreateContextDirect(const SECKEYPublicKey *key, const SECItem *sig, + SECOidTag encAlg, SECOidTag hashAlg, + SECOidTag *hash, void *wincx) { - return vfy_CreateContext(key, sig, encAlg, hashAlg, hash, wincx); + return vfy_CreateContext(key, sig, encAlg, hashAlg, hash, wincx); } VFYContext * VFY_CreateContextWithAlgorithmID(const SECKEYPublicKey *key, const SECItem *sig, - const SECAlgorithmID *sigAlgorithm, SECOidTag *hash, void *wincx) + const SECAlgorithmID *sigAlgorithm, SECOidTag *hash, void *wincx) { SECOidTag encAlg, hashAlg; - SECStatus rv = sec_DecodeSigAlg(key, - SECOID_GetAlgorithmTag((SECAlgorithmID *)sigAlgorithm), - &sigAlgorithm->parameters, &encAlg, &hashAlg); + SECStatus rv = sec_DecodeSigAlg(key, + SECOID_GetAlgorithmTag((SECAlgorithmID *)sigAlgorithm), + &sigAlgorithm->parameters, &encAlg, &hashAlg); if (rv != SECSuccess) { - return NULL; + return NULL; } return vfy_CreateContext(key, sig, encAlg, hashAlg, hash, wincx); } @@ -506,19 +516,19 @@ void VFY_DestroyContext(VFYContext *cx, PRBool freeit) { if (cx) { - if (cx->hashcx != NULL) { - (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); - cx->hashcx = NULL; - } - if (cx->key) { - SECKEY_DestroyPublicKey(cx->key); - } - if (cx->pkcs1RSADigestInfo) { - PORT_Free(cx->pkcs1RSADigestInfo); - } - if (freeit) { - PORT_ZFree(cx, sizeof(VFYContext)); - } + if (cx->hashcx != NULL) { + (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); + cx->hashcx = NULL; + } + if (cx->key) { + SECKEY_DestroyPublicKey(cx->key); + } + if (cx->pkcs1RSADigestInfo) { + PORT_Free(cx->pkcs1RSADigestInfo); + } + if (freeit) { + PORT_ZFree(cx, sizeof(VFYContext)); + } } } @@ -526,17 +536,17 @@ SECStatus VFY_Begin(VFYContext *cx) { if (cx->hashcx != NULL) { - (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); - cx->hashcx = NULL; + (*cx->hashobj->destroy)(cx->hashcx, PR_TRUE); + cx->hashcx = NULL; } cx->hashobj = HASH_GetHashObjectByOidTag(cx->hashAlg); - if (!cx->hashobj) - return SECFailure; /* error code is set */ + if (!cx->hashobj) + return SECFailure; /* error code is set */ cx->hashcx = (*cx->hashobj->create)(); if (cx->hashcx == NULL) - return SECFailure; + return SECFailure; (*cx->hashobj->begin)(cx->hashcx); return SECSuccess; @@ -546,8 +556,8 @@ SECStatus VFY_Update(VFYContext *cx, const unsigned char *input, unsigned inputLen) { if (cx->hashcx == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } (*cx->hashobj->update)(cx->hashcx, input, inputLen); return SECSuccess; @@ -558,65 +568,64 @@ VFY_EndWithSignature(VFYContext *cx, SECItem *sig) { unsigned char final[HASH_LENGTH_MAX]; unsigned part; - SECItem hash,dsasig; /* dsasig is also used for ECDSA */ + SECItem hash, dsasig; /* dsasig is also used for ECDSA */ SECStatus rv; if ((cx->hasSignature == PR_FALSE) && (sig == NULL)) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } if (cx->hashcx == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } (*cx->hashobj->end)(cx->hashcx, final, &part, sizeof(final)); switch (cx->key->keyType) { - case ecKey: - case dsaKey: - dsasig.data = cx->u.buffer; - dsasig.len = SECKEY_SignatureLen(cx->key); - if (dsasig.len == 0) { - return SECFailure; - } - if (sig) { - rv = decodeECorDSASignature(cx->encAlg, sig, dsasig.data, - dsasig.len); - if (rv != SECSuccess) { - PORT_SetError(SEC_ERROR_BAD_SIGNATURE); - return SECFailure; - } - } - hash.data = final; - hash.len = part; - if (PK11_Verify(cx->key,&dsasig,&hash,cx->wincx) != SECSuccess) { - PORT_SetError(SEC_ERROR_BAD_SIGNATURE); - return SECFailure; - } - break; - case rsaKey: - { - SECItem digest; - digest.data = final; - digest.len = part; - if (sig) { - SECOidTag hashid; - PORT_Assert(cx->hashAlg != SEC_OID_UNKNOWN); - rv = recoverPKCS1DigestInfo(cx->hashAlg, &hashid, - &cx->pkcs1RSADigestInfo, - &cx->pkcs1RSADigestInfoLen, - cx->key, - sig, cx->wincx); - PORT_Assert(cx->hashAlg == hashid); - if (rv != SECSuccess) { - return SECFailure; - } - } - return verifyPKCS1DigestInfo(cx, &digest); - } - default: - PORT_SetError(SEC_ERROR_BAD_SIGNATURE); - return SECFailure; /* shouldn't happen */ + case ecKey: + case dsaKey: + dsasig.data = cx->u.buffer; + dsasig.len = SECKEY_SignatureLen(cx->key); + if (dsasig.len == 0) { + return SECFailure; + } + if (sig) { + rv = decodeECorDSASignature(cx->encAlg, sig, dsasig.data, + dsasig.len); + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_BAD_SIGNATURE); + return SECFailure; + } + } + hash.data = final; + hash.len = part; + if (PK11_Verify(cx->key, &dsasig, &hash, cx->wincx) != SECSuccess) { + PORT_SetError(SEC_ERROR_BAD_SIGNATURE); + return SECFailure; + } + break; + case rsaKey: { + SECItem digest; + digest.data = final; + digest.len = part; + if (sig) { + SECOidTag hashid; + PORT_Assert(cx->hashAlg != SEC_OID_UNKNOWN); + rv = recoverPKCS1DigestInfo(cx->hashAlg, &hashid, + &cx->pkcs1RSADigestInfo, + &cx->pkcs1RSADigestInfoLen, + cx->key, + sig, cx->wincx); + PORT_Assert(cx->hashAlg == hashid); + if (rv != SECSuccess) { + return SECFailure; + } + } + return verifyPKCS1DigestInfo(cx, &digest); + } + default: + PORT_SetError(SEC_ERROR_BAD_SIGNATURE); + return SECFailure; /* shouldn't happen */ } return SECSuccess; } @@ -624,7 +633,7 @@ VFY_EndWithSignature(VFYContext *cx, SECItem *sig) SECStatus VFY_End(VFYContext *cx) { - return VFY_EndWithSignature(cx,NULL); + return VFY_EndWithSignature(cx, NULL); } /************************************************************************/ @@ -632,9 +641,9 @@ VFY_End(VFYContext *cx) * Verify that a previously-computed digest matches a signature. */ static SECStatus -vfy_VerifyDigest(const SECItem *digest, const SECKEYPublicKey *key, - const SECItem *sig, SECOidTag encAlg, SECOidTag hashAlg, - void *wincx) +vfy_VerifyDigest(const SECItem *digest, const SECKEYPublicKey *key, + const SECItem *sig, SECOidTag encAlg, SECOidTag hashAlg, + void *wincx) { SECStatus rv; VFYContext *cx; @@ -644,48 +653,49 @@ vfy_VerifyDigest(const SECItem *digest, const SECKEYPublicKey *key, cx = vfy_CreateContext(key, sig, encAlg, hashAlg, NULL, wincx); if (cx != NULL) { - switch (key->keyType) { - case rsaKey: - rv = verifyPKCS1DigestInfo(cx, digest); - break; - case dsaKey: - case ecKey: - dsasig.data = cx->u.buffer; - dsasig.len = SECKEY_SignatureLen(cx->key); - if (dsasig.len == 0) { - break; - } - if (PK11_Verify(cx->key, &dsasig, (SECItem *)digest, cx->wincx) - != SECSuccess) { - PORT_SetError(SEC_ERROR_BAD_SIGNATURE); - } else { - rv = SECSuccess; - } - break; - default: - break; - } - VFY_DestroyContext(cx, PR_TRUE); + switch (key->keyType) { + case rsaKey: + rv = verifyPKCS1DigestInfo(cx, digest); + break; + case dsaKey: + case ecKey: + dsasig.data = cx->u.buffer; + dsasig.len = SECKEY_SignatureLen(cx->key); + if (dsasig.len == 0) { + break; + } + if (PK11_Verify(cx->key, &dsasig, (SECItem *)digest, cx->wincx) != + SECSuccess) { + PORT_SetError(SEC_ERROR_BAD_SIGNATURE); + } + else { + rv = SECSuccess; + } + break; + default: + break; + } + VFY_DestroyContext(cx, PR_TRUE); } return rv; } SECStatus -VFY_VerifyDigestDirect(const SECItem *digest, const SECKEYPublicKey *key, - const SECItem *sig, SECOidTag encAlg, - SECOidTag hashAlg, void *wincx) +VFY_VerifyDigestDirect(const SECItem *digest, const SECKEYPublicKey *key, + const SECItem *sig, SECOidTag encAlg, + SECOidTag hashAlg, void *wincx) { return vfy_VerifyDigest(digest, key, sig, encAlg, hashAlg, wincx); } SECStatus VFY_VerifyDigest(SECItem *digest, SECKEYPublicKey *key, SECItem *sig, - SECOidTag algid, void *wincx) + SECOidTag algid, void *wincx) { SECOidTag encAlg, hashAlg; SECStatus rv = sec_DecodeSigAlg(key, algid, NULL, &encAlg, &hashAlg); if (rv != SECSuccess) { - return SECFailure; + return SECFailure; } return vfy_VerifyDigest(digest, key, sig, encAlg, hashAlg, wincx); } @@ -695,44 +705,44 @@ VFY_VerifyDigest(SECItem *digest, SECKEYPublicKey *key, SECItem *sig, * will be compared with our target hash value. */ SECStatus -VFY_VerifyDigestWithAlgorithmID(const SECItem *digest, - const SECKEYPublicKey *key, const SECItem *sig, - const SECAlgorithmID *sigAlgorithm, - SECOidTag hashCmp, void *wincx) +VFY_VerifyDigestWithAlgorithmID(const SECItem *digest, + const SECKEYPublicKey *key, const SECItem *sig, + const SECAlgorithmID *sigAlgorithm, + SECOidTag hashCmp, void *wincx) { SECOidTag encAlg, hashAlg; - SECStatus rv = sec_DecodeSigAlg(key, - SECOID_GetAlgorithmTag((SECAlgorithmID *)sigAlgorithm), - &sigAlgorithm->parameters, &encAlg, &hashAlg); + SECStatus rv = sec_DecodeSigAlg(key, + SECOID_GetAlgorithmTag((SECAlgorithmID *)sigAlgorithm), + &sigAlgorithm->parameters, &encAlg, &hashAlg); if (rv != SECSuccess) { - return rv; + return rv; } - if ( hashCmp != SEC_OID_UNKNOWN && - hashAlg != SEC_OID_UNKNOWN && - hashCmp != hashAlg) { - PORT_SetError(SEC_ERROR_BAD_SIGNATURE); - return SECFailure; + if (hashCmp != SEC_OID_UNKNOWN && + hashAlg != SEC_OID_UNKNOWN && + hashCmp != hashAlg) { + PORT_SetError(SEC_ERROR_BAD_SIGNATURE); + return SECFailure; } return vfy_VerifyDigest(digest, key, sig, encAlg, hashAlg, wincx); } static SECStatus vfy_VerifyData(const unsigned char *buf, int len, const SECKEYPublicKey *key, - const SECItem *sig, SECOidTag encAlg, SECOidTag hashAlg, - SECOidTag *hash, void *wincx) + const SECItem *sig, SECOidTag encAlg, SECOidTag hashAlg, + SECOidTag *hash, void *wincx) { SECStatus rv; VFYContext *cx; cx = vfy_CreateContext(key, sig, encAlg, hashAlg, hash, wincx); if (cx == NULL) - return SECFailure; + return SECFailure; rv = VFY_Begin(cx); if (rv == SECSuccess) { - rv = VFY_Update(cx, (unsigned char *)buf, len); - if (rv == SECSuccess) - rv = VFY_End(cx); + rv = VFY_Update(cx, (unsigned char *)buf, len); + if (rv == SECSuccess) + rv = VFY_End(cx); } VFY_DestroyContext(cx, PR_TRUE); @@ -740,39 +750,39 @@ vfy_VerifyData(const unsigned char *buf, int len, const SECKEYPublicKey *key, } SECStatus -VFY_VerifyDataDirect(const unsigned char *buf, int len, - const SECKEYPublicKey *key, const SECItem *sig, - SECOidTag encAlg, SECOidTag hashAlg, - SECOidTag *hash, void *wincx) +VFY_VerifyDataDirect(const unsigned char *buf, int len, + const SECKEYPublicKey *key, const SECItem *sig, + SECOidTag encAlg, SECOidTag hashAlg, + SECOidTag *hash, void *wincx) { return vfy_VerifyData(buf, len, key, sig, encAlg, hashAlg, hash, wincx); } SECStatus VFY_VerifyData(const unsigned char *buf, int len, const SECKEYPublicKey *key, - const SECItem *sig, SECOidTag algid, void *wincx) + const SECItem *sig, SECOidTag algid, void *wincx) { SECOidTag encAlg, hashAlg; SECStatus rv = sec_DecodeSigAlg(key, algid, NULL, &encAlg, &hashAlg); if (rv != SECSuccess) { - return rv; + return rv; } return vfy_VerifyData(buf, len, key, sig, encAlg, hashAlg, NULL, wincx); } SECStatus -VFY_VerifyDataWithAlgorithmID(const unsigned char *buf, int len, - const SECKEYPublicKey *key, - const SECItem *sig, - const SECAlgorithmID *sigAlgorithm, - SECOidTag *hash, void *wincx) +VFY_VerifyDataWithAlgorithmID(const unsigned char *buf, int len, + const SECKEYPublicKey *key, + const SECItem *sig, + const SECAlgorithmID *sigAlgorithm, + SECOidTag *hash, void *wincx) { SECOidTag encAlg, hashAlg; SECOidTag sigAlg = SECOID_GetAlgorithmTag((SECAlgorithmID *)sigAlgorithm); - SECStatus rv = sec_DecodeSigAlg(key, sigAlg, - &sigAlgorithm->parameters, &encAlg, &hashAlg); + SECStatus rv = sec_DecodeSigAlg(key, sigAlg, + &sigAlgorithm->parameters, &encAlg, &hashAlg); if (rv != SECSuccess) { - return rv; + return rv; } return vfy_VerifyData(buf, len, key, sig, encAlg, hashAlg, hash, wincx); } diff --git a/security/nss/lib/freebl/ecl/ec_naf.c b/security/nss/lib/freebl/ecl/ec_naf.c index 3db6f300f718..20892f09d0f8 100644 --- a/security/nss/lib/freebl/ecl/ec_naf.c +++ b/security/nss/lib/freebl/ecl/ec_naf.c @@ -48,14 +48,14 @@ ec_compute_wNAF(signed char *out, int bitsize, const mp_int *in, int w) /* Subtract off out[i]. Note mp_sub_d only works with * unsigned digits */ if (out[i] >= 0) { - mp_sub_d(&k, out[i], &k); + MP_CHECKOK(mp_sub_d(&k, out[i], &k)); } else { - mp_add_d(&k, -(out[i]), &k); + MP_CHECKOK(mp_add_d(&k, -(out[i]), &k)); } } else { out[i] = 0; } - mp_div_2(&k, &k); + MP_CHECKOK(mp_div_2(&k, &k)); i++; } /* Zero out the remaining elements of the out array. */ diff --git a/security/nss/lib/freebl/ecl/ecp_256_32.c b/security/nss/lib/freebl/ecl/ecp_256_32.c index cd8cd23846df..eb7a4be63a12 100644 --- a/security/nss/lib/freebl/ecl/ecp_256_32.c +++ b/security/nss/lib/freebl/ecl/ecp_256_32.c @@ -1302,23 +1302,23 @@ static mp_err to_montgomery(felem out, const mp_int *in, const ECGroup *group) int i; mp_err res; - mp_init(&in_shifted); - s_mp_pad(&in_shifted, MP_USED(in) + MP_DIGITS_IN_256_BITS); + MP_CHECKOK(mp_init(&in_shifted)); + MP_CHECKOK(s_mp_pad(&in_shifted, MP_USED(in) + MP_DIGITS_IN_256_BITS)); memcpy(&MP_DIGIT(&in_shifted, MP_DIGITS_IN_256_BITS), MP_DIGITS(in), MP_USED(in)*sizeof(mp_digit)); - mp_mul_2(&in_shifted, &in_shifted); + MP_CHECKOK(mp_mul_2(&in_shifted, &in_shifted)); MP_CHECKOK(group->meth->field_mod(&in_shifted, &in_shifted, group->meth)); for (i = 0;; i++) { out[i] = MP_DIGIT(&in_shifted, 0) & kBottom29Bits; - mp_div_d(&in_shifted, kTwo29, &in_shifted, NULL); + MP_CHECKOK(mp_div_d(&in_shifted, kTwo29, &in_shifted, NULL)); i++; if (i == NLIMBS) break; out[i] = MP_DIGIT(&in_shifted, 0) & kBottom28Bits; - mp_div_d(&in_shifted, kTwo28, &in_shifted, NULL); + MP_CHECKOK(mp_div_d(&in_shifted, kTwo28, &in_shifted, NULL)); } CLEANUP: @@ -1334,8 +1334,8 @@ static mp_err from_montgomery(mp_int *out, const felem in, mp_err res; int i; - mp_init(&result); - mp_init(&tmp); + MP_CHECKOK(mp_init(&result)); + MP_CHECKOK(mp_init(&tmp)); MP_CHECKOK(mp_add_d(&tmp, in[NLIMBS-1], &result)); for (i = NLIMBS-2; i >= 0; i--) { diff --git a/security/nss/lib/freebl/ecl/ecp_aff.c b/security/nss/lib/freebl/ecl/ecp_aff.c index 92e860448ae5..41381073be05 100644 --- a/security/nss/lib/freebl/ecl/ecp_aff.c +++ b/security/nss/lib/freebl/ecl/ecp_aff.c @@ -280,8 +280,8 @@ ec_GFp_validate_point(const mp_int *px, const mp_int *py, const ECGroup *group) group->meth->field_enc(px, &pxt, group->meth); group->meth->field_enc(py, &pyt, group->meth); } else { - mp_copy(px, &pxt); - mp_copy(py, &pyt); + MP_CHECKOK( mp_copy(px, &pxt) ); + MP_CHECKOK( mp_copy(py, &pyt) ); } /* left-hand side: y^2 */ MP_CHECKOK( group->meth->field_sqr(&pyt, &accl, group->meth) ); diff --git a/security/nss/lib/freebl/mpi/mpi.c b/security/nss/lib/freebl/mpi/mpi.c index 84f9b97b63ea..ac19ead44c88 100644 --- a/security/nss/lib/freebl/mpi/mpi.c +++ b/security/nss/lib/freebl/mpi/mpi.c @@ -1336,7 +1336,7 @@ mp_err mp_sqrt(const mp_int *a, mp_int *b) } /* Copy result to output parameter */ - mp_sub_d(&x, 1, &x); + MP_CHECKOK(mp_sub_d(&x, 1, &x)); s_mp_exch(&x, b); CLEANUP: @@ -2959,8 +2959,12 @@ mp_err s_mp_mul_2d(mp_int *mp, mp_digit d) dshift = d / MP_DIGIT_BIT; bshift = d % MP_DIGIT_BIT; /* bits to be shifted out of the top word */ - mask = ((mp_digit)~0 << (MP_DIGIT_BIT - bshift)); - mask &= MP_DIGIT(mp, MP_USED(mp) - 1); + if (bshift) { + mask = (mp_digit)~0 << (MP_DIGIT_BIT - bshift); + mask &= MP_DIGIT(mp, MP_USED(mp) - 1); + } else { + mask = 0; + } if (MP_OKAY != (res = s_mp_pad(mp, MP_USED(mp) + dshift + (mask != 0) ))) return res; diff --git a/security/nss/lib/freebl/mpi/mpmontg.c b/security/nss/lib/freebl/mpi/mpmontg.c index 9667755d0349..c14b104d9984 100644 --- a/security/nss/lib/freebl/mpi/mpmontg.c +++ b/security/nss/lib/freebl/mpi/mpmontg.c @@ -371,12 +371,12 @@ mp_err mp_exptmod_i(const mp_int * montBase, MP_CHECKOK( mp_init_copy(&oddPowers[0], montBase) ); - mp_init_size(&power2, nLen + 2 * MP_USED(montBase) + 2); + MP_CHECKOK( mp_init_size(&power2, nLen + 2 * MP_USED(montBase) + 2) ); MP_CHECKOK( mp_sqr(montBase, &power2) ); /* power2 = montBase ** 2 */ MP_CHECKOK( s_mp_redc(&power2, mmm) ); for (i = 1; i < odd_ints; ++i) { - mp_init_size(oddPowers + i, nLen + 2 * MP_USED(&power2) + 2); + MP_CHECKOK( mp_init_size(oddPowers + i, nLen + 2 * MP_USED(&power2) + 2) ); MP_CHECKOK( mp_mul(oddPowers + (i - 1), &power2, oddPowers + i) ); MP_CHECKOK( s_mp_redc(oddPowers + i, mmm) ); } diff --git a/security/nss/lib/freebl/mpi/mpprime.c b/security/nss/lib/freebl/mpi/mpprime.c index 9b97fb2063d6..e6f00996c6c9 100644 --- a/security/nss/lib/freebl/mpi/mpprime.c +++ b/security/nss/lib/freebl/mpi/mpprime.c @@ -297,7 +297,7 @@ mp_err mpp_pprime(mp_int *a, int nt) for(iter = 0; iter < nt; iter++) { /* Choose a random value for 1 < x < a */ - s_mp_pad(&x, USED(a)); + MP_CHECKOK( s_mp_pad(&x, USED(a)) ); mpp_random(&x); MP_CHECKOK( mp_mod(&x, a, &x) ); if(mp_cmp_d(&x, 1) <= 0) { diff --git a/security/nss/lib/freebl/rijndael.c b/security/nss/lib/freebl/rijndael.c index 4e4be79fdf10..8b3704bed86a 100644 --- a/security/nss/lib/freebl/rijndael.c +++ b/security/nss/lib/freebl/rijndael.c @@ -30,6 +30,9 @@ static PRBool use_hw_aes = PR_FALSE; static int has_intel_avx = 0; static int has_intel_clmul = 0; static PRBool use_hw_gcm = PR_FALSE; +#if defined(_MSC_VER) && !defined(_M_IX86) +#include /* for _xgetbv() */ +#endif #endif #endif /* USE_HW_AES */ diff --git a/security/nss/lib/freebl/rsa.c b/security/nss/lib/freebl/rsa.c index f885acc4433a..823d8def2028 100644 --- a/security/nss/lib/freebl/rsa.c +++ b/security/nss/lib/freebl/rsa.c @@ -747,8 +747,7 @@ RSA_PopulatePrivateKey(RSAPrivateKey *key) } /* if we have the modulus and one prime, calculate the second. */ if ((prime_count == 1) && (hasModulus)) { - mp_div(&n,&p,&q,&r); - if (mp_cmp_z(&r) != 0) { + if (mp_div(&n,&p,&q,&r) != MP_OKAY || mp_cmp_z(&r) != 0) { /* p is not a factor or n, fail */ err = MP_BADARG; goto cleanup; @@ -1096,9 +1095,7 @@ init_blinding_params(RSABlindingParams *rsabp, RSAPrivateKey *key, rsabp->free = bp; /* List elements are keyed using the modulus */ - SECITEM_CopyItem(NULL, &rsabp->modulus, &key->modulus); - - return SECSuccess; + return SECITEM_CopyItem(NULL, &rsabp->modulus, &key->modulus); } static SECStatus diff --git a/security/nss/lib/libpkix/pkix/util/pkix_tools.h b/security/nss/lib/libpkix/pkix/util/pkix_tools.h index 1a4689da78c7..5a8ef2741e61 100755 --- a/security/nss/lib/libpkix/pkix/util/pkix_tools.h +++ b/security/nss/lib/libpkix/pkix/util/pkix_tools.h @@ -1458,8 +1458,8 @@ extern const char *PKIX_ERRORCLASSNAMES[PKIX_NUMERRORCLASSES]; extern PRLogModuleInfo *pkixLog; -#define PKIX_MAGIC_HEADER LL_INIT(0xFEEDC0FF, 0xEEFACADE) -#define PKIX_MAGIC_HEADER_DESTROYED LL_INIT(0xBAADF00D, 0xDEADBEEF) +#define PKIX_MAGIC_HEADER PR_UINT64(0xFEEDC0FFEEFACADE) +#define PKIX_MAGIC_HEADER_DESTROYED PR_UINT64(0xBAADF00DDEADBEEF) /* see source file for function documentation */ diff --git a/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.c b/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.c index 30aefb817c07..471f92004aa8 100755 --- a/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.c +++ b/security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.c @@ -39,10 +39,10 @@ const SEC_ASN1Template SECOID_AlgorithmIDTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECAlgorithmID) }, { SEC_ASN1_OBJECT_ID, - offsetof(SECAlgorithmID,algorithm), }, + offsetof(SECAlgorithmID,algorithm) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, - offsetof(SECAlgorithmID,parameters), }, - { 0, } + offsetof(SECAlgorithmID,parameters) }, + { 0 } }; */ /* --Private-HttpCertStoreContext-Object Functions----------------------- */ diff --git a/security/nss/lib/manifest.mn b/security/nss/lib/manifest.mn index dd4b54292789..ce3a3e6c59a6 100644 --- a/security/nss/lib/manifest.mn +++ b/security/nss/lib/manifest.mn @@ -5,6 +5,38 @@ CORE_DEPTH = .. DEPTH = .. +# Building softoken (and freebl) only requires that the paths +# to the locations where the util headers and libraries were +# previously installed by a prior util-only build - likely in +# in a system location that varies with the distribution. This +# cannot be addressed here and requires that downstream package +# mantainers add suitable modifications. Building full nss will +# not have that problem as everything is available. + +SOFTOKEN_SRCDIRS= +NSS_SRCDIRS= + +ifndef NSS_BUILD_UTIL_ONLY +SOFTOKEN_SRCDIRS = \ + $(FREEBL_SRCDIR) \ + $(SQLITE_SRCDIR) \ + $(DBM_SRCDIR) \ + $(SOFTOKEN_SRCDIR) \ + $(NULL) +ifndef NSS_BUILD_SOFTOKEN_ONLY +# the rest of nss +NSS_SRCDIRS = \ + base dev pki \ + libpkix \ + certdb certhigh pk11wrap cryptohi nss \ + $(ZLIB_SRCDIR) ssl \ + pkcs7 pkcs12 smime \ + crmf jar \ + ckfw $(SYSINIT_SRCDIR) \ + $(NULL) +endif +endif + # # organized by DLL # @@ -18,17 +50,8 @@ DEPTH = .. # crmf jar (not dll's) DIRS = \ $(UTIL_SRCDIR) \ - $(FREEBL_SRCDIR) \ - $(SQLITE_SRCDIR) \ - $(DBM_SRCDIR) \ - $(SOFTOKEN_SRCDIR) \ - base dev pki \ - libpkix \ - certdb certhigh pk11wrap cryptohi nss \ - $(ZLIB_SRCDIR) ssl \ - pkcs7 pkcs12 smime \ - crmf jar \ - ckfw $(SYSINIT_SRCDIR) \ + $(SOFTOKEN_SRCDIRS) \ + $(NSS_SRCDIRS) \ $(NULL) # fortcrypt is no longer built diff --git a/security/nss/lib/nss/nss.def b/security/nss/lib/nss/nss.def index cd2920c05d9b..1760b96e4176 100644 --- a/security/nss/lib/nss/nss.def +++ b/security/nss/lib/nss/nss.def @@ -1090,3 +1090,10 @@ SECMOD_CreateModuleEx; ;+ local: ;+ *; ;+}; +;+NSS_3.22 { # NSS 3.22 release +;+ global: +PK11_SignWithMechanism; +PK11_VerifyWithMechanism; +;+ local: +;+ *; +;+}; diff --git a/security/nss/lib/nss/nss.h b/security/nss/lib/nss/nss.h index 2433cfc19494..9458afb0f456 100644 --- a/security/nss/lib/nss/nss.h +++ b/security/nss/lib/nss/nss.h @@ -33,12 +33,12 @@ * The format of the version string should be * ".[.[.]][ ][ ]" */ -#define NSS_VERSION "3.21" _NSS_ECC_STRING _NSS_CUSTOMIZED +#define NSS_VERSION "3.22" _NSS_ECC_STRING _NSS_CUSTOMIZED " Beta" #define NSS_VMAJOR 3 -#define NSS_VMINOR 21 +#define NSS_VMINOR 22 #define NSS_VPATCH 0 #define NSS_VBUILD 0 -#define NSS_BETA PR_FALSE +#define NSS_BETA PR_TRUE #ifndef RC_INVOKED @@ -296,9 +296,13 @@ SECStatus NSS_UnregisterShutdown(NSS_ShutdownFunc sFunc, void *appData); /* Available options for NSS_OptionSet() and NSS_OptionGet(). */ -#define NSS_RSA_MIN_KEY_SIZE (1<<0) -#define NSS_DH_MIN_KEY_SIZE (1<<1) -#define NSS_DSA_MIN_KEY_SIZE (1<<2) +#define NSS_RSA_MIN_KEY_SIZE 0x001 +#define NSS_DH_MIN_KEY_SIZE 0x002 +#define NSS_DSA_MIN_KEY_SIZE 0x004 +#define NSS_TLS_VERSION_MIN_POLICY 0x008 +#define NSS_TLS_VERSION_MAX_POLICY 0x009 +#define NSS_DTLS_VERSION_MIN_POLICY 0x00a +#define NSS_DTLS_VERSION_MAX_POLICY 0x00b /* * Set and get global options for the NSS library. diff --git a/security/nss/lib/nss/nssoptions.c b/security/nss/lib/nss/nssoptions.c index 10b0138df589..7a77b8f367b5 100644 --- a/security/nss/lib/nss/nssoptions.c +++ b/security/nss/lib/nss/nssoptions.c @@ -19,12 +19,20 @@ struct nssOps { PRInt32 rsaMinKeySize; PRInt32 dhMinKeySize; PRInt32 dsaMinKeySize; + PRInt32 tlsVersionMinPolicy; + PRInt32 tlsVersionMaxPolicy; + PRInt32 dtlsVersionMinPolicy; + PRInt32 dtlsVersionMaxPolicy; }; static struct nssOps nss_ops = { SSL_RSA_MIN_MODULUS_BITS, SSL_DH_MIN_P_BITS, - SSL_DSA_MIN_P_BITS + SSL_DSA_MIN_P_BITS, + 1, /* Set TLS min to less the the smallest legal SSL value */ + 0xffff, /* set TLS max to more than the largest legal SSL value */ + 1, + 0xffff, }; SECStatus @@ -42,6 +50,18 @@ SECStatus rv = SECSuccess; case NSS_DSA_MIN_KEY_SIZE: nss_ops.dsaMinKeySize = value; break; + case NSS_TLS_VERSION_MIN_POLICY: + nss_ops.tlsVersionMinPolicy = value; + break; + case NSS_TLS_VERSION_MAX_POLICY: + nss_ops.tlsVersionMaxPolicy = value; + break; + case NSS_DTLS_VERSION_MIN_POLICY: + nss_ops.dtlsVersionMinPolicy = value; + break; + case NSS_DTLS_VERSION_MAX_POLICY: + nss_ops.dtlsVersionMaxPolicy = value; + break; default: rv = SECFailure; } @@ -64,6 +84,18 @@ SECStatus rv = SECSuccess; case NSS_DSA_MIN_KEY_SIZE: *value = nss_ops.dsaMinKeySize; break; + case NSS_TLS_VERSION_MIN_POLICY: + *value = nss_ops.tlsVersionMinPolicy; + break; + case NSS_TLS_VERSION_MAX_POLICY: + *value = nss_ops.tlsVersionMaxPolicy; + break; + case NSS_DTLS_VERSION_MIN_POLICY: + *value = nss_ops.dtlsVersionMinPolicy; + break; + case NSS_DTLS_VERSION_MAX_POLICY: + *value = nss_ops.dtlsVersionMaxPolicy; + break; default: rv = SECFailure; } diff --git a/security/nss/lib/pk11wrap/pk11obj.c b/security/nss/lib/pk11wrap/pk11obj.c index 848b45a01791..260aeed69873 100644 --- a/security/nss/lib/pk11wrap/pk11obj.c +++ b/security/nss/lib/pk11wrap/pk11obj.c @@ -25,6 +25,8 @@ SECItem * PK11_BlockData(SECItem *data,unsigned long size) { SECItem *newData; + if (size == 0u) return NULL; + newData = (SECItem *)PORT_Alloc(sizeof(SECItem)); if (newData == NULL) return NULL; @@ -665,6 +667,18 @@ PK11_VerifyRecover(SECKEYPublicKey *key, const SECItem *sig, SECStatus PK11_Verify(SECKEYPublicKey *key, const SECItem *sig, const SECItem *hash, void *wincx) +{ + CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType); + return PK11_VerifyWithMechanism(key, mech, NULL, sig, hash, wincx); +} + +/* + * Verify a signature from its hash using the given algorithm. + */ +SECStatus +PK11_VerifyWithMechanism(SECKEYPublicKey *key, CK_MECHANISM_TYPE mechanism, + const SECItem *param, const SECItem *sig, + const SECItem *hash, void *wincx) { PK11SlotInfo *slot = key->pkcs11Slot; CK_OBJECT_HANDLE id = key->pkcs11ID; @@ -673,7 +687,11 @@ PK11_Verify(SECKEYPublicKey *key, const SECItem *sig, const SECItem *hash, CK_SESSION_HANDLE session; CK_RV crv; - mech.mechanism = PK11_MapSignKeyType(key->keyType); + mech.mechanism = mechanism; + if (param) { + mech.pParameter = param->data; + mech.ulParameterLen = param->len; + } if (slot == NULL) { unsigned int length = 0; @@ -736,6 +754,17 @@ PK11_Verify(SECKEYPublicKey *key, const SECItem *sig, const SECItem *hash, */ SECStatus PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, const SECItem *hash) +{ + CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType); + return PK11_SignWithMechanism(key, mech, NULL, sig, hash); +} + +/* + * Sign a hash using the given algorithm. + */ +SECStatus +PK11_SignWithMechanism(SECKEYPrivateKey *key, CK_MECHANISM_TYPE mechanism, + const SECItem *param, SECItem *sig, const SECItem *hash) { PK11SlotInfo *slot = key->pkcs11Slot; CK_MECHANISM mech = {0, NULL, 0 }; @@ -745,7 +774,11 @@ PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, const SECItem *hash) CK_ULONG len; CK_RV crv; - mech.mechanism = PK11_MapSignKeyType(key->keyType); + mech.mechanism = mechanism; + if (param) { + mech.pParameter = param->data; + mech.ulParameterLen = param->len; + } if (SECKEY_HAS_ATTRIBUTE_SET(key,CKA_PRIVATE)) { PK11_HandlePasswordCheck(slot, key->wincx); diff --git a/security/nss/lib/pk11wrap/pk11pars.c b/security/nss/lib/pk11wrap/pk11pars.c index 40ac7908575a..5585de1df378 100644 --- a/security/nss/lib/pk11wrap/pk11pars.c +++ b/security/nss/lib/pk11wrap/pk11pars.c @@ -7,6 +7,7 @@ */ #include +#include #include "pkcs11.h" #include "seccomon.h" #include "secmod.h" @@ -14,8 +15,8 @@ #include "secmodti.h" #include "pki3hack.h" #include "secerr.h" - -#include "utilpars.h" +#include "nss.h" +#include "utilpars.h" /* create a new module */ static SECMODModule * @@ -137,6 +138,506 @@ SECMOD_CreateModule(const char *library, const char *moduleName, return SECMOD_CreateModuleEx(library, moduleName, parameters, nss, NULL); } +/* + * NSS config options format: + * + * The specified ciphers will be allowed by policy, but an application + * may allow more by policy explicitly: + * config="allow=curve1:curve2:hash1:hash2:rsa-1024..." + * + * Only the specified hashes and curves will be allowed: + * config="disallow=all allow=sha1:sha256:secp256r1:secp384r1" + * + * Only the specified hashes and curves will be allowed, and + * RSA keys of 2048 or more will be accepted, and DH key exchange + * with 1024-bit primes or more: + * config="disallow=all allow=sha1:sha256:secp256r1:secp384r1:min-rsa=2048:min-dh=1024" + * + * A policy that enables the AES ciphersuites and the SECP256/384 curves: + * config="allow=aes128-cbc:aes128-gcm:TLS1.0:TLS1.2:TLS1.1:HMAC-SHA1:SHA1:SHA256:SHA384:RSA:ECDHE-RSA:SECP256R1:SECP384R1" + * + * Disallow values are parsed first, then allow values, independent of the + * order they appear. + * + * Future key words (not yet implemented): + * enable: turn on ciphersuites by default. + * disable: turn off ciphersuites by default without disallowing them by policy. + * flags: turn on the following flags: + * ssl-lock: turn off the ability for applications to change policy with + * the SSL_SetCipherPolicy (or SSL_SetPolicy). + * policy-lock: turn off the ability for applications to change policy with + * the call NSS_SetAlgorithmPolicy. + * ssl-default-lock: turn off the ability for applications to change cipher + * suite states with SSL_EnableCipher, SSL_DisableCipher. + * + */ + +typedef struct { + const char *name; + unsigned name_size; + SECOidTag oid; + PRUint32 val; +} oidValDef; + +typedef struct { + const char *name; + unsigned name_size; + PRInt32 option; +} optionFreeDef; + +typedef struct { + const char *name; + unsigned name_size; + PRUint32 flag; +} policyFlagDef; + +/* + * This table should be merged with the SECOID table. + */ +#define CIPHER_NAME(x) x,(sizeof(x)-1) +static const oidValDef algOptList[] = { + /* Curves */ + {CIPHER_NAME("PRIME192V1"),SEC_OID_ANSIX962_EC_PRIME192V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("PRIME192V2"), SEC_OID_ANSIX962_EC_PRIME192V2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("PRIME192V3"), SEC_OID_ANSIX962_EC_PRIME192V3, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("PRIME239V1"), SEC_OID_ANSIX962_EC_PRIME239V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("PRIME239V2"), SEC_OID_ANSIX962_EC_PRIME239V2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("PRIME239V3"), SEC_OID_ANSIX962_EC_PRIME239V3, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("PRIME256V1"), SEC_OID_ANSIX962_EC_PRIME256V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP112R1"), SEC_OID_SECG_EC_SECP112R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP112R2"), SEC_OID_SECG_EC_SECP112R2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP128R1"), SEC_OID_SECG_EC_SECP128R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP128R2"), SEC_OID_SECG_EC_SECP128R2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP160K1"), SEC_OID_SECG_EC_SECP160K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP160R1"), SEC_OID_SECG_EC_SECP160R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP160R2"), SEC_OID_SECG_EC_SECP160R2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP192K1"), SEC_OID_SECG_EC_SECP192K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP192R1"), SEC_OID_ANSIX962_EC_PRIME192V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP224K1"), SEC_OID_SECG_EC_SECP224K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP256K1"), SEC_OID_SECG_EC_SECP256K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP256R1"), SEC_OID_ANSIX962_EC_PRIME256V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP384R1"), SEC_OID_SECG_EC_SECP384R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECP521R1"), SEC_OID_SECG_EC_SECP521R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + /* ANSI X9.62 named elliptic curves (characteristic two field) */ + {CIPHER_NAME("C2PNB163V1"), SEC_OID_ANSIX962_EC_C2PNB163V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2PNB163V2"), SEC_OID_ANSIX962_EC_C2PNB163V2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2PNB163V3"), SEC_OID_ANSIX962_EC_C2PNB163V3, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2PNB176V1"), SEC_OID_ANSIX962_EC_C2PNB176V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB191V1"), SEC_OID_ANSIX962_EC_C2TNB191V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB191V2"), SEC_OID_ANSIX962_EC_C2TNB191V2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB191V3"), SEC_OID_ANSIX962_EC_C2TNB191V3, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2ONB191V4"), SEC_OID_ANSIX962_EC_C2ONB191V4, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2ONB191V5"), SEC_OID_ANSIX962_EC_C2ONB191V5, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2PNB208W1"), SEC_OID_ANSIX962_EC_C2PNB208W1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB239V1"), SEC_OID_ANSIX962_EC_C2TNB239V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB239V2"), SEC_OID_ANSIX962_EC_C2TNB239V2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB239V3"), SEC_OID_ANSIX962_EC_C2TNB239V3, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2ONB239V4"), SEC_OID_ANSIX962_EC_C2ONB239V4, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2ONB239V5"), SEC_OID_ANSIX962_EC_C2ONB239V5, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2PNB272W1"), SEC_OID_ANSIX962_EC_C2PNB272W1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2PNB304W1"), SEC_OID_ANSIX962_EC_C2PNB304W1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB359V1"), SEC_OID_ANSIX962_EC_C2TNB359V1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2PNB368W1"), SEC_OID_ANSIX962_EC_C2PNB368W1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("C2TNB431R1"), SEC_OID_ANSIX962_EC_C2TNB431R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + /* SECG named elliptic curves (characteristic two field) */ + {CIPHER_NAME("SECT113R1"), SEC_OID_SECG_EC_SECT113R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT131R1"), SEC_OID_SECG_EC_SECT113R2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT131R1"), SEC_OID_SECG_EC_SECT131R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT131R2"), SEC_OID_SECG_EC_SECT131R2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT163K1"), SEC_OID_SECG_EC_SECT163K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT163R1"), SEC_OID_SECG_EC_SECT163R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT163R2"), SEC_OID_SECG_EC_SECT163R2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT193R1"), SEC_OID_SECG_EC_SECT193R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT193R2"), SEC_OID_SECG_EC_SECT193R2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT233K1"), SEC_OID_SECG_EC_SECT233K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT233R1"), SEC_OID_SECG_EC_SECT233R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT239K1"), SEC_OID_SECG_EC_SECT239K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT283K1"), SEC_OID_SECG_EC_SECT283K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT283R1"), SEC_OID_SECG_EC_SECT283R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT409K1"), SEC_OID_SECG_EC_SECT409K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT409R1"), SEC_OID_SECG_EC_SECT409R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT571K1"), SEC_OID_SECG_EC_SECT571K1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SECT571R1"), SEC_OID_SECG_EC_SECT571R1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + + /* Hashes */ + {CIPHER_NAME("MD2"), SEC_OID_MD2, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("MD4"), SEC_OID_MD4, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("MD5"), SEC_OID_MD5, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SHA1"), SEC_OID_SHA1, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SHA224"), SEC_OID_SHA224, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SHA256"), SEC_OID_SHA256, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SHA384"), SEC_OID_SHA384, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("SHA512"), SEC_OID_SHA512, + NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_CERT_SIGNATURE}, + + /* MACs */ + {CIPHER_NAME("HMAC-SHA1"), SEC_OID_HMAC_SHA1, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("HMAC-SHA224"), SEC_OID_HMAC_SHA224, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("HMAC-SHA256"), SEC_OID_HMAC_SHA256, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("HMAC-SHA384"), SEC_OID_HMAC_SHA384, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("HMAC-SHA512"), SEC_OID_HMAC_SHA512, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("HMAC-MD5"), SEC_OID_HMAC_MD5, NSS_USE_ALG_IN_SSL}, + + /* Ciphers */ + {CIPHER_NAME("AES128-CBC"), SEC_OID_AES_128_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("AES192-CBC"), SEC_OID_AES_192_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("AES256-CBC"), SEC_OID_AES_256_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("AES128-GCM"), SEC_OID_AES_128_GCM, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("AES192-GCM"), SEC_OID_AES_192_GCM, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("AES256-GCM"), SEC_OID_AES_256_GCM, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("CAMELLIA128-CBC"), SEC_OID_CAMELLIA_128_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("CAMELLIA192-CBC"), SEC_OID_CAMELLIA_192_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("CAMELLIA256-CBC"), SEC_OID_CAMELLIA_256_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("SEED-CBC"), SEC_OID_SEED_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("DES-EDE3-CBC"), SEC_OID_DES_EDE3_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("DES-40-CBC"), SEC_OID_DES_40_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("DES-CBC"), SEC_OID_DES_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("NULL-CIPHER"), SEC_OID_NULL_CIPHER, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("RC2"), SEC_OID_RC2_CBC, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("RC4"), SEC_OID_RC4, NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("IDEA"), SEC_OID_IDEA_CBC, NSS_USE_ALG_IN_SSL}, + + /* Key exchange */ + {CIPHER_NAME("RSA"), SEC_OID_TLS_RSA, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("RSA-EXPORT"), SEC_OID_TLS_RSA_EXPORT, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("DHE-RSA"), SEC_OID_TLS_DHE_RSA, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("DHE-DSS"), SEC_OID_TLS_DHE_DSS, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("DH-RSA"), SEC_OID_TLS_DH_RSA, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("DH-DSS"), SEC_OID_TLS_DH_DSS, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("ECDHE-ECDSA"), SEC_OID_TLS_ECDHE_ECDSA, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("ECDHE-RSA"), SEC_OID_TLS_ECDHE_RSA, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("ECDH-ECDSA"), SEC_OID_TLS_ECDH_ECDSA, NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("ECDH-RSA"), SEC_OID_TLS_ECDH_RSA, NSS_USE_ALG_IN_SSL_KX}, +}; + +static const optionFreeDef sslOptList[] = { + /* Versions */ + {CIPHER_NAME("SSL2.0"), 0x002}, + {CIPHER_NAME("SSL3.0"), 0x300}, + {CIPHER_NAME("SSL3.1"), 0x301}, + {CIPHER_NAME("TLS1.0"), 0x301}, + {CIPHER_NAME("TLS1.1"), 0x302}, + {CIPHER_NAME("TLS1.2"), 0x303}, + {CIPHER_NAME("TLS1.3"), 0x304}, + {CIPHER_NAME("DTLS1.0"),0x302}, + {CIPHER_NAME("DTLS1.1"),0x302}, + {CIPHER_NAME("DTLS1.2"),0x303}, + {CIPHER_NAME("DTLS1.3"),0x304}, +}; + +static const optionFreeDef freeOptList[] = { + + /* Restrictions for asymetric keys */ + {CIPHER_NAME("RSA-MIN"), NSS_RSA_MIN_KEY_SIZE}, + {CIPHER_NAME("DH-MIN"), NSS_DH_MIN_KEY_SIZE}, + {CIPHER_NAME("DSA-MIN"), NSS_DSA_MIN_KEY_SIZE}, + /* constraints on SSL Protocols */ + {CIPHER_NAME("TLS-VERSION-MIN"), NSS_TLS_VERSION_MIN_POLICY}, + {CIPHER_NAME("TLS-VERSION-MAX"), NSS_TLS_VERSION_MAX_POLICY}, + /* constraints on DTLS Protocols */ + {CIPHER_NAME("DTLS-VERSION-MIN"), NSS_DTLS_VERSION_MIN_POLICY}, + {CIPHER_NAME("DTLS-VERSION-MAX"), NSS_DTLS_VERSION_MIN_POLICY} +}; + +static const policyFlagDef policyFlagList[] = { + {CIPHER_NAME("SSL"), NSS_USE_ALG_IN_SSL}, + {CIPHER_NAME("SSL-KEY-EXCHANGE"), NSS_USE_ALG_IN_SSL_KX}, + /* add other key exhanges in the future */ + {CIPHER_NAME("KEY-EXCHANGE"), NSS_USE_ALG_IN_SSL_KX}, + {CIPHER_NAME("CERT-SIGNATURE"), NSS_USE_ALG_IN_CERT_SIGNATURE}, + /* add other signatures in the future */ + {CIPHER_NAME("SIGNATURE"), NSS_USE_ALG_IN_CERT_SIGNATURE}, + /* enable everything */ + {CIPHER_NAME("ALL"), NSS_USE_ALG_IN_SSL|NSS_USE_ALG_IN_SSL_KX| + NSS_USE_ALG_IN_CERT_SIGNATURE}, + {CIPHER_NAME("NONE"), 0} +}; + +/* + * Get the next cipher on the list. point to the next one in 'next'. + * return the length; + */ +static const char * +secmod_ArgGetSubValue(const char *cipher, char sep1, char sep2, + int *len, const char **next) +{ + const char *start = cipher; + + if (start == NULL) { + *len = 0; + *next = NULL; + return start; + } + + for (; *cipher && *cipher != sep2; cipher++) { + if (*cipher == sep1) { + *next = cipher+1; + *len = cipher - start; + return start; + } + } + *next = NULL; + *len = cipher-start; + return start; +} + +static PRUint32 +secmod_parsePolicyValue(const char *policyFlags, int policyLength) +{ + const char *flag, *currentString; + PRUint32 flags = 0; + int i; + + for (currentString = policyFlags; currentString + && currentString < policyFlags + policyLength; ) { + int length; + flag = secmod_ArgGetSubValue(currentString, ',', ':', &length, + ¤tString); + if (length == 0) { + continue; + } + for (i = 0; i < PR_ARRAY_SIZE(policyFlagList); i++) { + const policyFlagDef *policy = &policyFlagList[i]; + unsigned name_size = policy->name_size; + if ((policy->name_size == length) && + PORT_Strncasecmp(policy->name, flag, name_size) == 0) { + flags |= policy->flag; + break; + } + } + } + return flags; +} + + +/* allow symbolic names for values. The only ones currently defines or + * SSL protocol versions. */ +static PRInt32 +secmod_getPolicyOptValue(const char *policyValue, int policyValueLength) +{ + PRInt32 val = atoi(policyValue); + int i; + + + if ((val != 0) || (*policyValue == '0')) { + return val; + } + for (i = 0; i < PR_ARRAY_SIZE(sslOptList); i++) { + if (policyValueLength == sslOptList[i].name_size && + PORT_Strncasecmp(sslOptList[i].name, policyValue, + sslOptList[i].name_size) == 0 ) { + val = sslOptList[i].option; + break; + } + } + return val; +} + +static SECStatus secmod_applyCryptoPolicy(const char *policyString, + PRBool allow) +{ + const char *cipher, *currentString; + unsigned i; + SECStatus rv = SECSuccess; + PRBool unknown; + + + if (policyString == NULL || policyString[0] == 0) { + return SECSuccess; /* do nothing */ + } + + /* if we change any of these, make sure it gets applied in ssl as well */ + NSS_SetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, NSS_USE_POLICY_IN_SSL, 0); + + for (currentString = policyString; currentString; ) { + int length; + PRBool newValue = PR_FALSE; + + cipher = secmod_ArgGetSubValue(currentString, ':', 0, &length, + ¤tString); + unknown = PR_TRUE; + if (length >= 3 && cipher[3] == '/') { + newValue = PR_TRUE; + } + if ((newValue || (length == 3)) + && PORT_Strncasecmp(cipher, "all", 3) == 0) { + /* disable or enable all options by default */ + PRUint32 value = 0; + if (newValue) { + value = secmod_parsePolicyValue(&cipher[3]+1, length-3-1); + } + for (i = 0; i < PR_ARRAY_SIZE(algOptList); i++) { + PRUint32 enable, disable; + if (!newValue) { + value = algOptList[i].val; + } + if (allow) { + enable = value; + disable = 0; + } else { + enable = 0; + disable = value; + } + NSS_SetAlgorithmPolicy(algOptList[i].oid, enable, disable); + } + continue; + } + + for (i = 0; i < PR_ARRAY_SIZE(algOptList); i++) { + const oidValDef *algOpt = &algOptList[i]; + unsigned name_size = algOpt->name_size; + PRBool newValue = PR_FALSE; + + if ((length >= name_size) && (cipher[name_size] == '/')) { + newValue = PR_TRUE; + } + if ( (newValue || algOpt->name_size == length) && + PORT_Strncasecmp(algOpt->name, cipher, name_size) == 0) { + PRUint32 value = algOpt->val; + PRUint32 enable, disable; + if (newValue) { + value = secmod_parsePolicyValue(&cipher[name_size]+1, + length-name_size-1); + } + if (allow) { + enable = value; + disable = 0; + } else { + enable = 0; + disable = value; + } + rv = NSS_SetAlgorithmPolicy(algOpt->oid, enable, disable); + if (rv != SECSuccess) { + /* could not enable option */ + /* NSS_SetAlgorithPolicy should have set the error code */ + return SECFailure; + } + unknown = PR_FALSE; + break; + } + } + if (!unknown) { + continue; + } + + for (i = 0; i < PR_ARRAY_SIZE(freeOptList); i++) { + const optionFreeDef *freeOpt = &freeOptList[i]; + unsigned name_size = freeOpt->name_size; + + if ((length > name_size) && cipher[name_size] == '=' && + PORT_Strncasecmp(freeOpt->name, cipher, name_size) == 0 ) { + PRInt32 val = secmod_getPolicyOptValue( &cipher[name_size+1], + length-name_size-1); + + rv = NSS_OptionSet(freeOpt->option, val); + if (rv != SECSuccess) { + /* could not enable option */ + /* NSS_OptionSet should have set the error code */ + return SECFailure; + } + /* to allow the policy to expand in the future. ignore ciphers + * we don't understand */ + unknown = PR_FALSE; + break; + } + } + } + return rv; +} + +static SECStatus +secmod_parseCryptoPolicy(const char *policyConfig) +{ + char *disallow, *allow; + SECStatus rv; + + if (policyConfig == NULL) { + return SECSuccess; /* no policy given */ + } + /* make sure we initialize the oid table and set all the default policy + * values first so we can override them here */ + rv = SECOID_Init(); + if (rv != SECSuccess) { + return rv; + } + disallow = NSSUTIL_ArgGetParamValue("disallow",policyConfig); + rv = secmod_applyCryptoPolicy(disallow, PR_FALSE); + if (disallow) PORT_Free(disallow); + if (rv != SECSuccess) { + return rv; + } + allow = NSSUTIL_ArgGetParamValue("allow",policyConfig); + rv = secmod_applyCryptoPolicy(allow, PR_TRUE); + if (allow) PORT_Free(allow); + return rv; +} + /* * for 3.4 we continue to use the old SECMODModule structure */ @@ -145,10 +646,20 @@ SECMOD_CreateModuleEx(const char *library, const char *moduleName, const char *parameters, const char *nss, const char *config) { - SECMODModule *mod = secmod_NewModule(); + SECMODModule *mod; + SECStatus rv; char *slotParams,*ciphers; /* pk11pars.h still does not have const char * interfaces */ char *nssc = (char *)nss; + + rv = secmod_parseCryptoPolicy(config); + + /* do not load the module if policy parsing fails */ + if (rv != SECSuccess) { + return NULL; + } + + mod = secmod_NewModule(); if (mod == NULL) return NULL; mod->commonName = PORT_ArenaStrdup(mod->arena,moduleName ? moduleName : ""); @@ -159,9 +670,7 @@ SECMOD_CreateModuleEx(const char *library, const char *moduleName, if (parameters) { mod->libraryParams = PORT_ArenaStrdup(mod->arena,parameters); } - if (config) { - /* XXX: Apply configuration */ - } + mod->internal = NSSUTIL_ArgHasFlag("flags","internal",nssc); mod->isFIPS = NSSUTIL_ArgHasFlag("flags","FIPS",nssc); mod->isCritical = NSSUTIL_ArgHasFlag("flags","critical",nssc); @@ -316,18 +825,18 @@ secmod_doDescCopy(char *target, int *targetLen, const char *desc, * spec. */ char * -secmod_ParseModuleSpecForTokens(PRBool convert, PRBool isFIPS, - char *moduleSpec, char ***children, +secmod_ParseModuleSpecForTokens(PRBool convert, PRBool isFIPS, + const char *moduleSpec, char ***children, CK_SLOT_ID **ids) { int newSpecLen = PORT_Strlen(moduleSpec)+2; char *newSpec = PORT_Alloc(newSpecLen); char *newSpecPtr = newSpec; - char *modulePrev = moduleSpec; + const char *modulePrev = moduleSpec; char *target = NULL; char *tmp = NULL; char **childArray = NULL; - char *tokenIndex; + const char *tokenIndex; CK_SLOT_ID *idArray = NULL; int tokenCount = 0; int i; @@ -487,7 +996,7 @@ secmod_ParseModuleSpecForTokens(PRBool convert, PRBool isFIPS, /* get the database and flags from the spec */ static char * -secmod_getConfigDir(char *spec, char **certPrefix, char **keyPrefix, +secmod_getConfigDir(const char *spec, char **certPrefix, char **keyPrefix, PRBool *readOnly) { char * config = NULL; diff --git a/security/nss/lib/pk11wrap/pk11pbe.c b/security/nss/lib/pk11wrap/pk11pbe.c index cc72faf608b1..35205bbfffdd 100644 --- a/security/nss/lib/pk11wrap/pk11pbe.c +++ b/security/nss/lib/pk11wrap/pk11pbe.c @@ -636,7 +636,7 @@ sec_pkcs5CreateAlgorithmID(SECOidTag algorithm, goto loser; } } - /* currently only SEC_OID_HMAC_SHA1 is defined */ + /* currently SEC_OID_HMAC_SHA1 is the default */ if (prfAlg == SEC_OID_UNKNOWN) { prfAlg = SEC_OID_HMAC_SHA1; } @@ -805,13 +805,26 @@ pbe_PK11AlgidToParam(SECAlgorithmID *algid,SECItem *mech) p5_param.pPrfAlgId->algorithm.data != 0) { prfAlgTag = SECOID_GetAlgorithmTag(p5_param.pPrfAlgId); } - if (prfAlgTag == SEC_OID_HMAC_SHA1) { - pbeV2_params->prf = CKP_PKCS5_PBKD2_HMAC_SHA1; - } else { - /* only SHA1_HMAC is currently supported by PKCS #11 */ - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - goto loser; - } + switch (prfAlgTag) { + case SEC_OID_HMAC_SHA1: + pbeV2_params->prf = CKP_PKCS5_PBKD2_HMAC_SHA1; + break; + case SEC_OID_HMAC_SHA224: + pbeV2_params->prf = CKP_PKCS5_PBKD2_HMAC_SHA224; + break; + case SEC_OID_HMAC_SHA256: + pbeV2_params->prf = CKP_PKCS5_PBKD2_HMAC_SHA256; + break; + case SEC_OID_HMAC_SHA384: + pbeV2_params->prf = CKP_PKCS5_PBKD2_HMAC_SHA384; + break; + case SEC_OID_HMAC_SHA512: + pbeV2_params->prf = CKP_PKCS5_PBKD2_HMAC_SHA512; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + goto loser; + } /* probably should fetch these from the prfAlgid */ pbeV2_params->pPrfData = NULL; diff --git a/security/nss/lib/pk11wrap/pk11pub.h b/security/nss/lib/pk11wrap/pk11pub.h index d4565eb4e005..c130e1e143be 100644 --- a/security/nss/lib/pk11wrap/pk11pub.h +++ b/security/nss/lib/pk11wrap/pk11pub.h @@ -709,12 +709,20 @@ int PK11_SignatureLen(SECKEYPrivateKey *key); PK11SlotInfo * PK11_GetSlotFromPrivateKey(SECKEYPrivateKey *key); SECStatus PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, const SECItem *hash); +SECStatus PK11_SignWithMechanism(SECKEYPrivateKey *key, + CK_MECHANISM_TYPE mechanism, + const SECItem *param, SECItem *sig, + const SECItem *hash); SECStatus PK11_SignWithSymKey(PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism, SECItem *param, SECItem *sig, const SECItem *data); SECStatus PK11_VerifyRecover(SECKEYPublicKey *key, const SECItem *sig, SECItem *dsig, void * wincx); SECStatus PK11_Verify(SECKEYPublicKey *key, const SECItem *sig, const SECItem *hash, void *wincx); +SECStatus PK11_VerifyWithMechanism(SECKEYPublicKey *key, + CK_MECHANISM_TYPE mechanism, + const SECItem *param, const SECItem *sig, + const SECItem *hash, void *wincx); diff --git a/security/nss/lib/pk11wrap/pk11util.c b/security/nss/lib/pk11wrap/pk11util.c index 4a384ad5bc2a..88f7e004017e 100644 --- a/security/nss/lib/pk11wrap/pk11util.c +++ b/security/nss/lib/pk11wrap/pk11util.c @@ -640,6 +640,11 @@ SECMOD_AddNewModuleEx(const char* moduleName, const char* dllPath, PR_TRUE: PR_FALSE; result = PK11_UpdateSlotAttribute(slot, &(PK11_DefaultArray[i]), add); + if (result != SECSuccess) { + SECMOD_ReleaseReadLock(moduleLock); + SECMOD_DestroyModule(module); + return result; + } } /* for each mechanism */ /* disable each slot if the defaultFlags say so */ if (defaultMechanismFlags & PK11_DISABLE_FLAG) { diff --git a/security/nss/lib/pk11wrap/secmodi.h b/security/nss/lib/pk11wrap/secmodi.h index 830fb67b5a9c..5bc49b43893e 100644 --- a/security/nss/lib/pk11wrap/secmodi.h +++ b/security/nss/lib/pk11wrap/secmodi.h @@ -76,8 +76,8 @@ void secmod_FreeConfigList(SECMODConfigList *conflist, int count); * secmod_FreeChildren */ char *secmod_ParseModuleSpecForTokens(PRBool convert, PRBool isFIPS, - char *moduleSpec, - char ***children, + const char *moduleSpec, + char ***children, CK_SLOT_ID **ids); void secmod_FreeChildren(char **children, CK_SLOT_ID *ids); char *secmod_MkAppendTokensList(PLArenaPool *arena, char *origModuleSpec, diff --git a/security/nss/lib/pkcs7/secmime.c b/security/nss/lib/pkcs7/secmime.c index 12a1e20019e7..8b369bf1e44c 100644 --- a/security/nss/lib/pkcs7/secmime.c +++ b/security/nss/lib/pkcs7/secmime.c @@ -305,10 +305,10 @@ static const SEC_ASN1Template smime_capability_template[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(smime_capability) }, { SEC_ASN1_OBJECT_ID, - offsetof(smime_capability,capabilityID), }, + offsetof(smime_capability,capabilityID) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, - offsetof(smime_capability,parameters), }, - { 0, } + offsetof(smime_capability,parameters) }, + { 0 } }; static const SEC_ASN1Template smime_capabilities_template[] = { diff --git a/security/nss/lib/pki/certificate.c b/security/nss/lib/pki/certificate.c index fdf147c9e3dd..b5d986abe16d 100644 --- a/security/nss/lib/pki/certificate.c +++ b/security/nss/lib/pki/certificate.c @@ -1122,6 +1122,9 @@ nssCRL_Create ( &rvCRL->url, &rvCRL->isKRL); if (status != PR_SUCCESS) { + if (!arena) { + nssPKIObject_Destroy((nssPKIObject *)rvCRL); + } return (NSSCRL *)NULL; } return rvCRL; diff --git a/security/nss/lib/pki/pki3hack.c b/security/nss/lib/pki/pki3hack.c index b14509285877..4186143e5f66 100644 --- a/security/nss/lib/pki/pki3hack.c +++ b/security/nss/lib/pki/pki3hack.c @@ -830,8 +830,10 @@ fill_CERTCertificateFields(NSSCertificate *c, CERTCertificate *cc, PRBool forced cc->trust = trust; CERT_UnlockCertTrust(cc); } - nssCryptokiObject_Destroy(instance); } + if (instance) { + nssCryptokiObject_Destroy(instance); + } /* database handle is now the trust domain */ cc->dbhandle = c->object.trustDomain; /* subjectList ? */ diff --git a/security/nss/lib/smime/cmscipher.c b/security/nss/lib/smime/cmscipher.c index 998ad16a760f..44ba4840dda5 100644 --- a/security/nss/lib/smime/cmscipher.c +++ b/security/nss/lib/smime/cmscipher.c @@ -693,8 +693,12 @@ NSS_CMSCipherContext_Encrypt(NSSCMSCipherContext *cc, unsigned char *output, } if (final) { - padlen = padsize - (pcount % padsize); - PORT_Memset (pbuf + pcount, padlen, padlen); + if (padsize <= 0) { + padlen = 0; + } else { + padlen = padsize - (pcount % padsize); + PORT_Memset (pbuf + pcount, padlen, padlen); + } rv = (* cc->doit) (cc->cx, output, &ofraglen, max_output_len, pbuf, pcount+padlen); if (rv != SECSuccess) diff --git a/security/nss/lib/smime/smimeutil.c b/security/nss/lib/smime/smimeutil.c index 84d1960a0cfe..a722586d6881 100644 --- a/security/nss/lib/smime/smimeutil.c +++ b/security/nss/lib/smime/smimeutil.c @@ -47,10 +47,10 @@ static const SEC_ASN1Template NSSSMIMECapabilityTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSSMIMECapability) }, { SEC_ASN1_OBJECT_ID, - offsetof(NSSSMIMECapability,capabilityID), }, + offsetof(NSSSMIMECapability,capabilityID) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, - offsetof(NSSSMIMECapability,parameters), }, - { 0, } + offsetof(NSSSMIMECapability,parameters) }, + { 0 } }; static const SEC_ASN1Template NSSSMIMECapabilitiesTemplate[] = { @@ -97,7 +97,7 @@ static const SEC_ASN1Template smime_encryptionkeypref_template[] = { offsetof(NSSSMIMEEncryptionKeyPreference,id.subjectKeyID), SEC_ASN1_SUB(SEC_OctetStringTemplate), NSSSMIMEEncryptionKeyPref_SubjectKeyID }, - { 0, } + { 0 } }; /* smime_cipher_map - map of SMIME symmetric "ciphers" to algtag & parameters */ diff --git a/security/nss/lib/softoken/fipstest.c b/security/nss/lib/softoken/fipstest.c index aed33bb0a8c3..c3b0d616870f 100644 --- a/security/nss/lib/softoken/fipstest.c +++ b/security/nss/lib/softoken/fipstest.c @@ -1512,8 +1512,8 @@ sftk_fips_RSA_PowerUpSelfTest( void ) NSSLOWKEYPrivateKey * rsa_private_key; SECStatus rsa_status; - NSSLOWKEYPublicKey low_public_key = { NULL, NSSLOWKEYRSAKey, }; - NSSLOWKEYPrivateKey low_private_key = { NULL, NSSLOWKEYRSAKey, }; + 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]; diff --git a/security/nss/lib/softoken/legacydb/lowcert.c b/security/nss/lib/softoken/legacydb/lowcert.c index a8191d87a186..f3939229299a 100644 --- a/security/nss/lib/softoken/legacydb/lowcert.c +++ b/security/nss/lib/softoken/legacydb/lowcert.c @@ -23,23 +23,23 @@ static const SEC_ASN1Template nsslowcert_SubjectPublicKeyInfoTemplate[] = { offsetof(NSSLOWCERTSubjectPublicKeyInfo,algorithm), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_BIT_STRING, - offsetof(NSSLOWCERTSubjectPublicKeyInfo,subjectPublicKey), }, - { 0, } + offsetof(NSSLOWCERTSubjectPublicKeyInfo,subjectPublicKey) }, + { 0 } }; static const SEC_ASN1Template nsslowcert_RSAPublicKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPublicKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.modulus), }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.publicExponent), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.modulus) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.publicExponent) }, + { 0 } }; static const SEC_ASN1Template nsslowcert_DSAPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dsa.publicValue), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dsa.publicValue) }, + { 0 } }; static const SEC_ASN1Template nsslowcert_DHPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dh.publicValue), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dh.publicValue) }, + { 0 } }; /* diff --git a/security/nss/lib/softoken/legacydb/lowkey.c b/security/nss/lib/softoken/legacydb/lowkey.c index 7521dac81c9e..8a3ff4a5f795 100644 --- a/security/nss/lib/softoken/legacydb/lowkey.c +++ b/security/nss/lib/softoken/legacydb/lowkey.c @@ -47,7 +47,7 @@ const SEC_ASN1Template lg_nsslowkey_PQGParamsTemplate[] = { { SEC_ASN1_INTEGER, offsetof(PQGParams,prime) }, { SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) }, { SEC_ASN1_INTEGER, offsetof(PQGParams,base) }, - { 0, } + { 0 } }; const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate[] = { @@ -87,7 +87,7 @@ const SEC_ASN1Template lg_nsslowkey_DSAPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.publicValue) }, { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.privateValue) }, - { 0, } + { 0 } }; const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyTemplate[] = { @@ -96,7 +96,7 @@ const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyTemplate[] = { { 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, } + { 0 } }; #ifndef NSS_DISABLE_ECC @@ -110,7 +110,7 @@ const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyTemplate[] = { const SEC_ASN1Template lg_nsslowkey_ECParamsTemplate[] = { { SEC_ASN1_CHOICE, offsetof(ECParams,type), NULL, sizeof(ECParams) }, { SEC_ASN1_OBJECT_ID, offsetof(ECParams,curveOID), NULL, ec_params_named }, - { 0, } + { 0 } }; @@ -145,7 +145,7 @@ const SEC_ASN1Template lg_nsslowkey_ECPrivateKeyTemplate[] = { SEC_ASN1_XTRN | 1, offsetof(NSSLOWKEYPrivateKey,u.ec.publicValue), SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { 0, } + { 0 } }; diff --git a/security/nss/lib/softoken/legacydb/pcertdb.c b/security/nss/lib/softoken/legacydb/pcertdb.c index 418de0b83456..7ad86e30db9d 100644 --- a/security/nss/lib/softoken/legacydb/pcertdb.c +++ b/security/nss/lib/softoken/legacydb/pcertdb.c @@ -3651,11 +3651,17 @@ UpdateV6DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) PORT_Free(tmpbuf); tmpbuf = NULL; } + if (ret) { + return SECFailure; + } } } } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); ret = certdb_Sync(handle->permCertDB, 0); + if (ret) { + return SECFailure; + } ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); if ( ret ) { @@ -3742,6 +3748,9 @@ endloop: } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); ret = certdb_Sync(handle->permCertDB, 0); + if (ret) { + return SECFailure; + } (* updatedb->close)(updatedb); return(SECSuccess); diff --git a/security/nss/lib/softoken/lowkey.c b/security/nss/lib/softoken/lowkey.c index d0433421020f..b50ee1ffe556 100644 --- a/security/nss/lib/softoken/lowkey.c +++ b/security/nss/lib/softoken/lowkey.c @@ -53,7 +53,7 @@ const SEC_ASN1Template nsslowkey_PQGParamsTemplate[] = { { SEC_ASN1_INTEGER, offsetof(PQGParams,prime) }, { SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) }, { SEC_ASN1_INTEGER, offsetof(PQGParams,base) }, - { 0, } + { 0 } }; const SEC_ASN1Template nsslowkey_RSAPrivateKeyTemplate[] = { @@ -75,7 +75,7 @@ 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, } + { 0 } }; const SEC_ASN1Template nsslowkey_DSAPrivateKeyExportTemplate[] = { @@ -88,7 +88,7 @@ const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[] = { { 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, } + { 0 } }; #ifndef NSS_DISABLE_ECC @@ -102,7 +102,7 @@ const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[] = { 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, } + { 0 } }; @@ -138,7 +138,7 @@ const SEC_ASN1Template nsslowkey_ECPrivateKeyTemplate[] = { SEC_ASN1_XTRN | 1, offsetof(NSSLOWKEYPrivateKey,u.ec.publicValue), SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { 0, } + { 0 } }; #endif /* NSS_DISABLE_ECC */ /* diff --git a/security/nss/lib/softoken/lowpbe.c b/security/nss/lib/softoken/lowpbe.c index 16d4c91416e4..8e178b48ff02 100644 --- a/security/nss/lib/softoken/lowpbe.c +++ b/security/nss/lib/softoken/lowpbe.c @@ -53,9 +53,7 @@ struct nsspkcs5V2PBEParameterStr { }; typedef struct nsspkcs5V2PBEParameterStr nsspkcs5V2PBEParameter; -#define PBKDF2 -#ifdef PBKDF2 static const SEC_ASN1Template NSSPKCS5V2PBES2ParameterTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(nsspkcs5V2PBEParameter) }, @@ -81,7 +79,6 @@ static const SEC_ASN1Template NSSPKCS5V2PBEParameterTemplate[] = SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { 0 } }; -#endif SECStatus nsspkcs5_HashBuf(const SECHashObject *hashObj, unsigned char *dest, @@ -301,8 +298,6 @@ nsspkcs5_PBKDF1Extended(const SECHashObject *hashObj, return newHash; } -#ifdef PBKDF2 - /* * PBDKDF2 is PKCS #5 v2.0 it's currently not used by NSS */ @@ -413,7 +408,6 @@ loser: return result; } -#endif #define HMAC_BUFFER 64 #define NSSPBE_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y)) @@ -600,14 +594,12 @@ nsspkcs5_ComputeKeyAndIV(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, } break; -#ifdef PBKDF2 case NSSPKCS5_PBKDF2: hash = nsspkcs5_PBKDF2(hashObj,pbe_param,pwitem); if (getIV) { PORT_Memcpy(iv->data, pbe_param->ivData, iv->len); } break; -#endif case NSSPKCS5_PKCS12_V2: if (getIV) { hash = nsspkcs5_PKCS12PBE(hashObj,pbe_param,pwitem, @@ -651,13 +643,14 @@ loser: } static SECStatus -nsspkcs5_FillInParam(SECOidTag algorithm, NSSPKCS5PBEParameter *pbe_param) +nsspkcs5_FillInParam(SECOidTag algorithm, HASH_HashType hashType, + NSSPKCS5PBEParameter *pbe_param) { PRBool skipType = PR_FALSE; pbe_param->keyLen = 5; pbe_param->ivLen = 8; - pbe_param->hashType = HASH_AlgSHA1; + pbe_param->hashType = hashType; pbe_param->pbeType = NSSPKCS5_PBKDF1; pbe_param->encAlg = SEC_OID_RC2_CBC; pbe_param->is2KeyDES = PR_FALSE; @@ -717,7 +710,6 @@ finish_des: pbe_param->encAlg = SEC_OID_RC4; break; -#ifdef PBKDF2 case SEC_OID_PKCS5_PBKDF2: case SEC_OID_PKCS5_PBES2: case SEC_OID_PKCS5_PBMAC1: @@ -727,7 +719,6 @@ finish_des: pbe_param->encAlg = SEC_OID_PKCS5_PBKDF2; pbe_param->keyLen = 0; /* needs to be set by caller after return */ break; -#endif default: return SECFailure; @@ -739,7 +730,8 @@ finish_des: /* decode the algid and generate a PKCS 5 parameter from it */ NSSPKCS5PBEParameter * -nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator) +nsspkcs5_NewParam(SECOidTag alg, HASH_HashType hashType, SECItem *salt, + int iterationCount) { PLArenaPool *arena = NULL; NSSPKCS5PBEParameter *pbe_param = NULL; @@ -759,12 +751,12 @@ nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator) pbe_param->poolp = arena; - rv = nsspkcs5_FillInParam(alg, pbe_param); + rv = nsspkcs5_FillInParam(alg, hashType, pbe_param); if (rv != SECSuccess) { goto loser; } - pbe_param->iter = iterator; + pbe_param->iter = iterationCount; if (salt) { rv = SECITEM_CopyItem(arena,&pbe_param->salt,salt); } @@ -823,7 +815,7 @@ nsspkcs5_AlgidToParam(SECAlgorithmID *algid) goto loser; } - pbe_param = nsspkcs5_NewParam(algorithm, NULL, 1); + pbe_param = nsspkcs5_NewParam(algorithm, HASH_AlgSHA1, NULL, 1); if (pbe_param == NULL) { goto loser; } @@ -839,7 +831,6 @@ nsspkcs5_AlgidToParam(SECAlgorithmID *algid) rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, NSSPKCS5PKCS12V2PBEParameterTemplate, &algid->parameters); break; -#ifdef PBKDF2 case NSSPKCS5_PBKDF2: PORT_Memset(&pbev2_param,0, sizeof(pbev2_param)); /* just the PBE */ @@ -874,7 +865,6 @@ nsspkcs5_AlgidToParam(SECAlgorithmID *algid) rv = SECFailure; } break; -#endif } loser: @@ -1316,7 +1306,6 @@ nsspkcs5_CreateAlgorithmID(PLArenaPool *arena, SECOidTag algorithm, dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, NSSPKCS5PKCS12V2PBEParameterTemplate); break; -#ifdef PBKDF2 case NSSPKCS5_PBKDF2: if (pbe_param->keyLength.data == NULL) { dummy = SEC_ASN1EncodeInteger(pbe_param->poolp, @@ -1347,7 +1336,6 @@ nsspkcs5_CreateAlgorithmID(PLArenaPool *arena, SECOidTag algorithm, dummy = SEC_ASN1EncodeItem(arena, &der_param, &pkcs5v2_param, NSSPKCS5V2PBES2ParameterTemplate); break; -#endif default: break; } diff --git a/security/nss/lib/softoken/lowpbe.h b/security/nss/lib/softoken/lowpbe.h index 00c1007f552a..3bf04f4392f4 100644 --- a/security/nss/lib/softoken/lowpbe.h +++ b/security/nss/lib/softoken/lowpbe.h @@ -77,7 +77,8 @@ nsspkcs5_AlgidToParam(SECAlgorithmID *algid); * keyDB which only support PKCS 5 v1, PFX, and PKCS 12. */ NSSPKCS5PBEParameter * -nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator); +nsspkcs5_NewParam(SECOidTag alg, HASH_HashType hashType, SECItem *salt, + int iterationCount); /* Encrypt/Decrypt data using password based encryption. diff --git a/security/nss/lib/softoken/pkcs11c.c b/security/nss/lib/softoken/pkcs11c.c index 8755f24c3abb..3c96849f9797 100644 --- a/security/nss/lib/softoken/pkcs11c.c +++ b/security/nss/lib/softoken/pkcs11c.c @@ -2096,10 +2096,10 @@ static DERTemplate SECAlgorithmIDTemplate[] = { { DER_SEQUENCE, 0, NULL, sizeof(SECAlgorithmID) }, { DER_OBJECT_ID, - offsetof(SECAlgorithmID,algorithm), }, + offsetof(SECAlgorithmID,algorithm) }, { DER_OPTIONAL | DER_ANY, - offsetof(SECAlgorithmID,parameters), }, - { 0, } + offsetof(SECAlgorithmID,parameters) }, + { 0 } }; /* @@ -2111,10 +2111,10 @@ static DERTemplate SGNDigestInfoTemplate[] = { 0, NULL, sizeof(SGNDigestInfo) }, { DER_INLINE, offsetof(SGNDigestInfo,digestAlgorithm), - SECAlgorithmIDTemplate, }, + SECAlgorithmIDTemplate }, { DER_OCTET_STRING, - offsetof(SGNDigestInfo,digest), }, - { 0, } + offsetof(SGNDigestInfo,digest) }, + { 0 } }; /* @@ -3735,6 +3735,7 @@ nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, SECOidData *oid; CK_PBE_PARAMS *pbe_params = NULL; NSSPKCS5PBEParameter *params = NULL; + HASH_HashType hashType = HASH_AlgSHA1; CK_PKCS5_PBKD2_PARAMS *pbkd2_params = NULL; SECItem salt; CK_ULONG iteration = 0; @@ -3748,6 +3749,28 @@ nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, if (pMechanism->mechanism == CKM_PKCS5_PBKD2) { pbkd2_params = (CK_PKCS5_PBKD2_PARAMS *)pMechanism->pParameter; + if (pbkd2_params == NULL) { + return CKR_MECHANISM_PARAM_INVALID; + } + switch (pbkd2_params->prf) { + case CKP_PKCS5_PBKD2_HMAC_SHA1: + hashType = HASH_AlgSHA1; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA224: + hashType = HASH_AlgSHA224; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA256: + hashType = HASH_AlgSHA256; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA384: + hashType = HASH_AlgSHA384; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA512: + hashType = HASH_AlgSHA512; + break; + default: + return CKR_MECHANISM_PARAM_INVALID; + } if (pbkd2_params->saltSource != CKZ_SALT_SPECIFIED) { return CKR_MECHANISM_PARAM_INVALID; } @@ -3760,7 +3783,7 @@ nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, salt.len = (unsigned int)pbe_params->ulSaltLen; iteration = pbe_params->ulIteration; } - params=nsspkcs5_NewParam(oid->offset, &salt, iteration); + params=nsspkcs5_NewParam(oid->offset, hashType, &salt, iteration); if (params == NULL) { return CKR_MECHANISM_INVALID; } @@ -3783,14 +3806,6 @@ nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, *key_length = params->keyLen; break; case SEC_OID_PKCS5_PBKDF2: - /* sigh, PKCS #11 currently only defines SHA1 for the KDF hash type. - * we do the check here because this where we would handle multiple - * hash types in the future */ - if (pbkd2_params == NULL || - pbkd2_params->prf != CKP_PKCS5_PBKD2_HMAC_SHA1) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } /* key type must already be set */ if (*key_type == CKK_INVALID_KEY_TYPE) { crv = CKR_TEMPLATE_INCOMPLETE; diff --git a/security/nss/lib/softoken/sftkpars.c b/security/nss/lib/softoken/sftkpars.c index 465cbcecc594..da4f9e187f50 100644 --- a/security/nss/lib/softoken/sftkpars.c +++ b/security/nss/lib/softoken/sftkpars.c @@ -42,7 +42,7 @@ sftk_parseTokenParameters(char *param, sftk_token_parameters *parsed) { int next; char *tmp = NULL; - char *index; + const char *index; index = NSSUTIL_ArgStrip(param); while (*index) { @@ -72,7 +72,7 @@ sftk_parseTokenParameters(char *param, sftk_token_parameters *parsed) static void sftk_parseTokens(char *tokenParams, sftk_parameters *parsed) { - char *tokenIndex; + const char *tokenIndex; sftk_token_parameters *tokens = NULL; int i=0,count = 0,next; @@ -120,7 +120,7 @@ sftk_parseParameters(char *param, sftk_parameters *parsed, PRBool isFIPS) { int next; char *tmp = NULL; - char *index; + const char *index; char *certPrefix = NULL, *keyPrefix = NULL; char *tokdes = NULL, *ptokdes = NULL, *pupdtokdes = NULL; char *slotdes = NULL, *pslotdes = NULL; diff --git a/security/nss/lib/softoken/sftkpwd.c b/security/nss/lib/softoken/sftkpwd.c index d8ce857757d6..f17da7e00f50 100644 --- a/security/nss/lib/softoken/sftkpwd.c +++ b/security/nss/lib/softoken/sftkpwd.c @@ -277,7 +277,8 @@ sftkdb_EncryptAttribute(PLArenaPool *arena, SECItem *passKey, cipherValue.salt.data = saltData; RNG_GenerateGlobalRandomBytes(saltData,cipherValue.salt.len); - param = nsspkcs5_NewParam(cipherValue.alg, &cipherValue.salt, 1); + param = nsspkcs5_NewParam(cipherValue.alg, HASH_AlgSHA1, &cipherValue.salt, + 1); if (param == NULL) { rv = SECFailure; goto loser; @@ -449,7 +450,7 @@ sftkdb_SignAttribute(PLArenaPool *arena, SECItem *passKey, RNG_GenerateGlobalRandomBytes(saltData,prfLength); /* initialize our pkcs5 parameter */ - param = nsspkcs5_NewParam(signValue.alg, &signValue.salt, 1); + param = nsspkcs5_NewParam(signValue.alg, HASH_AlgSHA1, &signValue.salt, 1); if (param == NULL) { rv = SECFailure; goto loser; diff --git a/security/nss/lib/softoken/softkver.h b/security/nss/lib/softoken/softkver.h index c7e25e1beac7..9838e3b2e4bd 100644 --- a/security/nss/lib/softoken/softkver.h +++ b/security/nss/lib/softoken/softkver.h @@ -25,11 +25,11 @@ * The format of the version string should be * ".[.[.]][ ][ ]" */ -#define SOFTOKEN_VERSION "3.21" SOFTOKEN_ECC_STRING +#define SOFTOKEN_VERSION "3.22" SOFTOKEN_ECC_STRING " Beta" #define SOFTOKEN_VMAJOR 3 -#define SOFTOKEN_VMINOR 21 +#define SOFTOKEN_VMINOR 22 #define SOFTOKEN_VPATCH 0 #define SOFTOKEN_VBUILD 0 -#define SOFTOKEN_BETA PR_FALSE +#define SOFTOKEN_BETA PR_TRUE #endif /* _SOFTKVER_H_ */ diff --git a/security/nss/lib/ssl/dtlscon.c b/security/nss/lib/ssl/dtlscon.c index 1b21107094e8..940831e6de9c 100644 --- a/security/nss/lib/ssl/dtlscon.c +++ b/security/nss/lib/ssl/dtlscon.c @@ -1023,7 +1023,7 @@ alert_loser: (void)SSL3_SendAlert(ss, alert_fatal, desc); loser: - errCode = ssl_MapLowLevelError(errCode); + ssl_MapLowLevelError(errCode); return SECFailure; } diff --git a/security/nss/lib/ssl/ssl.def b/security/nss/lib/ssl/ssl.def index 44db4e5ee3c9..2c1d009950a1 100644 --- a/security/nss/lib/ssl/ssl.def +++ b/security/nss/lib/ssl/ssl.def @@ -187,3 +187,10 @@ SSL_SignatureMaxCount; ;+ local: ;+*; ;+}; +;+NSS_3.22 { # NSS 3.22 release +;+ global: +SSL_PeerSignedCertTimestamps; +SSL_SetSignedCertTimestamps; +;+ local: +;+*; +;+}; diff --git a/security/nss/lib/ssl/ssl.h b/security/nss/lib/ssl/ssl.h index 2a527693b19d..a301d0113dc0 100644 --- a/security/nss/lib/ssl/ssl.h +++ b/security/nss/lib/ssl/ssl.h @@ -203,6 +203,8 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd); */ #define SSL_ENABLE_EXTENDED_MASTER_SECRET 30 +/* Request Signed Certificate Timestamps via TLS extension (client) */ +#define SSL_ENABLE_SIGNED_CERT_TIMESTAMPS 31 #ifdef SSL_DEPRECATED_FUNCTION /* Old deprecated function names */ @@ -560,6 +562,23 @@ SSL_IMPORT CERTCertList *SSL_PeerCertificateChain(PRFileDesc *fd); */ SSL_IMPORT const SECItemArray * SSL_PeerStapledOCSPResponses(PRFileDesc *fd); +/* SSL_PeerSignedCertTimestamps returns the signed_certificate_timestamp + * extension data provided by the TLS server. The return value is a pointer + * to an internal SECItem that contains the returned response (as a serialized + * SignedCertificateTimestampList, see RFC 6962). The returned pointer is only + * valid until the callback function that calls SSL_PeerSignedCertTimestamps + * (e.g. the authenticate certificate hook, or the handshake callback) returns. + * + * If no Signed Certificate Timestamps were given by the server then the result + * will be empty. If there was an error, then the result will be NULL. + * + * You must set the SSL_ENABLE_SIGNED_CERT_TIMESTAMPS option to indicate support + * for Signed Certificate Timestamps to a server. + * + * libssl does not do any parsing or validation of the response itself. + */ +SSL_IMPORT const SECItem * SSL_PeerSignedCertTimestamps(PRFileDesc *fd); + /* SSL_SetStapledOCSPResponses stores an array of one or multiple OCSP responses * in the fd's data, which may be sent as part of a server side cert_status * handshake message. Parameter |responses| is for the server certificate of @@ -570,6 +589,18 @@ SSL_IMPORT SECStatus SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, SSLKEAType kea); +/* + * SSL_SetSignedCertTimestamps stores serialized signed_certificate_timestamp + * extension data in the fd. The signed_certificate_timestamp data is sent + * during the handshake (if requested by the client). Parameter |scts| + * is for the server certificate of the key exchange type |kea|. + * The function will duplicate the provided data item. To clear previously + * set data for a given key exchange type |kea|, pass NULL to |scts|. + */ +SSL_IMPORT SECStatus +SSL_SetSignedCertTimestamps(PRFileDesc *fd, const SECItem *scts, + SSLKEAType kea); + /* ** Authenticate certificate hook. Called when a certificate comes in ** (because of SSL_REQUIRE_CERTIFICATE in SSL_Enable) to authenticate the diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c index 8f1c547f4d19..a8e5eb9f9524 100644 --- a/security/nss/lib/ssl/ssl3con.c +++ b/security/nss/lib/ssl/ssl3con.c @@ -270,55 +270,55 @@ static SSL3Statistics ssl3stats; /* indexed by SSL3BulkCipher */ static const ssl3BulkCipherDef bulk_cipher_defs[] = { /* |--------- Lengths --------| */ - /* cipher calg k s type i b t n */ - /* e e v l a o */ - /* y c | o g n */ - /* | r | c | c */ - /* | e | k | e */ - /* | t | | | | */ - {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, - {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, - {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, - {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, - {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, - {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, - {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, - {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, - {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, - {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, - {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, - {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, - {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, - {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, - {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, - {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, - {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, + /* cipher calg k s type i b t n o */ + /* e e v l a o i */ + /* y c | o g n d */ + /* | r | c | c | */ + /* | e | k | e | */ + /* | t | | | | | */ + {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0, SEC_OID_NULL_CIPHER}, + {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0, SEC_OID_RC4}, + {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0, SEC_OID_RC4_40}, + {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0, SEC_OID_RC4_56}, + {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0, SEC_OID_RC2_CBC}, + {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0, SEC_OID_RC2_40_CBC}, + {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0, SEC_OID_DES_CBC}, + {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0, SEC_OID_DES_EDE3_CBC}, + {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0, SEC_OID_DES_40_CBC}, + {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0, SEC_OID_IDEA_CBC}, + {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0, SEC_OID_AES_128_CBC}, + {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0, SEC_OID_AES_256_CBC}, + {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0, SEC_OID_CAMELLIA_128_CBC}, + {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0, SEC_OID_CAMELLIA_256_CBC}, + {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0, SEC_OID_SEED_CBC}, + {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8, SEC_OID_AES_128_GCM}, + {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0, 0}, }; static const ssl3KEADef kea_defs[] = { /* indexed by SSL3KeyExchangeAlgorithm */ - /* kea exchKeyType signKeyType is_limited limit tls_keygen ephemeral */ - {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE}, - {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE, PR_FALSE}, - {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE, PR_FALSE}, - {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE}, - {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE, PR_TRUE}, - {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_TRUE}, - {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE, PR_TRUE}, - {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE, PR_FALSE}, + /* kea exchKeyType signKeyType is_limited limit tls_keygen ephemeral oid */ + {kea_null, kt_null, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_FALSE, 0}, + {kea_rsa, kt_rsa, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE, SEC_OID_TLS_RSA}, + {kea_rsa_export, kt_rsa, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE, SEC_OID_TLS_RSA_EXPORT}, + {kea_rsa_export_1024,kt_rsa, ssl_sign_rsa, PR_TRUE, 1024, PR_FALSE, PR_FALSE, SEC_OID_TLS_RSA_EXPORT}, + {kea_dh_dss, kt_dh, ssl_sign_dsa, PR_FALSE, 0, PR_FALSE, PR_FALSE, SEC_OID_TLS_DH_DSS}, + {kea_dh_dss_export, kt_dh, ssl_sign_dsa, PR_TRUE, 512, PR_FALSE, PR_FALSE, SEC_OID_TLS_DH_DSS_EXPORT}, + {kea_dh_rsa, kt_dh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE, SEC_OID_TLS_DH_RSA}, + {kea_dh_rsa_export, kt_dh, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE, SEC_OID_TLS_DH_RSA_EXPORT}, + {kea_dhe_dss, kt_dh, ssl_sign_dsa, PR_FALSE, 0, PR_FALSE, PR_TRUE, SEC_OID_TLS_DHE_DSS}, + {kea_dhe_dss_export, kt_dh, ssl_sign_dsa, PR_TRUE, 512, PR_FALSE, PR_TRUE, SEC_OID_TLS_DHE_DSS_EXPORT}, + {kea_dhe_rsa, kt_dh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE, SEC_OID_TLS_DHE_RSA}, + {kea_dhe_rsa_export, kt_dh, ssl_sign_rsa, PR_TRUE, 512, PR_FALSE, PR_TRUE, SEC_OID_TLS_DHE_RSA_EXPORT}, + {kea_dh_anon, kt_dh, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE, SEC_OID_TLS_DH_ANON}, + {kea_dh_anon_export, kt_dh, ssl_sign_null, PR_TRUE, 512, PR_FALSE, PR_TRUE, SEC_OID_TLS_DH_ANON_EXPORT}, + {kea_rsa_fips, kt_rsa, ssl_sign_rsa, PR_FALSE, 0, PR_TRUE, PR_FALSE, SEC_OID_TLS_RSA}, #ifndef NSS_DISABLE_ECC - {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE}, + {kea_ecdh_ecdsa, kt_ecdh, ssl_sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA}, + {kea_ecdhe_ecdsa, kt_ecdh, ssl_sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA}, + {kea_ecdh_rsa, kt_ecdh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE, SEC_OID_TLS_ECDH_RSA}, + {kea_ecdhe_rsa, kt_ecdh, ssl_sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE, SEC_OID_TLS_ECDHE_RSA}, + {kea_ecdh_anon, kt_ecdh, ssl_sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE, SEC_OID_TLS_ECDH_ANON}, #endif /* NSS_DISABLE_ECC */ }; @@ -500,13 +500,13 @@ static const SSLCipher2Mech alg2Mech[] = { static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ /* mac mmech pad_size mac_size */ - { mac_null, mmech_invalid, 0, 0 }, - { mac_md5, mmech_md5, 48, MD5_LENGTH }, - { mac_sha, mmech_sha, 40, SHA1_LENGTH}, - {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH }, - {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH}, - {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH}, - { mac_aead, mmech_invalid, 0, 0 }, + { mac_null, mmech_invalid, 0, 0 , 0}, + { mac_md5, mmech_md5, 48, MD5_LENGTH, SEC_OID_HMAC_MD5 }, + { mac_sha, mmech_sha, 40, SHA1_LENGTH, SEC_OID_HMAC_SHA1}, + {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH, SEC_OID_HMAC_MD5}, + {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH, SEC_OID_HMAC_SHA1}, + {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH, SEC_OID_HMAC_SHA256}, + { mac_aead, mmech_invalid, 0, 0, 0 }, }; /* indexed by SSL3BulkCipher */ @@ -4865,7 +4865,8 @@ tls12_loser: if (!spec->master_secret) { PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); - return SECFailure; + rv = SECFailure; + goto loser; } s[0] = (unsigned char)(sender >> 24); @@ -6542,10 +6543,12 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; PORT_Assert(ss->ssl3.hs.suite_def); if (!ss->ssl3.hs.suite_def) { - PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE); + errCode = SEC_ERROR_LIBRARY_FAILURE; + PORT_SetError(errCode); goto loser; /* we don't send alerts for our screw-ups. */ } - + ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; + /* find selected compression method in our list. */ temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); if (temp < 0) { @@ -6785,9 +6788,20 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) sid->u.ssl3.keys.extendedMasterSecretUsed = ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); + /* Copy Signed Certificate Timestamps, if any. */ + if (ss->xtnData.signedCertTimestamps.data) { + rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps, + &ss->xtnData.signedCertTimestamps); + if (rv != SECSuccess) + goto loser; + /* Clean up the temporary pointer to the handshake buffer. */ + ss->xtnData.signedCertTimestamps.data = NULL; + ss->xtnData.signedCertTimestamps.len = 0; + } + ss->ssl3.hs.isResuming = PR_FALSE; - if (ss->ssl3.hs.kea_def->signKeyType != sign_null) { - /* All current cipher suites other than those with sign_null (i.e., + if (ss->ssl3.hs.kea_def->signKeyType != ssl_sign_null) { + /* All current cipher suites other than those with ssl_sign_null (i.e., * (EC)DH_anon_* suites) require a certificate, so use that signal. */ ss->ssl3.hs.ws = wait_server_cert; } else { @@ -6803,7 +6817,10 @@ alert_loser: (void)SSL3_SendAlert(ss, alert_fatal, desc); loser: - errCode = ssl_MapLowLevelError(errCode); + /* Clean up the temporary pointer to the handshake buffer. */ + ss->xtnData.signedCertTimestamps.data = NULL; + ss->xtnData.signedCertTimestamps.len = 0; + ssl_MapLowLevelError(errCode); return SECFailure; } @@ -7135,7 +7152,7 @@ ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, { SECStatus rv; SSLSignType sigAlg; - PRBool preferSha1; + PRBool preferSha1 = PR_FALSE; PRBool supportsSha1 = PR_FALSE; PRBool supportsSha256 = PR_FALSE; PRBool needBackupHash = PR_FALSE; @@ -8203,6 +8220,8 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ss->ssl3.hs.cipher_suite = suite->cipher_suite; ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); + ss->ssl3.hs.kea_def = + &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; /* Use the cached compression method. */ @@ -8249,6 +8268,8 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ss->ssl3.hs.cipher_suite = suite->cipher_suite; ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); + ss->ssl3.hs.kea_def = + &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; goto suite_found; } @@ -8826,6 +8847,8 @@ ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) ss->ssl3.hs.cipher_suite = suite->cipher_suite; ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); + ss->ssl3.hs.kea_def = + &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; goto suite_found; } @@ -8999,7 +9022,7 @@ ssl3_SendServerHello(sslSocket *ss) extensions_len -= 2; rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); if (rv != SECSuccess) - return rv; /* err set by ssl3_SetupPendingCipherSpec */ + return rv; /* err set by ssl3_AppendHandshakeNumber */ sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, &ss->xtnData.serverSenders[0]); PORT_Assert(sent_len == extensions_len); @@ -9174,38 +9197,10 @@ static SECStatus ssl3_PickSignatureHashAlgorithm(sslSocket *ss, SSLSignatureAndHashAlg* out) { - SSLSignType sigAlg; PRUint32 policy; unsigned int i, j; - switch (ss->ssl3.hs.kea_def->kea) { - case kea_rsa: - case kea_rsa_export: - case kea_rsa_export_1024: - case kea_dh_rsa: - case kea_dh_rsa_export: - case kea_dhe_rsa: - case kea_dhe_rsa_export: - case kea_rsa_fips: - case kea_ecdh_rsa: - case kea_ecdhe_rsa: - sigAlg = ssl_sign_rsa; - break; - case kea_dh_dss: - case kea_dh_dss_export: - case kea_dhe_dss: - case kea_dhe_dss_export: - sigAlg = ssl_sign_dsa; - break; - case kea_ecdh_ecdsa: - case kea_ecdhe_ecdsa: - sigAlg = ssl_sign_ecdsa; - break; - default: - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; - } - out->sigAlg = sigAlg; + out->sigAlg = ss->ssl3.hs.kea_def->signKeyType; if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) { /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and @@ -9228,12 +9223,12 @@ ssl3_PickSignatureHashAlgorithm(sslSocket *ss, const SSLSignatureAndHashAlg *serverPref = &ss->ssl3.signatureAlgorithms[i]; SECOidTag hashOID; - if (serverPref->sigAlg != sigAlg) { + if (serverPref->sigAlg != out->sigAlg) { continue; } hashOID = ssl3_TLSHashAlgorithmToOID(serverPref->hashAlg); - if ((NSS_GetAlgorithmPolicy(hashOID, &policy) != SECSuccess) - || !(policy & NSS_USE_ALG_IN_SSL_KX)) { + if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) + && !(policy & NSS_USE_ALG_IN_SSL_KX)) { /* we ignore hashes we don't support */ continue; } @@ -9241,7 +9236,7 @@ ssl3_PickSignatureHashAlgorithm(sslSocket *ss, const SSLSignatureAndHashAlg *clientPref = &ss->ssl3.hs.clientSigAndHash[j]; if (clientPref->hashAlg == serverPref->hashAlg && - clientPref->sigAlg == sigAlg) { + clientPref->sigAlg == out->sigAlg) { out->hashAlg = serverPref->hashAlg; return SECSuccess; } @@ -10392,8 +10387,6 @@ ssl3_CleanupPeerCerts(sslSocket *ss) /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete * ssl3 CertificateStatus message. * Caller must hold Handshake and RecvBuf locks. - * This is always called before ssl3_HandleCertificate, even if the Certificate - * message is sent first. */ static SECStatus ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) @@ -10925,8 +10918,8 @@ ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); rv = SECFailure; #else - SECItem inData = { siBuffer, }; - SECItem outData = { siBuffer, }; + SECItem inData = { siBuffer }; + SECItem outData = { siBuffer }; PRBool isFIPS = PR_FALSE; inData.data = (unsigned char *) val; @@ -12930,4 +12923,55 @@ ssl3_DestroySSL3Info(sslSocket *ss) SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); } +#define MAP_NULL(x) (((x)!=0)?(x):SEC_OID_NULL_CIPHER) + +SECStatus ssl3_ApplyNSSPolicy(void) + { + unsigned i; + SECStatus rv; + PRUint32 policy = 0; + + rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy); + if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) { + return SECSuccess; /* do nothing */ + } + + /* disable every ciphersuite */ + for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) { + const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i]; + SECOidTag policyOid; + + policyOid=MAP_NULL(kea_defs[suite->key_exchange_alg].oid); + rv = NSS_GetAlgorithmPolicy(policyOid, &policy); + if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL_KX)) { + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); + continue; + } + + policyOid=MAP_NULL(bulk_cipher_defs[suite->bulk_cipher_alg].oid); + rv = NSS_GetAlgorithmPolicy(policyOid, &policy); + if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); + continue; + } + + if (bulk_cipher_defs[suite->bulk_cipher_alg].type != type_aead) { + policyOid=MAP_NULL(mac_defs[suite->mac_alg].oid); + rv = NSS_GetAlgorithmPolicy(policyOid, &policy); + if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, + SSL_NOT_ALLOWED); + continue; + } + } + } + + rv = ssl3_ConstrainRangeByPolicy(); + + return rv; +} + /* End of ssl3con.c */ diff --git a/security/nss/lib/ssl/ssl3ecc.c b/security/nss/lib/ssl/ssl3ecc.c index 94008a012b25..e414940c3474 100644 --- a/security/nss/lib/ssl/ssl3ecc.c +++ b/security/nss/lib/ssl/ssl3ecc.c @@ -162,6 +162,7 @@ SECStatus ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params) { SECOidData *oidData = NULL; + PRUint32 policyFlags = 0; if ((curve <= ec_noName) || (curve >= ec_pastLastName) || ((oidData = SECOID_FindOIDByTag(ecName2OIDTag[curve])) == NULL)) { @@ -169,6 +170,12 @@ ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params) return SECFailure; } + if ( (NSS_GetAlgorithmPolicy(ecName2OIDTag[curve], &policyFlags) + == SECSuccess) && !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); + return SECFailure; + } + SECITEM_AllocItem(arena, params, (2 + oidData->oid.len)); /* * params->data needs to contain the ASN encoding of an object ID (OID) @@ -187,6 +194,7 @@ params2ecName(SECKEYECParams * params) { SECItem oid = { siBuffer, NULL, 0}; SECOidData *oidData = NULL; + PRUint32 policyFlags = 0; ECName i; /* @@ -198,6 +206,10 @@ params2ecName(SECKEYECParams * params) oid.len = params->len - 2; oid.data = params->data + 2; if ((oidData = SECOID_FindOID(&oid)) == NULL) return ec_noName; + if ((NSS_GetAlgorithmPolicy(oidData->offset, &policyFlags) + == SECSuccess) && !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { + return ec_noName; + } for (i = ec_noName + 1; i < ec_pastLastName; i++) { if (ecName2OIDTag[i] == oidData->offset) return i; @@ -1057,31 +1069,25 @@ ssl3_IsECCEnabled(sslSocket * ss) /* Prefabricated TLS client hello extension, Elliptic Curves List, * offers only 3 curves, the Suite B curves, 23-25 */ -static const PRUint8 suiteBECList[12] = { - BE(10), /* Extension type */ - BE( 8), /* octets that follow ( 3 pairs + 1 length pair) */ - BE( 6), /* octets that follow ( 3 pairs) */ - BE(23), BE(24), BE(25) +static const PRUint8 suiteBECList[] = { + 23, 24, 25 }; /* Prefabricated TLS client hello extension, Elliptic Curves List, * offers curves 1-25. */ -static const PRUint8 tlsECList[56] = { - BE(10), /* Extension type */ - BE(52), /* octets that follow (25 pairs + 1 length pair) */ - BE(50), /* octets that follow (25 pairs) */ - BE( 1), BE( 2), BE( 3), BE( 4), BE( 5), BE( 6), BE( 7), - BE( 8), BE( 9), BE(10), BE(11), BE(12), BE(13), BE(14), BE(15), - BE(16), BE(17), BE(18), BE(19), BE(20), BE(21), BE(22), BE(23), - BE(24), BE(25) +static const PRUint8 tlsECList[] = { + 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, + 25 }; static const PRUint8 ecPtFmt[6] = { BE(11), /* Extension type */ BE( 2), /* octets that follow */ - 1, /* octets that follow */ - 0 /* uncompressed type only */ + 1, /* octets that follow */ + 0 /* uncompressed type only */ }; /* This function already presumes we can do ECC, ssl3_IsECCEnabled must be @@ -1108,6 +1114,13 @@ ssl3_SuiteBOnly(sslSocket *ss) return PR_FALSE; } +#define APPEND_CURVE(CURVE_ID) \ + if ((NSS_GetAlgorithmPolicy(ecName2OIDTag[CURVE_ID], &policy) \ + == SECFailure) || (policy & NSS_USE_ALG_IN_SSL_KX)) { \ + enabledCurves[pos++] = 0; \ + enabledCurves[pos++] = CURVE_ID; \ + } + /* Send our "canned" (precompiled) Supported Elliptic Curves extension, * which says that we support all TLS-defined named curves. */ @@ -1117,43 +1130,85 @@ ssl3_SendSupportedCurvesXtn( PRBool append, PRUint32 maxBytes) { + unsigned char enabledCurves[64]; + PRUint32 policy; + PRInt32 extension_length; PRInt32 ecListSize = 0; - const PRUint8 *ecList = NULL; + unsigned int pos = 0; + unsigned int i; if (!ss || !ssl3_IsECCEnabled(ss)) return 0; + PORT_Assert(sizeof(enabledCurves) > sizeof(tlsECList)*2); if (ssl3_SuiteBOnly(ss)) { - ecListSize = sizeof suiteBECList; - ecList = suiteBECList; + for (i=0; i < sizeof(suiteBECList); i++) { + APPEND_CURVE(suiteBECList[i]); + } + ecListSize = pos; } else { - ecListSize = sizeof tlsECList; - ecList = tlsECList; + for (i=0; i < sizeof(tlsECList); i++) { + APPEND_CURVE(tlsECList[i]); + } + ecListSize = pos; } + extension_length = + 2 /* extension type */ + + 2 /* extension length */ + + 2 /* elliptic curves length */ + + ecListSize; - if (maxBytes < (PRUint32)ecListSize) { + + if (maxBytes < (PRUint32)extension_length) { return 0; } + if (append) { - SECStatus rv = ssl3_AppendHandshake(ss, ecList, ecListSize); - if (rv != SECSuccess) - return -1; + SECStatus rv; + rv = ssl3_AppendHandshakeNumber(ss, ssl_elliptic_curves_xtn, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_AppendHandshakeVariable(ss, enabledCurves,ecListSize, 2); + if (rv != SECSuccess) + return -1; if (!ss->sec.isServer) { TLSExtensionData *xtnData = &ss->xtnData; xtnData->advertised[xtnData->numAdvertised++] = ssl_elliptic_curves_xtn; } } - return ecListSize; + return extension_length; } PRUint32 ssl3_GetSupportedECCurveMask(sslSocket *ss) { + int i; + PRUint32 curves = 0; + PRUint32 policyFlags = 0; + + PORT_Assert(ec_pastLastName < sizeof(PRUint32)*8); + if (ssl3_SuiteBOnly(ss)) { - return SSL3_SUITE_B_SUPPORTED_CURVES_MASK; + curves = SSL3_SUITE_B_SUPPORTED_CURVES_MASK; + } else { + curves = SSL3_ALL_SUPPORTED_CURVES_MASK; } - return SSL3_ALL_SUPPORTED_CURVES_MASK; + + for (i= ec_noName+1; i < ec_pastLastName; i++) { + PRUint32 curve_bit = (1U << i); + if ((curves & curve_bit) && + (NSS_GetAlgorithmPolicy(ecName2OIDTag[i], &policyFlags) + == SECSuccess) && + !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { + curves &= ~curve_bit; + } + } + return curves; + } /* Send our "canned" (precompiled) Supported Point Formats extension, diff --git a/security/nss/lib/ssl/ssl3ext.c b/security/nss/lib/ssl/ssl3ext.c index cf04abaed40d..0dd87e08253a 100644 --- a/security/nss/lib/ssl/ssl3ext.c +++ b/security/nss/lib/ssl/ssl3ext.c @@ -87,6 +87,19 @@ static PRInt32 ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, static SECStatus ssl3_ServerHandleSigAlgsXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data); +static PRInt32 ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss, + PRBool append, + PRUint32 maxBytes); +static SECStatus ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss, + PRUint16 ex_type, + SECItem *data); +static PRInt32 ssl3_ServerSendSignedCertTimestampXtn(sslSocket * ss, + PRBool append, + PRUint32 maxBytes); +static SECStatus ssl3_ServerHandleSignedCertTimestampXtn(sslSocket *ss, + PRUint16 ex_type, + SECItem *data); + static PRInt32 ssl3_ClientSendDraftVersionXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes); static SECStatus ssl3_ServerHandleDraftVersionXtn(sslSocket *ss, PRUint16 ex_type, @@ -263,6 +276,7 @@ static const ssl3HelloExtensionHandler clientHelloHandlers[] = { { ssl_signature_algorithms_xtn, &ssl3_ServerHandleSigAlgsXtn }, { ssl_tls13_draft_version_xtn, &ssl3_ServerHandleDraftVersionXtn }, { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn }, + { ssl_signed_cert_timestamp_xtn, &ssl3_ServerHandleSignedCertTimestampXtn }, { -1, NULL } }; @@ -278,6 +292,7 @@ static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = { { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn }, { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn }, { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn }, + { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn }, { -1, NULL } }; @@ -308,6 +323,7 @@ ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = { { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn }, { ssl_tls13_draft_version_xtn, &ssl3_ClientSendDraftVersionXtn }, { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn}, + { ssl_signed_cert_timestamp_xtn, &ssl3_ClientSendSignedCertTimestampXtn }, /* any extra entries will appear as { 0, NULL } */ }; @@ -966,23 +982,24 @@ ssl3_ServerSendStatusRequestXtn( PRUint32 maxBytes) { PRInt32 extension_length; + SSLKEAType effectiveExchKeyType; SECStatus rv; - int i; - PRBool haveStatus = PR_FALSE; - for (i = kt_null; i < kt_kea_size; i++) { - /* TODO: This is a temporary workaround. - * The correct code needs to see if we have an OCSP response for - * the server certificate being used, rather than if we have any - * OCSP response. See also ssl3_SendCertificateStatus. - */ - if (ss->certStatusArray[i] && ss->certStatusArray[i]->len) { - haveStatus = PR_TRUE; - break; - } + /* ssl3_SendCertificateStatus (which sents the certificate status data) + * uses the exact same logic to select the server certificate + * and determine if we have the status for that certificate. */ + + if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || + ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { + effectiveExchKeyType = ssl_kea_rsa; + } else { + effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; } - if (!haveStatus) + + if (!ss->certStatusArray[effectiveExchKeyType] || + !ss->certStatusArray[effectiveExchKeyType]->len) { return 0; + } extension_length = 2 + 2; if (maxBytes < (PRUint32)extension_length) { @@ -997,6 +1014,7 @@ ssl3_ServerSendStatusRequestXtn( rv = ssl3_AppendHandshakeNumber(ss, 0, 2); if (rv != SECSuccess) return -1; + /* The certificate status data is sent in ssl3_SendCertificateStatus. */ } return extension_length; @@ -1077,7 +1095,7 @@ ssl3_SendNewSessionTicket(sslSocket *ss) SSL3KEAType effectiveExchKeyType = ssl_kea_null; PRUint32 padding_length; PRUint32 message_length; - PRUint32 cert_length; + PRUint32 cert_length = 0; PRUint8 length_buf[4]; PRUint32 now; PK11SymKey *aes_key_pkcs11; @@ -1113,8 +1131,9 @@ ssl3_SendNewSessionTicket(sslSocket *ss) PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT; - cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ? - 3 + ss->sec.ci.sid->peerCert->derCert.len : 0; + if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) { + cert_length = 3 + ss->sec.ci.sid->peerCert->derCert.len; + } /* Get IV and encryption keys */ ivItem.data = iv; @@ -2010,8 +2029,11 @@ ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, int i; if (!sender) { - sender = ss->version > SSL_LIBRARY_VERSION_3_0 ? - &clientHelloSendersTLS[0] : &clientHelloSendersSSL3[0]; + if (ss->version > SSL_LIBRARY_VERSION_3_0) { + sender = &clientHelloSendersTLS[0]; + } else { + sender = &clientHelloSendersSSL3[0]; + } } for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) { @@ -2040,7 +2062,8 @@ ssl3_SendRenegotiationInfoXtn( PRBool append, PRUint32 maxBytes) { - PRInt32 len, needed; + PRInt32 len = 0; + PRInt32 needed; /* In draft-ietf-tls-renegotiation-03, it is NOT RECOMMENDED to send * both the SCSV and the empty RI, so when we send SCSV in @@ -2048,9 +2071,10 @@ ssl3_SendRenegotiationInfoXtn( */ if (!ss || ss->ssl3.hs.sendingSCSV) return 0; - len = !ss->firstHsDone ? 0 : - (ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2 - : ss->ssl3.hs.finishedBytes); + if (ss->firstHsDone) { + len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2 + : ss->ssl3.hs.finishedBytes; + } needed = 5 + len; if (maxBytes < (PRUint32)needed) { return 0; @@ -2682,3 +2706,125 @@ ssl3_HandleExtendedMasterSecretXtn(sslSocket * ss, PRUint16 ex_type, } return SECSuccess; } + + +/* ssl3_ClientSendSignedCertTimestampXtn sends the signed_certificate_timestamp + * extension for TLS ClientHellos. */ +static PRInt32 +ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss, PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length = 2 /* extension_type */ + + 2 /* length(extension_data) */; + + /* Only send the extension if processing is enabled. */ + if (!ss->opt.enableSignedCertTimestamps) + return 0; + + if (append && maxBytes >= extension_length) { + SECStatus rv; + /* extension_type */ + rv = ssl3_AppendHandshakeNumber(ss, + ssl_signed_cert_timestamp_xtn, + 2); + if (rv != SECSuccess) + goto loser; + /* zero length */ + rv = ssl3_AppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + goto loser; + ss->xtnData.advertised[ss->xtnData.numAdvertised++] = + ssl_signed_cert_timestamp_xtn; + } else if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + + return extension_length; +loser: + return -1; +} + +static SECStatus +ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type, + SECItem *data) +{ + /* We do not yet know whether we'll be resuming a session or creating + * a new one, so we keep a pointer to the data in the TLSExtensionData + * structure. This pointer is only valid in the scope of + * ssl3_HandleServerHello, and, if not resuming a session, the data is + * copied once a new session structure has been set up. + * All parsing is currently left to the application and we accept + * everything, including empty data. + */ + SECItem *scts = &ss->xtnData.signedCertTimestamps; + PORT_Assert(!scts->data && !scts->len); + + if (!data->len) { + /* Empty extension data: RFC 6962 mandates non-empty contents. */ + return SECFailure; + } + *scts = *data; + /* Keep track of negotiated extensions. */ + ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; + return SECSuccess; +} + +static PRInt32 +ssl3_ServerSendSignedCertTimestampXtn(sslSocket * ss, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + SSLKEAType effectiveExchKeyType; + const SECItem *scts; + + if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || + ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { + effectiveExchKeyType = ssl_kea_rsa; + } else { + effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; + } + + scts = &ss->signedCertTimestamps[effectiveExchKeyType]; + + if (!scts->len) { + /* No timestamps to send */ + return 0; + } + + extension_length = 2 /* extension_type */ + + 2 /* length(extension_data) */ + + scts->len; + + if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + if (append) { + SECStatus rv; + /* extension_type */ + rv = ssl3_AppendHandshakeNumber(ss, + ssl_signed_cert_timestamp_xtn, + 2); + if (rv != SECSuccess) goto loser; + /* extension_data */ + rv = ssl3_AppendHandshakeVariable(ss, scts->data, scts->len, 2); + if (rv != SECSuccess) goto loser; + } + + return extension_length; + +loser: + return -1; +} + +static SECStatus +ssl3_ServerHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type, + SECItem *data) +{ + ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; + PORT_Assert(ss->sec.isServer); + return ssl3_RegisterServerHelloExtensionSender(ss, ex_type, + ssl3_ServerSendSignedCertTimestampXtn); +} diff --git a/security/nss/lib/ssl/sslcon.c b/security/nss/lib/ssl/sslcon.c index ccd00260ec2e..8cc8f954f84b 100644 --- a/security/nss/lib/ssl/sslcon.c +++ b/security/nss/lib/ssl/sslcon.c @@ -51,21 +51,21 @@ typedef struct ssl2SpecsStr { static const ssl2Specs ssl_Specs[] = { /* NONE */ - { 0, 0, 0, 0, }, + { 0, 0, 0, 0 }, /* SSL_CK_RC4_128_WITH_MD5 */ - { 2, 16, 1, 0, CKM_RC4, 16, 0, 0, }, + { 2, 16, 1, 0, CKM_RC4, 16, 0, 0 }, /* SSL_CK_RC4_128_EXPORT40_WITH_MD5 */ - { 2, 16, 1, 0, CKM_RC4, 16, 11, 0, }, + { 2, 16, 1, 0, CKM_RC4, 16, 11, 0 }, /* SSL_CK_RC2_128_CBC_WITH_MD5 */ - { 2, 16, 8, 3, CKM_RC2_CBC, 16, 0, 8, }, + { 2, 16, 8, 3, CKM_RC2_CBC, 16, 0, 8 }, /* SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 */ - { 2, 16, 8, 3, CKM_RC2_CBC, 16, 11, 8, }, + { 2, 16, 8, 3, CKM_RC2_CBC, 16, 11, 8 }, /* SSL_CK_IDEA_128_CBC_WITH_MD5 */ - { 0, 0, 0, 0, }, + { 0, 0, 0, 0 }, /* SSL_CK_DES_64_CBC_WITH_MD5 */ - { 1, 8, 8, 3, CKM_DES_CBC, 8, 0, 8, }, + { 1, 8, 8, 3, CKM_DES_CBC, 8, 0, 8 }, /* SSL_CK_DES_192_EDE3_CBC_WITH_MD5 */ - { 3, 24, 8, 3, CKM_DES3_CBC, 24, 0, 8, }, + { 3, 24, 8, 3, CKM_DES3_CBC, 24, 0, 8 }, }; #define SET_ERROR_CODE /* reminder */ diff --git a/security/nss/lib/ssl/sslimpl.h b/security/nss/lib/ssl/sslimpl.h index ad31aaef74fa..af12971b7541 100644 --- a/security/nss/lib/ssl/sslimpl.h +++ b/security/nss/lib/ssl/sslimpl.h @@ -38,12 +38,6 @@ */ typedef SSLKEAType SSL3KEAType; typedef SSLMACAlgorithm SSL3MACAlgorithm; -typedef SSLSignType SSL3SignType; - -#define sign_null ssl_sign_null -#define sign_rsa ssl_sign_rsa -#define sign_dsa ssl_sign_dsa -#define sign_ecdsa ssl_sign_ecdsa #define calg_null ssl_calg_null #define calg_rc4 ssl_calg_rc4 @@ -338,6 +332,7 @@ typedef struct sslOptionsStr { unsigned int enableFallbackSCSV : 1; /* 29 */ unsigned int enableServerDhe : 1; /* 30 */ unsigned int enableExtendedMS : 1; /* 31 */ + unsigned int enableSignedCertTimestamps : 1; /* 32 */ } sslOptions; typedef enum { sslHandshakingUndetermined = 0, @@ -497,9 +492,9 @@ typedef PRUint16 DTLSEpoch; typedef void (*DTLSTimerCb)(sslSocket *); -#define MAX_MAC_CONTEXT_BYTES 400 /* 400 is large enough for MD5, SHA-1, and - * SHA-256. For SHA-384 support, increase - * it to 712. */ +/* 400 is large enough for MD5, SHA-1, and SHA-256. + * For SHA-384 support, increase it to 712. */ +#define MAX_MAC_CONTEXT_BYTES 400 #define MAX_MAC_CONTEXT_LLONGS (MAX_MAC_CONTEXT_BYTES / 8) #define MAX_CIPHER_CONTEXT_BYTES 2080 @@ -701,6 +696,11 @@ struct sslSessionIDStr { SECItem srvName; + /* Signed certificate timestamps received in a TLS extension. + ** (used only in client). + */ + SECItem signedCertTimestamps; + /* This lock is lazily initialized by CacheSID when a sid is first * cached. Before then, there is no need to lock anything because * the sid isn't being shared by anything. @@ -735,7 +735,7 @@ typedef struct ssl3CipherSuiteDefStr { typedef struct { SSL3KeyExchangeAlgorithm kea; SSL3KEAType exchKeyType; - SSL3SignType signKeyType; + SSLSignType signKeyType; /* For export cipher suites: * is_limited identifies a suite as having a limit on the key size. * key_size_limit provides the corresponding limit. */ @@ -745,6 +745,8 @@ typedef struct { /* True if the key exchange for the suite is ephemeral. Or to be more * precise: true if the ServerKeyExchange message is always required. */ PRBool ephemeral; + /* An OID describing the key exchange */ + SECOidTag oid; } ssl3KEADef; /* @@ -760,6 +762,7 @@ struct ssl3BulkCipherDefStr { int block_size; int tag_size; /* authentication tag size for AEAD ciphers. */ int explicit_nonce_size; /* for AEAD ciphers. */ + SECOidTag oid; }; /* @@ -770,6 +773,7 @@ struct ssl3MACDefStr { CK_MECHANISM_TYPE mmech; int pad_size; int mac_size; + SECOidTag oid; }; typedef enum { @@ -815,6 +819,18 @@ struct TLSExtensionDataStr { * is beyond ssl3_HandleClientHello function. */ SECItem *sniNameArr; PRUint32 sniNameArrSize; + + /* Signed Certificate Timestamps extracted from the TLS extension. + * (client only). + * This container holds a temporary pointer to the extension data, + * until a session structure (the sec.ci.sid of an sslSocket) is setup + * that can hold a permanent copy of the data + * (in sec.ci.sid.u.ssl3.signedCertTimestamps). + * The data pointed to by this structure is neither explicitly allocated + * nor copied: the pointer points to the handshake message buffer and is + * only valid in the scope of ssl3_HandleServerHello. + */ + SECItem signedCertTimestamps; }; typedef SECStatus (*sslRestartTarget)(sslSocket *); @@ -1011,8 +1027,9 @@ struct ssl3StateStr { unsigned int signatureAlgorithmCount; }; -#define DTLS_MAX_MTU 1500U /* Ethernet MTU but without subtracting the - * headers, so slightly larger than expected */ +/* Ethernet MTU but without subtracting the headers, + * so slightly larger than expected */ +#define DTLS_MAX_MTU 1500U #define IS_DTLS(ss) (ss->protocolVariant == ssl_variant_datagram) typedef struct { @@ -1314,6 +1331,11 @@ const unsigned char * preferredCipher; sslServerCerts serverCerts[kt_kea_size]; /* each cert needs its own status */ SECItemArray * certStatusArray[kt_kea_size]; + /* Serialized signed certificate timestamps to be sent to the client + ** in a TLS extension (server only). Each certificate needs its own + ** timestamps item. + */ + SECItem signedCertTimestamps[kt_kea_size]; ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED]; ssl3KeyPair * ephemeralECDHKeyPair; /* for ECDHE-* handshake */ @@ -1460,6 +1482,13 @@ extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled); extern void ssl_FinishHandshake(sslSocket *ss); +extern SECStatus ssl_CipherPolicySet(PRInt32 which, PRInt32 policy); + +extern SECStatus ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled); + +extern SECStatus ssl3_ConstrainRangeByPolicy(void); + + /* Returns PR_TRUE if we are still waiting for the server to respond to our * client second round. Once we've received any part of the server's second * round then we don't bother trying to false start since it is almost always @@ -1648,11 +1677,13 @@ extern PRUint32 ssl3_GetSupportedECCurveMask(sslSocket *ss); /* Macro for finding a curve equivalent in strength to RSA key's */ +/* clang-format off */ #define SSL_RSASTRENGTH_TO_ECSTRENGTH(s) \ ((s <= 1024) ? 160 \ : ((s <= 2048) ? 224 \ : ((s <= 3072) ? 256 \ : ((s <= 7168) ? 384 : 521 ) ) ) ) +/* clang-format on */ /* Types and names of elliptic curves used in TLS */ typedef enum { ec_type_explicitPrime = 1, @@ -1946,6 +1977,8 @@ SECStatus SSL_DisableDefaultExportCipherSuites(void); SECStatus SSL_DisableExportCipherSuites(PRFileDesc * fd); PRBool SSL_IsExportCipherSuite(PRUint16 cipherSuite); +SECStatus ssl3_ApplyNSSPolicy(void); + extern SECStatus ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, unsigned int labelLen, diff --git a/security/nss/lib/ssl/sslinfo.c b/security/nss/lib/ssl/sslinfo.c index 216ab0fa040d..a9c57e9d6656 100644 --- a/security/nss/lib/ssl/sslinfo.c +++ b/security/nss/lib/ssl/sslinfo.c @@ -166,91 +166,91 @@ SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, static const SSLCipherSuiteInfo suiteInfo[] = { /* <------ Cipher suite --------------------> */ -{0,CS(TLS_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, +{0,CS(TLS_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA), S_DSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256), S_DSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_RSA, C_AES, B_256, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_RSA, C_AES, B_256, M_SHA, 1, 0, 0, }, +{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, +{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA), S_DSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256), S_DSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, +{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_RSA, C_AES, B_256, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_RSA, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256), S_DSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256), S_DSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_RC4_128_SHA), S_RSA, K_RSA, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_RC4_128_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_RSA, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_RSA, C_AES, B_128, M_SHA, 1, 0, 0, }, +{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, +{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256), S_DSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256), S_DSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0 }, +{0,CS(TLS_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_RSA_WITH_RC4_128_SHA), S_RSA, K_RSA, C_RC4, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_RSA_WITH_RC4_128_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0 }, +{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_RSA, C_AES, B_128, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_RSA, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA), S_DSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0, }, -{0,CS(SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 1, }, -{0,CS(TLS_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 0, }, +{0,CS(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA), S_DSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, +{0,CS(SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 1 }, +{0,CS(TLS_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_DES_CBC_SHA), S_RSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_DES_CBC_SHA), S_DSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0, }, -{0,CS(SSL_RSA_FIPS_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 1, }, -{0,CS(TLS_RSA_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 0, }, +{0,CS(TLS_DHE_RSA_WITH_DES_CBC_SHA), S_RSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0 }, +{0,CS(TLS_DHE_DSS_WITH_DES_CBC_SHA), S_DSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0 }, +{0,CS(SSL_RSA_FIPS_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 1 }, +{0,CS(TLS_RSA_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 0 }, -{0,CS(TLS_RSA_EXPORT1024_WITH_RC4_56_SHA), S_RSA, K_RSA, C_RC4, B_56, M_SHA, 0, 1, 0, }, -{0,CS(TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 1, 0, }, -{0,CS(TLS_RSA_EXPORT_WITH_RC4_40_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0, }, -{0,CS(TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0, }, -{0,CS(TLS_RSA_WITH_NULL_SHA256), S_RSA, K_RSA, C_NULL,B_0, M_SHA256, 0, 1, 0, }, -{0,CS(TLS_RSA_WITH_NULL_SHA), S_RSA, K_RSA, C_NULL,B_0, M_SHA, 0, 1, 0, }, -{0,CS(TLS_RSA_WITH_NULL_MD5), S_RSA, K_RSA, C_NULL,B_0, M_MD5, 0, 1, 0, }, +{0,CS(TLS_RSA_EXPORT1024_WITH_RC4_56_SHA), S_RSA, K_RSA, C_RC4, B_56, M_SHA, 0, 1, 0 }, +{0,CS(TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 1, 0 }, +{0,CS(TLS_RSA_EXPORT_WITH_RC4_40_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0 }, +{0,CS(TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0 }, +{0,CS(TLS_RSA_WITH_NULL_SHA256), S_RSA, K_RSA, C_NULL,B_0, M_SHA256, 0, 1, 0 }, +{0,CS(TLS_RSA_WITH_NULL_SHA), S_RSA, K_RSA, C_NULL,B_0, M_SHA, 0, 1, 0 }, +{0,CS(TLS_RSA_WITH_NULL_MD5), S_RSA, K_RSA, C_NULL,B_0, M_MD5, 0, 1, 0 }, #ifndef NSS_DISABLE_ECC /* ECC cipher suites */ -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, +{0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, +{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, -{0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0, }, +{0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0, }, +{0,CS(TLS_ECDHE_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDH_RSA_WITH_NULL_SHA), S_RSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0, }, +{0,CS(TLS_ECDH_RSA_WITH_NULL_SHA), S_RSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDH_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_RSA_WITH_NULL_SHA), S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0, }, +{0,CS(TLS_ECDHE_RSA_WITH_NULL_SHA), S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDHE_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, +{0,CS(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0 }, +{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, +{0,CS(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0 }, #endif /* NSS_DISABLE_ECC */ /* SSL 2 table */ -{0,CK(SSL_CK_RC4_128_WITH_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_RC2_128_CBC_WITH_MD5), S_RSA, K_RSA, C_RC2, B_128, M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_DES_192_EDE3_CBC_WITH_MD5), S_RSA, K_RSA, C_3DES,B_3DES,M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_DES_64_CBC_WITH_MD5), S_RSA, K_RSA, C_DES, B_DES, M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_RC4_128_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0, }, -{0,CK(SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0, } +{0,CK(SSL_CK_RC4_128_WITH_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0 }, +{0,CK(SSL_CK_RC2_128_CBC_WITH_MD5), S_RSA, K_RSA, C_RC2, B_128, M_MD5, 0, 0, 0 }, +{0,CK(SSL_CK_DES_192_EDE3_CBC_WITH_MD5), S_RSA, K_RSA, C_3DES,B_3DES,M_MD5, 0, 0, 0 }, +{0,CK(SSL_CK_DES_64_CBC_WITH_MD5), S_RSA, K_RSA, C_DES, B_DES, M_MD5, 0, 0, 0 }, +{0,CK(SSL_CK_RC4_128_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0 }, +{0,CK(SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0 } }; #define NUM_SUITEINFOS ((sizeof suiteInfo) / (sizeof suiteInfo[0])) diff --git a/security/nss/lib/ssl/sslinit.c b/security/nss/lib/ssl/sslinit.c index bb9df255f35d..d7eac6dda5bf 100644 --- a/security/nss/lib/ssl/sslinit.c +++ b/security/nss/lib/ssl/sslinit.c @@ -11,23 +11,50 @@ #include "secerr.h" #include "ssl.h" #include "sslimpl.h" +#include "sslproto.h" -static int ssl_inited = 0; +static int ssl_isInited = 0; +static PRCallOnceType ssl_init = { 0 }; -SECStatus -ssl_Init(void) +PRStatus +ssl_InitCallOnce(void *arg) { - if (!ssl_inited) { - if (ssl_InitializePRErrorTable() != SECSuccess) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return (SECFailure); - } + int *error = (int *)arg; + SECStatus rv; + rv = ssl_InitializePRErrorTable(); + if (rv != SECSuccess) { + *error = SEC_ERROR_NO_MEMORY; + return PR_FAILURE; + } #ifdef DEBUG ssl3_CheckCipherSuiteOrderConsistency(); #endif - ssl_inited = 1; + rv = ssl3_ApplyNSSPolicy(); + if (rv != SECSuccess) { + *error = PORT_GetError(); + return PR_FAILURE; + } + return PR_SUCCESS; +} + + +SECStatus +ssl_Init(void) +{ + PRStatus nrv; + + /* short circuit test if we are already inited */ + if (!ssl_isInited) { + int error; + /* only do this once at init time, block all others until we are done */ + nrv = PR_CallOnceWithArg(&ssl_init, ssl_InitCallOnce, &error); + if (nrv != PR_SUCCESS) { + PORT_SetError(error); + return SECFailure; + } + ssl_isInited = 1; } return SECSuccess; } diff --git a/security/nss/lib/ssl/sslnonce.c b/security/nss/lib/ssl/sslnonce.c index 2e861f15760d..bb4da3b90518 100644 --- a/security/nss/lib/ssl/sslnonce.c +++ b/security/nss/lib/ssl/sslnonce.c @@ -179,6 +179,9 @@ ssl_DestroySID(sslSessionID *sid) if (sid->u.ssl3.srvName.data) { SECITEM_FreeItem(&sid->u.ssl3.srvName, PR_FALSE); } + if (sid->u.ssl3.signedCertTimestamps.data) { + SECITEM_FreeItem(&sid->u.ssl3.signedCertTimestamps, PR_FALSE); + } if (sid->u.ssl3.lock) { PR_DestroyRWLock(sid->u.ssl3.lock); diff --git a/security/nss/lib/ssl/sslsock.c b/security/nss/lib/ssl/sslsock.c index f73500925f1b..b29913aaf9ac 100644 --- a/security/nss/lib/ssl/sslsock.c +++ b/security/nss/lib/ssl/sslsock.c @@ -85,7 +85,8 @@ static sslOptions ssl_defaults = { PR_TRUE, /* reuseServerECDHEKey */ PR_FALSE, /* enableFallbackSCSV */ PR_TRUE, /* enableServerDhe */ - PR_FALSE /* enableExtendedMS */ + PR_FALSE, /* enableExtendedMS */ + PR_FALSE, /* enableSignedCertTimestamps */ }; /* @@ -104,6 +105,12 @@ static SSLVersionRange versions_defaults_datagram = { #define VERSIONS_DEFAULTS(variant) \ (variant == ssl_variant_stream ? &versions_defaults_stream : \ &versions_defaults_datagram) +#define VERSIONS_POLICY_MIN(variant) \ + (variant == ssl_variant_stream ? NSS_TLS_VERSION_MIN_POLICY : \ + NSS_DTLS_VERSION_MIN_POLICY) +#define VERSIONS_POLICY_MAX(variant) \ + (variant == ssl_variant_stream ? NSS_TLS_VERSION_MAX_POLICY : \ + NSS_DTLS_VERSION_MAX_POLICY) sslSessionIDLookupFunc ssl_sid_lookup; sslSessionIDCacheFunc ssl_sid_cache; @@ -400,6 +407,9 @@ ssl_DestroySocketContents(sslSocket *ss) SECITEM_FreeArray(ss->certStatusArray[i], PR_TRUE); ss->certStatusArray[i] = NULL; } + if (ss->signedCertTimestamps[i].data) { + SECITEM_FreeItem(&ss->signedCertTimestamps[i], PR_FALSE); + } } if (ss->stepDownKeyPair) { ssl3_FreeKeyPair(ss->stepDownKeyPair); @@ -529,12 +539,22 @@ static PRStatus SSL_BypassSetup(void) #endif } +static PRBool ssl_VersionIsSupportedByPolicy( + SSLProtocolVariant protocolVariant, SSL3ProtocolVersion version); + /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_TLS, on) described in * ssl.h in the section "SSL version range setting API". */ static void ssl_EnableTLS(SSLVersionRange *vrange, PRBool on) { + if (on) { + /* don't turn it on if tls1.0 disallowed by by policy */ + if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, + SSL_LIBRARY_VERSION_TLS_1_0)) { + return; + } + } if (SSL3_ALL_VERSIONS_DISABLED(vrange)) { if (on) { vrange->min = SSL_LIBRARY_VERSION_TLS_1_0; @@ -565,6 +585,13 @@ ssl_EnableTLS(SSLVersionRange *vrange, PRBool on) static void ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on) { + if (on) { + /* don't turn it on if ssl3 disallowed by by policy */ + if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, + SSL_LIBRARY_VERSION_3_0)) { + return; + } + } if (SSL3_ALL_VERSIONS_DISABLED(vrange)) { if (on) { vrange->min = SSL_LIBRARY_VERSION_3_0; @@ -690,6 +717,13 @@ SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on) } break; } + if (on) { + /* don't turn it on if ssl2 disallowed by by policy */ + if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, + SSL_LIBRARY_VERSION_2)) { + break; + } + } ss->opt.enableSSL2 = on; if (on) { ss->opt.v2CompatibleHello = on; @@ -830,6 +864,10 @@ SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on) ss->opt.enableExtendedMS = on; break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + ss->opt.enableSignedCertTimestamps = on; + break; + default: PORT_SetError(SEC_ERROR_INVALID_ARGS); rv = SECFailure; @@ -908,6 +946,9 @@ SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn) case SSL_ENABLE_SERVER_DHE: on = ss->opt.enableServerDhe; break; case SSL_ENABLE_EXTENDED_MASTER_SECRET: on = ss->opt.enableExtendedMS; break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + on = ss->opt.enableSignedCertTimestamps; + break; default: PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -983,6 +1024,9 @@ SSL_OptionGetDefault(PRInt32 which, PRBool *pOn) case SSL_ENABLE_EXTENDED_MASTER_SECRET: on = ssl_defaults.enableExtendedMS; break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + on = ssl_defaults.enableSignedCertTimestamps; + break; default: PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -1057,6 +1101,13 @@ SSL_OptionSetDefault(PRInt32 which, PRBool on) break; case SSL_ENABLE_SSL2: + if (on) { + /* don't turn it on if ssl2 disallowed by by policy */ + if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, + SSL_LIBRARY_VERSION_2)) { + break; + } + } ssl_defaults.enableSSL2 = on; if (on) { ssl_defaults.v2CompatibleHello = on; @@ -1174,6 +1225,10 @@ SSL_OptionSetDefault(PRInt32 which, PRBool on) ssl_defaults.enableExtendedMS = on; break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + ssl_defaults.enableSignedCertTimestamps = on; + break; + default: PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; @@ -1215,13 +1270,9 @@ SSL_SetPolicy(long which, int policy) } SECStatus -SSL_CipherPolicySet(PRInt32 which, PRInt32 policy) +ssl_CipherPolicySet(PRInt32 which, PRInt32 policy) { - SECStatus rv = ssl_Init(); - - if (rv != SECSuccess) { - return rv; - } + SECStatus rv = SECSuccess; if (ssl_IsRemovedCipherSuite(which)) { rv = SECSuccess; @@ -1232,6 +1283,16 @@ SSL_CipherPolicySet(PRInt32 which, PRInt32 policy) } return rv; } +SECStatus +SSL_CipherPolicySet(PRInt32 which, PRInt32 policy) +{ + SECStatus rv = ssl_Init(); + + if (rv != SECSuccess) { + return rv; + } + return ssl_CipherPolicySet(which, policy); +} SECStatus SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy) @@ -1274,13 +1335,9 @@ SSL_EnableCipher(long which, PRBool enabled) } SECStatus -SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled) +ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled) { - SECStatus rv = ssl_Init(); - - if (rv != SECSuccess) { - return rv; - } + SECStatus rv = SECSuccess; if (ssl_IsRemovedCipherSuite(which)) return SECSuccess; @@ -1296,6 +1353,17 @@ SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled) return rv; } +SECStatus +SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled) +{ + SECStatus rv = ssl_Init(); + + if (rv != SECSuccess) { + return rv; + } + return ssl_CipherPrefSetDefault(which, enabled); +} + SECStatus SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) { @@ -1371,6 +1439,14 @@ NSS_SetDomesticPolicy(void) { SECStatus status = SECSuccess; const PRUint16 *cipher; + SECStatus rv; + PRUint32 policy; + + /* If we've already defined some policy oids, skip changing them */ + rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy); + if ((rv == SECSuccess) && (policy & NSS_USE_POLICY_IN_SSL)) { + return ssl_Init(); /* make sure the policies have bee loaded */ + } for (cipher = SSL_ImplementedCiphers; *cipher != 0; ++cipher) { status = SSL_SetPolicy(*cipher, SSL_ALLOWED); @@ -1922,6 +1998,16 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) if (!ss->certStatusArray[i]) goto loser; } + if (sm->signedCertTimestamps[i].data) { + if (ss->signedCertTimestamps[i].data) { + SECITEM_FreeItem(&ss->signedCertTimestamps[i], PR_FALSE); + } + if (SECITEM_CopyItem(NULL, + &ss->signedCertTimestamps[i], + &sm->signedCertTimestamps[i]) != SECSuccess) { + goto loser; + } + } } if (mc->serverKeyPair) { if (sc->serverKeyPair) { @@ -1982,10 +2068,106 @@ loser: return NULL; } +/* + * Get the user supplied range + */ +static SECStatus +ssl3_GetRangePolicy(SSLProtocolVariant protocolVariant, SSLVersionRange *prange) +{ + SECStatus rv; + PRUint32 policy; + PRInt32 option; + + /* only use policy constraints if we've set the apply ssl policy bit */ + rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy); + if ((rv != SECSuccess) || !(policy & NSS_USE_POLICY_IN_SSL)) { + return SECFailure; + } + rv=NSS_OptionGet(VERSIONS_POLICY_MIN(protocolVariant),&option); + if (rv != SECSuccess) { + return rv; + } + prange->min = (PRUint16) option; + rv=NSS_OptionGet(VERSIONS_POLICY_MAX(protocolVariant),&option); + if (rv != SECSuccess) { + return rv; + } + prange->max = (PRUint16) option; + if (prange->max < prange->min) { + return SECFailure; /* don't accept an invalid policy */ + } + return SECSuccess; +} + +/* + * Constrain a single protocol variant's range based on the user policy + */ +static SECStatus +ssl3_ConstrainVariantRangeByPolicy(SSLProtocolVariant protocolVariant) +{ + SSLVersionRange vrange; + SSLVersionRange pvrange; + SECStatus rv; + + vrange = *VERSIONS_DEFAULTS(protocolVariant); + rv = ssl3_GetRangePolicy(protocolVariant, &pvrange); + if (rv != SECSuccess) { + return SECSuccess; /* we don't have any policy */ + } + vrange.min = PR_MAX(vrange.min, pvrange.min); + vrange.max = PR_MIN(vrange.max, pvrange.max); + if (vrange.max >= vrange.min) { + *VERSIONS_DEFAULTS(protocolVariant) = vrange; + } else { + /* there was no overlap, turn off range altogether */ + pvrange.min = pvrange.max = SSL_LIBRARY_VERSION_NONE; + *VERSIONS_DEFAULTS(protocolVariant) = pvrange; + } + return SECSuccess; +} + +static PRBool +ssl_VersionIsSupportedByPolicy(SSLProtocolVariant protocolVariant, + SSL3ProtocolVersion version) +{ + SSLVersionRange pvrange; + SECStatus rv; + + rv = ssl3_GetRangePolicy(protocolVariant, &pvrange); + if (rv == SECSuccess) { + if ((version > pvrange.max) || (version < pvrange.min)) { + return PR_FALSE; /* disallowed by policy */ + } + } + return PR_TRUE; +} + +/* + * This is called at SSL init time to constrain the existing range based + * on user supplied policy. + */ +SECStatus +ssl3_ConstrainRangeByPolicy(void) +{ + SECStatus rv; + rv = ssl3_ConstrainVariantRangeByPolicy(ssl_variant_stream); + if (rv != SECSuccess) { + return rv; + } + rv = ssl3_ConstrainVariantRangeByPolicy(ssl_variant_datagram); + if (rv != SECSuccess) { + return rv; + } + return SECSuccess; +} + PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant, SSL3ProtocolVersion version) { + if (!ssl_VersionIsSupportedByPolicy(protocolVariant, version)) { + return PR_FALSE; + } switch (protocolVariant) { case ssl_variant_stream: return (version >= SSL_LIBRARY_VERSION_3_0 && @@ -2013,6 +2195,29 @@ ssl3_VersionRangeIsValid(SSLProtocolVariant protocolVariant, ssl3_VersionIsSupported(protocolVariant, vrange->max); } +const SECItem * +SSL_PeerSignedCertTimestamps(PRFileDesc *fd) +{ + sslSocket *ss = ssl_FindSocket(fd); + + if (!ss) { + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerSignedCertTimestamps", + SSL_GETPID(), fd)); + return NULL; + } + + if (!ss->sec.ci.sid) { + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); + return NULL; + } + + if (ss->sec.ci.sid->version < SSL_LIBRARY_VERSION_3_0) { + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); + return NULL; + } + return &ss->sec.ci.sid->u.ssl3.signedCertTimestamps; +} + SECStatus SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant, SSLVersionRange *vrange) @@ -2489,7 +2694,7 @@ SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, } if ( kea <= 0 || kea >= kt_kea_size) { - SSL_DBG(("%d: SSL[%d]: invalid key in SSL_SetStapledOCSPResponses", + SSL_DBG(("%d: SSL[%d]: invalid key type in SSL_SetStapledOCSPResponses", SSL_GETPID(), fd)); return SECFailure; } @@ -2504,6 +2709,35 @@ SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, return (ss->certStatusArray[kea] || !responses) ? SECSuccess : SECFailure; } +SECStatus +SSL_SetSignedCertTimestamps(PRFileDesc *fd, const SECItem *scts, SSLKEAType kea) +{ + sslSocket *ss; + + ss = ssl_FindSocket(fd); + if (!ss) { + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSignedCertTimestamps", + SSL_GETPID(), fd)); + return SECFailure; + } + + if (kea <= 0 || kea >= kt_kea_size) { + SSL_DBG(("%d: SSL[%d]: invalid key type in SSL_SetSignedCertTimestamps", + SSL_GETPID(), fd)); + return SECFailure; + } + + if (ss->signedCertTimestamps[kea].data) { + SECITEM_FreeItem(&ss->signedCertTimestamps[kea], PR_FALSE); + } + + if (!scts) { + return SECSuccess; + } + + return SECITEM_CopyItem(NULL, &ss->signedCertTimestamps[kea], scts); +} + SECStatus SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID) { diff --git a/security/nss/lib/ssl/sslt.h b/security/nss/lib/ssl/sslt.h index cd742bbb2ed1..8e893258e6cb 100644 --- a/security/nss/lib/ssl/sslt.h +++ b/security/nss/lib/ssl/sslt.h @@ -234,6 +234,8 @@ typedef enum { ssl_signature_algorithms_xtn = 13, ssl_use_srtp_xtn = 14, ssl_app_layer_protocol_xtn = 16, + /* signed_certificate_timestamp extension, RFC 6962 */ + ssl_signed_cert_timestamp_xtn = 18, ssl_padding_xtn = 21, ssl_extended_master_secret_xtn = 23, ssl_session_ticket_xtn = 35, @@ -242,7 +244,7 @@ typedef enum { ssl_tls13_draft_version_xtn = 0xff02 /* experimental number */ } SSLExtensionType; -#define SSL_MAX_EXTENSIONS 12 /* doesn't include ssl_padding_xtn. */ +#define SSL_MAX_EXTENSIONS 13 /* doesn't include ssl_padding_xtn. */ typedef enum { ssl_dhe_group_none = 0, diff --git a/security/nss/lib/sysinit/nsssysinit.c b/security/nss/lib/sysinit/nsssysinit.c index 60015dd70686..5d139ab866d7 100644 --- a/security/nss/lib/sysinit/nsssysinit.c +++ b/security/nss/lib/sysinit/nsssysinit.c @@ -318,10 +318,10 @@ overlapstrcpy(char *target, char *src) /* filename is the directory pointed to by configdir= */ /* stripped is the rest of the parameters with configdir= stripped out */ static SECStatus -parse_parameters(char *parameters, char **filename, char **stripped) +parse_parameters(const char *parameters, char **filename, char **stripped) { - char *sourcePrev; - char *sourceCurr; + const char *sourcePrev; + const char *sourceCurr; char *targetCurr; char *newStripped; *filename = NULL; diff --git a/security/nss/lib/util/dertime.c b/security/nss/lib/util/dertime.c index 3a2782771a90..c196abbfc1b7 100644 --- a/security/nss/lib/util/dertime.c +++ b/security/nss/lib/util/dertime.c @@ -19,10 +19,10 @@ p += 2; \ } -static const PRTime January1st1 = (PRTime) LL_INIT(0xff234001U, 0x00d44000U); -static const PRTime January1st1950 = (PRTime) LL_INIT(0xfffdc1f8U, 0x793da000U); -static const PRTime January1st2050 = LL_INIT(0x0008f81e, 0x1b098000); -static const PRTime January1st10000 = LL_INIT(0x0384440c, 0xcc736000); +static const PRTime January1st1 = PR_INT64(0xff23400100d44000); +static const PRTime January1st1950 = PR_INT64(0xfffdc1f8793da000); +static const PRTime January1st2050 = PR_INT64(0x0008f81e1b098000); +static const PRTime January1st10000 = PR_INT64(0x0384440ccc736000); /* gmttime must contains UTC time in micro-seconds unit */ SECStatus diff --git a/security/nss/lib/util/nssutil.h b/security/nss/lib/util/nssutil.h index 0c8b480f563c..8f84a34e9ecb 100644 --- a/security/nss/lib/util/nssutil.h +++ b/security/nss/lib/util/nssutil.h @@ -19,12 +19,12 @@ * The format of the version string should be * ".[.[.]][ ]" */ -#define NSSUTIL_VERSION "3.21" +#define NSSUTIL_VERSION "3.22 Beta" #define NSSUTIL_VMAJOR 3 -#define NSSUTIL_VMINOR 21 +#define NSSUTIL_VMINOR 22 #define NSSUTIL_VPATCH 0 #define NSSUTIL_VBUILD 0 -#define NSSUTIL_BETA PR_FALSE +#define NSSUTIL_BETA PR_TRUE SEC_BEGIN_PROTOS diff --git a/security/nss/lib/util/pkcs11t.h b/security/nss/lib/util/pkcs11t.h index 23931413e440..3fd66115fd60 100644 --- a/security/nss/lib/util/pkcs11t.h +++ b/security/nss/lib/util/pkcs11t.h @@ -1787,9 +1787,15 @@ 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 - +/* The following PRFs are defined in PKCS #5 v2.1. */ +#define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001 +#define CKP_PKCS5_PBKD2_HMAC_GOSTR3411 0x00000002 +#define CKP_PKCS5_PBKD2_HMAC_SHA224 0x00000003 +#define CKP_PKCS5_PBKD2_HMAC_SHA256 0x00000004 +#define CKP_PKCS5_PBKD2_HMAC_SHA384 0x00000005 +#define CKP_PKCS5_PBKD2_HMAC_SHA512 0x00000006 +#define CKP_PKCS5_PBKD2_HMAC_SHA512_224 0x00000007 +#define CKP_PKCS5_PBKD2_HMAC_SHA512_256 0x00000008 /* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is new for v2.10. * CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the diff --git a/security/nss/lib/util/secoid.c b/security/nss/lib/util/secoid.c index 002099215b5d..71fd24cf3848 100644 --- a/security/nss/lib/util/secoid.c +++ b/security/nss/lib/util/secoid.c @@ -163,6 +163,11 @@ const char __nss_util_version[] = "Version: NSS " NSSUTIL_VERSION _DEBUG_STRING; #define CAMELLIA_ENCRYPT_OID MITSUBISHI_ALG,1 #define CAMELLIA_WRAP_OID MITSUBISHI_ALG,3 +/* For IDEA: 1.3.6.1.4.1.188.7.1.1 + */ +#define ASCOM_OID 0x2b,0x6,0x1,0x4,0x1,0xbc +#define ASCOM_IDEA_ALG ASCOM_OID,0x7,0x1,0x1 + /* for SEED : iso(1) member-body(2) korea(410) * kisa(200004) algorithm(1) */ @@ -459,6 +464,10 @@ CONST_OID netscapeSMimeKEA[] = { NETSCAPE_ALGS, 0x01 }; CONST_OID skipjackCBC[] = { MISSI, 0x04 }; CONST_OID dhPublicKey[] = { ANSI_X942_ALGORITHM, 0x1 }; +CONST_OID idea_CBC[] = { ASCOM_IDEA_ALG, 2 }; +CONST_OID aes128_GCM[] = { AES, 0x6 }; +CONST_OID aes192_GCM[] = { AES, 0x1a }; +CONST_OID aes256_GCM[] = { AES, 0x2e }; CONST_OID aes128_ECB[] = { AES, 1 }; CONST_OID aes128_CBC[] = { AES, 2 }; #ifdef DEFINE_ALL_AES_CIPHERS @@ -579,8 +588,10 @@ CONST_OID evIncorporationCountry[] = { EV_NAME_ATTRIBUTE, 3 }; #define OI(x) { siDEROID, (unsigned char *)x, sizeof x } #ifndef SECOID_NO_STRINGS #define OD(oid,tag,desc,mech,ext) { OI(oid), tag, desc, mech, ext } +#define ODE(tag,desc,mech,ext) { { siDEROID, NULL, 0 }, tag, desc, mech, ext } #else #define OD(oid,tag,desc,mech,ext) { OI(oid), tag, 0, mech, ext } +#define ODE(tag,desc,mech,ext) { { siDEROID, NULL, 0 }, tag, 0, mech, ext } #endif #if defined(NSS_ALLOW_UNSUPPORTED_CRITICAL) @@ -1639,7 +1650,67 @@ const static SECOidData oids[SEC_OID_TOTAL] = { "Microsoft Trust List Signing", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), OD( x520Name, SEC_OID_AVA_NAME, - "X520 Name", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ) + "X520 Name", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + + + OD( aes128_GCM, SEC_OID_AES_128_GCM, + "AES-128-GCM", CKM_AES_GCM, INVALID_CERT_EXTENSION ), + OD( aes192_GCM, SEC_OID_AES_192_GCM, + "AES-192-GCM", CKM_AES_GCM, INVALID_CERT_EXTENSION ), + OD( aes256_GCM, SEC_OID_AES_256_GCM, + "AES-256-GCM", CKM_AES_GCM, INVALID_CERT_EXTENSION ), + OD( idea_CBC, SEC_OID_IDEA_CBC, + "IDEA_CBC", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + + ODE( SEC_OID_RC2_40_CBC, + "RC2-40-CBC", CKM_RC2_CBC, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_DES_40_CBC, + "DES-40-CBC", CKM_RC2_CBC, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_RC4_40, + "RC4-40", CKM_RC4, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_RC4_56, + "RC4-56", CKM_RC4, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_NULL_CIPHER, + "NULL cipher", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_HMAC_MD5, + "HMAC-MD5", CKM_MD5_HMAC, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_RSA, + "TLS RSA key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DHE_RSA, + "TLS DHE-RSA key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DHE_DSS, + "TLS DHE-DSS key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DH_RSA, + "TLS DH-RSA key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DH_DSS, + "TLS DH-DSS key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DH_ANON, + "TLS DH-ANON key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_ECDHE_ECDSA, + "TLS ECDHE-ECDSA key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_ECDHE_RSA, + "TLS ECDHE-RSA key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_ECDH_ECDSA, + "TLS ECDH-ECDSA key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_ECDH_RSA, + "TLS ECDH-RSA key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_ECDH_ANON, + "TLS ECDH-ANON key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_RSA_EXPORT, + "TLS RSA-EXPORT key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DHE_RSA_EXPORT, + "TLS DHE-RSA-EXPORT key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DHE_DSS_EXPORT, + "TLS DHE-DSS-EXPORT key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DH_RSA_EXPORT, + "TLS DH-RSA-EXPORT key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DH_DSS_EXPORT, + "TLS DH-DSS-EXPORT key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_TLS_DH_ANON_EXPORT, + "TLS DH-ANON-EXPORT key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_APPLY_SSL_POLICY, + "Apply SSL policy (pseudo-OID)", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + }; /* PRIVATE EXTENDED SECOID Table @@ -1872,6 +1943,7 @@ secoid_HashNumber(const void *key) return (PLHashNumber)((char *)key - (char *)NULL); } +#define DEF_FLAGS (NSS_USE_ALG_IN_CERT_SIGNATURE|NSS_USE_ALG_IN_SSL_KX|NSS_USE_ALG_IN_SSL_KX) static void handleHashAlgSupport(char * envVal) { @@ -1887,14 +1959,14 @@ handleHashAlgSupport(char * envVal) *nextArg++ = '\0'; } } - notEnable = (*arg == '-') ? (NSS_USE_ALG_IN_CERT_SIGNATURE|NSS_USE_ALG_IN_SSL_KX) : 0; + notEnable = (*arg == '-') ? (DEF_FLAGS) : 0; if ((*arg == '+' || *arg == '-') && *++arg) { int i; for (i = 1; i < SEC_OID_TOTAL; i++) { if (oids[i].desc && strstr(arg, oids[i].desc)) { xOids[i].notPolicyFlags = notEnable | - (xOids[i].notPolicyFlags & ~(NSS_USE_ALG_IN_CERT_SIGNATURE|NSS_USE_ALG_IN_SSL_KX)); + (xOids[i].notPolicyFlags & ~(DEF_FLAGS)); } } } @@ -1930,6 +2002,9 @@ SECOID_Init(void) xOids[SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC].notPolicyFlags = ~0; } + /* turn off NSS_USE_POLICY_IN_SSL by default */ + xOids[SEC_OID_APPLY_SSL_POLICY].notPolicyFlags = NSS_USE_POLICY_IN_SSL; + envVal = PR_GetEnv("NSS_HASH_ALG_SUPPORT"); if (envVal) handleHashAlgSupport(envVal); diff --git a/security/nss/lib/util/secoidt.h b/security/nss/lib/util/secoidt.h index 747450ed06bc..0b4bfc4a4e93 100644 --- a/security/nss/lib/util/secoidt.h +++ b/security/nss/lib/util/secoidt.h @@ -443,6 +443,42 @@ typedef enum { /* The 'name' attribute type in X.520 */ SEC_OID_AVA_NAME = 317, + + SEC_OID_AES_128_GCM = 318, + SEC_OID_AES_192_GCM = 319, + SEC_OID_AES_256_GCM = 320, + SEC_OID_IDEA_CBC = 321, + + /* pseudo - OIDs */ + + SEC_OID_RC2_40_CBC = 322, + SEC_OID_DES_40_CBC = 323, + SEC_OID_RC4_40 = 324, + SEC_OID_RC4_56 = 325, + SEC_OID_NULL_CIPHER = 326, + + SEC_OID_HMAC_MD5 = 327, + + SEC_OID_TLS_RSA = 328, + SEC_OID_TLS_DHE_RSA = 329, + SEC_OID_TLS_DHE_DSS = 330, + SEC_OID_TLS_DH_RSA = 331, + SEC_OID_TLS_DH_DSS = 332, + SEC_OID_TLS_DH_ANON = 333, + SEC_OID_TLS_ECDHE_ECDSA = 334, + SEC_OID_TLS_ECDHE_RSA = 335, + SEC_OID_TLS_ECDH_ECDSA = 336, + SEC_OID_TLS_ECDH_RSA = 337, + SEC_OID_TLS_ECDH_ANON = 338, + SEC_OID_TLS_RSA_EXPORT = 339, + + SEC_OID_TLS_DHE_RSA_EXPORT = 340, + SEC_OID_TLS_DHE_DSS_EXPORT = 341, + SEC_OID_TLS_DH_RSA_EXPORT = 342, + SEC_OID_TLS_DH_DSS_EXPORT = 343, + SEC_OID_TLS_DH_ANON_EXPORT = 344, + SEC_OID_APPLY_SSL_POLICY = 345, + SEC_OID_TOTAL } SECOidTag; @@ -477,6 +513,8 @@ struct SECOidDataStr { #define NSS_USE_ALG_IN_CERT_SIGNATURE 0x00000001 /* CRLs and OCSP, too */ #define NSS_USE_ALG_IN_CMS_SIGNATURE 0x00000002 /* used in S/MIME */ #define NSS_USE_ALG_IN_SSL_KX 0x00000004 /* used in SSL key exchange */ +#define NSS_USE_ALG_IN_SSL 0x00000008 /* used in SSL record protocol */ +#define NSS_USE_POLICY_IN_SSL 0x00000010 /* enable policy in SSL protocol */ #define NSS_USE_ALG_RESERVED 0xfffffffc /* may be used in future */ /* Code MUST NOT SET or CLEAR reserved bits, and must NOT depend on them diff --git a/security/nss/lib/util/templates.c b/security/nss/lib/util/templates.c index e5f1ebc2489e..bf5d69e81b33 100644 --- a/security/nss/lib/util/templates.c +++ b/security/nss/lib/util/templates.c @@ -22,10 +22,10 @@ const SEC_ASN1Template SECOID_AlgorithmIDTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SECAlgorithmID) }, { SEC_ASN1_OBJECT_ID, - offsetof(SECAlgorithmID,algorithm), }, + offsetof(SECAlgorithmID,algorithm) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, - offsetof(SECAlgorithmID,parameters), }, - { 0, } + offsetof(SECAlgorithmID,parameters) }, + { 0 } }; SEC_ASN1_CHOOSER_IMPLEMENT(SECOID_AlgorithmIDTemplate) diff --git a/security/nss/lib/util/utilmod.c b/security/nss/lib/util/utilmod.c index 4be99ade2f86..230b5c97dd5a 100644 --- a/security/nss/lib/util/utilmod.c +++ b/security/nss/lib/util/utilmod.c @@ -165,7 +165,7 @@ char *_NSSUTIL_GetOldSecmodName(const char *dbname,const char *filename) static SECStatus nssutil_AddSecmodDBEntry(const char *appName, const char *filename, const char *dbname, - char *module, PRBool rw); + const char *module, PRBool rw); enum lfopen_mode { lfopen_truncate, lfopen_append }; @@ -210,7 +210,7 @@ nssutil_ReadSecmodDB(const char *appName, char *paramsValue=NULL; PRBool failed = PR_TRUE; - moduleList = (char **) PORT_ZAlloc(useCount*sizeof(char **)); + moduleList = (char **) PORT_ZAlloc(useCount*sizeof(char *)); if (moduleList == NULL) return NULL; if (dbname == NULL) { @@ -387,7 +387,7 @@ done: status = PR_Access(olddbname, PR_ACCESS_EXISTS); if (status == PR_SUCCESS) { PR_smprintf_free(olddbname); - PORT_ZFree(moduleList, useCount*sizeof(char **)); + PORT_ZFree(moduleList, useCount*sizeof(char *)); PORT_SetError(SEC_ERROR_LEGACY_DATABASE); return NULL; } @@ -469,7 +469,7 @@ static SECStatus nssutil_DeleteSecmodDBEntry(const char *appName, const char *filename, const char *dbname, - char *args, + const char *args, PRBool rw) { /* SHDB_FIXME implement */ @@ -610,7 +610,7 @@ loser: static SECStatus nssutil_AddSecmodDBEntry(const char *appName, const char *filename, const char *dbname, - char *module, PRBool rw) + const char *module, PRBool rw) { os_stat_type stat_existing; os_open_permissions_type file_mode; diff --git a/security/nss/lib/util/utilpars.c b/security/nss/lib/util/utilpars.c index 278f9c426dd8..3f293408ca82 100644 --- a/security/nss/lib/util/utilpars.c +++ b/security/nss/lib/util/utilpars.c @@ -49,7 +49,7 @@ PRBool NSSUTIL_ArgIsQuote(char c) { return PR_FALSE; } -char *NSSUTIL_ArgStrip(char *c) { +const char *NSSUTIL_ArgStrip(const char *c) { while (*c && NSSUTIL_ArgIsBlank(*c)) c++; return c; } @@ -58,8 +58,8 @@ char *NSSUTIL_ArgStrip(char *c) { * find the end of the current tag/value pair. string should be pointing just * after the equal sign. Handles quoted characters. */ -char * -NSSUTIL_ArgFindEnd(char *string) { +const char * +NSSUTIL_ArgFindEnd(const char *string) { char endChar = ' '; PRBool lastEscape = PR_FALSE; @@ -91,9 +91,9 @@ NSSUTIL_ArgFindEnd(char *string) { * the equal sign. */ char * -NSSUTIL_ArgFetchValue(char *string, int *pcount) +NSSUTIL_ArgFetchValue(const char *string, int *pcount) { - char *end = NSSUTIL_ArgFindEnd(string); + const char *end = NSSUTIL_ArgFindEnd(string); char *retString, *copyString; PRBool lastEscape = PR_FALSE; int len; @@ -127,10 +127,10 @@ NSSUTIL_ArgFetchValue(char *string, int *pcount) /* * point to the next parameter in string */ -char * -NSSUTIL_ArgSkipParameter(char *string) +const char * +NSSUTIL_ArgSkipParameter(const char *string) { - char *end; + const char *end; /* look for the end of the = */ for (;*string; string++) { if (*string == '=') { string++; break; } @@ -146,7 +146,7 @@ NSSUTIL_ArgSkipParameter(char *string) * get the value from that tag value pair. */ char * -NSSUTIL_ArgGetParamValue(char *paramName,char *parameters) +NSSUTIL_ArgGetParamValue(const char *paramName, const char *parameters) { char searchValue[256]; int paramLen = strlen(paramName); @@ -175,8 +175,8 @@ NSSUTIL_ArgGetParamValue(char *paramName,char *parameters) /* * find the next flag in the parameter list */ -char * -NSSUTIL_ArgNextFlag(char *flags) +const char * +NSSUTIL_ArgNextFlag(const char *flags) { for (; *flags ; flags++) { if (*flags == ',') { @@ -191,9 +191,10 @@ NSSUTIL_ArgNextFlag(char *flags) * return true if the flag is set in the label parameter. */ PRBool -NSSUTIL_ArgHasFlag(char *label, char *flag, char *parameters) +NSSUTIL_ArgHasFlag(const char *label, const char *flag, const char *parameters) { - char *flags,*index; + char *flags; + const char *index; int len = strlen(flag); PRBool found = PR_FALSE; @@ -214,7 +215,7 @@ NSSUTIL_ArgHasFlag(char *label, char *flag, char *parameters) * decode a number. handle octal (leading '0'), hex (leading '0x') or decimal */ long -NSSUTIL_ArgDecodeNumber(char *num) +NSSUTIL_ArgDecodeNumber(const char *num) { int radix = 10; unsigned long value = 0; @@ -264,10 +265,10 @@ NSSUTIL_ArgDecodeNumber(char *num) * value before the equal size. */ char * -NSSUTIL_ArgGetLabel(char *inString, int *next) +NSSUTIL_ArgGetLabel(const char *inString, int *next) { char *name=NULL; - char *string; + const char *string; int len; /* look for the end of the