diff --git a/cmd/addbuiltin/addbuiltin.c b/cmd/addbuiltin/addbuiltin.c index 2226a159c0..3da6652a3b 100644 --- a/cmd/addbuiltin/addbuiltin.c +++ b/cmd/addbuiltin/addbuiltin.c @@ -18,53 +18,56 @@ #include #endif -void dumpbytes(unsigned char *buf, int len) +void +dumpbytes(unsigned char *buf, int len) { int i; - for (i=0; i < len; i++) { - if ((i !=0) && ((i & 0xf) == 0)) { - printf("\n"); - } - printf("\\%03o",buf[i]); + for (i = 0; i < len; i++) { + if ((i != 0) && ((i & 0xf) == 0)) { + printf("\n"); + } + printf("\\%03o", buf[i]); } printf("\n"); } -char *getTrustString(unsigned int trust) +char * +getTrustString(unsigned int trust) { if (trust & CERTDB_TRUSTED) { - if (trust & CERTDB_TRUSTED_CA) { - return "CKT_NSS_TRUSTED_DELEGATOR"; - } else { - return "CKT_NSS_TRUSTED"; - } + if (trust & CERTDB_TRUSTED_CA) { + return "CKT_NSS_TRUSTED_DELEGATOR"; + } else { + return "CKT_NSS_TRUSTED"; + } } else { - if (trust & CERTDB_TRUSTED_CA) { - return "CKT_NSS_TRUSTED_DELEGATOR"; - } else if (trust & CERTDB_VALID_CA) { - return "CKT_NSS_VALID_DELEGATOR"; - } else if (trust & CERTDB_TERMINAL_RECORD) { - return "CKT_NSS_NOT_TRUSTED"; - } else { - return "CKT_NSS_MUST_VERIFY_TRUST"; - } + if (trust & CERTDB_TRUSTED_CA) { + return "CKT_NSS_TRUSTED_DELEGATOR"; + } else if (trust & CERTDB_VALID_CA) { + return "CKT_NSS_VALID_DELEGATOR"; + } else if (trust & CERTDB_TERMINAL_RECORD) { + return "CKT_NSS_NOT_TRUSTED"; + } else { + return "CKT_NSS_MUST_VERIFY_TRUST"; + } } return "CKT_NSS_TRUST_UNKNOWN"; /* not reached */ } static const SEC_ASN1Template serialTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(CERTCertificate,serialNumber) }, + { SEC_ASN1_INTEGER, offsetof(CERTCertificate, serialNumber) }, { 0 } }; -void print_crl_info(CERTName *name, SECItem *serial) +void +print_crl_info(CERTName *name, SECItem *serial) { PRBool saveWrapeState = SECU_GetWrapEnabled(); SECU_EnableWrap(PR_FALSE); SECU_PrintNameQuotesOptional(stdout, name, "# Issuer", 0, PR_FALSE); printf("\n"); - + SECU_PrintInteger(stdout, serial, "# Serial Number", 0); SECU_EnableWrap(saveWrapeState); @@ -77,79 +80,80 @@ ConvertCRLEntry(SECItem *sdder, PRInt32 crlentry, char *nickname) PLArenaPool *arena = NULL; CERTSignedCrl *newCrl = NULL; CERTCrlEntry *entry; - + CERTName *name = NULL; SECItem *derName = NULL; SECItem *serial = NULL; - + rv = SEC_ERROR_NO_MEMORY; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (!arena) - return rv; + return rv; newCrl = CERT_DecodeDERCrlWithFlags(arena, sdder, SEC_CRL_TYPE, - CRL_DECODE_DEFAULT_OPTIONS); + CRL_DECODE_DEFAULT_OPTIONS); if (!newCrl) - return SECFailure; - + return SECFailure; + name = &newCrl->crl.name; derName = &newCrl->crl.derName; - + if (newCrl->crl.entries != NULL) { - PRInt32 iv = 0; - while ((entry = newCrl->crl.entries[iv++]) != NULL) { - if (crlentry == iv) { - serial = &entry->serialNumber; - break; - } - } + PRInt32 iv = 0; + while ((entry = newCrl->crl.entries[iv++]) != NULL) { + if (crlentry == iv) { + serial = &entry->serialNumber; + break; + } + } } - + if (!name || !derName || !serial) - return SECFailure; - - printf("\n# Distrust \"%s\"\n",nickname); + return SECFailure; + + printf("\n# Distrust \"%s\"\n", nickname); print_crl_info(name, serial); printf("CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST\n"); printf("CKA_TOKEN CK_BBOOL CK_TRUE\n"); printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n"); printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n"); - printf("CKA_LABEL UTF8 \"%s\"\n",nickname); - + printf("CKA_LABEL UTF8 \"%s\"\n", nickname); + printf("CKA_ISSUER MULTILINE_OCTAL\n"); - dumpbytes(derName->data,derName->len); + dumpbytes(derName->data, derName->len); printf("END\n"); printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n"); printf("\\002\\%03o", serial->len); /* 002: type integer; len >=3 digits */ - dumpbytes(serial->data,serial->len); + dumpbytes(serial->data, serial->len); printf("END\n"); - + printf("CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_NOT_TRUSTED\n"); printf("CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_NOT_TRUSTED\n"); printf("CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_NOT_TRUSTED\n"); printf("CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE\n"); - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return rv; } -void print_info(SECItem *sdder, CERTCertificate *c) +void +print_info(SECItem *sdder, CERTCertificate *c) { PRBool saveWrapeState = SECU_GetWrapEnabled(); SECU_EnableWrap(PR_FALSE); SECU_PrintNameQuotesOptional(stdout, &c->issuer, "# Issuer", 0, PR_FALSE); printf("\n"); - + SECU_PrintInteger(stdout, &c->serialNumber, "# Serial Number", 0); SECU_PrintNameQuotesOptional(stdout, &c->subject, "# Subject", 0, PR_FALSE); printf("\n"); SECU_PrintTimeChoice(stdout, &c->validity.notBefore, "# Not Valid Before", 0); - SECU_PrintTimeChoice(stdout, &c->validity.notAfter, "# Not Valid After ", 0); - + SECU_PrintTimeChoice(stdout, &c->validity.notAfter, "# Not Valid After ", 0); + SECU_PrintFingerprints(stdout, sdder, "# Fingerprint", 0); SECU_EnableWrap(saveWrapeState); @@ -169,43 +173,43 @@ ConvertCertificate(SECItem *sdder, char *nickname, CERTCertTrust *trust, cert = CERT_DecodeDERCertificate(sdder, PR_FALSE, nickname); if (!cert) { - return SECFailure; + return SECFailure; } - serial = SEC_ASN1EncodeItem(NULL,NULL,cert,serialTemplate); + serial = SEC_ASN1EncodeItem(NULL, NULL, cert, serialTemplate); if (!serial) { - return SECFailure; + return SECFailure; } - + if (!excludeCert) { - printf("\n#\n# Certificate \"%s\"\n#\n",nickname); - print_info(sdder, cert); - printf("CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE\n"); - printf("CKA_TOKEN CK_BBOOL CK_TRUE\n"); - printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n"); - printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n"); - printf("CKA_LABEL UTF8 \"%s\"\n",nickname); - printf("CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509\n"); - printf("CKA_SUBJECT MULTILINE_OCTAL\n"); - dumpbytes(cert->derSubject.data,cert->derSubject.len); - printf("END\n"); - printf("CKA_ID UTF8 \"0\"\n"); - printf("CKA_ISSUER MULTILINE_OCTAL\n"); - dumpbytes(cert->derIssuer.data,cert->derIssuer.len); - printf("END\n"); - printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n"); - dumpbytes(serial->data,serial->len); - printf("END\n"); - printf("CKA_VALUE MULTILINE_OCTAL\n"); - dumpbytes(sdder->data,sdder->len); - printf("END\n"); + printf("\n#\n# Certificate \"%s\"\n#\n", nickname); + print_info(sdder, cert); + printf("CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE\n"); + printf("CKA_TOKEN CK_BBOOL CK_TRUE\n"); + printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n"); + printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n"); + printf("CKA_LABEL UTF8 \"%s\"\n", nickname); + printf("CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509\n"); + printf("CKA_SUBJECT MULTILINE_OCTAL\n"); + dumpbytes(cert->derSubject.data, cert->derSubject.len); + printf("END\n"); + printf("CKA_ID UTF8 \"0\"\n"); + printf("CKA_ISSUER MULTILINE_OCTAL\n"); + dumpbytes(cert->derIssuer.data, cert->derIssuer.len); + printf("END\n"); + printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n"); + dumpbytes(serial->data, serial->len); + printf("END\n"); + printf("CKA_VALUE MULTILINE_OCTAL\n"); + dumpbytes(sdder->data, sdder->len); + printf("END\n"); } - - if ((trust->sslFlags | trust->emailFlags | trust->objectSigningFlags) - == CERTDB_TERMINAL_RECORD) - trust_info = "Distrust"; + + if ((trust->sslFlags | trust->emailFlags | trust->objectSigningFlags) == + CERTDB_TERMINAL_RECORD) + trust_info = "Distrust"; else - trust_info = "Trust for"; - + trust_info = "Trust for"; + printf("\n# %s \"%s\"\n", trust_info, nickname); print_info(sdder, cert); @@ -213,32 +217,32 @@ ConvertCertificate(SECItem *sdder, char *nickname, CERTCertTrust *trust, printf("CKA_TOKEN CK_BBOOL CK_TRUE\n"); printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n"); printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n"); - printf("CKA_LABEL UTF8 \"%s\"\n",nickname); - + printf("CKA_LABEL UTF8 \"%s\"\n", nickname); + if (!excludeHash) { - PK11_HashBuf(SEC_OID_SHA1, sha1_hash, sdder->data, sdder->len); - printf("CKA_CERT_SHA1_HASH MULTILINE_OCTAL\n"); - dumpbytes(sha1_hash,SHA1_LENGTH); - printf("END\n"); - PK11_HashBuf(SEC_OID_MD5, md5_hash, sdder->data, sdder->len); - printf("CKA_CERT_MD5_HASH MULTILINE_OCTAL\n"); - dumpbytes(md5_hash,MD5_LENGTH); - printf("END\n"); + PK11_HashBuf(SEC_OID_SHA1, sha1_hash, sdder->data, sdder->len); + printf("CKA_CERT_SHA1_HASH MULTILINE_OCTAL\n"); + dumpbytes(sha1_hash, SHA1_LENGTH); + printf("END\n"); + PK11_HashBuf(SEC_OID_MD5, md5_hash, sdder->data, sdder->len); + printf("CKA_CERT_MD5_HASH MULTILINE_OCTAL\n"); + dumpbytes(md5_hash, MD5_LENGTH); + printf("END\n"); } printf("CKA_ISSUER MULTILINE_OCTAL\n"); - dumpbytes(cert->derIssuer.data,cert->derIssuer.len); + dumpbytes(cert->derIssuer.data, cert->derIssuer.len); printf("END\n"); printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n"); - dumpbytes(serial->data,serial->len); + dumpbytes(serial->data, serial->len); printf("END\n"); - + printf("CKA_TRUST_SERVER_AUTH CK_TRUST %s\n", - getTrustString(trust->sslFlags)); + getTrustString(trust->sslFlags)); printf("CKA_TRUST_EMAIL_PROTECTION CK_TRUST %s\n", - getTrustString(trust->emailFlags)); + getTrustString(trust->emailFlags)); printf("CKA_TRUST_CODE_SIGNING CK_TRUST %s\n", - getTrustString(trust->objectSigningFlags)); + getTrustString(trust->objectSigningFlags)); #ifdef notdef printf("CKA_TRUST_CLIENT_AUTH CK_TRUST CKT_NSS_TRUSTED\n"); printf("CKA_TRUST_DIGITAL_SIGNATURE CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n"); @@ -248,111 +252,113 @@ ConvertCertificate(SECItem *sdder, char *nickname, CERTCertTrust *trust, printf("CKA_TRUST_KEY_AGREEMENT CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n"); printf("CKA_TRUST_KEY_CERT_SIGN CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n"); #endif - + step_up = (trust->sslFlags & CERTDB_GOVT_APPROVED_CA); printf("CKA_TRUST_STEP_UP_APPROVED CK_BBOOL %s\n", - step_up ? "CK_TRUE" : "CK_FALSE"); + step_up ? "CK_TRUE" : "CK_FALSE"); PORT_Free(sdder->data); - return(rv); - + return (rv); } -void printheader() { +void +printheader() +{ printf("# \n" -"# This Source Code Form is subject to the terms of the Mozilla Public\n" -"# License, v. 2.0. If a copy of the MPL was not distributed with this\n" -"# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n" - "#\n" - "CVS_ID \"@(#) $RCSfile$ $Revision$ $Date$\"\n" - "\n" - "#\n" - "# certdata.txt\n" - "#\n" - "# This file contains the object definitions for the certs and other\n" - "# information \"built into\" NSS.\n" - "#\n" - "# Object definitions:\n" - "#\n" - "# Certificates\n" - "#\n" - "# -- Attribute -- -- type -- -- value --\n" - "# CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE\n" - "# CKA_TOKEN CK_BBOOL CK_TRUE\n" - "# CKA_PRIVATE CK_BBOOL CK_FALSE\n" - "# CKA_MODIFIABLE CK_BBOOL CK_FALSE\n" - "# CKA_LABEL UTF8 (varies)\n" - "# CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509\n" - "# CKA_SUBJECT DER+base64 (varies)\n" - "# CKA_ID byte array (varies)\n" - "# CKA_ISSUER DER+base64 (varies)\n" - "# CKA_SERIAL_NUMBER DER+base64 (varies)\n" - "# CKA_VALUE DER+base64 (varies)\n" - "# CKA_NSS_EMAIL ASCII7 (unused here)\n" - "#\n" - "# Trust\n" - "#\n" - "# -- Attribute -- -- type -- -- value --\n" - "# CKA_CLASS CK_OBJECT_CLASS CKO_TRUST\n" - "# CKA_TOKEN CK_BBOOL CK_TRUE\n" - "# CKA_PRIVATE CK_BBOOL CK_FALSE\n" - "# CKA_MODIFIABLE CK_BBOOL CK_FALSE\n" - "# CKA_LABEL UTF8 (varies)\n" - "# CKA_ISSUER DER+base64 (varies)\n" - "# CKA_SERIAL_NUMBER DER+base64 (varies)\n" - "# CKA_CERT_HASH binary+base64 (varies)\n" - "# CKA_EXPIRES CK_DATE (not used here)\n" - "# CKA_TRUST_DIGITAL_SIGNATURE CK_TRUST (varies)\n" - "# CKA_TRUST_NON_REPUDIATION CK_TRUST (varies)\n" - "# CKA_TRUST_KEY_ENCIPHERMENT CK_TRUST (varies)\n" - "# CKA_TRUST_DATA_ENCIPHERMENT CK_TRUST (varies)\n" - "# CKA_TRUST_KEY_AGREEMENT CK_TRUST (varies)\n" - "# CKA_TRUST_KEY_CERT_SIGN CK_TRUST (varies)\n" - "# CKA_TRUST_CRL_SIGN CK_TRUST (varies)\n" - "# CKA_TRUST_SERVER_AUTH CK_TRUST (varies)\n" - "# CKA_TRUST_CLIENT_AUTH CK_TRUST (varies)\n" - "# CKA_TRUST_CODE_SIGNING CK_TRUST (varies)\n" - "# CKA_TRUST_EMAIL_PROTECTION CK_TRUST (varies)\n" - "# CKA_TRUST_IPSEC_END_SYSTEM CK_TRUST (varies)\n" - "# CKA_TRUST_IPSEC_TUNNEL CK_TRUST (varies)\n" - "# CKA_TRUST_IPSEC_USER CK_TRUST (varies)\n" - "# CKA_TRUST_TIME_STAMPING CK_TRUST (varies)\n" - "# (other trust attributes can be defined)\n" - "#\n" - "\n" - "#\n" - "# The object to tell NSS that this is a root list and we don't\n" - "# have to go looking for others.\n" - "#\n" - "BEGINDATA\n" - "CKA_CLASS CK_OBJECT_CLASS CKO_NSS_BUILTIN_ROOT_LIST\n" - "CKA_TOKEN CK_BBOOL CK_TRUE\n" - "CKA_PRIVATE CK_BBOOL CK_FALSE\n" - "CKA_MODIFIABLE CK_BBOOL CK_FALSE\n" - "CKA_LABEL UTF8 \"Mozilla Builtin Roots\"\n"); + "# This Source Code Form is subject to the terms of the Mozilla Public\n" + "# License, v. 2.0. If a copy of the MPL was not distributed with this\n" + "# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n" + "#\n" + "CVS_ID \"@(#) $RCSfile$ $Revision$ $Date$\"\n" + "\n" + "#\n" + "# certdata.txt\n" + "#\n" + "# This file contains the object definitions for the certs and other\n" + "# information \"built into\" NSS.\n" + "#\n" + "# Object definitions:\n" + "#\n" + "# Certificates\n" + "#\n" + "# -- Attribute -- -- type -- -- value --\n" + "# CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE\n" + "# CKA_TOKEN CK_BBOOL CK_TRUE\n" + "# CKA_PRIVATE CK_BBOOL CK_FALSE\n" + "# CKA_MODIFIABLE CK_BBOOL CK_FALSE\n" + "# CKA_LABEL UTF8 (varies)\n" + "# CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509\n" + "# CKA_SUBJECT DER+base64 (varies)\n" + "# CKA_ID byte array (varies)\n" + "# CKA_ISSUER DER+base64 (varies)\n" + "# CKA_SERIAL_NUMBER DER+base64 (varies)\n" + "# CKA_VALUE DER+base64 (varies)\n" + "# CKA_NSS_EMAIL ASCII7 (unused here)\n" + "#\n" + "# Trust\n" + "#\n" + "# -- Attribute -- -- type -- -- value --\n" + "# CKA_CLASS CK_OBJECT_CLASS CKO_TRUST\n" + "# CKA_TOKEN CK_BBOOL CK_TRUE\n" + "# CKA_PRIVATE CK_BBOOL CK_FALSE\n" + "# CKA_MODIFIABLE CK_BBOOL CK_FALSE\n" + "# CKA_LABEL UTF8 (varies)\n" + "# CKA_ISSUER DER+base64 (varies)\n" + "# CKA_SERIAL_NUMBER DER+base64 (varies)\n" + "# CKA_CERT_HASH binary+base64 (varies)\n" + "# CKA_EXPIRES CK_DATE (not used here)\n" + "# CKA_TRUST_DIGITAL_SIGNATURE CK_TRUST (varies)\n" + "# CKA_TRUST_NON_REPUDIATION CK_TRUST (varies)\n" + "# CKA_TRUST_KEY_ENCIPHERMENT CK_TRUST (varies)\n" + "# CKA_TRUST_DATA_ENCIPHERMENT CK_TRUST (varies)\n" + "# CKA_TRUST_KEY_AGREEMENT CK_TRUST (varies)\n" + "# CKA_TRUST_KEY_CERT_SIGN CK_TRUST (varies)\n" + "# CKA_TRUST_CRL_SIGN CK_TRUST (varies)\n" + "# CKA_TRUST_SERVER_AUTH CK_TRUST (varies)\n" + "# CKA_TRUST_CLIENT_AUTH CK_TRUST (varies)\n" + "# CKA_TRUST_CODE_SIGNING CK_TRUST (varies)\n" + "# CKA_TRUST_EMAIL_PROTECTION CK_TRUST (varies)\n" + "# CKA_TRUST_IPSEC_END_SYSTEM CK_TRUST (varies)\n" + "# CKA_TRUST_IPSEC_TUNNEL CK_TRUST (varies)\n" + "# CKA_TRUST_IPSEC_USER CK_TRUST (varies)\n" + "# CKA_TRUST_TIME_STAMPING CK_TRUST (varies)\n" + "# (other trust attributes can be defined)\n" + "#\n" + "\n" + "#\n" + "# The object to tell NSS that this is a root list and we don't\n" + "# have to go looking for others.\n" + "#\n" + "BEGINDATA\n" + "CKA_CLASS CK_OBJECT_CLASS CKO_NSS_BUILTIN_ROOT_LIST\n" + "CKA_TOKEN CK_BBOOL CK_TRUE\n" + "CKA_PRIVATE CK_BBOOL CK_FALSE\n" + "CKA_MODIFIABLE CK_BBOOL CK_FALSE\n" + "CKA_LABEL UTF8 \"Mozilla Builtin Roots\"\n"); } -static void Usage(char *progName) +static void +Usage(char *progName) { fprintf(stderr, "%s -t trust -n nickname [-i certfile] [-c] [-h]\n", progName); - fprintf(stderr, + fprintf(stderr, "\tRead a der-encoded cert from certfile or stdin, and output\n" "\tit to stdout in a format suitable for the builtin root module.\n" "\tExample: %s -n MyCA -t \"C,C,C\" -i myca.der >> certdata.txt\n", progName); fprintf(stderr, "%s -D -n label [-i certfile]\n", progName); - fprintf(stderr, + fprintf(stderr, "\tRead a der-encoded cert from certfile or stdin, and output\n" "\ta distrust record.\n" - "\t(-D is equivalent to -t p,p,p -c -h)\n"); + "\t(-D is equivalent to -t p,p,p -c -h)\n"); fprintf(stderr, "%s -C -e crl-entry-number -n label [-i crlfile]\n", progName); - fprintf(stderr, + fprintf(stderr, "\tRead a CRL from crlfile or stdin, and output\n" "\ta distrust record (issuer+serial).\n" - "\t(-C implies -c -h)\n"); + "\t(-C implies -c -h)\n"); fprintf(stderr, "%-15s trust flags (cCTpPuw).\n", "-t trust"); - fprintf(stderr, "%-15s nickname to assign to builtin cert, or\n", - "-n nickname"); + fprintf(stderr, "%-15s nickname to assign to builtin cert, or\n", + "-n nickname"); fprintf(stderr, "%-15s a label for the distrust record.\n", ""); fprintf(stderr, "%-15s exclude the certificate (only add a trust record)\n", "-c"); fprintf(stderr, "%-15s exclude hash from trust record\n", "-h"); @@ -376,18 +382,19 @@ enum { }; static secuCommandFlag addbuiltin_options[] = -{ - { /* opt_Input */ 'i', PR_TRUE, 0, PR_FALSE }, - { /* opt_Nickname */ 'n', PR_TRUE, 0, PR_FALSE }, - { /* opt_Trust */ 't', PR_TRUE, 0, PR_FALSE }, - { /* opt_Distrust */ 'D', PR_FALSE, 0, PR_FALSE }, - { /* opt_ExcludeCert */ 'c', PR_FALSE, 0, PR_FALSE }, - { /* opt_ExcludeHash */ 'h', PR_FALSE, 0, PR_FALSE }, - { /* opt_DistrustCRL */ 'C', PR_FALSE, 0, PR_FALSE }, - { /* opt_CRLEnry */ 'e', PR_TRUE, 0, PR_FALSE }, -}; - -int main(int argc, char **argv) + { + { /* opt_Input */ 'i', PR_TRUE, 0, PR_FALSE }, + { /* opt_Nickname */ 'n', PR_TRUE, 0, PR_FALSE }, + { /* opt_Trust */ 't', PR_TRUE, 0, PR_FALSE }, + { /* opt_Distrust */ 'D', PR_FALSE, 0, PR_FALSE }, + { /* opt_ExcludeCert */ 'c', PR_FALSE, 0, PR_FALSE }, + { /* opt_ExcludeHash */ 'h', PR_FALSE, 0, PR_FALSE }, + { /* opt_DistrustCRL */ 'C', PR_FALSE, 0, PR_FALSE }, + { /* opt_CRLEnry */ 'e', PR_TRUE, 0, PR_FALSE }, + }; + +int +main(int argc, char **argv) { SECStatus rv; char *nickname = NULL; @@ -401,44 +408,43 @@ int main(int argc, char **argv) PRBool decodeTrust = PR_FALSE; secuCommand addbuiltin = { 0 }; - addbuiltin.numOptions = sizeof(addbuiltin_options)/sizeof(secuCommandFlag); + addbuiltin.numOptions = sizeof(addbuiltin_options) / sizeof(secuCommandFlag); addbuiltin.options = addbuiltin_options; progName = strrchr(argv[0], '/'); - progName = progName ? progName+1 : argv[0]; + progName = progName ? progName + 1 : argv[0]; rv = SECU_ParseCommandLine(argc, argv, progName, &addbuiltin); if (rv != SECSuccess) - Usage(progName); - + Usage(progName); + if (addbuiltin.options[opt_Trust].activated) - ++mutuallyExclusiveOpts; + ++mutuallyExclusiveOpts; if (addbuiltin.options[opt_Distrust].activated) - ++mutuallyExclusiveOpts; + ++mutuallyExclusiveOpts; if (addbuiltin.options[opt_DistrustCRL].activated) - ++mutuallyExclusiveOpts; + ++mutuallyExclusiveOpts; if (mutuallyExclusiveOpts != 1) { fprintf(stderr, "%s: you must specify exactly one of -t or -D or -C\n", progName); Usage(progName); } - + if (addbuiltin.options[opt_DistrustCRL].activated) { - if (!addbuiltin.options[opt_CRLEnry].activated) { - fprintf(stderr, "%s: you must specify the CRL entry number.\n", - progName); - Usage(progName); - } - else { - crlentry = atoi(addbuiltin.options[opt_CRLEnry].arg); - if (crlentry < 1) { - fprintf(stderr, "%s: The CRL entry number must be > 0.\n", - progName); - Usage(progName); - } - } + if (!addbuiltin.options[opt_CRLEnry].activated) { + fprintf(stderr, "%s: you must specify the CRL entry number.\n", + progName); + Usage(progName); + } else { + crlentry = atoi(addbuiltin.options[opt_CRLEnry].arg); + if (crlentry < 1) { + fprintf(stderr, "%s: The CRL entry number must be > 0.\n", + progName); + Usage(progName); + } + } } if (!addbuiltin.options[opt_Nickname].activated) { @@ -448,27 +454,27 @@ int main(int argc, char **argv) } if (addbuiltin.options[opt_Input].activated) { - infile = PR_Open(addbuiltin.options[opt_Input].arg, PR_RDONLY, 00660); - if (!infile) { - fprintf(stderr, "%s: failed to open input file.\n", progName); - exit(1); - } + infile = PR_Open(addbuiltin.options[opt_Input].arg, PR_RDONLY, 00660); + if (!infile) { + fprintf(stderr, "%s: failed to open input file.\n", progName); + exit(1); + } } else { #if defined(WIN32) - /* If we're going to read binary data from stdin, we must put stdin + /* If we're going to read binary data from stdin, we must put stdin ** into O_BINARY mode or else incoming \r\n's will become \n's, ** and latin-1 characters will be altered. */ - int smrv = _setmode(_fileno(stdin), _O_BINARY); - if (smrv == -1) { - fprintf(stderr, - "%s: Cannot change stdin to binary mode. Use -i option instead.\n", - progName); - exit(1); - } + int smrv = _setmode(_fileno(stdin), _O_BINARY); + if (smrv == -1) { + fprintf(stderr, + "%s: Cannot change stdin to binary mode. Use -i option instead.\n", + progName); + exit(1); + } #endif - infile = PR_STDIN; + infile = PR_STDIN; } #if defined(WIN32) @@ -476,70 +482,68 @@ int main(int argc, char **argv) ** carriage returns. */ { - int smrv = _setmode(_fileno(stdout), _O_BINARY); - if (smrv == -1) { - fprintf(stderr, "%s: Cannot change stdout to binary mode.\n", progName); - exit(1); - } + int smrv = _setmode(_fileno(stdout), _O_BINARY); + if (smrv == -1) { + fprintf(stderr, "%s: Cannot change stdout to binary mode.\n", progName); + exit(1); + } } #endif nickname = strdup(addbuiltin.options[opt_Nickname].arg); - + NSS_NoDB_Init(NULL); if (addbuiltin.options[opt_Distrust].activated || addbuiltin.options[opt_DistrustCRL].activated) { - addbuiltin.options[opt_ExcludeCert].activated = PR_TRUE; - addbuiltin.options[opt_ExcludeHash].activated = PR_TRUE; + addbuiltin.options[opt_ExcludeCert].activated = PR_TRUE; + addbuiltin.options[opt_ExcludeHash].activated = PR_TRUE; } - + if (addbuiltin.options[opt_Distrust].activated) { trusts = strdup("p,p,p"); - decodeTrust = PR_TRUE; - } - else if (addbuiltin.options[opt_Trust].activated) { + decodeTrust = PR_TRUE; + } else if (addbuiltin.options[opt_Trust].activated) { trusts = strdup(addbuiltin.options[opt_Trust].arg); - decodeTrust = PR_TRUE; + decodeTrust = PR_TRUE; } - + if (decodeTrust) { - rv = CERT_DecodeTrustString(&trust, trusts); - if (rv) { - fprintf(stderr, "%s: incorrectly formatted trust string.\n", progName); - Usage(progName); - } + rv = CERT_DecodeTrustString(&trust, trusts); + if (rv) { + fprintf(stderr, "%s: incorrectly formatted trust string.\n", progName); + Usage(progName); + } } - + if (addbuiltin.options[opt_Trust].activated && addbuiltin.options[opt_ExcludeHash].activated) { - if ((trust.sslFlags | trust.emailFlags | trust.objectSigningFlags) - != CERTDB_TERMINAL_RECORD) { - fprintf(stderr, "%s: Excluding the hash only allowed with distrust.\n", progName); - Usage(progName); - } + if ((trust.sslFlags | trust.emailFlags | trust.objectSigningFlags) != + CERTDB_TERMINAL_RECORD) { + fprintf(stderr, "%s: Excluding the hash only allowed with distrust.\n", progName); + Usage(progName); + } } SECU_FileToItem(&derItem, infile); - + /*printheader();*/ - + if (addbuiltin.options[opt_DistrustCRL].activated) { - rv = ConvertCRLEntry(&derItem, crlentry, nickname); - } - else { - rv = ConvertCertificate(&derItem, nickname, &trust, - addbuiltin.options[opt_ExcludeCert].activated, - addbuiltin.options[opt_ExcludeHash].activated); - if (rv) { - fprintf(stderr, "%s: failed to convert certificate.\n", progName); - exit(1); - } + rv = ConvertCRLEntry(&derItem, crlentry, nickname); + } else { + rv = ConvertCertificate(&derItem, nickname, &trust, + addbuiltin.options[opt_ExcludeCert].activated, + addbuiltin.options[opt_ExcludeHash].activated); + if (rv) { + fprintf(stderr, "%s: failed to convert certificate.\n", progName); + exit(1); + } } - + if (NSS_Shutdown() != SECSuccess) { exit(1); } - return(SECSuccess); + return (SECSuccess); } diff --git a/cmd/atob/atob.c b/cmd/atob/atob.c index cdc9dd6ac9..115b0e9a0f 100644 --- a/cmd/atob/atob.c +++ b/cmd/atob/atob.c @@ -9,8 +9,8 @@ #if defined(XP_WIN) || (defined(__sun) && !defined(SVR4)) #if !defined(WIN32) -extern int fread(char *, size_t, size_t, FILE*); -extern int fwrite(char *, size_t, size_t, FILE*); +extern int fread(char *, size_t, size_t, FILE *); +extern int fwrite(char *, size_t, size_t, FILE *); extern int fprintf(FILE *, char *, ...); #endif #endif @@ -20,16 +20,16 @@ extern int fprintf(FILE *, char *, ...); #include "io.h" #endif -static PRInt32 -output_binary (void *arg, const unsigned char *obuf, PRInt32 size) +static PRInt32 +output_binary(void *arg, const unsigned char *obuf, PRInt32 size) { FILE *outFile = arg; int nb; nb = fwrite(obuf, 1, size, outFile); if (nb != size) { - PORT_SetError(SEC_ERROR_IO); - return -1; + PORT_SetError(SEC_ERROR_IO); + return -1; } return nb; @@ -38,12 +38,11 @@ output_binary (void *arg, const unsigned char *obuf, PRInt32 size) static PRBool isBase64Char(char c) { - return ((c >= 'A' && c <= 'Z') - || (c >= 'a' && c <= 'z') - || (c >= '0' && c <= '9') - || c == '+' - || c == '/' - || c == '='); + return ((c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || + c == '+' || c == '/' || + c == '='); } static SECStatus @@ -56,57 +55,61 @@ decode_file(FILE *outFile, FILE *inFile) cx = NSSBase64Decoder_Create(output_binary, outFile); if (!cx) { - return -1; + return -1; } for (;;) { - if (feof(inFile)) break; - if (!fgets(ibuf, sizeof(ibuf), inFile)) { - if (ferror(inFile)) { - PORT_SetError(SEC_ERROR_IO); - goto loser; - } - /* eof */ - break; - } - for (ptr = ibuf; *ptr; ++ptr) { - char c = *ptr; - if (c == '\n' || c == '\r') { - break; /* found end of line */ - } - if (!isBase64Char(c)) { - ptr = ibuf; /* ignore line */ - break; - } - } - if (ibuf == ptr) { - continue; /* skip empty or non-base64 line */ - } - - status = NSSBase64Decoder_Update(cx, ibuf, ptr-ibuf); - if (status != SECSuccess) goto loser; + if (feof(inFile)) + break; + if (!fgets(ibuf, sizeof(ibuf), inFile)) { + if (ferror(inFile)) { + PORT_SetError(SEC_ERROR_IO); + goto loser; + } + /* eof */ + break; + } + for (ptr = ibuf; *ptr; ++ptr) { + char c = *ptr; + if (c == '\n' || c == '\r') { + break; /* found end of line */ + } + if (!isBase64Char(c)) { + ptr = ibuf; /* ignore line */ + break; + } + } + if (ibuf == ptr) { + continue; /* skip empty or non-base64 line */ + } + + status = NSSBase64Decoder_Update(cx, ibuf, ptr - ibuf); + if (status != SECSuccess) + goto loser; } return NSSBase64Decoder_Destroy(cx, PR_FALSE); - loser: - (void) NSSBase64Decoder_Destroy(cx, PR_TRUE); +loser: + (void)NSSBase64Decoder_Destroy(cx, PR_TRUE); return status; } -static void Usage(char *progName) +static void +Usage(char *progName) { fprintf(stderr, - "Usage: %s [-i input] [-o output]\n", - progName); + "Usage: %s [-i input] [-o output]\n", + progName); fprintf(stderr, "%-20s Define an input file to use (default is stdin)\n", - "-i input"); + "-i input"); fprintf(stderr, "%-20s Define an output file to use (default is stdout)\n", - "-o output"); + "-o output"); exit(-1); } -int main(int argc, char **argv) +int +main(int argc, char **argv) { char *progName; SECStatus rv; @@ -117,54 +120,55 @@ int main(int argc, char **argv) inFile = 0; outFile = 0; progName = strrchr(argv[0], '/'); - progName = progName ? progName+1 : argv[0]; + progName = progName ? progName + 1 : argv[0]; /* Parse command line arguments */ optstate = PL_CreateOptState(argc, argv, "?hi:o:"); while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { - switch (optstate->option) { - case '?': - case 'h': - Usage(progName); - break; - - case 'i': - inFile = fopen(optstate->value, "r"); - if (!inFile) { - fprintf(stderr, "%s: unable to open \"%s\" for reading\n", - progName, optstate->value); - return -1; - } - break; - - case 'o': - outFile = fopen(optstate->value, "wb"); - if (!outFile) { - fprintf(stderr, "%s: unable to open \"%s\" for writing\n", - progName, optstate->value); - return -1; - } - break; - } + switch (optstate->option) { + case '?': + case 'h': + Usage(progName); + break; + + case 'i': + inFile = fopen(optstate->value, "r"); + if (!inFile) { + fprintf(stderr, "%s: unable to open \"%s\" for reading\n", + progName, optstate->value); + return -1; + } + break; + + case 'o': + outFile = fopen(optstate->value, "wb"); + if (!outFile) { + fprintf(stderr, "%s: unable to open \"%s\" for writing\n", + progName, optstate->value); + return -1; + } + break; + } } - if (!inFile) inFile = stdin; + if (!inFile) + inFile = stdin; if (!outFile) { #if defined(WIN32) - int smrv = _setmode(_fileno(stdout), _O_BINARY); - if (smrv == -1) { - fprintf(stderr, - "%s: Cannot change stdout to binary mode. Use -o option instead.\n", - progName); - return smrv; - } + int smrv = _setmode(_fileno(stdout), _O_BINARY); + if (smrv == -1) { + fprintf(stderr, + "%s: Cannot change stdout to binary mode. Use -o option instead.\n", + progName); + return smrv; + } #endif - outFile = stdout; + outFile = stdout; } rv = decode_file(outFile, inFile); if (rv != SECSuccess) { - fprintf(stderr, "%s: lossage: error=%d errno=%d\n", - progName, PORT_GetError(), errno); - return -1; + fprintf(stderr, "%s: lossage: error=%d errno=%d\n", + progName, PORT_GetError(), errno); + return -1; } return 0; } diff --git a/cmd/bltest/blapitest.c b/cmd/bltest/blapitest.c index 050bebfd92..e02b3476f0 100644 --- a/cmd/bltest/blapitest.c +++ b/cmd/bltest/blapitest.c @@ -23,10 +23,10 @@ #ifndef NSS_DISABLE_ECC #include "ecl-curve.h" -SECStatus EC_DecodeParams(const SECItem *encodedParams, - ECParams **ecparams); +SECStatus EC_DecodeParams(const SECItem *encodedParams, + ECParams **ecparams); SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams, - const ECParams *srcParams); + const ECParams *srcParams); #endif char *progName; @@ -36,48 +36,49 @@ char *testdir = NULL; #define WORDSIZE sizeof(unsigned long) -#define CHECKERROR(rv, ln) \ - if (rv) { \ - PRErrorCode prerror = PR_GetError(); \ - PR_fprintf(PR_STDERR, "%s: ERR %d (%s) at line %d.\n", progName, \ - prerror, PORT_ErrorToString(prerror), ln); \ - exit(-1); \ +#define CHECKERROR(rv, ln) \ + if (rv) { \ + PRErrorCode prerror = PR_GetError(); \ + PR_fprintf(PR_STDERR, "%s: ERR %d (%s) at line %d.\n", progName, \ + prerror, PORT_ErrorToString(prerror), ln); \ + exit(-1); \ } /* Macros for performance timing. */ #define TIMESTART() \ time1 = PR_IntervalNow(); -#define TIMEFINISH(time, reps) \ +#define TIMEFINISH(time, reps) \ time2 = (PRIntervalTime)(PR_IntervalNow() - time1); \ - time1 = PR_IntervalToMilliseconds(time2); \ - time = ((double)(time1))/reps; - -#define TIMEMARK(seconds) \ - time1 = PR_SecondsToInterval(seconds); \ - { \ - PRInt64 tmp; \ - if (time2 == 0) { \ - time2 = 1; \ - } \ - LL_DIV(tmp, time1, time2); \ - if (tmp < 10) { \ - if (tmp == 0) { \ - opsBetweenChecks = 1; \ - } else { \ + time1 = PR_IntervalToMilliseconds(time2); \ + time = ((double)(time1)) / reps; + +#define TIMEMARK(seconds) \ + time1 = PR_SecondsToInterval(seconds); \ + { \ + PRInt64 tmp; \ + if (time2 == 0) { \ + time2 = 1; \ + } \ + LL_DIV(tmp, time1, time2); \ + if (tmp < 10) { \ + if (tmp == 0) { \ + opsBetweenChecks = 1; \ + } else { \ LL_L2I(opsBetweenChecks, tmp); \ - } \ - } else { \ - opsBetweenChecks = 10; \ - } \ - } \ - time2 = time1; \ + } \ + } else { \ + opsBetweenChecks = 10; \ + } \ + } \ + time2 = time1; \ time1 = PR_IntervalNow(); #define TIMETOFINISH() \ PR_IntervalNow() - time1 >= time2 -static void Usage() +static void +Usage() { #define PRINTUSAGE(subject, option, predicate) \ fprintf(stderr, "%10s %s\t%s\n", subject, option, predicate); @@ -85,108 +86,108 @@ static void Usage() PRINTUSAGE(progName, "[-DEHSVR]", "List available cipher modes"); /* XXX */ fprintf(stderr, "\n"); PRINTUSAGE(progName, "-E -m mode ", "Encrypt a buffer"); - PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]"); - PRINTUSAGE("", "", "[-b bufsize] [-g keysize] [-e exp] [-r rounds]"); - PRINTUSAGE("", "", "[-w wordsize] [-p repetitions | -5 time_interval]"); - PRINTUSAGE("", "", "[-4 th_num]"); - PRINTUSAGE("", "-m", "cipher mode to use"); - PRINTUSAGE("", "-i", "file which contains input buffer"); - PRINTUSAGE("", "-o", "file for output buffer"); - PRINTUSAGE("", "-k", "file which contains key"); - PRINTUSAGE("", "-v", "file which contains initialization vector"); - PRINTUSAGE("", "-b", "size of input buffer"); - PRINTUSAGE("", "-g", "key size (in bytes)"); - PRINTUSAGE("", "-p", "do performance test"); - PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); - PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); - PRINTUSAGE("", "--aad", "File with contains additional auth data"); + PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]"); + PRINTUSAGE("", "", "[-b bufsize] [-g keysize] [-e exp] [-r rounds]"); + PRINTUSAGE("", "", "[-w wordsize] [-p repetitions | -5 time_interval]"); + PRINTUSAGE("", "", "[-4 th_num]"); + PRINTUSAGE("", "-m", "cipher mode to use"); + PRINTUSAGE("", "-i", "file which contains input buffer"); + PRINTUSAGE("", "-o", "file for output buffer"); + PRINTUSAGE("", "-k", "file which contains key"); + PRINTUSAGE("", "-v", "file which contains initialization vector"); + PRINTUSAGE("", "-b", "size of input buffer"); + PRINTUSAGE("", "-g", "key size (in bytes)"); + PRINTUSAGE("", "-p", "do performance test"); + PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); + PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); + PRINTUSAGE("", "--aad", "File with contains additional auth data"); PRINTUSAGE("(rsa)", "-e", "rsa public exponent"); PRINTUSAGE("(rc5)", "-r", "number of rounds"); PRINTUSAGE("(rc5)", "-w", "wordsize (32 or 64)"); fprintf(stderr, "\n"); PRINTUSAGE(progName, "-D -m mode", "Decrypt a buffer"); - PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]"); - PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); - PRINTUSAGE("", "-m", "cipher mode to use"); - PRINTUSAGE("", "-i", "file which contains input buffer"); - PRINTUSAGE("", "-o", "file for output buffer"); - PRINTUSAGE("", "-k", "file which contains key"); - PRINTUSAGE("", "-v", "file which contains initialization vector"); - PRINTUSAGE("", "-p", "do performance test"); - PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); - PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); - PRINTUSAGE("", "--aad", "File with contains additional auth data"); + PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]"); + PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); + PRINTUSAGE("", "-m", "cipher mode to use"); + PRINTUSAGE("", "-i", "file which contains input buffer"); + PRINTUSAGE("", "-o", "file for output buffer"); + PRINTUSAGE("", "-k", "file which contains key"); + PRINTUSAGE("", "-v", "file which contains initialization vector"); + PRINTUSAGE("", "-p", "do performance test"); + PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); + PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); + PRINTUSAGE("", "--aad", "File with contains additional auth data"); fprintf(stderr, "\n"); PRINTUSAGE(progName, "-H -m mode", "Hash a buffer"); - PRINTUSAGE("", "", "[-i plaintext] [-o hash]"); - PRINTUSAGE("", "", "[-b bufsize]"); - PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); - PRINTUSAGE("", "-m", "cipher mode to use"); - PRINTUSAGE("", "-i", "file which contains input buffer"); - PRINTUSAGE("", "-o", "file for hash"); - PRINTUSAGE("", "-b", "size of input buffer"); - PRINTUSAGE("", "-p", "do performance test"); - PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); - PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); + PRINTUSAGE("", "", "[-i plaintext] [-o hash]"); + PRINTUSAGE("", "", "[-b bufsize]"); + PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); + PRINTUSAGE("", "-m", "cipher mode to use"); + PRINTUSAGE("", "-i", "file which contains input buffer"); + PRINTUSAGE("", "-o", "file for hash"); + PRINTUSAGE("", "-b", "size of input buffer"); + PRINTUSAGE("", "-p", "do performance test"); + PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); + PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); fprintf(stderr, "\n"); PRINTUSAGE(progName, "-S -m mode", "Sign a buffer"); - PRINTUSAGE("", "", "[-i plaintext] [-o signature] [-k key]"); - PRINTUSAGE("", "", "[-b bufsize]"); + PRINTUSAGE("", "", "[-i plaintext] [-o signature] [-k key]"); + PRINTUSAGE("", "", "[-b bufsize]"); #ifndef NSS_DISABLE_ECC - PRINTUSAGE("", "", "[-n curvename]"); + PRINTUSAGE("", "", "[-n curvename]"); #endif - PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); - PRINTUSAGE("", "-m", "cipher mode to use"); - PRINTUSAGE("", "-i", "file which contains input buffer"); - PRINTUSAGE("", "-o", "file for signature"); - PRINTUSAGE("", "-k", "file which contains key"); + PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); + PRINTUSAGE("", "-m", "cipher mode to use"); + PRINTUSAGE("", "-i", "file which contains input buffer"); + PRINTUSAGE("", "-o", "file for signature"); + PRINTUSAGE("", "-k", "file which contains key"); #ifndef NSS_DISABLE_ECC - PRINTUSAGE("", "-n", "name of curve for EC key generation; one of:"); - PRINTUSAGE("", "", " sect163k1, nistk163, sect163r1, sect163r2,"); - PRINTUSAGE("", "", " nistb163, sect193r1, sect193r2, sect233k1, nistk233,"); - PRINTUSAGE("", "", " sect233r1, nistb233, sect239k1, sect283k1, nistk283,"); - PRINTUSAGE("", "", " sect283r1, nistb283, sect409k1, nistk409, sect409r1,"); - PRINTUSAGE("", "", " nistb409, sect571k1, nistk571, sect571r1, nistb571,"); - PRINTUSAGE("", "", " secp160k1, secp160r1, secp160r2, secp192k1, secp192r1,"); - PRINTUSAGE("", "", " nistp192, secp224k1, secp224r1, nistp224, secp256k1,"); - PRINTUSAGE("", "", " secp256r1, nistp256, secp384r1, nistp384, secp521r1,"); - PRINTUSAGE("", "", " nistp521, prime192v1, prime192v2, prime192v3,"); - PRINTUSAGE("", "", " prime239v1, prime239v2, prime239v3, c2pnb163v1,"); - PRINTUSAGE("", "", " c2pnb163v2, c2pnb163v3, c2pnb176v1, c2tnb191v1,"); - PRINTUSAGE("", "", " c2tnb191v2, c2tnb191v3, c2onb191v4, c2onb191v5,"); - PRINTUSAGE("", "", " c2pnb208w1, c2tnb239v1, c2tnb239v2, c2tnb239v3,"); - PRINTUSAGE("", "", " c2onb239v4, c2onb239v5, c2pnb272w1, c2pnb304w1,"); - PRINTUSAGE("", "", " c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1,"); - PRINTUSAGE("", "", " secp112r2, secp128r1, secp128r2, sect113r1, sect113r2,"); - PRINTUSAGE("", "", " sect131r1, sect131r2"); + PRINTUSAGE("", "-n", "name of curve for EC key generation; one of:"); + PRINTUSAGE("", "", " sect163k1, nistk163, sect163r1, sect163r2,"); + PRINTUSAGE("", "", " nistb163, sect193r1, sect193r2, sect233k1, nistk233,"); + PRINTUSAGE("", "", " sect233r1, nistb233, sect239k1, sect283k1, nistk283,"); + PRINTUSAGE("", "", " sect283r1, nistb283, sect409k1, nistk409, sect409r1,"); + PRINTUSAGE("", "", " nistb409, sect571k1, nistk571, sect571r1, nistb571,"); + PRINTUSAGE("", "", " secp160k1, secp160r1, secp160r2, secp192k1, secp192r1,"); + PRINTUSAGE("", "", " nistp192, secp224k1, secp224r1, nistp224, secp256k1,"); + PRINTUSAGE("", "", " secp256r1, nistp256, secp384r1, nistp384, secp521r1,"); + PRINTUSAGE("", "", " nistp521, prime192v1, prime192v2, prime192v3,"); + PRINTUSAGE("", "", " prime239v1, prime239v2, prime239v3, c2pnb163v1,"); + PRINTUSAGE("", "", " c2pnb163v2, c2pnb163v3, c2pnb176v1, c2tnb191v1,"); + PRINTUSAGE("", "", " c2tnb191v2, c2tnb191v3, c2onb191v4, c2onb191v5,"); + PRINTUSAGE("", "", " c2pnb208w1, c2tnb239v1, c2tnb239v2, c2tnb239v3,"); + PRINTUSAGE("", "", " c2onb239v4, c2onb239v5, c2pnb272w1, c2pnb304w1,"); + PRINTUSAGE("", "", " c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1,"); + PRINTUSAGE("", "", " secp112r2, secp128r1, secp128r2, sect113r1, sect113r2,"); + PRINTUSAGE("", "", " sect131r1, sect131r2"); #endif - PRINTUSAGE("", "-p", "do performance test"); - PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); - PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); + PRINTUSAGE("", "-p", "do performance test"); + PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); + PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); fprintf(stderr, "\n"); PRINTUSAGE(progName, "-V -m mode", "Verify a signed buffer"); - PRINTUSAGE("", "", "[-i plaintext] [-s signature] [-k key]"); - PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); - PRINTUSAGE("", "-m", "cipher mode to use"); - PRINTUSAGE("", "-i", "file which contains input buffer"); - PRINTUSAGE("", "-s", "file which contains signature of input buffer"); - PRINTUSAGE("", "-k", "file which contains key"); - PRINTUSAGE("", "-p", "do performance test"); - PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); - PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); + PRINTUSAGE("", "", "[-i plaintext] [-s signature] [-k key]"); + PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]"); + PRINTUSAGE("", "-m", "cipher mode to use"); + PRINTUSAGE("", "-i", "file which contains input buffer"); + PRINTUSAGE("", "-s", "file which contains signature of input buffer"); + PRINTUSAGE("", "-k", "file which contains key"); + PRINTUSAGE("", "-p", "do performance test"); + PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads"); + PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)"); fprintf(stderr, "\n"); - PRINTUSAGE(progName, "-N -m mode -b bufsize", - "Create a nonce plaintext and key"); - PRINTUSAGE("", "", "[-g keysize] [-u cxreps]"); - PRINTUSAGE("", "-g", "key size (in bytes)"); - PRINTUSAGE("", "-u", "number of repetitions of context creation"); + PRINTUSAGE(progName, "-N -m mode -b bufsize", + "Create a nonce plaintext and key"); + PRINTUSAGE("", "", "[-g keysize] [-u cxreps]"); + PRINTUSAGE("", "-g", "key size (in bytes)"); + PRINTUSAGE("", "-u", "number of repetitions of context creation"); fprintf(stderr, "\n"); - PRINTUSAGE(progName, "-R [-g keysize] [-e exp]", - "Test the RSA populate key function"); - PRINTUSAGE("", "", "[-r repetitions]"); - PRINTUSAGE("", "-g", "key size (in bytes)"); - PRINTUSAGE("", "-e", "rsa public exponent"); - PRINTUSAGE("", "-r", "repetitions of the test"); + PRINTUSAGE(progName, "-R [-g keysize] [-e exp]", + "Test the RSA populate key function"); + PRINTUSAGE("", "", "[-r repetitions]"); + PRINTUSAGE("", "-g", "key size (in bytes)"); + PRINTUSAGE("", "-e", "rsa public exponent"); + PRINTUSAGE("", "-r", "repetitions of the test"); fprintf(stderr, "\n"); PRINTUSAGE(progName, "-F", "Run the FIPS self-test"); fprintf(stderr, "\n"); @@ -199,7 +200,7 @@ static void Usage() /* XXX argh */ struct item_with_arena { - SECItem *item; + SECItem *item; PLArenaPool *arena; }; @@ -211,13 +212,13 @@ get_binary(void *arg, const unsigned char *ibuf, PRInt32 size) SECItem *tmp; int index; if (binary->data == NULL) { - tmp = SECITEM_AllocItem(it->arena, NULL, size); - binary->data = tmp->data; - binary->len = tmp->len; - index = 0; + tmp = SECITEM_AllocItem(it->arena, NULL, size); + binary->data = tmp->data; + binary->len = tmp->len; + index = 0; } else { - SECITEM_ReallocItem(NULL, binary, binary->len, binary->len + size); - index = binary->len; + SECITEM_ReallocItem(NULL, binary, binary->len, binary->len + size); + index = binary->len; } PORT_Memcpy(&binary->data[index], ibuf, size); return binary->len; @@ -234,8 +235,8 @@ atob(SECItem *ascii, SECItem *binary, PLArenaPool *arena) binary->len = 0; it.item = binary; it.arena = arena; - len = (strncmp((const char *)&ascii->data[ascii->len-2],"\r\n",2)) ? - ascii->len : ascii->len-2; + len = (strncmp((const char *)&ascii->data[ascii->len - 2], "\r\n", 2)) ? ascii->len + : ascii->len - 2; cx = NSSBase64Decoder_Create(get_binary, &it); status = NSSBase64Decoder_Update(cx, (const char *)ascii->data, len); status = NSSBase64Decoder_Destroy(cx, PR_FALSE); @@ -248,8 +249,8 @@ output_ascii(void *arg, const char *obuf, PRInt32 size) PRFileDesc *outfile = arg; PRInt32 nb = PR_Write(outfile, obuf, size); if (nb != size) { - PORT_SetError(SEC_ERROR_IO); - return -1; + PORT_SetError(SEC_ERROR_IO); + return -1; } return nb; } @@ -260,7 +261,7 @@ btoa_file(SECItem *binary, PRFileDesc *outfile) SECStatus status; NSSBase64Encoder *cx; if (binary->len == 0) - return SECSuccess; + return SECSuccess; cx = NSSBase64Encoder_Create(output_ascii, outfile); status = NSSBase64Encoder_Update(cx, binary->data, binary->len); status = NSSBase64Encoder_Destroy(cx, PR_FALSE); @@ -274,19 +275,19 @@ hex_from_2char(unsigned char *c2, unsigned char *byteval) int i; unsigned char offset; *byteval = 0; - for (i=0; i<2; i++) { - if (c2[i] >= '0' && c2[i] <= '9') { - offset = c2[i] - '0'; - *byteval |= offset << 4*(1-i); - } else if (c2[i] >= 'a' && c2[i] <= 'f') { - offset = c2[i] - 'a'; - *byteval |= (offset + 10) << 4*(1-i); - } else if (c2[i] >= 'A' && c2[i] <= 'F') { - offset = c2[i] - 'A'; - *byteval |= (offset + 10) << 4*(1-i); - } else { - return SECFailure; - } + for (i = 0; i < 2; i++) { + if (c2[i] >= '0' && c2[i] <= '9') { + offset = c2[i] - '0'; + *byteval |= offset << 4 * (1 - i); + } else if (c2[i] >= 'a' && c2[i] <= 'f') { + offset = c2[i] - 'a'; + *byteval |= (offset + 10) << 4 * (1 - i); + } else if (c2[i] >= 'A' && c2[i] <= 'F') { + offset = c2[i] - 'A'; + *byteval |= (offset + 10) << 4 * (1 - i); + } else { + return SECFailure; + } } return SECSuccess; } @@ -296,13 +297,13 @@ char2_from_hex(unsigned char byteval, char *c2) { int i; unsigned char offset; - for (i=0; i<2; i++) { - offset = (byteval >> 4*(1-i)) & 0x0f; - if (offset < 10) { - c2[i] = '0' + offset; - } else { - c2[i] = 'A' + offset - 10; - } + for (i = 0; i < 2; i++) { + offset = (byteval >> 4 * (1 - i)) & 0x0f; + if (offset < 10) { + c2[i] = '0' + offset; + } else { + c2[i] = 'A' + offset - 10; + } } return SECSuccess; } @@ -314,13 +315,13 @@ serialize_key(SECItem *it, int ni, PRFileDesc *file) int i; NSSBase64Encoder *cx; cx = NSSBase64Encoder_Create(output_ascii, file); - for (i=0; ilen >> 24) & 0xff; - len[1] = (it->len >> 16) & 0xff; - len[2] = (it->len >> 8) & 0xff; - len[3] = (it->len & 0xff); - NSSBase64Encoder_Update(cx, len, 4); - NSSBase64Encoder_Update(cx, it->data, it->len); + for (i = 0; i < ni; i++, it++) { + len[0] = (it->len >> 24) & 0xff; + len[1] = (it->len >> 16) & 0xff; + len[2] = (it->len >> 8) & 0xff; + len[3] = (it->len & 0xff); + NSSBase64Encoder_Update(cx, len, 4); + NSSBase64Encoder_Update(cx, it->data, it->len); } NSSBase64Encoder_Destroy(cx, PR_FALSE); PR_Write(file, "\r\n", 2); @@ -332,23 +333,23 @@ key_from_filedata(PLArenaPool *arena, SECItem *it, int ns, int ni, SECItem *file int fpos = 0; int i, len; unsigned char *buf = filedata->data; - for (i=0; i 0) { - it->len = len; - it->data = PORT_ArenaAlloc(arena, it->len); - PORT_Memcpy(it->data, &buf[fpos], it->len); - } else { - it->len = 0; - it->data = NULL; - } - it++; - } - fpos += len; + for (i = 0; i < ni; i++) { + len = (buf[fpos++] & 0xff) << 24; + len |= (buf[fpos++] & 0xff) << 16; + len |= (buf[fpos++] & 0xff) << 8; + len |= (buf[fpos++] & 0xff); + if (ns <= i) { + if (len > 0) { + it->len = len; + it->data = PORT_ArenaAlloc(arena, it->len); + PORT_Memcpy(it->data, &buf[fpos], it->len); + } else { + it->len = 0; + it->data = NULL; + } + it++; + } + fpos += len; } } @@ -420,92 +421,92 @@ typedef struct curveNameTagPairStr { SECOidTag curveOidTag; } CurveNameTagPair; -#define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP192R1 +#define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP192R1 /* #define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP160R1 */ static CurveNameTagPair nameTagPair[] = -{ - { "sect163k1", SEC_OID_SECG_EC_SECT163K1}, - { "nistk163", SEC_OID_SECG_EC_SECT163K1}, - { "sect163r1", SEC_OID_SECG_EC_SECT163R1}, - { "sect163r2", SEC_OID_SECG_EC_SECT163R2}, - { "nistb163", SEC_OID_SECG_EC_SECT163R2}, - { "sect193r1", SEC_OID_SECG_EC_SECT193R1}, - { "sect193r2", SEC_OID_SECG_EC_SECT193R2}, - { "sect233k1", SEC_OID_SECG_EC_SECT233K1}, - { "nistk233", SEC_OID_SECG_EC_SECT233K1}, - { "sect233r1", SEC_OID_SECG_EC_SECT233R1}, - { "nistb233", SEC_OID_SECG_EC_SECT233R1}, - { "sect239k1", SEC_OID_SECG_EC_SECT239K1}, - { "sect283k1", SEC_OID_SECG_EC_SECT283K1}, - { "nistk283", SEC_OID_SECG_EC_SECT283K1}, - { "sect283r1", SEC_OID_SECG_EC_SECT283R1}, - { "nistb283", SEC_OID_SECG_EC_SECT283R1}, - { "sect409k1", SEC_OID_SECG_EC_SECT409K1}, - { "nistk409", SEC_OID_SECG_EC_SECT409K1}, - { "sect409r1", SEC_OID_SECG_EC_SECT409R1}, - { "nistb409", SEC_OID_SECG_EC_SECT409R1}, - { "sect571k1", SEC_OID_SECG_EC_SECT571K1}, - { "nistk571", SEC_OID_SECG_EC_SECT571K1}, - { "sect571r1", SEC_OID_SECG_EC_SECT571R1}, - { "nistb571", SEC_OID_SECG_EC_SECT571R1}, - { "secp160k1", SEC_OID_SECG_EC_SECP160K1}, - { "secp160r1", SEC_OID_SECG_EC_SECP160R1}, - { "secp160r2", SEC_OID_SECG_EC_SECP160R2}, - { "secp192k1", SEC_OID_SECG_EC_SECP192K1}, - { "secp192r1", SEC_OID_SECG_EC_SECP192R1}, - { "nistp192", SEC_OID_SECG_EC_SECP192R1}, - { "secp224k1", SEC_OID_SECG_EC_SECP224K1}, - { "secp224r1", SEC_OID_SECG_EC_SECP224R1}, - { "nistp224", SEC_OID_SECG_EC_SECP224R1}, - { "secp256k1", SEC_OID_SECG_EC_SECP256K1}, - { "secp256r1", SEC_OID_SECG_EC_SECP256R1}, - { "nistp256", SEC_OID_SECG_EC_SECP256R1}, - { "secp384r1", SEC_OID_SECG_EC_SECP384R1}, - { "nistp384", SEC_OID_SECG_EC_SECP384R1}, - { "secp521r1", SEC_OID_SECG_EC_SECP521R1}, - { "nistp521", SEC_OID_SECG_EC_SECP521R1}, - - { "prime192v1", SEC_OID_ANSIX962_EC_PRIME192V1 }, - { "prime192v2", SEC_OID_ANSIX962_EC_PRIME192V2 }, - { "prime192v3", SEC_OID_ANSIX962_EC_PRIME192V3 }, - { "prime239v1", SEC_OID_ANSIX962_EC_PRIME239V1 }, - { "prime239v2", SEC_OID_ANSIX962_EC_PRIME239V2 }, - { "prime239v3", SEC_OID_ANSIX962_EC_PRIME239V3 }, - - { "c2pnb163v1", SEC_OID_ANSIX962_EC_C2PNB163V1 }, - { "c2pnb163v2", SEC_OID_ANSIX962_EC_C2PNB163V2 }, - { "c2pnb163v3", SEC_OID_ANSIX962_EC_C2PNB163V3 }, - { "c2pnb176v1", SEC_OID_ANSIX962_EC_C2PNB176V1 }, - { "c2tnb191v1", SEC_OID_ANSIX962_EC_C2TNB191V1 }, - { "c2tnb191v2", SEC_OID_ANSIX962_EC_C2TNB191V2 }, - { "c2tnb191v3", SEC_OID_ANSIX962_EC_C2TNB191V3 }, - { "c2onb191v4", SEC_OID_ANSIX962_EC_C2ONB191V4 }, - { "c2onb191v5", SEC_OID_ANSIX962_EC_C2ONB191V5 }, - { "c2pnb208w1", SEC_OID_ANSIX962_EC_C2PNB208W1 }, - { "c2tnb239v1", SEC_OID_ANSIX962_EC_C2TNB239V1 }, - { "c2tnb239v2", SEC_OID_ANSIX962_EC_C2TNB239V2 }, - { "c2tnb239v3", SEC_OID_ANSIX962_EC_C2TNB239V3 }, - { "c2onb239v4", SEC_OID_ANSIX962_EC_C2ONB239V4 }, - { "c2onb239v5", SEC_OID_ANSIX962_EC_C2ONB239V5 }, - { "c2pnb272w1", SEC_OID_ANSIX962_EC_C2PNB272W1 }, - { "c2pnb304w1", SEC_OID_ANSIX962_EC_C2PNB304W1 }, - { "c2tnb359v1", SEC_OID_ANSIX962_EC_C2TNB359V1 }, - { "c2pnb368w1", SEC_OID_ANSIX962_EC_C2PNB368W1 }, - { "c2tnb431r1", SEC_OID_ANSIX962_EC_C2TNB431R1 }, - - { "secp112r1", SEC_OID_SECG_EC_SECP112R1}, - { "secp112r2", SEC_OID_SECG_EC_SECP112R2}, - { "secp128r1", SEC_OID_SECG_EC_SECP128R1}, - { "secp128r2", SEC_OID_SECG_EC_SECP128R2}, - - { "sect113r1", SEC_OID_SECG_EC_SECT113R1}, - { "sect113r2", SEC_OID_SECG_EC_SECT113R2}, - { "sect131r1", SEC_OID_SECG_EC_SECT131R1}, - { "sect131r2", SEC_OID_SECG_EC_SECT131R2}, -}; - -static SECItem * + { + { "sect163k1", SEC_OID_SECG_EC_SECT163K1 }, + { "nistk163", SEC_OID_SECG_EC_SECT163K1 }, + { "sect163r1", SEC_OID_SECG_EC_SECT163R1 }, + { "sect163r2", SEC_OID_SECG_EC_SECT163R2 }, + { "nistb163", SEC_OID_SECG_EC_SECT163R2 }, + { "sect193r1", SEC_OID_SECG_EC_SECT193R1 }, + { "sect193r2", SEC_OID_SECG_EC_SECT193R2 }, + { "sect233k1", SEC_OID_SECG_EC_SECT233K1 }, + { "nistk233", SEC_OID_SECG_EC_SECT233K1 }, + { "sect233r1", SEC_OID_SECG_EC_SECT233R1 }, + { "nistb233", SEC_OID_SECG_EC_SECT233R1 }, + { "sect239k1", SEC_OID_SECG_EC_SECT239K1 }, + { "sect283k1", SEC_OID_SECG_EC_SECT283K1 }, + { "nistk283", SEC_OID_SECG_EC_SECT283K1 }, + { "sect283r1", SEC_OID_SECG_EC_SECT283R1 }, + { "nistb283", SEC_OID_SECG_EC_SECT283R1 }, + { "sect409k1", SEC_OID_SECG_EC_SECT409K1 }, + { "nistk409", SEC_OID_SECG_EC_SECT409K1 }, + { "sect409r1", SEC_OID_SECG_EC_SECT409R1 }, + { "nistb409", SEC_OID_SECG_EC_SECT409R1 }, + { "sect571k1", SEC_OID_SECG_EC_SECT571K1 }, + { "nistk571", SEC_OID_SECG_EC_SECT571K1 }, + { "sect571r1", SEC_OID_SECG_EC_SECT571R1 }, + { "nistb571", SEC_OID_SECG_EC_SECT571R1 }, + { "secp160k1", SEC_OID_SECG_EC_SECP160K1 }, + { "secp160r1", SEC_OID_SECG_EC_SECP160R1 }, + { "secp160r2", SEC_OID_SECG_EC_SECP160R2 }, + { "secp192k1", SEC_OID_SECG_EC_SECP192K1 }, + { "secp192r1", SEC_OID_SECG_EC_SECP192R1 }, + { "nistp192", SEC_OID_SECG_EC_SECP192R1 }, + { "secp224k1", SEC_OID_SECG_EC_SECP224K1 }, + { "secp224r1", SEC_OID_SECG_EC_SECP224R1 }, + { "nistp224", SEC_OID_SECG_EC_SECP224R1 }, + { "secp256k1", SEC_OID_SECG_EC_SECP256K1 }, + { "secp256r1", SEC_OID_SECG_EC_SECP256R1 }, + { "nistp256", SEC_OID_SECG_EC_SECP256R1 }, + { "secp384r1", SEC_OID_SECG_EC_SECP384R1 }, + { "nistp384", SEC_OID_SECG_EC_SECP384R1 }, + { "secp521r1", SEC_OID_SECG_EC_SECP521R1 }, + { "nistp521", SEC_OID_SECG_EC_SECP521R1 }, + + { "prime192v1", SEC_OID_ANSIX962_EC_PRIME192V1 }, + { "prime192v2", SEC_OID_ANSIX962_EC_PRIME192V2 }, + { "prime192v3", SEC_OID_ANSIX962_EC_PRIME192V3 }, + { "prime239v1", SEC_OID_ANSIX962_EC_PRIME239V1 }, + { "prime239v2", SEC_OID_ANSIX962_EC_PRIME239V2 }, + { "prime239v3", SEC_OID_ANSIX962_EC_PRIME239V3 }, + + { "c2pnb163v1", SEC_OID_ANSIX962_EC_C2PNB163V1 }, + { "c2pnb163v2", SEC_OID_ANSIX962_EC_C2PNB163V2 }, + { "c2pnb163v3", SEC_OID_ANSIX962_EC_C2PNB163V3 }, + { "c2pnb176v1", SEC_OID_ANSIX962_EC_C2PNB176V1 }, + { "c2tnb191v1", SEC_OID_ANSIX962_EC_C2TNB191V1 }, + { "c2tnb191v2", SEC_OID_ANSIX962_EC_C2TNB191V2 }, + { "c2tnb191v3", SEC_OID_ANSIX962_EC_C2TNB191V3 }, + { "c2onb191v4", SEC_OID_ANSIX962_EC_C2ONB191V4 }, + { "c2onb191v5", SEC_OID_ANSIX962_EC_C2ONB191V5 }, + { "c2pnb208w1", SEC_OID_ANSIX962_EC_C2PNB208W1 }, + { "c2tnb239v1", SEC_OID_ANSIX962_EC_C2TNB239V1 }, + { "c2tnb239v2", SEC_OID_ANSIX962_EC_C2TNB239V2 }, + { "c2tnb239v3", SEC_OID_ANSIX962_EC_C2TNB239V3 }, + { "c2onb239v4", SEC_OID_ANSIX962_EC_C2ONB239V4 }, + { "c2onb239v5", SEC_OID_ANSIX962_EC_C2ONB239V5 }, + { "c2pnb272w1", SEC_OID_ANSIX962_EC_C2PNB272W1 }, + { "c2pnb304w1", SEC_OID_ANSIX962_EC_C2PNB304W1 }, + { "c2tnb359v1", SEC_OID_ANSIX962_EC_C2TNB359V1 }, + { "c2pnb368w1", SEC_OID_ANSIX962_EC_C2PNB368W1 }, + { "c2tnb431r1", SEC_OID_ANSIX962_EC_C2TNB431R1 }, + + { "secp112r1", SEC_OID_SECG_EC_SECP112R1 }, + { "secp112r2", SEC_OID_SECG_EC_SECP112R2 }, + { "secp128r1", SEC_OID_SECG_EC_SECP128R1 }, + { "secp128r2", SEC_OID_SECG_EC_SECP128R2 }, + + { "sect113r1", SEC_OID_SECG_EC_SECT113R1 }, + { "sect113r2", SEC_OID_SECG_EC_SECT113R2 }, + { "sect131r1", SEC_OID_SECG_EC_SECT131R1 }, + { "sect131r2", SEC_OID_SECG_EC_SECT131R2 }, + }; + +static SECItem * getECParams(const char *curve) { SECItem *ecparams; @@ -514,26 +515,26 @@ getECParams(const char *curve) int i, numCurves; if (curve != NULL) { - numCurves = sizeof(nameTagPair)/sizeof(CurveNameTagPair); - for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); - i++) { - if (PL_strcmp(curve, nameTagPair[i].curveName) == 0) - curveOidTag = nameTagPair[i].curveOidTag; - } + numCurves = sizeof(nameTagPair) / sizeof(CurveNameTagPair); + for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); + i++) { + if (PL_strcmp(curve, nameTagPair[i].curveName) == 0) + curveOidTag = nameTagPair[i].curveOidTag; + } } /* Return NULL if curve name is not recognized */ - if ((curveOidTag == SEC_OID_UNKNOWN) || - (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) { + if ((curveOidTag == SEC_OID_UNKNOWN) || + (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) { fprintf(stderr, "Unrecognized elliptic curve %s\n", curve); - return NULL; + return NULL; } ecparams = SECITEM_AllocItem(NULL, NULL, (2 + oidData->oid.len)); - /* + /* * ecparams->data needs to contain the ASN encoding of an object ID (OID) - * representing the named curve. The actual OID is in + * representing the named curve. The actual OID is in * oidData->oid.data so we simply prepend 0x06 and OID length */ ecparams->data[0] = SEC_ASN1_OBJECT_ID; @@ -592,128 +593,128 @@ dump_rsakey(RSAPrivateKey *key) } typedef enum { - bltestBase64Encoded, /* Base64 encoded ASCII */ - bltestBinary, /* straight binary */ - bltestHexSpaceDelim, /* 0x12 0x34 0xab 0xCD ... */ - bltestHexStream /* 1234abCD ... */ + bltestBase64Encoded, /* Base64 encoded ASCII */ + bltestBinary, /* straight binary */ + bltestHexSpaceDelim, /* 0x12 0x34 0xab 0xCD ... */ + bltestHexStream /* 1234abCD ... */ } bltestIOMode; typedef struct { - SECItem buf; - SECItem pBuf; - bltestIOMode mode; - PRFileDesc* file; + SECItem buf; + SECItem pBuf; + bltestIOMode mode; + PRFileDesc *file; } bltestIO; -typedef SECStatus (* bltestSymmCipherFn)(void *cx, - unsigned char *output, - unsigned int *outputLen, - unsigned int maxOutputLen, - const unsigned char *input, - unsigned int inputLen); - -typedef SECStatus (* bltestAEADFn)(void *cx, - unsigned char *output, - unsigned int *outputLen, - unsigned int maxOutputLen, - const unsigned char *input, - unsigned int inputLen, - const unsigned char *nonce, - unsigned int nonceLen, - const unsigned char *ad, - unsigned int adLen); - -typedef SECStatus (* bltestPubKeyCipherFn)(void *key, - SECItem *output, - const SECItem *input); - -typedef SECStatus (* bltestHashCipherFn)(unsigned char *dest, - const unsigned char *src, - PRUint32 src_length); +typedef SECStatus (*bltestSymmCipherFn)(void *cx, + unsigned char *output, + unsigned int *outputLen, + unsigned int maxOutputLen, + const unsigned char *input, + unsigned int inputLen); + +typedef SECStatus (*bltestAEADFn)(void *cx, + unsigned char *output, + unsigned int *outputLen, + unsigned int maxOutputLen, + const unsigned char *input, + unsigned int inputLen, + const unsigned char *nonce, + unsigned int nonceLen, + const unsigned char *ad, + unsigned int adLen); + +typedef SECStatus (*bltestPubKeyCipherFn)(void *key, + SECItem *output, + const SECItem *input); + +typedef SECStatus (*bltestHashCipherFn)(unsigned char *dest, + const unsigned char *src, + PRUint32 src_length); /* Note: Algorithms are grouped in order to support is_symmkeyCipher / * is_pubkeyCipher / is_hashCipher / is_sigCipher */ typedef enum { bltestINVALID = -1, - bltestDES_ECB, /* Symmetric Key Ciphers */ - bltestDES_CBC, /* . */ - bltestDES_EDE_ECB, /* . */ - bltestDES_EDE_CBC, /* . */ - bltestRC2_ECB, /* . */ - bltestRC2_CBC, /* . */ - bltestRC4, /* . */ + bltestDES_ECB, /* Symmetric Key Ciphers */ + bltestDES_CBC, /* . */ + bltestDES_EDE_ECB, /* . */ + bltestDES_EDE_CBC, /* . */ + bltestRC2_ECB, /* . */ + bltestRC2_CBC, /* . */ + bltestRC4, /* . */ #ifdef NSS_SOFTOKEN_DOES_RC5 - bltestRC5_ECB, /* . */ - bltestRC5_CBC, /* . */ + bltestRC5_ECB, /* . */ + bltestRC5_CBC, /* . */ #endif - bltestAES_ECB, /* . */ - bltestAES_CBC, /* . */ - bltestAES_CTS, /* . */ - bltestAES_CTR, /* . */ - bltestAES_GCM, /* . */ - bltestCAMELLIA_ECB, /* . */ - bltestCAMELLIA_CBC, /* . */ - bltestSEED_ECB, /* SEED algorithm */ - bltestSEED_CBC, /* SEED algorithm */ - bltestCHACHA20, /* ChaCha20 + Poly1305 */ - bltestRSA, /* Public Key Ciphers */ - bltestRSA_OAEP, /* . (Public Key Enc.) */ - bltestRSA_PSS, /* . (Public Key Sig.) */ + bltestAES_ECB, /* . */ + bltestAES_CBC, /* . */ + bltestAES_CTS, /* . */ + bltestAES_CTR, /* . */ + bltestAES_GCM, /* . */ + bltestCAMELLIA_ECB, /* . */ + bltestCAMELLIA_CBC, /* . */ + bltestSEED_ECB, /* SEED algorithm */ + bltestSEED_CBC, /* SEED algorithm */ + bltestCHACHA20, /* ChaCha20 + Poly1305 */ + bltestRSA, /* Public Key Ciphers */ + bltestRSA_OAEP, /* . (Public Key Enc.) */ + bltestRSA_PSS, /* . (Public Key Sig.) */ #ifndef NSS_DISABLE_ECC - bltestECDSA, /* . (Public Key Sig.) */ + bltestECDSA, /* . (Public Key Sig.) */ #endif - bltestDSA, /* . (Public Key Sig.) */ - bltestMD2, /* Hash algorithms */ - bltestMD5, /* . */ - bltestSHA1, /* . */ - bltestSHA224, /* . */ - bltestSHA256, /* . */ - bltestSHA384, /* . */ - bltestSHA512, /* . */ + bltestDSA, /* . (Public Key Sig.) */ + bltestMD2, /* Hash algorithms */ + bltestMD5, /* . */ + bltestSHA1, /* . */ + bltestSHA224, /* . */ + bltestSHA256, /* . */ + bltestSHA384, /* . */ + bltestSHA512, /* . */ NUMMODES } bltestCipherMode; static char *mode_strings[] = -{ - "des_ecb", - "des_cbc", - "des3_ecb", - "des3_cbc", - "rc2_ecb", - "rc2_cbc", - "rc4", + { + "des_ecb", + "des_cbc", + "des3_ecb", + "des3_cbc", + "rc2_ecb", + "rc2_cbc", + "rc4", #ifdef NSS_SOFTOKEN_DOES_RC5 - "rc5_ecb", - "rc5_cbc", + "rc5_ecb", + "rc5_cbc", #endif - "aes_ecb", - "aes_cbc", - "aes_cts", - "aes_ctr", - "aes_gcm", - "camellia_ecb", - "camellia_cbc", - "seed_ecb", - "seed_cbc", - "chacha20_poly1305", - "rsa", - "rsa_oaep", - "rsa_pss", + "aes_ecb", + "aes_cbc", + "aes_cts", + "aes_ctr", + "aes_gcm", + "camellia_ecb", + "camellia_cbc", + "seed_ecb", + "seed_cbc", + "chacha20_poly1305", + "rsa", + "rsa_oaep", + "rsa_pss", #ifndef NSS_DISABLE_ECC - "ecdsa", + "ecdsa", #endif - /*"pqg",*/ - "dsa", - "md2", - "md5", - "sha1", - "sha224", - "sha256", - "sha384", - "sha512", -}; + /*"pqg",*/ + "dsa", + "md2", + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + }; typedef struct { @@ -731,8 +732,8 @@ typedef struct { bltestIO key; bltestIO iv; - int rounds; - int wordsize; + int rounds; + int wordsize; } bltestRC5Params; typedef struct @@ -743,31 +744,31 @@ typedef struct /* OAEP & PSS */ HASH_HashType hashAlg; HASH_HashType maskHashAlg; - bltestIO seed; /* salt if PSS */ + bltestIO seed; /* salt if PSS */ } bltestRSAParams; typedef struct { - bltestIO pqgdata; + bltestIO pqgdata; unsigned int keysize; - bltestIO keyseed; - bltestIO sigseed; + bltestIO keyseed; + bltestIO sigseed; PQGParams *pqg; } bltestDSAParams; #ifndef NSS_DISABLE_ECC typedef struct { - char *curveName; - bltestIO sigseed; + char *curveName; + bltestIO sigseed; } bltestECDSAParams; #endif typedef struct { bltestIO key; - void * privKey; - void * pubKey; + void *privKey; + void *pubKey; bltestIO sig; /* if doing verify, the signature (which may come * from sigfile. */ @@ -782,27 +783,26 @@ typedef struct typedef struct { - bltestIO key; /* unused */ - PRBool restart; + bltestIO key; /* unused */ + PRBool restart; } bltestHashParams; -typedef union -{ - bltestIO key; +typedef union { + bltestIO key; bltestSymmKeyParams sk; bltestAuthSymmKeyParams ask; - bltestRC5Params rc5; - bltestAsymKeyParams asymk; - bltestHashParams hash; + bltestRC5Params rc5; + bltestAsymKeyParams asymk; + bltestHashParams hash; } bltestParams; typedef struct bltestCipherInfoStr bltestCipherInfo; -struct bltestCipherInfoStr { +struct bltestCipherInfoStr { PLArenaPool *arena; /* link to next in multithreaded test */ bltestCipherInfo *next; - PRThread *cipherThread; + PRThread *cipherThread; /* MonteCarlo test flag*/ PRBool mCarlo; @@ -814,19 +814,19 @@ struct bltestCipherInfoStr { /* Cipher-specific parameters */ bltestParams params; /* Cipher mode */ - bltestCipherMode mode; + bltestCipherMode mode; /* Cipher function (encrypt/decrypt/sign/verify/hash) */ union { - bltestSymmCipherFn symmkeyCipher; - bltestAEADFn aeadCipher; - bltestPubKeyCipherFn pubkeyCipher; - bltestHashCipherFn hashCipher; + bltestSymmCipherFn symmkeyCipher; + bltestAEADFn aeadCipher; + bltestPubKeyCipherFn pubkeyCipher; + bltestHashCipherFn hashCipher; } cipher; /* performance testing */ - int repetitionsToPerfom; - int seconds; - int repetitions; - int cxreps; + int repetitionsToPerfom; + int seconds; + int repetitions; + int cxreps; double cxtime; double optime; }; @@ -836,7 +836,7 @@ is_symmkeyCipher(bltestCipherMode mode) { /* change as needed! */ if (mode >= bltestDES_ECB && mode <= bltestSEED_CBC) - return PR_TRUE; + return PR_TRUE; return PR_FALSE; } @@ -845,10 +845,10 @@ is_aeadCipher(bltestCipherMode mode) { /* change as needed! */ switch (mode) { - case bltestCHACHA20: - return PR_TRUE; - default: - return PR_FALSE; + case bltestCHACHA20: + return PR_TRUE; + default: + return PR_FALSE; } } @@ -857,26 +857,25 @@ is_authCipher(bltestCipherMode mode) { /* change as needed! */ switch (mode) { - case bltestAES_GCM: - case bltestCHACHA20: - return PR_TRUE; - default: - return PR_FALSE; + case bltestAES_GCM: + case bltestCHACHA20: + return PR_TRUE; + default: + return PR_FALSE; } } - PRBool is_singleShotCipher(bltestCipherMode mode) { /* change as needed! */ switch (mode) { - case bltestAES_GCM: - case bltestAES_CTS: - case bltestCHACHA20: - return PR_TRUE; - default: - return PR_FALSE; + case bltestAES_GCM: + case bltestAES_CTS: + case bltestCHACHA20: + return PR_TRUE; + default: + return PR_FALSE; } } @@ -885,7 +884,7 @@ is_pubkeyCipher(bltestCipherMode mode) { /* change as needed! */ if (mode >= bltestRSA && mode <= bltestDSA) - return PR_TRUE; + return PR_TRUE; return PR_FALSE; } @@ -894,7 +893,7 @@ is_hashCipher(bltestCipherMode mode) { /* change as needed! */ if (mode >= bltestMD2 && mode <= bltestSHA512) - return PR_TRUE; + return PR_TRUE; return PR_FALSE; } @@ -903,7 +902,7 @@ is_sigCipher(bltestCipherMode mode) { /* change as needed! */ if (mode >= bltestRSA_PSS && mode <= bltestDSA) - return PR_TRUE; + return PR_TRUE; return PR_FALSE; } @@ -912,22 +911,22 @@ cipher_requires_IV(bltestCipherMode mode) { /* change as needed! */ switch (mode) { - case bltestDES_CBC: - case bltestDES_EDE_CBC: - case bltestRC2_CBC: + case bltestDES_CBC: + case bltestDES_EDE_CBC: + case bltestRC2_CBC: #ifdef NSS_SOFTOKEN_DOES_RC5 - case bltestRC5_CBC: + case bltestRC5_CBC: #endif - case bltestAES_CBC: - case bltestAES_CTS: - case bltestAES_CTR: - case bltestAES_GCM: - case bltestCAMELLIA_CBC: - case bltestSEED_CBC: - case bltestCHACHA20: - return PR_TRUE; - default: - return PR_FALSE; + case bltestAES_CBC: + case bltestAES_CTS: + case bltestAES_CTR: + case bltestAES_GCM: + case bltestCAMELLIA_CBC: + case bltestSEED_CBC: + case bltestCHACHA20: + return PR_TRUE; + default: + return PR_FALSE; } } @@ -935,7 +934,7 @@ SECStatus finishIO(bltestIO *output, PRFileDesc *file); SECStatus setupIO(PLArenaPool *arena, bltestIO *input, PRFileDesc *file, - char *str, int numBytes) + char *str, int numBytes) { SECStatus rv = SECSuccess; SECItem fileData; @@ -944,70 +943,76 @@ setupIO(PLArenaPool *arena, bltestIO *input, PRFileDesc *file, unsigned int i, j; if (file && (numBytes == 0 || file == PR_STDIN)) { - /* grabbing data from a file */ - rv = SECU_FileToItem(&fileData, file); - if (rv != SECSuccess) - return SECFailure; - in = &fileData; + /* grabbing data from a file */ + rv = SECU_FileToItem(&fileData, file); + if (rv != SECSuccess) + return SECFailure; + in = &fileData; } else if (str) { - /* grabbing data from command line */ - fileData.data = (unsigned char *)str; - fileData.len = PL_strlen(str); - in = &fileData; + /* grabbing data from command line */ + fileData.data = (unsigned char *)str; + fileData.len = PL_strlen(str); + in = &fileData; } else if (file) { - /* create nonce */ - SECITEM_AllocItem(arena, &input->buf, numBytes); - RNG_GenerateGlobalRandomBytes(input->buf.data, numBytes); - return finishIO(input, file); + /* create nonce */ + SECITEM_AllocItem(arena, &input->buf, numBytes); + RNG_GenerateGlobalRandomBytes(input->buf.data, numBytes); + return finishIO(input, file); } else { - return SECFailure; + return SECFailure; } switch (input->mode) { - case bltestBase64Encoded: - if (in->len == 0) { - input->buf.data = NULL; - input->buf.len = 0; - break; - } - rv = atob(in, &input->buf, arena); - break; - case bltestBinary: - if (in->len == 0) { - input->buf.data = NULL; - input->buf.len = 0; - break; - } - if (in->data[in->len-1] == '\n') --in->len; - if (in->data[in->len-1] == '\r') --in->len; - SECITEM_CopyItem(arena, &input->buf, in); - break; - case bltestHexSpaceDelim: - SECITEM_AllocItem(arena, &input->buf, in->len/5); - for (i=0, j=0; ilen; i+=5, j++) { - tok = &in->data[i]; - if (tok[0] != '0' || tok[1] != 'x' || tok[4] != ' ') - /* bad hex token */ - break; - - rv = hex_from_2char(&tok[2], input->buf.data + j); - if (rv) - break; - } - break; - case bltestHexStream: - SECITEM_AllocItem(arena, &input->buf, in->len/2); - for (i=0, j=0; ilen; i+=2, j++) { - tok = &in->data[i]; - rv = hex_from_2char(tok, input->buf.data + j); - if (rv) - break; - } - break; + case bltestBase64Encoded: + if (in->len == 0) { + input->buf.data = NULL; + input->buf.len = 0; + break; + } + rv = atob(in, &input->buf, arena); + break; + case bltestBinary: + if (in->len == 0) { + input->buf.data = NULL; + input->buf.len = 0; + break; + } + if (in->data[in->len - 1] == '\n') + --in->len; + if (in->data[in->len - 1] == '\r') + --in->len; + SECITEM_CopyItem(arena, &input->buf, in); + break; + case bltestHexSpaceDelim: + SECITEM_AllocItem(arena, &input->buf, in->len / 5); + for (i = 0, j = 0; i < + in->len; + i += 5, j++) { + tok = &in->data[i]; + if (tok[0] != '0' || tok[1] != 'x' || tok[4] != ' ') + /* bad hex token */ + break; + + rv = hex_from_2char(&tok[2], input->buf.data + j); + if (rv) + break; + } + break; + case bltestHexStream: + SECITEM_AllocItem(arena, &input->buf, in->len / 2); + for (i = 0, j = 0; i < + in->len; + i += 2, j++) { + tok = &in->data[i]; + rv = hex_from_2char(tok, input->buf.data + j); + if (rv) + break; + } + break; } if (file) - SECITEM_FreeItem(&fileData, PR_FALSE); + SECITEM_FreeItem(&fileData, PR_FALSE); return rv; } @@ -1021,41 +1026,41 @@ finishIO(bltestIO *output, PRFileDesc *file) char hexstr[5]; unsigned int i; if (output->pBuf.len > 0) { - it = &output->pBuf; + it = &output->pBuf; } else { - it = &output->buf; + it = &output->buf; } switch (output->mode) { - case bltestBase64Encoded: - rv = btoa_file(it, file); - break; - case bltestBinary: - nb = PR_Write(file, it->data, it->len); - rv = (nb == (PRInt32)it->len) ? SECSuccess : SECFailure; - break; - case bltestHexSpaceDelim: - hexstr[0] = '0'; - hexstr[1] = 'x'; - hexstr[4] = ' '; - for (i=0; ilen; i++) { - byteval = it->data[i]; - rv = char2_from_hex(byteval, hexstr + 2); - nb = PR_Write(file, hexstr, 5); - if (rv) - break; - } - PR_Write(file, "\n", 1); - break; - case bltestHexStream: - for (i=0; ilen; i++) { - byteval = it->data[i]; - rv = char2_from_hex(byteval, hexstr); - if (rv) - break; - nb = PR_Write(file, hexstr, 2); - } - PR_Write(file, "\n", 1); - break; + case bltestBase64Encoded: + rv = btoa_file(it, file); + break; + case bltestBinary: + nb = PR_Write(file, it->data, it->len); + rv = (nb == (PRInt32)it->len) ? SECSuccess : SECFailure; + break; + case bltestHexSpaceDelim: + hexstr[0] = '0'; + hexstr[1] = 'x'; + hexstr[4] = ' '; + for (i = 0; i < it->len; i++) { + byteval = it->data[i]; + rv = char2_from_hex(byteval, hexstr + 2); + nb = PR_Write(file, hexstr, 5); + if (rv) + break; + } + PR_Write(file, "\n", 1); + break; + case bltestHexStream: + for (i = 0; i < it->len; i++) { + byteval = it->data[i]; + rv = char2_from_hex(byteval, hexstr); + if (rv) + break; + nb = PR_Write(file, hexstr, 2); + } + PR_Write(file, "\n", 1); + break; } return rv; } @@ -1065,8 +1070,8 @@ bltestCopyIO(PLArenaPool *arena, bltestIO *dest, bltestIO *src) { SECITEM_CopyItem(arena, &dest->buf, &src->buf); if (src->pBuf.len > 0) { - dest->pBuf.len = src->pBuf.len; - dest->pBuf.data = dest->buf.data + (src->pBuf.data - src->buf.data); + dest->pBuf.len = src->pBuf.len; + dest->pBuf.data = dest->buf.data + (src->pBuf.data - src->buf.data); } dest->mode = src->mode; dest->file = src->file; @@ -1078,20 +1083,20 @@ misalignBuffer(PLArenaPool *arena, bltestIO *io, int off) ptrdiff_t offset = (ptrdiff_t)io->buf.data % WORDSIZE; int length = io->buf.len; if (offset != off) { - SECITEM_ReallocItemV2(arena, &io->buf, length + 2*WORDSIZE); - /* offset may have changed? */ - offset = (ptrdiff_t)io->buf.data % WORDSIZE; - if (offset != off) { - memmove(io->buf.data + off, io->buf.data, length); - io->pBuf.data = io->buf.data + off; - io->pBuf.len = length; - } else { - io->pBuf.data = io->buf.data; - io->pBuf.len = length; - } + SECITEM_ReallocItemV2(arena, &io->buf, length + 2 * WORDSIZE); + /* offset may have changed? */ + offset = (ptrdiff_t)io->buf.data % WORDSIZE; + if (offset != off) { + memmove(io->buf.data + off, io->buf.data, length); + io->pBuf.data = io->buf.data + off; + io->pBuf.len = length; + } else { + io->pBuf.data = io->buf.data; + io->pBuf.len = length; + } } else { - io->pBuf.data = io->buf.data; - io->pBuf.len = length; + io->pBuf.data = io->buf.data; + io->pBuf.len = length; } } @@ -1169,10 +1174,10 @@ aes_Decrypt(void *cx, unsigned char *output, unsigned int *outputLen, SECStatus chacha20_poly1305_Encrypt(void *cx, unsigned char *output, - unsigned int *outputLen, unsigned int maxOutputLen, - const unsigned char *input, unsigned int inputLen, - const unsigned char *nonce, unsigned int nonceLen, - const unsigned char *ad, unsigned int adLen) + unsigned int *outputLen, unsigned int maxOutputLen, + const unsigned char *input, unsigned int inputLen, + const unsigned char *nonce, unsigned int nonceLen, + const unsigned char *ad, unsigned int adLen) { return ChaCha20Poly1305_Seal((ChaCha20Poly1305Context *)cx, output, outputLen, maxOutputLen, input, inputLen, @@ -1181,10 +1186,10 @@ chacha20_poly1305_Encrypt(void *cx, unsigned char *output, SECStatus chacha20_poly1305_Decrypt(void *cx, unsigned char *output, - unsigned int *outputLen, unsigned int maxOutputLen, - const unsigned char *input, unsigned int inputLen, - const unsigned char *nonce, unsigned int nonceLen, - const unsigned char *ad, unsigned int adLen) + unsigned int *outputLen, unsigned int maxOutputLen, + const unsigned char *input, unsigned int inputLen, + const unsigned char *nonce, unsigned int nonceLen, + const unsigned char *ad, unsigned int adLen) { return ChaCha20Poly1305_Open((ChaCha20Poly1305Context *)cx, output, outputLen, maxOutputLen, input, inputLen, @@ -1193,40 +1198,40 @@ chacha20_poly1305_Decrypt(void *cx, unsigned char *output, SECStatus camellia_Encrypt(void *cx, unsigned char *output, unsigned int *outputLen, - unsigned int maxOutputLen, const unsigned char *input, - unsigned int inputLen) + unsigned int maxOutputLen, const unsigned char *input, + unsigned int inputLen) { return Camellia_Encrypt((CamelliaContext *)cx, output, outputLen, - maxOutputLen, - input, inputLen); + maxOutputLen, + input, inputLen); } SECStatus camellia_Decrypt(void *cx, unsigned char *output, unsigned int *outputLen, - unsigned int maxOutputLen, const unsigned char *input, - unsigned int inputLen) + unsigned int maxOutputLen, const unsigned char *input, + unsigned int inputLen) { return Camellia_Decrypt((CamelliaContext *)cx, output, outputLen, - maxOutputLen, - input, inputLen); + maxOutputLen, + input, inputLen); } SECStatus seed_Encrypt(void *cx, unsigned char *output, unsigned int *outputLen, - unsigned int maxOutputLen, const unsigned char *input, - unsigned int inputLen) + unsigned int maxOutputLen, const unsigned char *input, + unsigned int inputLen) { return SEED_Encrypt((SEEDContext *)cx, output, outputLen, maxOutputLen, - input, inputLen); + input, inputLen); } SECStatus seed_Decrypt(void *cx, unsigned char *output, unsigned int *outputLen, - unsigned int maxOutputLen, const unsigned char *input, - unsigned int inputLen) + unsigned int maxOutputLen, const unsigned char *input, + unsigned int inputLen) { return SEED_Decrypt((SEEDContext *)cx, output, outputLen, maxOutputLen, - input, inputLen); + input, inputLen); } SECStatus @@ -1237,7 +1242,7 @@ rsa_PublicKeyOp(void *cx, SECItem *output, const SECItem *input) SECStatus rv = RSA_PublicKeyOp(pubKey, output->data, input->data); if (rv == SECSuccess) { output->len = pubKey->modulus.data[0] ? pubKey->modulus.len : - pubKey->modulus.len - 1; + pubKey->modulus.len - 1; } return rv; } @@ -1250,7 +1255,7 @@ rsa_PrivateKeyOp(void *cx, SECItem *output, const SECItem *input) SECStatus rv = RSA_PrivateKeyOp(privKey, output->data, input->data); if (rv == SECSuccess) { output->len = privKey->modulus.data[0] ? privKey->modulus.len : - privKey->modulus.len - 1; + privKey->modulus.len - 1; } return rv; } @@ -1336,10 +1341,10 @@ ecdsa_signDigest(void *cx, SECItem *output, const SECItem *input) bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx; if (params->cipherParams.ecdsa.sigseed.buf.len > 0) { return ECDSA_SignDigestWithSeed( - (ECPrivateKey *)params->privKey, - output, input, - params->cipherParams.ecdsa.sigseed.buf.data, - params->cipherParams.ecdsa.sigseed.buf.len); + (ECPrivateKey *)params->privKey, + output, input, + params->cipherParams.ecdsa.sigseed.buf.data, + params->cipherParams.ecdsa.sigseed.buf.len); } return ECDSA_SignDigest((ECPrivateKey *)params->privKey, output, input); } @@ -1360,35 +1365,43 @@ bltest_des_init(bltestCipherInfo *cipherInfo, PRBool encrypt) int minorMode; int i; switch (cipherInfo->mode) { - case bltestDES_ECB: minorMode = NSS_DES; break; - case bltestDES_CBC: minorMode = NSS_DES_CBC; break; - case bltestDES_EDE_ECB: minorMode = NSS_DES_EDE3; break; - case bltestDES_EDE_CBC: minorMode = NSS_DES_EDE3_CBC; break; - default: - return SECFailure; + case bltestDES_ECB: + minorMode = NSS_DES; + break; + case bltestDES_CBC: + minorMode = NSS_DES_CBC; + break; + case bltestDES_EDE_ECB: + minorMode = NSS_DES_EDE3; + break; + case bltestDES_EDE_CBC: + minorMode = NSS_DES_EDE3_CBC; + break; + default: + return SECFailure; } - cipherInfo->cx = (void*)DES_CreateContext(desp->key.buf.data, - desp->iv.buf.data, - minorMode, encrypt); + cipherInfo->cx = (void *)DES_CreateContext(desp->key.buf.data, + desp->iv.buf.data, + minorMode, encrypt); if (cipherInfo->cxreps > 0) { - DESContext **dummycx; - dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(DESContext *)); - TIMESTART(); - for (i=0; icxreps; i++) { - dummycx[i] = (void*)DES_CreateContext(desp->key.buf.data, - desp->iv.buf.data, - minorMode, encrypt); - } - TIMEFINISH(cipherInfo->cxtime, 1.0); - for (i=0; icxreps; i++) { - DES_DestroyContext(dummycx[i], PR_TRUE); - } - PORT_Free(dummycx); + DESContext **dummycx; + dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(DESContext *)); + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + dummycx[i] = (void *)DES_CreateContext(desp->key.buf.data, + desp->iv.buf.data, + minorMode, encrypt); + } + TIMEFINISH(cipherInfo->cxtime, 1.0); + for (i = 0; i < cipherInfo->cxreps; i++) { + DES_DestroyContext(dummycx[i], PR_TRUE); + } + PORT_Free(dummycx); } if (encrypt) - cipherInfo->cipher.symmkeyCipher = des_Encrypt; + cipherInfo->cipher.symmkeyCipher = des_Encrypt; else - cipherInfo->cipher.symmkeyCipher = des_Decrypt; + cipherInfo->cipher.symmkeyCipher = des_Decrypt; return SECSuccess; } @@ -1400,37 +1413,41 @@ bltest_rc2_init(bltestCipherInfo *cipherInfo, PRBool encrypt) int minorMode; int i; switch (cipherInfo->mode) { - case bltestRC2_ECB: minorMode = NSS_RC2; break; - case bltestRC2_CBC: minorMode = NSS_RC2_CBC; break; - default: - return SECFailure; + case bltestRC2_ECB: + minorMode = NSS_RC2; + break; + case bltestRC2_CBC: + minorMode = NSS_RC2_CBC; + break; + default: + return SECFailure; } - cipherInfo->cx = (void*)RC2_CreateContext(rc2p->key.buf.data, - rc2p->key.buf.len, - rc2p->iv.buf.data, - minorMode, - rc2p->key.buf.len); + cipherInfo->cx = (void *)RC2_CreateContext(rc2p->key.buf.data, + rc2p->key.buf.len, + rc2p->iv.buf.data, + minorMode, + rc2p->key.buf.len); if (cipherInfo->cxreps > 0) { - RC2Context **dummycx; - dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC2Context *)); - TIMESTART(); - for (i=0; icxreps; i++) { - dummycx[i] = (void*)RC2_CreateContext(rc2p->key.buf.data, - rc2p->key.buf.len, - rc2p->iv.buf.data, - minorMode, - rc2p->key.buf.len); - } - TIMEFINISH(cipherInfo->cxtime, 1.0); - for (i=0; icxreps; i++) { - RC2_DestroyContext(dummycx[i], PR_TRUE); - } - PORT_Free(dummycx); + RC2Context **dummycx; + dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC2Context *)); + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + dummycx[i] = (void *)RC2_CreateContext(rc2p->key.buf.data, + rc2p->key.buf.len, + rc2p->iv.buf.data, + minorMode, + rc2p->key.buf.len); + } + TIMEFINISH(cipherInfo->cxtime, 1.0); + for (i = 0; i < cipherInfo->cxreps; i++) { + RC2_DestroyContext(dummycx[i], PR_TRUE); + } + PORT_Free(dummycx); } if (encrypt) - cipherInfo->cipher.symmkeyCipher = rc2_Encrypt; + cipherInfo->cipher.symmkeyCipher = rc2_Encrypt; else - cipherInfo->cipher.symmkeyCipher = rc2_Decrypt; + cipherInfo->cipher.symmkeyCipher = rc2_Decrypt; return SECSuccess; } @@ -1440,26 +1457,26 @@ bltest_rc4_init(bltestCipherInfo *cipherInfo, PRBool encrypt) PRIntervalTime time1, time2; int i; bltestSymmKeyParams *rc4p = &cipherInfo->params.sk; - cipherInfo->cx = (void*)RC4_CreateContext(rc4p->key.buf.data, - rc4p->key.buf.len); + cipherInfo->cx = (void *)RC4_CreateContext(rc4p->key.buf.data, + rc4p->key.buf.len); if (cipherInfo->cxreps > 0) { - RC4Context **dummycx; - dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC4Context *)); - TIMESTART(); - for (i=0; icxreps; i++) { - dummycx[i] = (void*)RC4_CreateContext(rc4p->key.buf.data, - rc4p->key.buf.len); - } - TIMEFINISH(cipherInfo->cxtime, 1.0); - for (i=0; icxreps; i++) { - RC4_DestroyContext(dummycx[i], PR_TRUE); - } - PORT_Free(dummycx); + RC4Context **dummycx; + dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC4Context *)); + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + dummycx[i] = (void *)RC4_CreateContext(rc4p->key.buf.data, + rc4p->key.buf.len); + } + TIMEFINISH(cipherInfo->cxtime, 1.0); + for (i = 0; i < cipherInfo->cxreps; i++) { + RC4_DestroyContext(dummycx[i], PR_TRUE); + } + PORT_Free(dummycx); } if (encrypt) - cipherInfo->cipher.symmkeyCipher = rc4_Encrypt; + cipherInfo->cipher.symmkeyCipher = rc4_Encrypt; else - cipherInfo->cipher.symmkeyCipher = rc4_Decrypt; + cipherInfo->cipher.symmkeyCipher = rc4_Decrypt; return SECSuccess; } @@ -1471,20 +1488,24 @@ bltest_rc5_init(bltestCipherInfo *cipherInfo, PRBool encrypt) bltestRC5Params *rc5p = &cipherInfo->params.rc5; int minorMode; switch (cipherInfo->mode) { - case bltestRC5_ECB: minorMode = NSS_RC5; break; - case bltestRC5_CBC: minorMode = NSS_RC5_CBC; break; - default: - return SECFailure; + case bltestRC5_ECB: + minorMode = NSS_RC5; + break; + case bltestRC5_CBC: + minorMode = NSS_RC5_CBC; + break; + default: + return SECFailure; } TIMESTART(); - cipherInfo->cx = (void*)RC5_CreateContext(&rc5p->key.buf, - rc5p->rounds, rc5p->wordsize, - rc5p->iv.buf.data, minorMode); + cipherInfo->cx = (void *)RC5_CreateContext(&rc5p->key.buf, + rc5p->rounds, rc5p->wordsize, + rc5p->iv.buf.data, minorMode); TIMEFINISH(cipherInfo->cxtime, 1.0); if (encrypt) - cipherInfo->cipher.symmkeyCipher = RC5_Encrypt; + cipherInfo->cipher.symmkeyCipher = RC5_Encrypt; else - cipherInfo->cipher.symmkeyCipher = RC5_Decrypt; + cipherInfo->cipher.symmkeyCipher = RC5_Decrypt; return SECSuccess; #else return SECFailure; @@ -1498,7 +1519,7 @@ bltest_aes_init(bltestCipherInfo *cipherInfo, PRBool encrypt) bltestAuthSymmKeyParams *gcmp = &cipherInfo->params.ask; int minorMode; int i; - int keylen = aesp->key.buf.len; + int keylen = aesp->key.buf.len; unsigned int blocklen = AES_BLOCK_SIZE; PRIntervalTime time1, time2; unsigned char *params; @@ -1508,53 +1529,59 @@ bltest_aes_init(bltestCipherInfo *cipherInfo, PRBool encrypt) params = aesp->iv.buf.data; switch (cipherInfo->mode) { - case bltestAES_ECB: minorMode = NSS_AES; break; - case bltestAES_CBC: minorMode = NSS_AES_CBC; break; - case bltestAES_CTS: minorMode = NSS_AES_CTS; break; - case bltestAES_CTR: - minorMode = NSS_AES_CTR; - ctrParams.ulCounterBits = 32; - len = PR_MIN(aesp->iv.buf.len, blocklen); - PORT_Memset(ctrParams.cb, 0, blocklen); - PORT_Memcpy(ctrParams.cb, aesp->iv.buf.data, len); - params = (unsigned char *)&ctrParams; - break; - case bltestAES_GCM: - minorMode = NSS_AES_GCM; - gcmParams.pIv = gcmp->sk.iv.buf.data; - gcmParams.ulIvLen = gcmp->sk.iv.buf.len; - gcmParams.pAAD = gcmp->aad.buf.data; - gcmParams.ulAADLen = gcmp->aad.buf.len; - gcmParams.ulTagBits = blocklen*8; - params = (unsigned char *)&gcmParams; - break; - default: - return SECFailure; + case bltestAES_ECB: + minorMode = NSS_AES; + break; + case bltestAES_CBC: + minorMode = NSS_AES_CBC; + break; + case bltestAES_CTS: + minorMode = NSS_AES_CTS; + break; + case bltestAES_CTR: + minorMode = NSS_AES_CTR; + ctrParams.ulCounterBits = 32; + len = PR_MIN(aesp->iv.buf.len, blocklen); + PORT_Memset(ctrParams.cb, 0, blocklen); + PORT_Memcpy(ctrParams.cb, aesp->iv.buf.data, len); + params = (unsigned char *)&ctrParams; + break; + case bltestAES_GCM: + minorMode = NSS_AES_GCM; + gcmParams.pIv = gcmp->sk.iv.buf.data; + gcmParams.ulIvLen = gcmp->sk.iv.buf.len; + gcmParams.pAAD = gcmp->aad.buf.data; + gcmParams.ulAADLen = gcmp->aad.buf.len; + gcmParams.ulTagBits = blocklen * 8; + params = (unsigned char *)&gcmParams; + break; + default: + return SECFailure; } - cipherInfo->cx = (void*)AES_CreateContext(aesp->key.buf.data, - params, - minorMode, encrypt, - keylen, blocklen); + cipherInfo->cx = (void *)AES_CreateContext(aesp->key.buf.data, + params, + minorMode, encrypt, + keylen, blocklen); if (cipherInfo->cxreps > 0) { - AESContext **dummycx; - dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(AESContext *)); - TIMESTART(); - for (i=0; icxreps; i++) { - dummycx[i] = (void*)AES_CreateContext(aesp->key.buf.data, - params, - minorMode, encrypt, - keylen, blocklen); - } - TIMEFINISH(cipherInfo->cxtime, 1.0); - for (i=0; icxreps; i++) { - AES_DestroyContext(dummycx[i], PR_TRUE); - } - PORT_Free(dummycx); + AESContext **dummycx; + dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(AESContext *)); + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + dummycx[i] = (void *)AES_CreateContext(aesp->key.buf.data, + params, + minorMode, encrypt, + keylen, blocklen); + } + TIMEFINISH(cipherInfo->cxtime, 1.0); + for (i = 0; i < cipherInfo->cxreps; i++) { + AES_DestroyContext(dummycx[i], PR_TRUE); + } + PORT_Free(dummycx); } if (encrypt) - cipherInfo->cipher.symmkeyCipher = aes_Encrypt; + cipherInfo->cipher.symmkeyCipher = aes_Encrypt; else - cipherInfo->cipher.symmkeyCipher = aes_Decrypt; + cipherInfo->cipher.symmkeyCipher = aes_Decrypt; return SECSuccess; } @@ -1564,39 +1591,43 @@ bltest_camellia_init(bltestCipherInfo *cipherInfo, PRBool encrypt) bltestSymmKeyParams *camelliap = &cipherInfo->params.sk; int minorMode; int i; - int keylen = camelliap->key.buf.len; + int keylen = camelliap->key.buf.len; PRIntervalTime time1, time2; - + switch (cipherInfo->mode) { - case bltestCAMELLIA_ECB: minorMode = NSS_CAMELLIA; break; - case bltestCAMELLIA_CBC: minorMode = NSS_CAMELLIA_CBC; break; - default: - return SECFailure; + case bltestCAMELLIA_ECB: + minorMode = NSS_CAMELLIA; + break; + case bltestCAMELLIA_CBC: + minorMode = NSS_CAMELLIA_CBC; + break; + default: + return SECFailure; } - cipherInfo->cx = (void*)Camellia_CreateContext(camelliap->key.buf.data, - camelliap->iv.buf.data, - minorMode, encrypt, - keylen); + cipherInfo->cx = (void *)Camellia_CreateContext(camelliap->key.buf.data, + camelliap->iv.buf.data, + minorMode, encrypt, + keylen); if (cipherInfo->cxreps > 0) { - CamelliaContext **dummycx; - dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(CamelliaContext *)); - TIMESTART(); - for (i=0; icxreps; i++) { - dummycx[i] = (void*)Camellia_CreateContext(camelliap->key.buf.data, - camelliap->iv.buf.data, - minorMode, encrypt, - keylen); - } - TIMEFINISH(cipherInfo->cxtime, 1.0); - for (i=0; icxreps; i++) { - Camellia_DestroyContext(dummycx[i], PR_TRUE); - } - PORT_Free(dummycx); + CamelliaContext **dummycx; + dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(CamelliaContext *)); + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + dummycx[i] = (void *)Camellia_CreateContext(camelliap->key.buf.data, + camelliap->iv.buf.data, + minorMode, encrypt, + keylen); + } + TIMEFINISH(cipherInfo->cxtime, 1.0); + for (i = 0; i < cipherInfo->cxreps; i++) { + Camellia_DestroyContext(dummycx[i], PR_TRUE); + } + PORT_Free(dummycx); } if (encrypt) - cipherInfo->cipher.symmkeyCipher = camellia_Encrypt; + cipherInfo->cipher.symmkeyCipher = camellia_Encrypt; else - cipherInfo->cipher.symmkeyCipher = camellia_Decrypt; + cipherInfo->cipher.symmkeyCipher = camellia_Decrypt; return SECSuccess; } @@ -1609,35 +1640,39 @@ bltest_seed_init(bltestCipherInfo *cipherInfo, PRBool encrypt) int i; switch (cipherInfo->mode) { - case bltestSEED_ECB: minorMode = NSS_SEED; break; - case bltestSEED_CBC: minorMode = NSS_SEED_CBC; break; - default: - return SECFailure; + case bltestSEED_ECB: + minorMode = NSS_SEED; + break; + case bltestSEED_CBC: + minorMode = NSS_SEED_CBC; + break; + default: + return SECFailure; } - cipherInfo->cx = (void*)SEED_CreateContext(seedp->key.buf.data, - seedp->iv.buf.data, - minorMode, encrypt); + cipherInfo->cx = (void *)SEED_CreateContext(seedp->key.buf.data, + seedp->iv.buf.data, + minorMode, encrypt); if (cipherInfo->cxreps > 0) { - SEEDContext **dummycx; - dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(SEEDContext *)); - TIMESTART(); - for (i=0; icxreps; i++) { - dummycx[i] = (void*)SEED_CreateContext(seedp->key.buf.data, - seedp->iv.buf.data, - minorMode, encrypt); - } - TIMEFINISH(cipherInfo->cxtime, 1.0); - for (i=0; icxreps; i++) { - SEED_DestroyContext(dummycx[i], PR_TRUE); - } - PORT_Free(dummycx); + SEEDContext **dummycx; + dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(SEEDContext *)); + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + dummycx[i] = (void *)SEED_CreateContext(seedp->key.buf.data, + seedp->iv.buf.data, + minorMode, encrypt); + } + TIMEFINISH(cipherInfo->cxtime, 1.0); + for (i = 0; i < cipherInfo->cxreps; i++) { + SEED_DestroyContext(dummycx[i], PR_TRUE); + } + PORT_Free(dummycx); } if (encrypt) - cipherInfo->cipher.symmkeyCipher = seed_Encrypt; + cipherInfo->cipher.symmkeyCipher = seed_Encrypt; else - cipherInfo->cipher.symmkeyCipher = seed_Decrypt; - - return SECSuccess; + cipherInfo->cipher.symmkeyCipher = seed_Decrypt; + + return SECSuccess; } SECStatus @@ -1649,9 +1684,9 @@ bltest_chacha20_init(bltestCipherInfo *cipherInfo, PRBool encrypt) sk->key.buf.len, tagLen); if (encrypt) - cipherInfo->cipher.aeadCipher = chacha20_poly1305_Encrypt; + cipherInfo->cipher.aeadCipher = chacha20_poly1305_Encrypt; else - cipherInfo->cipher.aeadCipher = chacha20_poly1305_Decrypt; + cipherInfo->cipher.aeadCipher = chacha20_poly1305_Decrypt; return SECSuccess; } @@ -1673,32 +1708,32 @@ bltest_rsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt) /* For performance testing */ if (cipherInfo->cxreps > 0) { - /* Create space for n private key objects */ - dummyKey = (RSAPrivateKey **)PORT_Alloc(cipherInfo->cxreps * - sizeof(RSAPrivateKey *)); - /* Time n keygens, storing in the array */ - TIMESTART(); - for (i=0; icxreps; i++) - dummyKey[i] = RSA_NewKey(rsap->keysizeInBits, - &privKey->publicExponent); - TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps); - /* Free the n key objects */ - for (i=0; icxreps; i++) - PORT_FreeArena(dummyKey[i]->arena, PR_TRUE); - PORT_Free(dummyKey); + /* Create space for n private key objects */ + dummyKey = (RSAPrivateKey **)PORT_Alloc(cipherInfo->cxreps * + sizeof(RSAPrivateKey *)); + /* Time n keygens, storing in the array */ + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) + dummyKey[i] = RSA_NewKey(rsap->keysizeInBits, + &privKey->publicExponent); + TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps); + /* Free the n key objects */ + for (i = 0; i < cipherInfo->cxreps; i++) + PORT_FreeArena(dummyKey[i]->arena, PR_TRUE); + PORT_Free(dummyKey); } if ((encrypt && !is_sigCipher(cipherInfo->mode)) || (!encrypt && is_sigCipher(cipherInfo->mode))) { - /* Have to convert private key to public key. Memory - * is freed with private key's arena */ - pubKey = (RSAPublicKey *)PORT_ArenaAlloc(privKey->arena, - sizeof(RSAPublicKey)); - pubKey->modulus.len = privKey->modulus.len; - pubKey->modulus.data = privKey->modulus.data; - pubKey->publicExponent.len = privKey->publicExponent.len; - pubKey->publicExponent.data = privKey->publicExponent.data; - asymk->pubKey = (void *)pubKey; + /* Have to convert private key to public key. Memory + * is freed with private key's arena */ + pubKey = (RSAPublicKey *)PORT_ArenaAlloc(privKey->arena, + sizeof(RSAPublicKey)); + pubKey->modulus.len = privKey->modulus.len; + pubKey->modulus.data = privKey->modulus.data; + pubKey->publicExponent.len = privKey->publicExponent.len; + pubKey->publicExponent.data = privKey->publicExponent.data; + asymk->pubKey = (void *)pubKey; } switch (cipherInfo->mode) { case bltestRSA: @@ -1723,8 +1758,8 @@ SECStatus blapi_pqg_param_gen(unsigned int keysize, PQGParams **pqg, PQGVerify **vfy) { if (keysize < 1024) { - int j = PQG_PBITS_TO_INDEX(keysize); - return PQG_ParamGen(j, pqg, vfy); + int j = PQG_PBITS_TO_INDEX(keysize); + return PQG_ParamGen(j, pqg, vfy); } return PQG_ParamGenV2(keysize, 0, 0, pqg, vfy); } @@ -1755,47 +1790,47 @@ bltest_dsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt) cipherInfo->cx = asymk; /* For performance testing */ if (cipherInfo->cxreps > 0) { - /* Create space for n private key objects */ - dummyKey = (DSAPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps * - sizeof(DSAPrivateKey *)); - /* Time n keygens, storing in the array */ - TIMESTART(); - for (i=0; icxreps; i++) { - dummypqg = NULL; - blapi_pqg_param_gen(dsap->keysize, &dummypqg, &ignore); - DSA_NewKey(dummypqg, &dummyKey[i]); - } - TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps); - /* Free the n key objects */ - for (i=0; icxreps; i++) - PORT_FreeArena(dummyKey[i]->params.arena, PR_TRUE); - PORT_Free(dummyKey); + /* Create space for n private key objects */ + dummyKey = (DSAPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps * + sizeof(DSAPrivateKey *)); + /* Time n keygens, storing in the array */ + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + dummypqg = NULL; + blapi_pqg_param_gen(dsap->keysize, &dummypqg, &ignore); + DSA_NewKey(dummypqg, &dummyKey[i]); + } + TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps); + /* Free the n key objects */ + for (i = 0; i < cipherInfo->cxreps; i++) + PORT_FreeArena(dummyKey[i]->params.arena, PR_TRUE); + PORT_Free(dummyKey); } if (!dsap->pqg && dsap->pqgdata.buf.len > 0) { - dsap->pqg = pqg_from_filedata(&dsap->pqgdata.buf); + dsap->pqg = pqg_from_filedata(&dsap->pqgdata.buf); } if (!asymk->privKey && asymk->key.buf.len > 0) { - asymk->privKey = dsakey_from_filedata(&asymk->key.buf); + asymk->privKey = dsakey_from_filedata(&asymk->key.buf); } if (encrypt) { - cipherInfo->cipher.pubkeyCipher = dsa_signDigest; + cipherInfo->cipher.pubkeyCipher = dsa_signDigest; } else { - /* Have to convert private key to public key. Memory - * is freed with private key's arena */ - DSAPublicKey *pubkey; - DSAPrivateKey *key = (DSAPrivateKey *)asymk->privKey; - pubkey = (DSAPublicKey *)PORT_ArenaZAlloc(key->params.arena, - sizeof(DSAPublicKey)); - pubkey->params.prime.len = key->params.prime.len; - pubkey->params.prime.data = key->params.prime.data; - pubkey->params.subPrime.len = key->params.subPrime.len; - pubkey->params.subPrime.data = key->params.subPrime.data; - pubkey->params.base.len = key->params.base.len; - pubkey->params.base.data = key->params.base.data; - pubkey->publicValue.len = key->publicValue.len; - pubkey->publicValue.data = key->publicValue.data; - asymk->pubKey = pubkey; - cipherInfo->cipher.pubkeyCipher = dsa_verifyDigest; + /* Have to convert private key to public key. Memory + * is freed with private key's arena */ + DSAPublicKey *pubkey; + DSAPrivateKey *key = (DSAPrivateKey *)asymk->privKey; + pubkey = (DSAPublicKey *)PORT_ArenaZAlloc(key->params.arena, + sizeof(DSAPublicKey)); + pubkey->params.prime.len = key->params.prime.len; + pubkey->params.prime.data = key->params.prime.data; + pubkey->params.subPrime.len = key->params.subPrime.len; + pubkey->params.subPrime.data = key->params.subPrime.data; + pubkey->params.base.len = key->params.base.len; + pubkey->params.base.data = key->params.base.data; + pubkey->publicValue.len = key->publicValue.len; + pubkey->publicValue.data = key->publicValue.data; + asymk->pubKey = pubkey; + cipherInfo->cipher.pubkeyCipher = dsa_verifyDigest; } return SECSuccess; } @@ -1811,58 +1846,58 @@ bltest_ecdsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt) cipherInfo->cx = asymk; /* For performance testing */ if (cipherInfo->cxreps > 0) { - /* Create space for n private key objects */ - dummyKey = (ECPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps * - sizeof(ECPrivateKey *)); - /* Time n keygens, storing in the array */ - TIMESTART(); - for (i=0; icxreps; i++) { - EC_NewKey(&((ECPrivateKey *)asymk->privKey)->ecParams, &dummyKey[i]); - } - TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps); - /* Free the n key objects */ - for (i=0; icxreps; i++) - PORT_FreeArena(dummyKey[i]->ecParams.arena, PR_TRUE); - PORT_Free(dummyKey); + /* Create space for n private key objects */ + dummyKey = (ECPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps * + sizeof(ECPrivateKey *)); + /* Time n keygens, storing in the array */ + TIMESTART(); + for (i = 0; i < cipherInfo->cxreps; i++) { + EC_NewKey(&((ECPrivateKey *)asymk->privKey)->ecParams, &dummyKey[i]); + } + TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps); + /* Free the n key objects */ + for (i = 0; i < cipherInfo->cxreps; i++) + PORT_FreeArena(dummyKey[i]->ecParams.arena, PR_TRUE); + PORT_Free(dummyKey); } if (!asymk->privKey && asymk->key.buf.len > 0) { asymk->privKey = eckey_from_filedata(&asymk->key.buf); } if (encrypt) { - cipherInfo->cipher.pubkeyCipher = ecdsa_signDigest; + cipherInfo->cipher.pubkeyCipher = ecdsa_signDigest; } else { - /* Have to convert private key to public key. Memory - * is freed with private key's arena */ - ECPublicKey *pubkey; - ECPrivateKey *key = (ECPrivateKey *)asymk->privKey; - pubkey = (ECPublicKey *)PORT_ArenaZAlloc(key->ecParams.arena, - sizeof(ECPublicKey)); - pubkey->ecParams.type = key->ecParams.type; - pubkey->ecParams.fieldID.size = key->ecParams.fieldID.size; - pubkey->ecParams.fieldID.type = key->ecParams.fieldID.type; - pubkey->ecParams.fieldID.u.prime.len = key->ecParams.fieldID.u.prime.len; - pubkey->ecParams.fieldID.u.prime.data = key->ecParams.fieldID.u.prime.data; - pubkey->ecParams.fieldID.k1 = key->ecParams.fieldID.k1; - pubkey->ecParams.fieldID.k2 = key->ecParams.fieldID.k2; - pubkey->ecParams.fieldID.k3 = key->ecParams.fieldID.k3; - pubkey->ecParams.curve.a.len = key->ecParams.curve.a.len; - pubkey->ecParams.curve.a.data = key->ecParams.curve.a.data; - pubkey->ecParams.curve.b.len = key->ecParams.curve.b.len; - pubkey->ecParams.curve.b.data = key->ecParams.curve.b.data; - pubkey->ecParams.curve.seed.len = key->ecParams.curve.seed.len; - pubkey->ecParams.curve.seed.data = key->ecParams.curve.seed.data; - pubkey->ecParams.base.len = key->ecParams.base.len; - pubkey->ecParams.base.data = key->ecParams.base.data; - pubkey->ecParams.order.len = key->ecParams.order.len; - pubkey->ecParams.order.data = key->ecParams.order.data; - pubkey->ecParams.cofactor = key->ecParams.cofactor; - pubkey->ecParams.DEREncoding.len = key->ecParams.DEREncoding.len; - pubkey->ecParams.DEREncoding.data = key->ecParams.DEREncoding.data; - pubkey->ecParams.name= key->ecParams.name; - pubkey->publicValue.len = key->publicValue.len; - pubkey->publicValue.data = key->publicValue.data; - asymk->pubKey = pubkey; - cipherInfo->cipher.pubkeyCipher = ecdsa_verifyDigest; + /* Have to convert private key to public key. Memory + * is freed with private key's arena */ + ECPublicKey *pubkey; + ECPrivateKey *key = (ECPrivateKey *)asymk->privKey; + pubkey = (ECPublicKey *)PORT_ArenaZAlloc(key->ecParams.arena, + sizeof(ECPublicKey)); + pubkey->ecParams.type = key->ecParams.type; + pubkey->ecParams.fieldID.size = key->ecParams.fieldID.size; + pubkey->ecParams.fieldID.type = key->ecParams.fieldID.type; + pubkey->ecParams.fieldID.u.prime.len = key->ecParams.fieldID.u.prime.len; + pubkey->ecParams.fieldID.u.prime.data = key->ecParams.fieldID.u.prime.data; + pubkey->ecParams.fieldID.k1 = key->ecParams.fieldID.k1; + pubkey->ecParams.fieldID.k2 = key->ecParams.fieldID.k2; + pubkey->ecParams.fieldID.k3 = key->ecParams.fieldID.k3; + pubkey->ecParams.curve.a.len = key->ecParams.curve.a.len; + pubkey->ecParams.curve.a.data = key->ecParams.curve.a.data; + pubkey->ecParams.curve.b.len = key->ecParams.curve.b.len; + pubkey->ecParams.curve.b.data = key->ecParams.curve.b.data; + pubkey->ecParams.curve.seed.len = key->ecParams.curve.seed.len; + pubkey->ecParams.curve.seed.data = key->ecParams.curve.seed.data; + pubkey->ecParams.base.len = key->ecParams.base.len; + pubkey->ecParams.base.data = key->ecParams.base.data; + pubkey->ecParams.order.len = key->ecParams.order.len; + pubkey->ecParams.order.data = key->ecParams.order.data; + pubkey->ecParams.cofactor = key->ecParams.cofactor; + pubkey->ecParams.DEREncoding.len = key->ecParams.DEREncoding.len; + pubkey->ecParams.DEREncoding.data = key->ecParams.DEREncoding.data; + pubkey->ecParams.name = key->ecParams.name; + pubkey->publicValue.len = key->publicValue.len; + pubkey->publicValue.data = key->publicValue.data; + asymk->pubKey = pubkey; + cipherInfo->cipher.pubkeyCipher = ecdsa_verifyDigest; } return SECSuccess; } @@ -1874,7 +1909,8 @@ md2_HashBuf(unsigned char *dest, const unsigned char *src, PRUint32 src_length) { unsigned int len; MD2Context *cx = MD2_NewContext(); - if (cx == NULL) return SECFailure; + if (cx == NULL) + return SECFailure; MD2_Begin(cx); MD2_Update(cx, src, src_length); MD2_End(cx, dest, &len, MD2_LENGTH); @@ -1893,26 +1929,26 @@ md2_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_length) cx = MD2_NewContext(); MD2_Begin(cx); /* divide message by 4, restarting 3 times */ - quarter = (src_length + 3)/ 4; - for (i=0; i < 4 && src_length > 0; i++) { - MD2_Update(cx, src + i*quarter, PR_MIN(quarter, src_length)); - len = MD2_FlattenSize(cx); - cxbytes = PORT_Alloc(len); - MD2_Flatten(cx, cxbytes); - cx_cpy = MD2_Resurrect(cxbytes, NULL); - if (!cx_cpy) { - PR_fprintf(PR_STDERR, "%s: MD2_Resurrect failed!\n", progName); - goto finish; - } - rv = PORT_Memcmp(cx, cx_cpy, len); - if (rv) { - MD2_DestroyContext(cx_cpy, PR_TRUE); - PR_fprintf(PR_STDERR, "%s: MD2_restart failed!\n", progName); - goto finish; - } - MD2_DestroyContext(cx_cpy, PR_TRUE); - PORT_Free(cxbytes); - src_length -= quarter; + quarter = (src_length + 3) / 4; + for (i = 0; i < 4 && src_length > 0; i++) { + MD2_Update(cx, src + i * quarter, PR_MIN(quarter, src_length)); + len = MD2_FlattenSize(cx); + cxbytes = PORT_Alloc(len); + MD2_Flatten(cx, cxbytes); + cx_cpy = MD2_Resurrect(cxbytes, NULL); + if (!cx_cpy) { + PR_fprintf(PR_STDERR, "%s: MD2_Resurrect failed!\n", progName); + goto finish; + } + rv = PORT_Memcmp(cx, cx_cpy, len); + if (rv) { + MD2_DestroyContext(cx_cpy, PR_TRUE); + PR_fprintf(PR_STDERR, "%s: MD2_restart failed!\n", progName); + goto finish; + } + MD2_DestroyContext(cx_cpy, PR_TRUE); + PORT_Free(cxbytes); + src_length -= quarter; } MD2_End(cx, dest, &len, MD2_LENGTH); finish: @@ -1931,27 +1967,27 @@ md5_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_length) cx = MD5_NewContext(); MD5_Begin(cx); /* divide message by 4, restarting 3 times */ - quarter = (src_length + 3)/ 4; - for (i=0; i < 4 && src_length > 0; i++) { - MD5_Update(cx, src + i*quarter, PR_MIN(quarter, src_length)); - len = MD5_FlattenSize(cx); - cxbytes = PORT_Alloc(len); - MD5_Flatten(cx, cxbytes); - cx_cpy = MD5_Resurrect(cxbytes, NULL); - if (!cx_cpy) { - PR_fprintf(PR_STDERR, "%s: MD5_Resurrect failed!\n", progName); - rv = SECFailure; - goto finish; - } - rv = PORT_Memcmp(cx, cx_cpy, len); - if (rv) { - MD5_DestroyContext(cx_cpy, PR_TRUE); - PR_fprintf(PR_STDERR, "%s: MD5_restart failed!\n", progName); - goto finish; - } - MD5_DestroyContext(cx_cpy, PR_TRUE); - PORT_Free(cxbytes); - src_length -= quarter; + quarter = (src_length + 3) / 4; + for (i = 0; i < 4 && src_length > 0; i++) { + MD5_Update(cx, src + i * quarter, PR_MIN(quarter, src_length)); + len = MD5_FlattenSize(cx); + cxbytes = PORT_Alloc(len); + MD5_Flatten(cx, cxbytes); + cx_cpy = MD5_Resurrect(cxbytes, NULL); + if (!cx_cpy) { + PR_fprintf(PR_STDERR, "%s: MD5_Resurrect failed!\n", progName); + rv = SECFailure; + goto finish; + } + rv = PORT_Memcmp(cx, cx_cpy, len); + if (rv) { + MD5_DestroyContext(cx_cpy, PR_TRUE); + PR_fprintf(PR_STDERR, "%s: MD5_restart failed!\n", progName); + goto finish; + } + MD5_DestroyContext(cx_cpy, PR_TRUE); + PORT_Free(cxbytes); + src_length -= quarter; } MD5_End(cx, dest, &len, MD5_LENGTH); finish: @@ -1970,27 +2006,27 @@ sha1_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_length) cx = SHA1_NewContext(); SHA1_Begin(cx); /* divide message by 4, restarting 3 times */ - quarter = (src_length + 3)/ 4; - for (i=0; i < 4 && src_length > 0; i++) { - SHA1_Update(cx, src + i*quarter, PR_MIN(quarter, src_length)); - len = SHA1_FlattenSize(cx); - cxbytes = PORT_Alloc(len); - SHA1_Flatten(cx, cxbytes); - cx_cpy = SHA1_Resurrect(cxbytes, NULL); - if (!cx_cpy) { - PR_fprintf(PR_STDERR, "%s: SHA1_Resurrect failed!\n", progName); - rv = SECFailure; - goto finish; - } - rv = PORT_Memcmp(cx, cx_cpy, len); - if (rv) { - SHA1_DestroyContext(cx_cpy, PR_TRUE); - PR_fprintf(PR_STDERR, "%s: SHA1_restart failed!\n", progName); - goto finish; - } - SHA1_DestroyContext(cx_cpy, PR_TRUE); - PORT_Free(cxbytes); - src_length -= quarter; + quarter = (src_length + 3) / 4; + for (i = 0; i < 4 && src_length > 0; i++) { + SHA1_Update(cx, src + i * quarter, PR_MIN(quarter, src_length)); + len = SHA1_FlattenSize(cx); + cxbytes = PORT_Alloc(len); + SHA1_Flatten(cx, cxbytes); + cx_cpy = SHA1_Resurrect(cxbytes, NULL); + if (!cx_cpy) { + PR_fprintf(PR_STDERR, "%s: SHA1_Resurrect failed!\n", progName); + rv = SECFailure; + goto finish; + } + rv = PORT_Memcmp(cx, cx_cpy, len); + if (rv) { + SHA1_DestroyContext(cx_cpy, PR_TRUE); + PR_fprintf(PR_STDERR, "%s: SHA1_restart failed!\n", progName); + goto finish; + } + SHA1_DestroyContext(cx_cpy, PR_TRUE); + PORT_Free(cxbytes); + src_length -= quarter; } SHA1_End(cx, dest, &len, MD5_LENGTH); finish: @@ -2010,27 +2046,27 @@ SHA224_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_lengt SHA224_Begin(cx); /* divide message by 4, restarting 3 times */ quarter = (src_length + 3) / 4; - for (i=0; i < 4 && src_length > 0; i++) { - SHA224_Update(cx, src + i*quarter, PR_MIN(quarter, src_length)); - len = SHA224_FlattenSize(cx); - cxbytes = PORT_Alloc(len); - SHA224_Flatten(cx, cxbytes); - cx_cpy = SHA224_Resurrect(cxbytes, NULL); - if (!cx_cpy) { - PR_fprintf(PR_STDERR, "%s: SHA224_Resurrect failed!\n", progName); - rv = SECFailure; - goto finish; - } - rv = PORT_Memcmp(cx, cx_cpy, len); - if (rv) { - SHA224_DestroyContext(cx_cpy, PR_TRUE); - PR_fprintf(PR_STDERR, "%s: SHA224_restart failed!\n", progName); - goto finish; - } - - SHA224_DestroyContext(cx_cpy, PR_TRUE); - PORT_Free(cxbytes); - src_length -= quarter; + for (i = 0; i < 4 && src_length > 0; i++) { + SHA224_Update(cx, src + i * quarter, PR_MIN(quarter, src_length)); + len = SHA224_FlattenSize(cx); + cxbytes = PORT_Alloc(len); + SHA224_Flatten(cx, cxbytes); + cx_cpy = SHA224_Resurrect(cxbytes, NULL); + if (!cx_cpy) { + PR_fprintf(PR_STDERR, "%s: SHA224_Resurrect failed!\n", progName); + rv = SECFailure; + goto finish; + } + rv = PORT_Memcmp(cx, cx_cpy, len); + if (rv) { + SHA224_DestroyContext(cx_cpy, PR_TRUE); + PR_fprintf(PR_STDERR, "%s: SHA224_restart failed!\n", progName); + goto finish; + } + + SHA224_DestroyContext(cx_cpy, PR_TRUE); + PORT_Free(cxbytes); + src_length -= quarter; } SHA224_End(cx, dest, &len, MD5_LENGTH); finish: @@ -2049,27 +2085,27 @@ SHA256_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_lengt cx = SHA256_NewContext(); SHA256_Begin(cx); /* divide message by 4, restarting 3 times */ - quarter = (src_length + 3)/ 4; - for (i=0; i < 4 && src_length > 0; i++) { - SHA256_Update(cx, src + i*quarter, PR_MIN(quarter, src_length)); - len = SHA256_FlattenSize(cx); - cxbytes = PORT_Alloc(len); - SHA256_Flatten(cx, cxbytes); - cx_cpy = SHA256_Resurrect(cxbytes, NULL); - if (!cx_cpy) { - PR_fprintf(PR_STDERR, "%s: SHA256_Resurrect failed!\n", progName); - rv = SECFailure; - goto finish; - } - rv = PORT_Memcmp(cx, cx_cpy, len); - if (rv) { - SHA256_DestroyContext(cx_cpy, PR_TRUE); - PR_fprintf(PR_STDERR, "%s: SHA256_restart failed!\n", progName); - goto finish; - } - SHA256_DestroyContext(cx_cpy, PR_TRUE); - PORT_Free(cxbytes); - src_length -= quarter; + quarter = (src_length + 3) / 4; + for (i = 0; i < 4 && src_length > 0; i++) { + SHA256_Update(cx, src + i * quarter, PR_MIN(quarter, src_length)); + len = SHA256_FlattenSize(cx); + cxbytes = PORT_Alloc(len); + SHA256_Flatten(cx, cxbytes); + cx_cpy = SHA256_Resurrect(cxbytes, NULL); + if (!cx_cpy) { + PR_fprintf(PR_STDERR, "%s: SHA256_Resurrect failed!\n", progName); + rv = SECFailure; + goto finish; + } + rv = PORT_Memcmp(cx, cx_cpy, len); + if (rv) { + SHA256_DestroyContext(cx_cpy, PR_TRUE); + PR_fprintf(PR_STDERR, "%s: SHA256_restart failed!\n", progName); + goto finish; + } + SHA256_DestroyContext(cx_cpy, PR_TRUE); + PORT_Free(cxbytes); + src_length -= quarter; } SHA256_End(cx, dest, &len, MD5_LENGTH); finish: @@ -2088,27 +2124,27 @@ SHA384_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_lengt cx = SHA384_NewContext(); SHA384_Begin(cx); /* divide message by 4, restarting 3 times */ - quarter = (src_length + 3)/ 4; - for (i=0; i < 4 && src_length > 0; i++) { - SHA384_Update(cx, src + i*quarter, PR_MIN(quarter, src_length)); - len = SHA384_FlattenSize(cx); - cxbytes = PORT_Alloc(len); - SHA384_Flatten(cx, cxbytes); - cx_cpy = SHA384_Resurrect(cxbytes, NULL); - if (!cx_cpy) { - PR_fprintf(PR_STDERR, "%s: SHA384_Resurrect failed!\n", progName); - rv = SECFailure; - goto finish; - } - rv = PORT_Memcmp(cx, cx_cpy, len); - if (rv) { - SHA384_DestroyContext(cx_cpy, PR_TRUE); - PR_fprintf(PR_STDERR, "%s: SHA384_restart failed!\n", progName); - goto finish; - } - SHA384_DestroyContext(cx_cpy, PR_TRUE); - PORT_Free(cxbytes); - src_length -= quarter; + quarter = (src_length + 3) / 4; + for (i = 0; i < 4 && src_length > 0; i++) { + SHA384_Update(cx, src + i * quarter, PR_MIN(quarter, src_length)); + len = SHA384_FlattenSize(cx); + cxbytes = PORT_Alloc(len); + SHA384_Flatten(cx, cxbytes); + cx_cpy = SHA384_Resurrect(cxbytes, NULL); + if (!cx_cpy) { + PR_fprintf(PR_STDERR, "%s: SHA384_Resurrect failed!\n", progName); + rv = SECFailure; + goto finish; + } + rv = PORT_Memcmp(cx, cx_cpy, len); + if (rv) { + SHA384_DestroyContext(cx_cpy, PR_TRUE); + PR_fprintf(PR_STDERR, "%s: SHA384_restart failed!\n", progName); + goto finish; + } + SHA384_DestroyContext(cx_cpy, PR_TRUE); + PORT_Free(cxbytes); + src_length -= quarter; } SHA384_End(cx, dest, &len, MD5_LENGTH); finish: @@ -2127,27 +2163,27 @@ SHA512_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_lengt cx = SHA512_NewContext(); SHA512_Begin(cx); /* divide message by 4, restarting 3 times */ - quarter = (src_length + 3)/ 4; - for (i=0; i < 4 && src_length > 0; i++) { - SHA512_Update(cx, src + i*quarter, PR_MIN(quarter, src_length)); - len = SHA512_FlattenSize(cx); - cxbytes = PORT_Alloc(len); - SHA512_Flatten(cx, cxbytes); - cx_cpy = SHA512_Resurrect(cxbytes, NULL); - if (!cx_cpy) { - PR_fprintf(PR_STDERR, "%s: SHA512_Resurrect failed!\n", progName); - rv = SECFailure; - goto finish; - } - rv = PORT_Memcmp(cx, cx_cpy, len); - if (rv) { - SHA512_DestroyContext(cx_cpy, PR_TRUE); - PR_fprintf(PR_STDERR, "%s: SHA512_restart failed!\n", progName); - goto finish; - } - SHA512_DestroyContext(cx_cpy, PR_TRUE); - PORT_Free(cxbytes); - src_length -= quarter; + quarter = (src_length + 3) / 4; + for (i = 0; i < 4 && src_length > 0; i++) { + SHA512_Update(cx, src + i * quarter, PR_MIN(quarter, src_length)); + len = SHA512_FlattenSize(cx); + cxbytes = PORT_Alloc(len); + SHA512_Flatten(cx, cxbytes); + cx_cpy = SHA512_Resurrect(cxbytes, NULL); + if (!cx_cpy) { + PR_fprintf(PR_STDERR, "%s: SHA512_Resurrect failed!\n", progName); + rv = SECFailure; + goto finish; + } + rv = PORT_Memcmp(cx, cx_cpy, len); + if (rv) { + SHA512_DestroyContext(cx_cpy, PR_TRUE); + PR_fprintf(PR_STDERR, "%s: SHA512_restart failed!\n", progName); + goto finish; + } + SHA512_DestroyContext(cx_cpy, PR_TRUE); + PORT_Free(cxbytes); + src_length -= quarter; } SHA512_End(cx, dest, &len, MD5_LENGTH); finish: @@ -2158,9 +2194,9 @@ SHA512_restart(unsigned char *dest, const unsigned char *src, PRUint32 src_lengt SECStatus pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file, #ifndef NSS_DISABLE_ECC - int keysize, int exponent, char *curveName) + int keysize, int exponent, char *curveName) #else - int keysize, int exponent) + int keysize, int exponent) #endif { int i; @@ -2177,74 +2213,74 @@ pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file, ECPrivateKey **ecKey = NULL; #endif switch (cipherInfo->mode) { - case bltestRSA: - case bltestRSA_PSS: - case bltestRSA_OAEP: - rsap = &asymk->cipherParams.rsa; - rsaKey = (RSAPrivateKey **)&asymk->privKey; - if (keysize > 0) { - SECItem expitem = { 0, 0, 0 }; - SECITEM_AllocItem(cipherInfo->arena, &expitem, sizeof(int)); - for (i = 1; i <= sizeof(int); i++) - expitem.data[i-1] = exponent >> (8*(sizeof(int) - i)); - *rsaKey = RSA_NewKey(keysize * 8, &expitem); - serialize_key(&(*rsaKey)->version, 9, file); - rsap->keysizeInBits = keysize * 8; - } else { - setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0); - *rsaKey = rsakey_from_filedata(&asymk->key.buf); - rsap->keysizeInBits = (*rsaKey)->modulus.len * 8; - } - break; - case bltestDSA: - dsap = &asymk->cipherParams.dsa; - dsaKey = (DSAPrivateKey **)&asymk->privKey; - if (keysize > 0) { - dsap->keysize = keysize*8; - if (!dsap->pqg) - bltest_pqg_init(dsap); - rv = DSA_NewKey(dsap->pqg, dsaKey); - CHECKERROR(rv, __LINE__); - serialize_key(&(*dsaKey)->params.prime, 5, file); - } else { - setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0); - *dsaKey = dsakey_from_filedata(&asymk->key.buf); - dsap->keysize = (*dsaKey)->params.prime.len*8; - } - break; + case bltestRSA: + case bltestRSA_PSS: + case bltestRSA_OAEP: + rsap = &asymk->cipherParams.rsa; + rsaKey = (RSAPrivateKey **)&asymk->privKey; + if (keysize > 0) { + SECItem expitem = { 0, 0, 0 }; + SECITEM_AllocItem(cipherInfo->arena, &expitem, sizeof(int)); + for (i = 1; i <= sizeof(int); i++) + expitem.data[i - 1] = exponent >> (8 * (sizeof(int) - i)); + *rsaKey = RSA_NewKey(keysize * 8, &expitem); + serialize_key(&(*rsaKey)->version, 9, file); + rsap->keysizeInBits = keysize * 8; + } else { + setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0); + *rsaKey = rsakey_from_filedata(&asymk->key.buf); + rsap->keysizeInBits = (*rsaKey)->modulus.len * 8; + } + break; + case bltestDSA: + dsap = &asymk->cipherParams.dsa; + dsaKey = (DSAPrivateKey **)&asymk->privKey; + if (keysize > 0) { + dsap->keysize = keysize * 8; + if (!dsap->pqg) + bltest_pqg_init(dsap); + rv = DSA_NewKey(dsap->pqg, dsaKey); + CHECKERROR(rv, __LINE__); + serialize_key(&(*dsaKey)->params.prime, 5, file); + } else { + setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0); + *dsaKey = dsakey_from_filedata(&asymk->key.buf); + dsap->keysize = (*dsaKey)->params.prime.len * 8; + } + break; #ifndef NSS_DISABLE_ECC - case bltestECDSA: - ecKey = (ECPrivateKey **)&asymk->privKey; - if (curveName != NULL) { - tmpECParamsDER = getECParams(curveName); - rv = SECOID_Init(); - CHECKERROR(rv, __LINE__); - rv = EC_DecodeParams(tmpECParamsDER, &tmpECParams) == SECFailure; - CHECKERROR(rv, __LINE__); - rv = EC_NewKey(tmpECParams, ecKey); - CHECKERROR(rv, __LINE__); - ecSerialize[0].type = tmpECParamsDER->type; - ecSerialize[0].data = tmpECParamsDER->data; - ecSerialize[0].len = tmpECParamsDER->len; - ecSerialize[1].type = (*ecKey)->publicValue.type; - ecSerialize[1].data = (*ecKey)->publicValue.data; - ecSerialize[1].len = (*ecKey)->publicValue.len; - ecSerialize[2].type = (*ecKey)->privateValue.type; - ecSerialize[2].data = (*ecKey)->privateValue.data; - ecSerialize[2].len = (*ecKey)->privateValue.len; - serialize_key(&(ecSerialize[0]), 3, file); - SECITEM_FreeItem(tmpECParamsDER, PR_TRUE); - PORT_FreeArena(tmpECParams->arena, PR_TRUE); - rv = SECOID_Shutdown(); - CHECKERROR(rv, __LINE__); - } else { - setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0); - *ecKey = eckey_from_filedata(&asymk->key.buf); - } - break; + case bltestECDSA: + ecKey = (ECPrivateKey **)&asymk->privKey; + if (curveName != NULL) { + tmpECParamsDER = getECParams(curveName); + rv = SECOID_Init(); + CHECKERROR(rv, __LINE__); + rv = EC_DecodeParams(tmpECParamsDER, &tmpECParams) == SECFailure; + CHECKERROR(rv, __LINE__); + rv = EC_NewKey(tmpECParams, ecKey); + CHECKERROR(rv, __LINE__); + ecSerialize[0].type = tmpECParamsDER->type; + ecSerialize[0].data = tmpECParamsDER->data; + ecSerialize[0].len = tmpECParamsDER->len; + ecSerialize[1].type = (*ecKey)->publicValue.type; + ecSerialize[1].data = (*ecKey)->publicValue.data; + ecSerialize[1].len = (*ecKey)->publicValue.len; + ecSerialize[2].type = (*ecKey)->privateValue.type; + ecSerialize[2].data = (*ecKey)->privateValue.data; + ecSerialize[2].len = (*ecKey)->privateValue.len; + serialize_key(&(ecSerialize[0]), 3, file); + SECITEM_FreeItem(tmpECParamsDER, PR_TRUE); + PORT_FreeArena(tmpECParams->arena, PR_TRUE); + rv = SECOID_Shutdown(); + CHECKERROR(rv, __LINE__); + } else { + setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0); + *ecKey = eckey_from_filedata(&asymk->key.buf); + } + break; #endif - default: - return SECFailure; + default: + return SECFailure; } return SECSuccess; } @@ -2255,144 +2291,144 @@ cipherInit(bltestCipherInfo *cipherInfo, PRBool encrypt) PRBool restart; int outlen; switch (cipherInfo->mode) { - case bltestDES_ECB: - case bltestDES_CBC: - case bltestDES_EDE_ECB: - case bltestDES_EDE_CBC: - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - cipherInfo->input.pBuf.len); - return bltest_des_init(cipherInfo, encrypt); - break; - case bltestRC2_ECB: - case bltestRC2_CBC: - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - cipherInfo->input.pBuf.len); - return bltest_rc2_init(cipherInfo, encrypt); - break; - case bltestRC4: - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - cipherInfo->input.pBuf.len); - return bltest_rc4_init(cipherInfo, encrypt); - break; + case bltestDES_ECB: + case bltestDES_CBC: + case bltestDES_EDE_ECB: + case bltestDES_EDE_CBC: + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + cipherInfo->input.pBuf.len); + return bltest_des_init(cipherInfo, encrypt); + break; + case bltestRC2_ECB: + case bltestRC2_CBC: + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + cipherInfo->input.pBuf.len); + return bltest_rc2_init(cipherInfo, encrypt); + break; + case bltestRC4: + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + cipherInfo->input.pBuf.len); + return bltest_rc4_init(cipherInfo, encrypt); + break; #ifdef NSS_SOFTOKEN_DOES_RC5 - case bltestRC5_ECB: - case bltestRC5_CBC: - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - cipherInfo->input.pBuf.len); + case bltestRC5_ECB: + case bltestRC5_CBC: + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + cipherInfo->input.pBuf.len); #endif - return bltest_rc5_init(cipherInfo, encrypt); - break; - case bltestAES_ECB: - case bltestAES_CBC: - case bltestAES_CTS: - case bltestAES_CTR: - case bltestAES_GCM: - outlen = cipherInfo->input.pBuf.len; - if (cipherInfo->mode == bltestAES_GCM && encrypt) { - outlen += 16; - } - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen); - return bltest_aes_init(cipherInfo, encrypt); - break; - case bltestCAMELLIA_ECB: - case bltestCAMELLIA_CBC: - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - cipherInfo->input.pBuf.len); - return bltest_camellia_init(cipherInfo, encrypt); - break; - case bltestSEED_ECB: - case bltestSEED_CBC: - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - cipherInfo->input.pBuf.len); - return bltest_seed_init(cipherInfo, encrypt); - break; - case bltestCHACHA20: - outlen = cipherInfo->input.pBuf.len + (encrypt ? 16 : 0); - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen); - return bltest_chacha20_init(cipherInfo, encrypt); - break; - case bltestRSA: - case bltestRSA_OAEP: - case bltestRSA_PSS: - if (encrypt || cipherInfo->mode != bltestRSA_PSS) { - /* Don't allocate a buffer for PSS in verify mode, as no actual - * output is produced. */ - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - RSA_MAX_MODULUS_BITS / 8); - } - return bltest_rsa_init(cipherInfo, encrypt); - break; - case bltestDSA: - if (encrypt) { - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - DSA_MAX_SIGNATURE_LEN); - } - return bltest_dsa_init(cipherInfo, encrypt); - break; + return bltest_rc5_init(cipherInfo, encrypt); + break; + case bltestAES_ECB: + case bltestAES_CBC: + case bltestAES_CTS: + case bltestAES_CTR: + case bltestAES_GCM: + outlen = cipherInfo->input.pBuf.len; + if (cipherInfo->mode == bltestAES_GCM && encrypt) { + outlen += 16; + } + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen); + return bltest_aes_init(cipherInfo, encrypt); + break; + case bltestCAMELLIA_ECB: + case bltestCAMELLIA_CBC: + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + cipherInfo->input.pBuf.len); + return bltest_camellia_init(cipherInfo, encrypt); + break; + case bltestSEED_ECB: + case bltestSEED_CBC: + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + cipherInfo->input.pBuf.len); + return bltest_seed_init(cipherInfo, encrypt); + break; + case bltestCHACHA20: + outlen = cipherInfo->input.pBuf.len + (encrypt ? 16 : 0); + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen); + return bltest_chacha20_init(cipherInfo, encrypt); + break; + case bltestRSA: + case bltestRSA_OAEP: + case bltestRSA_PSS: + if (encrypt || cipherInfo->mode != bltestRSA_PSS) { + /* Don't allocate a buffer for PSS in verify mode, as no actual + * output is produced. */ + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + RSA_MAX_MODULUS_BITS / 8); + } + return bltest_rsa_init(cipherInfo, encrypt); + break; + case bltestDSA: + if (encrypt) { + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + DSA_MAX_SIGNATURE_LEN); + } + return bltest_dsa_init(cipherInfo, encrypt); + break; #ifndef NSS_DISABLE_ECC - case bltestECDSA: - if (encrypt) { - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - 2 * MAX_ECKEY_LEN); - } - return bltest_ecdsa_init(cipherInfo, encrypt); - break; + case bltestECDSA: + if (encrypt) { + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + 2 * MAX_ECKEY_LEN); + } + return bltest_ecdsa_init(cipherInfo, encrypt); + break; #endif - case bltestMD2: - restart = cipherInfo->params.hash.restart; - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - MD2_LENGTH); - cipherInfo->cipher.hashCipher = (restart) ? md2_restart : md2_HashBuf; - return SECSuccess; - break; - case bltestMD5: - restart = cipherInfo->params.hash.restart; - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - MD5_LENGTH); - cipherInfo->cipher.hashCipher = (restart) ? md5_restart : MD5_HashBuf; - return SECSuccess; - break; - case bltestSHA1: - restart = cipherInfo->params.hash.restart; - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - SHA1_LENGTH); - cipherInfo->cipher.hashCipher = (restart) ? sha1_restart : SHA1_HashBuf; - return SECSuccess; - break; - case bltestSHA224: - restart = cipherInfo->params.hash.restart; - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - SHA224_LENGTH); - cipherInfo->cipher.hashCipher = (restart) ? SHA224_restart - : SHA224_HashBuf; - return SECSuccess; - break; - case bltestSHA256: - restart = cipherInfo->params.hash.restart; - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - SHA256_LENGTH); - cipherInfo->cipher.hashCipher = (restart) ? SHA256_restart - : SHA256_HashBuf; - return SECSuccess; - break; - case bltestSHA384: - restart = cipherInfo->params.hash.restart; - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - SHA384_LENGTH); - cipherInfo->cipher.hashCipher = (restart) ? SHA384_restart - : SHA384_HashBuf; - return SECSuccess; - break; - case bltestSHA512: - restart = cipherInfo->params.hash.restart; - SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, - SHA512_LENGTH); - cipherInfo->cipher.hashCipher = (restart) ? SHA512_restart - : SHA512_HashBuf; - return SECSuccess; - break; - default: - return SECFailure; + case bltestMD2: + restart = cipherInfo->params.hash.restart; + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + MD2_LENGTH); + cipherInfo->cipher.hashCipher = (restart) ? md2_restart : md2_HashBuf; + return SECSuccess; + break; + case bltestMD5: + restart = cipherInfo->params.hash.restart; + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + MD5_LENGTH); + cipherInfo->cipher.hashCipher = (restart) ? md5_restart : MD5_HashBuf; + return SECSuccess; + break; + case bltestSHA1: + restart = cipherInfo->params.hash.restart; + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + SHA1_LENGTH); + cipherInfo->cipher.hashCipher = (restart) ? sha1_restart : SHA1_HashBuf; + return SECSuccess; + break; + case bltestSHA224: + restart = cipherInfo->params.hash.restart; + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + SHA224_LENGTH); + cipherInfo->cipher.hashCipher = (restart) ? SHA224_restart + : SHA224_HashBuf; + return SECSuccess; + break; + case bltestSHA256: + restart = cipherInfo->params.hash.restart; + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + SHA256_LENGTH); + cipherInfo->cipher.hashCipher = (restart) ? SHA256_restart + : SHA256_HashBuf; + return SECSuccess; + break; + case bltestSHA384: + restart = cipherInfo->params.hash.restart; + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + SHA384_LENGTH); + cipherInfo->cipher.hashCipher = (restart) ? SHA384_restart + : SHA384_HashBuf; + return SECSuccess; + break; + case bltestSHA512: + restart = cipherInfo->params.hash.restart; + SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, + SHA512_LENGTH); + cipherInfo->cipher.hashCipher = (restart) ? SHA512_restart + : SHA512_HashBuf; + return SECSuccess; + break; + default: + return SECFailure; } return SECSuccess; } @@ -2409,9 +2445,8 @@ cipherDoOp(bltestCipherInfo *cipherInfo) dummyOut = PORT_Alloc(maxLen); if (is_symmkeyCipher(cipherInfo->mode)) { const unsigned char *input = cipherInfo->input.pBuf.data; - unsigned int inputLen = is_singleShotCipher(cipherInfo->mode) ? - cipherInfo->input.pBuf.len : - PR_MIN(cipherInfo->input.pBuf.len, 16); + unsigned int inputLen = is_singleShotCipher(cipherInfo->mode) ? cipherInfo->input.pBuf.len + : PR_MIN(cipherInfo->input.pBuf.len, 16); unsigned char *output = cipherInfo->output.pBuf.data; unsigned int outputLen = maxLen; unsigned int totalOutputLen = 0; @@ -2430,28 +2465,28 @@ cipherDoOp(bltestCipherInfo *cipherInfo) output, &len, outputLen, input, inputLen); CHECKERROR(rv, __LINE__); - totalOutputLen += len; + totalOutputLen += len; } - cipherInfo->output.pBuf.len = totalOutputLen; + cipherInfo->output.pBuf.len = totalOutputLen; TIMEFINISH(cipherInfo->optime, 1.0); cipherInfo->repetitions = 0; if (cipherInfo->repetitionsToPerfom != 0) { TIMESTART(); - for (i=0; irepetitionsToPerfom; i++, - cipherInfo->repetitions++) { + for (i = 0; i < cipherInfo->repetitionsToPerfom; i++, + cipherInfo->repetitions++) { (*cipherInfo->cipher.symmkeyCipher)(cipherInfo->cx, dummyOut, &len, maxLen, cipherInfo->input.pBuf.data, cipherInfo->input.pBuf.len); - + CHECKERROR(rv, __LINE__); } } else { int opsBetweenChecks = 0; TIMEMARK(cipherInfo->seconds); - while (! (TIMETOFINISH())) { + while (!(TIMETOFINISH())) { int j = 0; - for (;j < opsBetweenChecks;j++) { + for (; j < opsBetweenChecks; j++) { (*cipherInfo->cipher.symmkeyCipher)( cipherInfo->cx, dummyOut, &len, maxLen, cipherInfo->input.pBuf.data, @@ -2471,11 +2506,11 @@ cipherDoOp(bltestCipherInfo *cipherInfo) TIMESTART(); rv = (*cipherInfo->cipher.aeadCipher)( - cipherInfo->cx, - output, &outputLen, maxLen, - input, inputLen, - sk->iv.buf.data, sk->iv.buf.len, - ask->aad.buf.data, ask->aad.buf.len); + cipherInfo->cx, + output, &outputLen, maxLen, + input, inputLen, + sk->iv.buf.data, sk->iv.buf.len, + ask->aad.buf.data, ask->aad.buf.len); CHECKERROR(rv, __LINE__); cipherInfo->output.pBuf.len = outputLen; TIMEFINISH(cipherInfo->optime, 1.0); @@ -2483,28 +2518,28 @@ cipherDoOp(bltestCipherInfo *cipherInfo) cipherInfo->repetitions = 0; if (cipherInfo->repetitionsToPerfom != 0) { TIMESTART(); - for (i=0; irepetitionsToPerfom; i++, - cipherInfo->repetitions++) { + for (i = 0; i < cipherInfo->repetitionsToPerfom; i++, + cipherInfo->repetitions++) { rv = (*cipherInfo->cipher.aeadCipher)( - cipherInfo->cx, - output, &outputLen, maxLen, - input, inputLen, - sk->iv.buf.data, sk->iv.buf.len, - ask->aad.buf.data, ask->aad.buf.len); + cipherInfo->cx, + output, &outputLen, maxLen, + input, inputLen, + sk->iv.buf.data, sk->iv.buf.len, + ask->aad.buf.data, ask->aad.buf.len); CHECKERROR(rv, __LINE__); } } else { int opsBetweenChecks = 0; TIMEMARK(cipherInfo->seconds); - while (! (TIMETOFINISH())) { + while (!(TIMETOFINISH())) { int j = 0; - for (;j < opsBetweenChecks;j++) { + for (; j < opsBetweenChecks; j++) { (*cipherInfo->cipher.aeadCipher)( - cipherInfo->cx, - output, &outputLen, maxLen, - input, inputLen, - sk->iv.buf.data, sk->iv.buf.len, - ask->aad.buf.data, ask->aad.buf.len); + cipherInfo->cx, + output, &outputLen, maxLen, + input, inputLen, + sk->iv.buf.data, sk->iv.buf.len, + ask->aad.buf.data, ask->aad.buf.len); } cipherInfo->repetitions += j; } @@ -2520,21 +2555,21 @@ cipherDoOp(bltestCipherInfo *cipherInfo) cipherInfo->repetitions = 0; if (cipherInfo->repetitionsToPerfom != 0) { TIMESTART(); - for (i=0; irepetitionsToPerfom; + for (i = 0; i < cipherInfo->repetitionsToPerfom; i++, cipherInfo->repetitions++) { SECItem dummy; dummy.data = dummyOut; dummy.len = maxLen; - (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx, &dummy, + (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx, &dummy, &cipherInfo->input.pBuf); CHECKERROR(rv, __LINE__); } } else { int opsBetweenChecks = 0; TIMEMARK(cipherInfo->seconds); - while (! (TIMETOFINISH())) { + while (!(TIMETOFINISH())) { int j = 0; - for (;j < opsBetweenChecks;j++) { + for (; j < opsBetweenChecks; j++) { SECItem dummy; dummy.data = dummyOut; dummy.len = maxLen; @@ -2556,7 +2591,7 @@ cipherDoOp(bltestCipherInfo *cipherInfo) cipherInfo->repetitions = 0; if (cipherInfo->repetitionsToPerfom != 0) { TIMESTART(); - for (i=0; irepetitionsToPerfom; + for (i = 0; i < cipherInfo->repetitionsToPerfom; i++, cipherInfo->repetitions++) { (*cipherInfo->cipher.hashCipher)(dummyOut, cipherInfo->input.pBuf.data, @@ -2566,9 +2601,9 @@ cipherDoOp(bltestCipherInfo *cipherInfo) } else { int opsBetweenChecks = 0; TIMEMARK(cipherInfo->seconds); - while (! (TIMETOFINISH())) { + while (!(TIMETOFINISH())) { int j = 0; - for (;j < opsBetweenChecks;j++) { + for (; j < opsBetweenChecks; j++) { bltestIO *input = &cipherInfo->input; (*cipherInfo->cipher.hashCipher)(dummyOut, input->pBuf.data, @@ -2590,62 +2625,63 @@ cipherFinish(bltestCipherInfo *cipherInfo) SECStatus rv = SECSuccess; switch (cipherInfo->mode) { - case bltestDES_ECB: - case bltestDES_CBC: - case bltestDES_EDE_ECB: - case bltestDES_EDE_CBC: - DES_DestroyContext((DESContext *)cipherInfo->cx, PR_TRUE); - break; - case bltestAES_GCM: - case bltestAES_ECB: - case bltestAES_CBC: - case bltestAES_CTS: - case bltestAES_CTR: - AES_DestroyContext((AESContext *)cipherInfo->cx, PR_TRUE); - break; - case bltestCAMELLIA_ECB: - case bltestCAMELLIA_CBC: - Camellia_DestroyContext((CamelliaContext *)cipherInfo->cx, PR_TRUE); - break; - case bltestSEED_ECB: - case bltestSEED_CBC: - SEED_DestroyContext((SEEDContext *)cipherInfo->cx, PR_TRUE); - break; - case bltestCHACHA20: - ChaCha20Poly1305_DestroyContext((ChaCha20Poly1305Context *) - cipherInfo->cx, PR_TRUE); - break; - case bltestRC2_ECB: - case bltestRC2_CBC: - RC2_DestroyContext((RC2Context *)cipherInfo->cx, PR_TRUE); - break; - case bltestRC4: - RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE); - break; + case bltestDES_ECB: + case bltestDES_CBC: + case bltestDES_EDE_ECB: + case bltestDES_EDE_CBC: + DES_DestroyContext((DESContext *)cipherInfo->cx, PR_TRUE); + break; + case bltestAES_GCM: + case bltestAES_ECB: + case bltestAES_CBC: + case bltestAES_CTS: + case bltestAES_CTR: + AES_DestroyContext((AESContext *)cipherInfo->cx, PR_TRUE); + break; + case bltestCAMELLIA_ECB: + case bltestCAMELLIA_CBC: + Camellia_DestroyContext((CamelliaContext *)cipherInfo->cx, PR_TRUE); + break; + case bltestSEED_ECB: + case bltestSEED_CBC: + SEED_DestroyContext((SEEDContext *)cipherInfo->cx, PR_TRUE); + break; + case bltestCHACHA20: + ChaCha20Poly1305_DestroyContext((ChaCha20Poly1305Context *) + cipherInfo->cx, + PR_TRUE); + break; + case bltestRC2_ECB: + case bltestRC2_CBC: + RC2_DestroyContext((RC2Context *)cipherInfo->cx, PR_TRUE); + break; + case bltestRC4: + RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE); + break; #ifdef NSS_SOFTOKEN_DOES_RC5 - case bltestRC5_ECB: - case bltestRC5_CBC: - RC5_DestroyContext((RC5Context *)cipherInfo->cx, PR_TRUE); - break; + case bltestRC5_ECB: + case bltestRC5_CBC: + RC5_DestroyContext((RC5Context *)cipherInfo->cx, PR_TRUE); + break; #endif - case bltestRSA: /* keys are alloc'ed within cipherInfo's arena, */ - case bltestRSA_PSS: /* will be freed with it. */ - case bltestRSA_OAEP: - case bltestDSA: + case bltestRSA: /* keys are alloc'ed within cipherInfo's arena, */ + case bltestRSA_PSS: /* will be freed with it. */ + case bltestRSA_OAEP: + case bltestDSA: #ifndef NSS_DISABLE_ECC - case bltestECDSA: + case bltestECDSA: #endif - case bltestMD2: /* hash contexts are ephemeral */ - case bltestMD5: - case bltestSHA1: - case bltestSHA224: - case bltestSHA256: - case bltestSHA384: - case bltestSHA512: - return SECSuccess; - break; - default: - return SECFailure; + case bltestMD2: /* hash contexts are ephemeral */ + case bltestMD5: + case bltestSHA1: + case bltestSHA224: + case bltestSHA256: + case bltestSHA384: + case bltestSHA512: + return SECSuccess; + break; + default: + return SECFailure; } return rv; } @@ -2656,11 +2692,12 @@ print_exponent(SECItem *exp) int i; int e = 0; if (exp->len <= 4) { - for (i=exp->len; i >=0; --i) e |= exp->data[exp->len-i] << 8*(i-1); - fprintf(stdout, "%12d", e); + for (i = exp->len; i >= 0; --i) + e |= exp->data[exp->len - i] << 8 * (i - 1); + fprintf(stdout, "%12d", e); } else { - e = 8*exp->len; - fprintf(stdout, "~2**%-8d", e); + e = 8 * exp->len; + fprintf(stdout, "~2**%-8d", e); } } @@ -2679,17 +2716,17 @@ splitToReportUnit(PRInt64 res, int *resArr, int *del, int size) } } -static char* +static char * getHighUnitBytes(PRInt64 res) { - int spl[] = {0, 0, 0, 0}; - int del[] = {1024, 1024, 1024, 1024}; - char *marks[] = {"b", "Kb", "Mb", "Gb"}; + int spl[] = { 0, 0, 0, 0 }; + int del[] = { 1024, 1024, 1024, 1024 }; + char *marks[] = { "b", "Kb", "Mb", "Gb" }; int i = 3; splitToReportUnit(res, spl, del, 4); - for (;i>0;i--) { + for (; i > 0; i--) { if (spl[i] != 0) { break; } @@ -2698,7 +2735,6 @@ getHighUnitBytes(PRInt64 res) return PR_smprintf("%d%s", spl[i], marks[i]); } - static void printPR_smpString(const char *sformat, char *reportStr, const char *nformat, PRInt64 rNum) @@ -2711,17 +2747,17 @@ printPR_smpString(const char *sformat, char *reportStr, } } -static char* +static char * getHighUnitOps(PRInt64 res) { - int spl[] = {0, 0, 0, 0}; - int del[] = {1000, 1000, 1000, 1000}; - char *marks[] = {"", "T", "M", "B"}; + int spl[] = { 0, 0, 0, 0 }; + int del[] = { 1000, 1000, 1000, 1000 }; + char *marks[] = { "", "T", "M", "B" }; int i = 3; splitToReportUnit(res, spl, del, 4); - for (;i>0;i--) { + for (; i > 0; i--) { if (spl[i] != 0) { break; } @@ -2735,12 +2771,12 @@ dump_performance_info(bltestCipherInfo *infoList, double totalTimeInt, PRBool encrypt, PRBool cxonly) { bltestCipherInfo *info = infoList; - + PRInt64 totalIn = 0; PRBool td = PR_TRUE; - int repetitions = 0; - int cxreps = 0; + int repetitions = 0; + int cxreps = 0; double cxtime = 0; double optime = 0; while (info != NULL) { @@ -2748,8 +2784,8 @@ dump_performance_info(bltestCipherInfo *infoList, double totalTimeInt, cxreps += info->cxreps; cxtime += info->cxtime; optime += info->optime; - totalIn += (PRInt64) info->input.buf.len * (PRInt64) info->repetitions; - + totalIn += (PRInt64)info->input.buf.len * (PRInt64)info->repetitions; + info = info->next; } info = infoList; @@ -2758,79 +2794,79 @@ dump_performance_info(bltestCipherInfo *infoList, double totalTimeInt, fprintf(stdout, "%12s", "in"); print_td: switch (info->mode) { - case bltestDES_ECB: - case bltestDES_CBC: - case bltestDES_EDE_ECB: - case bltestDES_EDE_CBC: - case bltestAES_ECB: - case bltestAES_CBC: - case bltestAES_CTS: - case bltestAES_CTR: - case bltestAES_GCM: - case bltestCAMELLIA_ECB: - case bltestCAMELLIA_CBC: - case bltestSEED_ECB: - case bltestSEED_CBC: - case bltestRC2_ECB: - case bltestRC2_CBC: - case bltestRC4: - if (td) - fprintf(stdout, "%8s", "symmkey"); - else - fprintf(stdout, "%8d", 8*info->params.sk.key.buf.len); - break; + case bltestDES_ECB: + case bltestDES_CBC: + case bltestDES_EDE_ECB: + case bltestDES_EDE_CBC: + case bltestAES_ECB: + case bltestAES_CBC: + case bltestAES_CTS: + case bltestAES_CTR: + case bltestAES_GCM: + case bltestCAMELLIA_ECB: + case bltestCAMELLIA_CBC: + case bltestSEED_ECB: + case bltestSEED_CBC: + case bltestRC2_ECB: + case bltestRC2_CBC: + case bltestRC4: + if (td) + fprintf(stdout, "%8s", "symmkey"); + else + fprintf(stdout, "%8d", 8 * info->params.sk.key.buf.len); + break; #ifdef NSS_SOFTOKEN_DOES_RC5 - case bltestRC5_ECB: - case bltestRC5_CBC: - if (info->params.sk.key.buf.len > 0) - printf("symmetric key(bytes)=%d,", info->params.sk.key.buf.len); - if (info->rounds > 0) - printf("rounds=%d,", info->params.rc5.rounds); - if (info->wordsize > 0) - printf("wordsize(bytes)=%d,", info->params.rc5.wordsize); - break; + case bltestRC5_ECB: + case bltestRC5_CBC: + if (info->params.sk.key.buf.len > 0) + printf("symmetric key(bytes)=%d,", info->params.sk.key.buf.len); + if (info->rounds > 0) + printf("rounds=%d,", info->params.rc5.rounds); + if (info->wordsize > 0) + printf("wordsize(bytes)=%d,", info->params.rc5.wordsize); + break; #endif - case bltestRSA: - case bltestRSA_PSS: - case bltestRSA_OAEP: - if (td) { - fprintf(stdout, "%8s", "rsa_mod"); - fprintf(stdout, "%12s", "rsa_pe"); - } else { - bltestAsymKeyParams *asymk = &info->params.asymk; - fprintf(stdout, "%8d", asymk->cipherParams.rsa.keysizeInBits); - print_exponent( - &((RSAPrivateKey *)asymk->privKey)->publicExponent); - } - break; - case bltestDSA: - if (td) { - fprintf(stdout, "%8s", "pqg_mod"); - } else { - fprintf(stdout, "%8d", info->params.asymk.cipherParams.dsa.keysize); - } - break; + case bltestRSA: + case bltestRSA_PSS: + case bltestRSA_OAEP: + if (td) { + fprintf(stdout, "%8s", "rsa_mod"); + fprintf(stdout, "%12s", "rsa_pe"); + } else { + bltestAsymKeyParams *asymk = &info->params.asymk; + fprintf(stdout, "%8d", asymk->cipherParams.rsa.keysizeInBits); + print_exponent( + &((RSAPrivateKey *)asymk->privKey)->publicExponent); + } + break; + case bltestDSA: + if (td) { + fprintf(stdout, "%8s", "pqg_mod"); + } else { + fprintf(stdout, "%8d", info->params.asymk.cipherParams.dsa.keysize); + } + break; #ifndef NSS_DISABLE_ECC - case bltestECDSA: - if (td) { - fprintf(stdout, "%12s", "ec_curve"); - } else { - ECPrivateKey *key = (ECPrivateKey*)info->params.asymk.privKey; - ECCurveName curveName = key->ecParams.name; - fprintf(stdout, "%12s", - ecCurve_map[curveName]? ecCurve_map[curveName]->text: - "Unsupported curve"); - } - break; + case bltestECDSA: + if (td) { + fprintf(stdout, "%12s", "ec_curve"); + } else { + ECPrivateKey *key = (ECPrivateKey *)info->params.asymk.privKey; + ECCurveName curveName = key->ecParams.name; + fprintf(stdout, "%12s", + ecCurve_map[curveName] ? ecCurve_map[curveName]->text : + "Unsupported curve"); + } + break; #endif - case bltestMD2: - case bltestMD5: - case bltestSHA1: - case bltestSHA256: - case bltestSHA384: - case bltestSHA512: - default: - break; + case bltestMD2: + case bltestMD5: + case bltestSHA1: + case bltestSHA256: + case bltestSHA384: + case bltestSHA512: + default: + break; } if (!td) { PRInt64 totalThroughPut; @@ -2851,7 +2887,7 @@ dump_performance_info(bltestCipherInfo *infoList, double totalTimeInt, fprintf(stdout, "\n"); return; } - + fprintf(stdout, "%8s", "opreps"); fprintf(stdout, "%8s", "cxreps"); fprintf(stdout, "%12s", "context"); @@ -2862,7 +2898,7 @@ dump_performance_info(bltestCipherInfo *infoList, double totalTimeInt, fprintf(stdout, "%8s", mode_strings[info->mode]); fprintf(stdout, "_%c", (cxonly) ? 'c' : (encrypt) ? 'e' : 'd'); printPR_smpString("%12s", getHighUnitBytes(totalIn), "%12d", totalIn); - + td = !td; goto print_td; } @@ -2873,8 +2909,8 @@ printmodes() bltestCipherMode mode; int nummodes = sizeof(mode_strings) / sizeof(char *); fprintf(stderr, "%s: Available modes (specify with -m):\n", progName); - for (mode=0; modemode = ioMode; @@ -2900,8 +2936,8 @@ load_file_data(PLArenaPool *arena, bltestIO *data, data->pBuf.len = 0; file = PR_Open(fn, PR_RDONLY, 00660); if (file) { - setupIO(arena, data, file, NULL, 0); - PR_Close(file); + setupIO(arena, data, file, NULL, 0); + PR_Close(file); } } @@ -2909,7 +2945,7 @@ HASH_HashType mode_str_to_hash_alg(const SECItem *modeStr) { bltestCipherMode mode; - char* tempModeStr = NULL; + char *tempModeStr = NULL; if (!modeStr || modeStr->len == 0) return HASH_AlgNULL; tempModeStr = PORT_Alloc(modeStr->len + 1); @@ -2920,20 +2956,28 @@ mode_str_to_hash_alg(const SECItem *modeStr) mode = get_mode(tempModeStr); PORT_Free(tempModeStr); switch (mode) { - case bltestMD2: return HASH_AlgMD2; - case bltestMD5: return HASH_AlgMD5; - case bltestSHA1: return HASH_AlgSHA1; - case bltestSHA224: return HASH_AlgSHA224; - case bltestSHA256: return HASH_AlgSHA256; - case bltestSHA384: return HASH_AlgSHA384; - case bltestSHA512: return HASH_AlgSHA512; - default: return HASH_AlgNULL; + case bltestMD2: + return HASH_AlgMD2; + case bltestMD5: + return HASH_AlgMD5; + case bltestSHA1: + return HASH_AlgSHA1; + case bltestSHA224: + return HASH_AlgSHA224; + case bltestSHA256: + return HASH_AlgSHA256; + case bltestSHA384: + return HASH_AlgSHA384; + case bltestSHA512: + return HASH_AlgSHA512; + default: + return HASH_AlgNULL; } } void get_params(PLArenaPool *arena, bltestParams *params, - bltestCipherMode mode, int j) + bltestCipherMode mode, int j) { char filename[256]; char *modestr = mode_strings[mode]; @@ -2945,175 +2989,176 @@ get_params(PLArenaPool *arena, bltestParams *params, int index = 0; #endif switch (mode) { - case bltestAES_GCM: - case bltestCHACHA20: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "aad", j); - load_file_data(arena, ¶ms->ask.aad, filename, bltestBinary); - case bltestDES_CBC: - case bltestDES_EDE_CBC: - case bltestRC2_CBC: - case bltestAES_CBC: - case bltestAES_CTS: - case bltestAES_CTR: - case bltestCAMELLIA_CBC: - case bltestSEED_CBC: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j); - load_file_data(arena, ¶ms->sk.iv, filename, bltestBinary); - case bltestDES_ECB: - case bltestDES_EDE_ECB: - case bltestRC2_ECB: - case bltestRC4: - case bltestAES_ECB: - case bltestCAMELLIA_ECB: - case bltestSEED_ECB: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); - load_file_data(arena, ¶ms->sk.key, filename, bltestBinary); - break; + case bltestAES_GCM: + case bltestCHACHA20: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "aad", j); + load_file_data(arena, ¶ms->ask.aad, filename, bltestBinary); + case bltestDES_CBC: + case bltestDES_EDE_CBC: + case bltestRC2_CBC: + case bltestAES_CBC: + case bltestAES_CTS: + case bltestAES_CTR: + case bltestCAMELLIA_CBC: + case bltestSEED_CBC: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j); + load_file_data(arena, ¶ms->sk.iv, filename, bltestBinary); + case bltestDES_ECB: + case bltestDES_EDE_ECB: + case bltestRC2_ECB: + case bltestRC4: + case bltestAES_ECB: + case bltestCAMELLIA_ECB: + case bltestSEED_ECB: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); + load_file_data(arena, ¶ms->sk.key, filename, bltestBinary); + break; #ifdef NSS_SOFTOKEN_DOES_RC5 - case bltestRC5_ECB: - case bltestRC5_CBC: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j); - load_file_data(arena, ¶ms->sk.iv, filename, bltestBinary); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); - load_file_data(arena, ¶ms->sk.key, filename, bltestBinary); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, - "params", j); - file = fopen(filename, "r"); - if (!file) return; - param = malloc(100); - len = fread(param, 1, 100, file); - while (index < len) { - mark = PL_strchr(param, '='); - *mark = '\0'; - val = mark + 1; - mark = PL_strchr(val, '\n'); - *mark = '\0'; - if (PL_strcmp(param, "rounds") == 0) { - params->rc5.rounds = atoi(val); - } else if (PL_strcmp(param, "wordsize") == 0) { - params->rc5.wordsize = atoi(val); - } - index += PL_strlen(param) + PL_strlen(val) + 2; - param = mark + 1; - } - break; + case bltestRC5_ECB: + case bltestRC5_CBC: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j); + load_file_data(arena, ¶ms->sk.iv, filename, bltestBinary); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); + load_file_data(arena, ¶ms->sk.key, filename, bltestBinary); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, + "params", j); + file = fopen(filename, "r"); + if (!file) + return; + param = malloc(100); + len = fread(param, 1, 100, file); + while (index < len) { + mark = PL_strchr(param, '='); + *mark = '\0'; + val = mark + 1; + mark = PL_strchr(val, '\n'); + *mark = '\0'; + if (PL_strcmp(param, "rounds") == 0) { + params->rc5.rounds = atoi(val); + } else if (PL_strcmp(param, "wordsize") == 0) { + params->rc5.wordsize = atoi(val); + } + index += PL_strlen(param) + PL_strlen(val) + 2; + param = mark + 1; + } + break; #endif - case bltestRSA_PSS: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j); - load_file_data(arena, ¶ms->asymk.sig, filename, bltestBase64Encoded); - /* fall through */ - case bltestRSA_OAEP: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "seed", j); - load_file_data(arena, ¶ms->asymk.cipherParams.rsa.seed, - filename, bltestBase64Encoded); - - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "hash", j); - load_file_data(arena, &tempIO, filename, bltestBinary); - params->asymk.cipherParams.rsa.hashAlg = - mode_str_to_hash_alg(&tempIO.buf); - - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "maskhash", j); - load_file_data(arena, &tempIO, filename, bltestBinary); - params->asymk.cipherParams.rsa.maskHashAlg = - mode_str_to_hash_alg(&tempIO.buf); - /* fall through */ - case bltestRSA: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); - load_file_data(arena, ¶ms->asymk.key, filename, - bltestBase64Encoded); - params->asymk.privKey = - (void *)rsakey_from_filedata(¶ms->asymk.key.buf); - break; - case bltestDSA: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); - load_file_data(arena, ¶ms->asymk.key, filename, bltestBase64Encoded); - params->asymk.privKey = - (void *)dsakey_from_filedata(¶ms->asymk.key.buf); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "pqg", j); - load_file_data(arena, ¶ms->asymk.cipherParams.dsa.pqgdata, filename, - bltestBase64Encoded); - params->asymk.cipherParams.dsa.pqg = - pqg_from_filedata(¶ms->asymk.cipherParams.dsa.pqgdata.buf); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "keyseed", j); - load_file_data(arena, ¶ms->asymk.cipherParams.dsa.keyseed, filename, - bltestBase64Encoded); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j); - load_file_data(arena, ¶ms->asymk.cipherParams.dsa.sigseed, filename, - bltestBase64Encoded); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext",j); - load_file_data(arena, ¶ms->asymk.sig, filename, bltestBase64Encoded); - break; + case bltestRSA_PSS: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j); + load_file_data(arena, ¶ms->asymk.sig, filename, bltestBase64Encoded); + /* fall through */ + case bltestRSA_OAEP: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "seed", j); + load_file_data(arena, ¶ms->asymk.cipherParams.rsa.seed, + filename, bltestBase64Encoded); + + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "hash", j); + load_file_data(arena, &tempIO, filename, bltestBinary); + params->asymk.cipherParams.rsa.hashAlg = + mode_str_to_hash_alg(&tempIO.buf); + + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "maskhash", j); + load_file_data(arena, &tempIO, filename, bltestBinary); + params->asymk.cipherParams.rsa.maskHashAlg = + mode_str_to_hash_alg(&tempIO.buf); + /* fall through */ + case bltestRSA: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); + load_file_data(arena, ¶ms->asymk.key, filename, + bltestBase64Encoded); + params->asymk.privKey = + (void *)rsakey_from_filedata(¶ms->asymk.key.buf); + break; + case bltestDSA: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); + load_file_data(arena, ¶ms->asymk.key, filename, bltestBase64Encoded); + params->asymk.privKey = + (void *)dsakey_from_filedata(¶ms->asymk.key.buf); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "pqg", j); + load_file_data(arena, ¶ms->asymk.cipherParams.dsa.pqgdata, filename, + bltestBase64Encoded); + params->asymk.cipherParams.dsa.pqg = + pqg_from_filedata(¶ms->asymk.cipherParams.dsa.pqgdata.buf); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "keyseed", j); + load_file_data(arena, ¶ms->asymk.cipherParams.dsa.keyseed, filename, + bltestBase64Encoded); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j); + load_file_data(arena, ¶ms->asymk.cipherParams.dsa.sigseed, filename, + bltestBase64Encoded); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j); + load_file_data(arena, ¶ms->asymk.sig, filename, bltestBase64Encoded); + break; #ifndef NSS_DISABLE_ECC - case bltestECDSA: - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); - load_file_data(arena, ¶ms->asymk.key, filename, bltestBase64Encoded); - params->asymk.privKey = - (void *)eckey_from_filedata(¶ms->asymk.key.buf); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j); - load_file_data(arena, ¶ms->asymk.cipherParams.ecdsa.sigseed, - filename, bltestBase64Encoded); - sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext",j); - load_file_data(arena, ¶ms->asymk.sig, filename, bltestBase64Encoded); - break; + case bltestECDSA: + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j); + load_file_data(arena, ¶ms->asymk.key, filename, bltestBase64Encoded); + params->asymk.privKey = + (void *)eckey_from_filedata(¶ms->asymk.key.buf); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j); + load_file_data(arena, ¶ms->asymk.cipherParams.ecdsa.sigseed, + filename, bltestBase64Encoded); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j); + load_file_data(arena, ¶ms->asymk.sig, filename, bltestBase64Encoded); + break; #endif - case bltestMD2: - case bltestMD5: - case bltestSHA1: - case bltestSHA224: - case bltestSHA256: - case bltestSHA384: - case bltestSHA512: - /*params->hash.restart = PR_TRUE;*/ - params->hash.restart = PR_FALSE; - break; - default: - break; + case bltestMD2: + case bltestMD5: + case bltestSHA1: + case bltestSHA224: + case bltestSHA256: + case bltestSHA384: + case bltestSHA512: + /*params->hash.restart = PR_TRUE;*/ + params->hash.restart = PR_FALSE; + break; + default: + break; } } SECStatus verify_self_test(bltestIO *result, bltestIO *cmp, bltestCipherMode mode, - PRBool forward, SECStatus sigstatus) + PRBool forward, SECStatus sigstatus) { PRBool equal; char *modestr = mode_strings[mode]; equal = SECITEM_ItemsAreEqual(&result->pBuf, &cmp->buf); if (is_sigCipher(mode)) { - if (forward) { - if (equal) { - printf("Signature self-test for %s passed.\n", modestr); - } else { - printf("Signature self-test for %s failed!\n", modestr); - } - return equal ? SECSuccess : SECFailure; - } else { - if (sigstatus == SECSuccess) { - printf("Verification self-test for %s passed.\n", modestr); - } else { - printf("Verification self-test for %s failed!\n", modestr); - } - return sigstatus; - } + if (forward) { + if (equal) { + printf("Signature self-test for %s passed.\n", modestr); + } else { + printf("Signature self-test for %s failed!\n", modestr); + } + return equal ? SECSuccess : SECFailure; + } else { + if (sigstatus == SECSuccess) { + printf("Verification self-test for %s passed.\n", modestr); + } else { + printf("Verification self-test for %s failed!\n", modestr); + } + return sigstatus; + } } else if (is_hashCipher(mode)) { - if (equal) { - printf("Hash self-test for %s passed.\n", modestr); - } else { - printf("Hash self-test for %s failed!\n", modestr); - } + if (equal) { + printf("Hash self-test for %s passed.\n", modestr); + } else { + printf("Hash self-test for %s failed!\n", modestr); + } } else { - if (forward) { - if (equal) { - printf("Encryption self-test for %s passed.\n", modestr); - } else { - printf("Encryption self-test for %s failed!\n", modestr); - } - } else { - if (equal) { - printf("Decryption self-test for %s passed.\n", modestr); - } else { - printf("Decryption self-test for %s failed!\n", modestr); - } - } + if (forward) { + if (equal) { + printf("Encryption self-test for %s passed.\n", modestr); + } else { + printf("Encryption self-test for %s failed!\n", modestr); + } + } else { + if (equal) { + printf("Decryption self-test for %s passed.\n", modestr); + } else { + printf("Decryption self-test for %s failed!\n", modestr); + } + } } return equal ? SECSuccess : SECFailure; } @@ -3126,7 +3171,7 @@ ReadFileToItem(SECItem *dst, const char *filename) file = PR_Open(filename, PR_RDONLY, 00660); if (!file) { - return SECFailure; + return SECFailure; } rv = SECU_FileToItem(dst, file); PR_Close(file); @@ -3153,97 +3198,97 @@ blapi_selftest(bltestCipherMode *modes, int numModes, int inoff, int outoff, cipherInfo.arena = arena; nummodes = (numModes == 0) ? NUMMODES : numModes; - for (i=0; i < nummodes; i++) { - if (numModes > 0) - mode = modes[i]; - else - mode = i; - if (mode == bltestINVALID) { - fprintf(stderr, "%s: Skipping invalid mode.\n",progName); - continue; - } - modestr = mode_strings[mode]; - cipherInfo.mode = mode; - params = &cipherInfo.params; - /* get the number of tests in the directory */ - sprintf(filename, "%s/tests/%s/%s", testdir, modestr, "numtests"); - if (ReadFileToItem(&item, filename) != SECSuccess) { - fprintf(stderr, "%s: Cannot read file %s.\n", progName, filename); - rv = SECFailure; - continue; - } - /* loop over the tests in the directory */ - numtests = 0; - for (j=0; jasymk.sig, &cipherInfo.output); - } - } - if (!decrypt) - continue; - /* Reverse Operation (Decrypt/Verify) - ** Align the input buffer (ciphertext) according to request - ** then perform operation and compare to plaintext - */ - if (is_sigCipher(mode)) { - bltestCopyIO(arena, &cipherInfo.input, &pt); - bltestCopyIO(arena, &cipherInfo.output, ¶ms->asymk.sig); - } else { - bltestCopyIO(arena, &cipherInfo.input, &ct); - memset(&cipherInfo.output.buf, 0, sizeof cipherInfo.output.buf); - } - misalignBuffer(arena, &cipherInfo.input, inoff); - rv |= cipherInit(&cipherInfo, PR_FALSE); - misalignBuffer(arena, &cipherInfo.output, outoff); - srv = SECSuccess; - srv |= cipherDoOp(&cipherInfo); - rv |= cipherFinish(&cipherInfo); - rv |= verify_self_test(&cipherInfo.output, - &pt, mode, PR_FALSE, srv); - } + for (i = 0; i < nummodes; i++) { + if (numModes > 0) + mode = modes[i]; + else + mode = i; + if (mode == bltestINVALID) { + fprintf(stderr, "%s: Skipping invalid mode.\n", progName); + continue; + } + modestr = mode_strings[mode]; + cipherInfo.mode = mode; + params = &cipherInfo.params; + /* get the number of tests in the directory */ + sprintf(filename, "%s/tests/%s/%s", testdir, modestr, "numtests"); + if (ReadFileToItem(&item, filename) != SECSuccess) { + fprintf(stderr, "%s: Cannot read file %s.\n", progName, filename); + rv = SECFailure; + continue; + } + /* loop over the tests in the directory */ + numtests = 0; + for (j = 0; j < item.len; j++) { + if (!isdigit(item.data[j])) { + break; + } + numtests *= 10; + numtests += (int)(item.data[j] - '0'); + } + for (j = 0; j < numtests; j++) { + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, + "plaintext", j); + load_file_data(arena, &pt, filename, + is_sigCipher(mode) ? bltestBase64Encoded + : bltestBinary); + sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, + "ciphertext", j); + load_file_data(arena, &ct, filename, bltestBase64Encoded); + + get_params(arena, params, mode, j); + /* Forward Operation (Encrypt/Sign/Hash) + ** Align the input buffer (plaintext) according to request + ** then perform operation and compare to ciphertext + */ + if (encrypt) { + bltestCopyIO(arena, &cipherInfo.input, &pt); + misalignBuffer(arena, &cipherInfo.input, inoff); + memset(&cipherInfo.output.buf, 0, sizeof cipherInfo.output.buf); + rv |= cipherInit(&cipherInfo, PR_TRUE); + misalignBuffer(arena, &cipherInfo.output, outoff); + rv |= cipherDoOp(&cipherInfo); + rv |= cipherFinish(&cipherInfo); + rv |= verify_self_test(&cipherInfo.output, + &ct, mode, PR_TRUE, SECSuccess); + /* If testing hash, only one op to test */ + if (is_hashCipher(mode)) + continue; + if (is_sigCipher(mode)) { + /* Verify operations support detached signature files. For + ** consistency between tests that run Sign/Verify back to + ** back (eg: self-tests) and tests that are only running + ** verify operations, copy the output into the sig buf, + ** and then copy the sig buf back out when verifying. For + ** self-tests, this is unnecessary copying, but for + ** verify-only operations, this ensures that the output + ** buffer is properly configured + */ + bltestCopyIO(arena, ¶ms->asymk.sig, &cipherInfo.output); + } + } + if (!decrypt) + continue; + /* Reverse Operation (Decrypt/Verify) + ** Align the input buffer (ciphertext) according to request + ** then perform operation and compare to plaintext + */ + if (is_sigCipher(mode)) { + bltestCopyIO(arena, &cipherInfo.input, &pt); + bltestCopyIO(arena, &cipherInfo.output, ¶ms->asymk.sig); + } else { + bltestCopyIO(arena, &cipherInfo.input, &ct); + memset(&cipherInfo.output.buf, 0, sizeof cipherInfo.output.buf); + } + misalignBuffer(arena, &cipherInfo.input, inoff); + rv |= cipherInit(&cipherInfo, PR_FALSE); + misalignBuffer(arena, &cipherInfo.output, outoff); + srv = SECSuccess; + srv |= cipherDoOp(&cipherInfo); + rv |= cipherFinish(&cipherInfo); + rv |= verify_self_test(&cipherInfo.output, + &pt, mode, PR_FALSE, srv); + } } return rv; } @@ -3255,40 +3300,41 @@ dump_file(bltestCipherMode mode, char *filename) PLArenaPool *arena = NULL; arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE); if (mode == bltestRSA || mode == bltestRSA_PSS || mode == bltestRSA_OAEP) { - RSAPrivateKey *key; - load_file_data(arena, &keydata, filename, bltestBase64Encoded); - key = rsakey_from_filedata(&keydata.buf); - dump_rsakey(key); + RSAPrivateKey *key; + load_file_data(arena, &keydata, filename, bltestBase64Encoded); + key = rsakey_from_filedata(&keydata.buf); + dump_rsakey(key); } else if (mode == bltestDSA) { #if 0 - PQGParams *pqg; - get_file_data(filename, &item, PR_TRUE); - pqg = pqg_from_filedata(&item); - dump_pqg(pqg); + PQGParams *pqg; + get_file_data(filename, &item, PR_TRUE); + pqg = pqg_from_filedata(&item); + dump_pqg(pqg); #endif - DSAPrivateKey *key; - load_file_data(arena, &keydata, filename, bltestBase64Encoded); - key = dsakey_from_filedata(&keydata.buf); - dump_dsakey(key); + DSAPrivateKey *key; + load_file_data(arena, &keydata, filename, bltestBase64Encoded); + key = dsakey_from_filedata(&keydata.buf); + dump_dsakey(key); #ifndef NSS_DISABLE_ECC } else if (mode == bltestECDSA) { - ECPrivateKey *key; - load_file_data(arena, &keydata, filename, bltestBase64Encoded); - key = eckey_from_filedata(&keydata.buf); - dump_eckey(key); + ECPrivateKey *key; + load_file_data(arena, &keydata, filename, bltestBase64Encoded); + key = eckey_from_filedata(&keydata.buf); + dump_eckey(key); #endif } PORT_FreeArena(arena, PR_FALSE); return SECFailure; } -void ThreadExecTest(void *data) +void +ThreadExecTest(void *data) { - bltestCipherInfo *cipherInfo = (bltestCipherInfo*)data; + bltestCipherInfo *cipherInfo = (bltestCipherInfo *)data; if (cipherInfo->mCarlo == PR_TRUE) { int mciter; - for (mciter=0; mciter<10000; mciter++) { + for (mciter = 0; mciter < 10000; mciter++) { cipherDoOp(cipherInfo); memcpy(cipherInfo->input.buf.data, cipherInfo->output.buf.data, @@ -3300,7 +3346,8 @@ void ThreadExecTest(void *data) cipherFinish(cipherInfo); } -static void rsaPrivKeyReset(RSAPrivateKey *tstKey) +static void +rsaPrivKeyReset(RSAPrivateKey *tstKey) { PLArenaPool *arena; @@ -3326,24 +3373,23 @@ static void rsaPrivKeyReset(RSAPrivateKey *tstKey) arena = tstKey->arena; tstKey->arena = NULL; if (arena) { - PORT_FreeArena(arena, PR_TRUE); + PORT_FreeArena(arena, PR_TRUE); } } - -#define RSA_TEST_EQUAL(comp) \ - if (!SECITEM_ItemsAreEqual(&(src->comp),&(dest->comp))) { \ - fprintf(stderr, "key->" #comp " not equal"); \ - if (src->comp.len != dest->comp.len) { \ - fprintf(stderr, "src_len = %d, dest_len = %d", \ - src->comp.len, dest->comp.len); \ - } \ - fprintf(stderr, "\n"); \ - areEqual = PR_FALSE; \ +#define RSA_TEST_EQUAL(comp) \ + if (!SECITEM_ItemsAreEqual(&(src->comp), &(dest->comp))) { \ + fprintf(stderr, "key->" #comp " not equal"); \ + if (src->comp.len != dest->comp.len) { \ + fprintf(stderr, "src_len = %d, dest_len = %d", \ + src->comp.len, dest->comp.len); \ + } \ + fprintf(stderr, "\n"); \ + areEqual = PR_FALSE; \ } - -static PRBool rsaPrivKeysAreEqual(RSAPrivateKey *src, RSAPrivateKey *dest) +static PRBool +rsaPrivKeysAreEqual(RSAPrivateKey *src, RSAPrivateKey *dest) { PRBool areEqual = PR_TRUE; RSA_TEST_EQUAL(modulus) @@ -3355,10 +3401,10 @@ static PRBool rsaPrivKeysAreEqual(RSAPrivateKey *src, RSAPrivateKey *dest) RSA_TEST_EQUAL(exponent2) RSA_TEST_EQUAL(coefficient) if (!areEqual) { - fprintf(stderr, "original key:\n"); - dump_rsakey(src); - fprintf(stderr, "recreated key:\n"); - dump_rsakey(dest); + fprintf(stderr, "original key:\n"); + dump_rsakey(src); + fprintf(stderr, "recreated key:\n"); + dump_rsakey(dest); } return areEqual; } @@ -3367,7 +3413,8 @@ static PRBool rsaPrivKeysAreEqual(RSAPrivateKey *src, RSAPrivateKey *dest) * Test the RSA populate command to see that it can really build * keys from it's components. */ -static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) +static int +doRSAPopulateTest(unsigned int keySize, unsigned long exponent) { RSAPrivateKey *srcKey; RSAPrivateKey tstKey = { 0 }; @@ -3378,11 +3425,11 @@ static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) int failed = 0; int i; - for (i=0; i < sizeof(unsigned long); i++) { - int shift = (sizeof(unsigned long) - i -1 ) * 8; - if (expLen || (exponent && ((unsigned long)0xffL << shift))) { - pubExp[expLen] = (unsigned char) ((exponent >> shift) & 0xff); - expLen++; + for (i = 0; i < sizeof(unsigned long); i++) { + int shift = (sizeof(unsigned long) - i - 1) * 8; + if (expLen || (exponent && ((unsigned long)0xffL << shift))) { + pubExp[expLen] = (unsigned char)((exponent >> shift) & 0xff); + expLen++; } } @@ -3391,8 +3438,8 @@ static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) srcKey = RSA_NewKey(keySize, &expitem); if (srcKey == NULL) { - fprintf(stderr, "RSA Key Gen failed"); - return -1; + fprintf(stderr, "RSA Key Gen failed"); + return -1; } /* test the basic case - most common, public exponent, modulus, prime */ @@ -3405,11 +3452,11 @@ static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) rv = RSA_PopulatePrivateKey(&tstKey); if (rv != SECSuccess) { - fprintf(stderr, "RSA Populate failed: pubExp mod p\n"); - failed = 1; + fprintf(stderr, "RSA Populate failed: pubExp mod p\n"); + failed = 1; } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) { - fprintf(stderr, "RSA Populate key mismatch: pubExp mod p\n"); - failed = 1; + fprintf(stderr, "RSA Populate key mismatch: pubExp mod p\n"); + failed = 1; } /* test the basic2 case, public exponent, modulus, prime2 */ @@ -3421,11 +3468,11 @@ static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) rv = RSA_PopulatePrivateKey(&tstKey); if (rv != SECSuccess) { - fprintf(stderr, "RSA Populate failed: pubExp mod q\n"); - failed = 1; + fprintf(stderr, "RSA Populate failed: pubExp mod q\n"); + failed = 1; } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) { - fprintf(stderr, "RSA Populate key mismatch: pubExp mod q\n"); - failed = 1; + fprintf(stderr, "RSA Populate key mismatch: pubExp mod q\n"); + failed = 1; } /* test the medium case, private exponent, prime1, prime2 */ @@ -3437,11 +3484,11 @@ static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) rv = RSA_PopulatePrivateKey(&tstKey); if (rv != SECSuccess) { - fprintf(stderr, "RSA Populate failed: privExp p q\n"); - failed = 1; + fprintf(stderr, "RSA Populate failed: privExp p q\n"); + failed = 1; } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) { - fprintf(stderr, "RSA Populate key mismatch: privExp p q\n"); - failed = 1; + fprintf(stderr, "RSA Populate key mismatch: privExp p q\n"); + failed = 1; } /* test the advanced case, public exponent, private exponent, prime2 */ @@ -3453,16 +3500,16 @@ static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) rv = RSA_PopulatePrivateKey(&tstKey); if (rv != SECSuccess) { - fprintf(stderr, "RSA Populate failed: pubExp privExp q\n"); - fprintf(stderr, " - not fatal\n"); - /* it's possible that we can't uniquely determine the original key - * from just the exponents and prime. Populate returns an error rather - * than return the wrong key. */ + fprintf(stderr, "RSA Populate failed: pubExp privExp q\n"); + fprintf(stderr, " - not fatal\n"); + /* it's possible that we can't uniquely determine the original key + * from just the exponents and prime. Populate returns an error rather + * than return the wrong key. */ } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) { - /* if we returned a key, it *must* be correct */ - fprintf(stderr, "RSA Populate key mismatch: pubExp privExp q\n"); - rv = RSA_PrivateKeyCheck(&tstKey); - failed = 1; + /* if we returned a key, it *must* be correct */ + fprintf(stderr, "RSA Populate key mismatch: pubExp privExp q\n"); + rv = RSA_PrivateKeyCheck(&tstKey); + failed = 1; } /* test the advanced case2, public exponent, private exponent, modulus */ @@ -3474,18 +3521,16 @@ static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent) rv = RSA_PopulatePrivateKey(&tstKey); if (rv != SECSuccess) { - fprintf(stderr, "RSA Populate failed: pubExp privExp mod\n"); - failed = 1; + fprintf(stderr, "RSA Populate failed: pubExp privExp mod\n"); + failed = 1; } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) { - fprintf(stderr, "RSA Populate key mismatch: pubExp privExp mod\n"); - failed = 1; + fprintf(stderr, "RSA Populate key mismatch: pubExp privExp mod\n"); + failed = 1; } return failed ? -1 : 0; } - - /* bltest commands */ enum { cmd_Decrypt = 0, @@ -3540,74 +3585,75 @@ enum { }; static secuCommandFlag bltest_commands[] = -{ - { /* cmd_Decrypt */ 'D', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Encrypt */ 'E', PR_FALSE, 0, PR_FALSE }, - { /* cmd_FIPS */ 'F', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Hash */ 'H', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Nonce */ 'N', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Dump */ 'P', PR_FALSE, 0, PR_FALSE }, - { /* cmd_RSAPopulate*/ 'R', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Sign */ 'S', PR_FALSE, 0, PR_FALSE }, - { /* cmd_SelfTest */ 'T', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Verify */ 'V', PR_FALSE, 0, PR_FALSE } -}; + { + { /* cmd_Decrypt */ 'D', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Encrypt */ 'E', PR_FALSE, 0, PR_FALSE }, + { /* cmd_FIPS */ 'F', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Hash */ 'H', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Nonce */ 'N', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Dump */ 'P', PR_FALSE, 0, PR_FALSE }, + { /* cmd_RSAPopulate*/ 'R', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Sign */ 'S', PR_FALSE, 0, PR_FALSE }, + { /* cmd_SelfTest */ 'T', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Verify */ 'V', PR_FALSE, 0, PR_FALSE } + }; static secuCommandFlag bltest_options[] = -{ - { /* opt_B64 */ 'a', PR_FALSE, 0, PR_FALSE }, - { /* opt_BufSize */ 'b', PR_TRUE, 0, PR_FALSE }, - { /* opt_Restart */ 'c', PR_FALSE, 0, PR_FALSE }, - { /* opt_SelfTestDir */ 'd', PR_TRUE, 0, PR_FALSE }, - { /* opt_Exponent */ 'e', PR_TRUE, 0, PR_FALSE }, - { /* opt_SigFile */ 'f', PR_TRUE, 0, PR_FALSE }, - { /* opt_KeySize */ 'g', PR_TRUE, 0, PR_FALSE }, - { /* opt_Hex */ 'h', PR_FALSE, 0, PR_FALSE }, - { /* opt_Input */ 'i', PR_TRUE, 0, PR_FALSE }, - { /* opt_PQGFile */ 'j', PR_TRUE, 0, PR_FALSE }, - { /* opt_Key */ 'k', PR_TRUE, 0, PR_FALSE }, - { /* opt_HexWSpc */ 'l', PR_FALSE, 0, PR_FALSE }, - { /* opt_Mode */ 'm', PR_TRUE, 0, PR_FALSE }, + { + { /* opt_B64 */ 'a', PR_FALSE, 0, PR_FALSE }, + { /* opt_BufSize */ 'b', PR_TRUE, 0, PR_FALSE }, + { /* opt_Restart */ 'c', PR_FALSE, 0, PR_FALSE }, + { /* opt_SelfTestDir */ 'd', PR_TRUE, 0, PR_FALSE }, + { /* opt_Exponent */ 'e', PR_TRUE, 0, PR_FALSE }, + { /* opt_SigFile */ 'f', PR_TRUE, 0, PR_FALSE }, + { /* opt_KeySize */ 'g', PR_TRUE, 0, PR_FALSE }, + { /* opt_Hex */ 'h', PR_FALSE, 0, PR_FALSE }, + { /* opt_Input */ 'i', PR_TRUE, 0, PR_FALSE }, + { /* opt_PQGFile */ 'j', PR_TRUE, 0, PR_FALSE }, + { /* opt_Key */ 'k', PR_TRUE, 0, PR_FALSE }, + { /* opt_HexWSpc */ 'l', PR_FALSE, 0, PR_FALSE }, + { /* opt_Mode */ 'm', PR_TRUE, 0, PR_FALSE }, #ifndef NSS_DISABLE_ECC - { /* opt_CurveName */ 'n', PR_TRUE, 0, PR_FALSE }, + { /* opt_CurveName */ 'n', PR_TRUE, 0, PR_FALSE }, #endif - { /* opt_Output */ 'o', PR_TRUE, 0, PR_FALSE }, - { /* opt_Repetitions */ 'p', PR_TRUE, 0, PR_FALSE }, - { /* opt_ZeroBuf */ 'q', PR_FALSE, 0, PR_FALSE }, - { /* opt_Rounds */ 'r', PR_TRUE, 0, PR_FALSE }, - { /* opt_Seed */ 's', PR_TRUE, 0, PR_FALSE }, - { /* opt_SigSeedFile */ 't', PR_TRUE, 0, PR_FALSE }, - { /* opt_CXReps */ 'u', PR_TRUE, 0, PR_FALSE }, - { /* opt_IV */ 'v', PR_TRUE, 0, PR_FALSE }, - { /* opt_WordSize */ 'w', PR_TRUE, 0, PR_FALSE }, - { /* opt_UseSeed */ 'x', PR_FALSE, 0, PR_FALSE }, - { /* opt_UseSigSeed */ 'y', PR_FALSE, 0, PR_FALSE }, - { /* opt_SeedFile */ 'z', PR_FALSE, 0, PR_FALSE }, - { /* opt_AAD */ 0 , PR_TRUE, 0, PR_FALSE, "aad" }, - { /* opt_InputOffset */ '1', PR_TRUE, 0, PR_FALSE }, - { /* opt_OutputOffset */ '2', PR_TRUE, 0, PR_FALSE }, - { /* opt_MonteCarlo */ '3', PR_FALSE, 0, PR_FALSE }, - { /* opt_ThreadNum */ '4', PR_TRUE, 0, PR_FALSE }, - { /* opt_SecondsToRun */ '5', PR_TRUE, 0, PR_FALSE }, - { /* opt_CmdLine */ '-', PR_FALSE, 0, PR_FALSE } -}; - -int main(int argc, char **argv) + { /* opt_Output */ 'o', PR_TRUE, 0, PR_FALSE }, + { /* opt_Repetitions */ 'p', PR_TRUE, 0, PR_FALSE }, + { /* opt_ZeroBuf */ 'q', PR_FALSE, 0, PR_FALSE }, + { /* opt_Rounds */ 'r', PR_TRUE, 0, PR_FALSE }, + { /* opt_Seed */ 's', PR_TRUE, 0, PR_FALSE }, + { /* opt_SigSeedFile */ 't', PR_TRUE, 0, PR_FALSE }, + { /* opt_CXReps */ 'u', PR_TRUE, 0, PR_FALSE }, + { /* opt_IV */ 'v', PR_TRUE, 0, PR_FALSE }, + { /* opt_WordSize */ 'w', PR_TRUE, 0, PR_FALSE }, + { /* opt_UseSeed */ 'x', PR_FALSE, 0, PR_FALSE }, + { /* opt_UseSigSeed */ 'y', PR_FALSE, 0, PR_FALSE }, + { /* opt_SeedFile */ 'z', PR_FALSE, 0, PR_FALSE }, + { /* opt_AAD */ 0, PR_TRUE, 0, PR_FALSE, "aad" }, + { /* opt_InputOffset */ '1', PR_TRUE, 0, PR_FALSE }, + { /* opt_OutputOffset */ '2', PR_TRUE, 0, PR_FALSE }, + { /* opt_MonteCarlo */ '3', PR_FALSE, 0, PR_FALSE }, + { /* opt_ThreadNum */ '4', PR_TRUE, 0, PR_FALSE }, + { /* opt_SecondsToRun */ '5', PR_TRUE, 0, PR_FALSE }, + { /* opt_CmdLine */ '-', PR_FALSE, 0, PR_FALSE } + }; + +int +main(int argc, char **argv) { SECStatus rv = SECFailure; - double totalTime = 0.0; - PRIntervalTime time1, time2; - PRFileDesc *outfile = NULL; - bltestCipherInfo *cipherInfoListHead, *cipherInfo = NULL; - bltestIOMode ioMode; - int bufsize, exponent, curThrdNum; + double totalTime = 0.0; + PRIntervalTime time1, time2; + PRFileDesc *outfile = NULL; + bltestCipherInfo *cipherInfoListHead, *cipherInfo = NULL; + bltestIOMode ioMode; + int bufsize, exponent, curThrdNum; #ifndef NSS_DISABLE_ECC - char *curveName = NULL; + char *curveName = NULL; #endif - int i, commandsEntered; - int inoff, outoff; - int threads = 1; + int i, commandsEntered; + int inoff, outoff; + int threads = 1; secuCommand bltest; bltest.numCommands = sizeof(bltest_commands) / sizeof(secuCommandFlag); @@ -3616,32 +3662,31 @@ int main(int argc, char **argv) bltest.options = bltest_options; progName = strrchr(argv[0], '/'); - if (!progName) - progName = strrchr(argv[0], '\\'); - progName = progName ? progName+1 : argv[0]; + if (!progName) + progName = strrchr(argv[0], '\\'); + progName = progName ? progName + 1 : argv[0]; rv = NSS_InitializePRErrorTable(); if (rv != SECSuccess) { - SECU_PrintPRandOSError(progName); - return -1; + SECU_PrintPRandOSError(progName); + return -1; } rv = RNG_RNGInit(); if (rv != SECSuccess) { - SECU_PrintPRandOSError(progName); - return -1; + SECU_PrintPRandOSError(progName); + return -1; } rv = BL_Init(); if (rv != SECSuccess) { - SECU_PrintPRandOSError(progName); - return -1; + SECU_PrintPRandOSError(progName); + return -1; } RNG_SystemInfoForRNG(); - rv = SECU_ParseCommandLine(argc, argv, progName, &bltest); if (rv == SECFailure) { - fprintf(stderr, "%s: command line parsing error!\n", progName); - goto print_usage; + fprintf(stderr, "%s: command line parsing error!\n", progName); + goto print_usage; } rv = SECFailure; @@ -3650,37 +3695,36 @@ int main(int argc, char **argv) /* Check the number of commands entered on the command line. */ commandsEntered = 0; - for (i=0; i 1 && - !(commandsEntered == 2 && bltest.commands[cmd_SelfTest].activated)) { - fprintf(stderr, "%s: one command at a time!\n", progName); + !(commandsEntered == 2 && bltest.commands[cmd_SelfTest].activated)) { + fprintf(stderr, "%s: one command at a time!\n", progName); goto print_usage; } if (commandsEntered == 0) { - fprintf(stderr, "%s: you must enter a command!\n", progName); + fprintf(stderr, "%s: you must enter a command!\n", progName); goto print_usage; } - if (bltest.commands[cmd_Sign].activated) - bltest.commands[cmd_Encrypt].activated = PR_TRUE; + bltest.commands[cmd_Encrypt].activated = PR_TRUE; if (bltest.commands[cmd_Verify].activated) - bltest.commands[cmd_Decrypt].activated = PR_TRUE; + bltest.commands[cmd_Decrypt].activated = PR_TRUE; if (bltest.commands[cmd_Hash].activated) - bltest.commands[cmd_Encrypt].activated = PR_TRUE; + bltest.commands[cmd_Encrypt].activated = PR_TRUE; inoff = outoff = 0; if (bltest.options[opt_InputOffset].activated) - inoff = PORT_Atoi(bltest.options[opt_InputOffset].arg); + inoff = PORT_Atoi(bltest.options[opt_InputOffset].arg); if (bltest.options[opt_OutputOffset].activated) - outoff = PORT_Atoi(bltest.options[opt_OutputOffset].arg); + outoff = PORT_Atoi(bltest.options[opt_OutputOffset].arg); - testdir = (bltest.options[opt_SelfTestDir].activated) ? - strdup(bltest.options[opt_SelfTestDir].arg) : "."; + testdir = (bltest.options[opt_SelfTestDir].activated) ? strdup(bltest.options[opt_SelfTestDir].arg) + : "."; /* * Handle three simple cases first @@ -3688,69 +3732,70 @@ int main(int argc, char **argv) /* test the RSA_PopulatePrivateKey function */ if (bltest.commands[cmd_RSAPopulate].activated) { - unsigned int keySize = 1024; - unsigned long exponent = 65537; - int rounds = 1; - int ret = -1; - - if (bltest.options[opt_KeySize].activated) { - keySize = PORT_Atoi(bltest.options[opt_KeySize].arg); - } - if (bltest.options[opt_Rounds].activated) { - rounds = PORT_Atoi(bltest.options[opt_Rounds].arg); - } - if (bltest.options[opt_Exponent].activated) { - exponent = PORT_Atoi(bltest.options[opt_Exponent].arg); - } - - for (i=0; i < rounds; i++) { - printf("Running RSA Populate test round %d\n",i); - ret = doRSAPopulateTest(keySize,exponent); - if (ret != 0) { - break; - } - } - if (ret != 0) { - fprintf(stderr,"RSA Populate test round %d: FAILED\n",i); - } - return ret; + unsigned int keySize = 1024; + unsigned long exponent = 65537; + int rounds = 1; + int ret = -1; + + if (bltest.options[opt_KeySize].activated) { + keySize = PORT_Atoi(bltest.options[opt_KeySize].arg); + } + if (bltest.options[opt_Rounds].activated) { + rounds = PORT_Atoi(bltest.options[opt_Rounds].arg); + } + if (bltest.options[opt_Exponent].activated) { + exponent = PORT_Atoi(bltest.options[opt_Exponent].arg); + } + + for (i = 0; i < rounds; i++) { + printf("Running RSA Populate test round %d\n", i); + ret = doRSAPopulateTest(keySize, exponent); + if (ret != 0) { + break; + } + } + if (ret != 0) { + fprintf(stderr, "RSA Populate test round %d: FAILED\n", i); + } + return ret; } /* Do BLAPI self-test */ if (bltest.commands[cmd_SelfTest].activated) { - PRBool encrypt = PR_TRUE, decrypt = PR_TRUE; - /* user may specified a set of ciphers to test. parse them. */ - bltestCipherMode modesToTest[NUMMODES]; - int numModesToTest = 0; - char *tok, *str; - str = bltest.options[opt_Mode].arg; - while (str) { - tok = strchr(str, ','); - if (tok) *tok = '\0'; - modesToTest[numModesToTest++] = get_mode(str); - if (tok) { - *tok = ','; - str = tok + 1; - } else { - break; - } - } - if (bltest.commands[cmd_Decrypt].activated && - !bltest.commands[cmd_Encrypt].activated) - encrypt = PR_FALSE; - if (bltest.commands[cmd_Encrypt].activated && - !bltest.commands[cmd_Decrypt].activated) - decrypt = PR_FALSE; - rv = blapi_selftest(modesToTest, numModesToTest, inoff, outoff, - encrypt, decrypt); - PORT_Free(cipherInfo); - return rv == SECSuccess ? 0 : 1; + PRBool encrypt = PR_TRUE, decrypt = PR_TRUE; + /* user may specified a set of ciphers to test. parse them. */ + bltestCipherMode modesToTest[NUMMODES]; + int numModesToTest = 0; + char *tok, *str; + str = bltest.options[opt_Mode].arg; + while (str) { + tok = strchr(str, ','); + if (tok) + *tok = '\0'; + modesToTest[numModesToTest++] = get_mode(str); + if (tok) { + *tok = ','; + str = tok + 1; + } else { + break; + } + } + if (bltest.commands[cmd_Decrypt].activated && + !bltest.commands[cmd_Encrypt].activated) + encrypt = PR_FALSE; + if (bltest.commands[cmd_Encrypt].activated && + !bltest.commands[cmd_Decrypt].activated) + decrypt = PR_FALSE; + rv = blapi_selftest(modesToTest, numModesToTest, inoff, outoff, + encrypt, decrypt); + PORT_Free(cipherInfo); + return rv == SECSuccess ? 0 : 1; } /* Do FIPS self-test */ if (bltest.commands[cmd_FIPS].activated) { - CK_RV ckrv = sftk_FIPSEntryOK(); - fprintf(stdout, "CK_RV: %ld.\n", ckrv); + CK_RV ckrv = sftk_FIPSEntryOK(); + fprintf(stdout, "CK_RV: %ld.\n", ckrv); PORT_Free(cipherInfo); if (ckrv == CKR_OK) return SECSuccess; @@ -3762,29 +3807,28 @@ int main(int argc, char **argv) */ if ((bltest.commands[cmd_Decrypt].activated || - bltest.commands[cmd_Verify].activated) && - bltest.options[opt_BufSize].activated) { - fprintf(stderr, "%s: Cannot use a nonce as input to decrypt/verify.\n", - progName); + bltest.commands[cmd_Verify].activated) && + bltest.options[opt_BufSize].activated) { + fprintf(stderr, "%s: Cannot use a nonce as input to decrypt/verify.\n", + progName); goto print_usage; } if (bltest.options[opt_Mode].activated) { - cipherInfo->mode = get_mode(bltest.options[opt_Mode].arg); - if (cipherInfo->mode == bltestINVALID) { + cipherInfo->mode = get_mode(bltest.options[opt_Mode].arg); + if (cipherInfo->mode == bltestINVALID) { goto print_usage; - } + } } else { - fprintf(stderr, "%s: You must specify a cipher mode with -m.\n", - progName); + fprintf(stderr, "%s: You must specify a cipher mode with -m.\n", + progName); goto print_usage; } - if (bltest.options[opt_Repetitions].activated && bltest.options[opt_SecondsToRun].activated) { fprintf(stderr, "%s: Operation time should be defined in either " - "repetitions(-p) or seconds(-5) not both", + "repetitions(-p) or seconds(-5) not both", progName); goto print_usage; } @@ -3802,7 +3846,6 @@ int main(int argc, char **argv) cipherInfo->seconds = 0; } - if (bltest.options[opt_CXReps].activated) { cipherInfo->cxreps = PORT_Atoi(bltest.options[opt_CXReps].arg); } else { @@ -3824,21 +3867,23 @@ int main(int argc, char **argv) } /* default input mode is binary */ - ioMode = (bltest.options[opt_B64].activated) ? bltestBase64Encoded : - (bltest.options[opt_Hex].activated) ? bltestHexStream : - (bltest.options[opt_HexWSpc].activated) ? bltestHexSpaceDelim : - bltestBinary; + ioMode = (bltest.options[opt_B64].activated) + ? bltestBase64Encoded + : (bltest.options[opt_Hex].activated) + ? bltestHexStream + : (bltest.options[opt_HexWSpc].activated) ? bltestHexSpaceDelim + : bltestBinary; if (bltest.options[opt_Exponent].activated) - exponent = PORT_Atoi(bltest.options[opt_Exponent].arg); + exponent = PORT_Atoi(bltest.options[opt_Exponent].arg); else - exponent = 65537; + exponent = 65537; #ifndef NSS_DISABLE_ECC if (bltest.options[opt_CurveName].activated) - curveName = PORT_Strdup(bltest.options[opt_CurveName].arg); + curveName = PORT_Strdup(bltest.options[opt_CurveName].arg); else - curveName = NULL; + curveName = NULL; #endif if (bltest.commands[cmd_Verify].activated && @@ -3846,7 +3891,7 @@ int main(int argc, char **argv) fprintf(stderr, "%s: You must specify a signature file with -f.\n", progName); -print_usage: + print_usage: if (cipherInfo) { PORT_Free(cipherInfo); } @@ -3859,12 +3904,12 @@ int main(int argc, char **argv) cipherInfo->mCarlo = PR_FALSE; } - for (curThrdNum = 0;curThrdNum < threads;curThrdNum++) { - int keysize = 0; - PRFileDesc *file = NULL, *infile; - bltestParams *params; - char *instr = NULL; - PLArenaPool *arena; + for (curThrdNum = 0; curThrdNum < threads; curThrdNum++) { + int keysize = 0; + PRFileDesc *file = NULL, *infile; + bltestParams *params; + char *instr = NULL; + PLArenaPool *arena; if (curThrdNum > 0) { bltestCipherInfo *newCInfo = PORT_ZNew(bltestCipherInfo); @@ -3888,13 +3933,13 @@ int main(int argc, char **argv) } cipherInfo->arena = arena; params = &cipherInfo->params; - + /* Set up an encryption key. */ keysize = 0; file = NULL; if (is_symmkeyCipher(cipherInfo->mode) || - is_aeadCipher(cipherInfo->mode)) { - char *keystr = NULL; /* if key is on command line */ + is_aeadCipher(cipherInfo->mode)) { + char *keystr = NULL; /* if key is on command line */ if (bltest.options[opt_Key].activated) { if (bltest.options[opt_CmdLine].activated) { keystr = bltest.options[opt_Key].arg; @@ -3908,7 +3953,7 @@ int main(int argc, char **argv) else keysize = 8; /* use 64-bit default (DES) */ /* save the random key for reference */ - file = PR_Open("tmp.key", PR_WRONLY|PR_CREATE_FILE, 00660); + file = PR_Open("tmp.key", PR_WRONLY | PR_CREATE_FILE, 00660); } params->key.mode = ioMode; setupIO(cipherInfo->arena, ¶ms->key, file, keystr, keysize); @@ -3922,7 +3967,7 @@ int main(int argc, char **argv) keysize = PORT_Atoi(bltest.options[opt_KeySize].arg); else keysize = 64; /* use 512-bit default */ - file = PR_Open("tmp.key", PR_WRONLY|PR_CREATE_FILE, 00660); + file = PR_Open("tmp.key", PR_WRONLY | PR_CREATE_FILE, 00660); } params->key.mode = bltestBase64Encoded; #ifndef NSS_DISABLE_ECC @@ -3953,7 +3998,7 @@ int main(int argc, char **argv) } } else { /* save the random iv for reference */ - file = PR_Open("tmp.iv", PR_WRONLY|PR_CREATE_FILE, 00660); + file = PR_Open("tmp.iv", PR_WRONLY | PR_CREATE_FILE, 00660); } memset(&skp->iv, 0, sizeof skp->iv); skp->iv.mode = ioMode; @@ -3986,7 +4031,7 @@ int main(int argc, char **argv) PR_Close(file); } } - + if (bltest.commands[cmd_Verify].activated) { file = PR_Open(bltest.options[opt_SigFile].arg, PR_RDONLY, 00660); if (is_sigCipher(cipherInfo->mode)) { @@ -3998,7 +4043,7 @@ int main(int argc, char **argv) PR_Close(file); } } - + if (bltest.options[opt_PQGFile].activated) { file = PR_Open(bltest.options[opt_PQGFile].arg, PR_RDONLY, 00660); params->asymk.cipherParams.dsa.pqgdata.mode = bltestBase64Encoded; @@ -4016,10 +4061,10 @@ int main(int argc, char **argv) infile = NULL; } else { /* form file name from testdir and input arg. */ - char * filename = bltest.options[opt_Input].arg; - if (bltest.options[opt_SelfTestDir].activated && + char *filename = bltest.options[opt_Input].arg; + if (bltest.options[opt_SelfTestDir].activated && testdir && filename && filename[0] != '/') { - filename = PR_smprintf("%s/tests/%s/%s", testdir, + filename = PR_smprintf("%s/tests/%s/%s", testdir, mode_strings[cipherInfo->mode], filename); if (!filename) { @@ -4040,7 +4085,7 @@ int main(int argc, char **argv) fprintf(stderr, "%s: Can not allocate memory.\n", progName); goto exit_point; } - infile = PR_Open(tmpFName, PR_WRONLY|PR_CREATE_FILE, 00660); + infile = PR_Open(tmpFName, PR_WRONLY | PR_CREATE_FILE, 00660); PR_smprintf_free(tmpFName); } else { infile = PR_STDIN; @@ -4054,20 +4099,20 @@ int main(int argc, char **argv) /* Set up the output stream */ if (bltest.options[opt_Output].activated) { /* form file name from testdir and input arg. */ - char * filename = bltest.options[opt_Output].arg; - if (bltest.options[opt_SelfTestDir].activated && + char *filename = bltest.options[opt_Output].arg; + if (bltest.options[opt_SelfTestDir].activated && testdir && filename && filename[0] != '/') { - filename = PR_smprintf("%s/tests/%s/%s", testdir, + filename = PR_smprintf("%s/tests/%s/%s", testdir, mode_strings[cipherInfo->mode], filename); if (!filename) { fprintf(stderr, "%s: Can not allocate memory.\n", progName); goto exit_point; } - outfile = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 00660); + outfile = PR_Open(filename, PR_WRONLY | PR_CREATE_FILE, 00660); PR_smprintf_free(filename); } else { - outfile = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 00660); + outfile = PR_Open(filename, PR_WRONLY | PR_CREATE_FILE, 00660); } } else { outfile = PR_STDOUT; @@ -4103,16 +4148,16 @@ int main(int argc, char **argv) TIMESTART(); cipherInfo = cipherInfoListHead; while (cipherInfo != NULL) { - cipherInfo->cipherThread = + cipherInfo->cipherThread = PR_CreateThread(PR_USER_THREAD, - ThreadExecTest, - cipherInfo, - PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, - PR_JOINABLE_THREAD, - 0); + ThreadExecTest, + cipherInfo, + PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, + PR_JOINABLE_THREAD, + 0); cipherInfo = cipherInfo->next; - } + } cipherInfo = cipherInfoListHead; while (cipherInfo != NULL) { @@ -4122,19 +4167,19 @@ int main(int argc, char **argv) } TIMEFINISH(totalTime, 1); } - + cipherInfo = cipherInfoListHead; if (cipherInfo->repetitions > 0 || cipherInfo->cxreps > 0 || threads > 1) dump_performance_info(cipherInfoListHead, totalTime, bltest.commands[cmd_Encrypt].activated, - (cipherInfo->repetitions == 0)); - + (cipherInfo->repetitions == 0)); + rv = SECSuccess; - exit_point: +exit_point: if (outfile && outfile != PR_STDOUT) - PR_Close(outfile); + PR_Close(outfile); cipherInfo = cipherInfoListHead; while (cipherInfo != NULL) { bltestCipherInfo *tmpInfo = cipherInfo; @@ -4149,4 +4194,3 @@ int main(int argc, char **argv) return SECSuccess; } - diff --git a/cmd/bltest/tests/aes_gcm/hex.c b/cmd/bltest/tests/aes_gcm/hex.c index 6ad2851792..cdf583da2f 100644 --- a/cmd/bltest/tests/aes_gcm/hex.c +++ b/cmd/bltest/tests/aes_gcm/hex.c @@ -2,67 +2,77 @@ #include #include -int tohex(int c) +int +tohex(int c) { - if ((c >= '0') && (c <= '9')) { + if ((c >= '0') && (c <= '9')) { return c - '0'; - } - if ((c >= 'a') && (c <= 'f')) { + } + if ((c >= 'a') && (c <= 'f')) { return c - 'a' + 10; - } - if ((c >= 'A') && (c <= 'F')) { + } + if ((c >= 'A') && (c <= 'F')) { return c - 'A' + 10; - } - return 0; + } + return 0; } -int isspace(int c) +int +isspace(int c) { - if (c <= ' ') return 1; - if (c == '\n') return 1; - if (c == '\t') return 1; - if (c == ':') return 1; - if (c == ';') return 1; - if (c == ',') return 1; - return 0; + if (c <= ' ') + return 1; + if (c == '\n') + return 1; + if (c == '\t') + return 1; + if (c == ':') + return 1; + if (c == ';') + return 1; + if (c == ',') + return 1; + return 0; } -void verify_nibble(int nibble, int current) +void +verify_nibble(int nibble, int current) { - if (nibble != 0) { - fprintf(stderr,"count mismatch %d (nibbles=0x%x)\n",nibble,current); + if (nibble != 0) { + fprintf(stderr, "count mismatch %d (nibbles=0x%x)\n", nibble, current); fflush(stderr); - } + } } -int main(int argc, char **argv) +int +main(int argc, char **argv) { - int c; - int current = 0; - int nibble = 0; - int skip = 0; + int c; + int current = 0; + int nibble = 0; + int skip = 0; - if (argv[1]) { + if (argv[1]) { skip = atoi(argv[1]); - } + } #define NIBBLE_COUNT 2 - while ((c=getchar()) != EOF) { - if (isspace(c)) { - verify_nibble(nibble,current); - continue; - } - if (skip) { - skip--; - continue; - } - current = current << 4 | tohex(c); - nibble++; - if (nibble == NIBBLE_COUNT) { - putchar(current); - nibble = 0; - current = 0; - } - } - return 0; + while ((c = getchar()) != EOF) { + if (isspace(c)) { + verify_nibble(nibble, current); + continue; + } + if (skip) { + skip--; + continue; + } + current = current << 4 | tohex(c); + nibble++; + if (nibble == NIBBLE_COUNT) { + putchar(current); + nibble = 0; + current = 0; + } + } + return 0; } diff --git a/cmd/btoa/btoa.c b/cmd/btoa/btoa.c index 9416feb478..2a5e6d4c65 100644 --- a/cmd/btoa/btoa.c +++ b/cmd/btoa/btoa.c @@ -9,8 +9,8 @@ #if defined(XP_WIN) || (defined(__sun) && !defined(SVR4)) #if !defined(WIN32) -extern int fread(char *, size_t, size_t, FILE*); -extern int fwrite(char *, size_t, size_t, FILE*); +extern int fread(char *, size_t, size_t, FILE *); +extern int fwrite(char *, size_t, size_t, FILE *); extern int fprintf(FILE *, char *, ...); #endif #endif @@ -20,16 +20,16 @@ extern int fprintf(FILE *, char *, ...); #include "io.h" #endif -static PRInt32 -output_ascii (void *arg, const char *obuf, PRInt32 size) +static PRInt32 +output_ascii(void *arg, const char *obuf, PRInt32 size) { FILE *outFile = arg; int nb; nb = fwrite(obuf, 1, size, outFile); if (nb != size) { - PORT_SetError(SEC_ERROR_IO); - return -1; + PORT_SetError(SEC_ERROR_IO); + return -1; } return nb; @@ -45,30 +45,32 @@ encode_file(FILE *outFile, FILE *inFile) cx = NSSBase64Encoder_Create(output_ascii, outFile); if (!cx) { - return -1; + return -1; } for (;;) { - if (feof(inFile)) break; - nb = fread(ibuf, 1, sizeof(ibuf), inFile); - if (nb != sizeof(ibuf)) { - if (nb == 0) { - if (ferror(inFile)) { - PORT_SetError(SEC_ERROR_IO); - goto loser; - } - /* eof */ - break; - } - } - - status = NSSBase64Encoder_Update(cx, ibuf, nb); - if (status != SECSuccess) goto loser; + if (feof(inFile)) + break; + nb = fread(ibuf, 1, sizeof(ibuf), inFile); + if (nb != sizeof(ibuf)) { + if (nb == 0) { + if (ferror(inFile)) { + PORT_SetError(SEC_ERROR_IO); + goto loser; + } + /* eof */ + break; + } + } + + status = NSSBase64Encoder_Update(cx, ibuf, nb); + if (status != SECSuccess) + goto loser; } status = NSSBase64Encoder_Destroy(cx, PR_FALSE); if (status != SECSuccess) - return status; + return status; /* * Add a trailing CRLF. Note this must be done *after* the call @@ -78,28 +80,30 @@ encode_file(FILE *outFile, FILE *inFile) fwrite("\r\n", 1, 2, outFile); return SECSuccess; - loser: - (void) NSSBase64Encoder_Destroy(cx, PR_TRUE); +loser: + (void)NSSBase64Encoder_Destroy(cx, PR_TRUE); return status; } -static void Usage(char *progName) +static void +Usage(char *progName) { fprintf(stderr, - "Usage: %s [-i input] [-o output]\n", - progName); + "Usage: %s [-i input] [-o output]\n", + progName); fprintf(stderr, "%-20s Define an input file to use (default is stdin)\n", - "-i input"); + "-i input"); fprintf(stderr, "%-20s Define an output file to use (default is stdout)\n", - "-o output"); + "-o output"); fprintf(stderr, "%-20s Wrap output in BEGIN/END lines and the given suffix\n", - "-w suffix"); + "-w suffix"); fprintf(stderr, "%-20s (use \"c\" as a shortcut for suffix CERTIFICATE)\n", - ""); + ""); exit(-1); } -int main(int argc, char **argv) +int +main(int argc, char **argv) { char *progName; SECStatus rv; @@ -112,88 +116,88 @@ int main(int argc, char **argv) outFile = 0; progName = strrchr(argv[0], '/'); if (!progName) - progName = strrchr(argv[0], '\\'); - progName = progName ? progName+1 : argv[0]; + progName = strrchr(argv[0], '\\'); + progName = progName ? progName + 1 : argv[0]; /* Parse command line arguments */ optstate = PL_CreateOptState(argc, argv, "i:o:w:"); while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { - switch (optstate->option) { - default: - Usage(progName); - break; - - case 'i': - inFile = fopen(optstate->value, "rb"); - if (!inFile) { - fprintf(stderr, "%s: unable to open \"%s\" for reading\n", - progName, optstate->value); - return -1; - } - break; - - case 'o': - outFile = fopen(optstate->value, "wb"); - if (!outFile) { - fprintf(stderr, "%s: unable to open \"%s\" for writing\n", - progName, optstate->value); - return -1; - } - break; - - case 'w': - if (!strcmp(optstate->value, "c")) - suffix = strdup("CERTIFICATE"); - else - suffix = strdup(optstate->value); - break; - } + switch (optstate->option) { + default: + Usage(progName); + break; + + case 'i': + inFile = fopen(optstate->value, "rb"); + if (!inFile) { + fprintf(stderr, "%s: unable to open \"%s\" for reading\n", + progName, optstate->value); + return -1; + } + break; + + case 'o': + outFile = fopen(optstate->value, "wb"); + if (!outFile) { + fprintf(stderr, "%s: unable to open \"%s\" for writing\n", + progName, optstate->value); + return -1; + } + break; + + case 'w': + if (!strcmp(optstate->value, "c")) + suffix = strdup("CERTIFICATE"); + else + suffix = strdup(optstate->value); + break; + } } if (status == PL_OPT_BAD) - Usage(progName); + Usage(progName); if (!inFile) { #if defined(WIN32) - /* If we're going to read binary data from stdin, we must put stdin - ** into O_BINARY mode or else incoming \r\n's will become \n's. - */ - - int smrv = _setmode(_fileno(stdin), _O_BINARY); - if (smrv == -1) { - fprintf(stderr, - "%s: Cannot change stdin to binary mode. Use -i option instead.\n", - progName); - return smrv; - } + /* If we're going to read binary data from stdin, we must put stdin + ** into O_BINARY mode or else incoming \r\n's will become \n's. + */ + + int smrv = _setmode(_fileno(stdin), _O_BINARY); + if (smrv == -1) { + fprintf(stderr, + "%s: Cannot change stdin to binary mode. Use -i option instead.\n", + progName); + return smrv; + } #endif - inFile = stdin; + inFile = stdin; } if (!outFile) { #if defined(WIN32) - /* We're going to write binary data to stdout. We must put stdout - ** into O_BINARY mode or else outgoing \r\n's will become \r\r\n's. - */ - - int smrv = _setmode(_fileno(stdout), _O_BINARY); - if (smrv == -1) { - fprintf(stderr, - "%s: Cannot change stdout to binary mode. Use -o option instead.\n", - progName); - return smrv; - } + /* We're going to write binary data to stdout. We must put stdout + ** into O_BINARY mode or else outgoing \r\n's will become \r\r\n's. + */ + + int smrv = _setmode(_fileno(stdout), _O_BINARY); + if (smrv == -1) { + fprintf(stderr, + "%s: Cannot change stdout to binary mode. Use -o option instead.\n", + progName); + return smrv; + } #endif - outFile = stdout; + outFile = stdout; } if (suffix) { - fprintf(outFile, "-----BEGIN %s-----\n", suffix); + fprintf(outFile, "-----BEGIN %s-----\n", suffix); } rv = encode_file(outFile, inFile); if (rv != SECSuccess) { - fprintf(stderr, "%s: lossage: error=%d errno=%d\n", - progName, PORT_GetError(), errno); - return -1; + fprintf(stderr, "%s: lossage: error=%d errno=%d\n", + progName, PORT_GetError(), errno); + return -1; } if (suffix) { - fprintf(outFile, "-----END %s-----\n", suffix); + fprintf(outFile, "-----END %s-----\n", suffix); } return 0; } diff --git a/cmd/certcgi/certcgi.c b/cmd/certcgi/certcgi.c index 1095d80edf..3120de8090 100644 --- a/cmd/certcgi/certcgi.c +++ b/cmd/certcgi/certcgi.c @@ -4,7 +4,6 @@ /* Cert-O-Matic CGI */ - #include "nspr.h" #include "prtypes.h" #include "prtime.h" @@ -22,14 +21,13 @@ #include "certxutl.h" #include "nss.h" - /* #define TEST 1 */ /* #define FILEOUT 1 */ /* #define OFFLINE 1 */ -#define START_FIELDS 100 -#define PREFIX_LEN 6 -#define SERIAL_FILE "../serial" -#define DB_DIRECTORY ".." +#define START_FIELDS 100 +#define PREFIX_LEN 6 +#define SERIAL_FILE "../serial" +#define DB_DIRECTORY ".." static char *progName; @@ -40,19 +38,14 @@ struct PairStr { char *data; }; - char prefix[PREFIX_LEN]; - const SEC_ASN1Template CERTIA5TypeTemplate[] = { { SEC_ASN1_IA5_STRING } }; - - -SECKEYPrivateKey *privkeys[9] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL}; - +SECKEYPrivateKey *privkeys[9] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL }; #ifdef notdef const SEC_ASN1Template CERT_GeneralNameTemplate[] = { @@ -60,9 +53,8 @@ const SEC_ASN1Template CERT_GeneralNameTemplate[] = { }; #endif - static void -error_out(char *error_string) +error_out(char *error_string) { printf("Content-type: text/plain\n\n"); printf("%s", error_string); @@ -77,860 +69,840 @@ error_allocate(void) error_out("ERROR: Unable to allocate memory"); } - static char * -make_copy_string(char *read_pos, - int length, - char sentinal_value) - /* copys string from to a new string it creates and +make_copy_string(char *read_pos, + int length, + char sentinal_value) +/* copys string from to a new string it creates and returns a pointer to the new string */ { - int remaining = length; - char *write_pos; - char *new; + int remaining = length; + char *write_pos; + char *new; - new = write_pos = (char *) PORT_Alloc (length); + new = write_pos = (char *)PORT_Alloc(length); if (new == NULL) { - error_allocate(); + error_allocate(); } while (*read_pos != sentinal_value) { - if (remaining == 1) { - remaining += length; - length = length * 2; - new = PORT_Realloc(new,length); - if (new == NULL) { - error_allocate(); - } - write_pos = new + length - remaining; - } - *write_pos = *read_pos; - ++write_pos; - ++read_pos; - remaining = remaining - 1; + if (remaining == 1) { + remaining += length; + length = length * 2; + new = PORT_Realloc(new, length); + if (new == NULL) { + error_allocate(); + } + write_pos = new + length - remaining; + } + *write_pos = *read_pos; + ++write_pos; + ++read_pos; + remaining = remaining - 1; } *write_pos = '\0'; return new; } - static SECStatus clean_input(Pair *data) - /* converts the non-alphanumeric characters in a form post +/* converts the non-alphanumeric characters in a form post from hex codes back to characters */ { - int length; - int hi_digit; - int low_digit; - char character; - char *begin_pos; - char *read_pos; - char *write_pos; - PRBool name = PR_TRUE; + int length; + int hi_digit; + int low_digit; + char character; + char *begin_pos; + char *read_pos; + char *write_pos; + PRBool name = PR_TRUE; begin_pos = data->name; while (begin_pos != NULL) { - length = strlen(begin_pos); - read_pos = write_pos = begin_pos; - while ((read_pos - begin_pos) < length) { - if (*read_pos == '+') { - *read_pos = ' '; - } - if (*read_pos == '%') { - hi_digit = *(read_pos + 1); - low_digit = *(read_pos +2); - read_pos += 3; - if (isdigit(hi_digit)){ - hi_digit = hi_digit - '0'; - } else { - hi_digit = toupper(hi_digit); - if (isxdigit(hi_digit)) { - hi_digit = (hi_digit - 'A') + 10; - } else { - error_out("ERROR: Form data incorrectly formated"); - } - } - if (isdigit(low_digit)){ - low_digit = low_digit - '0'; - } else { - low_digit = toupper(low_digit); - if ((low_digit >='A') && (low_digit <= 'F')) { - low_digit = (low_digit - 'A') + 10; - } else { - error_out("ERROR: Form data incorrectly formated"); - } - } - character = (hi_digit << 4) | low_digit; - if (character != 10) { - *write_pos = character; - ++write_pos; - } - } else { - *write_pos = *read_pos; - ++write_pos; - ++read_pos; - } - } - *write_pos = '\0'; - if (name == PR_TRUE) { - begin_pos = data->data; - name = PR_FALSE; - } else { - data++; - begin_pos = data->name; - name = PR_TRUE; - } + length = strlen(begin_pos); + read_pos = write_pos = begin_pos; + while ((read_pos - begin_pos) < length) { + if (*read_pos == '+') { + *read_pos = ' '; + } + if (*read_pos == '%') { + hi_digit = *(read_pos + 1); + low_digit = *(read_pos + 2); + read_pos += 3; + if (isdigit(hi_digit)) { + hi_digit = hi_digit - '0'; + } else { + hi_digit = toupper(hi_digit); + if (isxdigit(hi_digit)) { + hi_digit = (hi_digit - 'A') + 10; + } else { + error_out("ERROR: Form data incorrectly formated"); + } + } + if (isdigit(low_digit)) { + low_digit = low_digit - '0'; + } else { + low_digit = toupper(low_digit); + if ((low_digit >= 'A') && (low_digit <= 'F')) { + low_digit = (low_digit - 'A') + 10; + } else { + error_out("ERROR: Form data incorrectly formated"); + } + } + character = (hi_digit << 4) | low_digit; + if (character != 10) { + *write_pos = character; + ++write_pos; + } + } else { + *write_pos = *read_pos; + ++write_pos; + ++read_pos; + } + } + *write_pos = '\0'; + if (name == PR_TRUE) { + begin_pos = data->data; + name = PR_FALSE; + } else { + data++; + begin_pos = data->name; + name = PR_TRUE; + } } return SECSuccess; } static char * -make_name(char *new_data) - /* gets the next field name in the input string and returns +make_name(char *new_data) +/* gets the next field name in the input string and returns a pointer to a string containing a copy of it */ { - int length = 20; - char *name; + int length = 20; + char *name; name = make_copy_string(new_data, length, '='); return name; } - + static char * -make_data(char *new_data) - /* gets the data for the next field in the input string +make_data(char *new_data) +/* gets the data for the next field in the input string and returns a pointer to a string containing it */ { - int length = 100; - char *data; - char *read_pos; + int length = 100; + char *data; + char *read_pos; read_pos = new_data; while (*(read_pos - 1) != '=') { - ++read_pos; + ++read_pos; } data = make_copy_string(read_pos, length, '&'); return data; } - static Pair -make_pair(char *new_data) - /* makes a pair name/data pair from the input string */ +make_pair(char *new_data) +/* makes a pair name/data pair from the input string */ { - Pair temp; + Pair temp; temp.name = make_name(new_data); temp.data = make_data(new_data); return temp; } - - static Pair * -make_datastruct(char *data, int len) - /* parses the input from the form post into a data +make_datastruct(char *data, int len) +/* parses the input from the form post into a data structure of field name/data pairs */ { - Pair *datastruct; - Pair *current; - char *curr_pos; - int fields = START_FIELDS; - int remaining = START_FIELDS; + Pair *datastruct; + Pair *current; + char *curr_pos; + int fields = START_FIELDS; + int remaining = START_FIELDS; curr_pos = data; - datastruct = current = (Pair *) PORT_Alloc(fields * sizeof(Pair)); + datastruct = current = (Pair *)PORT_Alloc(fields * sizeof(Pair)); if (datastruct == NULL) { - error_allocate(); + error_allocate(); } while (curr_pos - data < len) { - if (remaining == 1) { - remaining += fields; - fields = fields * 2; - datastruct = (Pair *) PORT_Realloc - (datastruct, fields * sizeof(Pair)); - if (datastruct == NULL) { - error_allocate(); - } - current = datastruct + (fields - remaining); - } - *current = make_pair(curr_pos); - while (*curr_pos != '&') { - ++curr_pos; - } - ++curr_pos; - ++current; - remaining = remaining - 1; + if (remaining == 1) { + remaining += fields; + fields = fields * 2; + datastruct = (Pair *)PORT_Realloc(datastruct, fields * + sizeof(Pair)); + if (datastruct == NULL) { + error_allocate(); + } + current = datastruct + (fields - remaining); + } + *current = make_pair(curr_pos); + while (*curr_pos != '&') { + ++curr_pos; + } + ++curr_pos; + ++current; + remaining = remaining - 1; } current->name = NULL; return datastruct; } static char * -return_name(Pair *data_struct, - int n) - /* returns a pointer to the name of the nth +return_name(Pair *data_struct, + int n) +/* returns a pointer to the name of the nth (starting from 0) item in the data structure */ { - char *name; + char *name; if ((data_struct + n)->name != NULL) { - name = (data_struct + n)->name; - return name; + name = (data_struct + n)->name; + return name; } else { - return NULL; + return NULL; } } static char * -return_data(Pair *data_struct,int n) - /* returns a pointer to the data of the nth (starting from 0) +return_data(Pair *data_struct, int n) +/* returns a pointer to the data of the nth (starting from 0) itme in the data structure */ { - char *data; + char *data; data = (data_struct + n)->data; return data; } - static char * -add_prefix(char *field_name) +add_prefix(char *field_name) { - extern char prefix[PREFIX_LEN]; - int i = 0; - char *rv; - char *write; + extern char prefix[PREFIX_LEN]; + int i = 0; + char *rv; + char *write; rv = write = PORT_Alloc(PORT_Strlen(prefix) + PORT_Strlen(field_name) + 1); - for(i = 0; i < PORT_Strlen(prefix); i++) { - *write = prefix[i]; - write++; + for (i = 0; i < PORT_Strlen(prefix); i++) { + *write = prefix[i]; + write++; } *write = '\0'; - rv = PORT_Strcat(rv,field_name); + rv = PORT_Strcat(rv, field_name); return rv; } - static char * -find_field(Pair *data, - char *field_name, - PRBool add_pre) - /* returns a pointer to the data of the first pair +find_field(Pair *data, + char *field_name, + PRBool add_pre) +/* returns a pointer to the data of the first pair thats name matches the string it is passed */ { - int i = 0; - char *retrieved; - int found = 0; + int i = 0; + char *retrieved; + int found = 0; if (add_pre) { - field_name = add_prefix(field_name); + field_name = add_prefix(field_name); } - while(return_name(data, i) != NULL) { - if (PORT_Strcmp(return_name(data, i), field_name) == 0) { - retrieved = return_data(data, i); - found = 1; - break; - } - i++; + while (return_name(data, i) != NULL) { + if (PORT_Strcmp(return_name(data, i), field_name) == 0) { + retrieved = return_data(data, i); + found = 1; + break; + } + i++; } if (!found) { - retrieved = NULL; + retrieved = NULL; } return retrieved; } static PRBool -find_field_bool(Pair *data, - char *fieldname, - PRBool add_pre) +find_field_bool(Pair *data, + char *fieldname, + PRBool add_pre) { - char *rv; + char *rv; rv = find_field(data, fieldname, add_pre); - - if ((rv != NULL) && (PORT_Strcmp(rv, "true")) == 0) { - return PR_TRUE; + + if ((rv != NULL) && (PORT_Strcmp(rv, "true")) == 0) { + return PR_TRUE; } else { - return PR_FALSE; + return PR_FALSE; } } static CERTCertificateRequest * -makeCertReq(Pair *form_data, - int which_priv_key) - /* makes and encodes a certrequest */ +makeCertReq(Pair *form_data, + int which_priv_key) +/* makes and encodes a certrequest */ { - PK11SlotInfo *slot; - CERTCertificateRequest *certReq = NULL; + PK11SlotInfo *slot; + CERTCertificateRequest *certReq = NULL; CERTSubjectPublicKeyInfo *spki; - SECKEYPrivateKey *privkey = NULL; - SECKEYPublicKey *pubkey = NULL; - CERTName *name; - char *key; - extern SECKEYPrivateKey *privkeys[9]; - int keySizeInBits; - char *challenge = "foo"; - SECStatus rv = SECSuccess; - PQGParams *pqgParams = NULL; - PQGVerify *pqgVfy = NULL; + SECKEYPrivateKey *privkey = NULL; + SECKEYPublicKey *pubkey = NULL; + CERTName *name; + char *key; + extern SECKEYPrivateKey *privkeys[9]; + int keySizeInBits; + char *challenge = "foo"; + SECStatus rv = SECSuccess; + PQGParams *pqgParams = NULL; + PQGVerify *pqgVfy = NULL; name = CERT_AsciiToName(find_field(form_data, "subject", PR_TRUE)); if (name == NULL) { - error_out("ERROR: Unable to create Subject Name"); + error_out("ERROR: Unable to create Subject Name"); } key = find_field(form_data, "key", PR_TRUE); if (key == NULL) { - switch (*find_field(form_data, "keysize", PR_TRUE)) { - case '0': - keySizeInBits = 2048; - break; - case '1': - keySizeInBits = 1024; - break; - case '2': - keySizeInBits = 512; - break; - default: - error_out("ERROR: Unsupported Key length selected"); - } - if (find_field_bool(form_data, "keyType-dsa", PR_TRUE)) { - rv = PK11_PQG_ParamGen(keySizeInBits, &pqgParams, &pqgVfy); - if (rv != SECSuccess) { - error_out("ERROR: Unable to generate PQG parameters"); - } - slot = PK11_GetBestSlot(CKM_DSA_KEY_PAIR_GEN, NULL); - privkey = PK11_GenerateKeyPair(slot, CKM_DSA_KEY_PAIR_GEN, - pqgParams,&pubkey, PR_FALSE, - PR_TRUE, NULL); - } else { - privkey = SECKEY_CreateRSAPrivateKey(keySizeInBits, &pubkey, NULL); - } - privkeys[which_priv_key] = privkey; - spki = SECKEY_CreateSubjectPublicKeyInfo(pubkey); + switch (*find_field(form_data, "keysize", PR_TRUE)) { + case '0': + keySizeInBits = 2048; + break; + case '1': + keySizeInBits = 1024; + break; + case '2': + keySizeInBits = 512; + break; + default: + error_out("ERROR: Unsupported Key length selected"); + } + if (find_field_bool(form_data, "keyType-dsa", PR_TRUE)) { + rv = PK11_PQG_ParamGen(keySizeInBits, &pqgParams, &pqgVfy); + if (rv != SECSuccess) { + error_out("ERROR: Unable to generate PQG parameters"); + } + slot = PK11_GetBestSlot(CKM_DSA_KEY_PAIR_GEN, NULL); + privkey = PK11_GenerateKeyPair(slot, CKM_DSA_KEY_PAIR_GEN, + pqgParams, &pubkey, PR_FALSE, + PR_TRUE, NULL); + } else { + privkey = SECKEY_CreateRSAPrivateKey(keySizeInBits, &pubkey, NULL); + } + privkeys[which_priv_key] = privkey; + spki = SECKEY_CreateSubjectPublicKeyInfo(pubkey); } else { - spki = SECKEY_ConvertAndDecodePublicKeyAndChallenge(key, challenge, - NULL); - if (spki == NULL) { - error_out("ERROR: Unable to decode Public Key and Challenge String"); - } + spki = SECKEY_ConvertAndDecodePublicKeyAndChallenge(key, challenge, + NULL); + if (spki == NULL) { + error_out("ERROR: Unable to decode Public Key and Challenge String"); + } } certReq = CERT_CreateCertificateRequest(name, spki, NULL); if (certReq == NULL) { - error_out("ERROR: Unable to create Certificate Request"); + error_out("ERROR: Unable to create Certificate Request"); } if (pubkey != NULL) { - SECKEY_DestroyPublicKey(pubkey); + SECKEY_DestroyPublicKey(pubkey); } if (spki != NULL) { - SECKEY_DestroySubjectPublicKeyInfo(spki); + SECKEY_DestroySubjectPublicKeyInfo(spki); } if (pqgParams != NULL) { - PK11_PQG_DestroyParams(pqgParams); + PK11_PQG_DestroyParams(pqgParams); } if (pqgVfy != NULL) { - PK11_PQG_DestroyVerify(pqgVfy); + PK11_PQG_DestroyVerify(pqgVfy); } return certReq; } - - static CERTCertificate * -MakeV1Cert(CERTCertDBHandle *handle, - CERTCertificateRequest *req, - char *issuerNameStr, - PRBool selfsign, - int serialNumber, - int warpmonths, - Pair *data) +MakeV1Cert(CERTCertDBHandle *handle, + CERTCertificateRequest *req, + char *issuerNameStr, + PRBool selfsign, + int serialNumber, + int warpmonths, + Pair *data) { - CERTCertificate *issuerCert = NULL; - CERTValidity *validity; - CERTCertificate *cert = NULL; - PRExplodedTime printableTime; - PRTime now, - after; - if ( !selfsign ) { - issuerCert = CERT_FindCertByNameString(handle, issuerNameStr); - if (!issuerCert) { - error_out("ERROR: Could not find issuer's certificate"); - return NULL; - } + CERTCertificate *issuerCert = NULL; + CERTValidity *validity; + CERTCertificate *cert = NULL; + PRExplodedTime printableTime; + PRTime now, + after; + if (!selfsign) { + issuerCert = CERT_FindCertByNameString(handle, issuerNameStr); + if (!issuerCert) { + error_out("ERROR: Could not find issuer's certificate"); + return NULL; + } } if (find_field_bool(data, "manValidity", PR_TRUE)) { - (void)DER_AsciiToTime(&now, find_field(data, "notBefore", PR_TRUE)); + (void)DER_AsciiToTime(&now, find_field(data, "notBefore", PR_TRUE)); } else { - now = PR_Now(); + now = PR_Now(); } - PR_ExplodeTime (now, PR_GMTParameters, &printableTime); - if ( warpmonths ) { - printableTime.tm_month += warpmonths; - now = PR_ImplodeTime (&printableTime); - PR_ExplodeTime (now, PR_GMTParameters, &printableTime); + PR_ExplodeTime(now, PR_GMTParameters, &printableTime); + if (warpmonths) { + printableTime.tm_month += warpmonths; + now = PR_ImplodeTime(&printableTime); + PR_ExplodeTime(now, PR_GMTParameters, &printableTime); } if (find_field_bool(data, "manValidity", PR_TRUE)) { - (void)DER_AsciiToTime(&after, find_field(data, "notAfter", PR_TRUE)); - PR_ExplodeTime (after, PR_GMTParameters, &printableTime); + (void)DER_AsciiToTime(&after, find_field(data, "notAfter", PR_TRUE)); + PR_ExplodeTime(after, PR_GMTParameters, &printableTime); } else { - printableTime.tm_month += 3; - after = PR_ImplodeTime (&printableTime); + printableTime.tm_month += 3; + after = PR_ImplodeTime(&printableTime); } /* note that the time is now in micro-second unit */ - validity = CERT_CreateValidity (now, after); + validity = CERT_CreateValidity(now, after); - if ( selfsign ) { - cert = CERT_CreateCertificate - (serialNumber,&(req->subject), validity, req); + if (selfsign) { + cert = CERT_CreateCertificate(serialNumber, &(req->subject), validity, req); } else { - cert = CERT_CreateCertificate - (serialNumber,&(issuerCert->subject), validity, req); + cert = CERT_CreateCertificate(serialNumber, &(issuerCert->subject), validity, req); } - + CERT_DestroyValidity(validity); - if ( issuerCert ) { - CERT_DestroyCertificate (issuerCert); + if (issuerCert) { + CERT_DestroyCertificate(issuerCert); } - return(cert); + return (cert); } static int -get_serial_number(Pair *data) +get_serial_number(Pair *data) { - int serial = 0; - int error; - char *filename = SERIAL_FILE; - char *SN; - FILE *serialFile; - + int serial = 0; + int error; + char *filename = SERIAL_FILE; + char *SN; + FILE *serialFile; if (find_field_bool(data, "serial-auto", PR_TRUE)) { - serialFile = fopen(filename, "r"); - if (serialFile != NULL) { - size_t nread = fread(&serial, sizeof(int), 1, serialFile); - if (ferror(serialFile) != 0 || nread != 1) { - error_out("Error: Unable to read serial number file"); - } - if (serial == -1) { - serial = 21; - } - fclose(serialFile); - ++serial; - serialFile = fopen(filename,"w"); - if (serialFile == NULL) { - error_out("ERROR: Unable to open serial number file for writing"); - } - fwrite(&serial, sizeof(int), 1, serialFile); - if (ferror(serialFile) != 0) { - error_out("Error: Unable to write to serial number file"); - } - } else { - fclose(serialFile); - serialFile = fopen(filename,"w"); - if (serialFile == NULL) { - error_out("ERROR: Unable to open serial number file"); - } - serial = 21; - fwrite(&serial, sizeof(int), 1, serialFile); - if (ferror(serialFile) != 0) { - error_out("Error: Unable to write to serial number file"); - } - error = ferror(serialFile); - if (error != 0) { - error_out("ERROR: Unable to write to serial file"); - } - } - fclose(serialFile); + serialFile = fopen(filename, "r"); + if (serialFile != NULL) { + size_t nread = fread(&serial, sizeof(int), 1, serialFile); + if (ferror(serialFile) != 0 || nread != 1) { + error_out("Error: Unable to read serial number file"); + } + if (serial == -1) { + serial = 21; + } + fclose(serialFile); + ++serial; + serialFile = fopen(filename, "w"); + if (serialFile == NULL) { + error_out("ERROR: Unable to open serial number file for writing"); + } + fwrite(&serial, sizeof(int), 1, serialFile); + if (ferror(serialFile) != 0) { + error_out("Error: Unable to write to serial number file"); + } + } else { + fclose(serialFile); + serialFile = fopen(filename, "w"); + if (serialFile == NULL) { + error_out("ERROR: Unable to open serial number file"); + } + serial = 21; + fwrite(&serial, sizeof(int), 1, serialFile); + if (ferror(serialFile) != 0) { + error_out("Error: Unable to write to serial number file"); + } + error = ferror(serialFile); + if (error != 0) { + error_out("ERROR: Unable to write to serial file"); + } + } + fclose(serialFile); } else { - SN = find_field(data, "serial_value", PR_TRUE); - while (*SN != '\0') { - serial = serial * 16; - if ((*SN >= 'A') && (*SN <='F')) { - serial += *SN - 'A' + 10; - } else { - if ((*SN >= 'a') && (*SN <='f')) { - serial += *SN - 'a' + 10; - } else { - serial += *SN - '0'; - } - } - ++SN; - } + SN = find_field(data, "serial_value", PR_TRUE); + while (*SN != '\0') { + serial = serial * 16; + if ((*SN >= 'A') && (*SN <= 'F')) { + serial += *SN - 'A' + 10; + } else { + if ((*SN >= 'a') && (*SN <= 'f')) { + serial += *SN - 'a' + 10; + } else { + serial += *SN - '0'; + } + } + ++SN; + } } return serial; } - - -typedef SECStatus (* EXTEN_VALUE_ENCODER) - (PLArenaPool *extHandle, void *value, SECItem *encodedValue); +typedef SECStatus (*EXTEN_VALUE_ENCODER)(PLArenaPool *extHandle, void *value, SECItem *encodedValue); -static SECStatus +static SECStatus EncodeAndAddExtensionValue( - PLArenaPool *arena, - void *extHandle, - void *value, - PRBool criticality, - int extenType, - EXTEN_VALUE_ENCODER EncodeValueFn) + PLArenaPool *arena, + void *extHandle, + void *value, + PRBool criticality, + int extenType, + EXTEN_VALUE_ENCODER EncodeValueFn) { - SECItem encodedValue; - SECStatus rv; - + SECItem encodedValue; + SECStatus rv; encodedValue.data = NULL; encodedValue.len = 0; rv = (*EncodeValueFn)(arena, value, &encodedValue); if (rv != SECSuccess) { - error_out("ERROR: Unable to encode extension value"); + error_out("ERROR: Unable to encode extension value"); } - rv = CERT_AddExtension - (extHandle, extenType, &encodedValue, criticality, PR_TRUE); + rv = CERT_AddExtension(extHandle, extenType, &encodedValue, criticality, PR_TRUE); return (rv); } - - -static SECStatus -AddKeyUsage (void *extHandle, - Pair *data) +static SECStatus +AddKeyUsage(void *extHandle, + Pair *data) { - SECItem bitStringValue; - unsigned char keyUsage = 0x0; + SECItem bitStringValue; + unsigned char keyUsage = 0x0; - if (find_field_bool(data,"keyUsage-digitalSignature", PR_TRUE)){ - keyUsage |= (0x80 >> 0); + if (find_field_bool(data, "keyUsage-digitalSignature", PR_TRUE)) { + keyUsage |= (0x80 >> 0); } - if (find_field_bool(data,"keyUsage-nonRepudiation", PR_TRUE)){ - keyUsage |= (0x80 >> 1); + if (find_field_bool(data, "keyUsage-nonRepudiation", PR_TRUE)) { + keyUsage |= (0x80 >> 1); } - if (find_field_bool(data,"keyUsage-keyEncipherment", PR_TRUE)){ - keyUsage |= (0x80 >> 2); + if (find_field_bool(data, "keyUsage-keyEncipherment", PR_TRUE)) { + keyUsage |= (0x80 >> 2); } - if (find_field_bool(data,"keyUsage-dataEncipherment", PR_TRUE)){ - keyUsage |= (0x80 >> 3); + if (find_field_bool(data, "keyUsage-dataEncipherment", PR_TRUE)) { + keyUsage |= (0x80 >> 3); } - if (find_field_bool(data,"keyUsage-keyAgreement", PR_TRUE)){ - keyUsage |= (0x80 >> 4); + if (find_field_bool(data, "keyUsage-keyAgreement", PR_TRUE)) { + keyUsage |= (0x80 >> 4); } - if (find_field_bool(data,"keyUsage-keyCertSign", PR_TRUE)) { - keyUsage |= (0x80 >> 5); + if (find_field_bool(data, "keyUsage-keyCertSign", PR_TRUE)) { + keyUsage |= (0x80 >> 5); } - if (find_field_bool(data,"keyUsage-cRLSign", PR_TRUE)) { - keyUsage |= (0x80 >> 6); + if (find_field_bool(data, "keyUsage-cRLSign", PR_TRUE)) { + keyUsage |= (0x80 >> 6); } bitStringValue.data = &keyUsage; bitStringValue.len = 1; - return (CERT_EncodeAndAddBitStrExtension - (extHandle, SEC_OID_X509_KEY_USAGE, &bitStringValue, - (find_field_bool(data, "keyUsage-crit", PR_TRUE)))); - + return (CERT_EncodeAndAddBitStrExtension(extHandle, SEC_OID_X509_KEY_USAGE, &bitStringValue, + (find_field_bool(data, "keyUsage-crit", PR_TRUE)))); } static CERTOidSequence * CreateOidSequence(void) { - CERTOidSequence *rv = (CERTOidSequence *)NULL; - PLArenaPool *arena = (PLArenaPool *)NULL; + CERTOidSequence *rv = (CERTOidSequence *)NULL; + PLArenaPool *arena = (PLArenaPool *)NULL; - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if( (PLArenaPool *)NULL == arena ) { - goto loser; - } + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if ((PLArenaPool *)NULL == arena) { + goto loser; + } - rv = (CERTOidSequence *)PORT_ArenaZAlloc(arena, sizeof(CERTOidSequence)); - if( (CERTOidSequence *)NULL == rv ) { - goto loser; - } + rv = (CERTOidSequence *)PORT_ArenaZAlloc(arena, sizeof(CERTOidSequence)); + if ((CERTOidSequence *)NULL == rv) { + goto loser; + } - rv->oids = (SECItem **)PORT_ArenaZAlloc(arena, sizeof(SECItem *)); - if( (SECItem **)NULL == rv->oids ) { - goto loser; - } + rv->oids = (SECItem **)PORT_ArenaZAlloc(arena, sizeof(SECItem *)); + if ((SECItem **)NULL == rv->oids) { + goto loser; + } - rv->arena = arena; - return rv; + rv->arena = arena; + return rv; - loser: - if( (PLArenaPool *)NULL != arena ) { - PORT_FreeArena(arena, PR_FALSE); - } +loser: + if ((PLArenaPool *)NULL != arena) { + PORT_FreeArena(arena, PR_FALSE); + } - return (CERTOidSequence *)NULL; + return (CERTOidSequence *)NULL; } static SECStatus AddOidToSequence(CERTOidSequence *os, SECOidTag oidTag) { - SECItem **oids; - PRUint32 count = 0; - SECOidData *od; + SECItem **oids; + PRUint32 count = 0; + SECOidData *od; - od = SECOID_FindOIDByTag(oidTag); - if( (SECOidData *)NULL == od ) { - return SECFailure; - } + od = SECOID_FindOIDByTag(oidTag); + if ((SECOidData *)NULL == od) { + return SECFailure; + } - for( oids = os->oids; (SECItem *)NULL != *oids; oids++ ) { - count++; - } + for (oids = os->oids; (SECItem *)NULL != *oids; oids++) { + count++; + } - /* ArenaZRealloc */ + /* ArenaZRealloc */ - { - PRUint32 i; + { + PRUint32 i; - oids = (SECItem **)PORT_ArenaZAlloc(os->arena, sizeof(SECItem *) * (count+2)); - if( (SECItem **)NULL == oids ) { - return SECFailure; - } - - for( i = 0; i < count; i++ ) { - oids[i] = os->oids[i]; - } + oids = (SECItem **)PORT_ArenaZAlloc(os->arena, sizeof(SECItem *) * (count + 2)); + if ((SECItem **)NULL == oids) { + return SECFailure; + } - /* ArenaZFree(os->oids); */ - } + for (i = 0; i < count; i++) { + oids[i] = os->oids[i]; + } - os->oids = oids; - os->oids[count] = &od->oid; + /* ArenaZFree(os->oids); */ + } - return SECSuccess; + os->oids = oids; + os->oids[count] = &od->oid; + + return SECSuccess; } static SECItem * EncodeOidSequence(CERTOidSequence *os) { - SECItem *rv; - extern const SEC_ASN1Template CERT_OidSeqTemplate[]; + SECItem *rv; + extern const SEC_ASN1Template CERT_OidSeqTemplate[]; - rv = (SECItem *)PORT_ArenaZAlloc(os->arena, sizeof(SECItem)); - if( (SECItem *)NULL == rv ) { - goto loser; - } + rv = (SECItem *)PORT_ArenaZAlloc(os->arena, sizeof(SECItem)); + if ((SECItem *)NULL == rv) { + goto loser; + } - if( !SEC_ASN1EncodeItem(os->arena, rv, os, CERT_OidSeqTemplate) ) { - goto loser; - } + if (!SEC_ASN1EncodeItem(os->arena, rv, os, CERT_OidSeqTemplate)) { + goto loser; + } - return rv; + return rv; - loser: - return (SECItem *)NULL; +loser: + return (SECItem *)NULL; } static SECStatus AddExtKeyUsage(void *extHandle, Pair *data) { - SECStatus rv; - CERTOidSequence *os; - SECItem *value; - PRBool crit; - - os = CreateOidSequence(); - if( (CERTOidSequence *)NULL == os ) { - return SECFailure; - } - - if( find_field_bool(data, "extKeyUsage-serverAuth", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_SERVER_AUTH); - if( SECSuccess != rv ) goto loser; - } - - if( find_field_bool(data, "extKeyUsage-msTrustListSign", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_MS_EXT_KEY_USAGE_CTL_SIGNING); - if( SECSuccess != rv ) goto loser; - } - - if( find_field_bool(data, "extKeyUsage-clientAuth", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH); - if( SECSuccess != rv ) goto loser; - } - - if( find_field_bool(data, "extKeyUsage-codeSign", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CODE_SIGN); - if( SECSuccess != rv ) goto loser; - } - - if( find_field_bool(data, "extKeyUsage-emailProtect", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_EMAIL_PROTECT); - if( SECSuccess != rv ) goto loser; - } - - if( find_field_bool(data, "extKeyUsage-timeStamp", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_TIME_STAMP); - if( SECSuccess != rv ) goto loser; - } - - if( find_field_bool(data, "extKeyUsage-ocspResponder", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_OCSP_RESPONDER); - if( SECSuccess != rv ) goto loser; - } - - if( find_field_bool(data, "extKeyUsage-NS-govtApproved", PR_TRUE) ) { - rv = AddOidToSequence(os, SEC_OID_NS_KEY_USAGE_GOVT_APPROVED); - if( SECSuccess != rv ) goto loser; - } - - value = EncodeOidSequence(os); - - crit = find_field_bool(data, "extKeyUsage-crit", PR_TRUE); - - rv = CERT_AddExtension(extHandle, SEC_OID_X509_EXT_KEY_USAGE, value, - crit, PR_TRUE); - /*FALLTHROUGH*/ - loser: - CERT_DestroyOidSequence(os); - return rv; + SECStatus rv; + CERTOidSequence *os; + SECItem *value; + PRBool crit; + + os = CreateOidSequence(); + if ((CERTOidSequence *)NULL == os) { + return SECFailure; + } + + if (find_field_bool(data, "extKeyUsage-serverAuth", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_SERVER_AUTH); + if (SECSuccess != rv) + goto loser; + } + + if (find_field_bool(data, "extKeyUsage-msTrustListSign", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_MS_EXT_KEY_USAGE_CTL_SIGNING); + if (SECSuccess != rv) + goto loser; + } + + if (find_field_bool(data, "extKeyUsage-clientAuth", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH); + if (SECSuccess != rv) + goto loser; + } + + if (find_field_bool(data, "extKeyUsage-codeSign", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CODE_SIGN); + if (SECSuccess != rv) + goto loser; + } + + if (find_field_bool(data, "extKeyUsage-emailProtect", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_EMAIL_PROTECT); + if (SECSuccess != rv) + goto loser; + } + + if (find_field_bool(data, "extKeyUsage-timeStamp", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_TIME_STAMP); + if (SECSuccess != rv) + goto loser; + } + + if (find_field_bool(data, "extKeyUsage-ocspResponder", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_OCSP_RESPONDER); + if (SECSuccess != rv) + goto loser; + } + + if (find_field_bool(data, "extKeyUsage-NS-govtApproved", PR_TRUE)) { + rv = AddOidToSequence(os, SEC_OID_NS_KEY_USAGE_GOVT_APPROVED); + if (SECSuccess != rv) + goto loser; + } + + value = EncodeOidSequence(os); + + crit = find_field_bool(data, "extKeyUsage-crit", PR_TRUE); + + rv = CERT_AddExtension(extHandle, SEC_OID_X509_EXT_KEY_USAGE, value, + crit, PR_TRUE); +/*FALLTHROUGH*/ +loser: + CERT_DestroyOidSequence(os); + return rv; } static SECStatus -AddSubKeyID(void *extHandle, - Pair *data, - CERTCertificate *subjectCert) +AddSubKeyID(void *extHandle, + Pair *data, + CERTCertificate *subjectCert) { - SECItem encodedValue; - SECStatus rv; - char *read; - char *write; - char *first; - char character; - int high_digit = 0, - low_digit = 0; - int len; - PRBool odd = PR_FALSE; - + SECItem encodedValue; + SECStatus rv; + char *read; + char *write; + char *first; + char character; + int high_digit = 0, + low_digit = 0; + int len; + PRBool odd = PR_FALSE; encodedValue.data = NULL; encodedValue.len = 0; - first = read = write = find_field(data,"subjectKeyIdentifier-text", - PR_TRUE); + first = read = write = find_field(data, "subjectKeyIdentifier-text", + PR_TRUE); len = PORT_Strlen(first); - odd = ((len % 2) != 0 ) ? PR_TRUE : PR_FALSE; + odd = ((len % 2) != 0) ? PR_TRUE : PR_FALSE; if (find_field_bool(data, "subjectKeyIdentifier-radio-hex", PR_TRUE)) { - if (odd) { - error_out("ERROR: Improperly formated subject key identifier, hex values must be expressed as an octet string"); - } - while (*read != '\0') { - if (!isxdigit(*read)) { - error_out("ERROR: Improperly formated subject key identifier"); - } - *read = toupper(*read); - if ((*read >= 'A') && (*read <= 'F')) { - high_digit = *read - 'A' + 10; - } else { - high_digit = *read - '0'; - } - ++read; - if (!isxdigit(*read)) { - error_out("ERROR: Improperly formated subject key identifier"); - } - *read = toupper(*read); - if ((*read >= 'A') && (*read <= 'F')) { - low_digit = *(read) - 'A' + 10; - } else { - low_digit = *(read) - '0'; - } - character = (high_digit << 4) | low_digit; - *write = character; - ++write; - ++read; - } - *write = '\0'; - len = write - first; - } - subjectCert->subjectKeyID.data = (unsigned char *) find_field - (data,"subjectKeyIdentifier-text", PR_TRUE); + if (odd) { + error_out("ERROR: Improperly formated subject key identifier, hex values must be expressed as an octet string"); + } + while (*read != '\0') { + if (!isxdigit(*read)) { + error_out("ERROR: Improperly formated subject key identifier"); + } + *read = toupper(*read); + if ((*read >= 'A') && (*read <= 'F')) { + high_digit = *read - 'A' + 10; + } else { + high_digit = *read - '0'; + } + ++read; + if (!isxdigit(*read)) { + error_out("ERROR: Improperly formated subject key identifier"); + } + *read = toupper(*read); + if ((*read >= 'A') && (*read <= 'F')) { + low_digit = *(read) - 'A' + 10; + } else { + low_digit = *(read) - '0'; + } + character = (high_digit << 4) | low_digit; + *write = character; + ++write; + ++read; + } + *write = '\0'; + len = write - first; + } + subjectCert->subjectKeyID.data = (unsigned char *)find_field(data, "subjectKeyIdentifier-text", PR_TRUE); subjectCert->subjectKeyID.len = len; - rv = CERT_EncodeSubjectKeyID - (NULL, &subjectCert->subjectKeyID, &encodedValue); + rv = CERT_EncodeSubjectKeyID(NULL, &subjectCert->subjectKeyID, &encodedValue); if (rv) { - return (rv); + return (rv); } - return (CERT_AddExtension(extHandle, SEC_OID_X509_SUBJECT_KEY_ID, - &encodedValue, PR_FALSE, PR_TRUE)); + return (CERT_AddExtension(extHandle, SEC_OID_X509_SUBJECT_KEY_ID, + &encodedValue, PR_FALSE, PR_TRUE)); } - -static SECStatus -AddAuthKeyID (void *extHandle, - Pair *data, - char *issuerNameStr, - CERTCertDBHandle *handle) +static SECStatus +AddAuthKeyID(void *extHandle, + Pair *data, + char *issuerNameStr, + CERTCertDBHandle *handle) { - CERTAuthKeyID *authKeyID = NULL; - PLArenaPool *arena = NULL; - SECStatus rv = SECSuccess; - CERTCertificate *issuerCert = NULL; - CERTGeneralName *genNames; - CERTName *directoryName = NULL; - + CERTAuthKeyID *authKeyID = NULL; + PLArenaPool *arena = NULL; + SECStatus rv = SECSuccess; + CERTCertificate *issuerCert = NULL; + CERTGeneralName *genNames; + CERTName *directoryName = NULL; issuerCert = CERT_FindCertByNameString(handle, issuerNameStr); arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - error_allocate(); + if (!arena) { + error_allocate(); } - authKeyID = PORT_ArenaZAlloc (arena, sizeof (CERTAuthKeyID)); + authKeyID = PORT_ArenaZAlloc(arena, sizeof(CERTAuthKeyID)); if (authKeyID == NULL) { - error_allocate(); - } - if (find_field_bool(data, "authorityKeyIdentifier-radio-keyIdentifier", - PR_TRUE)) { - authKeyID->keyID.data = PORT_ArenaAlloc (arena, PORT_Strlen - ((char *)issuerCert->subjectKeyID.data)); - if (authKeyID->keyID.data == NULL) { - error_allocate(); - } - PORT_Memcpy (authKeyID->keyID.data, issuerCert->subjectKeyID.data, - authKeyID->keyID.len = - PORT_Strlen((char *)issuerCert->subjectKeyID.data)); + error_allocate(); + } + if (find_field_bool(data, "authorityKeyIdentifier-radio-keyIdentifier", + PR_TRUE)) { + authKeyID->keyID.data = PORT_ArenaAlloc(arena, PORT_Strlen((char *)issuerCert->subjectKeyID.data)); + if (authKeyID->keyID.data == NULL) { + error_allocate(); + } + PORT_Memcpy(authKeyID->keyID.data, issuerCert->subjectKeyID.data, + authKeyID->keyID.len = + PORT_Strlen((char *)issuerCert->subjectKeyID.data)); } else { - - PORT_Assert (arena); - genNames = (CERTGeneralName *) PORT_ArenaZAlloc (arena, (sizeof(CERTGeneralName))); - if (genNames == NULL){ - error_allocate(); - } - genNames->l.next = genNames->l.prev = &(genNames->l); - genNames->type = certDirectoryName; - - directoryName = CERT_AsciiToName(issuerCert->subjectName); - if (!directoryName) { - error_out("ERROR: Unable to create Directory Name"); - } - rv = CERT_CopyName (arena, &genNames->name.directoryName, - directoryName); - CERT_DestroyName (directoryName); - if (rv != SECSuccess) { - error_out("ERROR: Unable to copy Directory Name"); - } - authKeyID->authCertIssuer = genNames; - if (authKeyID->authCertIssuer == NULL && SECFailure == - PORT_GetError ()) { - error_out("ERROR: Unable to get Issuer General Name for Authority Key ID Extension"); - } - authKeyID->authCertSerialNumber = issuerCert->serialNumber; - } - rv = EncodeAndAddExtensionValue(arena, extHandle, authKeyID, PR_FALSE, - SEC_OID_X509_AUTH_KEY_ID, - (EXTEN_VALUE_ENCODER) - CERT_EncodeAuthKeyID); + + PORT_Assert(arena); + genNames = (CERTGeneralName *)PORT_ArenaZAlloc(arena, (sizeof(CERTGeneralName))); + if (genNames == NULL) { + error_allocate(); + } + genNames->l.next = genNames->l.prev = &(genNames->l); + genNames->type = certDirectoryName; + + directoryName = CERT_AsciiToName(issuerCert->subjectName); + if (!directoryName) { + error_out("ERROR: Unable to create Directory Name"); + } + rv = CERT_CopyName(arena, &genNames->name.directoryName, + directoryName); + CERT_DestroyName(directoryName); + if (rv != SECSuccess) { + error_out("ERROR: Unable to copy Directory Name"); + } + authKeyID->authCertIssuer = genNames; + if (authKeyID->authCertIssuer == NULL && SECFailure == + PORT_GetError()) { + error_out("ERROR: Unable to get Issuer General Name for Authority Key ID Extension"); + } + authKeyID->authCertSerialNumber = issuerCert->serialNumber; + } + rv = EncodeAndAddExtensionValue(arena, extHandle, authKeyID, PR_FALSE, + SEC_OID_X509_AUTH_KEY_ID, + (EXTEN_VALUE_ENCODER) + CERT_EncodeAuthKeyID); if (arena) { - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return (rv); } - -static SECStatus -AddPrivKeyUsagePeriod(void *extHandle, - Pair *data, - CERTCertificate *cert) +static SECStatus +AddPrivKeyUsagePeriod(void *extHandle, + Pair *data, + CERTCertificate *cert) { char *notBeforeStr; char *notAfterStr; @@ -938,17 +910,16 @@ AddPrivKeyUsagePeriod(void *extHandle, SECStatus rv = SECSuccess; CERTPrivKeyUsagePeriod *pkup; - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - error_allocate(); + if (!arena) { + error_allocate(); } - pkup = PORT_ArenaZNew (arena, CERTPrivKeyUsagePeriod); + pkup = PORT_ArenaZNew(arena, CERTPrivKeyUsagePeriod); if (pkup == NULL) { - error_allocate(); + error_allocate(); } - notBeforeStr = (char *) PORT_Alloc(16 ); - notAfterStr = (char *) PORT_Alloc(16 ); + notBeforeStr = (char *)PORT_Alloc(16); + notAfterStr = (char *)PORT_Alloc(16); *notBeforeStr = '\0'; *notAfterStr = '\0'; pkup->arena = arena; @@ -957,264 +928,259 @@ AddPrivKeyUsagePeriod(void *extHandle, pkup->notAfter.len = 0; pkup->notAfter.data = NULL; if (find_field_bool(data, "privKeyUsagePeriod-radio-notBefore", PR_TRUE) || - find_field_bool(data, "privKeyUsagePeriod-radio-both", PR_TRUE)) { - pkup->notBefore.len = 15; - pkup->notBefore.data = (unsigned char *)notBeforeStr; - if (find_field_bool(data, "privKeyUsagePeriod-notBefore-radio-manual", - PR_TRUE)) { - PORT_Strcat(notBeforeStr,find_field(data, - "privKeyUsagePeriod-notBefore-year", - PR_TRUE)); - PORT_Strcat(notBeforeStr,find_field(data, - "privKeyUsagePeriod-notBefore-month", - PR_TRUE)); - PORT_Strcat(notBeforeStr,find_field(data, - "privKeyUsagePeriod-notBefore-day", - PR_TRUE)); - PORT_Strcat(notBeforeStr,find_field(data, - "privKeyUsagePeriod-notBefore-hour", - PR_TRUE)); - PORT_Strcat(notBeforeStr,find_field(data, - "privKeyUsagePeriod-notBefore-minute", - PR_TRUE)); - PORT_Strcat(notBeforeStr,find_field(data, - "privKeyUsagePeriod-notBefore-second", - PR_TRUE)); - if ((*(notBeforeStr + 14) != '\0') || - (!isdigit(*(notBeforeStr + 13))) || - (*(notBeforeStr + 12) >= '5' && *(notBeforeStr + 12) <= '0') || - (!isdigit(*(notBeforeStr + 11))) || - (*(notBeforeStr + 10) >= '5' && *(notBeforeStr + 10) <= '0') || - (!isdigit(*(notBeforeStr + 9))) || - (*(notBeforeStr + 8) >= '2' && *(notBeforeStr + 8) <= '0') || - (!isdigit(*(notBeforeStr + 7))) || - (*(notBeforeStr + 6) >= '3' && *(notBeforeStr + 6) <= '0') || - (!isdigit(*(notBeforeStr + 5))) || - (*(notBeforeStr + 4) >= '1' && *(notBeforeStr + 4) <= '0') || - (!isdigit(*(notBeforeStr + 3))) || - (!isdigit(*(notBeforeStr + 2))) || - (!isdigit(*(notBeforeStr + 1))) || - (!isdigit(*(notBeforeStr + 0))) || - (*(notBeforeStr + 8) == '2' && *(notBeforeStr + 9) >= '4') || - (*(notBeforeStr + 6) == '3' && *(notBeforeStr + 7) >= '1') || - (*(notBeforeStr + 4) == '1' && *(notBeforeStr + 5) >= '2')) { - error_out("ERROR: Improperly formated private key usage period"); - } - *(notBeforeStr + 14) = 'Z'; - *(notBeforeStr + 15) = '\0'; - } else { - if ((*(cert->validity.notBefore.data) > '5') || - ((*(cert->validity.notBefore.data) == '5') && - (*(cert->validity.notBefore.data + 1) != '0'))) { - PORT_Strcat(notBeforeStr, "19"); - } else { - PORT_Strcat(notBeforeStr, "20"); - } - PORT_Strcat(notBeforeStr, (char *)cert->validity.notBefore.data); - } + find_field_bool(data, "privKeyUsagePeriod-radio-both", PR_TRUE)) { + pkup->notBefore.len = 15; + pkup->notBefore.data = (unsigned char *)notBeforeStr; + if (find_field_bool(data, "privKeyUsagePeriod-notBefore-radio-manual", + PR_TRUE)) { + PORT_Strcat(notBeforeStr, find_field(data, + "privKeyUsagePeriod-notBefore-year", + PR_TRUE)); + PORT_Strcat(notBeforeStr, find_field(data, + "privKeyUsagePeriod-notBefore-month", + PR_TRUE)); + PORT_Strcat(notBeforeStr, find_field(data, + "privKeyUsagePeriod-notBefore-day", + PR_TRUE)); + PORT_Strcat(notBeforeStr, find_field(data, + "privKeyUsagePeriod-notBefore-hour", + PR_TRUE)); + PORT_Strcat(notBeforeStr, find_field(data, + "privKeyUsagePeriod-notBefore-minute", + PR_TRUE)); + PORT_Strcat(notBeforeStr, find_field(data, + "privKeyUsagePeriod-notBefore-second", + PR_TRUE)); + if ((*(notBeforeStr + 14) != '\0') || + (!isdigit(*(notBeforeStr + 13))) || + (*(notBeforeStr + 12) >= '5' && *(notBeforeStr + 12) <= '0') || + (!isdigit(*(notBeforeStr + 11))) || + (*(notBeforeStr + 10) >= '5' && *(notBeforeStr + 10) <= '0') || + (!isdigit(*(notBeforeStr + 9))) || + (*(notBeforeStr + 8) >= '2' && *(notBeforeStr + 8) <= '0') || + (!isdigit(*(notBeforeStr + 7))) || + (*(notBeforeStr + 6) >= '3' && *(notBeforeStr + 6) <= '0') || + (!isdigit(*(notBeforeStr + 5))) || + (*(notBeforeStr + 4) >= '1' && *(notBeforeStr + 4) <= '0') || + (!isdigit(*(notBeforeStr + 3))) || + (!isdigit(*(notBeforeStr + 2))) || + (!isdigit(*(notBeforeStr + 1))) || + (!isdigit(*(notBeforeStr + 0))) || + (*(notBeforeStr + 8) == '2' && *(notBeforeStr + 9) >= '4') || + (*(notBeforeStr + 6) == '3' && *(notBeforeStr + 7) >= '1') || + (*(notBeforeStr + 4) == '1' && *(notBeforeStr + 5) >= '2')) { + error_out("ERROR: Improperly formated private key usage period"); + } + *(notBeforeStr + 14) = 'Z'; + *(notBeforeStr + 15) = '\0'; + } else { + if ((*(cert->validity.notBefore.data) > '5') || + ((*(cert->validity.notBefore.data) == '5') && + (*(cert->validity.notBefore.data + 1) != '0'))) { + PORT_Strcat(notBeforeStr, "19"); + } else { + PORT_Strcat(notBeforeStr, "20"); + } + PORT_Strcat(notBeforeStr, (char *)cert->validity.notBefore.data); + } } if (find_field_bool(data, "privKeyUsagePeriod-radio-notAfter", PR_TRUE) || - find_field_bool(data, "privKeyUsagePeriod-radio-both", PR_TRUE)) { - pkup->notAfter.len = 15; - pkup->notAfter.data = (unsigned char *)notAfterStr; - PORT_Strcat(notAfterStr,find_field(data,"privKeyUsagePeriod-notAfter-year", - PR_TRUE)); - PORT_Strcat(notAfterStr,find_field(data,"privKeyUsagePeriod-notAfter-month", - PR_TRUE)); - PORT_Strcat(notAfterStr,find_field(data,"privKeyUsagePeriod-notAfter-day", - PR_TRUE)); - PORT_Strcat(notAfterStr,find_field(data,"privKeyUsagePeriod-notAfter-hour", - PR_TRUE)); - PORT_Strcat(notAfterStr,find_field(data,"privKeyUsagePeriod-notAfter-minute", - PR_TRUE)); - PORT_Strcat(notAfterStr,find_field(data,"privKeyUsagePeriod-notAfter-second", - PR_TRUE)); - if ((*(notAfterStr + 14) != '\0') || - (!isdigit(*(notAfterStr + 13))) || - (*(notAfterStr + 12) >= '5' && *(notAfterStr + 12) <= '0') || - (!isdigit(*(notAfterStr + 11))) || - (*(notAfterStr + 10) >= '5' && *(notAfterStr + 10) <= '0') || - (!isdigit(*(notAfterStr + 9))) || - (*(notAfterStr + 8) >= '2' && *(notAfterStr + 8) <= '0') || - (!isdigit(*(notAfterStr + 7))) || - (*(notAfterStr + 6) >= '3' && *(notAfterStr + 6) <= '0') || - (!isdigit(*(notAfterStr + 5))) || - (*(notAfterStr + 4) >= '1' && *(notAfterStr + 4) <= '0') || - (!isdigit(*(notAfterStr + 3))) || - (!isdigit(*(notAfterStr + 2))) || - (!isdigit(*(notAfterStr + 1))) || - (!isdigit(*(notAfterStr + 0))) || - (*(notAfterStr + 8) == '2' && *(notAfterStr + 9) >= '4') || - (*(notAfterStr + 6) == '3' && *(notAfterStr + 7) >= '1') || - (*(notAfterStr + 4) == '1' && *(notAfterStr + 5) >= '2')) { - error_out("ERROR: Improperly formated private key usage period"); - } - *(notAfterStr + 14) = 'Z'; - *(notAfterStr + 15) = '\0'; - } - - PORT_Assert (arena); - - rv = EncodeAndAddExtensionValue(arena, extHandle, pkup, - find_field_bool(data, - "privKeyUsagePeriod-crit", - PR_TRUE), - SEC_OID_X509_PRIVATE_KEY_USAGE_PERIOD, - (EXTEN_VALUE_ENCODER) - CERT_EncodePrivateKeyUsagePeriod); + find_field_bool(data, "privKeyUsagePeriod-radio-both", PR_TRUE)) { + pkup->notAfter.len = 15; + pkup->notAfter.data = (unsigned char *)notAfterStr; + PORT_Strcat(notAfterStr, find_field(data, "privKeyUsagePeriod-notAfter-year", + PR_TRUE)); + PORT_Strcat(notAfterStr, find_field(data, "privKeyUsagePeriod-notAfter-month", + PR_TRUE)); + PORT_Strcat(notAfterStr, find_field(data, "privKeyUsagePeriod-notAfter-day", + PR_TRUE)); + PORT_Strcat(notAfterStr, find_field(data, "privKeyUsagePeriod-notAfter-hour", + PR_TRUE)); + PORT_Strcat(notAfterStr, find_field(data, "privKeyUsagePeriod-notAfter-minute", + PR_TRUE)); + PORT_Strcat(notAfterStr, find_field(data, "privKeyUsagePeriod-notAfter-second", + PR_TRUE)); + if ((*(notAfterStr + 14) != '\0') || + (!isdigit(*(notAfterStr + 13))) || + (*(notAfterStr + 12) >= '5' && *(notAfterStr + 12) <= '0') || + (!isdigit(*(notAfterStr + 11))) || + (*(notAfterStr + 10) >= '5' && *(notAfterStr + 10) <= '0') || + (!isdigit(*(notAfterStr + 9))) || + (*(notAfterStr + 8) >= '2' && *(notAfterStr + 8) <= '0') || + (!isdigit(*(notAfterStr + 7))) || + (*(notAfterStr + 6) >= '3' && *(notAfterStr + 6) <= '0') || + (!isdigit(*(notAfterStr + 5))) || + (*(notAfterStr + 4) >= '1' && *(notAfterStr + 4) <= '0') || + (!isdigit(*(notAfterStr + 3))) || + (!isdigit(*(notAfterStr + 2))) || + (!isdigit(*(notAfterStr + 1))) || + (!isdigit(*(notAfterStr + 0))) || + (*(notAfterStr + 8) == '2' && *(notAfterStr + 9) >= '4') || + (*(notAfterStr + 6) == '3' && *(notAfterStr + 7) >= '1') || + (*(notAfterStr + 4) == '1' && *(notAfterStr + 5) >= '2')) { + error_out("ERROR: Improperly formated private key usage period"); + } + *(notAfterStr + 14) = 'Z'; + *(notAfterStr + 15) = '\0'; + } + + PORT_Assert(arena); + + rv = EncodeAndAddExtensionValue(arena, extHandle, pkup, + find_field_bool(data, + "privKeyUsagePeriod-crit", + PR_TRUE), + SEC_OID_X509_PRIVATE_KEY_USAGE_PERIOD, + (EXTEN_VALUE_ENCODER) + CERT_EncodePrivateKeyUsagePeriod); if (arena) { - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } if (notBeforeStr != NULL) { - PORT_Free(notBeforeStr); + PORT_Free(notBeforeStr); } if (notAfterStr != NULL) { - PORT_Free(notAfterStr); + PORT_Free(notAfterStr); } return (rv); -} +} -static SECStatus -AddBasicConstraint(void *extHandle, - Pair *data) +static SECStatus +AddBasicConstraint(void *extHandle, + Pair *data) { - CERTBasicConstraints basicConstraint; - SECItem encodedValue; - SECStatus rv; + CERTBasicConstraints basicConstraint; + SECItem encodedValue; + SECStatus rv; encodedValue.data = NULL; encodedValue.len = 0; basicConstraint.pathLenConstraint = CERT_UNLIMITED_PATH_CONSTRAINT; - basicConstraint.isCA = (find_field_bool(data,"basicConstraints-cA-radio-CA", - PR_TRUE)); - if (find_field_bool(data,"basicConstraints-pathLengthConstraint", PR_TRUE)){ - basicConstraint.pathLenConstraint = atoi - (find_field(data,"basicConstraints-pathLengthConstraint-text", - PR_TRUE)); - } - - rv = CERT_EncodeBasicConstraintValue (NULL, &basicConstraint, - &encodedValue); - if (rv) - return (rv); - rv = CERT_AddExtension(extHandle, SEC_OID_X509_BASIC_CONSTRAINTS, - &encodedValue, - (find_field_bool(data,"basicConstraints-crit", - PR_TRUE)), PR_TRUE); + basicConstraint.isCA = (find_field_bool(data, "basicConstraints-cA-radio-CA", + PR_TRUE)); + if (find_field_bool(data, "basicConstraints-pathLengthConstraint", PR_TRUE)) { + basicConstraint.pathLenConstraint = atoi(find_field(data, "basicConstraints-pathLengthConstraint-text", + PR_TRUE)); + } - PORT_Free (encodedValue.data); + rv = CERT_EncodeBasicConstraintValue(NULL, &basicConstraint, + &encodedValue); + if (rv) + return (rv); + rv = CERT_AddExtension(extHandle, SEC_OID_X509_BASIC_CONSTRAINTS, + &encodedValue, + (find_field_bool(data, "basicConstraints-crit", + PR_TRUE)), + PR_TRUE); + + PORT_Free(encodedValue.data); return (rv); } - - -static SECStatus -AddNscpCertType (void *extHandle, - Pair *data) +static SECStatus +AddNscpCertType(void *extHandle, + Pair *data) { - SECItem bitStringValue; - unsigned char CertType = 0x0; + SECItem bitStringValue; + unsigned char CertType = 0x0; - if (find_field_bool(data,"netscape-cert-type-ssl-client", PR_TRUE)){ - CertType |= (0x80 >> 0); + if (find_field_bool(data, "netscape-cert-type-ssl-client", PR_TRUE)) { + CertType |= (0x80 >> 0); } - if (find_field_bool(data,"netscape-cert-type-ssl-server", PR_TRUE)){ - CertType |= (0x80 >> 1); + if (find_field_bool(data, "netscape-cert-type-ssl-server", PR_TRUE)) { + CertType |= (0x80 >> 1); } - if (find_field_bool(data,"netscape-cert-type-smime", PR_TRUE)){ - CertType |= (0x80 >> 2); + if (find_field_bool(data, "netscape-cert-type-smime", PR_TRUE)) { + CertType |= (0x80 >> 2); } - if (find_field_bool(data,"netscape-cert-type-object-signing", PR_TRUE)){ - CertType |= (0x80 >> 3); + if (find_field_bool(data, "netscape-cert-type-object-signing", PR_TRUE)) { + CertType |= (0x80 >> 3); } - if (find_field_bool(data,"netscape-cert-type-reserved", PR_TRUE)){ - CertType |= (0x80 >> 4); + if (find_field_bool(data, "netscape-cert-type-reserved", PR_TRUE)) { + CertType |= (0x80 >> 4); } - if (find_field_bool(data,"netscape-cert-type-ssl-ca", PR_TRUE)) { - CertType |= (0x80 >> 5); + if (find_field_bool(data, "netscape-cert-type-ssl-ca", PR_TRUE)) { + CertType |= (0x80 >> 5); } - if (find_field_bool(data,"netscape-cert-type-smime-ca", PR_TRUE)) { - CertType |= (0x80 >> 6); + if (find_field_bool(data, "netscape-cert-type-smime-ca", PR_TRUE)) { + CertType |= (0x80 >> 6); } - if (find_field_bool(data,"netscape-cert-type-object-signing-ca", PR_TRUE)) { - CertType |= (0x80 >> 7); + if (find_field_bool(data, "netscape-cert-type-object-signing-ca", PR_TRUE)) { + CertType |= (0x80 >> 7); } bitStringValue.data = &CertType; bitStringValue.len = 1; - return (CERT_EncodeAndAddBitStrExtension - (extHandle, SEC_OID_NS_CERT_EXT_CERT_TYPE, &bitStringValue, - (find_field_bool(data, "netscape-cert-type-crit", PR_TRUE)))); + return (CERT_EncodeAndAddBitStrExtension(extHandle, SEC_OID_NS_CERT_EXT_CERT_TYPE, &bitStringValue, + (find_field_bool(data, "netscape-cert-type-crit", PR_TRUE)))); } - static SECStatus -add_IA5StringExtension(void *extHandle, - char *string, - PRBool crit, - int idtag) +add_IA5StringExtension(void *extHandle, + char *string, + PRBool crit, + int idtag) { - SECItem encodedValue; - SECStatus rv; + SECItem encodedValue; + SECStatus rv; encodedValue.data = NULL; encodedValue.len = 0; rv = CERT_EncodeIA5TypeExtension(NULL, string, &encodedValue); if (rv) { - return (rv); + return (rv); } return (CERT_AddExtension(extHandle, idtag, &encodedValue, crit, PR_TRUE)); } static SECItem * -string_to_oid(char *string) +string_to_oid(char *string) { - int i; - int length = 20; - int remaining; - int first_value; - int second_value; - int value; - int oidLength; - unsigned char *oidString; - unsigned char *write; - unsigned char *read; - unsigned char *temp; - SECItem *oid; - - + int i; + int length = 20; + int remaining; + int first_value; + int second_value; + int value; + int oidLength; + unsigned char *oidString; + unsigned char *write; + unsigned char *read; + unsigned char *temp; + SECItem *oid; + remaining = length; i = 0; while (*string == ' ') { - string++; + string++; } while (isdigit(*(string + i))) { - i++; + i++; } if (*(string + i) == '.') { - *(string + i) = '\0'; + *(string + i) = '\0'; } else { - error_out("ERROR: Improperly formated OID"); + error_out("ERROR: Improperly formated OID"); } first_value = atoi(string); if (first_value < 0 || first_value > 2) { - error_out("ERROR: Improperly formated OID"); + error_out("ERROR: Improperly formated OID"); } string += i + 1; i = 0; while (isdigit(*(string + i))) { - i++; + i++; } if (*(string + i) == '.') { - *(string + i) = '\0'; + *(string + i) = '\0'; } else { - error_out("ERROR: Improperly formated OID"); + error_out("ERROR: Improperly formated OID"); } second_value = atoi(string); if (second_value < 0 || second_value > 39) { - error_out("ERROR: Improperly formated OID"); + error_out("ERROR: Improperly formated OID"); } oidString = PORT_ZAlloc(2); *oidString = (first_value * 40) + second_value; @@ -1224,59 +1190,59 @@ string_to_oid(char *string) i = 0; temp = write = PORT_ZAlloc(length); while (*string != '\0') { - value = 0; - while(isdigit(*(string + i))) { - i++; - } - if (*(string + i) == '\0') { - value = atoi(string); - string += i; - } else { - if (*(string + i) == '.') { - *(string + i) = '\0'; - value = atoi(string); - string += i + 1; - } else { - *(string + i) = '\0'; - i++; - value = atoi(string); - while (*(string + i) == ' ') - i++; - if (*(string + i) != '\0') { - error_out("ERROR: Improperly formated OID"); - } - } - } - i = 0; - while (value != 0) { - if (remaining < 1) { - remaining += length; - length = length * 2; - temp = PORT_Realloc(temp, length); - write = temp + length - remaining; - } - *write = (value & 0x7f) | (0x80); - write++; - remaining--; - value = value >> 7; - } - *temp = *temp & (0x7f); - oidLength += write - temp; - oidString = PORT_Realloc(oidString, (oidLength + 1)); - read = write - 1; - write = oidLength + oidString - 1; - for (i = 0; i < (length - remaining); i++) { - *write = *read; - write--; - read++; - } - write = temp; - remaining = length; + value = 0; + while (isdigit(*(string + i))) { + i++; + } + if (*(string + i) == '\0') { + value = atoi(string); + string += i; + } else { + if (*(string + i) == '.') { + *(string + i) = '\0'; + value = atoi(string); + string += i + 1; + } else { + *(string + i) = '\0'; + i++; + value = atoi(string); + while (*(string + i) == ' ') + i++; + if (*(string + i) != '\0') { + error_out("ERROR: Improperly formated OID"); + } + } + } + i = 0; + while (value != 0) { + if (remaining < 1) { + remaining += length; + length = length * 2; + temp = PORT_Realloc(temp, length); + write = temp + length - remaining; + } + *write = (value & 0x7f) | (0x80); + write++; + remaining--; + value = value >> 7; + } + *temp = *temp & (0x7f); + oidLength += write - temp; + oidString = PORT_Realloc(oidString, (oidLength + 1)); + read = write - 1; + write = oidLength + oidString - 1; + for (i = 0; i < (length - remaining); i++) { + *write = *read; + write--; + read++; + } + write = temp; + remaining = length; } *(oidString + oidLength) = '\0'; - oid = (SECItem *) PORT_ZAlloc(sizeof(SECItem)); + oid = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); oid->data = oidString; - oid->len = oidLength; + oid->len = oidLength; PORT_Free(temp); return oid; } @@ -1284,62 +1250,62 @@ string_to_oid(char *string) static SECItem * string_to_ipaddress(char *string) { - int i = 0; - int value; - int j = 0; - SECItem *ipaddress; - + int i = 0; + int value; + int j = 0; + SECItem *ipaddress; while (*string == ' ') { - string++; + string++; } - ipaddress = (SECItem *) PORT_ZAlloc(sizeof(SECItem)); + ipaddress = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); ipaddress->data = PORT_ZAlloc(9); while (*string != '\0' && j < 8) { - while (isdigit(*(string + i))) { - i++; - } - if (*(string + i) == '.') { - *(string + i) = '\0'; - value = atoi(string); - string = string + i + 1; - i = 0; - } else { - if (*(string + i) == '\0') { - value = atoi(string); - string = string + i; - i = 0; - } else { - *(string + i) = '\0'; - while (*(string + i) == ' ') { - i++; - } - if (*(string + i) == '\0') { - value = atoi(string); - string = string + i; - i = 0; - } else { - error_out("ERROR: Improperly formated IP Address"); - } - } - } - if (value >= 0 && value < 256) { - *(ipaddress->data + j) = value; - } else { - error_out("ERROR: Improperly formated IP Address"); - } - j++; + while (isdigit(*(string + i))) { + i++; + } + if (*(string + i) == '.') { + *(string + i) = '\0'; + value = atoi(string); + string = string + i + 1; + i = 0; + } else { + if (*(string + i) == '\0') { + value = atoi(string); + string = string + i; + i = 0; + } else { + *(string + i) = '\0'; + while (*(string + i) == ' ') { + i++; + } + if (*(string + i) == '\0') { + value = atoi(string); + string = string + i; + i = 0; + } else { + error_out("ERROR: Improperly formated IP Address"); + } + } + } + if (value >= 0 && value < 256) { + *(ipaddress->data + j) = value; + } else { + error_out("ERROR: Improperly formated IP Address"); + } + j++; } *(ipaddress->data + j) = '\0'; if (j != 4 && j != 8) { - error_out("ERROR: Improperly formated IP Address"); + error_out("ERROR: Improperly formated IP Address"); } ipaddress->len = j; return ipaddress; } static int -chr_to_hex(char c) { +chr_to_hex(char c) +{ if (isdigit(c)) { return c - '0'; } @@ -1352,16 +1318,16 @@ chr_to_hex(char c) { static SECItem * string_to_binary(char *string) { - SECItem *rv; + SECItem *rv; - rv = (SECItem *) PORT_ZAlloc(sizeof(SECItem)); + rv = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); if (rv == NULL) { - error_allocate(); + error_allocate(); } - rv->data = (unsigned char *) PORT_ZAlloc((PORT_Strlen(string))/3 + 2); + rv->data = (unsigned char *)PORT_ZAlloc((PORT_Strlen(string)) / 3 + 2); rv->len = 0; while (*string && !isxdigit(*string)) { - string++; + string++; } while (*string) { int high, low; @@ -1370,14 +1336,14 @@ string_to_binary(char *string) if (high < 0 || low < 0) { error_out("ERROR: Improperly formated binary encoding"); } - rv->data[(rv->len)++] = high << 4 | low; + rv->data[(rv->len)++] = high << 4 | low; if (*string != ':') { break; } ++string; } while (*string == ' ') { - ++string; + ++string; } if (*string) { error_out("ERROR: Junk after binary encoding"); @@ -1387,595 +1353,575 @@ string_to_binary(char *string) } static SECStatus -MakeGeneralName(char *name, - CERTGeneralName *genName, - PLArenaPool *arena) +MakeGeneralName(char *name, + CERTGeneralName *genName, + PLArenaPool *arena) { - SECItem *oid; - SECOidData *oidData; - SECItem *ipaddress; - SECItem *temp = NULL; - int i; - int nameType; - PRBool binary = PR_FALSE; - SECStatus rv = SECSuccess; - PRBool nickname = PR_FALSE; + SECItem *oid; + SECOidData *oidData; + SECItem *ipaddress; + SECItem *temp = NULL; + int i; + int nameType; + PRBool binary = PR_FALSE; + SECStatus rv = SECSuccess; + PRBool nickname = PR_FALSE; PORT_Assert(genName); PORT_Assert(arena); nameType = *(name + PORT_Strlen(name) - 1) - '0'; - if (nameType == 0 && *(name +PORT_Strlen(name) - 2) == '1') { - nickname = PR_TRUE; - nameType = certOtherName; + if (nameType == 0 && *(name + PORT_Strlen(name) - 2) == '1') { + nickname = PR_TRUE; + nameType = certOtherName; } if (nameType < 1 || nameType > 9) { - error_out("ERROR: Unknown General Name Type"); + error_out("ERROR: Unknown General Name Type"); } *(name + PORT_Strlen(name) - 4) = '\0'; genName->type = nameType; - + switch (genName->type) { - case certURI: - case certRFC822Name: - case certDNSName: { - genName->name.other.data = (unsigned char *)name; - genName->name.other.len = PORT_Strlen(name); - break; - } - - case certIPAddress: { - ipaddress = string_to_ipaddress(name); - genName->name.other.data = ipaddress->data; - genName->name.other.len = ipaddress->len; - break; - } - - case certRegisterID: { - oid = string_to_oid(name); - genName->name.other.data = oid->data; - genName->name.other.len = oid->len; - break; - } - - case certEDIPartyName: - case certX400Address: { - - genName->name.other.data = PORT_ArenaAlloc (arena, - PORT_Strlen (name) + 2); - if (genName->name.other.data == NULL) { - error_allocate(); - } - - PORT_Memcpy (genName->name.other.data + 2, name, PORT_Strlen (name)); - /* This may not be accurate for all cases. - For now, use this tag type */ - genName->name.other.data[0] = (char)(((genName->type - 1) & - 0x1f)| 0x80); - genName->name.other.data[1] = (char)PORT_Strlen (name); - genName->name.other.len = PORT_Strlen (name) + 2; - break; - } - - case certOtherName: { - i = 0; - if (!nickname) { - while (!isdigit(*(name + PORT_Strlen(name) - i))) { - i++; - } - if (*(name + PORT_Strlen(name) - i) == '1') { - binary = PR_TRUE; - } else { - binary = PR_FALSE; - } - while (*(name + PORT_Strlen(name) - i) != '-') { - i++; - } - *(name + PORT_Strlen(name) - i - 1) = '\0'; - i = 0; - while (*(name + i) != '-') { - i++; - } - *(name + i - 1) = '\0'; - oid = string_to_oid(name + i + 2); - } else { - oidData = SECOID_FindOIDByTag(SEC_OID_NETSCAPE_NICKNAME); - oid = &oidData->oid; - while (*(name + PORT_Strlen(name) - i) != '-') { - i++; - } - *(name + PORT_Strlen(name) - i) = '\0'; - } - genName->name.OthName.oid.data = oid->data; - genName->name.OthName.oid.len = oid->len; - if (binary) { - temp = string_to_binary(name); - genName->name.OthName.name.data = temp->data; - genName->name.OthName.name.len = temp->len; - } else { - temp = (SECItem *) PORT_ZAlloc(sizeof(SECItem)); - if (temp == NULL) { - error_allocate(); - } - temp->data = (unsigned char *)name; - temp->len = PORT_Strlen(name); - SEC_ASN1EncodeItem (arena, &(genName->name.OthName.name), temp, - CERTIA5TypeTemplate); - } - PORT_Free(temp); - break; - } - - case certDirectoryName: { - CERTName *directoryName = NULL; - - directoryName = CERT_AsciiToName (name); - if (!directoryName) { - error_out("ERROR: Improperly formated alternative name"); - break; - } - rv = CERT_CopyName (arena, &genName->name.directoryName, - directoryName); - CERT_DestroyName (directoryName); - - break; - } + case certURI: + case certRFC822Name: + case certDNSName: { + genName->name.other.data = (unsigned char *)name; + genName->name.other.len = PORT_Strlen(name); + break; + } + + case certIPAddress: { + ipaddress = string_to_ipaddress(name); + genName->name.other.data = ipaddress->data; + genName->name.other.len = ipaddress->len; + break; + } + + case certRegisterID: { + oid = string_to_oid(name); + genName->name.other.data = oid->data; + genName->name.other.len = oid->len; + break; + } + + case certEDIPartyName: + case certX400Address: { + + genName->name.other.data = PORT_ArenaAlloc(arena, + PORT_Strlen(name) + 2); + if (genName->name.other.data == NULL) { + error_allocate(); + } + + PORT_Memcpy(genName->name.other.data + 2, name, PORT_Strlen(name)); + /* This may not be accurate for all cases. + For now, use this tag type */ + genName->name.other.data[0] = (char)(((genName->type - 1) & + 0x1f) | + 0x80); + genName->name.other.data[1] = (char)PORT_Strlen(name); + genName->name.other.len = PORT_Strlen(name) + 2; + break; + } + + case certOtherName: { + i = 0; + if (!nickname) { + while (!isdigit(*(name + PORT_Strlen(name) - i))) { + i++; + } + if (*(name + PORT_Strlen(name) - i) == '1') { + binary = PR_TRUE; + } else { + binary = PR_FALSE; + } + while (*(name + PORT_Strlen(name) - i) != '-') { + i++; + } + *(name + PORT_Strlen(name) - i - 1) = '\0'; + i = 0; + while (*(name + i) != '-') { + i++; + } + *(name + i - 1) = '\0'; + oid = string_to_oid(name + i + 2); + } else { + oidData = SECOID_FindOIDByTag(SEC_OID_NETSCAPE_NICKNAME); + oid = &oidData->oid; + while (*(name + PORT_Strlen(name) - i) != '-') { + i++; + } + *(name + PORT_Strlen(name) - i) = '\0'; + } + genName->name.OthName.oid.data = oid->data; + genName->name.OthName.oid.len = oid->len; + if (binary) { + temp = string_to_binary(name); + genName->name.OthName.name.data = temp->data; + genName->name.OthName.name.len = temp->len; + } else { + temp = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); + if (temp == NULL) { + error_allocate(); + } + temp->data = (unsigned char *)name; + temp->len = PORT_Strlen(name); + SEC_ASN1EncodeItem(arena, &(genName->name.OthName.name), temp, + CERTIA5TypeTemplate); + } + PORT_Free(temp); + break; + } + + case certDirectoryName: { + CERTName *directoryName = NULL; + + directoryName = CERT_AsciiToName(name); + if (!directoryName) { + error_out("ERROR: Improperly formated alternative name"); + break; + } + rv = CERT_CopyName(arena, &genName->name.directoryName, + directoryName); + CERT_DestroyName(directoryName); + + break; + } } genName->l.next = &(genName->l); genName->l.prev = &(genName->l); return rv; } - static CERTGeneralName * -MakeAltName(Pair *data, - char *which, - PLArenaPool *arena) +MakeAltName(Pair *data, + char *which, + PLArenaPool *arena) { - CERTGeneralName *SubAltName; - CERTGeneralName *current; - CERTGeneralName *newname; - char *name = NULL; - SECStatus rv = SECSuccess; - int len; - + CERTGeneralName *SubAltName; + CERTGeneralName *current; + CERTGeneralName *newname; + char *name = NULL; + SECStatus rv = SECSuccess; + int len; len = PORT_Strlen(which); name = find_field(data, which, PR_TRUE); - SubAltName = current = (CERTGeneralName *) PORT_ZAlloc - (sizeof(CERTGeneralName)); + SubAltName = current = (CERTGeneralName *)PORT_ZAlloc(sizeof(CERTGeneralName)); if (current == NULL) { - error_allocate(); + error_allocate(); } while (name != NULL) { - rv = MakeGeneralName(name, current, arena); - - if (rv != SECSuccess) { - break; - } - if (*(which + len -1) < '9') { - *(which + len - 1) = *(which + len - 1) + 1; - } else { - if (isdigit(*(which + len - 2) )) { - *(which + len - 2) = *(which + len - 2) + 1; - *(which + len - 1) = '0'; - } else { - *(which + len - 1) = '1'; - *(which + len) = '0'; - *(which + len + 1) = '\0'; - len++; - } - } - len = PORT_Strlen(which); - name = find_field(data, which, PR_TRUE); - if (name != NULL) { - newname = (CERTGeneralName *) PORT_ZAlloc(sizeof(CERTGeneralName)); - if (newname == NULL) { - error_allocate(); - } - current->l.next = &(newname->l); - newname->l.prev = &(current->l); - current = newname; + rv = MakeGeneralName(name, current, arena); + + if (rv != SECSuccess) { + break; + } + if (*(which + len - 1) < '9') { + *(which + len - 1) = *(which + len - 1) + 1; + } else { + if (isdigit(*(which + len - 2))) { + *(which + len - 2) = *(which + len - 2) + 1; + *(which + len - 1) = '0'; + } else { + *(which + len - 1) = '1'; + *(which + len) = '0'; + *(which + len + 1) = '\0'; + len++; + } + } + len = PORT_Strlen(which); + name = find_field(data, which, PR_TRUE); + if (name != NULL) { + newname = (CERTGeneralName *)PORT_ZAlloc(sizeof(CERTGeneralName)); + if (newname == NULL) { + error_allocate(); + } + current->l.next = &(newname->l); + newname->l.prev = &(current->l); + current = newname; newname = NULL; - } else { - current->l.next = &(SubAltName->l); - SubAltName->l.prev = &(current->l); - } + } else { + current->l.next = &(SubAltName->l); + SubAltName->l.prev = &(current->l); + } } if (rv == SECFailure) { - return NULL; + return NULL; } return SubAltName; } static CERTNameConstraints * -MakeNameConstraints(Pair *data, - PLArenaPool *arena) +MakeNameConstraints(Pair *data, + PLArenaPool *arena) { - CERTNameConstraints *NameConstraints; - CERTNameConstraint *current = NULL; - CERTNameConstraint *last_permited = NULL; - CERTNameConstraint *last_excluded = NULL; - char *constraint = NULL; - char *which; - SECStatus rv = SECSuccess; - int len; - int i; - long max; - long min; - PRBool permited; - - - NameConstraints = (CERTNameConstraints *) PORT_ZAlloc - (sizeof(CERTNameConstraints)); - which = make_copy_string("NameConstraintSelect0", 25,'\0'); + CERTNameConstraints *NameConstraints; + CERTNameConstraint *current = NULL; + CERTNameConstraint *last_permited = NULL; + CERTNameConstraint *last_excluded = NULL; + char *constraint = NULL; + char *which; + SECStatus rv = SECSuccess; + int len; + int i; + long max; + long min; + PRBool permited; + + NameConstraints = (CERTNameConstraints *)PORT_ZAlloc(sizeof(CERTNameConstraints)); + which = make_copy_string("NameConstraintSelect0", 25, '\0'); len = PORT_Strlen(which); constraint = find_field(data, which, PR_TRUE); NameConstraints->permited = NameConstraints->excluded = NULL; while (constraint != NULL) { - current = (CERTNameConstraint *) PORT_ZAlloc - (sizeof(CERTNameConstraint)); - if (current == NULL) { - error_allocate(); - } - i = 0; - while (*(constraint + PORT_Strlen(constraint) - i) != '-') { - i++; - } - *(constraint + PORT_Strlen(constraint) - i - 1) = '\0'; - max = (long) atoi(constraint + PORT_Strlen(constraint) + 3); - if (max > 0) { - (void) SEC_ASN1EncodeInteger(arena, ¤t->max, max); - } - i = 0; - while (*(constraint + PORT_Strlen(constraint) - i) != '-') { - i++; - } + current = (CERTNameConstraint *)PORT_ZAlloc(sizeof(CERTNameConstraint)); + if (current == NULL) { + error_allocate(); + } + i = 0; + while (*(constraint + PORT_Strlen(constraint) - i) != '-') { + i++; + } *(constraint + PORT_Strlen(constraint) - i - 1) = '\0'; - min = (long) atoi(constraint + PORT_Strlen(constraint) + 3); - (void) SEC_ASN1EncodeInteger(arena, ¤t->min, min); - while (*(constraint + PORT_Strlen(constraint) - i) != '-') { - i++; - } + max = (long)atoi(constraint + PORT_Strlen(constraint) + 3); + if (max > 0) { + (void)SEC_ASN1EncodeInteger(arena, ¤t->max, max); + } + i = 0; + while (*(constraint + PORT_Strlen(constraint) - i) != '-') { + i++; + } + *(constraint + PORT_Strlen(constraint) - i - 1) = '\0'; + min = (long)atoi(constraint + PORT_Strlen(constraint) + 3); + (void)SEC_ASN1EncodeInteger(arena, ¤t->min, min); + while (*(constraint + PORT_Strlen(constraint) - i) != '-') { + i++; + } *(constraint + PORT_Strlen(constraint) - i - 1) = '\0'; - if (*(constraint + PORT_Strlen(constraint) + 3) == 'p') { - permited = PR_TRUE; - } else { - permited = PR_FALSE; - } - rv = MakeGeneralName(constraint, &(current->name), arena); - - if (rv != SECSuccess) { - break; - } - if (*(which + len - 1) < '9') { - *(which + len - 1) = *(which + len - 1) + 1; - } else { - if (isdigit(*(which + len - 2) )) { - *(which + len - 2) = *(which + len - 2) + 1; - *(which + len - 1) = '0'; - } else { - *(which + len - 1) = '1'; - *(which + len) = '0'; - *(which + len + 1) = '\0'; - len++; - } - } - len = PORT_Strlen(which); - if (permited) { - if (NameConstraints->permited == NULL) { - NameConstraints->permited = last_permited = current; - } - last_permited->l.next = &(current->l); - current->l.prev = &(last_permited->l); - last_permited = current; - } else { - if (NameConstraints->excluded == NULL) { - NameConstraints->excluded = last_excluded = current; - } - last_excluded->l.next = &(current->l); - current->l.prev = &(last_excluded->l); - last_excluded = current; - } - constraint = find_field(data, which, PR_TRUE); - if (constraint != NULL) { - current = (CERTNameConstraint *) PORT_ZAlloc(sizeof(CERTNameConstraint)); - if (current == NULL) { - error_allocate(); - } - } + if (*(constraint + PORT_Strlen(constraint) + 3) == 'p') { + permited = PR_TRUE; + } else { + permited = PR_FALSE; + } + rv = MakeGeneralName(constraint, &(current->name), arena); + + if (rv != SECSuccess) { + break; + } + if (*(which + len - 1) < '9') { + *(which + len - 1) = *(which + len - 1) + 1; + } else { + if (isdigit(*(which + len - 2))) { + *(which + len - 2) = *(which + len - 2) + 1; + *(which + len - 1) = '0'; + } else { + *(which + len - 1) = '1'; + *(which + len) = '0'; + *(which + len + 1) = '\0'; + len++; + } + } + len = PORT_Strlen(which); + if (permited) { + if (NameConstraints->permited == NULL) { + NameConstraints->permited = last_permited = current; + } + last_permited->l.next = &(current->l); + current->l.prev = &(last_permited->l); + last_permited = current; + } else { + if (NameConstraints->excluded == NULL) { + NameConstraints->excluded = last_excluded = current; + } + last_excluded->l.next = &(current->l); + current->l.prev = &(last_excluded->l); + last_excluded = current; + } + constraint = find_field(data, which, PR_TRUE); + if (constraint != NULL) { + current = (CERTNameConstraint *)PORT_ZAlloc(sizeof(CERTNameConstraint)); + if (current == NULL) { + error_allocate(); + } + } } if (NameConstraints->permited != NULL) { - last_permited->l.next = &(NameConstraints->permited->l); - NameConstraints->permited->l.prev = &(last_permited->l); + last_permited->l.next = &(NameConstraints->permited->l); + NameConstraints->permited->l.prev = &(last_permited->l); } if (NameConstraints->excluded != NULL) { - last_excluded->l.next = &(NameConstraints->excluded->l); - NameConstraints->excluded->l.prev = &(last_excluded->l); + last_excluded->l.next = &(NameConstraints->excluded->l); + NameConstraints->excluded->l.prev = &(last_excluded->l); } if (which != NULL) { - PORT_Free(which); + PORT_Free(which); } if (rv == SECFailure) { - return NULL; + return NULL; } return NameConstraints; } - - static SECStatus -AddAltName(void *extHandle, - Pair *data, - char *issuerNameStr, - CERTCertDBHandle *handle, - int type) +AddAltName(void *extHandle, + Pair *data, + char *issuerNameStr, + CERTCertDBHandle *handle, + int type) { - PRBool autoIssuer = PR_FALSE; - PLArenaPool *arena = NULL; - CERTGeneralName *genName = NULL; - char *which = NULL; - char *name = NULL; - SECStatus rv = SECSuccess; - SECItem *issuersAltName = NULL; - CERTCertificate *issuerCert = NULL; + PRBool autoIssuer = PR_FALSE; + PLArenaPool *arena = NULL; + CERTGeneralName *genName = NULL; + char *which = NULL; + char *name = NULL; + SECStatus rv = SECSuccess; + SECItem *issuersAltName = NULL; + CERTCertificate *issuerCert = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - error_allocate(); + error_allocate(); } if (type == 0) { - which = make_copy_string("SubAltNameSelect0", 20,'\0'); - genName = MakeAltName(data, which, arena); + which = make_copy_string("SubAltNameSelect0", 20, '\0'); + genName = MakeAltName(data, which, arena); } else { - if (autoIssuer) { - autoIssuer = find_field_bool(data,"IssuerAltNameSourceRadio-auto", - PR_TRUE); - issuerCert = CERT_FindCertByNameString(handle, issuerNameStr); - rv = cert_FindExtension((*issuerCert).extensions, - SEC_OID_X509_SUBJECT_ALT_NAME, - issuersAltName); - if (issuersAltName == NULL) { - name = PORT_Alloc(PORT_Strlen((*issuerCert).subjectName) + 4); - PORT_Strcpy(name, (*issuerCert).subjectName); - PORT_Strcat(name, " - 5"); - } - } else { - which = make_copy_string("IssuerAltNameSelect0", 20,'\0'); - genName = MakeAltName(data, which, arena); - } + if (autoIssuer) { + autoIssuer = find_field_bool(data, "IssuerAltNameSourceRadio-auto", + PR_TRUE); + issuerCert = CERT_FindCertByNameString(handle, issuerNameStr); + rv = cert_FindExtension((*issuerCert).extensions, + SEC_OID_X509_SUBJECT_ALT_NAME, + issuersAltName); + if (issuersAltName == NULL) { + name = PORT_Alloc(PORT_Strlen((*issuerCert).subjectName) + 4); + PORT_Strcpy(name, (*issuerCert).subjectName); + PORT_Strcat(name, " - 5"); + } + } else { + which = make_copy_string("IssuerAltNameSelect0", 20, '\0'); + genName = MakeAltName(data, which, arena); + } } if (type == 0) { - EncodeAndAddExtensionValue(arena, extHandle, genName, - find_field_bool(data, "SubAltName-crit", - PR_TRUE), - SEC_OID_X509_SUBJECT_ALT_NAME, - (EXTEN_VALUE_ENCODER) - CERT_EncodeAltNameExtension); + EncodeAndAddExtensionValue(arena, extHandle, genName, + find_field_bool(data, "SubAltName-crit", + PR_TRUE), + SEC_OID_X509_SUBJECT_ALT_NAME, + (EXTEN_VALUE_ENCODER) + CERT_EncodeAltNameExtension); } else { - if (autoIssuer && (name == NULL)) { - rv = CERT_AddExtension - (extHandle, SEC_OID_X509_ISSUER_ALT_NAME, issuersAltName, - find_field_bool(data, "IssuerAltName-crit", PR_TRUE), PR_TRUE); - } else { - EncodeAndAddExtensionValue(arena, extHandle, genName, - find_field_bool(data, - "IssuerAltName-crit", - PR_TRUE), - SEC_OID_X509_ISSUER_ALT_NAME, - (EXTEN_VALUE_ENCODER) - CERT_EncodeAltNameExtension); - } + if (autoIssuer && (name == NULL)) { + rv = CERT_AddExtension(extHandle, SEC_OID_X509_ISSUER_ALT_NAME, issuersAltName, + find_field_bool(data, "IssuerAltName-crit", PR_TRUE), PR_TRUE); + } else { + EncodeAndAddExtensionValue(arena, extHandle, genName, + find_field_bool(data, + "IssuerAltName-crit", + PR_TRUE), + SEC_OID_X509_ISSUER_ALT_NAME, + (EXTEN_VALUE_ENCODER) + CERT_EncodeAltNameExtension); + } } if (which != NULL) { - PORT_Free(which); + PORT_Free(which); } if (issuerCert != NULL) { - CERT_DestroyCertificate(issuerCert); + CERT_DestroyCertificate(issuerCert); } return rv; } - static SECStatus -AddNameConstraints(void *extHandle, - Pair *data) +AddNameConstraints(void *extHandle, + Pair *data) { - PLArenaPool *arena = NULL; + PLArenaPool *arena = NULL; CERTNameConstraints *constraints = NULL; - SECStatus rv = SECSuccess; - + SECStatus rv = SECSuccess; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - error_allocate(); + error_allocate(); } constraints = MakeNameConstraints(data, arena); if (constraints != NULL) { - EncodeAndAddExtensionValue(arena, extHandle, constraints, PR_TRUE, - SEC_OID_X509_NAME_CONSTRAINTS, - (EXTEN_VALUE_ENCODER) - CERT_EncodeNameConstraintsExtension); + EncodeAndAddExtensionValue(arena, extHandle, constraints, PR_TRUE, + SEC_OID_X509_NAME_CONSTRAINTS, + (EXTEN_VALUE_ENCODER) + CERT_EncodeNameConstraintsExtension); } if (arena != NULL) { - PORT_ArenaRelease (arena, NULL); + PORT_ArenaRelease(arena, NULL); } return rv; } - static SECStatus -add_extensions(CERTCertificate *subjectCert, - Pair *data, - char *issuerNameStr, - CERTCertDBHandle *handle) +add_extensions(CERTCertificate *subjectCert, + Pair *data, + char *issuerNameStr, + CERTCertDBHandle *handle) { - void *extHandle; - SECStatus rv = SECSuccess; - + void *extHandle; + SECStatus rv = SECSuccess; - extHandle = CERT_StartCertExtensions (subjectCert); + extHandle = CERT_StartCertExtensions(subjectCert); if (extHandle == NULL) { - error_out("ERROR: Unable to get certificates extension handle"); + error_out("ERROR: Unable to get certificates extension handle"); } if (find_field_bool(data, "keyUsage", PR_TRUE)) { - rv = AddKeyUsage(extHandle, data); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Key Usage extension"); - } + rv = AddKeyUsage(extHandle, data); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Key Usage extension"); + } } - if( find_field_bool(data, "extKeyUsage", PR_TRUE) ) { - rv = AddExtKeyUsage(extHandle, data); - if( SECSuccess != rv ) { - error_out("ERROR: Unable to add Extended Key Usage extension"); - } + if (find_field_bool(data, "extKeyUsage", PR_TRUE)) { + rv = AddExtKeyUsage(extHandle, data); + if (SECSuccess != rv) { + error_out("ERROR: Unable to add Extended Key Usage extension"); + } } if (find_field_bool(data, "basicConstraints", PR_TRUE)) { - rv = AddBasicConstraint(extHandle, data); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Basic Constraint extension"); - } + rv = AddBasicConstraint(extHandle, data); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Basic Constraint extension"); + } } if (find_field_bool(data, "subjectKeyIdentifier", PR_TRUE)) { - rv = AddSubKeyID(extHandle, data, subjectCert); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Subject Key Identifier Extension"); - } + rv = AddSubKeyID(extHandle, data, subjectCert); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Subject Key Identifier Extension"); + } } if (find_field_bool(data, "authorityKeyIdentifier", PR_TRUE)) { - rv = AddAuthKeyID (extHandle, data, issuerNameStr, handle); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Authority Key Identifier extension"); - } + rv = AddAuthKeyID(extHandle, data, issuerNameStr, handle); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Authority Key Identifier extension"); + } } if (find_field_bool(data, "privKeyUsagePeriod", PR_TRUE)) { - rv = AddPrivKeyUsagePeriod (extHandle, data, subjectCert); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Private Key Usage Period extension"); - } + rv = AddPrivKeyUsagePeriod(extHandle, data, subjectCert); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Private Key Usage Period extension"); + } } if (find_field_bool(data, "SubAltName", PR_TRUE)) { - rv = AddAltName (extHandle, data, NULL, NULL, 0); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Subject Alternative Name extension"); - } + rv = AddAltName(extHandle, data, NULL, NULL, 0); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Subject Alternative Name extension"); + } } if (find_field_bool(data, "IssuerAltName", PR_TRUE)) { - rv = AddAltName (extHandle, data, issuerNameStr, handle, 1); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Issuer Alternative Name Extension"); - } + rv = AddAltName(extHandle, data, issuerNameStr, handle, 1); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Issuer Alternative Name Extension"); + } } if (find_field_bool(data, "NameConstraints", PR_TRUE)) { - rv = AddNameConstraints(extHandle, data); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Name Constraints Extension"); - } + rv = AddNameConstraints(extHandle, data); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Name Constraints Extension"); + } } if (find_field_bool(data, "netscape-cert-type", PR_TRUE)) { - rv = AddNscpCertType(extHandle, data); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape Certificate Type Extension"); - } + rv = AddNscpCertType(extHandle, data); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape Certificate Type Extension"); + } } if (find_field_bool(data, "netscape-base-url", PR_TRUE)) { - rv = add_IA5StringExtension(extHandle, - find_field(data, "netscape-base-url-text", - PR_TRUE), - find_field_bool(data, - "netscape-base-url-crit", - PR_TRUE), - SEC_OID_NS_CERT_EXT_BASE_URL); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape Base URL Extension"); - } + rv = add_IA5StringExtension(extHandle, + find_field(data, "netscape-base-url-text", + PR_TRUE), + find_field_bool(data, + "netscape-base-url-crit", + PR_TRUE), + SEC_OID_NS_CERT_EXT_BASE_URL); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape Base URL Extension"); + } } if (find_field_bool(data, "netscape-revocation-url", PR_TRUE)) { - rv = add_IA5StringExtension(extHandle, - find_field(data, - "netscape-revocation-url-text", - PR_TRUE), - find_field_bool - (data, "netscape-revocation-url-crit", - PR_TRUE), - SEC_OID_NS_CERT_EXT_REVOCATION_URL); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape Revocation URL Extension"); - } + rv = add_IA5StringExtension(extHandle, + find_field(data, + "netscape-revocation-url-text", + PR_TRUE), + find_field_bool(data, "netscape-revocation-url-crit", + PR_TRUE), + SEC_OID_NS_CERT_EXT_REVOCATION_URL); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape Revocation URL Extension"); + } } if (find_field_bool(data, "netscape-ca-revocation-url", PR_TRUE)) { - rv = add_IA5StringExtension(extHandle, - find_field(data, - "netscape-ca-revocation-url-text", - PR_TRUE), - find_field_bool - (data, "netscape-ca-revocation-url-crit" - , PR_TRUE), - SEC_OID_NS_CERT_EXT_CA_REVOCATION_URL); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape CA Revocation URL Extension"); - } + rv = add_IA5StringExtension(extHandle, + find_field(data, + "netscape-ca-revocation-url-text", + PR_TRUE), + find_field_bool(data, "netscape-ca-revocation-url-crit", PR_TRUE), + SEC_OID_NS_CERT_EXT_CA_REVOCATION_URL); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape CA Revocation URL Extension"); + } } if (find_field_bool(data, "netscape-cert-renewal-url", PR_TRUE)) { - rv = add_IA5StringExtension(extHandle, - find_field(data, - "netscape-cert-renewal-url-text", - PR_TRUE), - find_field_bool - (data, "netscape-cert-renewal-url-crit", - PR_TRUE), - SEC_OID_NS_CERT_EXT_CERT_RENEWAL_URL); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape Certificate Renewal URL Extension"); - } + rv = add_IA5StringExtension(extHandle, + find_field(data, + "netscape-cert-renewal-url-text", + PR_TRUE), + find_field_bool(data, "netscape-cert-renewal-url-crit", + PR_TRUE), + SEC_OID_NS_CERT_EXT_CERT_RENEWAL_URL); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape Certificate Renewal URL Extension"); + } } if (find_field_bool(data, "netscape-ca-policy-url", PR_TRUE)) { - rv = add_IA5StringExtension(extHandle, - find_field(data, - "netscape-ca-policy-url-text", - PR_TRUE), - find_field_bool - (data, "netscape-ca-policy-url-crit", - PR_TRUE), - SEC_OID_NS_CERT_EXT_CA_POLICY_URL); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape CA Policy URL Extension"); - } + rv = add_IA5StringExtension(extHandle, + find_field(data, + "netscape-ca-policy-url-text", + PR_TRUE), + find_field_bool(data, "netscape-ca-policy-url-crit", + PR_TRUE), + SEC_OID_NS_CERT_EXT_CA_POLICY_URL); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape CA Policy URL Extension"); + } } if (find_field_bool(data, "netscape-ssl-server-name", PR_TRUE)) { - rv = add_IA5StringExtension(extHandle, - find_field(data, - "netscape-ssl-server-name-text", - PR_TRUE), - find_field_bool - (data, "netscape-ssl-server-name-crit", - PR_TRUE), - SEC_OID_NS_CERT_EXT_SSL_SERVER_NAME); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape SSL Server Name Extension"); - } + rv = add_IA5StringExtension(extHandle, + find_field(data, + "netscape-ssl-server-name-text", + PR_TRUE), + find_field_bool(data, "netscape-ssl-server-name-crit", + PR_TRUE), + SEC_OID_NS_CERT_EXT_SSL_SERVER_NAME); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape SSL Server Name Extension"); + } } if (find_field_bool(data, "netscape-comment", PR_TRUE)) { - rv = add_IA5StringExtension(extHandle, - find_field(data, "netscape-comment-text", - PR_TRUE), - find_field_bool(data, - "netscape-comment-crit", - PR_TRUE), - SEC_OID_NS_CERT_EXT_COMMENT); - if (rv != SECSuccess) { - error_out("ERROR: Unable to add Netscape Comment Extension"); - } + rv = add_IA5StringExtension(extHandle, + find_field(data, "netscape-comment-text", + PR_TRUE), + find_field_bool(data, + "netscape-comment-crit", + PR_TRUE), + SEC_OID_NS_CERT_EXT_COMMENT); + if (rv != SECSuccess) { + error_out("ERROR: Unable to add Netscape Comment Extension"); + } } CERT_FinishExtensions(extHandle); return (rv); } - - char * return_dbpasswd(PK11SlotInfo *slot, PRBool retry, void *data) { @@ -1983,143 +1929,138 @@ return_dbpasswd(PK11SlotInfo *slot, PRBool retry, void *data) /* don't clobber our poor smart card */ if (retry == PR_TRUE) { - return NULL; + return NULL; } rv = PORT_Alloc(4); PORT_Strcpy(rv, "foo"); return rv; } - SECKEYPrivateKey * -FindPrivateKeyFromNameStr(char *name, - CERTCertDBHandle *certHandle) +FindPrivateKeyFromNameStr(char *name, + CERTCertDBHandle *certHandle) { - SECKEYPrivateKey *key; - CERTCertificate *cert; - CERTCertificate *p11Cert; - + SECKEYPrivateKey *key; + CERTCertificate *cert; + CERTCertificate *p11Cert; - /* We don't presently have a PK11 function to find a cert by - ** subject name. + /* We don't presently have a PK11 function to find a cert by + ** subject name. ** We do have a function to find a cert in the internal slot's ** cert db by subject name, but it doesn't setup the slot info. - ** So, this HACK works, but should be replaced as soon as we + ** So, this HACK works, but should be replaced as soon as we ** have a function to search for certs accross slots by subject name. */ cert = CERT_FindCertByNameString(certHandle, name); if (cert == NULL || cert->nickname == NULL) { - error_out("ERROR: Unable to retrieve issuers certificate"); + error_out("ERROR: Unable to retrieve issuers certificate"); } p11Cert = PK11_FindCertFromNickname(cert->nickname, NULL); if (p11Cert == NULL) { - error_out("ERROR: Unable to retrieve issuers certificate"); + error_out("ERROR: Unable to retrieve issuers certificate"); } key = PK11_FindKeyByAnyCert(p11Cert, NULL); return key; } static SECItem * -SignCert(CERTCertificate *cert, - char *issuerNameStr, - Pair *data, - CERTCertDBHandle *handle, - int which_key) +SignCert(CERTCertificate *cert, + char *issuerNameStr, + Pair *data, + CERTCertDBHandle *handle, + int which_key) { - SECItem der; - SECKEYPrivateKey *caPrivateKey = NULL; - SECStatus rv; - PLArenaPool *arena; - SECOidTag algID; + SECItem der; + SECKEYPrivateKey *caPrivateKey = NULL; + SECStatus rv; + PLArenaPool *arena; + SECOidTag algID; if (which_key == 0) { - caPrivateKey = FindPrivateKeyFromNameStr(issuerNameStr, handle); + caPrivateKey = FindPrivateKeyFromNameStr(issuerNameStr, handle); } else { - caPrivateKey = privkeys[which_key - 1]; + caPrivateKey = privkeys[which_key - 1]; } if (caPrivateKey == NULL) { - error_out("ERROR: unable to retrieve issuers key"); + error_out("ERROR: unable to retrieve issuers key"); } - + arena = cert->arena; algID = SEC_GetSignatureAlgorithmOidTag(caPrivateKey->keyType, - SEC_OID_UNKNOWN); + SEC_OID_UNKNOWN); if (algID == SEC_OID_UNKNOWN) { - error_out("ERROR: Unknown key type for issuer."); - goto done; + error_out("ERROR: Unknown key type for issuer."); + goto done; } rv = SECOID_SetAlgorithmID(arena, &cert->signature, algID, 0); if (rv != SECSuccess) { - error_out("ERROR: Could not set signature algorithm id."); + error_out("ERROR: Could not set signature algorithm id."); } - if (find_field_bool(data,"ver-1", PR_TRUE)) { - *(cert->version.data) = 0; - cert->version.len = 1; + if (find_field_bool(data, "ver-1", PR_TRUE)) { + *(cert->version.data) = 0; + cert->version.len = 1; } else { - *(cert->version.data) = 2; - cert->version.len = 1; + *(cert->version.data) = 2; + cert->version.len = 1; } der.data = NULL; der.len = 0; - (void) SEC_ASN1EncodeItem (arena, &der, cert, CERT_CertificateTemplate); + (void)SEC_ASN1EncodeItem(arena, &der, cert, CERT_CertificateTemplate); if (der.data == NULL) { - error_out("ERROR: Could not encode certificate.\n"); + error_out("ERROR: Could not encode certificate.\n"); } - rv = SEC_DerSignData (arena, &(cert->derCert), der.data, der.len, caPrivateKey, - algID); + rv = SEC_DerSignData(arena, &(cert->derCert), der.data, der.len, caPrivateKey, + algID); if (rv != SECSuccess) { - error_out("ERROR: Could not sign encoded certificate data.\n"); + error_out("ERROR: Could not sign encoded certificate data.\n"); } done: SECKEY_DestroyPrivateKey(caPrivateKey); return &(cert->derCert); } - int main(int argc, char **argv) { - int length = 500; - int remaining = 500; - int n; - int i; - int serial; - int chainLen; - int which_key; - char *pos; + int length = 500; + int remaining = 500; + int n; + int i; + int serial; + int chainLen; + int which_key; + char *pos; #ifdef OFFLINE - char *form_output = "key=MIIBPTCBpzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA7SLqjWBL9Wl11Vlg%0AaMqZCvcQOL%2FnvSqYPPRP0XZy9SoAeyWzQnBOiCm2t8H5mK7r2jnKdAQOmfhjaJil%0A3hNVu3SekHOXF6Ze7bkWa6%2FSGVcY%2FojkydxFSgY43nd1iydzPQDp8WWLL%2BpVpt%2B%2B%0ATRhFtVXbF0fQI03j9h3BoTgP2lkCAwEAARYDZm9vMA0GCSqGSIb3DQEBBAUAA4GB%0AAJ8UfRKJ0GtG%2B%2BufCC6tAfTzKrq3CTBHnom55EyXcsAsv6WbDqI%2F0rLAPkn2Xo1r%0AnNhtMxIuj441blMt%2Fa3AGLOy5zmC7Qawt8IytvQikQ1XTpTBCXevytrmLjCmlURr%0ANJryTM48WaMQHiMiJpbXCqVJC1d%2FpEWBtqvALzZaOOIy&subject=CN%3D%22test%22%26serial-auto%3Dtrue%26serial_value%3D%26ver-1%3Dtrue%26ver-3%3Dfalse%26caChoiceradio-SignWithDefaultkey%3Dtrue%26caChoiceradio-SignWithRandomChain%3Dfalse%26autoCAs%3D%26caChoiceradio-SignWithSpecifiedChain%3Dfalse%26manCAs%3D%26%24"; + char *form_output = "key=MIIBPTCBpzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA7SLqjWBL9Wl11Vlg%0AaMqZCvcQOL%2FnvSqYPPRP0XZy9SoAeyWzQnBOiCm2t8H5mK7r2jnKdAQOmfhjaJil%0A3hNVu3SekHOXF6Ze7bkWa6%2FSGVcY%2FojkydxFSgY43nd1iydzPQDp8WWLL%2BpVpt%2B%2B%0ATRhFtVXbF0fQI03j9h3BoTgP2lkCAwEAARYDZm9vMA0GCSqGSIb3DQEBBAUAA4GB%0AAJ8UfRKJ0GtG%2B%2BufCC6tAfTzKrq3CTBHnom55EyXcsAsv6WbDqI%2F0rLAPkn2Xo1r%0AnNhtMxIuj441blMt%2Fa3AGLOy5zmC7Qawt8IytvQikQ1XTpTBCXevytrmLjCmlURr%0ANJryTM48WaMQHiMiJpbXCqVJC1d%2FpEWBtqvALzZaOOIy&subject=CN%3D%22test%22%26serial-auto%3Dtrue%26serial_value%3D%26ver-1%3Dtrue%26ver-3%3Dfalse%26caChoiceradio-SignWithDefaultkey%3Dtrue%26caChoiceradio-SignWithRandomChain%3Dfalse%26autoCAs%3D%26caChoiceradio-SignWithSpecifiedChain%3Dfalse%26manCAs%3D%26%24"; #else - char *form_output; + char *form_output; #endif - char *issuerNameStr; - char *certName; - char *DBdir = DB_DIRECTORY; - char *prefixs[10] = {"CA#1-", "CA#2-", "CA#3-", - "CA#4-", "CA#5-", "CA#6-", - "CA#7-", "CA#8-", "CA#9-", ""}; - Pair *form_data; - CERTCertificate *cert; - CERTCertDBHandle *handle; + char *issuerNameStr; + char *certName; + char *DBdir = DB_DIRECTORY; + char *prefixs[10] = { "CA#1-", "CA#2-", "CA#3-", + "CA#4-", "CA#5-", "CA#6-", + "CA#7-", "CA#8-", "CA#9-", "" }; + Pair *form_data; + CERTCertificate *cert; + CERTCertDBHandle *handle; CERTCertificateRequest *certReq = NULL; - int warpmonths = 0; - SECItem *certDER; + int warpmonths = 0; + SECItem *certDER; #ifdef FILEOUT - FILE *outfile; + FILE *outfile; #endif - SECStatus status = SECSuccess; - extern char prefix[PREFIX_LEN]; - SEC_PKCS7ContentInfo *certChain; - SECItem *encodedCertChain; - PRBool UChain = PR_FALSE; - + SECStatus status = SECSuccess; + extern char prefix[PREFIX_LEN]; + SEC_PKCS7ContentInfo *certChain; + SECItem *encodedCertChain; + PRBool UChain = PR_FALSE; progName = strrchr(argv[0], '/'); - progName = progName ? progName+1 : argv[0]; - + progName = progName ? progName + 1 : argv[0]; #ifdef TEST sleep(20); @@ -2129,31 +2070,31 @@ main(int argc, char **argv) PK11_SetPasswordFunc(return_dbpasswd); status = NSS_InitReadWrite(DBdir); if (status != SECSuccess) { - SECU_PrintPRandOSError(progName); - return -1; + SECU_PrintPRandOSError(progName); + return -1; } handle = CERT_GetDefaultCertDB(); - prefix[0]= '\0'; + prefix[0] = '\0'; #if !defined(OFFLINE) - form_output = (char*) PORT_Alloc(length); + form_output = (char *)PORT_Alloc(length); if (form_output == NULL) { - error_allocate(); + error_allocate(); } pos = form_output; - while (feof(stdin) == 0 ) { - if (remaining <= 1) { - remaining += length; - length = length * 2; - form_output = PORT_Realloc(form_output, (length)); - if (form_output == NULL) { - error_allocate(); - } - pos = form_output + length - remaining; - } - n = fread(pos, 1, (size_t) (remaining - 1), stdin); - pos += n; - remaining -= n; + while (feof(stdin) == 0) { + if (remaining <= 1) { + remaining += length; + length = length * 2; + form_output = PORT_Realloc(form_output, (length)); + if (form_output == NULL) { + error_allocate(); + } + pos = form_output + length - remaining; + } + n = fread(pos, 1, (size_t)(remaining - 1), stdin); + pos += n; + remaining -= n; } *pos = '&'; pos++; @@ -2178,112 +2119,110 @@ main(int argc, char **argv) #endif #ifdef FILEOUT i = 0; - while(return_name(form_data, i) != NULL) { - printf("%s",return_name(form_data,i)); + while (return_name(form_data, i) != NULL) { + printf("%s", return_name(form_data, i)); printf("=\n"); - printf("%s",return_data(form_data,i)); + printf("%s", return_data(form_data, i)); printf("\n"); - i++; + i++; } printf("I got that done, woo hoo\n"); fflush(stdout); #endif issuerNameStr = PORT_Alloc(200); if (find_field_bool(form_data, "caChoiceradio-SignWithSpecifiedChain", - PR_FALSE)) { - UChain = PR_TRUE; - chainLen = atoi(find_field(form_data, "manCAs", PR_FALSE)); - PORT_Strcpy(prefix, prefixs[0]); - issuerNameStr = PORT_Strcpy(issuerNameStr, - "CN=Cert-O-Matic II, O=Cert-O-Matic II"); - if (chainLen == 0) { - UChain = PR_FALSE; - } + PR_FALSE)) { + UChain = PR_TRUE; + chainLen = atoi(find_field(form_data, "manCAs", PR_FALSE)); + PORT_Strcpy(prefix, prefixs[0]); + issuerNameStr = PORT_Strcpy(issuerNameStr, + "CN=Cert-O-Matic II, O=Cert-O-Matic II"); + if (chainLen == 0) { + UChain = PR_FALSE; + } } else { - if (find_field_bool(form_data, "caChoiceradio-SignWithRandomChain", - PR_FALSE)) { - PORT_Strcpy(prefix,prefixs[9]); - chainLen = atoi(find_field(form_data, "autoCAs", PR_FALSE)); - if (chainLen < 1 || chainLen > 18) { - issuerNameStr = PORT_Strcpy(issuerNameStr, - "CN=CA18, O=Cert-O-Matic II"); - } - issuerNameStr = PORT_Strcpy(issuerNameStr, "CN=CA"); - issuerNameStr = PORT_Strcat(issuerNameStr, - find_field(form_data,"autoCAs", PR_FALSE)); - issuerNameStr = PORT_Strcat(issuerNameStr,", O=Cert-O-Matic II"); - } else { - issuerNameStr = PORT_Strcpy(issuerNameStr, - "CN=Cert-O-Matic II, O=Cert-O-Matic II"); - } - chainLen = 0; + if (find_field_bool(form_data, "caChoiceradio-SignWithRandomChain", + PR_FALSE)) { + PORT_Strcpy(prefix, prefixs[9]); + chainLen = atoi(find_field(form_data, "autoCAs", PR_FALSE)); + if (chainLen < 1 || chainLen > 18) { + issuerNameStr = PORT_Strcpy(issuerNameStr, + "CN=CA18, O=Cert-O-Matic II"); + } + issuerNameStr = PORT_Strcpy(issuerNameStr, "CN=CA"); + issuerNameStr = PORT_Strcat(issuerNameStr, + find_field(form_data, "autoCAs", PR_FALSE)); + issuerNameStr = PORT_Strcat(issuerNameStr, ", O=Cert-O-Matic II"); + } else { + issuerNameStr = PORT_Strcpy(issuerNameStr, + "CN=Cert-O-Matic II, O=Cert-O-Matic II"); + } + chainLen = 0; } i = -1; which_key = 0; do { - extern SECStatus cert_GetKeyID(CERTCertificate *cert); - i++; - if (i != 0 && UChain) { - PORT_Strcpy(prefix, prefixs[i]); - } - /* find_field(form_data,"subject", PR_TRUE); */ - certReq = makeCertReq(form_data, which_key); + extern SECStatus cert_GetKeyID(CERTCertificate * cert); + i++; + if (i != 0 && UChain) { + PORT_Strcpy(prefix, prefixs[i]); + } + /* find_field(form_data,"subject", PR_TRUE); */ + certReq = makeCertReq(form_data, which_key); #ifdef OFFLINE - serial = 900; + serial = 900; #else - serial = get_serial_number(form_data); + serial = get_serial_number(form_data); #endif - cert = MakeV1Cert(handle, certReq, issuerNameStr, PR_FALSE, - serial, warpmonths, form_data); - if (certReq != NULL) { - CERT_DestroyCertificateRequest(certReq); - } - if (find_field_bool(form_data,"ver-3", PR_TRUE)) { - status = add_extensions(cert, form_data, issuerNameStr, handle); - if (status != SECSuccess) { - error_out("ERROR: Unable to add extensions"); - } - } - status = cert_GetKeyID(cert); - if (status == SECFailure) { - error_out("ERROR: Unable to get Key ID."); - } - certDER = SignCert(cert, issuerNameStr, form_data, handle, which_key); - CERT_NewTempCertificate(handle, certDER, NULL, PR_FALSE, PR_TRUE); - issuerNameStr = find_field(form_data, "subject", PR_TRUE); - /* SECITEM_FreeItem(certDER, PR_TRUE); */ - CERT_DestroyCertificate(cert); - if (i == (chainLen - 1)) { - i = 8; - } - ++which_key; + cert = MakeV1Cert(handle, certReq, issuerNameStr, PR_FALSE, + serial, warpmonths, form_data); + if (certReq != NULL) { + CERT_DestroyCertificateRequest(certReq); + } + if (find_field_bool(form_data, "ver-3", PR_TRUE)) { + status = add_extensions(cert, form_data, issuerNameStr, handle); + if (status != SECSuccess) { + error_out("ERROR: Unable to add extensions"); + } + } + status = cert_GetKeyID(cert); + if (status == SECFailure) { + error_out("ERROR: Unable to get Key ID."); + } + certDER = SignCert(cert, issuerNameStr, form_data, handle, which_key); + CERT_NewTempCertificate(handle, certDER, NULL, PR_FALSE, PR_TRUE); + issuerNameStr = find_field(form_data, "subject", PR_TRUE); + /* SECITEM_FreeItem(certDER, PR_TRUE); */ + CERT_DestroyCertificate(cert); + if (i == (chainLen - 1)) { + i = 8; + } + ++which_key; } while (i < 9 && UChain); - - #ifdef FILEOUT outfile = fopen("../certout", "wb"); #endif certName = find_field(form_data, "subject", PR_FALSE); cert = CERT_FindCertByNameString(handle, certName); - certChain = SEC_PKCS7CreateCertsOnly (cert, PR_TRUE, handle); + certChain = SEC_PKCS7CreateCertsOnly(cert, PR_TRUE, handle); if (certChain == NULL) { - error_out("ERROR: No certificates in cert chain"); + error_out("ERROR: No certificates in cert chain"); } - encodedCertChain = SEC_PKCS7EncodeItem (NULL, NULL, certChain, NULL, NULL, - NULL); + encodedCertChain = SEC_PKCS7EncodeItem(NULL, NULL, certChain, NULL, NULL, + NULL); if (encodedCertChain) { #if !defined(FILEOUT) - printf("Content-type: application/x-x509-user-cert\r\n"); - printf("Content-length: %d\r\n\r\n", encodedCertChain->len); - fwrite (encodedCertChain->data, 1, encodedCertChain->len, stdout); + printf("Content-type: application/x-x509-user-cert\r\n"); + printf("Content-length: %d\r\n\r\n", encodedCertChain->len); + fwrite(encodedCertChain->data, 1, encodedCertChain->len, stdout); #else - fwrite (encodedCertChain->data, 1, encodedCertChain->len, outfile); + fwrite(encodedCertChain->data, 1, encodedCertChain->len, outfile); #endif } else { - error_out("Error: Unable to DER encode certificate"); + error_out("Error: Unable to DER encode certificate"); } #ifdef FILEOUT printf("\nI got here!\n"); @@ -2296,4 +2235,3 @@ main(int argc, char **argv) } return 0; } - diff --git a/cmd/certutil/certext.c b/cmd/certutil/certext.c index 8796747d8b..12af615717 100644 --- a/cmd/certutil/certext.c +++ b/cmd/certutil/certext.c @@ -30,12 +30,15 @@ #include "genname.h" #include "prnetdb.h" -#define GEN_BREAK(e) rv=e; break; +#define GEN_BREAK(e) \ + rv = e; \ + break; static char * -Gets_s(char *buff, size_t size) { +Gets_s(char *buff, size_t size) +{ char *str; - + if (buff == NULL || size < 1) { PORT_Assert(0); return NULL; @@ -46,7 +49,7 @@ Gets_s(char *buff, size_t size) { * fgets() automatically converts native text file * line endings to '\n'. As defensive programming * (just in case fgets has a bug or we put stdin in - * binary mode by mistake), we handle three native + * binary mode by mistake), we handle three native * text file line endings here: * '\n' Unix (including Linux and Mac OS X) * '\r''\n' DOS/Windows & OS/2 @@ -65,13 +68,12 @@ Gets_s(char *buff, size_t size) { return str; } - static SECStatus -PrintChoicesAndGetAnswer(char* str, char* rBuff, int rSize) +PrintChoicesAndGetAnswer(char *str, char *rBuff, int rSize) { fputs(str, stdout); fputs(" > ", stdout); - fflush (stdout); + fflush(stdout); if (Gets_s(rBuff, rSize) == NULL) { PORT_SetError(SEC_ERROR_INPUT_LEN); return SECFailure; @@ -90,114 +92,116 @@ GetGeneralName(PLArenaPool *arena, CERTGeneralName *useExistingName, PRBool only char buffer[512]; void *mark; - PORT_Assert (arena); - mark = PORT_ArenaMark (arena); + PORT_Assert(arena); + mark = PORT_ArenaMark(arena); do { if (PrintChoicesAndGetAnswer( - "\nSelect one of the following general name type: \n" - "\t2 - rfc822Name\n" - "\t3 - dnsName\n" - "\t5 - directoryName\n" - "\t7 - uniformResourceidentifier\n" - "\t8 - ipAddress\n" - "\t9 - registerID\n" - "\tAny other number to finish\n" - "\t\tChoice:", buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); - } - intValue = PORT_Atoi (buffer); + "\nSelect one of the following general name type: \n" + "\t2 - rfc822Name\n" + "\t3 - dnsName\n" + "\t5 - directoryName\n" + "\t7 - uniformResourceidentifier\n" + "\t8 - ipAddress\n" + "\t9 - registerID\n" + "\tAny other number to finish\n" + "\t\tChoice:", + buffer, sizeof(buffer)) == SECFailure) { + GEN_BREAK(SECFailure); + } + intValue = PORT_Atoi(buffer); /* * Should use ZAlloc instead of Alloc to avoid problem with garbage * initialized pointers in CERT_CopyName */ switch (intValue) { - case certRFC822Name: - case certDNSName: - case certDirectoryName: - case certURI: - case certIPAddress: - case certRegisterID: - break; - default: - intValue = 0; /* force a break for anything else */ - } + case certRFC822Name: + case certDNSName: + case certDirectoryName: + case certURI: + case certIPAddress: + case certRegisterID: + break; + default: + intValue = 0; /* force a break for anything else */ + } if (intValue == 0) - break; - - if (namesList == NULL) { + break; + + if (namesList == NULL) { if (useExistingName) { namesList = current = tail = useExistingName; } else { namesList = current = tail = PORT_ArenaZNew(arena, CERTGeneralName); } - } else { - current = PORT_ArenaZNew(arena, CERTGeneralName); - } - if (current == NULL) { - GEN_BREAK (SECFailure); - } + } else { + current = PORT_ArenaZNew(arena, CERTGeneralName); + } + if (current == NULL) { + GEN_BREAK(SECFailure); + } current->type = intValue; - puts ("\nEnter data:"); - fflush (stdout); - if (Gets_s (buffer, sizeof(buffer)) == NULL) { + puts("\nEnter data:"); + fflush(stdout); + if (Gets_s(buffer, sizeof(buffer)) == NULL) { PORT_SetError(SEC_ERROR_INPUT_LEN); - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } switch (current->type) { - case certURI: - case certDNSName: - case certRFC822Name: - current->name.other.data = - PORT_ArenaAlloc (arena, strlen (buffer)); - if (current->name.other.data == NULL) { - GEN_BREAK (SECFailure); - } - PORT_Memcpy(current->name.other.data, buffer, - current->name.other.len = strlen(buffer)); - break; + case certURI: + case certDNSName: + case certRFC822Name: + current->name.other.data = + PORT_ArenaAlloc(arena, strlen(buffer)); + if (current->name.other.data == NULL) { + GEN_BREAK(SECFailure); + } + PORT_Memcpy(current->name.other.data, buffer, + current->name.other.len = strlen(buffer)); + break; + + case certEDIPartyName: + case certIPAddress: + case certOtherName: + case certRegisterID: + case certX400Address: { - case certEDIPartyName: - case certIPAddress: - case certOtherName: - case certRegisterID: - case certX400Address: { + current->name.other.data = + PORT_ArenaAlloc(arena, strlen(buffer) + 2); + if (current->name.other.data == NULL) { + GEN_BREAK(SECFailure); + } - current->name.other.data = - PORT_ArenaAlloc (arena, strlen (buffer) + 2); - if (current->name.other.data == NULL) { - GEN_BREAK (SECFailure); + PORT_Memcpy(current->name.other.data + 2, buffer, + strlen(buffer)); + /* This may not be accurate for all cases. For now, + * use this tag type */ + current->name.other.data[0] = + (char)(((current->type - 1) & 0x1f) | 0x80); + current->name.other.data[1] = (char)strlen(buffer); + current->name.other.len = strlen(buffer) + 2; + break; } - - PORT_Memcpy (current->name.other.data + 2, buffer, - strlen (buffer)); - /* This may not be accurate for all cases. For now, - * use this tag type */ - current->name.other.data[0] = - (char)(((current->type - 1) & 0x1f)| 0x80); - current->name.other.data[1] = (char)strlen (buffer); - current->name.other.len = strlen (buffer) + 2; - break; - } - case certDirectoryName: { - CERTName *directoryName = NULL; - - directoryName = CERT_AsciiToName (buffer); - if (!directoryName) { - fprintf(stderr, "certutil: improperly formatted name: " - "\"%s\"\n", buffer); + case certDirectoryName: { + CERTName *directoryName = NULL; + + directoryName = CERT_AsciiToName(buffer); + if (!directoryName) { + fprintf(stderr, "certutil: improperly formatted name: " + "\"%s\"\n", + buffer); + break; + } + + rv = CERT_CopyName(arena, ¤t->name.directoryName, + directoryName); + CERT_DestroyName(directoryName); + break; } - - rv = CERT_CopyName (arena, ¤t->name.directoryName, - directoryName); - CERT_DestroyName (directoryName); - - break; - } } if (rv != SECSuccess) break; @@ -205,11 +209,11 @@ GetGeneralName(PLArenaPool *arena, CERTGeneralName *useExistingName, PRBool only current->l.prev = &(tail->l); tail->l.next = &(current->l); tail = current; - - }while (!onlyOne); + + } while (!onlyOne); if (rv != SECSuccess) { - PORT_ArenaRelease (arena, mark); + PORT_ArenaRelease(arena, mark); namesList = NULL; } return (namesList); @@ -218,10 +222,10 @@ GetGeneralName(PLArenaPool *arena, CERTGeneralName *useExistingName, PRBool only static CERTGeneralName * CreateGeneralName(PLArenaPool *arena) { - return GetGeneralName(arena, NULL, PR_FALSE); + return GetGeneralName(arena, NULL, PR_FALSE); } -static SECStatus +static SECStatus GetString(PLArenaPool *arena, char *prompt, SECItem *value) { char buffer[251]; @@ -230,23 +234,23 @@ GetString(PLArenaPool *arena, char *prompt, SECItem *value) buffer[0] = '\0'; value->data = NULL; value->len = 0; - - puts (prompt); - buffPrt = Gets_s (buffer, sizeof(buffer)); + + puts(prompt); + buffPrt = Gets_s(buffer, sizeof(buffer)); /* returned NULL here treated the same way as empty string */ - if (buffPrt && strlen (buffer) > 0) { - value->data = PORT_ArenaAlloc (arena, strlen (buffer)); + if (buffPrt && strlen(buffer) > 0) { + value->data = PORT_ArenaAlloc(arena, strlen(buffer)); if (value->data == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); + PORT_SetError(SEC_ERROR_NO_MEMORY); return (SECFailure); } - PORT_Memcpy (value->data, buffer, value->len = strlen(buffer)); + PORT_Memcpy(value->data, buffer, value->len = strlen(buffer)); } return (SECSuccess); } -static PRBool -GetYesNo(char *prompt) +static PRBool +GetYesNo(char *prompt) { char buf[3]; char *buffPrt; @@ -265,7 +269,7 @@ GetYesNo(char *prompt) * A special value "critical" can be parsed out from the supplied sting.*/ static SECStatus -parseNextCmdInput(const char * const *valueArray, int *value, char **nextPos, +parseNextCmdInput(const char *const *valueArray, int *value, char **nextPos, PRBool *critical) { char *thisPos = *nextPos; @@ -306,24 +310,24 @@ parseNextCmdInput(const char * const *valueArray, int *value, char **nextPos, return SECFailure; } -static const char * const -keyUsageKeyWordArray[] = { "digitalSignature", - "nonRepudiation", - "keyEncipherment", - "dataEncipherment", - "keyAgreement", - "certSigning", - "crlSigning", - NULL}; - -static SECStatus -AddKeyUsage (void *extHandle, const char *userSuppliedValue) +static const char *const + keyUsageKeyWordArray[] = { "digitalSignature", + "nonRepudiation", + "keyEncipherment", + "dataEncipherment", + "keyAgreement", + "certSigning", + "crlSigning", + NULL }; + +static SECStatus +AddKeyUsage(void *extHandle, const char *userSuppliedValue) { SECItem bitStringValue; unsigned char keyUsage = 0x0; char buffer[5]; int value; - char *nextPos = (char*)userSuppliedValue; + char *nextPos = (char *)userSuppliedValue; PRBool isCriticalExt = PR_FALSE; if (!userSuppliedValue) { @@ -332,15 +336,15 @@ AddKeyUsage (void *extHandle, const char *userSuppliedValue) "\t\t0 - Digital Signature\n" "\t\t1 - Non-repudiation\n" "\t\t2 - Key encipherment\n" - "\t\t3 - Data encipherment\n" + "\t\t3 - Data encipherment\n" "\t\t4 - Key agreement\n" - "\t\t5 - Cert signing key\n" + "\t\t5 - Cert signing key\n" "\t\t6 - CRL signing key\n" "\t\tOther to finish\n", buffer, sizeof(buffer)) == SECFailure) { return SECFailure; } - value = PORT_Atoi (buffer); + value = PORT_Atoi(buffer); if (value < 0 || value > 6) break; if (value == 0) { @@ -369,13 +373,10 @@ AddKeyUsage (void *extHandle, const char *userSuppliedValue) bitStringValue.data = &keyUsage; bitStringValue.len = 1; - return (CERT_EncodeAndAddBitStrExtension - (extHandle, SEC_OID_X509_KEY_USAGE, &bitStringValue, - isCriticalExt)); - + return (CERT_EncodeAndAddBitStrExtension(extHandle, SEC_OID_X509_KEY_USAGE, &bitStringValue, + isCriticalExt)); } - static CERTOidSequence * CreateOidSequence(void) { @@ -383,17 +384,17 @@ CreateOidSequence(void) PLArenaPool *arena = (PLArenaPool *)NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if( (PLArenaPool *)NULL == arena ) { + if ((PLArenaPool *)NULL == arena) { goto loser; } rv = (CERTOidSequence *)PORT_ArenaZNew(arena, CERTOidSequence); - if( (CERTOidSequence *)NULL == rv ) { + if ((CERTOidSequence *)NULL == rv) { goto loser; } rv->oids = (SECItem **)PORT_ArenaZNew(arena, SECItem *); - if( (SECItem **)NULL == rv->oids ) { + if ((SECItem **)NULL == rv->oids) { goto loser; } @@ -401,7 +402,7 @@ CreateOidSequence(void) return rv; loser: - if( (PLArenaPool *)NULL != arena ) { + if ((PLArenaPool *)NULL != arena) { PORT_FreeArena(arena, PR_FALSE); } @@ -424,11 +425,11 @@ AddOidToSequence(CERTOidSequence *os, SECOidTag oidTag) SECOidData *od; od = SECOID_FindOIDByTag(oidTag); - if( (SECOidData *)NULL == od ) { + if ((SECOidData *)NULL == od) { return SECFailure; } - for( oids = os->oids; (SECItem *)NULL != *oids; oids++ ) { + for (oids = os->oids; (SECItem *)NULL != *oids; oids++) { if (*oids == &od->oid) { /* We already have this oid */ return SECSuccess; @@ -442,11 +443,11 @@ AddOidToSequence(CERTOidSequence *os, SECOidTag oidTag) PRUint32 i; oids = (SECItem **)PORT_ArenaZNewArray(os->arena, SECItem *, count + 2); - if( (SECItem **)NULL == oids ) { + if ((SECItem **)NULL == oids) { return SECFailure; } - - for( i = 0; i < count; i++ ) { + + for (i = 0; i < count; i++) { oids[i] = os->oids[i]; } @@ -466,18 +467,17 @@ const SEC_ASN1Template CERT_OidSeqTemplate[] = { SEC_ASN1_SUB(SEC_ObjectIDTemplate) } }; - static SECItem * EncodeOidSequence(CERTOidSequence *os) { SECItem *rv; rv = (SECItem *)PORT_ArenaZNew(os->arena, SECItem); - if( (SECItem *)NULL == rv ) { + if ((SECItem *)NULL == rv) { goto loser; } - if( !SEC_ASN1EncodeItem(os->arena, rv, os, CERT_OidSeqTemplate) ) { + if (!SEC_ASN1EncodeItem(os->arena, rv, os, CERT_OidSeqTemplate)) { goto loser; } @@ -487,19 +487,19 @@ EncodeOidSequence(CERTOidSequence *os) return (SECItem *)NULL; } -static const char * const -extKeyUsageKeyWordArray[] = { "serverAuth", - "clientAuth", - "codeSigning", - "emailProtection", - "timeStamp", - "ocspResponder", - "stepUp", - "msTrustListSigning", - NULL}; - -static SECStatus -AddExtKeyUsage (void *extHandle, const char *userSuppliedValue) +static const char *const + extKeyUsageKeyWordArray[] = { "serverAuth", + "clientAuth", + "codeSigning", + "emailProtection", + "timeStamp", + "ocspResponder", + "stepUp", + "msTrustListSigning", + NULL }; + +static SECStatus +AddExtKeyUsage(void *extHandle, const char *userSuppliedValue) { char buffer[5]; int value; @@ -507,10 +507,10 @@ AddExtKeyUsage (void *extHandle, const char *userSuppliedValue) SECStatus rv; SECItem *item; PRBool isCriticalExt = PR_FALSE; - char *nextPos = (char*)userSuppliedValue; - + char *nextPos = (char *)userSuppliedValue; + os = CreateOidSequence(); - if( (CERTOidSequence *)NULL == os ) { + if ((CERTOidSequence *)NULL == os) { return SECFailure; } @@ -530,7 +530,7 @@ AddExtKeyUsage (void *extHandle, const char *userSuppliedValue) GEN_BREAK(SECFailure); } value = PORT_Atoi(buffer); - + if (value == 0) { /* Checking that zero value of variable 'value' * corresponds to '0' input made by user */ @@ -546,38 +546,38 @@ AddExtKeyUsage (void *extHandle, const char *userSuppliedValue) } } - switch( value ) { - case 0: - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_SERVER_AUTH); - break; - case 1: - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH); - break; - case 2: - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CODE_SIGN); - break; - case 3: - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_EMAIL_PROTECT); - break; - case 4: - rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_TIME_STAMP); - break; - case 5: - rv = AddOidToSequence(os, SEC_OID_OCSP_RESPONDER); - break; - case 6: - rv = AddOidToSequence(os, SEC_OID_NS_KEY_USAGE_GOVT_APPROVED); - break; - case 7: - rv = AddOidToSequence(os, SEC_OID_MS_EXT_KEY_USAGE_CTL_SIGNING); - break; - default: - goto endloop; + switch (value) { + case 0: + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_SERVER_AUTH); + break; + case 1: + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH); + break; + case 2: + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_CODE_SIGN); + break; + case 3: + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_EMAIL_PROTECT); + break; + case 4: + rv = AddOidToSequence(os, SEC_OID_EXT_KEY_USAGE_TIME_STAMP); + break; + case 5: + rv = AddOidToSequence(os, SEC_OID_OCSP_RESPONDER); + break; + case 6: + rv = AddOidToSequence(os, SEC_OID_NS_KEY_USAGE_GOVT_APPROVED); + break; + case 7: + rv = AddOidToSequence(os, SEC_OID_MS_EXT_KEY_USAGE_CTL_SIGNING); + break; + default: + goto endloop; } if (userSuppliedValue && !nextPos) break; - if( SECSuccess != rv ) + if (SECSuccess != rv) goto loser; } @@ -590,31 +590,31 @@ AddExtKeyUsage (void *extHandle, const char *userSuppliedValue) rv = CERT_AddExtension(extHandle, SEC_OID_X509_EXT_KEY_USAGE, item, isCriticalExt, PR_TRUE); - /*FALLTHROUGH*/ +/*FALLTHROUGH*/ loser: DestroyOidSequence(os); return rv; } -static const char * const -nsCertTypeKeyWordArray[] = { "sslClient", - "sslServer", - "smime", - "objectSigning", - "Not!Used", - "sslCA", - "smimeCA", - "objectSigningCA", - NULL }; - -static SECStatus -AddNscpCertType (void *extHandle, const char *userSuppliedValue) +static const char *const + nsCertTypeKeyWordArray[] = { "sslClient", + "sslServer", + "smime", + "objectSigning", + "Not!Used", + "sslCA", + "smimeCA", + "objectSigningCA", + NULL }; + +static SECStatus +AddNscpCertType(void *extHandle, const char *userSuppliedValue) { SECItem bitStringValue; unsigned char keyUsage = 0x0; char buffer[5]; int value; - char *nextPos = (char*)userSuppliedValue; + char *nextPos = (char *)userSuppliedValue; PRBool isCriticalExt = PR_FALSE; if (!userSuppliedValue) { @@ -623,16 +623,16 @@ AddNscpCertType (void *extHandle, const char *userSuppliedValue) "\t\t0 - SSL Client\n" "\t\t1 - SSL Server\n" "\t\t2 - S/MIME\n" - "\t\t3 - Object Signing\n" + "\t\t3 - Object Signing\n" "\t\t4 - Reserved for future use\n" - "\t\t5 - SSL CA\n" + "\t\t5 - SSL CA\n" "\t\t6 - S/MIME CA\n" "\t\t7 - Object Signing CA\n" "\t\tOther to finish\n", buffer, sizeof(buffer)) == SECFailure) { return SECFailure; } - value = PORT_Atoi (buffer); + value = PORT_Atoi(buffer); if (value < 0 || value > 7) break; if (value == 0) { @@ -661,10 +661,8 @@ AddNscpCertType (void *extHandle, const char *userSuppliedValue) bitStringValue.data = &keyUsage; bitStringValue.len = 1; - return (CERT_EncodeAndAddBitStrExtension - (extHandle, SEC_OID_NS_CERT_EXT_CERT_TYPE, &bitStringValue, - isCriticalExt)); - + return (CERT_EncodeAndAddBitStrExtension(extHandle, SEC_OID_NS_CERT_EXT_CERT_TYPE, &bitStringValue, + isCriticalExt)); } SECStatus @@ -686,7 +684,7 @@ GetOidFromString(PLArenaPool *arena, SECItem *to, */ tag = SEC_OID_UNKNOWN; coid = SECOID_FindOIDByTag(tag); - for ( ; coid; coid = SECOID_FindOIDByTag(++tag)) { + for (; coid; coid = SECOID_FindOIDByTag(++tag)) { if (PORT_Strncasecmp(from, coid->desc, fromLen) == 0) { break; } @@ -698,7 +696,7 @@ GetOidFromString(PLArenaPool *arena, SECItem *to, return SECITEM_CopyItem(arena, to, &coid->oid); } -static SECStatus +static SECStatus AddSubjectAltNames(PLArenaPool *arena, CERTGeneralName **existingListp, const char *constNames, CERTGeneralNameType type) { @@ -707,9 +705,9 @@ AddSubjectAltNames(PLArenaPool *arena, CERTGeneralName **existingListp, PRCList *prev = NULL; char *cp, *nextName = NULL; SECStatus rv = SECSuccess; - PRBool readTypeFromName = (PRBool) (type == 0); + PRBool readTypeFromName = (PRBool)(type == 0); char *names = NULL; - + if (constNames) names = PORT_Strdup(constNames); @@ -728,7 +726,7 @@ AddSubjectAltNames(PLArenaPool *arena, CERTGeneralName **existingListp, * as a parameter to this function will be used. * If the type value is zero (undefined), we'll fail. */ - for (cp=names; cp; cp=nextName) { + for (cp = names; cp; cp = nextName) { int len; char *oidString; char *nextComma; @@ -744,13 +742,13 @@ AddSubjectAltNames(PLArenaPool *arena, CERTGeneralName **existingListp, nextComma = PORT_Strchr(cp, ','); if (nextComma) { *nextComma = 0; - nextName = nextComma+1; + nextName = nextComma + 1; } if ((*cp) == 0) { continue; } if (readTypeFromName) { - char *save=cp; + char *save = cp; /* Because we already replaced nextComma with end-of-string, * a found colon belongs to the current name */ cp = PORT_Strchr(cp, ':'); @@ -779,92 +777,92 @@ AddSubjectAltNames(PLArenaPool *arena, CERTGeneralName **existingListp, current->type = type; switch (type) { - /* string types */ - case certRFC822Name: - case certDNSName: - case certURI: - current->name.other.data = - (unsigned char *) PORT_ArenaStrdup(arena,cp); - current->name.other.len = PORT_Strlen(cp); - break; - /* unformated data types */ - case certX400Address: - case certEDIPartyName: - /* turn a string into a data and len */ - rv = SECFailure; /* punt on these for now */ - fprintf(stderr,"EDI Party Name and X.400 Address not supported\n"); - break; - case certDirectoryName: - /* certDirectoryName */ - name = CERT_AsciiToName(cp); - if (name == NULL) { - rv = SECFailure; - fprintf(stderr, "Invalid Directory Name (\"%s\")\n", cp); + /* string types */ + case certRFC822Name: + case certDNSName: + case certURI: + current->name.other.data = + (unsigned char *)PORT_ArenaStrdup(arena, cp); + current->name.other.len = PORT_Strlen(cp); break; - } - rv = CERT_CopyName(arena,¤t->name.directoryName,name); - CERT_DestroyName(name); - break; - /* types that require more processing */ - case certIPAddress: - /* convert the string to an ip address */ - status = PR_StringToNetAddr(cp, &addr); - if (status != PR_SUCCESS) { - rv = SECFailure; - fprintf(stderr, "Invalid IP Address (\"%s\")\n", cp); + /* unformated data types */ + case certX400Address: + case certEDIPartyName: + /* turn a string into a data and len */ + rv = SECFailure; /* punt on these for now */ + fprintf(stderr, "EDI Party Name and X.400 Address not supported\n"); break; - } + case certDirectoryName: + /* certDirectoryName */ + name = CERT_AsciiToName(cp); + if (name == NULL) { + rv = SECFailure; + fprintf(stderr, "Invalid Directory Name (\"%s\")\n", cp); + break; + } + rv = CERT_CopyName(arena, ¤t->name.directoryName, name); + CERT_DestroyName(name); + break; + /* types that require more processing */ + case certIPAddress: + /* convert the string to an ip address */ + status = PR_StringToNetAddr(cp, &addr); + if (status != PR_SUCCESS) { + rv = SECFailure; + fprintf(stderr, "Invalid IP Address (\"%s\")\n", cp); + break; + } - if (PR_NetAddrFamily(&addr) == PR_AF_INET) { - len = sizeof(addr.inet.ip); - data = (unsigned char *)&addr.inet.ip; - } else if (PR_NetAddrFamily(&addr) == PR_AF_INET6) { - len = sizeof(addr.ipv6.ip); - data = (unsigned char *)&addr.ipv6.ip; - } else { - fprintf(stderr, "Invalid IP Family\n"); - rv = SECFailure; + if (PR_NetAddrFamily(&addr) == PR_AF_INET) { + len = sizeof(addr.inet.ip); + data = (unsigned char *)&addr.inet.ip; + } else if (PR_NetAddrFamily(&addr) == PR_AF_INET6) { + len = sizeof(addr.ipv6.ip); + data = (unsigned char *)&addr.ipv6.ip; + } else { + fprintf(stderr, "Invalid IP Family\n"); + rv = SECFailure; + break; + } + current->name.other.data = PORT_ArenaAlloc(arena, len); + if (current->name.other.data == NULL) { + rv = SECFailure; + break; + } + current->name.other.len = len; + PORT_Memcpy(current->name.other.data, data, len); break; - } - current->name.other.data = PORT_ArenaAlloc(arena, len); - if (current->name.other.data == NULL) { - rv = SECFailure; + case certRegisterID: + rv = GetOidFromString(arena, ¤t->name.other, cp, strlen(cp)); break; - } - current->name.other.len = len; - PORT_Memcpy(current->name.other.data,data, len); - break; - case certRegisterID: - rv = GetOidFromString(arena, ¤t->name.other, cp, strlen(cp)); - break; - case certOtherName: - oidString = cp; - cp = PORT_Strchr(cp,';'); - if (cp == NULL) { - rv = SECFailure; - fprintf(stderr, "missing name in other name\n"); + case certOtherName: + oidString = cp; + cp = PORT_Strchr(cp, ';'); + if (cp == NULL) { + rv = SECFailure; + fprintf(stderr, "missing name in other name\n"); + break; + } + *cp++ = 0; + current->name.OthName.name.data = + (unsigned char *)PORT_ArenaStrdup(arena, cp); + if (current->name.OthName.name.data == NULL) { + rv = SECFailure; + break; + } + current->name.OthName.name.len = PORT_Strlen(cp); + rv = GetOidFromString(arena, ¤t->name.OthName.oid, + oidString, strlen(oidString)); break; - } - *cp++ = 0; - current->name.OthName.name.data = - (unsigned char *) PORT_ArenaStrdup(arena,cp); - if (current->name.OthName.name.data == NULL) { + default: rv = SECFailure; + fprintf(stderr, "Missing or invalid Subject Alternate Name type\n"); break; - } - current->name.OthName.name.len = PORT_Strlen(cp); - rv = GetOidFromString(arena, ¤t->name.OthName.oid, - oidString, strlen(oidString)); - break; - default: - rv = SECFailure; - fprintf(stderr, "Missing or invalid Subject Alternate Name type\n"); - break; } if (rv == SECFailure) { break; } - + if (prev) { current->l.prev = prev; prev->next = &(current->l); @@ -885,8 +883,7 @@ AddSubjectAltNames(PLArenaPool *arena, CERTGeneralName **existingListp, nameList->l.prev = existingprev; existingprev->next = &(nameList->l); current->l.next = &((*existingListp)->l); - } - else { + } else { /* make nameList circular and set it as the new existingList */ nameList->l.prev = prev; current->l.next = &(nameList->l); @@ -896,39 +893,39 @@ AddSubjectAltNames(PLArenaPool *arena, CERTGeneralName **existingListp, return rv; } -static SECStatus +static SECStatus AddEmailSubjectAlt(PLArenaPool *arena, CERTGeneralName **existingListp, const char *emailAddrs) { - return AddSubjectAltNames(arena, existingListp, emailAddrs, + return AddSubjectAltNames(arena, existingListp, emailAddrs, certRFC822Name); } -static SECStatus +static SECStatus AddDNSSubjectAlt(PLArenaPool *arena, CERTGeneralName **existingListp, const char *dnsNames) { return AddSubjectAltNames(arena, existingListp, dnsNames, certDNSName); } -static SECStatus +static SECStatus AddGeneralSubjectAlt(PLArenaPool *arena, CERTGeneralName **existingListp, const char *altNames) { return AddSubjectAltNames(arena, existingListp, altNames, 0); } -static SECStatus +static SECStatus AddBasicConstraint(void *extHandle) { - CERTBasicConstraints basicConstraint; + CERTBasicConstraints basicConstraint; SECStatus rv; char buffer[10]; PRBool yesNoAns; do { basicConstraint.pathLenConstraint = CERT_UNLIMITED_PATH_CONSTRAINT; - basicConstraint.isCA = GetYesNo ("Is this a CA certificate [y/N]?"); + basicConstraint.isCA = GetYesNo("Is this a CA certificate [y/N]?"); buffer[0] = '\0'; if (PrintChoicesAndGetAnswer("Enter the path length constraint, " @@ -936,39 +933,39 @@ AddBasicConstraint(void *extHandle) buffer, sizeof(buffer)) == SECFailure) { GEN_BREAK(SECFailure); } - if (PORT_Strlen (buffer) > 0) - basicConstraint.pathLenConstraint = PORT_Atoi (buffer); + if (PORT_Strlen(buffer) > 0) + basicConstraint.pathLenConstraint = PORT_Atoi(buffer); - yesNoAns = GetYesNo ("Is this a critical extension [y/N]?"); + yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); rv = SECU_EncodeAndAddExtensionValue(NULL, extHandle, - &basicConstraint, yesNoAns, SEC_OID_X509_BASIC_CONSTRAINTS, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeBasicConstraintValue); + &basicConstraint, yesNoAns, SEC_OID_X509_BASIC_CONSTRAINTS, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeBasicConstraintValue); } while (0); return (rv); } -static SECStatus +static SECStatus AddNameConstraints(void *extHandle) { - PLArenaPool *arena = NULL; - CERTNameConstraints *constraints = NULL; + PLArenaPool *arena = NULL; + CERTNameConstraints *constraints = NULL; - CERTNameConstraint *current = NULL; - CERTNameConstraint *last_permited = NULL; - CERTNameConstraint *last_excluded = NULL; - SECStatus rv = SECSuccess; + CERTNameConstraint *current = NULL; + CERTNameConstraint *last_permited = NULL; + CERTNameConstraint *last_excluded = NULL; + SECStatus rv = SECSuccess; char buffer[512]; int intValue = 0; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena) { - constraints = PORT_ArenaZNew(arena, CERTNameConstraints); + constraints = PORT_ArenaZNew(arena, CERTNameConstraints); } - if (!arena || ! constraints) { + if (!arena || !constraints) { SECU_PrintError(progName, "out of memory"); PORT_FreeArena(arena, PR_FALSE); return SECFailure; @@ -982,43 +979,44 @@ AddNameConstraints(void *extHandle) GEN_BREAK(SECFailure); } - (void) SEC_ASN1EncodeInteger(arena, ¤t->min, 0); + (void)SEC_ASN1EncodeInteger(arena, ¤t->min, 0); if (!GetGeneralName(arena, ¤t->name, PR_TRUE)) { GEN_BREAK(SECFailure); } if (PrintChoicesAndGetAnswer("Type of Name Constraint?\n" - "\t1 - permitted\n\t2 - excluded\n\tAny" - "other number to finish\n\tChoice", - buffer, sizeof(buffer)) != SECSuccess) { + "\t1 - permitted\n\t2 - excluded\n\tAny" + "other number to finish\n\tChoice", + buffer, sizeof(buffer)) != + SECSuccess) { GEN_BREAK(SECFailure); } intValue = PORT_Atoi(buffer); switch (intValue) { - case 1: - if (constraints->permited == NULL) { - constraints->permited = last_permited = current; - } - last_permited->l.next = &(current->l); - current->l.prev = &(last_permited->l); - last_permited = current; - break; - case 2: - if (constraints->excluded == NULL) { - constraints->excluded = last_excluded = current; - } - last_excluded->l.next = &(current->l); - current->l.prev = &(last_excluded->l); - last_excluded = current; - break; + case 1: + if (constraints->permited == NULL) { + constraints->permited = last_permited = current; + } + last_permited->l.next = &(current->l); + current->l.prev = &(last_permited->l); + last_permited = current; + break; + case 2: + if (constraints->excluded == NULL) { + constraints->excluded = last_excluded = current; + } + last_excluded->l.next = &(current->l); + current->l.prev = &(last_excluded->l); + last_excluded = current; + break; } - + PR_snprintf(buffer, sizeof(buffer), "Add another entry to the" - " Name Constraint Extension [y/N]"); + " Name Constraint Extension [y/N]"); - if (GetYesNo (buffer) == 0) { + if (GetYesNo(buffer) == 0) { break; } @@ -1039,69 +1037,70 @@ AddNameConstraints(void *extHandle) } rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, constraints, - yesNoAns, oidIdent, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeNameConstraintsExtension); + yesNoAns, oidIdent, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeNameConstraintsExtension); } if (arena) PORT_FreeArena(arena, PR_FALSE); return (rv); } -static SECStatus -AddAuthKeyID (void *extHandle) +static SECStatus +AddAuthKeyID(void *extHandle) { - CERTAuthKeyID *authKeyID = NULL; + CERTAuthKeyID *authKeyID = NULL; PLArenaPool *arena = NULL; SECStatus rv = SECSuccess; PRBool yesNoAns; do { arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { SECU_PrintError(progName, "out of memory"); - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - if (GetYesNo ("Enter value for the authKeyID extension [y/N]?") == 0) + if (GetYesNo("Enter value for the authKeyID extension [y/N]?") == 0) break; authKeyID = PORT_ArenaZNew(arena, CERTAuthKeyID); if (authKeyID == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - rv = GetString (arena, "Enter value for the key identifier fields," - "enter to omit:", &authKeyID->keyID); + rv = GetString(arena, "Enter value for the key identifier fields," + "enter to omit:", + &authKeyID->keyID); if (rv != SECSuccess) break; SECU_SECItemHexStringToBinary(&authKeyID->keyID); - authKeyID->authCertIssuer = CreateGeneralName (arena); - if (authKeyID->authCertIssuer == NULL && - SECFailure == PORT_GetError ()) + authKeyID->authCertIssuer = CreateGeneralName(arena); + if (authKeyID->authCertIssuer == NULL && + SECFailure == PORT_GetError()) break; + rv = GetString(arena, "Enter value for the authCertSerial field, " + "enter to omit:", + &authKeyID->authCertSerialNumber); - rv = GetString (arena, "Enter value for the authCertSerial field, " - "enter to omit:", &authKeyID->authCertSerialNumber); - - yesNoAns = GetYesNo ("Is this a critical extension [y/N]?"); + yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, - authKeyID, yesNoAns, SEC_OID_X509_AUTH_KEY_ID, - (EXTEN_EXT_VALUE_ENCODER) CERT_EncodeAuthKeyID); + authKeyID, yesNoAns, SEC_OID_X509_AUTH_KEY_ID, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeAuthKeyID); if (rv) break; } while (0); if (arena) - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return (rv); -} - -static SECStatus -AddSubjKeyID (void *extHandle) +} + +static SECStatus +AddSubjKeyID(void *extHandle) { SECItem keyID; PLArenaPool *arena = NULL; @@ -1110,34 +1109,35 @@ AddSubjKeyID (void *extHandle) do { arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { SECU_PrintError(progName, "out of memory"); - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } printf("Adding Subject Key ID extension.\n"); - rv = GetString (arena, "Enter value for the key identifier fields," - "enter to omit:", &keyID); + rv = GetString(arena, "Enter value for the key identifier fields," + "enter to omit:", + &keyID); if (rv != SECSuccess) break; SECU_SECItemHexStringToBinary(&keyID); - yesNoAns = GetYesNo ("Is this a critical extension [y/N]?"); + yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, - &keyID, yesNoAns, SEC_OID_X509_SUBJECT_KEY_ID, - (EXTEN_EXT_VALUE_ENCODER) CERT_EncodeSubjectKeyID); + &keyID, yesNoAns, SEC_OID_X509_SUBJECT_KEY_ID, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeSubjectKeyID); if (rv) break; } while (0); if (arena) - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return (rv); -} +} -static SECStatus +static SECStatus AddCrlDistPoint(void *extHandle) { PLArenaPool *arena = NULL; @@ -1148,7 +1148,7 @@ AddCrlDistPoint(void *extHandle) char buffer[512]; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) + if (!arena) return (SECFailure); do { @@ -1156,8 +1156,8 @@ AddCrlDistPoint(void *extHandle) current = PORT_ArenaZNew(arena, CRLDistributionPoint); if (current == NULL) { - GEN_BREAK (SECFailure); - } + GEN_BREAK(SECFailure); + } /* Get the distributionPointName fields - this field is optional */ if (PrintChoicesAndGetAnswer( @@ -1165,36 +1165,36 @@ AddCrlDistPoint(void *extHandle) "\t1 - Full Name\n\t2 - Relative Name\n\tAny other " "number to finish\n\t\tChoice: ", buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); - } - intValue = PORT_Atoi (buffer); + GEN_BREAK(SECFailure); + } + intValue = PORT_Atoi(buffer); switch (intValue) { - case generalName: - current->distPointType = intValue; - current->distPoint.fullName = CreateGeneralName (arena); - rv = PORT_GetError(); - break; + case generalName: + current->distPointType = intValue; + current->distPoint.fullName = CreateGeneralName(arena); + rv = PORT_GetError(); + break; - case relativeDistinguishedName: { - CERTName *name; + case relativeDistinguishedName: { + CERTName *name; - current->distPointType = intValue; - puts ("Enter the relative name: "); - fflush (stdout); - if (Gets_s (buffer, sizeof(buffer)) == NULL) { - GEN_BREAK (SECFailure); - } - /* For simplicity, use CERT_AsciiToName to converse from a string + current->distPointType = intValue; + puts("Enter the relative name: "); + fflush(stdout); + if (Gets_s(buffer, sizeof(buffer)) == NULL) { + GEN_BREAK(SECFailure); + } + /* For simplicity, use CERT_AsciiToName to converse from a string to NAME, but we only interest in the first RDN */ - name = CERT_AsciiToName (buffer); - if (!name) { - GEN_BREAK (SECFailure); + name = CERT_AsciiToName(buffer); + if (!name) { + GEN_BREAK(SECFailure); + } + rv = CERT_CopyRDN(arena, ¤t->distPoint.relativeName, + name->rdns[0]); + CERT_DestroyName(name); + break; } - rv = CERT_CopyRDN (arena, ¤t->distPoint.relativeName, - name->rdns[0]); - CERT_DestroyName (name); - break; - } } if (rv != SECSuccess) break; @@ -1210,7 +1210,7 @@ AddCrlDistPoint(void *extHandle) buffer, sizeof(buffer)) == SECFailure) { GEN_BREAK(SECFailure); } - intValue = PORT_Atoi (buffer); + intValue = PORT_Atoi(buffer); if (intValue == 0) { /* Checking that zero value of variable 'value' * corresponds to '0' input made by user */ @@ -1219,65 +1219,62 @@ AddCrlDistPoint(void *extHandle) intValue = -1; } } - if (intValue >= 0 && intValue <8) { - current->reasons.data = PORT_ArenaAlloc (arena, sizeof(char)); + if (intValue >= 0 && intValue < 8) { + current->reasons.data = PORT_ArenaAlloc(arena, sizeof(char)); if (current->reasons.data == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } *current->reasons.data = (char)(0x80 >> intValue); current->reasons.len = 1; } - puts ("Enter value for the CRL Issuer name:\n"); - current->crlIssuer = CreateGeneralName (arena); + puts("Enter value for the CRL Issuer name:\n"); + current->crlIssuer = CreateGeneralName(arena); if (current->crlIssuer == NULL && (rv = PORT_GetError()) == SECFailure) break; if (crlDistPoints == NULL) { crlDistPoints = PORT_ArenaZNew(arena, CERTCrlDistributionPoints); if (crlDistPoints == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } } crlDistPoints->distPoints = - PORT_ArenaGrow (arena, crlDistPoints->distPoints, - sizeof (*crlDistPoints->distPoints) * count, - sizeof (*crlDistPoints->distPoints) *(count + 1)); + PORT_ArenaGrow(arena, crlDistPoints->distPoints, + sizeof(*crlDistPoints->distPoints) * count, + sizeof(*crlDistPoints->distPoints) * (count + 1)); if (crlDistPoints->distPoints == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } crlDistPoints->distPoints[count] = current; ++count; if (GetYesNo("Enter another value for the CRLDistributionPoint " - "extension [y/N]?") == 0) { + "extension [y/N]?") == 0) { /* Add null to the end to mark end of data */ crlDistPoints->distPoints = PORT_ArenaGrow(arena, crlDistPoints->distPoints, - sizeof (*crlDistPoints->distPoints) * count, - sizeof (*crlDistPoints->distPoints) *(count + 1)); - crlDistPoints->distPoints[count] = NULL; + sizeof(*crlDistPoints->distPoints) * count, + sizeof(*crlDistPoints->distPoints) * (count + 1)); + crlDistPoints->distPoints[count] = NULL; break; } - } while (1); - + if (rv == SECSuccess) { - PRBool yesNoAns = GetYesNo ("Is this a critical extension [y/N]?"); + PRBool yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, - crlDistPoints, yesNoAns, SEC_OID_X509_CRL_DIST_POINTS, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeCRLDistributionPoints); + crlDistPoints, yesNoAns, SEC_OID_X509_CRL_DIST_POINTS, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeCRLDistributionPoints); } if (arena) - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return (rv); } - - -static SECStatus +static SECStatus AddPolicyConstraints(void *extHandle) { CERTCertificatePolicyConstraints *policyConstr; @@ -1290,7 +1287,7 @@ AddPolicyConstraints(void *extHandle) PRBool skipExt = PR_TRUE; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { SECU_PrintError(progName, "out of memory"); return SECFailure; } @@ -1302,14 +1299,15 @@ AddPolicyConstraints(void *extHandle) } if (PrintChoicesAndGetAnswer("for requireExplicitPolicy enter the number " - "of certs in path\nbefore explicit policy is required\n" - "(press Enter to omit)", buffer, sizeof(buffer)) == SECFailure) { + "of certs in path\nbefore explicit policy is required\n" + "(press Enter to omit)", + buffer, sizeof(buffer)) == SECFailure) { goto loser; } if (PORT_Strlen(buffer)) { value = PORT_Atoi(buffer); - if (value < 0) { + if (value < 0) { goto loser; } item = &policyConstr->explicitPolicySkipCerts; @@ -1321,15 +1319,16 @@ AddPolicyConstraints(void *extHandle) } if (PrintChoicesAndGetAnswer("for inihibitPolicyMapping enter " - "the number of certs in path\n" - "after which policy mapping is not allowed\n" - "(press Enter to omit)", buffer, sizeof(buffer)) == SECFailure) { + "the number of certs in path\n" + "after which policy mapping is not allowed\n" + "(press Enter to omit)", + buffer, sizeof(buffer)) == SECFailure) { goto loser; } if (PORT_Strlen(buffer)) { value = PORT_Atoi(buffer); - if (value < 0) { + if (value < 0) { goto loser; } item = &policyConstr->inhibitMappingSkipCerts; @@ -1339,29 +1338,27 @@ AddPolicyConstraints(void *extHandle) } skipExt = PR_FALSE; } - - + if (!skipExt) { yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, policyConstr, - yesNoAns, SEC_OID_X509_POLICY_CONSTRAINTS, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodePolicyConstraintsExtension); + yesNoAns, SEC_OID_X509_POLICY_CONSTRAINTS, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodePolicyConstraintsExtension); } else { - fprintf(stdout, "Policy Constraint extensions must contain " + fprintf(stdout, "Policy Constraint extensions must contain " "at least one policy field\n"); - rv = SECFailure; + rv = SECFailure; } - + loser: if (arena) { - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return (rv); } - -static SECStatus +static SECStatus AddInhibitAnyPolicy(void *extHandle) { CERTCertificateInhibitAny certInhibitAny; @@ -1371,10 +1368,9 @@ AddInhibitAnyPolicy(void *extHandle) char buffer[10]; int value; PRBool yesNoAns; - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { SECU_PrintError(progName, "out of memory"); return SECFailure; } @@ -1395,21 +1391,20 @@ AddInhibitAnyPolicy(void *extHandle) if (!dummy) { goto loser; } - + yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); - + rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, &certInhibitAny, - yesNoAns, SEC_OID_X509_INHIBIT_ANY_POLICY, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeInhibitAnyExtension); + yesNoAns, SEC_OID_X509_INHIBIT_ANY_POLICY, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeInhibitAnyExtension); loser: if (arena) { - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return (rv); } - -static SECStatus +static SECStatus AddPolicyMappings(void *extHandle) { CERTPolicyMap **policyMapArr = NULL; @@ -1418,9 +1413,9 @@ AddPolicyMappings(void *extHandle) SECStatus rv = SECSuccess; int count = 0; char buffer[512]; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { SECU_PrintError(progName, "out of memory"); return SECFailure; } @@ -1429,7 +1424,7 @@ AddPolicyMappings(void *extHandle) if (PrintChoicesAndGetAnswer("Enter an Object Identifier (dotted " "decimal format) for Issuer Domain Policy", buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } current = PORT_ArenaZNew(arena, CERTPolicyMap); @@ -1445,7 +1440,7 @@ AddPolicyMappings(void *extHandle) if (PrintChoicesAndGetAnswer("Enter an Object Identifier for " "Subject Domain Policy", buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } rv = SEC_StringToOID(arena, ¤t->subjectDomainPolicy, buffer, 0); @@ -1456,29 +1451,29 @@ AddPolicyMappings(void *extHandle) if (policyMapArr == NULL) { policyMapArr = PORT_ArenaZNew(arena, CERTPolicyMap *); if (policyMapArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } } policyMapArr = PORT_ArenaGrow(arena, policyMapArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); + sizeof(current) * count, + sizeof(current) * (count + 1)); if (policyMapArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - + policyMapArr[count] = current; ++count; - + if (!GetYesNo("Enter another Policy Mapping [y/N]")) { /* Add null to the end to mark end of data */ - policyMapArr = PORT_ArenaGrow (arena, policyMapArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); + policyMapArr = PORT_ArenaGrow(arena, policyMapArr, + sizeof(current) * count, + sizeof(current) * (count + 1)); if (policyMapArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - policyMapArr[count] = NULL; + policyMapArr[count] = NULL; break; } @@ -1491,11 +1486,11 @@ AddPolicyMappings(void *extHandle) mappings.arena = arena; mappings.policyMaps = policyMapArr; rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, &mappings, - yesNoAns, SEC_OID_X509_POLICY_MAPPINGS, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodePolicyMappingExtension); + yesNoAns, SEC_OID_X509_POLICY_MAPPINGS, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodePolicyMappingExtension); } if (arena) - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return (rv); } @@ -1504,7 +1499,6 @@ enum PoliciQualifierEnum { userNotice = 2 }; - static CERTPolicyQualifier ** RequestPolicyQualifiers(PLArenaPool *arena, SECItem *policyID) { @@ -1528,175 +1522,178 @@ RequestPolicyQualifiers(PLArenaPool *arena, SECItem *policyID) /* Get the accessMethod fields */ SECU_PrintObjectID(stdout, policyID, - "Choose the type of qualifier for policy" , 0); + "Choose the type of qualifier for policy", 0); if (PrintChoicesAndGetAnswer( "\t1 - CPS Pointer qualifier\n" "\t2 - User notice qualifier\n" "\tAny other number to finish\n" - "\t\tChoice: ", buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); + "\t\tChoice: ", + buffer, sizeof(buffer)) == SECFailure) { + GEN_BREAK(SECFailure); } intValue = PORT_Atoi(buffer); switch (intValue) { - case cpsPointer: { - SECItem input; + case cpsPointer: { + SECItem input; - oid = SECOID_FindOIDByTag(SEC_OID_PKIX_CPS_POINTER_QUALIFIER); - if (PrintChoicesAndGetAnswer("Enter CPS pointer URI: ", - buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); - } - input.len = PORT_Strlen(buffer); - input.data = (void*)PORT_ArenaStrdup(arena, buffer); - if (input.data == NULL || - SEC_ASN1EncodeItem(arena, ¤t->qualifierValue, &input, - SEC_ASN1_GET(SEC_IA5StringTemplate)) == NULL) { - GEN_BREAK (SECFailure); - } - break; - } - case userNotice: { - SECItem **noticeNumArr; - CERTUserNotice *notice = PORT_ArenaZNew(arena, CERTUserNotice); - if (!notice) { - GEN_BREAK(SECFailure); + oid = SECOID_FindOIDByTag(SEC_OID_PKIX_CPS_POINTER_QUALIFIER); + if (PrintChoicesAndGetAnswer("Enter CPS pointer URI: ", + buffer, sizeof(buffer)) == SECFailure) { + GEN_BREAK(SECFailure); + } + input.len = PORT_Strlen(buffer); + input.data = (void *)PORT_ArenaStrdup(arena, buffer); + if (input.data == NULL || + SEC_ASN1EncodeItem(arena, ¤t->qualifierValue, &input, + SEC_ASN1_GET(SEC_IA5StringTemplate)) == NULL) { + GEN_BREAK(SECFailure); + } + break; } - - oid = SECOID_FindOIDByTag(SEC_OID_PKIX_USER_NOTICE_QUALIFIER); + case userNotice: { + SECItem **noticeNumArr; + CERTUserNotice *notice = PORT_ArenaZNew(arena, CERTUserNotice); + if (!notice) { + GEN_BREAK(SECFailure); + } - if (GetYesNo("\t add a User Notice reference? [y/N]")) { + oid = SECOID_FindOIDByTag(SEC_OID_PKIX_USER_NOTICE_QUALIFIER); - if (PrintChoicesAndGetAnswer("Enter user organization string: ", - buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); - } + if (GetYesNo("\t add a User Notice reference? [y/N]")) { - notice->noticeReference.organization.type = siAsciiString; - notice->noticeReference.organization.len = - PORT_Strlen(buffer); - notice->noticeReference.organization.data = - (void*)PORT_ArenaStrdup(arena, buffer); - - - noticeNumArr = PORT_ArenaZNewArray(arena, SECItem *, 2); - if (!noticeNumArr) { - GEN_BREAK (SECFailure); - } - - do { - SECItem *noticeNum; - - noticeNum = PORT_ArenaZNew(arena, SECItem); - - if (PrintChoicesAndGetAnswer( - "Enter User Notice reference number " - "(or -1 to quit): ", - buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); + if (PrintChoicesAndGetAnswer("Enter user organization string: ", + buffer, sizeof(buffer)) == + SECFailure) { + GEN_BREAK(SECFailure); + } + + notice->noticeReference.organization.type = siAsciiString; + notice->noticeReference.organization.len = + PORT_Strlen(buffer); + notice->noticeReference.organization.data = + (void *)PORT_ArenaStrdup(arena, buffer); + + noticeNumArr = PORT_ArenaZNewArray(arena, SECItem *, 2); + if (!noticeNumArr) { + GEN_BREAK(SECFailure); } - - intValue = PORT_Atoi(buffer); - if (noticeNum == NULL) { - if (intValue < 0) { - fprintf(stdout, "a noticeReference must have at " - "least one reference number\n"); - GEN_BREAK (SECFailure); - } - } else { - if (intValue >= 0) { - noticeNumArr = PORT_ArenaGrow(arena, noticeNumArr, - sizeof (current) * inCount, - sizeof (current) *(inCount + 1)); - if (noticeNumArr == NULL) { - GEN_BREAK (SECFailure); + + do { + SECItem *noticeNum; + + noticeNum = PORT_ArenaZNew(arena, SECItem); + + if (PrintChoicesAndGetAnswer( + "Enter User Notice reference number " + "(or -1 to quit): ", + buffer, sizeof(buffer)) == SECFailure) { + GEN_BREAK(SECFailure); + } + + intValue = PORT_Atoi(buffer); + if (noticeNum == NULL) { + if (intValue < 0) { + fprintf(stdout, "a noticeReference must have at " + "least one reference number\n"); + GEN_BREAK(SECFailure); } - } else { - break; - } + } else { + if (intValue >= 0) { + noticeNumArr = PORT_ArenaGrow(arena, noticeNumArr, + sizeof(current) * + inCount, + sizeof(current) * + (inCount + 1)); + if (noticeNumArr == NULL) { + GEN_BREAK(SECFailure); + } + } else { + break; + } + } + if (!SEC_ASN1EncodeInteger(arena, noticeNum, intValue)) { + GEN_BREAK(SECFailure); + } + noticeNumArr[inCount++] = noticeNum; + noticeNumArr[inCount] = NULL; + + } while (1); + if (rv == SECFailure) { + GEN_BREAK(SECFailure); + } + notice->noticeReference.noticeNumbers = noticeNumArr; + rv = CERT_EncodeNoticeReference(arena, ¬ice->noticeReference, + ¬ice->derNoticeReference); + if (rv == SECFailure) { + GEN_BREAK(SECFailure); } - if (!SEC_ASN1EncodeInteger(arena, noticeNum, intValue)) { - GEN_BREAK (SECFailure); - } - noticeNumArr[inCount++] = noticeNum; - noticeNumArr[inCount] = NULL; - - } while (1); - if (rv == SECFailure) { - GEN_BREAK(SECFailure); } - notice->noticeReference.noticeNumbers = noticeNumArr; - rv = CERT_EncodeNoticeReference(arena, ¬ice->noticeReference, - ¬ice->derNoticeReference); + if (GetYesNo("\t EnterUser Notice explicit text? [y/N]")) { + /* Getting only 200 bytes - RFC limitation */ + if (PrintChoicesAndGetAnswer( + "\t", buffer, 200) == SECFailure) { + GEN_BREAK(SECFailure); + } + notice->displayText.type = siAsciiString; + notice->displayText.len = PORT_Strlen(buffer); + notice->displayText.data = + (void *)PORT_ArenaStrdup(arena, buffer); + if (notice->displayText.data == NULL) { + GEN_BREAK(SECFailure); + } + } + + rv = CERT_EncodeUserNotice(arena, notice, ¤t->qualifierValue); if (rv == SECFailure) { GEN_BREAK(SECFailure); } - } - if (GetYesNo("\t EnterUser Notice explicit text? [y/N]")) { - /* Getting only 200 bytes - RFC limitation */ - if (PrintChoicesAndGetAnswer( - "\t", buffer, 200) == SECFailure) { - GEN_BREAK (SECFailure); - } - notice->displayText.type = siAsciiString; - notice->displayText.len = PORT_Strlen(buffer); - notice->displayText.data = - (void*)PORT_ArenaStrdup(arena, buffer); - if (notice->displayText.data == NULL) { - GEN_BREAK(SECFailure); - } - } - rv = CERT_EncodeUserNotice(arena, notice, ¤t->qualifierValue); - if (rv == SECFailure) { - GEN_BREAK(SECFailure); + break; } - - break; - } } if (rv == SECFailure || oid == NULL || - SECITEM_CopyItem(arena, ¤t->qualifierID, &oid->oid) - == SECFailure) { - GEN_BREAK (SECFailure); + SECITEM_CopyItem(arena, ¤t->qualifierID, &oid->oid) == + SECFailure) { + GEN_BREAK(SECFailure); } if (!policyQualifArr) { policyQualifArr = PORT_ArenaZNew(arena, CERTPolicyQualifier *); } else { - policyQualifArr = PORT_ArenaGrow (arena, policyQualifArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); - } + policyQualifArr = PORT_ArenaGrow(arena, policyQualifArr, + sizeof(current) * count, + sizeof(current) * (count + 1)); + } if (policyQualifArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - + policyQualifArr[count] = current; ++count; - if (!GetYesNo ("Enter another policy qualifier [y/N]")) { + if (!GetYesNo("Enter another policy qualifier [y/N]")) { /* Add null to the end to mark end of data */ policyQualifArr = PORT_ArenaGrow(arena, policyQualifArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); + sizeof(current) * count, + sizeof(current) * (count + 1)); if (policyQualifArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - policyQualifArr[count] = NULL; + policyQualifArr[count] = NULL; break; } } while (1); if (rv != SECSuccess) { - PORT_ArenaRelease (arena, mark); + PORT_ArenaRelease(arena, mark); policyQualifArr = NULL; } return (policyQualifArr); } -static SECStatus +static SECStatus AddCertPolicies(void *extHandle) { CERTPolicyInfo **certPoliciesArr = NULL; @@ -1707,7 +1704,7 @@ AddCertPolicies(void *extHandle) char buffer[512]; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { SECU_PrintError(progName, "out of memory"); return SECFailure; } @@ -1720,47 +1717,47 @@ AddCertPolicies(void *extHandle) if (PrintChoicesAndGetAnswer("Enter a CertPolicy Object Identifier " "(dotted decimal format)\n" - "or \"any\" for AnyPolicy:", + "or \"any\" for AnyPolicy:", buffer, sizeof(buffer)) == SECFailure) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); + } + + if (strncmp(buffer, "any", 3) == 0) { + /* use string version of X509_CERTIFICATE_POLICIES.anyPolicy */ + strcpy(buffer, "OID.2.5.29.32.0"); } - - if (strncmp(buffer, "any", 3) == 0) { - /* use string version of X509_CERTIFICATE_POLICIES.anyPolicy */ - strcpy(buffer, "OID.2.5.29.32.0"); - } rv = SEC_StringToOID(arena, ¤t->policyID, buffer, 0); if (rv == SECFailure) { GEN_BREAK(SECFailure); } - - current->policyQualifiers = - RequestPolicyQualifiers(arena, ¤t->policyID); + + current->policyQualifiers = + RequestPolicyQualifiers(arena, ¤t->policyID); if (!certPoliciesArr) { certPoliciesArr = PORT_ArenaZNew(arena, CERTPolicyInfo *); } else { - certPoliciesArr = PORT_ArenaGrow(arena, certPoliciesArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); - } + certPoliciesArr = PORT_ArenaGrow(arena, certPoliciesArr, + sizeof(current) * count, + sizeof(current) * (count + 1)); + } if (certPoliciesArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - + certPoliciesArr[count] = current; ++count; - - if (!GetYesNo ("Enter another PolicyInformation field [y/N]?")) { + + if (!GetYesNo("Enter another PolicyInformation field [y/N]?")) { /* Add null to the end to mark end of data */ certPoliciesArr = PORT_ArenaGrow(arena, certPoliciesArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); + sizeof(current) * count, + sizeof(current) * (count + 1)); if (certPoliciesArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - certPoliciesArr[count] = NULL; + certPoliciesArr[count] = NULL; break; } @@ -1772,13 +1769,13 @@ AddCertPolicies(void *extHandle) policies.arena = arena; policies.policyInfos = certPoliciesArr; - + rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, &policies, - yesNoAns, SEC_OID_X509_CERTIFICATE_POLICIES, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeCertPoliciesExtension); + yesNoAns, SEC_OID_X509_CERTIFICATE_POLICIES, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeCertPoliciesExtension); } if (arena) - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return (rv); } @@ -1791,9 +1788,9 @@ enum SubjInfoAccessTypesEnum { caRepository = 1, timeStamping = 2 }; - + /* Encode and add an AIA or SIA extension */ -static SECStatus +static SECStatus AddInfoAccess(void *extHandle, PRBool addSIAExt, PRBool isCACert) { CERTAuthInfoAccess **infoAccArr = NULL; @@ -1806,7 +1803,7 @@ AddInfoAccess(void *extHandle, PRBool addSIAExt, PRBool isCACert) int intValue = 0; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { + if (!arena) { SECU_PrintError(progName, "out of memory"); return SECFailure; } @@ -1822,82 +1819,83 @@ AddInfoAccess(void *extHandle, PRBool addSIAExt, PRBool isCACert) if (addSIAExt) { if (isCACert) { puts("Adding \"CA Repository\" access method type for " - "Subject Information Access extension:\n"); + "Subject Information Access extension:\n"); intValue = caRepository; } else { puts("Adding \"Time Stamping Services\" access method type for " - "Subject Information Access extension:\n"); + "Subject Information Access extension:\n"); intValue = timeStamping; } } else { if (PrintChoicesAndGetAnswer("Enter access method type " - "for Authority Information Access extension:\n" - "\t1 - CA Issuers\n\t2 - OCSP\n\tAny" - "other number to finish\n\tChoice", - buffer, sizeof(buffer)) != SECSuccess) { - GEN_BREAK (SECFailure); + "for Authority Information Access extension:\n" + "\t1 - CA Issuers\n\t2 - OCSP\n\tAny" + "other number to finish\n\tChoice", + buffer, sizeof(buffer)) != + SECSuccess) { + GEN_BREAK(SECFailure); } intValue = PORT_Atoi(buffer); } if (addSIAExt) { switch (intValue) { - case caRepository: - oid = SECOID_FindOIDByTag(SEC_OID_PKIX_CA_REPOSITORY); - break; - - case timeStamping: - oid = SECOID_FindOIDByTag(SEC_OID_PKIX_TIMESTAMPING); - break; - } + case caRepository: + oid = SECOID_FindOIDByTag(SEC_OID_PKIX_CA_REPOSITORY); + break; + + case timeStamping: + oid = SECOID_FindOIDByTag(SEC_OID_PKIX_TIMESTAMPING); + break; + } } else { switch (intValue) { - case caIssuers: - oid = SECOID_FindOIDByTag(SEC_OID_PKIX_CA_ISSUERS); - break; - - case ocsp: - oid = SECOID_FindOIDByTag(SEC_OID_PKIX_OCSP); - break; - } + case caIssuers: + oid = SECOID_FindOIDByTag(SEC_OID_PKIX_CA_ISSUERS); + break; + + case ocsp: + oid = SECOID_FindOIDByTag(SEC_OID_PKIX_OCSP); + break; + } } if (oid == NULL || - SECITEM_CopyItem(arena, ¤t->method, &oid->oid) - == SECFailure) { - GEN_BREAK (SECFailure); + SECITEM_CopyItem(arena, ¤t->method, &oid->oid) == + SECFailure) { + GEN_BREAK(SECFailure); } current->location = CreateGeneralName(arena); if (!current->location) { GEN_BREAK(SECFailure); } - + if (infoAccArr == NULL) { infoAccArr = PORT_ArenaZNew(arena, CERTAuthInfoAccess *); } else { - infoAccArr = PORT_ArenaGrow(arena, infoAccArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); - } + infoAccArr = PORT_ArenaGrow(arena, infoAccArr, + sizeof(current) * count, + sizeof(current) * (count + 1)); + } if (infoAccArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - + infoAccArr[count] = current; ++count; - + PR_snprintf(buffer, sizeof(buffer), "Add another location to the %s" - " Information Access extension [y/N]", + " Information Access extension [y/N]", (addSIAExt) ? "Subject" : "Authority"); - if (GetYesNo (buffer) == 0) { + if (GetYesNo(buffer) == 0) { /* Add null to the end to mark end of data */ infoAccArr = PORT_ArenaGrow(arena, infoAccArr, - sizeof (current) * count, - sizeof (current) *(count + 1)); + sizeof(current) * count, + sizeof(current) * (count + 1)); if (infoAccArr == NULL) { - GEN_BREAK (SECFailure); + GEN_BREAK(SECFailure); } - infoAccArr[count] = NULL; + infoAccArr[count] = NULL; break; } @@ -1907,13 +1905,13 @@ AddInfoAccess(void *extHandle, PRBool addSIAExt, PRBool isCACert) int oidIdent = SEC_OID_X509_AUTH_INFO_ACCESS; PRBool yesNoAns = GetYesNo("Is this a critical extension [y/N]?"); - + if (addSIAExt) { oidIdent = SEC_OID_X509_SUBJECT_INFO_ACCESS; } rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, infoAccArr, - yesNoAns, oidIdent, - (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeInfoAccessExtension); + yesNoAns, oidIdent, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeInfoAccessExtension); } if (arena) PORT_FreeArena(arena, PR_FALSE); @@ -1932,7 +1930,7 @@ parseNextGenericExt(const char *nextExtension, const char **oid, int *oidLen, const char *nextColon; const char *nextComma; const char *iter = nextExtension; - + if (!iter || !*iter) return SECFailure; @@ -1987,33 +1985,33 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames, SECStatus rv = SECSuccess; char *errstring = NULL; const char *nextExtension = NULL; - + do { /* Add key usage extension */ if (extList[ext_keyUsage].activated) { rv = AddKeyUsage(extHandle, extList[ext_keyUsage].arg); if (rv) { - errstring = "KeyUsage"; + errstring = "KeyUsage"; break; - } + } } /* Add extended key usage extension */ if (extList[ext_extKeyUsage].activated) { rv = AddExtKeyUsage(extHandle, extList[ext_extKeyUsage].arg); if (rv) { - errstring = "ExtendedKeyUsage"; + errstring = "ExtendedKeyUsage"; break; - } + } } /* Add basic constraint extension */ if (extList[ext_basicConstraint].activated) { rv = AddBasicConstraint(extHandle); if (rv) { - errstring = "BasicConstraint"; + errstring = "BasicConstraint"; break; - } + } } /* Add name constraints extension */ @@ -2028,88 +2026,88 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames, if (extList[ext_authorityKeyID].activated) { rv = AddAuthKeyID(extHandle); if (rv) { - errstring = "AuthorityKeyID"; + errstring = "AuthorityKeyID"; break; - } + } } if (extList[ext_subjectKeyID].activated) { rv = AddSubjKeyID(extHandle); if (rv) { - errstring = "SubjectKeyID"; + errstring = "SubjectKeyID"; break; - } - } + } + } if (extList[ext_CRLDistPts].activated) { rv = AddCrlDistPoint(extHandle); if (rv) { - errstring = "CRLDistPoints"; + errstring = "CRLDistPoints"; break; - } + } } if (extList[ext_NSCertType].activated) { rv = AddNscpCertType(extHandle, extList[ext_NSCertType].arg); if (rv) { - errstring = "NSCertType"; + errstring = "NSCertType"; break; - } + } } if (extList[ext_authInfoAcc].activated || extList[ext_subjInfoAcc].activated) { rv = AddInfoAccess(extHandle, extList[ext_subjInfoAcc].activated, - extList[ext_basicConstraint].activated); + extList[ext_basicConstraint].activated); if (rv) { - errstring = "InformationAccess"; + errstring = "InformationAccess"; break; - } + } } if (extList[ext_certPolicies].activated) { rv = AddCertPolicies(extHandle); if (rv) { - errstring = "Policies"; + errstring = "Policies"; break; - } + } } if (extList[ext_policyMappings].activated) { rv = AddPolicyMappings(extHandle); if (rv) { - errstring = "PolicyMappings"; + errstring = "PolicyMappings"; break; - } + } } if (extList[ext_policyConstr].activated) { rv = AddPolicyConstraints(extHandle); if (rv) { - errstring = "PolicyConstraints"; + errstring = "PolicyConstraints"; break; - } + } } if (extList[ext_inhibitAnyPolicy].activated) { rv = AddInhibitAnyPolicy(extHandle); if (rv) { - errstring = "InhibitAnyPolicy"; + errstring = "InhibitAnyPolicy"; break; - } + } } if (emailAddrs || dnsNames || extList[ext_subjectAltName].activated) { PLArenaPool *arena; CERTGeneralName *namelist = NULL; SECItem item = { 0, NULL, 0 }; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { rv = SECFailure; break; } - + rv = SECSuccess; if (emailAddrs) { @@ -2121,26 +2119,26 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames, } if (extList[ext_subjectAltName].activated) { - rv |= AddGeneralSubjectAlt(arena, &namelist, + rv |= AddGeneralSubjectAlt(arena, &namelist, extList[ext_subjectAltName].arg); } if (rv == SECSuccess) { - rv = CERT_EncodeAltNameExtension(arena, namelist, &item); - if (rv == SECSuccess) { + rv = CERT_EncodeAltNameExtension(arena, namelist, &item); + if (rv == SECSuccess) { rv = CERT_AddExtension(extHandle, - SEC_OID_X509_SUBJECT_ALT_NAME, - &item, PR_FALSE, PR_TRUE); - } + SEC_OID_X509_SUBJECT_ALT_NAME, + &item, PR_FALSE, PR_TRUE); + } } - PORT_FreeArena(arena, PR_FALSE); - if (rv) { + PORT_FreeArena(arena, PR_FALSE); + if (rv) { errstring = "SubjectAltName"; break; - } + } } } while (0); - + if (rv != SECSuccess) { SECU_PrintError(progName, "Problem creating %s extension", errstring); } @@ -2156,7 +2154,7 @@ AddExtensions(void *extHandle, const char *emailAddrs, const char *dnsNames, rv = parseNextGenericExt(nextExtension, &oid, &oidLen, &crit, &critLen, &filename, &filenameLen, &next); - if (rv!= SECSuccess) { + if (rv != SECSuccess) { SECU_PrintError(progName, "error parsing generic extension parameter %s", nextExtension); diff --git a/cmd/certutil/certutil.c b/cmd/certutil/certutil.c index da8ae17a92..c15897e719 100644 --- a/cmd/certutil/certutil.c +++ b/cmd/certutil/certutil.c @@ -37,12 +37,14 @@ #include "nss.h" #include "certutil.h" -#define MIN_KEY_BITS 512 +#define MIN_KEY_BITS 512 /* MAX_KEY_BITS should agree with MAX_RSA_MODULUS in freebl */ -#define MAX_KEY_BITS 8192 -#define DEFAULT_KEY_BITS 2048 +#define MAX_KEY_BITS 8192 +#define DEFAULT_KEY_BITS 2048 -#define GEN_BREAK(e) rv=e; break; +#define GEN_BREAK(e) \ + rv = e; \ + break; char *progName; @@ -55,49 +57,48 @@ GetCertRequest(const SECItem *reqDER) SECStatus rv; do { - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - GEN_BREAK (SECFailure); - } - - certReq = (CERTCertificateRequest*) PORT_ArenaZAlloc - (arena, sizeof(CERTCertificateRequest)); - if (!certReq) { - GEN_BREAK(SECFailure); - } - certReq->arena = arena; - - /* Since cert request is a signed data, must decode to get the inner - data - */ - PORT_Memset(&signedData, 0, sizeof(signedData)); - rv = SEC_ASN1DecodeItem(arena, &signedData, - SEC_ASN1_GET(CERT_SignedDataTemplate), reqDER); - if (rv) { - break; - } - rv = SEC_ASN1DecodeItem(arena, certReq, - SEC_ASN1_GET(CERT_CertificateRequestTemplate), &signedData.data); - if (rv) { - break; - } - rv = CERT_VerifySignedDataWithPublicKeyInfo(&signedData, - &certReq->subjectPublicKeyInfo, NULL /* wincx */); - } while (0); - - if (rv) { - SECU_PrintError(progName, "bad certificate request\n"); - if (arena) { - PORT_FreeArena(arena, PR_FALSE); - } - certReq = NULL; - } - - return certReq; + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (arena == NULL) { + GEN_BREAK(SECFailure); + } + + certReq = (CERTCertificateRequest *)PORT_ArenaZAlloc(arena, sizeof(CERTCertificateRequest)); + if (!certReq) { + GEN_BREAK(SECFailure); + } + certReq->arena = arena; + + /* Since cert request is a signed data, must decode to get the inner + data + */ + PORT_Memset(&signedData, 0, sizeof(signedData)); + rv = SEC_ASN1DecodeItem(arena, &signedData, + SEC_ASN1_GET(CERT_SignedDataTemplate), reqDER); + if (rv) { + break; + } + rv = SEC_ASN1DecodeItem(arena, certReq, + SEC_ASN1_GET(CERT_CertificateRequestTemplate), &signedData.data); + if (rv) { + break; + } + rv = CERT_VerifySignedDataWithPublicKeyInfo(&signedData, + &certReq->subjectPublicKeyInfo, NULL /* wincx */); + } while (0); + + if (rv) { + SECU_PrintError(progName, "bad certificate request\n"); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); + } + certReq = NULL; + } + + return certReq; } static SECStatus -AddCert(PK11SlotInfo *slot, CERTCertDBHandle *handle, char *name, char *trusts, +AddCert(PK11SlotInfo *slot, CERTCertDBHandle *handle, char *name, char *trusts, const SECItem *certDER, PRBool emailcert, void *pwdata) { CERTCertTrust *trust = NULL; @@ -105,74 +106,74 @@ AddCert(PK11SlotInfo *slot, CERTCertDBHandle *handle, char *name, char *trusts, SECStatus rv; do { - /* Read in an ASCII cert and return a CERTCertificate */ - cert = CERT_DecodeCertFromPackage((char *)certDER->data, certDER->len); - if (!cert) { - SECU_PrintError(progName, "could not decode certificate"); - GEN_BREAK(SECFailure); - } - - /* Create a cert trust */ - trust = (CERTCertTrust *)PORT_ZAlloc(sizeof(CERTCertTrust)); - if (!trust) { - SECU_PrintError(progName, "unable to allocate cert trust"); - GEN_BREAK(SECFailure); - } - - rv = CERT_DecodeTrustString(trust, trusts); - if (rv) { - SECU_PrintError(progName, "unable to decode trust string"); - GEN_BREAK(SECFailure); - } - - rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE); - if (rv != SECSuccess) { - /* sigh, PK11_Import Cert and CERT_ChangeCertTrust should have - * been coded to take a password arg. */ - if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { - rv = PK11_Authenticate(slot, PR_TRUE, pwdata); - if (rv != SECSuccess) { - SECU_PrintError(progName, - "could not authenticate to token %s.", - PK11_GetTokenName(slot)); - GEN_BREAK(SECFailure); - } - rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, - name, PR_FALSE); - } - if (rv != SECSuccess) { - SECU_PrintError(progName, - "could not add certificate to token or database"); - GEN_BREAK(SECFailure); - } - } - - rv = CERT_ChangeCertTrust(handle, cert, trust); - if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { - rv = PK11_Authenticate(slot, PR_TRUE, pwdata); - if (rv != SECSuccess) { - SECU_PrintError(progName, - "could not authenticate to token %s.", - PK11_GetTokenName(slot)); - GEN_BREAK(SECFailure); - } - rv = CERT_ChangeCertTrust(handle, cert, trust); - } - if (rv != SECSuccess) { - SECU_PrintError(progName, - "could not change trust on certificate"); - GEN_BREAK(SECFailure); - } - } - - if ( emailcert ) { - CERT_SaveSMimeProfile(cert, NULL, pwdata); - } + /* Read in an ASCII cert and return a CERTCertificate */ + cert = CERT_DecodeCertFromPackage((char *)certDER->data, certDER->len); + if (!cert) { + SECU_PrintError(progName, "could not decode certificate"); + GEN_BREAK(SECFailure); + } + + /* Create a cert trust */ + trust = (CERTCertTrust *)PORT_ZAlloc(sizeof(CERTCertTrust)); + if (!trust) { + SECU_PrintError(progName, "unable to allocate cert trust"); + GEN_BREAK(SECFailure); + } + + rv = CERT_DecodeTrustString(trust, trusts); + if (rv) { + SECU_PrintError(progName, "unable to decode trust string"); + GEN_BREAK(SECFailure); + } + + rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, name, PR_FALSE); + if (rv != SECSuccess) { + /* sigh, PK11_Import Cert and CERT_ChangeCertTrust should have + * been coded to take a password arg. */ + if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { + rv = PK11_Authenticate(slot, PR_TRUE, pwdata); + if (rv != SECSuccess) { + SECU_PrintError(progName, + "could not authenticate to token %s.", + PK11_GetTokenName(slot)); + GEN_BREAK(SECFailure); + } + rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, + name, PR_FALSE); + } + if (rv != SECSuccess) { + SECU_PrintError(progName, + "could not add certificate to token or database"); + GEN_BREAK(SECFailure); + } + } + + rv = CERT_ChangeCertTrust(handle, cert, trust); + if (rv != SECSuccess) { + if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { + rv = PK11_Authenticate(slot, PR_TRUE, pwdata); + if (rv != SECSuccess) { + SECU_PrintError(progName, + "could not authenticate to token %s.", + PK11_GetTokenName(slot)); + GEN_BREAK(SECFailure); + } + rv = CERT_ChangeCertTrust(handle, cert, trust); + } + if (rv != SECSuccess) { + SECU_PrintError(progName, + "could not change trust on certificate"); + GEN_BREAK(SECFailure); + } + } + + if (emailcert) { + CERT_SaveSMimeProfile(cert, NULL, pwdata); + } } while (0); - CERT_DestroyCertificate (cert); + CERT_DestroyCertificate(cert); PORT_Free(trust); return rv; @@ -181,7 +182,7 @@ AddCert(PK11SlotInfo *slot, CERTCertDBHandle *handle, char *name, char *trusts, static SECStatus CertReq(SECKEYPrivateKey *privk, SECKEYPublicKey *pubk, KeyType keyType, SECOidTag hashAlgTag, CERTName *subject, const char *phone, int ascii, - const char *emailAddrs, const char *dnsNames, + const char *emailAddrs, const char *dnsNames, certutilExtnList extnList, const char *extGeneric, /*out*/ SECItem *result) { @@ -197,32 +198,32 @@ CertReq(SECKEYPrivateKey *privk, SECKEYPublicKey *pubk, KeyType keyType, /* Create info about public key */ spki = SECKEY_CreateSubjectPublicKeyInfo(pubk); if (!spki) { - SECU_PrintError(progName, "unable to create subject public key"); - return SECFailure; + SECU_PrintError(progName, "unable to create subject public key"); + return SECFailure; } - + /* Generate certificate request */ cr = CERT_CreateCertificateRequest(subject, spki, NULL); SECKEY_DestroySubjectPublicKeyInfo(spki); if (!cr) { - SECU_PrintError(progName, "unable to make certificate request"); - return SECFailure; + SECU_PrintError(progName, "unable to make certificate request"); + return SECFailure; } arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - SECU_PrintError(progName, "out of memory"); - return SECFailure; + if (!arena) { + SECU_PrintError(progName, "out of memory"); + return SECFailure; } - + extHandle = CERT_StartCertificateRequestAttributes(cr); if (extHandle == NULL) { - PORT_FreeArena (arena, PR_FALSE); - return SECFailure; + PORT_FreeArena(arena, PR_FALSE); + return SECFailure; } - if (AddExtensions(extHandle, emailAddrs, dnsNames, extnList, extGeneric) - != SECSuccess) { - PORT_FreeArena (arena, PR_FALSE); + if (AddExtensions(extHandle, emailAddrs, dnsNames, extnList, extGeneric) != + SECSuccess) { + PORT_FreeArena(arena, PR_FALSE); return SECFailure; } CERT_FinishExtensions(extHandle); @@ -233,158 +234,159 @@ CertReq(SECKEYPrivateKey *privk, SECKEYPublicKey *pubk, KeyType keyType, SEC_ASN1_GET(CERT_CertificateRequestTemplate)); CERT_DestroyCertificateRequest(cr); if (encoding == NULL) { - PORT_FreeArena (arena, PR_FALSE); - SECU_PrintError(progName, "der encoding of request failed"); - return SECFailure; + PORT_FreeArena(arena, PR_FALSE); + SECU_PrintError(progName, "der encoding of request failed"); + return SECFailure; } /* Sign the request */ signAlgTag = SEC_GetSignatureAlgorithmOidTag(keyType, hashAlgTag); if (signAlgTag == SEC_OID_UNKNOWN) { - PORT_FreeArena (arena, PR_FALSE); - SECU_PrintError(progName, "unknown Key or Hash type"); - return SECFailure; + PORT_FreeArena(arena, PR_FALSE); + SECU_PrintError(progName, "unknown Key or Hash type"); + return SECFailure; } rv = SEC_DerSignData(arena, &signedReq, encoding->data, encoding->len, - privk, signAlgTag); + privk, signAlgTag); if (rv) { - PORT_FreeArena (arena, PR_FALSE); - SECU_PrintError(progName, "signing of data failed"); - return SECFailure; + PORT_FreeArena(arena, PR_FALSE); + SECU_PrintError(progName, "signing of data failed"); + return SECFailure; } /* Encode request in specified format */ if (ascii) { - char *obuf; - char *header, *name, *email, *org, *state, *country; - - obuf = BTOA_ConvertItemToAscii(&signedReq); - if (!obuf) { - goto oom; - } - - name = CERT_GetCommonName(subject); - if (!name) { - name = PORT_Strdup("(not specified)"); - } - - if (!phone) - phone = "(not specified)"; - - email = CERT_GetCertEmailAddress(subject); - if (!email) - email = PORT_Strdup("(not specified)"); - - org = CERT_GetOrgName(subject); - if (!org) - org = PORT_Strdup("(not specified)"); - - state = CERT_GetStateName(subject); - if (!state) - state = PORT_Strdup("(not specified)"); - - country = CERT_GetCountryName(subject); - if (!country) - country = PORT_Strdup("(not specified)"); - - header = PR_smprintf( - "\nCertificate request generated by Netscape certutil\n" - "Phone: %s\n\n" - "Common Name: %s\n" - "Email: %s\n" - "Organization: %s\n" - "State: %s\n" - "Country: %s\n\n" - "%s\n", - phone, name, email, org, state, country, NS_CERTREQ_HEADER); - - PORT_Free(name); - PORT_Free(email); - PORT_Free(org); - PORT_Free(state); - PORT_Free(country); - - if (header) { - char * trailer = PR_smprintf("\n%s\n", NS_CERTREQ_TRAILER); - if (trailer) { - PRUint32 headerLen = PL_strlen(header); - PRUint32 obufLen = PL_strlen(obuf); - PRUint32 trailerLen = PL_strlen(trailer); - SECITEM_AllocItem(NULL, result, - headerLen + obufLen + trailerLen); - if (result->data) { - PORT_Memcpy(result->data, header, headerLen); - PORT_Memcpy(result->data + headerLen, obuf, obufLen); - PORT_Memcpy(result->data + headerLen + obufLen, - trailer, trailerLen); - } - PR_smprintf_free(trailer); - } - PR_smprintf_free(header); - } - PORT_Free(obuf); + char *obuf; + char *header, *name, *email, *org, *state, *country; + + obuf = BTOA_ConvertItemToAscii(&signedReq); + if (!obuf) { + goto oom; + } + + name = CERT_GetCommonName(subject); + if (!name) { + name = PORT_Strdup("(not specified)"); + } + + if (!phone) + phone = "(not specified)"; + + email = CERT_GetCertEmailAddress(subject); + if (!email) + email = PORT_Strdup("(not specified)"); + + org = CERT_GetOrgName(subject); + if (!org) + org = PORT_Strdup("(not specified)"); + + state = CERT_GetStateName(subject); + if (!state) + state = PORT_Strdup("(not specified)"); + + country = CERT_GetCountryName(subject); + if (!country) + country = PORT_Strdup("(not specified)"); + + header = PR_smprintf( + "\nCertificate request generated by Netscape certutil\n" + "Phone: %s\n\n" + "Common Name: %s\n" + "Email: %s\n" + "Organization: %s\n" + "State: %s\n" + "Country: %s\n\n" + "%s\n", + phone, name, email, org, state, country, NS_CERTREQ_HEADER); + + PORT_Free(name); + PORT_Free(email); + PORT_Free(org); + PORT_Free(state); + PORT_Free(country); + + if (header) { + char *trailer = PR_smprintf("\n%s\n", NS_CERTREQ_TRAILER); + if (trailer) { + PRUint32 headerLen = PL_strlen(header); + PRUint32 obufLen = PL_strlen(obuf); + PRUint32 trailerLen = PL_strlen(trailer); + SECITEM_AllocItem(NULL, result, + headerLen + obufLen + trailerLen); + if (result->data) { + PORT_Memcpy(result->data, header, headerLen); + PORT_Memcpy(result->data + headerLen, obuf, obufLen); + PORT_Memcpy(result->data + headerLen + obufLen, + trailer, trailerLen); + } + PR_smprintf_free(trailer); + } + PR_smprintf_free(header); + } + PORT_Free(obuf); } else { - (void) SECITEM_CopyItem(NULL, result, &signedReq); + (void)SECITEM_CopyItem(NULL, result, &signedReq); } if (!result->data) { -oom: SECU_PrintError(progName, "out of memory"); - PORT_SetError(SEC_ERROR_NO_MEMORY); - rv = SECFailure; + oom: + SECU_PrintError(progName, "out of memory"); + PORT_SetError(SEC_ERROR_NO_MEMORY); + rv = SECFailure; } - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return rv; } -static SECStatus +static SECStatus ChangeTrustAttributes(CERTCertDBHandle *handle, PK11SlotInfo *slot, - char *name, char *trusts, void *pwdata) + char *name, char *trusts, void *pwdata) { SECStatus rv; CERTCertificate *cert; CERTCertTrust *trust; - + cert = CERT_FindCertByNicknameOrEmailAddr(handle, name); if (!cert) { - SECU_PrintError(progName, "could not find certificate named \"%s\"", - name); - return SECFailure; + SECU_PrintError(progName, "could not find certificate named \"%s\"", + name); + return SECFailure; } trust = (CERTCertTrust *)PORT_ZAlloc(sizeof(CERTCertTrust)); if (!trust) { - SECU_PrintError(progName, "unable to allocate cert trust"); - return SECFailure; + SECU_PrintError(progName, "unable to allocate cert trust"); + return SECFailure; } /* This function only decodes these characters: pPwcTCu, */ rv = CERT_DecodeTrustString(trust, trusts); if (rv) { - SECU_PrintError(progName, "unable to decode trust string"); - return SECFailure; + SECU_PrintError(progName, "unable to decode trust string"); + return SECFailure; } /* CERT_ChangeCertTrust API does not have a way to pass in * a context, so NSS can't prompt for the password if it needs to. - * check to see if the failure was token not logged in and + * check to see if the failure was token not logged in and * log in if need be. */ rv = CERT_ChangeCertTrust(handle, cert, trust); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { - rv = PK11_Authenticate(slot, PR_TRUE, pwdata); - if (rv != SECSuccess) { - SECU_PrintError(progName, "could not authenticate to token %s.", + if (PORT_GetError() == SEC_ERROR_TOKEN_NOT_LOGGED_IN) { + rv = PK11_Authenticate(slot, PR_TRUE, pwdata); + if (rv != SECSuccess) { + SECU_PrintError(progName, "could not authenticate to token %s.", PK11_GetTokenName(slot)); - return SECFailure; - } - rv = CERT_ChangeCertTrust(handle, cert, trust); - } - if (rv != SECSuccess) { - SECU_PrintError(progName, "unable to modify trust attributes"); - return SECFailure; - } + return SECFailure; + } + rv = CERT_ChangeCertTrust(handle, cert, trust); + } + if (rv != SECSuccess) { + SECU_PrintError(progName, "unable to modify trust attributes"); + return SECFailure; + } } CERT_DestroyCertificate(cert); @@ -400,21 +402,22 @@ DumpChain(CERTCertDBHandle *handle, char *name, PRBool ascii) the_cert = SECU_FindCertByNicknameOrFilename(handle, name, ascii, NULL); if (!the_cert) { - SECU_PrintError(progName, "Could not find: %s\n", name); - return SECFailure; + SECU_PrintError(progName, "Could not find: %s\n", name); + return SECFailure; } chain = CERT_CertChainFromCert(the_cert, 0, PR_TRUE); CERT_DestroyCertificate(the_cert); if (!chain) { - SECU_PrintError(progName, "Could not obtain chain for: %s\n", name); - return SECFailure; + SECU_PrintError(progName, "Could not obtain chain for: %s\n", name); + return SECFailure; } - for (i=chain->len-1; i>=0; i--) { - CERTCertificate *c; - c = CERT_FindCertByDERCert(handle, &chain->certs[i]); - for (j=i; jlen-1; j++) printf(" "); - printf("\"%s\" [%s]\n\n", c->nickname, c->subjectName); - CERT_DestroyCertificate(c); + for (i = chain->len - 1; i >= 0; i--) { + CERTCertificate *c; + c = CERT_FindCertByDERCert(handle, &chain->certs[i]); + for (j = i; j < chain->len - 1; j++) + printf(" "); + printf("\"%s\" [%s]\n\n", c->nickname, c->subjectName); + CERT_DestroyCertificate(c); } CERT_DestroyCertificateList(chain); return SECSuccess; @@ -428,55 +431,55 @@ outputCertOrExtension(CERTCertificate *the_cert, PRBool raw, PRBool ascii, PRInt32 numBytes; SECStatus rv = SECFailure; if (extensionOID) { - int i; - PRBool found = PR_FALSE; - for (i=0; the_cert->extensions[i] != NULL; i++) { - CERTCertExtension *extension = the_cert->extensions[i]; - if (SECITEM_CompareItem(&extension->id, extensionOID) == SECEqual) { - found = PR_TRUE; - numBytes = PR_Write(outfile, extension->value.data, - extension->value.len); - rv = SECSuccess; - if (numBytes != (PRInt32) extension->value.len) { - SECU_PrintSystemError(progName, "error writing extension"); - rv = SECFailure; - } - break; - } - } - if (!found) { - SECU_PrintSystemError(progName, "extension not found"); - rv = SECFailure; - } + int i; + PRBool found = PR_FALSE; + for (i = 0; the_cert->extensions[i] != NULL; i++) { + CERTCertExtension *extension = the_cert->extensions[i]; + if (SECITEM_CompareItem(&extension->id, extensionOID) == SECEqual) { + found = PR_TRUE; + numBytes = PR_Write(outfile, extension->value.data, + extension->value.len); + rv = SECSuccess; + if (numBytes != (PRInt32)extension->value.len) { + SECU_PrintSystemError(progName, "error writing extension"); + rv = SECFailure; + } + break; + } + } + if (!found) { + SECU_PrintSystemError(progName, "extension not found"); + rv = SECFailure; + } } else { - data.data = the_cert->derCert.data; - data.len = the_cert->derCert.len; - if (ascii) { - PR_fprintf(outfile, "%s\n%s\n%s\n", NS_CERT_HEADER, - BTOA_DataToAscii(data.data, data.len), NS_CERT_TRAILER); - rv = SECSuccess; - } else if (raw) { - numBytes = PR_Write(outfile, data.data, data.len); - rv = SECSuccess; - if (numBytes != (PRInt32) data.len) { - SECU_PrintSystemError(progName, "error writing raw cert"); - rv = SECFailure; - } - } else { - rv = SEC_PrintCertificateAndTrust(the_cert, "Certificate", NULL); - if (rv != SECSuccess) { - SECU_PrintError(progName, "problem printing certificate"); - } - } + data.data = the_cert->derCert.data; + data.len = the_cert->derCert.len; + if (ascii) { + PR_fprintf(outfile, "%s\n%s\n%s\n", NS_CERT_HEADER, + BTOA_DataToAscii(data.data, data.len), NS_CERT_TRAILER); + rv = SECSuccess; + } else if (raw) { + numBytes = PR_Write(outfile, data.data, data.len); + rv = SECSuccess; + if (numBytes != (PRInt32)data.len) { + SECU_PrintSystemError(progName, "error writing raw cert"); + rv = SECFailure; + } + } else { + rv = SEC_PrintCertificateAndTrust(the_cert, "Certificate", NULL); + if (rv != SECSuccess) { + SECU_PrintError(progName, "problem printing certificate"); + } + } } return rv; } static SECStatus listCerts(CERTCertDBHandle *handle, char *name, char *email, - PK11SlotInfo *slot, PRBool raw, PRBool ascii, - SECItem *extensionOID, - PRFileDesc *outfile, void *pwarg) + PK11SlotInfo *slot, PRBool raw, PRBool ascii, + SECItem *extensionOID, + PRFileDesc *outfile, void *pwarg) { SECStatus rv = SECFailure; CERTCertList *certs; @@ -492,76 +495,76 @@ listCerts(CERTCertDBHandle *handle, char *name, char *email, } } if (name) { - CERTCertificate *the_cert = + CERTCertificate *the_cert = SECU_FindCertByNicknameOrFilename(handle, name, ascii, NULL); if (!the_cert) { SECU_PrintError(progName, "Could not find cert: %s\n", name); return SECFailure; } - /* Here, we have one cert with the desired nickname or email - * address. Now, we will attempt to get a list of ALL certs - * with the same subject name as the cert we have. That list - * should contain, at a minimum, the one cert we have already found. - * If the list of certs is empty (NULL), the libraries have failed. - */ - certs = CERT_CreateSubjectCertList(NULL, handle, &the_cert->derSubject, - PR_Now(), PR_FALSE); - CERT_DestroyCertificate(the_cert); - if (!certs) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - SECU_PrintError(progName, "problem printing certificates"); - return SECFailure; - } - for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs); - node = CERT_LIST_NEXT(node)) { - rv = outputCertOrExtension(node->cert, raw, ascii, extensionOID, + /* Here, we have one cert with the desired nickname or email + * address. Now, we will attempt to get a list of ALL certs + * with the same subject name as the cert we have. That list + * should contain, at a minimum, the one cert we have already found. + * If the list of certs is empty (NULL), the libraries have failed. + */ + certs = CERT_CreateSubjectCertList(NULL, handle, &the_cert->derSubject, + PR_Now(), PR_FALSE); + CERT_DestroyCertificate(the_cert); + if (!certs) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + SECU_PrintError(progName, "problem printing certificates"); + return SECFailure; + } + for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node, certs); + node = CERT_LIST_NEXT(node)) { + rv = outputCertOrExtension(node->cert, raw, ascii, extensionOID, outfile); - if (rv != SECSuccess) { - break; - } - } + if (rv != SECSuccess) { + break; + } + } } else if (email) { - certs = PK11_FindCertsFromEmailAddress(email, NULL); - if (!certs) { - SECU_PrintError(progName, - "Could not find certificates for email address: %s\n", - email); - return SECFailure; - } - for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs); - node = CERT_LIST_NEXT(node)) { - rv = outputCertOrExtension(node->cert, raw, ascii, extensionOID, + certs = PK11_FindCertsFromEmailAddress(email, NULL); + if (!certs) { + SECU_PrintError(progName, + "Could not find certificates for email address: %s\n", + email); + return SECFailure; + } + for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node, certs); + node = CERT_LIST_NEXT(node)) { + rv = outputCertOrExtension(node->cert, raw, ascii, extensionOID, outfile); - if (rv != SECSuccess) { - break; - } - } + if (rv != SECSuccess) { + break; + } + } } else { - certs = PK11_ListCertsInSlot(slot); - if (certs) { - for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs); - node = CERT_LIST_NEXT(node)) { - SECU_PrintCertNickname(node,stdout); - } - rv = SECSuccess; - } + certs = PK11_ListCertsInSlot(slot); + if (certs) { + for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node, certs); + node = CERT_LIST_NEXT(node)) { + SECU_PrintCertNickname(node, stdout); + } + rv = SECSuccess; + } } if (certs) { CERT_DestroyCertList(certs); } if (rv) { - SECU_PrintError(progName, "problem printing certificate nicknames"); - return SECFailure; + SECU_PrintError(progName, "problem printing certificate nicknames"); + return SECFailure; } - return SECSuccess; /* not rv ?? */ + return SECSuccess; /* not rv ?? */ } static SECStatus -ListCerts(CERTCertDBHandle *handle, char *nickname, char *email, +ListCerts(CERTCertDBHandle *handle, char *nickname, char *email, PK11SlotInfo *slot, PRBool raw, PRBool ascii, - SECItem *extensionOID, - PRFileDesc *outfile, secuPWData *pwdata) + SECItem *extensionOID, + PRFileDesc *outfile, secuPWData *pwdata) { SECStatus rv; @@ -571,23 +574,23 @@ ListCerts(CERTCertDBHandle *handle, char *nickname, char *email, "SSL,S/MIME,JAR/XPI"); } if (slot == NULL) { - CERTCertList *list; - CERTCertListNode *node; - - list = PK11_ListCerts(PK11CertListAll, pwdata); - for (node = CERT_LIST_HEAD(list); !CERT_LIST_END(node, list); - node = CERT_LIST_NEXT(node)) { - SECU_PrintCertNickname(node, stdout); - } - CERT_DestroyCertList(list); - return SECSuccess; - } + CERTCertList *list; + CERTCertListNode *node; + + list = PK11_ListCerts(PK11CertListAll, pwdata); + for (node = CERT_LIST_HEAD(list); !CERT_LIST_END(node, list); + node = CERT_LIST_NEXT(node)) { + SECU_PrintCertNickname(node, stdout); + } + CERT_DestroyCertList(list); + return SECSuccess; + } rv = listCerts(handle, nickname, email, slot, raw, ascii, extensionOID, outfile, pwdata); return rv; } -static SECStatus +static SECStatus DeleteCert(CERTCertDBHandle *handle, char *name) { SECStatus rv; @@ -595,20 +598,20 @@ DeleteCert(CERTCertDBHandle *handle, char *name) cert = CERT_FindCertByNicknameOrEmailAddr(handle, name); if (!cert) { - SECU_PrintError(progName, "could not find certificate named \"%s\"", - name); - return SECFailure; + SECU_PrintError(progName, "could not find certificate named \"%s\"", + name); + return SECFailure; } rv = SEC_DeletePermCertificate(cert); CERT_DestroyCertificate(cert); if (rv) { - SECU_PrintError(progName, "unable to delete certificate"); + SECU_PrintError(progName, "unable to delete certificate"); } return rv; } -static SECStatus +static SECStatus RenameCert(CERTCertDBHandle *handle, char *name, char *newName) { SECStatus rv; @@ -616,15 +619,15 @@ RenameCert(CERTCertDBHandle *handle, char *name, char *newName) cert = CERT_FindCertByNicknameOrEmailAddr(handle, name); if (!cert) { - SECU_PrintError(progName, "could not find certificate named \"%s\"", - name); - return SECFailure; + SECU_PrintError(progName, "could not find certificate named \"%s\"", + name); + return SECFailure; } rv = __PK11_SetCertificateNickname(cert, newName); CERT_DestroyCertificate(cert); if (rv) { - SECU_PrintError(progName, "unable to rename certificate"); + SECU_PrintError(progName, "unable to rename certificate"); } return rv; } @@ -642,107 +645,107 @@ ValidateCert(CERTCertDBHandle *handle, char *name, char *date, CERTVerifyLog *log = NULL; if (!certUsage) { - PORT_SetError (SEC_ERROR_INVALID_ARGS); - return (SECFailure); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return (SECFailure); } - + switch (*certUsage) { - case 'O': - usage = certificateUsageStatusResponder; - break; - case 'L': - usage = certificateUsageSSLCA; - break; - case 'A': - usage = certificateUsageAnyCA; - break; - case 'Y': - usage = certificateUsageVerifyCA; - break; - case 'C': - usage = certificateUsageSSLClient; - break; - case 'V': - usage = certificateUsageSSLServer; - break; - case 'S': - usage = certificateUsageEmailSigner; - break; - case 'R': - usage = certificateUsageEmailRecipient; - break; - case 'J': - usage = certificateUsageObjectSigner; - break; - default: - PORT_SetError (SEC_ERROR_INVALID_ARGS); - return (SECFailure); + case 'O': + usage = certificateUsageStatusResponder; + break; + case 'L': + usage = certificateUsageSSLCA; + break; + case 'A': + usage = certificateUsageAnyCA; + break; + case 'Y': + usage = certificateUsageVerifyCA; + break; + case 'C': + usage = certificateUsageSSLClient; + break; + case 'V': + usage = certificateUsageSSLServer; + break; + case 'S': + usage = certificateUsageEmailSigner; + break; + case 'R': + usage = certificateUsageEmailRecipient; + break; + case 'J': + usage = certificateUsageObjectSigner; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return (SECFailure); } do { - cert = SECU_FindCertByNicknameOrFilename(handle, name, ascii, + cert = SECU_FindCertByNicknameOrFilename(handle, name, ascii, NULL); - if (!cert) { - SECU_PrintError(progName, "could not find certificate named \"%s\"", - name); - GEN_BREAK (SECFailure) - } - - if (date != NULL) { - rv = DER_AsciiToTime(&timeBoundary, date); - if (rv) { - SECU_PrintError(progName, "invalid input date"); - GEN_BREAK (SECFailure) - } - } else { - timeBoundary = PR_Now(); - } - - if ( logit ) { - log = &reallog; - - log->count = 0; - log->head = NULL; - log->tail = NULL; - log->arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( log->arena == NULL ) { - SECU_PrintError(progName, "out of memory"); - GEN_BREAK (SECFailure) - } - } - - rv = CERT_VerifyCertificate(handle, cert, checkSig, usage, - timeBoundary, pwdata, log, &usage); - if ( log ) { - if ( log->head == NULL ) { - fprintf(stdout, "%s: certificate is valid\n", progName); - GEN_BREAK (SECSuccess) - } else { - char *name; - CERTVerifyLogNode *node; - - node = log->head; - while ( node ) { - if ( node->cert->nickname != NULL ) { - name = node->cert->nickname; - } else { - name = node->cert->subjectName; - } - fprintf(stderr, "%s : %s\n", name, - SECU_Strerror(node->error)); - CERT_DestroyCertificate(node->cert); - node = node->next; - } - } - } else { - if (rv != SECSuccess) { - PRErrorCode perr = PORT_GetError(); - fprintf(stdout, "%s: certificate is invalid: %s\n", - progName, SECU_Strerror(perr)); - GEN_BREAK (SECFailure) - } - fprintf(stdout, "%s: certificate is valid\n", progName); - GEN_BREAK (SECSuccess) - } + if (!cert) { + SECU_PrintError(progName, "could not find certificate named \"%s\"", + name); + GEN_BREAK(SECFailure) + } + + if (date != NULL) { + rv = DER_AsciiToTime(&timeBoundary, date); + if (rv) { + SECU_PrintError(progName, "invalid input date"); + GEN_BREAK(SECFailure) + } + } else { + timeBoundary = PR_Now(); + } + + if (logit) { + log = &reallog; + + log->count = 0; + log->head = NULL; + log->tail = NULL; + log->arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (log->arena == NULL) { + SECU_PrintError(progName, "out of memory"); + GEN_BREAK(SECFailure) + } + } + + rv = CERT_VerifyCertificate(handle, cert, checkSig, usage, + timeBoundary, pwdata, log, &usage); + if (log) { + if (log->head == NULL) { + fprintf(stdout, "%s: certificate is valid\n", progName); + GEN_BREAK(SECSuccess) + } else { + char *name; + CERTVerifyLogNode *node; + + node = log->head; + while (node) { + if (node->cert->nickname != NULL) { + name = node->cert->nickname; + } else { + name = node->cert->subjectName; + } + fprintf(stderr, "%s : %s\n", name, + SECU_Strerror(node->error)); + CERT_DestroyCertificate(node->cert); + node = node->next; + } + } + } else { + if (rv != SECSuccess) { + PRErrorCode perr = PORT_GetError(); + fprintf(stdout, "%s: certificate is invalid: %s\n", + progName, SECU_Strerror(perr)); + GEN_BREAK(SECFailure) + } + fprintf(stdout, "%s: certificate is valid\n", progName); + GEN_BREAK(SECSuccess) + } } while (0); if (cert) { @@ -753,65 +756,66 @@ ValidateCert(CERTCertDBHandle *handle, char *name, char *date, } static PRBool -ItemIsPrintableASCII(const SECItem * item) +ItemIsPrintableASCII(const SECItem *item) { unsigned char *src = item->data; - unsigned int len = item->len; + unsigned int len = item->len; while (len-- > 0) { unsigned char uc = *src++; - if (uc < 0x20 || uc > 0x7e) - return PR_FALSE; + if (uc < 0x20 || uc > 0x7e) + return PR_FALSE; } return PR_TRUE; } /* Caller ensures that dst is at least item->len*2+1 bytes long */ static void -SECItemToHex(const SECItem * item, char * dst) +SECItemToHex(const SECItem *item, char *dst) { if (dst && item && item->data) { - unsigned char * src = item->data; - unsigned int len = item->len; - for (; len > 0; --len, dst += 2) { - sprintf(dst, "%02x", *src++); - } - *dst = '\0'; + unsigned char *src = item->data; + unsigned int len = item->len; + for (; len > 0; --len, dst += 2) { + sprintf(dst, "%02x", *src++); + } + *dst = '\0'; } } -static const char * const keyTypeName[] = { - "null", "rsa", "dsa", "fortezza", "dh", "kea", "ec" }; +static const char *const keyTypeName[] = { + "null", "rsa", "dsa", "fortezza", "dh", "kea", "ec" +}; #define MAX_CKA_ID_BIN_LEN 20 #define MAX_CKA_ID_STR_LEN 40 /* print key number, key ID (in hex or ASCII), key label (nickname) */ static SECStatus -PrintKey(PRFileDesc *out, const char *nickName, int count, +PrintKey(PRFileDesc *out, const char *nickName, int count, SECKEYPrivateKey *key, void *pwarg) { - SECItem * ckaID; + SECItem *ckaID; char ckaIDbuf[MAX_CKA_ID_STR_LEN + 4]; pwarg = NULL; ckaID = PK11_GetLowLevelKeyIDForPrivateKey(key); if (!ckaID) { - strcpy(ckaIDbuf, "(no CKA_ID)"); + strcpy(ckaIDbuf, "(no CKA_ID)"); } else if (ItemIsPrintableASCII(ckaID)) { - int len = PR_MIN(MAX_CKA_ID_STR_LEN, ckaID->len); - ckaIDbuf[0] = '"'; - memcpy(ckaIDbuf + 1, ckaID->data, len); - ckaIDbuf[1 + len] = '"'; - ckaIDbuf[2 + len] = '\0'; + int len = PR_MIN(MAX_CKA_ID_STR_LEN, ckaID->len); + ckaIDbuf[0] = '"'; + memcpy(ckaIDbuf + 1, ckaID->data, len); + ckaIDbuf[1 + len] = '"'; + ckaIDbuf[2 + len] = '\0'; } else { - /* print ckaid in hex */ - SECItem idItem = *ckaID; - if (idItem.len > MAX_CKA_ID_BIN_LEN) - idItem.len = MAX_CKA_ID_BIN_LEN; + /* print ckaid in hex */ + SECItem idItem = *ckaID; + if (idItem.len > MAX_CKA_ID_BIN_LEN) + idItem.len = MAX_CKA_ID_BIN_LEN; SECItemToHex(&idItem, ckaIDbuf); } - PR_fprintf(out, "<%2d> %-8.8s %-42.42s %s\n", count, + PR_fprintf(out, "<%2d> %-8.8s %-42.42s %s\n", count, keyTypeName[key->keyType], ckaIDbuf, nickName); SECITEM_ZfreeItem(ckaID, PR_TRUE); @@ -820,7 +824,7 @@ PrintKey(PRFileDesc *out, const char *nickName, int count, /* returns SECSuccess if ANY keys are found, SECFailure otherwise. */ static SECStatus -ListKeysInSlot(PK11SlotInfo *slot, const char *nickName, KeyType keyType, +ListKeysInSlot(PK11SlotInfo *slot, const char *nickName, KeyType keyType, void *pwarg) { SECKEYPrivateKeyList *list; @@ -836,90 +840,90 @@ ListKeysInSlot(PK11SlotInfo *slot, const char *nickName, KeyType keyType, } } - if (nickName && nickName[0]) - list = PK11_ListPrivKeysInSlot(slot, (char *)nickName, pwarg); + if (nickName && nickName[0]) + list = PK11_ListPrivKeysInSlot(slot, (char *)nickName, pwarg); else - list = PK11_ListPrivateKeysInSlot(slot); + list = PK11_ListPrivateKeysInSlot(slot); if (list == NULL) { - SECU_PrintError(progName, "problem listing keys"); - return SECFailure; + SECU_PrintError(progName, "problem listing keys"); + return SECFailure; } - for (node=PRIVKEY_LIST_HEAD(list); - !PRIVKEY_LIST_END(node,list); - node=PRIVKEY_LIST_NEXT(node)) { - char * keyName; - static const char orphan[] = { "(orphan)" }; + for (node = PRIVKEY_LIST_HEAD(list); + !PRIVKEY_LIST_END(node, list); + node = PRIVKEY_LIST_NEXT(node)) { + char *keyName; + static const char orphan[] = { "(orphan)" }; - if (keyType != nullKey && keyType != node->key->keyType) - continue; + if (keyType != nullKey && keyType != node->key->keyType) + continue; keyName = PK11_GetPrivateKeyNickname(node->key); - if (!keyName || !keyName[0]) { - /* Try extra hard to find nicknames for keys that lack them. */ - CERTCertificate * cert; - PORT_Free((void *)keyName); - keyName = NULL; - cert = PK11_GetCertFromPrivateKey(node->key); - if (cert) { - if (cert->nickname && cert->nickname[0]) { - keyName = PORT_Strdup(cert->nickname); - } else if (cert->emailAddr && cert->emailAddr[0]) { - keyName = PORT_Strdup(cert->emailAddr); - } - CERT_DestroyCertificate(cert); - } - } - if (nickName) { - if (!keyName || PL_strcmp(keyName,nickName)) { - /* PKCS#11 module returned unwanted keys */ - PORT_Free((void *)keyName); - continue; - } - } - if (!keyName) - keyName = (char *)orphan; - - PrintKey(PR_STDOUT, keyName, count, node->key, pwarg); - - if (keyName != (char *)orphan) - PORT_Free((void *)keyName); - count++; + if (!keyName || !keyName[0]) { + /* Try extra hard to find nicknames for keys that lack them. */ + CERTCertificate *cert; + PORT_Free((void *)keyName); + keyName = NULL; + cert = PK11_GetCertFromPrivateKey(node->key); + if (cert) { + if (cert->nickname && cert->nickname[0]) { + keyName = PORT_Strdup(cert->nickname); + } else if (cert->emailAddr && cert->emailAddr[0]) { + keyName = PORT_Strdup(cert->emailAddr); + } + CERT_DestroyCertificate(cert); + } + } + if (nickName) { + if (!keyName || PL_strcmp(keyName, nickName)) { + /* PKCS#11 module returned unwanted keys */ + PORT_Free((void *)keyName); + continue; + } + } + if (!keyName) + keyName = (char *)orphan; + + PrintKey(PR_STDOUT, keyName, count, node->key, pwarg); + + if (keyName != (char *)orphan) + PORT_Free((void *)keyName); + count++; } SECKEY_DestroyPrivateKeyList(list); if (count == 0) { - PR_fprintf(PR_STDOUT, "%s: no keys found\n", progName); - return SECFailure; + PR_fprintf(PR_STDOUT, "%s: no keys found\n", progName); + return SECFailure; } return SECSuccess; } /* returns SECSuccess if ANY keys are found, SECFailure otherwise. */ static SECStatus -ListKeys(PK11SlotInfo *slot, const char *nickName, int index, +ListKeys(PK11SlotInfo *slot, const char *nickName, int index, KeyType keyType, PRBool dopriv, secuPWData *pwdata) { SECStatus rv = SECFailure; - static const char fmt[] = \ - "%s: Checking token \"%.33s\" in slot \"%.65s\"\n"; + static const char fmt[] = + "%s: Checking token \"%.33s\" in slot \"%.65s\"\n"; if (slot == NULL) { - PK11SlotList *list; - PK11SlotListElement *le; - - list= PK11_GetAllTokens(CKM_INVALID_MECHANISM,PR_FALSE,PR_FALSE,pwdata); - if (list) { - for (le = list->head; le; le = le->next) { - PR_fprintf(PR_STDOUT, fmt, progName, - PK11_GetTokenName(le->slot), - PK11_GetSlotName(le->slot)); - rv &= ListKeysInSlot(le->slot,nickName,keyType,pwdata); - } - PK11_FreeSlotList(list); - } + PK11SlotList *list; + PK11SlotListElement *le; + + list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_FALSE, pwdata); + if (list) { + for (le = list->head; le; le = le->next) { + PR_fprintf(PR_STDOUT, fmt, progName, + PK11_GetTokenName(le->slot), + PK11_GetSlotName(le->slot)); + rv &= ListKeysInSlot(le->slot, nickName, keyType, pwdata); + } + PK11_FreeSlotList(list); + } } else { - PR_fprintf(PR_STDOUT, fmt, progName, PK11_GetTokenName(slot), - PK11_GetSlotName(slot)); - rv = ListKeysInSlot(slot,nickName,keyType,pwdata); + PR_fprintf(PR_STDOUT, fmt, progName, PK11_GetTokenName(slot), + PK11_GetSlotName(slot)); + rv = ListKeysInSlot(slot, nickName, keyType, pwdata); } return rv; } @@ -942,19 +946,18 @@ DeleteKey(char *nickname, secuPWData *pwdata) } cert = PK11_FindCertFromNickname(nickname, pwdata); if (!cert) { - PK11_FreeSlot(slot); - return SECFailure; + PK11_FreeSlot(slot); + return SECFailure; } rv = PK11_DeleteTokenCertAndKey(cert, pwdata); if (rv != SECSuccess) { - SECU_PrintError("problem deleting private key \"%s\"\n", nickname); + SECU_PrintError("problem deleting private key \"%s\"\n", nickname); } CERT_DestroyCertificate(cert); PK11_FreeSlot(slot); return rv; } - /* * L i s t M o d u l e s * @@ -970,104 +973,107 @@ ListModules(void) PK11SlotListElement *le; /* get them all! */ - list = PK11_GetAllTokens(CKM_INVALID_MECHANISM,PR_FALSE,PR_FALSE,NULL); - if (list == NULL) return SECFailure; + list = PK11_GetAllTokens(CKM_INVALID_MECHANISM, PR_FALSE, PR_FALSE, NULL); + if (list == NULL) + return SECFailure; /* look at each slot*/ - for (le = list->head ; le; le = le->next) { - printf ("\n"); - printf (" slot: %s\n", PK11_GetSlotName(le->slot)); - printf (" token: %s\n", PK11_GetTokenName(le->slot)); + for (le = list->head; le; le = le->next) { + printf("\n"); + printf(" slot: %s\n", PK11_GetSlotName(le->slot)); + printf(" token: %s\n", PK11_GetTokenName(le->slot)); } PK11_FreeSlotList(list); return SECSuccess; } -static void +static void PrintSyntax(char *progName) { -#define FPS fprintf(stderr, +#define FPS fprintf(stderr, FPS "Type %s -H for more detailed descriptions\n", progName); FPS "Usage: %s -N [-d certdir] [-P dbprefix] [-f pwfile] [--empty-password]\n", progName); FPS "Usage: %s -T [-d certdir] [-P dbprefix] [-h token-name]\n" - "\t\t [-f pwfile] [-0 SSO-password]\n", progName); + "\t\t [-f pwfile] [-0 SSO-password]\n", progName); FPS "\t%s -A -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n", - progName); + progName); FPS "\t%s -B -i batch-file\n", progName); FPS "\t%s -C [-c issuer-name | -x] -i cert-request-file -o cert-file\n" - "\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n" + "\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n" "\t\t [-f pwfile] [-d certdir] [-P dbprefix] [-Z hashAlg]\n" "\t\t [-1 | --keyUsage [keyUsageKeyword,..]] [-2] [-3] [-4]\n" "\t\t [-5 | --nsCertType [nsCertTypeKeyword,...]]\n" "\t\t [-6 | --extKeyUsage [extKeyUsageKeyword,...]] [-7 emailAddrs]\n" "\t\t [-8 dns-names] [-a]\n", - progName); + progName); FPS "\t%s -D -n cert-name [-d certdir] [-P dbprefix]\n", progName); FPS "\t%s --rename -n cert-name --new-n new-cert-name\n" "\t\t [-d certdir] [-P dbprefix]\n", progName); FPS "\t%s -E -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n", - progName); - FPS "\t%s -F -n nickname [-d certdir] [-P dbprefix]\n", - progName); - FPS "\t%s -G -n key-name [-h token-name] [-k rsa] [-g key-size] [-y exp]\n" - "\t\t [-f pwfile] [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); + progName); + FPS "\t%s -F -n nickname [-d certdir] [-P dbprefix]\n", + progName); + FPS "\t%s -G -n key-name [-h token-name] [-k rsa] [-g key-size] [-y exp]\n" + "\t\t [-f pwfile] [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); FPS "\t%s -G [-h token-name] -k dsa [-q pqgfile -g key-size] [-f pwfile]\n" - "\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); + "\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); #ifndef NSS_DISABLE_ECC FPS "\t%s -G [-h token-name] -k ec -q curve [-f pwfile]\n" - "\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); - FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|ec|rsa|all]\n", - progName); + "\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName); + FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|ec|rsa|all]\n", + progName); #else - FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|rsa|all]\n", - progName); + FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|rsa|all]\n", + progName); #endif /* NSS_DISABLE_ECC */ FPS "\t\t [-f pwfile] [-X] [-d certdir] [-P dbprefix]\n"); FPS "\t%s --upgrade-merge --source-dir upgradeDir --upgrade-id uniqueID\n", - progName); + progName); FPS "\t\t [--upgrade-token-name tokenName] [-d targetDBDir]\n"); FPS "\t\t [-P targetDBPrefix] [--source-prefix upgradeDBPrefix]\n"); FPS "\t\t [-f targetPWfile] [-@ upgradePWFile]\n"); FPS "\t%s --merge --source-dir sourceDBDir [-d targetDBdir]\n", - progName); + progName); FPS "\t\t [-P targetDBPrefix] [--source-prefix sourceDBPrefix]\n"); FPS "\t\t [-f targetPWfile] [-@ sourcePWFile]\n"); FPS "\t%s -L [-n cert-name] [-h token-name] [--email email-address]\n", - progName); + progName); FPS "\t\t [-X] [-r] [-a] [--dump-ext-val OID] [-d certdir] [-P dbprefix]\n"); FPS "\t%s -M -n cert-name -t trustargs [-d certdir] [-P dbprefix]\n", - progName); + progName); FPS "\t%s -O -n cert-name [-X] [-d certdir] [-a] [-P dbprefix]\n", progName); FPS "\t%s -R -s subj -o cert-request-file [-d certdir] [-P dbprefix] [-p phone] [-a]\n" "\t\t [-7 emailAddrs] [-k key-type-or-id] [-h token-name] [-f pwfile]\n" "\t\t [-g key-size] [-Z hashAlg]\n", - progName); + progName); FPS "\t%s -V -n cert-name -u usage [-b time] [-e] [-a]\n" - "\t\t[-X] [-d certdir] [-P dbprefix]\n", - progName); + "\t\t[-X] [-d certdir] [-P dbprefix]\n", + progName); FPS "Usage: %s -W [-d certdir] [-f pwfile] [-@newpwfile]\n", - progName); + progName); FPS "\t%s -S -n cert-name -s subj [-c issuer-name | -x] -t trustargs\n" - "\t\t [-k key-type-or-id] [-q key-params] [-h token-name] [-g key-size]\n" + "\t\t [-k key-type-or-id] [-q key-params] [-h token-name] [-g key-size]\n" "\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n" "\t\t [-f pwfile] [-d certdir] [-P dbprefix] [-Z hashAlg]\n" "\t\t [-p phone] [-1] [-2] [-3] [-4] [-5] [-6] [-7 emailAddrs]\n" "\t\t [-8 DNS-names]\n" "\t\t [--extAIA] [--extSIA] [--extCP] [--extPM] [--extPC] [--extIA]\n" "\t\t [--extSKID] [--extNC] [--extSAN type:name[,type:name]...]\n" - "\t\t [--extGeneric OID:critical-flag:filename[,OID:critical-flag:filename]...]\n", progName); + "\t\t [--extGeneric OID:critical-flag:filename[,OID:critical-flag:filename]...]\n", progName); FPS "\t%s -U [-X] [-d certdir] [-P dbprefix]\n", progName); exit(1); } enum usage_level { - usage_all = 0, usage_selected = 1 + usage_all = 0, + usage_selected = 1 }; static void luCommonDetailsAE(); -static void luA(enum usage_level ul, const char *command) +static void +luA(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "A")); if (ul == usage_all || !command || is_my_command) @@ -1077,13 +1083,13 @@ static void luA(enum usage_level ul, const char *command) return; if (ul == usage_all) { FPS "%-20s\n", " All options under -E apply"); - } - else { + } else { luCommonDetailsAE(); } } -static void luB(enum usage_level ul, const char *command) +static void +luB(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "B")); if (ul == usage_all || !command || is_my_command) @@ -1093,7 +1099,8 @@ static void luB(enum usage_level ul, const char *command) FPS "%-20s Specify the batch file\n", " -i batch-file"); } -static void luE(enum usage_level ul, const char *command) +static void +luE(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "E")); if (ul == usage_all || !command || is_my_command) @@ -1104,7 +1111,8 @@ static void luE(enum usage_level ul, const char *command) luCommonDetailsAE(); } -static void luCommonDetailsAE() +static void +luCommonDetailsAE() { FPS "%-20s Specify the nickname of the certificate to add\n", " -n cert-name"); @@ -1133,7 +1141,8 @@ static void luCommonDetailsAE() FPS "\n"); } -static void luC(enum usage_level ul, const char *command) +static void +luC(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "C")); if (ul == usage_all || !command || is_my_command) @@ -1198,7 +1207,8 @@ static void luC(enum usage_level ul, const char *command) FPS "\n"); } -static void luG(enum usage_level ul, const char *command) +static void +luG(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "G")); if (ul == usage_all || !command || is_my_command) @@ -1273,7 +1283,8 @@ static void luG(enum usage_level ul, const char *command) FPS "\n"); } -static void luD(enum usage_level ul, const char *command) +static void +luD(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "D")); if (ul == usage_all || !command || is_my_command) @@ -1288,10 +1299,10 @@ static void luD(enum usage_level ul, const char *command) FPS "%-20s Cert & Key database prefix\n", " -P dbprefix"); FPS "\n"); - } -static void luF(enum usage_level ul, const char *command) +static void +luF(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "F")); if (ul == usage_all || !command || is_my_command) @@ -1306,10 +1317,10 @@ static void luF(enum usage_level ul, const char *command) FPS "%-20s Cert & Key database prefix\n", " -P dbprefix"); FPS "\n"); - } -static void luU(enum usage_level ul, const char *command) +static void +luU(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "U")); if (ul == usage_all || !command || is_my_command) @@ -1324,10 +1335,10 @@ static void luU(enum usage_level ul, const char *command) FPS "%-20s force the database to open R/W\n", " -X"); FPS "\n"); - } -static void luK(enum usage_level ul, const char *command) +static void +luK(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "K")); if (ul == usage_all || !command || is_my_command) @@ -1357,7 +1368,8 @@ static void luK(enum usage_level ul, const char *command) FPS "\n"); } -static void luL(enum usage_level ul, const char *command) +static void +luL(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "L")); if (ul == usage_all || !command || is_my_command) @@ -1388,7 +1400,8 @@ static void luL(enum usage_level ul, const char *command) FPS "\n"); } -static void luM(enum usage_level ul, const char *command) +static void +luM(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "M")); if (ul == usage_all || !command || is_my_command) @@ -1407,7 +1420,8 @@ static void luM(enum usage_level ul, const char *command) FPS "\n"); } -static void luN(enum usage_level ul, const char *command) +static void +luN(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "N")); if (ul == usage_all || !command || is_my_command) @@ -1426,7 +1440,8 @@ static void luN(enum usage_level ul, const char *command) FPS "\n"); } -static void luT(enum usage_level ul, const char *command) +static void +luT(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "T")); if (ul == usage_all || !command || is_my_command) @@ -1445,7 +1460,8 @@ static void luT(enum usage_level ul, const char *command) FPS "\n"); } -static void luO(enum usage_level ul, const char *command) +static void +luO(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "O")); if (ul == usage_all || !command || is_my_command) @@ -1466,7 +1482,8 @@ static void luO(enum usage_level ul, const char *command) FPS "\n"); } -static void luR(enum usage_level ul, const char *command) +static void +luR(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "R")); if (ul == usage_all || !command || is_my_command) @@ -1520,7 +1537,8 @@ static void luR(enum usage_level ul, const char *command) FPS "\n"); } -static void luV(enum usage_level ul, const char *command) +static void +luV(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "V")); if (ul == usage_all || !command || is_my_command) @@ -1533,7 +1551,7 @@ static void luV(enum usage_level ul, const char *command) FPS "%-20s validity time (\"YYMMDDHHMMSS[+HHMM|-HHMM|Z]\")\n", " -b time"); FPS "%-20s Check certificate signature \n", - " -e "); + " -e "); FPS "%-20s Specify certificate usage:\n", " -u certusage"); FPS "%-25s C \t SSL Client\n", ""); FPS "%-25s V \t SSL Server\n", ""); @@ -1541,9 +1559,9 @@ static void luV(enum usage_level ul, const char *command) FPS "%-25s A \t Any CA\n", ""); FPS "%-25s Y \t Verify CA\n", ""); FPS "%-25s S \t Email signer\n", ""); - FPS "%-25s R \t Email Recipient\n", ""); - FPS "%-25s O \t OCSP status responder\n", ""); - FPS "%-25s J \t Object signer\n", ""); + FPS "%-25s R \t Email Recipient\n", ""); + FPS "%-25s O \t OCSP status responder\n", ""); + FPS "%-25s J \t Object signer\n", ""); FPS "%-20s Cert database directory (default is ~/.netscape)\n", " -d certdir"); FPS "%-20s Input the certificate in ASCII (RFC1113); default is binary\n", @@ -1555,7 +1573,8 @@ static void luV(enum usage_level ul, const char *command) FPS "\n"); } -static void luW(enum usage_level ul, const char *command) +static void +luW(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "W")); if (ul == usage_all || !command || is_my_command) @@ -1572,7 +1591,8 @@ static void luW(enum usage_level ul, const char *command) FPS "\n"); } -static void luRename(enum usage_level ul, const char *command) +static void +luRename(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "rename")); if (ul == usage_all || !command || is_my_command) @@ -1591,7 +1611,8 @@ static void luRename(enum usage_level ul, const char *command) FPS "\n"); } -static void luUpgradeMerge(enum usage_level ul, const char *command) +static void +luUpgradeMerge(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "upgrade-merge")); if (ul == usage_all || !command || is_my_command) @@ -1618,7 +1639,8 @@ static void luUpgradeMerge(enum usage_level ul, const char *command) FPS "\n"); } -static void luMerge(enum usage_level ul, const char *command) +static void +luMerge(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "merge")); if (ul == usage_all || !command || is_my_command) @@ -1641,7 +1663,8 @@ static void luMerge(enum usage_level ul, const char *command) FPS "\n"); } -static void luS(enum usage_level ul, const char *command) +static void +luS(enum usage_level ul, const char *command) { int is_my_command = (command && 0 == strcmp(command, "S")); if (ul == usage_all || !command || is_my_command) @@ -1732,12 +1755,12 @@ static void luS(enum usage_level ul, const char *command) " --extNC "); FPS "%-20s \n" "%-20s Create a Subject Alt Name extension with one or multiple names\n", - " --extSAN type:name[,type:name]...", ""); + " --extSAN type:name[,type:name]...", ""); FPS "%-20s - type: directory, dn, dns, edi, ediparty, email, ip, ipaddr,\n", ""); FPS "%-20s other, registerid, rfc822, uri, x400, x400addr\n", ""); FPS "%-20s \n" "%-20s Add one or multiple extensions that certutil cannot encode yet,\n" - "%-20s by loading their encodings from external files.\n", + "%-20s by loading their encodings from external files.\n", " --extGeneric OID:critical-flag:filename[,OID:critical-flag:filename]...", "", ""); FPS "%-20s - OID (example): 1.2.3.4\n", ""); FPS "%-20s - critical-flag: critical or not-critical\n", ""); @@ -1745,7 +1768,8 @@ static void luS(enum usage_level ul, const char *command) FPS "\n"); } -static void LongUsage(char *progName, enum usage_level ul, const char *command) +static void +LongUsage(char *progName, enum usage_level ul, const char *command) { luA(ul, command); luB(ul, command); @@ -1775,26 +1799,27 @@ static void Usage(char *progName) { PR_fprintf(PR_STDERR, - "%s - Utility to manipulate NSS certificate databases\n\n" - "Usage: %s -d \n\n" - "Valid commands:\n", progName, progName); + "%s - Utility to manipulate NSS certificate databases\n\n" + "Usage: %s -d \n\n" + "Valid commands:\n", + progName, progName); LongUsage(progName, usage_selected, NULL); PR_fprintf(PR_STDERR, "\n" - "%s -H : Print available options for the given command\n" - "%s -H : Print complete help output of all commands and options\n" - "%s --syntax : Print a short summary of all commands and options\n", - progName, progName, progName); + "%s -H : Print available options for the given command\n" + "%s -H : Print complete help output of all commands and options\n" + "%s --syntax : Print a short summary of all commands and options\n", + progName, progName, progName); exit(1); } static CERTCertificate * -MakeV1Cert( CERTCertDBHandle * handle, - CERTCertificateRequest *req, - char * issuerNickName, - PRBool selfsign, - unsigned int serialNumber, - int warpmonths, - int validityMonths) +MakeV1Cert(CERTCertDBHandle *handle, + CERTCertificateRequest *req, + char *issuerNickName, + PRBool selfsign, + unsigned int serialNumber, + int warpmonths, + int validityMonths) { CERTCertificate *issuerCert = NULL; CERTValidity *validity; @@ -1802,185 +1827,184 @@ MakeV1Cert( CERTCertDBHandle * handle, PRExplodedTime printableTime; PRTime now, after; - if ( !selfsign ) { - issuerCert = CERT_FindCertByNicknameOrEmailAddr(handle, issuerNickName); - if (!issuerCert) { - SECU_PrintError(progName, "could not find certificate named \"%s\"", - issuerNickName); - return NULL; - } + if (!selfsign) { + issuerCert = CERT_FindCertByNicknameOrEmailAddr(handle, issuerNickName); + if (!issuerCert) { + SECU_PrintError(progName, "could not find certificate named \"%s\"", + issuerNickName); + return NULL; + } } now = PR_Now(); - PR_ExplodeTime (now, PR_GMTParameters, &printableTime); - if ( warpmonths ) { - printableTime.tm_month += warpmonths; - now = PR_ImplodeTime (&printableTime); - PR_ExplodeTime (now, PR_GMTParameters, &printableTime); + PR_ExplodeTime(now, PR_GMTParameters, &printableTime); + if (warpmonths) { + printableTime.tm_month += warpmonths; + now = PR_ImplodeTime(&printableTime); + PR_ExplodeTime(now, PR_GMTParameters, &printableTime); } printableTime.tm_month += validityMonths; - after = PR_ImplodeTime (&printableTime); + after = PR_ImplodeTime(&printableTime); /* note that the time is now in micro-second unit */ - validity = CERT_CreateValidity (now, after); + validity = CERT_CreateValidity(now, after); if (validity) { - cert = CERT_CreateCertificate(serialNumber, - (selfsign ? &req->subject - : &issuerCert->subject), - validity, req); - + cert = CERT_CreateCertificate(serialNumber, + (selfsign ? &req->subject + : &issuerCert->subject), + validity, req); + CERT_DestroyValidity(validity); } - if ( issuerCert ) { - CERT_DestroyCertificate (issuerCert); + if (issuerCert) { + CERT_DestroyCertificate(issuerCert); } - - return(cert); + + return (cert); } static SECStatus -SignCert(CERTCertDBHandle *handle, CERTCertificate *cert, PRBool selfsign, +SignCert(CERTCertDBHandle *handle, CERTCertificate *cert, PRBool selfsign, SECOidTag hashAlgTag, SECKEYPrivateKey *privKey, char *issuerNickName, int certVersion, void *pwarg) { SECItem der; - SECKEYPrivateKey *caPrivateKey = NULL; + SECKEYPrivateKey *caPrivateKey = NULL; SECStatus rv; PLArenaPool *arena; SECOidTag algID; void *dummy; - if( !selfsign ) { - CERTCertificate *issuer = PK11_FindCertFromNickname(issuerNickName, pwarg); - if( (CERTCertificate *)NULL == issuer ) { - SECU_PrintError(progName, "unable to find issuer with nickname %s", - issuerNickName); - return SECFailure; - } + if (!selfsign) { + CERTCertificate *issuer = PK11_FindCertFromNickname(issuerNickName, pwarg); + if ((CERTCertificate *)NULL == issuer) { + SECU_PrintError(progName, "unable to find issuer with nickname %s", + issuerNickName); + return SECFailure; + } - privKey = caPrivateKey = PK11_FindKeyByAnyCert(issuer, pwarg); - CERT_DestroyCertificate(issuer); - if (caPrivateKey == NULL) { - SECU_PrintError(progName, "unable to retrieve key %s", issuerNickName); - return SECFailure; - } + privKey = caPrivateKey = PK11_FindKeyByAnyCert(issuer, pwarg); + CERT_DestroyCertificate(issuer); + if (caPrivateKey == NULL) { + SECU_PrintError(progName, "unable to retrieve key %s", issuerNickName); + return SECFailure; + } } - + arena = cert->arena; algID = SEC_GetSignatureAlgorithmOidTag(privKey->keyType, hashAlgTag); if (algID == SEC_OID_UNKNOWN) { - fprintf(stderr, "Unknown key or hash type for issuer."); - rv = SECFailure; - goto done; + fprintf(stderr, "Unknown key or hash type for issuer."); + rv = SECFailure; + goto done; } rv = SECOID_SetAlgorithmID(arena, &cert->signature, algID, 0); if (rv != SECSuccess) { - fprintf(stderr, "Could not set signature algorithm id."); - goto done; + fprintf(stderr, "Could not set signature algorithm id."); + goto done; } - switch(certVersion) { - case (SEC_CERTIFICATE_VERSION_1): - /* The initial version for x509 certificates is version one + switch (certVersion) { + case (SEC_CERTIFICATE_VERSION_1): + /* The initial version for x509 certificates is version one * and this default value must be an implicit DER encoding. */ - cert->version.data = NULL; - cert->version.len = 0; - break; - case (SEC_CERTIFICATE_VERSION_2): - case (SEC_CERTIFICATE_VERSION_3): - case 3: /* unspecified format (would be version 4 certificate). */ - *(cert->version.data) = certVersion; - cert->version.len = 1; - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + cert->version.data = NULL; + cert->version.len = 0; + break; + case (SEC_CERTIFICATE_VERSION_2): + case (SEC_CERTIFICATE_VERSION_3): + case 3: /* unspecified format (would be version 4 certificate). */ + *(cert->version.data) = certVersion; + cert->version.len = 1; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } der.len = 0; der.data = NULL; - dummy = SEC_ASN1EncodeItem (arena, &der, cert, - SEC_ASN1_GET(CERT_CertificateTemplate)); + dummy = SEC_ASN1EncodeItem(arena, &der, cert, + SEC_ASN1_GET(CERT_CertificateTemplate)); if (!dummy) { - fprintf (stderr, "Could not encode certificate.\n"); - rv = SECFailure; - goto done; + fprintf(stderr, "Could not encode certificate.\n"); + rv = SECFailure; + goto done; } rv = SEC_DerSignData(arena, &cert->derCert, der.data, der.len, privKey, algID); if (rv != SECSuccess) { - fprintf (stderr, "Could not sign encoded certificate data.\n"); - /* result allocated out of the arena, it will be freed - * when the arena is freed */ - goto done; + fprintf(stderr, "Could not sign encoded certificate data.\n"); + /* result allocated out of the arena, it will be freed + * when the arena is freed */ + goto done; } done: if (caPrivateKey) { - SECKEY_DestroyPrivateKey(caPrivateKey); + SECKEY_DestroyPrivateKey(caPrivateKey); } return rv; } static SECStatus CreateCert( - CERTCertDBHandle *handle, - PK11SlotInfo *slot, - char * issuerNickName, - const SECItem * certReqDER, - SECKEYPrivateKey **selfsignprivkey, - void *pwarg, - SECOidTag hashAlgTag, - unsigned int serialNumber, - int warpmonths, - int validityMonths, - const char *emailAddrs, - const char *dnsNames, - PRBool ascii, - PRBool selfsign, - certutilExtnList extnList, - const char *extGeneric, - int certVersion, - SECItem * certDER) + CERTCertDBHandle *handle, + PK11SlotInfo *slot, + char *issuerNickName, + const SECItem *certReqDER, + SECKEYPrivateKey **selfsignprivkey, + void *pwarg, + SECOidTag hashAlgTag, + unsigned int serialNumber, + int warpmonths, + int validityMonths, + const char *emailAddrs, + const char *dnsNames, + PRBool ascii, + PRBool selfsign, + certutilExtnList extnList, + const char *extGeneric, + int certVersion, + SECItem *certDER) { - void * extHandle; - CERTCertificate *subjectCert = NULL; - CERTCertificateRequest *certReq = NULL; - SECStatus rv = SECSuccess; + void *extHandle; + CERTCertificate *subjectCert = NULL; + CERTCertificateRequest *certReq = NULL; + SECStatus rv = SECSuccess; CERTCertExtension **CRexts; do { - /* Create a certrequest object from the input cert request der */ - certReq = GetCertRequest(certReqDER); - if (certReq == NULL) { - GEN_BREAK (SECFailure) - } - - subjectCert = MakeV1Cert (handle, certReq, issuerNickName, selfsign, - serialNumber, warpmonths, validityMonths); - if (subjectCert == NULL) { - GEN_BREAK (SECFailure) - } - - - extHandle = CERT_StartCertExtensions (subjectCert); - if (extHandle == NULL) { - GEN_BREAK (SECFailure) - } - + /* Create a certrequest object from the input cert request der */ + certReq = GetCertRequest(certReqDER); + if (certReq == NULL) { + GEN_BREAK(SECFailure) + } + + subjectCert = MakeV1Cert(handle, certReq, issuerNickName, selfsign, + serialNumber, warpmonths, validityMonths); + if (subjectCert == NULL) { + GEN_BREAK(SECFailure) + } + + extHandle = CERT_StartCertExtensions(subjectCert); + if (extHandle == NULL) { + GEN_BREAK(SECFailure) + } + rv = AddExtensions(extHandle, emailAddrs, dnsNames, extnList, extGeneric); if (rv != SECSuccess) { - GEN_BREAK (SECFailure) - } - + GEN_BREAK(SECFailure) + } + if (certReq->attributes != NULL && - certReq->attributes[0] != NULL && - certReq->attributes[0]->attrType.data != NULL && - certReq->attributes[0]->attrType.len > 0 && - SECOID_FindOIDTag(&certReq->attributes[0]->attrType) - == SEC_OID_PKCS9_EXTENSION_REQUEST) { + certReq->attributes[0] != NULL && + certReq->attributes[0]->attrType.data != NULL && + certReq->attributes[0]->attrType.len > 0 && + SECOID_FindOIDTag(&certReq->attributes[0]->attrType) == + SEC_OID_PKCS9_EXTENSION_REQUEST) { rv = CERT_GetCertificateRequestExtensions(certReq, &CRexts); if (rv != SECSuccess) break; @@ -1989,91 +2013,89 @@ CreateCert( break; } - CERT_FinishExtensions(extHandle); + CERT_FinishExtensions(extHandle); - /* self-signing a cert request, find the private key */ - if (selfsign && *selfsignprivkey == NULL) { - *selfsignprivkey = PK11_FindKeyByDERCert(slot, subjectCert, pwarg); - if (!*selfsignprivkey) { - fprintf(stderr, "Failed to locate private key.\n"); - rv = SECFailure; - break; - } - } + /* self-signing a cert request, find the private key */ + if (selfsign && *selfsignprivkey == NULL) { + *selfsignprivkey = PK11_FindKeyByDERCert(slot, subjectCert, pwarg); + if (!*selfsignprivkey) { + fprintf(stderr, "Failed to locate private key.\n"); + rv = SECFailure; + break; + } + } - rv = SignCert(handle, subjectCert, selfsign, hashAlgTag, - *selfsignprivkey, issuerNickName, + rv = SignCert(handle, subjectCert, selfsign, hashAlgTag, + *selfsignprivkey, issuerNickName, certVersion, pwarg); - if (rv != SECSuccess) - break; - - rv = SECFailure; - if (ascii) { - char * asciiDER = BTOA_DataToAscii(subjectCert->derCert.data, - subjectCert->derCert.len); - if (asciiDER) { - char * wrapped = PR_smprintf("%s\n%s\n%s\n", - NS_CERT_HEADER, - asciiDER, - NS_CERT_TRAILER); - if (wrapped) { - PRUint32 wrappedLen = PL_strlen(wrapped); - if (SECITEM_AllocItem(NULL, certDER, wrappedLen)) { - PORT_Memcpy(certDER->data, wrapped, wrappedLen); - rv = SECSuccess; - } - PR_smprintf_free(wrapped); - } - PORT_Free(asciiDER); - } - } else { - rv = SECITEM_CopyItem(NULL, certDER, &subjectCert->derCert); - } + if (rv != SECSuccess) + break; + + rv = SECFailure; + if (ascii) { + char *asciiDER = BTOA_DataToAscii(subjectCert->derCert.data, + subjectCert->derCert.len); + if (asciiDER) { + char *wrapped = PR_smprintf("%s\n%s\n%s\n", + NS_CERT_HEADER, + asciiDER, + NS_CERT_TRAILER); + if (wrapped) { + PRUint32 wrappedLen = PL_strlen(wrapped); + if (SECITEM_AllocItem(NULL, certDER, wrappedLen)) { + PORT_Memcpy(certDER->data, wrapped, wrappedLen); + rv = SECSuccess; + } + PR_smprintf_free(wrapped); + } + PORT_Free(asciiDER); + } + } else { + rv = SECITEM_CopyItem(NULL, certDER, &subjectCert->derCert); + } } while (0); - CERT_DestroyCertificateRequest (certReq); - CERT_DestroyCertificate (subjectCert); + CERT_DestroyCertificateRequest(certReq); + CERT_DestroyCertificate(subjectCert); if (rv != SECSuccess) { - PRErrorCode perr = PR_GetError(); + PRErrorCode perr = PR_GetError(); fprintf(stderr, "%s: unable to create cert (%s)\n", progName, - SECU_Strerror(perr)); + SECU_Strerror(perr)); } return (rv); } - /* * map a class to a user presentable string */ static const char *objClassArray[] = { - "Data", - "Certificate", - "Public Key", - "Private Key", - "Secret Key", - "Hardware Feature", - "Domain Parameters", - "Mechanism" + "Data", + "Certificate", + "Public Key", + "Private Key", + "Secret Key", + "Hardware Feature", + "Domain Parameters", + "Mechanism" }; static const char *objNSSClassArray[] = { - "CKO_NSS", - "Crl", - "SMIME Record", - "Trust", - "Builtin Root List" + "CKO_NSS", + "Crl", + "SMIME Record", + "Trust", + "Builtin Root List" }; - const char * getObjectClass(CK_ULONG classType) { - static char buf[sizeof(CK_ULONG)*2+3]; + static char buf[sizeof(CK_ULONG) * 2 + 3]; if (classType <= CKO_MECHANISM) { - return objClassArray[classType]; + return objClassArray[classType]; } if (classType >= CKO_NSS && classType <= CKO_NSS_BUILTIN_ROOT_LIST) { - return objNSSClassArray[classType - CKO_NSS]; + return objNSSClassArray[classType - CKO_NSS]; } sprintf(buf, "0x%lx", classType); return buf; @@ -2081,83 +2103,83 @@ getObjectClass(CK_ULONG classType) typedef struct { char *name; - int nameSize; + int nameSize; CK_ULONG value; } flagArray; -#define NAME_SIZE(x) #x,sizeof(#x)-1 +#define NAME_SIZE(x) #x, sizeof(#x) - 1 flagArray opFlagsArray[] = -{ - {NAME_SIZE(encrypt), CKF_ENCRYPT}, - {NAME_SIZE(decrypt), CKF_DECRYPT}, - {NAME_SIZE(sign), CKF_SIGN}, - {NAME_SIZE(sign_recover), CKF_SIGN_RECOVER}, - {NAME_SIZE(verify), CKF_VERIFY}, - {NAME_SIZE(verify_recover), CKF_VERIFY_RECOVER}, - {NAME_SIZE(wrap), CKF_WRAP}, - {NAME_SIZE(unwrap), CKF_UNWRAP}, - {NAME_SIZE(derive), CKF_DERIVE}, -}; - -int opFlagsCount = sizeof(opFlagsArray)/sizeof(flagArray); + { + { NAME_SIZE(encrypt), CKF_ENCRYPT }, + { NAME_SIZE(decrypt), CKF_DECRYPT }, + { NAME_SIZE(sign), CKF_SIGN }, + { NAME_SIZE(sign_recover), CKF_SIGN_RECOVER }, + { NAME_SIZE(verify), CKF_VERIFY }, + { NAME_SIZE(verify_recover), CKF_VERIFY_RECOVER }, + { NAME_SIZE(wrap), CKF_WRAP }, + { NAME_SIZE(unwrap), CKF_UNWRAP }, + { NAME_SIZE(derive), CKF_DERIVE }, + }; + +int opFlagsCount = sizeof(opFlagsArray) / sizeof(flagArray); flagArray attrFlagsArray[] = -{ - {NAME_SIZE(token), PK11_ATTR_TOKEN}, - {NAME_SIZE(session), PK11_ATTR_SESSION}, - {NAME_SIZE(private), PK11_ATTR_PRIVATE}, - {NAME_SIZE(public), PK11_ATTR_PUBLIC}, - {NAME_SIZE(modifiable), PK11_ATTR_MODIFIABLE}, - {NAME_SIZE(unmodifiable), PK11_ATTR_UNMODIFIABLE}, - {NAME_SIZE(sensitive), PK11_ATTR_SENSITIVE}, - {NAME_SIZE(insensitive), PK11_ATTR_INSENSITIVE}, - {NAME_SIZE(extractable), PK11_ATTR_EXTRACTABLE}, - {NAME_SIZE(unextractable), PK11_ATTR_UNEXTRACTABLE} - -}; - -int attrFlagsCount = sizeof(attrFlagsArray)/sizeof(flagArray); + { + { NAME_SIZE(token), PK11_ATTR_TOKEN }, + { NAME_SIZE(session), PK11_ATTR_SESSION }, + { NAME_SIZE(private), PK11_ATTR_PRIVATE }, + { NAME_SIZE(public), PK11_ATTR_PUBLIC }, + { NAME_SIZE(modifiable), PK11_ATTR_MODIFIABLE }, + { NAME_SIZE(unmodifiable), PK11_ATTR_UNMODIFIABLE }, + { NAME_SIZE(sensitive), PK11_ATTR_SENSITIVE }, + { NAME_SIZE(insensitive), PK11_ATTR_INSENSITIVE }, + { NAME_SIZE(extractable), PK11_ATTR_EXTRACTABLE }, + { NAME_SIZE(unextractable), PK11_ATTR_UNEXTRACTABLE } + + }; + +int attrFlagsCount = sizeof(attrFlagsArray) / sizeof(flagArray); #define MAX_STRING 30 CK_ULONG GetFlags(char *flagsString, flagArray *flagArray, int count) { - CK_ULONG flagsValue = strtol(flagsString, NULL, 0); - int i; - - if ((flagsValue != 0) || (*flagsString == 0)) { - return flagsValue; - } - while (*flagsString) { - for (i=0; i < count; i++) { - if (strncmp(flagsString, flagArray[i].name, flagArray[i].nameSize) - == 0) { - flagsValue |= flagArray[i].value; - flagsString += flagArray[i].nameSize; - if (*flagsString != 0) { - flagsString++; - } - break; - } - } - if (i == count) { - char name[MAX_STRING]; - char *tok; - - strncpy(name,flagsString, MAX_STRING); - name[MAX_STRING-1] = 0; - tok = strchr(name, ','); - if (tok) { - *tok = 0; - } - fprintf(stderr,"Unknown flag (%s)\n",name); - tok = strchr(flagsString, ','); - if (tok == NULL) { - break; - } - flagsString = tok+1; - } + CK_ULONG flagsValue = strtol(flagsString, NULL, 0); + int i; + + if ((flagsValue != 0) || (*flagsString == 0)) { + return flagsValue; + } + while (*flagsString) { + for (i = 0; i < count; i++) { + if (strncmp(flagsString, flagArray[i].name, flagArray[i].nameSize) == + 0) { + flagsValue |= flagArray[i].value; + flagsString += flagArray[i].nameSize; + if (*flagsString != 0) { + flagsString++; + } + break; + } + } + if (i == count) { + char name[MAX_STRING]; + char *tok; + + strncpy(name, flagsString, MAX_STRING); + name[MAX_STRING - 1] = 0; + tok = strchr(name, ','); + if (tok) { + *tok = 0; + } + fprintf(stderr, "Unknown flag (%s)\n", name); + tok = strchr(flagsString, ','); + if (tok == NULL) { + break; + } + flagsString = tok + 1; + } } return flagsValue; } @@ -2174,15 +2196,16 @@ GetAttrFlags(char *flags) return GetFlags(flags, attrFlagsArray, attrFlagsCount); } -char *mkNickname(unsigned char *data, int len) +char * +mkNickname(unsigned char *data, int len) { - char *nick = PORT_Alloc(len+1); - if (!nick) { - return nick; - } - PORT_Memcpy(nick, data, len); - nick[len] = 0; - return nick; + char *nick = PORT_Alloc(len + 1); + if (!nick) { + return nick; + } + PORT_Memcpy(nick, data, len); + nick[len] = 0; + return nick; } /* @@ -2194,37 +2217,37 @@ DumpMergeLog(const char *progname, PK11MergeLog *log) PK11MergeLogNode *node; for (node = log->head; node; node = node->next) { - SECItem attrItem; - char *nickname = NULL; - const char *objectClass = NULL; - SECStatus rv; - - attrItem.data = NULL; - rv = PK11_ReadRawAttribute(PK11_TypeGeneric, node->object, - CKA_LABEL, &attrItem); - if (rv == SECSuccess) { - nickname = mkNickname(attrItem.data, attrItem.len); - PORT_Free(attrItem.data); - } - attrItem.data = NULL; - rv = PK11_ReadRawAttribute(PK11_TypeGeneric, node->object, - CKA_CLASS, &attrItem); - if (rv == SECSuccess) { - if (attrItem.len == sizeof(CK_ULONG)) { - objectClass = getObjectClass(*(CK_ULONG *)attrItem.data); - } - PORT_Free(attrItem.data); - } - - fprintf(stderr, "%s: Could not merge object %s (type %s): %s\n", - progName, - nickname ? nickname : "unnamed", - objectClass ? objectClass : "unknown", - SECU_Strerror(node->error)); - - if (nickname) { - PORT_Free(nickname); - } + SECItem attrItem; + char *nickname = NULL; + const char *objectClass = NULL; + SECStatus rv; + + attrItem.data = NULL; + rv = PK11_ReadRawAttribute(PK11_TypeGeneric, node->object, + CKA_LABEL, &attrItem); + if (rv == SECSuccess) { + nickname = mkNickname(attrItem.data, attrItem.len); + PORT_Free(attrItem.data); + } + attrItem.data = NULL; + rv = PK11_ReadRawAttribute(PK11_TypeGeneric, node->object, + CKA_CLASS, &attrItem); + if (rv == SECSuccess) { + if (attrItem.len == sizeof(CK_ULONG)) { + objectClass = getObjectClass(*(CK_ULONG *)attrItem.data); + } + PORT_Free(attrItem.data); + } + + fprintf(stderr, "%s: Could not merge object %s (type %s): %s\n", + progName, + nickname ? nickname : "unnamed", + objectClass ? objectClass : "unknown", + SECU_Strerror(node->error)); + + if (nickname) { + PORT_Free(nickname); + } } } @@ -2326,176 +2349,174 @@ enum certutilOpts { opt_Help }; -static const -secuCommandFlag commands_init[] = -{ - { /* cmd_AddCert */ 'A', PR_FALSE, 0, PR_FALSE }, - { /* cmd_CreateNewCert */ 'C', PR_FALSE, 0, PR_FALSE }, - { /* cmd_DeleteCert */ 'D', PR_FALSE, 0, PR_FALSE }, - { /* cmd_AddEmailCert */ 'E', PR_FALSE, 0, PR_FALSE }, - { /* cmd_DeleteKey */ 'F', PR_FALSE, 0, PR_FALSE }, - { /* cmd_GenKeyPair */ 'G', PR_FALSE, 0, PR_FALSE }, - { /* cmd_PrintHelp */ 'H', PR_FALSE, 0, PR_FALSE, "help" }, - { /* cmd_PrintSyntax */ 0, PR_FALSE, 0, PR_FALSE, - "syntax" }, - { /* cmd_ListKeys */ 'K', PR_FALSE, 0, PR_FALSE }, - { /* cmd_ListCerts */ 'L', PR_FALSE, 0, PR_FALSE }, - { /* cmd_ModifyCertTrust */ 'M', PR_FALSE, 0, PR_FALSE }, - { /* cmd_NewDBs */ 'N', PR_FALSE, 0, PR_FALSE }, - { /* cmd_DumpChain */ 'O', PR_FALSE, 0, PR_FALSE }, - { /* cmd_CertReq */ 'R', PR_FALSE, 0, PR_FALSE }, - { /* cmd_CreateAndAddCert */ 'S', PR_FALSE, 0, PR_FALSE }, - { /* cmd_TokenReset */ 'T', PR_FALSE, 0, PR_FALSE }, - { /* cmd_ListModules */ 'U', PR_FALSE, 0, PR_FALSE }, - { /* cmd_CheckCertValidity */ 'V', PR_FALSE, 0, PR_FALSE }, - { /* cmd_ChangePassword */ 'W', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Version */ 'Y', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Batch */ 'B', PR_FALSE, 0, PR_FALSE }, - { /* cmd_Merge */ 0, PR_FALSE, 0, PR_FALSE, "merge" }, - { /* cmd_UpgradeMerge */ 0, PR_FALSE, 0, PR_FALSE, - "upgrade-merge" }, - { /* cmd_Rename */ 0, PR_FALSE, 0, PR_FALSE, - "rename" } -}; +static const secuCommandFlag commands_init[] = + { + { /* cmd_AddCert */ 'A', PR_FALSE, 0, PR_FALSE }, + { /* cmd_CreateNewCert */ 'C', PR_FALSE, 0, PR_FALSE }, + { /* cmd_DeleteCert */ 'D', PR_FALSE, 0, PR_FALSE }, + { /* cmd_AddEmailCert */ 'E', PR_FALSE, 0, PR_FALSE }, + { /* cmd_DeleteKey */ 'F', PR_FALSE, 0, PR_FALSE }, + { /* cmd_GenKeyPair */ 'G', PR_FALSE, 0, PR_FALSE }, + { /* cmd_PrintHelp */ 'H', PR_FALSE, 0, PR_FALSE, "help" }, + { /* cmd_PrintSyntax */ 0, PR_FALSE, 0, PR_FALSE, + "syntax" }, + { /* cmd_ListKeys */ 'K', PR_FALSE, 0, PR_FALSE }, + { /* cmd_ListCerts */ 'L', PR_FALSE, 0, PR_FALSE }, + { /* cmd_ModifyCertTrust */ 'M', PR_FALSE, 0, PR_FALSE }, + { /* cmd_NewDBs */ 'N', PR_FALSE, 0, PR_FALSE }, + { /* cmd_DumpChain */ 'O', PR_FALSE, 0, PR_FALSE }, + { /* cmd_CertReq */ 'R', PR_FALSE, 0, PR_FALSE }, + { /* cmd_CreateAndAddCert */ 'S', PR_FALSE, 0, PR_FALSE }, + { /* cmd_TokenReset */ 'T', PR_FALSE, 0, PR_FALSE }, + { /* cmd_ListModules */ 'U', PR_FALSE, 0, PR_FALSE }, + { /* cmd_CheckCertValidity */ 'V', PR_FALSE, 0, PR_FALSE }, + { /* cmd_ChangePassword */ 'W', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Version */ 'Y', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Batch */ 'B', PR_FALSE, 0, PR_FALSE }, + { /* cmd_Merge */ 0, PR_FALSE, 0, PR_FALSE, "merge" }, + { /* cmd_UpgradeMerge */ 0, PR_FALSE, 0, PR_FALSE, + "upgrade-merge" }, + { /* cmd_Rename */ 0, PR_FALSE, 0, PR_FALSE, + "rename" } + }; #define NUM_COMMANDS ((sizeof commands_init) / (sizeof commands_init[0])) - -static const -secuCommandFlag options_init[] = -{ - { /* opt_SSOPass */ '0', PR_TRUE, 0, PR_FALSE }, - { /* opt_AddKeyUsageExt */ '1', PR_FALSE, 0, PR_FALSE }, - { /* opt_AddBasicConstraintExt*/ '2', PR_FALSE, 0, PR_FALSE }, - { /* opt_AddAuthorityKeyIDExt*/ '3', PR_FALSE, 0, PR_FALSE }, - { /* opt_AddCRLDistPtsExt */ '4', PR_FALSE, 0, PR_FALSE }, - { /* opt_AddNSCertTypeExt */ '5', PR_FALSE, 0, PR_FALSE }, - { /* opt_AddExtKeyUsageExt */ '6', PR_FALSE, 0, PR_FALSE }, - { /* opt_ExtendedEmailAddrs */ '7', PR_TRUE, 0, PR_FALSE }, - { /* opt_ExtendedDNSNames */ '8', PR_TRUE, 0, PR_FALSE }, - { /* opt_ASCIIForIO */ 'a', PR_FALSE, 0, PR_FALSE }, - { /* opt_ValidityTime */ 'b', PR_TRUE, 0, PR_FALSE }, - { /* opt_IssuerName */ 'c', PR_TRUE, 0, PR_FALSE }, - { /* opt_CertDir */ 'd', PR_TRUE, 0, PR_FALSE }, - { /* opt_VerifySig */ 'e', PR_FALSE, 0, PR_FALSE }, - { /* opt_PasswordFile */ 'f', PR_TRUE, 0, PR_FALSE }, - { /* opt_KeySize */ 'g', PR_TRUE, 0, PR_FALSE }, - { /* opt_TokenName */ 'h', PR_TRUE, 0, PR_FALSE }, - { /* opt_InputFile */ 'i', PR_TRUE, 0, PR_FALSE }, - { /* opt_Emailaddress */ 0, PR_TRUE, 0, PR_FALSE, "email" }, - { /* opt_KeyIndex */ 'j', PR_TRUE, 0, PR_FALSE }, - { /* opt_KeyType */ 'k', PR_TRUE, 0, PR_FALSE }, - { /* opt_DetailedInfo */ 'l', PR_FALSE, 0, PR_FALSE }, - { /* opt_SerialNumber */ 'm', PR_TRUE, 0, PR_FALSE }, - { /* opt_Nickname */ 'n', PR_TRUE, 0, PR_FALSE }, - { /* opt_OutputFile */ 'o', PR_TRUE, 0, PR_FALSE }, - { /* opt_PhoneNumber */ 'p', PR_TRUE, 0, PR_FALSE }, - { /* opt_DBPrefix */ 'P', PR_TRUE, 0, PR_FALSE }, - { /* opt_PQGFile */ 'q', PR_TRUE, 0, PR_FALSE }, - { /* opt_BinaryDER */ 'r', PR_FALSE, 0, PR_FALSE }, - { /* opt_Subject */ 's', PR_TRUE, 0, PR_FALSE }, - { /* opt_Trust */ 't', PR_TRUE, 0, PR_FALSE }, - { /* opt_Usage */ 'u', PR_TRUE, 0, PR_FALSE }, - { /* opt_Validity */ 'v', PR_TRUE, 0, PR_FALSE }, - { /* opt_OffsetMonths */ 'w', PR_TRUE, 0, PR_FALSE }, - { /* opt_SelfSign */ 'x', PR_FALSE, 0, PR_FALSE }, - { /* opt_RW */ 'X', PR_FALSE, 0, PR_FALSE }, - { /* opt_Exponent */ 'y', PR_TRUE, 0, PR_FALSE }, - { /* opt_NoiseFile */ 'z', PR_TRUE, 0, PR_FALSE }, - { /* opt_Hash */ 'Z', PR_TRUE, 0, PR_FALSE }, - { /* opt_NewPasswordFile */ '@', PR_TRUE, 0, PR_FALSE }, - { /* opt_AddAuthInfoAccExt */ 0, PR_FALSE, 0, PR_FALSE, "extAIA" }, - { /* opt_AddSubjInfoAccExt */ 0, PR_FALSE, 0, PR_FALSE, "extSIA" }, - { /* opt_AddCertPoliciesExt */ 0, PR_FALSE, 0, PR_FALSE, "extCP" }, - { /* opt_AddPolicyMapExt */ 0, PR_FALSE, 0, PR_FALSE, "extPM" }, - { /* opt_AddPolicyConstrExt */ 0, PR_FALSE, 0, PR_FALSE, "extPC" }, - { /* opt_AddInhibAnyExt */ 0, PR_FALSE, 0, PR_FALSE, "extIA" }, - { /* opt_AddNameConstraintsExt*/ 0, PR_FALSE, 0, PR_FALSE, "extNC" }, - { /* opt_AddSubjectKeyIDExt */ 0, PR_FALSE, 0, PR_FALSE, - "extSKID" }, - { /* opt_AddCmdKeyUsageExt */ 0, PR_TRUE, 0, PR_FALSE, - "keyUsage" }, - { /* opt_AddCmdNSCertTypeExt */ 0, PR_TRUE, 0, PR_FALSE, - "nsCertType" }, - { /* opt_AddCmdExtKeyUsageExt*/ 0, PR_TRUE, 0, PR_FALSE, - "extKeyUsage" }, - - { /* opt_SourceDir */ 0, PR_TRUE, 0, PR_FALSE, - "source-dir"}, - { /* opt_SourcePrefix */ 0, PR_TRUE, 0, PR_FALSE, - "source-prefix"}, - { /* opt_UpgradeID */ 0, PR_TRUE, 0, PR_FALSE, - "upgrade-id"}, - { /* opt_UpgradeTokenName */ 0, PR_TRUE, 0, PR_FALSE, - "upgrade-token-name"}, - { /* opt_KeyOpFlagsOn */ 0, PR_TRUE, 0, PR_FALSE, - "keyOpFlagsOn"}, - { /* opt_KeyOpFlagsOff */ 0, PR_TRUE, 0, PR_FALSE, - "keyOpFlagsOff"}, - { /* opt_KeyAttrFlags */ 0, PR_TRUE, 0, PR_FALSE, - "keyAttrFlags"}, - { /* opt_EmptyPassword */ 0, PR_FALSE, 0, PR_FALSE, - "empty-password"}, - { /* opt_CertVersion */ 0, PR_TRUE, 0, PR_FALSE, - "certVersion"}, - { /* opt_AddSubjectAltExt */ 0, PR_TRUE, 0, PR_FALSE, "extSAN"}, - { /* opt_DumpExtensionValue */ 0, PR_TRUE, 0, PR_FALSE, - "dump-ext-val"}, - { /* opt_GenericExtensions */ 0, PR_TRUE, 0, PR_FALSE, - "extGeneric"}, - { /* opt_NewNickname */ 0, PR_TRUE, 0, PR_FALSE, - "new-n"}, -}; -#define NUM_OPTIONS ((sizeof options_init) / (sizeof options_init[0])) + +static const secuCommandFlag options_init[] = + { + { /* opt_SSOPass */ '0', PR_TRUE, 0, PR_FALSE }, + { /* opt_AddKeyUsageExt */ '1', PR_FALSE, 0, PR_FALSE }, + { /* opt_AddBasicConstraintExt*/ '2', PR_FALSE, 0, PR_FALSE }, + { /* opt_AddAuthorityKeyIDExt*/ '3', PR_FALSE, 0, PR_FALSE }, + { /* opt_AddCRLDistPtsExt */ '4', PR_FALSE, 0, PR_FALSE }, + { /* opt_AddNSCertTypeExt */ '5', PR_FALSE, 0, PR_FALSE }, + { /* opt_AddExtKeyUsageExt */ '6', PR_FALSE, 0, PR_FALSE }, + { /* opt_ExtendedEmailAddrs */ '7', PR_TRUE, 0, PR_FALSE }, + { /* opt_ExtendedDNSNames */ '8', PR_TRUE, 0, PR_FALSE }, + { /* opt_ASCIIForIO */ 'a', PR_FALSE, 0, PR_FALSE }, + { /* opt_ValidityTime */ 'b', PR_TRUE, 0, PR_FALSE }, + { /* opt_IssuerName */ 'c', PR_TRUE, 0, PR_FALSE }, + { /* opt_CertDir */ 'd', PR_TRUE, 0, PR_FALSE }, + { /* opt_VerifySig */ 'e', PR_FALSE, 0, PR_FALSE }, + { /* opt_PasswordFile */ 'f', PR_TRUE, 0, PR_FALSE }, + { /* opt_KeySize */ 'g', PR_TRUE, 0, PR_FALSE }, + { /* opt_TokenName */ 'h', PR_TRUE, 0, PR_FALSE }, + { /* opt_InputFile */ 'i', PR_TRUE, 0, PR_FALSE }, + { /* opt_Emailaddress */ 0, PR_TRUE, 0, PR_FALSE, "email" }, + { /* opt_KeyIndex */ 'j', PR_TRUE, 0, PR_FALSE }, + { /* opt_KeyType */ 'k', PR_TRUE, 0, PR_FALSE }, + { /* opt_DetailedInfo */ 'l', PR_FALSE, 0, PR_FALSE }, + { /* opt_SerialNumber */ 'm', PR_TRUE, 0, PR_FALSE }, + { /* opt_Nickname */ 'n', PR_TRUE, 0, PR_FALSE }, + { /* opt_OutputFile */ 'o', PR_TRUE, 0, PR_FALSE }, + { /* opt_PhoneNumber */ 'p', PR_TRUE, 0, PR_FALSE }, + { /* opt_DBPrefix */ 'P', PR_TRUE, 0, PR_FALSE }, + { /* opt_PQGFile */ 'q', PR_TRUE, 0, PR_FALSE }, + { /* opt_BinaryDER */ 'r', PR_FALSE, 0, PR_FALSE }, + { /* opt_Subject */ 's', PR_TRUE, 0, PR_FALSE }, + { /* opt_Trust */ 't', PR_TRUE, 0, PR_FALSE }, + { /* opt_Usage */ 'u', PR_TRUE, 0, PR_FALSE }, + { /* opt_Validity */ 'v', PR_TRUE, 0, PR_FALSE }, + { /* opt_OffsetMonths */ 'w', PR_TRUE, 0, PR_FALSE }, + { /* opt_SelfSign */ 'x', PR_FALSE, 0, PR_FALSE }, + { /* opt_RW */ 'X', PR_FALSE, 0, PR_FALSE }, + { /* opt_Exponent */ 'y', PR_TRUE, 0, PR_FALSE }, + { /* opt_NoiseFile */ 'z', PR_TRUE, 0, PR_FALSE }, + { /* opt_Hash */ 'Z', PR_TRUE, 0, PR_FALSE }, + { /* opt_NewPasswordFile */ '@', PR_TRUE, 0, PR_FALSE }, + { /* opt_AddAuthInfoAccExt */ 0, PR_FALSE, 0, PR_FALSE, "extAIA" }, + { /* opt_AddSubjInfoAccExt */ 0, PR_FALSE, 0, PR_FALSE, "extSIA" }, + { /* opt_AddCertPoliciesExt */ 0, PR_FALSE, 0, PR_FALSE, "extCP" }, + { /* opt_AddPolicyMapExt */ 0, PR_FALSE, 0, PR_FALSE, "extPM" }, + { /* opt_AddPolicyConstrExt */ 0, PR_FALSE, 0, PR_FALSE, "extPC" }, + { /* opt_AddInhibAnyExt */ 0, PR_FALSE, 0, PR_FALSE, "extIA" }, + { /* opt_AddNameConstraintsExt*/ 0, PR_FALSE, 0, PR_FALSE, "extNC" }, + { /* opt_AddSubjectKeyIDExt */ 0, PR_FALSE, 0, PR_FALSE, + "extSKID" }, + { /* opt_AddCmdKeyUsageExt */ 0, PR_TRUE, 0, PR_FALSE, + "keyUsage" }, + { /* opt_AddCmdNSCertTypeExt */ 0, PR_TRUE, 0, PR_FALSE, + "nsCertType" }, + { /* opt_AddCmdExtKeyUsageExt*/ 0, PR_TRUE, 0, PR_FALSE, + "extKeyUsage" }, + + { /* opt_SourceDir */ 0, PR_TRUE, 0, PR_FALSE, + "source-dir" }, + { /* opt_SourcePrefix */ 0, PR_TRUE, 0, PR_FALSE, + "source-prefix" }, + { /* opt_UpgradeID */ 0, PR_TRUE, 0, PR_FALSE, + "upgrade-id" }, + { /* opt_UpgradeTokenName */ 0, PR_TRUE, 0, PR_FALSE, + "upgrade-token-name" }, + { /* opt_KeyOpFlagsOn */ 0, PR_TRUE, 0, PR_FALSE, + "keyOpFlagsOn" }, + { /* opt_KeyOpFlagsOff */ 0, PR_TRUE, 0, PR_FALSE, + "keyOpFlagsOff" }, + { /* opt_KeyAttrFlags */ 0, PR_TRUE, 0, PR_FALSE, + "keyAttrFlags" }, + { /* opt_EmptyPassword */ 0, PR_FALSE, 0, PR_FALSE, + "empty-password" }, + { /* opt_CertVersion */ 0, PR_TRUE, 0, PR_FALSE, + "certVersion" }, + { /* opt_AddSubjectAltExt */ 0, PR_TRUE, 0, PR_FALSE, "extSAN" }, + { /* opt_DumpExtensionValue */ 0, PR_TRUE, 0, PR_FALSE, + "dump-ext-val" }, + { /* opt_GenericExtensions */ 0, PR_TRUE, 0, PR_FALSE, + "extGeneric" }, + { /* opt_NewNickname */ 0, PR_TRUE, 0, PR_FALSE, + "new-n" }, + }; +#define NUM_OPTIONS ((sizeof options_init) / (sizeof options_init[0])) static secuCommandFlag certutil_commands[NUM_COMMANDS]; -static secuCommandFlag certutil_options [NUM_OPTIONS ]; +static secuCommandFlag certutil_options[NUM_OPTIONS]; static const secuCommand certutil = { - NUM_COMMANDS, - NUM_OPTIONS, - certutil_commands, + NUM_COMMANDS, + NUM_OPTIONS, + certutil_commands, certutil_options }; static certutilExtnList certutil_extns; -static int +static int certutil_main(int argc, char **argv, PRBool initialize) { CERTCertDBHandle *certHandle; PK11SlotInfo *slot = NULL; - CERTName * subject = 0; - PRFileDesc *inFile = PR_STDIN; - PRFileDesc *outFile = PR_STDOUT; - SECItem certReqDER = { siBuffer, NULL, 0 }; - SECItem certDER = { siBuffer, NULL, 0 }; - const char *slotname = "internal"; - const char *certPrefix = ""; - char * sourceDir = ""; - const char *srcCertPrefix = ""; - char * upgradeID = ""; - char * upgradeTokenName = ""; - KeyType keytype = rsaKey; - char * name = NULL; - char * newName = NULL; - char * email = NULL; - char * keysource = NULL; - SECOidTag hashAlgTag = SEC_OID_UNKNOWN; - int keysize = DEFAULT_KEY_BITS; - int publicExponent = 0x010001; - int certVersion = SEC_CERTIFICATE_VERSION_3; - unsigned int serialNumber = 0; - int warpmonths = 0; - int validityMonths = 3; - int commandsEntered = 0; - char commandToRun = '\0'; - secuPWData pwdata = { PW_NONE, 0 }; - secuPWData pwdata2 = { PW_NONE, 0 }; - PRBool readOnly = PR_FALSE; - PRBool initialized = PR_FALSE; - CK_FLAGS keyOpFlagsOn = 0; - CK_FLAGS keyOpFlagsOff = 0; - PK11AttrFlags keyAttrFlags = - PK11_ATTR_TOKEN | PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE; + CERTName *subject = 0; + PRFileDesc *inFile = PR_STDIN; + PRFileDesc *outFile = PR_STDOUT; + SECItem certReqDER = { siBuffer, NULL, 0 }; + SECItem certDER = { siBuffer, NULL, 0 }; + const char *slotname = "internal"; + const char *certPrefix = ""; + char *sourceDir = ""; + const char *srcCertPrefix = ""; + char *upgradeID = ""; + char *upgradeTokenName = ""; + KeyType keytype = rsaKey; + char *name = NULL; + char *newName = NULL; + char *email = NULL; + char *keysource = NULL; + SECOidTag hashAlgTag = SEC_OID_UNKNOWN; + int keysize = DEFAULT_KEY_BITS; + int publicExponent = 0x010001; + int certVersion = SEC_CERTIFICATE_VERSION_3; + unsigned int serialNumber = 0; + int warpmonths = 0; + int validityMonths = 3; + int commandsEntered = 0; + char commandToRun = '\0'; + secuPWData pwdata = { PW_NONE, 0 }; + secuPWData pwdata2 = { PW_NONE, 0 }; + PRBool readOnly = PR_FALSE; + PRBool initialized = PR_FALSE; + CK_FLAGS keyOpFlagsOn = 0; + CK_FLAGS keyOpFlagsOff = 0; + PK11AttrFlags keyAttrFlags = + PK11_ATTR_TOKEN | PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE; SECKEYPrivateKey *privkey = NULL; SECKEYPublicKey *pubkey = NULL; @@ -2504,14 +2525,14 @@ certutil_main(int argc, char **argv, PRBool initialize) SECStatus rv; progName = PORT_Strrchr(argv[0], '/'); - progName = progName ? progName+1 : argv[0]; + progName = progName ? progName + 1 : argv[0]; memcpy(certutil_commands, commands_init, sizeof commands_init); - memcpy(certutil_options, options_init, sizeof options_init); + memcpy(certutil_options, options_init, sizeof options_init); rv = SECU_ParseCommandLine(argc, argv, progName, &certutil); if (rv != SECSuccess) - Usage(progName); + Usage(progName); if (certutil.commands[cmd_PrintSyntax].activated) { PrintSyntax(progName); @@ -2529,115 +2550,113 @@ certutil_main(int argc, char **argv, PRBool initialize) buf[0] = certutil.commands[i].flag; buf[1] = 0; command = buf; - } - else { + } else { command = certutil.commands[i].longform; } break; } } - LongUsage(progName, (command ? usage_selected : usage_all), command); + LongUsage(progName, (command ? usage_selected : usage_all), command); exit(1); } if (certutil.options[opt_PasswordFile].arg) { - pwdata.source = PW_FROMFILE; - pwdata.data = certutil.options[opt_PasswordFile].arg; + pwdata.source = PW_FROMFILE; + pwdata.data = certutil.options[opt_PasswordFile].arg; } if (certutil.options[opt_NewPasswordFile].arg) { - pwdata2.source = PW_FROMFILE; - pwdata2.data = certutil.options[opt_NewPasswordFile].arg; + pwdata2.source = PW_FROMFILE; + pwdata2.data = certutil.options[opt_NewPasswordFile].arg; } if (certutil.options[opt_CertDir].activated) - SECU_ConfigDirectory(certutil.options[opt_CertDir].arg); + SECU_ConfigDirectory(certutil.options[opt_CertDir].arg); if (certutil.options[opt_SourceDir].activated) - sourceDir = certutil.options[opt_SourceDir].arg; + sourceDir = certutil.options[opt_SourceDir].arg; if (certutil.options[opt_UpgradeID].activated) - upgradeID = certutil.options[opt_UpgradeID].arg; + upgradeID = certutil.options[opt_UpgradeID].arg; if (certutil.options[opt_UpgradeTokenName].activated) - upgradeTokenName = certutil.options[opt_UpgradeTokenName].arg; + upgradeTokenName = certutil.options[opt_UpgradeTokenName].arg; if (certutil.options[opt_KeySize].activated) { - keysize = PORT_Atoi(certutil.options[opt_KeySize].arg); - if ((keysize < MIN_KEY_BITS) || (keysize > MAX_KEY_BITS)) { - PR_fprintf(PR_STDERR, + keysize = PORT_Atoi(certutil.options[opt_KeySize].arg); + if ((keysize < MIN_KEY_BITS) || (keysize > MAX_KEY_BITS)) { + PR_fprintf(PR_STDERR, "%s -g: Keysize must be between %d and %d.\n", - progName, MIN_KEY_BITS, MAX_KEY_BITS); - return 255; - } + progName, MIN_KEY_BITS, MAX_KEY_BITS); + return 255; + } #ifndef NSS_DISABLE_ECC - if (keytype == ecKey) { - PR_fprintf(PR_STDERR, "%s -g: Not for ec keys.\n", progName); - return 255; - } + if (keytype == ecKey) { + PR_fprintf(PR_STDERR, "%s -g: Not for ec keys.\n", progName); + return 255; + } #endif /* NSS_DISABLE_ECC */ - } /* -h specify token name */ if (certutil.options[opt_TokenName].activated) { - if (PL_strcmp(certutil.options[opt_TokenName].arg, "all") == 0) - slotname = NULL; - else - slotname = certutil.options[opt_TokenName].arg; + if (PL_strcmp(certutil.options[opt_TokenName].arg, "all") == 0) + slotname = NULL; + else + slotname = certutil.options[opt_TokenName].arg; } /* -Z hash type */ if (certutil.options[opt_Hash].activated) { - char * arg = certutil.options[opt_Hash].arg; + char *arg = certutil.options[opt_Hash].arg; hashAlgTag = SECU_StringToSignatureAlgTag(arg); if (hashAlgTag == SEC_OID_UNKNOWN) { - PR_fprintf(PR_STDERR, "%s -Z: %s is not a recognized type.\n", - progName, arg); - return 255; - } + PR_fprintf(PR_STDERR, "%s -Z: %s is not a recognized type.\n", + progName, arg); + return 255; + } } /* -k key type */ if (certutil.options[opt_KeyType].activated) { - char * arg = certutil.options[opt_KeyType].arg; - if (PL_strcmp(arg, "rsa") == 0) { - keytype = rsaKey; - } else if (PL_strcmp(arg, "dsa") == 0) { - keytype = dsaKey; + char *arg = certutil.options[opt_KeyType].arg; + if (PL_strcmp(arg, "rsa") == 0) { + keytype = rsaKey; + } else if (PL_strcmp(arg, "dsa") == 0) { + keytype = dsaKey; #ifndef NSS_DISABLE_ECC - } else if (PL_strcmp(arg, "ec") == 0) { - keytype = ecKey; + } else if (PL_strcmp(arg, "ec") == 0) { + keytype = ecKey; #endif /* NSS_DISABLE_ECC */ - } else if (PL_strcmp(arg, "all") == 0) { - keytype = nullKey; - } else { - /* use an existing private/public key pair */ - keysource = arg; - } + } else if (PL_strcmp(arg, "all") == 0) { + keytype = nullKey; + } else { + /* use an existing private/public key pair */ + keysource = arg; + } } else if (certutil.commands[cmd_ListKeys].activated) { - keytype = nullKey; + keytype = nullKey; } if (certutil.options[opt_KeyOpFlagsOn].activated) { - keyOpFlagsOn = GetOpFlags(certutil.options[opt_KeyOpFlagsOn].arg); + keyOpFlagsOn = GetOpFlags(certutil.options[opt_KeyOpFlagsOn].arg); } if (certutil.options[opt_KeyOpFlagsOff].activated) { - keyOpFlagsOff = GetOpFlags(certutil.options[opt_KeyOpFlagsOff].arg); - keyOpFlagsOn &=~keyOpFlagsOff; /* make off override on */ + keyOpFlagsOff = GetOpFlags(certutil.options[opt_KeyOpFlagsOff].arg); + keyOpFlagsOn &= ~keyOpFlagsOff; /* make off override on */ } if (certutil.options[opt_KeyAttrFlags].activated) { - keyAttrFlags = GetAttrFlags(certutil.options[opt_KeyAttrFlags].arg); + keyAttrFlags = GetAttrFlags(certutil.options[opt_KeyAttrFlags].arg); } /* -m serial number */ if (certutil.options[opt_SerialNumber].activated) { - int sn = PORT_Atoi(certutil.options[opt_SerialNumber].arg); - if (sn < 0) { - PR_fprintf(PR_STDERR, "%s -m: %s is not a valid serial number.\n", - progName, certutil.options[opt_SerialNumber].arg); - return 255; - } - serialNumber = sn; + int sn = PORT_Atoi(certutil.options[opt_SerialNumber].arg); + if (sn < 0) { + PR_fprintf(PR_STDERR, "%s -m: %s is not a valid serial number.\n", + progName, certutil.options[opt_SerialNumber].arg); + return 255; + } + serialNumber = sn; } /* -P certdb name prefix */ @@ -2661,54 +2680,54 @@ certutil_main(int argc, char **argv, PRBool initialize) /* -q PQG file or curve name */ if (certutil.options[opt_PQGFile].activated) { #ifndef NSS_DISABLE_ECC - if ((keytype != dsaKey) && (keytype != ecKey)) { - PR_fprintf(PR_STDERR, "%s -q: specifies a PQG file for DSA keys" \ - " (-k dsa) or a named curve for EC keys (-k ec)\n)", - progName); -#else /* } */ - if (keytype != dsaKey) { - PR_fprintf(PR_STDERR, "%s -q: PQG file is for DSA key (-k dsa).\n)", - progName); + if ((keytype != dsaKey) && (keytype != ecKey)) { + PR_fprintf(PR_STDERR, "%s -q: specifies a PQG file for DSA keys" + " (-k dsa) or a named curve for EC keys (-k ec)\n)", + progName); +#else /* } */ + if (keytype != dsaKey) { + PR_fprintf(PR_STDERR, "%s -q: PQG file is for DSA key (-k dsa).\n)", + progName); #endif /* NSS_DISABLE_ECC */ - return 255; - } + return 255; + } } /* -s subject name */ if (certutil.options[opt_Subject].activated) { - subject = CERT_AsciiToName(certutil.options[opt_Subject].arg); - if (!subject) { - PR_fprintf(PR_STDERR, "%s -s: improperly formatted name: \"%s\"\n", - progName, certutil.options[opt_Subject].arg); - return 255; - } + subject = CERT_AsciiToName(certutil.options[opt_Subject].arg); + if (!subject) { + PR_fprintf(PR_STDERR, "%s -s: improperly formatted name: \"%s\"\n", + progName, certutil.options[opt_Subject].arg); + return 255; + } } /* -v validity period */ if (certutil.options[opt_Validity].activated) { - validityMonths = PORT_Atoi(certutil.options[opt_Validity].arg); - if (validityMonths < 0) { - PR_fprintf(PR_STDERR, "%s -v: incorrect validity period: \"%s\"\n", - progName, certutil.options[opt_Validity].arg); - return 255; - } + validityMonths = PORT_Atoi(certutil.options[opt_Validity].arg); + if (validityMonths < 0) { + PR_fprintf(PR_STDERR, "%s -v: incorrect validity period: \"%s\"\n", + progName, certutil.options[opt_Validity].arg); + return 255; + } } /* -w warp months */ if (certutil.options[opt_OffsetMonths].activated) - warpmonths = PORT_Atoi(certutil.options[opt_OffsetMonths].arg); + warpmonths = PORT_Atoi(certutil.options[opt_OffsetMonths].arg); /* -y public exponent (for RSA) */ if (certutil.options[opt_Exponent].activated) { - publicExponent = PORT_Atoi(certutil.options[opt_Exponent].arg); - if ((publicExponent != 3) && - (publicExponent != 17) && - (publicExponent != 65537)) { - PR_fprintf(PR_STDERR, "%s -y: incorrect public exponent %d.", - progName, publicExponent); - PR_fprintf(PR_STDERR, "Must be 3, 17, or 65537.\n"); - return 255; - } + publicExponent = PORT_Atoi(certutil.options[opt_Exponent].arg); + if ((publicExponent != 3) && + (publicExponent != 17) && + (publicExponent != 65537)) { + PR_fprintf(PR_STDERR, "%s -y: incorrect public exponent %d.", + progName, publicExponent); + PR_fprintf(PR_STDERR, "Must be 3, 17, or 65537.\n"); + return 255; + } } /* --certVersion */ @@ -2716,60 +2735,59 @@ certutil_main(int argc, char **argv, PRBool initialize) certVersion = PORT_Atoi(certutil.options[opt_CertVersion].arg); if (certVersion < 1 || certVersion > 4) { PR_fprintf(PR_STDERR, "%s -certVersion: incorrect certificate version %d.", - progName, certVersion); + progName, certVersion); PR_fprintf(PR_STDERR, "Must be 1, 2, 3 or 4.\n"); return 255; } certVersion = certVersion - 1; } - /* Check number of commands entered. */ commandsEntered = 0; - for (i=0; i< certutil.numCommands; i++) { - if (certutil.commands[i].activated) { - commandToRun = certutil.commands[i].flag; - commandsEntered++; - } - if (commandsEntered > 1) - break; + for (i = 0; i < certutil.numCommands; i++) { + if (certutil.commands[i].activated) { + commandToRun = certutil.commands[i].flag; + commandsEntered++; + } + if (commandsEntered > 1) + break; } if (commandsEntered > 1) { - PR_fprintf(PR_STDERR, "%s: only one command at a time!\n", progName); - PR_fprintf(PR_STDERR, "You entered: "); - for (i=0; i< certutil.numCommands; i++) { - if (certutil.commands[i].activated) - PR_fprintf(PR_STDERR, " -%c", certutil.commands[i].flag); - } - PR_fprintf(PR_STDERR, "\n"); - return 255; + PR_fprintf(PR_STDERR, "%s: only one command at a time!\n", progName); + PR_fprintf(PR_STDERR, "You entered: "); + for (i = 0; i < certutil.numCommands; i++) { + if (certutil.commands[i].activated) + PR_fprintf(PR_STDERR, " -%c", certutil.commands[i].flag); + } + PR_fprintf(PR_STDERR, "\n"); + return 255; } if (commandsEntered == 0) { - Usage(progName); + Usage(progName); } if (certutil.commands[cmd_ListCerts].activated || - certutil.commands[cmd_PrintHelp].activated || - certutil.commands[cmd_ListKeys].activated || - certutil.commands[cmd_ListModules].activated || - certutil.commands[cmd_CheckCertValidity].activated || - certutil.commands[cmd_Version].activated ) { - readOnly = !certutil.options[opt_RW].activated; + certutil.commands[cmd_PrintHelp].activated || + certutil.commands[cmd_ListKeys].activated || + certutil.commands[cmd_ListModules].activated || + certutil.commands[cmd_CheckCertValidity].activated || + certutil.commands[cmd_Version].activated) { + readOnly = !certutil.options[opt_RW].activated; } /* -A, -D, -F, -M, -S, -V, and all require -n */ if ((certutil.commands[cmd_AddCert].activated || certutil.commands[cmd_DeleteCert].activated || certutil.commands[cmd_DeleteKey].activated || - certutil.commands[cmd_DumpChain].activated || + certutil.commands[cmd_DumpChain].activated || certutil.commands[cmd_ModifyCertTrust].activated || certutil.commands[cmd_CreateAndAddCert].activated || certutil.commands[cmd_CheckCertValidity].activated) && !certutil.options[opt_Nickname].activated) { - PR_fprintf(PR_STDERR, - "%s -%c: nickname is required for this command (-n).\n", - progName, commandToRun); - return 255; + PR_fprintf(PR_STDERR, + "%s -%c: nickname is required for this command (-n).\n", + progName, commandToRun); + return 255; } /* -A, -E, -M, -S require trust */ @@ -2778,10 +2796,10 @@ certutil_main(int argc, char **argv, PRBool initialize) certutil.commands[cmd_ModifyCertTrust].activated || certutil.commands[cmd_CreateAndAddCert].activated) && !certutil.options[opt_Trust].activated) { - PR_fprintf(PR_STDERR, - "%s -%c: trust is required for this command (-t).\n", - progName, commandToRun); - return 255; + PR_fprintf(PR_STDERR, + "%s -%c: trust is required for this command (-t).\n", + progName, commandToRun); + return 255; } /* if -L is given raw, ascii or dump mode, it must be for only one cert. */ @@ -2790,49 +2808,49 @@ certutil_main(int argc, char **argv, PRBool initialize) certutil.options[opt_DumpExtensionValue].activated || certutil.options[opt_BinaryDER].activated) && !certutil.options[opt_Nickname].activated) { - PR_fprintf(PR_STDERR, - "%s: nickname is required to dump cert in raw or ascii mode.\n", - progName); - return 255; + PR_fprintf(PR_STDERR, + "%s: nickname is required to dump cert in raw or ascii mode.\n", + progName); + return 255; } - + /* -L can only be in (raw || ascii). */ if (certutil.commands[cmd_ListCerts].activated && certutil.options[opt_ASCIIForIO].activated && certutil.options[opt_BinaryDER].activated) { - PR_fprintf(PR_STDERR, - "%s: cannot specify both -r and -a when dumping cert.\n", - progName); - return 255; + PR_fprintf(PR_STDERR, + "%s: cannot specify both -r and -a when dumping cert.\n", + progName); + return 255; } /* If making a cert request, need a subject. */ if ((certutil.commands[cmd_CertReq].activated || certutil.commands[cmd_CreateAndAddCert].activated) && !(certutil.options[opt_Subject].activated || keysource)) { - PR_fprintf(PR_STDERR, - "%s -%c: subject is required to create a cert request.\n", - progName, commandToRun); - return 255; + PR_fprintf(PR_STDERR, + "%s -%c: subject is required to create a cert request.\n", + progName, commandToRun); + return 255; } /* If making a cert, need a serial number. */ if ((certutil.commands[cmd_CreateNewCert].activated || certutil.commands[cmd_CreateAndAddCert].activated) && - !certutil.options[opt_SerialNumber].activated) { - /* Make a default serial number from the current time. */ - PRTime now = PR_Now(); - LL_USHR(now, now, 19); - LL_L2UI(serialNumber, now); + !certutil.options[opt_SerialNumber].activated) { + /* Make a default serial number from the current time. */ + PRTime now = PR_Now(); + LL_USHR(now, now, 19); + LL_L2UI(serialNumber, now); } /* Validation needs the usage to validate for. */ if (certutil.commands[cmd_CheckCertValidity].activated && !certutil.options[opt_Usage].activated) { - PR_fprintf(PR_STDERR, - "%s -V: specify a usage to validate the cert for (-u).\n", - progName); - return 255; + PR_fprintf(PR_STDERR, + "%s -V: specify a usage to validate the cert for (-u).\n", + progName); + return 255; } /* Rename needs an old and a new nickname */ @@ -2840,92 +2858,90 @@ certutil_main(int argc, char **argv, PRBool initialize) !(certutil.options[opt_Nickname].activated && certutil.options[opt_NewNickname].activated)) { - PR_fprintf(PR_STDERR, - "%s --rename: specify an old nickname (-n) and\n" + PR_fprintf(PR_STDERR, + "%s --rename: specify an old nickname (-n) and\n" " a new nickname (--new-n).\n", - progName); - return 255; + progName); + return 255; } - /* Upgrade/Merge needs a source database and a upgrade id. */ if (certutil.commands[cmd_UpgradeMerge].activated && !(certutil.options[opt_SourceDir].activated && certutil.options[opt_UpgradeID].activated)) { - PR_fprintf(PR_STDERR, - "%s --upgrade-merge: specify an upgrade database directory " - "(--source-dir) and\n" + PR_fprintf(PR_STDERR, + "%s --upgrade-merge: specify an upgrade database directory " + "(--source-dir) and\n" " an upgrade ID (--upgrade-id).\n", - progName); - return 255; + progName); + return 255; } /* Merge needs a source database */ if (certutil.commands[cmd_Merge].activated && !certutil.options[opt_SourceDir].activated) { - - PR_fprintf(PR_STDERR, - "%s --merge: specify an source database directory " - "(--source-dir)\n", - progName); - return 255; + PR_fprintf(PR_STDERR, + "%s --merge: specify an source database directory " + "(--source-dir)\n", + progName); + return 255; } - /* To make a cert, need either a issuer or to self-sign it. */ if (certutil.commands[cmd_CreateAndAddCert].activated && - !(certutil.options[opt_IssuerName].activated || + !(certutil.options[opt_IssuerName].activated || certutil.options[opt_SelfSign].activated)) { - PR_fprintf(PR_STDERR, - "%s -S: must specify issuer (-c) or self-sign (-x).\n", - progName); - return 255; + PR_fprintf(PR_STDERR, + "%s -S: must specify issuer (-c) or self-sign (-x).\n", + progName); + return 255; } - /* Using slotname == NULL for listing keys and certs on all slots, + /* Using slotname == NULL for listing keys and certs on all slots, * but only that. */ if (!(certutil.commands[cmd_ListKeys].activated || - certutil.commands[cmd_DumpChain].activated || - certutil.commands[cmd_ListCerts].activated) && slotname == NULL) { - PR_fprintf(PR_STDERR, - "%s -%c: cannot use \"-h all\" for this command.\n", - progName, commandToRun); - return 255; + certutil.commands[cmd_DumpChain].activated || + certutil.commands[cmd_ListCerts].activated) && + slotname == NULL) { + PR_fprintf(PR_STDERR, + "%s -%c: cannot use \"-h all\" for this command.\n", + progName, commandToRun); + return 255; } /* Using keytype == nullKey for list all key types, but only that. */ if (!certutil.commands[cmd_ListKeys].activated && keytype == nullKey) { - PR_fprintf(PR_STDERR, - "%s -%c: cannot use \"-k all\" for this command.\n", - progName, commandToRun); - return 255; + PR_fprintf(PR_STDERR, + "%s -%c: cannot use \"-k all\" for this command.\n", + progName, commandToRun); + return 255; } /* Open the input file. */ if (certutil.options[opt_InputFile].activated) { - inFile = PR_Open(certutil.options[opt_InputFile].arg, PR_RDONLY, 0); - if (!inFile) { - PR_fprintf(PR_STDERR, - "%s: unable to open \"%s\" for reading (%ld, %ld).\n", - progName, certutil.options[opt_InputFile].arg, - PR_GetError(), PR_GetOSError()); - return 255; - } + inFile = PR_Open(certutil.options[opt_InputFile].arg, PR_RDONLY, 0); + if (!inFile) { + PR_fprintf(PR_STDERR, + "%s: unable to open \"%s\" for reading (%ld, %ld).\n", + progName, certutil.options[opt_InputFile].arg, + PR_GetError(), PR_GetOSError()); + return 255; + } } /* Open the output file. */ if (certutil.options[opt_OutputFile].activated) { - outFile = PR_Open(certutil.options[opt_OutputFile].arg, + outFile = PR_Open(certutil.options[opt_OutputFile].arg, PR_CREATE_FILE | PR_RDWR | PR_TRUNCATE, 00660); - if (!outFile) { - PR_fprintf(PR_STDERR, - "%s: unable to open \"%s\" for writing (%ld, %ld).\n", - progName, certutil.options[opt_OutputFile].arg, - PR_GetError(), PR_GetOSError()); - return 255; - } + if (!outFile) { + PR_fprintf(PR_STDERR, + "%s: unable to open \"%s\" for writing (%ld, %ld).\n", + progName, certutil.options[opt_OutputFile].arg, + PR_GetError(), PR_GetOSError()); + return 255; + } } name = SECU_GetOptionArg(&certutil, opt_Nickname); @@ -2937,58 +2953,58 @@ certutil_main(int argc, char **argv, PRBool initialize) if (PR_TRUE == initialize) { /* Initialize NSPR and NSS. */ PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1); - if (!certutil.commands[cmd_UpgradeMerge].activated) { - rv = NSS_Initialize(SECU_ConfigDirectory(NULL), - certPrefix, certPrefix, - "secmod.db", readOnly ? NSS_INIT_READONLY: 0); - } else { - rv = NSS_InitWithMerge(SECU_ConfigDirectory(NULL), - certPrefix, certPrefix, "secmod.db", - sourceDir, srcCertPrefix, srcCertPrefix, - upgradeID, upgradeTokenName, - readOnly ? NSS_INIT_READONLY: 0); - } + if (!certutil.commands[cmd_UpgradeMerge].activated) { + rv = NSS_Initialize(SECU_ConfigDirectory(NULL), + certPrefix, certPrefix, + "secmod.db", readOnly ? NSS_INIT_READONLY : 0); + } else { + rv = NSS_InitWithMerge(SECU_ConfigDirectory(NULL), + certPrefix, certPrefix, "secmod.db", + sourceDir, srcCertPrefix, srcCertPrefix, + upgradeID, upgradeTokenName, + readOnly ? NSS_INIT_READONLY : 0); + } if (rv != SECSuccess) { - SECU_PrintPRandOSError(progName); - rv = SECFailure; - goto shutdown; + SECU_PrintPRandOSError(progName); + rv = SECFailure; + goto shutdown; } initialized = PR_TRUE; - SECU_RegisterDynamicOids(); + SECU_RegisterDynamicOids(); } certHandle = CERT_GetDefaultCertDB(); if (certutil.commands[cmd_Version].activated) { - printf("Certificate database content version: command not implemented.\n"); + printf("Certificate database content version: command not implemented.\n"); } if (PL_strcmp(slotname, "internal") == 0) - slot = PK11_GetInternalKeySlot(); + slot = PK11_GetInternalKeySlot(); else if (slotname != NULL) - slot = PK11_FindSlotByName(slotname); + slot = PK11_FindSlotByName(slotname); - if ( !slot && (certutil.commands[cmd_NewDBs].activated || - certutil.commands[cmd_ModifyCertTrust].activated || - certutil.commands[cmd_ChangePassword].activated || - certutil.commands[cmd_TokenReset].activated || - certutil.commands[cmd_CreateAndAddCert].activated || - certutil.commands[cmd_AddCert].activated || - certutil.commands[cmd_Merge].activated || - certutil.commands[cmd_UpgradeMerge].activated || - certutil.commands[cmd_AddEmailCert].activated)) { - - SECU_PrintError(progName, "could not find the slot %s",slotname); - rv = SECFailure; - goto shutdown; + if (!slot && (certutil.commands[cmd_NewDBs].activated || + certutil.commands[cmd_ModifyCertTrust].activated || + certutil.commands[cmd_ChangePassword].activated || + certutil.commands[cmd_TokenReset].activated || + certutil.commands[cmd_CreateAndAddCert].activated || + certutil.commands[cmd_AddCert].activated || + certutil.commands[cmd_Merge].activated || + certutil.commands[cmd_UpgradeMerge].activated || + certutil.commands[cmd_AddEmailCert].activated)) { + + SECU_PrintError(progName, "could not find the slot %s", slotname); + rv = SECFailure; + goto shutdown; } /* If creating new database, initialize the password. */ if (certutil.commands[cmd_NewDBs].activated) { - if(certutil.options[opt_EmptyPassword].activated && (PK11_NeedUserInit(slot))) - PK11_InitPin(slot, (char*)NULL, ""); - else - SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg, - certutil.options[opt_NewPasswordFile].arg); + if (certutil.options[opt_EmptyPassword].activated && (PK11_NeedUserInit(slot))) + PK11_InitPin(slot, (char *)NULL, ""); + else + SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg, + certutil.options[opt_NewPasswordFile].arg); } /* walk through the upgrade merge if necessary. @@ -2997,215 +3013,215 @@ certutil_main(int argc, char **argv, PRBool initialize) * the general case where 2 database need to be merged together. */ if (certutil.commands[cmd_UpgradeMerge].activated) { - if (*upgradeTokenName == 0) { - upgradeTokenName = upgradeID; - } - if (!PK11_IsInternal(slot)) { - fprintf(stderr, "Only internal DB's can be upgraded\n"); - rv = SECSuccess; - goto shutdown; - } - if (!PK11_IsRemovable(slot)) { - printf("database already upgraded.\n"); - rv = SECSuccess; - goto shutdown; - } - if (!PK11_NeedLogin(slot)) { - printf("upgrade complete!\n"); - rv = SECSuccess; - goto shutdown; - } - /* authenticate to the old DB if necessary */ - if (PORT_Strcmp(PK11_GetTokenName(slot), upgradeTokenName) == 0) { - /* if we need a password, supply it. This will be the password - * for the old database */ - rv = PK11_Authenticate(slot, PR_FALSE, &pwdata2); - if (rv != SECSuccess) { - SECU_PrintError(progName, "Could not get password for %s", - upgradeTokenName); - goto shutdown; - } - /* - * if we succeeded above, but still aren't logged in, that means - * we just supplied the password for the old database. We may - * need the password for the new database. NSS will automatically - * change the token names at this point - */ - if (PK11_IsLoggedIn(slot, &pwdata)) { - printf("upgrade complete!\n"); - rv = SECSuccess; - goto shutdown; - } - } - - /* call PK11_IsPresent to update our cached token information */ - if (!PK11_IsPresent(slot)) { - /* this shouldn't happen. We call isPresent to force a token - * info update */ - fprintf(stderr, "upgrade/merge internal error\n"); - rv = SECFailure; - goto shutdown; - } - - /* the token is now set to the state of the source database, - * if we need a password for it, PK11_Authenticate will - * automatically prompt us */ - rv = PK11_Authenticate(slot, PR_FALSE, &pwdata); - if (rv == SECSuccess) { - printf("upgrade complete!\n"); - } else { + if (*upgradeTokenName == 0) { + upgradeTokenName = upgradeID; + } + if (!PK11_IsInternal(slot)) { + fprintf(stderr, "Only internal DB's can be upgraded\n"); + rv = SECSuccess; + goto shutdown; + } + if (!PK11_IsRemovable(slot)) { + printf("database already upgraded.\n"); + rv = SECSuccess; + goto shutdown; + } + if (!PK11_NeedLogin(slot)) { + printf("upgrade complete!\n"); + rv = SECSuccess; + goto shutdown; + } + /* authenticate to the old DB if necessary */ + if (PORT_Strcmp(PK11_GetTokenName(slot), upgradeTokenName) == 0) { + /* if we need a password, supply it. This will be the password + * for the old database */ + rv = PK11_Authenticate(slot, PR_FALSE, &pwdata2); + if (rv != SECSuccess) { + SECU_PrintError(progName, "Could not get password for %s", + upgradeTokenName); + goto shutdown; + } + /* + * if we succeeded above, but still aren't logged in, that means + * we just supplied the password for the old database. We may + * need the password for the new database. NSS will automatically + * change the token names at this point + */ + if (PK11_IsLoggedIn(slot, &pwdata)) { + printf("upgrade complete!\n"); + rv = SECSuccess; + goto shutdown; + } + } + + /* call PK11_IsPresent to update our cached token information */ + if (!PK11_IsPresent(slot)) { + /* this shouldn't happen. We call isPresent to force a token + * info update */ + fprintf(stderr, "upgrade/merge internal error\n"); + rv = SECFailure; + goto shutdown; + } + + /* the token is now set to the state of the source database, + * if we need a password for it, PK11_Authenticate will + * automatically prompt us */ + rv = PK11_Authenticate(slot, PR_FALSE, &pwdata); + if (rv == SECSuccess) { + printf("upgrade complete!\n"); + } else { SECU_PrintError(progName, "Could not get password for %s", - PK11_GetTokenName(slot)); - } - goto shutdown; + PK11_GetTokenName(slot)); + } + goto shutdown; } /* * merge 2 databases. */ if (certutil.commands[cmd_Merge].activated) { - PK11SlotInfo *sourceSlot = NULL; - PK11MergeLog *log; - char *modspec = PR_smprintf( - "configDir='%s' certPrefix='%s' tokenDescription='%s'", - sourceDir, srcCertPrefix, - *upgradeTokenName ? upgradeTokenName : "Source Database"); - - if (!modspec) { - rv = SECFailure; - goto shutdown; - } - - sourceSlot = SECMOD_OpenUserDB(modspec); - PR_smprintf_free(modspec); - if (!sourceSlot) { - SECU_PrintError(progName, "couldn't open source database"); - rv = SECFailure; - goto shutdown; - } - - rv = PK11_Authenticate(slot, PR_FALSE, &pwdata); - if (rv != SECSuccess) { - SECU_PrintError(progName, "Couldn't get password for %s", - PK11_GetTokenName(slot)); - goto merge_fail; - } - - rv = PK11_Authenticate(sourceSlot, PR_FALSE, &pwdata2); - if (rv != SECSuccess) { - SECU_PrintError(progName, "Couldn't get password for %s", - PK11_GetTokenName(sourceSlot)); - goto merge_fail; - } - - log = PK11_CreateMergeLog(); - if (!log) { - rv = SECFailure; - SECU_PrintError(progName, "couldn't create error log"); - goto merge_fail; - } - - rv = PK11_MergeTokens(slot, sourceSlot, log, &pwdata, &pwdata2); - if (rv != SECSuccess) { - DumpMergeLog(progName, log); - } - PK11_DestroyMergeLog(log); - -merge_fail: - SECMOD_CloseUserDB(sourceSlot); - PK11_FreeSlot(sourceSlot); - goto shutdown; + PK11SlotInfo *sourceSlot = NULL; + PK11MergeLog *log; + char *modspec = PR_smprintf( + "configDir='%s' certPrefix='%s' tokenDescription='%s'", + sourceDir, srcCertPrefix, + *upgradeTokenName ? upgradeTokenName : "Source Database"); + + if (!modspec) { + rv = SECFailure; + goto shutdown; + } + + sourceSlot = SECMOD_OpenUserDB(modspec); + PR_smprintf_free(modspec); + if (!sourceSlot) { + SECU_PrintError(progName, "couldn't open source database"); + rv = SECFailure; + goto shutdown; + } + + rv = PK11_Authenticate(slot, PR_FALSE, &pwdata); + if (rv != SECSuccess) { + SECU_PrintError(progName, "Couldn't get password for %s", + PK11_GetTokenName(slot)); + goto merge_fail; + } + + rv = PK11_Authenticate(sourceSlot, PR_FALSE, &pwdata2); + if (rv != SECSuccess) { + SECU_PrintError(progName, "Couldn't get password for %s", + PK11_GetTokenName(sourceSlot)); + goto merge_fail; + } + + log = PK11_CreateMergeLog(); + if (!log) { + rv = SECFailure; + SECU_PrintError(progName, "couldn't create error log"); + goto merge_fail; + } + + rv = PK11_MergeTokens(slot, sourceSlot, log, &pwdata, &pwdata2); + if (rv != SECSuccess) { + DumpMergeLog(progName, log); + } + PK11_DestroyMergeLog(log); + + merge_fail: + SECMOD_CloseUserDB(sourceSlot); + PK11_FreeSlot(sourceSlot); + goto shutdown; } /* The following 8 options are mutually exclusive with all others. */ /* List certs (-L) */ if (certutil.commands[cmd_ListCerts].activated) { - if (certutil.options[opt_DumpExtensionValue].activated) { - const char *oid_str; - SECItem oid_item; + if (certutil.options[opt_DumpExtensionValue].activated) { + const char *oid_str; + SECItem oid_item; SECStatus srv; - oid_item.data = NULL; - oid_item.len = 0; - oid_str = certutil.options[opt_DumpExtensionValue].arg; - srv = GetOidFromString(NULL, &oid_item, oid_str, strlen(oid_str)); - if (srv != SECSuccess) { - SECU_PrintError(progName, "malformed extension OID %s", - oid_str); - goto shutdown; - } - rv = ListCerts(certHandle, name, email, slot, - PR_TRUE /*binary*/, PR_FALSE /*ascii*/, - &oid_item, - outFile, &pwdata); - } else { - rv = ListCerts(certHandle, name, email, slot, - certutil.options[opt_BinaryDER].activated, - certutil.options[opt_ASCIIForIO].activated, - NULL, outFile, &pwdata); - } - goto shutdown; + oid_item.data = NULL; + oid_item.len = 0; + oid_str = certutil.options[opt_DumpExtensionValue].arg; + srv = GetOidFromString(NULL, &oid_item, oid_str, strlen(oid_str)); + if (srv != SECSuccess) { + SECU_PrintError(progName, "malformed extension OID %s", + oid_str); + goto shutdown; + } + rv = ListCerts(certHandle, name, email, slot, + PR_TRUE /*binary*/, PR_FALSE /*ascii*/, + &oid_item, + outFile, &pwdata); + } else { + rv = ListCerts(certHandle, name, email, slot, + certutil.options[opt_BinaryDER].activated, + certutil.options[opt_ASCIIForIO].activated, + NULL, outFile, &pwdata); + } + goto shutdown; } if (certutil.commands[cmd_DumpChain].activated) { - rv = DumpChain(certHandle, name, + rv = DumpChain(certHandle, name, certutil.options[opt_ASCIIForIO].activated); - goto shutdown; + goto shutdown; } /* XXX needs work */ /* List keys (-K) */ if (certutil.commands[cmd_ListKeys].activated) { - rv = ListKeys(slot, name, 0 /*keyindex*/, keytype, PR_FALSE /*dopriv*/, - &pwdata); - goto shutdown; + rv = ListKeys(slot, name, 0 /*keyindex*/, keytype, PR_FALSE /*dopriv*/, + &pwdata); + goto shutdown; } /* List modules (-U) */ if (certutil.commands[cmd_ListModules].activated) { - rv = ListModules(); - goto shutdown; + rv = ListModules(); + goto shutdown; } /* Delete cert (-D) */ if (certutil.commands[cmd_DeleteCert].activated) { - rv = DeleteCert(certHandle, name); - goto shutdown; + rv = DeleteCert(certHandle, name); + goto shutdown; } /* Rename cert (--rename) */ if (certutil.commands[cmd_Rename].activated) { - rv = RenameCert(certHandle, name, newName); - goto shutdown; + rv = RenameCert(certHandle, name, newName); + goto shutdown; } /* Delete key (-F) */ if (certutil.commands[cmd_DeleteKey].activated) { - rv = DeleteKey(name, &pwdata); - goto shutdown; + rv = DeleteKey(name, &pwdata); + goto shutdown; } /* Modify trust attribute for cert (-M) */ if (certutil.commands[cmd_ModifyCertTrust].activated) { - rv = ChangeTrustAttributes(certHandle, slot, name, - certutil.options[opt_Trust].arg, &pwdata); - goto shutdown; + rv = ChangeTrustAttributes(certHandle, slot, name, + certutil.options[opt_Trust].arg, &pwdata); + goto shutdown; } /* Change key db password (-W) (future - change pw to slot?) */ if (certutil.commands[cmd_ChangePassword].activated) { - rv = SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg, - certutil.options[opt_NewPasswordFile].arg); - goto shutdown; + rv = SECU_ChangePW2(slot, 0, 0, certutil.options[opt_PasswordFile].arg, + certutil.options[opt_NewPasswordFile].arg); + goto shutdown; } /* Reset the a token */ if (certutil.commands[cmd_TokenReset].activated) { - char *sso_pass = ""; + char *sso_pass = ""; - if (certutil.options[opt_SSOPass].activated) { - sso_pass = certutil.options[opt_SSOPass].arg; - } - rv = PK11_ResetToken(slot,sso_pass); + if (certutil.options[opt_SSOPass].activated) { + sso_pass = certutil.options[opt_SSOPass].arg; + } + rv = PK11_ResetToken(slot, sso_pass); - goto shutdown; + goto shutdown; } /* Check cert validity against current time (-V) */ if (certutil.commands[cmd_CheckCertValidity].activated) { - /* XXX temporary hack for fips - must log in to get priv key */ - if (certutil.options[opt_VerifySig].activated) { - if (slot && PK11_NeedLogin(slot)) { + /* XXX temporary hack for fips - must log in to get priv key */ + if (certutil.options[opt_VerifySig].activated) { + if (slot && PK11_NeedLogin(slot)) { SECStatus newrv = PK11_Authenticate(slot, PR_TRUE, &pwdata); if (newrv != SECSuccess) { SECU_PrintError(progName, "could not authenticate to token %s.", @@ -3213,17 +3229,17 @@ certutil_main(int argc, char **argv, PRBool initialize) goto shutdown; } } - } - rv = ValidateCert(certHandle, name, - certutil.options[opt_ValidityTime].arg, - certutil.options[opt_Usage].arg, - certutil.options[opt_VerifySig].activated, - certutil.options[opt_DetailedInfo].activated, - certutil.options[opt_ASCIIForIO].activated, - &pwdata); - if (rv != SECSuccess && PR_GetError() == SEC_ERROR_INVALID_ARGS) + } + rv = ValidateCert(certHandle, name, + certutil.options[opt_ValidityTime].arg, + certutil.options[opt_Usage].arg, + certutil.options[opt_VerifySig].activated, + certutil.options[opt_DetailedInfo].activated, + certutil.options[opt_ASCIIForIO].activated, + &pwdata); + if (rv != SECSuccess && PR_GetError() == SEC_ERROR_INVALID_ARGS) SECU_PrintError(progName, "validation failed"); - goto shutdown; + goto shutdown; } /* @@ -3233,68 +3249,68 @@ certutil_main(int argc, char **argv, PRBool initialize) /* These commands may require keygen. */ if (certutil.commands[cmd_CertReq].activated || certutil.commands[cmd_CreateAndAddCert].activated || - certutil.commands[cmd_GenKeyPair].activated) { - if (keysource) { - CERTCertificate *keycert; - keycert = CERT_FindCertByNicknameOrEmailAddr(certHandle, keysource); - if (!keycert) { - keycert = PK11_FindCertFromNickname(keysource, NULL); - if (!keycert) { - SECU_PrintError(progName, - "%s is neither a key-type nor a nickname", keysource); - return SECFailure; - } - } - privkey = PK11_FindKeyByDERCert(slot, keycert, &pwdata); - if (privkey) - pubkey = CERT_ExtractPublicKey(keycert); - if (!pubkey) { - SECU_PrintError(progName, - "Could not get keys from cert %s", keysource); - rv = SECFailure; - CERT_DestroyCertificate(keycert); - goto shutdown; - } - keytype = privkey->keyType; - /* On CertReq for renewal if no subject has been - * specified obtain it from the certificate. - */ - if (certutil.commands[cmd_CertReq].activated && !subject) { - subject = CERT_AsciiToName(keycert->subjectName); - if (!subject) { - SECU_PrintError(progName, - "Could not get subject from certificate %s", keysource); - CERT_DestroyCertificate(keycert); - rv = SECFailure; - goto shutdown; - } - } - CERT_DestroyCertificate(keycert); - } else { - privkey = - CERTUTIL_GeneratePrivateKey(keytype, slot, keysize, - publicExponent, - certutil.options[opt_NoiseFile].arg, - &pubkey, - certutil.options[opt_PQGFile].arg, - keyAttrFlags, - keyOpFlagsOn, - keyOpFlagsOff, - &pwdata); - if (privkey == NULL) { - SECU_PrintError(progName, "unable to generate key(s)\n"); - rv = SECFailure; - goto shutdown; - } - } - privkey->wincx = &pwdata; - PORT_Assert(pubkey != NULL); - - /* If all that was needed was keygen, exit. */ - if (certutil.commands[cmd_GenKeyPair].activated) { - rv = SECSuccess; - goto shutdown; - } + certutil.commands[cmd_GenKeyPair].activated) { + if (keysource) { + CERTCertificate *keycert; + keycert = CERT_FindCertByNicknameOrEmailAddr(certHandle, keysource); + if (!keycert) { + keycert = PK11_FindCertFromNickname(keysource, NULL); + if (!keycert) { + SECU_PrintError(progName, + "%s is neither a key-type nor a nickname", keysource); + return SECFailure; + } + } + privkey = PK11_FindKeyByDERCert(slot, keycert, &pwdata); + if (privkey) + pubkey = CERT_ExtractPublicKey(keycert); + if (!pubkey) { + SECU_PrintError(progName, + "Could not get keys from cert %s", keysource); + rv = SECFailure; + CERT_DestroyCertificate(keycert); + goto shutdown; + } + keytype = privkey->keyType; + /* On CertReq for renewal if no subject has been + * specified obtain it from the certificate. + */ + if (certutil.commands[cmd_CertReq].activated && !subject) { + subject = CERT_AsciiToName(keycert->subjectName); + if (!subject) { + SECU_PrintError(progName, + "Could not get subject from certificate %s", keysource); + CERT_DestroyCertificate(keycert); + rv = SECFailure; + goto shutdown; + } + } + CERT_DestroyCertificate(keycert); + } else { + privkey = + CERTUTIL_GeneratePrivateKey(keytype, slot, keysize, + publicExponent, + certutil.options[opt_NoiseFile].arg, + &pubkey, + certutil.options[opt_PQGFile].arg, + keyAttrFlags, + keyOpFlagsOn, + keyOpFlagsOff, + &pwdata); + if (privkey == NULL) { + SECU_PrintError(progName, "unable to generate key(s)\n"); + rv = SECFailure; + goto shutdown; + } + } + privkey->wincx = &pwdata; + PORT_Assert(pubkey != NULL); + + /* If all that was needed was keygen, exit. */ + if (certutil.commands[cmd_GenKeyPair].activated) { + rv = SECSuccess; + goto shutdown; + } } /* If we need a list of extensions convert the flags into list format */ @@ -3311,15 +3327,15 @@ certutil_main(int argc, char **argv, PRBool initialize) certutil.options[opt_AddCmdKeyUsageExt].arg; } certutil_extns[ext_basicConstraint].activated = - certutil.options[opt_AddBasicConstraintExt].activated; + certutil.options[opt_AddBasicConstraintExt].activated; certutil_extns[ext_nameConstraints].activated = - certutil.options[opt_AddNameConstraintsExt].activated; + certutil.options[opt_AddNameConstraintsExt].activated; certutil_extns[ext_authorityKeyID].activated = - certutil.options[opt_AddAuthorityKeyIDExt].activated; + certutil.options[opt_AddAuthorityKeyIDExt].activated; certutil_extns[ext_subjectKeyID].activated = - certutil.options[opt_AddSubjectKeyIDExt].activated; + certutil.options[opt_AddSubjectKeyIDExt].activated; certutil_extns[ext_CRLDistPts].activated = - certutil.options[opt_AddCRLDistPtsExt].activated; + certutil.options[opt_AddCRLDistPtsExt].activated; certutil_extns[ext_NSCertType].activated = certutil.options[opt_AddCmdNSCertTypeExt].activated; if (!certutil_extns[ext_NSCertType].activated) { @@ -3340,36 +3356,36 @@ certutil_main(int argc, char **argv, PRBool initialize) certutil.options[opt_AddCmdExtKeyUsageExt].arg; } certutil_extns[ext_subjectAltName].activated = - certutil.options[opt_AddSubjectAltNameExt].activated; + certutil.options[opt_AddSubjectAltNameExt].activated; if (certutil_extns[ext_subjectAltName].activated) { certutil_extns[ext_subjectAltName].arg = certutil.options[opt_AddSubjectAltNameExt].arg; } certutil_extns[ext_authInfoAcc].activated = - certutil.options[opt_AddAuthInfoAccExt].activated; + certutil.options[opt_AddAuthInfoAccExt].activated; certutil_extns[ext_subjInfoAcc].activated = - certutil.options[opt_AddSubjInfoAccExt].activated; + certutil.options[opt_AddSubjInfoAccExt].activated; certutil_extns[ext_certPolicies].activated = - certutil.options[opt_AddCertPoliciesExt].activated; + certutil.options[opt_AddCertPoliciesExt].activated; certutil_extns[ext_policyMappings].activated = - certutil.options[opt_AddPolicyMapExt].activated; + certutil.options[opt_AddPolicyMapExt].activated; certutil_extns[ext_policyConstr].activated = - certutil.options[opt_AddPolicyConstrExt].activated; + certutil.options[opt_AddPolicyConstrExt].activated; certutil_extns[ext_inhibitAnyPolicy].activated = - certutil.options[opt_AddInhibAnyExt].activated; + certutil.options[opt_AddInhibAnyExt].activated; } /* -A -C or -E Read inFile */ if (certutil.commands[cmd_CreateNewCert].activated || - certutil.commands[cmd_AddCert].activated || - certutil.commands[cmd_AddEmailCert].activated) { - PRBool isCreate = certutil.commands[cmd_CreateNewCert].activated; - rv = SECU_ReadDERFromFile(isCreate ? &certReqDER : &certDER, inFile, - certutil.options[opt_ASCIIForIO].activated, - PR_TRUE); - if (rv) - goto shutdown; + certutil.commands[cmd_AddCert].activated || + certutil.commands[cmd_AddEmailCert].activated) { + PRBool isCreate = certutil.commands[cmd_CreateNewCert].activated; + rv = SECU_ReadDERFromFile(isCreate ? &certReqDER : &certDER, inFile, + certutil.options[opt_ASCIIForIO].activated, + PR_TRUE); + if (rv) + goto shutdown; } /* @@ -3378,18 +3394,19 @@ certutil_main(int argc, char **argv, PRBool initialize) /* Make a cert request (-R). */ if (certutil.commands[cmd_CertReq].activated) { - rv = CertReq(privkey, pubkey, keytype, hashAlgTag, subject, - certutil.options[opt_PhoneNumber].arg, - certutil.options[opt_ASCIIForIO].activated, - certutil.options[opt_ExtendedEmailAddrs].arg, - certutil.options[opt_ExtendedDNSNames].arg, + rv = CertReq(privkey, pubkey, keytype, hashAlgTag, subject, + certutil.options[opt_PhoneNumber].arg, + certutil.options[opt_ASCIIForIO].activated, + certutil.options[opt_ExtendedEmailAddrs].arg, + certutil.options[opt_ExtendedDNSNames].arg, certutil_extns, - (certutil.options[opt_GenericExtensions].activated ? - certutil.options[opt_GenericExtensions].arg : NULL), + (certutil.options[opt_GenericExtensions].activated ? + certutil.options[opt_GenericExtensions].arg + : NULL), &certReqDER); - if (rv) - goto shutdown; - privkey->wincx = &pwdata; + if (rv) + goto shutdown; + privkey->wincx = &pwdata; } /* @@ -3401,105 +3418,107 @@ certutil_main(int argc, char **argv, PRBool initialize) * and output the cert to another file. */ if (certutil.commands[cmd_CreateAndAddCert].activated) { - static certutilExtnList nullextnlist = {{PR_FALSE, NULL}}; - rv = CertReq(privkey, pubkey, keytype, hashAlgTag, subject, - certutil.options[opt_PhoneNumber].arg, - PR_FALSE, /* do not BASE64-encode regardless of -a option */ - NULL, - NULL, + static certutilExtnList nullextnlist = { { PR_FALSE, NULL } }; + rv = CertReq(privkey, pubkey, keytype, hashAlgTag, subject, + certutil.options[opt_PhoneNumber].arg, + PR_FALSE, /* do not BASE64-encode regardless of -a option */ + NULL, + NULL, nullextnlist, - (certutil.options[opt_GenericExtensions].activated ? - certutil.options[opt_GenericExtensions].arg : NULL), - &certReqDER); - if (rv) - goto shutdown; - privkey->wincx = &pwdata; + (certutil.options[opt_GenericExtensions].activated ? + certutil.options[opt_GenericExtensions].arg + : NULL), + &certReqDER); + if (rv) + goto shutdown; + privkey->wincx = &pwdata; } /* Create a certificate (-C or -S). */ if (certutil.commands[cmd_CreateAndAddCert].activated || - certutil.commands[cmd_CreateNewCert].activated) { - rv = CreateCert(certHandle, slot, - certutil.options[opt_IssuerName].arg, - &certReqDER, &privkey, &pwdata, hashAlgTag, - serialNumber, warpmonths, validityMonths, - certutil.options[opt_ExtendedEmailAddrs].arg, - certutil.options[opt_ExtendedDNSNames].arg, - certutil.options[opt_ASCIIForIO].activated && - certutil.commands[cmd_CreateNewCert].activated, - certutil.options[opt_SelfSign].activated, - certutil_extns, - (certutil.options[opt_GenericExtensions].activated ? - certutil.options[opt_GenericExtensions].arg : NULL), + certutil.commands[cmd_CreateNewCert].activated) { + rv = CreateCert(certHandle, slot, + certutil.options[opt_IssuerName].arg, + &certReqDER, &privkey, &pwdata, hashAlgTag, + serialNumber, warpmonths, validityMonths, + certutil.options[opt_ExtendedEmailAddrs].arg, + certutil.options[opt_ExtendedDNSNames].arg, + certutil.options[opt_ASCIIForIO].activated && + certutil.commands[cmd_CreateNewCert].activated, + certutil.options[opt_SelfSign].activated, + certutil_extns, + (certutil.options[opt_GenericExtensions].activated ? + certutil.options[opt_GenericExtensions].arg + : NULL), certVersion, - &certDER); - if (rv) - goto shutdown; + &certDER); + if (rv) + goto shutdown; } - /* + /* * Adding a cert to the database (or slot) */ /* -A -E or -S Add the cert to the DB */ if (certutil.commands[cmd_CreateAndAddCert].activated || - certutil.commands[cmd_AddCert].activated || - certutil.commands[cmd_AddEmailCert].activated) { - if (strstr(certutil.options[opt_Trust].arg, "u")) { - fprintf(stderr, "Notice: Trust flag u is set automatically if the " - "private key is present.\n"); - } - rv = AddCert(slot, certHandle, name, - certutil.options[opt_Trust].arg, - &certDER, - certutil.commands[cmd_AddEmailCert].activated,&pwdata); - if (rv) - goto shutdown; + certutil.commands[cmd_AddCert].activated || + certutil.commands[cmd_AddEmailCert].activated) { + if (strstr(certutil.options[opt_Trust].arg, "u")) { + fprintf(stderr, "Notice: Trust flag u is set automatically if the " + "private key is present.\n"); + } + rv = AddCert(slot, certHandle, name, + certutil.options[opt_Trust].arg, + &certDER, + certutil.commands[cmd_AddEmailCert].activated, &pwdata); + if (rv) + goto shutdown; } if (certutil.commands[cmd_CertReq].activated || - certutil.commands[cmd_CreateNewCert].activated) { - SECItem * item = certutil.commands[cmd_CertReq].activated ? &certReqDER - : &certDER; - PRInt32 written = PR_Write(outFile, item->data, item->len); - if (written < 0 || (PRUint32) written != item->len) { - rv = SECFailure; - } + certutil.commands[cmd_CreateNewCert].activated) { + SECItem *item = certutil.commands[cmd_CertReq].activated ? &certReqDER + : &certDER; + PRInt32 written = PR_Write(outFile, item->data, item->len); + if (written < 0 || (PRUint32)written != item->len) { + rv = SECFailure; + } } shutdown: if (slot) { - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); } if (privkey) { - SECKEY_DestroyPrivateKey(privkey); + SECKEY_DestroyPrivateKey(privkey); } if (pubkey) { - SECKEY_DestroyPublicKey(pubkey); + SECKEY_DestroyPublicKey(pubkey); } if (subject) { - CERT_DestroyName(subject); + CERT_DestroyName(subject); } if (name) { - PL_strfree(name); + PL_strfree(name); } if (newName) { - PL_strfree(newName); + PL_strfree(newName); } if (inFile && inFile != PR_STDIN) { - PR_Close(inFile); + PR_Close(inFile); } if (outFile && outFile != PR_STDOUT) { - PR_Close(outFile); + PR_Close(outFile); } SECITEM_FreeItem(&certReqDER, PR_FALSE); SECITEM_FreeItem(&certDER, PR_FALSE); if (pwdata.data && pwdata.source == PW_PLAINTEXT) { - /* Allocated by a PL_strdup call in SECU_GetModulePassword. */ - PL_strfree(pwdata.data); + /* Allocated by a PL_strdup call in SECU_GetModulePassword. */ + PL_strfree(pwdata.data); } if (email) { - PL_strfree(email); + PL_strfree(email); } /* Open the batch command file. @@ -3520,106 +3539,106 @@ certutil_main(int argc, char **argv, PRBool initialize) */ if ((SECSuccess == rv) && certutil.commands[cmd_Batch].activated) { - FILE* batchFile = NULL; + FILE *batchFile = NULL; char *nextcommand = NULL; - PRInt32 cmd_len = 0, buf_size = 0; - static const int increment = 512; + PRInt32 cmd_len = 0, buf_size = 0; + static const int increment = 512; if (!certutil.options[opt_InputFile].activated || !certutil.options[opt_InputFile].arg) { - PR_fprintf(PR_STDERR, - "%s: no batch input file specified.\n", - progName); - return 255; + PR_fprintf(PR_STDERR, + "%s: no batch input file specified.\n", + progName); + return 255; } batchFile = fopen(certutil.options[opt_InputFile].arg, "r"); if (!batchFile) { - PR_fprintf(PR_STDERR, - "%s: unable to open \"%s\" for reading (%ld, %ld).\n", - progName, certutil.options[opt_InputFile].arg, - PR_GetError(), PR_GetOSError()); - return 255; + PR_fprintf(PR_STDERR, + "%s: unable to open \"%s\" for reading (%ld, %ld).\n", + progName, certutil.options[opt_InputFile].arg, + PR_GetError(), PR_GetOSError()); + return 255; } /* read and execute command-lines in a loop */ - while ( SECSuccess == rv ) { + while (SECSuccess == rv) { PRBool invalid = PR_FALSE; int newargc = 2; - char* space = NULL; - char* nextarg = NULL; - char** newargv = NULL; - char* crlf; - - if (cmd_len + increment > buf_size) { - char * new_buf; - buf_size += increment; - new_buf = PORT_Realloc(nextcommand, buf_size); - if (!new_buf) { - PR_fprintf(PR_STDERR, "%s: PORT_Realloc(%ld) failed\n", - progName, buf_size); - break; - } - nextcommand = new_buf; - nextcommand[cmd_len] = '\0'; - } - if (!fgets(nextcommand + cmd_len, buf_size - cmd_len, batchFile)) { - break; - } + char *space = NULL; + char *nextarg = NULL; + char **newargv = NULL; + char *crlf; + + if (cmd_len + increment > buf_size) { + char *new_buf; + buf_size += increment; + new_buf = PORT_Realloc(nextcommand, buf_size); + if (!new_buf) { + PR_fprintf(PR_STDERR, "%s: PORT_Realloc(%ld) failed\n", + progName, buf_size); + break; + } + nextcommand = new_buf; + nextcommand[cmd_len] = '\0'; + } + if (!fgets(nextcommand + cmd_len, buf_size - cmd_len, batchFile)) { + break; + } crlf = PORT_Strrchr(nextcommand, '\n'); if (crlf) { *crlf = '\0'; } - cmd_len = strlen(nextcommand); - if (cmd_len && nextcommand[cmd_len - 1] == '\\') { - nextcommand[--cmd_len] = '\0'; - continue; - } + cmd_len = strlen(nextcommand); + if (cmd_len && nextcommand[cmd_len - 1] == '\\') { + nextcommand[--cmd_len] = '\0'; + continue; + } /* we now need to split the command into argc / argv format */ - newargv = PORT_Alloc(sizeof(char*)*(newargc+1)); + newargv = PORT_Alloc(sizeof(char *) * (newargc + 1)); newargv[0] = progName; newargv[1] = nextcommand; nextarg = nextcommand; - while ((space = PORT_Strpbrk(nextarg, " \f\n\r\t\v")) ) { - while (isspace(*space) ) { + while ((space = PORT_Strpbrk(nextarg, " \f\n\r\t\v"))) { + while (isspace(*space)) { *space = '\0'; - space ++; + space++; } if (*space == '\0') { break; } else if (*space != '\"') { nextarg = space; } else { - char* closingquote = strchr(space+1, '\"'); + char *closingquote = strchr(space + 1, '\"'); if (closingquote) { *closingquote = '\0'; space++; - nextarg = closingquote+1; + nextarg = closingquote + 1; } else { invalid = PR_TRUE; nextarg = space; } } newargc++; - newargv = PORT_Realloc(newargv, sizeof(char*)*(newargc+1)); - newargv[newargc-1] = space; + newargv = PORT_Realloc(newargv, sizeof(char *) * (newargc + 1)); + newargv[newargc - 1] = space; } newargv[newargc] = NULL; - + /* invoke next command */ if (PR_TRUE == invalid) { PR_fprintf(PR_STDERR, "Missing closing quote in batch command :\n%s\nNot executed.\n", nextcommand); rv = SECFailure; } else { - if (0 != certutil_main(newargc, newargv, PR_FALSE) ) + if (0 != certutil_main(newargc, newargv, PR_FALSE)) rv = SECFailure; } PORT_Free(newargv); - cmd_len = 0; - nextcommand[0] = '\0'; + cmd_len = 0; + nextcommand[0] = '\0'; } - PORT_Free(nextcommand); + PORT_Free(nextcommand); fclose(batchFile); } @@ -3627,9 +3646,9 @@ certutil_main(int argc, char **argv, PRBool initialize) exit(1); } if (rv == SECSuccess) { - return 0; + return 0; } else { - return 255; + return 255; } } @@ -3641,4 +3660,3 @@ main(int argc, char **argv) PR_Cleanup(); return rv; } - diff --git a/cmd/certutil/certutil.h b/cmd/certutil/certutil.h index 9286649071..565587264d 100644 --- a/cmd/certutil/certutil.h +++ b/cmd/certutil/certutil.h @@ -3,11 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _CERTUTIL_H -#define _CERTUTIL_H +#define _CERTUTIL_H extern SECKEYPrivateKey * CERTUTIL_GeneratePrivateKey(KeyType keytype, - PK11SlotInfo *slot, + PK11SlotInfo *slot, int rsasize, int publicExponent, char *noise, @@ -41,7 +41,7 @@ enum certutilExtns { typedef struct ExtensionEntryStr { PRBool activated; - const char *arg; + const char *arg; } ExtensionEntry; typedef ExtensionEntry certutilExtnList[ext_End]; @@ -54,5 +54,4 @@ extern SECStatus GetOidFromString(PLArenaPool *arena, SECItem *to, const char *from, size_t fromLen); -#endif /* _CERTUTIL_H */ - +#endif /* _CERTUTIL_H */ diff --git a/cmd/certutil/keystuff.c b/cmd/certutil/keystuff.c index 1bc6cab4ad..27a38450bf 100644 --- a/cmd/certutil/keystuff.c +++ b/cmd/certutil/keystuff.c @@ -12,13 +12,13 @@ #include #endif -#if defined(XP_WIN) || defined (XP_PC) +#if defined(XP_WIN) || defined(XP_PC) #include #include #endif #if defined(__sun) && !defined(SVR4) -extern int fclose(FILE*); +extern int fclose(FILE *); extern int fprintf(FILE *, char *, ...); extern int isatty(int); extern char *sys_errlist[]; @@ -35,13 +35,15 @@ extern char *sys_errlist[]; #define NUM_KEYSTROKES 120 #define RAND_BUF_SIZE 60 -#define ERROR_BREAK rv = SECFailure;break; +#define ERROR_BREAK \ + rv = SECFailure; \ + break; 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) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams, prime) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams, subPrime) }, + { SEC_ASN1_INTEGER, offsetof(SECKEYPQGParams, base) }, { 0 } }; @@ -49,20 +51,21 @@ const SEC_ASN1Template SECKEY_PQGParamsTemplate[] = { static int UpdateRNG(void) { - char randbuf[RAND_BUF_SIZE]; - int fd, count; - int c; - int rv = 0; + char randbuf[RAND_BUF_SIZE]; + int fd, count; + int c; + int rv = 0; #ifdef XP_UNIX - cc_t orig_cc_min; - cc_t orig_cc_time; - tcflag_t orig_lflag; + cc_t orig_cc_min; + cc_t orig_cc_time; + tcflag_t orig_lflag; struct termios tio; #endif - char meter[] = { - "\r| |" }; + char meter[] = { + "\r| |" + }; -#define FPS fprintf(stderr, +#define FPS fprintf(stderr, FPS "\n"); FPS "A random seed must be generated that will be used in the\n"); FPS "creation of your key. One of the easiest ways to create a\n"); @@ -95,19 +98,19 @@ UpdateRNG(void) count = 0; while (count < sizeof randbuf) { #if defined(XP_UNIX) - c = getc(stdin); + c = getc(stdin); #else - c = getch(); + c = getch(); #endif - if (c == EOF) { - rv = -1; - break; - } - randbuf[count] = c; - if (count == 0 || c != randbuf[count-1]) { - count++; - FPS "*"); - } + if (c == EOF) { + rv = -1; + break; + } + randbuf[count] = c; + if (count == 0 || c != randbuf[count - 1]) { + count++; + FPS "*"); + } } PK11_RandomUpdate(randbuf, sizeof randbuf); memset(randbuf, 0, sizeof randbuf); @@ -115,9 +118,9 @@ UpdateRNG(void) FPS "\n\n"); FPS "Finished. Press enter to continue: "); while ((c = getc(stdin)) != '\n' && c != EOF) - ; - if (c == EOF) - rv = -1; + ; + if (c == EOF) + rv = -1; FPS "\n"); #undef FPS @@ -132,78 +135,78 @@ UpdateRNG(void) return rv; } -static const unsigned char P[] = { 0, - 0xc6, 0x2a, 0x47, 0x73, 0xea, 0x78, 0xfa, 0x65, - 0x47, 0x69, 0x39, 0x10, 0x08, 0x55, 0x6a, 0xdd, - 0xbf, 0x77, 0xe1, 0x9a, 0x69, 0x73, 0xba, 0x66, - 0x37, 0x08, 0x93, 0x9e, 0xdb, 0x5d, 0x01, 0x08, - 0xb8, 0x3a, 0x73, 0xe9, 0x85, 0x5f, 0xa7, 0x2b, - 0x63, 0x7f, 0xd0, 0xc6, 0x4c, 0xdc, 0xfc, 0x8b, - 0xa6, 0x03, 0xc9, 0x9c, 0x80, 0x5e, 0xec, 0xc6, - 0x21, 0x23, 0xf7, 0x8e, 0xa4, 0x7b, 0x77, 0x83, - 0x02, 0x44, 0xf8, 0x05, 0xd7, 0x36, 0x52, 0x13, - 0x57, 0x78, 0x97, 0xf3, 0x7b, 0xcf, 0x1f, 0xc9, - 0x2a, 0xa4, 0x71, 0x9d, 0xa8, 0xd8, 0x5d, 0xc5, - 0x3b, 0x64, 0x3a, 0x72, 0x60, 0x62, 0xb0, 0xb8, - 0xf3, 0xb1, 0xe7, 0xb9, 0x76, 0xdf, 0x74, 0xbe, - 0x87, 0x6a, 0xd2, 0xf1, 0xa9, 0x44, 0x8b, 0x63, - 0x76, 0x4f, 0x5d, 0x21, 0x63, 0xb5, 0x4f, 0x3c, - 0x7b, 0x61, 0xb2, 0xf3, 0xea, 0xc5, 0xd8, 0xef, - 0x30, 0x50, 0x59, 0x33, 0x61, 0xc0, 0xf3, 0x6e, - 0x21, 0xcf, 0x15, 0x35, 0x4a, 0x87, 0x2b, 0xc3, - 0xf6, 0x5a, 0x1f, 0x24, 0x22, 0xc5, 0xeb, 0x47, - 0x34, 0x4a, 0x1b, 0xb5, 0x2e, 0x71, 0x52, 0x8f, - 0x2d, 0x7d, 0xa9, 0x96, 0x8a, 0x7c, 0x61, 0xdb, - 0xc0, 0xdc, 0xf1, 0xca, 0x28, 0x69, 0x1c, 0x97, - 0xad, 0xea, 0x0d, 0x9e, 0x02, 0xe6, 0xe5, 0x7d, - 0xad, 0xe0, 0x42, 0x91, 0x4d, 0xfa, 0xe2, 0x81, - 0x16, 0x2b, 0xc2, 0x96, 0x3b, 0x32, 0x8c, 0x20, - 0x69, 0x8b, 0x5b, 0x17, 0x3c, 0xf9, 0x13, 0x6c, - 0x98, 0x27, 0x1c, 0xca, 0xcf, 0x33, 0xaa, 0x93, - 0x21, 0xaf, 0x17, 0x6e, 0x5e, 0x00, 0x37, 0xd9, - 0x34, 0x8a, 0x47, 0xd2, 0x1c, 0x67, 0x32, 0x60, - 0xb6, 0xc7, 0xb0, 0xfd, 0x32, 0x90, 0x93, 0x32, - 0xaa, 0x11, 0xba, 0x23, 0x19, 0x39, 0x6a, 0x42, - 0x7c, 0x1f, 0xb7, 0x28, 0xdb, 0x64, 0xad, 0xd9 }; +static const unsigned char P[] = { 0, + 0xc6, 0x2a, 0x47, 0x73, 0xea, 0x78, 0xfa, 0x65, + 0x47, 0x69, 0x39, 0x10, 0x08, 0x55, 0x6a, 0xdd, + 0xbf, 0x77, 0xe1, 0x9a, 0x69, 0x73, 0xba, 0x66, + 0x37, 0x08, 0x93, 0x9e, 0xdb, 0x5d, 0x01, 0x08, + 0xb8, 0x3a, 0x73, 0xe9, 0x85, 0x5f, 0xa7, 0x2b, + 0x63, 0x7f, 0xd0, 0xc6, 0x4c, 0xdc, 0xfc, 0x8b, + 0xa6, 0x03, 0xc9, 0x9c, 0x80, 0x5e, 0xec, 0xc6, + 0x21, 0x23, 0xf7, 0x8e, 0xa4, 0x7b, 0x77, 0x83, + 0x02, 0x44, 0xf8, 0x05, 0xd7, 0x36, 0x52, 0x13, + 0x57, 0x78, 0x97, 0xf3, 0x7b, 0xcf, 0x1f, 0xc9, + 0x2a, 0xa4, 0x71, 0x9d, 0xa8, 0xd8, 0x5d, 0xc5, + 0x3b, 0x64, 0x3a, 0x72, 0x60, 0x62, 0xb0, 0xb8, + 0xf3, 0xb1, 0xe7, 0xb9, 0x76, 0xdf, 0x74, 0xbe, + 0x87, 0x6a, 0xd2, 0xf1, 0xa9, 0x44, 0x8b, 0x63, + 0x76, 0x4f, 0x5d, 0x21, 0x63, 0xb5, 0x4f, 0x3c, + 0x7b, 0x61, 0xb2, 0xf3, 0xea, 0xc5, 0xd8, 0xef, + 0x30, 0x50, 0x59, 0x33, 0x61, 0xc0, 0xf3, 0x6e, + 0x21, 0xcf, 0x15, 0x35, 0x4a, 0x87, 0x2b, 0xc3, + 0xf6, 0x5a, 0x1f, 0x24, 0x22, 0xc5, 0xeb, 0x47, + 0x34, 0x4a, 0x1b, 0xb5, 0x2e, 0x71, 0x52, 0x8f, + 0x2d, 0x7d, 0xa9, 0x96, 0x8a, 0x7c, 0x61, 0xdb, + 0xc0, 0xdc, 0xf1, 0xca, 0x28, 0x69, 0x1c, 0x97, + 0xad, 0xea, 0x0d, 0x9e, 0x02, 0xe6, 0xe5, 0x7d, + 0xad, 0xe0, 0x42, 0x91, 0x4d, 0xfa, 0xe2, 0x81, + 0x16, 0x2b, 0xc2, 0x96, 0x3b, 0x32, 0x8c, 0x20, + 0x69, 0x8b, 0x5b, 0x17, 0x3c, 0xf9, 0x13, 0x6c, + 0x98, 0x27, 0x1c, 0xca, 0xcf, 0x33, 0xaa, 0x93, + 0x21, 0xaf, 0x17, 0x6e, 0x5e, 0x00, 0x37, 0xd9, + 0x34, 0x8a, 0x47, 0xd2, 0x1c, 0x67, 0x32, 0x60, + 0xb6, 0xc7, 0xb0, 0xfd, 0x32, 0x90, 0x93, 0x32, + 0xaa, 0x11, 0xba, 0x23, 0x19, 0x39, 0x6a, 0x42, + 0x7c, 0x1f, 0xb7, 0x28, 0xdb, 0x64, 0xad, 0xd9 }; static const unsigned char Q[] = { 0, - 0xe6, 0xa3, 0xc9, 0xc6, 0x51, 0x92, 0x8b, 0xb3, - 0x98, 0x8f, 0x97, 0xb8, 0x31, 0x0d, 0x4a, 0x03, - 0x1e, 0xba, 0x4e, 0xe6, 0xc8, 0x90, 0x98, 0x1d, - 0x3a, 0x95, 0xf4, 0xf1 }; -static const unsigned char G[] = { - 0x70, 0x32, 0x58, 0x5d, 0xb3, 0xbf, 0xc3, 0x62, - 0x63, 0x0b, 0xf8, 0xa5, 0xe1, 0xed, 0xeb, 0x79, - 0xac, 0x18, 0x41, 0x64, 0xb3, 0xda, 0x4c, 0xa7, - 0x92, 0x63, 0xb1, 0x33, 0x7c, 0xcb, 0x43, 0xdc, - 0x1f, 0x38, 0x63, 0x5e, 0x0e, 0x6d, 0x45, 0xd1, - 0xc9, 0x67, 0xf3, 0xcf, 0x3d, 0x2d, 0x16, 0x4e, - 0x92, 0x16, 0x06, 0x59, 0x29, 0x89, 0x6f, 0x54, - 0xff, 0xc5, 0x71, 0xc8, 0x3a, 0x95, 0x84, 0xb6, - 0x7e, 0x7b, 0x1e, 0x8b, 0x47, 0x9d, 0x7a, 0x3a, - 0x36, 0x9b, 0x70, 0x2f, 0xd1, 0xbd, 0xef, 0xe8, - 0x3a, 0x41, 0xd4, 0xf3, 0x1f, 0x81, 0xc7, 0x1f, - 0x96, 0x7c, 0x30, 0xab, 0xf4, 0x7a, 0xac, 0x93, - 0xed, 0x6f, 0x67, 0xb0, 0xc9, 0x5b, 0xf3, 0x83, - 0x9d, 0xa0, 0xd7, 0xb9, 0x01, 0xed, 0x28, 0xae, - 0x1c, 0x6e, 0x2e, 0x48, 0xac, 0x9f, 0x7d, 0xf3, - 0x00, 0x48, 0xee, 0x0e, 0xfb, 0x7e, 0x5e, 0xcb, - 0xf5, 0x39, 0xd8, 0x92, 0x90, 0x61, 0x2d, 0x1e, - 0x3c, 0xd3, 0x55, 0x0d, 0x34, 0xd1, 0x81, 0xc4, - 0x89, 0xea, 0x94, 0x2b, 0x56, 0x33, 0x73, 0x58, - 0x48, 0xbf, 0x23, 0x72, 0x19, 0x5f, 0x19, 0xac, - 0xff, 0x09, 0xc8, 0xcd, 0xab, 0x71, 0xef, 0x9e, - 0x20, 0xfd, 0xe3, 0xb8, 0x27, 0x9e, 0x65, 0xb1, - 0x85, 0xcd, 0x88, 0xfe, 0xd4, 0xd7, 0x64, 0x4d, - 0xe1, 0xe8, 0xa6, 0xe5, 0x96, 0xc8, 0x5d, 0x9c, - 0xc6, 0x70, 0x6b, 0xba, 0x77, 0x4e, 0x90, 0x4a, - 0xb0, 0x96, 0xc5, 0xa0, 0x9e, 0x2c, 0x01, 0x03, - 0xbe, 0xbd, 0x71, 0xba, 0x0a, 0x6f, 0x9f, 0xe5, - 0xdb, 0x04, 0x08, 0xf2, 0x9e, 0x0f, 0x1b, 0xac, - 0xcd, 0xbb, 0x65, 0x12, 0xcf, 0x77, 0xc9, 0x7d, - 0xbe, 0x94, 0x4b, 0x9c, 0x5b, 0xde, 0x0d, 0xfa, - 0x57, 0xdd, 0x77, 0x32, 0xf0, 0x5b, 0x34, 0xfd, - 0x19, 0x95, 0x33, 0x60, 0x87, 0xe2, 0xa2, 0xf4 }; - + 0xe6, 0xa3, 0xc9, 0xc6, 0x51, 0x92, 0x8b, 0xb3, + 0x98, 0x8f, 0x97, 0xb8, 0x31, 0x0d, 0x4a, 0x03, + 0x1e, 0xba, 0x4e, 0xe6, 0xc8, 0x90, 0x98, 0x1d, + 0x3a, 0x95, 0xf4, 0xf1 }; +static const unsigned char G[] = { + 0x70, 0x32, 0x58, 0x5d, 0xb3, 0xbf, 0xc3, 0x62, + 0x63, 0x0b, 0xf8, 0xa5, 0xe1, 0xed, 0xeb, 0x79, + 0xac, 0x18, 0x41, 0x64, 0xb3, 0xda, 0x4c, 0xa7, + 0x92, 0x63, 0xb1, 0x33, 0x7c, 0xcb, 0x43, 0xdc, + 0x1f, 0x38, 0x63, 0x5e, 0x0e, 0x6d, 0x45, 0xd1, + 0xc9, 0x67, 0xf3, 0xcf, 0x3d, 0x2d, 0x16, 0x4e, + 0x92, 0x16, 0x06, 0x59, 0x29, 0x89, 0x6f, 0x54, + 0xff, 0xc5, 0x71, 0xc8, 0x3a, 0x95, 0x84, 0xb6, + 0x7e, 0x7b, 0x1e, 0x8b, 0x47, 0x9d, 0x7a, 0x3a, + 0x36, 0x9b, 0x70, 0x2f, 0xd1, 0xbd, 0xef, 0xe8, + 0x3a, 0x41, 0xd4, 0xf3, 0x1f, 0x81, 0xc7, 0x1f, + 0x96, 0x7c, 0x30, 0xab, 0xf4, 0x7a, 0xac, 0x93, + 0xed, 0x6f, 0x67, 0xb0, 0xc9, 0x5b, 0xf3, 0x83, + 0x9d, 0xa0, 0xd7, 0xb9, 0x01, 0xed, 0x28, 0xae, + 0x1c, 0x6e, 0x2e, 0x48, 0xac, 0x9f, 0x7d, 0xf3, + 0x00, 0x48, 0xee, 0x0e, 0xfb, 0x7e, 0x5e, 0xcb, + 0xf5, 0x39, 0xd8, 0x92, 0x90, 0x61, 0x2d, 0x1e, + 0x3c, 0xd3, 0x55, 0x0d, 0x34, 0xd1, 0x81, 0xc4, + 0x89, 0xea, 0x94, 0x2b, 0x56, 0x33, 0x73, 0x58, + 0x48, 0xbf, 0x23, 0x72, 0x19, 0x5f, 0x19, 0xac, + 0xff, 0x09, 0xc8, 0xcd, 0xab, 0x71, 0xef, 0x9e, + 0x20, 0xfd, 0xe3, 0xb8, 0x27, 0x9e, 0x65, 0xb1, + 0x85, 0xcd, 0x88, 0xfe, 0xd4, 0xd7, 0x64, 0x4d, + 0xe1, 0xe8, 0xa6, 0xe5, 0x96, 0xc8, 0x5d, 0x9c, + 0xc6, 0x70, 0x6b, 0xba, 0x77, 0x4e, 0x90, 0x4a, + 0xb0, 0x96, 0xc5, 0xa0, 0x9e, 0x2c, 0x01, 0x03, + 0xbe, 0xbd, 0x71, 0xba, 0x0a, 0x6f, 0x9f, 0xe5, + 0xdb, 0x04, 0x08, 0xf2, 0x9e, 0x0f, 0x1b, 0xac, + 0xcd, 0xbb, 0x65, 0x12, 0xcf, 0x77, 0xc9, 0x7d, + 0xbe, 0x94, 0x4b, 0x9c, 0x5b, 0xde, 0x0d, 0xfa, + 0x57, 0xdd, 0x77, 0x32, 0xf0, 0x5b, 0x34, 0xfd, + 0x19, 0x95, 0x33, 0x60, 0x87, 0xe2, 0xa2, 0xf4 +}; /* P, Q, G have been generated using the NSS makepqg utility: * makepqg -l 2048 -g 224 -r @@ -236,33 +239,33 @@ decode_pqg_params(const char *str) PLArenaPool *arena; SECKEYPQGParams *params; SECStatus status; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) return NULL; - + params = PORT_ArenaZAlloc(arena, sizeof(SECKEYPQGParams)); if (params == NULL) goto loser; params->arena = arena; - + buf = (char *)ATOB_AsciiToData(str, &len); if ((buf == NULL) || (len == 0)) goto loser; - + status = SEC_ASN1Decode(arena, params, SECKEY_PQGParamsTemplate, buf, len); if (status != SECSuccess) goto loser; - + return params; - + loser: if (arena != NULL) PORT_FreeArena(arena, PR_FALSE); return NULL; } -void +void CERTUTIL_DestroyParamsPQG(SECKEYPQGParams *params) { if (params->arena) { @@ -274,110 +277,110 @@ static int pqg_prime_bits(const SECKEYPQGParams *params) { int primeBits = 0; - + if (params != NULL) { - int i; - for (i = 0; params->prime.data[i] == 0; i++) { - /* empty */; - } - primeBits = (params->prime.len - i) * 8; + int i; + for (i = 0; params->prime.data[i] == 0; i++) { + /* empty */; + } + primeBits = (params->prime.len - i) * 8; } - + return primeBits; } static char * getPQGString(const char *filename) { - unsigned char *buf = NULL; - PRFileDesc *src; - PRInt32 numBytes; - PRStatus prStatus; - PRFileInfo info; + unsigned char *buf = NULL; + PRFileDesc *src; + PRInt32 numBytes; + PRStatus prStatus; + PRFileInfo info; - src = PR_Open(filename, PR_RDONLY, 0); + src = PR_Open(filename, PR_RDONLY, 0); if (!src) { - fprintf(stderr, "Failed to open PQG file %s\n", filename); - return NULL; + fprintf(stderr, "Failed to open PQG file %s\n", filename); + return NULL; } prStatus = PR_GetOpenFileInfo(src, &info); if (prStatus == PR_SUCCESS) { - buf = (unsigned char*)PORT_Alloc(info.size + 1); + buf = (unsigned char *)PORT_Alloc(info.size + 1); } if (!buf) { - PR_Close(src); - fprintf(stderr, "Failed to read PQG file %s\n", filename); - return NULL; + PR_Close(src); + fprintf(stderr, "Failed to read PQG file %s\n", filename); + return NULL; } numBytes = PR_Read(src, buf, info.size); PR_Close(src); if (numBytes != info.size) { - PORT_Free(buf); - fprintf(stderr, "Failed to read PQG file %s\n", filename); - PORT_SetError(SEC_ERROR_IO); - return NULL; + PORT_Free(buf); + fprintf(stderr, "Failed to read PQG file %s\n", filename); + PORT_SetError(SEC_ERROR_IO); + return NULL; } - if (buf[numBytes-1] == '\n') - numBytes--; - if (buf[numBytes-1] == '\r') - numBytes--; + if (buf[numBytes - 1] == '\n') + numBytes--; + if (buf[numBytes - 1] == '\r') + numBytes--; buf[numBytes] = 0; - + return (char *)buf; } -static SECKEYPQGParams* +static SECKEYPQGParams * getpqgfromfile(int keyBits, const char *pqgFile) { char *end, *str, *pqgString; - SECKEYPQGParams* params = NULL; + SECKEYPQGParams *params = NULL; str = pqgString = getPQGString(pqgFile); - if (!str) - return NULL; + if (!str) + return NULL; do { - end = PORT_Strchr(str, ','); - if (end) - *end = '\0'; - params = decode_pqg_params(str); - if (params) { - int primeBits = pqg_prime_bits(params); - if (keyBits == primeBits) - break; - CERTUTIL_DestroyParamsPQG(params); - params = NULL; - } - if (end) - str = end + 1; + end = PORT_Strchr(str, ','); + if (end) + *end = '\0'; + params = decode_pqg_params(str); + if (params) { + int primeBits = pqg_prime_bits(params); + if (keyBits == primeBits) + break; + CERTUTIL_DestroyParamsPQG(params); + params = NULL; + } + if (end) + str = end + 1; } while (end); PORT_Free(pqgString); return params; } -static SECStatus +static SECStatus CERTUTIL_FileForRNG(const char *noise) { char buf[2048]; PRFileDesc *fd; PRInt32 count; - fd = PR_Open(noise,PR_RDONLY,0); + fd = PR_Open(noise, PR_RDONLY, 0); if (!fd) { - fprintf(stderr, "failed to open noise file."); - return SECFailure; + fprintf(stderr, "failed to open noise file."); + return SECFailure; } do { - count = PR_Read(fd,buf,sizeof(buf)); - if (count > 0) { - PK11_RandomUpdate(buf,count); - } + count = PR_Read(fd, buf, sizeof(buf)); + if (count > 0) { + PK11_RandomUpdate(buf, count); + } } while (count > 0); PR_Close(fd); @@ -390,92 +393,92 @@ typedef struct curveNameTagPairStr { SECOidTag curveOidTag; } CurveNameTagPair; -#define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP192R1 +#define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP192R1 /* #define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP160R1 */ static CurveNameTagPair nameTagPair[] = -{ - { "sect163k1", SEC_OID_SECG_EC_SECT163K1}, - { "nistk163", SEC_OID_SECG_EC_SECT163K1}, - { "sect163r1", SEC_OID_SECG_EC_SECT163R1}, - { "sect163r2", SEC_OID_SECG_EC_SECT163R2}, - { "nistb163", SEC_OID_SECG_EC_SECT163R2}, - { "sect193r1", SEC_OID_SECG_EC_SECT193R1}, - { "sect193r2", SEC_OID_SECG_EC_SECT193R2}, - { "sect233k1", SEC_OID_SECG_EC_SECT233K1}, - { "nistk233", SEC_OID_SECG_EC_SECT233K1}, - { "sect233r1", SEC_OID_SECG_EC_SECT233R1}, - { "nistb233", SEC_OID_SECG_EC_SECT233R1}, - { "sect239k1", SEC_OID_SECG_EC_SECT239K1}, - { "sect283k1", SEC_OID_SECG_EC_SECT283K1}, - { "nistk283", SEC_OID_SECG_EC_SECT283K1}, - { "sect283r1", SEC_OID_SECG_EC_SECT283R1}, - { "nistb283", SEC_OID_SECG_EC_SECT283R1}, - { "sect409k1", SEC_OID_SECG_EC_SECT409K1}, - { "nistk409", SEC_OID_SECG_EC_SECT409K1}, - { "sect409r1", SEC_OID_SECG_EC_SECT409R1}, - { "nistb409", SEC_OID_SECG_EC_SECT409R1}, - { "sect571k1", SEC_OID_SECG_EC_SECT571K1}, - { "nistk571", SEC_OID_SECG_EC_SECT571K1}, - { "sect571r1", SEC_OID_SECG_EC_SECT571R1}, - { "nistb571", SEC_OID_SECG_EC_SECT571R1}, - { "secp160k1", SEC_OID_SECG_EC_SECP160K1}, - { "secp160r1", SEC_OID_SECG_EC_SECP160R1}, - { "secp160r2", SEC_OID_SECG_EC_SECP160R2}, - { "secp192k1", SEC_OID_SECG_EC_SECP192K1}, - { "secp192r1", SEC_OID_SECG_EC_SECP192R1}, - { "nistp192", SEC_OID_SECG_EC_SECP192R1}, - { "secp224k1", SEC_OID_SECG_EC_SECP224K1}, - { "secp224r1", SEC_OID_SECG_EC_SECP224R1}, - { "nistp224", SEC_OID_SECG_EC_SECP224R1}, - { "secp256k1", SEC_OID_SECG_EC_SECP256K1}, - { "secp256r1", SEC_OID_SECG_EC_SECP256R1}, - { "nistp256", SEC_OID_SECG_EC_SECP256R1}, - { "secp384r1", SEC_OID_SECG_EC_SECP384R1}, - { "nistp384", SEC_OID_SECG_EC_SECP384R1}, - { "secp521r1", SEC_OID_SECG_EC_SECP521R1}, - { "nistp521", SEC_OID_SECG_EC_SECP521R1}, - - { "prime192v1", SEC_OID_ANSIX962_EC_PRIME192V1 }, - { "prime192v2", SEC_OID_ANSIX962_EC_PRIME192V2 }, - { "prime192v3", SEC_OID_ANSIX962_EC_PRIME192V3 }, - { "prime239v1", SEC_OID_ANSIX962_EC_PRIME239V1 }, - { "prime239v2", SEC_OID_ANSIX962_EC_PRIME239V2 }, - { "prime239v3", SEC_OID_ANSIX962_EC_PRIME239V3 }, - - { "c2pnb163v1", SEC_OID_ANSIX962_EC_C2PNB163V1 }, - { "c2pnb163v2", SEC_OID_ANSIX962_EC_C2PNB163V2 }, - { "c2pnb163v3", SEC_OID_ANSIX962_EC_C2PNB163V3 }, - { "c2pnb176v1", SEC_OID_ANSIX962_EC_C2PNB176V1 }, - { "c2tnb191v1", SEC_OID_ANSIX962_EC_C2TNB191V1 }, - { "c2tnb191v2", SEC_OID_ANSIX962_EC_C2TNB191V2 }, - { "c2tnb191v3", SEC_OID_ANSIX962_EC_C2TNB191V3 }, - { "c2onb191v4", SEC_OID_ANSIX962_EC_C2ONB191V4 }, - { "c2onb191v5", SEC_OID_ANSIX962_EC_C2ONB191V5 }, - { "c2pnb208w1", SEC_OID_ANSIX962_EC_C2PNB208W1 }, - { "c2tnb239v1", SEC_OID_ANSIX962_EC_C2TNB239V1 }, - { "c2tnb239v2", SEC_OID_ANSIX962_EC_C2TNB239V2 }, - { "c2tnb239v3", SEC_OID_ANSIX962_EC_C2TNB239V3 }, - { "c2onb239v4", SEC_OID_ANSIX962_EC_C2ONB239V4 }, - { "c2onb239v5", SEC_OID_ANSIX962_EC_C2ONB239V5 }, - { "c2pnb272w1", SEC_OID_ANSIX962_EC_C2PNB272W1 }, - { "c2pnb304w1", SEC_OID_ANSIX962_EC_C2PNB304W1 }, - { "c2tnb359v1", SEC_OID_ANSIX962_EC_C2TNB359V1 }, - { "c2pnb368w1", SEC_OID_ANSIX962_EC_C2PNB368W1 }, - { "c2tnb431r1", SEC_OID_ANSIX962_EC_C2TNB431R1 }, - - { "secp112r1", SEC_OID_SECG_EC_SECP112R1}, - { "secp112r2", SEC_OID_SECG_EC_SECP112R2}, - { "secp128r1", SEC_OID_SECG_EC_SECP128R1}, - { "secp128r2", SEC_OID_SECG_EC_SECP128R2}, - - { "sect113r1", SEC_OID_SECG_EC_SECT113R1}, - { "sect113r2", SEC_OID_SECG_EC_SECT113R2}, - { "sect131r1", SEC_OID_SECG_EC_SECT131R1}, - { "sect131r2", SEC_OID_SECG_EC_SECT131R2}, -}; - -static SECKEYECParams * + { + { "sect163k1", SEC_OID_SECG_EC_SECT163K1 }, + { "nistk163", SEC_OID_SECG_EC_SECT163K1 }, + { "sect163r1", SEC_OID_SECG_EC_SECT163R1 }, + { "sect163r2", SEC_OID_SECG_EC_SECT163R2 }, + { "nistb163", SEC_OID_SECG_EC_SECT163R2 }, + { "sect193r1", SEC_OID_SECG_EC_SECT193R1 }, + { "sect193r2", SEC_OID_SECG_EC_SECT193R2 }, + { "sect233k1", SEC_OID_SECG_EC_SECT233K1 }, + { "nistk233", SEC_OID_SECG_EC_SECT233K1 }, + { "sect233r1", SEC_OID_SECG_EC_SECT233R1 }, + { "nistb233", SEC_OID_SECG_EC_SECT233R1 }, + { "sect239k1", SEC_OID_SECG_EC_SECT239K1 }, + { "sect283k1", SEC_OID_SECG_EC_SECT283K1 }, + { "nistk283", SEC_OID_SECG_EC_SECT283K1 }, + { "sect283r1", SEC_OID_SECG_EC_SECT283R1 }, + { "nistb283", SEC_OID_SECG_EC_SECT283R1 }, + { "sect409k1", SEC_OID_SECG_EC_SECT409K1 }, + { "nistk409", SEC_OID_SECG_EC_SECT409K1 }, + { "sect409r1", SEC_OID_SECG_EC_SECT409R1 }, + { "nistb409", SEC_OID_SECG_EC_SECT409R1 }, + { "sect571k1", SEC_OID_SECG_EC_SECT571K1 }, + { "nistk571", SEC_OID_SECG_EC_SECT571K1 }, + { "sect571r1", SEC_OID_SECG_EC_SECT571R1 }, + { "nistb571", SEC_OID_SECG_EC_SECT571R1 }, + { "secp160k1", SEC_OID_SECG_EC_SECP160K1 }, + { "secp160r1", SEC_OID_SECG_EC_SECP160R1 }, + { "secp160r2", SEC_OID_SECG_EC_SECP160R2 }, + { "secp192k1", SEC_OID_SECG_EC_SECP192K1 }, + { "secp192r1", SEC_OID_SECG_EC_SECP192R1 }, + { "nistp192", SEC_OID_SECG_EC_SECP192R1 }, + { "secp224k1", SEC_OID_SECG_EC_SECP224K1 }, + { "secp224r1", SEC_OID_SECG_EC_SECP224R1 }, + { "nistp224", SEC_OID_SECG_EC_SECP224R1 }, + { "secp256k1", SEC_OID_SECG_EC_SECP256K1 }, + { "secp256r1", SEC_OID_SECG_EC_SECP256R1 }, + { "nistp256", SEC_OID_SECG_EC_SECP256R1 }, + { "secp384r1", SEC_OID_SECG_EC_SECP384R1 }, + { "nistp384", SEC_OID_SECG_EC_SECP384R1 }, + { "secp521r1", SEC_OID_SECG_EC_SECP521R1 }, + { "nistp521", SEC_OID_SECG_EC_SECP521R1 }, + + { "prime192v1", SEC_OID_ANSIX962_EC_PRIME192V1 }, + { "prime192v2", SEC_OID_ANSIX962_EC_PRIME192V2 }, + { "prime192v3", SEC_OID_ANSIX962_EC_PRIME192V3 }, + { "prime239v1", SEC_OID_ANSIX962_EC_PRIME239V1 }, + { "prime239v2", SEC_OID_ANSIX962_EC_PRIME239V2 }, + { "prime239v3", SEC_OID_ANSIX962_EC_PRIME239V3 }, + + { "c2pnb163v1", SEC_OID_ANSIX962_EC_C2PNB163V1 }, + { "c2pnb163v2", SEC_OID_ANSIX962_EC_C2PNB163V2 }, + { "c2pnb163v3", SEC_OID_ANSIX962_EC_C2PNB163V3 }, + { "c2pnb176v1", SEC_OID_ANSIX962_EC_C2PNB176V1 }, + { "c2tnb191v1", SEC_OID_ANSIX962_EC_C2TNB191V1 }, + { "c2tnb191v2", SEC_OID_ANSIX962_EC_C2TNB191V2 }, + { "c2tnb191v3", SEC_OID_ANSIX962_EC_C2TNB191V3 }, + { "c2onb191v4", SEC_OID_ANSIX962_EC_C2ONB191V4 }, + { "c2onb191v5", SEC_OID_ANSIX962_EC_C2ONB191V5 }, + { "c2pnb208w1", SEC_OID_ANSIX962_EC_C2PNB208W1 }, + { "c2tnb239v1", SEC_OID_ANSIX962_EC_C2TNB239V1 }, + { "c2tnb239v2", SEC_OID_ANSIX962_EC_C2TNB239V2 }, + { "c2tnb239v3", SEC_OID_ANSIX962_EC_C2TNB239V3 }, + { "c2onb239v4", SEC_OID_ANSIX962_EC_C2ONB239V4 }, + { "c2onb239v5", SEC_OID_ANSIX962_EC_C2ONB239V5 }, + { "c2pnb272w1", SEC_OID_ANSIX962_EC_C2PNB272W1 }, + { "c2pnb304w1", SEC_OID_ANSIX962_EC_C2PNB304W1 }, + { "c2tnb359v1", SEC_OID_ANSIX962_EC_C2TNB359V1 }, + { "c2pnb368w1", SEC_OID_ANSIX962_EC_C2PNB368W1 }, + { "c2tnb431r1", SEC_OID_ANSIX962_EC_C2TNB431R1 }, + + { "secp112r1", SEC_OID_SECG_EC_SECP112R1 }, + { "secp112r2", SEC_OID_SECG_EC_SECP112R2 }, + { "secp128r1", SEC_OID_SECG_EC_SECP128R1 }, + { "secp128r2", SEC_OID_SECG_EC_SECP128R2 }, + + { "sect113r1", SEC_OID_SECG_EC_SECT113R1 }, + { "sect113r2", SEC_OID_SECG_EC_SECT113R2 }, + { "sect131r1", SEC_OID_SECG_EC_SECT131R1 }, + { "sect131r2", SEC_OID_SECG_EC_SECT131R2 }, + }; + +static SECKEYECParams * getECParams(const char *curve) { SECKEYECParams *ecparams; @@ -484,19 +487,19 @@ getECParams(const char *curve) int i, numCurves; if (curve != NULL) { - numCurves = sizeof(nameTagPair)/sizeof(CurveNameTagPair); - for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); - i++) { - if (PL_strcmp(curve, nameTagPair[i].curveName) == 0) - curveOidTag = nameTagPair[i].curveOidTag; - } + numCurves = sizeof(nameTagPair) / sizeof(CurveNameTagPair); + for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); + i++) { + if (PL_strcmp(curve, nameTagPair[i].curveName) == 0) + curveOidTag = nameTagPair[i].curveOidTag; + } } /* Return NULL if curve name is not recognized */ - if ((curveOidTag == SEC_OID_UNKNOWN) || - (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) { + if ((curveOidTag == SEC_OID_UNKNOWN) || + (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) { fprintf(stderr, "Unrecognized elliptic curve %s\n", curve); - return NULL; + return NULL; } ecparams = SECITEM_AllocItem(NULL, NULL, (2 + oidData->oid.len)); @@ -516,86 +519,92 @@ getECParams(const char *curve) SECKEYPrivateKey * CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size, - int publicExponent, const char *noise, - SECKEYPublicKey **pubkeyp, const char *pqgFile, - PK11AttrFlags attrFlags, CK_FLAGS opFlagsOn, - CK_FLAGS opFlagsOff, secuPWData *pwdata) + int publicExponent, const char *noise, + SECKEYPublicKey **pubkeyp, const char *pqgFile, + PK11AttrFlags attrFlags, CK_FLAGS opFlagsOn, + CK_FLAGS opFlagsOff, secuPWData *pwdata) { - CK_MECHANISM_TYPE mechanism; - PK11RSAGenParams rsaparams; - SECKEYPQGParams * dsaparams = NULL; - void * params; - SECKEYPrivateKey * privKey = NULL; + CK_MECHANISM_TYPE mechanism; + PK11RSAGenParams rsaparams; + SECKEYPQGParams *dsaparams = NULL; + void *params; + SECKEYPrivateKey *privKey = NULL; if (slot == NULL) - return NULL; + return NULL; if (PK11_Authenticate(slot, PR_TRUE, pwdata) != SECSuccess) - return NULL; + return NULL; /* * Do some random-number initialization. */ if (noise) { - SECStatus rv = CERTUTIL_FileForRNG(noise); - if (rv != SECSuccess) { - PORT_SetError(PR_END_OF_FILE_ERROR); /* XXX */ - return NULL; - } + SECStatus rv = CERTUTIL_FileForRNG(noise); + if (rv != SECSuccess) { + PORT_SetError(PR_END_OF_FILE_ERROR); /* XXX */ + return NULL; + } } else { - int rv = UpdateRNG(); - if (rv) { - PORT_SetError(PR_END_OF_FILE_ERROR); - return NULL; - } + int rv = UpdateRNG(); + if (rv) { + PORT_SetError(PR_END_OF_FILE_ERROR); + return NULL; + } } switch (keytype) { - case rsaKey: - rsaparams.keySizeInBits = size; - rsaparams.pe = publicExponent; - mechanism = CKM_RSA_PKCS_KEY_PAIR_GEN; - params = &rsaparams; - break; - case dsaKey: - mechanism = CKM_DSA_KEY_PAIR_GEN; - if (pqgFile) { - dsaparams = getpqgfromfile(size, pqgFile); - if (dsaparams == NULL) - return NULL; - params = dsaparams; - } else { - /* cast away const, and don't set dsaparams */ - params = (void *)&default_pqg_params; - } - break; + case rsaKey: + rsaparams.keySizeInBits = size; + rsaparams.pe = publicExponent; + mechanism = CKM_RSA_PKCS_KEY_PAIR_GEN; + params = &rsaparams; + break; + case dsaKey: + mechanism = CKM_DSA_KEY_PAIR_GEN; + if (pqgFile) { + dsaparams = getpqgfromfile(size, pqgFile); + if (dsaparams == NULL) + return NULL; + params = dsaparams; + } else { + /* cast away const, and don't set dsaparams */ + params = (void *)&default_pqg_params; + } + break; #ifndef NSS_DISABLE_ECC - case ecKey: - mechanism = CKM_EC_KEY_PAIR_GEN; - /* For EC keys, PQGFile determines EC parameters */ - if ((params = (void *) getECParams(pqgFile)) == NULL) - return NULL; - break; + case ecKey: + mechanism = CKM_EC_KEY_PAIR_GEN; + /* For EC keys, PQGFile determines EC parameters */ + if ((params = (void *)getECParams(pqgFile)) == NULL) + return NULL; + break; #endif /* NSS_DISABLE_ECC */ - default: - return NULL; + default: + return NULL; } fprintf(stderr, "\n\n"); fprintf(stderr, "Generating key. This may take a few moments...\n\n"); privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism, params, pubkeyp, - attrFlags, opFlagsOn, opFlagsOn|opFlagsOff, - pwdata /*wincx*/); + attrFlags, opFlagsOn, opFlagsOn | + opFlagsOff, + pwdata /*wincx*/); /* free up the params */ switch (keytype) { - case dsaKey: if (dsaparams) CERTUTIL_DestroyParamsPQG(dsaparams); - break; + case dsaKey: + if (dsaparams) + CERTUTIL_DestroyParamsPQG(dsaparams); + break; #ifndef NSS_DISABLE_ECC - case ecKey: SECITEM_FreeItem((SECItem *)params, PR_TRUE); break; + case ecKey: + SECITEM_FreeItem((SECItem *)params, PR_TRUE); + break; #endif - default: /* nothing to free */ break; + default: /* nothing to free */ + break; } return privKey; } diff --git a/cmd/chktest/chktest.c b/cmd/chktest/chktest.c index 49c2a16ef6..a33d184570 100644 --- a/cmd/chktest/chktest.c +++ b/cmd/chktest/chktest.c @@ -8,7 +8,8 @@ #include "blapi.h" #include "secutil.h" -static int Usage() +static int +Usage() { fprintf(stderr, "Usage: chktest \n"); fprintf(stderr, " Will test for valid chk file.\n"); @@ -16,14 +17,15 @@ static int Usage() exit(1); } -int main(int argc, char **argv) +int +main(int argc, char **argv) { SECStatus rv = SECFailure; PRBool good_result = PR_FALSE; if (argc != 2) - return Usage(); - + return Usage(); + rv = RNG_RNGInit(); if (rv != SECSuccess) { SECU_PrintPRandOSError(""); @@ -37,7 +39,7 @@ int main(int argc, char **argv) RNG_SystemInfoForRNG(); good_result = BLAPI_SHVerifyFile(argv[1]); - printf("%s\n", - (good_result ? "SUCCESS" : "FAILURE")); + printf("%s\n", + (good_result ? "SUCCESS" : "FAILURE")); return (good_result) ? SECSuccess : SECFailure; } diff --git a/cmd/crlutil/crlgen.c b/cmd/crlutil/crlgen.c index 1fad324909..5ff84c1904 100644 --- a/cmd/crlutil/crlgen.c +++ b/cmd/crlutil/crlgen.c @@ -9,7 +9,6 @@ ** */ - #include #include @@ -23,7 +22,6 @@ #include "pk11func.h" #include "crlgen.h" - /* Destroys extHandle and data. data was create on heap. * extHandle creaded by CERT_StartCRLEntryExtensions. entry * was allocated on arena.*/ @@ -38,9 +36,8 @@ destroyEntryData(CRLGENEntryData *data) PORT_Free(data); } - /* Prints error messages along with line number */ -void +void crlgen_PrintError(int line, char *msg, ...) { va_list args; @@ -54,21 +51,20 @@ crlgen_PrintError(int line, char *msg, ...) } /* Finds CRLGENEntryData in hashtable according PRUint64 value * - certId : cert serial number*/ -static CRLGENEntryData* -crlgen_FindEntry(CRLGENGeneratorData *crlGenData, SECItem *certId) +static CRLGENEntryData * +crlgen_FindEntry(CRLGENGeneratorData *crlGenData, SECItem *certId) { if (!crlGenData->entryDataHashTable || !certId) return NULL; - return (CRLGENEntryData*) + return (CRLGENEntryData *) PL_HashTableLookup(crlGenData->entryDataHashTable, certId); } - /* Removes CRLGENEntryData from hashtable according to certId * - certId : cert serial number*/ static SECStatus -crlgen_RmEntry(CRLGENGeneratorData *crlGenData, SECItem *certId) +crlgen_RmEntry(CRLGENGeneratorData *crlGenData, SECItem *certId) { CRLGENEntryData *data = NULL; @@ -83,10 +79,9 @@ crlgen_RmEntry(CRLGENGeneratorData *crlGenData, SECItem *certId) return SECFailure; } - /* Stores CRLGENEntryData in hashtable according to certId * - certId : cert serial number*/ -static CRLGENEntryData* +static CRLGENEntryData * crlgen_PlaceAnEntry(CRLGENGeneratorData *crlGenData, CERTCrlEntry *entry, SECItem *certId) { @@ -106,7 +101,7 @@ crlgen_PlaceAnEntry(CRLGENGeneratorData *crlGenData, newData->entry = entry; newData->certId = certId; if (!PL_HashTableAdd(crlGenData->entryDataHashTable, - newData->certId, newData)) { + newData->certId, newData)) { crlgen_PrintError(crlGenData->parsedLineNum, "Can not add entryData structure\n"); return NULL; @@ -122,7 +117,7 @@ struct commitData { /* HT PL_HashTableEnumerateEntries callback. Sorts hashtable entries of the * table he. Returns value through arg parameter*/ -static PRIntn PR_CALLBACK +static PRIntn PR_CALLBACK crlgen_CommitEntryData(PLHashEntry *he, PRIntn i, void *arg) { CRLGENEntryData *data = NULL; @@ -131,23 +126,21 @@ crlgen_CommitEntryData(PLHashEntry *he, PRIntn i, void *arg) if (!he) { return HT_ENUMERATE_NEXT; } - data = (CRLGENEntryData*)he->value; + data = (CRLGENEntryData *)he->value; PORT_Assert(data); PORT_Assert(arg); if (data) { - struct commitData *dt = (struct commitData*)arg; + struct commitData *dt = (struct commitData *)arg; dt->entries[dt->pos++] = data->entry; destroyEntryData(data); } return HT_ENUMERATE_NEXT; } - - /* Copy char * datainto allocated in arena SECItem */ -static SECStatus +static SECStatus crlgen_SetString(PLArenaPool *arena, const char *dataIn, SECItem *value) { SECItem item; @@ -158,7 +151,7 @@ crlgen_SetString(PLArenaPool *arena, const char *dataIn, SECItem *value) return SECFailure; } - item.data = (void*)dataIn; + item.data = (void *)dataIn; item.len = PORT_Strlen(dataIn); return SECITEM_CopyItem(arena, value, &item); @@ -166,8 +159,8 @@ crlgen_SetString(PLArenaPool *arena, const char *dataIn, SECItem *value) /* Creates CERTGeneralName from parsed data for the Authority Key Extension */ static CERTGeneralName * -crlgen_GetGeneralName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, - const char *data) +crlgen_GetGeneralName(PLArenaPool *arena, CRLGENGeneratorData *crlGenData, + const char *data) { CERTGeneralName *namesList = NULL; CERTGeneralName *current; @@ -181,13 +174,13 @@ crlgen_GetGeneralName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, if (!data) return NULL; - PORT_Assert (arena); + PORT_Assert(arena); if (!arena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; } - mark = PORT_ArenaMark (arena); + mark = PORT_ArenaMark(arena); nextChunk = data; currData = data; @@ -207,7 +200,7 @@ crlgen_GetGeneralName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, (nextChunk - sepPrt - 1)); buffer[nextChunk - sepPrt - 1] = '\0'; } - nameLen = PR_MIN(sepPrt - currData, sizeof(name) - 1 ); + nameLen = PR_MIN(sepPrt - currData, sizeof(name) - 1); PORT_Memcpy(name, currData, nameLen); name[nameLen] = '\0'; currData = nextChunk + 1; @@ -230,7 +223,8 @@ crlgen_GetGeneralName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, intValue = certIPAddress; else if (!PORT_Strcmp(name, "registerID")) intValue = certRegisterID; - else intValue = -1; + else + intValue = -1; if (intValue >= certOtherName && intValue <= certRegisterID) { if (namesList == NULL) { @@ -249,52 +243,52 @@ crlgen_GetGeneralName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, } current->type = intValue; switch (current->type) { - case certURI: - case certDNSName: - case certRFC822Name: - current->name.other.data = PORT_ArenaAlloc (arena, strlen (buffer)); - if (current->name.other.data == NULL) { - rv = SECFailure; - break; - } - PORT_Memcpy(current->name.other.data, buffer, - current->name.other.len = strlen(buffer)); - break; - - case certEDIPartyName: - case certIPAddress: - case certOtherName: - case certRegisterID: - case certX400Address: { - - current->name.other.data = PORT_ArenaAlloc (arena, strlen (buffer) + 2); - if (current->name.other.data == NULL) { - rv = SECFailure; - break; - } - - PORT_Memcpy (current->name.other.data + 2, buffer, strlen (buffer)); -/* This may not be accurate for all cases.For now, use this tag type */ - current->name.other.data[0] = (char)(((current->type - 1) & 0x1f)| 0x80); - current->name.other.data[1] = (char)strlen (buffer); - current->name.other.len = strlen (buffer) + 2; - break; - } - - case certDirectoryName: { - CERTName *directoryName = NULL; - - directoryName = CERT_AsciiToName (buffer); - if (!directoryName) { - rv = SECFailure; - break; - } - - rv = CERT_CopyName (arena, ¤t->name.directoryName, directoryName); - CERT_DestroyName (directoryName); - - break; - } + case certURI: + case certDNSName: + case certRFC822Name: + current->name.other.data = PORT_ArenaAlloc(arena, strlen(buffer)); + if (current->name.other.data == NULL) { + rv = SECFailure; + break; + } + PORT_Memcpy(current->name.other.data, buffer, + current->name.other.len = strlen(buffer)); + break; + + case certEDIPartyName: + case certIPAddress: + case certOtherName: + case certRegisterID: + case certX400Address: { + + current->name.other.data = PORT_ArenaAlloc(arena, strlen(buffer) + 2); + if (current->name.other.data == NULL) { + rv = SECFailure; + break; + } + + PORT_Memcpy(current->name.other.data + 2, buffer, strlen(buffer)); + /* This may not be accurate for all cases.For now, use this tag type */ + current->name.other.data[0] = (char)(((current->type - 1) & 0x1f) | 0x80); + current->name.other.data[1] = (char)strlen(buffer); + current->name.other.len = strlen(buffer) + 2; + break; + } + + case certDirectoryName: { + CERTName *directoryName = NULL; + + directoryName = CERT_AsciiToName(buffer); + if (!directoryName) { + rv = SECFailure; + break; + } + + rv = CERT_CopyName(arena, ¤t->name.directoryName, directoryName); + CERT_DestroyName(directoryName); + + break; + } } if (rv != SECSuccess) break; @@ -303,10 +297,10 @@ crlgen_GetGeneralName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, tail->l.next = &(current->l); tail = current; - } while(nextChunk != data + strlen(data)); + } while (nextChunk != data + strlen(data)); if (rv != SECSuccess) { - PORT_ArenaRelease (arena, mark); + PORT_ArenaRelease(arena, mark); namesList = NULL; } return (namesList); @@ -314,8 +308,8 @@ crlgen_GetGeneralName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, /* Creates CERTGeneralName from parsed data for the Authority Key Extension */ static CERTGeneralName * -crlgen_DistinguishedName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, - const char *data) +crlgen_DistinguishedName(PLArenaPool *arena, CRLGENGeneratorData *crlGenData, + const char *data) { CERTName *directoryName = NULL; CERTGeneralName *current; @@ -324,13 +318,13 @@ crlgen_DistinguishedName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, if (!data) return NULL; - PORT_Assert (arena); + PORT_Assert(arena); if (!arena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; } - mark = PORT_ArenaMark (arena); + mark = PORT_ArenaMark(arena); current = PORT_ArenaZNew(arena, CERTGeneralName); if (current == NULL) { @@ -339,29 +333,28 @@ crlgen_DistinguishedName (PLArenaPool *arena, CRLGENGeneratorData *crlGenData, current->type = certDirectoryName; current->l.next = ¤t->l; current->l.prev = ¤t->l; - - directoryName = CERT_AsciiToName ((char*)data); + + directoryName = CERT_AsciiToName((char *)data); if (!directoryName) { goto loser; } - - rv = CERT_CopyName (arena, ¤t->name.directoryName, directoryName); - CERT_DestroyName (directoryName); - loser: + rv = CERT_CopyName(arena, ¤t->name.directoryName, directoryName); + CERT_DestroyName(directoryName); + +loser: if (rv != SECSuccess) { - PORT_SetError (rv); - PORT_ArenaRelease (arena, mark); + PORT_SetError(rv); + PORT_ArenaRelease(arena, mark); current = NULL; } return (current); } - /* Adding Authority Key ID extension to extension handle. */ -static SECStatus -crlgen_AddAuthKeyID (CRLGENGeneratorData *crlGenData, - const char **dataArr) +static SECStatus +crlgen_AddAuthKeyID(CRLGENGeneratorData *crlGenData, + const char **dataArr) { void *extHandle = NULL; CERTAuthKeyID *authKeyID = NULL; @@ -394,18 +387,18 @@ crlgen_AddAuthKeyID (CRLGENGeneratorData *crlGenData, } if (dataArr[3] == NULL) { - rv = crlgen_SetString (arena, dataArr[2], &authKeyID->keyID); + rv = crlgen_SetString(arena, dataArr[2], &authKeyID->keyID); if (rv != SECSuccess) goto loser; } else { - rv = crlgen_SetString (arena, dataArr[3], - &authKeyID->authCertSerialNumber); + rv = crlgen_SetString(arena, dataArr[3], + &authKeyID->authCertSerialNumber); if (rv != SECSuccess) goto loser; - authKeyID->authCertIssuer = - crlgen_DistinguishedName (arena, crlGenData, dataArr[2]); - if (authKeyID->authCertIssuer == NULL && SECFailure == PORT_GetError ()){ + authKeyID->authCertIssuer = + crlgen_DistinguishedName(arena, crlGenData, dataArr[2]); + if (authKeyID->authCertIssuer == NULL && SECFailure == PORT_GetError()) { crlgen_PrintError(crlGenData->parsedLineNum, "syntax error.\n"); rv = SECFailure; goto loser; @@ -415,25 +408,24 @@ crlgen_AddAuthKeyID (CRLGENGeneratorData *crlGenData, rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, authKeyID, (*dataArr[1] == '1') ? PR_TRUE : PR_FALSE, - SEC_OID_X509_AUTH_KEY_ID, - (EXTEN_EXT_VALUE_ENCODER) CERT_EncodeAuthKeyID); - loser: + SEC_OID_X509_AUTH_KEY_ID, + (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeAuthKeyID); +loser: if (arena) - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return rv; -} +} /* Creates and add Subject Alternative Names extension */ -static SECStatus +static SECStatus crlgen_AddIssuerAltNames(CRLGENGeneratorData *crlGenData, - const char **dataArr) + const char **dataArr) { CERTGeneralName *nameList = NULL; PLArenaPool *arena = NULL; void *extHandle = NULL; SECStatus rv = SECSuccess; - PORT_Assert(dataArr && crlGenData); if (!crlGenData || !dataArr) { return SECFailure; @@ -475,16 +467,16 @@ crlgen_AddIssuerAltNames(CRLGENGeneratorData *crlGenData, rv = SECU_EncodeAndAddExtensionValue(arena, extHandle, nameList, (*dataArr[1] == '1') ? PR_TRUE : PR_FALSE, - SEC_OID_X509_ISSUER_ALT_NAME, + SEC_OID_X509_ISSUER_ALT_NAME, (EXTEN_EXT_VALUE_ENCODER)CERT_EncodeAltNameExtension); - loser: +loser: if (arena) - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return rv; } /* Creates and adds CRLNumber extension to extension handle. - * Since, this is CRL extension, extension handle is the one + * Since, this is CRL extension, extension handle is the one * related to CRL extensions */ static SECStatus crlgen_AddCrlNumber(CRLGENGeneratorData *crlGenData, const char **dataArr) @@ -525,21 +517,19 @@ crlgen_AddCrlNumber(CRLGENGeneratorData *crlGenData, const char **dataArr) goto loser; } - rv = CERT_AddExtension (extHandle, SEC_OID_X509_CRL_NUMBER, &encodedItem, - (*dataArr[1] == '1') ? PR_TRUE : PR_FALSE, - PR_TRUE); + rv = CERT_AddExtension(extHandle, SEC_OID_X509_CRL_NUMBER, &encodedItem, + (*dataArr[1] == '1') ? PR_TRUE : PR_FALSE, + PR_TRUE); - loser: +loser: if (arena) PORT_FreeArena(arena, PR_FALSE); return rv; - } - /* Creates Cert Revocation Reason code extension. Encodes it and * returns as SECItem structure */ -static SECItem* +static SECItem * crlgen_CreateReasonCode(PLArenaPool *arena, const char **dataArr, int *extCode) { @@ -551,11 +541,11 @@ crlgen_CreateReasonCode(PLArenaPool *arena, const char **dataArr, PORT_Assert(arena && dataArr); if (!arena || !dataArr) { goto loser; - } + } mark = PORT_ArenaMark(arena); - encodedItem = PORT_ArenaZNew (arena, SECItem); + encodedItem = PORT_ArenaZNew(arena, SECItem); if (encodedItem == NULL) { goto loser; } @@ -566,10 +556,10 @@ crlgen_CreateReasonCode(PLArenaPool *arena, const char **dataArr, } code = atoi(dataArr[2]); - /* aACompromise(10) is the last possible of the values + /* aACompromise(10) is the last possible of the values * for the Reason Core Extension */ if ((code == 0 && *dataArr[2] != '0') || code > 10) { - + PORT_SetError(SEC_ERROR_INVALID_ARGS); goto loser; } @@ -582,18 +572,18 @@ crlgen_CreateReasonCode(PLArenaPool *arena, const char **dataArr, *extCode = SEC_OID_X509_REASON_CODE; return encodedItem; - loser: +loser: if (mark) { - PORT_ArenaRelease (arena, mark); + PORT_ArenaRelease(arena, mark); } return NULL; } /* Creates Cert Invalidity Date extension. Encodes it and * returns as SECItem structure */ -static SECItem* +static SECItem * crlgen_CreateInvalidityDate(PLArenaPool *arena, const char **dataArr, - int *extCode) + int *extCode) { SECItem *encodedItem; int length = 0; @@ -602,7 +592,7 @@ crlgen_CreateInvalidityDate(PLArenaPool *arena, const char **dataArr, PORT_Assert(arena && dataArr); if (!arena || !dataArr) { goto loser; - } + } mark = PORT_ArenaMark(arena); @@ -620,12 +610,12 @@ crlgen_CreateInvalidityDate(PLArenaPool *arena, const char **dataArr, } PORT_Memcpy(encodedItem->data, dataArr[2], (encodedItem->len = length) * - sizeof(char)); + sizeof(char)); *extCode = SEC_OID_X509_INVALID_DATE; return encodedItem; - - loser: + +loser: if (mark) { PORT_ArenaRelease(arena, mark); } @@ -638,26 +628,25 @@ crlgen_CreateInvalidityDate(PLArenaPool *arena, const char **dataArr, static SECStatus crlgen_AddEntryExtension(CRLGENGeneratorData *crlGenData, const char **dataArr, char *extName, - SECItem* (*extCreator)(PLArenaPool *arena, + SECItem *(*extCreator)(PLArenaPool *arena, const char **dataArr, int *extCode)) { PRUint64 i = 0; SECStatus rv = SECFailure; int extCode = 0; - PRUint64 lastRange ; + PRUint64 lastRange; SECItem *ext = NULL; PLArenaPool *arena = NULL; - - PORT_Assert(crlGenData && dataArr); + PORT_Assert(crlGenData && dataArr); if (!crlGenData || !dataArr) { goto loser; - } - + } + if (!dataArr[0] || !dataArr[1]) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - crlgen_PrintError(crlGenData->parsedLineNum, + crlgen_PrintError(crlGenData->parsedLineNum, "insufficient number of arguments.\n"); } @@ -670,16 +659,16 @@ crlgen_AddEntryExtension(CRLGENGeneratorData *crlGenData, ext = extCreator(arena, dataArr, &extCode); if (ext == NULL) { - crlgen_PrintError(crlGenData->parsedLineNum, + crlgen_PrintError(crlGenData->parsedLineNum, "got error while creating extension: %s\n", extName); goto loser; } - for (i = 0;i < lastRange;i++) { - CRLGENEntryData * extData = NULL; + for (i = 0; i < lastRange; i++) { + CRLGENEntryData *extData = NULL; void *extHandle = NULL; - SECItem * certIdItem = + SECItem *certIdItem = SEC_ASN1EncodeInteger(arena, NULL, crlGenData->rangeFrom + i); if (!certIdItem) { @@ -700,9 +689,9 @@ crlgen_AddEntryExtension(CRLGENGeneratorData *crlGenData, if (extHandle == NULL) { extHandle = extData->extHandle = CERT_StartCRLEntryExtensions(&crlGenData->signCrl->crl, - (CERTCrlEntry*)extData->entry); + (CERTCrlEntry *)extData->entry); } - rv = CERT_AddExtension (extHandle, extCode, ext, + rv = CERT_AddExtension(extHandle, extCode, ext, (*dataArr[1] == '1') ? PR_TRUE : PR_FALSE, PR_TRUE); if (rv == SECFailure) { @@ -710,13 +699,12 @@ crlgen_AddEntryExtension(CRLGENGeneratorData *crlGenData, } } - loser: +loser: if (arena) PORT_FreeArena(arena, PR_FALSE); return rv; } - /* Commits all added entries and their's extensions into CRL. */ SECStatus CRLGEN_CommitExtensionsAndEntries(CRLGENGeneratorData *crlGenData) @@ -744,7 +732,7 @@ CRLGEN_CommitExtensionsAndEntries(CRLGENGeneratorData *crlGenData) size = crlGenData->entryDataHashTable->nentries; crl->entries = NULL; if (size) { - crl->entries = PORT_ArenaZNewArray(arena, CERTCrlEntry*, size + 1); + crl->entries = PORT_ArenaZNewArray(arena, CERTCrlEntry *, size + 1); if (!crl->entries) { rv = SECFailure; } else { @@ -780,11 +768,11 @@ crlgen_InitExtensionHandle(void *extHandle, extension = *extensions; while (extension) { - SECOidTag oidTag = SECOID_FindOIDTag (&extension->id); -/* shell we skip unknown extensions? */ - CERT_AddExtension (extHandle, oidTag, &extension->value, - (extension->critical.len != 0) ? PR_TRUE : PR_FALSE, - PR_FALSE); + SECOidTag oidTag = SECOID_FindOIDTag(&extension->id); + /* shell we skip unknown extensions? */ + CERT_AddExtension(extHandle, oidTag, &extension->value, + (extension->critical.len != 0) ? PR_TRUE : PR_FALSE, + PR_FALSE); extension = *(++extensions); } return SECSuccess; @@ -819,9 +807,9 @@ CRLGEN_ExtHandleInit(CRLGENGeneratorData *crlGenData) CRLGENEntryData *extData = crlgen_PlaceAnEntry(crlGenData, *entry, &(*entry)->serialNumber); if ((*entry)->extensions) { - extData->extHandle = + extData->extHandle = CERT_StartCRLEntryExtensions(&crlGenData->signCrl->crl, - (CERTCrlEntry*)extData->entry); + (CERTCrlEntry *)extData->entry); if (crlgen_InitExtensionHandle(extData->extHandle, (*entry)->extensions) == SECFailure) return SECFailure; @@ -866,14 +854,14 @@ crlgen_SetNewRangeField(CRLGENGeneratorData *crlGenData, char *value) rangeFrom = atoi(rangeFromS); *dashPos = '-'; - rangeToS = (char*)(dashPos + 1); + rangeToS = (char *)(dashPos + 1); rangeTo = atol(rangeToS); } else { rangeFrom = atol(value); rangeTo = rangeFrom; } - if (rangeFrom < 1 || rangeToparsedLineNum, "bad cert id range: %s.\n", value); @@ -891,7 +879,7 @@ crlgen_SetNewRangeField(CRLGENGeneratorData *crlGenData, char *value) static SECStatus crlgen_SetIssuerField(CRLGENGeneratorData *crlGenData, char *value) { - crlgen_PrintError(crlGenData->parsedLineNum, + crlgen_PrintError(crlGenData->parsedLineNum, "Can not change CRL issuer field.\n"); return SECFailure; } @@ -925,7 +913,7 @@ crlgen_SetTimeField(CRLGENGeneratorData *crlGenData, char *value, return SECFailure; } length = PORT_Strlen(value); - + if (setThisUpdate == PR_TRUE) { timeDest = &crl->lastUpdate; } else { @@ -943,7 +931,6 @@ crlgen_SetTimeField(CRLGENGeneratorData *crlGenData, char *value, return SECSuccess; } - /* Adds new extension into CRL or added cert handles */ static SECStatus crlgen_AddExtension(CRLGENGeneratorData *crlGenData, const char **extData) @@ -956,7 +943,7 @@ crlgen_AddExtension(CRLGENGeneratorData *crlGenData, const char **extData) if (extData == NULL || *extData == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - crlgen_PrintError(crlGenData->parsedLineNum, + crlgen_PrintError(crlGenData->parsedLineNum, "insufficient number of arguments.\n"); return SECFailure; } @@ -980,14 +967,12 @@ crlgen_AddExtension(CRLGENGeneratorData *crlGenData, const char **extData) } } - - /* Created CRLGENEntryData for cert with serial number certId and * adds it to entryDataHashTable. certId can be a single cert serial * number or an inclusive rage of certs */ static SECStatus crlgen_AddCert(CRLGENGeneratorData *crlGenData, - char *certId, char *revocationDate) + char *certId, char *revocationDate) { CERTSignedCrl *signCrl; SECItem *certIdItem; @@ -997,7 +982,6 @@ crlgen_AddCert(CRLGENGeneratorData *crlGenData, SECStatus rv = SECFailure; void *mark; - PORT_Assert(crlGenData && crlGenData->signCrl && crlGenData->signCrl->arena); if (!crlGenData || !crlGenData->signCrl || !crlGenData->signCrl->arena) { @@ -1024,7 +1008,7 @@ crlgen_AddCert(CRLGENGeneratorData *crlGenData, rangeFrom = crlGenData->rangeFrom; rangeTo = crlGenData->rangeTo; - for (i = 0;i < rangeTo - rangeFrom + 1;i++) { + for (i = 0; i < rangeTo - rangeFrom + 1; i++) { CERTCrlEntry *entry; mark = PORT_ArenaMark(arena); entry = PORT_ArenaZNew(arena, CERTCrlEntry); @@ -1042,7 +1026,8 @@ crlgen_AddCert(CRLGENGeneratorData *crlGenData, crlgen_PrintError(crlGenData->parsedLineNum, "entry already exists. Use \"range\" " "and \"rmcert\" before adding a new one with the " - "same serial number %ld\n", rangeFrom + i); + "same serial number %ld\n", + rangeFrom + i); goto loser; } @@ -1060,7 +1045,6 @@ crlgen_AddCert(CRLGENGeneratorData *crlGenData, timeValLength * sizeof(char)); entry->revocationDate.len = timeValLength; - entry->extensions = NULL; if (!crlgen_PlaceAnEntry(crlGenData, entry, certIdItem)) { goto loser; @@ -1069,14 +1053,13 @@ crlgen_AddCert(CRLGENGeneratorData *crlGenData, } rv = SECSuccess; - loser: +loser: if (mark) { PORT_ArenaRelease(arena, mark); } return rv; } - /* Removes certs from entryDataHashTable which have certId serial number. * certId can have value of a range of certs */ static SECStatus @@ -1095,8 +1078,8 @@ crlgen_RmCert(CRLGENGeneratorData *crlGenData, char *certId) return SECFailure; } - for (i = 0;i < crlGenData->rangeTo - crlGenData->rangeFrom + 1;i++) { - SECItem* certIdItem = SEC_ASN1EncodeInteger(NULL, NULL, + for (i = 0; i < crlGenData->rangeTo - crlGenData->rangeFrom + 1; i++) { + SECItem *certIdItem = SEC_ASN1EncodeInteger(NULL, NULL, crlGenData->rangeFrom + i); if (certIdItem) { CRLGENEntryData *extData = @@ -1115,16 +1098,16 @@ crlgen_RmCert(CRLGENGeneratorData *crlGenData, char *certId) /************************************************************************* * Lex Parser Helper functions are used to store parsed information - * in context related structures. Context(or state) is identified base on + * in context related structures. Context(or state) is identified base on * a type of a instruction parser currently is going through. New context * is identified by first token in a line. It can be addcert context, * addext context, etc. */ -/* Updates CRL field depending on current context */ +/* Updates CRL field depending on current context */ static SECStatus crlgen_updateCrlFn_field(CRLGENGeneratorData *crlGenData, void *str) { - CRLGENCrlField *fieldStr = (CRLGENCrlField*)str; + CRLGENCrlField *fieldStr = (CRLGENCrlField *)str; PORT_Assert(crlGenData); if (!crlGenData) { @@ -1132,35 +1115,35 @@ crlgen_updateCrlFn_field(CRLGENGeneratorData *crlGenData, void *str) return SECFailure; } - switch(crlGenData->contextId) { - case CRLGEN_ISSUER_CONTEXT: - crlgen_SetIssuerField(crlGenData, fieldStr->value); - break; - case CRLGEN_UPDATE_CONTEXT: - return crlgen_SetTimeField(crlGenData, fieldStr->value, PR_TRUE); - break; - case CRLGEN_NEXT_UPDATE_CONTEXT: - return crlgen_SetTimeField(crlGenData, fieldStr->value, PR_FALSE); - break; - case CRLGEN_CHANGE_RANGE_CONTEXT: - return crlgen_SetNewRangeField(crlGenData, fieldStr->value); - break; - default: - crlgen_PrintError(crlGenData->parsedLineNum, - "syntax error (unknow token type: %d)\n", - crlGenData->contextId); - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + switch (crlGenData->contextId) { + case CRLGEN_ISSUER_CONTEXT: + crlgen_SetIssuerField(crlGenData, fieldStr->value); + break; + case CRLGEN_UPDATE_CONTEXT: + return crlgen_SetTimeField(crlGenData, fieldStr->value, PR_TRUE); + break; + case CRLGEN_NEXT_UPDATE_CONTEXT: + return crlgen_SetTimeField(crlGenData, fieldStr->value, PR_FALSE); + break; + case CRLGEN_CHANGE_RANGE_CONTEXT: + return crlgen_SetNewRangeField(crlGenData, fieldStr->value); + break; + default: + crlgen_PrintError(crlGenData->parsedLineNum, + "syntax error (unknow token type: %d)\n", + crlGenData->contextId); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } return SECSuccess; } -/* Sets parsed data for CRL field update into temporary structure */ +/* Sets parsed data for CRL field update into temporary structure */ static SECStatus crlgen_setNextDataFn_field(CRLGENGeneratorData *crlGenData, void *str, - void *data, unsigned short dtype) + void *data, unsigned short dtype) { - CRLGENCrlField *fieldStr = (CRLGENCrlField*)str; + CRLGENCrlField *fieldStr = (CRLGENCrlField *)str; PORT_Assert(crlGenData); if (!crlGenData) { @@ -1169,29 +1152,29 @@ crlgen_setNextDataFn_field(CRLGENGeneratorData *crlGenData, void *str, } switch (crlGenData->contextId) { - case CRLGEN_CHANGE_RANGE_CONTEXT: - if (dtype != CRLGEN_TYPE_DIGIT && dtype != CRLGEN_TYPE_DIGIT_RANGE) { - crlgen_PrintError(crlGenData->parsedLineNum, - "range value should have " - "numeric or numeric range values.\n"); - return SECFailure; - } - break; - case CRLGEN_NEXT_UPDATE_CONTEXT: - case CRLGEN_UPDATE_CONTEXT: - if (dtype != CRLGEN_TYPE_ZDATE){ - crlgen_PrintError(crlGenData->parsedLineNum, - "bad formated date. Should be " - "YYYYMMDDHHMMSSZ.\n"); - return SECFailure; - } - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - crlgen_PrintError(crlGenData->parsedLineNum, - "syntax error (unknow token type: %d).\n", - crlGenData->contextId, data); - return SECFailure; + case CRLGEN_CHANGE_RANGE_CONTEXT: + if (dtype != CRLGEN_TYPE_DIGIT && dtype != CRLGEN_TYPE_DIGIT_RANGE) { + crlgen_PrintError(crlGenData->parsedLineNum, + "range value should have " + "numeric or numeric range values.\n"); + return SECFailure; + } + break; + case CRLGEN_NEXT_UPDATE_CONTEXT: + case CRLGEN_UPDATE_CONTEXT: + if (dtype != CRLGEN_TYPE_ZDATE) { + crlgen_PrintError(crlGenData->parsedLineNum, + "bad formated date. Should be " + "YYYYMMDDHHMMSSZ.\n"); + return SECFailure; + } + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + crlgen_PrintError(crlGenData->parsedLineNum, + "syntax error (unknow token type: %d).\n", + crlGenData->contextId, data); + return SECFailure; } fieldStr->value = PORT_Strdup(data); if (!fieldStr->value) { @@ -1200,11 +1183,11 @@ crlgen_setNextDataFn_field(CRLGENGeneratorData *crlGenData, void *str, return SECSuccess; } -/* Triggers cert entries update depending on current context */ +/* Triggers cert entries update depending on current context */ static SECStatus crlgen_updateCrlFn_cert(CRLGENGeneratorData *crlGenData, void *str) { - CRLGENCertEntry *certStr = (CRLGENCertEntry*)str; + CRLGENCertEntry *certStr = (CRLGENCertEntry *)str; PORT_Assert(crlGenData); if (!crlGenData) { @@ -1212,28 +1195,27 @@ crlgen_updateCrlFn_cert(CRLGENGeneratorData *crlGenData, void *str) return SECFailure; } - switch(crlGenData->contextId) { - case CRLGEN_ADD_CERT_CONTEXT: - return crlgen_AddCert(crlGenData, certStr->certId, - certStr->revocationTime); - case CRLGEN_RM_CERT_CONTEXT: - return crlgen_RmCert(crlGenData, certStr->certId); - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - crlgen_PrintError(crlGenData->parsedLineNum, - "syntax error (unknow token type: %d).\n", - crlGenData->contextId); - return SECFailure; + switch (crlGenData->contextId) { + case CRLGEN_ADD_CERT_CONTEXT: + return crlgen_AddCert(crlGenData, certStr->certId, + certStr->revocationTime); + case CRLGEN_RM_CERT_CONTEXT: + return crlgen_RmCert(crlGenData, certStr->certId); + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + crlgen_PrintError(crlGenData->parsedLineNum, + "syntax error (unknow token type: %d).\n", + crlGenData->contextId); + return SECFailure; } } - -/* Sets parsed data for CRL entries update into temporary structure */ +/* Sets parsed data for CRL entries update into temporary structure */ static SECStatus crlgen_setNextDataFn_cert(CRLGENGeneratorData *crlGenData, void *str, - void *data, unsigned short dtype) + void *data, unsigned short dtype) { - CRLGENCertEntry *certStr = (CRLGENCertEntry*)str; + CRLGENCertEntry *certStr = (CRLGENCertEntry *)str; PORT_Assert(crlGenData); if (!crlGenData) { @@ -1241,50 +1223,50 @@ crlgen_setNextDataFn_cert(CRLGENGeneratorData *crlGenData, void *str, return SECFailure; } - switch(dtype) { - case CRLGEN_TYPE_DIGIT: - case CRLGEN_TYPE_DIGIT_RANGE: - certStr->certId = PORT_Strdup(data); - if (!certStr->certId) { - return SECFailure; - } - break; - case CRLGEN_TYPE_DATE: - case CRLGEN_TYPE_ZDATE: - certStr->revocationTime = PORT_Strdup(data); - if (!certStr->revocationTime) { - return SECFailure; - } - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - crlgen_PrintError(crlGenData->parsedLineNum, - "syntax error (unknow token type: %d).\n", - crlGenData->contextId); - return SECFailure; + switch (dtype) { + case CRLGEN_TYPE_DIGIT: + case CRLGEN_TYPE_DIGIT_RANGE: + certStr->certId = PORT_Strdup(data); + if (!certStr->certId) { + return SECFailure; + } + break; + case CRLGEN_TYPE_DATE: + case CRLGEN_TYPE_ZDATE: + certStr->revocationTime = PORT_Strdup(data); + if (!certStr->revocationTime) { + return SECFailure; + } + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + crlgen_PrintError(crlGenData->parsedLineNum, + "syntax error (unknow token type: %d).\n", + crlGenData->contextId); + return SECFailure; } return SECSuccess; } -/* Triggers cert entries/crl extension update */ +/* Triggers cert entries/crl extension update */ static SECStatus crlgen_updateCrlFn_extension(CRLGENGeneratorData *crlGenData, void *str) { - CRLGENExtensionEntry *extStr = (CRLGENExtensionEntry*)str; + CRLGENExtensionEntry *extStr = (CRLGENExtensionEntry *)str; - return crlgen_AddExtension(crlGenData, (const char**)extStr->extData); + return crlgen_AddExtension(crlGenData, (const char **)extStr->extData); } /* Defines maximum number of fields extension may have */ #define MAX_EXT_DATA_LENGTH 10 /* Sets parsed extension data for CRL entries/CRL extensions update - * into temporary structure */ + * into temporary structure */ static SECStatus crlgen_setNextDataFn_extension(CRLGENGeneratorData *crlGenData, void *str, - void *data, unsigned short dtype) + void *data, unsigned short dtype) { - CRLGENExtensionEntry *extStr = (CRLGENExtensionEntry*)str; + CRLGENExtensionEntry *extStr = (CRLGENExtensionEntry *)str; PORT_Assert(crlGenData); if (!crlGenData) { @@ -1300,7 +1282,7 @@ crlgen_setNextDataFn_extension(CRLGENGeneratorData *crlGenData, void *str, } if (extStr->nextUpdatedData >= MAX_EXT_DATA_LENGTH) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - crlgen_PrintError(crlGenData->parsedLineNum, + crlgen_PrintError(crlGenData->parsedLineNum, "number of fields in extension " "exceeded maximum allowed data length: %d.\n", MAX_EXT_DATA_LENGTH); @@ -1315,7 +1297,6 @@ crlgen_setNextDataFn_extension(CRLGENGeneratorData *crlGenData, void *str, return SECSuccess; } - /**************************************************************************************** * Top level functions are triggered directly by parser. */ @@ -1328,32 +1309,32 @@ void crlgen_destroyTempData(CRLGENGeneratorData *crlGenData) { if (crlGenData->contextId != CRLGEN_UNKNOWN_CONTEXT) { - switch(crlGenData->contextId) { - case CRLGEN_ISSUER_CONTEXT: - case CRLGEN_UPDATE_CONTEXT: - case CRLGEN_NEXT_UPDATE_CONTEXT: - case CRLGEN_CHANGE_RANGE_CONTEXT: - if (crlGenData->crlField->value) - PORT_Free(crlGenData->crlField->value); - PORT_Free(crlGenData->crlField); - break; - case CRLGEN_ADD_CERT_CONTEXT: - case CRLGEN_RM_CERT_CONTEXT: - if (crlGenData->certEntry->certId) - PORT_Free(crlGenData->certEntry->certId); - if (crlGenData->certEntry->revocationTime) - PORT_Free(crlGenData->certEntry->revocationTime); - PORT_Free(crlGenData->certEntry); - break; - case CRLGEN_ADD_EXTENSION_CONTEXT: - if (crlGenData->extensionEntry->extData) { - int i = 0; - for (;i < crlGenData->extensionEntry->nextUpdatedData;i++) - PORT_Free(*(crlGenData->extensionEntry->extData + i)); - PORT_Free(crlGenData->extensionEntry->extData); - } - PORT_Free(crlGenData->extensionEntry); - break; + switch (crlGenData->contextId) { + case CRLGEN_ISSUER_CONTEXT: + case CRLGEN_UPDATE_CONTEXT: + case CRLGEN_NEXT_UPDATE_CONTEXT: + case CRLGEN_CHANGE_RANGE_CONTEXT: + if (crlGenData->crlField->value) + PORT_Free(crlGenData->crlField->value); + PORT_Free(crlGenData->crlField); + break; + case CRLGEN_ADD_CERT_CONTEXT: + case CRLGEN_RM_CERT_CONTEXT: + if (crlGenData->certEntry->certId) + PORT_Free(crlGenData->certEntry->certId); + if (crlGenData->certEntry->revocationTime) + PORT_Free(crlGenData->certEntry->revocationTime); + PORT_Free(crlGenData->certEntry); + break; + case CRLGEN_ADD_EXTENSION_CONTEXT: + if (crlGenData->extensionEntry->extData) { + int i = 0; + for (; i < crlGenData->extensionEntry->nextUpdatedData; i++) + PORT_Free(*(crlGenData->extensionEntry->extData + i)); + PORT_Free(crlGenData->extensionEntry->extData); + } + PORT_Free(crlGenData->extensionEntry); + break; } crlGenData->contextId = CRLGEN_UNKNOWN_CONTEXT; } @@ -1370,29 +1351,28 @@ crlgen_updateCrl(CRLGENGeneratorData *crlGenData) return SECFailure; } - switch(crlGenData->contextId) { - case CRLGEN_ISSUER_CONTEXT: - case CRLGEN_UPDATE_CONTEXT: - case CRLGEN_NEXT_UPDATE_CONTEXT: - case CRLGEN_CHANGE_RANGE_CONTEXT: - rv = crlGenData->crlField->updateCrlFn(crlGenData, crlGenData->crlField); - break; - case CRLGEN_RM_CERT_CONTEXT: - case CRLGEN_ADD_CERT_CONTEXT: - rv = crlGenData->certEntry->updateCrlFn(crlGenData, crlGenData->certEntry); - break; - case CRLGEN_ADD_EXTENSION_CONTEXT: - rv = crlGenData->extensionEntry-> - updateCrlFn(crlGenData, crlGenData->extensionEntry); - break; - case CRLGEN_UNKNOWN_CONTEXT: - break; - default: - crlgen_PrintError(crlGenData->parsedLineNum, - "unknown lang context type code: %d.\n", - crlGenData->contextId); - PORT_Assert(0); - return SECFailure; + switch (crlGenData->contextId) { + case CRLGEN_ISSUER_CONTEXT: + case CRLGEN_UPDATE_CONTEXT: + case CRLGEN_NEXT_UPDATE_CONTEXT: + case CRLGEN_CHANGE_RANGE_CONTEXT: + rv = crlGenData->crlField->updateCrlFn(crlGenData, crlGenData->crlField); + break; + case CRLGEN_RM_CERT_CONTEXT: + case CRLGEN_ADD_CERT_CONTEXT: + rv = crlGenData->certEntry->updateCrlFn(crlGenData, crlGenData->certEntry); + break; + case CRLGEN_ADD_EXTENSION_CONTEXT: + rv = crlGenData->extensionEntry->updateCrlFn(crlGenData, crlGenData->extensionEntry); + break; + case CRLGEN_UNKNOWN_CONTEXT: + break; + default: + crlgen_PrintError(crlGenData->parsedLineNum, + "unknown lang context type code: %d.\n", + crlGenData->contextId); + PORT_Assert(0); + return SECFailure; } /* Clrean structures after crl update */ crlgen_destroyTempData(crlGenData); @@ -1414,32 +1394,31 @@ crlgen_setNextData(CRLGENGeneratorData *crlGenData, void *data, return SECFailure; } - switch(crlGenData->contextId) { - case CRLGEN_ISSUER_CONTEXT: - case CRLGEN_UPDATE_CONTEXT: - case CRLGEN_NEXT_UPDATE_CONTEXT: - case CRLGEN_CHANGE_RANGE_CONTEXT: - rv = crlGenData->crlField->setNextDataFn(crlGenData, crlGenData->crlField, - data, dtype); - break; - case CRLGEN_ADD_CERT_CONTEXT: - case CRLGEN_RM_CERT_CONTEXT: - rv = crlGenData->certEntry->setNextDataFn(crlGenData, crlGenData->certEntry, - data, dtype); - break; - case CRLGEN_ADD_EXTENSION_CONTEXT: - rv = - crlGenData->extensionEntry-> - setNextDataFn(crlGenData, crlGenData->extensionEntry, data, dtype); - break; - case CRLGEN_UNKNOWN_CONTEXT: - break; - default: - crlgen_PrintError(crlGenData->parsedLineNum, - "unknown context type: %d.\n", - crlGenData->contextId); - PORT_Assert(0); - return SECFailure; + switch (crlGenData->contextId) { + case CRLGEN_ISSUER_CONTEXT: + case CRLGEN_UPDATE_CONTEXT: + case CRLGEN_NEXT_UPDATE_CONTEXT: + case CRLGEN_CHANGE_RANGE_CONTEXT: + rv = crlGenData->crlField->setNextDataFn(crlGenData, crlGenData->crlField, + data, dtype); + break; + case CRLGEN_ADD_CERT_CONTEXT: + case CRLGEN_RM_CERT_CONTEXT: + rv = crlGenData->certEntry->setNextDataFn(crlGenData, crlGenData->certEntry, + data, dtype); + break; + case CRLGEN_ADD_EXTENSION_CONTEXT: + rv = + crlGenData->extensionEntry->setNextDataFn(crlGenData, crlGenData->extensionEntry, data, dtype); + break; + case CRLGEN_UNKNOWN_CONTEXT: + break; + default: + crlgen_PrintError(crlGenData->parsedLineNum, + "unknown context type: %d.\n", + crlGenData->contextId); + PORT_Assert(0); + return SECFailure; } return rv; } @@ -1456,59 +1435,58 @@ crlgen_createNewLangStruct(CRLGENGeneratorData *crlGenData, return SECFailure; } - switch(structType) { - case CRLGEN_ISSUER_CONTEXT: - case CRLGEN_UPDATE_CONTEXT: - case CRLGEN_NEXT_UPDATE_CONTEXT: - case CRLGEN_CHANGE_RANGE_CONTEXT: - crlGenData->crlField = PORT_New(CRLGENCrlField); - if (!crlGenData->crlField) { - return SECFailure; - } - crlGenData->contextId = structType; - crlGenData->crlField->value = NULL; - crlGenData->crlField->updateCrlFn = &crlgen_updateCrlFn_field; - crlGenData->crlField->setNextDataFn = &crlgen_setNextDataFn_field; - break; - case CRLGEN_RM_CERT_CONTEXT: - case CRLGEN_ADD_CERT_CONTEXT: - crlGenData->certEntry = PORT_New(CRLGENCertEntry); - if (!crlGenData->certEntry) { - return SECFailure; - } - crlGenData->contextId = structType; - crlGenData->certEntry->certId = 0; - crlGenData->certEntry->revocationTime = NULL; - crlGenData->certEntry->updateCrlFn = &crlgen_updateCrlFn_cert; - crlGenData->certEntry->setNextDataFn = &crlgen_setNextDataFn_cert; - break; - case CRLGEN_ADD_EXTENSION_CONTEXT: - crlGenData->extensionEntry = PORT_New(CRLGENExtensionEntry); - if (!crlGenData->extensionEntry) { - return SECFailure; - } - crlGenData->contextId = structType; - crlGenData->extensionEntry->extData = NULL; - crlGenData->extensionEntry->nextUpdatedData = 0; - crlGenData->extensionEntry->updateCrlFn = - &crlgen_updateCrlFn_extension; - crlGenData->extensionEntry->setNextDataFn = - &crlgen_setNextDataFn_extension; - break; - case CRLGEN_UNKNOWN_CONTEXT: - break; - default: - crlgen_PrintError(crlGenData->parsedLineNum, - "unknown context type: %d.\n", structType); - PORT_Assert(0); - return SECFailure; + switch (structType) { + case CRLGEN_ISSUER_CONTEXT: + case CRLGEN_UPDATE_CONTEXT: + case CRLGEN_NEXT_UPDATE_CONTEXT: + case CRLGEN_CHANGE_RANGE_CONTEXT: + crlGenData->crlField = PORT_New(CRLGENCrlField); + if (!crlGenData->crlField) { + return SECFailure; + } + crlGenData->contextId = structType; + crlGenData->crlField->value = NULL; + crlGenData->crlField->updateCrlFn = &crlgen_updateCrlFn_field; + crlGenData->crlField->setNextDataFn = &crlgen_setNextDataFn_field; + break; + case CRLGEN_RM_CERT_CONTEXT: + case CRLGEN_ADD_CERT_CONTEXT: + crlGenData->certEntry = PORT_New(CRLGENCertEntry); + if (!crlGenData->certEntry) { + return SECFailure; + } + crlGenData->contextId = structType; + crlGenData->certEntry->certId = 0; + crlGenData->certEntry->revocationTime = NULL; + crlGenData->certEntry->updateCrlFn = &crlgen_updateCrlFn_cert; + crlGenData->certEntry->setNextDataFn = &crlgen_setNextDataFn_cert; + break; + case CRLGEN_ADD_EXTENSION_CONTEXT: + crlGenData->extensionEntry = PORT_New(CRLGENExtensionEntry); + if (!crlGenData->extensionEntry) { + return SECFailure; + } + crlGenData->contextId = structType; + crlGenData->extensionEntry->extData = NULL; + crlGenData->extensionEntry->nextUpdatedData = 0; + crlGenData->extensionEntry->updateCrlFn = + &crlgen_updateCrlFn_extension; + crlGenData->extensionEntry->setNextDataFn = + &crlgen_setNextDataFn_extension; + break; + case CRLGEN_UNKNOWN_CONTEXT: + break; + default: + crlgen_PrintError(crlGenData->parsedLineNum, + "unknown context type: %d.\n", structType); + PORT_Assert(0); + return SECFailure; } return SECSuccess; } - /* Parser initialization function */ -CRLGENGeneratorData* +CRLGENGeneratorData * CRLGEN_InitCrlGeneration(CERTSignedCrl *signCrl, PRFileDesc *src) { CRLGENGeneratorData *crlGenData = NULL; @@ -1524,7 +1502,7 @@ CRLGEN_InitCrlGeneration(CERTSignedCrl *signCrl, PRFileDesc *src) return NULL; } - crlGenData->entryDataHashTable = + crlGenData->entryDataHashTable = PL_NewHashTable(0, SECITEM_Hash, SECITEM_HashCompare, PL_CompareValues, NULL, NULL); if (!crlGenData->entryDataHashTable) { @@ -1555,4 +1533,3 @@ CRLGEN_FinalizeCrlGeneration(CRLGENGeneratorData *crlGenData) PL_HashTableDestroy(crlGenData->entryDataHashTable); PORT_Free(crlGenData); } - diff --git a/cmd/crlutil/crlgen.h b/cmd/crlutil/crlgen.h index dffd1e8295..3ec792108b 100644 --- a/cmd/crlutil/crlgen.h +++ b/cmd/crlutil/crlgen.h @@ -2,7 +2,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 _CRLGEN_H_ #define _CRLGEN_H_ @@ -13,31 +12,29 @@ #include "certt.h" #include "secoidt.h" - -#define CRLGEN_UNKNOWN_CONTEXT 0 -#define CRLGEN_ISSUER_CONTEXT 1 -#define CRLGEN_UPDATE_CONTEXT 2 -#define CRLGEN_NEXT_UPDATE_CONTEXT 3 -#define CRLGEN_ADD_EXTENSION_CONTEXT 4 -#define CRLGEN_ADD_CERT_CONTEXT 6 -#define CRLGEN_CHANGE_RANGE_CONTEXT 7 -#define CRLGEN_RM_CERT_CONTEXT 8 - -#define CRLGEN_TYPE_DATE 0 -#define CRLGEN_TYPE_ZDATE 1 -#define CRLGEN_TYPE_DIGIT 2 -#define CRLGEN_TYPE_DIGIT_RANGE 3 -#define CRLGEN_TYPE_OID 4 -#define CRLGEN_TYPE_STRING 5 -#define CRLGEN_TYPE_ID 6 - - -typedef struct CRLGENGeneratorDataStr CRLGENGeneratorData; -typedef struct CRLGENEntryDataStr CRLGENEntryData; -typedef struct CRLGENExtensionEntryStr CRLGENExtensionEntry; -typedef struct CRLGENCertEntrySrt CRLGENCertEntry; -typedef struct CRLGENCrlFieldStr CRLGENCrlField; -typedef struct CRLGENEntriesSortedDataStr CRLGENEntriesSortedData; +#define CRLGEN_UNKNOWN_CONTEXT 0 +#define CRLGEN_ISSUER_CONTEXT 1 +#define CRLGEN_UPDATE_CONTEXT 2 +#define CRLGEN_NEXT_UPDATE_CONTEXT 3 +#define CRLGEN_ADD_EXTENSION_CONTEXT 4 +#define CRLGEN_ADD_CERT_CONTEXT 6 +#define CRLGEN_CHANGE_RANGE_CONTEXT 7 +#define CRLGEN_RM_CERT_CONTEXT 8 + +#define CRLGEN_TYPE_DATE 0 +#define CRLGEN_TYPE_ZDATE 1 +#define CRLGEN_TYPE_DIGIT 2 +#define CRLGEN_TYPE_DIGIT_RANGE 3 +#define CRLGEN_TYPE_OID 4 +#define CRLGEN_TYPE_STRING 5 +#define CRLGEN_TYPE_ID 6 + +typedef struct CRLGENGeneratorDataStr CRLGENGeneratorData; +typedef struct CRLGENEntryDataStr CRLGENEntryData; +typedef struct CRLGENExtensionEntryStr CRLGENExtensionEntry; +typedef struct CRLGENCertEntrySrt CRLGENCertEntry; +typedef struct CRLGENCrlFieldStr CRLGENCrlField; +typedef struct CRLGENEntriesSortedDataStr CRLGENEntriesSortedData; /* Exported functions */ @@ -56,17 +53,15 @@ extern void CRLGEN_FinalizeCrlGeneration(CRLGENGeneratorData *crlGenData); /* Parser initialization function. Creates CRLGENGeneratorData structure * for the current thread */ -extern CRLGENGeneratorData* CRLGEN_InitCrlGeneration(CERTSignedCrl *newCrl, +extern CRLGENGeneratorData *CRLGEN_InitCrlGeneration(CERTSignedCrl *newCrl, PRFileDesc *src); - /* This lock is defined in crlgen_lex.c(derived from crlgen_lex.l). * It controls access to invocation of yylex, allows to parse one * script at a time */ extern void CRLGEN_InitCrlGenParserLock(); extern void CRLGEN_DestroyCrlGenParserLock(); - /* The following function types are used to define functions for each of * CRLGENExtensionEntryStr, CRLGENCertEntrySrt, CRLGENCrlFieldStr to * provide functionality needed for these structures*/ @@ -77,13 +72,13 @@ typedef SECStatus createNewLangStructFn_t(CRLGENGeneratorData *crlGenData, void *str, unsigned i); /* Sets reports failure to parser if anything goes wrong */ -extern void crlgen_setFailure(CRLGENGeneratorData *str, char *); +extern void crlgen_setFailure(CRLGENGeneratorData *str, char *); /* Collects data in to one of the current data structure that corresponds * to the correct context type. This function gets called after each token * is found for a particular line */ extern SECStatus crlgen_setNextData(CRLGENGeneratorData *str, void *data, - unsigned short dtype); + unsigned short dtype); /* initiates crl update with collected data. This function is called at the * end of each line */ @@ -94,8 +89,7 @@ extern SECStatus crlgen_updateCrl(CRLGENGeneratorData *str); extern SECStatus crlgen_createNewLangStruct(CRLGENGeneratorData *str, unsigned structType); - -/* CRLGENExtensionEntry is used to store addext request data for either +/* CRLGENExtensionEntry is used to store addext request data for either * CRL extensions or CRL entry extensions. The differentiation between * is based on order and type of extension been added. * - extData : all data in request staring from name of the extension are @@ -104,9 +98,9 @@ extern SECStatus crlgen_createNewLangStruct(CRLGENGeneratorData *str, */ struct CRLGENExtensionEntryStr { char **extData; - int nextUpdatedData; - updateCrlFn_t *updateCrlFn; - setNextDataFn_t *setNextDataFn; + int nextUpdatedData; + updateCrlFn_t *updateCrlFn; + setNextDataFn_t *setNextDataFn; }; /* CRLGENCeryestEntry is used to store addcert request data @@ -117,17 +111,16 @@ struct CRLGENExtensionEntryStr { struct CRLGENCertEntrySrt { char *certId; char *revocationTime; - updateCrlFn_t *updateCrlFn; + updateCrlFn_t *updateCrlFn; setNextDataFn_t *setNextDataFn; }; - /* CRLGENCrlField is used to store crl fields record like update time, next * update time, etc. * - value: value of the parsed field data*/ struct CRLGENCrlFieldStr { char *value; - updateCrlFn_t *updateCrlFn; + updateCrlFn_t *updateCrlFn; setNextDataFn_t *setNextDataFn; }; @@ -166,21 +159,20 @@ struct CRLGENEntryDataStr { * - parserStatus : current status of parser. Triggers parser to abort when * set to SECFailure * - src : PRFileDesc structure pointer of crl generator config file - * - parsedLineNum : currently parsing line. Keeping it to report errors */ + * - parsedLineNum : currently parsing line. Keeping it to report errors */ struct CRLGENGeneratorDataStr { unsigned short contextId; - CRLGENCrlField *crlField; - CRLGENCertEntry *certEntry; - CRLGENExtensionEntry *extensionEntry; + CRLGENCrlField *crlField; + CRLGENCertEntry *certEntry; + CRLGENExtensionEntry *extensionEntry; PRUint64 rangeFrom; PRUint64 rangeTo; CERTSignedCrl *signCrl; void *crlExtHandle; PLHashTable *entryDataHashTable; - + PRFileDesc *src; int parsedLineNum; }; - #endif /* _CRLGEN_H_ */ diff --git a/cmd/crlutil/crlgen_lex.c b/cmd/crlutil/crlgen_lex.c index b9cb8b3f8f..fb53ec844f 100644 --- a/cmd/crlutil/crlgen_lex.c +++ b/cmd/crlutil/crlgen_lex.c @@ -32,19 +32,19 @@ /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST -#else /* ! __cplusplus */ +#else /* ! __cplusplus */ #if __STDC__ #define YY_USE_PROTOS #define YY_USE_CONST -#endif /* __STDC__ */ -#endif /* ! __cplusplus */ +#endif /* __STDC__ */ +#endif /* ! __cplusplus */ #ifdef __TURBOC__ - #pragma warn -rch - #pragma warn -use +#pragma warn - rch +#pragma warn - use #include #include #define YY_USE_CONST @@ -57,7 +57,6 @@ #define yyconst #endif - #ifdef YY_USE_PROTOS #define YY_PROTO(proto) proto #else @@ -72,7 +71,7 @@ * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) +#define YY_SC_TO_UI(c) ((unsigned int)(unsigned char)c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less @@ -91,7 +90,7 @@ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart( yyin ) +#define YY_NEW_FILE yyrestart(yyin) #define YY_END_OF_BUFFER_CHAR 0 @@ -111,10 +110,10 @@ extern FILE *yyin, *yyout; * int a single C statement (which needs a semi-colon terminator). This * avoids problems with code like: * - * if ( condition_holds ) - * yyless( 5 ); - * else - * do_something_else(); + * if ( condition_holds ) + * yyless( 5 ); + * else + * do_something_else(); * * Prior to using the do-while the compiler would get upset at the * "else" because it interpreted the "if" statement as being all @@ -123,18 +122,16 @@ extern FILE *yyin, *yyout; /* Return all but the first 'n' matched characters back to the input stream. */ -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - *yy_cp = yy_hold_char; \ - YY_RESTORE_YY_MORE_OFFSET \ - yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ - YY_DO_BEFORE_ACTION; /* set up yytext again */ \ - } \ - while ( 0 ) +#define yyless(n) \ + do { \ + /* Undo effects of setting up yytext. */ \ + *yy_cp = yy_hold_char; \ + YY_RESTORE_YY_MORE_OFFSET \ + yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up yytext again */ \ + } while (0) -#define unput(c) yyunput( c, yytext_ptr ) +#define unput(c) yyunput(c, yytext_ptr) /* The following is because we cannot portably get our hands on size_t * (without autoconf's help, which isn't available because we want @@ -142,63 +139,61 @@ extern FILE *yyin, *yyout; */ typedef unsigned int yy_size_t; - -struct yy_buffer_state - { - FILE *yy_input_file; - - char *yy_ch_buf; /* input buffer */ - char *yy_buf_pos; /* current position in input buffer */ - - /* Size of input buffer in bytes, not including room for EOB - * characters. - */ - yy_size_t yy_buf_size; - - /* Number of characters read into yy_ch_buf, not including EOB - * characters. - */ - int yy_n_chars; - - /* Whether we "own" the buffer - i.e., we know we created it, - * and can realloc() it to grow it, and should free() it to - * delete it. - */ - int yy_is_our_buffer; - - /* Whether this is an "interactive" input source; if so, and - * if we're using stdio for input, then we want to use getc() - * instead of fread(), to make sure we stop fetching input after - * each newline. - */ - int yy_is_interactive; - - /* Whether we're considered to be at the beginning of a line. - * If so, '^' rules will be active on the next match, otherwise - * not. - */ - int yy_at_bol; - - /* Whether to try to fill the input buffer when we reach the - * end of it. - */ - int yy_fill_buffer; - - int yy_buffer_status; +struct yy_buffer_state { + FILE *yy_input_file; + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + yy_size_t yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 - /* When an EOF's been seen but there's still some text to process - * then we mark the buffer as YY_EOF_PENDING, to indicate that we - * shouldn't try reading from the input source any more. We might - * still have a bunch of tokens to match, though, because of - * possible backing-up. - * - * When we actually see the EOF, we change the status to "new" - * (via yyrestart()), so that the user can continue scanning by - * just pointing yyin at a new input file. - */ +/* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via yyrestart()), so that the user can continue scanning by + * just pointing yyin at a new input file. + */ #define YY_BUFFER_EOF_PENDING 2 - }; +}; static YY_BUFFER_STATE yy_current_buffer = 0; @@ -208,85 +203,84 @@ static YY_BUFFER_STATE yy_current_buffer = 0; */ #define YY_CURRENT_BUFFER yy_current_buffer - /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; -static int yy_n_chars; /* number of characters read into yy_ch_buf */ - +static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; -static int yy_init = 1; /* whether we need to initialize */ -static int yy_start = 0; /* start state number */ +static char *yy_c_buf_p = (char *)0; +static int yy_init = 1; /* whether we need to initialize */ +static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; -void yyrestart YY_PROTO(( FILE *input_file )); +void yyrestart YY_PROTO((FILE * input_file)); -void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); -void yy_load_buffer_state YY_PROTO(( void )); -YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); -void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); -void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); -void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); -#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) +void yy_switch_to_buffer YY_PROTO((YY_BUFFER_STATE new_buffer)); +void yy_load_buffer_state YY_PROTO((void)); +YY_BUFFER_STATE yy_create_buffer YY_PROTO((FILE * file, int size)); +void yy_delete_buffer YY_PROTO((YY_BUFFER_STATE b)); +void yy_init_buffer YY_PROTO((YY_BUFFER_STATE b, FILE *file)); +void yy_flush_buffer YY_PROTO((YY_BUFFER_STATE b)); +#define YY_FLUSH_BUFFER yy_flush_buffer(yy_current_buffer) -YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); -YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); -YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); +YY_BUFFER_STATE yy_scan_buffer YY_PROTO((char *base, yy_size_t size)); +YY_BUFFER_STATE yy_scan_string YY_PROTO((yyconst char *yy_str)); +YY_BUFFER_STATE yy_scan_bytes YY_PROTO((yyconst char *bytes, int len)); -static void *yy_flex_alloc YY_PROTO(( yy_size_t )); -static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); -static void yy_flex_free YY_PROTO(( void * )); +static void *yy_flex_alloc YY_PROTO((yy_size_t)); +static void *yy_flex_realloc YY_PROTO((void *, yy_size_t)); +static void yy_flex_free YY_PROTO((void *)); #define yy_new_buffer yy_create_buffer -#define yy_set_interactive(is_interactive) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_is_interactive = is_interactive; \ - } +#define yy_set_interactive(is_interactive) \ + { \ + if (!yy_current_buffer) \ + yy_current_buffer = yy_create_buffer(yyin, YY_BUF_SIZE); \ + yy_current_buffer->yy_is_interactive = is_interactive; \ + } -#define yy_set_bol(at_bol) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_at_bol = at_bol; \ - } +#define yy_set_bol(at_bol) \ + { \ + if (!yy_current_buffer) \ + yy_current_buffer = yy_create_buffer(yyin, YY_BUF_SIZE); \ + yy_current_buffer->yy_at_bol = at_bol; \ + } #define YY_AT_BOL() (yy_current_buffer->yy_at_bol) typedef unsigned char YY_CHAR; -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; +FILE *yyin = (FILE *)0, *yyout = (FILE *)0; typedef int yy_state_type; extern char *yytext; #define yytext_ptr yytext -static yy_state_type yy_get_previous_state YY_PROTO(( void )); -static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); -static int yy_get_next_buffer YY_PROTO(( void )); -static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); +static yy_state_type yy_get_previous_state YY_PROTO((void)); +static yy_state_type yy_try_NUL_trans YY_PROTO((yy_state_type current_state)); +static int yy_get_next_buffer YY_PROTO((void)); +static void yy_fatal_error YY_PROTO((yyconst char msg[])); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ -#define YY_DO_BEFORE_ACTION \ - yytext_ptr = yy_bp; \ - yytext_ptr -= yy_more_len; \ - yyleng = (int) (yy_cp - yytext_ptr); \ - yy_hold_char = *yy_cp; \ - *yy_cp = '\0'; \ - yy_c_buf_p = yy_cp; +#define YY_DO_BEFORE_ACTION \ + yytext_ptr = yy_bp; \ + yytext_ptr -= yy_more_len; \ + yyleng = (int)(yy_cp - yytext_ptr); \ + yy_hold_char = *yy_cp; \ + *yy_cp = '\0'; \ + yy_c_buf_p = yy_cp; #define YY_NUM_RULES 17 #define YY_END_OF_BUFFER 18 +/* clang-format off */ static yyconst short int yy_accept[67] = { 0, 0, 0, 18, 16, 14, 15, 16, 11, 12, 2, @@ -420,6 +414,7 @@ static yyconst short int yy_chk[235] = 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66 } ; +/* clang-format on */ static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; @@ -444,14 +439,14 @@ static SECStatus parserStatus = SECSuccess; static CRLGENGeneratorData *parserData; static PRFileDesc *src; -#define YY_INPUT(buf,result,max_size) \ - if ( parserStatus != SECFailure) { \ - if (((result = PR_Read(src, buf, max_size)) == 0) && \ - ferror( yyin )) \ - return SECFailure; \ - } else { return SECFailure; } - - +#define YY_INPUT(buf, result, max_size) \ + if (parserStatus != SECFailure) { \ + if (((result = PR_Read(src, buf, max_size)) == 0) && \ + ferror(yyin)) \ + return SECFailure; \ + } else { \ + return SECFailure; \ + } /* Macros after this point can all be overridden by user definitions in * section 1. @@ -459,29 +454,29 @@ static PRFileDesc *src; #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus -extern "C" int yywrap YY_PROTO(( void )); +extern "C" int yywrap YY_PROTO((void)); #else -extern int yywrap YY_PROTO(( void )); +extern int yywrap YY_PROTO((void)); #endif #endif #ifndef YY_NO_UNPUT -static void yyunput YY_PROTO(( int c, char *buf_ptr )); +static void yyunput YY_PROTO((int c, char *buf_ptr)); #endif #ifndef yytext_ptr -static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); +static void yy_flex_strncpy YY_PROTO((char *, yyconst char *, int)); #endif #ifdef YY_NEED_STRLEN -static int yy_flex_strlen YY_PROTO(( yyconst char * )); +static int yy_flex_strlen YY_PROTO((yyconst char *)); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus -static int yyinput YY_PROTO(( void )); +static int yyinput YY_PROTO((void)); #else -static int input YY_PROTO(( void )); +static int input YY_PROTO((void)); #endif #endif @@ -490,13 +485,13 @@ static int yy_start_stack_ptr = 0; static int yy_start_stack_depth = 0; static int *yy_start_stack = 0; #ifndef YY_NO_PUSH_STATE -static void yy_push_state YY_PROTO(( int new_state )); +static void yy_push_state YY_PROTO((int new_state)); #endif #ifndef YY_NO_POP_STATE -static void yy_pop_state YY_PROTO(( void )); +static void yy_pop_state YY_PROTO((void)); #endif #ifndef YY_NO_TOP_STATE -static int yy_top_state YY_PROTO(( void )); +static int yy_top_state YY_PROTO((void)); #endif #else @@ -531,29 +526,28 @@ YY_MALLOC_DECL /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ -#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) +#define ECHO (void)fwrite(yytext, yyleng, 1, yyout) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT -#define YY_INPUT(buf,result,max_size) \ - if ( yy_current_buffer->yy_is_interactive ) \ - { \ - int c = '*', n; \ - for ( n = 0; n < max_size && \ - (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ - buf[n] = (char) c; \ - if ( c == '\n' ) \ - buf[n++] = (char) c; \ - if ( c == EOF && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - result = n; \ - } \ - else if ( ((result = fread( buf, 1, max_size, yyin )) == 0) \ - && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); +#define YY_INPUT(buf, result, max_size) \ + if (yy_current_buffer->yy_is_interactive) { \ + int c = '*', n; \ + for (n = 0; n < max_size && \ + (c = getc(yyin)) != EOF && c != '\n'; \ + ++n) \ + buf[n] = (char)c; \ + if (c == '\n') \ + buf[n++] = (char)c; \ + if (c == EOF && ferror(yyin)) \ + YY_FATAL_ERROR("input in flex scanner failed"); \ + result = n; \ + } else if (((result = fread(buf, 1, max_size, yyin)) == 0) && \ + ferror(yyin)) \ + YY_FATAL_ERROR("input in flex scanner failed"); #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - @@ -571,14 +565,14 @@ YY_MALLOC_DECL /* Report a fatal error. */ #ifndef YY_FATAL_ERROR -#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) +#define YY_FATAL_ERROR(msg) yy_fatal_error(msg) #endif /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL -#define YY_DECL int yylex YY_PROTO(( void )) +#define YY_DECL int yylex YY_PROTO((void)) #endif /* Code executed at the beginning of each rule, after yytext and yyleng @@ -593,1044 +587,1037 @@ YY_MALLOC_DECL #define YY_BREAK break; #endif -#define YY_RULE_SETUP \ - if ( yyleng > 0 ) \ - yy_current_buffer->yy_at_bol = \ - (yytext[yyleng - 1] == '\n'); \ - YY_USER_ACTION +#define YY_RULE_SETUP \ + if (yyleng > 0) \ + yy_current_buffer->yy_at_bol = \ + (yytext[yyleng - 1] == '\n'); \ + YY_USER_ACTION YY_DECL - { - register yy_state_type yy_current_state; - register char *yy_cp = NULL, *yy_bp = NULL; - register int yy_act; +{ + register yy_state_type yy_current_state; + register char *yy_cp = NULL, *yy_bp = NULL; + register int yy_act; #line 28 "crlgen_lex_orig.l" + if (yy_init) { + yy_init = 0; +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif - if ( yy_init ) - { - yy_init = 0; + if (!yy_start) + yy_start = 1; /* first start state */ -#ifdef YY_USER_INIT - YY_USER_INIT; -#endif - - if ( ! yy_start ) - yy_start = 1; /* first start state */ - - if ( ! yyin ) - yyin = stdin; - - if ( ! yyout ) - yyout = stdout; - - if ( ! yy_current_buffer ) - yy_current_buffer = - yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_load_buffer_state(); - } - - while ( 1 ) /* loops until end-of-file is reached */ - { - yy_more_len = 0; - if ( yy_more_flag ) - { - yy_more_len = yy_c_buf_p - yytext_ptr; - yy_more_flag = 0; - } - yy_cp = yy_c_buf_p; - - /* Support of yytext. */ - *yy_cp = yy_hold_char; - - /* yy_bp points to the position in yy_ch_buf of the start of - * the current run. - */ - yy_bp = yy_cp; - - yy_current_state = yy_start; - yy_current_state += YY_AT_BOL(); -yy_match: - do - { - register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 67 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - ++yy_cp; - } - while ( yy_base[yy_current_state] != 205 ); - -yy_find_action: - yy_act = yy_accept[yy_current_state]; - if ( yy_act == 0 ) - { /* have to back up */ - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - yy_act = yy_accept[yy_current_state]; - } - - YY_DO_BEFORE_ACTION; - - -do_action: /* This label is used only to access EOF actions. */ - - - switch ( yy_act ) - { /* beginning of action switch */ - case 0: /* must back up */ - /* undo the effects of YY_DO_BEFORE_ACTION */ - *yy_cp = yy_hold_char; - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - goto yy_find_action; - -case 1: -YY_RULE_SETUP + if (!yyin) + yyin = stdin; + + if (!yyout) + yyout = stdout; + + if (!yy_current_buffer) + yy_current_buffer = + yy_create_buffer(yyin, YY_BUF_SIZE); + + yy_load_buffer_state(); + } + + while (1) /* loops until end-of-file is reached */ + { + yy_more_len = 0; + if (yy_more_flag) { + yy_more_len = yy_c_buf_p - yytext_ptr; + yy_more_flag = 0; + } + yy_cp = yy_c_buf_p; + + /* Support of yytext. */ + *yy_cp = yy_hold_char; + + /* yy_bp points to the position in yy_ch_buf of the start of + * the current run. + */ + yy_bp = yy_cp; + + yy_current_state = yy_start; + yy_current_state += YY_AT_BOL(); + yy_match: + do { + register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; + if (yy_accept[yy_current_state]) { + yy_last_accepting_state = yy_current_state; + yy_last_accepting_cpos = yy_cp; + } + while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { + yy_current_state = (int)yy_def[yy_current_state]; + if (yy_current_state >= 67) + yy_c = yy_meta[(unsigned int)yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int)yy_c]; + ++yy_cp; + } while (yy_base[yy_current_state] != 205); + + yy_find_action: + yy_act = yy_accept[yy_current_state]; + if (yy_act == 0) { /* have to back up */ + yy_cp = yy_last_accepting_cpos; + yy_current_state = yy_last_accepting_state; + yy_act = yy_accept[yy_current_state]; + } + + YY_DO_BEFORE_ACTION; + + do_action: /* This label is used only to access EOF actions. */ + + switch (yy_act) { /* beginning of action switch */ + case 0: /* must back up */ + /* undo the effects of YY_DO_BEFORE_ACTION */ + *yy_cp = yy_hold_char; + yy_cp = yy_last_accepting_cpos; + yy_current_state = yy_last_accepting_state; + goto yy_find_action; + + case 1: + YY_RULE_SETUP #line 30 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_ZDATE); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 2: -YY_RULE_SETUP + { + parserStatus = + crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_ZDATE); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 2: + YY_RULE_SETUP #line 36 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_DIGIT); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 3: -YY_RULE_SETUP + { + parserStatus = + crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_DIGIT); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 3: + YY_RULE_SETUP #line 42 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_DIGIT_RANGE); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 4: -YY_RULE_SETUP + { + parserStatus = + crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_DIGIT_RANGE); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 4: + YY_RULE_SETUP #line 48 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_OID); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 5: -YY_RULE_SETUP + { + parserStatus = + crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_OID); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 5: + YY_RULE_SETUP #line 54 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_createNewLangStruct(parserData, CRLGEN_ISSUER_CONTEXT); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 6: -YY_RULE_SETUP + { + parserStatus = + crlgen_createNewLangStruct(parserData, CRLGEN_ISSUER_CONTEXT); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 6: + YY_RULE_SETUP #line 60 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_createNewLangStruct(parserData, CRLGEN_UPDATE_CONTEXT); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 7: -YY_RULE_SETUP + { + parserStatus = + crlgen_createNewLangStruct(parserData, CRLGEN_UPDATE_CONTEXT); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 7: + YY_RULE_SETUP #line 65 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_createNewLangStruct(parserData, CRLGEN_NEXT_UPDATE_CONTEXT); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 8: -YY_RULE_SETUP + { + parserStatus = + crlgen_createNewLangStruct(parserData, CRLGEN_NEXT_UPDATE_CONTEXT); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 8: + YY_RULE_SETUP #line 71 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_createNewLangStruct(parserData, CRLGEN_CHANGE_RANGE_CONTEXT); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 9: -YY_RULE_SETUP + { + parserStatus = + crlgen_createNewLangStruct(parserData, CRLGEN_CHANGE_RANGE_CONTEXT); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 9: + YY_RULE_SETUP #line 77 "crlgen_lex_orig.l" -{ -if (strcmp(yytext, "addcert") == 0) { - parserStatus = crlgen_createNewLangStruct(parserData, - CRLGEN_ADD_CERT_CONTEXT); - if (parserStatus != SECSuccess) - return parserStatus; -} else if (strcmp(yytext, "rmcert") == 0) { - parserStatus = crlgen_createNewLangStruct(parserData, - CRLGEN_RM_CERT_CONTEXT); - if (parserStatus != SECSuccess) - return parserStatus; -} else if (strcmp(yytext, "addext") == 0) { - parserStatus = crlgen_createNewLangStruct(parserData, - CRLGEN_ADD_EXTENSION_CONTEXT); - if (parserStatus != SECSuccess) - return parserStatus; -} else { - parserStatus = crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_ID); - if (parserStatus != SECSuccess) - return parserStatus; -} -} - YY_BREAK -case 10: -YY_RULE_SETUP + { + if (strcmp(yytext, "addcert") == + 0) { + parserStatus = + crlgen_createNewLangStruct(parserData, + CRLGEN_ADD_CERT_CONTEXT); + if (parserStatus != + SECSuccess) + return parserStatus; + } else if (strcmp(yytext, "rmcert") == + 0) { + parserStatus = + crlgen_createNewLangStruct(parserData, + CRLGEN_RM_CERT_CONTEXT); + if (parserStatus != + SECSuccess) + return parserStatus; + } else if (strcmp(yytext, "addext") == + 0) { + parserStatus = + crlgen_createNewLangStruct(parserData, + CRLGEN_ADD_EXTENSION_CONTEXT); + if (parserStatus != + SECSuccess) + return parserStatus; + } else { + parserStatus = + crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_ID); + if (parserStatus != + SECSuccess) + return parserStatus; + } + } + YY_BREAK + case 10: + YY_RULE_SETUP #line 100 "crlgen_lex_orig.l" - YY_BREAK -case 11: -YY_RULE_SETUP + YY_BREAK + case 11: + YY_RULE_SETUP #line 102 "crlgen_lex_orig.l" -{ -if (yytext[yyleng-1] == '\\') { - yymore(); -} else { - register int c; - c = input(); - if (c != '\"') { - printf( "Error: Line ending \" is missing: %c\n", c); - unput(c); - } else { - parserStatus = crlgen_setNextData(parserData, yytext + 1, - CRLGEN_TYPE_STRING); - if (parserStatus != SECSuccess) - return parserStatus; - } -} -} - YY_BREAK -case 12: -YY_RULE_SETUP + { + if (yytext[yyleng - + 1] == + '\\') { + yymore(); + } else { + register int c; + c = + input(); + if (c != + '\"') { + printf("Error: Line ending \" is missing: %c\n", c); + unput(c); + } else { + parserStatus = + crlgen_setNextData(parserData, yytext + 1, + CRLGEN_TYPE_STRING); + if (parserStatus != + SECSuccess) + return parserStatus; + } + } + } + YY_BREAK + case 12: + YY_RULE_SETUP #line 120 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_STRING); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 13: -YY_RULE_SETUP + { + parserStatus = + crlgen_setNextData(parserData, yytext, CRLGEN_TYPE_STRING); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 13: + YY_RULE_SETUP #line 128 "crlgen_lex_orig.l" -/* eat up one-line comments */ {} - YY_BREAK -case 14: -YY_RULE_SETUP + /* eat up one-line comments */ {} + YY_BREAK + case 14: + YY_RULE_SETUP #line 130 "crlgen_lex_orig.l" -{} - YY_BREAK -case 15: -YY_RULE_SETUP + { + } + YY_BREAK + case 15: + YY_RULE_SETUP #line 132 "crlgen_lex_orig.l" -{ -parserStatus = crlgen_updateCrl(parserData); -if (parserStatus != SECSuccess) - return parserStatus; -} - YY_BREAK -case 16: -YY_RULE_SETUP + { + parserStatus = + crlgen_updateCrl(parserData); + if (parserStatus != + SECSuccess) + return parserStatus; + } + YY_BREAK + case 16: + YY_RULE_SETUP #line 138 "crlgen_lex_orig.l" -{ - fprintf(stderr, "Syntax error at line %d: unknown token %s\n", - parserData->parsedLineNum, yytext); - return SECFailure; -} - YY_BREAK -case 17: -YY_RULE_SETUP + { + fprintf(stderr, "Syntax error at line %d: unknown token %s\n", + parserData->parsedLineNum, yytext); + return SECFailure; + } + YY_BREAK + case 17: + YY_RULE_SETUP #line 144 "crlgen_lex_orig.l" -ECHO; - YY_BREAK -case YY_STATE_EOF(INITIAL): - yyterminate(); - - case YY_END_OF_BUFFER: - { - /* Amount of text matched not including the EOB char. */ - int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; - - /* Undo the effects of YY_DO_BEFORE_ACTION. */ - *yy_cp = yy_hold_char; - YY_RESTORE_YY_MORE_OFFSET - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) - { - /* We're scanning a new file or input source. It's - * possible that this happened because the user - * just pointed yyin at a new source and called - * yylex(). If so, then we have to assure - * consistency between yy_current_buffer and our - * globals. Here is the right place to do so, because - * this is the first action (other than possibly a - * back-up) that will match for the new input source. - */ - yy_n_chars = yy_current_buffer->yy_n_chars; - yy_current_buffer->yy_input_file = yyin; - yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; - } - - /* Note that here we test for yy_c_buf_p "<=" to the position - * of the first EOB in the buffer, since yy_c_buf_p will - * already have been incremented past the NUL character - * (since all states make transitions on EOB to the - * end-of-buffer state). Contrast this with the test - * in input(). - */ - if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - { /* This was really a NUL. */ - yy_state_type yy_next_state; - - yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - /* Okay, we're now positioned to make the NUL - * transition. We couldn't have - * yy_get_previous_state() go ahead and do it - * for us because it doesn't know how to deal - * with the possibility of jamming (and we don't - * want to build jamming into it because then it - * will run more slowly). - */ - - yy_next_state = yy_try_NUL_trans( yy_current_state ); - - yy_bp = yytext_ptr + YY_MORE_ADJ; - - if ( yy_next_state ) - { - /* Consume the NUL. */ - yy_cp = ++yy_c_buf_p; - yy_current_state = yy_next_state; - goto yy_match; - } - - else - { - yy_cp = yy_c_buf_p; - goto yy_find_action; - } - } - - else switch ( yy_get_next_buffer() ) - { - case EOB_ACT_END_OF_FILE: - { - yy_did_buffer_switch_on_eof = 0; - - if ( yywrap() ) - { - /* Note: because we've taken care in - * yy_get_next_buffer() to have set up - * yytext, we can now set up - * yy_c_buf_p so that if some total - * hoser (like flex itself) wants to - * call the scanner after we return the - * YY_NULL, it'll still work - another - * YY_NULL will get returned. - */ - yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; - - yy_act = YY_STATE_EOF(YY_START); - goto do_action; - } - - else - { - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; - } - break; - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = - yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_match; - - case EOB_ACT_LAST_MATCH: - yy_c_buf_p = - &yy_current_buffer->yy_ch_buf[yy_n_chars]; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_find_action; - } - break; - } - - default: - YY_FATAL_ERROR( - "fatal flex scanner internal error--no action found" ); - } /* end of action switch */ - } /* end of scanning one token */ - } /* end of yylex */ - + ECHO; + YY_BREAK + case YY_STATE_EOF(INITIAL): + yyterminate(); + + case YY_END_OF_BUFFER: { + /* Amount of text matched not including the EOB char. */ + int yy_amount_of_matched_text = (int)(yy_cp - yytext_ptr) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *yy_cp = yy_hold_char; + YY_RESTORE_YY_MORE_OFFSET + + if (yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW) { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed yyin at a new source and called + * yylex(). If so, then we have to assure + * consistency between yy_current_buffer and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + yy_n_chars = yy_current_buffer->yy_n_chars; + yy_current_buffer->yy_input_file = yyin; + yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if (yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars]) { /* This was really a NUL. */ + yy_state_type yy_next_state; + + yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state(); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + yy_next_state = yy_try_NUL_trans(yy_current_state); + + yy_bp = yytext_ptr + YY_MORE_ADJ; + + if (yy_next_state) { + /* Consume the NUL. */ + yy_cp = ++yy_c_buf_p; + yy_current_state = yy_next_state; + goto yy_match; + } + + else { + yy_cp = yy_c_buf_p; + goto yy_find_action; + } + } + + else + switch (yy_get_next_buffer()) { + case EOB_ACT_END_OF_FILE: { + yy_did_buffer_switch_on_eof = 0; + + if (yywrap()) { + /* Note: because we've taken care in + * yy_get_next_buffer() to have set up + * yytext, we can now set up + * yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; + + yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else { + if (!yy_did_buffer_switch_on_eof) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + yy_c_buf_p = + yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state(); + + yy_cp = yy_c_buf_p; + yy_bp = yytext_ptr + YY_MORE_ADJ; + goto yy_match; + + case EOB_ACT_LAST_MATCH: + yy_c_buf_p = + &yy_current_buffer->yy_ch_buf[yy_n_chars]; + + yy_current_state = yy_get_previous_state(); + + yy_cp = yy_c_buf_p; + yy_bp = yytext_ptr + YY_MORE_ADJ; + goto yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found"); + } /* end of action switch */ + } /* end of scanning one token */ +} /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: - * EOB_ACT_LAST_MATCH - - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position - * EOB_ACT_END_OF_FILE - end of file + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file */ -static int yy_get_next_buffer() - { - register char *dest = yy_current_buffer->yy_ch_buf; - register char *source = yytext_ptr; - register int number_to_move, i; - int ret_val; - - if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) - YY_FATAL_ERROR( - "fatal flex scanner internal error--end of buffer missed" ); - - if ( yy_current_buffer->yy_fill_buffer == 0 ) - { /* Don't try to fill the buffer, so this is an EOF. */ - if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) - { - /* We matched a single character, the EOB, so - * treat this as a final EOF. - */ - return EOB_ACT_END_OF_FILE; - } - - else - { - /* We matched some text prior to the EOB, first - * process it. - */ - return EOB_ACT_LAST_MATCH; - } - } - - /* Try to read more data. */ - - /* First move last chars to start of buffer. */ - number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; - - for ( i = 0; i < number_to_move; ++i ) - *(dest++) = *(source++); - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) - /* don't do the read, it's not guaranteed to return an EOF, - * just force an EOF - */ - yy_current_buffer->yy_n_chars = yy_n_chars = 0; - - else - { - int num_to_read = - yy_current_buffer->yy_buf_size - number_to_move - 1; - - while ( num_to_read <= 0 ) - { /* Not enough room in the buffer - grow it. */ +static int +yy_get_next_buffer() +{ + register char *dest = yy_current_buffer->yy_ch_buf; + register char *source = yytext_ptr; + register int number_to_move, i; + int ret_val; + + if (yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1]) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed"); + + if (yy_current_buffer->yy_fill_buffer == 0) { /* Don't try to fill the buffer, so this is an EOF. */ + if (yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1) { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (int)(yy_c_buf_p - yytext_ptr) - 1; + + for (i = 0; i < number_to_move; ++i) + *(dest++) = *(source++); + + if (yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + yy_current_buffer->yy_n_chars = yy_n_chars = 0; + + else { + int num_to_read = + yy_current_buffer->yy_buf_size - number_to_move - 1; + + while (num_to_read <= 0) { /* Not enough room in the buffer - grow it. */ #ifdef YY_USES_REJECT - YY_FATAL_ERROR( -"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); + YY_FATAL_ERROR( + "input buffer overflow, can't enlarge buffer because scanner uses REJECT"); #else - /* just a shorter name for the current buffer */ - YY_BUFFER_STATE b = yy_current_buffer; + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = yy_current_buffer; - int yy_c_buf_p_offset = - (int) (yy_c_buf_p - b->yy_ch_buf); + int yy_c_buf_p_offset = + (int)(yy_c_buf_p - b->yy_ch_buf); - if ( b->yy_is_our_buffer ) - { - int new_size = b->yy_buf_size * 2; + if (b->yy_is_our_buffer) { + int new_size = b->yy_buf_size * 2; - if ( new_size <= 0 ) - b->yy_buf_size += b->yy_buf_size / 8; - else - b->yy_buf_size *= 2; + if (new_size <= 0) + b->yy_buf_size += b->yy_buf_size / 8; + else + b->yy_buf_size *= 2; - b->yy_ch_buf = (char *) - /* Include room in for 2 EOB chars. */ - yy_flex_realloc( (void *) b->yy_ch_buf, - b->yy_buf_size + 2 ); - } - else - /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; + b->yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + yy_flex_realloc((void *)b->yy_ch_buf, + b->yy_buf_size + 2); + } else + /* Can't grow it, we don't own it. */ + b->yy_ch_buf = 0; - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( - "fatal error - scanner input buffer overflow" ); + if (!b->yy_ch_buf) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow"); - yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; + yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; - num_to_read = yy_current_buffer->yy_buf_size - - number_to_move - 1; + num_to_read = yy_current_buffer->yy_buf_size - + number_to_move - 1; #endif - } - - if ( num_to_read > YY_READ_BUF_SIZE ) - num_to_read = YY_READ_BUF_SIZE; - - /* Read in more data. */ - YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), - yy_n_chars, num_to_read ); + } - yy_current_buffer->yy_n_chars = yy_n_chars; - } + if (num_to_read > YY_READ_BUF_SIZE) + num_to_read = YY_READ_BUF_SIZE; - if ( yy_n_chars == 0 ) - { - if ( number_to_move == YY_MORE_ADJ ) - { - ret_val = EOB_ACT_END_OF_FILE; - yyrestart( yyin ); - } + /* Read in more data. */ + YY_INPUT((&yy_current_buffer->yy_ch_buf[number_to_move]), + yy_n_chars, num_to_read); - else - { - ret_val = EOB_ACT_LAST_MATCH; - yy_current_buffer->yy_buffer_status = - YY_BUFFER_EOF_PENDING; - } - } + yy_current_buffer->yy_n_chars = yy_n_chars; + } - else - ret_val = EOB_ACT_CONTINUE_SCAN; + if (yy_n_chars == 0) { + if (number_to_move == YY_MORE_ADJ) { + ret_val = EOB_ACT_END_OF_FILE; + yyrestart(yyin); + } + + else { + ret_val = EOB_ACT_LAST_MATCH; + yy_current_buffer->yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } - yy_n_chars += number_to_move; - yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; - yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; + else + ret_val = EOB_ACT_CONTINUE_SCAN; - yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; + yy_n_chars += number_to_move; + yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; + yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; - return ret_val; - } + yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; + return ret_val; +} /* yy_get_previous_state - get the state just before the EOB char was reached */ -static yy_state_type yy_get_previous_state() - { - register yy_state_type yy_current_state; - register char *yy_cp; - - yy_current_state = yy_start; - yy_current_state += YY_AT_BOL(); - - for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) - { - register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 67 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - } - - return yy_current_state; - } +static yy_state_type +yy_get_previous_state() +{ + register yy_state_type yy_current_state; + register char *yy_cp; + + yy_current_state = yy_start; + yy_current_state += YY_AT_BOL(); + + for (yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp) { + register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + if (yy_accept[yy_current_state]) { + yy_last_accepting_state = yy_current_state; + yy_last_accepting_cpos = yy_cp; + } + while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { + yy_current_state = (int)yy_def[yy_current_state]; + if (yy_current_state >= 67) + yy_c = yy_meta[(unsigned int)yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int)yy_c]; + } + return yy_current_state; +} /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis - * next_state = yy_try_NUL_trans( current_state ); + * next_state = yy_try_NUL_trans( current_state ); */ #ifdef YY_USE_PROTOS -static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) +static yy_state_type +yy_try_NUL_trans(yy_state_type yy_current_state) #else -static yy_state_type yy_try_NUL_trans( yy_current_state ) -yy_state_type yy_current_state; -#endif - { - register int yy_is_jam; - register char *yy_cp = yy_c_buf_p; - - register YY_CHAR yy_c = 1; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 67 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - yy_is_jam = (yy_current_state == 66); - - return yy_is_jam ? 0 : yy_current_state; - } +static yy_state_type yy_try_NUL_trans(yy_current_state) + yy_state_type yy_current_state; +#endif +{ + register int yy_is_jam; + register char *yy_cp = yy_c_buf_p; + + register YY_CHAR yy_c = 1; + if (yy_accept[yy_current_state]) { + yy_last_accepting_state = yy_current_state; + yy_last_accepting_cpos = yy_cp; + } + while (yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state) { + yy_current_state = (int)yy_def[yy_current_state]; + if (yy_current_state >= 67) + yy_c = yy_meta[(unsigned int)yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int)yy_c]; + yy_is_jam = (yy_current_state == 66); + return yy_is_jam ? 0 : yy_current_state; +} #ifndef YY_NO_UNPUT #ifdef YY_USE_PROTOS -static void yyunput( int c, register char *yy_bp ) +static void +yyunput(int c, register char *yy_bp) #else -static void yyunput( c, yy_bp ) -int c; +static void yyunput(c, yy_bp) int c; register char *yy_bp; #endif - { - register char *yy_cp = yy_c_buf_p; - - /* undo effects of setting up yytext */ - *yy_cp = yy_hold_char; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - { /* need to shift things up to make room */ - /* +2 for EOB chars. */ - register int number_to_move = yy_n_chars + 2; - register char *dest = &yy_current_buffer->yy_ch_buf[ - yy_current_buffer->yy_buf_size + 2]; - register char *source = - &yy_current_buffer->yy_ch_buf[number_to_move]; +{ + register char *yy_cp = yy_c_buf_p; - while ( source > yy_current_buffer->yy_ch_buf ) - *--dest = *--source; + /* undo effects of setting up yytext */ + *yy_cp = yy_hold_char; - yy_cp += (int) (dest - source); - yy_bp += (int) (dest - source); - yy_current_buffer->yy_n_chars = - yy_n_chars = yy_current_buffer->yy_buf_size; + if (yy_cp < yy_current_buffer->yy_ch_buf + 2) { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + register int number_to_move = yy_n_chars + 2; + register char *dest = &yy_current_buffer->yy_ch_buf[yy_current_buffer->yy_buf_size + + 2]; + register char *source = + &yy_current_buffer->yy_ch_buf[number_to_move]; - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - YY_FATAL_ERROR( "flex scanner push-back overflow" ); - } + while (source > yy_current_buffer->yy_ch_buf) + *--dest = *--source; - *--yy_cp = (char) c; + yy_cp += (int)(dest - source); + yy_bp += (int)(dest - source); + yy_current_buffer->yy_n_chars = + yy_n_chars = yy_current_buffer->yy_buf_size; + if (yy_cp < yy_current_buffer->yy_ch_buf + 2) + YY_FATAL_ERROR("flex scanner push-back overflow"); + } - yytext_ptr = yy_bp; - yy_hold_char = *yy_cp; - yy_c_buf_p = yy_cp; - } -#endif /* ifndef YY_NO_UNPUT */ + *--yy_cp = (char)c; + yytext_ptr = yy_bp; + yy_hold_char = *yy_cp; + yy_c_buf_p = yy_cp; +} +#endif /* ifndef YY_NO_UNPUT */ #ifndef YY_NO_INPUT #ifdef __cplusplus -static int yyinput() +static int +yyinput() #else -static int input() -#endif - { - int c; - - *yy_c_buf_p = yy_hold_char; - - if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) - { - /* yy_c_buf_p now points to the character we want to return. - * If this occurs *before* the EOB characters, then it's a - * valid NUL; if not, then we've hit the end of the buffer. - */ - if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - /* This was really a NUL. */ - *yy_c_buf_p = '\0'; - - else - { /* need more input */ - int offset = yy_c_buf_p - yytext_ptr; - ++yy_c_buf_p; - - switch ( yy_get_next_buffer() ) - { - case EOB_ACT_LAST_MATCH: - /* This happens because yy_g_n_b() - * sees that we've accumulated a - * token and flags that we need to - * try matching the token before - * proceeding. But for input(), - * there's no matching to consider. - * So convert the EOB_ACT_LAST_MATCH - * to EOB_ACT_END_OF_FILE. - */ - - /* Reset buffer status. */ - yyrestart( yyin ); - - /* fall through */ - - case EOB_ACT_END_OF_FILE: - { - if ( yywrap() ) - return EOF; - - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; +static int +input() +#endif +{ + int c; + + *yy_c_buf_p = yy_hold_char; + + if (*yy_c_buf_p == YY_END_OF_BUFFER_CHAR) { + /* yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if (yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars]) + /* This was really a NUL. */ + *yy_c_buf_p = '\0'; + + else { /* need more input */ + int offset = yy_c_buf_p - yytext_ptr; + ++yy_c_buf_p; + + switch (yy_get_next_buffer()) { + case EOB_ACT_LAST_MATCH: + /* This happens because yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + yyrestart(yyin); + + /* fall through */ + + case EOB_ACT_END_OF_FILE: { + if (yywrap()) + return EOF; + + if (!yy_did_buffer_switch_on_eof) + YY_NEW_FILE; #ifdef __cplusplus - return yyinput(); + return yyinput(); #else - return input(); + return input(); #endif - } + } - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = yytext_ptr + offset; - break; - } - } - } + case EOB_ACT_CONTINUE_SCAN: + yy_c_buf_p = yytext_ptr + offset; + break; + } + } + } - c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ - *yy_c_buf_p = '\0'; /* preserve yytext */ - yy_hold_char = *++yy_c_buf_p; + c = *(unsigned char *)yy_c_buf_p; /* cast for 8-bit char's */ + *yy_c_buf_p = '\0'; /* preserve yytext */ + yy_hold_char = *++yy_c_buf_p; - yy_current_buffer->yy_at_bol = (c == '\n'); + yy_current_buffer->yy_at_bol = (c == '\n'); - return c; - } + return c; +} #endif /* YY_NO_INPUT */ #ifdef YY_USE_PROTOS -void yyrestart( FILE *input_file ) +void +yyrestart(FILE *input_file) #else -void yyrestart( input_file ) -FILE *input_file; +void yyrestart(input_file) + FILE *input_file; #endif - { - if ( ! yy_current_buffer ) - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_init_buffer( yy_current_buffer, input_file ); - yy_load_buffer_state(); - } +{ + if (!yy_current_buffer) + yy_current_buffer = yy_create_buffer(yyin, YY_BUF_SIZE); + yy_init_buffer(yy_current_buffer, input_file); + yy_load_buffer_state(); +} #ifdef YY_USE_PROTOS -void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) +void +yy_switch_to_buffer(YY_BUFFER_STATE new_buffer) #else -void yy_switch_to_buffer( new_buffer ) -YY_BUFFER_STATE new_buffer; +void yy_switch_to_buffer(new_buffer) + YY_BUFFER_STATE new_buffer; #endif - { - if ( yy_current_buffer == new_buffer ) - return; - - if ( yy_current_buffer ) - { - /* Flush out information for old buffer. */ - *yy_c_buf_p = yy_hold_char; - yy_current_buffer->yy_buf_pos = yy_c_buf_p; - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - yy_current_buffer = new_buffer; - yy_load_buffer_state(); +{ + if (yy_current_buffer == new_buffer) + return; + + if (yy_current_buffer) { + /* Flush out information for old buffer. */ + *yy_c_buf_p = yy_hold_char; + yy_current_buffer->yy_buf_pos = yy_c_buf_p; + yy_current_buffer->yy_n_chars = yy_n_chars; + } - /* We don't actually know whether we did this switch during - * EOF (yywrap()) processing, but the only time this flag - * is looked at is after yywrap() is called, so it's safe - * to go ahead and always set it. - */ - yy_did_buffer_switch_on_eof = 1; - } + yy_current_buffer = new_buffer; + yy_load_buffer_state(); + /* We don't actually know whether we did this switch during + * EOF (yywrap()) processing, but the only time this flag + * is looked at is after yywrap() is called, so it's safe + * to go ahead and always set it. + */ + yy_did_buffer_switch_on_eof = 1; +} #ifdef YY_USE_PROTOS -void yy_load_buffer_state( void ) +void +yy_load_buffer_state(void) #else -void yy_load_buffer_state() +void +yy_load_buffer_state() #endif - { - yy_n_chars = yy_current_buffer->yy_n_chars; - yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; - yyin = yy_current_buffer->yy_input_file; - yy_hold_char = *yy_c_buf_p; - } - +{ + yy_n_chars = yy_current_buffer->yy_n_chars; + yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; + yyin = yy_current_buffer->yy_input_file; + yy_hold_char = *yy_c_buf_p; +} #ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) +YY_BUFFER_STATE +yy_create_buffer(FILE *file, int size) #else -YY_BUFFER_STATE yy_create_buffer( file, size ) -FILE *file; +YY_BUFFER_STATE yy_create_buffer(file, size) + FILE *file; int size; #endif - { - YY_BUFFER_STATE b; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); +{ + YY_BUFFER_STATE b; - b->yy_buf_size = size; + b = (YY_BUFFER_STATE)yy_flex_alloc(sizeof(struct yy_buffer_state)); + if (!b) + YY_FATAL_ERROR("out of dynamic memory in yy_create_buffer()"); - /* yy_ch_buf has to be 2 characters longer than the size given because - * we need to put in 2 end-of-buffer characters. - */ - b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + b->yy_buf_size = size; - b->yy_is_our_buffer = 1; + /* yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->yy_ch_buf = (char *)yy_flex_alloc(b->yy_buf_size + 2); + if (!b->yy_ch_buf) + YY_FATAL_ERROR("out of dynamic memory in yy_create_buffer()"); - yy_init_buffer( b, file ); + b->yy_is_our_buffer = 1; - return b; - } + yy_init_buffer(b, file); + return b; +} #ifdef YY_USE_PROTOS -void yy_delete_buffer( YY_BUFFER_STATE b ) +void +yy_delete_buffer(YY_BUFFER_STATE b) #else -void yy_delete_buffer( b ) -YY_BUFFER_STATE b; +void yy_delete_buffer(b) + YY_BUFFER_STATE b; #endif - { - if ( ! b ) - return; - - if ( b == yy_current_buffer ) - yy_current_buffer = (YY_BUFFER_STATE) 0; - - if ( b->yy_is_our_buffer ) - yy_flex_free( (void *) b->yy_ch_buf ); +{ + if (!b) + return; - yy_flex_free( (void *) b ); - } + if (b == yy_current_buffer) + yy_current_buffer = (YY_BUFFER_STATE)0; + if (b->yy_is_our_buffer) + yy_flex_free((void *)b->yy_ch_buf); + yy_flex_free((void *)b); +} #ifdef YY_USE_PROTOS -void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) +void +yy_init_buffer(YY_BUFFER_STATE b, FILE *file) #else -void yy_init_buffer( b, file ) -YY_BUFFER_STATE b; +void yy_init_buffer(b, file) + YY_BUFFER_STATE b; FILE *file; #endif +{ + yy_flush_buffer(b); - { - yy_flush_buffer( b ); - - b->yy_input_file = file; - b->yy_fill_buffer = 1; + b->yy_input_file = file; + b->yy_fill_buffer = 1; #if YY_ALWAYS_INTERACTIVE - b->yy_is_interactive = 1; + b->yy_is_interactive = 1; #else #if YY_NEVER_INTERACTIVE - b->yy_is_interactive = 0; + b->yy_is_interactive = 0; #else - b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; + b->yy_is_interactive = file ? (isatty(fileno(file)) > 0) : 0; #endif #endif - } - +} #ifdef YY_USE_PROTOS -void yy_flush_buffer( YY_BUFFER_STATE b ) +void +yy_flush_buffer(YY_BUFFER_STATE b) #else -void yy_flush_buffer( b ) -YY_BUFFER_STATE b; +void yy_flush_buffer(b) + YY_BUFFER_STATE b; #endif - { - if ( ! b ) - return; - - b->yy_n_chars = 0; +{ + if (!b) + return; - /* We always need two end-of-buffer characters. The first causes - * a transition to the end-of-buffer state. The second causes - * a jam in that state. - */ - b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; - b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + b->yy_n_chars = 0; - b->yy_buf_pos = &b->yy_ch_buf[0]; + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; - b->yy_at_bol = 1; - b->yy_buffer_status = YY_BUFFER_NEW; + b->yy_buf_pos = &b->yy_ch_buf[0]; - if ( b == yy_current_buffer ) - yy_load_buffer_state(); - } + b->yy_at_bol = 1; + b->yy_buffer_status = YY_BUFFER_NEW; + if (b == yy_current_buffer) + yy_load_buffer_state(); +} #ifndef YY_NO_SCAN_BUFFER #ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) +YY_BUFFER_STATE +yy_scan_buffer(char *base, yy_size_t size) #else -YY_BUFFER_STATE yy_scan_buffer( base, size ) -char *base; +YY_BUFFER_STATE yy_scan_buffer(base, size) char *base; yy_size_t size; #endif - { - YY_BUFFER_STATE b; - - if ( size < 2 || - base[size-2] != YY_END_OF_BUFFER_CHAR || - base[size-1] != YY_END_OF_BUFFER_CHAR ) - /* They forgot to leave room for the EOB's. */ - return 0; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ - b->yy_buf_pos = b->yy_ch_buf = base; - b->yy_is_our_buffer = 0; - b->yy_input_file = 0; - b->yy_n_chars = b->yy_buf_size; - b->yy_is_interactive = 0; - b->yy_at_bol = 1; - b->yy_fill_buffer = 0; - b->yy_buffer_status = YY_BUFFER_NEW; - - yy_switch_to_buffer( b ); - - return b; - } +{ + YY_BUFFER_STATE b; + + if (size < 2 || + base[size - 2] != YY_END_OF_BUFFER_CHAR || + base[size - 1] != YY_END_OF_BUFFER_CHAR) + /* They forgot to leave room for the EOB's. */ + return 0; + + b = (YY_BUFFER_STATE)yy_flex_alloc(sizeof(struct yy_buffer_state)); + if (!b) + YY_FATAL_ERROR("out of dynamic memory in yy_scan_buffer()"); + + b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ + b->yy_buf_pos = b->yy_ch_buf = base; + b->yy_is_our_buffer = 0; + b->yy_input_file = 0; + b->yy_n_chars = b->yy_buf_size; + b->yy_is_interactive = 0; + b->yy_at_bol = 1; + b->yy_fill_buffer = 0; + b->yy_buffer_status = YY_BUFFER_NEW; + + yy_switch_to_buffer(b); + + return b; +} #endif - #ifndef YY_NO_SCAN_STRING #ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) +YY_BUFFER_STATE +yy_scan_string(yyconst char *yy_str) #else -YY_BUFFER_STATE yy_scan_string( yy_str ) -yyconst char *yy_str; +YY_BUFFER_STATE yy_scan_string(yy_str) + yyconst char *yy_str; #endif - { - int len; - for ( len = 0; yy_str[len]; ++len ) - ; +{ + int len; + for (len = 0; yy_str[len]; ++len) + ; - return yy_scan_bytes( yy_str, len ); - } + return yy_scan_bytes(yy_str, len); +} #endif - #ifndef YY_NO_SCAN_BYTES #ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) +YY_BUFFER_STATE +yy_scan_bytes(yyconst char *bytes, int len) #else -YY_BUFFER_STATE yy_scan_bytes( bytes, len ) -yyconst char *bytes; +YY_BUFFER_STATE yy_scan_bytes(bytes, len) + yyconst char *bytes; int len; #endif - { - YY_BUFFER_STATE b; - char *buf; - yy_size_t n; - int i; +{ + YY_BUFFER_STATE b; + char *buf; + yy_size_t n; + int i; - /* Get memory for full buffer, including space for trailing EOB's. */ - n = len + 2; - buf = (char *) yy_flex_alloc( n ); - if ( ! buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); + /* Get memory for full buffer, including space for trailing EOB's. */ + n = len + 2; + buf = (char *)yy_flex_alloc(n); + if (!buf) + YY_FATAL_ERROR("out of dynamic memory in yy_scan_bytes()"); - for ( i = 0; i < len; ++i ) - buf[i] = bytes[i]; + for (i = 0; i < len; ++i) + buf[i] = bytes[i]; - buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; + buf[len] = buf[len + 1] = YY_END_OF_BUFFER_CHAR; - b = yy_scan_buffer( buf, n ); - if ( ! b ) - YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); + b = yy_scan_buffer(buf, n); + if (!b) + YY_FATAL_ERROR("bad buffer in yy_scan_bytes()"); - /* It's okay to grow etc. this buffer, and we should throw it - * away when we're done. - */ - b->yy_is_our_buffer = 1; + /* It's okay to grow etc. this buffer, and we should throw it + * away when we're done. + */ + b->yy_is_our_buffer = 1; - return b; - } + return b; +} #endif - #ifndef YY_NO_PUSH_STATE #ifdef YY_USE_PROTOS -static void yy_push_state( int new_state ) +static void +yy_push_state(int new_state) #else -static void yy_push_state( new_state ) -int new_state; +static void yy_push_state(new_state) int new_state; #endif - { - if ( yy_start_stack_ptr >= yy_start_stack_depth ) - { - yy_size_t new_size; +{ + if (yy_start_stack_ptr >= yy_start_stack_depth) { + yy_size_t new_size; - yy_start_stack_depth += YY_START_STACK_INCR; - new_size = yy_start_stack_depth * sizeof( int ); + yy_start_stack_depth += YY_START_STACK_INCR; + new_size = yy_start_stack_depth * sizeof(int); - if ( ! yy_start_stack ) - yy_start_stack = (int *) yy_flex_alloc( new_size ); + if (!yy_start_stack) + yy_start_stack = (int *)yy_flex_alloc(new_size); - else - yy_start_stack = (int *) yy_flex_realloc( - (void *) yy_start_stack, new_size ); + else + yy_start_stack = (int *)yy_flex_realloc( + (void *)yy_start_stack, new_size); - if ( ! yy_start_stack ) - YY_FATAL_ERROR( - "out of memory expanding start-condition stack" ); - } + if (!yy_start_stack) + YY_FATAL_ERROR( + "out of memory expanding start-condition stack"); + } - yy_start_stack[yy_start_stack_ptr++] = YY_START; + yy_start_stack[yy_start_stack_ptr++] = YY_START; - BEGIN(new_state); - } + BEGIN(new_state); +} #endif - #ifndef YY_NO_POP_STATE -static void yy_pop_state() - { - if ( --yy_start_stack_ptr < 0 ) - YY_FATAL_ERROR( "start-condition stack underflow" ); +static void +yy_pop_state() +{ + if (--yy_start_stack_ptr < 0) + YY_FATAL_ERROR("start-condition stack underflow"); - BEGIN(yy_start_stack[yy_start_stack_ptr]); - } + BEGIN(yy_start_stack[yy_start_stack_ptr]); +} #endif - #ifndef YY_NO_TOP_STATE -static int yy_top_state() - { - return yy_start_stack[yy_start_stack_ptr - 1]; - } +static int +yy_top_state() +{ + return yy_start_stack[yy_start_stack_ptr - 1]; +} #endif #ifndef YY_EXIT_FAILURE @@ -1638,113 +1625,110 @@ static int yy_top_state() #endif #ifdef YY_USE_PROTOS -static void yy_fatal_error( yyconst char msg[] ) +static void +yy_fatal_error(yyconst char msg[]) #else -static void yy_fatal_error( msg ) -char msg[]; +static void yy_fatal_error(msg) char msg[]; #endif - { - (void) fprintf( stderr, "%s\n", msg ); - exit( YY_EXIT_FAILURE ); - } - - +{ + (void)fprintf(stderr, "%s\n", msg); + exit(YY_EXIT_FAILURE); +} /* Redefine yyless() so it works in section 3 code. */ #undef yyless -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - yytext[yyleng] = yy_hold_char; \ - yy_c_buf_p = yytext + n; \ - yy_hold_char = *yy_c_buf_p; \ - *yy_c_buf_p = '\0'; \ - yyleng = n; \ - } \ - while ( 0 ) - +#define yyless(n) \ + do { \ + /* Undo effects of setting up yytext. */ \ + yytext[yyleng] = yy_hold_char; \ + yy_c_buf_p = yytext + n; \ + yy_hold_char = *yy_c_buf_p; \ + *yy_c_buf_p = '\0'; \ + yyleng = n; \ + } while (0) /* Internal utility routines. */ #ifndef yytext_ptr #ifdef YY_USE_PROTOS -static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) +static void +yy_flex_strncpy(char *s1, yyconst char *s2, int n) #else -static void yy_flex_strncpy( s1, s2, n ) -char *s1; +static void yy_flex_strncpy(s1, s2, n) char *s1; yyconst char *s2; int n; #endif - { - register int i; - for ( i = 0; i < n; ++i ) - s1[i] = s2[i]; - } +{ + register int i; + for (i = 0; i < n; ++i) + s1[i] = s2[i]; +} #endif #ifdef YY_NEED_STRLEN #ifdef YY_USE_PROTOS -static int yy_flex_strlen( yyconst char *s ) +static int +yy_flex_strlen(yyconst char *s) #else -static int yy_flex_strlen( s ) -yyconst char *s; +static int yy_flex_strlen(s) + yyconst char *s; #endif - { - register int n; - for ( n = 0; s[n]; ++n ) - ; +{ + register int n; + for (n = 0; s[n]; ++n) + ; - return n; - } + return n; +} #endif - #ifdef YY_USE_PROTOS -static void *yy_flex_alloc( yy_size_t size ) +static void * +yy_flex_alloc(yy_size_t size) #else -static void *yy_flex_alloc( size ) -yy_size_t size; +static void *yy_flex_alloc(size) + yy_size_t size; #endif - { - return (void *) malloc( size ); - } +{ + return (void *)malloc(size); +} #ifdef YY_USE_PROTOS -static void *yy_flex_realloc( void *ptr, yy_size_t size ) +static void * +yy_flex_realloc(void *ptr, yy_size_t size) #else -static void *yy_flex_realloc( ptr, size ) -void *ptr; +static void *yy_flex_realloc(ptr, size) void *ptr; yy_size_t size; #endif - { - /* The cast to (char *) in the following accommodates both - * implementations that use char* generic pointers, and those - * that use void* generic pointers. It works with the latter - * because both ANSI C and C++ allow castless assignment from - * any pointer type to void*, and deal with argument conversions - * as though doing an assignment. - */ - return (void *) realloc( (char *) ptr, size ); - } +{ + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return (void *)realloc((char *)ptr, size); +} #ifdef YY_USE_PROTOS -static void yy_flex_free( void *ptr ) +static void +yy_flex_free(void *ptr) #else -static void yy_flex_free( ptr ) -void *ptr; +static void yy_flex_free(ptr) void *ptr; #endif - { - free( ptr ); - } +{ + free(ptr); +} #if YY_MAIN -int main() - { - yylex(); - return 0; - } +int +main() +{ + yylex(); + return 0; +} #endif #line 144 "crlgen_lex_orig.l" @@ -1752,18 +1736,20 @@ int main() static PRLock *parserInvocationLock; -void CRLGEN_InitCrlGenParserLock() +void +CRLGEN_InitCrlGenParserLock() { parserInvocationLock = PR_NewLock(); } -void CRLGEN_DestroyCrlGenParserLock() +void +CRLGEN_DestroyCrlGenParserLock() { PR_DestroyLock(parserInvocationLock); } - -SECStatus CRLGEN_StartCrlGen(CRLGENGeneratorData *parserCtlData) +SECStatus +CRLGEN_StartCrlGen(CRLGENGeneratorData *parserCtlData) { SECStatus rv; @@ -1780,4 +1766,8 @@ SECStatus CRLGEN_StartCrlGen(CRLGENGeneratorData *parserCtlData) return rv; } -int yywrap() {return 1;} +int +yywrap() +{ + return 1; +} diff --git a/cmd/crlutil/crlutil.c b/cmd/crlutil/crlutil.c index d501371402..9fca6b40bc 100644 --- a/cmd/crlutil/crlutil.c +++ b/cmd/crlutil/crlutil.c @@ -25,10 +25,10 @@ static char *progName; -static CERTSignedCrl *FindCRL - (CERTCertDBHandle *certHandle, char *name, int type) +static CERTSignedCrl * +FindCRL(CERTCertDBHandle *certHandle, char *name, int type) { - CERTSignedCrl *crl = NULL; + CERTSignedCrl *crl = NULL; CERTCertificate *cert = NULL; SECItem derName; @@ -39,14 +39,14 @@ static CERTSignedCrl *FindCRL if (!cert) { CERTName *certName = NULL; PLArenaPool *arena = NULL; - + certName = CERT_AsciiToName(name); if (certName) { arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena) { - SECItem *nameItem = - SEC_ASN1EncodeItem (arena, NULL, (void *)certName, - SEC_ASN1_GET(CERT_NameTemplate)); + SECItem *nameItem = + SEC_ASN1EncodeItem(arena, NULL, (void *)certName, + SEC_ASN1_GET(CERT_NameTemplate)); if (nameItem) { SECITEM_CopyItem(NULL, &derName, nameItem); } @@ -61,34 +61,35 @@ static CERTSignedCrl *FindCRL } } else { SECITEM_CopyItem(NULL, &derName, &cert->derSubject); - CERT_DestroyCertificate (cert); + CERT_DestroyCertificate(cert); } - + crl = SEC_FindCrlByName(certHandle, &derName, type); - if (crl ==NULL) - SECU_PrintError - (progName, "could not find %s's CRL", name); + if (crl == NULL) + SECU_PrintError(progName, "could not find %s's CRL", name); if (derName.data) { SECITEM_FreeItem(&derName, PR_FALSE); } return (crl); } -static SECStatus DisplayCRL (CERTCertDBHandle *certHandle, char *nickName, int crlType) +static SECStatus +DisplayCRL(CERTCertDBHandle *certHandle, char *nickName, int crlType) { CERTSignedCrl *crl = NULL; - crl = FindCRL (certHandle, nickName, crlType); - + crl = FindCRL(certHandle, nickName, crlType); + if (crl) { - SECU_PrintCRLInfo (stdout, &crl->crl, "CRL Info:\n", 0); - SEC_DestroyCrl (crl); - return SECSuccess; + SECU_PrintCRLInfo(stdout, &crl->crl, "CRL Info:\n", 0); + SEC_DestroyCrl(crl); + return SECSuccess; } return SECFailure; } -static void ListCRLNames (CERTCertDBHandle *certHandle, int crlType, PRBool deletecrls) +static void +ListCRLNames(CERTCertDBHandle *certHandle, int crlType, PRBool deletecrls) { CERTCrlHeadNode *crlList = NULL; CERTCrlNode *crlNode = NULL; @@ -97,131 +98,130 @@ static void ListCRLNames (CERTCertDBHandle *certHandle, int crlType, PRBool dele SECStatus rv; do { - arena = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE); - if (arena == NULL) { - fprintf(stderr, "%s: fail to allocate memory\n", progName); - break; - } - - name = PORT_ArenaZAlloc (arena, sizeof(*name)); - if (name == NULL) { - fprintf(stderr, "%s: fail to allocate memory\n", progName); - break; - } - name->arena = arena; - - rv = SEC_LookupCrls (certHandle, &crlList, crlType); - if (rv != SECSuccess) { - fprintf(stderr, "%s: fail to look up CRLs (%s)\n", progName, - SECU_Strerror(PORT_GetError())); - break; - } - - /* just in case */ - if (!crlList) - break; - - crlNode = crlList->first; - - fprintf (stdout, "\n"); - fprintf (stdout, "\n%-40s %-5s\n\n", "CRL names", "CRL Type"); - while (crlNode) { - char* asciiname = NULL; - CERTCertificate *cert = NULL; - if (crlNode->crl && crlNode->crl->crl.derName.data != NULL) { - cert = CERT_FindCertByName(certHandle, - &crlNode->crl->crl.derName); - if (!cert) { - SECU_PrintError(progName, "could not find signing " - "certificate in database"); - } - } - if (cert) { - char* certName = NULL; - if (cert->nickname && PORT_Strlen(cert->nickname) > 0) { - certName = cert->nickname; - } else if (cert->emailAddr && PORT_Strlen(cert->emailAddr) > 0) { - certName = cert->emailAddr; - } - if (certName) { - asciiname = PORT_Strdup(certName); - } - CERT_DestroyCertificate(cert); - } - - if (!asciiname) { - name = &crlNode->crl->crl.name; - if (!name){ - SECU_PrintError(progName, "fail to get the CRL " - "issuer name"); - continue; - } - asciiname = CERT_NameToAscii(name); - } - fprintf (stdout, "%-40s %-5s\n", asciiname, "CRL"); - if (asciiname) { - PORT_Free(asciiname); - } - if ( PR_TRUE == deletecrls) { - CERTSignedCrl* acrl = NULL; - SECItem* issuer = &crlNode->crl->crl.derName; + arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); + if (arena == NULL) { + fprintf(stderr, "%s: fail to allocate memory\n", progName); + break; + } + + name = PORT_ArenaZAlloc(arena, sizeof(*name)); + if (name == NULL) { + fprintf(stderr, "%s: fail to allocate memory\n", progName); + break; + } + name->arena = arena; + + rv = SEC_LookupCrls(certHandle, &crlList, crlType); + if (rv != SECSuccess) { + fprintf(stderr, "%s: fail to look up CRLs (%s)\n", progName, + SECU_Strerror(PORT_GetError())); + break; + } + + /* just in case */ + if (!crlList) + break; + + crlNode = crlList->first; + + fprintf(stdout, "\n"); + fprintf(stdout, "\n%-40s %-5s\n\n", "CRL names", "CRL Type"); + while (crlNode) { + char *asciiname = NULL; + CERTCertificate *cert = NULL; + if (crlNode->crl && crlNode->crl->crl.derName.data != NULL) { + cert = CERT_FindCertByName(certHandle, + &crlNode->crl->crl.derName); + if (!cert) { + SECU_PrintError(progName, "could not find signing " + "certificate in database"); + } + } + if (cert) { + char *certName = NULL; + if (cert->nickname && PORT_Strlen(cert->nickname) > 0) { + certName = cert->nickname; + } else if (cert->emailAddr && PORT_Strlen(cert->emailAddr) > 0) { + certName = cert->emailAddr; + } + if (certName) { + asciiname = PORT_Strdup(certName); + } + CERT_DestroyCertificate(cert); + } + + if (!asciiname) { + name = &crlNode->crl->crl.name; + if (!name) { + SECU_PrintError(progName, "fail to get the CRL " + "issuer name"); + continue; + } + asciiname = CERT_NameToAscii(name); + } + fprintf(stdout, "%-40s %-5s\n", asciiname, "CRL"); + if (asciiname) { + PORT_Free(asciiname); + } + if (PR_TRUE == deletecrls) { + CERTSignedCrl *acrl = NULL; + SECItem *issuer = &crlNode->crl->crl.derName; acrl = SEC_FindCrlByName(certHandle, issuer, crlType); - if (acrl) - { + if (acrl) { SEC_DeletePermCRL(acrl); SEC_DestroyCrl(acrl); } } crlNode = crlNode->next; - } - + } + } while (0); if (crlList) - PORT_FreeArena (crlList->arena, PR_FALSE); - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(crlList->arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } -static SECStatus ListCRL (CERTCertDBHandle *certHandle, char *nickName, int crlType) +static SECStatus +ListCRL(CERTCertDBHandle *certHandle, char *nickName, int crlType) { if (nickName == NULL) { - ListCRLNames (certHandle, crlType, PR_FALSE); - return SECSuccess; - } + ListCRLNames(certHandle, crlType, PR_FALSE); + return SECSuccess; + } - return DisplayCRL (certHandle, nickName, crlType); + return DisplayCRL(certHandle, nickName, crlType); } - - -static SECStatus DeleteCRL (CERTCertDBHandle *certHandle, char *name, int type) +static SECStatus +DeleteCRL(CERTCertDBHandle *certHandle, char *name, int type) { - CERTSignedCrl *crl = NULL; + CERTSignedCrl *crl = NULL; SECStatus rv = SECFailure; - crl = FindCRL (certHandle, name, type); + crl = FindCRL(certHandle, name, type); if (!crl) { - SECU_PrintError - (progName, "could not find the issuer %s's CRL", name); - return SECFailure; + SECU_PrintError(progName, "could not find the issuer %s's CRL", name); + return SECFailure; } - rv = SEC_DeletePermCRL (crl); + rv = SEC_DeletePermCRL(crl); SEC_DestroyCrl(crl); if (rv != SECSuccess) { - SECU_PrintError(progName, "fail to delete the issuer %s's CRL " - "from the perm database (reason: %s)", - name, SECU_Strerror(PORT_GetError())); - return SECFailure; + SECU_PrintError(progName, "fail to delete the issuer %s's CRL " + "from the perm database (reason: %s)", + name, SECU_Strerror(PORT_GetError())); + return SECFailure; } return (rv); } -SECStatus ImportCRL (CERTCertDBHandle *certHandle, char *url, int type, - PRFileDesc *inFile, PRInt32 importOptions, PRInt32 decodeOptions, - secuPWData *pwdata) +SECStatus +ImportCRL(CERTCertDBHandle *certHandle, char *url, int type, + PRFileDesc *inFile, PRInt32 importOptions, PRInt32 decodeOptions, + secuPWData *pwdata) { CERTSignedCrl *crl = NULL; SECItem crlDER; - PK11SlotInfo* slot = NULL; + PK11SlotInfo *slot = NULL; int rv; #if defined(DEBUG_jp96085) PRIntervalTime starttime, endtime, elapsed; @@ -230,12 +230,11 @@ SECStatus ImportCRL (CERTCertDBHandle *certHandle, char *url, int type, crlDER.data = NULL; - /* Read in the entire file specified with the -f argument */ rv = SECU_ReadDERFromFile(&crlDER, inFile, PR_FALSE, PR_FALSE); if (rv != SECSuccess) { - SECU_PrintError(progName, "unable to read input file"); - return (SECFailure); + SECU_PrintError(progName, "unable to read input file"); + return (SECFailure); } decodeOptions |= CRL_DECODE_DONT_COPY_DER; @@ -243,16 +242,16 @@ SECStatus ImportCRL (CERTCertDBHandle *certHandle, char *url, int type, slot = PK11_GetInternalKeySlot(); if (PK11_NeedLogin(slot)) { - rv = PK11_Authenticate(slot, PR_TRUE, pwdata); - if (rv != SECSuccess) - goto loser; + rv = PK11_Authenticate(slot, PR_TRUE, pwdata); + if (rv != SECSuccess) + goto loser; } - + #if defined(DEBUG_jp96085) starttime = PR_IntervalNow(); #endif crl = PK11_ImportCRL(slot, &crlDER, url, type, - NULL, importOptions, NULL, decodeOptions); + NULL, importOptions, NULL, decodeOptions); #if defined(DEBUG_jp96085) endtime = PR_IntervalNow(); elapsed = endtime - starttime; @@ -262,70 +261,71 @@ SECStatus ImportCRL (CERTCertDBHandle *certHandle, char *url, int type, printf("Elapsed : %2d:%2d.%3d\n", mins, secs, msecs); #endif if (!crl) { - const char *errString; - - rv = SECFailure; - errString = SECU_Strerror(PORT_GetError()); - if ( errString && PORT_Strlen (errString) == 0) - SECU_PrintError (progName, - "CRL is not imported (error: input CRL is not up to date.)"); - else - SECU_PrintError (progName, "unable to import CRL"); + const char *errString; + + rv = SECFailure; + errString = SECU_Strerror(PORT_GetError()); + if (errString && PORT_Strlen(errString) == 0) + SECU_PrintError(progName, + "CRL is not imported (error: input CRL is not up to date.)"); + else + SECU_PrintError(progName, "unable to import CRL"); } else { - SEC_DestroyCrl (crl); + SEC_DestroyCrl(crl); } - loser: +loser: if (slot) { PK11_FreeSlot(slot); } return (rv); } -SECStatus DumpCRL(PRFileDesc *inFile) +SECStatus +DumpCRL(PRFileDesc *inFile) { int rv; PLArenaPool *arena = NULL; CERTSignedCrl *newCrl = NULL; - + SECItem crlDER; crlDER.data = NULL; /* Read in the entire file specified with the -f argument */ rv = SECU_ReadDERFromFile(&crlDER, inFile, PR_FALSE, PR_FALSE); if (rv != SECSuccess) { - SECU_PrintError(progName, "unable to read input file"); - return (SECFailure); + SECU_PrintError(progName, "unable to read input file"); + return (SECFailure); } - + rv = SEC_ERROR_NO_MEMORY; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (!arena) - return rv; + return rv; newCrl = CERT_DecodeDERCrlWithFlags(arena, &crlDER, SEC_CRL_TYPE, - CRL_DECODE_DEFAULT_OPTIONS); + CRL_DECODE_DEFAULT_OPTIONS); if (!newCrl) - return SECFailure; - - SECU_PrintCRLInfo (stdout, &newCrl->crl, "CRL file contents", 0); - - PORT_FreeArena (arena, PR_FALSE); + return SECFailure; + + SECU_PrintCRLInfo(stdout, &newCrl->crl, "CRL file contents", 0); + + PORT_FreeArena(arena, PR_FALSE); return rv; } -static CERTCertificate* +static CERTCertificate * FindSigningCert(CERTCertDBHandle *certHandle, CERTSignedCrl *signCrl, char *certNickName) -{ +{ CERTCertificate *cert = NULL, *certTemp = NULL; SECStatus rv = SECFailure; - CERTAuthKeyID* authorityKeyID = NULL; - SECItem* subject = NULL; + CERTAuthKeyID *authorityKeyID = NULL; + SECItem *subject = NULL; PORT_Assert(certHandle != NULL); if (!certHandle || (!signCrl && !certNickName)) { SECU_PrintError(progName, "invalid args for function " - "FindSigningCert \n"); + "FindSigningCert \n"); return NULL; } @@ -338,7 +338,8 @@ FindSigningCert(CERTCertDBHandle *certHandle, CERTSignedCrl *signCrl, certTemp = CERT_FindCertByNickname(certHandle, certNickName); if (!certTemp) { SECU_PrintError(progName, "could not find certificate \"%s\" " - "in database", certNickName); + "in database", + certNickName); goto loser; } subject = &certTemp->derSubject; @@ -347,13 +348,13 @@ FindSigningCert(CERTCertDBHandle *certHandle, CERTSignedCrl *signCrl, cert = SECU_FindCrlIssuer(certHandle, subject, authorityKeyID, PR_Now()); if (!cert) { SECU_PrintError(progName, "could not find signing certificate " - "in database"); + "in database"); goto loser; } else { rv = SECSuccess; } - loser: +loser: if (certTemp) CERT_DestroyCertificate(certTemp); if (cert && rv != SECSuccess) @@ -361,13 +362,13 @@ FindSigningCert(CERTCertDBHandle *certHandle, CERTSignedCrl *signCrl, return cert; } -static CERTSignedCrl* +static CERTSignedCrl * CreateModifiedCRLCopy(PLArenaPool *arena, CERTCertDBHandle *certHandle, - CERTCertificate **cert, char *certNickName, - PRFileDesc *inFile, PRInt32 decodeOptions, - PRInt32 importOptions) + CERTCertificate **cert, char *certNickName, + PRFileDesc *inFile, PRInt32 decodeOptions, + PRInt32 importOptions) { - SECItem crlDER = {0, NULL, 0}; + SECItem crlDER = { 0, NULL, 0 }; CERTSignedCrl *signCrl = NULL; CERTSignedCrl *modCrl = NULL; PLArenaPool *modArena = NULL; @@ -384,7 +385,7 @@ CreateModifiedCRLCopy(PLArenaPool *arena, CERTCertDBHandle *certHandle, SECU_PrintError(progName, "fail to allocate memory\n"); return NULL; } - + if (inFile != NULL) { rv = SECU_ReadDERFromFile(&crlDER, inFile, PR_FALSE, PR_FALSE); if (rv != SECSuccess) { @@ -392,17 +393,17 @@ CreateModifiedCRLCopy(PLArenaPool *arena, CERTCertDBHandle *certHandle, PORT_FreeArena(modArena, PR_FALSE); goto loser; } - + decodeOptions |= CRL_DECODE_DONT_COPY_DER; - + modCrl = CERT_DecodeDERCrlWithFlags(modArena, &crlDER, SEC_CRL_TYPE, decodeOptions); if (!modCrl) { SECU_PrintError(progName, "fail to decode CRL"); goto loser; } - - if (0 == (importOptions & CRL_IMPORT_BYPASS_CHECKS)){ + + if (0 == (importOptions & CRL_IMPORT_BYPASS_CHECKS)) { /* If caCert is a v2 certificate, make sure that it * can be used for crl signing purpose */ *cert = FindSigningCert(certHandle, modCrl, NULL); @@ -435,9 +436,9 @@ CreateModifiedCRLCopy(PLArenaPool *arena, CERTCertDBHandle *certHandle, rv = SECU_CopyCRL(arena, &signCrl->crl, &modCrl->crl); if (rv != SECSuccess) { SECU_PrintError(progName, "unable to dublicate crl for " - "modification."); + "modification."); goto loser; - } + } /* Make sure the update time is current. It can be modified later * by "update