Bug 1245053, landing NSS_3_23_BETA5, r=mt
authorKai Engert <kaie@kuix.de>
Tue, 23 Feb 2016 00:50:19 +0100
changeset 321423 361020c5f9545e1d43729351c2cb35a3a63ecda2
parent 321422 e6abb35f9fb9339241aca3a8ec255b16636d80d7
child 321424 3858cae0e82229f747487d651c5d986fa1f6213f
push id5913
push userjlund@mozilla.com
push dateMon, 25 Apr 2016 16:57:49 +0000
treeherdermozilla-beta@dcaf0a6fa115 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmt
bugs1245053
milestone47.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1245053, landing NSS_3_23_BETA5, r=mt
security/nss/TAG-INFO
security/nss/circle.yml
security/nss/cmd/bltest/blapitest.c
security/nss/cmd/bltest/tests/chacha20_poly1305/aad0
security/nss/cmd/bltest/tests/chacha20_poly1305/aad1
security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext0
security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext1
security/nss/cmd/bltest/tests/chacha20_poly1305/iv0
security/nss/cmd/bltest/tests/chacha20_poly1305/iv1
security/nss/cmd/bltest/tests/chacha20_poly1305/key0
security/nss/cmd/bltest/tests/chacha20_poly1305/key1
security/nss/cmd/bltest/tests/chacha20_poly1305/numtests
security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext0
security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext1
security/nss/cmd/ssltap/ssltap.c
security/nss/coreconf/Werror.mk
security/nss/coreconf/config.mk
security/nss/coreconf/coreconf.dep
security/nss/external_tests/pk11_gtest/manifest.mn
security/nss/external_tests/pk11_gtest/pk11_chacha20poly1305_unittest.cc
security/nss/external_tests/ssl_gtest/libssl_internals.c
security/nss/external_tests/ssl_gtest/libssl_internals.h
security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc
security/nss/external_tests/ssl_gtest/tls_agent.cc
security/nss/lib/freebl/Makefile
security/nss/lib/freebl/blapi.h
security/nss/lib/freebl/blapit.h
security/nss/lib/freebl/chacha20.c
security/nss/lib/freebl/chacha20.h
security/nss/lib/freebl/chacha20_vec.c
security/nss/lib/freebl/chacha20poly1305.c
security/nss/lib/freebl/chacha20poly1305.h
security/nss/lib/freebl/intel-aes.s
security/nss/lib/freebl/ldvector.c
security/nss/lib/freebl/loader.c
security/nss/lib/freebl/loader.h
security/nss/lib/freebl/manifest.mn
security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c
security/nss/lib/freebl/poly1305.c
security/nss/lib/freebl/poly1305.h
security/nss/lib/pk11wrap/pk11mech.c
security/nss/lib/pk11wrap/pk11pars.c
security/nss/lib/pkcs7/p7local.c
security/nss/lib/softoken/pkcs11.c
security/nss/lib/softoken/pkcs11c.c
security/nss/lib/softoken/pkcs11i.h
security/nss/lib/ssl/SSLerrs.h
security/nss/lib/ssl/authcert.c
security/nss/lib/ssl/cmpcert.c
security/nss/lib/ssl/derive.c
security/nss/lib/ssl/dtlscon.c
security/nss/lib/ssl/notes.txt
security/nss/lib/ssl/os2_err.c
security/nss/lib/ssl/os2_err.h
security/nss/lib/ssl/preenc.h
security/nss/lib/ssl/prelib.c
security/nss/lib/ssl/ssl.def
security/nss/lib/ssl/ssl.h
security/nss/lib/ssl/ssl3con.c
security/nss/lib/ssl/ssl3ecc.c
security/nss/lib/ssl/ssl3ext.c
security/nss/lib/ssl/ssl3gthr.c
security/nss/lib/ssl/ssl3prot.h
security/nss/lib/ssl/sslauth.c
security/nss/lib/ssl/sslcon.c
security/nss/lib/ssl/ssldef.c
security/nss/lib/ssl/sslenum.c
security/nss/lib/ssl/sslerr.c
security/nss/lib/ssl/sslerr.h
security/nss/lib/ssl/sslerrstrs.c
security/nss/lib/ssl/sslgathr.c
security/nss/lib/ssl/sslimpl.h
security/nss/lib/ssl/sslinfo.c
security/nss/lib/ssl/sslinit.c
security/nss/lib/ssl/sslmutex.c
security/nss/lib/ssl/sslmutex.h
security/nss/lib/ssl/sslnonce.c
security/nss/lib/ssl/sslproto.h
security/nss/lib/ssl/sslreveal.c
security/nss/lib/ssl/sslsecur.c
security/nss/lib/ssl/sslsnce.c
security/nss/lib/ssl/sslsock.c
security/nss/lib/ssl/sslt.h
security/nss/lib/ssl/ssltrace.c
security/nss/lib/ssl/tls13con.c
security/nss/lib/ssl/tls13con.h
security/nss/lib/ssl/tls13hkdf.c
security/nss/lib/ssl/tls13hkdf.h
security/nss/lib/ssl/unix_err.c
security/nss/lib/ssl/unix_err.h
security/nss/lib/ssl/win32err.c
security/nss/lib/ssl/win32err.h
security/nss/lib/util/pkcs11n.h
security/nss/lib/util/secasn1d.c
security/nss/lib/util/secoid.c
security/nss/lib/util/secoidt.h
security/nss/lib/util/utf8.c
security/nss/tests/cipher/cipher.txt
security/nss/tests/ssl/ssl.sh
security/nss/tests/ssl/sslcov.txt
--- a/security/nss/TAG-INFO
+++ b/security/nss/TAG-INFO
@@ -1,1 +1,1 @@
-NSS_3_23_BETA4
+NSS_3_23_BETA5
--- a/security/nss/circle.yml
+++ b/security/nss/circle.yml
@@ -1,20 +1,19 @@
 checkout:
     post:
         - cd ..; hg clone https://hg.mozilla.org/projects/nspr
 
 test:
     override:
         - make nss_build_all
-        - cd tests; NSS_TESTS=ssl_gtests NSS_CYCLES=standard ./all.sh
+        - cd tests; NSS_TESTS="ssl_gtests pk11_gtests der_gtests" NSS_CYCLES=standard ./all.sh
         - BUILD_OPT=1 make nss_build_all
-        - cd tests; BUILD_OPT=1 NSS_TESTS=ssl_gtests NSS_CYCLES=standard ./all.sh
+        - cd tests; BUILD_OPT=1 NSS_TESTS="ssl_gtests pk11_gtests der_gtests" NSS_CYCLES=standard ./all.sh
 
 machine:
     environment:
         { USE_64: 1,
           NSS_ENABLE_TLS_1_3: 1,
-          NSS_BUILD_GTESTS: 1,
         }
     hosts:
 
 
--- a/security/nss/cmd/bltest/blapitest.c
+++ b/security/nss/cmd/bltest/blapitest.c
@@ -608,16 +608,27 @@ typedef struct
 
 typedef SECStatus (* bltestSymmCipherFn)(void *cx,
 					 unsigned char *output,
 					 unsigned int *outputLen,
 					 unsigned int maxOutputLen,
 					 const unsigned char *input,
 					 unsigned int inputLen);
 
+typedef SECStatus (* bltestAEADFn)(void *cx,
+                                   unsigned char *output,
+                                   unsigned int *outputLen,
+                                   unsigned int maxOutputLen,
+                                   const unsigned char *input,
+                                   unsigned int inputLen,
+                                   const unsigned char *nonce,
+                                   unsigned int nonceLen,
+                                   const unsigned char *ad,
+                                   unsigned int adLen);
+
 typedef SECStatus (* bltestPubKeyCipherFn)(void *key,
 					   SECItem *output,
 					   const SECItem *input);
 
 typedef SECStatus (* bltestHashCipherFn)(unsigned char *dest,
 					 const unsigned char *src,
 					 PRUint32 src_length);
 
@@ -641,16 +652,17 @@ typedef enum {
     bltestAES_CBC,        /* .                     */
     bltestAES_CTS,        /* .                     */
     bltestAES_CTR,        /* .                     */
     bltestAES_GCM,        /* .                     */
     bltestCAMELLIA_ECB,   /* .                     */
     bltestCAMELLIA_CBC,   /* .                     */
     bltestSEED_ECB,       /* SEED algorithm	   */
     bltestSEED_CBC,       /* SEED algorithm	   */
+    bltestCHACHA20,       /* ChaCha20 + Poly1305   */
     bltestRSA,            /* Public Key Ciphers    */
     bltestRSA_OAEP,       /* . (Public Key Enc.)   */
     bltestRSA_PSS,        /* . (Public Key Sig.)   */
 #ifndef NSS_DISABLE_ECC
     bltestECDSA,          /* . (Public Key Sig.)   */
 #endif
     bltestDSA,            /* . (Public Key Sig.)   */
     bltestMD2,		  /* Hash algorithms	   */
@@ -680,16 +692,17 @@ static char *mode_strings[] =
     "aes_cbc",
     "aes_cts",
     "aes_ctr",
     "aes_gcm",
     "camellia_ecb",
     "camellia_cbc",
     "seed_ecb",
     "seed_cbc",
+    "chacha20_poly1305",
     "rsa",
     "rsa_oaep",
     "rsa_pss",
 #ifndef NSS_DISABLE_ECC
     "ecdsa",
 #endif
     /*"pqg",*/
     "dsa",
@@ -800,16 +813,17 @@ struct  bltestCipherInfoStr {
     bltestIO output;
     /* Cipher-specific parameters */
     bltestParams params;
     /* Cipher mode */
     bltestCipherMode  mode;
     /* Cipher function (encrypt/decrypt/sign/verify/hash) */
     union {
 	bltestSymmCipherFn   symmkeyCipher;
+	bltestAEADFn         aeadCipher;
 	bltestPubKeyCipherFn pubkeyCipher;
 	bltestHashCipherFn   hashCipher;
     } cipher;
     /* performance testing */
     int   repetitionsToPerfom;
     int   seconds;
     int	  repetitions;
     int   cxreps;
@@ -822,34 +836,53 @@ is_symmkeyCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestDES_ECB && mode <= bltestSEED_CBC)
 	return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
+is_aeadCipher(bltestCipherMode mode)
+{
+    /* change as needed! */
+    switch (mode) {
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
+}
+
+PRBool
 is_authCipher(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestAES_GCM)
-	return PR_TRUE;
-    return PR_FALSE;
+    switch (mode) {
+	case bltestAES_GCM:
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
 }
 
 
 PRBool
 is_singleShotCipher(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestAES_GCM)
-	return PR_TRUE;
-    if (mode == bltestAES_CTS)
-	return PR_TRUE;
-    return PR_FALSE;
+    switch (mode) {
+	case bltestAES_GCM:
+	case bltestAES_CTS:
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
 }
 
 PRBool
 is_pubkeyCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestRSA && mode <= bltestDSA)
 	return PR_TRUE;
@@ -873,26 +906,34 @@ is_sigCipher(bltestCipherMode mode)
        return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
 cipher_requires_IV(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestDES_CBC || mode == bltestDES_EDE_CBC ||
-	mode == bltestRC2_CBC || 
+    switch (mode) {
+	case bltestDES_CBC:
+	case bltestDES_EDE_CBC:
+	case bltestRC2_CBC:
 #ifdef NSS_SOFTOKEN_DOES_RC5
-	mode == bltestRC5_CBC ||
+	case bltestRC5_CBC:
 #endif
-	mode == bltestAES_CBC || mode == bltestAES_CTS || 
-	mode == bltestAES_CTR || mode == bltestAES_GCM ||
-	mode == bltestCAMELLIA_CBC || mode == bltestSEED_CBC)
-	return PR_TRUE;
-    return PR_FALSE;
+	case bltestAES_CBC:
+	case bltestAES_CTS:
+	case bltestAES_CTR:
+	case bltestAES_GCM:
+	case bltestCAMELLIA_CBC:
+	case bltestSEED_CBC:
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
 }
 
 SECStatus finishIO(bltestIO *output, PRFileDesc *file);
 
 SECStatus
 setupIO(PLArenaPool *arena, bltestIO *input, PRFileDesc *file,
 	char *str, int numBytes)
 {
@@ -1122,16 +1163,40 @@ aes_Decrypt(void *cx, unsigned char *out
             unsigned int maxOutputLen, const unsigned char *input,
             unsigned int inputLen)
 {
     return AES_Decrypt((AESContext *)cx, output, outputLen, maxOutputLen,
                        input, inputLen);
 }
 
 SECStatus
+chacha20_poly1305_Encrypt(void *cx, unsigned char *output,
+                         unsigned int *outputLen, unsigned int maxOutputLen,
+                         const unsigned char *input, unsigned int inputLen,
+                         const unsigned char *nonce, unsigned int nonceLen,
+                         const unsigned char *ad, unsigned int adLen)
+{
+    return ChaCha20Poly1305_Seal((ChaCha20Poly1305Context *)cx, output,
+                                 outputLen, maxOutputLen, input, inputLen,
+                                 nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
+chacha20_poly1305_Decrypt(void *cx, unsigned char *output,
+                         unsigned int *outputLen, unsigned int maxOutputLen,
+                         const unsigned char *input, unsigned int inputLen,
+                         const unsigned char *nonce, unsigned int nonceLen,
+                         const unsigned char *ad, unsigned int adLen)
+{
+    return ChaCha20Poly1305_Open((ChaCha20Poly1305Context *)cx, output,
+                                 outputLen, maxOutputLen, input, inputLen,
+                                 nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
 camellia_Encrypt(void *cx, unsigned char *output, unsigned int *outputLen,
 		 unsigned int maxOutputLen, const unsigned char *input,
 		 unsigned int inputLen)
 {
     return Camellia_Encrypt((CamelliaContext *)cx, output, outputLen,
 			    maxOutputLen,
 			    input, inputLen);
 }
@@ -1571,16 +1636,31 @@ bltest_seed_init(bltestCipherInfo *ciphe
 	cipherInfo->cipher.symmkeyCipher = seed_Encrypt;
     else
 	cipherInfo->cipher.symmkeyCipher = seed_Decrypt;
 	
 	return SECSuccess;
 }
 
 SECStatus
+bltest_chacha20_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
+{
+    const unsigned int tagLen = 16;
+    const bltestSymmKeyParams *sk = &cipherInfo->params.sk;
+    cipherInfo->cx = ChaCha20Poly1305_CreateContext(sk->key.buf.data,
+                                                    sk->key.buf.len, tagLen);
+
+    if (encrypt)
+	cipherInfo->cipher.aeadCipher = chacha20_poly1305_Encrypt;
+    else
+	cipherInfo->cipher.aeadCipher = chacha20_poly1305_Decrypt;
+    return SECSuccess;
+}
+
+SECStatus
 bltest_rsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     int i;
     RSAPrivateKey **dummyKey;
     RSAPrivateKey *privKey;
     RSAPublicKey *pubKey;
     PRIntervalTime time1, time2;
 
@@ -2221,16 +2301,21 @@ cipherInit(bltestCipherInfo *cipherInfo,
 	return bltest_camellia_init(cipherInfo, encrypt);
 	break;
     case bltestSEED_ECB:
     case bltestSEED_CBC:
 	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
 			  cipherInfo->input.pBuf.len);
 	return bltest_seed_init(cipherInfo, encrypt);
 	break;
+    case bltestCHACHA20:
+	outlen = cipherInfo->input.pBuf.len + (encrypt ? 16 : 0);
+	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen);
+	return bltest_chacha20_init(cipherInfo, encrypt);
+	break;
     case bltestRSA:
     case bltestRSA_OAEP:
     case bltestRSA_PSS:
 	if (encrypt || cipherInfo->mode != bltestRSA_PSS) {
 		/* Don't allocate a buffer for PSS in verify mode, as no actual
 		 * output is produced. */
 		SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
 		                  RSA_MAX_MODULUS_BITS / 8);
@@ -2371,16 +2456,65 @@ cipherDoOp(bltestCipherInfo *cipherInfo)
                         cipherInfo->cx, dummyOut, &len, maxLen,
                         cipherInfo->input.pBuf.data,
                         cipherInfo->input.pBuf.len);
                 }
                 cipherInfo->repetitions += j;
             }
         }
         TIMEFINISH(cipherInfo->optime, 1.0);
+    } else if (is_aeadCipher(cipherInfo->mode)) {
+        const unsigned char *input = cipherInfo->input.pBuf.data;
+        unsigned int inputLen = cipherInfo->input.pBuf.len;
+        unsigned char *output = cipherInfo->output.pBuf.data;
+        unsigned int outputLen;
+        bltestSymmKeyParams *sk = &cipherInfo->params.sk;
+        bltestAuthSymmKeyParams *ask = &cipherInfo->params.ask;
+
+        TIMESTART();
+        rv = (*cipherInfo->cipher.aeadCipher)(
+                cipherInfo->cx,
+                output, &outputLen, maxLen,
+                input, inputLen,
+                sk->iv.buf.data, sk->iv.buf.len,
+                ask->aad.buf.data, ask->aad.buf.len);
+        CHECKERROR(rv, __LINE__);
+        cipherInfo->output.pBuf.len = outputLen;
+        TIMEFINISH(cipherInfo->optime, 1.0);
+
+        cipherInfo->repetitions = 0;
+        if (cipherInfo->repetitionsToPerfom != 0) {
+            TIMESTART();
+            for (i=0; i<cipherInfo->repetitionsToPerfom; i++,
+                     cipherInfo->repetitions++) {
+                rv = (*cipherInfo->cipher.aeadCipher)(
+                        cipherInfo->cx,
+                        output, &outputLen, maxLen,
+                        input, inputLen,
+                        sk->iv.buf.data, sk->iv.buf.len,
+                        ask->aad.buf.data, ask->aad.buf.len);
+                CHECKERROR(rv, __LINE__);
+            }
+        } else {
+            int opsBetweenChecks = 0;
+            TIMEMARK(cipherInfo->seconds);
+            while (! (TIMETOFINISH())) {
+                int j = 0;
+                for (;j < opsBetweenChecks;j++) {
+                    (*cipherInfo->cipher.aeadCipher)(
+                            cipherInfo->cx,
+                            output, &outputLen, maxLen,
+                            input, inputLen,
+                            sk->iv.buf.data, sk->iv.buf.len,
+                            ask->aad.buf.data, ask->aad.buf.len);
+                }
+                cipherInfo->repetitions += j;
+            }
+        }
+        TIMEFINISH(cipherInfo->optime, 1.0);
     } else if (is_pubkeyCipher(cipherInfo->mode)) {
         TIMESTART();
         rv = (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx,
                                                 &cipherInfo->output.pBuf,
                                                 &cipherInfo->input.pBuf);
         TIMEFINISH(cipherInfo->optime, 1.0);
         CHECKERROR(rv, __LINE__);
         cipherInfo->repetitions = 0;
@@ -2472,16 +2606,20 @@ cipherFinish(bltestCipherInfo *cipherInf
     case bltestCAMELLIA_ECB:
     case bltestCAMELLIA_CBC:
 	Camellia_DestroyContext((CamelliaContext *)cipherInfo->cx, PR_TRUE);
 	break;
     case bltestSEED_ECB:
     case bltestSEED_CBC:
 	SEED_DestroyContext((SEEDContext *)cipherInfo->cx, PR_TRUE);
 	break;
+    case bltestCHACHA20:
+	ChaCha20Poly1305_DestroyContext((ChaCha20Poly1305Context *)
+                                        cipherInfo->cx, PR_TRUE);
+	break;
     case bltestRC2_ECB:
     case bltestRC2_CBC:
 	RC2_DestroyContext((RC2Context *)cipherInfo->cx, PR_TRUE);
 	break;
     case bltestRC4:
 	RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE);
 	break;
 #ifdef NSS_SOFTOKEN_DOES_RC5
@@ -2803,16 +2941,17 @@ get_params(PLArenaPool *arena, bltestPar
 
 #ifdef NSS_SOFTOKEN_DOES_RC5
     FILE *file;
     char *mark, *param, *val;
     int index = 0;
 #endif
     switch (mode) {
     case bltestAES_GCM:
+    case bltestCHACHA20:
 	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "aad", j);
 	load_file_data(arena, &params->ask.aad, filename, bltestBinary);
     case bltestDES_CBC:
     case bltestDES_EDE_CBC:
     case bltestRC2_CBC:
     case bltestAES_CBC:
     case bltestAES_CTS:
     case bltestAES_CTR:
@@ -3748,17 +3887,18 @@ print_usage:
             goto exit_point;
         }
         cipherInfo->arena = arena;
         params = &cipherInfo->params;
         
         /* Set up an encryption key. */
         keysize = 0;
         file = NULL;
-        if (is_symmkeyCipher(cipherInfo->mode)) {
+        if (is_symmkeyCipher(cipherInfo->mode) ||
+	    is_aeadCipher(cipherInfo->mode)) {
             char *keystr = NULL;  /* if key is on command line */
             if (bltest.options[opt_Key].activated) {
                 if (bltest.options[opt_CmdLine].activated) {
                     keystr = bltest.options[opt_Key].arg;
                 } else {
                     file = PR_Open(bltest.options[opt_Key].arg,
                                    PR_RDONLY, 00660);
                 }
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/aad0
@@ -0,0 +1,1 @@
+PQRSΐΑΒΓΔΕΖΗ
\ No newline at end of file
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..91287a1a2e38397b4bd5081fadab286c1fbd971a
GIT binary patch
literal 12
Pc%1ue+|kAW27VI(7}Nt4
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext0
@@ -0,0 +1,1 @@
+0xqNNGSOYNt7hq+8U+9+wqSt7VEpbgj+qeK1pzbuYtY9vqRejKlnEoL6+2naknKLGnHeCp4GCykF1qW2fs07NpLdvX8td4uMmAOu4ygJG1j6syTk+tZ1lFWFgItIMde8P/Te8I5Lep3ldtJlhs7GS2EWGuELWU8J4mp+kC7L0GAGkQ==
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext1
@@ -0,0 +1,1 @@
+ZKCGFXWGGvRg8GLHm+ZDvV6AXP00XPOJ8QhnCsdsjLJMbPwYdV1D7qCe6U44LSawvbe3PDIbAQDU8Dt/NViUzzMvgw5xC5fOmMioSr0LlIEUrRduAI0zvWD5grH/N8hVl5egbvTw72HBhjJOKzUGODYGkHtqfAKw+fYVe1PIZ+S5Fmx2e4BNRqWbUhbN56TpkEDFpAQzIl7igqGwoGxSPq9FNNf4P6EVWwBHcYy8VGoNBysEs1ZO6htCInP1SCcaC7IxYFP6dpkZVevWMVlDTs67TkZtrloQc6ZydicJehBJ5hfZHTYQlPpo8P93mHEwMFvqui7aBN+Ze3FNbG8sKaatXLQCKwJwm+6tnWeJDLsiOSM2/qGFHzg=
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..7e8a175046dde8a759e54a088eac41101ebd5782
GIT binary patch
literal 12
Tc${NrU|?`?baHlab#n&*3A6$v
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..7c8b98f50daf0ac0902bf4c98da4c5f6a91ca994
GIT binary patch
literal 12
Tc${NkU|?WmVrF4wW9I+>0E7S~
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/key0
@@ -0,0 +1,1 @@
+€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/key1
@@ -0,0 +1,1 @@
+’@₯λUӊσ3ˆ†φ΅πG9Α@+€	Κ\Ό puΐ
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/numtests
@@ -0,0 +1,1 @@
+2
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext0
@@ -0,0 +1,1 @@
+Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext1
@@ -0,0 +1,1 @@
+Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as /β€œwork in progress./”
\ No newline at end of file
--- a/security/nss/cmd/ssltap/ssltap.c
+++ b/security/nss/cmd/ssltap/ssltap.c
@@ -438,16 +438,20 @@ const char * V2CipherString(int cs_int)
   case 0x00C027:    cs_str = "TLS/ECDHE-RSA/AES128-CBC/SHA256"; break;
   case 0x00C028:    cs_str = "TLS/ECDHE-RSA/AES256-CBC/SHA384"; break;
   case 0x00C029:    cs_str = "TLS/ECDH-RSA/AES128-CBC/SHA256"; break;
   case 0x00C02A:    cs_str = "TLS/ECDH-RSA/AES256-CBC/SHA384"; break;
   case 0x00C02B:    cs_str = "TLS/ECDHE-ECDSA/AES128-GCM/SHA256"; break;
   case 0x00C02C:    cs_str = "TLS/ECDHE-ECDSA/AES256-GCM/SHA384"; break;
   case 0x00C02F:    cs_str = "TLS/ECDHE-RSA/AES128-GCM/SHA256"; break;
 
+  case 0x00CCA8:    cs_str = "TLS/ECDHE-RSA/CHACHA20-POLY1305/SHA256"; break;
+  case 0x00CCA9:    cs_str = "TLS/ECDHE-ECDSA/CHACHA20-POLY1305/SHA256"; break;
+  case 0x00CCAA:    cs_str = "TLS/DHE-RSA/CHACHA20-POLY1305/SHA256"; break;
+
   case 0x00FEFF:    cs_str = "SSL3/RSA-FIPS/3DESEDE-CBC/SHA";	break;
   case 0x00FEFE:    cs_str = "SSL3/RSA-FIPS/DES-CBC/SHA";	break;
   case 0x00FFE1:    cs_str = "SSL3/RSA-FIPS/DES56-CBC/SHA";     break;
   case 0x00FFE0:    cs_str = "SSL3/RSA-FIPS/3DES192EDE-CBC/SHA";break;
 
   /* the string literal is broken up to avoid trigraphs */
   default:          cs_str = "????" "/????????" "/?????????" "/???"; break;
   }
--- a/security/nss/coreconf/Werror.mk
+++ b/security/nss/coreconf/Werror.mk
@@ -2,28 +2,38 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # This sets WARNING_CFLAGS for gcc-like compilers.
 
 ifndef CC_IS_GCC
   CC_IS_GCC := $(shell $(CC) -x c -E -Wall -Werror /dev/null >/dev/null 2>&1 && echo 1)
+  # Export CC_IS_GCC to save a shell invocation when recursing.
   export CC_IS_GCC
 endif
 
 ifndef CC_NAME
   ifeq (1,$(CC_IS_GCC))
     CC_NAME := $(shell $(CC) -? 2>&1 >/dev/null | sed -e 's/:.*//;1q')
   else
     CC_NAME := $(notdir $(CC))
   endif
+  # Export CC_NAME to save a shell invocation when recursing.
   export CC_NAME
 endif
 
+ifndef GCC_VERSION
+  ifeq (1,$(CC_IS_GCC))
+    GCC_VERSION := $(subst ., ,$(shell $(CC) -dumpversion || echo x.x.x))
+    # Export GCC_VERSION to save a shell invocation when recursing.
+    export GCC_VERSION
+  endif
+endif
+
 ifndef WARNING_CFLAGS
   ifneq (1,$(CC_IS_GCC))
     WARNING_CFLAGS = $(NULL)
   else
     # This tests to see if enabling the warning is possible before
     # setting an option to disable it.
     disable_warning = $(shell $(CC) -x c -E -Werror -W$(1) /dev/null >/dev/null 2>&1 && echo -Wno-$(1))
 
@@ -50,28 +60,27 @@ ifndef WARNING_CFLAGS
         #   sprintf is often misused; please use snprintf [-Werror]
         # So, just suppress -Werror entirely on Android
         NSS_ENABLE_WERROR = 0
         $(warning OS_TARGET is Android, disabling -Werror)
       else
         ifeq ($(CC_NAME),clang)
           # Clang reports its version as an older gcc, but it's OK
           NSS_ENABLE_WERROR = 1
-        else
-          CC_VERSION := $(subst ., ,$(shell $(CC) -dumpversion))
-          ifneq (,$(filter 4.8 4.9,$(word 1,$(CC_VERSION)).$(word 2,$(CC_VERSION))))
+        else ifeq ($(CC_NAME),gcc)
+          ifneq (,$(filter 4.8 4.9,$(word 1,$(GCC_VERSION)).$(word 2,$(GCC_VERSION))))
             NSS_ENABLE_WERROR = 1
           endif
-          ifeq (,$(filter 0 1 2 3 4,$(word 1,$(CC_VERSION))))
+          ifeq (,$(filter 0 1 2 3 4,$(word 1,$(GCC_VERSION))))
             NSS_ENABLE_WERROR = 1
           endif
-          ifndef NSS_ENABLE_WERROR
-            $(warning Unable to find gcc 4.8 or greater, disabling -Werror)
-            NSS_ENABLE_WERROR = 0
-          endif
+        endif
+        ifndef NSS_ENABLE_WERROR
+          $(warning Unable to find gcc 4.8 or greater, disabling -Werror)
+          NSS_ENABLE_WERROR = 0
         endif
       endif
     endif #ndef NSS_ENABLE_WERROR
 
     ifeq ($(NSS_ENABLE_WERROR),1)
       WARNING_CFLAGS += -Werror
     else
       # Old versions of gcc (< 4.8) don't support #pragma diagnostic in functions.
--- a/security/nss/coreconf/config.mk
+++ b/security/nss/coreconf/config.mk
@@ -161,16 +161,20 @@ endif
 ifdef BUILD_LIBPKIX_TESTS
 DEFINES += -DBUILD_LIBPKIX_TESTS
 endif
 
 ifdef NSS_DISABLE_DBM
 DEFINES += -DNSS_DISABLE_DBM
 endif
 
+ifdef NSS_DISABLE_CHACHAPOLY
+DEFINES += -DNSS_DISABLE_CHACHAPOLY
+endif
+
 ifdef NSS_PKIX_NO_LDAP
 DEFINES += -DNSS_PKIX_NO_LDAP
 endif
 
 # Avoid building object leak test code for optimized library
 ifndef BUILD_OPT
 ifdef PKIX_OBJECT_LEAK_TEST
 DEFINES += -DPKIX_OBJECT_LEAK_TEST
--- a/security/nss/coreconf/coreconf.dep
+++ b/security/nss/coreconf/coreconf.dep
@@ -5,8 +5,9 @@
 
 /*
  * 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/external_tests/pk11_gtest/manifest.mn
+++ b/security/nss/external_tests/pk11_gtest/manifest.mn
@@ -2,16 +2,17 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 CORE_DEPTH = ../..
 DEPTH      = ../..
 MODULE = nss
 
 CPPSRCS = \
+      pk11_chacha20poly1305_unittest.cc \
       pk11_pbkdf2_unittest.cc \
       pk11_prf_unittest.cc \
       pk11_rsapss_unittest.cc \
       pk11_gtest.cc \
       $(NULL)
 
 INCLUDES += -I$(CORE_DEPTH)/external_tests/google_test/gtest/include \
             -I$(CORE_DEPTH)/external_tests/common
new file mode 100644
--- /dev/null
+++ b/security/nss/external_tests/pk11_gtest/pk11_chacha20poly1305_unittest.cc
@@ -0,0 +1,277 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "pk11pub.h"
+#include "sechash.h"
+#include <memory>
+
+#include "gtest/gtest.h"
+#include "scoped_ptrs.h"
+
+namespace nss_test {
+
+// ChaCha20/Poly1305 Test Vector 1, RFC 7539
+// <http://tools.ietf.org/html/rfc7539#section-2.8.2>
+const uint8_t kTestVector1Data[] = {
+  0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65,
+  0x6e, 0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68,
+  0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39,
+  0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64,
+  0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e,
+  0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f,
+  0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c,
+  0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f,
+  0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69, 0x74, 0x2e
+};
+const uint8_t kTestVector1AAD[] = {
+  0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7
+};
+const uint8_t kTestVector1Key[] = {
+  0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c,
+  0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
+  0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f
+};
+const uint8_t kTestVector1IV[] = {
+  0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
+};
+const uint8_t kTestVector1CT[] = {
+  0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53,
+  0xef, 0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe, 0xa9, 0xe2,
+  0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67,
+  0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0x0a,
+  0x9e, 0x06, 0x0b, 0x29, 0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92,
+  0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x03, 0xae, 0xe3, 0x28, 0x09,
+  0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80,
+  0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d,
+  0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b, 0x61, 0x16, 0x1a, 0xe1, 0x0b,
+  0x59, 0x4f, 0x09, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x06, 0x91
+};
+
+// ChaCha20/Poly1305 Test Vector 2, RFC 7539
+// <http://tools.ietf.org/html/rfc7539#appendix-A.5>
+const uint8_t kTestVector2Data[] = {
+  0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2d, 0x44, 0x72, 0x61, 0x66,
+  0x74, 0x73, 0x20, 0x61, 0x72, 0x65, 0x20, 0x64, 0x72, 0x61, 0x66, 0x74, 0x20,
+  0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x76, 0x61, 0x6c,
+  0x69, 0x64, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x61, 0x20, 0x6d, 0x61, 0x78, 0x69,
+  0x6d, 0x75, 0x6d, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x69, 0x78, 0x20, 0x6d, 0x6f,
+  0x6e, 0x74, 0x68, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6d, 0x61, 0x79, 0x20,
+  0x62, 0x65, 0x20, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x2c, 0x20, 0x72,
+  0x65, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x64, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x6f,
+  0x62, 0x73, 0x6f, 0x6c, 0x65, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x6f,
+  0x74, 0x68, 0x65, 0x72, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74,
+  0x73, 0x20, 0x61, 0x74, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x74, 0x69, 0x6d, 0x65,
+  0x2e, 0x20, 0x49, 0x74, 0x20, 0x69, 0x73, 0x20, 0x69, 0x6e, 0x61, 0x70, 0x70,
+  0x72, 0x6f, 0x70, 0x72, 0x69, 0x61, 0x74, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x75,
+  0x73, 0x65, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2d, 0x44,
+  0x72, 0x61, 0x66, 0x74, 0x73, 0x20, 0x61, 0x73, 0x20, 0x72, 0x65, 0x66, 0x65,
+  0x72, 0x65, 0x6e, 0x63, 0x65, 0x20, 0x6d, 0x61, 0x74, 0x65, 0x72, 0x69, 0x61,
+  0x6c, 0x20, 0x6f, 0x72, 0x20, 0x74, 0x6f, 0x20, 0x63, 0x69, 0x74, 0x65, 0x20,
+  0x74, 0x68, 0x65, 0x6d, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x74, 0x68,
+  0x61, 0x6e, 0x20, 0x61, 0x73, 0x20, 0x2f, 0xe2, 0x80, 0x9c, 0x77, 0x6f, 0x72,
+  0x6b, 0x20, 0x69, 0x6e, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73,
+  0x2e, 0x2f, 0xe2, 0x80, 0x9d
+};
+const uint8_t kTestVector2AAD[] = {
+  0xf3, 0x33, 0x88, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4e, 0x91
+};
+const uint8_t kTestVector2Key[] = {
+  0x1c, 0x92, 0x40, 0xa5, 0xeb, 0x55, 0xd3, 0x8a, 0xf3, 0x33, 0x88, 0x86, 0x04,
+  0xf6, 0xb5, 0xf0, 0x47, 0x39, 0x17, 0xc1, 0x40, 0x2b, 0x80, 0x09, 0x9d, 0xca,
+  0x5c, 0xbc, 0x20, 0x70, 0x75, 0xc0
+};
+const uint8_t kTestVector2IV[] = {
+  0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
+};
+const uint8_t kTestVector2CT[] = {
+  0x64, 0xa0, 0x86, 0x15, 0x75, 0x86, 0x1a, 0xf4, 0x60, 0xf0, 0x62, 0xc7, 0x9b,
+  0xe6, 0x43, 0xbd, 0x5e, 0x80, 0x5c, 0xfd, 0x34, 0x5c, 0xf3, 0x89, 0xf1, 0x08,
+  0x67, 0x0a, 0xc7, 0x6c, 0x8c, 0xb2, 0x4c, 0x6c, 0xfc, 0x18, 0x75, 0x5d, 0x43,
+  0xee, 0xa0, 0x9e, 0xe9, 0x4e, 0x38, 0x2d, 0x26, 0xb0, 0xbd, 0xb7, 0xb7, 0x3c,
+  0x32, 0x1b, 0x01, 0x00, 0xd4, 0xf0, 0x3b, 0x7f, 0x35, 0x58, 0x94, 0xcf, 0x33,
+  0x2f, 0x83, 0x0e, 0x71, 0x0b, 0x97, 0xce, 0x98, 0xc8, 0xa8, 0x4a, 0xbd, 0x0b,
+  0x94, 0x81, 0x14, 0xad, 0x17, 0x6e, 0x00, 0x8d, 0x33, 0xbd, 0x60, 0xf9, 0x82,
+  0xb1, 0xff, 0x37, 0xc8, 0x55, 0x97, 0x97, 0xa0, 0x6e, 0xf4, 0xf0, 0xef, 0x61,
+  0xc1, 0x86, 0x32, 0x4e, 0x2b, 0x35, 0x06, 0x38, 0x36, 0x06, 0x90, 0x7b, 0x6a,
+  0x7c, 0x02, 0xb0, 0xf9, 0xf6, 0x15, 0x7b, 0x53, 0xc8, 0x67, 0xe4, 0xb9, 0x16,
+  0x6c, 0x76, 0x7b, 0x80, 0x4d, 0x46, 0xa5, 0x9b, 0x52, 0x16, 0xcd, 0xe7, 0xa4,
+  0xe9, 0x90, 0x40, 0xc5, 0xa4, 0x04, 0x33, 0x22, 0x5e, 0xe2, 0x82, 0xa1, 0xb0,
+  0xa0, 0x6c, 0x52, 0x3e, 0xaf, 0x45, 0x34, 0xd7, 0xf8, 0x3f, 0xa1, 0x15, 0x5b,
+  0x00, 0x47, 0x71, 0x8c, 0xbc, 0x54, 0x6a, 0x0d, 0x07, 0x2b, 0x04, 0xb3, 0x56,
+  0x4e, 0xea, 0x1b, 0x42, 0x22, 0x73, 0xf5, 0x48, 0x27, 0x1a, 0x0b, 0xb2, 0x31,
+  0x60, 0x53, 0xfa, 0x76, 0x99, 0x19, 0x55, 0xeb, 0xd6, 0x31, 0x59, 0x43, 0x4e,
+  0xce, 0xbb, 0x4e, 0x46, 0x6d, 0xae, 0x5a, 0x10, 0x73, 0xa6, 0x72, 0x76, 0x27,
+  0x09, 0x7a, 0x10, 0x49, 0xe6, 0x17, 0xd9, 0x1d, 0x36, 0x10, 0x94, 0xfa, 0x68,
+  0xf0, 0xff, 0x77, 0x98, 0x71, 0x30, 0x30, 0x5b, 0xea, 0xba, 0x2e, 0xda, 0x04,
+  0xdf, 0x99, 0x7b, 0x71, 0x4d, 0x6c, 0x6f, 0x2c, 0x29, 0xa6, 0xad, 0x5c, 0xb4,
+  0x02, 0x2b, 0x02, 0x70, 0x9b, 0xee, 0xad, 0x9d, 0x67, 0x89, 0x0c, 0xbb, 0x22,
+  0x39, 0x23, 0x36, 0xfe, 0xa1, 0x85, 0x1f, 0x38
+};
+
+class Pkcs11ChaCha20Poly1305Test : public ::testing::Test {
+ public:
+  void EncryptDecrypt(PK11SymKey* symKey,
+                      const uint8_t* data, size_t data_len,
+                      const uint8_t* aad, size_t aad_len,
+                      const uint8_t* iv, size_t iv_len,
+                      const uint8_t* ct = nullptr, size_t ct_len = 0)
+  {
+    // Prepare AEAD params.
+    CK_NSS_AEAD_PARAMS aead_params;
+    aead_params.pNonce = toUcharPtr(iv);
+    aead_params.ulNonceLen = iv_len;
+    aead_params.pAAD = toUcharPtr(aad);
+    aead_params.ulAADLen = aad_len;
+    aead_params.ulTagLen = 16;
+
+    SECItem params = { siBuffer, reinterpret_cast<unsigned char*>(&aead_params),
+                       sizeof(aead_params) };
+
+    // Encrypt.
+    unsigned int outputLen = 0;
+    std::vector<uint8_t> output(data_len + aead_params.ulTagLen);
+    SECStatus rv = PK11_Encrypt(symKey, mech, &params, &output[0], &outputLen,
+                                output.size(), data, data_len);
+    EXPECT_EQ(rv, SECSuccess);
+
+    // Check ciphertext and tag.
+    if (ct) {
+      EXPECT_TRUE(!memcmp(ct, &output[0], outputLen));
+    }
+
+    // Decrypt.
+    unsigned int decryptedLen = 0;
+    std::vector<uint8_t> decrypted(data_len);
+    rv = PK11_Decrypt(symKey, mech, &params, &decrypted[0], &decryptedLen,
+                      decrypted.size(), &output[0], outputLen);
+    EXPECT_EQ(rv, SECSuccess);
+
+    // Check the plaintext.
+    EXPECT_TRUE(!memcmp(data, &decrypted[0], decryptedLen));
+
+    // Decrypt with bogus data.
+    {
+      std::vector<uint8_t> bogusCiphertext(output);
+      bogusCiphertext[0] ^= 0xff;
+      rv = PK11_Decrypt(symKey, mech, &params, &decrypted[0], &decryptedLen,
+                        decrypted.size(), &bogusCiphertext[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+
+    // Decrypt with bogus tag.
+    {
+      std::vector<uint8_t> bogusTag(output);
+      bogusTag[outputLen - 1] ^= 0xff;
+      rv = PK11_Decrypt(symKey, mech, &params, &decrypted[0], &decryptedLen,
+                        decrypted.size(), &bogusTag[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+
+    // Decrypt with bogus IV.
+    {
+      SECItem bogusParams(params);
+      CK_NSS_AEAD_PARAMS bogusAeadParams(aead_params);
+      bogusParams.data = reinterpret_cast<unsigned char*>(&bogusAeadParams);
+
+      std::vector<uint8_t> bogusIV(iv, iv + iv_len);
+      bogusAeadParams.pNonce = toUcharPtr(&bogusIV[0]);
+      bogusIV[0] ^= 0xff;
+
+      rv = PK11_Decrypt(symKey, mech, &bogusParams, &decrypted[0],
+                        &decryptedLen, data_len, &output[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+
+    // Decrypt with bogus additional data.
+    {
+      SECItem bogusParams(params);
+      CK_NSS_AEAD_PARAMS bogusAeadParams(aead_params);
+      bogusParams.data = reinterpret_cast<unsigned char*>(&bogusAeadParams);
+
+      std::vector<uint8_t> bogusAAD(aad, aad + aad_len);
+      bogusAeadParams.pAAD = toUcharPtr(&bogusAAD[0]);
+      bogusAAD[0] ^= 0xff;
+
+      rv = PK11_Decrypt(symKey, mech, &bogusParams, &decrypted[0],
+                        &decryptedLen, data_len, &output[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+  }
+
+  void EncryptDecrypt(const uint8_t* key, size_t key_len,
+                      const uint8_t* data, size_t data_len,
+                      const uint8_t* aad, size_t aad_len,
+                      const uint8_t* iv, size_t iv_len,
+                      const uint8_t* ct, size_t ct_len)
+  {
+    ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+    SECItem keyItem = { siBuffer, toUcharPtr(key),
+                        static_cast<unsigned int>(key_len) };
+
+    // Import key.
+    ScopedPK11SymKey symKey(PK11_ImportSymKey(slot.get(), mech,
+                                              PK11_OriginUnwrap, CKA_ENCRYPT,
+                                              &keyItem, nullptr));
+    EXPECT_TRUE(!!symKey);
+
+    // Check.
+    EncryptDecrypt(symKey.get(), data, data_len, aad, aad_len, iv, iv_len, ct,
+                   ct_len);
+  }
+
+ protected:
+  CK_MECHANISM_TYPE mech = CKM_NSS_CHACHA20_POLY1305;
+
+  unsigned char* toUcharPtr(const uint8_t* v) {
+    return const_cast<unsigned char*>(
+      static_cast<const unsigned char*>(v));
+  }
+};
+
+#define ENCRYPT_DECRYPT(v) \
+  EncryptDecrypt(v ## Key, sizeof(v ## Key), \
+                 v ## Data, sizeof(v ## Data), \
+                 v ## AAD, sizeof(v ## AAD), \
+                 v ## IV, sizeof(v ## IV), \
+                 v ## CT, sizeof(v ## CT));
+
+TEST_F(Pkcs11ChaCha20Poly1305Test, GenerateEncryptDecrypt) {
+  // Generate a random key.
+  ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+  ScopedPK11SymKey symKey(PK11_KeyGen(slot.get(), mech, nullptr, 32, nullptr));
+  EXPECT_TRUE(!!symKey);
+
+  // Generate random data.
+  std::vector<uint8_t> data(512);
+  SECStatus rv = PK11_GenerateRandomOnSlot(slot.get(), &data[0], data.size());
+  EXPECT_EQ(rv, SECSuccess);
+
+  // Generate random AAD.
+  std::vector<uint8_t> aad(16);
+  rv = PK11_GenerateRandomOnSlot(slot.get(), &aad[0], aad.size());
+  EXPECT_EQ(rv, SECSuccess);
+
+  // Generate random IV.
+  std::vector<uint8_t> iv(12);
+  rv = PK11_GenerateRandomOnSlot(slot.get(), &iv[0], iv.size());
+  EXPECT_EQ(rv, SECSuccess);
+
+  // Check.
+  EncryptDecrypt(symKey.get(), &data[0], data.size(), &aad[0], aad.size(),
+                 &iv[0], iv.size());
+}
+
+TEST_F(Pkcs11ChaCha20Poly1305Test, CheckTestVector1) {
+  ENCRYPT_DECRYPT(kTestVector1);
+}
+
+TEST_F(Pkcs11ChaCha20Poly1305Test, CheckTestVector2) {
+  ENCRYPT_DECRYPT(kTestVector2);
+}
+
+}  // namespace nss_test
+
--- a/security/nss/external_tests/ssl_gtest/libssl_internals.c
+++ b/security/nss/external_tests/ssl_gtest/libssl_internals.c
@@ -19,8 +19,29 @@ SSLInt_IncrementClientHandshakeVersion(P
     if (!ss) {
         return SECFailure;
     }
 
     ++ss->clientHelloVersion;
 
     return SECSuccess;
 }
+
+PRUint32
+SSLInt_DetermineKEABits(PRUint16 serverKeyBits, SSLAuthType authAlgorithm) {
+    // For ECDSA authentication we expect a curve for key exchange with the
+    // same strength as the one used for the certificate's signature.
+    if (authAlgorithm == ssl_auth_ecdsa) {
+        return serverKeyBits;
+    }
+
+    PORT_Assert(authAlgorithm == ssl_auth_rsa);
+    PRUint32 minKeaBits;
+#ifdef NSS_ECC_MORE_THAN_SUITE_B
+    // P-192 is the smallest curve we want to use.
+    minKeaBits = 192U;
+#else
+    // P-256 is the smallest supported curve.
+    minKeaBits = 256U;
+#endif
+
+    return PR_MAX(SSL_RSASTRENGTH_TO_ECSTRENGTH(serverKeyBits), minKeaBits);
+}
--- a/security/nss/external_tests/ssl_gtest/libssl_internals.h
+++ b/security/nss/external_tests/ssl_gtest/libssl_internals.h
@@ -4,14 +4,18 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef libssl_internals_h_
 #define libssl_internals_h_
 
 #include "prio.h"
 #include "seccomon.h"
+#include "sslt.h"
 
 SECStatus SSLInt_IncrementClientHandshakeVersion(PRFileDesc *fd);
 
+PRUint32 SSLInt_DetermineKEABits(PRUint16 serverKeyBits,
+                                 SSLAuthType authAlgorithm);
+
 #endif
 
 
--- a/security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc
+++ b/security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc
@@ -103,16 +103,39 @@ class TlsServerKeyExchangeEcdhe {
     }
 
     return parser.ReadVariable(&public_key_, 1);
   }
 
   DataBuffer public_key_;
 };
 
+class TlsChaCha20Poly1305Test : public TlsConnectTls12 {
+ public:
+  void ConnectSendReceive(PRUint32 cipher_suite)
+  {
+    // Disable all ciphers.
+    client_->DisableCiphersByKeyExchange(ssl_kea_rsa);
+    client_->DisableCiphersByKeyExchange(ssl_kea_dh);
+    client_->DisableCiphersByKeyExchange(ssl_kea_ecdh);
+
+    // Re-enable ChaCha20/Poly1305.
+    SECStatus rv = SSL_CipherPrefSet(client_->ssl_fd(), cipher_suite, PR_TRUE);
+    EXPECT_EQ(SECSuccess, rv);
+
+    Connect();
+    SendReceive();
+
+    // Check that we used the right cipher suite.
+    int16_t actual, expected = static_cast<int16_t>(cipher_suite);
+    EXPECT_TRUE(client_->cipher_suite(&actual) && actual == expected);
+    EXPECT_TRUE(server_->cipher_suite(&actual) && actual == expected);
+  }
+};
+
 TEST_P(TlsConnectGeneric, SetupOnly) {}
 
 TEST_P(TlsConnectGeneric, Connect) {
   SetExpectedVersion(std::get<1>(GetParam()));
   Connect();
   CheckKeys(ssl_kea_ecdh, ssl_auth_rsa);
 }
 
@@ -537,16 +560,29 @@ TEST_P(TlsConnectStreamPre13, ConnectEcd
                         dhe1.public_key_.len())));
 }
 
 TEST_P(TlsConnectGeneric, ConnectSendReceive) {
   Connect();
   SendReceive();
 }
 
+TEST_P(TlsChaCha20Poly1305Test, SendReceiveChaCha20Poly1305DheRsa) {
+  ConnectSendReceive(TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
+}
+
+TEST_P(TlsChaCha20Poly1305Test, SendReceiveChaCha20Poly1305EcdheRsa) {
+  ConnectSendReceive(TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
+}
+
+TEST_P(TlsChaCha20Poly1305Test, SendReceiveChaCha20Poly1305EcdheEcdsa) {
+  ResetEcdsa();
+  ConnectSendReceive(TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
+}
+
 // The next two tests takes advantage of the fact that we
 // automatically read the first 1024 bytes, so if
 // we provide 1200 bytes, they overrun the read buffer
 // provided by the calling test.
 
 // DTLS should return an error.
 TEST_P(TlsConnectDatagram, ShortRead) {
   Connect();
@@ -941,16 +977,18 @@ INSTANTIATE_TEST_CASE_P(VariantsStream10
 INSTANTIATE_TEST_CASE_P(VariantsAll, TlsConnectGeneric,
                         ::testing::Combine(
                           TlsConnectTestBase::kTlsModesAll,
                           TlsConnectTestBase::kTlsV11V12));
 INSTANTIATE_TEST_CASE_P(VersionsDatagram, TlsConnectDatagram,
                         TlsConnectTestBase::kTlsV11V12);
 INSTANTIATE_TEST_CASE_P(Variants12, TlsConnectTls12,
                         TlsConnectTestBase::kTlsModesAll);
+INSTANTIATE_TEST_CASE_P(Variants12, TlsChaCha20Poly1305Test,
+                        TlsConnectTestBase::kTlsModesAll);
 INSTANTIATE_TEST_CASE_P(Pre12Stream, TlsConnectPre12,
                         ::testing::Combine(
                           TlsConnectTestBase::kTlsModesStream,
                           TlsConnectTestBase::kTlsV10));
 INSTANTIATE_TEST_CASE_P(Pre12All, TlsConnectPre12,
                         ::testing::Combine(
                           TlsConnectTestBase::kTlsModesAll,
                           TlsConnectTestBase::kTlsV11));
--- a/security/nss/external_tests/ssl_gtest/tls_agent.cc
+++ b/security/nss/external_tests/ssl_gtest/tls_agent.cc
@@ -8,16 +8,21 @@
 
 #include "pk11func.h"
 #include "ssl.h"
 #include "sslerr.h"
 #include "sslproto.h"
 #include "keyhi.h"
 #include "databuffer.h"
 
+extern "C" {
+// This is not something that should make you happy.
+#include "libssl_internals.h"
+}
+
 #define GTEST_HAS_RTTI 0
 #include "gtest/gtest.h"
 
 namespace nss_test {
 
 
 const char* TlsAgent::states[] = {"INIT", "CONNECTING", "CONNECTED", "ERROR"};
 
@@ -190,16 +195,17 @@ void TlsAgent::DisableCiphersByKeyExchan
   EXPECT_TRUE(EnsureTlsSetup());
 
   for (size_t i = 0; i < SSL_NumImplementedCiphers; ++i) {
     SSLCipherSuiteInfo csinfo;
 
     SECStatus rv = SSL_GetCipherSuiteInfo(SSL_ImplementedCiphers[i],
                                           &csinfo, sizeof(csinfo));
     ASSERT_EQ(SECSuccess, rv);
+    EXPECT_EQ(sizeof(csinfo), csinfo.length);
 
     if (csinfo.keaType == kea) {
       rv = SSL_CipherPrefSet(ssl_fd_, SSL_ImplementedCiphers[i], PR_FALSE);
       EXPECT_EQ(SECSuccess, rv);
     }
   }
 }
 
@@ -286,19 +292,22 @@ void TlsAgent::SetSignatureAlgorithms(co
   }
   EXPECT_EQ(i, configuredCount) << "algorithms in use were all set";
 }
 
 void TlsAgent::CheckKEAType(SSLKEAType type) const {
   EXPECT_EQ(STATE_CONNECTED, state_);
   EXPECT_EQ(type, csinfo_.keaType);
 
+  PRUint32 ecKEAKeyBits = SSLInt_DetermineKEABits(server_key_bits_,
+                                                  csinfo_.authAlgorithm);
+
   switch (type) {
       case ssl_kea_ecdh:
-          EXPECT_EQ(256U, info_.keaKeyBits);
+          EXPECT_EQ(ecKEAKeyBits, info_.keaKeyBits);
           break;
       case ssl_kea_dh:
           EXPECT_EQ(2048U, info_.keaKeyBits);
           break;
       case ssl_kea_rsa:
           EXPECT_EQ(server_key_bits_, info_.keaKeyBits);
           break;
       default:
@@ -373,16 +382,17 @@ void TlsAgent::CheckErrorCode(int32_t ex
   EXPECT_EQ(STATE_ERROR, state_);
   EXPECT_EQ(expected, error_code_);
 }
 
 void TlsAgent::CheckPreliminaryInfo() {
   SSLPreliminaryChannelInfo info;
   EXPECT_EQ(SECSuccess,
             SSL_GetPreliminaryChannelInfo(ssl_fd_, &info, sizeof(info)));
+  EXPECT_EQ(sizeof(info), info.length);
   EXPECT_TRUE(info.valuesSet & ssl_preinfo_version);
   EXPECT_TRUE(info.valuesSet & ssl_preinfo_cipher_suite);
 
   // A version of 0 is invalid and indicates no expectation.  This value is
   // initialized to 0 so that tests that don't explicitly set an expected
   // version can negotiate a version.
   if (!expected_version_) {
     expected_version_ = info.protocolVersion;
@@ -418,25 +428,27 @@ void TlsAgent::CheckCallbacks() const {
 }
 
 void TlsAgent::Connected() {
   LOG("Handshake success");
   CheckCallbacks();
 
   SECStatus rv = SSL_GetChannelInfo(ssl_fd_, &info_, sizeof(info_));
   EXPECT_EQ(SECSuccess, rv);
+  EXPECT_EQ(sizeof(info_), info_.length);
 
   // Preliminary values are exposed through callbacks during the handshake.
   // If either expected values were set or the callbacks were called, check
   // that the final values are correct.
   EXPECT_EQ(expected_version_, info_.protocolVersion);
   EXPECT_EQ(expected_cipher_suite_, info_.cipherSuite);
 
   rv = SSL_GetCipherSuiteInfo(info_.cipherSuite, &csinfo_, sizeof(csinfo_));
   EXPECT_EQ(SECSuccess, rv);
+  EXPECT_EQ(sizeof(csinfo_), csinfo_.length);
 
   SetState(STATE_CONNECTED);
 }
 
 void TlsAgent::EnableExtendedMasterSecret() {
   ASSERT_TRUE(EnsureTlsSetup());
 
   SECStatus rv = SSL_OptionSet(ssl_fd_,
--- a/security/nss/lib/freebl/Makefile
+++ b/security/nss/lib/freebl/Makefile
@@ -477,16 +477,43 @@ ifndef NSS_DISABLE_ECC
     ifdef ECL_USE_FP
 	#enable floating point ECC code	
 	DEFINES  += -DECL_USE_FP
 	ECL_SRCS += ecp_fp160.c ecp_fp192.c ecp_fp224.c ecp_fp.c
 	ECL_HDRS += ecp_fp.h
     endif
 endif
 
+# poly1305-donna-x64-sse2-incremental-source.c requires __int128 support
+# in GCC 4.6.0.
+ifeq ($(CC_NAME),clang)
+    HAVE_INT128_SUPPORT = 1
+else ifeq (1,$(CC_IS_GCC))
+    ifneq (,$(filter 4.6 4.7 4.8 4.9,$(word 1,$(GCC_VERSION)).$(word 2,$(GCC_VERSION))))
+        HAVE_INT128_SUPPORT = 1
+    endif
+    ifeq (,$(filter 0 1 2 3 4,$(word 1,$(GCC_VERSION))))
+        HAVE_INT128_SUPPORT = 1
+    endif
+endif
+
+ifndef NSS_DISABLE_CHACHAPOLY
+    ifeq ($(CPU_ARCH),x86_64)
+        ifdef HAVE_INT128_SUPPORT
+            EXTRA_SRCS += poly1305-donna-x64-sse2-incremental-source.c
+        else
+            EXTRA_SRCS += poly1305.c
+        endif
+        EXTRA_SRCS += chacha20_vec.c
+    else
+        EXTRA_SRCS += poly1305.c
+        EXTRA_SRCS += chacha20.c
+    endif # x86_64
+endif # NSS_DISABLE_CHACHAPOLY
+
 #######################################################################
 # (5) Execute "global" rules. (OPTIONAL)                              #
 #######################################################################
 
 include $(CORE_DEPTH)/coreconf/rules.mk
 
 #######################################################################
 # (6) Execute "component" rules. (OPTIONAL)                           #
--- a/security/nss/lib/freebl/blapi.h
+++ b/security/nss/lib/freebl/blapi.h
@@ -981,16 +981,45 @@ Camellia_Encrypt(CamelliaContext *cx, un
 **	"input" the input data
 **	"inputLen" the amount of input data
 */
 extern SECStatus 
 Camellia_Decrypt(CamelliaContext *cx, unsigned char *output,
 		 unsigned int *outputLen, unsigned int maxOutputLen,
 		 const unsigned char *input, unsigned int inputLen);
 
+/******************************************/
+/*
+** ChaCha20+Poly1305 AEAD
+*/
+
+extern SECStatus ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,
+                                              const unsigned char *key,
+                                              unsigned int keyLen,
+                                              unsigned int tagLen);
+
+extern ChaCha20Poly1305Context *ChaCha20Poly1305_CreateContext(
+    const unsigned char *key, unsigned int keyLen, unsigned int tagLen);
+
+extern void ChaCha20Poly1305_DestroyContext(ChaCha20Poly1305Context *ctx,
+                                            PRBool freeit);
+
+extern SECStatus ChaCha20Poly1305_Seal(
+    const ChaCha20Poly1305Context *ctx, unsigned char *output,
+    unsigned int *outputLen, unsigned int maxOutputLen,
+    const unsigned char *input, unsigned int inputLen,
+    const unsigned char *nonce, unsigned int nonceLen,
+    const unsigned char *ad, unsigned int adLen);
+
+extern SECStatus ChaCha20Poly1305_Open(
+    const ChaCha20Poly1305Context *ctx, unsigned char *output,
+    unsigned int *outputLen, unsigned int maxOutputLen,
+    const unsigned char *input, unsigned int inputLen,
+    const unsigned char *nonce, unsigned int nonceLen,
+    const unsigned char *ad, unsigned int adLen);
 
 /******************************************/
 /*
 ** MD5 secure hash function
 */
 
 /*
 ** Hash a null terminated string "src" into "dest" using MD5
--- a/security/nss/lib/freebl/blapit.h
+++ b/security/nss/lib/freebl/blapit.h
@@ -217,16 +217,17 @@ struct AESContextStr        ;
 struct CamelliaContextStr   ;
 struct MD2ContextStr        ;
 struct MD5ContextStr        ;
 struct SHA1ContextStr       ;
 struct SHA256ContextStr     ;
 struct SHA512ContextStr     ;
 struct AESKeyWrapContextStr ;
 struct SEEDContextStr       ;	
+struct ChaCha20Poly1305ContextStr;
 
 typedef struct DESContextStr        DESContext;
 typedef struct RC2ContextStr        RC2Context;
 typedef struct RC4ContextStr        RC4Context;
 typedef struct RC5ContextStr        RC5Context;
 typedef struct AESContextStr        AESContext;
 typedef struct CamelliaContextStr   CamelliaContext;
 typedef struct MD2ContextStr        MD2Context;
@@ -235,16 +236,17 @@ typedef struct SHA1ContextStr       SHA1
 typedef struct SHA256ContextStr     SHA256Context;
 /* SHA224Context is really a SHA256ContextStr.  This is not a mistake. */
 typedef struct SHA256ContextStr     SHA224Context;
 typedef struct SHA512ContextStr     SHA512Context;
 /* SHA384Context is really a SHA512ContextStr.  This is not a mistake. */
 typedef struct SHA512ContextStr     SHA384Context;
 typedef struct AESKeyWrapContextStr AESKeyWrapContext;
 typedef struct SEEDContextStr	    SEEDContext;	
+typedef struct ChaCha20Poly1305ContextStr ChaCha20Poly1305Context;
 
 /***************************************************************************
 ** RSA Public and Private Key structures
 */
 
 /* member names from PKCS#1, section 7.1 */
 struct RSAPublicKeyStr {
     PLArenaPool * arena;
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/chacha20.c
@@ -0,0 +1,111 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Adopted from the public domain code in NaCl by djb. */
+
+#include <string.h>
+#include <stdio.h>
+
+#include "prtypes.h"
+#include "secport.h"
+#include "chacha20.h"
+
+#if defined(_MSC_VER)
+#pragma intrinsic(_lrotl)
+#define ROTL32(x, n) _lrotl(x, n)
+#else
+#define ROTL32(x, n) ((x << n) | (x >> ((8 * sizeof x) - n)))
+#endif
+
+#define ROTATE(v, c) ROTL32((v), (c))
+
+#define U32TO8_LITTLE(p, v)                                                    \
+    { (p)[0] = ((v)      ) & 0xff; (p)[1] = ((v) >>  8) & 0xff;                \
+      (p)[2] = ((v) >> 16) & 0xff; (p)[3] = ((v) >> 24) & 0xff; }
+#define U8TO32_LITTLE(p)                                                       \
+    (((PRUint32)((p)[0])      ) | ((PRUint32)((p)[1]) <<  8) |                 \
+     ((PRUint32)((p)[2]) << 16) | ((PRUint32)((p)[3]) << 24))
+
+#define QUARTERROUND(x, a, b, c, d)                                            \
+    x[a] = x[a] + x[b]; x[d] = ROTATE(x[d] ^ x[a], 16);                        \
+    x[c] = x[c] + x[d]; x[b] = ROTATE(x[b] ^ x[c], 12);                        \
+    x[a] = x[a] + x[b]; x[d] = ROTATE(x[d] ^ x[a],  8);                        \
+    x[c] = x[c] + x[d]; x[b] = ROTATE(x[b] ^ x[c],  7);
+
+static void
+ChaChaCore(unsigned char output[64], const PRUint32 input[16], int num_rounds)
+{
+    PRUint32 x[16];
+    int i;
+
+    PORT_Memcpy(x, input, sizeof(PRUint32) * 16);
+    for (i = num_rounds; i > 0; i -= 2) {
+        QUARTERROUND(x, 0, 4, 8, 12)
+        QUARTERROUND(x, 1, 5, 9, 13)
+        QUARTERROUND(x, 2, 6, 10, 14)
+        QUARTERROUND(x, 3, 7, 11, 15)
+        QUARTERROUND(x, 0, 5, 10, 15)
+        QUARTERROUND(x, 1, 6, 11, 12)
+        QUARTERROUND(x, 2, 7, 8, 13)
+        QUARTERROUND(x, 3, 4, 9, 14)
+    }
+
+    for (i = 0; i < 16; ++i) {
+        x[i] = x[i] + input[i];
+    }
+    for (i = 0; i < 16; ++i) {
+        U32TO8_LITTLE(output + 4 * i, x[i]);
+    }
+}
+
+static const unsigned char sigma[16] = "expand 32-byte k";
+
+void
+ChaCha20XOR(unsigned char *out, const unsigned char *in, unsigned int inLen,
+            const unsigned char key[32], const unsigned char nonce[12],
+            uint32_t counter)
+{
+    unsigned char block[64];
+    PRUint32 input[16];
+    unsigned int i;
+
+    input[4] = U8TO32_LITTLE(key + 0);
+    input[5] = U8TO32_LITTLE(key + 4);
+    input[6] = U8TO32_LITTLE(key + 8);
+    input[7] = U8TO32_LITTLE(key + 12);
+
+    input[8] = U8TO32_LITTLE(key + 16);
+    input[9] = U8TO32_LITTLE(key + 20);
+    input[10] = U8TO32_LITTLE(key + 24);
+    input[11] = U8TO32_LITTLE(key + 28);
+
+    input[0] = U8TO32_LITTLE(sigma + 0);
+    input[1] = U8TO32_LITTLE(sigma + 4);
+    input[2] = U8TO32_LITTLE(sigma + 8);
+    input[3] = U8TO32_LITTLE(sigma + 12);
+
+    input[12] = counter;
+    input[13] = U8TO32_LITTLE(nonce + 0);
+    input[14] = U8TO32_LITTLE(nonce + 4);
+    input[15] = U8TO32_LITTLE(nonce + 8);
+
+    while (inLen >= 64) {
+        ChaChaCore(block, input, 20);
+        for (i = 0; i < 64; i++) {
+            out[i] = in[i] ^ block[i];
+        }
+
+        input[12]++;
+        inLen -= 64;
+        in += 64;
+        out += 64;
+    }
+
+    if (inLen > 0) {
+        ChaChaCore(block, input, 20);
+        for (i = 0; i < inLen; i++) {
+            out[i] = in[i] ^ block[i];
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/chacha20.h
@@ -0,0 +1,26 @@
+/*
+ * chacha20.h - header file for ChaCha20 implementation.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef FREEBL_CHACHA20_H_
+#define FREEBL_CHACHA20_H_
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+#include "prtypes.h"
+typedef PRUint32 uint32_t;
+typedef PRUint64 uint64_t;
+#else
+#include <stdint.h>
+#endif
+
+/* ChaCha20XOR encrypts |inLen| bytes from |in| with the given key and
+ * nonce and writes the result to |out|, which may be equal to |in|. The
+ * initial block counter is specified by |counter|. */
+extern void ChaCha20XOR(unsigned char *out, const unsigned char *in,
+                        unsigned int inLen, const unsigned char key[32],
+                        const unsigned char nonce[12], uint32_t counter);
+
+#endif /* FREEBL_CHACHA20_H_ */
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/chacha20_vec.c
@@ -0,0 +1,278 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This implementation is by Ted Krovetz and was submitted to SUPERCOP and
+ * marked as public domain. It was been altered to allow for non-aligned inputs
+ * and to allow the block counter to be passed in specifically. */
+
+#include <string.h>
+
+#include "chacha20.h"
+
+#ifndef CHACHA_RNDS
+#define CHACHA_RNDS 20    /* 8 (high speed), 20 (conservative), 12 (middle) */
+#endif
+
+/* Architecture-neutral way to specify 16-byte vector of ints              */
+typedef unsigned vec __attribute__ ((vector_size (16)));
+
+/* This implementation is designed for Neon, SSE and AltiVec machines. The
+ * following specify how to do certain vector operations efficiently on
+ * each architecture, using intrinsics.
+ * This implementation supports parallel processing of multiple blocks,
+ * including potentially using general-purpose registers.
+ */
+#if __ARM_NEON__
+#include <arm_neon.h>
+#define GPR_TOO   1
+#define VBPI      2
+#define ONE       (vec)vsetq_lane_u32(1,vdupq_n_u32(0),0)
+#define LOAD(m)   (vec)(*((vec*)(m)))
+#define STORE(m,r) (*((vec*)(m))) = (r)
+#define ROTV1(x)  (vec)vextq_u32((uint32x4_t)x,(uint32x4_t)x,1)
+#define ROTV2(x)  (vec)vextq_u32((uint32x4_t)x,(uint32x4_t)x,2)
+#define ROTV3(x)  (vec)vextq_u32((uint32x4_t)x,(uint32x4_t)x,3)
+#define ROTW16(x) (vec)vrev32q_u16((uint16x8_t)x)
+#if __clang__
+#define ROTW7(x)  (x << ((vec){ 7, 7, 7, 7})) ^ (x >> ((vec){25,25,25,25}))
+#define ROTW8(x)  (x << ((vec){ 8, 8, 8, 8})) ^ (x >> ((vec){24,24,24,24}))
+#define ROTW12(x) (x << ((vec){12,12,12,12})) ^ (x >> ((vec){20,20,20,20}))
+#else
+#define ROTW7(x)  (vec)vsriq_n_u32(vshlq_n_u32((uint32x4_t)x,7),(uint32x4_t)x,25)
+#define ROTW8(x)  (vec)vsriq_n_u32(vshlq_n_u32((uint32x4_t)x,8),(uint32x4_t)x,24)
+#define ROTW12(x) (vec)vsriq_n_u32(vshlq_n_u32((uint32x4_t)x,12),(uint32x4_t)x,20)
+#endif
+#elif __SSE2__
+#include <emmintrin.h>
+#define GPR_TOO   0
+#if __clang__
+#define VBPI      4
+#else
+#define VBPI      3
+#endif
+#define ONE       (vec)_mm_set_epi32(0,0,0,1)
+#define LOAD(m)   (vec)_mm_loadu_si128((__m128i*)(m))
+#define STORE(m,r) _mm_storeu_si128((__m128i*)(m), (__m128i) (r))
+#define ROTV1(x)  (vec)_mm_shuffle_epi32((__m128i)x,_MM_SHUFFLE(0,3,2,1))
+#define ROTV2(x)  (vec)_mm_shuffle_epi32((__m128i)x,_MM_SHUFFLE(1,0,3,2))
+#define ROTV3(x)  (vec)_mm_shuffle_epi32((__m128i)x,_MM_SHUFFLE(2,1,0,3))
+#define ROTW7(x)  (vec)(_mm_slli_epi32((__m128i)x, 7) ^ _mm_srli_epi32((__m128i)x,25))
+#define ROTW12(x) (vec)(_mm_slli_epi32((__m128i)x,12) ^ _mm_srli_epi32((__m128i)x,20))
+#if __SSSE3__
+#include <tmmintrin.h>
+#define ROTW8(x)  (vec)_mm_shuffle_epi8((__m128i)x,_mm_set_epi8(14,13,12,15,10,9,8,11,6,5,4,7,2,1,0,3))
+#define ROTW16(x) (vec)_mm_shuffle_epi8((__m128i)x,_mm_set_epi8(13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2))
+#else
+#define ROTW8(x)  (vec)(_mm_slli_epi32((__m128i)x, 8) ^ _mm_srli_epi32((__m128i)x,24))
+#define ROTW16(x) (vec)(_mm_slli_epi32((__m128i)x,16) ^ _mm_srli_epi32((__m128i)x,16))
+#endif
+#else
+#error -- Implementation supports only machines with neon or SSE2
+#endif
+
+#ifndef REVV_BE
+#define REVV_BE(x)  (x)
+#endif
+
+#ifndef REVW_BE
+#define REVW_BE(x)  (x)
+#endif
+
+#define BPI      (VBPI + GPR_TOO)  /* Blocks computed per loop iteration   */
+
+#define DQROUND_VECTORS(a,b,c,d)                \
+    a += b; d ^= a; d = ROTW16(d);              \
+    c += d; b ^= c; b = ROTW12(b);              \
+    a += b; d ^= a; d = ROTW8(d);               \
+    c += d; b ^= c; b = ROTW7(b);               \
+    b = ROTV1(b); c = ROTV2(c);  d = ROTV3(d);  \
+    a += b; d ^= a; d = ROTW16(d);              \
+    c += d; b ^= c; b = ROTW12(b);              \
+    a += b; d ^= a; d = ROTW8(d);               \
+    c += d; b ^= c; b = ROTW7(b);               \
+    b = ROTV3(b); c = ROTV2(c); d = ROTV1(d);
+
+#define QROUND_WORDS(a,b,c,d) \
+  a = a+b; d ^= a; d = d<<16 | d>>16; \
+  c = c+d; b ^= c; b = b<<12 | b>>20; \
+  a = a+b; d ^= a; d = d<< 8 | d>>24; \
+  c = c+d; b ^= c; b = b<< 7 | b>>25;
+
+#define WRITE_XOR(in, op, d, v0, v1, v2, v3)                \
+    STORE(op + d + 0, LOAD(in + d + 0) ^ REVV_BE(v0));      \
+    STORE(op + d + 4, LOAD(in + d + 4) ^ REVV_BE(v1));      \
+    STORE(op + d + 8, LOAD(in + d + 8) ^ REVV_BE(v2));      \
+    STORE(op + d +12, LOAD(in + d +12) ^ REVV_BE(v3));
+
+void
+ChaCha20XOR(unsigned char *out, const unsigned char *in, unsigned int inlen,
+            const unsigned char key[32], const unsigned char nonce[12],
+            uint32_t counter)
+{
+    unsigned iters, i, *op=(unsigned *)out, *ip=(unsigned *)in, *kp;
+#if defined(__ARM_NEON__)
+    unsigned *np;
+#endif
+    vec s0, s1, s2, s3;
+#if !defined(__ARM_NEON__) && !defined(__SSE2__)
+    __attribute__ ((aligned (16))) unsigned key[8], nonce[4];
+#endif
+    __attribute__ ((aligned (16))) unsigned chacha_const[] =
+        {0x61707865,0x3320646E,0x79622D32,0x6B206574};
+#if defined(__ARM_NEON__) || defined(__SSE2__)
+    kp = (unsigned *)key;
+#else
+    ((vec *)key)[0] = REVV_BE(((vec *)key)[0]);
+    ((vec *)key)[1] = REVV_BE(((vec *)key)[1]);
+    ((unsigned *)nonce)[0] = REVW_BE(((unsigned *)nonce)[0]);
+    ((unsigned *)nonce)[1] = REVW_BE(((unsigned *)nonce)[1]);
+    ((unsigned *)nonce)[2] = REVW_BE(((unsigned *)nonce)[2]);
+    ((unsigned *)nonce)[3] = REVW_BE(((unsigned *)nonce)[3]);
+    kp = (unsigned *)key;
+    np = (unsigned *)nonce;
+#endif
+#if defined(__ARM_NEON__)
+    np = (unsigned*) nonce;
+#endif
+    s0 = LOAD(chacha_const);
+    s1 = LOAD(&((vec*)kp)[0]);
+    s2 = LOAD(&((vec*)kp)[1]);
+    s3 = (vec) {
+        counter,
+        ((uint32_t*)nonce)[0],
+        ((uint32_t*)nonce)[1],
+        ((uint32_t*)nonce)[2]
+    };
+
+    for (iters = 0; iters < inlen/(BPI*64); iters++) {
+#if GPR_TOO
+        register unsigned x0, x1, x2, x3, x4, x5, x6, x7, x8,
+                  x9, x10, x11, x12, x13, x14, x15;
+#endif
+#if VBPI > 2
+        vec v8,v9,v10,v11;
+#endif
+#if VBPI > 3
+        vec v12,v13,v14,v15;
+#endif
+
+        vec v0,v1,v2,v3,v4,v5,v6,v7;
+        v4 = v0 = s0; v5 = v1 = s1; v6 = v2 = s2; v3 = s3;
+        v7 = v3 + ONE;
+#if VBPI > 2
+        v8 = v4; v9 = v5; v10 = v6;
+        v11 =  v7 + ONE;
+#endif
+#if VBPI > 3
+        v12 = v8; v13 = v9; v14 = v10;
+        v15 = v11 + ONE;
+#endif
+#if GPR_TOO
+        x0 = chacha_const[0]; x1 = chacha_const[1];
+        x2 = chacha_const[2]; x3 = chacha_const[3];
+        x4 = kp[0]; x5 = kp[1]; x6  = kp[2]; x7  = kp[3];
+        x8 = kp[4]; x9 = kp[5]; x10 = kp[6]; x11 = kp[7];
+        x12 = counter+BPI*iters+(BPI-1); x13 = np[0];
+        x14 = np[1]; x15 = np[2];
+#endif
+        for (i = CHACHA_RNDS/2; i; i--) {
+            DQROUND_VECTORS(v0,v1,v2,v3)
+            DQROUND_VECTORS(v4,v5,v6,v7)
+#if VBPI > 2
+            DQROUND_VECTORS(v8,v9,v10,v11)
+#endif
+#if VBPI > 3
+            DQROUND_VECTORS(v12,v13,v14,v15)
+#endif
+#if GPR_TOO
+            QROUND_WORDS( x0, x4, x8,x12)
+            QROUND_WORDS( x1, x5, x9,x13)
+            QROUND_WORDS( x2, x6,x10,x14)
+            QROUND_WORDS( x3, x7,x11,x15)
+            QROUND_WORDS( x0, x5,x10,x15)
+            QROUND_WORDS( x1, x6,x11,x12)
+            QROUND_WORDS( x2, x7, x8,x13)
+            QROUND_WORDS( x3, x4, x9,x14)
+#endif
+        }
+
+        WRITE_XOR(ip, op, 0, v0+s0, v1+s1, v2+s2, v3+s3)
+        s3 += ONE;
+        WRITE_XOR(ip, op, 16, v4+s0, v5+s1, v6+s2, v7+s3)
+        s3 += ONE;
+#if VBPI > 2
+        WRITE_XOR(ip, op, 32, v8+s0, v9+s1, v10+s2, v11+s3)
+        s3 += ONE;
+#endif
+#if VBPI > 3
+        WRITE_XOR(ip, op, 48, v12+s0, v13+s1, v14+s2, v15+s3)
+        s3 += ONE;
+#endif
+        ip += VBPI*16;
+        op += VBPI*16;
+#if GPR_TOO
+        op[0]  = REVW_BE(REVW_BE(ip[0])  ^ (x0  + chacha_const[0]));
+        op[1]  = REVW_BE(REVW_BE(ip[1])  ^ (x1  + chacha_const[1]));
+        op[2]  = REVW_BE(REVW_BE(ip[2])  ^ (x2  + chacha_const[2]));
+        op[3]  = REVW_BE(REVW_BE(ip[3])  ^ (x3  + chacha_const[3]));
+        op[4]  = REVW_BE(REVW_BE(ip[4])  ^ (x4  + kp[0]));
+        op[5]  = REVW_BE(REVW_BE(ip[5])  ^ (x5  + kp[1]));
+        op[6]  = REVW_BE(REVW_BE(ip[6])  ^ (x6  + kp[2]));
+        op[7]  = REVW_BE(REVW_BE(ip[7])  ^ (x7  + kp[3]));
+        op[8]  = REVW_BE(REVW_BE(ip[8])  ^ (x8  + kp[4]));
+        op[9]  = REVW_BE(REVW_BE(ip[9])  ^ (x9  + kp[5]));
+        op[10] = REVW_BE(REVW_BE(ip[10]) ^ (x10 + kp[6]));
+        op[11] = REVW_BE(REVW_BE(ip[11]) ^ (x11 + kp[7]));
+        op[12] = REVW_BE(REVW_BE(ip[12]) ^ (x12 + counter+BPI*iters+(BPI-1)));
+        op[13] = REVW_BE(REVW_BE(ip[13]) ^ (x13 + np[0]));
+        op[14] = REVW_BE(REVW_BE(ip[14]) ^ (x14 + np[1]));
+        op[15] = REVW_BE(REVW_BE(ip[15]) ^ (x15 + np[2]));
+        s3 += ONE;
+        ip += 16;
+        op += 16;
+#endif
+    }
+
+    for (iters = inlen%(BPI*64)/64; iters != 0; iters--) {
+        vec v0 = s0, v1 = s1, v2 = s2, v3 = s3;
+        for (i = CHACHA_RNDS/2; i; i--) {
+            DQROUND_VECTORS(v0,v1,v2,v3);
+        }
+        WRITE_XOR(ip, op, 0, v0+s0, v1+s1, v2+s2, v3+s3)
+        s3 += ONE;
+        ip += 16;
+        op += 16;
+    }
+
+    inlen = inlen % 64;
+    if (inlen) {
+        __attribute__ ((aligned (16))) vec buf[4];
+        vec v0,v1,v2,v3;
+        v0 = s0; v1 = s1; v2 = s2; v3 = s3;
+        for (i = CHACHA_RNDS/2; i; i--) {
+            DQROUND_VECTORS(v0,v1,v2,v3);
+        }
+
+        if (inlen >= 16) {
+            STORE(op + 0, LOAD(ip + 0) ^ REVV_BE(v0 + s0));
+            if (inlen >= 32) {
+                STORE(op + 4, LOAD(ip + 4) ^ REVV_BE(v1 + s1));
+                if (inlen >= 48) {
+                    STORE(op + 8, LOAD(ip + 8) ^ REVV_BE(v2 + s2));
+                    buf[3] = REVV_BE(v3 + s3);
+                } else {
+                    buf[2] = REVV_BE(v2 + s2);
+                }
+            } else {
+                buf[1] = REVV_BE(v1 + s1);
+            }
+        } else {
+            buf[0] = REVV_BE(v0 + s0);
+        }
+
+        for (i=inlen & ~15; i<inlen; i++) {
+            ((char *)op)[i] = ((char *)ip)[i] ^ ((char *)buf)[i];
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/chacha20poly1305.c
@@ -0,0 +1,198 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifdef FREEBL_NO_DEPEND
+#include "stubs.h"
+#endif
+
+#include <string.h>
+#include <stdio.h>
+
+#include "seccomon.h"
+#include "secerr.h"
+#include "blapit.h"
+
+#ifndef NSS_DISABLE_CHACHAPOLY
+#include "poly1305.h"
+#include "chacha20.h"
+#include "chacha20poly1305.h"
+#endif
+
+/* Poly1305Do writes the Poly1305 authenticator of the given additional data
+ * and ciphertext to |out|. */
+#ifndef NSS_DISABLE_CHACHAPOLY
+static void
+Poly1305Do(unsigned char *out, const unsigned char *ad, unsigned int adLen,
+           const unsigned char *ciphertext, unsigned int ciphertextLen,
+           const unsigned char key[32])
+{
+    poly1305_state state;
+    unsigned int j;
+    unsigned char lengthBytes[8];
+    static const unsigned char zeros[15];
+    unsigned int i;
+
+    Poly1305Init(&state, key);
+    Poly1305Update(&state, ad, adLen);
+    if (adLen % 16 > 0) {
+        Poly1305Update(&state, zeros, 16 - adLen % 16);
+    }
+    Poly1305Update(&state, ciphertext, ciphertextLen);
+    if (ciphertextLen % 16 > 0) {
+        Poly1305Update(&state, zeros, 16 - ciphertextLen % 16);
+    }
+    j = adLen;
+    for (i = 0; i < sizeof(lengthBytes); i++) {
+        lengthBytes[i] = j;
+        j >>= 8;
+    }
+    Poly1305Update(&state, lengthBytes, sizeof(lengthBytes));
+    j = ciphertextLen;
+    for (i = 0; i < sizeof(lengthBytes); i++) {
+        lengthBytes[i] = j;
+        j >>= 8;
+    }
+    Poly1305Update(&state, lengthBytes, sizeof(lengthBytes));
+    Poly1305Finish(&state, out);
+}
+#endif
+
+SECStatus
+ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,
+                             const unsigned char *key, unsigned int keyLen,
+                             unsigned int tagLen)
+{
+#ifdef NSS_DISABLE_CHACHAPOLY
+    return SECFailure;
+#else
+    if (keyLen != 32) {
+        PORT_SetError(SEC_ERROR_BAD_KEY);
+        return SECFailure;
+    }
+    if (tagLen == 0 || tagLen > 16) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+
+    PORT_Memcpy(ctx->key, key, sizeof(ctx->key));
+    ctx->tagLen = tagLen;
+
+    return SECSuccess;
+#endif
+}
+
+ChaCha20Poly1305Context *
+ChaCha20Poly1305_CreateContext(const unsigned char *key, unsigned int keyLen,
+                               unsigned int tagLen)
+{
+#ifdef NSS_DISABLE_CHACHAPOLY
+    return NULL;
+#else
+    ChaCha20Poly1305Context *ctx;
+
+    ctx = PORT_New(ChaCha20Poly1305Context);
+    if (ctx == NULL) {
+        return NULL;
+    }
+
+    if (ChaCha20Poly1305_InitContext(ctx, key, keyLen, tagLen) != SECSuccess) {
+        PORT_Free(ctx);
+        ctx = NULL;
+    }
+
+    return ctx;
+#endif
+}
+
+void
+ChaCha20Poly1305_DestroyContext(ChaCha20Poly1305Context *ctx, PRBool freeit)
+{
+#ifndef NSS_DISABLE_CHACHAPOLY
+    PORT_Memset(ctx, 0, sizeof(*ctx));
+    if (freeit) {
+        PORT_Free(ctx);
+    }
+#endif
+}
+
+SECStatus
+ChaCha20Poly1305_Seal(const ChaCha20Poly1305Context *ctx, unsigned char *output,
+                      unsigned int *outputLen, unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+#ifdef NSS_DISABLE_CHACHAPOLY
+    return SECFailure;
+#else
+    unsigned char block[64];
+    unsigned char tag[16];
+
+    if (nonceLen != 12) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+    *outputLen = inputLen + ctx->tagLen;
+    if (maxOutputLen < *outputLen) {
+        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+        return SECFailure;
+    }
+
+    PORT_Memset(block, 0, sizeof(block));
+    // Generate a block of keystream. The first 32 bytes will be the poly1305
+    // key. The remainder of the block is discarded.
+    ChaCha20XOR(block, block, sizeof(block), ctx->key, nonce, 0);
+    ChaCha20XOR(output, input, inputLen, ctx->key, nonce, 1);
+
+    Poly1305Do(tag, ad, adLen, output, inputLen, block);
+    PORT_Memcpy(output + inputLen, tag, ctx->tagLen);
+
+    return SECSuccess;
+#endif
+}
+
+SECStatus
+ChaCha20Poly1305_Open(const ChaCha20Poly1305Context *ctx, unsigned char *output,
+                      unsigned int *outputLen, unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+#ifdef NSS_DISABLE_CHACHAPOLY
+    return SECFailure;
+#else
+    unsigned char block[64];
+    unsigned char tag[16];
+    unsigned int ciphertextLen;
+
+    if (nonceLen != 12) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+    if (inputLen < ctx->tagLen) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+    ciphertextLen = inputLen - ctx->tagLen;
+    *outputLen = ciphertextLen;
+    if (maxOutputLen < *outputLen) {
+        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+        return SECFailure;
+    }
+
+    PORT_Memset(block, 0, sizeof(block));
+    // Generate a block of keystream. The first 32 bytes will be the poly1305
+    // key. The remainder of the block is discarded.
+    ChaCha20XOR(block, block, sizeof(block), ctx->key, nonce, 0);
+    Poly1305Do(tag, ad, adLen, input, ciphertextLen, block);
+    if (NSS_SecureMemcmp(tag, &input[ciphertextLen], ctx->tagLen) != 0) {
+        PORT_SetError(SEC_ERROR_BAD_DATA);
+        return SECFailure;
+    }
+
+    ChaCha20XOR(output, input, ciphertextLen, ctx->key, nonce, 1);
+
+    return SECSuccess;
+#endif
+}
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/chacha20poly1305.h
@@ -0,0 +1,15 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef _CHACHA20_POLY1305_H_
+#define _CHACHA20_POLY1305_H_ 1
+
+/* ChaCha20Poly1305ContextStr saves the key and tag length for a
+ * ChaCha20+Poly1305 AEAD operation. */
+struct ChaCha20Poly1305ContextStr {
+    unsigned char key[32];
+    unsigned char tagLen;
+};
+
+#endif /* _CHACHA20_POLY1305_H_ */
--- a/security/nss/lib/freebl/intel-aes.s
+++ b/security/nss/lib/freebl/intel-aes.s
@@ -2,16 +2,30 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 	.text
 
 #define IV_OFFSET 16
 #define EXPANDED_KEY_OFFSET 48
 
+/*
+ * Warning: the length values used in this module are "unsigned int"
+ * in C, which is 32-bit.  When they're passed in registers, use only
+ * the low 32 bits, because the top half is unspecified.
+ *
+ * This is called from C code, so the contents of those bits can
+ * depend on the C compiler's optimization decisions.  This means that
+ * mistakes might not be obvious in testing if those bits happen to be
+ * zero in your build.
+ *
+ * Exception: 32-bit lea instructions use a 64-bit address because the
+ * address size doesn't affect the result, and that form is more
+ * compactly encoded and preferred by compilers over a 32-bit address.
+ */
 
 /* in %rdi : the key
    in %rsi : buffer for expanded key
 */
 	.type intel_aes_encrypt_init_128,@function
 	.globl intel_aes_encrypt_init_128
 	.align	16
 intel_aes_encrypt_init_128:
@@ -114,37 +128,38 @@ key_expansion128:
 	addq	$16, %rsi
 	ret
 	.size key_expansion128, .-key_expansion128
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_encrypt_ecb_128,@function
 	.globl intel_aes_encrypt_ecb_128
 	.align	16
 intel_aes_encrypt_ecb_128:
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdi), %xmm2
 	movdqu	160(%rdi), %xmm12
 	xor	%eax, %eax
-//	cmpq	$8*16, %r9
-	cmpq	$128, %r9
+//	cmpl	$8*16, %r9d
+	cmpl	$128, %r9d
 	jb	1f
-//	leaq	-8*16(%r9), %r11
-	leaq	-128(%r9), %r11
+//	leal	-8*16(%r9), %r11d
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -255,21 +270,21 @@ 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-//	addq	$8*16, %rax
-	addq	$128, %rax
-	cmpq	%r11, %rax
+//	addl	$8*16, %eax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm3
 	movdqu	32(%rdi), %xmm4
 	movdqu	48(%rdi), %xmm5
 	movdqu	64(%rdi), %xmm6
 	movdqu	80(%rdi), %xmm7
 	movdqu	96(%rdi), %xmm8
@@ -285,49 +300,50 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x0f,0x38,0xdc,0xce	/* aesenc	%xmm6, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xdc,0xcf	/* aesenc	%xmm7, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc8	/* aesenc	%xmm8, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc9	/* aesenc	%xmm9, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xca	/* aesenc	%xmm10, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcb	/* aesenc	%xmm11, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdd,0xcc	/* aesenclast %xmm12, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	xor	%eax, %eax
 	ret
 	.size intel_aes_encrypt_ecb_128, .-intel_aes_encrypt_ecb_128
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_decrypt_ecb_128,@function
 	.globl intel_aes_decrypt_ecb_128
 	.align	16
 intel_aes_decrypt_ecb_128:
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdi), %xmm2
 	movdqu	160(%rdi), %xmm12
 	xorl	%eax, %eax
-//	cmpq	$8*16, %r9
-	cmpq	$128, %r9
+//	cmpl	$8*16, %r9d
+	cmpl	$128, %r9d
 	jb	1f
-//	leaq	-8*16(%r9), %r11
-	leaq	-128(%r9), %r11
+//	leal	-8*16(%r9), %r11d
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -438,21 +454,21 @@ 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-//	addq	$8*16, %rax
-	addq	$128, %rax
-	cmpq	%r11, %rax
+//	addl	$8*16, %eax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm3
 	movdqu	32(%rdi), %xmm4
 	movdqu	48(%rdi), %xmm5
 	movdqu	64(%rdi), %xmm6
 	movdqu	80(%rdi), %xmm7
 	movdqu	96(%rdi), %xmm8
@@ -468,39 +484,40 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x41,0x0f,0x38,0xde,0xc8	/* aesdec	%xmm8, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcf	/* aesdec	%xmm7, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xce	/* aesdec	%xmm7, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcd	/* aesdec	%xmm7, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcc	/* aesdec	%xmm7, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcb	/* aesdec	%xmm7, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xdf,0xca	/* aesdeclast %xmm2, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	xor	%eax, %eax
 	ret
 	.size intel_aes_decrypt_ecb_128, .-intel_aes_decrypt_ecb_128
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_encrypt_cbc_128,@function
 	.globl intel_aes_encrypt_cbc_128
 	.align	16
 intel_aes_encrypt_cbc_128:
-	testq	%r9, %r9
+	testl	%r9d, %r9d
 	je	2f
 
 //	leaq	IV_OFFSET(%rdi), %rdx
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	16(%rdi), %rdx
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdx), %xmm0
@@ -527,52 +544,53 @@ 1:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x0f,0x38,0xdc,0xcf	/* aesenc	%xmm7, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc8	/* aesenc	%xmm8, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc9	/* aesenc	%xmm9, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xca	/* aesenc	%xmma, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcb	/* aesenc	%xmmb, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdd,0xcc	/* aesenclast %xmm12, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
 	movdqa	%xmm1, %xmm0
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	1b
 
 	movdqu	%xmm0, (%rdx)
 
 2:	xor	%eax, %eax
 	ret
 	.size intel_aes_encrypt_cbc_128, .-intel_aes_encrypt_cbc_128
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_decrypt_cbc_128,@function
 	.globl intel_aes_decrypt_cbc_128
 	.align	16
 intel_aes_decrypt_cbc_128:
 //	leaq	IV_OFFSET(%rdi), %rdx
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	16(%rdi), %rdx
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdx), %xmm0   /* iv */
 	movdqu	(%rdi), %xmm2   /* first key block */
 	movdqu	160(%rdi), %xmm12 /* last key block */
 	xorl	%eax, %eax
-	cmpq	$128, %r9
+	cmpl	$128, %r9d
 	jb	1f
-	leaq	-128(%r9), %r11
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3 /* 1st data block */
 	movdqu	16(%r8, %rax), %xmm4 /* 2d data block */
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -699,20 +717,20 @@ 2:	movdqu	(%r8, %rax), %xmm3 /* 1st data
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-	addq	$128, %rax
-	cmpq	%r11, %rax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm3
 	movdqu	32(%rdi), %xmm4
 	movdqu	48(%rdi), %xmm5
 	movdqu	64(%rdi), %xmm6
 	movdqu	80(%rdi), %xmm7
 	movdqu	96(%rdi), %xmm8
@@ -731,18 +749,18 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x0f,0x38,0xde,0xce	/* aesdec	%xmm6, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcd	/* aesdec	%xmm5, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcc	/* aesdec	%xmm4, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcb	/* aesdec	%xmm3, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xdf,0xca	/* aesdeclast %xmm2, %xmm1 */
 	pxor	%xmm0, %xmm1
 	movdqu	%xmm1, (%rsi, %rax)
 	movdqa	%xmm13, %xmm0
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	movdqu	%xmm0, (%rdx)
 
 	xor	%eax, %eax
 	ret
 	.size intel_aes_decrypt_cbc_128, .-intel_aes_decrypt_cbc_128
         
@@ -868,37 +886,38 @@ key_expansion192:
 	addq	$8, %rsi
 	ret
 	.size key_expansion192, .-key_expansion192
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_encrypt_ecb_192,@function
 	.globl intel_aes_encrypt_ecb_192
 	.align	16
 intel_aes_encrypt_ecb_192:
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdi), %xmm2
 	movdqu	192(%rdi), %xmm14
 	xorl	%eax, %eax
-//	cmpq	$8*16, %r9
-	cmpq	$128, %r9
+//	cmpl	$8*16, %r9d
+	cmpl	$128, %r9d
 	jb	1f
-//	leaq	-8*16(%r9), %r11
-	leaq	-128(%r9), %r11
+//	leal	-8*16(%r9), %r11d
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -1028,21 +1047,21 @@ 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-//	addq	$8*16, %rax
-	addq	$128, %rax
-	cmpq	%r11, %rax
+//	addl	$8*16, %eax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm3
 	movdqu	32(%rdi), %xmm4
 	movdqu	48(%rdi), %xmm5
 	movdqu	64(%rdi), %xmm6
 	movdqu	80(%rdi), %xmm7
 	movdqu	96(%rdi), %xmm8
@@ -1062,49 +1081,50 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc8	/* aesenc	%xmm8, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc9	/* aesenc	%xmm9, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xca	/* aesenc	%xmm10, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcb	/* aesenc	%xmm11, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcc	/* aesenc	%xmm12, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcd	/* aesenc	%xmm13, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdd,0xce	/* aesenclast %xmm14, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	xor	%eax, %eax
 	ret
 	.size intel_aes_encrypt_ecb_192, .-intel_aes_encrypt_ecb_192
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_decrypt_ecb_192,@function
 	.globl intel_aes_decrypt_ecb_192
 	.align	16
 intel_aes_decrypt_ecb_192:
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdi), %xmm2
 	movdqu	192(%rdi), %xmm14
 	xorl	%eax, %eax
-//	cmpq	$8*16, %r9
-	cmpq	$128, %r9
+//	cmpl	$8*16, %r9d
+	cmpl	$128, %r9d
 	jb	1f
-//	leaq	-8*16(%r9), %r11
-	leaq	-128(%r9), %r11
+//	leal	-8*16(%r9), %r11d
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -1234,21 +1254,21 @@ 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-//	addq	$8*16, %rax
-	addq	$128, %rax
-	cmpq	%r11, %rax
+//	addl	$8*16, %eax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm3
 	movdqu	32(%rdi), %xmm4
 	movdqu	48(%rdi), %xmm5
 	movdqu	64(%rdi), %xmm6
 	movdqu	80(%rdi), %xmm7
 	movdqu	96(%rdi), %xmm8
@@ -1268,39 +1288,40 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x41,0x0f,0x38,0xde,0xc8	/* aesdec	%xmm8, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcf	/* aesdec	%xmm7, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xce	/* aesdec	%xmm6, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcd	/* aesdec	%xmm5, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcc	/* aesdec	%xmm4, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcb	/* aesdec	%xmm3, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xdf,0xca	/* aesdeclast %xmm2, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	xor	%eax, %eax
 	ret
 	.size intel_aes_decrypt_ecb_192, .-intel_aes_decrypt_ecb_192
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_encrypt_cbc_192,@function
 	.globl intel_aes_encrypt_cbc_192
 	.align	16
 intel_aes_encrypt_cbc_192:
-	testq	%r9, %r9
+	testl	%r9d, %r9d
 	je	2f
 
 //	leaq	IV_OFFSET(%rdi), %rdx
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	16(%rdi), %rdx
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdx), %xmm0
@@ -1331,50 +1352,51 @@ 1:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc9	/* aesenc	%xmm9, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xca	/* aesenc	%xmm10, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcb	/* aesenc	%xmm11, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcc	/* aesenc	%xmm12, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcd	/* aesenc	%xmm13, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdd,0xce	/* aesenclast %xmm14, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
 	movdqa	%xmm1, %xmm0
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	1b
 
 	movdqu	%xmm0, (%rdx)
 
 2:	xor	%eax, %eax
 	ret
 	.size intel_aes_encrypt_cbc_192, .-intel_aes_encrypt_cbc_192
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %exx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_decrypt_cbc_192,@function
 	.globl intel_aes_decrypt_cbc_192
 	.align	16
 intel_aes_decrypt_cbc_192:
 	leaq	16(%rdi), %rdx
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdx), %xmm0
 	movdqu	(%rdi), %xmm2
 	movdqu	192(%rdi), %xmm14
 	xorl	%eax, %eax
-	cmpq	$128, %r9
+	cmpl	$128, %r9d
 	jb	1f
-	leaq	-128(%r9), %r11
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -1520,20 +1542,20 @@ 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-	addq	$128, %rax
-	cmpq	%r11, %rax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm3
 	movdqu	32(%rdi), %xmm4
 	movdqu	48(%rdi), %xmm5
 	movdqu	64(%rdi), %xmm6
 	movdqu	80(%rdi), %xmm7
 	movdqu	96(%rdi), %xmm8
@@ -1556,18 +1578,18 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x0f,0x38,0xde,0xce	/* aesdec	%xmm6, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcd	/* aesdec	%xmm5, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcc	/* aesdec	%xmm4, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcb	/* aesdec	%xmm3, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xdf,0xca	/* aesdeclast %xmm2, %xmm1 */
 	pxor	%xmm0, %xmm1
 	movdqu	%xmm1, (%rsi, %rax)
 	movdqa	%xmm15, %xmm0
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	movdqu	%xmm0, (%rdx)
 
 	xor	%eax, %eax
 	ret
 	.size intel_aes_decrypt_cbc_192, .-intel_aes_decrypt_cbc_192
 
@@ -1700,37 +1722,38 @@ key_expansion256:
 	addq	$16, %rsi
 	ret
 	.size key_expansion256, .-key_expansion256
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_encrypt_ecb_256,@function
 	.globl intel_aes_encrypt_ecb_256
 	.align	16
 intel_aes_encrypt_ecb_256:
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdi), %xmm2
 	movdqu	224(%rdi), %xmm15
 	xorl	%eax, %eax
-//	cmpq	$8*16, %r9
-	cmpq	$128, %r9
+//	cmpl	$8*16, %r9d
+	cmpl	$128, %r9d
 	jb	1f
-//	leaq	-8*16(%r9), %r11
-	leaq	-128(%r9), %r11
+//	leal	-8*16(%r9), %r11d
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -1879,21 +1902,21 @@ 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-//	addq	$8*16, %rax
-	addq	$128, %rax
-	cmpq	%r11, %rax
+//	addl	$8*16, %eax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	(%rdi), %xmm8
 	movdqu	16(%rdi), %xmm2
 	movdqu	32(%rdi), %xmm3
 	movdqu	48(%rdi), %xmm4
 	movdqu	64(%rdi), %xmm5
 	movdqu	80(%rdi), %xmm6
@@ -1919,49 +1942,50 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xc9	/* aesenc	%xmm9, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xca	/* aesenc	%xmm10, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcb	/* aesenc	%xmm11, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcc	/* aesenc	%xmm12, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcd	/* aesenc	%xmm13, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xce	/* aesenc	%xmm14, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdd,0xcf	/* aesenclast %xmm15, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	xor	%eax, %eax
 	ret
 	.size intel_aes_encrypt_ecb_256, .-intel_aes_encrypt_ecb_256
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_decrypt_ecb_256,@function
 	.globl intel_aes_decrypt_ecb_256
 	.align	16
 intel_aes_decrypt_ecb_256:
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdi), %xmm2
 	movdqu	224(%rdi), %xmm15
 	xorl	%eax, %eax
-//	cmpq	$8*16, %r9
-	cmpq	$128, %r9
+//	cmpl	$8*16, %r9d
+	cmpl	$128, %r9d
 	jb	1f
-//	leaq	-8*16(%r9), %r11
-	leaq	-128(%r9), %r11
+//	leal	-8*16(%r9), %r11d
+	leal	-128(%r9), %r11d
 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -2110,21 +2134,21 @@ 2:	movdqu	(%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-//	addq	$8*16, %rax
-	addq	$128, %rax
-	cmpq	%r11, %rax
+//	addl	$8*16, %eax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm2
 	movdqu	32(%rdi), %xmm3
 	movdqu	48(%rdi), %xmm4
 	movdqu	64(%rdi), %xmm5
 	movdqu	80(%rdi), %xmm6
 	movdqu	96(%rdi), %xmm7
@@ -2150,39 +2174,40 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x0f,0x38,0xde,0xce	/* aesdec	%xmm6, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcd	/* aesdec	%xmm5, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcc	/* aesdec	%xmm4, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcb	/* aesdec	%xmm3, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xca	/* aesdec	%xmm2, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdf,0xc8	/* aesdeclast %xmm8, %xmm1 */
 	movdqu	112(%rdi), %xmm8
 	movdqu	%xmm1, (%rsi, %rax)
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	xor	%eax, %eax
 	ret
 	.size intel_aes_decrypt_ecb_256, .-intel_aes_decrypt_ecb_256
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_encrypt_cbc_256,@function
 	.globl intel_aes_encrypt_cbc_256
 	.align	16
 intel_aes_encrypt_cbc_256:
-	testq	%r9, %r9
+	testl	%r9d, %r9d
 	je	2f
 
 //	leaq	IV_OFFSET(%rdi), %rdx
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	16(%rdi), %rdx
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdx), %xmm0
@@ -2218,54 +2243,55 @@ 1:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xca	/* aesenc	%xmm10, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcb	/* aesenc	%xmm11, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcc	/* aesenc	%xmm12, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xcd	/* aesenc	%xmm13, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdc,0xce	/* aesenc	%xmm14, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdd,0xcf	/* aesenclast %xmm15, %xmm1 */
 	movdqu	%xmm1, (%rsi, %rax)
 	movdqa	%xmm1, %xmm0
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	1b
 
 	movdqu	%xmm0, (%rdx)
 
 2:	xor	%eax, %eax
 	ret
 	.size intel_aes_encrypt_cbc_256, .-intel_aes_encrypt_cbc_256
 
 
 /* in %rdi : cx - context
    in %rsi : output - pointer to output buffer
    in %rdx : outputLen - pointer to variable for length of output
-             (filled by caller)
-   in %rcx : maxOutputLen - length of output buffer
+             (already filled in by caller)
+   in %ecx : maxOutputLen - length of output buffer
+             (already checked by caller)
    in %r8  : input - pointer to input buffer
-   in %r9  : inputLen - length of input buffer
+   in %r9d : inputLen - length of input buffer
    on stack: blocksize - AES blocksize (always 16, unused)
 */
 	.type intel_aes_decrypt_cbc_256,@function
 	.globl intel_aes_decrypt_cbc_256
 	.align	16
 intel_aes_decrypt_cbc_256:
 //	leaq	IV_OFFSET(%rdi), %rdx
 //	leaq	EXPANDED_KEY_OFFSET(%rdi), %rdi
 	leaq	16(%rdi), %rdx
 	leaq	48(%rdi), %rdi
 
 	movdqu	(%rdx), %xmm0
 	movdqu	(%rdi), %xmm2
 	movdqu	224(%rdi), %xmm15
 	xorl	%eax, %eax
-//	cmpq	$8*16, %r9
-	cmpq	$128, %r9
+//	cmpl	$8*16, %r9d
+	cmpl	$128, %r9d
 	jb	1f
-//	leaq	-8*16(%r9), %r11
-	leaq	-128(%r9), %r11
+//	leal	-8*16(%r9), %r11d
+	leal	-128(%r9), %r11d
 2:	movdqu  (%r8, %rax), %xmm3
 	movdqu	16(%r8, %rax), %xmm4
 	movdqu	32(%r8, %rax), %xmm5
 	movdqu	48(%r8, %rax), %xmm6
 	movdqu	64(%r8, %rax), %xmm7
 	movdqu	80(%r8, %rax), %xmm8
 	movdqu	96(%r8, %rax), %xmm9
 	movdqu	112(%r8, %rax), %xmm10
@@ -2430,21 +2456,21 @@ 2:	movdqu  (%r8, %rax), %xmm3
 	movdqu	%xmm3, (%rsi, %rax)
 	movdqu	%xmm4, 16(%rsi, %rax)
 	movdqu	%xmm5, 32(%rsi, %rax)
 	movdqu	%xmm6, 48(%rsi, %rax)
 	movdqu	%xmm7, 64(%rsi, %rax)
 	movdqu	%xmm8, 80(%rsi, %rax)
 	movdqu	%xmm9, 96(%rsi, %rax)
 	movdqu	%xmm10, 112(%rsi, %rax)
-//	addq	$8*16, %rax
-	addq	$128, %rax
-	cmpq	%r11, %rax
+//	addl	$8*16, %eax
+	addl	$128, %eax
+	cmpl	%r11d, %eax
 	jbe	2b
-1:	cmpq	%rax, %r9
+1:	cmpl	%eax, %r9d
 	je	5f
 
 	movdqu	16(%rdi), %xmm2
 	movdqu	32(%rdi), %xmm3
 	movdqu	48(%rdi), %xmm4
 	movdqu	64(%rdi), %xmm5
 	movdqu	80(%rdi), %xmm6
 	movdqu	96(%rdi), %xmm7
@@ -2472,17 +2498,17 @@ 4:	movdqu	(%r8, %rax), %xmm1
 	.byte 0x66,0x0f,0x38,0xde,0xcc	/* aesdec	%xmm4, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xcb	/* aesdec	%xmm3, %xmm1 */
 	.byte 0x66,0x0f,0x38,0xde,0xca	/* aesdec	%xmm2, %xmm1 */
 	.byte 0x66,0x41,0x0f,0x38,0xdf,0xc8	/* aesdeclast %xmm8, %xmm1 */
 	movdqu	112(%rdi), %xmm8
 	pxor	%xmm0, %xmm1
 	movdqu	(%r8, %rax), %xmm0  /* fetch the IV before we store the block */
 	movdqu	%xmm1, (%rsi, %rax) /* in case input buf = output buf */
-	addq	$16, %rax
-	cmpq	%rax, %r9
+	addl	$16, %eax
+	cmpl	%eax, %r9d
 	jne	4b
 
 5:	movdqu	%xmm0, (%rdx)
 
 	xor	%eax, %eax
 	ret
 	.size intel_aes_decrypt_cbc_256, .-intel_aes_decrypt_cbc_256
--- a/security/nss/lib/freebl/ldvector.c
+++ b/security/nss/lib/freebl/ldvector.c
@@ -281,19 +281,27 @@ static const struct FREEBLVectorStr vect
     RSA_Sign,
     RSA_CheckSign,
     RSA_CheckSignRecover,
 
     /* End of Version 3.016 */
 
     EC_FillParams,
     EC_DecodeParams,
-    EC_CopyParams
+    EC_CopyParams,
 
     /* End of Version 3.017 */
+
+    ChaCha20Poly1305_InitContext,
+    ChaCha20Poly1305_CreateContext,
+    ChaCha20Poly1305_DestroyContext,
+    ChaCha20Poly1305_Seal,
+    ChaCha20Poly1305_Open
+
+    /* End of Version 3.018 */
 };
 
 const FREEBLVector *
 FREEBL_GetVector(void)
 {
 #define NSS_VERSION_VARIABLE __nss_freebl_version
 #include "verref.h"
 
--- a/security/nss/lib/freebl/loader.c
+++ b/security/nss/lib/freebl/loader.c
@@ -2123,8 +2123,64 @@ SECStatus EC_DecodeParams(const SECItem 
 SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
                         const ECParams *srcParams)
 {
   if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
       return SECFailure;
   return (vector->p_EC_CopyParams)(arena, dstParams,  srcParams);
 }
 
+SECStatus
+ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,
+                             const unsigned char *key, unsigned int keyLen,
+                             unsigned int tagLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return SECFailure;
+  return (vector->p_ChaCha20Poly1305_InitContext)(ctx, key, keyLen, tagLen);
+}
+
+ChaCha20Poly1305Context *
+ChaCha20Poly1305_CreateContext(const unsigned char *key, unsigned int keyLen,
+                               unsigned int tagLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return NULL;
+  return (vector->p_ChaCha20Poly1305_CreateContext)(key, keyLen, tagLen);
+}
+
+void
+ChaCha20Poly1305_DestroyContext(ChaCha20Poly1305Context *ctx, PRBool freeit)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_ChaCha20Poly1305_DestroyContext)(ctx, freeit);
+}
+
+SECStatus
+ChaCha20Poly1305_Seal(const ChaCha20Poly1305Context *ctx,
+                      unsigned char *output, unsigned int *outputLen,
+                      unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return SECFailure;
+  return (vector->p_ChaCha20Poly1305_Seal)(
+      ctx, output, outputLen, maxOutputLen, input, inputLen,
+      nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
+ChaCha20Poly1305_Open(const ChaCha20Poly1305Context *ctx,
+                      unsigned char *output, unsigned int *outputLen,
+                      unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return SECFailure;
+  return (vector->p_ChaCha20Poly1305_Open)(
+      ctx, output, outputLen, maxOutputLen, input, inputLen,
+      nonce, nonceLen, ad, adLen);
+}
--- a/security/nss/lib/freebl/loader.h
+++ b/security/nss/lib/freebl/loader.h
@@ -5,17 +5,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _LOADER_H_
 #define _LOADER_H_ 1
 
 #include "blapi.h"
 
-#define FREEBL_VERSION 0x0311
+#define FREEBL_VERSION 0x0312
 
 struct FREEBLVectorStr {
 
   unsigned short length;  /* of this struct in bytes */
   unsigned short version; /* of this struct. */
 
   RSAPrivateKey * (* p_RSA_NewKey)(int         keySizeInBits,
 				 SECItem *   publicExponent);
@@ -702,16 +702,43 @@ struct FREEBLVectorStr {
                                const SECItem *encodedParams, ECParams *params);
  SECStatus (* p_EC_DecodeParams)(const SECItem *encodedParams,
                                ECParams **ecparams);
  SECStatus (* p_EC_CopyParams)(PLArenaPool *arena, ECParams *dstParams,
                                const ECParams *srcParams);
 
   /* Version 3.017 came to here */
 
+ SECStatus (* p_ChaCha20Poly1305_InitContext)(ChaCha20Poly1305Context *ctx,
+                                              const unsigned char *key,
+                                              unsigned int keyLen,
+                                              unsigned int tagLen);
+
+ ChaCha20Poly1305Context *(* p_ChaCha20Poly1305_CreateContext)(
+     const unsigned char *key, unsigned int keyLen, unsigned int tagLen);
+
+ void (* p_ChaCha20Poly1305_DestroyContext)(ChaCha20Poly1305Context *ctx,
+                                            PRBool freeit);
+
+ SECStatus (* p_ChaCha20Poly1305_Seal)(
+     const ChaCha20Poly1305Context *ctx, unsigned char *output,
+     unsigned int *outputLen, unsigned int maxOutputLen,
+     const unsigned char *input, unsigned int inputLen,
+     const unsigned char *nonce, unsigned int nonceLen,
+     const unsigned char *ad, unsigned int adLen);
+
+ SECStatus (* p_ChaCha20Poly1305_Open)(
+     const ChaCha20Poly1305Context *ctx, unsigned char *output,
+     unsigned int *outputLen, unsigned int maxOutputLen,
+     const unsigned char *input, unsigned int inputLen,
+     const unsigned char *nonce, unsigned int nonceLen,
+     const unsigned char *ad, unsigned int adLen);
+
+  /* Version 3.018 came to here */
+
   /* Add new function pointers at the end of this struct and bump
    * FREEBL_VERSION at the beginning of this file. */
  };
 
 typedef struct FREEBLVectorStr FREEBLVector;
 
 SEC_BEGIN_PROTOS
 
--- a/security/nss/lib/freebl/manifest.mn
+++ b/security/nss/lib/freebl/manifest.mn
@@ -51,16 +51,17 @@ EXPORTS = \
 	shsign.h \
 	ecl-exp.h \
 	$(LOWHASH_EXPORTS) \
 	$(NULL)
 
 PRIVATE_EXPORTS = \
 	alghmac.h \
 	blapi.h \
+	chacha20poly1305.h \
 	hmacct.h \
 	secmpi.h \
 	secrng.h \
 	ec.h \
 	ecl.h \
 	ecl-curve.h \
 	$(NULL)
 
@@ -96,16 +97,17 @@ CSRCS = \
 	alghmac.c \
 	rawhash.c \
 	alg2268.c \
 	arcfour.c \
 	arcfive.c \
 	desblapi.c \
 	des.c \
 	drbg.c \
+	chacha20poly1305.c \
 	cts.c \
 	ctr.c \
 	gcm.c \
 	hmacct.c \
 	rijndael.c \
 	aeskeywrap.c \
 	camellia.c \
 	dh.c \
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c
@@ -0,0 +1,623 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This implementation of poly1305 is by Andrew Moon
+ * (https://github.com/floodyberry/poly1305-donna) and released as public
+ * domain. It implements SIMD vectorization based on the algorithm described in
+ * http://cr.yp.to/papers.html#neoncrypto. Unrolled to 2 powers, i.e. 64 byte
+ * block size. */
+
+#include <emmintrin.h>
+#include <stdint.h>
+
+#include "poly1305.h"
+
+#define ALIGN(x) __attribute__((aligned(x)))
+#define INLINE inline
+#define U8TO64_LE(m) (*(uint64_t*)(m))
+#define U8TO32_LE(m) (*(uint32_t*)(m))
+#define U64TO8_LE(m,v) (*(uint64_t*)(m)) = v
+
+typedef __m128i xmmi;
+typedef unsigned __int128 uint128_t;
+
+static const uint32_t ALIGN(16) poly1305_x64_sse2_message_mask[4] = {(1 << 26) - 1, 0, (1 << 26) - 1, 0};
+static const uint32_t ALIGN(16) poly1305_x64_sse2_5[4] = {5, 0, 5, 0};
+static const uint32_t ALIGN(16) poly1305_x64_sse2_1shl128[4] = {(1 << 24), 0, (1 << 24), 0};
+
+static uint128_t INLINE
+add128(uint128_t a, uint128_t b) {
+	return a + b;
+}
+
+static uint128_t INLINE
+add128_64(uint128_t a, uint64_t b) {
+	return a + b;
+}
+
+static uint128_t INLINE
+mul64x64_128(uint64_t a, uint64_t b) {
+	return (uint128_t)a * b;
+}
+
+static uint64_t INLINE
+lo128(uint128_t a) {
+	return (uint64_t)a;
+}
+
+static uint64_t INLINE
+shr128(uint128_t v, const int shift) {
+	return (uint64_t)(v >> shift);
+}
+
+static uint64_t INLINE
+shr128_pair(uint64_t hi, uint64_t lo, const int shift) {
+	return (uint64_t)((((uint128_t)hi << 64) | lo) >> shift);
+}
+
+typedef struct poly1305_power_t {
+	union {
+		xmmi v;
+		uint64_t u[2];
+		uint32_t d[4];
+	} R20,R21,R22,R23,R24,S21,S22,S23,S24;
+} poly1305_power;
+
+typedef struct poly1305_state_internal_t {
+	poly1305_power P[2];     /* 288 bytes, top 32 bit halves unused = 144 bytes of free storage */
+	union {
+		xmmi H[5];           /*  80 bytes  */
+		uint64_t HH[10];
+	};
+	/* uint64_t r0,r1,r2;       [24 bytes] */
+	/* uint64_t pad0,pad1;      [16 bytes] */
+	uint64_t started;        /*   8 bytes  */
+	uint64_t leftover;       /*   8 bytes  */
+	uint8_t buffer[64];      /*  64 bytes  */
+} poly1305_state_internal;   /* 448 bytes total + 63 bytes for alignment = 511 bytes raw */
+
+static poly1305_state_internal INLINE
+*poly1305_aligned_state(poly1305_state *state) {
+	return (poly1305_state_internal *)(((uint64_t)state + 63) & ~63);
+}
+
+/* copy 0-63 bytes */
+static void INLINE
+poly1305_block_copy(uint8_t *dst, const uint8_t *src, size_t bytes) {
+	size_t offset = src - dst;
+	if (bytes & 32) {
+		_mm_storeu_si128((xmmi *)(dst + 0), _mm_loadu_si128((xmmi *)(dst + offset + 0)));
+		_mm_storeu_si128((xmmi *)(dst + 16), _mm_loadu_si128((xmmi *)(dst + offset + 16)));
+		dst += 32;
+	}
+	if (bytes & 16) { _mm_storeu_si128((xmmi *)dst, _mm_loadu_si128((xmmi *)(dst + offset))); dst += 16; }
+	if (bytes &  8) { *(uint64_t *)dst = *(uint64_t *)(dst + offset); dst += 8; }
+	if (bytes &  4) { *(uint32_t *)dst = *(uint32_t *)(dst + offset); dst += 4; }
+	if (bytes &  2) { *(uint16_t *)dst = *(uint16_t *)(dst + offset); dst += 2; }
+	if (bytes &  1) { *( uint8_t *)dst = *( uint8_t *)(dst + offset);           }
+}
+
+/* zero 0-15 bytes */
+static void INLINE
+poly1305_block_zero(uint8_t *dst, size_t bytes) {
+	if (bytes &  8) { *(uint64_t *)dst = 0; dst += 8; }
+	if (bytes &  4) { *(uint32_t *)dst = 0; dst += 4; }
+	if (bytes &  2) { *(uint16_t *)dst = 0; dst += 2; }
+	if (bytes &  1) { *( uint8_t *)dst = 0; }
+}
+
+static size_t INLINE
+poly1305_min(size_t a, size_t b) {
+	return (a < b) ? a : b;
+}
+
+void
+Poly1305Init(poly1305_state *state, const unsigned char key[32]) {
+	poly1305_state_internal *st = poly1305_aligned_state(state);
+	poly1305_power *p;
+	uint64_t r0,r1,r2;
+	uint64_t t0,t1;
+
+	/* clamp key */
+	t0 = U8TO64_LE(key + 0);
+	t1 = U8TO64_LE(key + 8);
+	r0 = t0 & 0xffc0fffffff; t0 >>= 44; t0 |= t1 << 20;
+	r1 = t0 & 0xfffffc0ffff; t1 >>= 24;
+	r2 = t1 & 0x00ffffffc0f;
+
+	/* store r in un-used space of st->P[1] */
+	p = &st->P[1];
+	p->R20.d[1] = (uint32_t)(r0      );
+	p->R20.d[3] = (uint32_t)(r0 >> 32);
+	p->R21.d[1] = (uint32_t)(r1      );
+	p->R21.d[3] = (uint32_t)(r1 >> 32);
+	p->R22.d[1] = (uint32_t)(r2      );
+	p->R22.d[3] = (uint32_t)(r2 >> 32);
+
+	/* store pad */
+	p->R23.d[1] = U8TO32_LE(key + 16);
+	p->R23.d[3] = U8TO32_LE(key + 20);
+	p->R24.d[1] = U8TO32_LE(key + 24);
+	p->R24.d[3] = U8TO32_LE(key + 28);
+
+	/* H = 0 */
+	st->H[0] = _mm_setzero_si128();
+	st->H[1] = _mm_setzero_si128();
+	st->H[2] = _mm_setzero_si128();
+	st->H[3] = _mm_setzero_si128();
+	st->H[4] = _mm_setzero_si128();
+
+	st->started = 0;
+	st->leftover = 0;
+}
+
+static void
+poly1305_first_block(poly1305_state_internal *st, const uint8_t *m) {
+	const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+	const xmmi FIVE = _mm_load_si128((xmmi*)poly1305_x64_sse2_5);
+	const xmmi HIBIT = _mm_load_si128((xmmi*)poly1305_x64_sse2_1shl128);
+	xmmi T5,T6;
+	poly1305_power *p;
+	uint128_t d[3];
+	uint64_t r0,r1,r2;
+	uint64_t r20,r21,r22,s22;
+	uint64_t pad0,pad1;
+	uint64_t c;
+	uint64_t i;
+
+	/* pull out stored info */
+	p = &st->P[1];
+
+	r0   = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+	r1   = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+	r2   = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+	pad0 = ((uint64_t)p->R23.d[3] << 32) | (uint64_t)p->R23.d[1];
+	pad1 = ((uint64_t)p->R24.d[3] << 32) | (uint64_t)p->R24.d[1];
+
+	/* compute powers r^2,r^4 */
+	r20 = r0;
+	r21 = r1;
+	r22 = r2;
+	for (i = 0; i < 2; i++) {
+		s22 = r22 * (5 << 2);
+
+		d[0] = add128(mul64x64_128(r20, r20), mul64x64_128(r21 * 2, s22));
+		d[1] = add128(mul64x64_128(r22, s22), mul64x64_128(r20 * 2, r21));
+		d[2] = add128(mul64x64_128(r21, r21), mul64x64_128(r22 * 2, r20));
+
+		                           r20 = lo128(d[0]) & 0xfffffffffff; c = shr128(d[0], 44);
+		d[1] = add128_64(d[1], c); r21 = lo128(d[1]) & 0xfffffffffff; c = shr128(d[1], 44);
+		d[2] = add128_64(d[2], c); r22 = lo128(d[2]) & 0x3ffffffffff; c = shr128(d[2], 42);
+		r20 += c * 5; c = (r20 >> 44); r20 = r20 & 0xfffffffffff;
+		r21 += c;
+
+		p->R20.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)( r20                     ) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R21.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r20 >> 26) | (r21 << 18)) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R22.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r21 >> 8)               ) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R23.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r21 >> 34) | (r22 << 10)) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R24.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r22 >> 16)              )            ), _MM_SHUFFLE(1,0,1,0));
+		p->S21.v = _mm_mul_epu32(p->R21.v, FIVE);
+		p->S22.v = _mm_mul_epu32(p->R22.v, FIVE);
+		p->S23.v = _mm_mul_epu32(p->R23.v, FIVE);
+		p->S24.v = _mm_mul_epu32(p->R24.v, FIVE);
+		p--;
+	}
+
+	/* put saved info back */
+	p = &st->P[1];
+	p->R20.d[1] = (uint32_t)(r0        );
+	p->R20.d[3] = (uint32_t)(r0   >> 32);
+	p->R21.d[1] = (uint32_t)(r1        );
+	p->R21.d[3] = (uint32_t)(r1   >> 32);
+	p->R22.d[1] = (uint32_t)(r2        );
+	p->R22.d[3] = (uint32_t)(r2   >> 32);
+	p->R23.d[1] = (uint32_t)(pad0      );
+	p->R23.d[3] = (uint32_t)(pad0 >> 32);
+	p->R24.d[1] = (uint32_t)(pad1      );
+	p->R24.d[3] = (uint32_t)(pad1 >> 32);
+
+	/* H = [Mx,My] */
+	T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+	T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+	st->H[0] = _mm_and_si128(MMASK, T5);
+	st->H[1] = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+	T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+	st->H[2] = _mm_and_si128(MMASK, T5);
+	st->H[3] = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+	st->H[4] = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+}
+
+static void
+poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, size_t bytes) {
+	const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+	const xmmi FIVE = _mm_load_si128((xmmi*)poly1305_x64_sse2_5);
+	const xmmi HIBIT = _mm_load_si128((xmmi*)poly1305_x64_sse2_1shl128);
+
+	poly1305_power *p;
+	xmmi H0,H1,H2,H3,H4;
+	xmmi T0,T1,T2,T3,T4,T5,T6;
+	xmmi M0,M1,M2,M3,M4;
+	xmmi C1,C2;
+
+	H0 = st->H[0];
+	H1 = st->H[1];
+	H2 = st->H[2];
+	H3 = st->H[3];
+	H4 = st->H[4];
+
+	while (bytes >= 64) {
+		/* H *= [r^4,r^4] */
+		p = &st->P[0];
+		T0 = _mm_mul_epu32(H0, p->R20.v);
+		T1 = _mm_mul_epu32(H0, p->R21.v);
+		T2 = _mm_mul_epu32(H0, p->R22.v);
+		T3 = _mm_mul_epu32(H0, p->R23.v);
+		T4 = _mm_mul_epu32(H0, p->R24.v);
+		T5 = _mm_mul_epu32(H1, p->S24.v); T6 = _mm_mul_epu32(H1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H2, p->S23.v); T6 = _mm_mul_epu32(H2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H3, p->S22.v); T6 = _mm_mul_epu32(H3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H4, p->S21.v); T6 = _mm_mul_epu32(H4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H1, p->R21.v); T6 = _mm_mul_epu32(H1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H2, p->R20.v); T6 = _mm_mul_epu32(H2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H3, p->S24.v); T6 = _mm_mul_epu32(H3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H4, p->S23.v); T6 = _mm_mul_epu32(H4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+		/* H += [Mx,My]*[r^2,r^2] */
+		T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+		T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+		M0 = _mm_and_si128(MMASK, T5);
+		M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+		M2 = _mm_and_si128(MMASK, T5);
+		M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+
+		p = &st->P[1];
+		T5 = _mm_mul_epu32(M0, p->R20.v); T6 = _mm_mul_epu32(M0, p->R21.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M1, p->S24.v); T6 = _mm_mul_epu32(M1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M2, p->S23.v); T6 = _mm_mul_epu32(M2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M3, p->S22.v); T6 = _mm_mul_epu32(M3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M4, p->S21.v); T6 = _mm_mul_epu32(M4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M0, p->R22.v); T6 = _mm_mul_epu32(M0, p->R23.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M1, p->R21.v); T6 = _mm_mul_epu32(M1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M2, p->R20.v); T6 = _mm_mul_epu32(M2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M3, p->S24.v); T6 = _mm_mul_epu32(M3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M4, p->S23.v); T6 = _mm_mul_epu32(M4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M0, p->R24.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+		/* H += [Mx,My] */
+		T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 32)), _mm_loadl_epi64((xmmi *)(m + 48)));
+		T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 40)), _mm_loadl_epi64((xmmi *)(m + 56)));
+		M0 = _mm_and_si128(MMASK, T5);
+		M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+		M2 = _mm_and_si128(MMASK, T5);
+		M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+
+		T0 = _mm_add_epi64(T0, M0);
+		T1 = _mm_add_epi64(T1, M1);
+		T2 = _mm_add_epi64(T2, M2);
+		T3 = _mm_add_epi64(T3, M3);
+		T4 = _mm_add_epi64(T4, M4);
+
+		/* reduce */
+		C1 = _mm_srli_epi64(T0, 26); C2 = _mm_srli_epi64(T3, 26); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_and_si128(T3, MMASK); T1 = _mm_add_epi64(T1, C1); T4 = _mm_add_epi64(T4, C2);
+		C1 = _mm_srli_epi64(T1, 26); C2 = _mm_srli_epi64(T4, 26); T1 = _mm_and_si128(T1, MMASK); T4 = _mm_and_si128(T4, MMASK); T2 = _mm_add_epi64(T2, C1); T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+		C1 = _mm_srli_epi64(T2, 26); C2 = _mm_srli_epi64(T0, 26); T2 = _mm_and_si128(T2, MMASK); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_add_epi64(T3, C1); T1 = _mm_add_epi64(T1, C2);
+		C1 = _mm_srli_epi64(T3, 26);                              T3 = _mm_and_si128(T3, MMASK);                                T4 = _mm_add_epi64(T4, C1);
+
+		/* H = (H*[r^4,r^4] + [Mx,My]*[r^2,r^2] + [Mx,My]) */
+		H0 = T0;
+		H1 = T1;
+		H2 = T2;
+		H3 = T3;
+		H4 = T4;
+
+		m += 64;
+		bytes -= 64;
+	}
+
+	st->H[0] = H0;
+	st->H[1] = H1;
+	st->H[2] = H2;
+	st->H[3] = H3;
+	st->H[4] = H4;
+}
+
+static size_t
+poly1305_combine(poly1305_state_internal *st, const uint8_t *m, size_t bytes) {
+	const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+	const xmmi HIBIT = _mm_load_si128((xmmi*)poly1305_x64_sse2_1shl128);
+	const xmmi FIVE = _mm_load_si128((xmmi*)poly1305_x64_sse2_5);
+
+	poly1305_power *p;
+	xmmi H0,H1,H2,H3,H4;
+	xmmi M0,M1,M2,M3,M4;
+	xmmi T0,T1,T2,T3,T4,T5,T6;
+	xmmi C1,C2;
+
+	uint64_t r0,r1,r2;
+	uint64_t t0,t1,t2,t3,t4;
+	uint64_t c;
+	size_t consumed = 0;
+
+	H0 = st->H[0];
+	H1 = st->H[1];
+	H2 = st->H[2];
+	H3 = st->H[3];
+	H4 = st->H[4];
+
+	/* p = [r^2,r^2] */
+	p = &st->P[1];
+
+	if (bytes >= 32) {
+		/* H *= [r^2,r^2] */
+		T0 = _mm_mul_epu32(H0, p->R20.v);
+		T1 = _mm_mul_epu32(H0, p->R21.v);
+		T2 = _mm_mul_epu32(H0, p->R22.v);
+		T3 = _mm_mul_epu32(H0, p->R23.v);
+		T4 = _mm_mul_epu32(H0, p->R24.v);
+		T5 = _mm_mul_epu32(H1, p->S24.v); T6 = _mm_mul_epu32(H1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H2, p->S23.v); T6 = _mm_mul_epu32(H2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H3, p->S22.v); T6 = _mm_mul_epu32(H3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H4, p->S21.v); T6 = _mm_mul_epu32(H4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H1, p->R21.v); T6 = _mm_mul_epu32(H1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H2, p->R20.v); T6 = _mm_mul_epu32(H2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H3, p->S24.v); T6 = _mm_mul_epu32(H3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H4, p->S23.v); T6 = _mm_mul_epu32(H4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+		/* H += [Mx,My] */
+		T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+		T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+		M0 = _mm_and_si128(MMASK, T5);
+		M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+		M2 = _mm_and_si128(MMASK, T5);
+		M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+
+		T0 = _mm_add_epi64(T0, M0);
+		T1 = _mm_add_epi64(T1, M1);
+		T2 = _mm_add_epi64(T2, M2);
+		T3 = _mm_add_epi64(T3, M3);
+		T4 = _mm_add_epi64(T4, M4);
+
+		/* reduce */
+		C1 = _mm_srli_epi64(T0, 26); C2 = _mm_srli_epi64(T3, 26); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_and_si128(T3, MMASK); T1 = _mm_add_epi64(T1, C1); T4 = _mm_add_epi64(T4, C2);
+		C1 = _mm_srli_epi64(T1, 26); C2 = _mm_srli_epi64(T4, 26); T1 = _mm_and_si128(T1, MMASK); T4 = _mm_and_si128(T4, MMASK); T2 = _mm_add_epi64(T2, C1); T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+		C1 = _mm_srli_epi64(T2, 26); C2 = _mm_srli_epi64(T0, 26); T2 = _mm_and_si128(T2, MMASK); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_add_epi64(T3, C1); T1 = _mm_add_epi64(T1, C2);
+		C1 = _mm_srli_epi64(T3, 26);                              T3 = _mm_and_si128(T3, MMASK);                                T4 = _mm_add_epi64(T4, C1);
+
+		/* H = (H*[r^2,r^2] + [Mx,My]) */
+		H0 = T0;
+		H1 = T1;
+		H2 = T2;
+		H3 = T3;
+		H4 = T4;
+
+		consumed = 32;
+	}
+
+	/* finalize, H *= [r^2,r] */
+	r0 = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+	r1 = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+	r2 = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+
+	p->R20.d[2] = (uint32_t)( r0                    ) & 0x3ffffff;
+	p->R21.d[2] = (uint32_t)((r0 >> 26) | (r1 << 18)) & 0x3ffffff;
+	p->R22.d[2] = (uint32_t)((r1 >> 8)              ) & 0x3ffffff;
+	p->R23.d[2] = (uint32_t)((r1 >> 34) | (r2 << 10)) & 0x3ffffff;
+	p->R24.d[2] = (uint32_t)((r2 >> 16)             )            ;
+	p->S21.d[2] = p->R21.d[2] * 5;
+	p->S22.d[2] = p->R22.d[2] * 5;
+	p->S23.d[2] = p->R23.d[2] * 5;
+	p->S24.d[2] = p->R24.d[2] * 5;
+
+	/* H *= [r^2,r] */
+	T0 = _mm_mul_epu32(H0, p->R20.v);
+	T1 = _mm_mul_epu32(H0, p->R21.v);
+	T2 = _mm_mul_epu32(H0, p->R22.v);
+	T3 = _mm_mul_epu32(H0, p->R23.v);
+	T4 = _mm_mul_epu32(H0, p->R24.v);
+	T5 = _mm_mul_epu32(H1, p->S24.v); T6 = _mm_mul_epu32(H1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H2, p->S23.v); T6 = _mm_mul_epu32(H2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H3, p->S22.v); T6 = _mm_mul_epu32(H3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H4, p->S21.v); T6 = _mm_mul_epu32(H4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H1, p->R21.v); T6 = _mm_mul_epu32(H1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H2, p->R20.v); T6 = _mm_mul_epu32(H2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H3, p->S24.v); T6 = _mm_mul_epu32(H3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H4, p->S23.v); T6 = _mm_mul_epu32(H4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+	T5 = _mm_mul_epu32(H2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+	T5 = _mm_mul_epu32(H3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+	T5 = _mm_mul_epu32(H4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+	C1 = _mm_srli_epi64(T0, 26); C2 = _mm_srli_epi64(T3, 26); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_and_si128(T3, MMASK); T1 = _mm_add_epi64(T1, C1); T4 = _mm_add_epi64(T4, C2);
+	C1 = _mm_srli_epi64(T1, 26); C2 = _mm_srli_epi64(T4, 26); T1 = _mm_and_si128(T1, MMASK); T4 = _mm_and_si128(T4, MMASK); T2 = _mm_add_epi64(T2, C1); T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+	C1 = _mm_srli_epi64(T2, 26); C2 = _mm_srli_epi64(T0, 26); T2 = _mm_and_si128(T2, MMASK); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_add_epi64(T3, C1); T1 = _mm_add_epi64(T1, C2);
+	C1 = _mm_srli_epi64(T3, 26);                              T3 = _mm_and_si128(T3, MMASK);                                T4 = _mm_add_epi64(T4, C1);
+
+	/* H = H[0]+H[1] */
+	H0 = _mm_add_epi64(T0, _mm_srli_si128(T0, 8));
+	H1 = _mm_add_epi64(T1, _mm_srli_si128(T1, 8));
+	H2 = _mm_add_epi64(T2, _mm_srli_si128(T2, 8));
+	H3 = _mm_add_epi64(T3, _mm_srli_si128(T3, 8));
+	H4 = _mm_add_epi64(T4, _mm_srli_si128(T4, 8));
+
+	t0 = _mm_cvtsi128_si32(H0)    ; c = (t0 >> 26); t0 &= 0x3ffffff;
+	t1 = _mm_cvtsi128_si32(H1) + c; c = (t1 >> 26); t1 &= 0x3ffffff;
+	t2 = _mm_cvtsi128_si32(H2) + c; c = (t2 >> 26); t2 &= 0x3ffffff;
+	t3 = _mm_cvtsi128_si32(H3) + c; c = (t3 >> 26); t3 &= 0x3ffffff;
+	t4 = _mm_cvtsi128_si32(H4) + c; c = (t4 >> 26); t4 &= 0x3ffffff;
+	t0 =              t0 + (c * 5); c = (t0 >> 26); t0 &= 0x3ffffff;
+	t1 =              t1 + c;
+
+	st->HH[0] =  ((t0      ) | (t1 << 26)             ) & 0xfffffffffffull;
+	st->HH[1] =  ((t1 >> 18) | (t2 <<  8) | (t3 << 34)) & 0xfffffffffffull;
+	st->HH[2] =  ((t3 >> 10) | (t4 << 16)             ) & 0x3ffffffffffull;
+
+	return consumed;
+}
+
+void
+Poly1305Update(poly1305_state *state, const unsigned char *m, size_t bytes) {
+	poly1305_state_internal *st = poly1305_aligned_state(state);
+	size_t want;
+
+	/* need at least 32 initial bytes to start the accelerated branch */
+	if (!st->started) {
+		if ((st->leftover == 0) && (bytes > 32)) {
+			poly1305_first_block(st, m);
+			m += 32;
+			bytes -= 32;
+		} else {
+			want = poly1305_min(32 - st->leftover, bytes);
+			poly1305_block_copy(st->buffer + st->leftover, m, want);
+			bytes -= want;
+			m += want;
+			st->leftover += want;
+			if ((st->leftover < 32) || (bytes == 0))
+				return;
+			poly1305_first_block(st, st->buffer);
+			st->leftover = 0;
+		}
+		st->started = 1;
+	}
+
+	/* handle leftover */
+	if (st->leftover) {
+		want = poly1305_min(64 - st->leftover, bytes);
+		poly1305_block_copy(st->buffer + st->leftover, m, want);
+		bytes -= want;
+		m += want;
+		st->leftover += want;
+		if (st->leftover < 64)
+			return;
+		poly1305_blocks(st, st->buffer, 64);
+		st->leftover = 0;
+	}
+
+	/* process 64 byte blocks */
+	if (bytes >= 64) {
+		want = (bytes & ~63);
+		poly1305_blocks(st, m, want);
+		m += want;
+		bytes -= want;
+	}
+
+	if (bytes) {
+		poly1305_block_copy(st->buffer + st->leftover, m, bytes);
+		st->leftover += bytes;
+	}
+}
+
+void
+Poly1305Finish(poly1305_state *state, unsigned char mac[16]) {
+	poly1305_state_internal *st = poly1305_aligned_state(state);
+	size_t leftover = st->leftover;
+	uint8_t *m = st->buffer;
+	uint128_t d[3];
+	uint64_t h0,h1,h2;
+	uint64_t t0,t1;
+	uint64_t g0,g1,g2,c,nc;
+	uint64_t r0,r1,r2,s1,s2;
+	poly1305_power *p;
+
+	if (st->started) {
+		size_t consumed = poly1305_combine(st, m, leftover);
+		leftover -= consumed;
+		m += consumed;
+	}
+
+	/* st->HH will either be 0 or have the combined result */
+	h0 = st->HH[0];
+	h1 = st->HH[1];
+	h2 = st->HH[2];
+
+	p = &st->P[1];
+	r0 = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+	r1 = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+	r2 = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+	s1 = r1 * (5 << 2);
+	s2 = r2 * (5 << 2);
+
+	if (leftover < 16)
+		goto poly1305_donna_atmost15bytes;
+
+poly1305_donna_atleast16bytes:
+	t0 = U8TO64_LE(m + 0);
+	t1 = U8TO64_LE(m + 8);
+	h0 += t0 & 0xfffffffffff;
+	t0 = shr128_pair(t1, t0, 44);
+	h1 += t0 & 0xfffffffffff;
+	h2 += (t1 >> 24) | ((uint64_t)1 << 40);
+
+poly1305_donna_mul:
+	d[0] = add128(add128(mul64x64_128(h0, r0), mul64x64_128(h1, s2)), mul64x64_128(h2, s1));
+	d[1] = add128(add128(mul64x64_128(h0, r1), mul64x64_128(h1, r0)), mul64x64_128(h2, s2));
+	d[2] = add128(add128(mul64x64_128(h0, r2), mul64x64_128(h1, r1)), mul64x64_128(h2, r0));
+	                           h0 = lo128(d[0]) & 0xfffffffffff; c = shr128(d[0], 44);
+	d[1] = add128_64(d[1], c); h1 = lo128(d[1]) & 0xfffffffffff; c = shr128(d[1], 44);
+	d[2] = add128_64(d[2], c); h2 = lo128(d[2]) & 0x3ffffffffff; c = shr128(d[2], 42);
+	h0   += c * 5;
+
+	m += 16;
+	leftover -= 16;
+	if (leftover >= 16) goto poly1305_donna_atleast16bytes;
+
+	/* final bytes */
+poly1305_donna_atmost15bytes:
+	if (!leftover) goto poly1305_donna_finish;
+
+	m[leftover++] = 1;
+	poly1305_block_zero(m + leftover, 16 - leftover);
+	leftover = 16;
+
+	t0 = U8TO64_LE(m+0);
+	t1 = U8TO64_LE(m+8);
+	h0 += t0 & 0xfffffffffff; t0 = shr128_pair(t1, t0, 44);
+	h1 += t0 & 0xfffffffffff;
+	h2 += (t1 >> 24);
+
+	goto poly1305_donna_mul;
+
+poly1305_donna_finish:
+	             c = (h0 >> 44); h0 &= 0xfffffffffff;
+	h1 += c;     c = (h1 >> 44); h1 &= 0xfffffffffff;
+	h2 += c;     c = (h2 >> 42); h2 &= 0x3ffffffffff;
+	h0 += c * 5;
+
+	g0 = h0 + 5; c = (g0 >> 44); g0 &= 0xfffffffffff;
+	g1 = h1 + c; c = (g1 >> 44); g1 &= 0xfffffffffff;
+	g2 = h2 + c - ((uint64_t)1 << 42);
+
+	c = (g2 >> 63) - 1;
+	nc = ~c;
+	h0 = (h0 & nc) | (g0 & c);
+	h1 = (h1 & nc) | (g1 & c);
+	h2 = (h2 & nc) | (g2 & c);
+
+	/* pad */
+	t0 = ((uint64_t)p->R23.d[3] << 32) | (uint64_t)p->R23.d[1];
+	t1 = ((uint64_t)p->R24.d[3] << 32) | (uint64_t)p->R24.d[1];
+	h0 += (t0 & 0xfffffffffff)    ; c = (h0 >> 44); h0 &= 0xfffffffffff; t0 = shr128_pair(t1, t0, 44);
+	h1 += (t0 & 0xfffffffffff) + c; c = (h1 >> 44); h1 &= 0xfffffffffff; t1 = (t1 >> 24);
+	h2 += (t1                ) + c;
+
+	U64TO8_LE(mac + 0, ((h0      ) | (h1 << 44)));
+	U64TO8_LE(mac + 8, ((h1 >> 20) | (h2 << 24)));
+}
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/poly1305.c
@@ -0,0 +1,261 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This implementation of poly1305 is by Andrew Moon
+ * (https://github.com/floodyberry/poly1305-donna) and released as public
+ * domain. */
+
+#include <string.h>
+
+#include "poly1305.h"
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+#include "prtypes.h"
+typedef PRUint32 uint32_t;
+typedef PRUint64 uint64_t;
+#else
+#include <stdint.h>
+#endif
+
+#if defined(NSS_X86) || defined(NSS_X64)
+/* We can assume little-endian. */
+static uint32_t U8TO32_LE(const unsigned char *m) {
+	uint32_t r;
+	memcpy(&r, m, sizeof(r));
+	return r;
+}
+
+static void U32TO8_LE(unsigned char *m, uint32_t v) {
+	memcpy(m, &v, sizeof(v));
+}
+#else
+static uint32_t U8TO32_LE(const unsigned char *m) {
+	return (uint32_t)m[0] |
+	       (uint32_t)m[1] << 8 |
+	       (uint32_t)m[2] << 16 |
+	       (uint32_t)m[3] << 24;
+}
+
+static void U32TO8_LE(unsigned char *m, uint32_t v) {
+	m[0] = v;
+	m[1] = v >> 8;
+	m[2] = v >> 16;
+	m[3] = v >> 24;
+}
+#endif
+
+static uint64_t
+mul32x32_64(uint32_t a, uint32_t b) {
+	return (uint64_t)a * b;
+}
+
+struct poly1305_state_st {
+	uint32_t r0,r1,r2,r3,r4;
+	uint32_t s1,s2,s3,s4;
+	uint32_t h0,h1,h2,h3,h4;
+	unsigned char buf[16];
+	unsigned int buf_used;
+	unsigned char key[16];
+};
+
+/* update updates |state| given some amount of input data. This function may
+ * only be called with a |len| that is not a multiple of 16 at the end of the
+ * data. Otherwise the input must be buffered into 16 byte blocks. */
+static void update(struct poly1305_state_st *state, const unsigned char *in,
+		   size_t len) {
+	uint32_t t0,t1,t2,t3;
+	uint64_t t[5];
+	uint32_t b;
+	uint64_t c;
+	size_t j;
+	unsigned char mp[16];
+
+	if (len < 16)
+		goto poly1305_donna_atmost15bytes;
+
+poly1305_donna_16bytes:
+	t0 = U8TO32_LE(in);
+	t1 = U8TO32_LE(in+4);
+	t2 = U8TO32_LE(in+8);
+	t3 = U8TO32_LE(in+12);
+
+	in += 16;
+	len -= 16;
+
+	state->h0 += t0 & 0x3ffffff;
+	state->h1 += ((((uint64_t)t1 << 32) | t0) >> 26) & 0x3ffffff;
+	state->h2 += ((((uint64_t)t2 << 32) | t1) >> 20) & 0x3ffffff;
+	state->h3 += ((((uint64_t)t3 << 32) | t2) >> 14) & 0x3ffffff;
+	state->h4 += (t3 >> 8) | (1 << 24);
+
+poly1305_donna_mul:
+	t[0] = mul32x32_64(state->h0,state->r0) +
+	       mul32x32_64(state->h1,state->s4) +
+	       mul32x32_64(state->h2,state->s3) +
+	       mul32x32_64(state->h3,state->s2) +
+	       mul32x32_64(state->h4,state->s1);
+	t[1] = mul32x32_64(state->h0,state->r1) +
+	       mul32x32_64(state->h1,state->r0) +
+	       mul32x32_64(state->h2,state->s4) +
+	       mul32x32_64(state->h3,state->s3) +
+	       mul32x32_64(state->h4,state->s2);
+	t[2] = mul32x32_64(state->h0,state->r2) +
+	       mul32x32_64(state->h1,state->r1) +
+	       mul32x32_64(state->h2,state->r0) +
+	       mul32x32_64(state->h3,state->s4) +
+	       mul32x32_64(state->h4,state->s3);
+	t[3] = mul32x32_64(state->h0,state->r3) +
+	       mul32x32_64(state->h1,state->r2) +
+	       mul32x32_64(state->h2,state->r1) +
+	       mul32x32_64(state->h3,state->r0) +
+	       mul32x32_64(state->h4,state->s4);
+	t[4] = mul32x32_64(state->h0,state->r4) +
+	       mul32x32_64(state->h1,state->r3) +
+	       mul32x32_64(state->h2,state->r2) +
+	       mul32x32_64(state->h3,state->r1) +
+	       mul32x32_64(state->h4,state->r0);
+
+	           state->h0 = (uint32_t)t[0] & 0x3ffffff; c =           (t[0] >> 26);
+	t[1] += c; state->h1 = (uint32_t)t[1] & 0x3ffffff; b = (uint32_t)(t[1] >> 26);
+	t[2] += b; state->h2 = (uint32_t)t[2] & 0x3ffffff; b = (uint32_t)(t[2] >> 26);
+	t[3] += b; state->h3 = (uint32_t)t[3] & 0x3ffffff; b = (uint32_t)(t[3] >> 26);
+	t[4] += b; state->h4 = (uint32_t)t[4] & 0x3ffffff; b = (uint32_t)(t[4] >> 26);
+	state->h0 += b * 5;
+
+	if (len >= 16)
+		goto poly1305_donna_16bytes;
+
+	/* final bytes */
+poly1305_donna_atmost15bytes:
+	if (!len)
+		return;
+
+	for (j = 0; j < len; j++)
+		mp[j] = in[j];
+	mp[j++] = 1;
+	for (; j < 16; j++)
+		mp[j] = 0;
+	len = 0;
+
+	t0 = U8TO32_LE(mp+0);
+	t1 = U8TO32_LE(mp+4);
+	t2 = U8TO32_LE(mp+8);
+	t3 = U8TO32_LE(mp+12);
+
+	state->h0 += t0 & 0x3ffffff;
+	state->h1 += ((((uint64_t)t1 << 32) | t0) >> 26) & 0x3ffffff;
+	state->h2 += ((((uint64_t)t2 << 32) | t1) >> 20) & 0x3ffffff;
+	state->h3 += ((((uint64_t)t3 << 32) | t2) >> 14) & 0x3ffffff;
+	state->h4 += (t3 >> 8);
+
+	goto poly1305_donna_mul;
+}
+
+void Poly1305Init(poly1305_state *statep, const unsigned char key[32]) {
+	struct poly1305_state_st *state = (struct poly1305_state_st*) statep;
+	uint32_t t0,t1,t2,t3;
+
+	t0 = U8TO32_LE(key+0);
+	t1 = U8TO32_LE(key+4);
+	t2 = U8TO32_LE(key+8);
+	t3 = U8TO32_LE(key+12);
+
+	/* precompute multipliers */
+	state->r0 = t0 & 0x3ffffff; t0 >>= 26; t0 |= t1 << 6;
+	state->r1 = t0 & 0x3ffff03; t1 >>= 20; t1 |= t2 << 12;
+	state->r2 = t1 & 0x3ffc0ff; t2 >>= 14; t2 |= t3 << 18;
+	state->r3 = t2 & 0x3f03fff; t3 >>= 8;
+	state->r4 = t3 & 0x00fffff;
+
+	state->s1 = state->r1 * 5;
+	state->s2 = state->r2 * 5;
+	state->s3 = state->r3 * 5;
+	state->s4 = state->r4 * 5;
+
+	/* init state */
+	state->h0 = 0;
+	state->h1 = 0;
+	state->h2 = 0;
+	state->h3 = 0;
+	state->h4 = 0;
+
+	state->buf_used = 0;
+	memcpy(state->key, key + 16, sizeof(state->key));
+}
+
+void Poly1305Update(poly1305_state *statep, const unsigned char *in,
+		     size_t in_len) {
+	unsigned int i;
+	struct poly1305_state_st *state = (struct poly1305_state_st*) statep;
+
+	if (state->buf_used) {
+		unsigned int todo = 16 - state->buf_used;
+		if (todo > in_len)
+			todo = in_len;
+		for (i = 0; i < todo; i++)
+			state->buf[state->buf_used + i] = in[i];
+		state->buf_used += todo;
+		in_len -= todo;
+		in += todo;
+
+		if (state->buf_used == 16) {
+			update(state, state->buf, 16);
+			state->buf_used = 0;
+		}
+	}
+
+	if (in_len >= 16) {
+		size_t todo = in_len & ~0xf;
+		update(state, in, todo);
+		in += todo;
+		in_len &= 0xf;
+	}
+
+	if (in_len) {
+		for (i = 0; i < in_len; i++)
+			state->buf[i] = in[i];
+		state->buf_used = in_len;
+	}
+}
+
+void Poly1305Finish(poly1305_state *statep, unsigned char mac[16]) {
+	struct poly1305_state_st *state = (struct poly1305_state_st*) statep;
+	uint64_t f0,f1,f2,f3;
+	uint32_t g0,g1,g2,g3,g4;
+	uint32_t b, nb;
+
+	if (state->buf_used)
+		update(state, state->buf, state->buf_used);
+
+	                    b = state->h0 >> 26; state->h0 = state->h0 & 0x3ffffff;
+	state->h1 +=     b; b = state->h1 >> 26; state->h1 = state->h1 & 0x3ffffff;
+	state->h2 +=     b; b = state->h2 >> 26; state->h2 = state->h2 & 0x3ffffff;
+	state->h3 +=     b; b = state->h3 >> 26; state->h3 = state->h3 & 0x3ffffff;
+	state->h4 +=     b; b = state->h4 >> 26; state->h4 = state->h4 & 0x3ffffff;
+	state->h0 += b * 5;
+
+	g0 = state->h0 + 5; b = g0 >> 26; g0 &= 0x3ffffff;
+	g1 = state->h1 + b; b = g1 >> 26; g1 &= 0x3ffffff;
+	g2 = state->h2 + b; b = g2 >> 26; g2 &= 0x3ffffff;
+	g3 = state->h3 + b; b = g3 >> 26; g3 &= 0x3ffffff;
+	g4 = state->h4 + b - (1 << 26);
+
+	b = (g4 >> 31) - 1;
+	nb = ~b;
+	state->h0 = (state->h0 & nb) | (g0 & b);
+	state->h1 = (state->h1 & nb) | (g1 & b);
+	state->h2 = (state->h2 & nb) | (g2 & b);
+	state->h3 = (state->h3 & nb) | (g3 & b);
+	state->h4 = (state->h4 & nb) | (g4 & b);
+
+	f0 = ((state->h0      ) | (state->h1 << 26)) + (uint64_t)U8TO32_LE(&state->key[0]);
+	f1 = ((state->h1 >>  6) | (state->h2 << 20)) + (uint64_t)U8TO32_LE(&state->key[4]);
+	f2 = ((state->h2 >> 12) | (state->h3 << 14)) + (uint64_t)U8TO32_LE(&state->key[8]);
+	f3 = ((state->h3 >> 18) | (state->h4 <<  8)) + (uint64_t)U8TO32_LE(&state->key[12]);
+
+	U32TO8_LE(&mac[ 0], (uint32_t)f0); f1 += (f0 >> 32);
+	U32TO8_LE(&mac[ 4], (uint32_t)f1); f2 += (f1 >> 32);
+	U32TO8_LE(&mac[ 8], (uint32_t)f2); f3 += (f2 >> 32);
+	U32TO8_LE(&mac[12], (uint32_t)f3);
+}
new file mode 100644
--- /dev/null
+++ b/security/nss/lib/freebl/poly1305.h
@@ -0,0 +1,28 @@
+/*
+ * poly1305.h - header file for Poly1305 implementation.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef FREEBL_POLY1305_H_
+#define FREEBL_POLY1305_H_
+
+typedef unsigned char poly1305_state[512];
+
+/* Poly1305Init sets up |state| so that it can be used to calculate an
+ * authentication tag with the one-time key |key|. Note that |key| is a
+ * one-time key and therefore there is no `reset' method because that would
+ * enable several messages to be authenticated with the same key. */
+extern void Poly1305Init(poly1305_state* state, const unsigned char key[32]);
+
+/* Poly1305Update processes |in_len| bytes from |in|. It can be called zero or
+ * more times after poly1305_init. */
+extern void Poly1305Update(poly1305_state* state, const unsigned char* in,
+                           size_t inLen);
+
+/* Poly1305Finish completes the poly1305 calculation and writes a 16 byte
+ * authentication tag to |mac|. */
+extern void Poly1305Finish(poly1305_state* state, unsigned char mac[16]);
+
+#endif /* FREEBL_POLY1305_H_ */
--- a/security/nss/lib/pk11wrap/pk11mech.c
+++ b/security/nss/lib/pk11wrap/pk11mech.c
@@ -147,16 +147,18 @@ PK11_AddMechanismEntry(CK_MECHANISM_TYPE
 CK_MECHANISM_TYPE
 PK11_GetKeyMechanism(CK_KEY_TYPE type)
 {
     switch (type) {
     case CKK_SEED:
 	return CKM_SEED_CBC;
     case CKK_CAMELLIA:
 	return CKM_CAMELLIA_CBC;
+    case CKK_NSS_CHACHA20:
+	return CKM_NSS_CHACHA20_POLY1305;
     case CKK_AES:
 	return CKM_AES_CBC;
     case CKK_DES:
 	return CKM_DES_CBC;
     case CKK_DES3:
 	return CKM_DES3_KEY_GEN;
     case CKK_DES2:
 	return CKM_DES2_KEY_GEN;
@@ -214,16 +216,19 @@ PK11_GetKeyType(CK_MECHANISM_TYPE type,u
 	return CKK_SEED;
     case CKM_CAMELLIA_ECB:
     case CKM_CAMELLIA_CBC:
     case CKM_CAMELLIA_MAC:
     case CKM_CAMELLIA_MAC_GENERAL:
     case CKM_CAMELLIA_CBC_PAD:
     case CKM_CAMELLIA_KEY_GEN:
 	return CKK_CAMELLIA;
+    case CKM_NSS_CHACHA20_POLY1305:
+    case CKM_NSS_CHACHA20_KEY_GEN:
+	return CKK_NSS_CHACHA20;
     case CKM_AES_ECB:
     case CKM_AES_CBC:
     case CKM_AES_CCM:
     case CKM_AES_CTR:
     case CKM_AES_CTS:
     case CKM_AES_GCM:
     case CKM_AES_MAC:
     case CKM_AES_MAC_GENERAL:
@@ -426,16 +431,18 @@ PK11_GetKeyGenWithSize(CK_MECHANISM_TYPE
 	return CKM_SEED_KEY_GEN;
     case CKM_CAMELLIA_ECB:
     case CKM_CAMELLIA_CBC:
     case CKM_CAMELLIA_MAC:
     case CKM_CAMELLIA_MAC_GENERAL:
     case CKM_CAMELLIA_CBC_PAD:
     case CKM_CAMELLIA_KEY_GEN:
 	return CKM_CAMELLIA_KEY_GEN;
+    case CKM_NSS_CHACHA20_POLY1305:
+	return CKM_NSS_CHACHA20_KEY_GEN;
     case CKM_AES_ECB:
     case CKM_AES_CBC:
     case CKM_AES_CCM:
     case CKM_AES_CTR:
     case CKM_AES_CTS:
     case CKM_AES_GCM:
     case CKM_AES_MAC:
     case CKM_AES_MAC_GENERAL:
--- a/security/nss/lib/pk11wrap/pk11pars.c
+++ b/security/nss/lib/pk11wrap/pk11pars.c
@@ -349,16 +349,17 @@ static const oidValDef algOptList[] = {
     {CIPHER_NAME("AES192-CBC"), SEC_OID_AES_192_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("AES256-CBC"), SEC_OID_AES_256_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("AES128-GCM"), SEC_OID_AES_128_GCM, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("AES192-GCM"), SEC_OID_AES_192_GCM, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("AES256-GCM"), SEC_OID_AES_256_GCM, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("CAMELLIA128-CBC"), SEC_OID_CAMELLIA_128_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("CAMELLIA192-CBC"), SEC_OID_CAMELLIA_192_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("CAMELLIA256-CBC"), SEC_OID_CAMELLIA_256_CBC, NSS_USE_ALG_IN_SSL},
+    {CIPHER_NAME("CHACHA20-POLY1305"), SEC_OID_CHACHA20_POLY1305, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("SEED-CBC"), SEC_OID_SEED_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("DES-EDE3-CBC"), SEC_OID_DES_EDE3_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("DES-40-CBC"), SEC_OID_DES_40_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("DES-CBC"), SEC_OID_DES_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("NULL-CIPHER"), SEC_OID_NULL_CIPHER, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("RC2"), SEC_OID_RC2_CBC, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("RC4"), SEC_OID_RC4, NSS_USE_ALG_IN_SSL},
     {CIPHER_NAME("IDEA"), SEC_OID_IDEA_CBC, NSS_USE_ALG_IN_SSL},
--- a/security/nss/lib/pkcs7/p7local.c
+++ b/security/nss/lib/pkcs7/p7local.c
@@ -706,17 +706,17 @@ sec_PKCS7Encrypt (sec_PKCS7CipherObject 
 
 	pcount = input_len - ifraglen;
 	PORT_Assert (pcount < bsize);
 	if (pcount)
 	    PORT_Memcpy (pbuf, input + ifraglen, pcount);
     }
 
     if (final) {
-	padlen = padsize - (pcount % padsize);
+	padlen = padsize ? padsize - (pcount % padsize) : 0;
 	PORT_Memset (pbuf + pcount, padlen, padlen);
 	rv = (* obj->doit) (obj->cx, output, &ofraglen, max_output_len,
 			    pbuf, pcount+padlen);
 	if (rv != SECSuccess)
 	    return rv;
 
 	/*
 	 * For now anyway, all of our ciphers have the same number of
--- a/security/nss/lib/softoken/pkcs11.c
+++ b/security/nss/lib/softoken/pkcs11.c
@@ -365,16 +365,21 @@ static const struct mechanismList mechan
      {CKM_CAMELLIA_CBC_PAD,	{16, 32, CKF_EN_DE_WR_UN},      PR_TRUE},
      /* ------------------------- SEED Operations --------------------------- */
      {CKM_SEED_KEY_GEN,		{16, 16, CKF_GENERATE},		PR_TRUE},
      {CKM_SEED_ECB,		{16, 16, CKF_EN_DE_WR_UN},	PR_TRUE},
      {CKM_SEED_CBC,		{16, 16, CKF_EN_DE_WR_UN},	PR_TRUE},
      {CKM_SEED_MAC,		{16, 16, CKF_SN_VR},		PR_TRUE},
      {CKM_SEED_MAC_GENERAL,	{16, 16, CKF_SN_VR},		PR_TRUE},
      {CKM_SEED_CBC_PAD,		{16, 16, CKF_EN_DE_WR_UN},	PR_TRUE},
+#ifndef NSS_DISABLE_CHACHAPOLY
+     /* ------------------------- ChaCha20 Operations ---------------------- */
+     {CKM_NSS_CHACHA20_KEY_GEN,	{32, 32, CKF_GENERATE},		PR_TRUE},
+     {CKM_NSS_CHACHA20_POLY1305,{32, 32, CKF_EN_DE},		PR_TRUE},
+#endif /* NSS_DISABLE_CHACHAPOLY */
      /* ------------------------- Hashing Operations ----------------------- */
      {CKM_MD2,			{0,   0, CKF_DIGEST},		PR_FALSE},
      {CKM_MD2_HMAC,		{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_MD2_HMAC_GENERAL,	{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_MD5,			{0,   0, CKF_DIGEST},		PR_FALSE},
      {CKM_MD5_HMAC,		{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_MD5_HMAC_GENERAL,	{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_SHA_1,		{0,   0, CKF_DIGEST},		PR_FALSE},
--- a/security/nss/lib/softoken/pkcs11c.c
+++ b/security/nss/lib/softoken/pkcs11c.c
@@ -660,16 +660,107 @@ sftk_RSADecryptOAEP(SFTKOAEPDecryptInfo 
                          info->params->ulSourceDataLen,
                          output, outputLen, maxLen, input, inputLen);
      if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
         sftk_fatalError = PR_TRUE;
     }
     return rv;
 }
 
+static SFTKChaCha20Poly1305Info *
+sftk_ChaCha20Poly1305_CreateContext(const unsigned char *key,
+                                    unsigned int keyLen,
+                                    const CK_NSS_AEAD_PARAMS *params)
+{
+    SFTKChaCha20Poly1305Info *ctx;
+
+    if (params->ulNonceLen != sizeof(ctx->nonce)) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return NULL;
+    }
+
+    ctx = PORT_New(SFTKChaCha20Poly1305Info);
+    if (ctx == NULL) {
+        return NULL;
+    }
+
+    if (ChaCha20Poly1305_InitContext(&ctx->freeblCtx, key, keyLen,
+                                     params->ulTagLen) != SECSuccess) {
+        PORT_Free(ctx);
+        return NULL;
+    }
+
+    PORT_Memcpy(ctx->nonce, params->pNonce, sizeof(ctx->nonce));
+
+    if (params->ulAADLen > sizeof(ctx->ad)) {
+        /* Need to allocate an overflow buffer for the additional data. */
+        ctx->adOverflow = (unsigned char *)PORT_Alloc(params->ulAADLen);
+        if (!ctx->adOverflow) {
+            PORT_Free(ctx);
+            return NULL;
+        }
+        PORT_Memcpy(ctx->adOverflow, params->pAAD, params->ulAADLen);
+    } else {
+        ctx->adOverflow = NULL;
+        PORT_Memcpy(ctx->ad, params->pAAD, params->ulAADLen);
+    }
+    ctx->adLen = params->ulAADLen;
+
+    return ctx;
+}
+
+static void
+sftk_ChaCha20Poly1305_DestroyContext(SFTKChaCha20Poly1305Info *ctx,
+                                     PRBool freeit)
+{
+    ChaCha20Poly1305_DestroyContext(&ctx->freeblCtx, PR_FALSE);
+    if (ctx->adOverflow != NULL) {
+        PORT_Free(ctx->adOverflow);
+        ctx->adOverflow = NULL;
+    }
+    ctx->adLen = 0;
+    if (freeit) {
+        PORT_Free(ctx);
+    }
+}
+
+static SECStatus
+sftk_ChaCha20Poly1305_Encrypt(const SFTKChaCha20Poly1305Info *ctx,
+                              unsigned char *output, unsigned int *outputLen,
+                              unsigned int maxOutputLen,
+                              const unsigned char *input, unsigned int inputLen)
+{
+    const unsigned char *ad = ctx->adOverflow;
+
+    if (ad == NULL) {
+        ad = ctx->ad;
+    }
+
+    return ChaCha20Poly1305_Seal(&ctx->freeblCtx, output, outputLen,
+                                 maxOutputLen, input, inputLen, ctx->nonce,
+                                 sizeof(ctx->nonce), ad, ctx->adLen);
+}
+
+static SECStatus
+sftk_ChaCha20Poly1305_Decrypt(const SFTKChaCha20Poly1305Info *ctx,
+                              unsigned char *output, unsigned int *outputLen,
+                              unsigned int maxOutputLen,
+                              const unsigned char *input, unsigned int inputLen)
+{
+    const unsigned char *ad = ctx->adOverflow;
+
+    if (ad == NULL) {
+        ad = ctx->ad;
+    }
+
+    return ChaCha20Poly1305_Open(&ctx->freeblCtx, output, outputLen,
+                                 maxOutputLen, input, inputLen, ctx->nonce,
+                                 sizeof(ctx->nonce), ad, ctx->adLen);
+}
+
 /** NSC_CryptInit initializes an encryption/Decryption operation.
  *
  * Always called by NSC_EncryptInit, NSC_DecryptInit, NSC_WrapKey,NSC_UnwrapKey.
  * Called by NSC_SignInit, NSC_VerifyInit (via sftk_InitCBCMac) only for block
  *  ciphers MAC'ing.
  */
 static CK_RV
 sftk_CryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
@@ -877,17 +968,16 @@ sftk_CryptInit(CK_SESSION_HANDLE hSessio
 	/* fall thru */
     case CKM_CDMF_ECB:
     case CKM_CDMF_CBC:
 	if (key_type != CKK_CDMF) {
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
 	    break;
 	}
 	t = (pMechanism->mechanism == CKM_CDMF_ECB) ? NSS_DES : NSS_DES_CBC;
-	if (crv != CKR_OK) break;
 	goto finish_des;
     case CKM_DES_ECB:
 	if (key_type != CKK_DES) {
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
 	    break;
 	}
 	t = NSS_DES;
 	goto finish_des;
@@ -1053,16 +1143,44 @@ finish_des:
 	if (context->cipherInfo == NULL) {
 	    crv = CKR_HOST_MEMORY;
 	    break;
 	}
 	context->update = (SFTKCipher) (isEncrypt ? AES_Encrypt : AES_Decrypt);
 	context->destroy = (SFTKDestroy) AES_DestroyContext;
 	break;
 
+    case CKM_NSS_CHACHA20_POLY1305:
+	if (pMechanism->ulParameterLen != sizeof(CK_NSS_AEAD_PARAMS)) {
+	    crv = CKR_MECHANISM_PARAM_INVALID;
+	    break;
+	}
+	context->multi = PR_FALSE;
+	if (key_type != CKK_NSS_CHACHA20) {
+	    crv = CKR_KEY_TYPE_INCONSISTENT;
+	    break;
+	}
+	att = sftk_FindAttribute(key,CKA_VALUE);
+	if (att == NULL) {
+	    crv = CKR_KEY_HANDLE_INVALID;
+	    break;
+	}
+	context->cipherInfo = sftk_ChaCha20Poly1305_CreateContext(
+		(unsigned char*) att->attrib.pValue, att->attrib.ulValueLen,
+		(CK_NSS_AEAD_PARAMS*) pMechanism->pParameter);
+	sftk_FreeAttribute(att);
+	if (context->cipherInfo == NULL) {
+	    crv = sftk_MapCryptError(PORT_GetError());
+	    break;
+	}
+	context->update = (SFTKCipher) (isEncrypt ? sftk_ChaCha20Poly1305_Encrypt :
+					sftk_ChaCha20Poly1305_Decrypt);
+	context->destroy = (SFTKDestroy) sftk_ChaCha20Poly1305_DestroyContext;
+	break;
+
     case CKM_NETSCAPE_AES_KEY_WRAP_PAD:
     	context->doPad = PR_TRUE;
 	/* fall thru */
     case CKM_NETSCAPE_AES_KEY_WRAP:
 	context->multi = PR_FALSE;
 	context->blockSize = 8;
 	if (key_type != CKK_AES) {
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
@@ -3650,16 +3768,20 @@ nsc_SetupBulkKeyGen(CK_MECHANISM_TYPE me
     case CKM_CAMELLIA_KEY_GEN:
 	*key_type = CKK_CAMELLIA;
 	if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE;
 	break;
     case CKM_AES_KEY_GEN:
 	*key_type = CKK_AES;
 	if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE;
 	break;
+    case CKM_NSS_CHACHA20_KEY_GEN:
+	*key_type = CKK_NSS_CHACHA20;
+	if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE;
+	break;
     default:
 	PORT_Assert(0);
 	crv = CKR_MECHANISM_INVALID;
 	break;
     }
 
     return crv;
 }
@@ -3911,16 +4033,17 @@ CK_RV NSC_GenerateKey(CK_SESSION_HANDLE 
 	checkWeak = PR_TRUE;
         /* fall through */
     case CKM_RC2_KEY_GEN:
     case CKM_RC4_KEY_GEN:
     case CKM_GENERIC_SECRET_KEY_GEN:
     case CKM_SEED_KEY_GEN:
     case CKM_CAMELLIA_KEY_GEN:
     case CKM_AES_KEY_GEN:
+    case CKM_NSS_CHACHA20_KEY_GEN:
 #if NSS_SOFTOKEN_DOES_RC5
     case CKM_RC5_KEY_GEN:
 #endif
 	crv = nsc_SetupBulkKeyGen(pMechanism->mechanism,&key_type,&key_length);
 	break;
     case CKM_SSL3_PRE_MASTER_KEY_GEN:
 	key_type = CKK_GENERIC_SECRET;
 	key_length = 48;
@@ -4052,24 +4175,25 @@ jpake1:
         return CKR_SESSION_HANDLE_INVALID;
     }
 
     /*
      * handle the base object stuff
      */
     crv = sftk_handleObject(key,session);
     sftk_FreeSession(session);
-    if (sftk_isTrue(key,CKA_SENSITIVE)) {
-	sftk_forceAttribute(key,CKA_ALWAYS_SENSITIVE,&cktrue,sizeof(CK_BBOOL));
-    }
-    if (!sftk_isTrue(key,CKA_EXTRACTABLE)) {
-	sftk_forceAttribute(key,CKA_NEVER_EXTRACTABLE,&cktrue,sizeof(CK_BBOOL));
-    }
-
-    *phKey = key->handle;
+    if (crv == CKR_OK && sftk_isTrue(key,CKA_SENSITIVE)) {
+	crv = sftk_forceAttribute(key,CKA_ALWAYS_SENSITIVE,&cktrue,sizeof(CK_BBOOL));
+    }
+    if (crv == CKR_OK && !sftk_isTrue(key,CKA_EXTRACTABLE)) {
+	crv = sftk_forceAttribute(key,CKA_NEVER_EXTRACTABLE,&cktrue,sizeof(CK_BBOOL));
+    }
+    if (crv == CKR_OK) {
+	*phKey = key->handle;
+    }
     sftk_FreeObject(key);
     return crv;
 }
 
 #define PAIRWISE_DIGEST_LENGTH			SHA1_LENGTH /* 160-bits */
 #define PAIRWISE_MESSAGE_LENGTH			20          /* 160-bits */
 
 /*
@@ -4858,51 +4982,56 @@ ecgn_done:
     sftk_FreeSession(session);
     if (crv != CKR_OK) {
 	sftk_FreeObject(publicKey);
 	NSC_DestroyObject(hSession,privateKey->handle);
 	sftk_FreeObject(privateKey);
 	return crv;
     }
     if (sftk_isTrue(privateKey,CKA_SENSITIVE)) {
-	sftk_forceAttribute(privateKey,CKA_ALWAYS_SENSITIVE,
+	crv = sftk_forceAttribute(privateKey,CKA_ALWAYS_SENSITIVE,
+						&cktrue,sizeof(CK_BBOOL));
+    }
+    if (crv == CKR_OK && sftk_isTrue(publicKey,CKA_SENSITIVE)) {
+	crv = sftk_forceAttribute(publicKey,CKA_ALWAYS_SENSITIVE,
 						&cktrue,sizeof(CK_BBOOL));
     }
-    if (sftk_isTrue(publicKey,CKA_SENSITIVE)) {
-	sftk_forceAttribute(publicKey,CKA_ALWAYS_SENSITIVE,
+    if (crv == CKR_OK && !sftk_isTrue(privateKey,CKA_EXTRACTABLE)) {
+	crv = sftk_forceAttribute(privateKey,CKA_NEVER_EXTRACTABLE,
 						&cktrue,sizeof(CK_BBOOL));
     }
-    if (!sftk_isTrue(privateKey,CKA_EXTRACTABLE)) {
-	sftk_forceAttribute(privateKey,CKA_NEVER_EXTRACTABLE,
+    if (crv == CKR_OK && !sftk_isTrue(publicKey,CKA_EXTRACTABLE)) {
+	crv = sftk_forceAttribute(publicKey,CKA_NEVER_EXTRACTABLE,
 						&cktrue,sizeof(CK_BBOOL));
     }
-    if (!sftk_isTrue(publicKey,CKA_EXTRACTABLE)) {
-	sftk_forceAttribute(publicKey,CKA_NEVER_EXTRACTABLE,
-						&cktrue,sizeof(CK_BBOOL));
-    }
-
-    /* Perform FIPS 140-2 pairwise consistency check. */
-    crv = sftk_PairwiseConsistencyCheck(hSession,
-					publicKey, privateKey, key_type);
+
+    if (crv == CKR_OK) {
+	/* Perform FIPS 140-2 pairwise consistency check. */
+	crv = sftk_PairwiseConsistencyCheck(hSession,
+					    publicKey, privateKey, key_type);
+	if (crv != CKR_OK) {
+	    if (sftk_audit_enabled) {
+		char msg[128];
+		PR_snprintf(msg,sizeof msg,
+			    "C_GenerateKeyPair(hSession=0x%08lX, "
+			    "pMechanism->mechanism=0x%08lX)=0x%08lX "
+			    "self-test: pair-wise consistency test failed",
+			    (PRUint32)hSession,(PRUint32)pMechanism->mechanism,
+			    (PRUint32)crv);
+		sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg);
+	    }
+	    return crv;
+	}
+    }
+
     if (crv != CKR_OK) {
 	NSC_DestroyObject(hSession,publicKey->handle);
 	sftk_FreeObject(publicKey);
 	NSC_DestroyObject(hSession,privateKey->handle);
 	sftk_FreeObject(privateKey);
-	if (sftk_audit_enabled) {
-	    char msg[128];
-	    PR_snprintf(msg,sizeof msg,
-			"C_GenerateKeyPair(hSession=0x%08lX, "
-			"pMechanism->mechanism=0x%08lX)=0x%08lX "
-			"self-test: pair-wise consistency test failed",
-			(PRUint32)hSession,(PRUint32)pMechanism->mechanism,
-			(PRUint32)crv);
-	    sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg);
-	}
-	return crv;
     }
 
     *phPrivateKey = privateKey->handle;
     *phPublicKey = publicKey->handle;
     sftk_FreeObject(publicKey);
     sftk_FreeObject(privateKey);
 
     return CKR_OK;
--- a/security/nss/lib/softoken/pkcs11i.h
+++ b/security/nss/lib/softoken/pkcs11i.h
@@ -9,16 +9,17 @@
 
 #include "nssilock.h"
 #include "seccomon.h"
 #include "secoidt.h"
 #include "lowkeyti.h" 
 #include "pkcs11t.h"
 
 #include "sftkdbt.h" 
+#include "chacha20poly1305.h"
 #include "hasht.h"
 
 /* 
  * Configuration Defines 
  *
  * The following defines affect the space verse speed trade offs of
  * the PKCS #11 module. For the most part the current settings are optimized
  * for web servers, where we want faster speed and lower lock contention at
@@ -99,16 +100,17 @@ typedef struct SFTKSessionStr SFTKSessio
 typedef struct SFTKSlotStr SFTKSlot;
 typedef struct SFTKSessionContextStr SFTKSessionContext;
 typedef struct SFTKSearchResultsStr SFTKSearchResults;
 typedef struct SFTKHashVerifyInfoStr SFTKHashVerifyInfo;
 typedef struct SFTKHashSignInfoStr SFTKHashSignInfo;
 typedef struct SFTKOAEPEncryptInfoStr SFTKOAEPEncryptInfo;
 typedef struct SFTKOAEPDecryptInfoStr SFTKOAEPDecryptInfo;
 typedef struct SFTKSSLMACInfoStr SFTKSSLMACInfo;
+typedef struct SFTKChaCha20Poly1305InfoStr SFTKChaCha20Poly1305Info;
 typedef struct SFTKItemTemplateStr SFTKItemTemplate;
 
 /* define function pointer typdefs for pointer tables */
 typedef void (*SFTKDestroy)(void *, PRBool);
 typedef void (*SFTKBegin)(void *);
 typedef SECStatus (*SFTKCipher)(void *,void *,unsigned int *,unsigned int,
 					void *, unsigned int);
 typedef SECStatus (*SFTKVerify)(void *,void *,unsigned int,void *,unsigned int);
@@ -394,16 +396,26 @@ struct SFTKSSLMACInfoStr {
     SFTKHash		update;
     SFTKEnd		end;
     CK_ULONG		macSize;
     int			padSize;
     unsigned char	key[MAX_KEY_LEN];
     unsigned int	keySize;
 };
 
+/* SFTKChaCha20Poly1305Info saves the key, tag length, nonce,
+ * and additional data for a ChaCha20+Poly1305 AEAD operation. */
+struct SFTKChaCha20Poly1305InfoStr {
+    ChaCha20Poly1305Context freeblCtx;
+    unsigned char nonce[12];
+    unsigned char ad[16];
+    unsigned char *adOverflow;
+    unsigned int adLen;
+};
+
 /*
  * Template based on SECItems, suitable for passing as arrays
  */
 struct SFTKItemTemplateStr {
     CK_ATTRIBUTE_TYPE	type;
     SECItem		*item;
 };
 
--- a/security/nss/lib/ssl/SSLerrs.h
+++ b/security/nss/lib/ssl/SSLerrs.h
@@ -1,466 +1,467 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* SSL-specific security error codes  */
 /* caller must include "sslerr.h" */
 
-ER3(SSL_ERROR_EXPORT_ONLY_SERVER,			SSL_ERROR_BASE + 0,
-"Unable to communicate securely.  Peer does not support high-grade encryption.")
+ER3(SSL_ERROR_EXPORT_ONLY_SERVER, SSL_ERROR_BASE + 0,
+    "Unable to communicate securely.  Peer does not support high-grade encryption.")
 
-ER3(SSL_ERROR_US_ONLY_SERVER,				SSL_ERROR_BASE + 1,
-"Unable to communicate securely.  Peer requires high-grade encryption which is not supported.")
+ER3(SSL_ERROR_US_ONLY_SERVER, SSL_ERROR_BASE + 1,
+    "Unable to communicate securely.  Peer requires high-grade encryption which is not supported.")
 
-ER3(SSL_ERROR_NO_CYPHER_OVERLAP,			SSL_ERROR_BASE + 2,
-"Cannot communicate securely with peer: no common encryption algorithm(s).")
+ER3(SSL_ERROR_NO_CYPHER_OVERLAP, SSL_ERROR_BASE + 2,
+    "Cannot communicate securely with peer: no common encryption algorithm(s).")
 
-ER3(SSL_ERROR_NO_CERTIFICATE,				SSL_ERROR_BASE + 3,
-"Unable to find the certificate or key necessary for authentication.")
+ER3(SSL_ERROR_NO_CERTIFICATE, SSL_ERROR_BASE + 3,
+    "Unable to find the certificate or key necessary for authentication.")
 
-ER3(SSL_ERROR_BAD_CERTIFICATE,				SSL_ERROR_BASE + 4,
-"Unable to communicate securely with peer: peers's certificate was rejected.")
+ER3(SSL_ERROR_BAD_CERTIFICATE, SSL_ERROR_BASE + 4,
+    "Unable to communicate securely with peer: peers's certificate was rejected.")
 
-ER3(SSL_ERROR_UNUSED_5,					SSL_ERROR_BASE + 5,
-"Unrecognized SSL error code.")
+ER3(SSL_ERROR_UNUSED_5, SSL_ERROR_BASE + 5,
+    "Unrecognized SSL error code.")
 
-ER3(SSL_ERROR_BAD_CLIENT,				SSL_ERROR_BASE + 6,
-"The server has encountered bad data from the client.")
+ER3(SSL_ERROR_BAD_CLIENT, SSL_ERROR_BASE + 6,
+    "The server has encountered bad data from the client.")
 
-ER3(SSL_ERROR_BAD_SERVER,				SSL_ERROR_BASE + 7,
-"The client has encountered bad data from the server.")
+ER3(SSL_ERROR_BAD_SERVER, SSL_ERROR_BASE + 7,
+    "The client has encountered bad data from the server.")
 
-ER3(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE,		SSL_ERROR_BASE + 8,
-"Unsupported certificate type.")
+ER3(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE, SSL_ERROR_BASE + 8,
+    "Unsupported certificate type.")
 
-ER3(SSL_ERROR_UNSUPPORTED_VERSION,			SSL_ERROR_BASE + 9,
-"Peer using unsupported version of security protocol.")
+ER3(SSL_ERROR_UNSUPPORTED_VERSION, SSL_ERROR_BASE + 9,
+    "Peer using unsupported version of security protocol.")
 
-ER3(SSL_ERROR_UNUSED_10,				SSL_ERROR_BASE + 10,
-"Unrecognized SSL error code.")
+ER3(SSL_ERROR_UNUSED_10, SSL_ERROR_BASE + 10,
+    "Unrecognized SSL error code.")
 
-ER3(SSL_ERROR_WRONG_CERTIFICATE,			SSL_ERROR_BASE + 11,
-"Client authentication failed: private key in key database does not match public key in certificate database.")
+ER3(SSL_ERROR_WRONG_CERTIFICATE, SSL_ERROR_BASE + 11,
+    "Client authentication failed: private key in key database does not match public key in certificate database.")
 
-ER3(SSL_ERROR_BAD_CERT_DOMAIN,				SSL_ERROR_BASE + 12,
-"Unable to communicate securely with peer: requested domain name does not match the server's certificate.")
+ER3(SSL_ERROR_BAD_CERT_DOMAIN, SSL_ERROR_BASE + 12,
+    "Unable to communicate securely with peer: requested domain name does not match the server's certificate.")
 
-ER3(SSL_ERROR_POST_WARNING,				SSL_ERROR_BASE + 13,
-"Unrecognized SSL error code.")
+ER3(SSL_ERROR_POST_WARNING, SSL_ERROR_BASE + 13,
+    "Unrecognized SSL error code.")
 
-ER3(SSL_ERROR_SSL2_DISABLED,				(SSL_ERROR_BASE + 14),
-"Peer only supports SSL version 2, which is locally disabled.")
+ER3(SSL_ERROR_SSL2_DISABLED, (SSL_ERROR_BASE + 14),
+    "Peer only supports SSL version 2, which is locally disabled.")
 
+ER3(SSL_ERROR_BAD_MAC_READ, (SSL_ERROR_BASE + 15),
+    "SSL received a record with an incorrect Message Authentication Code.")
 
-ER3(SSL_ERROR_BAD_MAC_READ,				(SSL_ERROR_BASE + 15),
-"SSL received a record with an incorrect Message Authentication Code.")
+ER3(SSL_ERROR_BAD_MAC_ALERT, (SSL_ERROR_BASE + 16),
+    "SSL peer reports incorrect Message Authentication Code.")
 
-ER3(SSL_ERROR_BAD_MAC_ALERT,				(SSL_ERROR_BASE + 16),
-"SSL peer reports incorrect Message Authentication Code.")
+ER3(SSL_ERROR_BAD_CERT_ALERT, (SSL_ERROR_BASE + 17),
+    "SSL peer cannot verify your certificate.")
 
-ER3(SSL_ERROR_BAD_CERT_ALERT,				(SSL_ERROR_BASE + 17),
-"SSL peer cannot verify your certificate.")
+ER3(SSL_ERROR_REVOKED_CERT_ALERT, (SSL_ERROR_BASE + 18),
+    "SSL peer rejected your certificate as revoked.")
 
-ER3(SSL_ERROR_REVOKED_CERT_ALERT,			(SSL_ERROR_BASE + 18),
-"SSL peer rejected your certificate as revoked.")
+ER3(SSL_ERROR_EXPIRED_CERT_ALERT, (SSL_ERROR_BASE + 19),
+    "SSL peer rejected your certificate as expired.")
 
-ER3(SSL_ERROR_EXPIRED_CERT_ALERT,			(SSL_ERROR_BASE + 19),
-"SSL peer rejected your certificate as expired.")
-
-ER3(SSL_ERROR_SSL_DISABLED,				(SSL_ERROR_BASE + 20),
-"Cannot connect: SSL is disabled.")
+ER3(SSL_ERROR_SSL_DISABLED, (SSL_ERROR_BASE + 20),
+    "Cannot connect: SSL is disabled.")
 
-ER3(SSL_ERROR_FORTEZZA_PQG,				(SSL_ERROR_BASE + 21),
-"Cannot connect: SSL peer is in another FORTEZZA domain.")
+ER3(SSL_ERROR_FORTEZZA_PQG, (SSL_ERROR_BASE + 21),
+    "Cannot connect: SSL peer is in another FORTEZZA domain.")
 
-ER3(SSL_ERROR_UNKNOWN_CIPHER_SUITE          , (SSL_ERROR_BASE + 22),
-"An unknown SSL cipher suite has been requested.")
+ER3(SSL_ERROR_UNKNOWN_CIPHER_SUITE, (SSL_ERROR_BASE + 22),
+    "An unknown SSL cipher suite has been requested.")
 
-ER3(SSL_ERROR_NO_CIPHERS_SUPPORTED          , (SSL_ERROR_BASE + 23),
-"No cipher suites are present and enabled in this program.")
+ER3(SSL_ERROR_NO_CIPHERS_SUPPORTED, (SSL_ERROR_BASE + 23),
+    "No cipher suites are present and enabled in this program.")
 
-ER3(SSL_ERROR_BAD_BLOCK_PADDING             , (SSL_ERROR_BASE + 24),
-"SSL received a record with bad block padding.")
+ER3(SSL_ERROR_BAD_BLOCK_PADDING, (SSL_ERROR_BASE + 24),
+    "SSL received a record with bad block padding.")
 
-ER3(SSL_ERROR_RX_RECORD_TOO_LONG            , (SSL_ERROR_BASE + 25),
-"SSL received a record that exceeded the maximum permissible length.")
+ER3(SSL_ERROR_RX_RECORD_TOO_LONG, (SSL_ERROR_BASE + 25),
+    "SSL received a record that exceeded the maximum permissible length.")
 
-ER3(SSL_ERROR_TX_RECORD_TOO_LONG            , (SSL_ERROR_BASE + 26),
-"SSL attempted to send a record that exceeded the maximum permissible length.")
+ER3(SSL_ERROR_TX_RECORD_TOO_LONG, (SSL_ERROR_BASE + 26),
+    "SSL attempted to send a record that exceeded the maximum permissible length.")
 
 /*
  * Received a malformed (too long or short or invalid content) SSL handshake.
  */
-ER3(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST    , (SSL_ERROR_BASE + 27),
-"SSL received a malformed Hello Request handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST, (SSL_ERROR_BASE + 27),
+    "SSL received a malformed Hello Request handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO     , (SSL_ERROR_BASE + 28),
-"SSL received a malformed Client Hello handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, (SSL_ERROR_BASE + 28),
+    "SSL received a malformed Client Hello handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_SERVER_HELLO     , (SSL_ERROR_BASE + 29),
-"SSL received a malformed Server Hello handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_SERVER_HELLO, (SSL_ERROR_BASE + 29),
+    "SSL received a malformed Server Hello handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_CERTIFICATE      , (SSL_ERROR_BASE + 30),
-"SSL received a malformed Certificate handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_CERTIFICATE, (SSL_ERROR_BASE + 30),
+    "SSL received a malformed Certificate handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH  , (SSL_ERROR_BASE + 31),
-"SSL received a malformed Server Key Exchange handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH, (SSL_ERROR_BASE + 31),
+    "SSL received a malformed Server Key Exchange handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_CERT_REQUEST     , (SSL_ERROR_BASE + 32),
-"SSL received a malformed Certificate Request handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_CERT_REQUEST, (SSL_ERROR_BASE + 32),
+    "SSL received a malformed Certificate Request handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_HELLO_DONE       , (SSL_ERROR_BASE + 33),
-"SSL received a malformed Server Hello Done handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_HELLO_DONE, (SSL_ERROR_BASE + 33),
+    "SSL received a malformed Server Hello Done handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_CERT_VERIFY      , (SSL_ERROR_BASE + 34),
-"SSL received a malformed Certificate Verify handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_CERT_VERIFY, (SSL_ERROR_BASE + 34),
+    "SSL received a malformed Certificate Verify handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH  , (SSL_ERROR_BASE + 35),
-"SSL received a malformed Client Key Exchange handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH, (SSL_ERROR_BASE + 35),
+    "SSL received a malformed Client Key Exchange handshake message.")
 
-ER3(SSL_ERROR_RX_MALFORMED_FINISHED         , (SSL_ERROR_BASE + 36),
-"SSL received a malformed Finished handshake message.")
+ER3(SSL_ERROR_RX_MALFORMED_FINISHED, (SSL_ERROR_BASE + 36),
+    "SSL received a malformed Finished handshake message.")
 
 /*
  * Received a malformed (too long or short) SSL record.
  */
-ER3(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER    , (SSL_ERROR_BASE + 37),
-"SSL received a malformed Change Cipher Spec record.")
+ER3(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER, (SSL_ERROR_BASE + 37),
+    "SSL received a malformed Change Cipher Spec record.")
 
-ER3(SSL_ERROR_RX_MALFORMED_ALERT            , (SSL_ERROR_BASE + 38),
-"SSL received a malformed Alert record.")
+ER3(SSL_ERROR_RX_MALFORMED_ALERT, (SSL_ERROR_BASE + 38),
+    "SSL received a malformed Alert record.")
 
-ER3(SSL_ERROR_RX_MALFORMED_HANDSHAKE        , (SSL_ERROR_BASE + 39),
-"SSL received a malformed Handshake record.")
+ER3(SSL_ERROR_RX_MALFORMED_HANDSHAKE, (SSL_ERROR_BASE + 39),
+    "SSL received a malformed Handshake record.")
 
-ER3(SSL_ERROR_RX_MALFORMED_APPLICATION_DATA , (SSL_ERROR_BASE + 40),
-"SSL received a malformed Application Data record.")
+ER3(SSL_ERROR_RX_MALFORMED_APPLICATION_DATA, (SSL_ERROR_BASE + 40),
+    "SSL received a malformed Application Data record.")
 
 /*
  * Received an SSL handshake that was inappropriate for the state we're in.
  * E.g. Server received message from server, or wrong state in state machine.
  */
-ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST   , (SSL_ERROR_BASE + 41),
-"SSL received an unexpected Hello Request handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST, (SSL_ERROR_BASE + 41),
+    "SSL received an unexpected Hello Request handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO    , (SSL_ERROR_BASE + 42),
-"SSL received an unexpected Client Hello handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO, (SSL_ERROR_BASE + 42),
+    "SSL received an unexpected Client Hello handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO    , (SSL_ERROR_BASE + 43),
-"SSL received an unexpected Server Hello handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO, (SSL_ERROR_BASE + 43),
+    "SSL received an unexpected Server Hello handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE     , (SSL_ERROR_BASE + 44),
-"SSL received an unexpected Certificate handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, (SSL_ERROR_BASE + 44),
+    "SSL received an unexpected Certificate handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH , (SSL_ERROR_BASE + 45),
-"SSL received an unexpected Server Key Exchange handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH, (SSL_ERROR_BASE + 45),
+    "SSL received an unexpected Server Key Exchange handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST    , (SSL_ERROR_BASE + 46),
-"SSL received an unexpected Certificate Request handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, (SSL_ERROR_BASE + 46),
+    "SSL received an unexpected Certificate Request handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE      , (SSL_ERROR_BASE + 47),
-"SSL received an unexpected Server Hello Done handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE, (SSL_ERROR_BASE + 47),
+    "SSL received an unexpected Server Hello Done handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY     , (SSL_ERROR_BASE + 48),
-"SSL received an unexpected Certificate Verify handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY, (SSL_ERROR_BASE + 48),
+    "SSL received an unexpected Certificate Verify handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH , (SSL_ERROR_BASE + 49),
-"SSL received an unexpected Client Key Exchange handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH, (SSL_ERROR_BASE + 49),
+    "SSL received an unexpected Client Key Exchange handshake message.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_FINISHED        , (SSL_ERROR_BASE + 50),
-"SSL received an unexpected Finished handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_FINISHED, (SSL_ERROR_BASE + 50),
+    "SSL received an unexpected Finished handshake message.")
 
 /*
  * Received an SSL record that was inappropriate for the state we're in.
  */
-ER3(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER   , (SSL_ERROR_BASE + 51),
-"SSL received an unexpected Change Cipher Spec record.")
+ER3(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, (SSL_ERROR_BASE + 51),
+    "SSL received an unexpected Change Cipher Spec record.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_ALERT           , (SSL_ERROR_BASE + 52),
-"SSL received an unexpected Alert record.")
+ER3(SSL_ERROR_RX_UNEXPECTED_ALERT, (SSL_ERROR_BASE + 52),
+    "SSL received an unexpected Alert record.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE       , (SSL_ERROR_BASE + 53),
-"SSL received an unexpected Handshake record.")
+ER3(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE, (SSL_ERROR_BASE + 53),
+    "SSL received an unexpected Handshake record.")
 
 ER3(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA, (SSL_ERROR_BASE + 54),
-"SSL received an unexpected Application Data record.")
+    "SSL received an unexpected Application Data record.")
 
 /*
  * Received record/message with unknown discriminant.
  */
-ER3(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE        , (SSL_ERROR_BASE + 55),
-"SSL received a record with an unknown content type.")
+ER3(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE, (SSL_ERROR_BASE + 55),
+    "SSL received a record with an unknown content type.")
 
-ER3(SSL_ERROR_RX_UNKNOWN_HANDSHAKE          , (SSL_ERROR_BASE + 56),
-"SSL received a handshake message with an unknown message type.")
+ER3(SSL_ERROR_RX_UNKNOWN_HANDSHAKE, (SSL_ERROR_BASE + 56),
+    "SSL received a handshake message with an unknown message type.")
 
-ER3(SSL_ERROR_RX_UNKNOWN_ALERT              , (SSL_ERROR_BASE + 57),
-"SSL received an alert record with an unknown alert description.")
+ER3(SSL_ERROR_RX_UNKNOWN_ALERT, (SSL_ERROR_BASE + 57),
+    "SSL received an alert record with an unknown alert description.")
 
 /*
  * Received an alert reporting what we did wrong.  (more alerts above)
  */
-ER3(SSL_ERROR_CLOSE_NOTIFY_ALERT            , (SSL_ERROR_BASE + 58),
-"SSL peer has closed this connection.")
+ER3(SSL_ERROR_CLOSE_NOTIFY_ALERT, (SSL_ERROR_BASE + 58),
+    "SSL peer has closed this connection.")
 
-ER3(SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT    , (SSL_ERROR_BASE + 59),
-"SSL peer was not expecting a handshake message it received.")
+ER3(SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT, (SSL_ERROR_BASE + 59),
+    "SSL peer was not expecting a handshake message it received.")
 
-ER3(SSL_ERROR_DECOMPRESSION_FAILURE_ALERT   , (SSL_ERROR_BASE + 60),
-"SSL peer was unable to successfully decompress an SSL record it received.")
+ER3(SSL_ERROR_DECOMPRESSION_FAILURE_ALERT, (SSL_ERROR_BASE + 60),
+    "SSL peer was unable to successfully decompress an SSL record it received.")
 
-ER3(SSL_ERROR_HANDSHAKE_FAILURE_ALERT       , (SSL_ERROR_BASE + 61),
-"SSL peer was unable to negotiate an acceptable set of security parameters.")
+ER3(SSL_ERROR_HANDSHAKE_FAILURE_ALERT, (SSL_ERROR_BASE + 61),
+    "SSL peer was unable to negotiate an acceptable set of security parameters.")
 
-ER3(SSL_ERROR_ILLEGAL_PARAMETER_ALERT       , (SSL_ERROR_BASE + 62),
-"SSL peer rejected a handshake message for unacceptable content.")
+ER3(SSL_ERROR_ILLEGAL_PARAMETER_ALERT, (SSL_ERROR_BASE + 62),
+    "SSL peer rejected a handshake message for unacceptable content.")
 
-ER3(SSL_ERROR_UNSUPPORTED_CERT_ALERT        , (SSL_ERROR_BASE + 63),
-"SSL peer does not support certificates of the type it received.")
+ER3(SSL_ERROR_UNSUPPORTED_CERT_ALERT, (SSL_ERROR_BASE + 63),
+    "SSL peer does not support certificates of the type it received.")
 
-ER3(SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT     , (SSL_ERROR_BASE + 64),
-"SSL peer had some unspecified issue with the certificate it received.")
+ER3(SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT, (SSL_ERROR_BASE + 64),
+    "SSL peer had some unspecified issue with the certificate it received.")
 
+ER3(SSL_ERROR_GENERATE_RANDOM_FAILURE, (SSL_ERROR_BASE + 65),
+    "SSL experienced a failure of its random number generator.")
 
-ER3(SSL_ERROR_GENERATE_RANDOM_FAILURE       , (SSL_ERROR_BASE + 65),
-"SSL experienced a failure of its random number generator.")
+ER3(SSL_ERROR_SIGN_HASHES_FAILURE, (SSL_ERROR_BASE + 66),
+    "Unable to digitally sign data required to verify your certificate.")
 
-ER3(SSL_ERROR_SIGN_HASHES_FAILURE           , (SSL_ERROR_BASE + 66),
-"Unable to digitally sign data required to verify your certificate.")
-
-ER3(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE    , (SSL_ERROR_BASE + 67),
-"SSL was unable to extract the public key from the peer's certificate.")
+ER3(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE, (SSL_ERROR_BASE + 67),
+    "SSL was unable to extract the public key from the peer's certificate.")
 
-ER3(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE   , (SSL_ERROR_BASE + 68),
-"Unspecified failure while processing SSL Server Key Exchange handshake.")
+ER3(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE, (SSL_ERROR_BASE + 68),
+    "Unspecified failure while processing SSL Server Key Exchange handshake.")
 
-ER3(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE   , (SSL_ERROR_BASE + 69),
-"Unspecified failure while processing SSL Client Key Exchange handshake.")
+ER3(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE, (SSL_ERROR_BASE + 69),
+    "Unspecified failure while processing SSL Client Key Exchange handshake.")
 
-ER3(SSL_ERROR_ENCRYPTION_FAILURE            , (SSL_ERROR_BASE + 70),
-"Bulk data encryption algorithm failed in selected cipher suite.")
+ER3(SSL_ERROR_ENCRYPTION_FAILURE, (SSL_ERROR_BASE + 70),
+    "Bulk data encryption algorithm failed in selected cipher suite.")
 
-ER3(SSL_ERROR_DECRYPTION_FAILURE            , (SSL_ERROR_BASE + 71),
-"Bulk data decryption algorithm failed in selected cipher suite.")
+ER3(SSL_ERROR_DECRYPTION_FAILURE, (SSL_ERROR_BASE + 71),
+    "Bulk data decryption algorithm failed in selected cipher suite.")
 
-ER3(SSL_ERROR_SOCKET_WRITE_FAILURE          , (SSL_ERROR_BASE + 72),
-"Attempt to write encrypted data to underlying socket failed.")
+ER3(SSL_ERROR_SOCKET_WRITE_FAILURE, (SSL_ERROR_BASE + 72),
+    "Attempt to write encrypted data to underlying socket failed.")
 
-ER3(SSL_ERROR_MD5_DIGEST_FAILURE            , (SSL_ERROR_BASE + 73),
-"MD5 digest function failed.")
+ER3(SSL_ERROR_MD5_DIGEST_FAILURE, (SSL_ERROR_BASE + 73),
+    "MD5 digest function failed.")
 
-ER3(SSL_ERROR_SHA_DIGEST_FAILURE            , (SSL_ERROR_BASE + 74),
-"SHA-1 digest function failed.")
+ER3(SSL_ERROR_SHA_DIGEST_FAILURE, (SSL_ERROR_BASE + 74),
+    "SHA-1 digest function failed.")
 
-ER3(SSL_ERROR_MAC_COMPUTATION_FAILURE       , (SSL_ERROR_BASE + 75),
-"MAC computation failed.")
+ER3(SSL_ERROR_MAC_COMPUTATION_FAILURE, (SSL_ERROR_BASE + 75),
+    "MAC computation failed.")
 
-ER3(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE       , (SSL_ERROR_BASE + 76),
-"Failure to create Symmetric Key context.")
+ER3(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE, (SSL_ERROR_BASE + 76),
+    "Failure to create Symmetric Key context.")
 
-ER3(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE        , (SSL_ERROR_BASE + 77),
-"Failure to unwrap the Symmetric key in Client Key Exchange message.")
+ER3(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE, (SSL_ERROR_BASE + 77),
+    "Failure to unwrap the Symmetric key in Client Key Exchange message.")
 
-ER3(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED   , (SSL_ERROR_BASE + 78),
-"SSL Server attempted to use domestic-grade public key with export cipher suite.")
+ER3(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED, (SSL_ERROR_BASE + 78),
+    "SSL Server attempted to use domestic-grade public key with export cipher suite.")
 
-ER3(SSL_ERROR_IV_PARAM_FAILURE              , (SSL_ERROR_BASE + 79),
-"PKCS11 code failed to translate an IV into a param.")
+ER3(SSL_ERROR_IV_PARAM_FAILURE, (SSL_ERROR_BASE + 79),
+    "PKCS11 code failed to translate an IV into a param.")
 
-ER3(SSL_ERROR_INIT_CIPHER_SUITE_FAILURE     , (SSL_ERROR_BASE + 80),
-"Failed to initialize the selected cipher suite.")
+ER3(SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, (SSL_ERROR_BASE + 80),
+    "Failed to initialize the selected cipher suite.")
 
-ER3(SSL_ERROR_SESSION_KEY_GEN_FAILURE       , (SSL_ERROR_BASE + 81),
-"Client failed to generate session keys for SSL session.")
+ER3(SSL_ERROR_SESSION_KEY_GEN_FAILURE, (SSL_ERROR_BASE + 81),
+    "Client failed to generate session keys for SSL session.")
 
-ER3(SSL_ERROR_NO_SERVER_KEY_FOR_ALG         , (SSL_ERROR_BASE + 82),
-"Server has no key for the attempted key exchange algorithm.")
+ER3(SSL_ERROR_NO_SERVER_KEY_FOR_ALG, (SSL_ERROR_BASE + 82),
+    "Server has no key for the attempted key exchange algorithm.")
 
-ER3(SSL_ERROR_TOKEN_INSERTION_REMOVAL       , (SSL_ERROR_BASE + 83),
-"PKCS#11 token was inserted or removed while operation was in progress.")
+ER3(SSL_ERROR_TOKEN_INSERTION_REMOVAL, (SSL_ERROR_BASE + 83),
+    "PKCS#11 token was inserted or removed while operation was in progress.")
 
-ER3(SSL_ERROR_TOKEN_SLOT_NOT_FOUND          , (SSL_ERROR_BASE + 84),
-"No PKCS#11 token could be found to do a required operation.")
+ER3(SSL_ERROR_TOKEN_SLOT_NOT_FOUND, (SSL_ERROR_BASE + 84),
+    "No PKCS#11 token could be found to do a required operation.")
 
-ER3(SSL_ERROR_NO_COMPRESSION_OVERLAP        , (SSL_ERROR_BASE + 85),
-"Cannot communicate securely with peer: no common compression algorithm(s).")
+ER3(SSL_ERROR_NO_COMPRESSION_OVERLAP, (SSL_ERROR_BASE + 85),
+    "Cannot communicate securely with peer: no common compression algorithm(s).")
 
-ER3(SSL_ERROR_HANDSHAKE_NOT_COMPLETED       , (SSL_ERROR_BASE + 86),
-"Cannot perform the operation until the handshake is complete.")
+ER3(SSL_ERROR_HANDSHAKE_NOT_COMPLETED, (SSL_ERROR_BASE + 86),
+    "Cannot perform the operation until the handshake is complete.")
 
-ER3(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE      , (SSL_ERROR_BASE + 87),
-"Received incorrect handshakes hash values from peer.")
+ER3(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE, (SSL_ERROR_BASE + 87),
+    "Received incorrect handshakes hash values from peer.")
 
-ER3(SSL_ERROR_CERT_KEA_MISMATCH             , (SSL_ERROR_BASE + 88),
-"The certificate provided cannot be used with the selected key exchange algorithm.")
+ER3(SSL_ERROR_CERT_KEA_MISMATCH, (SSL_ERROR_BASE + 88),
+    "The certificate provided cannot be used with the selected key exchange algorithm.")
 
-ER3(SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA	, (SSL_ERROR_BASE + 89),
-"No certificate authority is trusted for SSL client authentication.")
+ER3(SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA, (SSL_ERROR_BASE + 89),
+    "No certificate authority is trusted for SSL client authentication.")
 
-ER3(SSL_ERROR_SESSION_NOT_FOUND		, (SSL_ERROR_BASE + 90),
-"Client's SSL session ID not found in server's session cache.")
+ER3(SSL_ERROR_SESSION_NOT_FOUND, (SSL_ERROR_BASE + 90),
+    "Client's SSL session ID not found in server's session cache.")
 
-ER3(SSL_ERROR_DECRYPTION_FAILED_ALERT     , (SSL_ERROR_BASE + 91),
-"Peer was unable to decrypt an SSL record it received.")
+ER3(SSL_ERROR_DECRYPTION_FAILED_ALERT, (SSL_ERROR_BASE + 91),
+    "Peer was unable to decrypt an SSL record it received.")
 
-ER3(SSL_ERROR_RECORD_OVERFLOW_ALERT       , (SSL_ERROR_BASE + 92),
-"Peer received an SSL record that was longer than is permitted.")
+ER3(SSL_ERROR_RECORD_OVERFLOW_ALERT, (SSL_ERROR_BASE + 92),
+    "Peer received an SSL record that was longer than is permitted.")
 
-ER3(SSL_ERROR_UNKNOWN_CA_ALERT            , (SSL_ERROR_BASE + 93),
-"Peer does not recognize and trust the CA that issued your certificate.")
+ER3(SSL_ERROR_UNKNOWN_CA_ALERT, (SSL_ERROR_BASE + 93),
+    "Peer does not recognize and trust the CA that issued your certificate.")
 
-ER3(SSL_ERROR_ACCESS_DENIED_ALERT         , (SSL_ERROR_BASE + 94),
-"Peer received a valid certificate, but access was denied.")
+ER3(SSL_ERROR_ACCESS_DENIED_ALERT, (SSL_ERROR_BASE + 94),
+    "Peer received a valid certificate, but access was denied.")
 
-ER3(SSL_ERROR_DECODE_ERROR_ALERT          , (SSL_ERROR_BASE + 95),
-"Peer could not decode an SSL handshake message.")
+ER3(SSL_ERROR_DECODE_ERROR_ALERT, (SSL_ERROR_BASE + 95),
+    "Peer could not decode an SSL handshake message.")
 
-ER3(SSL_ERROR_DECRYPT_ERROR_ALERT         , (SSL_ERROR_BASE + 96),
-"Peer reports failure of signature verification or key exchange.")
+ER3(SSL_ERROR_DECRYPT_ERROR_ALERT, (SSL_ERROR_BASE + 96),
+    "Peer reports failure of signature verification or key exchange.")
 
-ER3(SSL_ERROR_EXPORT_RESTRICTION_ALERT    , (SSL_ERROR_BASE + 97),
-"Peer reports negotiation not in compliance with export regulations.")
+ER3(SSL_ERROR_EXPORT_RESTRICTION_ALERT, (SSL_ERROR_BASE + 97),
+    "Peer reports negotiation not in compliance with export regulations.")
 
-ER3(SSL_ERROR_PROTOCOL_VERSION_ALERT      , (SSL_ERROR_BASE + 98),
-"Peer reports incompatible or unsupported protocol version.")
+ER3(SSL_ERROR_PROTOCOL_VERSION_ALERT, (SSL_ERROR_BASE + 98),
+    "Peer reports incompatible or unsupported protocol version.")
 
-ER3(SSL_ERROR_INSUFFICIENT_SECURITY_ALERT , (SSL_ERROR_BASE + 99),
-"Server requires ciphers more secure than those supported by client.")
+ER3(SSL_ERROR_INSUFFICIENT_SECURITY_ALERT, (SSL_ERROR_BASE + 99),
+    "Server requires ciphers more secure than those supported by client.")
 
-ER3(SSL_ERROR_INTERNAL_ERROR_ALERT        , (SSL_ERROR_BASE + 100),
-"Peer reports it experienced an internal error.")
+ER3(SSL_ERROR_INTERNAL_ERROR_ALERT, (SSL_ERROR_BASE + 100),
+    "Peer reports it experienced an internal error.")
 
-ER3(SSL_ERROR_USER_CANCELED_ALERT         , (SSL_ERROR_BASE + 101),
-"Peer user canceled handshake.")
+ER3(SSL_ERROR_USER_CANCELED_ALERT, (SSL_ERROR_BASE + 101),
+    "Peer user canceled handshake.")
 
-ER3(SSL_ERROR_NO_RENEGOTIATION_ALERT      , (SSL_ERROR_BASE + 102),
-"Peer does not permit renegotiation of SSL security parameters.")
+ER3(SSL_ERROR_NO_RENEGOTIATION_ALERT, (SSL_ERROR_BASE + 102),
+    "Peer does not permit renegotiation of SSL security parameters.")
 
-ER3(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED , (SSL_ERROR_BASE + 103),
-"SSL server cache not configured and not disabled for this socket.")
+ER3(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED, (SSL_ERROR_BASE + 103),
+    "SSL server cache not configured and not disabled for this socket.")
 
-ER3(SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT    , (SSL_ERROR_BASE + 104),
-"SSL peer does not support requested TLS hello extension.")
+ER3(SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT, (SSL_ERROR_BASE + 104),
+    "SSL peer does not support requested TLS hello extension.")
 
-ER3(SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT , (SSL_ERROR_BASE + 105),
-"SSL peer could not obtain your certificate from the supplied URL.")
+ER3(SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT, (SSL_ERROR_BASE + 105),
+    "SSL peer could not obtain your certificate from the supplied URL.")
 
-ER3(SSL_ERROR_UNRECOGNIZED_NAME_ALERT        , (SSL_ERROR_BASE + 106),
-"SSL peer has no certificate for the requested DNS name.")
+ER3(SSL_ERROR_UNRECOGNIZED_NAME_ALERT, (SSL_ERROR_BASE + 106),
+    "SSL peer has no certificate for the requested DNS name.")
 
-ER3(SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT , (SSL_ERROR_BASE + 107),
-"SSL peer was unable to get an OCSP response for its certificate.")
+ER3(SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT, (SSL_ERROR_BASE + 107),
+    "SSL peer was unable to get an OCSP response for its certificate.")
 
-ER3(SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT      , (SSL_ERROR_BASE + 108),
-"SSL peer reported bad certificate hash value.")
+ER3(SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT, (SSL_ERROR_BASE + 108),
+    "SSL peer reported bad certificate hash value.")
 
 ER3(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET, (SSL_ERROR_BASE + 109),
-"SSL received an unexpected New Session Ticket handshake message.")
+    "SSL received an unexpected New Session Ticket handshake message.")
 
 ER3(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET, (SSL_ERROR_BASE + 110),
-"SSL received a malformed New Session Ticket handshake message.")
+    "SSL received a malformed New Session Ticket handshake message.")
 
-ER3(SSL_ERROR_DECOMPRESSION_FAILURE,           (SSL_ERROR_BASE + 111),
-"SSL received a compressed record that could not be decompressed.")
+ER3(SSL_ERROR_DECOMPRESSION_FAILURE, (SSL_ERROR_BASE + 111),
+    "SSL received a compressed record that could not be decompressed.")
 
-ER3(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED,       (SSL_ERROR_BASE + 112),
-"Renegotiation is not allowed on this SSL socket.")
+ER3(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED, (SSL_ERROR_BASE + 112),
+    "Renegotiation is not allowed on this SSL socket.")
 
-ER3(SSL_ERROR_UNSAFE_NEGOTIATION,              (SSL_ERROR_BASE + 113),
-"Peer attempted old style (potentially vulnerable) handshake.")
+ER3(SSL_ERROR_UNSAFE_NEGOTIATION, (SSL_ERROR_BASE + 113),
+    "Peer attempted old style (potentially vulnerable) handshake.")
 
 ER3(SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD, (SSL_ERROR_BASE + 114),
-"SSL received an unexpected uncompressed record.")
+    "SSL received an unexpected uncompressed record.")
 
-ER3(SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY,    (SSL_ERROR_BASE + 115),
-"SSL received a weak ephemeral Diffie-Hellman key in Server Key Exchange handshake message.")
+ER3(SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY, (SSL_ERROR_BASE + 115),
+    "SSL received a weak ephemeral Diffie-Hellman key in Server Key Exchange handshake message.")
 
-ER3(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID,      (SSL_ERROR_BASE + 116),
-"SSL received invalid NPN extension data.")
+ER3(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID, (SSL_ERROR_BASE + 116),
+    "SSL received invalid NPN extension data.")
 
-ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2,  (SSL_ERROR_BASE + 117),
-"SSL feature not supported for SSL 2.0 connections.")
+ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2, (SSL_ERROR_BASE + 117),
+    "SSL feature not supported for SSL 2.0 connections.")
 
 ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS, (SSL_ERROR_BASE + 118),
-"SSL feature not supported for servers.")
+    "SSL feature not supported for servers.")
 
 ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_CLIENTS, (SSL_ERROR_BASE + 119),
-"SSL feature not supported for clients.")
+    "SSL feature not supported for clients.")
 
-ER3(SSL_ERROR_INVALID_VERSION_RANGE,           (SSL_ERROR_BASE + 120),
-"SSL version range is not valid.")
+ER3(SSL_ERROR_INVALID_VERSION_RANGE, (SSL_ERROR_BASE + 120),
+    "SSL version range is not valid.")
 
-ER3(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION,   (SSL_ERROR_BASE + 121),
-"SSL peer selected a cipher suite disallowed for the selected protocol version.")
+ER3(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION, (SSL_ERROR_BASE + 121),
+    "SSL peer selected a cipher suite disallowed for the selected protocol version.")
 
 ER3(SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST, (SSL_ERROR_BASE + 122),
-"SSL received a malformed Hello Verify Request handshake message.")
+    "SSL received a malformed Hello Verify Request handshake message.")
 
 ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST, (SSL_ERROR_BASE + 123),
-"SSL received an unexpected Hello Verify Request handshake message.")
+    "SSL received an unexpected Hello Verify Request handshake message.")
 
 ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION, (SSL_ERROR_BASE + 124),
-"SSL feature not supported for the protocol version.")
+    "SSL feature not supported for the protocol version.")
 
-ER3(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS,       (SSL_ERROR_BASE + 125),
-"SSL received an unexpected Certificate Status handshake message.")
+ER3(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS, (SSL_ERROR_BASE + 125),
+    "SSL received an unexpected Certificate Status handshake message.")
 
 ER3(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM, (SSL_ERROR_BASE + 126),
-"Unsupported hash algorithm used by TLS peer.")
+    "Unsupported hash algorithm used by TLS peer.")
 
 ER3(SSL_ERROR_DIGEST_FAILURE, (SSL_ERROR_BASE + 127),
-"Digest function failed.")
+    "Digest function failed.")
 
 ER3(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM, (SSL_ERROR_BASE + 128),
-"Incorrect signature algorithm specified in a digitally-signed element.")
+    "Incorrect signature algorithm specified in a digitally-signed element.")
 
 ER3(SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK, (SSL_ERROR_BASE + 129),
-"The next protocol negotiation extension was enabled, but the callback was cleared prior to being needed.")
+    "The next protocol negotiation extension was enabled, but the callback was cleared prior to being needed.")
 
 ER3(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL, (SSL_ERROR_BASE + 130),
-"The server supports no protocols that the client advertises in the ALPN extension.")
+    "The server supports no protocols that the client advertises in the ALPN extension.")
 
 ER3(SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT, (SSL_ERROR_BASE + 131),
-"The server rejected the handshake because the client downgraded to a lower "
-"TLS version than the server supports.")
+    "The server rejected the handshake because the client downgraded to a lower "
+    "TLS version than the server supports.")
 
 ER3(SSL_ERROR_WEAK_SERVER_CERT_KEY, (SSL_ERROR_BASE + 132),
-"The server certificate included a public key that was too weak.")
+    "The server certificate included a public key that was too weak.")
 
 ER3(SSL_ERROR_RX_SHORT_DTLS_READ, (SSL_ERROR_BASE + 133),
-"Not enough room in buffer for DTLS record.")
+    "Not enough room in buffer for DTLS record.")
 
 ER3(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM, (SSL_ERROR_BASE + 134),
-"No supported TLS signature algorithm was configured.")
+    "No supported TLS signature algorithm was configured.")
 
 ER3(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM, (SSL_ERROR_BASE + 135),
-"The peer used an unsupported combination of signature and hash algorithm.")
+    "The peer used an unsupported combination of signature and hash algorithm.")
 
 ER3(SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET, (SSL_ERROR_BASE + 136),
-"The peer tried to resume without a correct extended_master_secret extension")
+    "The peer tried to resume without a correct extended_master_secret extension")
 
 ER3(SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET, (SSL_ERROR_BASE + 137),
-"The peer tried to resume with an unexpected extended_master_secret extension")
+    "The peer tried to resume with an unexpected extended_master_secret extension")
 
 ER3(SSL_ERROR_RX_MALFORMED_KEY_SHARE, (SSL_ERROR_BASE + 138),
-"SSL received a malformed Key Share extension.")
+    "SSL received a malformed Key Share extension.")
 
 ER3(SSL_ERROR_MISSING_KEY_SHARE, (SSL_ERROR_BASE + 139),
-"SSL expected a Key Share extension.")
+    "SSL expected a Key Share extension.")
 
 ER3(SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE, (SSL_ERROR_BASE + 140),
-"SSL received a malformed ECDHE key share handshake extension.")
+    "SSL received a malformed ECDHE key share handshake extension.")
 
 ER3(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE, (SSL_ERROR_BASE + 141),
-"SSL received a malformed DHE key share handshake extension.")
+    "SSL received a malformed DHE key share handshake extension.")
 
 ER3(SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS, (SSL_ERROR_BASE + 142),
-"SSL received a malformed Encrypted Extensions handshake message.")
+    "SSL received an unexpected Encrypted Extensions handshake message.")
 
 ER3(SSL_ERROR_MISSING_EXTENSION_ALERT, (SSL_ERROR_BASE + 143),
-"SSL received a missing_extenson alert.")
+    "SSL received a missing_extenson alert.")
 
 ER3(SSL_ERROR_KEY_EXCHANGE_FAILURE, (SSL_ERROR_BASE + 144),
-"SSL had an error performing key exchange.")
+    "SSL had an error performing key exchange.")
 
 ER3(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION, (SSL_ERROR_BASE + 145),
-"SSL received an extension that is not permitted for this version.")
+    "SSL received an extension that is not permitted for this version.")
+
+ER3(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS, (SSL_ERROR_BASE + 146),
+    "SSL received a malformed Encrypted Extensions handshake message.")
--- a/security/nss/lib/ssl/authcert.c
+++ b/security/nss/lib/ssl/authcert.c
@@ -11,79 +11,81 @@
 #include "secitem.h"
 #include "prnetdb.h"
 #include "cert.h"
 #include "nspr.h"
 #include "secder.h"
 #include "key.h"
 #include "nss.h"
 #include "ssl.h"
-#include "pk11func.h"	/* for PK11_ function calls */
+#include "pk11func.h" /* for PK11_ function calls */
 
 /*
  * This callback used by SSL to pull client sertificate upon
  * server request
  */
-SECStatus 
-NSS_GetClientAuthData(void *                       arg, 
-                      PRFileDesc *                 socket, 
-		      struct CERTDistNamesStr *    caNames, 
-		      struct CERTCertificateStr ** pRetCert, 
-		      struct SECKEYPrivateKeyStr **pRetKey)
+SECStatus
+NSS_GetClientAuthData(void *arg,
+                      PRFileDesc *socket,
+                      struct CERTDistNamesStr *caNames,
+                      struct CERTCertificateStr **pRetCert,
+                      struct SECKEYPrivateKeyStr **pRetKey)
 {
-  CERTCertificate *  cert = NULL;
-  SECKEYPrivateKey * privkey = NULL;
-  char *             chosenNickName = (char *)arg;    /* CONST */
-  void *             proto_win  = NULL;
-  SECStatus          rv         = SECFailure;
-  
-  proto_win = SSL_RevealPinArg(socket);
-  
-  if (chosenNickName) {
-    cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(),
-                                    chosenNickName, certUsageSSLClient,
-                                    PR_FALSE, proto_win);	
-    if ( cert ) {
-      privkey = PK11_FindKeyByAnyCert(cert, proto_win);
-      if ( privkey ) {
-	rv = SECSuccess;
-      } else {
-	CERT_DestroyCertificate(cert);
-      }
+    CERTCertificate *cert = NULL;
+    SECKEYPrivateKey *privkey = NULL;
+    char *chosenNickName = (char *)arg; /* CONST */
+    void *proto_win = NULL;
+    SECStatus rv = SECFailure;
+
+    proto_win = SSL_RevealPinArg(socket);
+
+    if (chosenNickName) {
+        cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(),
+                                        chosenNickName, certUsageSSLClient,
+                                        PR_FALSE, proto_win);
+        if (cert) {
+            privkey = PK11_FindKeyByAnyCert(cert, proto_win);
+            if (privkey) {
+                rv = SECSuccess;
+            }
+            else {
+                CERT_DestroyCertificate(cert);
+            }
+        }
     }
-  } else { /* no name given, automatically find the right cert. */
-    CERTCertNicknames * names;
-    int                 i;
-      
-    names = CERT_GetCertNicknames(CERT_GetDefaultCertDB(),
-				  SEC_CERT_NICKNAMES_USER, proto_win);
-    if (names != NULL) {
-      for (i = 0; i < names->numnicknames; i++) {
-	cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(),
-                            names->nicknames[i], certUsageSSLClient,
-                            PR_FALSE, proto_win);	
-	if ( !cert )
-	  continue;
-	/* Only check unexpired certs */
-	if (CERT_CheckCertValidTimes(cert, PR_Now(), PR_TRUE) != 
-	    secCertTimeValid ) {
-	  CERT_DestroyCertificate(cert);
-	  continue;
-	}
-	rv = NSS_CmpCertChainWCANames(cert, caNames);
-	if ( rv == SECSuccess ) {
-	  privkey = PK11_FindKeyByAnyCert(cert, proto_win);
-	  if ( privkey )
-	    break;
-	}
-	rv = SECFailure;
-	CERT_DestroyCertificate(cert);
-      } 
-      CERT_FreeNicknames(names);
+    else { /* no name given, automatically find the right cert. */
+        CERTCertNicknames *names;
+        int i;
+
+        names = CERT_GetCertNicknames(CERT_GetDefaultCertDB(),
+                                      SEC_CERT_NICKNAMES_USER, proto_win);
+        if (names != NULL) {
+            for (i = 0; i < names->numnicknames; i++) {
+                cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(),
+                                                names->nicknames[i], certUsageSSLClient,
+                                                PR_FALSE, proto_win);
+                if (!cert)
+                    continue;
+                /* Only check unexpired certs */
+                if (CERT_CheckCertValidTimes(cert, PR_Now(), PR_TRUE) !=
+                    secCertTimeValid) {
+                    CERT_DestroyCertificate(cert);
+                    continue;
+                }
+                rv = NSS_CmpCertChainWCANames(cert, caNames);
+                if (rv == SECSuccess) {
+                    privkey =
+                        PK11_FindKeyByAnyCert(cert, proto_win);
+                    if (privkey)
+                        break;
+                }
+                rv = SECFailure;
+                CERT_DestroyCertificate(cert);
+            }
+            CERT_FreeNicknames(names);
+        }
     }
-  }
-  if (rv == SECSuccess) {
-    *pRetCert = cert;
-    *pRetKey  = privkey;
-  }
-  return rv;
+    if (rv == SECSuccess) {
+        *pRetCert = cert;
+        *pRetKey = privkey;
+    }
+    return rv;
 }
-
--- a/security/nss/lib/ssl/cmpcert.c
+++ b/security/nss/lib/ssl/cmpcert.c
@@ -13,78 +13,80 @@
 #include "cert.h"
 #include "nspr.h"
 #include "secder.h"
 #include "key.h"
 #include "nss.h"
 
 /*
  * Look to see if any of the signers in the cert chain for "cert" are found
- * in the list of caNames.  
+ * in the list of caNames.
  * Returns SECSuccess if so, SECFailure if not.
  */
 SECStatus
 NSS_CmpCertChainWCANames(CERTCertificate *cert, CERTDistNames *caNames)
 {
-  SECItem *         caname;
-  CERTCertificate * curcert;
-  CERTCertificate * oldcert;
-  PRInt32           contentlen;
-  int               j;
-  int               headerlen;
-  int               depth;
-  SECStatus         rv;
-  SECItem           issuerName;
-  SECItem           compatIssuerName;
+    SECItem *caname;
+    CERTCertificate *curcert;
+    CERTCertificate *oldcert;
+    PRInt32 contentlen;
+    int j;
+    int headerlen;
+    int depth;
+    SECStatus rv;
+    SECItem issuerName;
+    SECItem compatIssuerName;
+
+    if (!cert || !caNames || !caNames->nnames || !caNames->names ||
+        !caNames->names->data)
+        return SECFailure;
+    depth = 0;
+    curcert = CERT_DupCertificate(cert);
+
+    while (curcert) {
+        issuerName = curcert->derIssuer;
 
-  if (!cert || !caNames || !caNames->nnames || !caNames->names ||
-      !caNames->names->data)
-    return SECFailure;
-  depth=0;
-  curcert = CERT_DupCertificate(cert);
-  
-  while( curcert ) {
-    issuerName = curcert->derIssuer;
-    
-    /* compute an alternate issuer name for compatibility with 2.0
-     * enterprise server, which send the CA names without
-     * the outer layer of DER header
-     */
-    rv = DER_Lengths(&issuerName, &headerlen, (PRUint32 *)&contentlen);
-    if ( rv == SECSuccess ) {
-      compatIssuerName.data = &issuerName.data[headerlen];
-      compatIssuerName.len = issuerName.len - headerlen;
-    } else {
-      compatIssuerName.data = NULL;
-      compatIssuerName.len = 0;
+        /* compute an alternate issuer name for compatibility with 2.0
+         * enterprise server, which send the CA names without
+         * the outer layer of DER header
+         */
+        rv = DER_Lengths(&issuerName, &headerlen, (PRUint32 *)&contentlen);
+        if (rv == SECSuccess) {
+            compatIssuerName.data = &issuerName.data[headerlen];
+            compatIssuerName.len = issuerName.len - headerlen;
+        }
+        else {
+            compatIssuerName.data = NULL;
+            compatIssuerName.len = 0;
+        }
+
+        for (j = 0; j < caNames->nnames; j++) {
+            caname = &caNames->names[j];
+            if (SECITEM_CompareItem(&issuerName, caname) == SECEqual) {
+                rv = SECSuccess;
+                CERT_DestroyCertificate(curcert);
+                goto done;
+            }
+            else if (SECITEM_CompareItem(&compatIssuerName, caname) == SECEqual) {
+                rv = SECSuccess;
+                CERT_DestroyCertificate(curcert);
+                goto done;
+            }
+        }
+        if ((depth <= 20) &&
+            (SECITEM_CompareItem(&curcert->derIssuer, &curcert->derSubject) !=
+             SECEqual)) {
+            oldcert = curcert;
+            curcert = CERT_FindCertByName(curcert->dbhandle,
+                                          &curcert->derIssuer);
+            CERT_DestroyCertificate(oldcert);
+            depth++;
+        }
+        else {
+            CERT_DestroyCertificate(curcert);
+            curcert = NULL;
+        }
     }
-    
-    for (j = 0; j < caNames->nnames; j++) {
-      caname = &caNames->names[j];
-      if (SECITEM_CompareItem(&issuerName, caname) == SECEqual) {
-	rv = SECSuccess;
-	CERT_DestroyCertificate(curcert);
-	goto done;
-      } else if (SECITEM_CompareItem(&compatIssuerName, caname) == SECEqual) {
-	rv = SECSuccess;
-	CERT_DestroyCertificate(curcert);
-	goto done;
-      }
-    }
-    if ( ( depth <= 20 ) &&
-	 ( SECITEM_CompareItem(&curcert->derIssuer, &curcert->derSubject)
-	   != SECEqual ) ) {
-      oldcert = curcert;
-      curcert = CERT_FindCertByName(curcert->dbhandle,
-				    &curcert->derIssuer);
-      CERT_DestroyCertificate(oldcert);
-      depth++;
-    } else {
-      CERT_DestroyCertificate(curcert);
-      curcert = NULL;
-    }
-  }
-  rv = SECFailure;
-  
+    rv = SECFailure;
+
 done:
-  return rv;
+    return rv;
 }
-
--- a/security/nss/lib/ssl/derive.c
+++ b/security/nss/lib/ssl/derive.c
@@ -1,18 +1,18 @@
 /*
  * Key Derivation that doesn't use PKCS11
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "ssl.h" 	/* prereq to sslimpl.h */
-#include "certt.h"	/* prereq to sslimpl.h */
-#include "keythi.h"	/* prereq to sslimpl.h */
+#include "ssl.h"    /* prereq to sslimpl.h */
+#include "certt.h"  /* prereq to sslimpl.h */
+#include "keythi.h" /* prereq to sslimpl.h */
 #include "sslimpl.h"
 #ifndef NO_PKCS11_BYPASS
 #include "blapi.h"
 #endif
 
 #include "keyhi.h"
 #include "pk11func.h"
 #include "secasn1.h"
@@ -21,876 +21,889 @@
 
 #include "sslproto.h"
 #include "sslerr.h"
 
 #ifndef NO_PKCS11_BYPASS
 /* make this a macro! */
 #ifdef NOT_A_MACRO
 static void
-buildSSLKey(unsigned char * keyBlock, unsigned int keyLen, SECItem * result,
-            const char * label)
+buildSSLKey(unsigned char *keyBlock, unsigned int keyLen, SECItem *result,
+            const char *label)
 {
     result->type = siBuffer;
     result->data = keyBlock;
-    result->len  = keyLen;
+    result->len = keyLen;
     PRINT_BUF(100, (NULL, label, keyBlock, keyLen));
 }
 #else
-#define buildSSLKey(keyBlock, keyLen, result, label) \
-{ \
-    (result)->type = siBuffer; \
-    (result)->data = keyBlock; \
-    (result)->len  = keyLen; \
-    PRINT_BUF(100, (NULL, label, keyBlock, keyLen)); \
-}
+#define buildSSLKey(keyBlock, keyLen, result, label)     \
+    {                                                    \
+        (result)->type = siBuffer;                       \
+        (result)->data = keyBlock;                       \
+        (result)->len = keyLen;                          \
+        PRINT_BUF(100, (NULL, label, keyBlock, keyLen)); \
+    }
 #endif
 
 /*
  * SSL Key generation given pre master secret
  */
 #ifndef NUM_MIXERS
 #define NUM_MIXERS 9
 #endif
-static const char * const mixers[NUM_MIXERS] = { 
-    "A", 
-    "BB", 
-    "CCC", 
-    "DDDD", 
-    "EEEEE", 
-    "FFFFFF", 
+static const char *const mixers[NUM_MIXERS] = {
+    "A",
+    "BB",
+    "CCC",
+    "DDDD",
+    "EEEEE",
+    "FFFFFF",
     "GGGGGGG",
     "HHHHHHHH",
-    "IIIIIIIII" 
+    "IIIIIIIII"
 };
 
-
 SECStatus
 ssl3_KeyAndMacDeriveBypass(
-    ssl3CipherSpec *      pwSpec,
-    const unsigned char * cr,
-    const unsigned char * sr,
-    PRBool                isTLS,
-    PRBool                isExport)
+    ssl3CipherSpec *pwSpec,
+    const unsigned char *cr,
+    const unsigned char *sr,
+    PRBool isTLS,
+    PRBool isExport)
 {
     const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
-    unsigned char * key_block    = pwSpec->key_block;
-    unsigned char * key_block2   = NULL;
-    unsigned int    block_bytes  = 0;
-    unsigned int    block_needed = 0;
-    unsigned int    i;
-    unsigned int    keySize;            /* actual    size of cipher keys */
-    unsigned int    effKeySize;		/* effective size of cipher keys */
-    unsigned int    macSize;		/* size of MAC secret */
-    unsigned int    IVSize;		/* size of IV */
-    PRBool          explicitIV = PR_FALSE;
-    SECStatus       rv    = SECFailure;
-    SECStatus       status = SECSuccess;
-    PRBool          isFIPS = PR_FALSE;
-    PRBool          isTLS12 = pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2;
+    unsigned char *key_block = pwSpec->key_block;
+    unsigned char *key_block2 = NULL;
+    unsigned int block_bytes = 0;
+    unsigned int block_needed = 0;
+    unsigned int i;
+    unsigned int keySize;    /* actual    size of cipher keys */
+    unsigned int effKeySize; /* effective size of cipher keys */
+    unsigned int macSize;    /* size of MAC secret */
+    unsigned int IVSize;     /* size of IV */
+    PRBool explicitIV = PR_FALSE;
+    SECStatus rv = SECFailure;
+    SECStatus status = SECSuccess;
+    PRBool isFIPS = PR_FALSE;
+    PRBool isTLS12 = pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2;
 
-    SECItem         srcr;
-    SECItem         crsr;
+    SECItem srcr;
+    SECItem crsr;
 
-    unsigned char     srcrdata[SSL3_RANDOM_LENGTH * 2];
-    unsigned char     crsrdata[SSL3_RANDOM_LENGTH * 2];
-    PRUint64          md5buf[22];
-    PRUint64          shabuf[40];
+    unsigned char srcrdata[SSL3_RANDOM_LENGTH * 2];
+    unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2];
+    PRUint64 md5buf[22];
+    PRUint64 shabuf[40];
 
 #define md5Ctx ((MD5Context *)md5buf)
 #define shaCtx ((SHA1Context *)shabuf)
 
-    static const SECItem zed  = { siBuffer, NULL, 0 };
+    static const SECItem zed = { siBuffer, NULL, 0 };
 
     if (pwSpec->msItem.data == NULL ||
-        pwSpec->msItem.len  != SSL3_MASTER_SECRET_LENGTH) {
-	PORT_SetError(SEC_ERROR_INVALID_ARGS);
-	return rv;
+        pwSpec->msItem.len != SSL3_MASTER_SECRET_LENGTH) {
+        PORT_SetError(SEC_ERROR_INVALID_ARGS);
+        return rv;
     }
 
-    PRINT_BUF(100, (NULL, "Master Secret", pwSpec->msItem.data, 
-                                           pwSpec->msItem.len));
+    PRINT_BUF(100, (NULL, "Master Secret", pwSpec->msItem.data,
+                    pwSpec->msItem.len));
 
     /* figure out how much is needed */
-    macSize    = pwSpec->mac_size;
-    keySize    = cipher_def->key_size;
+    macSize = pwSpec->mac_size;
+    keySize = cipher_def->key_size;
     effKeySize = cipher_def->secret_key_size;
-    IVSize     = cipher_def->iv_size;
+    IVSize = cipher_def->iv_size;
     if (keySize == 0) {
-	effKeySize = IVSize = 0; /* only MACing */
+        effKeySize = IVSize = 0; /* only MACing */
     }
     if (cipher_def->type == type_block &&
-	pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
-	/* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
-	explicitIV = PR_TRUE;
+        pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
+        /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
+        explicitIV = PR_TRUE;
     }
     block_needed =
-	2 * (macSize + effKeySize + ((!isExport && !explicitIV) * IVSize));
+        2 * (macSize + effKeySize + ((!isExport && !explicitIV) * IVSize));
 
     /*
      * clear out our returned keys so we can recover on failure
      */
-    pwSpec->client.write_key_item     = zed;
+    pwSpec->client.write_key_item = zed;
     pwSpec->client.write_mac_key_item = zed;
-    pwSpec->server.write_key_item     = zed;
+    pwSpec->server.write_key_item = zed;
     pwSpec->server.write_mac_key_item = zed;
 
     /* initialize the server random, client random block */
-    srcr.type   = siBuffer;
-    srcr.data   = srcrdata;
-    srcr.len    = sizeof srcrdata;
+    srcr.type = siBuffer;
+    srcr.data = srcrdata;
+    srcr.len = sizeof srcrdata;
     PORT_Memcpy(srcrdata, sr, SSL3_RANDOM_LENGTH);
     PORT_Memcpy(srcrdata + SSL3_RANDOM_LENGTH, cr, SSL3_RANDOM_LENGTH);
 
     /* initialize the client random, server random block */
-    crsr.type   = siBuffer;
-    crsr.data   = crsrdata;
-    crsr.len    = sizeof crsrdata;
+    crsr.type = siBuffer;
+    crsr.data = crsrdata;
+    crsr.len = sizeof crsrdata;
     PORT_Memcpy(crsrdata, cr, SSL3_RANDOM_LENGTH);
     PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, sr, SSL3_RANDOM_LENGTH);
     PRINT_BUF(100, (NULL, "Key & MAC CRSR", crsr.data, crsr.len));
 
     /*
      * generate the key material:
      */
     if (isTLS) {
-	SECItem       keyblk;
+        SECItem keyblk;
 
-	keyblk.type = siBuffer;
-	keyblk.data = key_block;
-	keyblk.len  = block_needed;
+        keyblk.type = siBuffer;
+        keyblk.data = key_block;
+        keyblk.len = block_needed;
 
-	if (isTLS12) {
-	    status = TLS_P_hash(HASH_AlgSHA256, &pwSpec->msItem,
-				"key expansion", &srcr, &keyblk, isFIPS);
-	} else {
-	    status = TLS_PRF(&pwSpec->msItem, "key expansion", &srcr, &keyblk,
-			     isFIPS);
-	}
-	if (status != SECSuccess) {
-	    goto key_and_mac_derive_fail;
-	}
-	block_bytes = keyblk.len;
-    } else {
-	/* key_block = 
-	 *     MD5(master_secret + SHA('A' + master_secret + 
-	 *                      ServerHello.random + ClientHello.random)) +
-	 *     MD5(master_secret + SHA('BB' + master_secret + 
-	 *                      ServerHello.random + ClientHello.random)) +
-	 *     MD5(master_secret + SHA('CCC' + master_secret + 
-	 *                      ServerHello.random + ClientHello.random)) +
-	 *     [...];
-	 */
-	unsigned int made = 0;
-	for (i = 0; made < block_needed && i < NUM_MIXERS; ++i) {
-	    unsigned int    outLen;
-	    unsigned char   sha_out[SHA1_LENGTH];
+        if (isTLS12) {
+            status = TLS_P_hash(HASH_AlgSHA256, &pwSpec->msItem,
+                                "key expansion", &srcr, &keyblk, isFIPS);
+        }
+        else {
+            status = TLS_PRF(&pwSpec->msItem, "key expansion", &srcr, &keyblk,
+                             isFIPS);
+        }
+        if (status != SECSuccess) {
+            goto key_and_mac_derive_fail;
+        }
+        block_bytes = keyblk.len;
+    }
+    else {
+       /* key_block =
+        *     MD5(master_secret + SHA('A' + master_secret +
+        *                      ServerHello.random + ClientHello.random)) +
+        *     MD5(master_secret + SHA('BB' + master_secret +
+        *                      ServerHello.random + ClientHello.random)) +
+        *     MD5(master_secret + SHA('CCC' + master_secret +
+        *                      ServerHello.random + ClientHello.random)) +
+        *     [...];
+        */
+        unsigned int made = 0;
+        for (i = 0; made < block_needed && i < NUM_MIXERS; ++i) {
+            unsigned int outLen;
+            unsigned char sha_out[SHA1_LENGTH];
 
-	    SHA1_Begin(shaCtx);
-	    SHA1_Update(shaCtx, (unsigned char*)(mixers[i]), i+1);
-	    SHA1_Update(shaCtx, pwSpec->msItem.data, pwSpec->msItem.len);
-	    SHA1_Update(shaCtx, srcr.data, srcr.len);
-	    SHA1_End(shaCtx, sha_out, &outLen, SHA1_LENGTH);
-	    PORT_Assert(outLen == SHA1_LENGTH);
+            SHA1_Begin(shaCtx);
+            SHA1_Update(shaCtx, (unsigned char *)(mixers[i]), i + 1);
+            SHA1_Update(shaCtx, pwSpec->msItem.data, pwSpec->msItem.len);
+            SHA1_Update(shaCtx, srcr.data, srcr.len);
+            SHA1_End(shaCtx, sha_out, &outLen, SHA1_LENGTH);
+            PORT_Assert(outLen == SHA1_LENGTH);
 
-	    MD5_Begin(md5Ctx);
-	    MD5_Update(md5Ctx, pwSpec->msItem.data, pwSpec->msItem.len);
-	    MD5_Update(md5Ctx, sha_out, outLen);
-	    MD5_End(md5Ctx, key_block + made, &outLen, MD5_LENGTH);
-	    PORT_Assert(outLen == MD5_LENGTH);
-	    made += MD5_LENGTH;
-	}
-	block_bytes = made;
+            MD5_Begin(md5Ctx);
+            MD5_Update(md5Ctx, pwSpec->msItem.data, pwSpec->msItem.len);
+            MD5_Update(md5Ctx, sha_out, outLen);
+            MD5_End(md5Ctx, key_block + made, &outLen, MD5_LENGTH);
+            PORT_Assert(outLen == MD5_LENGTH);
+            made += MD5_LENGTH;
+        }
+        block_bytes = made;
     }
     PORT_Assert(block_bytes >= block_needed);
     PORT_Assert(block_bytes <= sizeof pwSpec->key_block);
     PRINT_BUF(100, (NULL, "key block", key_block, block_bytes));
 
     /*
      * Put the key material where it goes.
      */
     key_block2 = key_block + block_bytes;
-    i = 0;			/* now shows how much consumed */
+    i = 0; /* now shows how much consumed */
 
-    /* 
+    /*
      * The key_block is partitioned as follows:
      * client_write_MAC_secret[CipherSpec.hash_size]
      */
-    buildSSLKey(&key_block[i],macSize, &pwSpec->client.write_mac_key_item, \
+    buildSSLKey(&key_block[i], macSize, &pwSpec->client.write_mac_key_item, \
                 "Client Write MAC Secret");
     i += macSize;
 
-    /* 
+    /*
      * server_write_MAC_secret[CipherSpec.hash_size]
      */
-    buildSSLKey(&key_block[i],macSize, &pwSpec->server.write_mac_key_item, \
+    buildSSLKey(&key_block[i], macSize, &pwSpec->server.write_mac_key_item, \
                 "Server Write MAC Secret");
     i += macSize;
 
     if (!keySize) {
-	/* only MACing */
-	buildSSLKey(NULL, 0, &pwSpec->client.write_key_item, \
-	            "Client Write Key (MAC only)");
-	buildSSLKey(NULL, 0, &pwSpec->server.write_key_item, \
-	            "Server Write Key (MAC only)");
-	buildSSLKey(NULL, 0, &pwSpec->client.write_iv_item, \
-	            "Client Write IV (MAC only)");
-	buildSSLKey(NULL, 0, &pwSpec->server.write_iv_item, \
-	            "Server Write IV (MAC only)");
-    } else if (!isExport) {
-	/* 
-	** Generate Domestic write keys and IVs.
-	** client_write_key[CipherSpec.key_material]
-	*/
-	buildSSLKey(&key_block[i], keySize, &pwSpec->client.write_key_item, \
-	            "Domestic Client Write Key");
-	i += keySize;
+        /* only MACing */
+        buildSSLKey(NULL, 0, &pwSpec->client.write_key_item, \
+                    "Client Write Key (MAC only)");
+        buildSSLKey(NULL, 0, &pwSpec->server.write_key_item, \
+                    "Server Write Key (MAC only)");
+        buildSSLKey(NULL, 0, &pwSpec->client.write_iv_item, \
+                    "Client Write IV (MAC only)");
+        buildSSLKey(NULL, 0, &pwSpec->server.write_iv_item, \
+                    "Server Write IV (MAC only)");
+    }
+    else if (!isExport) {
+        /*
+        ** Generate Domestic write keys and IVs.
+        ** client_write_key[CipherSpec.key_material]
+        */
+        buildSSLKey(&key_block[i], keySize, &pwSpec->client.write_key_item, \
+                    "Domestic Client Write Key");
+        i += keySize;
 
-	/* 
-	** server_write_key[CipherSpec.key_material]
-	*/
-	buildSSLKey(&key_block[i], keySize, &pwSpec->server.write_key_item, \
-	            "Domestic Server Write Key");
-	i += keySize;
+        /*
+        ** server_write_key[CipherSpec.key_material]
+        */
+        buildSSLKey(&key_block[i], keySize, &pwSpec->server.write_key_item, \
+                    "Domestic Server Write Key");
+        i += keySize;
 
-	if (IVSize > 0) {
-	    if (explicitIV) {
-		static unsigned char zero_block[32];
-		PORT_Assert(IVSize <= sizeof zero_block);
-		buildSSLKey(&zero_block[0], IVSize, \
-			    &pwSpec->client.write_iv_item, \
-			    "Domestic Client Write IV");
-		buildSSLKey(&zero_block[0], IVSize, \
-			    &pwSpec->server.write_iv_item, \
-			    "Domestic Server Write IV");
-	    } else {
-		/* 
-		** client_write_IV[CipherSpec.IV_size]
-		*/
-		buildSSLKey(&key_block[i], IVSize, \
-			    &pwSpec->client.write_iv_item, \
-			    "Domestic Client Write IV");
-		i += IVSize;
+        if (IVSize > 0) {
+            if (explicitIV) {
+                static unsigned char zero_block[32];
+                PORT_Assert(IVSize <= sizeof zero_block);
+                buildSSLKey(&zero_block[0], IVSize, \
+                            &pwSpec->client.write_iv_item, \
+                            "Domestic Client Write IV");
+                buildSSLKey(&zero_block[0], IVSize, \
+                            &pwSpec->server.write_iv_item, \
+                            "Domestic Server Write IV");
+            }
+            else {
+                /*
+                ** client_write_IV[CipherSpec.IV_size]
+                */
+                buildSSLKey(&key_block[i], IVSize, \
+                            &pwSpec->client.write_iv_item, \
+                            "Domestic Client Write IV");
+                i += IVSize;
 
-		/* 
-		** server_write_IV[CipherSpec.IV_size]
-		*/
-		buildSSLKey(&key_block[i], IVSize, \
-			    &pwSpec->server.write_iv_item, \
-			    "Domestic Server Write IV");
-		i += IVSize;
-	    }
-	}
-	PORT_Assert(i <= block_bytes);
-    } else if (!isTLS) { 
-	/*
-	** Generate SSL3 Export write keys and IVs.
-	*/
-	unsigned int    outLen;
+                /*
+                ** server_write_IV[CipherSpec.IV_size]
+                */
+                buildSSLKey(&key_block[i], IVSize, \
+                            &pwSpec->server.write_iv_item, \
+                            "Domestic Server Write IV");
+                i += IVSize;
+            }
+        }
+        PORT_Assert(i <= block_bytes);
+    }
+    else if (!isTLS) {
+        /*
+        ** Generate SSL3 Export write keys and IVs.
+        */
+        unsigned int outLen;
 
-	/*
-	** client_write_key[CipherSpec.key_material]
-	** final_client_write_key = MD5(client_write_key +
-	**                   ClientHello.random + ServerHello.random);
-	*/
-	MD5_Begin(md5Ctx);
-	MD5_Update(md5Ctx, &key_block[i], effKeySize);
-	MD5_Update(md5Ctx, crsr.data, crsr.len);
-	MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
-	i += effKeySize;
-	buildSSLKey(key_block2, keySize, &pwSpec->client.write_key_item, \
-	            "SSL3 Export Client Write Key");
-	key_block2 += keySize;
+        /*
+        ** client_write_key[CipherSpec.key_material]
+        ** final_client_write_key = MD5(client_write_key +
+        **                   ClientHello.random + ServerHello.random);
+        */
+        MD5_Begin(md5Ctx);
+        MD5_Update(md5Ctx, &key_block[i], effKeySize);
+        MD5_Update(md5Ctx, crsr.data, crsr.len);
+        MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
+        i += effKeySize;
+        buildSSLKey(key_block2, keySize, &pwSpec->client.write_key_item, \
+                    "SSL3 Export Client Write Key");
+        key_block2 += keySize;
 
-	/*
-	** server_write_key[CipherSpec.key_material]
-	** final_server_write_key = MD5(server_write_key +
-	**                    ServerHello.random + ClientHello.random);
-	*/
-	MD5_Begin(md5Ctx);
-	MD5_Update(md5Ctx, &key_block[i], effKeySize);
-	MD5_Update(md5Ctx, srcr.data, srcr.len);
-	MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
-	i += effKeySize;
-	buildSSLKey(key_block2, keySize, &pwSpec->server.write_key_item, \
-	            "SSL3 Export Server Write Key");
-	key_block2 += keySize;
-	PORT_Assert(i <= block_bytes);
+        /*
+        ** server_write_key[CipherSpec.key_material]
+        ** final_server_write_key = MD5(server_write_key +
+        **                    ServerHello.random + ClientHello.random);
+        */
+        MD5_Begin(md5Ctx);
+        MD5_Update(md5Ctx, &key_block[i], effKeySize);
+        MD5_Update(md5Ctx, srcr.data, srcr.len);
+        MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
+        i += effKeySize;
+        buildSSLKey(key_block2, keySize, &pwSpec->server.write_key_item, \
+                    "SSL3 Export Server Write Key");
+        key_block2 += keySize;
+        PORT_Assert(i <= block_bytes);
 
-	if (IVSize) {
-	    /*
-	    ** client_write_IV = 
-	    **	MD5(ClientHello.random + ServerHello.random);
-	    */
-	    MD5_Begin(md5Ctx);
-	    MD5_Update(md5Ctx, crsr.data, crsr.len);
-	    MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
-	    buildSSLKey(key_block2, IVSize, &pwSpec->client.write_iv_item, \
-	                "SSL3 Export Client Write IV");
-	    key_block2 += IVSize;
+        if (IVSize) {
+            /*
+            ** client_write_IV =
+            **  MD5(ClientHello.random + ServerHello.random);
+            */
+            MD5_Begin(md5Ctx);
+            MD5_Update(md5Ctx, crsr.data, crsr.len);
+            MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
+            buildSSLKey(key_block2, IVSize, &pwSpec->client.write_iv_item, \
+                        "SSL3 Export Client Write IV");
+            key_block2 += IVSize;
 
-	    /*
-	    ** server_write_IV = 
-	    **	MD5(ServerHello.random + ClientHello.random);
-	    */
-	    MD5_Begin(md5Ctx);
-	    MD5_Update(md5Ctx, srcr.data, srcr.len);
-	    MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
-	    buildSSLKey(key_block2, IVSize, &pwSpec->server.write_iv_item, \
-	                "SSL3 Export Server Write IV");
-	    key_block2 += IVSize;
-	}
+            /*
+            ** server_write_IV =
+            **  MD5(ServerHello.random + ClientHello.random);
+            */
+            MD5_Begin(md5Ctx);
+            MD5_Update(md5Ctx, srcr.data, srcr.len);
+            MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH);
+            buildSSLKey(key_block2, IVSize, &pwSpec->server.write_iv_item, \
+                        "SSL3 Export Server Write IV");
+            key_block2 += IVSize;
+        }
 
-	PORT_Assert(key_block2 - key_block <= sizeof pwSpec->key_block);
-    } else {
-	/*
-	** Generate TLS Export write keys and IVs.
-	*/
-	SECItem       secret ;
-	SECItem       keyblk ;
+        PORT_Assert(key_block2 - key_block <= sizeof pwSpec->key_block);
+    }
+    else {
+        /*
+        ** Generate TLS Export write keys and IVs.
+        */
+        SECItem secret;
+        SECItem keyblk;
 
-	secret.type = siBuffer;
-	keyblk.type = siBuffer;
-	/*
-	** client_write_key[CipherSpec.key_material]
-	** final_client_write_key = PRF(client_write_key, 
-	**                              "client write key",
-	**                              client_random + server_random);
-	*/
-	secret.data = &key_block[i];
-	secret.len  = effKeySize;
-	i          += effKeySize;
-	keyblk.data = key_block2;
-	keyblk.len  = keySize;
-	status = TLS_PRF(&secret, "client write key", &crsr, &keyblk, isFIPS);
-	if (status != SECSuccess) {
-	    goto key_and_mac_derive_fail;
-	}
-	buildSSLKey(key_block2, keySize, &pwSpec->client.write_key_item, \
-	            "TLS Export Client Write Key");
-	key_block2 += keySize;
+        secret.type = siBuffer;
+        keyblk.type = siBuffer;
+        /*
+        ** client_write_key[CipherSpec.key_material]
+        ** final_client_write_key = PRF(client_write_key,
+        **                              "client write key",
+        **                              client_random + server_random);
+        */
+        secret.data = &key_block[i];
+        secret.len = effKeySize;
+        i += effKeySize;
+        keyblk.data = key_block2;
+        keyblk.len = keySize;
+        status = TLS_PRF(&secret, "client write key", &crsr, &keyblk, isFIPS);
+        if (status != SECSuccess) {
+            goto key_and_mac_derive_fail;
+        }
+        buildSSLKey(key_block2, keySize, &pwSpec->client.write_key_item, \
+                    "TLS Export Client Write Key");
+        key_block2 += keySize;
 
-	/*
-	** server_write_key[CipherSpec.key_material]
-	** final_server_write_key = PRF(server_write_key,
-	**                              "server write key",
-	**                              client_random + server_random);
-	*/
-	secret.data = &key_block[i];
-	secret.len  = effKeySize;
-	i          += effKeySize;
-	keyblk.data = key_block2;
-	keyblk.len  = keySize;
-	status = TLS_PRF(&secret, "server write key", &crsr, &keyblk, isFIPS);
-	if (status != SECSuccess) {
-	    goto key_and_mac_derive_fail;
-	}
-	buildSSLKey(key_block2, keySize, &pwSpec->server.write_key_item, \
-	            "TLS Export Server Write Key");
-	key_block2 += keySize;
+        /*
+        ** server_write_key[CipherSpec.key_material]
+        ** final_server_write_key = PRF(server_write_key,
+        **                              "server write key",
+        **                              client_random + server_random);
+        */
+        secret.data = &key_block[i];
+        secret.len = effKeySize;
+        i += effKeySize;
+        keyblk.data = key_block2;
+        keyblk.len = keySize;
+        status = TLS_PRF(&secret, "server write key", &crsr, &keyblk, isFIPS);
+        if (status != SECSuccess) {
+            goto key_and_mac_derive_fail;
+        }
+        buildSSLKey(key_block2, keySize, &pwSpec->server.write_key_item, \
+                    "TLS Export Server Write Key");
+        key_block2 += keySize;
 
-	/*
-	** iv_block = PRF("", "IV block", client_random + server_random);
-	** client_write_IV[SecurityParameters.IV_size]
-	** server_write_IV[SecurityParameters.IV_size]
-	*/
-	if (IVSize) {
-	    secret.data = NULL;
-	    secret.len  = 0;
-	    keyblk.data = key_block2;
-	    keyblk.len  = 2 * IVSize;
-	    status = TLS_PRF(&secret, "IV block", &crsr, &keyblk, isFIPS);
-	    if (status != SECSuccess) {
-		goto key_and_mac_derive_fail;
-	    }
-	    buildSSLKey(key_block2,          IVSize, \
-	                &pwSpec->client.write_iv_item, \
-			"TLS Export Client Write IV");
-	    buildSSLKey(key_block2 + IVSize, IVSize, \
-	                &pwSpec->server.write_iv_item, \
-			"TLS Export Server Write IV");
-	    key_block2 += 2 * IVSize;
-	}
-	PORT_Assert(key_block2 - key_block <= sizeof pwSpec->key_block);
+        /*
+        ** iv_block = PRF("", "IV block", client_random + server_random);
+        ** client_write_IV[SecurityParameters.IV_size]
+        ** server_write_IV[SecurityParameters.IV_size]
+        */
+        if (IVSize) {
+            secret.data = NULL;
+            secret.len = 0;
+            keyblk.data = key_block2;
+            keyblk.len = 2 * IVSize;
+            status = TLS_PRF(&secret, "IV block", &crsr, &keyblk, isFIPS);
+            if (status != SECSuccess) {
+                goto key_and_mac_derive_fail;
+            }
+            buildSSLKey(key_block2, IVSize, \
+                        &pwSpec->client.write_iv_item, \
+                        "TLS Export Client Write IV");
+            buildSSLKey(key_block2 + IVSize, IVSize, \
+                        &pwSpec->server.write_iv_item, \
+                        "TLS Export Server Write IV");
+            key_block2 += 2 * IVSize;
+        }
+        PORT_Assert(key_block2 - key_block <= sizeof pwSpec->key_block);
     }
     rv = SECSuccess;
 
 key_and_mac_derive_fail:
 
     MD5_DestroyContext(md5Ctx, PR_FALSE);
     SHA1_DestroyContext(shaCtx, PR_FALSE);
 
     if (rv != SECSuccess) {
-	PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+        PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
     }
 
     return rv;
 }
 
-
 /* derive the Master Secret from the PMS */
 /* Presently, this is only done wtih RSA PMS, and only on the server side,
- * so isRSA is always true. 
+ * so isRSA is always true.
  */
 SECStatus
-ssl3_MasterSecretDeriveBypass( 
-    ssl3CipherSpec *      pwSpec,
-    const unsigned char * cr,
-    const unsigned char * sr,
-    const SECItem *       pms,
-    PRBool                isTLS,
-    PRBool                isRSA)
+ssl3_MasterSecretDeriveBypass(
+    ssl3CipherSpec *pwSpec,
+    const unsigned char *cr,
+    const unsigned char *sr,
+    const SECItem *pms,
+    PRBool isTLS,
+    PRBool isRSA)
 {
-    unsigned char * key_block    = pwSpec->key_block;
-    SECStatus       rv    = SECSuccess;
-    PRBool          isFIPS = PR_FALSE;
-    PRBool          isTLS12 = pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2;
+    unsigned char *key_block = pwSpec->key_block;
+    SECStatus rv = SECSuccess;
+    PRBool isFIPS = PR_FALSE;
+    PRBool isTLS12 = pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2;
 
-    SECItem         crsr;
+    SECItem crsr;
 
-    unsigned char     crsrdata[SSL3_RANDOM_LENGTH * 2];
-    PRUint64          md5buf[22];
-    PRUint64          shabuf[40];
+    unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2];
+    PRUint64 md5buf[22];
+    PRUint64 shabuf[40];
 
 #define md5Ctx ((MD5Context *)md5buf)
 #define shaCtx ((SHA1Context *)shabuf)
 
     /* first do the consistancy checks */
-    if (isRSA) { 
-	PORT_Assert(pms->len == SSL3_RSA_PMS_LENGTH);
-	if (pms->len != SSL3_RSA_PMS_LENGTH) {
-	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
-	    return SECFailure;
-	}
-	/* caller must test PMS version for rollback */
+    if (isRSA) {
+        PORT_Assert(pms->len == SSL3_RSA_PMS_LENGTH);
+        if (pms->len != SSL3_RSA_PMS_LENGTH) {
+            PORT_SetError(SEC_ERROR_INVALID_ARGS);
+            return SECFailure;
+        }
+        /* caller must test PMS version for rollback */
     }
 
     /* initialize the client random, server random block */
-    crsr.type   = siBuffer;
-    crsr.data   = crsrdata;
-    crsr.len    = sizeof crsrdata;
+    crsr.type = siBuffer;
+    crsr.data = crsrdata;
+    crsr.len = sizeof crsrdata;
     PORT_Memcpy(crsrdata, cr, SSL3_RANDOM_LENGTH);
     PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, sr, SSL3_RANDOM_LENGTH);
     PRINT_BUF(100, (NULL, "Master Secret CRSR", crsr.data, crsr.len));
 
     /* finally do the key gen */
     if (isTLS) {
-	SECItem master = { siBuffer, NULL, 0 };
+        SECItem master = { siBuffer, NULL, 0 };
 
-	master.data = key_block;
-	master.len = SSL3_MASTER_SECRET_LENGTH;
+        master.data = key_block;
+        master.len = SSL3_MASTER_SECRET_LENGTH;
 
-	if (isTLS12) {
-	    rv = TLS_P_hash(HASH_AlgSHA256, pms, "master secret", &crsr,
-			    &master, isFIPS);
-	} else {
-	    rv = TLS_PRF(pms, "master secret", &crsr, &master, isFIPS);
-	}
-	if (rv != SECSuccess) {
-	    PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
-	}
-    } else {
-	int i;
-	unsigned int made = 0;
-	for (i = 0; i < 3; i++) {
-	    unsigned int    outLen;
-	    unsigned char   sha_out[SHA1_LENGTH];
+        if (isTLS12) {
+            rv = TLS_P_hash(HASH_AlgSHA256, pms, "master secret", &crsr,
+                            &master, isFIPS);
+        }
+        else {
+            rv = TLS_PRF(pms, "master secret", &crsr, &master, isFIPS);
+        }
+        if (rv != SECSuccess) {
+            PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+        }
+    }
+    else {
+        int i;
+        unsigned int made = 0;
+        for (i = 0; i < 3; i++) {
+            unsigned int outLen;
+            unsigned char sha_out[SHA1_LENGTH];
 
-	    SHA1_Begin(shaCtx);
-	    SHA1_Update(shaCtx, (unsigned char*) mixers[i], i+1);
-	    SHA1_Update(shaCtx, pms->data, pms->len);
-	    SHA1_Update(shaCtx, crsr.data, crsr.len);
-	    SHA1_End(shaCtx, sha_out, &outLen, SHA1_LENGTH);
-	    PORT_Assert(outLen == SHA1_LENGTH);
+            SHA1_Begin(shaCtx);
+            SHA1_Update(shaCtx, (unsigned char *)mixers[i], i + 1);
+            SHA1_Update(shaCtx, pms->data, pms->len);
+            SHA1_Update(shaCtx, crsr.data, crsr.len);
+            SHA1_End(shaCtx, sha_out, &outLen, SHA1_LENGTH);
+            PORT_Assert(outLen == SHA1_LENGTH);
 
-	    MD5_Begin(md5Ctx);
-	    MD5_Update(md5Ctx, pms->data, pms->len);
-	    MD5_Update(md5Ctx, sha_out, outLen);
-	    MD5_End(md5Ctx, key_block + made, &outLen, MD5_LENGTH);
-	    PORT_Assert(outLen == MD5_LENGTH);
-	    made += outLen;
-	}
+            MD5_Begin(md5Ctx);
+            MD5_Update(md5Ctx, pms->data, pms->len);
+            MD5_Update(md5Ctx, sha_out, outLen);
+            MD5_End(md5Ctx, key_block + made, &outLen, MD5_LENGTH);
+            PORT_Assert(outLen == MD5_LENGTH);
+            made += outLen;
+        }
     }
 
     /* store the results */
-    PORT_Memcpy(pwSpec->raw_master_secret, key_block, 
-		SSL3_MASTER_SECRET_LENGTH);
+    PORT_Memcpy(pwSpec->raw_master_secret, key_block,
+                SSL3_MASTER_SECRET_LENGTH);
     pwSpec->msItem.data = pwSpec->raw_master_secret;
-    pwSpec->msItem.len  = SSL3_MASTER_SECRET_LENGTH;
-    PRINT_BUF(100, (NULL, "Master Secret", pwSpec->msItem.data, 
-                                           pwSpec->msItem.len));
+    pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH;
+    PRINT_BUF(100, (NULL, "Master Secret", pwSpec->msItem.data,
+                    pwSpec->msItem.len));
 
     return rv;
 }
 
 static SECStatus
 ssl_canExtractMS(PK11SymKey *pms, PRBool isTLS, PRBool isDH, PRBool *pcbp)
-{   SECStatus	      rv;
-    PK11SymKey *    ms = NULL;
-    SECItem         params = {siBuffer, NULL, 0};
+{
+    SECStatus rv;
+    PK11SymKey *ms = NULL;
+    SECItem params = { siBuffer, NULL, 0 };
     CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
-    unsigned char   rand[SSL3_RANDOM_LENGTH];
-    CK_VERSION      pms_version;
+    unsigned char rand[SSL3_RANDOM_LENGTH];
+    CK_VERSION pms_version;
     CK_MECHANISM_TYPE master_derive;
     CK_MECHANISM_TYPE key_derive;
-    CK_FLAGS          keyFlags;
-    
+    CK_FLAGS keyFlags;
+
     if (pms == NULL)
-	return(SECFailure);
+        return (SECFailure);
 
     PORT_Memset(rand, 0, SSL3_RANDOM_LENGTH);
 
     if (isTLS) {
-	if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
-	else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
-	key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
-	keyFlags      = CKF_SIGN | CKF_VERIFY;
-    } else {
-	if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
-	else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
-	key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
-	keyFlags      = 0;
+        if (isDH)
+            master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
+        else
+            master_derive = CKM_TLS_MASTER_KEY_DERIVE;
+        key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
+        keyFlags = CKF_SIGN | CKF_VERIFY;
+    }
+    else {
+        if (isDH)
+            master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
+        else
+            master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
+        key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
+        keyFlags = 0;
     }
 
-    master_params.pVersion                     = &pms_version;
-    master_params.RandomInfo.pClientRandom     = rand;
+    master_params.pVersion = &pms_version;
+    master_params.RandomInfo.pClientRandom = rand;
     master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
-    master_params.RandomInfo.pServerRandom     = rand;
+    master_params.RandomInfo.pServerRandom = rand;
     master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
 
-    params.data = (unsigned char *) &master_params;
-    params.len  = sizeof master_params;
+    params.data = (unsigned char *)&master_params;
+    params.len = sizeof master_params;
 
     ms = PK11_DeriveWithFlags(pms, master_derive, &params, key_derive,
-			      CKA_DERIVE, 0, keyFlags);
+                              CKA_DERIVE, 0, keyFlags);
     if (ms == NULL)
-	return(SECFailure);
+        return (SECFailure);
 
     rv = PK11_ExtractKeyValue(ms);
     *pcbp = (rv == SECSuccess);
     PK11_FreeSymKey(ms);
-    
-    return(rv);
 
+    return (rv);
 }
-#endif  /* !NO_PKCS11_BYPASS */
+#endif /* !NO_PKCS11_BYPASS */
 
 /* Check the key exchange algorithm for each cipher in the list to see if
- * a master secret key can be extracted. If the KEA will use keys from the 
+ * a master secret key can be extracted. If the KEA will use keys from the
  * specified cert make sure the extract operation is attempted from the slot
  * where the private key resides.
  * If MS can be extracted for all ciphers, (*pcanbypass) is set to TRUE and
  * SECSuccess is returned. In all other cases but one (*pcanbypass) is
  * set to FALSE and SECFailure is returned.
- * In that last case Derive() has been called successfully but the MS is null, 
+ * In that last case Derive() has been called successfully but the MS is null,
  * CanBypass sets (*pcanbypass) to FALSE and returns SECSuccess indicating the
  * arguments were all valid but the slot cannot be bypassed.
  */
 
 /* XXX Add SSL_CBP_TLS1_1 and test it in protocolmask when setting isTLS. */
 
-SECStatus 
+SECStatus
 SSL_CanBypass(CERTCertificate *cert, SECKEYPrivateKey *srvPrivkey,
-	      PRUint32 protocolmask, PRUint16 *ciphersuites, int nsuites,
+              PRUint32 protocolmask, PRUint16 *ciphersuites, int nsuites,
               PRBool *pcanbypass, void *pwArg)
 {
 #ifdef NO_PKCS11_BYPASS
     if (!pcanbypass) {
         PORT_SetError(SEC_ERROR_INVALID_ARGS);
         return SECFailure;
     }
     *pcanbypass = PR_FALSE;
     return SECSuccess;
 #else
-    SECStatus	      rv;
-    int		      i;
-    PRUint16	      suite;
-    PK11SymKey *      pms = NULL;
-    SECKEYPublicKey * srvPubkey = NULL;
-    KeyType	      privKeytype;
-    PK11SlotInfo *    slot = NULL;
-    SECItem           param;
-    CK_VERSION 	      version;
+    SECStatus rv;
+    int i;
+    PRUint16 suite;
+    PK11SymKey *pms = NULL;
+    SECKEYPublicKey *srvPubkey = NULL;
+    KeyType privKeytype;
+    PK11SlotInfo *slot = NULL;
+    SECItem param;
+    CK_VERSION version;
     CK_MECHANISM_TYPE mechanism_array[2];
-    SECItem           enc_pms = {siBuffer, NULL, 0};
-    PRBool	      isTLS = PR_FALSE;
+    SECItem enc_pms = { siBuffer, NULL, 0 };
+    PRBool isTLS = PR_FALSE;
     SSLCipherSuiteInfo csdef;
-    PRBool	      testrsa = PR_FALSE;
-    PRBool	      testrsa_export = PR_FALSE;
-    PRBool	      testecdh = PR_FALSE;
-    PRBool	      testecdhe = PR_FALSE;
+    PRBool testrsa = PR_FALSE;
+    PRBool testrsa_export = PR_FALSE;
+    PRBool testecdh = PR_FALSE;
+    PRBool testecdhe = PR_FALSE;
 #ifndef NSS_DISABLE_ECC
     SECKEYECParams ecParams = { siBuffer, NULL, 0 };
 #endif
 
     if (!cert || !srvPrivkey || !ciphersuites || !pcanbypass) {
-	PORT_SetError(SEC_ERROR_INVALID_ARGS);
+        PORT_SetError(SEC_ERROR_INVALID_ARGS);
         return SECFailure;
     }
-    
+
     srvPubkey = CERT_ExtractPublicKey(cert);
     if (!srvPubkey)
         return SECFailure;
-	
+
     *pcanbypass = PR_TRUE;
     rv = SECFailure;
-    
+
     /* determine which KEAs to test */
     /* 0 (TLS_NULL_WITH_NULL_NULL) is used as a list terminator because
      * SSL3 and TLS specs forbid negotiating that cipher suite number.
      */
-    for (i=0; i < nsuites && (suite = *ciphersuites++) != 0; i++) {
-	/* skip SSL2 cipher suites and ones NSS doesn't support */
-	if (SSL_GetCipherSuiteInfo(suite, &csdef, sizeof(csdef)) != SECSuccess
-	    || SSL_IS_SSL2_CIPHER(suite) )
-	    continue;
-	switch (csdef.keaType) {
-	case ssl_kea_rsa:
-	    switch (csdef.cipherSuite) {
-	    case TLS_RSA_EXPORT1024_WITH_RC4_56_SHA:
-	    case TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA:
-	    case TLS_RSA_EXPORT_WITH_RC4_40_MD5:
-	    case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
-		testrsa_export = PR_TRUE;
-	    }
-	    if (!testrsa_export)
-		testrsa = PR_TRUE;
-	    break;
-	case ssl_kea_ecdh:
-	    if (strcmp(csdef.keaTypeName, "ECDHE") == 0) /* ephemeral? */
-		testecdhe = PR_TRUE;
-	    else
-		testecdh = PR_TRUE;
-	    break;
-	case ssl_kea_dh:
-	    /* this is actually DHE */
-	default:
-	    continue;
-	}
+    for (i = 0; i < nsuites && (suite = *ciphersuites++) != 0; i++) {
+        /* skip SSL2 cipher suites and ones NSS doesn't support */
+        if (SSL_GetCipherSuiteInfo(suite, &csdef, sizeof(csdef)) != SECSuccess ||
+            SSL_IS_SSL2_CIPHER(suite))
+            continue;
+        switch (csdef.keaType) {
+            case ssl_kea_rsa:
+                switch (csdef.cipherSuite) {
+                    case TLS_RSA_EXPORT1024_WITH_RC4_56_SHA:
+                    case TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA:
+                    case TLS_RSA_EXPORT_WITH_RC4_40_MD5:
+                    case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
+                        testrsa_export = PR_TRUE;
+                }
+                if (!testrsa_export)
+                    testrsa = PR_TRUE;
+                break;
+            case ssl_kea_ecdh:
+                if (strcmp(csdef.keaTypeName, "ECDHE") == 0) /* ephemeral? */
+                    testecdhe = PR_TRUE;
+                else
+                    testecdh = PR_TRUE;
+                break;
+            case ssl_kea_dh:
+            /* this is actually DHE */
+            default:
+                continue;
+        }
     }
-    
+
     /* For each protocol try to derive and extract an MS.
      * Failure of function any function except MS extract means
      * continue with the next cipher test. Stop testing when the list is
      * exhausted or when the first MS extract--not derive--fails.
      */
     privKeytype = SECKEY_GetPrivateKeyType(srvPrivkey);
-    protocolmask &= SSL_CBP_SSL3|SSL_CBP_TLS1_0;
+    protocolmask &= SSL_CBP_SSL3 | SSL_CBP_TLS1_0;
     while (protocolmask) {
-	if (protocolmask & SSL_CBP_SSL3) {
-	    isTLS = PR_FALSE;
-	    protocolmask ^= SSL_CBP_SSL3;
-	} else {
-	    isTLS = PR_TRUE;
-	    protocolmask ^= SSL_CBP_TLS1_0;
-	}
+        if (protocolmask & SSL_CBP_SSL3) {
+            isTLS = PR_FALSE;
+            protocolmask ^= SSL_CBP_SSL3;
+        }
+        else {
+            isTLS = PR_TRUE;
+            protocolmask ^= SSL_CBP_TLS1_0;
+        }
 
-	if (privKeytype == rsaKey && testrsa_export) {
-	    if (PK11_GetPrivateModulusLen(srvPrivkey) > EXPORT_RSA_KEY_LENGTH) {
-		*pcanbypass = PR_FALSE;
-		rv = SECSuccess;
-		break;
-	    } else
-		testrsa = PR_TRUE;
-	}
-	for (; privKeytype == rsaKey && testrsa; ) {
-	    /* TLS_RSA */
-	    unsigned char     rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
-	    unsigned int      outLen = 0;
-	    CK_MECHANISM_TYPE target;
-	    SECStatus	      irv;
-	    
-	    mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
-	    mechanism_array[1] = CKM_RSA_PKCS;
+        if (privKeytype == rsaKey && testrsa_export) {
+            if (PK11_GetPrivateModulusLen(srvPrivkey) > EXPORT_RSA_KEY_LENGTH) {
+                *pcanbypass = PR_FALSE;
+                rv = SECSuccess;
+                break;
+            }
+            else
+                testrsa = PR_TRUE;
+        }
+        for (; privKeytype == rsaKey && testrsa;) {
+            /* TLS_RSA */
+            unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
+            unsigned int outLen = 0;
+            CK_MECHANISM_TYPE target;
+            SECStatus irv;
 
-	    slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
-	    if (slot == NULL) {
-		PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
-		break;
-	    }
+            mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
+            mechanism_array[1] = CKM_RSA_PKCS;
+
+            slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
+            if (slot == NULL) {
+                PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
+                break;
+            }
 
-	    /* Generate the pre-master secret ...  (client side) */
-	    version.major = 3 /*MSB(clientHelloVersion)*/;
-	    version.minor = 0 /*LSB(clientHelloVersion)*/;
-	    param.data = (unsigned char *)&version;
-	    param.len  = sizeof version;
-	    pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
-	    PK11_FreeSlot(slot);
-	    if (!pms)
-		break;
-	    /* now wrap it */
-	    enc_pms.len  = SECKEY_PublicKeyStrength(srvPubkey);
-	    enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
-	    if (enc_pms.data == NULL) {
-	        PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
-	        break;
-	    }
-	    irv = PK11_PubWrapSymKey(CKM_RSA_PKCS, srvPubkey, pms, &enc_pms);
-	    if (irv != SECSuccess) 
-		break;
-	    PK11_FreeSymKey(pms);
-	    pms = NULL;
-	    /* now do the server side--check the triple bypass first */
-	    rv = PK11_PrivDecryptPKCS1(srvPrivkey, rsaPmsBuf, &outLen,
-				       sizeof rsaPmsBuf,
-				       (unsigned char *)enc_pms.data,
-				       enc_pms.len);
-	    /* if decrypt worked we're done with the RSA test */
-	    if (rv == SECSuccess) {
-		*pcanbypass = PR_TRUE;
-		break;
-	    }
-	    /* check for fallback to double bypass */
-	    target = isTLS ? CKM_TLS_MASTER_KEY_DERIVE
-			: CKM_SSL3_MASTER_KEY_DERIVE;
-	    pms = PK11_PubUnwrapSymKey(srvPrivkey, &enc_pms,
-				       target, CKA_DERIVE, 0);
-	    rv = ssl_canExtractMS(pms, isTLS, PR_FALSE, pcanbypass);
-	    if (rv == SECSuccess && *pcanbypass == PR_FALSE)
-		goto done;
-	    break;
-	}
+            /* Generate the pre-master secret ...  (client side) */
+            version.major = 3 /*MSB(clientHelloVersion)*/;
+            version.minor = 0 /*LSB(clientHelloVersion)*/;
+            param.data = (unsigned char *)&version;
+            param.len = sizeof version;
+            pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
+            PK11_FreeSlot(slot);
+            if (!pms)
+                break;
+            /* now wrap it */
+            enc_pms.len = SECKEY_PublicKeyStrength(srvPubkey);
+            enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
+            if (enc_pms.data == NULL) {
+                PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
+                break;
+            }
+            irv = PK11_PubWrapSymKey(CKM_RSA_PKCS, srvPubkey, pms, &enc_pms);
+            if (irv != SECSuccess)
+                break;
+            PK11_FreeSymKey(pms);
+            pms = NULL;
+            /* now do the server side--check the triple bypass first */
+            rv = PK11_PrivDecryptPKCS1(srvPrivkey, rsaPmsBuf, &outLen,
+                                       sizeof rsaPmsBuf,
+                                       (unsigned char *)enc_pms.data,
+                                       enc_pms.len);
+            /* if decrypt worked we're done with the RSA test */
+            if (rv == SECSuccess) {
+                *pcanbypass = PR_TRUE;
+                break;
+            }
+            /* check for fallback to double bypass */
+            target = isTLS ? CKM_TLS_MASTER_KEY_DERIVE
+                           : CKM_SSL3_MASTER_KEY_DERIVE;
+            pms = PK11_PubUnwrapSymKey(srvPrivkey, &enc_pms,
+                                       target, CKA_DERIVE, 0);
+            rv = ssl_canExtractMS(pms, isTLS, PR_FALSE, pcanbypass);
+            if (rv == SECSuccess && *pcanbypass == PR_FALSE)
+                goto done;
+            break;
+        }
 
-	/* Check for NULL to avoid double free. 
-	 * SECItem_FreeItem sets data NULL in secitem.c#265 
-	 */
-	if (enc_pms.data != NULL) {
-	    SECITEM_FreeItem(&enc_pms, PR_FALSE);
+        /* Check for NULL to avoid double free.
+         * SECItem_FreeItem sets data NULL in secitem.c#265
+         */
+        if (enc_pms.data != NULL) {
+            SECITEM_FreeItem(&enc_pms, PR_FALSE);
         }
 #ifndef NSS_DISABLE_ECC
-	for (; (privKeytype == ecKey && ( testecdh || testecdhe)) ||
-	       (privKeytype == rsaKey && testecdhe); ) {
-	    CK_MECHANISM_TYPE target;
-	    SECKEYPublicKey  *keapub = NULL;
-	    SECKEYPrivateKey *keapriv;
-	    SECKEYPublicKey  *cpub = NULL; /* client's ephemeral ECDH keys */
-	    SECKEYPrivateKey *cpriv = NULL;
-	    SECKEYECParams   *pecParams = NULL;
+        for (; (privKeytype == ecKey && (testecdh || testecdhe)) ||
+               (privKeytype == rsaKey && testecdhe);) {
+            CK_MECHANISM_TYPE target;
+            SECKEYPublicKey *keapub = NULL;
+            SECKEYPrivateKey *keapriv;
+            SECKEYPublicKey *cpub = NULL; /* client's ephemeral ECDH keys */
+            SECKEYPrivateKey *cpriv = NULL;
+            SECKEYECParams *pecParams = NULL;
 
-	    if (privKeytype == ecKey && testecdhe) {
-		/* TLS_ECDHE_ECDSA */
-		pecParams = &srvPubkey->u.ec.DEREncodedParams;
-	    } else if (privKeytype == rsaKey && testecdhe) {
-		/* TLS_ECDHE_RSA */
-		ECName       ec_curve;
-		int		 serverKeyStrengthInBits;
-		int		 signatureKeyStrength;
-		int		 requiredECCbits;
+            if (privKeytype == ecKey && testecdhe) {
+                /* TLS_ECDHE_ECDSA */
+                pecParams = &srvPubkey->u.ec.DEREncodedParams;
+            }
+            else if (privKeytype == rsaKey && testecdhe) {
+                /* TLS_ECDHE_RSA */
+                ECName ec_curve;
+                int serverKeyStrengthInBits;
+                int signatureKeyStrength;
+                int requiredECCbits;
 
-		/* find a curve of equivalent strength to the RSA key's */
-		requiredECCbits = PK11_GetPrivateModulusLen(srvPrivkey);
-		if (requiredECCbits < 0)
-		    break;
-		requiredECCbits *= BPB;
-		serverKeyStrengthInBits = srvPubkey->u.rsa.modulus.len;
-		if (srvPubkey->u.rsa.modulus.data[0] == 0) {
-		    serverKeyStrengthInBits--;
-		}
-		/* convert to strength in bits */
-		serverKeyStrengthInBits *= BPB;
+                /* find a curve of equivalent strength to the RSA key's */
+                requiredECCbits = PK11_GetPrivateModulusLen(srvPrivkey);
+                if (requiredECCbits < 0)
+                    break;
+                requiredECCbits *= BPB;
+                serverKeyStrengthInBits = srvPubkey->u.rsa.modulus.len;
+                if (srvPubkey->u.rsa.modulus.data[0] == 0) {
+                    serverKeyStrengthInBits--;
+                }
+                /* convert to strength in bits */
+                serverKeyStrengthInBits *= BPB;
 
-		signatureKeyStrength =
-		    SSL_RSASTRENGTH_TO_ECSTRENGTH(serverKeyStrengthInBits);
+                signatureKeyStrength =
+                    SSL_RSASTRENGTH_TO_ECSTRENGTH(serverKeyStrengthInBits);
 
-		if ( requiredECCbits > signatureKeyStrength ) 
-		     requiredECCbits = signatureKeyStrength;
+                if (requiredECCbits > signatureKeyStrength)
+                    requiredECCbits = signatureKeyStrength;
 
-		ec_curve =
-		    ssl3_GetCurveWithECKeyStrength(
-					ssl3_GetSupportedECCurveMask(NULL),
-				  	requiredECCbits);
-		rv = ssl3_ECName2Params(NULL, ec_curve, &ecParams);
-		if (rv == SECFailure) {
-		    break;
-		}
-		pecParams = &ecParams;
-	    }
+                ec_curve =
+                    ssl3_GetCurveWithECKeyStrength(
+                        ssl3_GetSupportedECCurveMask(NULL),
+                        requiredECCbits);
+                rv = ssl3_ECName2Params(NULL, ec_curve, &ecParams);
+                if (rv == SECFailure) {
+                    break;
+                }
+                pecParams = &ecParams;
+            }
 
-	    if (testecdhe) {
-		/* generate server's ephemeral keys */
-		keapriv = SECKEY_CreateECPrivateKey(pecParams, &keapub, NULL); 
-		if (!keapriv || !keapub) {
-		    if (keapriv)
-			SECKEY_DestroyPrivateKey(keapriv);
-		    if (keapub)
-			SECKEY_DestroyPublicKey(keapub);
-		    PORT_SetError(SEC_ERROR_KEYGEN_FAIL);
-		    rv = SECFailure;
-		    break;
-		}
-	    } else {
-		/* TLS_ECDH_ECDSA */
-		keapub = srvPubkey;
-		keapriv = srvPrivkey;
-		pecParams = &srvPubkey->u.ec.DEREncodedParams;
-	    }
+            if (testecdhe) {
+                /* generate server's ephemeral keys */
+                keapriv = SECKEY_CreateECPrivateKey(pecParams, &keapub, NULL);
+                if (!keapriv || !keapub) {
+                    if (keapriv)
+                        SECKEY_DestroyPrivateKey(keapriv);
+                    if (keapub)
+                        SECKEY_DestroyPublicKey(keapub);
+                    PORT_SetError(SEC_ERROR_KEYGEN_FAIL);
+                    rv = SECFailure;
+                    break;
+                }
+            }
+            else {
+                /* TLS_ECDH_ECDSA */
+                keapub = srvPubkey;
+                keapriv = srvPrivkey;
+                pecParams = &srvPubkey->u.ec.DEREncodedParams;
+            }
 
-	    /* perform client side ops */
-	    /* generate a pair of ephemeral keys using server's parms */
-	    cpriv = SECKEY_CreateECPrivateKey(pecParams, &cpub, NULL);
-	    if (!cpriv || !cpub) {
-		if (testecdhe) {
-		    SECKEY_DestroyPrivateKey(keapriv);
-		    SECKEY_DestroyPublicKey(keapub);
-		}
-		PORT_SetError(SEC_ERROR_KEYGEN_FAIL);
-		rv = SECFailure;
-		break;
-	    }
-	    /* now do the server side */
-	    /* determine the PMS using client's public value */
-	    target = isTLS ? CKM_TLS_MASTER_KEY_DERIVE_DH
-			   : CKM_SSL3_MASTER_KEY_DERIVE_DH;
-	    pms = PK11_PubDeriveWithKDF(keapriv, cpub, PR_FALSE, NULL, NULL,
-				    CKM_ECDH1_DERIVE,
-				    target,
-				    CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
-	    rv = ssl_canExtractMS(pms, isTLS, PR_TRUE, pcanbypass);
-	    SECKEY_DestroyPrivateKey(cpriv);
-	    SECKEY_DestroyPublicKey(cpub);
-	    if (testecdhe) {
-		SECKEY_DestroyPrivateKey(keapriv);
-		SECKEY_DestroyPublicKey(keapub);
-	    }
-	    if (rv == SECSuccess && *pcanbypass == PR_FALSE)
-		goto done;
-	    break;
-	}
-	/* Check for NULL to avoid double free. */
-	if (ecParams.data != NULL) {
-	    PORT_Free(ecParams.data);
-	    ecParams.data = NULL;
-	}
+            /* perform client side ops */
+            /* generate a pair of ephemeral keys using server's parms */
+            cpriv = SECKEY_CreateECPrivateKey(pecParams, &cpub, NULL);
+            if (!cpriv || !cpub) {
+                if (testecdhe) {
+                    SECKEY_DestroyPrivateKey(keapriv);
+                    SECKEY_DestroyPublicKey(keapub);
+                }
+                PORT_SetError(SEC_ERROR_KEYGEN_FAIL);
+                rv = SECFailure;
+                break;
+            }
+            /* now do the server side */
+            /* determine the PMS using client's public value */
+            target = isTLS ? CKM_TLS_MASTER_KEY_DERIVE_DH
+                           : CKM_SSL3_MASTER_KEY_DERIVE_DH;
+            pms = PK11_PubDeriveWithKDF(keapriv, cpub, PR_FALSE, NULL, NULL,
+                                        CKM_ECDH1_DERIVE,
+                                        target,
+                                        CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
+            rv = ssl_canExtractMS(pms, isTLS, PR_TRUE, pcanbypass);
+            SECKEY_DestroyPrivateKey(cpriv);
+            SECKEY_DestroyPublicKey(cpub);
+            if (testecdhe) {
+                SECKEY_DestroyPrivateKey(keapriv);
+                SECKEY_DestroyPublicKey(keapub);
+            }
+            if (rv == SECSuccess && *pcanbypass == PR_FALSE)
+                goto done;
+            break;
+        }
+        /* Check for NULL to avoid double free. */
+        if (ecParams.data != NULL) {
+            PORT_Free(ecParams.data);
+            ecParams.data = NULL;
+        }
 #endif /* NSS_DISABLE_ECC */
-	if (pms)
-	    PK11_FreeSymKey(pms);
+        if (pms)
+            PK11_FreeSymKey(pms);
     }
 
     /* *pcanbypass has been set */
     rv = SECSuccess;
-    
-  done:
+
+done:
     if (pms)
-	PK11_FreeSymKey(pms);
+        PK11_FreeSymKey(pms);
 
-    /* Check for NULL to avoid double free. 
-     * SECItem_FreeItem sets data NULL in secitem.c#265 
+    /* Check for NULL to avoid double free.
+     * SECItem_FreeItem sets data NULL in secitem.c#265
      */
     if (enc_pms.data != NULL) {
-    	SECITEM_FreeItem(&enc_pms, PR_FALSE);
+        SECITEM_FreeItem(&enc_pms, PR_FALSE);
     }
 #ifndef NSS_DISABLE_ECC
     if (ecParams.data != NULL) {
         PORT_Free(ecParams.data);
         ecParams.data = NULL;
     }
 #endif /* NSS_DISABLE_ECC */
 
     if (srvPubkey) {
-    	SECKEY_DestroyPublicKey(srvPubkey);
-	srvPubkey = NULL;
+        SECKEY_DestroyPublicKey(srvPubkey);
+        srvPubkey = NULL;
     }
 
-
     return rv;
 #endif /* NO_PKCS11_BYPASS */
 }
-
--- a/security/nss/lib/ssl/dtlscon.c
+++ b/security/nss/lib/ssl/dtlscon.c
@@ -6,29 +6,29 @@
  * DTLS Protocol
  */
 
 #include "ssl.h"
 #include "sslimpl.h"
 #include "sslproto.h"
 
 #ifndef PR_ARRAY_SIZE
-#define PR_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
+#define PR_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
 #endif
 
 static SECStatus dtls_TransmitMessageFlight(sslSocket *ss);
 static void dtls_RetransmitTimerExpiredCb(sslSocket *ss);
 static SECStatus dtls_SendSavedWriteData(sslSocket *ss);
 
 /* -28 adjusts for the IP/UDP header */
 static const PRUint16 COMMON_MTU_VALUES[] = {
-    1500 - 28,  /* Ethernet MTU */
-    1280 - 28,  /* IPv6 minimum MTU */
-    576 - 28,   /* Common assumption */
-    256 - 28    /* We're in serious trouble now */
+    1500 - 28, /* Ethernet MTU */
+    1280 - 28, /* IPv6 minimum MTU */
+    576 - 28,  /* Common assumption */
+    256 - 28   /* We're in serious trouble now */
 };
 
 #define DTLS_COOKIE_BYTES 32
 
 /* List copied from ssl3con.c:cipherSuites */
 static const ssl3CipherSuite nonDTLSSuites[] = {
 #ifndef NSS_DISABLE_ECC
     TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
@@ -99,19 +99,19 @@ dtls_DTLSVersionToTLSVersion(SSL3Protoco
     }
 
     /* Return a fictional higher version than we know of */
     return SSL_LIBRARY_VERSION_MAX_SUPPORTED + 1;
 }
 
 /* On this socket, Disable non-DTLS cipher suites in the argument's list */
 SECStatus
-ssl3_DisableNonDTLSSuites(sslSocket * ss)
+ssl3_DisableNonDTLSSuites(sslSocket *ss)
 {
-    const ssl3CipherSuite * suite;
+    const ssl3CipherSuite *suite;
 
     for (suite = nonDTLSSuites; *suite; ++suite) {
         PORT_CheckSuccess(ssl3_CipherPrefSet(ss, *suite, PR_FALSE));
     }
     return SECSuccess;
 }
 
 /* Allocate a DTLSQueuedMessage.
@@ -185,18 +185,18 @@ dtls_FreeHandshakeMessages(PRCList *list
  *
  * (1) To pass the length to ssl3_HandleHandshakeMessage()
  * (2) To carry the length of a message currently being reassembled
  *
  * However, unlike ssl3_HandleHandshake(), it is not used to carry
  * the state of reassembly (i.e., whether one is in progress). That
  * is carried in recvdHighWater and recvdFragments.
  */
-#define OFFSET_BYTE(o) (o/8)
-#define OFFSET_MASK(o) (1 << (o%8))
+#define OFFSET_BYTE(o) (o / 8)
+#define OFFSET_MASK(o) (1 << (o % 8))
 
 SECStatus
 dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
 {
     /* XXX OK for now.
      * This doesn't work properly with asynchronous certificate validation.
      * because that returns a WOULDBLOCK error. The current DTLS
      * applications do not need asynchronous validation, but in the
@@ -224,17 +224,17 @@ dtls_HandleHandshake(sslSocket *ss, sslB
 
         /* Parse the header */
         type = buf.buf[0];
         message_length = (buf.buf[1] << 16) | (buf.buf[2] << 8) | buf.buf[3];
         message_seq = (buf.buf[4] << 8) | buf.buf[5];
         fragment_offset = (buf.buf[6] << 16) | (buf.buf[7] << 8) | buf.buf[8];
         fragment_length = (buf.buf[9] << 16) | (buf.buf[10] << 8) | buf.buf[11];
 
-#define MAX_HANDSHAKE_MSG_LEN 0x1ffff   /* 128k - 1 */
+#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
         if (message_length > MAX_HANDSHAKE_MSG_LEN) {
             (void)ssl3_DecodeError(ss);
             PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
             return SECFailure;
         }
 #undef MAX_HANDSHAKE_MSG_LEN
 
         buf.buf += 12;
@@ -258,19 +258,19 @@ dtls_HandleHandshake(sslSocket *ss, sslB
          *
          * 1. It's a partial next message.
          * 2. It's a partial or complete message beyond the next
          * 3. It's a message we've already seen
          *
          * If it's the complete next message we accept it right away.
          * This is the common case for short messages
          */
-        if ((message_seq == ss->ssl3.hs.recvMessageSeq)
-            && (fragment_offset == 0)
-            && (fragment_length == message_length)) {
+        if ((message_seq == ss->ssl3.hs.recvMessageSeq) &&
+            (fragment_offset == 0) &&
+            (fragment_length == message_length)) {
             /* Complete next message. Process immediately */
             ss->ssl3.hs.msg_type = (SSL3HandshakeType)type;
             ss->ssl3.hs.msg_len = message_length;
 
             /* At this point we are advancing our state machine, so
              * we can free our last flight of messages */
             dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
             ss->ssl3.hs.recvdHighWater = -1;
@@ -282,75 +282,81 @@ dtls_HandleHandshake(sslSocket *ss, sslB
                 ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
             }
 
             rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len);
             if (rv == SECFailure) {
                 /* Do not attempt to process rest of messages in this record */
                 break;
             }
-        } else {
+        }
+        else {
             if (message_seq < ss->ssl3.hs.recvMessageSeq) {
                 /* Case 3: we do an immediate retransmit if we're
                  * in a waiting state*/
                 if (ss->ssl3.hs.rtTimerCb == NULL) {
                     /* Ignore */
-                } else if (ss->ssl3.hs.rtTimerCb ==
+                }
+                else if (ss->ssl3.hs.rtTimerCb ==
                          dtls_RetransmitTimerExpiredCb) {
                     SSL_TRC(30, ("%d: SSL3[%d]: Retransmit detected",
                                  SSL_GETPID(), ss->fd));
                     /* Check to see if we retransmitted recently. If so,
                      * suppress the triggered retransmit. This avoids
                      * retransmit wars after packet loss.
                      * This is not in RFC 5346 but should be
                      */
                     if ((PR_IntervalNow() - ss->ssl3.hs.rtTimerStarted) >
                         (ss->ssl3.hs.rtTimeoutMs / 4)) {
-                            SSL_TRC(30,
-                            ("%d: SSL3[%d]: Shortcutting retransmit timer",
-                            SSL_GETPID(), ss->fd));
+                        SSL_TRC(30,
+                                ("%d: SSL3[%d]: Shortcutting retransmit timer",
+                                 SSL_GETPID(), ss->fd));
 
-                            /* Cancel the timer and call the CB,
-                             * which re-arms the timer */
-                            dtls_CancelTimer(ss);
-                            dtls_RetransmitTimerExpiredCb(ss);
-                            rv = SECSuccess;
-                            break;
-                        } else {
-                            SSL_TRC(30,
-                            ("%d: SSL3[%d]: We just retransmitted. Ignoring.",
-                            SSL_GETPID(), ss->fd));
-                            rv = SECSuccess;
-                            break;
-                        }
-                } else if (ss->ssl3.hs.rtTimerCb == dtls_FinishedTimerCb) {
+                        /* Cancel the timer and call the CB,
+                         * which re-arms the timer */
+                        dtls_CancelTimer(ss);
+                        dtls_RetransmitTimerExpiredCb(ss);
+                        rv = SECSuccess;
+                        break;
+                    }
+                    else {
+                        SSL_TRC(30,
+                                ("%d: SSL3[%d]: We just retransmitted. Ignoring.",
+                                 SSL_GETPID(), ss->fd));
+                        rv = SECSuccess;
+                        break;
+                    }
+                }
+                else if (ss->ssl3.hs.rtTimerCb == dtls_FinishedTimerCb) {
                     /* Retransmit the messages and re-arm the timer
                      * Note that we are not backing off the timer here.
                      * The spec isn't clear and my reasoning is that this
                      * may be a re-ordered packet rather than slowness,
                      * so let's be aggressive. */
                     dtls_CancelTimer(ss);
                     rv = dtls_TransmitMessageFlight(ss);
                     if (rv == SECSuccess) {
                         rv = dtls_StartTimer(ss, dtls_FinishedTimerCb);
                     }
                     if (rv != SECSuccess)
                         return rv;
                     break;
                 }
-            } else if (message_seq > ss->ssl3.hs.recvMessageSeq) {
+            }
+            else if (message_seq > ss->ssl3.hs.recvMessageSeq) {
                 /* Case 2
                  *
                  * Ignore this message. This means we don't handle out of
                  * order complete messages that well, but we're still
                  * compliant and this probably does not happen often
                  *
                  * XXX OK for now. Maybe do something smarter at some point?
                  */
-            } else {
+            }
+            else {
                 /* Case 1
                  *
                  * Buffer the fragment for reassembly
                  */
                 /* Make room for the message */
                 if (ss->ssl3.hs.recvdHighWater == -1) {
                     PRUint32 map_length = OFFSET_BYTE(message_length) + 1;
 
@@ -399,17 +405,18 @@ dtls_HandleHandshake(sslSocket *ss, sslB
                  * This avoids having to fill in the bitmask in the common
                  * case of adjacent fragments received in sequence
                  */
                 if (fragment_offset <= (unsigned int)ss->ssl3.hs.recvdHighWater) {
                     /* Either this is the adjacent fragment or an overlapping
                      * fragment */
                     ss->ssl3.hs.recvdHighWater = fragment_offset +
                                                  fragment_length;
-                } else {
+                }
+                else {
                     for (offset = fragment_offset;
                          offset < fragment_offset + fragment_length;
                          offset++) {
                         ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] |=
                             OFFSET_MASK(offset);
                     }
                 }
 
@@ -417,17 +424,18 @@ dtls_HandleHandshake(sslSocket *ss, sslB
                 for (offset = ss->ssl3.hs.recvdHighWater;
                      offset < ss->ssl3.hs.msg_len; offset++) {
                     /* Note that this loop is not efficient, since it counts
                      * bit by bit. If we have a lot of out-of-order packets,
                      * we should optimize this */
                     if (ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] &
                         OFFSET_MASK(offset)) {
                         ss->ssl3.hs.recvdHighWater++;
-                    } else {
+                    }
+                    else {
                         break;
                     }
                 }
 
                 /* If we have all the bytes, then we are good to go */
                 if (ss->ssl3.hs.recvdHighWater == ss->ssl3.hs.msg_len) {
                     ss->ssl3.hs.recvdHighWater = -1;
 
@@ -450,44 +458,46 @@ dtls_HandleHandshake(sslSocket *ss, sslB
                 }
             }
         }
 
         buf.buf += fragment_length;
         buf.len -= fragment_length;
     }
 
-    origBuf->len = 0;   /* So ssl3_GatherAppDataRecord will keep looping. */
+    origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
 
     /* XXX OK for now. In future handle rv == SECWouldBlock safely in order
      * to deal with asynchronous certificate verification */
     return rv;
 }
 
 /* Enqueue a message (either handshake or CCS)
  *
  * Called from:
  *              dtls_StageHandshakeMessage()
  *              ssl3_SendChangeCipherSpecs()
  */
-SECStatus dtls_QueueMessage(sslSocket *ss, SSL3ContentType type,
-    const SSL3Opaque *pIn, PRInt32 nIn)
+SECStatus
+dtls_QueueMessage(sslSocket *ss, SSL3ContentType type,
+                  const SSL3Opaque *pIn, PRInt32 nIn)
 {
     SECStatus rv = SECSuccess;
     DTLSQueuedMessage *msg = NULL;
 
     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
 
     msg = dtls_AllocQueuedMessage(ss->ssl3.cwSpec->epoch, type, pIn, nIn);
 
     if (!msg) {
         PORT_SetError(SEC_ERROR_NO_MEMORY);
         rv = SECFailure;
-    } else {
+    }
+    else {
         PR_APPEND_LINK(&msg->link, &ss->ssl3.hs.lastMessageFlight);
     }
 
     return rv;
 }
 
 /* Add DTLS handshake message to the pending queue
  * Empty the sendBuf buffer.
@@ -634,27 +644,28 @@ dtls_TransmitMessageFlight(sslSocket *ss
         }
 
         if ((msg->len + SSL3_BUFFER_FUDGE) <= room_left) {
             /* The message will fit, so encrypt and then continue with the
              * next packet */
             sent = ssl3_SendRecord(ss, msg->epoch, msg->type,
                                    msg->data, msg->len,
                                    ssl_SEND_FLAG_FORCE_INTO_BUFFER |
-                                   ssl_SEND_FLAG_USE_EPOCH);
+                                       ssl_SEND_FLAG_USE_EPOCH);
             if (sent != msg->len) {
                 rv = SECFailure;
                 if (sent != -1) {
                     PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
                 }
                 break;
             }
 
             room_left = ss->ssl3.mtu - ss->pendingBuf.len;
-        } else {
+        }
+        else {
             /* The message will not fit, so fragment.
              *
              * XXX OK for now. Arrange to coalesce the last fragment
              * of this message with the next message if possible.
              * That would be more efficient.
              */
             PRUint32 fragment_offset = 0;
             unsigned char fragment[DTLS_MAX_MTU]; /* >= than largest
@@ -694,34 +705,34 @@ dtls_TransmitMessageFlight(sslSocket *ss
 
                 /* Construct an appropriate-sized fragment */
                 /* Type, length, sequence */
                 PORT_Memcpy(fragment, msg->data, 6);
 
                 /* Offset */
                 fragment[6] = (fragment_offset >> 16) & 0xff;
                 fragment[7] = (fragment_offset >> 8) & 0xff;
-                fragment[8] = (fragment_offset) & 0xff;
+                fragment[8] = (fragment_offset)&0xff;
 
                 /* Fragment length */
                 fragment[9] = (fragment_len >> 16) & 0xff;
                 fragment[10] = (fragment_len >> 8) & 0xff;
-                fragment[11] = (fragment_len) & 0xff;
+                fragment[11] = (fragment_len)&0xff;
 
                 PORT_Memcpy(fragment + 12, content + fragment_offset,
                             fragment_len);
 
                 /*
                  *  Send the record. We do this in two stages
                  * 1. Encrypt
                  */
                 sent = ssl3_SendRecord(ss, msg->epoch, msg->type,
                                        fragment, fragment_len + 12,
                                        ssl_SEND_FLAG_FORCE_INTO_BUFFER |
-                                       ssl_SEND_FLAG_USE_EPOCH);
+                                           ssl_SEND_FLAG_USE_EPOCH);
                 if (sent != (fragment_len + 12)) {
                     rv = SECFailure;
                     if (sent != -1) {
                         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
                     }
                     break;
                 }
 
@@ -747,18 +758,18 @@ dtls_TransmitMessageFlight(sslSocket *ss
 }
 
 /* Flush the data in the pendingBuf and update the max message sent
  * so we can adjust the MTU estimate if we need to.
  * Wrapper for ssl_SendSavedWriteData.
  *
  * Called from dtls_TransmitMessageFlight()
  */
-static
-SECStatus dtls_SendSavedWriteData(sslSocket *ss)
+static SECStatus
+dtls_SendSavedWriteData(sslSocket *ss)
 {
     PRInt32 sent;
 
     sent = ssl_SendSavedWriteData(ss);
     if (sent < 0)
         return SECFailure;
 
     /* We should always have complete writes b/c datagram sockets
@@ -779,28 +790,28 @@ SECStatus dtls_SendSavedWriteData(sslSoc
 /* Compress, MAC, encrypt a DTLS record. Allows specification of
  * the epoch using epoch value. If use_epoch is PR_TRUE then
  * we use the provided epoch. If use_epoch is PR_FALSE then
  * whatever the current value is in effect is used.
  *
  * Called from ssl3_SendRecord()
  */
 SECStatus
-dtls_CompressMACEncryptRecord(sslSocket *        ss,
-                              DTLSEpoch          epoch,
-                              PRBool             use_epoch,
-                              SSL3ContentType    type,
-                              const SSL3Opaque * pIn,
-                              PRUint32           contentLen,
-                              sslBuffer        * wrBuf)
+dtls_CompressMACEncryptRecord(sslSocket *ss,
+                              DTLSEpoch epoch,
+                              PRBool use_epoch,
+                              SSL3ContentType type,
+                              const SSL3Opaque *pIn,
+                              PRUint32 contentLen,
+                              sslBuffer *wrBuf)
 {
     SECStatus rv = SECFailure;
-    ssl3CipherSpec *          cwSpec;
+    ssl3CipherSpec *cwSpec;
 
-    ssl_GetSpecReadLock(ss);    /********************************/
+    ssl_GetSpecReadLock(ss); /********************************/
 
     /* The reason for this switch-hitting code is that we might have
      * a flight of records spanning an epoch boundary, e.g.,
      *
      * ClientKeyExchange (epoch = 0)
      * ChangeCipherSpec (epoch = 0)
      * Finished (epoch = 1)
      *
@@ -809,29 +820,32 @@ dtls_CompressMACEncryptRecord(sslSocket 
      */
     if (use_epoch) {
         if (ss->ssl3.cwSpec->epoch == epoch)
             cwSpec = ss->ssl3.cwSpec;
         else if (ss->ssl3.pwSpec->epoch == epoch)
             cwSpec = ss->ssl3.pwSpec;
         else
             cwSpec = NULL;
-    } else {
+    }
+    else {
         cwSpec = ss->ssl3.cwSpec;
     }
 
     if (cwSpec) {
         if (ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3) {
             rv = ssl3_CompressMACEncryptRecord(cwSpec, ss->sec.isServer, PR_TRUE,
                                                PR_FALSE, type, pIn, contentLen,
                                                wrBuf);
-        } else {
+        }
+        else {
             rv = tls13_ProtectRecord(ss, type, pIn, contentLen, wrBuf);
         }
-    } else {
+    }
+    else {
         PR_NOT_REACHED("Couldn't find a cipher spec matching epoch");
         PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
     }
     ssl_ReleaseSpecReadLock(ss); /************************************/
 
     return rv;
 }
 
@@ -960,75 +974,74 @@ dtls_SetMTU(sslSocket *ss, PRUint16 adve
         if (COMMON_MTU_VALUES[i] <= advertised) {
             ss->ssl3.mtu = COMMON_MTU_VALUES[i];
             SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
             return;
         }
     }
 
     /* Fallback */
-    ss->ssl3.mtu = COMMON_MTU_VALUES[PR_ARRAY_SIZE(COMMON_MTU_VALUES)-1];
+    ss->ssl3.mtu = COMMON_MTU_VALUES[PR_ARRAY_SIZE(COMMON_MTU_VALUES) - 1];
     SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
 }
 
 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a
  * DTLS hello_verify_request
  * Caller must hold Handshake and RecvBuf locks.
  */
 SECStatus
 dtls_HandleHelloVerifyRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
 {
-    int                 errCode = SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST;
-    SECStatus           rv;
-    PRInt32             temp;
-    SECItem             cookie = {siBuffer, NULL, 0};
-    SSL3AlertDescription desc   = illegal_parameter;
+    int errCode = SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST;
+    SECStatus rv;
+    PRInt32 temp;
+    SECItem cookie = { siBuffer, NULL, 0 };
+    SSL3AlertDescription desc = illegal_parameter;
 
     SSL_TRC(3, ("%d: SSL3[%d]: handle hello_verify_request handshake",
-        SSL_GETPID(), ss->fd));
+                SSL_GETPID(), ss->fd));
     PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
 
     if (ss->ssl3.hs.ws != wait_server_hello) {
         errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST;
-        desc    = unexpected_message;
+        desc = unexpected_message;
         goto alert_loser;
     }
 
     /* The version */
     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
     if (temp < 0) {
-        goto loser;     /* alert has been sent */
+        goto loser; /* alert has been sent */
     }
 
     if (temp != SSL_LIBRARY_VERSION_DTLS_1_0_WIRE &&
         temp != SSL_LIBRARY_VERSION_DTLS_1_2_WIRE) {
         goto alert_loser;
     }
 
     /* The cookie */
     rv = ssl3_ConsumeHandshakeVariable(ss, &cookie, 1, &b, &length);
     if (rv != SECSuccess) {
-        goto loser;     /* alert has been sent */
+        goto loser; /* alert has been sent */
     }
     if (cookie.len > DTLS_COOKIE_BYTES) {
         desc = decode_error;
-        goto alert_loser;       /* malformed. */
+        goto alert_loser; /* malformed. */
     }
 
     PORT_Memcpy(ss->ssl3.hs.cookie, cookie.data, cookie.len);
     ss->ssl3.hs.cookieLen = cookie.len;
 
-
-    ssl_GetXmitBufLock(ss);             /*******************************/
+    ssl_GetXmitBufLock(ss); /*******************************/
 
     /* Now re-send the client hello */
     rv = ssl3_SendClientHello(ss, PR_TRUE);
 
-    ssl_ReleaseXmitBufLock(ss);         /*******************************/
+    ssl_ReleaseXmitBufLock(ss); /*******************************/
 
     if (rv == SECSuccess)
         return rv;
 
 alert_loser:
     (void)SSL3_SendAlert(ss, alert_fatal, desc);
 
 loser:
@@ -1122,17 +1135,17 @@ dtls_RecordSetRecvd(DTLSRecvdRecords *re
     offset = seq % DTLS_RECVD_RECORDS_WINDOW;
 
     records->data[offset / 8] |= (1 << (offset % 8));
 }
 
 SECStatus
 DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout)
 {
-    sslSocket * ss = NULL;
+    sslSocket *ss = NULL;
     PRIntervalTime elapsed;
     PRIntervalTime desired;
 
     ss = ssl_FindSocket(socket);
 
     if (!ss)
         return SECFailure;
 
@@ -1142,17 +1155,18 @@ DTLS_GetHandshakeTimeout(PRFileDesc *soc
     if (!ss->ssl3.hs.rtTimerCb)
         return SECFailure;
 
     elapsed = PR_IntervalNow() - ss->ssl3.hs.rtTimerStarted;
     desired = PR_MillisecondsToInterval(ss->ssl3.hs.rtTimeoutMs);
     if (elapsed > desired) {
         /* Timer expired */
         *timeout = PR_INTERVAL_NO_WAIT;
-    } else {
+    }
+    else {
         *timeout = desired - elapsed;
     }
 
     return SECSuccess;
 }
 
 /*
  * DTLS relevance checks:
@@ -1170,24 +1184,26 @@ PRBool
 dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *crSpec,
                 const SSL3Ciphertext *cText, PRUint64 *seqNum)
 {
     DTLSEpoch epoch = cText->seq_num.high >> 16;
     PRUint64 dtls_seq_num;
 
     if (crSpec->epoch != epoch) {
         SSL_DBG(("%d: SSL3[%d]: dtls_IsRelevant, received packet "
-                 "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
+                 "from irrelevant epoch %d",
+                 SSL_GETPID(), ss->fd, epoch));
         return PR_FALSE;
     }
 
     dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
                    ((PRUint64)cText->seq_num.low);
 
     if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
         SSL_DBG(("%d: SSL3[%d]: dtls_IsRelevant, rejecting "
-                 "potentially replayed packet", SSL_GETPID(), ss->fd));
+                 "potentially replayed packet",
+                 SSL_GETPID(), ss->fd));
         return PR_FALSE;
     }
 
     *seqNum = dtls_seq_num;
     return PR_TRUE;
 }
--- a/security/nss/lib/ssl/notes.txt
+++ b/security/nss/lib/ssl/notes.txt
@@ -5,130 +5,130 @@
 SSL's Buffers: enumerated and explained.
 
 ---------------------------------------------------------------------------
 incoming:
 
 gs = ss->gather
 hs = ss->ssl3->hs
 
-gs->inbuf	SSL3 only: incoming (encrypted) ssl records are placed here,
-		and then decrypted (or copied) to gs->buf.
+gs->inbuf   SSL3 only: incoming (encrypted) ssl records are placed here,
+        and then decrypted (or copied) to gs->buf.
 
-gs->buf		SSL2: incoming SSL records are put here, and then decrypted
-		in place.
-		SSL3: ssl3_HandleHandshake puts decrypted ssl records here.
+gs->buf     SSL2: incoming SSL records are put here, and then decrypted
+        in place.
+        SSL3: ssl3_HandleHandshake puts decrypted ssl records here.
 
-hs.msg_body	(SSL3 only) When an incoming handshake message spans more 
-		than one ssl record, the first part(s) of it are accumulated 
-		here until it all arrives.
+hs.msg_body (SSL3 only) When an incoming handshake message spans more
+        than one ssl record, the first part(s) of it are accumulated
+        here until it all arrives.
 
-hs.msgState	(SSL3 only) an alternative set of pointers/lengths for gs->buf.
-		Used only when a handleHandshake function returns SECWouldBlock.
-		ssl3_HandleHandshake remembers how far it previously got by
-		using these pointers instead of gs->buf when it is called 
-		after a previous SECWouldBlock return.
+hs.msgState (SSL3 only) an alternative set of pointers/lengths for gs->buf.
+        Used only when a handleHandshake function returns SECWouldBlock.
+        ssl3_HandleHandshake remembers how far it previously got by
+        using these pointers instead of gs->buf when it is called
+        after a previous SECWouldBlock return.
 
 ---------------------------------------------------------------------------
 outgoing:
 
 sec = ss->sec
-ci  = ss->sec->ci	/* connect info */
+ci  = ss->sec->ci   /* connect info */
 
-ci->sendBuf	Outgoing handshake messages are appended to this buffer.
-		This buffer will then be sent as a single SSL record.
+ci->sendBuf Outgoing handshake messages are appended to this buffer.
+        This buffer will then be sent as a single SSL record.
 
-sec->writeBuf	outgoing ssl records are constructed here and encrypted in 
-		place before being written or copied to pendingBuf.
+sec->writeBuf   outgoing ssl records are constructed here and encrypted in
+        place before being written or copied to pendingBuf.
 
-ss->pendingBuf	contains outgoing ciphertext that was saved after a write
-		attempt to the socket failed, e.g. EWouldBlock. 
-		Generally empty with blocking sockets (should be no incomplete
-		writes).
+ss->pendingBuf  contains outgoing ciphertext that was saved after a write
+        attempt to the socket failed, e.g. EWouldBlock.
+        Generally empty with blocking sockets (should be no incomplete
+        writes).
 
-ss->saveBuf	Used only by socks code.  Intended to be used to buffer 
-		outgoing data until a socks handshake completes.  However,
-		this buffer is always empty.  There is no code to put 
-		anything into it.
+ss->saveBuf Used only by socks code.  Intended to be used to buffer
+        outgoing data until a socks handshake completes.  However,
+        this buffer is always empty.  There is no code to put
+        anything into it.
 
 ---------------------------------------------------------------------------
 
-SECWouldBlock means that the function cannot make progress because it is 
-waiting for some event OTHER THAN socket I/O completion (e.g. waiting for 
+SECWouldBlock means that the function cannot make progress because it is
+waiting for some event OTHER THAN socket I/O completion (e.g. waiting for
 user dialog to finish).  It is not the same as EWOULDBLOCK.
 
 ---------------------------------------------------------------------------
 
 Rank (order) of locks
 
 recvLock ->\ firstHandshake -> recvbuf -> ssl3Handshake -> xmitbuf -> "spec"
 sendLock ->/
 
 crypto and hash Data that must be protected while turning plaintext into
 ciphertext:
 
-SSL2: 	(in ssl2_Send*)
-	sec->hash*
-	sec->hashcx 	(ptr and data)
-	sec->enc
-	sec->writecx*	(ptr and content)
-	sec->sendSecret*(ptr and content)
-	sec->sendSequence		locked by xmitBufLock
-	sec->blockSize
-	sec->writeBuf*  (ptr & content)	locked by xmitBufLock
-	"in"				locked by xmitBufLock
+SSL2:   (in ssl2_Send*)
+    sec->hash*
+    sec->hashcx     (ptr and data)
+    sec->enc
+    sec->writecx*   (ptr and content)
+    sec->sendSecret*(ptr and content)
+    sec->sendSequence       locked by xmitBufLock
+    sec->blockSize
+    sec->writeBuf*  (ptr & content) locked by xmitBufLock
+    "in"                locked by xmitBufLock
 
-SSl3:	(in ssl3_SendPlainText)
-	ss->ssl3		    (the pointer)
-	ss->ssl3->current_write*    (the pointer and the data in the spec
-				     and any data referenced by the spec.
+SSl3:   (in ssl3_SendPlainText)
+    ss->ssl3            (the pointer)
+    ss->ssl3->current_write*    (the pointer and the data in the spec
+                     and any data referenced by the spec.
 
-	ss->sec->isServer
-	ss->sec->writebuf* (ptr & content) locked by xmitBufLock
-	"buf" 				   locked by xmitBufLock
+    ss->sec->isServer
+    ss->sec->writebuf* (ptr & content) locked by xmitBufLock
+    "buf"                  locked by xmitBufLock
 
-crypto and hash data that must be protected while turning ciphertext into 
+crypto and hash data that must be protected while turning ciphertext into
 plaintext:
 
-SSL2:	(in ssl2_GatherData)
-	gs->*				(locked by recvBufLock )
-	sec->dec
-	sec->readcx
-	sec->hash* 		(ptr and data)
-	sec->hashcx 		(ptr and data)
+SSL2:   (in ssl2_GatherData)
+    gs->*               (locked by recvBufLock )
+    sec->dec
+    sec->readcx
+    sec->hash*      (ptr and data)
+    sec->hashcx         (ptr and data)
 
-SSL3:	(in ssl3_HandleRecord )
-	ssl3->current_read*	(the pointer and all data refernced)
-	ss->sec->isServer
+SSL3:   (in ssl3_HandleRecord )
+    ssl3->current_read* (the pointer and all data refernced)
+    ss->sec->isServer
 
 
 Data that must be protected while being used by a "writer":
 
 ss->pendingBuf.*
-ss->saveBuf.*		(which is dead)
+ss->saveBuf.*       (which is dead)
 
 in ssl3_sendPlainText
 
 ss->ssl3->current_write-> (spec)
 ss->sec->writeBuf.*
-ss->sec->isServer 
+ss->sec->isServer
 
 in SendBlock
 
 ss->sec->hash->length
 ss->sec->blockSize
 ss->sec->writeBuf.*
 ss->sec->sendSecret
 ss->sec->sendSequence
-ss->sec->writecx	*
+ss->sec->writecx    *
 ss->pendingBuf
 
 --------------------------------------------------------------------------
 
-Data variables (not const) protected by the "sslGlobalDataLock".  
+Data variables (not const) protected by the "sslGlobalDataLock".
 Note, this really should be a reader/writer lock.
 
-allowedByPolicy		sslcon.c
-maybeAllowedByPolicy	sslcon.c
-chosenPreference	sslcon.c
-policyWasSet		sslcon.c
+allowedByPolicy     sslcon.c
+maybeAllowedByPolicy    sslcon.c
+chosenPreference    sslcon.c
+policyWasSet        sslcon.c
 
-cipherSuites[] 		ssl3con.c
+cipherSuites[]      ssl3con.c
--- a/security/nss/lib/ssl/os2_err.c
+++ b/security/nss/lib/ssl/os2_err.c
@@ -1,280 +1,330 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /*
  * This file essentially replicates NSPR's source for the functions that
- * map system-specific error codes to NSPR error codes.  We would use 
+ * map system-specific error codes to NSPR error codes.  We would use
  * NSPR's functions, instead of duplicating them, but they're private.
  * As long as SSL's server session cache code must do platform native I/O
  * to accomplish its job, and NSPR's error mapping functions remain private,
  * this code will continue to need to be replicated.
- * 
+ *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "prerror.h"
 #include "prlog.h"
 #include <errno.h>
 
-
 /*
  * Based on win32err.c
  * OS2TODO Stub everything for now to build. HCT
  */
 
 /* forward declaration. */
 void nss_MD_os2_map_default_error(PRInt32 err);
 
-void nss_MD_os2_map_opendir_error(PRInt32 err)
+void
+nss_MD_os2_map_opendir_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_closedir_error(PRInt32 err)
+void
+nss_MD_os2_map_closedir_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_readdir_error(PRInt32 err)
+void
+nss_MD_os2_map_readdir_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_delete_error(PRInt32 err)
+void
+nss_MD_os2_map_delete_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
 /* The error code for stat() is in errno. */
-void nss_MD_os2_map_stat_error(PRInt32 err)
+void
+nss_MD_os2_map_stat_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_fstat_error(PRInt32 err)
+void
+nss_MD_os2_map_fstat_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_rename_error(PRInt32 err)
+void
+nss_MD_os2_map_rename_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
 /* The error code for access() is in errno. */
-void nss_MD_os2_map_access_error(PRInt32 err)
+void
+nss_MD_os2_map_access_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_mkdir_error(PRInt32 err)
+void
+nss_MD_os2_map_mkdir_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_rmdir_error(PRInt32 err)
+void
+nss_MD_os2_map_rmdir_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_read_error(PRInt32 err)
+void
+nss_MD_os2_map_read_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_transmitfile_error(PRInt32 err)
+void
+nss_MD_os2_map_transmitfile_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_write_error(PRInt32 err)
+void
+nss_MD_os2_map_write_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_lseek_error(PRInt32 err)
+void
+nss_MD_os2_map_lseek_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_fsync_error(PRInt32 err)
+void
+nss_MD_os2_map_fsync_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
 /*
  * For both CloseHandle() and closesocket().
  */
-void nss_MD_os2_map_close_error(PRInt32 err)
+void
+nss_MD_os2_map_close_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_socket_error(PRInt32 err)
+void
+nss_MD_os2_map_socket_error(PRInt32 err)
 {
-//  PR_ASSERT(err != WSANOTINITIALISED);
+    //  PR_ASSERT(err != WSANOTINITIALISED);
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_recv_error(PRInt32 err)
+void
+nss_MD_os2_map_recv_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_recvfrom_error(PRInt32 err)
+void
+nss_MD_os2_map_recvfrom_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_send_error(PRInt32 err)
+void
+nss_MD_os2_map_send_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//     case WSAEMSGSIZE: 	prError = PR_INVALID_ARGUMENT_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+      //     case WSAEMSGSIZE:  prError = PR_INVALID_ARGUMENT_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_sendto_error(PRInt32 err)
+void
+nss_MD_os2_map_sendto_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//    case WSAEMSGSIZE: 	prError = PR_INVALID_ARGUMENT_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+        //    case WSAEMSGSIZE:     prError = PR_INVALID_ARGUMENT_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_accept_error(PRInt32 err)
+void
+nss_MD_os2_map_accept_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//    case WSAEOPNOTSUPP: prError = PR_NOT_TCP_SOCKET_ERROR; break;
-//    case WSAEINVAL: 	prError = PR_INVALID_STATE_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+        //    case WSAEOPNOTSUPP: prError = PR_NOT_TCP_SOCKET_ERROR; break;
+        //    case WSAEINVAL:   prError = PR_INVALID_STATE_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_acceptex_error(PRInt32 err)
+void
+nss_MD_os2_map_acceptex_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_connect_error(PRInt32 err)
+void
+nss_MD_os2_map_connect_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//    case WSAEWOULDBLOCK: prError = PR_IN_PROGRESS_ERROR; break;
-//    case WSAEINVAL: 	prError = PR_ALREADY_INITIATED_ERROR; break;
-//    case WSAETIMEDOUT: 	prError = PR_IO_TIMEOUT_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+        //    case WSAEWOULDBLOCK: prError = PR_IN_PROGRESS_ERROR; break;
+        //    case WSAEINVAL:   prError = PR_ALREADY_INITIATED_ERROR; break;
+        //    case WSAETIMEDOUT:    prError = PR_IO_TIMEOUT_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_bind_error(PRInt32 err)
+void
+nss_MD_os2_map_bind_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//  case WSAEINVAL: 	prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+        //  case WSAEINVAL:     prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_listen_error(PRInt32 err)
+void
+nss_MD_os2_map_listen_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//    case WSAEOPNOTSUPP: prError = PR_NOT_TCP_SOCKET_ERROR; break;
-//    case WSAEINVAL: 	prError = PR_INVALID_STATE_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+        //    case WSAEOPNOTSUPP: prError = PR_NOT_TCP_SOCKET_ERROR; break;
+        //    case WSAEINVAL:   prError = PR_INVALID_STATE_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_shutdown_error(PRInt32 err)
+void
+nss_MD_os2_map_shutdown_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_getsockname_error(PRInt32 err)
+void
+nss_MD_os2_map_getsockname_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//    case WSAEINVAL: 	prError = PR_INVALID_STATE_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+        //    case WSAEINVAL:   prError = PR_INVALID_STATE_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_getpeername_error(PRInt32 err)
+void
+nss_MD_os2_map_getpeername_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_getsockopt_error(PRInt32 err)
+void
+nss_MD_os2_map_getsockopt_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_setsockopt_error(PRInt32 err)
+void
+nss_MD_os2_map_setsockopt_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_open_error(PRInt32 err)
+void
+nss_MD_os2_map_open_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-void nss_MD_os2_map_gethostname_error(PRInt32 err)
+void
+nss_MD_os2_map_gethostname_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
 /* Win32 select() only works on sockets.  So in this
-** context, WSAENOTSOCK is equivalent to EBADF on Unix.  
+** context, WSAENOTSOCK is equivalent to EBADF on Unix.
 */
-void nss_MD_os2_map_select_error(PRInt32 err)
+void
+nss_MD_os2_map_select_error(PRInt32 err)
 {
     PRErrorCode prError;
     switch (err) {
-//    case WSAENOTSOCK:	prError = PR_BAD_DESCRIPTOR_ERROR; break;
-    default:		nss_MD_os2_map_default_error(err); return;
+        //    case WSAENOTSOCK: prError = PR_BAD_DESCRIPTOR_ERROR; break;
+        default:
+            nss_MD_os2_map_default_error(err);
+            return;
     }
     PR_SetError(prError, err);
 }
 
-void nss_MD_os2_map_lockf_error(PRInt32 err)
+void
+nss_MD_os2_map_lockf_error(PRInt32 err)
 {
     nss_MD_os2_map_default_error(err);
 }
 
-
-
-void nss_MD_os2_map_default_error(PRInt32 err)
+void
+nss_MD_os2_map_default_error(PRInt32 err)
 {
     PRErrorCode prError;
 
     switch (err) {
-//    case ENOENT: 		prError = PR_FILE_NOT_FOUND_ERROR; break;
-//    case ERROR_ACCESS_DENIED: 	prError = PR_NO_ACCESS_RIGHTS_ERROR; break;
-//    case ERROR_ALREADY_EXISTS: 	prError = PR_FILE_EXISTS_ERROR; break;
-//    case ERROR_DISK_CORRUPT: 	prError = PR_IO_ERROR; break;
-//    case ERROR_DISK_FULL: 	prError = PR_NO_DEVICE_SPACE_ERROR; break;
+//    case ENOENT:      prError = PR_FILE_NOT_FOUND_ERROR; break;
+//    case ERROR_ACCESS_DENIED:     prError = PR_NO_ACCESS_RIGHTS_ERROR; break;
+//    case ERROR_ALREADY_EXISTS:    prError = PR_FILE_EXISTS_ERROR; break;
+//    case ERROR_DISK_CORRUPT:  prError = PR_IO_ERROR; break;
+//    case ERROR_DISK_FULL:     prError = PR_NO_DEVICE_SPACE_ERROR; break;
 //    case ERROR_DISK_OPERATION_FAILED: prError = PR_IO_ERROR; break;
-//    case ERROR_DRIVE_LOCKED: 	prError = PR_FILE_IS_LOCKED_ERROR; break;
+//    case ERROR_DRIVE_LOCKED:  prError = PR_FILE_IS_LOCKED_ERROR; break;
 //    case ERROR_FILENAME_EXCED_RANGE: prError = PR_NAME_TOO_LONG_ERROR; break;
-//    case ERROR_FILE_CORRUPT: 	prError = PR_IO_ERROR; break;
-//    case ERROR_FILE_EXISTS: 	prError = PR_FILE_EXISTS_ERROR; break;
-//    case ERROR_FILE_INVALID: 	prError = PR_BAD_DESCRIPTOR_ERROR; break;
+//    case ERROR_FILE_CORRUPT:  prError = PR_IO_ERROR; break;
+//    case ERROR_FILE_EXISTS:   prError = PR_FILE_EXISTS_ERROR; break;
+//    case ERROR_FILE_INVALID:  prError = PR_BAD_DESCRIPTOR_ERROR; break;
 #if ERROR_FILE_NOT_FOUND != ENOENT
-//    case ERROR_FILE_NOT_FOUND: 	prError = PR_FILE_NOT_FOUND_ERROR; break;
+//    case ERROR_FILE_NOT_FOUND:    prError = PR_FILE_NOT_FOUND_ERROR; break;
 #endif
-    default: 			prError = PR_UNKNOWN_ERROR; break;
+        default:
+            prError = PR_UNKNOWN_ERROR;
+            break;
     }
     PR_SetError(prError, err);
 }
-
--- a/security/nss/lib/ssl/os2_err.h
+++ b/security/nss/lib/ssl/os2_err.h
@@ -1,16 +1,16 @@
 /*
  * This file essentially replicates NSPR's source for the functions that
- * map system-specific error codes to NSPR error codes.  We would use 
+ * map system-specific error codes to NSPR error codes.  We would use
  * NSPR's functions, instead of duplicating them, but they're private.
  * As long as SSL's server session cache code must do platform native I/O
  * to accomplish its job, and NSPR's error mapping functions remain private,
  * This code will continue to need to be replicated.
- * 
+ *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*  NSPR doesn't make these functions public, so we have to duplicate
 **  them in NSS.
 */
 
--- a/security/nss/lib/ssl/preenc.h
+++ b/security/nss/lib/ssl/preenc.h
@@ -20,94 +20,94 @@ typedef struct PEHeaderStr PEHeader;
 #define PE_MIME_TYPE "application/pre-encrypted"
 
 typedef struct PEFortezzaHeaderStr PEFortezzaHeader;
 typedef struct PEFortezzaGeneratedHeaderStr PEFortezzaGeneratedHeader;
 typedef struct PEFixedKeyHeaderStr PEFixedKeyHeader;
 typedef struct PERSAKeyHeaderStr PERSAKeyHeader;
 
 struct PEFortezzaHeaderStr {
-    unsigned char key[12];      
-    unsigned char iv[24];       
-    unsigned char hash[20];     
-    unsigned char serial[8];    
+    unsigned char key[12];
+    unsigned char iv[24];
+    unsigned char hash[20];
+    unsigned char serial[8];
 };
 
 struct PEFortezzaGeneratedHeaderStr {
-    unsigned char key[12];      
-    unsigned char iv[24];       
-    unsigned char hash[20];     
-    unsigned char Ra[128];      
-    unsigned char Y[128];       
+    unsigned char key[12];
+    unsigned char iv[24];
+    unsigned char hash[20];
+    unsigned char Ra[128];
+    unsigned char Y[128];
 };
 
 struct PEFixedKeyHeaderStr {
-    unsigned char pkcs11Mech[4];  
-    unsigned char labelLen[2];	  
-    unsigned char keyIDLen[2];	  
-    unsigned char ivLen[2];	  
-    unsigned char keyLen[2];	  
-    unsigned char data[1];	  
+    unsigned char pkcs11Mech[4];
+    unsigned char labelLen[2];
+    unsigned char keyIDLen[2];
+    unsigned char ivLen[2];
+    unsigned char keyLen[2];
+    unsigned char data[1];
 };
 
 struct PERSAKeyHeaderStr {
-    unsigned char pkcs11Mech[4];  
-    unsigned char issuerLen[2];	  
-    unsigned char serialLen[2];	  
-    unsigned char ivLen[2];	  
-    unsigned char keyLen[2];	  
-    unsigned char data[1];	  
+    unsigned char pkcs11Mech[4];
+    unsigned char issuerLen[2];
+    unsigned char serialLen[2];
+    unsigned char ivLen[2];
+    unsigned char keyLen[2];
+    unsigned char data[1];
 };
 
 #define PEFIXED_Label(header) (header->data)
 #define PEFIXED_KeyID(header) (&header->data[GetInt2(header->labelLen)])
-#define PEFIXED_IV(header) (&header->data[GetInt2(header->labelLen)\
-						+GetInt2(header->keyIDLen)])
-#define PEFIXED_Key(header) (&header->data[GetInt2(header->labelLen)\
-			+GetInt2(header->keyIDLen)+GetInt2(header->keyLen)])
+#define PEFIXED_IV(header) (&header->data[GetInt2(header->labelLen) + \
+                                          GetInt2(header->keyIDLen)])
+#define PEFIXED_Key(header) (&header->data[GetInt2(header->labelLen) + \
+                                           GetInt2(header->keyIDLen) + \
+                                           GetInt2(header->keyLen)])
 #define PERSA_Issuer(header) (header->data)
 #define PERSA_Serial(header) (&header->data[GetInt2(header->issuerLen)])
-#define PERSA_IV(header) (&header->data[GetInt2(header->issuerLen)\
-						+GetInt2(header->serialLen)])
-#define PERSA_Key(header) (&header->data[GetInt2(header->issuerLen)\
-			+GetInt2(header->serialLen)+GetInt2(header->keyLen)])
+#define PERSA_IV(header) (&header->data[GetInt2(header->issuerLen) + \
+                                        GetInt2(header->serialLen)])
+#define PERSA_Key(header) (&header->data[GetInt2(header->issuerLen) + \
+                                         GetInt2(header->serialLen) + \
+                                         GetInt2(header->keyLen)])
 struct PEHeaderStr {
-    unsigned char magic  [2];		
-    unsigned char len    [2];		
-    unsigned char type   [2];		
-    unsigned char version[2];		
+    unsigned char magic[2];
+    unsigned char len[2];
+    unsigned char type[2];
+    unsigned char version[2];
     union {
-        PEFortezzaHeader          fortezza;
+        PEFortezzaHeader fortezza;
         PEFortezzaGeneratedHeader g_fortezza;
-	PEFixedKeyHeader          fixed;
-	PERSAKeyHeader            rsa;
+        PEFixedKeyHeader fixed;
+        PERSAKeyHeader rsa;
     } u;
 };
 
 #define PE_CRYPT_INTRO_LEN 8
 #define PE_INTRO_LEN 4
-#define PE_BASE_HEADER_LEN  8
+#define PE_BASE_HEADER_LEN 8
 
-#define PRE_BLOCK_SIZE 8         
-
+#define PRE_BLOCK_SIZE 8
 
 #define GetInt2(c) ((c[0] << 8) | c[1])
-#define GetInt4(c) (((unsigned long)c[0] << 24)|((unsigned long)c[1] << 16)\
-			|((unsigned long)c[2] << 8)| ((unsigned long)c[3]))
-#define PutInt2(c,i) ((c[1] = (i) & 0xff), (c[0] = ((i) >> 8) & 0xff))
-#define PutInt4(c,i) ((c[0]=((i) >> 24) & 0xff),(c[1]=((i) >> 16) & 0xff),\
-			(c[2] = ((i) >> 8) & 0xff), (c[3] = (i) & 0xff))
+#define GetInt4(c) (((unsigned long)c[0] << 24) | ((unsigned long)c[1] << 16) | \
+                    ((unsigned long)c[2] << 8) | ((unsigned long)c[3]))
+#define PutInt2(c, i) ((c[1] = (i)&0xff), (c[0] = ((i) >> 8) & 0xff))
+#define PutInt4(c, i) ((c[0] = ((i) >> 24) & 0xff), (c[1] = ((i) >> 16) & 0xff), \
+                       (c[2] = ((i) >> 8) & 0xff), (c[3] = (i)&0xff))
 
-#define PRE_MAGIC		0xc0de
-#define PRE_VERSION		0x1010
-#define PRE_FORTEZZA_FILE	0x00ff  
-#define PRE_FORTEZZA_STREAM	0x00f5  
-#define PRE_FORTEZZA_GEN_STREAM	0x00f6  
-#define PRE_FIXED_FILE		0x000f  
-#define PRE_RSA_FILE		0x001f  
-#define PRE_FIXED_STREAM	0x0005  
+#define PRE_MAGIC 0xc0de
+#define PRE_VERSION 0x1010
+#define PRE_FORTEZZA_FILE 0x00ff
+#define PRE_FORTEZZA_STREAM 0x00f5
+#define PRE_FORTEZZA_GEN_STREAM 0x00f6
+#define PRE_FIXED_FILE 0x000f
+#define PRE_RSA_FILE 0x001f
+#define PRE_FIXED_STREAM 0x0005
 
 PEHeader *SSL_PreencryptedStreamToFile(PRFileDesc *fd, PEHeader *,
-				       int *headerSize);
+                                       int *headerSize);
 
 PEHeader *SSL_PreencryptedFileToStream(PRFileDesc *fd, PEHeader *,
-				       int *headerSize);
-
+                                       int *headerSize);
--- a/security/nss/lib/ssl/prelib.c
+++ b/security/nss/lib/ssl/prelib.c
@@ -12,23 +12,23 @@
 #include "ssl.h"
 #include "keyhi.h"
 #include "secitem.h"
 #include "sslimpl.h"
 #include "pkcs11t.h"
 #include "preenc.h"
 #include "pk11func.h"
 
-PEHeader *SSL_PreencryptedStreamToFile(PRFileDesc *fd, PEHeader *inHeader, 
-				       int *headerSize)
+PEHeader *
+SSL_PreencryptedStreamToFile(PRFileDesc *fd, PEHeader *inHeader,
+                             int *headerSize)
 {
     PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
     return NULL;
 }
 
-PEHeader *SSL_PreencryptedFileToStream(PRFileDesc *fd, PEHeader *header, 
-							int *headerSize)
+PEHeader *
+SSL_PreencryptedFileToStream(PRFileDesc *fd, PEHeader *header,
+                             int *headerSize)
 {
     PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
     return NULL;
 }
-
-
--- a/security/nss/lib/ssl/ssl.def
+++ b/security/nss/lib/ssl/ssl.def
@@ -189,8 +189,14 @@ SSL_SignatureMaxCount;
 ;+};
 ;+NSS_3.22 {    # NSS 3.22 release
 ;+    global:
 SSL_PeerSignedCertTimestamps;
 SSL_SetSignedCertTimestamps;
 ;+    local:
 ;+*;
 ;+};
+;+NSS_3.23 {    # NSS 3.23 release
+;+    global:
+SSL_SetDowngradeCheckVersion;
+;+    local:
+;+*;
+;+};
--- a/security/nss/lib/ssl/ssl.h
+++ b/security/nss/lib/ssl/ssl.h
@@ -10,17 +10,17 @@
 
 #include "prtypes.h"
 #include "prerror.h"
 #include "prio.h"
 #include "seccomon.h"
 #include "cert.h"
 #include "keyt.h"
 
-#include "sslt.h"  /* public ssl data types */
+#include "sslt.h" /* public ssl data types */
 
 #if defined(_WIN32) && !defined(IN_LIBSSL) && !defined(NSS_USE_STATIC_LIBS)
 #define SSL_IMPORT extern __declspec(dllimport)
 #else
 #define SSL_IMPORT extern
 #endif
 
 SEC_BEGIN_PROTOS
@@ -33,99 +33,99 @@ SSL_IMPORT const PRUint16 *SSL_GetImplem
 
 /* number of entries in the above table. */
 SSL_IMPORT const PRUint16 SSL_NumImplementedCiphers;
 
 /* the same as the above, but is a function */
 SSL_IMPORT PRUint16 SSL_GetNumImplementedCiphers(void);
 
 /* Macro to tell which ciphers in table are SSL2 vs SSL3/TLS. */
-#define SSL_IS_SSL2_CIPHER(which) (((which) & 0xfff0) == 0xff00)
+#define SSL_IS_SSL2_CIPHER(which) (((which)&0xfff0) == 0xff00)
 
 /*
 ** Imports fd into SSL, returning a new socket.  Copies SSL configuration
 ** from model.
 */
 SSL_IMPORT PRFileDesc *SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd);
 
 /*
 ** Imports fd into DTLS, returning a new socket.  Copies DTLS configuration
 ** from model.
 */
 SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd);
 
 /*
 ** Enable/disable an ssl mode
 **
-** 	SSL_SECURITY:
-** 		enable/disable use of SSL security protocol before connect
+**  SSL_SECURITY:
+**    enable/disable use of SSL security protocol before connect
 **
-** 	SSL_SOCKS:
-** 		enable/disable use of socks before connect
-**		(No longer supported).
+**  SSL_SOCKS:
+**    enable/disable use of socks before connect
+**    (No longer supported).
 **
-** 	SSL_REQUEST_CERTIFICATE:
-** 		require a certificate during secure connect
+**  SSL_REQUEST_CERTIFICATE:
+**    require a certificate during secure connect
 */
 /* options */
-#define SSL_SECURITY			1 /* (on by default) */
-#define SSL_SOCKS			2 /* (off by default) */
-#define SSL_REQUEST_CERTIFICATE		3 /* (off by default) */
-#define SSL_HANDSHAKE_AS_CLIENT		5 /* force accept to hs as client */
-                               		  /* (off by default) */
-#define SSL_HANDSHAKE_AS_SERVER		6 /* force connect to hs as server */
-                               		  /* (off by default) */
+#define SSL_SECURITY 1            /* (on by default) */
+#define SSL_SOCKS 2               /* (off by default) */
+#define SSL_REQUEST_CERTIFICATE 3 /* (off by default) */
+#define SSL_HANDSHAKE_AS_CLIENT 5 /* force accept to hs as client */
+                                  /* (off by default) */
+#define SSL_HANDSHAKE_AS_SERVER 6 /* force connect to hs as server */
+                                  /* (off by default) */
 
 /* OBSOLETE: SSL v2 is obsolete and may be removed soon. */
-#define SSL_ENABLE_SSL2			7 /* enable ssl v2 (off by default) */
+#define SSL_ENABLE_SSL2 7 /* enable ssl v2 (off by default) */
 
 /* OBSOLETE: See "SSL Version Range API" below for the replacement and a
 ** description of the non-obvious semantics of using SSL_ENABLE_SSL3.
 */
-#define SSL_ENABLE_SSL3		        8 /* enable ssl v3 (on by default) */
+#define SSL_ENABLE_SSL3 8 /* enable ssl v3 (on by default) */
 
-#define SSL_NO_CACHE		        9 /* don't use the session cache */
-                    		          /* (off by default) */
-#define SSL_REQUIRE_CERTIFICATE        10 /* (SSL_REQUIRE_FIRST_HANDSHAKE */
-                                          /* by default) */
-#define SSL_ENABLE_FDX                 11 /* permit simultaneous read/write */
-                                          /* (off by default) */
+#define SSL_NO_CACHE 9             /* don't use the session cache */
+                                   /* (off by default) */
+#define SSL_REQUIRE_CERTIFICATE 10 /* (SSL_REQUIRE_FIRST_HANDSHAKE */
+                                   /* by default) */
+#define SSL_ENABLE_FDX 11          /* permit simultaneous read/write */
+                                   /* (off by default) */
 
 /* OBSOLETE: SSL v2 compatible hellos are not accepted by some TLS servers
 ** and cannot negotiate extensions. SSL v2 is obsolete. This option may be
 ** removed soon.
 */
-#define SSL_V2_COMPATIBLE_HELLO        12 /* send v3 client hello in v2 fmt */
-                                          /* (off by default) */
+#define SSL_V2_COMPATIBLE_HELLO 12 /* send v3 client hello in v2 fmt */
+                                   /* (off by default) */
 
 /* OBSOLETE: See "SSL Version Range API" below for the replacement and a
 ** description of the non-obvious semantics of using SSL_ENABLE_TLS.
 */
-#define SSL_ENABLE_TLS		       13 /* enable TLS (on by default) */
+#define SSL_ENABLE_TLS 13 /* enable TLS (on by default) */
 
-#define SSL_ROLLBACK_DETECTION         14 /* for compatibility, default: on */
-#define SSL_NO_STEP_DOWN               15 /* Disable export cipher suites   */
-                                          /* if step-down keys are needed.  */
-					  /* default: off, generate         */
-					  /* step-down keys if needed.      */
-#define SSL_BYPASS_PKCS11              16 /* use PKCS#11 for pub key only   */
-#define SSL_NO_LOCKS                   17 /* Don't use locks for protection */
-#define SSL_ENABLE_SESSION_TICKETS     18 /* Enable TLS SessionTicket       */
-                                          /* extension (off by default)     */
-#define SSL_ENABLE_DEFLATE             19 /* Enable TLS compression with    */
-                                          /* DEFLATE (off by default)       */
-#define SSL_ENABLE_RENEGOTIATION       20 /* Values below (default: never)  */
-#define SSL_REQUIRE_SAFE_NEGOTIATION   21 /* Peer must send Signaling       */
-					  /* Cipher Suite Value (SCSV) or   */
-                                          /* Renegotiation  Info (RI)       */
-					  /* extension in ALL handshakes.   */
-                                          /* default: off                   */
-#define SSL_ENABLE_FALSE_START         22 /* Enable SSL false start (off by */
-                                          /* default, applies only to       */
-                                          /* clients). False start is a     */
+#define SSL_ROLLBACK_DETECTION 14       /* for compatibility, default: on */
+#define SSL_NO_STEP_DOWN 15             /* Disable export cipher suites   */
+                                        /* if step-down keys are needed.  */
+                                        /* default: off, generate         */
+                                        /* step-down keys if needed.      */
+#define SSL_BYPASS_PKCS11 16            /* use PKCS#11 for pub key only   */
+#define SSL_NO_LOCKS 17                 /* Don't use locks for protection */
+#define SSL_ENABLE_SESSION_TICKETS 18   /* Enable TLS SessionTicket       */
+                                        /* extension (off by default)     */
+#define SSL_ENABLE_DEFLATE 19           /* Enable TLS compression with    */
+                                        /* DEFLATE (off by default)       */
+#define SSL_ENABLE_RENEGOTIATION 20     /* Values below (default: never)  */
+#define SSL_REQUIRE_SAFE_NEGOTIATION 21 /* Peer must send Signaling       */
+                                        /* Cipher Suite Value (SCSV) or   */
+                                        /* Renegotiation  Info (RI)       */
+                                        /* extension in ALL handshakes.   */
+                                        /* default: off                   */
+#define SSL_ENABLE_FALSE_START 22       /* Enable SSL false start (off by */
+                                        /* default, applies only to       */
+                                        /* clients). False start is a     */
 /* mode where an SSL client will start sending application data before
  * verifying the server's Finished message. This means that we could end up
  * sending data to an imposter. However, the data will be encrypted and
  * only the true server can derive the session key. Thus, so long as the
  * cipher isn't broken this is safe. The advantage of false start is that
  * it saves a round trip for client-speaks-first protocols when performing a
  * full handshake.
  *
@@ -155,17 +155,17 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRF
  * application_data record to every application_data record they send; we do
  * not do that because some implementations cannot handle empty
  * application_data records. Also, we only split application_data records and
  * not other types of records, because some implementations will not accept
  * fragmented records of some other types (e.g. some versions of NSS do not
  * accept fragmented alerts).
  */
 #define SSL_CBC_RANDOM_IV 23
-#define SSL_ENABLE_OCSP_STAPLING       24 /* Request OCSP stapling (client) */
+#define SSL_ENABLE_OCSP_STAPLING 24 /* Request OCSP stapling (client) */
 
 /* SSL_ENABLE_NPN controls whether the NPN extension is enabled for the initial
  * handshake when application layer protocol negotiation is used.
  * SSL_SetNextProtoCallback or SSL_SetNextProtoNego must be used to control the
  * application layer protocol negotiation; otherwise, the NPN extension will
  * not be negotiated. SSL_ENABLE_NPN is currently enabled by default but this
  * may change in future versions.
  */
@@ -184,34 +184,34 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRF
 
 /* SSL_REUSE_SERVER_ECDHE_KEY controls whether the ECDHE server key is
  * reused for multiple handshakes or generated each time.
  * SSL_REUSE_SERVER_ECDHE_KEY is currently enabled by default.
  * This socket option is for ECDHE, only. It is unrelated to DHE.
  */
 #define SSL_REUSE_SERVER_ECDHE_KEY 27
 
-#define SSL_ENABLE_FALLBACK_SCSV       28 /* Send fallback SCSV in
-                                           * handshakes. */
+#define SSL_ENABLE_FALLBACK_SCSV 28 /* Send fallback SCSV in \
+                                     * handshakes. */
 
 /* SSL_ENABLE_SERVER_DHE controls whether DHE is enabled for the server socket.
  */
 #define SSL_ENABLE_SERVER_DHE 29
 
 /* Use draft-ietf-tls-session-hash. Controls whether we offer the
  * extended_master_secret extension which, when accepted, hashes
  * the handshake transcript into the master secret. This option is
  * disabled by default.
  */
 #define SSL_ENABLE_EXTENDED_MASTER_SECRET 30
 
 /* Request Signed Certificate Timestamps via TLS extension (client) */
 #define SSL_ENABLE_SIGNED_CERT_TIMESTAMPS 31
 
-#ifdef SSL_DEPRECATED_FUNCTION 
+#ifdef SSL_DEPRECATED_FUNCTION
 /* Old deprecated function names */
 SSL_IMPORT SECStatus SSL_Enable(PRFileDesc *fd, int option, PRBool on);
 SSL_IMPORT SECStatus SSL_EnableDefault(int option, PRBool on);
 #endif
 
 /* New function names */
 SSL_IMPORT SECStatus SSL_OptionSet(PRFileDesc *fd, PRInt32 option, PRBool on);
 SSL_IMPORT SECStatus SSL_OptionGet(PRFileDesc *fd, PRInt32 option, PRBool *on);
@@ -224,23 +224,23 @@ SSL_IMPORT SECStatus SSL_CertDBHandleSet
  * |protos| and |protosLen| define a buffer which contains the server's
  * advertisement. This data is guaranteed to be well formed per the NPN spec.
  * |protoOut| is a buffer provided by the caller, of length 255 (the maximum
  * allowed by the protocol). On successful return, the protocol to be announced
  * to the server will be in |protoOut| and its length in |*protoOutLen|.
  *
  * The callback must return SECFailure or SECSuccess (not SECWouldBlock).
  */
-typedef SECStatus (PR_CALLBACK *SSLNextProtoCallback)(
+typedef SECStatus(PR_CALLBACK *SSLNextProtoCallback)(
     void *arg,
     PRFileDesc *fd,
-    const unsigned char* protos,
+    const unsigned char *protos,
     unsigned int protosLen,
-    unsigned char* protoOut,
-    unsigned int* protoOutLen,
+    unsigned char *protoOut,
+    unsigned int *protoOutLen,
     unsigned int protoMaxOut);
 
 /* SSL_SetNextProtoCallback sets a callback function to handle Next Protocol
  * Negotiation. It causes a client to advertise NPN. */
 SSL_IMPORT SECStatus SSL_SetNextProtoCallback(PRFileDesc *fd,
                                               SSLNextProtoCallback callback,
                                               void *arg);
 
@@ -258,47 +258,47 @@ SSL_IMPORT SECStatus SSL_SetNextProtoCal
  * Since NPN uses the first protocol as the fallback protocol, when sending an
  * ALPN extension, the first protocol is moved to the end of the list. This
  * indicates that the fallback protocol is the least preferred. The other
  * protocols should be in preference order.
  *
  * The supported protocols are specified in |data| in wire-format (8-bit
  * length-prefixed). For example: "\010http/1.1\006spdy/2". */
 SSL_IMPORT SECStatus SSL_SetNextProtoNego(PRFileDesc *fd,
-					  const unsigned char *data,
-					  unsigned int length);
+                                          const unsigned char *data,
+                                          unsigned int length);
 
-typedef enum SSLNextProtoState { 
-  SSL_NEXT_PROTO_NO_SUPPORT = 0, /* No peer support                */
-  SSL_NEXT_PROTO_NEGOTIATED = 1, /* Mutual agreement               */
-  SSL_NEXT_PROTO_NO_OVERLAP = 2, /* No protocol overlap found      */
-  SSL_NEXT_PROTO_SELECTED   = 3  /* Server selected proto (ALPN)   */
+typedef enum SSLNextProtoState {
+    SSL_NEXT_PROTO_NO_SUPPORT = 0, /* No peer support                */
+    SSL_NEXT_PROTO_NEGOTIATED = 1, /* Mutual agreement               */
+    SSL_NEXT_PROTO_NO_OVERLAP = 2, /* No protocol overlap found      */
+    SSL_NEXT_PROTO_SELECTED = 3    /* Server selected proto (ALPN)   */
 } SSLNextProtoState;
 
 /* SSL_GetNextProto can be used in the HandshakeCallback or any time after
  * a handshake to retrieve the result of the Next Protocol negotiation.
  *
  * The length of the negotiated protocol, if any, is written into *bufLen.
  * If the negotiated protocol is longer than bufLenMax, then SECFailure is
  * returned. Otherwise, the negotiated protocol, if any, is written into buf,
  * and SECSuccess is returned. */
 SSL_IMPORT SECStatus SSL_GetNextProto(PRFileDesc *fd,
-				      SSLNextProtoState *state,
-				      unsigned char *buf,
-				      unsigned int *bufLen,
-				      unsigned int bufLenMax);
+                                      SSLNextProtoState *state,
+                                      unsigned char *buf,
+                                      unsigned int *bufLen,
+                                      unsigned int bufLenMax);
 
 /*
 ** Control ciphers that SSL uses. If on is non-zero then the named cipher
-** is enabled, otherwise it is disabled. 
+** is enabled, otherwise it is disabled.
 ** The "cipher" values are defined in sslproto.h (the SSL_EN_* values).
 ** EnableCipher records user preferences.
 ** SetPolicy sets the policy according to the policy module.
 */
-#ifdef SSL_DEPRECATED_FUNCTION 
+#ifdef SSL_DEPRECATED_FUNCTION
 /* Old deprecated function names */
 SSL_IMPORT SECStatus SSL_EnableCipher(long which, PRBool enabled);
 SSL_IMPORT SECStatus SSL_SetPolicy(long which, int policy);
 #endif
 
 /* New function names */
 SSL_IMPORT SECStatus SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 cipher, PRBool enabled);
 SSL_IMPORT SECStatus SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 cipher, PRBool *enabled);
@@ -446,56 +446,56 @@ SSL_IMPORT SECStatus SSL_VersionRangeGet
 /* Sets the range of enabled-by-default SSL3/TLS versions for the given
 ** protocol variant to |*vrange|.
 */
 SSL_IMPORT SECStatus SSL_VersionRangeSetDefault(
     SSLProtocolVariant protocolVariant, const SSLVersionRange *vrange);
 
 /* Returns, in |*vrange|, the range of enabled SSL3/TLS versions for |fd|. */
 SSL_IMPORT SECStatus SSL_VersionRangeGet(PRFileDesc *fd,
-					 SSLVersionRange *vrange);
+                                         SSLVersionRange *vrange);
 
 /* Sets the range of enabled SSL3/TLS versions for |fd| to |*vrange|. */
 SSL_IMPORT SECStatus SSL_VersionRangeSet(PRFileDesc *fd,
-					 const SSLVersionRange *vrange);
+                                         const SSLVersionRange *vrange);
 
 /* Sets the version to check the server random against for the
  * fallback check defined in [draft-ietf-tls-tls13-11 Section 6.3.1.1].
  * This function is provided to allow for detection of forced downgrade
  * attacks against client-side reconnect-and-fallback outside of TLS
  * by setting |version| to be that of the original connection, rather
  * than that of the new connection.
  *
  * The default, which can also be enabled by setting |version| to
  * zero, is just to check against the max version in the
  * version range (see SSL_VersionRangeSet). */
 SSL_IMPORT SECStatus SSL_SetDowngradeCheckVersion(PRFileDesc *fd,
                                                   PRUint16 version);
 
 /* Values for "policy" argument to SSL_CipherPolicySet */
 /* Values returned by SSL_CipherPolicyGet. */
-#define SSL_NOT_ALLOWED		 0	      /* or invalid or unimplemented */
-#define SSL_ALLOWED		 1
-#define SSL_RESTRICTED		 2	      /* only with "Step-Up" certs. */
+#define SSL_NOT_ALLOWED 0 /* or invalid or unimplemented */
+#define SSL_ALLOWED 1
+#define SSL_RESTRICTED 2 /* only with "Step-Up" certs. */
 
 /* Values for "on" with SSL_REQUIRE_CERTIFICATE. */
-#define SSL_REQUIRE_NEVER           ((PRBool)0)
-#define SSL_REQUIRE_ALWAYS          ((PRBool)1)
+#define SSL_REQUIRE_NEVER ((PRBool)0)
+#define SSL_REQUIRE_ALWAYS ((PRBool)1)
 #define SSL_REQUIRE_FIRST_HANDSHAKE ((PRBool)2)
-#define SSL_REQUIRE_NO_ERROR        ((PRBool)3)
+#define SSL_REQUIRE_NO_ERROR ((PRBool)3)
 
 /* Values for "on" with SSL_ENABLE_RENEGOTIATION */
 /* Never renegotiate at all.                                               */
-#define SSL_RENEGOTIATE_NEVER        ((PRBool)0)
+#define SSL_RENEGOTIATE_NEVER ((PRBool)0)
 /* Renegotiate without restriction, whether or not the peer's client hello */
 /* bears the renegotiation info extension.  Vulnerable, as in the past.    */
 #define SSL_RENEGOTIATE_UNRESTRICTED ((PRBool)1)
 /* Only renegotiate if the peer's hello bears the TLS renegotiation_info   */
 /* extension. This is safe renegotiation.                                  */
-#define SSL_RENEGOTIATE_REQUIRES_XTN ((PRBool)2) 
+#define SSL_RENEGOTIATE_REQUIRES_XTN ((PRBool)2)
 /* Disallow unsafe renegotiation in server sockets only, but allow clients */
 /* to continue to renegotiate with vulnerable servers.                     */
 /* This value should only be used during the transition period when few    */
 /* servers have been upgraded.                                             */
 #define SSL_RENEGOTIATE_TRANSITIONAL ((PRBool)3)
 
 /*
 ** Reset the handshake state for fd. This will make the complete SSL
@@ -523,41 +523,41 @@ SSL_IMPORT SECStatus SSL_ForceHandshakeW
 ** certificate at the other end of the connection. For a client, this is
 ** the issuer of the server's certificate; for a server, this is the
 ** issuer of the client's certificate (if any). Subject is the subject of
 ** the other end's certificate. The pointers can be zero if the desired
 ** data is not needed.  All strings returned by this function are owned
 ** by the caller, and need to be freed with PORT_Free.
 */
 SSL_IMPORT SECStatus SSL_SecurityStatus(PRFileDesc *fd, int *on, char **cipher,
-			                int *keySize, int *secretKeySize,
-			                char **issuer, char **subject);
+                                        int *keySize, int *secretKeySize,
+                                        char **issuer, char **subject);
 
 /* Values for "on" */
-#define SSL_SECURITY_STATUS_NOOPT	-1
-#define SSL_SECURITY_STATUS_OFF		0
-#define SSL_SECURITY_STATUS_ON_HIGH	1
-#define SSL_SECURITY_STATUS_ON_LOW	2
-#define SSL_SECURITY_STATUS_FORTEZZA	3 /* NO LONGER SUPPORTED */
+#define SSL_SECURITY_STATUS_NOOPT -1
+#define SSL_SECURITY_STATUS_OFF 0
+#define SSL_SECURITY_STATUS_ON_HIGH 1
+#define SSL_SECURITY_STATUS_ON_LOW 2
+#define SSL_SECURITY_STATUS_FORTEZZA 3 /* NO LONGER SUPPORTED */
 
 /*
 ** Return the certificate for our SSL peer. If the client calls this
 ** it will always return the server's certificate. If the server calls
 ** this, it may return NULL if client authentication is not enabled or
 ** if the client had no certificate when asked.
-**	"fd" the socket "file" descriptor
+**  "fd" the socket "file" descriptor
 */
 SSL_IMPORT CERTCertificate *SSL_PeerCertificate(PRFileDesc *fd);
 
 /*
 ** Return the certificates presented by the SSL peer. If the SSL peer
 ** did not present certificates, return NULL with the
 ** SSL_ERROR_NO_CERTIFICATE error. On failure, return NULL with an error
 ** code other than SSL_ERROR_NO_CERTIFICATE.
-**	"fd" the socket "file" descriptor
+**  "fd" the socket "file" descriptor
 */
 SSL_IMPORT CERTCertList *SSL_PeerCertificateChain(PRFileDesc *fd);
 
 /* SSL_PeerStapledOCSPResponses returns the OCSP responses that were provided
  * by the TLS server. The return value is a pointer to an internal SECItemArray
  * that contains the returned OCSP responses; it is only valid until the
  * callback function that calls SSL_PeerStapledOCSPResponses returns.
  *
@@ -567,44 +567,44 @@ SSL_IMPORT CERTCertList *SSL_PeerCertifi
  * You must set the SSL_ENABLE_OCSP_STAPLING option to enable OCSP stapling.
  * to be provided by a server.
  *
  * libssl does not do any validation of the OCSP response itself; the
  * authenticate certificate hook is responsible for doing so. The default
  * authenticate certificate hook, SSL_AuthCertificate, does not implement
  * any OCSP stapling funtionality, but this may change in future versions.
  */
-SSL_IMPORT const SECItemArray * SSL_PeerStapledOCSPResponses(PRFileDesc *fd);
+SSL_IMPORT const SECItemArray *SSL_PeerStapledOCSPResponses(PRFileDesc *fd);
 
 /* SSL_PeerSignedCertTimestamps returns the signed_certificate_timestamp
  * extension data provided by the TLS server. The return value is a pointer
  * to an internal SECItem that contains the returned response (as a serialized
  * SignedCertificateTimestampList, see RFC 6962). The returned pointer is only
  * valid until the callback function that calls SSL_PeerSignedCertTimestamps
  * (e.g. the authenticate certificate hook, or the handshake callback) returns.
  *
  * If no Signed Certificate Timestamps were given by the server then the result
  * will be empty. If there was an error, then the result will be NULL.
  *
  * You must set the SSL_ENABLE_SIGNED_CERT_TIMESTAMPS option to indicate support
  * for Signed Certificate Timestamps to a server.
  *
  * libssl does not do any parsing or validation of the response itself.
  */
-SSL_IMPORT const SECItem * SSL_PeerSignedCertTimestamps(PRFileDesc *fd);
+SSL_IMPORT const SECItem *SSL_PeerSignedCertTimestamps(PRFileDesc *fd);
 
 /* SSL_SetStapledOCSPResponses stores an array of one or multiple OCSP responses
  * in the fd's data, which may be sent as part of a server side cert_status
  * handshake message. Parameter |responses| is for the server certificate of
  * the key exchange type |kea|.
  * The function will duplicate the responses array.
  */
 SSL_IMPORT SECStatus
 SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses,
-			    SSLKEAType kea);
+                            SSLKEAType kea);
 
 /*
  * SSL_SetSignedCertTimestamps stores serialized signed_certificate_timestamp
  * extension data in the fd. The signed_certificate_timestamp data is sent
  * during the handshake (if requested by the client). Parameter |scts|
  * is for the server certificate of the key exchange type |kea|.
  * The function will duplicate the provided data item. To clear previously
  * set data for a given key exchange type |kea|, pass NULL to |scts|.
@@ -639,51 +639,50 @@ SSL_SetSignedCertTimestamps(PRFileDesc *
 ** libssl does not provide a way for the authenticate certificate hook to
 ** indicate that an OCSP error (SEC_ERROR_OCSP_*) that it returns is an error
 ** in the stapled OCSP response or an error in some other OCSP response.
 ** Further, NSS does not provide a convenient way to control or determine
 ** which OCSP response(s) were used to validate a certificate chain.
 ** Consequently, the current version of libssl does not ever send the
 ** bad_certificate_status_response alert. This may change in future releases.
 */
-typedef SECStatus (PR_CALLBACK *SSLAuthCertificate)(void *arg, PRFileDesc *fd, 
-                                                    PRBool checkSig,
-                                                    PRBool isServer);
+typedef SECStatus(PR_CALLBACK *SSLAuthCertificate)(void *arg, PRFileDesc *fd,
+                                                   PRBool checkSig,
+                                                   PRBool isServer);
 
-SSL_IMPORT SECStatus SSL_AuthCertificateHook(PRFileDesc *fd, 
-					     SSLAuthCertificate f,
-				             void *arg);
+SSL_IMPORT SECStatus SSL_AuthCertificateHook(PRFileDesc *fd,
+                                             SSLAuthCertificate f,
+                                             void *arg);
 
 /* An implementation of the certificate authentication hook */
-SSL_IMPORT SECStatus SSL_AuthCertificate(void *arg, PRFileDesc *fd, 
-					 PRBool checkSig, PRBool isServer);
+SSL_IMPORT SECStatus SSL_AuthCertificate(void *arg, PRFileDesc *fd,
+                                         PRBool checkSig, PRBool isServer);
 
 /*
  * Prototype for SSL callback to get client auth data from the application.
- *	arg - application passed argument
- *	caNames - pointer to distinguished names of CAs that the server likes
- *	pRetCert - pointer to pointer to cert, for return of cert
- *	pRetKey - pointer to key pointer, for return of key
+ *  arg - application passed argument
+ *  caNames - pointer to distinguished names of CAs that the server likes
+ *  pRetCert - pointer to pointer to cert, for return of cert
+ *  pRetKey - pointer to key pointer, for return of key
  */
-typedef SECStatus (PR_CALLBACK *SSLGetClientAuthData)(void *arg,
-                                PRFileDesc *fd,
-                                CERTDistNames *caNames,
-                                CERTCertificate **pRetCert,/*return */
-                                SECKEYPrivateKey **pRetKey);/* return */
+typedef SECStatus(PR_CALLBACK *SSLGetClientAuthData)(void *arg,
+                                                     PRFileDesc *fd,
+                                                     CERTDistNames *caNames,
+                                                     CERTCertificate **pRetCert,  /*return */
+                                                     SECKEYPrivateKey **pRetKey); /* return */
 
 /*
  * Set the client side callback for SSL to retrieve user's private key
  * and certificate.
- *	fd - the file descriptor for the connection in question
- *	f - the application's callback that delivers the key and cert
- *	a - application specific data
+ *  fd - the file descriptor for the connection in question
+ *  f - the application's callback that delivers the key and cert
+ *  a - application specific data
  */
-SSL_IMPORT SECStatus SSL_GetClientAuthDataHook(PRFileDesc *fd, 
-			                       SSLGetClientAuthData f, void *a);
-
+SSL_IMPORT SECStatus SSL_GetClientAuthDataHook(PRFileDesc *fd,
+                                               SSLGetClientAuthData f, void *a);
 
 /*
 ** SNI extension processing callback function.
 ** It is called when SSL socket receives SNI extension in ClientHello message.
 ** Upon this callback invocation, application is responsible to reconfigure the
 ** socket with the data for a particular server name.
 ** There are three potential outcomes of this function invocation:
 **    * application does not recognize the name or the type and wants the
@@ -701,49 +700,49 @@ SSL_IMPORT SECStatus SSL_GetClientAuthDa
 ** LibSSL will ignore any SNI extension received in a ClientHello message
 ** if application does not register a SSLSNISocketConfig callback.
 ** Each type field of SECItem indicates the name type.
 ** NOTE: currently RFC3546 defines only one name type: sni_host_name.
 ** Client is allowed to send only one name per known type. LibSSL will
 ** send an "unrecognized_name" alert if SNI extension name list contains more
 ** then one name of a type.
 */
-typedef PRInt32 (PR_CALLBACK *SSLSNISocketConfig)(PRFileDesc *fd,
-                                            const SECItem *srvNameArr,
-                                                  PRUint32 srvNameArrSize,
-                                                  void *arg);
+typedef PRInt32(PR_CALLBACK *SSLSNISocketConfig)(PRFileDesc *fd,
+                                                 const SECItem *srvNameArr,
+                                                 PRUint32 srvNameArrSize,
+                                                 void *arg);
 
 /*
 ** SSLSNISocketConfig should return an index within 0 and srvNameArrSize-1
 ** when it has reconfigured the socket fd to use certs and keys, etc
 ** for a specific name. There are two other allowed return values. One
 ** tells libSSL to use the default cert and key.  The other tells libSSL
 ** to send the "unrecognized_name" alert.  These values are:
 **/
-#define SSL_SNI_CURRENT_CONFIG_IS_USED           -1
-#define SSL_SNI_SEND_ALERT                       -2
+#define SSL_SNI_CURRENT_CONFIG_IS_USED -1
+#define SSL_SNI_SEND_ALERT -2
 
 /*
 ** Set application implemented SNISocketConfig callback.
 */
-SSL_IMPORT SECStatus SSL_SNISocketConfigHook(PRFileDesc *fd, 
+SSL_IMPORT SECStatus SSL_SNISocketConfigHook(PRFileDesc *fd,
                                              SSLSNISocketConfig f,
                                              void *arg);
 
 /*
 ** Reconfigure fd SSL socket with model socket parameters. Sets
 ** server certs and keys, list of trust anchor, socket options
 ** and all SSL socket call backs and parameters.
 */
 SSL_IMPORT PRFileDesc *SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd);
 
 /*
  * Set the client side argument for SSL to retrieve PKCS #11 pin.
- *	fd - the file descriptor for the connection in question
- *	a - pkcs11 application specific data
+ *  fd - the file descriptor for the connection in question
+ *  a - pkcs11 application specific data
  */
 SSL_IMPORT SECStatus SSL_SetPKCS11PinArg(PRFileDesc *fd, void *a);
 
 /*
 ** This is a callback for dealing with server certs that are not authenticated
 ** by the client.  The client app can decide that it actually likes the
 ** cert by some external means and restart the connection.
 **
@@ -752,162 +751,161 @@ SSL_IMPORT SECStatus SSL_SetPKCS11PinArg
 ** considered invalid, or SECWouldBlock if the application will authenticate
 ** the certificate asynchronously. SECWouldBlock is only supported for
 ** non-blocking sockets.
 **
 ** See the documentation for SSL_AuthCertificateComplete for more information
 ** about the asynchronous behavior that occurs when the bad cert hook returns
 ** SECWouldBlock.
 */
-typedef SECStatus (PR_CALLBACK *SSLBadCertHandler)(void *arg, PRFileDesc *fd);
-SSL_IMPORT SECStatus SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, 
-				     void *arg);
+typedef SECStatus(PR_CALLBACK *SSLBadCertHandler)(void *arg, PRFileDesc *fd);
+SSL_IMPORT SECStatus SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f,
+                                     void *arg);
 
 /*
 ** Configure SSL socket for running a secure server. Needs the
 ** certificate for the server and the servers private key. The arguments
 ** are copied.
 */
 SSL_IMPORT SECStatus SSL_ConfigSecureServer(
-				PRFileDesc *fd, CERTCertificate *cert,
-				SECKEYPrivateKey *key, SSLKEAType kea);
+    PRFileDesc *fd, CERTCertificate *cert,
+    SECKEYPrivateKey *key, SSLKEAType kea);
 
 /*
 ** Allows SSL socket configuration with caller-supplied certificate chain.
 ** If certChainOpt is NULL, tries to find one.
 */
 SSL_IMPORT SECStatus
 SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert,
                                     const CERTCertificateList *certChainOpt,
                                     SECKEYPrivateKey *key, SSLKEAType kea);
 
 /*
 ** Configure a secure server's session-id cache. Define the maximum number
 ** of entries in the cache, the longevity of the entires, and the directory
-** where the cache files will be placed.  These values can be zero, and 
+** where the cache files will be placed.  These values can be zero, and
 ** if so, the implementation will choose defaults.
-** This version of the function is for use in applications that have only one 
+** This version of the function is for use in applications that have only one
 ** process that uses the cache (even if that process has multiple threads).
 */
-SSL_IMPORT SECStatus SSL_ConfigServerSessionIDCache(int      maxCacheEntries,
-					            PRUint32 timeout,
-					            PRUint32 ssl3_timeout,
-				              const char *   directory);
+SSL_IMPORT SECStatus SSL_ConfigServerSessionIDCache(int maxCacheEntries,
+                                                    PRUint32 timeout,
+                                                    PRUint32 ssl3_timeout,
+                                                    const char *directory);
 
 /* Configure a secure server's session-id cache. Depends on value of
  * enableMPCache, configures malti-proc or single proc cache. */
 SSL_IMPORT SECStatus SSL_ConfigServerSessionIDCacheWithOpt(
-                                                           PRUint32 timeout,
-                                                       PRUint32 ssl3_timeout,
-                                                     const char *   directory,
-                                                          int maxCacheEntries,
-                                                      int maxCertCacheEntries,
-                                                    int maxSrvNameCacheEntries,
-                                                           PRBool enableMPCache);
+    PRUint32 timeout,
+    PRUint32 ssl3_timeout,
+    const char *directory,
+    int maxCacheEntries,
+    int maxCertCacheEntries,
+    int maxSrvNameCacheEntries,
+    PRBool enableMPCache);
 
 /*
 ** Like SSL_ConfigServerSessionIDCache, with one important difference.
-** If the application will run multiple processes (as opposed to, or in 
+** If the application will run multiple processes (as opposed to, or in
 ** addition to multiple threads), then it must call this function, instead
 ** of calling SSL_ConfigServerSessionIDCache().
 ** This has nothing to do with the number of processORs, only processEs.
 ** This function sets up a Server Session ID (SID) cache that is safe for
 ** access by multiple processes on the same system.
 */
-SSL_IMPORT SECStatus SSL_ConfigMPServerSIDCache(int      maxCacheEntries, 
-				                PRUint32 timeout,
-			       	                PRUint32 ssl3_timeout, 
-		                          const char *   directory);
+SSL_IMPORT SECStatus SSL_ConfigMPServerSIDCache(int maxCacheEntries,
+                                                PRUint32 timeout,
+                                                PRUint32 ssl3_timeout,
+                                                const char *directory);
 
-/* Get and set the configured maximum number of mutexes used for the 
-** server's store of SSL sessions.  This value is used by the server 
-** session ID cache initialization functions shown above.  Note that on 
-** some platforms, these mutexes are actually implemented with POSIX 
+/* Get and set the configured maximum number of mutexes used for the
+** server's store of SSL sessions.  This value is used by the server
+** session ID cache initialization functions shown above.  Note that on
+** some platforms, these mutexes are actually implemented with POSIX
 ** semaphores, or with unnamed pipes.  The default value varies by platform.
-** An attempt to set a too-low maximum will return an error and the 
+** An attempt to set a too-low maximum will return an error and the
 ** configured value will not be changed.
 */
-SSL_IMPORT PRUint32  SSL_GetMaxServerCacheLocks(void);
+SSL_IMPORT PRUint32 SSL_GetMaxServerCacheLocks(void);
 SSL_IMPORT SECStatus SSL_SetMaxServerCacheLocks(PRUint32 maxLocks);
 
 /* environment variable set by SSL_ConfigMPServerSIDCache, and queried by
  * SSL_InheritMPServerSIDCache when envString is NULL.
  */
-#define SSL_ENV_VAR_NAME            "SSL_INHERITANCE"
+#define SSL_ENV_VAR_NAME "SSL_INHERITANCE"
 
-/* called in child to inherit SID Cache variables. 
+/* called in child to inherit SID Cache variables.
  * If envString is NULL, this function will use the value of the environment
- * variable "SSL_INHERITANCE", otherwise the string value passed in will be 
+ * variable "SSL_INHERITANCE", otherwise the string value passed in will be
  * used.
  */
-SSL_IMPORT SECStatus SSL_InheritMPServerSIDCache(const char * envString);
+SSL_IMPORT SECStatus SSL_InheritMPServerSIDCache(const char *envString);
 
 /*
 ** Set the callback that gets called when a TLS handshake is complete. The
 ** handshake callback is called after verifying the peer's Finished message and
 ** before processing incoming application data.
 **
 ** For the initial handshake: If the handshake false started (see
 ** SSL_ENABLE_FALSE_START), then application data may already have been sent
 ** before the handshake callback is called. If we did not false start then the
 ** callback will get called before any application data is sent.
 */
-typedef void (PR_CALLBACK *SSLHandshakeCallback)(PRFileDesc *fd,
-                                                 void *client_data);
-SSL_IMPORT SECStatus SSL_HandshakeCallback(PRFileDesc *fd, 
-			          SSLHandshakeCallback cb, void *client_data);
+typedef void(PR_CALLBACK *SSLHandshakeCallback)(PRFileDesc *fd,
+                                                void *client_data);
+SSL_IMPORT SECStatus SSL_HandshakeCallback(PRFileDesc *fd,
+                                           SSLHandshakeCallback cb, void *client_data);
 
 /* Applications that wish to enable TLS false start must set this callback
 ** function. NSS will invoke the functon to determine if a particular
 ** connection should use false start or not. SECSuccess indicates that the
 ** callback completed successfully, and if so *canFalseStart indicates if false
 ** start can be used. If the callback does not return SECSuccess then the
 ** handshake will be canceled. NSS's recommended criteria can be evaluated by
 ** calling SSL_RecommendedCanFalseStart.
 **
 ** If no false start callback is registered then false start will never be
 ** done, even if the SSL_ENABLE_FALSE_START option is enabled.
 **/
-typedef SECStatus (PR_CALLBACK *SSLCanFalseStartCallback)(
+typedef SECStatus(PR_CALLBACK *SSLCanFalseStartCallback)(
     PRFileDesc *fd, void *arg, PRBool *canFalseStart);
 
 SSL_IMPORT SECStatus SSL_SetCanFalseStartCallback(
     PRFileDesc *fd, SSLCanFalseStartCallback callback, void *arg);
 
 /* This function sets *canFalseStart according to the recommended criteria for
 ** false start. These criteria may change from release to release and may depend
 ** on which handshake features have been negotiated and/or properties of the
 ** certifciates/keys used on the connection.
 */
 SSL_IMPORT SECStatus SSL_RecommendedCanFalseStart(PRFileDesc *fd,
                                                   PRBool *canFalseStart);
 
 /*
 ** For the server, request a new handshake.  For the client, begin a new
-** handshake.  If flushCache is non-zero, the SSL3 cache entry will be 
+** handshake.  If flushCache is non-zero, the SSL3 cache entry will be
 ** flushed first, ensuring that a full SSL handshake will be done.
-** If flushCache is zero, and an SSL connection is established, it will 
-** do the much faster session restart handshake.  This will change the 
+** If flushCache is zero, and an SSL connection is established, it will
+** do the much faster session restart handshake.  This will change the
 ** session keys without doing another private key operation.
 */
 SSL_IMPORT SECStatus SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache);