Bug 741135, Update Mozilla to NSS 3.13.4, a=akeybl
authorKai Engert <kaie@kuix.de>
Thu, 26 Apr 2012 14:06:07 +0200
changeset 92887 7d395fbcb557f54b8293da9340ea4ad1cfaef3b1
parent 92871 37fdf8dbe871590f9cc9b31888c94ef072388c2c
child 93226 c8ab4b92efd0fc7216f908034df78d8c1e7c9d32
push idunknown
push userunknown
push dateunknown
reviewersakeybl
bugs741135
milestone10.0.5esrpre
Bug 741135, Update Mozilla to NSS 3.13.4, a=akeybl
client.py
security/coreconf/coreconf.dep
security/nss/TAG-INFO
security/nss/TAG-INFO-CKBI
security/nss/cmd/addbuiltin/addbuiltin.c
security/nss/cmd/certutil/certutil.c
security/nss/cmd/crlutil/crlutil.c
security/nss/cmd/lib/secutil.c
security/nss/cmd/lib/secutil.h
security/nss/cmd/selfserv/selfserv.c
security/nss/cmd/symkeyutil/symkeyutil.c
security/nss/lib/certdb/certdb.c
security/nss/lib/certdb/stanpcertdb.c
security/nss/lib/certhigh/certvfypkix.c
security/nss/lib/certhigh/ocsp.c
security/nss/lib/cryptohi/secvfy.c
security/nss/lib/freebl/blapi.h
security/nss/lib/freebl/blapit.h
security/nss/lib/freebl/dh.c
security/nss/lib/libpkix/pkix/results/pkix_valresult.c
security/nss/lib/libpkix/pkix/top/pkix_build.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.h
security/nss/lib/nss/nss.h
security/nss/lib/pk11wrap/pk11auth.c
security/nss/lib/pk11wrap/pk11merge.c
security/nss/lib/pk11wrap/pk11sdr.c
security/nss/lib/pkcs12/p12e.c
security/nss/lib/pkcs7/p7create.c
security/nss/lib/smime/smimeutil.c
security/nss/lib/softoken/legacydb/keydb.c
security/nss/lib/softoken/legacydb/lgcreate.c
security/nss/lib/softoken/legacydb/lowkey.c
security/nss/lib/softoken/legacydb/lowkeyti.h
security/nss/lib/softoken/softkver.h
security/nss/lib/ssl/ssl3con.c
security/nss/lib/ssl/ssl3ext.c
security/nss/lib/ssl/sslcon.c
security/nss/lib/ssl/sslenum.c
security/nss/lib/ssl/sslinfo.c
security/nss/lib/ssl/sslsecur.c
security/nss/lib/ssl/sslsock.c
security/nss/lib/util/ciferfam.h
security/nss/lib/util/nssutil.h
security/nss/lib/util/quickder.c
security/nss/lib/util/secitem.c
--- a/client.py
+++ b/client.py
@@ -86,16 +86,17 @@ elif action in ('update_nspr'):
     do_cvs_export(NSPR_DIRS, tag, options.cvsroot, options.cvs)
     print >>file("nsprpub/TAG-INFO", "w"), tag
 elif action in ('update_nss'):
     tag, = args[1:]
     if not options.cvsroot:
         options.cvsroot = os.environ.get('CVSROOT', CVSROOT_MOZILLA)
     do_cvs_export(NSS_DIRS, tag, options.cvsroot, options.cvs)
     print >>file("security/nss/TAG-INFO", "w"), tag
+    print >>file("security/nss/TAG-INFO-CKBI", "w"), tag
 elif action in ('update_libffi'):
     tag, = args[1:]
     if not options.cvsroot:
         options.cvsroot = CVSROOT_LIBFFI
     do_cvs_export(LIBFFI_DIRS, tag, options.cvsroot, options.cvs)
 else:
     o.print_help()
     sys.exit(2)
--- a/security/coreconf/coreconf.dep
+++ b/security/coreconf/coreconf.dep
@@ -38,9 +38,8 @@
 /*
  * A dummy header file that is a dependency for all the object files.
  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
  * depend builds.  See comments in rules.mk.
  */
 
 #error "Do not include this header file."
 
-
--- a/security/nss/TAG-INFO
+++ b/security/nss/TAG-INFO
@@ -1,1 +1,1 @@
-NSS_3_13_3_RTM
+NSS_3_13_4_RTM
new file mode 100644
--- /dev/null
+++ b/security/nss/TAG-INFO-CKBI
@@ -0,0 +1,1 @@
+NSS_3_13_4_RTM
--- a/security/nss/cmd/addbuiltin/addbuiltin.c
+++ b/security/nss/cmd/addbuiltin/addbuiltin.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Tool for converting builtin CA certs.
  *
- * $Id: addbuiltin.c,v 1.16 2011/04/13 00:10:21 rrelyea%redhat.com Exp $
+ * $Id: addbuiltin.c,v 1.17 2012/03/10 12:10:44 kaie%kuix.de Exp $
  */
 
 #include "nssrenam.h"
 #include "nss.h"
 #include "cert.h"
 #include "certdb.h"
 #include "secutil.h"
 #include "pk11func.h"
@@ -86,96 +86,211 @@ char *getTrustString(unsigned int trust)
     return "CKT_NSS_TRUST_UNKNOWN"; /* not reached */
 }
 
 static const SEC_ASN1Template serialTemplate[] = {
     { SEC_ASN1_INTEGER, offsetof(CERTCertificate,serialNumber) },
     { 0 }
 };
 
+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);
+}
+
 static SECStatus
-ConvertCertificate(SECItem *sdder, char *nickname, CERTCertTrust *trust)
+ConvertCRLEntry(SECItem *sdder, PRInt32 crlentry, char *nickname)
+{
+    int rv;
+    PRArenaPool *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;
+
+    newCrl = CERT_DecodeDERCrlWithFlags(arena, sdder, SEC_CRL_TYPE,
+					CRL_DECODE_DEFAULT_OPTIONS);
+    if (!newCrl)
+    	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;
+	    }
+	}
+    }
+    
+    if (!name || !derName || !serial)
+    	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_ISSUER MULTILINE_OCTAL\n");
+    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);
+    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);
+    return rv;
+}
+
+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_PrintFingerprints(stdout, sdder, "# Fingerprint", 0);
+
+    SECU_EnableWrap(saveWrapeState);
+}
+
+static SECStatus
+ConvertCertificate(SECItem *sdder, char *nickname, CERTCertTrust *trust,
+                   PRBool excludeCert, PRBool excludeHash)
 {
     SECStatus rv = SECSuccess;
     CERTCertificate *cert;
     unsigned char sha1_hash[SHA1_LENGTH];
     unsigned char md5_hash[MD5_LENGTH];
     SECItem *serial = NULL;
+    PRBool step_up = PR_FALSE;
+    const char *trust_info;
 
     cert = CERT_DecodeDERCertificate(sdder, PR_FALSE, nickname);
     if (!cert) {
 	return SECFailure;
     }
     serial = SEC_ASN1EncodeItem(NULL,NULL,cert,serialTemplate);
     if (!serial) {
 	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");
+    }
+    
+    if ((trust->sslFlags | trust->emailFlags | trust->objectSigningFlags) 
+         == CERTDB_TERMINAL_RECORD)
+      trust_info = "Distrust";
+    else
+      trust_info = "Trust for";
+    
+    printf("\n# %s \"%s\"\n", trust_info, nickname);
+    print_info(sdder, cert);
 
-    printf("\n#\n# Certificate \"%s\"\n#\n",nickname);
-    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");
-
-    PK11_HashBuf(SEC_OID_SHA1, sha1_hash, sdder->data, sdder->len);
-    PK11_HashBuf(SEC_OID_MD5, md5_hash, sdder->data, sdder->len);
-    printf("\n# Trust for Certificate \"%s\"\n",nickname);
     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_CERT_SHA1_HASH MULTILINE_OCTAL\n");
-    dumpbytes(sha1_hash,SHA1_LENGTH);
-    printf("END\n");
-    printf("CKA_CERT_MD5_HASH MULTILINE_OCTAL\n");
-    dumpbytes(md5_hash,MD5_LENGTH);
-    printf("END\n");
+    
+    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");
+    }
 
     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_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");
     printf("CKA_TRUST_NON_REPUDIATION CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     printf("CKA_TRUST_KEY_ENCIPHERMENT CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     printf("CKA_TRUST_DATA_ENCIPHERMENT CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     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",
-                trust->sslFlags & CERTDB_GOVT_APPROVED_CA ? 
-                "CK_TRUE" : "CK_FALSE");
-
+                step_up ? "CK_TRUE" : "CK_FALSE");
 
     PORT_Free(sdder->data);
     return(rv);
 
 }
 
 void printheader() {
     printf("# \n"
@@ -210,17 +325,17 @@ void printheader() {
 "# use your version of this file under the terms of the MPL, indicate your\n"
 "# decision by deleting the provisions above and replace them with the notice\n"
 "# and other provisions required by the GPL or the LGPL. If you do not delete\n"
 "# the provisions above, a recipient may use your version of this file under\n"
 "# the terms of any one of the MPL, the GPL or the LGPL.\n"
 "#\n"
 "# ***** END LICENSE BLOCK *****\n"
      "#\n"
-     "CVS_ID \"@(#) $RCSfile: addbuiltin.c,v $ $Revision: 1.16 $ $Date: 2011/04/13 00:10:21 $\"\n"
+     "CVS_ID \"@(#) $RCSfile: addbuiltin.c,v $ $Revision: 1.17 $ $Date: 2012/03/10 12:10:44 $\"\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"
@@ -280,69 +395,127 @@ void printheader() {
      "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)
 {
-    fprintf(stderr, "%s -n nickname -t trust [-i certfile]\n", progName);
+    fprintf(stderr, "%s -t trust -n nickname [-i certfile] [-c] [-h]\n", progName);
     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"
-            "\t(pipe through atob if the cert is b64-encoded)\n", progName);
-    fprintf(stderr, "%-15s nickname to assign to builtin cert.\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, 
+            "\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");
+    fprintf(stderr, "%s -C -e crl-entry-number -n label [-i crlfile]\n", progName);
+    fprintf(stderr, 
+            "\tRead a CRL from crlfile or stdin, and output\n"
+            "\ta distrust record (issuer+serial).\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 trust flags (cCTpPuw).\n", "-t trust");
-    fprintf(stderr, "%-15s file to read (default stdin)\n", "-i certfile");
+    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");
+    fprintf(stderr, "%-15s     (useful to distrust any matching issuer/serial)\n", "");
+    fprintf(stderr, "%-15s     (not allowed when adding positive trust)\n", "");
+    fprintf(stderr, "%-15s a CRL entry number, as shown by \"crlutil -S\"\n", "-e");
+    fprintf(stderr, "%-15s input file to read (default stdin)\n", "-i file");
+    fprintf(stderr, "%-15s     (pipe through atob if the cert is b64-encoded)\n", "");
     exit(-1);
 }
 
 enum {
     opt_Input = 0,
     opt_Nickname,
-    opt_Trust
+    opt_Trust,
+    opt_Distrust,
+    opt_ExcludeCert,
+    opt_ExcludeHash,
+    opt_DistrustCRL,
+    opt_CRLEnry
 };
 
 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_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;
-    char *trusts;
+    char *nickname = NULL;
+    char *trusts = NULL;
     char *progName;
     PRFileDesc *infile;
     CERTCertTrust trust = { 0 };
-    SECItem derCert = { 0 };
+    SECItem derItem = { 0 };
+    PRInt32 crlentry = 0;
+    PRInt32 mutuallyExclusiveOpts = 0;
+    PRBool decodeTrust = PR_FALSE;
 
     secuCommand addbuiltin = { 0 };
     addbuiltin.numOptions = sizeof(addbuiltin_options)/sizeof(secuCommandFlag);
     addbuiltin.options = addbuiltin_options;
 
     progName = strrchr(argv[0], '/');
     progName = progName ? progName+1 : argv[0];
 
     rv = SECU_ParseCommandLine(argc, argv, progName, &addbuiltin);
 
     if (rv != SECSuccess)
 	Usage(progName);
+    
+    if (addbuiltin.options[opt_Trust].activated)
+      ++mutuallyExclusiveOpts;
+    if (addbuiltin.options[opt_Distrust].activated)
+      ++mutuallyExclusiveOpts;
+    if (addbuiltin.options[opt_DistrustCRL].activated)
+      ++mutuallyExclusiveOpts;
 
-    if (!addbuiltin.options[opt_Nickname].activated &&
-        !addbuiltin.options[opt_Trust].activated) {
-	fprintf(stderr, "%s: you must specify both a nickname and trust.\n",
-		progName);
-	Usage(progName);
+    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_Nickname].activated) {
+        fprintf(stderr, "%s: you must specify parameter -n (a nickname or a label).\n",
+                progName);
+        Usage(progName);
     }
 
     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);
 	}
@@ -360,34 +533,66 @@ int main(int argc, char **argv)
 	            progName);
 	    exit(1);
 	}
 #endif
 	infile = PR_STDIN;
     }
 
     nickname = strdup(addbuiltin.options[opt_Nickname].arg);
-    trusts = strdup(addbuiltin.options[opt_Trust].arg);
-
+    
     NSS_NoDB_Init(NULL);
 
-    rv = CERT_DecodeTrustString(&trust, trusts);
-    if (rv) {
-	fprintf(stderr, "%s: incorrectly formatted trust string.\n", progName);
-	Usage(progName);
+    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;
+    }
+    
+    if (addbuiltin.options[opt_Distrust].activated) {
+        trusts = strdup("p,p,p");
+	decodeTrust = PR_TRUE;
+    }
+    else if (addbuiltin.options[opt_Trust].activated) {
+        trusts = strdup(addbuiltin.options[opt_Trust].arg);
+	decodeTrust = PR_TRUE;
+    }
+    
+    if (decodeTrust) {
+	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);
+	}
     }
 
-    SECU_FileToItem(&derCert, infile);
+    SECU_FileToItem(&derItem, infile);
     
     /*printheader();*/
-
-    rv = ConvertCertificate(&derCert, nickname, &trust);
-    if (rv) {
-	fprintf(stderr, "%s: failed to convert certificate.\n", progName);
-	exit(1);
+    
+    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);
+	}
     }
     
     if (NSS_Shutdown() != SECSuccess) {
         exit(1);
     }
 
     return(SECSuccess);
 }
--- a/security/nss/cmd/certutil/certutil.c
+++ b/security/nss/cmd/certutil/certutil.c
@@ -1166,17 +1166,17 @@ static void luC(enum usage_level ul, con
     FPS "%-20s Create authority key ID extension\n",
         "   -3 ");
     FPS "%-20s Create crl distribution point extension\n",
         "   -4 ");
     FPS "%-20s \n"
               "%-20s Create netscape cert type extension. Possible keywords:\n"
               "%-20s \"sslClient\", \"sslServer\", \"smime\", \"objectSigning\",\n"
               "%-20s \"sslCA\", \"smimeCA\", \"objectSigningCA\", \"critical\".\n",
-        "   -5 | -nsCertType keyword,keyword,... ", "", "", "");
+        "   -5 | --nsCertType keyword,keyword,... ", "", "", "");
     FPS "%-20s \n"
               "%-20s Create extended key usage extension. Possible keywords:\n"
               "%-20s \"serverAuth\", \"clientAuth\",\"codeSigning\",\n"
               "%-20s \"emailProtection\", \"timeStamp\",\"ocspResponder\",\n"
               "%-20s \"stepUp\", \"critical\"\n",
         "   -6 | --extKeyUsage keyword,keyword,...", "", "", "", "");
     FPS "%-20s Create an email subject alt name extension\n",
         "   -7 emailAddrs");
--- a/security/nss/cmd/crlutil/crlutil.c
+++ b/security/nss/cmd/crlutil/crlutil.c
@@ -308,16 +308,47 @@ SECStatus ImportCRL (CERTCertDBHandle *c
     }
   loser:
     if (slot) {
         PK11_FreeSlot(slot);
     }
     return (rv);
 }
 
+SECStatus DumpCRL(PRFileDesc *inFile)
+{
+    int rv;
+    PRArenaPool *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);
+    if (rv != SECSuccess) {
+	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;
+
+    newCrl = CERT_DecodeDERCrlWithFlags(arena, &crlDER, SEC_CRL_TYPE,
+					CRL_DECODE_DEFAULT_OPTIONS);
+    if (!newCrl)
+    	return SECFailure;
+    
+    SECU_PrintCRLInfo (stdout, &newCrl->crl, "CRL file contents", 0);
+    
+    PORT_FreeArena (arena, PR_FALSE);
+    return rv;
+}
 
 static CERTCertificate*
 FindSigningCert(CERTCertDBHandle *certHandle, CERTSignedCrl *signCrl,
                 char *certNickName)
 {                   
     CERTCertificate *cert = NULL, *certTemp = NULL;
     SECStatus rv = SECFailure;
     CERTAuthKeyID* authorityKeyID = NULL;
@@ -751,24 +782,25 @@ GenerateCRL (CERTCertDBHandle *certHandl
     return (rv);
 }
 
 static void Usage(char *progName)
 {
     fprintf(stderr,
 	    "Usage:  %s -L [-n nickname] [-d keydir] [-P dbprefix] [-t crlType]\n"
 	    "        %s -D -n nickname [-d keydir] [-P dbprefix]\n"
+	    "        %s -S -i crl\n"
 	    "        %s -I -i crl -t crlType [-u url] [-d keydir] [-P dbprefix] [-B] "
             "[-p pwd-file] -w [pwd-string]\n"
 	    "        %s -E -t crlType [-d keydir] [-P dbprefix]\n"
 	    "        %s -T\n"
 	    "        %s -G|-M -c crl-init-file -n nickname [-i crl] [-u url] "
             "[-d keydir] [-P dbprefix] [-Z alg] ] [-p pwd-file] -w [pwd-string] "
             "[-a] [-B]\n",
-	    progName, progName, progName, progName, progName, progName);
+	    progName, progName, progName, progName, progName, progName, progName);
 
     fprintf (stderr, "%-15s List CRL\n", "-L");
     fprintf(stderr, "%-20s Specify the nickname of the CA certificate\n",
 	    "-n nickname");
     fprintf(stderr, "%-20s Key database directory (default is ~/.netscape)\n",
 	    "-d keydir");
     fprintf(stderr, "%-20s Cert & Key database prefix (default is \"\")\n",
 	    "-P dbprefix");
@@ -783,16 +815,20 @@ static void Usage(char *progName)
 	    "-P dbprefix");
 
     fprintf (stderr, "%-15s Erase all CRLs of specified type from hte cert database\n", "-E");
     fprintf(stderr, "%-20s Specify the crl type.\n", "-t crlType");
     fprintf(stderr, "%-20s Key database directory (default is ~/.netscape)\n",
 	    "-d keydir");
     fprintf(stderr, "%-20s Cert & Key database prefix (default is \"\")\n",
 	    "-P dbprefix");
+    
+    fprintf (stderr, "%-15s Show contents of a CRL file (without database)\n", "-S");
+    fprintf(stderr, "%-20s Specify the file which contains the CRL to show\n",
+	    "-i crl");
 
     fprintf (stderr, "%-15s Import a CRL to the cert database\n", "-I");    
     fprintf(stderr, "%-20s Specify the file which contains the CRL to import\n",
 	    "-i crl");
     fprintf(stderr, "%-20s Specify the url.\n", "-u url");
     fprintf(stderr, "%-20s Specify the crl type.\n", "-t crlType");
     fprintf(stderr, "%-20s Key database directory (default is ~/.netscape)\n",
 	    "-d keydir");
@@ -830,25 +866,24 @@ static void Usage(char *progName)
     fprintf(stderr, "%-20s Specify the url.\n", "-u url");
     fprintf(stderr, "\n%-20s Bypass CA certificate checks.\n", "-B");
 
     exit(-1);
 }
 
 int main(int argc, char **argv)
 {
-    SECItem privKeyDER;
     CERTCertDBHandle *certHandle;
-    FILE *certFile;
     PRFileDesc *inFile;
     PRFileDesc *inCrlInitFile = NULL;
     int generateCRL;
     int modifyCRL;
     int listCRL;
     int importCRL;
+    int showFileCRL;
     int deleteCRL;
     int rv;
     char *nickName;
     char *url;
     char *dbPrefix = "";
     char *alg = NULL;
     char *outFile = NULL;
     char *slotName = NULL;
@@ -867,27 +902,25 @@ int main(int argc, char **argv)
     PRBool readonly = PR_FALSE;
 
     secuPWData  pwdata          = { PW_NONE, 0 };
 
     progName = strrchr(argv[0], '/');
     progName = progName ? progName+1 : argv[0];
 
     rv = 0;
-    deleteCRL = importCRL = listCRL = generateCRL = modifyCRL = 0;
-    certFile = NULL;
+    deleteCRL = importCRL = listCRL = generateCRL = modifyCRL = showFileCRL = 0;
     inFile = NULL;
     nickName = url = NULL;
-    privKeyDER.data = NULL;
     certHandle = NULL;
     crlType = SEC_CRL_TYPE;
     /*
      * Parse command line arguments
      */
-    optstate = PL_CreateOptState(argc, argv, "sqBCDGILMTEP:f:d:i:h:n:p:t:u:r:aZ:o:c:");
+    optstate = PL_CreateOptState(argc, argv, "sqBCDGILMSTEP:f:d:i:h:n:p:t:u:r:aZ:o:c:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	  case '?':
 	    Usage(progName);
 	    break;
 
           case 'T':
             test = PR_TRUE;
@@ -911,16 +944,20 @@ int main(int argc, char **argv)
 
 	  case 'D':
 	      deleteCRL = 1;
 	      break;
 
 	  case 'I':
 	      importCRL = 1;
 	      break;
+	      
+	  case 'S':
+	      showFileCRL = 1;
+	      break;
 	           
 	  case 'C':
 	  case 'L':
 	      listCRL = 1;
 	      break;
 
 	  case 'P':
  	    dbPrefix = strdup(optstate->value);
@@ -982,20 +1019,17 @@ int main(int argc, char **argv)
 	  case 'r': {
 	    const char* str = optstate->value;
 	    if (str && atoi(str)>0)
 		iterations = atoi(str);
 	    }
 	    break;
 	    
 	  case 't': {
-	    char *type;
-	    
-	    type = strdup(optstate->value);
-	    crlType = atoi (type);
+	    crlType = atoi(optstate->value);
 	    if (crlType != SEC_CRL_TYPE && crlType != SEC_KRL_TYPE) {
 		PR_fprintf(PR_STDERR, "%s: invalid crl type\n", progName);
 		PL_DestroyOptState(optstate);
 		return -1;
 	    }
 	    break;
 
 	  case 'q':
@@ -1013,35 +1047,42 @@ int main(int argc, char **argv)
 
           }
 	}
     }
     PL_DestroyOptState(optstate);
 
     if (deleteCRL && !nickName) Usage (progName);
     if (importCRL && !inFile) Usage (progName);
+    if (showFileCRL && !inFile) Usage (progName);
     if ((generateCRL && !nickName) ||
         (modifyCRL && !inFile && !nickName)) Usage (progName);
-    if (!(listCRL || deleteCRL || importCRL || generateCRL ||
+    if (!(listCRL || deleteCRL || importCRL || showFileCRL || generateCRL ||
 	  modifyCRL || test || erase)) Usage (progName);
 
-    if (listCRL) {
+    if (listCRL || showFileCRL) {
         readonly = PR_TRUE;
     }
     
     PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
 
     PK11_SetPasswordFunc(SECU_GetModulePassword);
 
-    secstatus = NSS_Initialize(SECU_ConfigDirectory(NULL), dbPrefix, dbPrefix,
-			       "secmod.db", readonly ? NSS_INIT_READONLY : 0);
-    if (secstatus != SECSuccess) {
-	SECU_PrintPRandOSError(progName);
-	return -1;
+    if (showFileCRL) {
+	NSS_NoDB_Init(NULL);
     }
+    else {
+	secstatus = NSS_Initialize(SECU_ConfigDirectory(NULL), dbPrefix, dbPrefix,
+				"secmod.db", readonly ? NSS_INIT_READONLY : 0);
+	if (secstatus != SECSuccess) {
+	    SECU_PrintPRandOSError(progName);
+	    return -1;
+	}
+    }
+    
     SECU_RegisterDynamicOids();
 
     certHandle = CERT_GetDefaultCertDB();
     if (certHandle == NULL) {
 	SECU_PrintError(progName, "unable to open the cert db");	    	
 	/*ignoring return value of NSS_Shutdown() as code returns -1*/
 	(void) NSS_Shutdown();
 	return (-1);
@@ -1054,16 +1095,19 @@ int main(int argc, char **argv)
 	if (deleteCRL) 
 	    DeleteCRL (certHandle, nickName, crlType);
 	else if (listCRL) {
 	    rv = ListCRL (certHandle, nickName, crlType);
 	}
 	else if (importCRL) {
 	    rv = ImportCRL (certHandle, url, crlType, inFile, importOptions,
 			    decodeOptions, &pwdata);
+	}
+	else if (showFileCRL) {
+	    rv = DumpCRL (inFile);
 	} else if (generateCRL || modifyCRL) {
 	    if (!inCrlInitFile)
 		inCrlInitFile = PR_STDIN;
 	    rv = GenerateCRL (certHandle, nickName, inCrlInitFile,
 			      inFile, outFile, ascii,  slotName,
 			      importOptions, alg, quiet,
 			      decodeOptions, url, &pwdata,
 			      modifyCRL);
--- a/security/nss/cmd/lib/secutil.c
+++ b/security/nss/cmd/lib/secutil.c
@@ -81,16 +81,29 @@ static char consoleName[] =  {
     "CON:"
 #endif
 #endif
 };
 
 #include "nssutil.h"
 #include "ssl.h"
 
+static PRBool wrapEnabled = PR_TRUE;
+
+void
+SECU_EnableWrap(PRBool enable)
+{
+    wrapEnabled = enable;
+}
+
+PRBool
+SECU_GetWrapEnabled()
+{
+    return wrapEnabled;
+}
 
 void 
 SECU_PrintErrMsg(FILE *out, int level, char *progName, char *msg, ...)
 {
     va_list args;
     PRErrorCode err = PORT_GetError();
     const char * errString = SECU_Strerror(err);
 
@@ -784,21 +797,25 @@ SECU_PrintAsHex(FILE *out, SECItem *data
     unsigned i;
     int column;
     PRBool isString     = PR_TRUE;
     PRBool isWhiteSpace = PR_TRUE;
     PRBool printedHex   = PR_FALSE;
     unsigned int limit = 15;
 
     if ( m ) {
-	SECU_Indent(out, level); fprintf(out, "%s:\n", m);
+	SECU_Indent(out, level); fprintf(out, "%s:", m);
 	level++;
+	if (wrapEnabled)
+	    fprintf(out, "\n");
     }
-    
-    SECU_Indent(out, level); column = level*INDENT_MULT;
+
+    if (wrapEnabled) {
+	SECU_Indent(out, level); column = level*INDENT_MULT;
+    }
     if (!data->len) {
 	fprintf(out, "(empty)\n");
 	return;
     }
     /* take a pass to see if it's all printable. */
     for (i = 0; i < data->len; i++) {
 	unsigned char val = data->data[i];
         if (!val || !isprint(val)) {
@@ -821,17 +838,18 @@ SECU_PrintAsHex(FILE *out, SECItem *data
 	if (i != data->len - 1) {
 	    fprintf(out, "%02x:", data->data[i]);
 	    column += 3;
 	} else {
 	    fprintf(out, "%02x", data->data[i]);
 	    column += 2;
 	    break;
 	}
-	if (column > 76 || (i % 16 == limit)) {
+	if (wrapEnabled &&
+	    (column > 76 || (i % 16 == limit))) {
 	    secu_Newline(out);
 	    SECU_Indent(out, level); 
 	    column = level*INDENT_MULT;
 	    limit = i % 16;
 	}
       }
       printedHex = PR_TRUE;
     }
@@ -844,17 +862,17 @@ SECU_PrintAsHex(FILE *out, SECItem *data
 	    unsigned char val = data->data[i];
 
 	    if (val) {
 		fprintf(out,"%c",val);
 		column++;
 	    } else {
 		column = 77;
 	    }
-	    if (column > 76) {
+	    if (wrapEnabled && column > 76) {
 		secu_Newline(out);
         	SECU_Indent(out, level); column = level*INDENT_MULT;
 	    }
 	}
     }
 	    
     if (column != level*INDENT_MULT) {
 	secu_Newline(out);
@@ -970,47 +988,59 @@ SECU_PrintInteger(FILE *out, SECItem *i,
 	    fprintf(out, "%s: %d (0x%x)\n", m, iv, iv);
 	} else {
 	    fprintf(out, "%d (0x%x)\n", iv, iv);
 	}
     }
 }
 
 static void
-secu_PrintRawString(FILE *out, SECItem *si, const char *m, int level)
+secu_PrintRawStringQuotesOptional(FILE *out, SECItem *si, const char *m, 
+				  int level, PRBool quotes)
 {
     int column;
     unsigned int i;
 
     if ( m ) {
 	SECU_Indent(out, level); fprintf(out, "%s: ", m);
 	column = (level * INDENT_MULT) + strlen(m) + 2;
 	level++;
     } else {
 	SECU_Indent(out, level); 
 	column = level*INDENT_MULT;
     }
-    fprintf(out, "\""); column++;
+    if (quotes) {
+	fprintf(out, "\""); column++;
+    }
 
     for (i = 0; i < si->len; i++) {
 	unsigned char val = si->data[i];
-	if (column > 76) {
+	if (wrapEnabled && column > 76) {
 	    secu_Newline(out);
 	    SECU_Indent(out, level); column = level*INDENT_MULT;
 	}
 
 	fprintf(out,"%c", printable[val]); column++;
     }
 
-    fprintf(out, "\""); column++;
-    if (column != level*INDENT_MULT || column > 76) {
+    if (quotes) {
+	fprintf(out, "\""); column++;
+    }
+    if (wrapEnabled &&
+        (column != level*INDENT_MULT || column > 76)) {
 	secu_Newline(out);
     }
 }
 
+static void
+secu_PrintRawString(FILE *out, SECItem *si, const char *m, int level)
+{
+    secu_PrintRawStringQuotesOptional(out, si, m, level, PR_TRUE);
+}
+
 void
 SECU_PrintString(FILE *out, SECItem *si, char *m, int level)
 {
     SECItem my = *si;
 
     if (SECSuccess != SECU_StripTagAndLength(&my) || !my.len)
     	return;
     secu_PrintRawString(out, &my, m, level);
@@ -2404,17 +2434,18 @@ SECU_PrintRDN(FILE *out, CERTRDN *rdn, c
     name.arena = NULL;
     name.rdns  = rdns;
     rdns[0] = rdn;
     rdns[1] = NULL;
     SECU_PrintName(out, &name, msg, level);
 }
 
 void
-SECU_PrintName(FILE *out, CERTName *name, const char *msg, int level)
+SECU_PrintNameQuotesOptional(FILE *out, CERTName *name, const char *msg, 
+			     int level, PRBool quotes)
 {
     char *nameStr = NULL;
     char *str;
     SECItem my;
 
     if (!name) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return;
@@ -2425,26 +2456,32 @@ SECU_PrintName(FILE *out, CERTName *name
 	str = nameStr = CERT_NameToAscii(name);
     }
     if (!str) {
     	str = "!Invalid AVA!";
     }
     my.data = (unsigned char *)str;
     my.len  = PORT_Strlen(str);
 #if 1
-    secu_PrintRawString(out, &my, msg, level);
+    secu_PrintRawStringQuotesOptional(out, &my, msg, level, quotes);
 #else
     SECU_Indent(out, level); fprintf(out, "%s: ", msg);
     fprintf(out, str);
     secu_Newline(out);
 #endif
     PORT_Free(nameStr);
 }
 
 void
+SECU_PrintName(FILE *out, CERTName *name, const char *msg, int level)
+{
+    SECU_PrintNameQuotesOptional(out, name, msg, level, PR_TRUE);
+}
+
+void
 printflags(char *trusts, unsigned int flags)
 {
     if (flags & CERTDB_VALID_CA)
 	if (!(flags & CERTDB_TRUSTED_CA) &&
 	    !(flags & CERTDB_TRUSTED_CLIENT_CA))
 	    PORT_Strcat(trusts, "c");
     if (flags & CERTDB_TERMINAL_RECORD)
 	if (!(flags & CERTDB_TRUSTED))
@@ -2748,33 +2785,48 @@ SECU_PrintFingerprints(FILE *out, SECIte
     SECItem fpItem;
 
     /* print MD5 fingerprint */
     memset(fingerprint, 0, sizeof fingerprint);
     rv = PK11_HashBuf(SEC_OID_MD5,fingerprint, derCert->data, derCert->len);
     fpItem.data = fingerprint;
     fpItem.len = MD5_LENGTH;
     fpStr = CERT_Hexify(&fpItem, 1);
-    SECU_Indent(out, level);  fprintf(out, "%s (MD5):\n", m);
-    SECU_Indent(out, level+1); fprintf(out, "%s\n", fpStr);
+    SECU_Indent(out, level);  fprintf(out, "%s (MD5):", m);
+    if (wrapEnabled) {
+	fprintf(out, "\n");
+	SECU_Indent(out, level+1);
+    }
+    else {
+	fprintf(out, " ");
+    }
+    fprintf(out, "%s\n", fpStr);
     PORT_Free(fpStr);
     fpStr = NULL;
     if (rv != SECSuccess && !err)
 	err = PORT_GetError();
 
     /* print SHA1 fingerprint */
     memset(fingerprint, 0, sizeof fingerprint);
     rv = PK11_HashBuf(SEC_OID_SHA1,fingerprint, derCert->data, derCert->len);
     fpItem.data = fingerprint;
     fpItem.len = SHA1_LENGTH;
     fpStr = CERT_Hexify(&fpItem, 1);
-    SECU_Indent(out, level);  fprintf(out, "%s (SHA1):\n", m);
-    SECU_Indent(out, level+1); fprintf(out, "%s\n", fpStr);
+    SECU_Indent(out, level);  fprintf(out, "%s (SHA1):", m);
+    if (wrapEnabled) {
+	fprintf(out, "\n");
+	SECU_Indent(out, level+1);
+    }
+    else {
+	fprintf(out, " ");
+    }
+    fprintf(out, "%s\n", fpStr);
     PORT_Free(fpStr);
-    fprintf(out, "\n");
+    if (wrapEnabled)
+	fprintf(out, "\n");
 
     if (err) 
 	PORT_SetError(err);
     if (err || rv != SECSuccess)
 	return SECFailure;
 
     return 0;
 }
@@ -2902,17 +2954,17 @@ SECU_PrintCRLInfo(FILE *out, CERTCrl *cr
     SECU_PrintName(out, &(crl->name), "Issuer", level + 1);
     SECU_PrintTimeChoice(out, &(crl->lastUpdate), "This Update", level + 1);
     if (crl->nextUpdate.data && crl->nextUpdate.len) /* is optional */
 	SECU_PrintTimeChoice(out, &(crl->nextUpdate), "Next Update", level + 1);
     
     if (crl->entries != NULL) {
 	iv = 0;
 	while ((entry = crl->entries[iv++]) != NULL) {
-	    sprintf(om, "Entry (%x):\n", iv); 
+	    sprintf(om, "Entry %d (0x%x):\n", iv, iv); 
 	    SECU_Indent(out, level + 1); fputs(om, out);
 	    SECU_PrintInteger(out, &(entry->serialNumber), "Serial Number",
 			      level + 2);
 	    SECU_PrintTimeChoice(out, &(entry->revocationDate), 
 	                         "Revocation Date", level + 2);
 	    SECU_PrintExtensions(out, entry->extensions, 
 	                         "Entry Extensions", level + 2);
 	}
--- a/security/nss/cmd/lib/secutil.h
+++ b/security/nss/cmd/lib/secutil.h
@@ -163,16 +163,19 @@ extern char *SECU_ConfigDirectory(const 
 ** Basic callback function for SSL_GetClientAuthDataHook
 */
 extern int
 SECU_GetClientAuthData(void *arg, PRFileDesc *fd,
 		       struct CERTDistNamesStr *caNames,
 		       struct CERTCertificateStr **pRetCert,
 		       struct SECKEYPrivateKeyStr **pRetKey);
 
+extern PRBool SECU_GetWrapEnabled();
+extern void SECU_EnableWrap(PRBool enable);
+
 /* print out an error message */
 extern void SECU_PrintError(char *progName, char *msg, ...);
 
 /* print out a system error message */
 extern void SECU_PrintSystemError(char *progName, char *msg, ...);
 
 /* revalidate the cert and print information about cert verification
  * failure at time == now */
@@ -308,16 +311,19 @@ extern void SECU_PrintAny(FILE *out, SEC
 
 extern void SECU_PrintPolicy(FILE *out, SECItem *value, char *msg, int level);
 extern void SECU_PrintPrivKeyUsagePeriodExtension(FILE *out, SECItem *value,
                                  char *msg, int level);
 
 extern void SECU_PrintExtensions(FILE *out, CERTCertExtension **extensions,
 				 char *msg, int level);
 
+extern void SECU_PrintNameQuotesOptional(FILE *out, CERTName *name, 
+					 const char *msg, int level, 
+					 PRBool quotes);
 extern void SECU_PrintName(FILE *out, CERTName *name, const char *msg,
                            int level);
 extern void SECU_PrintRDN(FILE *out, CERTRDN *rdn, const char *msg, int level);
 
 #ifdef SECU_GetPassword
 /* Convert a High public Key to a Low public Key */
 extern SECKEYLowPublicKey *SECU_ConvHighToLow(SECKEYPublicKey *pubHighKey);
 #endif
--- a/security/nss/cmd/selfserv/selfserv.c
+++ b/security/nss/cmd/selfserv/selfserv.c
@@ -798,16 +798,18 @@ PRBool hasSidCache     = PR_FALSE;
 PRBool disableStepDown = PR_FALSE;
 PRBool bypassPKCS11    = PR_FALSE;
 PRBool disableLocking  = PR_FALSE;
 PRBool testbypass      = PR_FALSE;
 PRBool enableSessionTickets = PR_FALSE;
 PRBool enableCompression    = PR_FALSE;
 PRBool failedToNegotiateName  = PR_FALSE;
 static char  *virtServerNameArray[MAX_VIRT_SERVER_NAME_ARRAY_INDEX];
+static int                  virtServerNameIndex = 1;
+
 
 static const char stopCmd[] = { "GET /stop " };
 static const char getCmd[]  = { "GET " };
 static const char EOFmsg[]  = { "EOF\r\n\r\n\r\n" };
 static const char outHeader[] = {
     "HTTP/1.0 200 OK\r\n"
     "Server: Generic Web Server\r\n"
     "Date: Tue, 26 Aug 1997 22:10:05 GMT\r\n"
@@ -1701,20 +1703,22 @@ server_main(
 
     if (enableCompression) {
 	rv = SSL_OptionSet(model_sock, SSL_ENABLE_DEFLATE, PR_TRUE);
 	if (rv != SECSuccess) {
 	    errExit("error enabling compression ");
 	}
     }
 
-    rv = SSL_SNISocketConfigHook(model_sock, mySSLSNISocketConfig,
-                                 (void*)&virtServerNameArray);
-    if (rv != SECSuccess) {
-        errExit("error enabling SNI extension ");
+    if (virtServerNameIndex >1) {
+        rv = SSL_SNISocketConfigHook(model_sock, mySSLSNISocketConfig,
+                                     (void*)&virtServerNameArray);
+        if (rv != SECSuccess) {
+            errExit("error enabling SNI extension ");
+        }
     }
 
     for (kea = kt_rsa; kea < kt_kea_size; kea++) {
 	if (cert[kea] != NULL) {
 	    secStatus = SSL_ConfigSecureServer(model_sock, 
 	    		cert[kea], privKey[kea], kea);
 	    if (secStatus != SECSuccess)
 		errExit("SSL_ConfigSecureServer");
@@ -1930,17 +1934,16 @@ main(int argc, char **argv)
     PRThread             *loggerThread = NULL;
     PRBool               debugCache = PR_FALSE; /* bug 90518 */
     char                 emptyString[] = { "" };
     char*                certPrefix = emptyString;
     PRUint32             protos = 0;
     SSL3Statistics      *ssl3stats;
     PRUint32             i;
     secuPWData  pwdata = { PW_NONE, 0 };
-    int                  virtServerNameIndex = 1;
     char                *expectedHostNameVal = NULL;
 
     tmp = strrchr(argv[0], '/');
     tmp = tmp ? tmp + 1 : argv[0];
     progName = strrchr(tmp, '\\');
     progName = progName ? progName + 1 : tmp;
 
     PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
--- a/security/nss/cmd/symkeyutil/symkeyutil.c
+++ b/security/nss/cmd/symkeyutil/symkeyutil.c
@@ -745,17 +745,17 @@ main(int argc, char **argv)
 	          "%s Couldn't read key ID file (%s).\n",
 	           progName, symKeyUtil.options[opt_WrapKeyIDFile].arg);
 	    return 255;
 	}
     }
 
     /*  -P certdb name prefix */
     if (symKeyUtil.options[opt_dbPrefix].activated)
-	certPrefix = strdup(symKeyUtil.options[opt_dbPrefix].arg);
+	certPrefix = symKeyUtil.options[opt_dbPrefix].arg;
 
     /*  Check number of commands entered.  */
     commandsEntered = 0;
     for (i=0; i< symKeyUtil.numCommands; i++) {
 	if (symKeyUtil.commands[i].activated) {
 	    commandToRun = symKeyUtil.commands[i].flag;
 	    commandsEntered++;
 	}
--- a/security/nss/lib/certdb/certdb.c
+++ b/security/nss/lib/certdb/certdb.c
@@ -34,17 +34,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Certificate handling code
  *
- * $Id: certdb.c,v 1.120 2011/11/17 00:20:20 bsmith%mozilla.com Exp $
+ * $Id: certdb.c,v 1.121.2.1 2012/04/03 00:38:19 wtc%google.com Exp $
  */
 
 #include "nssilock.h"
 #include "prmon.h"
 #include "prtime.h"
 #include "cert.h"
 #include "certi.h"
 #include "secder.h"
@@ -591,16 +591,30 @@ cert_ComputeCertType(CERTCertificate *ce
 	    SECSuccess){
 	    if (basicConstraintPresent == PR_TRUE &&
 		(basicConstraint.isCA)) {
 		nsCertType |= NS_CERT_TYPE_SSL_CA;
 	    } else {
 		nsCertType |= NS_CERT_TYPE_SSL_SERVER;
 	    }
 	}
+	/*
+	 * Treat certs with step-up OID as also having SSL server type.
+ 	 * COMODO needs this behaviour until June 2020.  See Bug 737802.
+	 */
+	if (findOIDinOIDSeqByTagNum(extKeyUsage, 
+				    SEC_OID_NS_KEY_USAGE_GOVT_APPROVED) ==
+	    SECSuccess){
+	    if (basicConstraintPresent == PR_TRUE &&
+		(basicConstraint.isCA)) {
+		nsCertType |= NS_CERT_TYPE_SSL_CA;
+	    } else {
+		nsCertType |= NS_CERT_TYPE_SSL_SERVER;
+	    }
+	}
 	if (findOIDinOIDSeqByTagNum(extKeyUsage,
 				    SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH) ==
 	    SECSuccess){
 	    if (basicConstraintPresent == PR_TRUE &&
 		(basicConstraint.isCA)) {
 		nsCertType |= NS_CERT_TYPE_SSL_CA;
 	    } else {
 		nsCertType |= NS_CERT_TYPE_SSL_CLIENT;
@@ -2936,16 +2950,17 @@ cert_InitLocks(void)
         }
     }
 
     if ( certTrustLock == NULL ) {
         certTrustLock = PZ_NewLock(nssILockCertDB);
         PORT_Assert(certTrustLock != NULL);
         if (!certTrustLock) {
             PZ_DestroyLock(certRefCountLock);
+            certRefCountLock = NULL;
             return SECFailure;
         }
     }    
 
     return SECSuccess;
 }
 
 SECStatus
--- a/security/nss/lib/certdb/stanpcertdb.c
+++ b/security/nss/lib/certdb/stanpcertdb.c
@@ -626,17 +626,17 @@ CERT_FindCertByDERCert(CERTCertDBHandle 
 	                                                       &encoding);
 	if (!c) return NULL;
     }
     return STAN_GetCERTCertificateOrRelease(c);
 }
 
 static CERTCertificate *
 common_FindCertByNicknameOrEmailAddrForUsage(CERTCertDBHandle *handle, 
-                                             char *name,
+                                             const char *name,
                                              PRBool anyUsage,
                                              SECCertUsage lookingForUsage)
 {
     NSSCryptoContext *cc;
     NSSCertificate *c, *ct;
     CERTCertificate *cert = NULL;
     NSSUsage usage;
     CERTCertList *certlist;
--- a/security/nss/lib/certhigh/certvfypkix.c
+++ b/security/nss/lib/certhigh/certvfypkix.c
@@ -1421,18 +1421,18 @@ cleanup:
 
 struct fake_PKIX_PL_CertStruct {
         CERTCertificate *nssCert;
 };
 
 /* This needs to be part of the PKIX_PL_* */
 /* This definitely needs to go away, and be replaced with
    a real accessor function in PKIX */
-CERTCertificate *
-cert_NSSCertFromPKIXCert(const PKIX_PL_Cert *pkix_cert, void *plContext)
+static CERTCertificate *
+cert_NSSCertFromPKIXCert(const PKIX_PL_Cert *pkix_cert)
 {
     struct fake_PKIX_PL_CertStruct *fcert = NULL;
 
     fcert = (struct fake_PKIX_PL_CertStruct*)pkix_cert;
 
     return CERT_DupCertificate(fcert->nssCert);
 }
 
@@ -2212,32 +2212,38 @@ do {
     }
 
     error = PKIX_ValidateResult_GetTrustAnchor( valResult, &trustAnchor,
                                                 plContext);
     if (error != NULL) {
         goto cleanup;
     }
 
-    error = PKIX_TrustAnchor_GetTrustedCert( trustAnchor, &trustAnchorCert,
-                                                plContext);
-    if (error != NULL) {
-        goto cleanup;
+    if (trustAnchor != NULL) {
+        error = PKIX_TrustAnchor_GetTrustedCert( trustAnchor, &trustAnchorCert,
+                                                 plContext);
+        if (error != NULL) {
+            goto cleanup;
+        }
     }
 
 #ifdef PKIX_OBJECT_LEAK_TEST
     /* Can not continue if error was generated but not returned.
      * Jumping to cleanup. */
     if (errorGenerated) goto cleanup;
 #endif /* PKIX_OBJECT_LEAK_TEST */
 
     oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_trustAnchor);
     if (oparam != NULL) {
-        oparam->value.pointer.cert = 
-                cert_NSSCertFromPKIXCert(trustAnchorCert,plContext);
+        if (trustAnchorCert != NULL) {
+            oparam->value.pointer.cert =
+                    cert_NSSCertFromPKIXCert(trustAnchorCert);
+        } else {
+            oparam->value.pointer.cert = NULL;
+        }
     }
 
     error = PKIX_BuildResult_GetCertChain( buildResult, &builtCertList,
                                                 plContext);
     if (error != NULL) {
         goto cleanup;
     }
 
--- a/security/nss/lib/certhigh/ocsp.c
+++ b/security/nss/lib/certhigh/ocsp.c
@@ -34,17 +34,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Implementation of OCSP services, for both client and server.
  * (XXX, really, mostly just for client right now, but intended to do both.)
  *
- * $Id: ocsp.c,v 1.67 2011/08/10 12:31:52 kaie%kuix.de Exp $
+ * $Id: ocsp.c,v 1.69 2012/03/14 22:26:53 wtc%google.com Exp $
  */
 
 #include "prerror.h"
 #include "prprf.h"
 #include "plarena.h"
 #include "prnetdb.h"
 
 #include "seccomon.h"
@@ -291,17 +291,17 @@ dumpCertID(CERTOCSPCertID *certID)
     printHexString("OCSP certID serial", &certID->serialNumber);
 }
 #endif
 
 SECStatus
 SEC_RegisterDefaultHttpClient(const SEC_HttpClientFcn *fcnTable)
 {
     if (!OCSP_Global.monitor) {
-      PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+      PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
       return SECFailure;
     }
     
     PR_EnterMonitor(OCSP_Global.monitor);
     OCSP_Global.defaultHttpClientFcn = fcnTable;
     PR_ExitMonitor(OCSP_Global.monitor);
     
     return SECSuccess;
@@ -310,17 +310,17 @@ SEC_RegisterDefaultHttpClient(const SEC_
 SECStatus
 CERT_RegisterAlternateOCSPAIAInfoCallBack(
 			CERT_StringFromCertFcn   newCallback,
 			CERT_StringFromCertFcn * oldCallback)
 {
     CERT_StringFromCertFcn old;
 
     if (!OCSP_Global.monitor) {
-      PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+      PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
       return SECFailure;
     }
 
     PR_EnterMonitor(OCSP_Global.monitor);
     old = OCSP_Global.alternateOCSPAIAFcn;
     OCSP_Global.alternateOCSPAIAFcn = newCallback;
     PR_ExitMonitor(OCSP_Global.monitor);
     if (oldCallback)
@@ -986,17 +986,17 @@ SECStatus OCSP_ShutdownGlobal(void)
  * A return value of NULL means: 
  *   The application did not register it's own HTTP client.
  */
 const SEC_HttpClientFcn *SEC_GetRegisteredHttpClient()
 {
     const SEC_HttpClientFcn *retval;
 
     if (!OCSP_Global.monitor) {
-      PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+      PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
       return NULL;
     }
 
     PR_EnterMonitor(OCSP_Global.monitor);
     retval = OCSP_Global.defaultHttpClientFcn;
     PR_ExitMonitor(OCSP_Global.monitor);
     
     return retval;
@@ -2695,20 +2695,20 @@ ocspSignature *
 ocsp_GetResponseSignature(CERTOCSPResponse *response)
 {
     ocspBasicOCSPResponse *basic;
 
     PORT_Assert(response != NULL);
     if (NULL == response->responseBytes) {
         return NULL;
     }
-    PORT_Assert(response->responseBytes != NULL);
-    PORT_Assert(response->responseBytes->responseTypeTag
-		== SEC_OID_PKIX_OCSP_BASIC_RESPONSE);
-
+    if (response->responseBytes->responseTypeTag
+        != SEC_OID_PKIX_OCSP_BASIC_RESPONSE) {
+        return NULL;
+    }
     basic = response->responseBytes->decodedResponse.basic;
     PORT_Assert(basic != NULL);
 
     return &(basic->responseSignature);
 }
 
 
 /*
--- a/security/nss/lib/cryptohi/secvfy.c
+++ b/security/nss/lib/cryptohi/secvfy.c
@@ -32,17 +32,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: secvfy.c,v 1.25 2011/10/22 14:35:42 wtc%google.com Exp $ */
+/* $Id: secvfy.c,v 1.28 2012/02/25 14:32:45 kaie%kuix.de Exp $ */
 
 #include <stdio.h>
 #include "cryptohi.h"
 #include "sechash.h"
 #include "keyhi.h"
 #include "secasn1.h"
 #include "secoid.h"
 #include "pk11func.h"
@@ -295,21 +295,23 @@ sec_DecodeSigAlg(const SECKEYPublicKey *
 	    PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
 	    return SECFailure;
 	}
 	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
 	if (arena == NULL) {
 	    return SECFailure;
 	}
 	rv = SEC_QuickDERDecodeItem(arena, &oid, hashParameterTemplate, param);
-	if (rv != SECSuccess) {
-	    PORT_FreeArena(arena, PR_FALSE);
+	if (rv == SECSuccess) {
+            *hashalg = SECOID_FindOIDTag(&oid);
+        }
+        PORT_FreeArena(arena, PR_FALSE);
+        if (rv != SECSuccess) {
 	    return rv;
 	}
-	*hashalg = SECOID_FindOIDTag(&oid);
 	/* only accept hash algorithms */
 	if (HASH_GetHashTypeByOidTag(*hashalg) == HASH_AlgNULL) {
 	    /* error set by HASH_GetHashTypeByOidTag */
 	    return SECFailure;
 	}
 	break;
       /* we don't implement MD4 hashes */
       case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION:
--- a/security/nss/lib/freebl/blapi.h
+++ b/security/nss/lib/freebl/blapi.h
@@ -32,17 +32,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: blapi.h,v 1.43 2011/10/29 23:28:45 wtc%google.com Exp $ */
+/* $Id: blapi.h,v 1.45 2012/03/28 22:38:27 rrelyea%redhat.com Exp $ */
 
 #ifndef _BLAPI_H_
 #define _BLAPI_H_
 
 #include "blapit.h"
 #include "hasht.h"
 #include "alghmac.h"
 
@@ -207,26 +207,31 @@ extern SECStatus DH_NewKey(DHParams *   
 /* 
 ** DH_Derive does the Diffie-Hellman phase 2 calculation, using the 
 ** other party's publicValue, and the prime and our privateValue.
 ** maxOutBytes is the requested length of the generated secret in bytes.  
 ** A zero value means produce a value of any length up to the size of 
 ** the prime.   If successful, derivedSecret->data is set 
 ** to the address of the newly allocated buffer containing the derived 
 ** secret, and derivedSecret->len is the size of the secret produced.
-** The size of the secret produced will never be larger than the length
-** of the prime, and it may be smaller than maxOutBytes.
+** The size of the secret produced will depend on the value of outBytes.
+** If outBytes is 0, the key length will be all the significant bytes of
+** the derived secret (leading zeros are dropped). This length could be less
+** than the length of the prime. If outBytes is nonzero, the length of the
+** produced key will be outBytes long. If the key is truncated, the most
+** significant bytes are truncated. If it is expanded, zero bytes are added
+** at the beginning.
 ** It is the caller's responsibility to free the allocated buffer 
 ** containing the derived secret.
 */
 extern SECStatus DH_Derive(SECItem *    publicValue, 
 		           SECItem *    prime, 
 			   SECItem *    privateValue, 
 			   SECItem *    derivedSecret,
-			   unsigned int maxOutBytes);
+			   unsigned int outBytes);
 
 /* 
 ** KEA_CalcKey returns octet string with the private key for a dual
 ** Diffie-Helman  key generation as specified for government key exchange.
 */
 extern SECStatus KEA_Derive(SECItem *prime, 
                             SECItem *public1, 
                             SECItem *public2, 
--- a/security/nss/lib/freebl/blapit.h
+++ b/security/nss/lib/freebl/blapit.h
@@ -33,17 +33,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: blapit.h,v 1.25 2012/01/13 16:53:15 emaldona%redhat.com Exp $ */
+/* $Id: blapit.h,v 1.26 2012/03/28 22:35:14 rrelyea%redhat.com Exp $ */
 
 #ifndef _BLAPIT_H_
 #define _BLAPIT_H_
 
 #include "seccomon.h"
 #include "prlink.h"
 #include "plarena.h"
 #include "ecl-exp.h"
@@ -137,17 +137,17 @@
 /*
  * These values come from the initial key size limits from the PKCS #11
  * module. They may be arbitrarily adjusted to any value freebl supports.
  */
 #define RSA_MIN_MODULUS_BITS   128
 #define RSA_MAX_MODULUS_BITS  8192
 #define RSA_MAX_EXPONENT_BITS   64
 #define DH_MIN_P_BITS	       128
-#define DH_MAX_P_BITS         2236
+#define DH_MAX_P_BITS         3072
 
 /*
  * The FIPS 186 algorithm for generating primes P and Q allows only 9
  * distinct values for the length of P, and only one value for the
  * length of Q.
  * The algorithm uses a variable j to indicate which of the 9 lengths
  * of P is to be used.
  * The following table relates j to the lengths of P and Q in bits.
--- a/security/nss/lib/freebl/dh.c
+++ b/security/nss/lib/freebl/dh.c
@@ -33,17 +33,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Diffie-Hellman parameter generation, key generation, and secret derivation.
  * KEA secret generation and verification.
  *
- * $Id: dh.c,v 1.9 2010/07/20 01:26:02 wtc%google.com Exp $
+ * $Id: dh.c,v 1.10 2012/03/28 22:35:14 rrelyea%redhat.com Exp $
  */
 #ifdef FREEBL_NO_DEPEND
 #include "stubs.h"
 #endif
 
 #include "prerr.h"
 #include "secerr.h"
 
@@ -210,17 +210,17 @@ cleanup:
     return rv;
 }
 
 SECStatus 
 DH_Derive(SECItem *publicValue, 
           SECItem *prime, 
           SECItem *privateValue, 
           SECItem *derivedSecret, 
-          unsigned int maxOutBytes)
+          unsigned int outBytes)
 {
     mp_int p, Xa, Yb, ZZ;
     mp_err err = MP_OKAY;
     int len = 0;
     unsigned int nb;
     unsigned char *secret = NULL;
     if (!publicValue || !prime || !privateValue || !derivedSecret) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
@@ -246,25 +246,34 @@ DH_Derive(SECItem *publicValue,
         err = MP_BADARG;
         goto cleanup;
     }
     /* allocate a buffer which can hold the entire derived secret. */
     secret = PORT_Alloc(len);
     /* grab the derived secret */
     err = mp_to_unsigned_octets(&ZZ, secret, len);
     if (err >= 0) err = MP_OKAY;
-    /* Take minimum of bytes requested and bytes in derived secret,
-    ** if maxOutBytes is 0 take all of the bytes from the derived secret.
+    /* 
+    ** if outBytes is 0 take all of the bytes from the derived secret.
+    ** if outBytes is not 0 take exactly outBytes from the derived secret, zero
+    ** pad at the beginning if necessary, and truncate beginning bytes 
+    ** if necessary.
     */
-    if (maxOutBytes > 0)
-	nb = PR_MIN(len, maxOutBytes);
+    if (outBytes > 0)
+	nb = outBytes;
     else
 	nb = len;
     SECITEM_AllocItem(NULL, derivedSecret, nb);
-    memcpy(derivedSecret->data, secret, nb);
+    if (len < nb) {
+	unsigned int offset = nb - len;
+	memset(derivedSecret->data, 0, offset);
+	memcpy(derivedSecret->data + offset, secret, len);
+    } else {
+	memcpy(derivedSecret->data, secret + len - nb, nb);
+    }
 cleanup:
     mp_clear(&p);
     mp_clear(&Xa);
     mp_clear(&Yb);
     mp_clear(&ZZ);
     if (secret) {
 	/* free the buffer allocated for the full secret. */
 	PORT_ZFree(secret, len);
--- a/security/nss/lib/libpkix/pkix/results/pkix_valresult.c
+++ b/security/nss/lib/libpkix/pkix/results/pkix_valresult.c
@@ -84,16 +84,18 @@ pkix_ValidateResult_Equals(
         PKIX_PL_Object *second,
         PKIX_Boolean *pResult,
         void *plContext)
 {
         PKIX_UInt32 secondType;
         PKIX_Boolean cmpResult;
         PKIX_ValidateResult *firstValResult = NULL;
         PKIX_ValidateResult *secondValResult = NULL;
+        PKIX_TrustAnchor *firstAnchor = NULL;
+        PKIX_TrustAnchor *secondAnchor = NULL;
         PKIX_PolicyNode *firstTree = NULL;
         PKIX_PolicyNode *secondTree = NULL;
 
         PKIX_ENTER(VALIDATERESULT, "pkix_ValidateResult_Equals");
         PKIX_NULLCHECK_THREE(first, second, pResult);
 
         PKIX_CHECK(pkix_CheckType(first, PKIX_VALIDATERESULT_TYPE, plContext),
                 PKIX_FIRSTOBJECTNOTVALIDATERESULT);
@@ -112,47 +114,46 @@ pkix_ValidateResult_Equals(
                 ((PKIX_PL_Object *)firstValResult->pubKey,
                 (PKIX_PL_Object *)secondValResult->pubKey,
                 &cmpResult,
                 plContext),
                 PKIX_OBJECTEQUALSFAILED);
 
         if (!cmpResult) goto cleanup;
 
-        PKIX_CHECK(PKIX_PL_Object_Equals
-                ((PKIX_PL_Object *)firstValResult->anchor,
-                (PKIX_PL_Object *)secondValResult->anchor,
-                &cmpResult,
-                plContext),
-                PKIX_OBJECTEQUALSFAILED);
+        firstAnchor = firstValResult->anchor;
+        secondAnchor = secondValResult->anchor;
+
+        if ((firstAnchor != NULL) && (secondAnchor != NULL)) {
+                PKIX_CHECK(PKIX_PL_Object_Equals
+                        ((PKIX_PL_Object *)firstAnchor,
+                        (PKIX_PL_Object *)secondAnchor,
+                        &cmpResult,
+                        plContext),
+                        PKIX_OBJECTEQUALSFAILED);
+        } else {
+                cmpResult = (firstAnchor == secondAnchor);
+        }
 
         if (!cmpResult) goto cleanup;
 
         firstTree = firstValResult->policyTree;
         secondTree = secondValResult->policyTree;
 
         if ((firstTree != NULL) && (secondTree != NULL)) {
                 PKIX_CHECK(PKIX_PL_Object_Equals
                         ((PKIX_PL_Object *)firstTree,
                         (PKIX_PL_Object *)secondTree,
                         &cmpResult,
                         plContext),
                         PKIX_OBJECTEQUALSFAILED);
         } else {
-                if (PKIX_EXACTLY_ONE_NULL(firstTree, secondTree)) {
-                        cmpResult = PKIX_FALSE;
-                }
+                cmpResult = (firstTree == secondTree);
         }
 
-        /*
-         * The remaining case is that both are null,
-         * which we consider equality.
-         *      cmpResult = PKIX_TRUE;
-         */
-
         *pResult = cmpResult;
 
 cleanup:
 
         PKIX_RETURN(VALIDATERESULT);
 }
 
 /*
@@ -165,36 +166,38 @@ pkix_ValidateResult_Hashcode(
         PKIX_UInt32 *pHashcode,
         void *plContext)
 {
         PKIX_ValidateResult *valResult = NULL;
         PKIX_UInt32 hash = 0;
         PKIX_UInt32 pubKeyHash = 0;
         PKIX_UInt32 anchorHash = 0;
         PKIX_UInt32 policyTreeHash = 0;
-        PKIX_PolicyNode *policyTree = NULL;
 
         PKIX_ENTER(VALIDATERESULT, "pkix_ValidateResult_Hashcode");
         PKIX_NULLCHECK_TWO(object, pHashcode);
 
         PKIX_CHECK(pkix_CheckType(object, PKIX_VALIDATERESULT_TYPE, plContext),
                 PKIX_OBJECTNOTVALIDATERESULT);
 
         valResult = (PKIX_ValidateResult*)object;
 
         PKIX_CHECK(PKIX_PL_Object_Hashcode
                 ((PKIX_PL_Object *)valResult->pubKey, &pubKeyHash, plContext),
                 PKIX_OBJECTHASHCODEFAILED);
 
-        PKIX_CHECK(PKIX_PL_Object_Hashcode
-                ((PKIX_PL_Object *)valResult->anchor, &anchorHash, plContext),
-                PKIX_OBJECTHASHCODEFAILED);
+        if (valResult->anchor) {
+                PKIX_CHECK(PKIX_PL_Object_Hashcode
+                        ((PKIX_PL_Object *)valResult->anchor,
+                        &anchorHash,
+                        plContext),
+                        PKIX_OBJECTHASHCODEFAILED);
+        }
 
-        policyTree = valResult->policyTree;
-        if (policyTree) {
+        if (valResult->policyTree) {
                 PKIX_CHECK(PKIX_PL_Object_Hashcode
                         ((PKIX_PL_Object *)valResult->policyTree,
                         &policyTreeHash,
                         plContext),
                         PKIX_OBJECTHASHCODEFAILED);
         }
 
         hash = 31*(31 * pubKeyHash + anchorHash) + policyTreeHash;
@@ -236,37 +239,45 @@ pkix_ValidateResult_ToString(
                 "]\n";
 
         PKIX_ENTER(VALIDATERESULT, "pkix_ValidateResult_ToString");
         PKIX_NULLCHECK_TWO(object, pString);
 
         PKIX_CHECK(pkix_CheckType(object, PKIX_VALIDATERESULT_TYPE, plContext),
                 PKIX_OBJECTNOTVALIDATERESULT);
 
+        PKIX_CHECK(PKIX_PL_String_Create
+                (PKIX_ESCASCII, asciiFormat, 0, &formatString, plContext),
+                PKIX_STRINGCREATEFAILED);
+
         valResult = (PKIX_ValidateResult*)object;
 
         anchor = valResult->anchor;
 
-        PKIX_CHECK(PKIX_PL_String_Create
-                (PKIX_ESCASCII, asciiFormat, 0, &formatString, plContext),
-                PKIX_STRINGCREATEFAILED);
-
-        PKIX_CHECK(PKIX_PL_Object_ToString
-                ((PKIX_PL_Object *)anchor, &anchorString, plContext),
-                PKIX_OBJECTTOSTRINGFAILED);
+        if (anchor) {
+                PKIX_CHECK(PKIX_PL_Object_ToString
+                        ((PKIX_PL_Object *)anchor, &anchorString, plContext),
+                        PKIX_OBJECTTOSTRINGFAILED);
+        } else {
+                PKIX_CHECK(PKIX_PL_String_Create
+                        (PKIX_ESCASCII,
+                        asciiNullString,
+                        0,
+                        &anchorString,
+                        plContext),
+                        PKIX_STRINGCREATEFAILED);
+        }
 
         pubKey = valResult->pubKey;
 
         PKIX_CHECK(PKIX_PL_Object_ToString
                 ((PKIX_PL_Object *)pubKey, &pubKeyString, plContext),
                 PKIX_OBJECTTOSTRINGFAILED);
 
-        PKIX_CHECK(PKIX_ValidateResult_GetPolicyTree
-                (valResult, &policyTree, plContext),
-                PKIX_VALIDATERESULTGETPOLICYTREEFAILED);
+        policyTree = valResult->policyTree;
 
         if (policyTree) {
                 PKIX_CHECK(PKIX_PL_Object_ToString
                         ((PKIX_PL_Object *)policyTree, &treeString, plContext),
                         PKIX_OBJECTTOSTRINGFAILED);
         } else {
                 PKIX_CHECK(PKIX_PL_String_Create
                         (PKIX_ESCASCII,
@@ -288,17 +299,16 @@ pkix_ValidateResult_ToString(
 
         *pString = valResultString;
 
 cleanup:
 
         PKIX_DECREF(formatString);
         PKIX_DECREF(anchorString);
         PKIX_DECREF(pubKeyString);
-        PKIX_DECREF(policyTree);
         PKIX_DECREF(treeString);
 
         PKIX_RETURN(VALIDATERESULT);
 }
 
 /*
  * FUNCTION: pkix_ValidateResult_RegisterSelf
  * DESCRIPTION:
@@ -342,17 +352,17 @@ pkix_ValidateResult_RegisterSelf(void *p
  *  Creates a new ValidateResult Object using the PublicKey pointed to by
  *  "pubKey", the TrustAnchor pointed to by "anchor", and the PolicyNode
  *  pointed to by "policyTree", and stores it at "pResult".
  *
  * PARAMETERS
  *  "pubKey"
  *      PublicKey of the desired ValidateResult. Must be non-NULL.
  *  "anchor"
- *      TrustAnchor of the desired Validateresult. Must be non-NULL.
+ *      TrustAnchor of the desired Validateresult. May be NULL.
  *  "policyTree"
  *      PolicyNode of the desired ValidateResult; may be NULL
  *  "pResult"
  *      Address where object pointer will be stored. Must be non-NULL.
  *  "plContext"
  *      Platform-specific context pointer.
  * THREAD SAFETY:
  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
@@ -366,17 +376,17 @@ pkix_ValidateResult_Create(
         PKIX_TrustAnchor *anchor,
         PKIX_PolicyNode *policyTree,
         PKIX_ValidateResult **pResult,
         void *plContext)
 {
         PKIX_ValidateResult *result = NULL;
 
         PKIX_ENTER(VALIDATERESULT, "pkix_ValidateResult_Create");
-        PKIX_NULLCHECK_THREE(pubKey, anchor, pResult);
+        PKIX_NULLCHECK_TWO(pubKey, pResult);
 
         PKIX_CHECK(PKIX_PL_Object_Alloc
                     (PKIX_VALIDATERESULT_TYPE,
                     sizeof (PKIX_ValidateResult),
                     (PKIX_PL_Object **)&result,
                     plContext),
                     PKIX_COULDNOTCREATEVALIDATERESULTOBJECT);
 
--- a/security/nss/lib/libpkix/pkix/top/pkix_build.c
+++ b/security/nss/lib/libpkix/pkix/top/pkix_build.c
@@ -170,17 +170,17 @@ cleanup:
  *  "prevCert"
  *      Address of Cert just traversed. Must be non-NULL.
  *  "traversedSubjNames"
  *      Address of List of GeneralNames that have been traversed.
  *      Must be non-NULL.
  *  "trustChain"
  *      Address of List of certificates traversed. Must be non-NULL.
  *  "parentState"
- *      Address of previous ForwardBuilder state
+ *      Address of previous ForwardBuilderState
  *  "pState"
  *      Address where ForwardBuilderState will be stored. Must be non-NULL.
  *  "plContext"
  *      Platform-specific context pointer.
  * THREAD SAFETY:
  *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
  * RETURNS:
  *  Returns NULL if the function succeeds.
@@ -3151,17 +3151,17 @@ fatal:
 }
 
 /*
  * FUNCTION: pkix_Build_InitiateBuildChain
  * DESCRIPTION:
  *
  *  This function initiates the search for a BuildChain, using the parameters
  *  provided in "procParams" and, if continuing a search that was suspended
- *  for I/O, using the ForwardBuilderState pointed to by "state".
+ *  for I/O, using the ForwardBuilderState pointed to by "pState".
  *
  *  If a successful chain is built, this function stores the BuildResult at
  *  "pBuildResult". Alternatively, if an operation using non-blocking I/O
  *  is in progress and the operation has not been completed, this function
  *  stores the platform-dependent non-blocking I/O context (nbioContext) at
  *  "pNBIOContext", the FowardBuilderState at "pState", and NULL at
  *  "pBuildResult". Finally, if chain building was unsuccessful, this function
  *  stores NULL at both "pState" and at "pBuildResult".
@@ -3226,17 +3226,16 @@ pkix_Build_InitiateBuildChain(
         PKIX_PL_PublicKey *targetPubKey = NULL;
         void *nbioContext = NULL;
         BuildConstants buildConstants;
 
         PKIX_List *tentativeChain = NULL;
         PKIX_ValidateResult *valResult = NULL;
         PKIX_BuildResult *buildResult = NULL;
         PKIX_List *certList = NULL;
-        PKIX_TrustAnchor *matchingAnchor = NULL;
         PKIX_ForwardBuilderState *state = NULL;
         PKIX_CertStore_CheckTrustCallback trustCallback = NULL;
         PKIX_CertSelector_MatchCallback selectorCallback = NULL;
         PKIX_Boolean trusted = PKIX_FALSE;
         PKIX_PL_AIAMgr *aiaMgr = NULL;
 
         PKIX_ENTER(BUILD, "pkix_Build_InitiateBuildChain");
         PKIX_NULLCHECK_FOUR(procParams, pNBIOContext, pState, pBuildResult);
@@ -3341,19 +3340,16 @@ pkix_Build_InitiateBuildChain(
                 PKIX_ERROR(PKIX_NOTARGETCERTSUPPLIED);
             }
 
             PKIX_CHECK(PKIX_PL_Cert_IsLeafCertTrusted
                     (targetCert,
                     &trusted, 
                     plContext),
                     PKIX_CERTISCERTTRUSTEDFAILED);
-            /* future: look at the |trusted| flag and force success. We only
-             * want to do this if we aren't validating against a policy (like
-             * EV). */
 
             PKIX_CHECK(PKIX_PL_Cert_GetAllSubjectNames
                     (targetCert,
                     &targetSubjNames,
                     plContext),
                     PKIX_CERTGETALLSUBJECTNAMESFAILED);
     
             PKIX_CHECK(PKIX_PL_Cert_GetSubjectPublicKey
@@ -3401,16 +3397,46 @@ pkix_Build_InitiateBuildChain(
                                 pkixErrorClass = PKIX_FATAL_ERROR;
                                 goto cleanup;
                             }
                     }
                     pkixErrorCode = PKIX_CERTCHECKVALIDITYFAILED;
                     goto cleanup;
                 }
             }
+
+            /* If the EE cert is trusted, force success. We only want to do
+             * this if we aren't validating against a policy (like EV). */
+            if (trusted && procParams->initialPolicies == NULL) {
+                if (pVerifyNode != NULL) {
+                    PKIX_Error *tempResult =
+                        pkix_VerifyNode_Create(targetCert, 0, NULL,
+                                               pVerifyNode,
+                                               plContext);
+                    if (tempResult) {
+                        pkixErrorResult = tempResult;
+                        pkixErrorCode = PKIX_VERIFYNODECREATEFAILED;
+                        pkixErrorClass = PKIX_FATAL_ERROR;
+                        goto cleanup;
+                    }
+                }
+                PKIX_CHECK(pkix_ValidateResult_Create
+                        (targetPubKey, NULL /* anchor */,
+                         NULL /* policyTree */, &valResult, plContext),
+                        PKIX_VALIDATERESULTCREATEFAILED);
+                PKIX_CHECK(
+                    pkix_BuildResult_Create(valResult, tentativeChain,
+                                            &buildResult, plContext),
+                    PKIX_BUILDRESULTCREATEFAILED);
+                *pBuildResult = buildResult;
+                /* Note that *pState is NULL.   The only side effect is that
+                 * the cert chain won't be cached in PKIX_BuildChain, which
+                 * is fine. */
+                goto cleanup;
+            }
     
             PKIX_CHECK(PKIX_ProcessingParams_GetCertStores
                     (procParams, &certStores, plContext),
                     PKIX_PROCESSINGPARAMSGETCERTSTORESFAILED);
     
             PKIX_CHECK(PKIX_List_GetLength
                     (certStores, &numCertStores, plContext),
                     PKIX_LISTGETLENGTHFAILED);
@@ -3574,21 +3600,19 @@ pkix_Build_InitiateBuildChain(
                     (state->buildConstants.targetCert,
                     &targetSubjNames,
                     plContext),
                     PKIX_CERTGETALLSUBJECTNAMESFAILED);
         }
 
         state->status = BUILD_INITIAL;
 
-        if (!matchingAnchor) {
-                pkixErrorResult =
-                    pkix_BuildForwardDepthFirstSearch(&nbioContext, state,
-                                                      &valResult, plContext);
-        }
+        pkixErrorResult =
+            pkix_BuildForwardDepthFirstSearch(&nbioContext, state,
+                                              &valResult, plContext);
 
         /* non-null nbioContext means the build would block */
         if (pkixErrorResult == NULL && nbioContext != NULL) {
 
                 *pNBIOContext = nbioContext;
                 *pBuildResult = NULL;
 
         /* no valResult means the build has failed */
@@ -3623,17 +3647,16 @@ cleanup:
         PKIX_DECREF(userCheckers);
         PKIX_DECREF(hintCerts);
         PKIX_DECREF(firstHintCert);
         PKIX_DECREF(testDate);
         PKIX_DECREF(targetPubKey);
         PKIX_DECREF(tentativeChain);
         PKIX_DECREF(valResult);
         PKIX_DECREF(certList);
-        PKIX_DECREF(matchingAnchor);
         PKIX_DECREF(trustedCert);
         PKIX_DECREF(state);
         PKIX_DECREF(aiaMgr);
 
         PKIX_RETURN(BUILD);
 }
 
 /*
--- a/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
+++ b/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
@@ -1664,23 +1664,23 @@ cleanup:
  */
 PKIX_Error *
 PKIX_PL_Cert_GetVersion(
         PKIX_PL_Cert *cert,
         PKIX_UInt32 *pVersion,
         void *plContext)
 {
         CERTCertificate *nssCert = NULL;
-        PKIX_UInt32 myVersion = 1;
+        PKIX_UInt32 myVersion = 0;  /* v1 */
 
         PKIX_ENTER(CERT, "PKIX_PL_Cert_GetVersion");
         PKIX_NULLCHECK_THREE(cert, cert->nssCert, pVersion);
 
         nssCert = cert->nssCert;
-        if (nssCert->version.data) {
+        if (nssCert->version.len != 0) {
                 myVersion = *(nssCert->version.data);
         }
 
         if (myVersion > 2){
                 PKIX_ERROR(PKIX_VERSIONVALUEMUSTBEV1V2ORV3);
         }
 
         *pVersion = myVersion;
--- a/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.h
+++ b/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.h
@@ -46,17 +46,20 @@
 
 #include "pkix_pl_common.h"
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 struct PKIX_PL_CertStruct {
-        CERTCertificate *nssCert;
+        CERTCertificate *nssCert;  /* Must be the first field.  The
+                                    * cert_NSSCertFromPKIXCert function in
+                                    * lib/certhigh/certvfypkix.c depends on
+                                    * this. */
         CERTGeneralName *nssSubjAltNames;
         PLArenaPool *arenaNameConstraints;
         PKIX_PL_X500Name *issuer;
         PKIX_PL_X500Name *subject;
         PKIX_List *subjAltNames;
         PKIX_Boolean subjAltNamesAbsent;
         PKIX_PL_OID *publicKeyAlgId;
         PKIX_PL_PublicKey *publicKey;
--- a/security/nss/lib/nss/nss.h
+++ b/security/nss/lib/nss/nss.h
@@ -31,17 +31,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: nss.h,v 1.91 2012/02/18 23:22:43 kaie%kuix.de Exp $ */
+/* $Id: nss.h,v 1.92.2.1 2012/04/06 15:20:43 kaie%kuix.de Exp $ */
 
 #ifndef __nss_h_
 #define __nss_h_
 
 /* The private macro _NSS_ECC_STRING is for NSS internal use only. */
 #ifdef NSS_ENABLE_ECC
 #ifdef NSS_ECC_MORE_THAN_SUITE_B
 #define _NSS_ECC_STRING " Extended ECC"
@@ -61,20 +61,20 @@
 
 /*
  * NSS's major version, minor version, patch level, build number, and whether
  * this is a beta release.
  *
  * The format of the version string should be
  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
  */
-#define NSS_VERSION  "3.13.3.0" _NSS_ECC_STRING _NSS_CUSTOMIZED
+#define NSS_VERSION  "3.13.4.0" _NSS_ECC_STRING _NSS_CUSTOMIZED
 #define NSS_VMAJOR   3
 #define NSS_VMINOR   13
-#define NSS_VPATCH   3
+#define NSS_VPATCH   4
 #define NSS_VBUILD   0
 #define NSS_BETA     PR_FALSE
 
 #ifndef RC_INVOKED
 
 #include "seccomon.h"
 
 typedef struct NSSInitParametersStr NSSInitParameters;
--- a/security/nss/lib/pk11wrap/pk11auth.c
+++ b/security/nss/lib/pk11wrap/pk11auth.c
@@ -160,17 +160,17 @@ PK11_CheckUserPassword(PK11SlotInfo *slo
     } else if (pw == NULL) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     } else {
 	len = PORT_Strlen(pw);
     }
 
     /*
-     * If the token does't need a login, don't try to relogin beause the
+     * If the token doesn't need a login, don't try to relogin because the
      * effect is undefined. It's not clear what it means to check a non-empty
      * password with such a token, so treat that as an error.
      */
     if (!slot->needLogin) {
         if (len == 0) {
             rv = SECSuccess;
         } else {
             PORT_SetError(SEC_ERROR_BAD_PASSWORD);
--- a/security/nss/lib/pk11wrap/pk11merge.c
+++ b/security/nss/lib/pk11wrap/pk11merge.c
@@ -1104,17 +1104,17 @@ pk11_mergeTrust(PK11SlotInfo *targetSlot
 	    CKA_TRUST_SERVER_AUTH, CKA_TRUST_CLIENT_AUTH,
 	    CKA_TRUST_CODE_SIGNING, CKA_TRUST_EMAIL_PROTECTION, 
 	    CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER, 
 	    CKA_TRUST_TIME_STAMPING
 	};
 	CK_ULONG trustAttrsCount = 
 		sizeof(trustAttrs)/sizeof(trustAttrs[0]);
 
-	int i;
+	CK_ULONG i;
 	CK_ATTRIBUTE targetTemplate, sourceTemplate;
 
 	/* existing trust record, merge the two together */
         for (i=0; i < trustAttrsCount; i++) {
 	    targetTemplate.type = sourceTemplate.type = trustAttrs[i];
 	    targetTemplate.pValue = sourceTemplate.pValue = NULL;
 	    targetTemplate.ulValueLen = sourceTemplate.ulValueLen = 0;
 	    PK11_GetAttributes(arena, sourceSlot, id, &sourceTemplate, 1);
--- a/security/nss/lib/pk11wrap/pk11sdr.c
+++ b/security/nss/lib/pk11wrap/pk11sdr.c
@@ -106,17 +106,17 @@ padBlock(SECItem *data, int blockSize, S
   return rv;
 }
 
 static SECStatus
 unpadBlock(SECItem *data, int blockSize, SECItem *result)
 {
   SECStatus rv = SECSuccess;
   int padLength;
-  int i;
+  unsigned int i;
 
   result->data = 0;
   result->len = 0;
 
   /* Remove the padding from the end if the input data */
   if (data->len == 0 || data->len % blockSize  != 0) { rv = SECFailure; goto loser; }
 
   padLength = data->data[data->len-1];
--- a/security/nss/lib/pkcs12/p12e.c
+++ b/security/nss/lib/pkcs12/p12e.c
@@ -45,16 +45,18 @@
 #include "secpkcs7.h"
 #include "secasn1.h"
 #include "secerr.h"
 #include "pk11func.h"
 #include "p12plcy.h"
 #include "p12local.h"
 #include "prcpucfg.h"
 
+extern const int NSS_PBE_DEFAULT_ITERATION_COUNT; /* defined in p7create.c */
+
 /*
 ** This PKCS12 file encoder uses numerous nested ASN.1 and PKCS7 encoder
 ** contexts.  It can be difficult to keep straight.  Here's a picture:
 **
 **  "outer"  ASN.1 encoder.  The output goes to the library caller's CB.
 **  "middle" PKCS7 encoder.  Feeds    the "outer" ASN.1 encoder.
 **  "middle" ASN1  encoder.  Encodes  the encrypted aSafes. 
 **                           Feeds    the "middle" P7 encoder above.
@@ -1251,18 +1253,19 @@ SEC_PKCS12AddKeyForCert(SEC_PKCS12Export
 	/* we want to make sure to take the key out of the key slot */
 	if(PK11_IsInternal(p12ctxt->slot)) {
 	    slot = PK11_GetInternalKeySlot();
 	} else {
 	    slot = PK11_ReferenceSlot(p12ctxt->slot);
 	}
 
 	epki = PK11_ExportEncryptedPrivateKeyInfo(slot, algorithm, 
-						  &uniPwitem, cert, 1, 
-						  p12ctxt->wincx);
+					    &uniPwitem, cert,
+					    NSS_PBE_DEFAULT_ITERATION_COUNT,
+					    p12ctxt->wincx);
 	PK11_FreeSlot(slot);
 	if(!epki) {
 	    PORT_SetError(SEC_ERROR_PKCS12_UNABLE_TO_EXPORT_KEY);
 	    goto loser;
 	}   
 	
 	keyItem = PORT_ArenaZAlloc(p12ctxt->arena, 
 				  sizeof(SECKEYEncryptedPrivateKeyInfo));
@@ -1600,30 +1603,36 @@ sec_pkcs12_encoder_start_context(SEC_PKC
 		goto loser;
 	    }
 	    if(SECITEM_CopyItem(p12exp->arena, &(p12enc->mac.macSalt), salt) 
 			!= SECSuccess) {
 		/* XXX salt is leaked */
 		PORT_SetError(SEC_ERROR_NO_MEMORY);
 		goto loser;
 	    }   
+	    if (!SEC_ASN1EncodeInteger(p12exp->arena, &(p12enc->mac.iter),
+				       NSS_PBE_DEFAULT_ITERATION_COUNT)) {
+		/* XXX salt is leaked */
+		goto loser;
+	    }
 
 	    /* generate HMAC key */
 	    if(!sec_pkcs12_convert_item_to_unicode(NULL, &pwd, 
 			p12exp->integrityInfo.pwdInfo.password, PR_TRUE, 
 			PR_TRUE, PR_TRUE)) {
 		/* XXX salt is leaked */
 		goto loser;
 	    }
 	    /*
 	     * This code only works with PKCS #12 Mac using PKCS #5 v1
 	     * PBA keygens. PKCS #5 v2 support will require a change to
 	     * the PKCS #12 spec.
 	     */
-	    params = PK11_CreatePBEParams(salt, &pwd, 1);
+	    params = PK11_CreatePBEParams(salt, &pwd,
+                                          NSS_PBE_DEFAULT_ITERATION_COUNT);
 	    SECITEM_ZfreeItem(salt, PR_TRUE);
 	    SECITEM_ZfreeItem(&pwd, PR_FALSE);
 
 	    /* get the PBA Mechanism to generate the key */
 	    switch (p12exp->integrityInfo.pwdInfo.algorithm) {
 	    case SEC_OID_SHA1:
 		integrityMechType = CKM_PBA_SHA1_WITH_SHA1_HMAC; break;
 	    case SEC_OID_MD5:
--- a/security/nss/lib/pkcs7/p7create.c
+++ b/security/nss/lib/pkcs7/p7create.c
@@ -32,31 +32,33 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * PKCS7 creation.
  *
- * $Id: p7create.c,v 1.9 2008/02/03 06:08:48 nelson%bolyard.com Exp $
+ * $Id: p7create.c,v 1.10 2012/03/19 22:16:34 kaie%kuix.de Exp $
  */
 
 #include "p7local.h"
 
 #include "cert.h"
 #include "secasn1.h"
 #include "secitem.h"
 #include "secoid.h"
 #include "pk11func.h"
 #include "prtime.h"
 #include "secerr.h"
 #include "secder.h"
 #include "secpkcs5.h"
 
+const int NSS_PBE_DEFAULT_ITERATION_COUNT = 2000; /* used in p12e.c too */
+
 static SECStatus
 sec_pkcs7_init_content_info (SEC_PKCS7ContentInfo *cinfo, PRArenaPool *poolp,
 			     SECOidTag kind, PRBool detached)
 {
     void *thing;
     int version;
     SECItem *versionp;
     SECStatus rv;
@@ -1288,17 +1290,19 @@ SEC_PKCS7CreateEncryptedData (SECOidTag 
         /* Assume password-based-encryption.  
          * Note: we can't generate pkcs5v2 from this interface.
          * PK11_CreateBPEAlgorithmID generates pkcs5v2 by accepting
          * non-PBE oids and assuming that they are pkcs5v2 oids, but
          * NSS_CMSEncryptedData_Create accepts non-PBE oids as regular
          * CMS encrypted data, so we can't tell SEC_PKCS7CreateEncryptedtedData
          * to create pkcs5v2 PBEs */
 	SECAlgorithmID *pbe_algid;
-	pbe_algid = PK11_CreatePBEAlgorithmID (algorithm, 1, NULL);
+	pbe_algid = PK11_CreatePBEAlgorithmID(algorithm,
+                                              NSS_PBE_DEFAULT_ITERATION_COUNT,
+                                              NULL);
 	if (pbe_algid == NULL) {
 	    rv = SECFailure;
 	} else {
 	    rv = SECOID_CopyAlgorithmID (cinfo->poolp, algid, pbe_algid);
 	    SECOID_DestroyAlgorithmID (pbe_algid, PR_TRUE);
 	}
     }
 
--- a/security/nss/lib/smime/smimeutil.c
+++ b/security/nss/lib/smime/smimeutil.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Stuff specific to S/MIME policy and interoperability.
  *
- * $Id: smimeutil.c,v 1.22 2011/08/21 01:14:18 wtc%google.com Exp $
+ * $Id: smimeutil.c,v 1.23 2012/03/01 18:33:11 kaie%kuix.de Exp $
  */
 
 #include "secmime.h"
 #include "secoid.h"
 #include "pk11func.h"
 #include "ciferfam.h"	/* for CIPHER_FAMILY symbols */
 #include "secasn1.h"
 #include "secitem.h"
@@ -147,17 +147,18 @@ typedef struct {
 static smime_cipher_map_entry smime_cipher_map[] = {
 /*    cipher			algtag			parms		enabled  allowed */
 /*    ---------------------------------------------------------------------------------- */
     { SMIME_RC2_CBC_40,		SEC_OID_RC2_CBC,	&param_int40,	PR_TRUE, PR_TRUE },
     { SMIME_DES_CBC_56,		SEC_OID_DES_CBC,	NULL,		PR_TRUE, PR_TRUE },
     { SMIME_RC2_CBC_64,		SEC_OID_RC2_CBC,	&param_int64,	PR_TRUE, PR_TRUE },
     { SMIME_RC2_CBC_128,	SEC_OID_RC2_CBC,	&param_int128,	PR_TRUE, PR_TRUE },
     { SMIME_DES_EDE3_168,	SEC_OID_DES_EDE3_CBC,	NULL,		PR_TRUE, PR_TRUE },
-    { SMIME_AES_CBC_128,	SEC_OID_AES_128_CBC,	NULL,		PR_TRUE, PR_TRUE }
+    { SMIME_AES_CBC_128,	SEC_OID_AES_128_CBC,	NULL,		PR_TRUE, PR_TRUE },
+    { SMIME_AES_CBC_256,	SEC_OID_AES_256_CBC,	NULL,		PR_TRUE, PR_TRUE }
 };
 static const int smime_cipher_map_count = sizeof(smime_cipher_map) / sizeof(smime_cipher_map_entry);
 
 /*
  * smime_mapi_by_cipher - find index into smime_cipher_map by cipher
  */
 static int
 smime_mapi_by_cipher(unsigned long cipher)
@@ -267,16 +268,19 @@ nss_smime_get_cipher_for_alg_and_key(SEC
 	c = SMIME_DES_CBC_56;
 	break;
     case SEC_OID_DES_EDE3_CBC:
 	c = SMIME_DES_EDE3_168;
 	break;
     case SEC_OID_AES_128_CBC:
 	c = SMIME_AES_CBC_128;
 	break;
+    case SEC_OID_AES_256_CBC:
+	c = SMIME_AES_CBC_256;
+	break;
     default:
 	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
 	return SECFailure;
     }
     *cipher = c;
     return SECSuccess;
 }
 
@@ -521,16 +525,19 @@ smime_keysize_by_cipher (unsigned long w
 	break;
       case SMIME_RC2_CBC_64:
 	keysize = 64;
 	break;
       case SMIME_RC2_CBC_128:
       case SMIME_AES_CBC_128:
 	keysize = 128;
 	break;
+      case SMIME_AES_CBC_256:
+	keysize = 256;
+	break;
       case SMIME_DES_CBC_56:
       case SMIME_DES_EDE3_168:
 	/*
 	 * These are special; since the key size is fixed, we actually
 	 * want to *avoid* specifying a key size.
 	 */
 	keysize = 0;
 	break;
--- a/security/nss/lib/softoken/legacydb/keydb.c
+++ b/security/nss/lib/softoken/legacydb/keydb.c
@@ -29,17 +29,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: keydb.c,v 1.12 2010/07/20 01:26:04 wtc%google.com Exp $ */
+/* $Id: keydb.c,v 1.12.2.1 2012/04/05 21:14:22 wtc%google.com Exp $ */
 
 #include "lowkeyi.h"
 #include "secasn1.h"
 #include "secder.h"
 #include "secoid.h"
 #include "blapi.h"
 #include "secitem.h"
 #include "pcert.h"
@@ -1785,16 +1785,45 @@ seckey_decrypt_private_key(SECItem*epki,
 	      case SEC_OID_PKCS1_RSA_ENCRYPTION:
 		pk->keyType = NSSLOWKEYRSAKey;
 		lg_prepare_low_rsa_priv_key_for_asn1(pk);
                 if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
                     &pki->privateKey) ) break;
 		rv = SEC_QuickDERDecodeItem(permarena, pk,
 					lg_nsslowkey_RSAPrivateKeyTemplate,
 					&newPrivateKey);
+		if (rv == SECSuccess) {
+		    break;
+		}
+		/* Try decoding with the alternative template, but only allow
+		 * a zero-length modulus for a secret key object.
+		 * See bug 715073.
+		 */
+		rv = SEC_QuickDERDecodeItem(permarena, pk,
+					lg_nsslowkey_RSAPrivateKeyTemplate2,
+					&newPrivateKey);
+		/* A publicExponent of 0 is the defining property of a secret
+		 * key disguised as an RSA key. When decoding with the
+		 * alternative template, only accept a secret key with an
+		 * improperly encoded modulus and a publicExponent of 0.
+		 */
+		if (rv == SECSuccess) {
+		    if (pk->u.rsa.modulus.len == 2 &&
+			pk->u.rsa.modulus.data[0] == SEC_ASN1_INTEGER &&
+			pk->u.rsa.modulus.data[1] == 0 &&
+			pk->u.rsa.publicExponent.len == 1 &&
+			pk->u.rsa.publicExponent.data[0] == 0) {
+			/* Fix the zero-length integer by setting it to 0. */
+			pk->u.rsa.modulus.data = pk->u.rsa.publicExponent.data;
+			pk->u.rsa.modulus.len = pk->u.rsa.publicExponent.len;
+		    } else {
+			PORT_SetError(SEC_ERROR_BAD_DER);
+			rv = SECFailure;
+		    }
+		}
 		break;
 	      case SEC_OID_ANSIX9_DSA_SIGNATURE:
 		pk->keyType = NSSLOWKEYDSAKey;
 		lg_prepare_low_dsa_priv_key_for_asn1(pk);
                 if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
                     &pki->privateKey) ) break;
 		rv = SEC_QuickDERDecodeItem(permarena, pk,
 					lg_nsslowkey_DSAPrivateKeyTemplate,
--- a/security/nss/lib/softoken/legacydb/lgcreate.c
+++ b/security/nss/lib/softoken/legacydb/lgcreate.c
@@ -811,21 +811,26 @@ static NSSLOWKEYPrivateKey *lg_mkSecretK
      *   private exponent - CKA_VALUE (the key itself)
      *   coefficient - CKA_KEY_TYPE, which indicates what encryption algorithm
      *      is used for the key.
      *   all others - set to integer 0
      */
     privKey->keyType = NSSLOWKEYRSAKey;
 
     /* The modulus is set to the key id of the symmetric key */
-    crv = lg_Attribute2SecItem(arena, CKA_ID, templ, count, 
-				&privKey->u.rsa.modulus);
-    if (crv != CKR_OK) goto loser;
+    privKey->u.rsa.modulus.data =
+		(unsigned char *) PORT_ArenaAlloc(arena, pubkey->len);
+    if (privKey->u.rsa.modulus.data == NULL) {
+	crv = CKR_HOST_MEMORY;
+	goto loser;
+    }
+    privKey->u.rsa.modulus.len = pubkey->len;
+    PORT_Memcpy(privKey->u.rsa.modulus.data, pubkey->data, pubkey->len);
 
-    /* The public exponent is set to 0 length to indicate a special key */
+    /* The public exponent is set to 0 to indicate a special key */
     privKey->u.rsa.publicExponent.len = sizeof derZero;
     privKey->u.rsa.publicExponent.data = derZero;
 
     /* The private exponent is the actual key value */
     crv = lg_PrivAttr2SecItem(arena, CKA_VALUE, templ, count,
 				&privKey->u.rsa.privateExponent, sdbpw);
     if (crv != CKR_OK) goto loser;
 
--- a/security/nss/lib/softoken/legacydb/lowkey.c
+++ b/security/nss/lib/softoken/legacydb/lowkey.c
@@ -92,16 +92,34 @@ const SEC_ASN1Template lg_nsslowkey_RSAP
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime1) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime2) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent1) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent2) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.coefficient) },
     { 0 }                                                                     
 };                                                                            
 
+/*
+ * Allows u.rsa.modulus to be zero length for secret keys with an empty
+ * CKA_ID incorrectly generated in NSS 3.13.3 or earlier.  Only used for
+ * decoding.  See bug 715073.
+ */
+const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate2[] = {
+    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.version) },
+    { SEC_ASN1_ANY, offsetof(NSSLOWKEYPrivateKey,u.rsa.modulus) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.publicExponent) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.privateExponent) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime1) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime2) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent1) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent2) },
+    { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.coefficient) },
+    { 0 }
+};
 
 const SEC_ASN1Template lg_nsslowkey_DSAPrivateKeyTemplate[] = {
     { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.publicValue) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.privateValue) },
     { 0, }
 };
 
--- a/security/nss/lib/softoken/legacydb/lowkeyti.h
+++ b/security/nss/lib/softoken/legacydb/lowkeyti.h
@@ -67,16 +67,17 @@ typedef struct NSSLOWKEYDBHandleStr NSSL
 
 #define NSSLOWKEY_VERSION	    0	/* what we *create* */
 
 /*
 ** Typedef for callback to get a password "key".
 */
 extern const SEC_ASN1Template lg_nsslowkey_PQGParamsTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate[];
+extern const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate2[];
 extern const SEC_ASN1Template lg_nsslowkey_DSAPrivateKeyTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyExportTemplate[];
 #ifdef NSS_ENABLE_ECC
 #define NSSLOWKEY_EC_PRIVATE_KEY_VERSION   1  /* as per SECG 1 C.4 */
 extern const SEC_ASN1Template lg_nsslowkey_ECParamsTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_ECPrivateKeyTemplate[];
 #endif /* NSS_ENABLE_ECC */
--- a/security/nss/lib/softoken/softkver.h
+++ b/security/nss/lib/softoken/softkver.h
@@ -52,16 +52,16 @@
 
 /*
  * Softoken's major version, minor version, patch level, build number,
  * and whether this is a beta release.
  *
  * The format of the version string should be
  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
  */
-#define SOFTOKEN_VERSION  "3.13.3.0" SOFTOKEN_ECC_STRING
+#define SOFTOKEN_VERSION  "3.13.4.0" SOFTOKEN_ECC_STRING
 #define SOFTOKEN_VMAJOR   3
 #define SOFTOKEN_VMINOR   13
-#define SOFTOKEN_VPATCH   3
+#define SOFTOKEN_VPATCH   4
 #define SOFTOKEN_VBUILD   0
 #define SOFTOKEN_BETA     PR_FALSE
 
 #endif /* _SOFTKVER_H_ */
--- a/security/nss/lib/ssl/ssl3con.c
+++ b/security/nss/lib/ssl/ssl3con.c
@@ -1,8 +1,9 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /*
  * SSL3 Protocol
  *
  * ***** BEGIN LICENSE BLOCK *****
  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  *
  * The contents of this file are subject to the Mozilla Public License Version
  * 1.1 (the "License"); you may not use this file except in compliance with
@@ -34,17 +35,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: ssl3con.c,v 1.164 2012/02/17 09:50:04 kaie%kuix.de Exp $ */
+/* $Id: ssl3con.c,v 1.167 2012/03/06 02:23:25 wtc%google.com Exp $ */
 
 #include "cert.h"
 #include "ssl.h"
 #include "cryptohi.h"	/* for DSAU_ stuff */
 #include "keyhi.h"
 #include "secder.h"
 #include "secitem.h"
 
@@ -136,18 +137,18 @@ static ssl3CipherSuiteCfg cipherSuites[s
 #ifdef NSS_ENABLE_ECC
  { TLS_ECDH_RSA_WITH_RC4_128_SHA,          SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
  { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
  { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,        SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
  { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
 #endif /* NSS_ENABLE_ECC */
  { TLS_RSA_WITH_SEED_CBC_SHA,              SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE}, 
  { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,  	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
+ { SSL_RSA_WITH_RC4_128_SHA,               SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
  { SSL_RSA_WITH_RC4_128_MD5,               SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
- { SSL_RSA_WITH_RC4_128_SHA,               SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
  { TLS_RSA_WITH_AES_128_CBC_SHA,     	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
 
 #ifdef NSS_ENABLE_ECC
  { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
  { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
 #endif /* NSS_ENABLE_ECC */
  { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
  { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
@@ -1427,17 +1428,17 @@ ssl3_InitCompressionContext(ssl3CipherSp
 /* Initialize encryption and MAC contexts for pending spec.
  * Master Secret already is derived in spec->msItem
  * Caller holds Spec write lock.
  */
 static SECStatus
 ssl3_InitPendingContextsBypass(sslSocket *ss)
 {
       ssl3CipherSpec  *  pwSpec;
-const ssl3BulkCipherDef *cipher_def;
+      const ssl3BulkCipherDef *cipher_def;
       void *             serverContext = NULL;
       void *             clientContext = NULL;
       BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
       int                mode     = 0;
       unsigned int       optArg1  = 0;
       unsigned int       optArg2  = 0;
       PRBool             server_encrypts = ss->sec.isServer;
       CK_ULONG           macLength;
@@ -1616,17 +1617,17 @@ ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype
 /* Initialize encryption and MAC contexts for pending spec.
  * Master Secret already is derived.
  * Caller holds Spec write lock.
  */
 static SECStatus
 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
 {
       ssl3CipherSpec  *  pwSpec;
-const ssl3BulkCipherDef *cipher_def;
+      const ssl3BulkCipherDef *cipher_def;
       PK11Context *      serverContext = NULL;
       PK11Context *      clientContext = NULL;
       SECItem *          param;
       CK_MECHANISM_TYPE  mechanism;
       CK_MECHANISM_TYPE  mac_mech;
       CK_ULONG           macLength;
       CK_ULONG           effKeyBits;
       SECItem            iv;
@@ -7044,17 +7045,17 @@ ssl3_SendServerHello(sslSocket *ss)
 
     return SECSuccess;
 }
 
 
 static SECStatus
 ssl3_SendServerKeyExchange(sslSocket *ss)
 {
-const ssl3KEADef *     kea_def     = ss->ssl3.hs.kea_def;
+    const ssl3KEADef * kea_def     = ss->ssl3.hs.kea_def;
     SECStatus          rv          = SECFailure;
     int                length;
     PRBool             isTLS;
     SECItem            signed_hash = {siBuffer, NULL, 0};
     SSL3Hashes         hashes;
     SECKEYPublicKey *  sdPub;	/* public key for step-down */
 
     SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
@@ -7143,17 +7144,17 @@ loser:
 }
 
 
 static SECStatus
 ssl3_SendCertificateRequest(sslSocket *ss)
 {
     SECItem *      name;
     CERTDistNames *ca_list;
-const uint8 *      certTypes;
+    const uint8 *  certTypes;
     SECItem *      names	= NULL;
     SECStatus      rv;
     int            length;
     int            i;
     int            calen	= 0;
     int            nnames	= 0;
     int            certTypesLength;
 
@@ -7487,17 +7488,17 @@ double_bypass:
  * ssl3 ClientKeyExchange message from the remote client
  * Caller must hold Handshake and RecvBuf locks.
  */
 static SECStatus
 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
 {
     SECKEYPrivateKey *serverKey         = NULL;
     SECStatus         rv;
-const ssl3KEADef *    kea_def;
+    const ssl3KEADef *kea_def;
     ssl3KeyPair     *serverKeyPair      = NULL;
 #ifdef NSS_ENABLE_ECC
     SECKEYPublicKey *serverPubKey       = NULL;
 #endif /* NSS_ENABLE_ECC */
 
     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
 		SSL_GETPID(), ss->fd));
 
@@ -8607,29 +8608,27 @@ xmit_loser:
 
     rv = ssl3_FinishHandshake(ss);
     return rv;
 }
 
 SECStatus
 ssl3_FinishHandshake(sslSocket * ss)
 {
-    SECStatus rv;
-
     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
     PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
 
     /* The first handshake is now completed. */
     ss->handshake           = NULL;
     ss->firstHsDone         = PR_TRUE;
 
-    if (ss->sec.ci.sid->cached == never_cached &&
-	!ss->opt.noCache && ss->sec.cache && ss->ssl3.hs.cacheSID) {
+    if (ss->ssl3.hs.cacheSID) {
 	(*ss->sec.cache)(ss->sec.ci.sid);
+	ss->ssl3.hs.cacheSID = PR_FALSE;
     }
 
     ss->ssl3.hs.ws = idle_handshake;
 
     /* Do the handshake callback for sslv3 here, if we cannot false start. */
     if (ss->handshakeCallback != NULL && !ssl3_CanFalseStart(ss)) {
 	(ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
     }
@@ -8940,17 +8939,17 @@ ssl3_HandleHandshake(sslSocket *ss, sslB
  *
  * This function aquires and releases the SSL3Handshake Lock, holding the
  * lock around any calls to functions that handle records other than
  * Application Data records.
  */
 SECStatus
 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
 {
-const ssl3BulkCipherDef *cipher_def;
+    const ssl3BulkCipherDef *cipher_def;
     ssl3CipherSpec *     crSpec;
     SECStatus            rv;
     unsigned int         hashBytes		= MAX_MAC_LENGTH + 1;
     unsigned int         padding_length;
     PRBool               isTLS;
     PRBool               padIsBad               = PR_FALSE;
     SSL3ContentType      rType;
     SSL3Opaque           hash[MAX_MAC_LENGTH];
--- a/security/nss/lib/ssl/ssl3ext.c
+++ b/security/nss/lib/ssl/ssl3ext.c
@@ -36,17 +36,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /* TLS extension code moved here from ssl3ecc.c */
-/* $Id: ssl3ext.c,v 1.21 2012/02/15 21:52:08 kaie%kuix.de Exp $ */
+/* $Id: ssl3ext.c,v 1.22 2012/03/12 19:14:12 wtc%google.com Exp $ */
 
 #include "nssrenam.h"
 #include "nss.h"
 #include "ssl.h"
 #include "sslproto.h"
 #include "sslimpl.h"
 #include "pk11pub.h"
 #include "blapi.h"
@@ -587,42 +587,41 @@ ssl3_ValidateNextProtoNego(const unsigne
 static SECStatus
 ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type,
 				  SECItem *data)
 {
     SECStatus rv;
     unsigned char resultBuffer[255];
     SECItem result = { siBuffer, resultBuffer, 0 };
 
-    if (ss->firstHsDone) {
-	PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
-	return SECFailure;
-    }
+    PORT_Assert(!ss->firstHsDone);
 
     rv = ssl3_ValidateNextProtoNego(data->data, data->len);
     if (rv != SECSuccess)
 	return rv;
 
     /* ss->nextProtoCallback cannot normally be NULL if we negotiated the
      * extension. However, It is possible that an application erroneously
      * cleared the callback between the time we sent the ClientHello and now.
      */
     PORT_Assert(ss->nextProtoCallback != NULL);
     if (!ss->nextProtoCallback) {
+	/* XXX Use a better error code. This is an application error, not an
+	 * NSS bug. */
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return SECFailure;
     }
 
     rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
 			       result.data, &result.len, sizeof resultBuffer);
     if (rv != SECSuccess)
 	return rv;
     /* If the callback wrote more than allowed to |result| it has corrupted our
      * stack. */
-    if (result.len > sizeof result) {
+    if (result.len > sizeof resultBuffer) {
 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
 	return SECFailure;
     }
 
     SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
     return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &result);
 }
 
--- a/security/nss/lib/ssl/sslcon.c
+++ b/security/nss/lib/ssl/sslcon.c
@@ -32,17 +32,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: sslcon.c,v 1.45 2011/11/19 21:58:21 bsmith%mozilla.com Exp $ */
+/* $Id: sslcon.c,v 1.46 2012/03/01 01:58:22 wtc%google.com Exp $ */
 
 #include "nssrenam.h"
 #include "cert.h"
 #include "secitem.h"
 #include "sechash.h"
 #include "cryptohi.h"		/* for SGN_ funcs */
 #include "keyhi.h" 		/* for SECKEY_ high level functions. */
 #include "ssl.h"
@@ -1430,17 +1430,17 @@ ssl2_CreateSessionCypher(sslSocket *ss, 
     SECItem           writeKey;
 
     void *readcx = 0;
     void *writecx = 0;
     readKey.data = 0;
     writeKey.data = 0;
 
     PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) );
-    if((ss->sec.ci.sid == 0))
+    if (ss->sec.ci.sid == 0)
     	goto sec_loser;	/* don't crash if asserts are off */
 
     /* Trying to cut down on all these switch statements that should be tables.
      * So, test cipherType once, here, and then use tables below. 
      */
     switch (cipherType) {
     case SSL_CK_RC4_128_EXPORT40_WITH_MD5:
     case SSL_CK_RC4_128_WITH_MD5:
--- a/security/nss/lib/ssl/sslenum.c
+++ b/security/nss/lib/ssl/sslenum.c
@@ -34,32 +34,35 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: sslenum.c,v 1.17 2010/02/10 18:07:21 wtc%google.com Exp $ */
+/* $Id: sslenum.c,v 1.18 2012/03/06 00:26:31 wtc%google.com Exp $ */
 
 #include "ssl.h"
 #include "sslproto.h"
 
 /*
  * The ciphers are listed in the following order:
  * - stronger ciphers before weaker ciphers
  * - national ciphers before international ciphers
  * - faster ciphers before slower ciphers
  *
  * National ciphers such as Camellia are listed before international ciphers
  * such as AES and RC4 to allow servers that prefer Camellia to negotiate
  * Camellia without having to disable AES and RC4, which are needed for
  * interoperability with clients that don't yet implement Camellia.
  *
+ * The ordering of cipher suites in this table must match the ordering in
+ * the cipherSuites table in ssl3con.c.
+ *
  * If new ECC cipher suites are added, also update the ssl3CipherSuite arrays
  * in ssl3ecc.c.
  */
 const PRUint16 SSL_ImplementedCiphers[] = {
     /* 256-bit */
 #ifdef NSS_ENABLE_ECC
     TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
     TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
@@ -90,18 +93,18 @@ const PRUint16 SSL_ImplementedCiphers[] 
 #ifdef NSS_ENABLE_ECC
     TLS_ECDH_RSA_WITH_RC4_128_SHA,
     TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
     TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
     TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
 #endif /* NSS_ENABLE_ECC */
     TLS_RSA_WITH_SEED_CBC_SHA,
     TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
+    SSL_RSA_WITH_RC4_128_SHA,
     SSL_RSA_WITH_RC4_128_MD5,
-    SSL_RSA_WITH_RC4_128_SHA,
     TLS_RSA_WITH_AES_128_CBC_SHA,
 
     /* 112-bit 3DES */
 #ifdef NSS_ENABLE_ECC
     TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
     TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
 #endif /* NSS_ENABLE_ECC */
     SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
--- a/security/nss/lib/ssl/sslinfo.c
+++ b/security/nss/lib/ssl/sslinfo.c
@@ -29,17 +29,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: sslinfo.c,v 1.24 2010/09/02 01:12:57 wtc%google.com Exp $ */
+/* $Id: sslinfo.c,v 1.25 2012/03/06 00:26:31 wtc%google.com Exp $ */
 #include "ssl.h"
 #include "sslimpl.h"
 #include "sslproto.h"
 
 static const char *
 ssl_GetCompressionMethodName(SSLCompressionMethod compression)
 {
     switch (compression) {
@@ -175,18 +175,18 @@ static const SSLCipherSuiteInfo suiteInf
 
 {0,CS(TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, },
 {0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, },
 {0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA),          S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0, },
 {0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA),      S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, },
 {0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA),      S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, },
 {0,CS(TLS_RSA_WITH_SEED_CBC_SHA),             S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0, },
 {0,CS(TLS_RSA_WITH_CAMELLIA_128_CBC_SHA),     S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, },
+{0,CS(SSL_RSA_WITH_RC4_128_SHA),              S_RSA, K_RSA, C_RC4, B_128, M_SHA, 0, 0, 0, },
 {0,CS(SSL_RSA_WITH_RC4_128_MD5),              S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0, },
-{0,CS(SSL_RSA_WITH_RC4_128_SHA),              S_RSA, K_RSA, C_RC4, B_128, M_SHA, 0, 0, 0, },
 {0,CS(TLS_RSA_WITH_AES_128_CBC_SHA),          S_RSA, K_RSA, C_AES, B_128, M_SHA, 1, 0, 0, },
 
 {0,CS(SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA),     S_RSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0, },
 {0,CS(SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA),     S_DSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0, },
 {0,CS(SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA),    S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 1, },
 {0,CS(SSL_RSA_WITH_3DES_EDE_CBC_SHA),         S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 0, },
 
 {0,CS(SSL_DHE_RSA_WITH_DES_CBC_SHA),          S_RSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0, },
--- a/security/nss/lib/ssl/sslsecur.c
+++ b/security/nss/lib/ssl/sslsecur.c
@@ -32,17 +32,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: sslsecur.c,v 1.57 2012/02/15 21:52:08 kaie%kuix.de Exp $ */
+/* $Id: sslsecur.c,v 1.58 2012/03/01 18:36:35 kaie%kuix.de Exp $ */
 #include "cert.h"
 #include "secitem.h"
 #include "keyhi.h"
 #include "ssl.h"
 #include "sslimpl.h"
 #include "sslproto.h"
 #include "secoid.h"	/* for SECOID_GetALgorithmTag */
 #include "pk11func.h"	/* for PK11_GenerateRandom */
@@ -1398,17 +1398,17 @@ SSL_InvalidateSession(PRFileDesc *fd)
 {
     sslSocket *   ss = ssl_FindSocket(fd);
     SECStatus     rv = SECFailure;
 
     if (ss) {
 	ssl_Get1stHandshakeLock(ss);
 	ssl_GetSSL3HandshakeLock(ss);
 
-	if (ss->sec.ci.sid) {
+	if (ss->sec.ci.sid && ss->sec.uncache) {
 	    ss->sec.uncache(ss->sec.ci.sid);
 	    rv = SECSuccess;
 	}
 
 	ssl_ReleaseSSL3HandshakeLock(ss);
 	ssl_Release1stHandshakeLock(ss);
     }
     return rv;
--- a/security/nss/lib/ssl/sslsock.c
+++ b/security/nss/lib/ssl/sslsock.c
@@ -35,17 +35,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: sslsock.c,v 1.82 2012/02/15 21:52:08 kaie%kuix.de Exp $ */
+/* $Id: sslsock.c,v 1.82.2.1 2012/03/31 23:16:38 wtc%google.com Exp $ */
 #include "seccomon.h"
 #include "cert.h"
 #include "keyhi.h"
 #include "ssl.h"
 #include "sslimpl.h"
 #include "sslproto.h"
 #include "nspr.h"
 #include "private/pprio.h"
@@ -1298,17 +1298,17 @@ SSL_SetNextProtoCallback(PRFileDesc *fd,
     ssl_GetSSL3HandshakeLock(ss);
     ss->nextProtoCallback = callback;
     ss->nextProtoArg = arg;
     ssl_ReleaseSSL3HandshakeLock(ss);
 
     return SECSuccess;
 }
 
-/* NextProtoStandardCallback is set as an NPN callback for the case when
+/* ssl_NextProtoNegoCallback is set as an NPN callback for the case when
  * SSL_SetNextProtoNego is used.
  */
 static SECStatus
 ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd,
 			  const unsigned char *protos, unsigned int protos_len,
 			  unsigned char *protoOut, unsigned int *protoOutLen,
 			  unsigned int protoMaxLen)
 {
@@ -1344,22 +1344,22 @@ ssl_NextProtoNegoCallback(void *arg, PRF
 	i += 1 + (unsigned int)protos[i];
     }
 
 pick_first:
     ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP;
     result = ss->opt.nextProtoNego.data;
 
 found:
-    *protoOutLen = result[0];
     if (protoMaxLen < result[0]) {
 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
 	return SECFailure;
     }
     memcpy(protoOut, result + 1, result[0]);
+    *protoOutLen = result[0];
     return SECSuccess;
 }
 
 SECStatus
 SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
 		     unsigned int length)
 {
     sslSocket *ss;
@@ -1403,23 +1403,22 @@ SSL_GetNextProto(PRFileDesc *fd, SSLNext
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 
     *state = ss->ssl3.nextProtoState;
 
     if (ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
 	ss->ssl3.nextProto.data) {
-	*bufLen = ss->ssl3.nextProto.len;
-	if (*bufLen > bufLenMax) {
+	if (ss->ssl3.nextProto.len > bufLenMax) {
 	    PORT_SetError(SEC_ERROR_OUTPUT_LEN);
-	    *bufLen = 0;
 	    return SECFailure;
 	}
 	PORT_Memcpy(buf, ss->ssl3.nextProto.data, ss->ssl3.nextProto.len);
+	*bufLen = ss->ssl3.nextProto.len;
     } else {
 	*bufLen = 0;
     }
 
     return SECSuccess;
 }
 
 PRFileDesc *
--- a/security/nss/lib/util/ciferfam.h
+++ b/security/nss/lib/util/ciferfam.h
@@ -33,17 +33,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * ciferfam.h - cipher familie IDs used for configuring ciphers for export
  *              control
  *
- * $Id: ciferfam.h,v 1.4 2007/10/12 01:44:50 julien.pierre.boogz%sun.com Exp $
+ * $Id: ciferfam.h,v 1.5 2012/03/01 18:33:11 kaie%kuix.de Exp $
  */
 
 #ifndef _CIFERFAM_H_
 #define _CIFERFAM_H_
 
 #include "utilrename.h"
 /* Cipher Suite "Families" */
 #define CIPHER_FAMILY_PKCS12			"PKCS12"
@@ -67,16 +67,17 @@
  * needs to be made smarter at the same time.
  */
 #define	SMIME_RC2_CBC_40		(CIPHER_FAMILYID_SMIME | 0001)
 #define	SMIME_RC2_CBC_64		(CIPHER_FAMILYID_SMIME | 0002)
 #define	SMIME_RC2_CBC_128		(CIPHER_FAMILYID_SMIME | 0003)
 #define	SMIME_DES_CBC_56		(CIPHER_FAMILYID_SMIME | 0011)
 #define	SMIME_DES_EDE3_168		(CIPHER_FAMILYID_SMIME | 0012)
 #define	SMIME_AES_CBC_128		(CIPHER_FAMILYID_SMIME | 0013)
+#define	SMIME_AES_CBC_256		(CIPHER_FAMILYID_SMIME | 0014)
 #define	SMIME_RC5PAD_64_16_40		(CIPHER_FAMILYID_SMIME | 0021)
 #define	SMIME_RC5PAD_64_16_64		(CIPHER_FAMILYID_SMIME | 0022)
 #define	SMIME_RC5PAD_64_16_128		(CIPHER_FAMILYID_SMIME | 0023)
 #define	SMIME_FORTEZZA			(CIPHER_FAMILYID_SMIME | 0031)
 
 /* PKCS12 "Cipher Suites" */
 
 #define	PKCS12_RC2_CBC_40		(CIPHER_FAMILYID_PKCS12 | 0001)
--- a/security/nss/lib/util/nssutil.h
+++ b/security/nss/lib/util/nssutil.h
@@ -46,20 +46,20 @@
 
 /*
  * NSS utilities's major version, minor version, patch level, build number,
  * and whether this is a beta release.
  *
  * The format of the version string should be
  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <Beta>]"
  */
-#define NSSUTIL_VERSION  "3.13.3.0"
+#define NSSUTIL_VERSION  "3.13.4.0"
 #define NSSUTIL_VMAJOR   3
 #define NSSUTIL_VMINOR   13
-#define NSSUTIL_VPATCH   3
+#define NSSUTIL_VPATCH   4
 #define NSSUTIL_VBUILD   0
 #define NSSUTIL_BETA     PR_FALSE
 
 SEC_BEGIN_PROTOS
 
 /*
  * Returns a const string of the UTIL library version.
  */
--- a/security/nss/lib/util/quickder.c
+++ b/security/nss/lib/util/quickder.c
@@ -810,65 +810,82 @@ static SECStatus DecodeItem(void* dest,
         }
         else
         {
             /* handle all other types as "save" */
             /* we should only get here for primitive universal types */
             SECItem newtemp = temp;
             rv = GetItem(&newtemp, &temp, PR_FALSE);
             save = PR_TRUE;
-            if ((SECSuccess == rv) && SEC_ASN1_UNIVERSAL == (kind & SEC_ASN1_CLASS_MASK))
-            switch (kind & SEC_ASN1_TAGNUM_MASK)
+            if ((SECSuccess == rv) &&
+                SEC_ASN1_UNIVERSAL == (kind & SEC_ASN1_CLASS_MASK))
             {
-            /* special cases of primitive types */
-            case SEC_ASN1_INTEGER:
+                unsigned long tagnum = kind & SEC_ASN1_TAGNUM_MASK;
+                if ( temp.len == 0 && (tagnum == SEC_ASN1_BOOLEAN ||
+                                       tagnum == SEC_ASN1_INTEGER ||
+                                       tagnum == SEC_ASN1_BIT_STRING ||
+                                       tagnum == SEC_ASN1_OBJECT_ID ||
+                                       tagnum == SEC_ASN1_ENUMERATED ||
+                                       tagnum == SEC_ASN1_UTC_TIME ||
+                                       tagnum == SEC_ASN1_GENERALIZED_TIME) )
                 {
-                    /* remove leading zeroes if the caller requested siUnsignedInteger
-                       This is to allow RSA key operations to work */
-                    SECItem* destItem = (SECItem*) ((char*)dest + templateEntry->offset);
-                    if (destItem && (siUnsignedInteger == destItem->type))
+                    /* these types MUST have at least one content octet */
+                    PORT_SetError(SEC_ERROR_BAD_DER);
+                    rv = SECFailure;
+                }
+                else
+                switch (tagnum)
+                {
+                /* special cases of primitive types */
+                case SEC_ASN1_INTEGER:
                     {
-                        while (temp.len > 1 && temp.data[0] == 0)
-                        {              /* leading 0 */
-                            temp.data++;
-                            temp.len--;
+                        /* remove leading zeroes if the caller requested
+                           siUnsignedInteger
+                           This is to allow RSA key operations to work */
+                        SECItem* destItem = (SECItem*) ((char*)dest +
+                                            templateEntry->offset);
+                        if (destItem && (siUnsignedInteger == destItem->type))
+                        {
+                            while (temp.len > 1 && temp.data[0] == 0)
+                            {              /* leading 0 */
+                                temp.data++;
+                                temp.len--;
+                            }
                         }
+                        break;
                     }
-                    break;
-                }
 
-            case SEC_ASN1_BIT_STRING:
-                {
-                    /* change the length in the SECItem to be the number of bits */
-                    if (temp.len && temp.data)
+                case SEC_ASN1_BIT_STRING:
                     {
-                        temp.len = (temp.len-1)*8 - ((*(unsigned char*)temp.data) & 0x7);
-                        temp.data = (unsigned char*)(temp.data+1);
+                        /* change the length in the SECItem to be the number
+                           of bits */
+                        temp.len = (temp.len-1)*8 - (temp.data[0] & 0x7);
+                        temp.data++;
+                        break;
                     }
-                    break;
-                }
 
-            default:
-                {
-                    break;
+                default:
+                    {
+                        break;
+                    }
                 }
             }
         }
     }
 
     if ((SECSuccess == rv) && (PR_TRUE == save))
     {
         SECItem* destItem = (SECItem*) ((char*)dest + templateEntry->offset);
         if (destItem)
         {
             /* we leave the type alone in the destination SECItem.
                If part of the destination was allocated by the decoder, in
                cases of POINTER, SET OF and SEQUENCE OF, then type is set to
                siBuffer due to the use of PORT_ArenaZAlloc*/
-            destItem->data = temp.data;
+            destItem->data = temp.len ? temp.data : NULL;
             destItem->len = temp.len;
         }
         else
         {
             PORT_SetError(SEC_ERROR_INVALID_ARGS);
             rv = SECFailure;
         }
     }
--- a/security/nss/lib/util/secitem.c
+++ b/security/nss/lib/util/secitem.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Support routines for SECItem data structure.
  *
- * $Id: secitem.c,v 1.16 2011/07/22 21:22:40 wtc%google.com Exp $
+ * $Id: secitem.c,v 1.17 2012/03/23 03:12:16 wtc%google.com Exp $
  */
 
 #include "seccomon.h"
 #include "secitem.h"
 #include "base64.h"
 #include "secerr.h"
 
 SECItem *
@@ -148,30 +148,30 @@ SECITEM_ReallocItem(PRArenaPool *arena, 
 
     return SECSuccess;
 }
 
 SECComparison
 SECITEM_CompareItem(const SECItem *a, const SECItem *b)
 {
     unsigned m;
-    SECComparison rv;
+    int rv;
 
     if (a == b)
     	return SECEqual;
     if (!a || !a->len || !a->data) 
         return (!b || !b->len || !b->data) ? SECEqual : SECLessThan;
     if (!b || !b->len || !b->data) 
     	return SECGreaterThan;
 
     m = ( ( a->len < b->len ) ? a->len : b->len );
     
-    rv = (SECComparison) PORT_Memcmp(a->data, b->data, m);
+    rv = PORT_Memcmp(a->data, b->data, m);
     if (rv) {
-	return rv;
+	return rv < 0 ? SECLessThan : SECGreaterThan;
     }
     if (a->len < b->len) {
 	return SECLessThan;
     }
     if (a->len == b->len) {
 	return SECEqual;
     }
     return SECGreaterThan;