From 5553a6adbfd64cca1395aac5b311dcccce3acd2f Mon Sep 17 00:00:00 2001 From: Kai Engert Date: Tue, 23 Feb 2016 00:50:19 +0100 Subject: [PATCH] Bug 1245053, landing NSS_3_23_BETA5, r=mt --- security/nss/TAG-INFO | 2 +- security/nss/circle.yml | 5 +- security/nss/cmd/bltest/blapitest.c | 174 +- .../cmd/bltest/tests/chacha20_poly1305/aad0 | 1 + .../cmd/bltest/tests/chacha20_poly1305/aad1 | Bin 0 -> 12 bytes .../tests/chacha20_poly1305/ciphertext0 | 1 + .../tests/chacha20_poly1305/ciphertext1 | 1 + .../cmd/bltest/tests/chacha20_poly1305/iv0 | Bin 0 -> 12 bytes .../cmd/bltest/tests/chacha20_poly1305/iv1 | Bin 0 -> 12 bytes .../cmd/bltest/tests/chacha20_poly1305/key0 | 1 + .../cmd/bltest/tests/chacha20_poly1305/key1 | 1 + .../bltest/tests/chacha20_poly1305/numtests | 1 + .../bltest/tests/chacha20_poly1305/plaintext0 | 1 + .../bltest/tests/chacha20_poly1305/plaintext1 | 1 + security/nss/cmd/ssltap/ssltap.c | 4 + security/nss/coreconf/Werror.mk | 25 +- security/nss/coreconf/config.mk | 4 + security/nss/coreconf/coreconf.dep | 1 + .../nss/external_tests/pk11_gtest/manifest.mn | 1 + .../pk11_chacha20poly1305_unittest.cc | 277 + .../ssl_gtest/libssl_internals.c | 21 + .../ssl_gtest/libssl_internals.h | 4 + .../ssl_gtest/ssl_loopback_unittest.cc | 38 + .../nss/external_tests/ssl_gtest/tls_agent.cc | 14 +- security/nss/lib/freebl/Makefile | 27 + security/nss/lib/freebl/blapi.h | 29 + security/nss/lib/freebl/blapit.h | 2 + security/nss/lib/freebl/chacha20.c | 111 + security/nss/lib/freebl/chacha20.h | 26 + security/nss/lib/freebl/chacha20_vec.c | 278 + security/nss/lib/freebl/chacha20poly1305.c | 198 + security/nss/lib/freebl/chacha20poly1305.h | 15 + security/nss/lib/freebl/intel-aes.s | 284 +- security/nss/lib/freebl/ldvector.c | 10 +- security/nss/lib/freebl/loader.c | 56 + security/nss/lib/freebl/loader.h | 29 +- security/nss/lib/freebl/manifest.mn | 2 + ...ly1305-donna-x64-sse2-incremental-source.c | 623 + security/nss/lib/freebl/poly1305.c | 261 + security/nss/lib/freebl/poly1305.h | 28 + security/nss/lib/pk11wrap/pk11mech.c | 7 + security/nss/lib/pk11wrap/pk11pars.c | 1 + security/nss/lib/pkcs7/p7local.c | 2 +- security/nss/lib/softoken/pkcs11.c | 5 + security/nss/lib/softoken/pkcs11c.c | 185 +- security/nss/lib/softoken/pkcs11i.h | 12 + security/nss/lib/ssl/SSLerrs.h | 533 +- security/nss/lib/ssl/authcert.c | 130 +- security/nss/lib/ssl/cmpcert.c | 124 +- security/nss/lib/ssl/derive.c | 1249 +- security/nss/lib/ssl/dtlscon.c | 170 +- security/nss/lib/ssl/notes.txt | 128 +- security/nss/lib/ssl/os2_err.c | 200 +- security/nss/lib/ssl/os2_err.h | 4 +- security/nss/lib/ssl/preenc.h | 110 +- security/nss/lib/ssl/prelib.c | 12 +- security/nss/lib/ssl/ssl.def | 6 + security/nss/lib/ssl/ssl.h | 401 +- security/nss/lib/ssl/ssl3con.c | 12889 ++++++++-------- security/nss/lib/ssl/ssl3ecc.c | 698 +- security/nss/lib/ssl/ssl3ext.c | 1096 +- security/nss/lib/ssl/ssl3gthr.c | 504 +- security/nss/lib/ssl/ssl3prot.h | 191 +- security/nss/lib/ssl/sslauth.c | 246 +- security/nss/lib/ssl/sslcon.c | 3614 ++--- security/nss/lib/ssl/ssldef.c | 149 +- security/nss/lib/ssl/sslenum.c | 11 +- security/nss/lib/ssl/sslerr.c | 32 +- security/nss/lib/ssl/sslerr.h | 357 +- security/nss/lib/ssl/sslerrstrs.c | 12 +- security/nss/lib/ssl/sslgathr.c | 542 +- security/nss/lib/ssl/sslimpl.h | 1918 +-- security/nss/lib/ssl/sslinfo.c | 437 +- security/nss/lib/ssl/sslinit.c | 29 +- security/nss/lib/ssl/sslmutex.c | 333 +- security/nss/lib/ssl/sslmutex.h | 58 +- security/nss/lib/ssl/sslnonce.c | 312 +- security/nss/lib/ssl/sslproto.h | 8 + security/nss/lib/ssl/sslreveal.c | 140 +- security/nss/lib/ssl/sslsecur.c | 1200 +- security/nss/lib/ssl/sslsnce.c | 1934 ++- security/nss/lib/ssl/sslsock.c | 2134 +-- security/nss/lib/ssl/sslt.h | 190 +- security/nss/lib/ssl/ssltrace.c | 341 +- security/nss/lib/ssl/tls13con.c | 620 +- security/nss/lib/ssl/tls13con.h | 2 +- security/nss/lib/ssl/tls13hkdf.c | 17 +- security/nss/lib/ssl/tls13hkdf.h | 6 +- security/nss/lib/ssl/unix_err.c | 728 +- security/nss/lib/ssl/unix_err.h | 4 +- security/nss/lib/ssl/win32err.c | 465 +- security/nss/lib/ssl/win32err.h | 4 +- security/nss/lib/util/pkcs11n.h | 13 + security/nss/lib/util/secasn1d.c | 51 +- security/nss/lib/util/secoid.c | 3 +- security/nss/lib/util/secoidt.h | 2 + security/nss/lib/util/utf8.c | 11 +- security/nss/tests/cipher/cipher.txt | 2 + security/nss/tests/ssl/ssl.sh | 18 +- security/nss/tests/ssl/sslcov.txt | 3 + 100 files changed, 20559 insertions(+), 16601 deletions(-) create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/aad0 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/aad1 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext0 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext1 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/iv0 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/iv1 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/key0 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/key1 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/numtests create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext0 create mode 100644 security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext1 create mode 100644 security/nss/external_tests/pk11_gtest/pk11_chacha20poly1305_unittest.cc create mode 100644 security/nss/lib/freebl/chacha20.c create mode 100644 security/nss/lib/freebl/chacha20.h create mode 100644 security/nss/lib/freebl/chacha20_vec.c create mode 100644 security/nss/lib/freebl/chacha20poly1305.c create mode 100644 security/nss/lib/freebl/chacha20poly1305.h create mode 100644 security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c create mode 100644 security/nss/lib/freebl/poly1305.c create mode 100644 security/nss/lib/freebl/poly1305.h diff --git a/security/nss/TAG-INFO b/security/nss/TAG-INFO index e2461df304e9..7b2b6db793ff 100644 --- a/security/nss/TAG-INFO +++ b/security/nss/TAG-INFO @@ -1 +1 @@ -NSS_3_23_BETA4 +NSS_3_23_BETA5 diff --git a/security/nss/circle.yml b/security/nss/circle.yml index 9438be1868e0..1d59854200b3 100644 --- a/security/nss/circle.yml +++ b/security/nss/circle.yml @@ -5,15 +5,14 @@ checkout: 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: diff --git a/security/nss/cmd/bltest/blapitest.c b/security/nss/cmd/bltest/blapitest.c index 204814d82d83..74de908dc526 100644 --- a/security/nss/cmd/bltest/blapitest.c +++ b/security/nss/cmd/bltest/blapitest.c @@ -613,6 +613,17 @@ typedef SECStatus (* bltestSymmCipherFn)(void *cx, 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); @@ -646,6 +657,7 @@ typedef enum { 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.) */ @@ -685,6 +697,7 @@ static char *mode_strings[] = "camellia_cbc", "seed_ecb", "seed_cbc", + "chacha20_poly1305", "rsa", "rsa_oaep", "rsa_pss", @@ -805,6 +818,7 @@ struct bltestCipherInfoStr { /* Cipher function (encrypt/decrypt/sign/verify/hash) */ union { bltestSymmCipherFn symmkeyCipher; + bltestAEADFn aeadCipher; bltestPubKeyCipherFn pubkeyCipher; bltestHashCipherFn hashCipher; } cipher; @@ -826,13 +840,29 @@ is_symmkeyCipher(bltestCipherMode mode) 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; + } } @@ -840,11 +870,14 @@ 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 @@ -878,16 +911,24 @@ 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); @@ -1126,6 +1167,30 @@ aes_Decrypt(void *cx, unsigned char *output, unsigned int *outputLen, 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, @@ -1575,6 +1640,21 @@ bltest_seed_init(bltestCipherInfo *cipherInfo, PRBool encrypt) 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) { @@ -2226,6 +2306,11 @@ cipherInit(bltestCipherInfo *cipherInfo, PRBool encrypt) 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: @@ -2376,6 +2461,55 @@ cipherDoOp(bltestCipherInfo *cipherInfo) } } 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; irepetitionsToPerfom; 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, @@ -2477,6 +2611,10 @@ cipherFinish(bltestCipherInfo *cipherInfo) 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); @@ -2808,6 +2946,7 @@ get_params(PLArenaPool *arena, bltestParams *params, #endif switch (mode) { case bltestAES_GCM: + case bltestCHACHA20: sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "aad", j); load_file_data(arena, ¶ms->ask.aad, filename, bltestBinary); case bltestDES_CBC: @@ -3753,7 +3892,8 @@ print_usage: /* 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) { diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/aad0 b/security/nss/cmd/bltest/tests/chacha20_poly1305/aad0 new file mode 100644 index 000000000000..a420ef184233 --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/aad0 @@ -0,0 +1 @@ +PQRSΐΑΒΓΔΕΖΗ \ No newline at end of file diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/aad1 b/security/nss/cmd/bltest/tests/chacha20_poly1305/aad1 new file mode 100644 index 0000000000000000000000000000000000000000..91287a1a2e38397b4bd5081fadab286c1fbd971a GIT binary patch literal 12 Pcmext+|kAW27VI(7}Nt4 literal 0 HcmV?d00001 diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext0 b/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext0 new file mode 100644 index 000000000000..a06f68b5f0e4 --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext0 @@ -0,0 +1 @@ +0xqNNGSOYNt7hq+8U+9+wqSt7VEpbgj+qeK1pzbuYtY9vqRejKlnEoL6+2naknKLGnHeCp4GCykF1qW2fs07NpLdvX8td4uMmAOu4ygJG1j6syTk+tZ1lFWFgItIMde8P/Te8I5Lep3ldtJlhs7GS2EWGuELWU8J4mp+kC7L0GAGkQ== diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext1 b/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext1 new file mode 100644 index 000000000000..e7f0d0100791 --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/ciphertext1 @@ -0,0 +1 @@ +ZKCGFXWGGvRg8GLHm+ZDvV6AXP00XPOJ8QhnCsdsjLJMbPwYdV1D7qCe6U44LSawvbe3PDIbAQDU8Dt/NViUzzMvgw5xC5fOmMioSr0LlIEUrRduAI0zvWD5grH/N8hVl5egbvTw72HBhjJOKzUGODYGkHtqfAKw+fYVe1PIZ+S5Fmx2e4BNRqWbUhbN56TpkEDFpAQzIl7igqGwoGxSPq9FNNf4P6EVWwBHcYy8VGoNBysEs1ZO6htCInP1SCcaC7IxYFP6dpkZVevWMVlDTs67TkZtrloQc6ZydicJehBJ5hfZHTYQlPpo8P93mHEwMFvqui7aBN+Ze3FNbG8sKaatXLQCKwJwm+6tnWeJDLsiOSM2/qGFHzg= diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/iv0 b/security/nss/cmd/bltest/tests/chacha20_poly1305/iv0 new file mode 100644 index 0000000000000000000000000000000000000000..7e8a175046dde8a759e54a088eac41101ebd5782 GIT binary patch literal 12 TcmZQ)U|?`?baHlab#n&*3A6$v literal 0 HcmV?d00001 diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/iv1 b/security/nss/cmd/bltest/tests/chacha20_poly1305/iv1 new file mode 100644 index 0000000000000000000000000000000000000000..7c8b98f50daf0ac0902bf4c98da4c5f6a91ca994 GIT binary patch literal 12 TcmZQzU|?WmVrF4wW9I+>0E7S~ literal 0 HcmV?d00001 diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/key0 b/security/nss/cmd/bltest/tests/chacha20_poly1305/key0 new file mode 100644 index 000000000000..503ecb84e00d --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/key0 @@ -0,0 +1 @@ +€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ \ No newline at end of file diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/key1 b/security/nss/cmd/bltest/tests/chacha20_poly1305/key1 new file mode 100644 index 000000000000..002bf1b45576 --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/key1 @@ -0,0 +1 @@ +’@₯λUӊσ3ˆ†φ΅πG9Α@+€ Κ\Ό puΐ \ No newline at end of file diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/numtests b/security/nss/cmd/bltest/tests/chacha20_poly1305/numtests new file mode 100644 index 000000000000..0cfbf08886fc --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/numtests @@ -0,0 +1 @@ +2 diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext0 b/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext0 new file mode 100644 index 000000000000..74c222908378 --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext0 @@ -0,0 +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 diff --git a/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext1 b/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext1 new file mode 100644 index 000000000000..029317d8ec09 --- /dev/null +++ b/security/nss/cmd/bltest/tests/chacha20_poly1305/plaintext1 @@ -0,0 +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 diff --git a/security/nss/cmd/ssltap/ssltap.c b/security/nss/cmd/ssltap/ssltap.c index 8ea465ef32f4..29b91910e4ab 100644 --- a/security/nss/cmd/ssltap/ssltap.c +++ b/security/nss/cmd/ssltap/ssltap.c @@ -443,6 +443,10 @@ const char * V2CipherString(int cs_int) 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; diff --git a/security/nss/coreconf/Werror.mk b/security/nss/coreconf/Werror.mk index 28a64059d98e..958a002d370e 100644 --- a/security/nss/coreconf/Werror.mk +++ b/security/nss/coreconf/Werror.mk @@ -7,6 +7,7 @@ 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 @@ -16,9 +17,18 @@ ifndef CC_NAME 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) @@ -55,18 +65,17 @@ ifndef WARNING_CFLAGS 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 diff --git a/security/nss/coreconf/config.mk b/security/nss/coreconf/config.mk index 134d0c8c11eb..61d757bcc133 100644 --- a/security/nss/coreconf/config.mk +++ b/security/nss/coreconf/config.mk @@ -166,6 +166,10 @@ 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 diff --git a/security/nss/coreconf/coreconf.dep b/security/nss/coreconf/coreconf.dep index 5182f75552c8..590d1bfaeee3 100644 --- a/security/nss/coreconf/coreconf.dep +++ b/security/nss/coreconf/coreconf.dep @@ -10,3 +10,4 @@ */ #error "Do not include this header file." + diff --git a/security/nss/external_tests/pk11_gtest/manifest.mn b/security/nss/external_tests/pk11_gtest/manifest.mn index 9494fed1822c..78178593973b 100644 --- a/security/nss/external_tests/pk11_gtest/manifest.mn +++ b/security/nss/external_tests/pk11_gtest/manifest.mn @@ -7,6 +7,7 @@ DEPTH = ../.. MODULE = nss CPPSRCS = \ + pk11_chacha20poly1305_unittest.cc \ pk11_pbkdf2_unittest.cc \ pk11_prf_unittest.cc \ pk11_rsapss_unittest.cc \ diff --git a/security/nss/external_tests/pk11_gtest/pk11_chacha20poly1305_unittest.cc b/security/nss/external_tests/pk11_gtest/pk11_chacha20poly1305_unittest.cc new file mode 100644 index 000000000000..a52e3170e594 --- /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 + +#include "gtest/gtest.h" +#include "scoped_ptrs.h" + +namespace nss_test { + +// ChaCha20/Poly1305 Test Vector 1, RFC 7539 +// +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 +// +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(&aead_params), + sizeof(aead_params) }; + + // Encrypt. + unsigned int outputLen = 0; + std::vector output(data_len + aead_params.ulTagLen); + SECStatus rv = PK11_Encrypt(symKey, mech, ¶ms, &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 decrypted(data_len); + rv = PK11_Decrypt(symKey, mech, ¶ms, &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 bogusCiphertext(output); + bogusCiphertext[0] ^= 0xff; + rv = PK11_Decrypt(symKey, mech, ¶ms, &decrypted[0], &decryptedLen, + decrypted.size(), &bogusCiphertext[0], outputLen); + EXPECT_NE(rv, SECSuccess); + } + + // Decrypt with bogus tag. + { + std::vector bogusTag(output); + bogusTag[outputLen - 1] ^= 0xff; + rv = PK11_Decrypt(symKey, mech, ¶ms, &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(&bogusAeadParams); + + std::vector 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(&bogusAeadParams); + + std::vector 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(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( + static_cast(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 data(512); + SECStatus rv = PK11_GenerateRandomOnSlot(slot.get(), &data[0], data.size()); + EXPECT_EQ(rv, SECSuccess); + + // Generate random AAD. + std::vector aad(16); + rv = PK11_GenerateRandomOnSlot(slot.get(), &aad[0], aad.size()); + EXPECT_EQ(rv, SECSuccess); + + // Generate random IV. + std::vector 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 + diff --git a/security/nss/external_tests/ssl_gtest/libssl_internals.c b/security/nss/external_tests/ssl_gtest/libssl_internals.c index db83ef6942d2..7043d035e538 100644 --- a/security/nss/external_tests/ssl_gtest/libssl_internals.c +++ b/security/nss/external_tests/ssl_gtest/libssl_internals.c @@ -24,3 +24,24 @@ SSLInt_IncrementClientHandshakeVersion(PRFileDesc *fd) 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); +} diff --git a/security/nss/external_tests/ssl_gtest/libssl_internals.h b/security/nss/external_tests/ssl_gtest/libssl_internals.h index db6d0af624f8..90c5c2ea3148 100644 --- a/security/nss/external_tests/ssl_gtest/libssl_internals.h +++ b/security/nss/external_tests/ssl_gtest/libssl_internals.h @@ -9,9 +9,13 @@ #include "prio.h" #include "seccomon.h" +#include "sslt.h" SECStatus SSLInt_IncrementClientHandshakeVersion(PRFileDesc *fd); +PRUint32 SSLInt_DetermineKEABits(PRUint16 serverKeyBits, + SSLAuthType authAlgorithm); + #endif diff --git a/security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc b/security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc index 443806b870b1..0e5dc3c6f7f1 100644 --- a/security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc +++ b/security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc @@ -108,6 +108,29 @@ class TlsServerKeyExchangeEcdhe { 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(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) { @@ -542,6 +565,19 @@ TEST_P(TlsConnectGeneric, ConnectSendReceive) { 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 @@ -946,6 +982,8 @@ 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, diff --git a/security/nss/external_tests/ssl_gtest/tls_agent.cc b/security/nss/external_tests/ssl_gtest/tls_agent.cc index ac1ad2ea75e7..ff3dc5a6dd23 100644 --- a/security/nss/external_tests/ssl_gtest/tls_agent.cc +++ b/security/nss/external_tests/ssl_gtest/tls_agent.cc @@ -13,6 +13,11 @@ #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" @@ -195,6 +200,7 @@ void TlsAgent::DisableCiphersByKeyExchange(SSLKEAType kea) { 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); @@ -291,9 +297,12 @@ 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); @@ -378,6 +387,7 @@ 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); @@ -423,6 +433,7 @@ void TlsAgent::Connected() { 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 @@ -432,6 +443,7 @@ void TlsAgent::Connected() { rv = SSL_GetCipherSuiteInfo(info_.cipherSuite, &csinfo_, sizeof(csinfo_)); EXPECT_EQ(SECSuccess, rv); + EXPECT_EQ(sizeof(csinfo_), csinfo_.length); SetState(STATE_CONNECTED); } diff --git a/security/nss/lib/freebl/Makefile b/security/nss/lib/freebl/Makefile index e8f94024139e..4d1860b5b9cd 100644 --- a/security/nss/lib/freebl/Makefile +++ b/security/nss/lib/freebl/Makefile @@ -482,6 +482,33 @@ ifndef NSS_DISABLE_ECC 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) # ####################################################################### diff --git a/security/nss/lib/freebl/blapi.h b/security/nss/lib/freebl/blapi.h index 8324714d825a..2b209015eaaa 100644 --- a/security/nss/lib/freebl/blapi.h +++ b/security/nss/lib/freebl/blapi.h @@ -986,6 +986,35 @@ 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); /******************************************/ /* diff --git a/security/nss/lib/freebl/blapit.h b/security/nss/lib/freebl/blapit.h index 8e172d424ef0..eacf48a7e243 100644 --- a/security/nss/lib/freebl/blapit.h +++ b/security/nss/lib/freebl/blapit.h @@ -222,6 +222,7 @@ struct SHA256ContextStr ; struct SHA512ContextStr ; struct AESKeyWrapContextStr ; struct SEEDContextStr ; +struct ChaCha20Poly1305ContextStr; typedef struct DESContextStr DESContext; typedef struct RC2ContextStr RC2Context; @@ -240,6 +241,7 @@ typedef struct SHA512ContextStr SHA512Context; typedef struct SHA512ContextStr SHA384Context; typedef struct AESKeyWrapContextStr AESKeyWrapContext; typedef struct SEEDContextStr SEEDContext; +typedef struct ChaCha20Poly1305ContextStr ChaCha20Poly1305Context; /*************************************************************************** ** RSA Public and Private Key structures diff --git a/security/nss/lib/freebl/chacha20.c b/security/nss/lib/freebl/chacha20.c new file mode 100644 index 000000000000..687be663958d --- /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 +#include + +#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]; + } + } +} diff --git a/security/nss/lib/freebl/chacha20.h b/security/nss/lib/freebl/chacha20.h new file mode 100644 index 000000000000..7e396fa8c0e6 --- /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 +#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_ */ diff --git a/security/nss/lib/freebl/chacha20_vec.c b/security/nss/lib/freebl/chacha20_vec.c new file mode 100644 index 000000000000..352b70d384c9 --- /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 + +#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 +#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 +#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 +#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 +#include + +#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 +} diff --git a/security/nss/lib/freebl/chacha20poly1305.h b/security/nss/lib/freebl/chacha20poly1305.h new file mode 100644 index 000000000000..c77632aa1398 --- /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_ */ diff --git a/security/nss/lib/freebl/intel-aes.s b/security/nss/lib/freebl/intel-aes.s index a83529a4803a..2dfcfa15b49f 100644 --- a/security/nss/lib/freebl/intel-aes.s +++ b/security/nss/lib/freebl/intel-aes.s @@ -7,6 +7,20 @@ #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 @@ -119,10 +133,11 @@ 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 @@ -135,11 +150,11 @@ intel_aes_encrypt_ecb_128: 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 @@ -260,11 +275,11 @@ intel_aes_encrypt_ecb_128: 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 @@ -290,8 +305,8 @@ intel_aes_encrypt_ecb_128: .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 @@ -302,10 +317,11 @@ 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 @@ -318,11 +334,11 @@ intel_aes_decrypt_ecb_128: 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 @@ -443,11 +459,11 @@ intel_aes_decrypt_ecb_128: 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 @@ -473,8 +489,8 @@ intel_aes_decrypt_ecb_128: .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 @@ -485,17 +501,18 @@ 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 @@ -532,8 +549,8 @@ intel_aes_encrypt_cbc_128: .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) @@ -546,10 +563,11 @@ 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 @@ -565,9 +583,9 @@ intel_aes_decrypt_cbc_128: 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 @@ -704,10 +722,10 @@ intel_aes_decrypt_cbc_128: 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 @@ -736,8 +754,8 @@ intel_aes_decrypt_cbc_128: 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) @@ -873,10 +891,11 @@ 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 @@ -889,11 +908,11 @@ intel_aes_encrypt_ecb_192: 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 @@ -1033,11 +1052,11 @@ intel_aes_encrypt_ecb_192: 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 @@ -1067,8 +1086,8 @@ intel_aes_encrypt_ecb_192: .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 @@ -1079,10 +1098,11 @@ 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 @@ -1095,11 +1115,11 @@ intel_aes_decrypt_ecb_192: 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 @@ -1239,11 +1259,11 @@ intel_aes_decrypt_ecb_192: 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 @@ -1273,8 +1293,8 @@ intel_aes_decrypt_ecb_192: .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 @@ -1285,17 +1305,18 @@ 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 @@ -1336,8 +1357,8 @@ intel_aes_encrypt_cbc_192: .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) @@ -1350,10 +1371,11 @@ 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 @@ -1367,9 +1389,9 @@ intel_aes_decrypt_cbc_192: 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 @@ -1525,10 +1547,10 @@ intel_aes_decrypt_cbc_192: 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 @@ -1561,8 +1583,8 @@ intel_aes_decrypt_cbc_192: 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) @@ -1705,10 +1727,11 @@ 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 @@ -1721,11 +1744,11 @@ intel_aes_encrypt_ecb_256: 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 @@ -1884,11 +1907,11 @@ intel_aes_encrypt_ecb_256: 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 @@ -1924,8 +1947,8 @@ intel_aes_encrypt_ecb_256: .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 @@ -1936,10 +1959,11 @@ 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 @@ -1952,11 +1976,11 @@ intel_aes_decrypt_ecb_256: 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 @@ -2115,11 +2139,11 @@ intel_aes_decrypt_ecb_256: 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 @@ -2155,8 +2179,8 @@ intel_aes_decrypt_ecb_256: .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 @@ -2167,17 +2191,18 @@ 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 @@ -2223,8 +2248,8 @@ intel_aes_encrypt_cbc_256: .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) @@ -2237,10 +2262,11 @@ 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 @@ -2256,11 +2282,11 @@ intel_aes_decrypt_cbc_256: 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 @@ -2435,11 +2461,11 @@ intel_aes_decrypt_cbc_256: 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 @@ -2477,8 +2503,8 @@ intel_aes_decrypt_cbc_256: 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) diff --git a/security/nss/lib/freebl/ldvector.c b/security/nss/lib/freebl/ldvector.c index 1d9affec234e..e11e4f6ae622 100644 --- a/security/nss/lib/freebl/ldvector.c +++ b/security/nss/lib/freebl/ldvector.c @@ -286,9 +286,17 @@ static const struct FREEBLVectorStr vector = 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 * diff --git a/security/nss/lib/freebl/loader.c b/security/nss/lib/freebl/loader.c index 12fe56003240..33075c19fb46 100644 --- a/security/nss/lib/freebl/loader.c +++ b/security/nss/lib/freebl/loader.c @@ -2128,3 +2128,59 @@ SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams, 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); +} diff --git a/security/nss/lib/freebl/loader.h b/security/nss/lib/freebl/loader.h index 65cfd76dea6c..9f533efd3911 100644 --- a/security/nss/lib/freebl/loader.h +++ b/security/nss/lib/freebl/loader.h @@ -10,7 +10,7 @@ #include "blapi.h" -#define FREEBL_VERSION 0x0311 +#define FREEBL_VERSION 0x0312 struct FREEBLVectorStr { @@ -707,6 +707,33 @@ struct FREEBLVectorStr { /* 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. */ }; diff --git a/security/nss/lib/freebl/manifest.mn b/security/nss/lib/freebl/manifest.mn index 1137e8521b5c..73e73ef8a83b 100644 --- a/security/nss/lib/freebl/manifest.mn +++ b/security/nss/lib/freebl/manifest.mn @@ -56,6 +56,7 @@ EXPORTS = \ PRIVATE_EXPORTS = \ alghmac.h \ blapi.h \ + chacha20poly1305.h \ hmacct.h \ secmpi.h \ secrng.h \ @@ -101,6 +102,7 @@ CSRCS = \ desblapi.c \ des.c \ drbg.c \ + chacha20poly1305.c \ cts.c \ ctr.c \ gcm.c \ diff --git a/security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c b/security/nss/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c new file mode 100644 index 000000000000..38cbf35fdac9 --- /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 +#include + +#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))); +} diff --git a/security/nss/lib/freebl/poly1305.c b/security/nss/lib/freebl/poly1305.c new file mode 100644 index 000000000000..da0ab6d78747 --- /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 + +#include "poly1305.h" + +#if defined(_MSC_VER) && _MSC_VER < 1600 +#include "prtypes.h" +typedef PRUint32 uint32_t; +typedef PRUint64 uint64_t; +#else +#include +#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); +} diff --git a/security/nss/lib/freebl/poly1305.h b/security/nss/lib/freebl/poly1305.h new file mode 100644 index 000000000000..0a463483fc1d --- /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_ */ diff --git a/security/nss/lib/pk11wrap/pk11mech.c b/security/nss/lib/pk11wrap/pk11mech.c index 29e86e644525..bab17e4e40c6 100644 --- a/security/nss/lib/pk11wrap/pk11mech.c +++ b/security/nss/lib/pk11wrap/pk11mech.c @@ -152,6 +152,8 @@ PK11_GetKeyMechanism(CK_KEY_TYPE type) 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: @@ -219,6 +221,9 @@ PK11_GetKeyType(CK_MECHANISM_TYPE type,unsigned long len) 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: @@ -431,6 +436,8 @@ PK11_GetKeyGenWithSize(CK_MECHANISM_TYPE type, int size) 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: diff --git a/security/nss/lib/pk11wrap/pk11pars.c b/security/nss/lib/pk11wrap/pk11pars.c index 51160bbda1ca..8dd07e7e5e41 100644 --- a/security/nss/lib/pk11wrap/pk11pars.c +++ b/security/nss/lib/pk11wrap/pk11pars.c @@ -354,6 +354,7 @@ static const oidValDef algOptList[] = { {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}, diff --git a/security/nss/lib/pkcs7/p7local.c b/security/nss/lib/pkcs7/p7local.c index 5e67a0ebaada..4d99384fc572 100644 --- a/security/nss/lib/pkcs7/p7local.c +++ b/security/nss/lib/pkcs7/p7local.c @@ -711,7 +711,7 @@ sec_PKCS7Encrypt (sec_PKCS7CipherObject *obj, unsigned char *output, } 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); diff --git a/security/nss/lib/softoken/pkcs11.c b/security/nss/lib/softoken/pkcs11.c index 97d6d3f377c2..443a09cca9ce 100644 --- a/security/nss/lib/softoken/pkcs11.c +++ b/security/nss/lib/softoken/pkcs11.c @@ -370,6 +370,11 @@ static const struct mechanismList mechanisms[] = { {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}, diff --git a/security/nss/lib/softoken/pkcs11c.c b/security/nss/lib/softoken/pkcs11c.c index ace74961d267..f0d36cc71f3f 100644 --- a/security/nss/lib/softoken/pkcs11c.c +++ b/security/nss/lib/softoken/pkcs11c.c @@ -665,6 +665,97 @@ sftk_RSADecryptOAEP(SFTKOAEPDecryptInfo *info, unsigned char *output, 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. @@ -882,7 +973,6 @@ sftk_CryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, 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) { @@ -1058,6 +1148,34 @@ finish_des: 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 */ @@ -3655,6 +3773,10 @@ nsc_SetupBulkKeyGen(CK_MECHANISM_TYPE mechanism, CK_KEY_TYPE *key_type, *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; @@ -3916,6 +4038,7 @@ CK_RV NSC_GenerateKey(CK_SESSION_HANDLE hSession, 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 @@ -4057,14 +4180,15 @@ jpake1: */ 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 (crv == CKR_OK && sftk_isTrue(key,CKA_SENSITIVE)) { + crv = 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)); + 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; } - - *phKey = key->handle; sftk_FreeObject(key); return crv; } @@ -4863,41 +4987,46 @@ ecgn_done: 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 (sftk_isTrue(publicKey,CKA_SENSITIVE)) { - sftk_forceAttribute(publicKey,CKA_ALWAYS_SENSITIVE, + if (crv == CKR_OK && sftk_isTrue(publicKey,CKA_SENSITIVE)) { + crv = sftk_forceAttribute(publicKey,CKA_ALWAYS_SENSITIVE, &cktrue,sizeof(CK_BBOOL)); } - if (!sftk_isTrue(privateKey,CKA_EXTRACTABLE)) { - sftk_forceAttribute(privateKey,CKA_NEVER_EXTRACTABLE, + if (crv == CKR_OK && !sftk_isTrue(privateKey,CKA_EXTRACTABLE)) { + crv = sftk_forceAttribute(privateKey,CKA_NEVER_EXTRACTABLE, &cktrue,sizeof(CK_BBOOL)); } - if (!sftk_isTrue(publicKey,CKA_EXTRACTABLE)) { - sftk_forceAttribute(publicKey,CKA_NEVER_EXTRACTABLE, + if (crv == CKR_OK && !sftk_isTrue(publicKey,CKA_EXTRACTABLE)) { + crv = 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; diff --git a/security/nss/lib/softoken/pkcs11i.h b/security/nss/lib/softoken/pkcs11i.h index 1023a0012d67..8f16357cecbe 100644 --- a/security/nss/lib/softoken/pkcs11i.h +++ b/security/nss/lib/softoken/pkcs11i.h @@ -14,6 +14,7 @@ #include "pkcs11t.h" #include "sftkdbt.h" +#include "chacha20poly1305.h" #include "hasht.h" /* @@ -104,6 +105,7 @@ 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 */ @@ -399,6 +401,16 @@ struct SFTKSSLMACInfoStr { 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 */ diff --git a/security/nss/lib/ssl/SSLerrs.h b/security/nss/lib/ssl/SSLerrs.h index 56d81f2dadf1..15bf0b404659 100644 --- a/security/nss/lib/ssl/SSLerrs.h +++ b/security/nss/lib/ssl/SSLerrs.h @@ -5,462 +5,463 @@ /* 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.") diff --git a/security/nss/lib/ssl/authcert.c b/security/nss/lib/ssl/authcert.c index bd0f6ed49a2b..85bbe8bbbdc0 100644 --- a/security/nss/lib/ssl/authcert.c +++ b/security/nss/lib/ssl/authcert.c @@ -16,74 +16,76 @@ #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); - } - } - } 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; -} + 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); + } + } + if (rv == SECSuccess) { + *pRetCert = cert; + *pRetKey = privkey; + } + return rv; +} diff --git a/security/nss/lib/ssl/cmpcert.c b/security/nss/lib/ssl/cmpcert.c index 6d8423822d51..168a6983cfc9 100644 --- a/security/nss/lib/ssl/cmpcert.c +++ b/security/nss/lib/ssl/cmpcert.c @@ -18,73 +18,75 @@ /* * 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; - - /* 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; + 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; + } + + 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; } - diff --git a/security/nss/lib/ssl/derive.c b/security/nss/lib/ssl/derive.c index 8b58b800d713..d325470515e6 100644 --- a/security/nss/lib/ssl/derive.c +++ b/security/nss/lib/ssl/derive.c @@ -5,9 +5,9 @@ * 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" @@ -26,22 +26,22 @@ /* 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 /* @@ -50,100 +50,99 @@ buildSSLKey(unsigned char * keyBlock, unsigned int keyLen, SECItem * result, #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)); @@ -152,53 +151,55 @@ ssl3_KeyAndMacDeriveBypass( * 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); @@ -208,208 +209,212 @@ ssl3_KeyAndMacDeriveBypass( * 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; @@ -419,177 +424,183 @@ key_and_mac_derive_fail: 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, ¶ms, 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 @@ -600,282 +611,286 @@ SSL_CanBypass(CERTCertificate *cert, SECKEYPrivateKey *srvPrivkey, *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; - /* 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, ¶m, 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; - } + slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); + if (slot == NULL) { + PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); + 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); + /* 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, ¶m, 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); } #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: - if (pms) - PK11_FreeSymKey(pms); - /* Check for NULL to avoid double free. - * SECItem_FreeItem sets data NULL in secitem.c#265 +done: + if (pms) + PK11_FreeSymKey(pms); + + /* 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) { @@ -885,12 +900,10 @@ SSL_CanBypass(CERTCertificate *cert, SECKEYPrivateKey *srvPrivkey, #endif /* NSS_DISABLE_ECC */ if (srvPubkey) { - SECKEY_DestroyPublicKey(srvPubkey); - srvPubkey = NULL; + SECKEY_DestroyPublicKey(srvPubkey); + srvPubkey = NULL; } - return rv; #endif /* NO_PKCS11_BYPASS */ } - diff --git a/security/nss/lib/ssl/dtlscon.c b/security/nss/lib/ssl/dtlscon.c index 6e42079c301a..5044c7c805f7 100644 --- a/security/nss/lib/ssl/dtlscon.c +++ b/security/nss/lib/ssl/dtlscon.c @@ -11,7 +11,7 @@ #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); @@ -20,10 +20,10 @@ 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 @@ -104,9 +104,9 @@ dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv) /* 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)); @@ -190,8 +190,8 @@ dtls_FreeHandshakeMessages(PRCList *list) * 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) @@ -229,7 +229,7 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) 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); @@ -263,9 +263,9 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * 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; @@ -287,13 +287,15 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) /* 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)); @@ -304,24 +306,26 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) */ 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 @@ -336,7 +340,8 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) 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 @@ -345,7 +350,8 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * * XXX OK for now. Maybe do something smarter at some point? */ - } else { + } + else { /* Case 1 * * Buffer the fragment for reassembly @@ -404,7 +410,8 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * fragment */ ss->ssl3.hs.recvdHighWater = fragment_offset + fragment_length; - } else { + } + else { for (offset = fragment_offset; offset < fragment_offset + fragment_length; offset++) { @@ -422,7 +429,8 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) if (ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] & OFFSET_MASK(offset)) { ss->ssl3.hs.recvdHighWater++; - } else { + } + else { break; } } @@ -455,7 +463,7 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) 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 */ @@ -468,8 +476,9 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * 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; @@ -482,7 +491,8 @@ SECStatus dtls_QueueMessage(sslSocket *ss, SSL3ContentType type, if (!msg) { PORT_SetError(SEC_ERROR_NO_MEMORY); rv = SECFailure; - } else { + } + else { PR_APPEND_LINK(&msg->link, &ss->ssl3.hs.lastMessageFlight); } @@ -639,7 +649,7 @@ dtls_TransmitMessageFlight(sslSocket *ss) 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) { @@ -649,7 +659,8 @@ dtls_TransmitMessageFlight(sslSocket *ss) } 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 @@ -699,12 +710,12 @@ dtls_TransmitMessageFlight(sslSocket *ss) /* 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); @@ -716,7 +727,7 @@ dtls_TransmitMessageFlight(sslSocket *ss) 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) { @@ -752,8 +763,8 @@ dtls_TransmitMessageFlight(sslSocket *ss) * * Called from dtls_TransmitMessageFlight() */ -static -SECStatus dtls_SendSavedWriteData(sslSocket *ss) +static SECStatus +dtls_SendSavedWriteData(sslSocket *ss) { PRInt32 sent; @@ -784,18 +795,18 @@ SECStatus dtls_SendSavedWriteData(sslSocket *ss) * 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., @@ -814,7 +825,8 @@ dtls_CompressMACEncryptRecord(sslSocket * ss, cwSpec = ss->ssl3.pwSpec; else cwSpec = NULL; - } else { + } + else { cwSpec = ss->ssl3.cwSpec; } @@ -823,10 +835,12 @@ dtls_CompressMACEncryptRecord(sslSocket * ss, 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); } @@ -965,7 +979,7 @@ dtls_SetMTU(sslSocket *ss, PRUint16 advertised) } /* 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)); } @@ -976,27 +990,27 @@ dtls_SetMTU(sslSocket *ss, PRUint16 advertised) 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 && @@ -1007,23 +1021,22 @@ dtls_HandleHelloVerifyRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) /* 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; @@ -1127,7 +1140,7 @@ dtls_RecordSetRecvd(DTLSRecvdRecords *records, PRUint64 seq) SECStatus DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout) { - sslSocket * ss = NULL; + sslSocket *ss = NULL; PRIntervalTime elapsed; PRIntervalTime desired; @@ -1147,7 +1160,8 @@ DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout) if (elapsed > desired) { /* Timer expired */ *timeout = PR_INTERVAL_NO_WAIT; - } else { + } + else { *timeout = desired - elapsed; } @@ -1175,7 +1189,8 @@ dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *crSpec, 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; } @@ -1184,7 +1199,8 @@ dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *crSpec, 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; } diff --git a/security/nss/lib/ssl/notes.txt b/security/nss/lib/ssl/notes.txt index a71c08ef2a56..cf514ad20f26 100644 --- a/security/nss/lib/ssl/notes.txt +++ b/security/nss/lib/ssl/notes.txt @@ -10,49 +10,49 @@ 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. --------------------------------------------------------------------------- @@ -65,51 +65,51 @@ 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 @@ -118,17 +118,17 @@ 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 diff --git a/security/nss/lib/ssl/os2_err.c b/security/nss/lib/ssl/os2_err.c index a69ca91d9cee..ae566f687a70 100644 --- a/security/nss/lib/ssl/os2_err.c +++ b/security/nss/lib/ssl/os2_err.c @@ -1,12 +1,12 @@ /* -*- 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/. */ @@ -15,7 +15,6 @@ #include "prlog.h" #include - /* * Based on win32err.c * OS2TODO Stub everything for now to build. HCT @@ -24,79 +23,94 @@ /* 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); } @@ -104,177 +118,213 @@ void nss_MD_os2_map_fsync_error(PRInt32 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); } - diff --git a/security/nss/lib/ssl/os2_err.h b/security/nss/lib/ssl/os2_err.h index 3052d54a7af5..15e47411a13d 100644 --- a/security/nss/lib/ssl/os2_err.h +++ b/security/nss/lib/ssl/os2_err.h @@ -1,11 +1,11 @@ /* * 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/. */ diff --git a/security/nss/lib/ssl/preenc.h b/security/nss/lib/ssl/preenc.h index af2475ddd2be..bebff89e22ca 100644 --- a/security/nss/lib/ssl/preenc.h +++ b/security/nss/lib/ssl/preenc.h @@ -25,89 +25,89 @@ 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 PRE_BLOCK_SIZE 8 +#define PE_BASE_HEADER_LEN 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); diff --git a/security/nss/lib/ssl/prelib.c b/security/nss/lib/ssl/prelib.c index a15174a31b19..4db9ffe699d2 100644 --- a/security/nss/lib/ssl/prelib.c +++ b/security/nss/lib/ssl/prelib.c @@ -17,18 +17,18 @@ #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; } - - diff --git a/security/nss/lib/ssl/ssl.def b/security/nss/lib/ssl/ssl.def index 2c1d009950a1..a05cb607129d 100644 --- a/security/nss/lib/ssl/ssl.def +++ b/security/nss/lib/ssl/ssl.def @@ -194,3 +194,9 @@ SSL_SetSignedCertTimestamps; ;+ local: ;+*; ;+}; +;+NSS_3.23 { # NSS 3.23 release +;+ global: +SSL_SetDowngradeCheckVersion; +;+ local: +;+*; +;+}; diff --git a/security/nss/lib/ssl/ssl.h b/security/nss/lib/ssl/ssl.h index c38460e544f5..3974ee8bdfbc 100644 --- a/security/nss/lib/ssl/ssl.h +++ b/security/nss/lib/ssl/ssl.h @@ -15,7 +15,7 @@ #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) @@ -38,7 +38,7 @@ SSL_IMPORT const PRUint16 SSL_NumImplementedCiphers; 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 @@ -55,72 +55,72 @@ 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 @@ -160,7 +160,7 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd); * 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. @@ -189,8 +189,8 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd); */ #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. */ @@ -206,7 +206,7 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd); /* 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); @@ -229,13 +229,13 @@ SSL_IMPORT SECStatus SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHan * * 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 @@ -263,14 +263,14 @@ SSL_IMPORT SECStatus SSL_SetNextProtoCallback(PRFileDesc *fd, * 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 @@ -281,19 +281,19 @@ typedef enum SSLNextProtoState { * 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); @@ -451,11 +451,11 @@ SSL_IMPORT SECStatus SSL_VersionRangeSetDefault( /* 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]. @@ -472,25 +472,25 @@ SSL_IMPORT SECStatus SSL_SetDowngradeCheckVersion(PRFileDesc *fd, /* 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 */ @@ -528,22 +528,22 @@ SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, ** 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); @@ -552,7 +552,7 @@ SSL_IMPORT CERTCertificate *SSL_PeerCertificate(PRFileDesc *fd); ** 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); @@ -572,7 +572,7 @@ SSL_IMPORT CERTCertList *SSL_PeerCertificateChain(PRFileDesc *fd); * 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 @@ -589,7 +589,7 @@ SSL_IMPORT const SECItemArray * SSL_PeerStapledOCSPResponses(PRFileDesc *fd); * * 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 @@ -599,7 +599,7 @@ SSL_IMPORT const SECItem * SSL_PeerSignedCertTimestamps(PRFileDesc *fd); */ SSL_IMPORT SECStatus SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, - SSLKEAType kea); + SSLKEAType kea); /* * SSL_SetSignedCertTimestamps stores serialized signed_certificate_timestamp @@ -644,41 +644,40 @@ SSL_SetSignedCertTimestamps(PRFileDesc *fd, const SECItem *scts, ** 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. @@ -706,10 +705,10 @@ SSL_IMPORT SECStatus SSL_GetClientAuthDataHook(PRFileDesc *fd, ** 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 @@ -718,13 +717,13 @@ typedef PRInt32 (PR_CALLBACK *SSLSNISocketConfig)(PRFileDesc *fd, ** 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); @@ -737,8 +736,8 @@ 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); @@ -757,9 +756,9 @@ SSL_IMPORT SECStatus SSL_SetPKCS11PinArg(PRFileDesc *fd, void *a); ** 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 @@ -767,8 +766,8 @@ SSL_IMPORT SECStatus SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, ** 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. @@ -782,63 +781,63 @@ SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert, /* ** 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 @@ -850,10 +849,10 @@ SSL_IMPORT SECStatus SSL_InheritMPServerSIDCache(const char * envString); ** 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 @@ -866,7 +865,7 @@ SSL_IMPORT SECStatus SSL_HandshakeCallback(PRFileDesc *fd, ** 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( @@ -882,10 +881,10 @@ SSL_IMPORT SECStatus SSL_RecommendedCanFalseStart(PRFileDesc *fd, /* ** 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); @@ -897,12 +896,11 @@ SSL_IMPORT SECStatus SSL_ReHandshakeWithTimeout(PRFileDesc *fd, PRBool flushCache, PRIntervalTime timeout); - -#ifdef SSL_DEPRECATED_FUNCTION +#ifdef SSL_DEPRECATED_FUNCTION /* deprecated! ** For the server, request a new handshake. For the client, begin a new -** handshake. Flushes SSL3 session cache entry first, ensuring that a -** full handshake will be done. +** handshake. Flushes SSL3 session cache entry first, ensuring that a +** full handshake will be done. ** This call is equivalent to SSL_ReHandshake(fd, PR_TRUE) */ SSL_IMPORT SECStatus SSL_RedoHandshake(PRFileDesc *fd); @@ -952,11 +950,11 @@ SSL_IMPORT SECStatus SSL_ShutdownServerSessionIDCache(void); SSL_IMPORT SECStatus SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID); /* -** Reveal the security information for the peer. +** Reveal the security information for the peer. */ -SSL_IMPORT CERTCertificate * SSL_RevealCert(PRFileDesc * socket); -SSL_IMPORT void * SSL_RevealPinArg(PRFileDesc * socket); -SSL_IMPORT char * SSL_RevealURL(PRFileDesc * socket); +SSL_IMPORT CERTCertificate *SSL_RevealCert(PRFileDesc *socket); +SSL_IMPORT void *SSL_RevealPinArg(PRFileDesc *socket); +SSL_IMPORT char *SSL_RevealURL(PRFileDesc *socket); /* This callback may be passed to the SSL library via a call to * SSL_GetClientAuthDataHook() for each SSL client socket. @@ -964,14 +962,14 @@ SSL_IMPORT char * SSL_RevealURL(PRFileDesc * socket); * (if any) to use to respond to a request for client authentication. * If arg is non-NULL, it is a pointer to a NULL-terminated string containing * the nickname of the cert/key pair to use. - * If arg is NULL, this function will search the cert and key databases for + * If arg is NULL, this function will search the cert and key databases for * a suitable match and send it if one is found. */ SSL_IMPORT SECStatus -NSS_GetClientAuthData(void * arg, - PRFileDesc * socket, - struct CERTDistNamesStr * caNames, - struct CERTCertificateStr ** pRetCert, +NSS_GetClientAuthData(void *arg, + PRFileDesc *socket, + struct CERTDistNamesStr *caNames, + struct CERTCertificateStr **pRetCert, struct SECKEYPrivateKeyStr **pRetKey); /* @@ -985,8 +983,8 @@ NSS_GetClientAuthData(void * arg, ** Otherwise returns SECFailure. */ SSL_IMPORT SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, - const PRUint16 *ciphers, - unsigned int numCiphers); + const PRUint16 *ciphers, + unsigned int numCiphers); /* ** Get the selected DTLS-SRTP cipher suite (if any). @@ -994,21 +992,21 @@ SSL_IMPORT SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, ** Returns SECFailure if not negotiated. */ SSL_IMPORT SECStatus SSL_GetSRTPCipher(PRFileDesc *fd, - PRUint16 *cipher); + PRUint16 *cipher); /* * 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. * Used by NSS_GetClientAuthData. May be used by other callback functions. */ -SSL_IMPORT SECStatus NSS_CmpCertChainWCANames(CERTCertificate *cert, - CERTDistNames *caNames); +SSL_IMPORT SECStatus NSS_CmpCertChainWCANames(CERTCertificate *cert, + CERTDistNames *caNames); -/* +/* * Returns key exchange type of the keys in an SSL server certificate. */ -SSL_IMPORT SSLKEAType NSS_FindCertKEAType(CERTCertificate * cert); +SSL_IMPORT SSLKEAType NSS_FindCertKEAType(CERTCertificate *cert); /* Set cipher policies to a predefined Domestic (U.S.A.) policy. * This essentially allows all supported ciphers. @@ -1022,16 +1020,18 @@ SSL_IMPORT SECStatus NSS_SetDomesticPolicy(void); SSL_IMPORT SECStatus NSS_SetExportPolicy(void); /* Set cipher policies to a predefined Policy that is exportable from the USA - * according to present U.S. policies as we understand them, and that the + * according to present U.S. policies as we understand them, and that the * nation of France will permit to be imported into their country. * It is the same as NSS_SetDomesticPolicy now. */ SSL_IMPORT SECStatus NSS_SetFrancePolicy(void); -SSL_IMPORT SSL3Statistics * SSL_GetStatistics(void); +SSL_IMPORT SSL3Statistics *SSL_GetStatistics(void); /* Report more information than SSL_SecurityStatus. - * Caller supplies the info struct. This function fills it in. + * Caller supplies the info struct. This function fills it in. Caller should + * pass sizeof(SSLChannelInfo) as the |len| argument. + * * The information here will be zeroed prior to details being confirmed. The * details are confirmed either when a Finished message is received, or - for a * client - when the second flight of messages have been sent. This function @@ -1041,8 +1041,9 @@ SSL_IMPORT SSL3Statistics * SSL_GetStatistics(void); SSL_IMPORT SECStatus SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len); /* Get preliminary information about a channel. - * This function can be called prior to handshake details being confirmed (see - * SSL_GetChannelInfo above for what that means). Thus, information provided by + * Caller supplies the info struct. This function fills it in. Caller should + * pass sizeof(SSLPreliminaryChannelInfo) as the |len| argument. + * * this function is available to SSLAuthCertificate, SSLGetClientAuthData, * SSLSNISocketConfig, and other callbacks that might be called during the * processing of the first flight of client of server handshake messages. @@ -1052,8 +1053,12 @@ SSL_IMPORT SECStatus SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, SSLPreliminaryChannelInfo *info, PRUintn len); -SSL_IMPORT SECStatus SSL_GetCipherSuiteInfo(PRUint16 cipherSuite, - SSLCipherSuiteInfo *info, PRUintn len); +/* Get information about cipher suite with id of |cipherSuite|. + * Caller supplies the info struct. This function fills it in. Caller should + * pass sizeof(SSLCipherSuiteInfo) as the |len| argument. + */ +SSL_IMPORT SECStatus SSL_GetCipherSuiteInfo(PRUint16 cipherSuite, + SSLCipherSuiteInfo *info, PRUintn len); /* Returnes negotiated through SNI host info. */ SSL_IMPORT SECItem *SSL_GetNegotiatedHostInfo(PRFileDesc *fd); @@ -1077,7 +1082,7 @@ SSL_IMPORT SECStatus SSL_ExportKeyingMaterial(PRFileDesc *fd, ** Return a new reference to the certificate that was most recently sent ** to the peer on this SSL/TLS connection, or NULL if none has been sent. */ -SSL_IMPORT CERTCertificate * SSL_LocalCertificate(PRFileDesc *fd); +SSL_IMPORT CERTCertificate *SSL_LocalCertificate(PRFileDesc *fd); /* Test an SSL configuration to see if SSL_BYPASS_PKCS11 can be turned on. ** Check the key exchange algorithm for each cipher in the list to see if @@ -1101,20 +1106,20 @@ SSL_IMPORT CERTCertificate * SSL_LocalCertificate(PRFileDesc *fd); **/ /* protocol mask bits */ -#define SSL_CBP_SSL3 0x0001 /* test SSL v3 mechanisms */ -#define SSL_CBP_TLS1_0 0x0002 /* test TLS v1.0 mechanisms */ +#define SSL_CBP_SSL3 0x0001 /* test SSL v3 mechanisms */ +#define SSL_CBP_TLS1_0 0x0002 /* test TLS v1.0 mechanisms */ SSL_IMPORT SECStatus SSL_CanBypass(CERTCertificate *cert, SECKEYPrivateKey *privKey, - PRUint32 protocolmask, - PRUint16 *ciphers, int nciphers, + PRUint32 protocolmask, + PRUint16 *ciphers, int nciphers, PRBool *pcanbypass, void *pwArg); /* ** Did the handshake with the peer negotiate the given extension? ** Output parameter valid only if function returns SECSuccess */ -SSL_IMPORT SECStatus SSL_HandshakeNegotiatedExtension(PRFileDesc * socket, +SSL_IMPORT SECStatus SSL_HandshakeNegotiatedExtension(PRFileDesc *socket, SSLExtensionType extId, PRBool *yes); @@ -1204,7 +1209,7 @@ extern const char *NSSSSL_GetVersion(void); * connection. */ SSL_IMPORT SECStatus SSL_AuthCertificateComplete(PRFileDesc *fd, - PRErrorCode error); + PRErrorCode error); SEC_END_PROTOS #endif /* __ssl_h_ */ diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c index cfed4de70a9b..c40fc71224d0 100644 --- a/security/nss/lib/ssl/ssl3con.c +++ b/security/nss/lib/ssl/ssl3con.c @@ -10,7 +10,7 @@ #include "cert.h" #include "ssl.h" -#include "cryptohi.h" /* for DSAU_ stuff */ +#include "cryptohi.h" /* for DSAU_ stuff */ #include "keyhi.h" #include "secder.h" #include "secitem.h" @@ -39,27 +39,29 @@ #endif #ifndef PK11_SETATTRS -#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ - (x)->pValue=(v); (x)->ulValueLen = (l); +#define PK11_SETATTRS(x, id, v, l) \ + (x)->type = (id); \ + (x)->pValue = (v); \ + (x)->ulValueLen = (l); #endif static SECStatus ssl3_AuthCertificate(sslSocket *ss); -static void ssl3_CleanupPeerCerts(sslSocket *ss); +static void ssl3_CleanupPeerCerts(sslSocket *ss); static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, - PK11SlotInfo * serverKeySlot); + PK11SlotInfo *serverKeySlot); static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms); static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss); -static SECStatus ssl3_HandshakeFailure( sslSocket *ss); -static SECStatus ssl3_InitState( sslSocket *ss); +static SECStatus ssl3_HandshakeFailure(sslSocket *ss); +static SECStatus ssl3_InitState(sslSocket *ss); static SECStatus ssl3_SendCertificateRequest(sslSocket *ss); -static SECStatus ssl3_SendNextProto( sslSocket *ss); -static SECStatus ssl3_SendFinished( sslSocket *ss, PRInt32 flags); -static SECStatus ssl3_SendServerHelloDone( sslSocket *ss); -static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss); -static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss, - const unsigned char *b, - unsigned int l); +static SECStatus ssl3_SendNextProto(sslSocket *ss); +static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags); +static SECStatus ssl3_SendServerHelloDone(sslSocket *ss); +static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss); +static SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss, + const unsigned char *b, + unsigned int l); static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length, @@ -67,18 +69,18 @@ static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, - int maxOutputLen, const unsigned char *input, - int inputLen); + int maxOutputLen, const unsigned char *input, + int inputLen); #ifndef NO_PKCS11_BYPASS static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, - unsigned char *out, int *outlen, int maxout, - const unsigned char *in, int inlen, - const unsigned char *additionalData, - int additionalDataLen); + unsigned char *out, int *outlen, int maxout, + const unsigned char *in, int inlen, + const unsigned char *additionalData, + int additionalDataLen); #endif #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ -#define MIN_SEND_BUF_LENGTH 4000 +#define MIN_SEND_BUF_LENGTH 4000 /* This list of SSL3 cipher suites is sorted in descending order of * precedence (desirability). It only includes cipher suites we implement. @@ -88,12 +90,15 @@ static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, * Important: See bug 946147 before enabling, reordering, or adding any cipher * suites to this list. */ +/* clang-format off */ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { /* cipher_suite policy enabled isPresent */ #ifndef NSS_DISABLE_ECC { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, + { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, + { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around * bug 946147. */ @@ -110,6 +115,7 @@ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { #endif /* NSS_DISABLE_ECC */ { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, + { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE, PR_FALSE}, { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, @@ -177,20 +183,21 @@ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, }; +/* clang-format on */ static const SSLSignatureAndHashAlg defaultSignatureAlgorithms[] = { - {ssl_hash_sha256, ssl_sign_rsa}, - {ssl_hash_sha384, ssl_sign_rsa}, - {ssl_hash_sha512, ssl_sign_rsa}, - {ssl_hash_sha1, ssl_sign_rsa}, + { ssl_hash_sha256, ssl_sign_rsa }, + { ssl_hash_sha384, ssl_sign_rsa }, + { ssl_hash_sha512, ssl_sign_rsa }, + { ssl_hash_sha1, ssl_sign_rsa }, #ifndef NSS_DISABLE_ECC - {ssl_hash_sha256, ssl_sign_ecdsa}, - {ssl_hash_sha384, ssl_sign_ecdsa}, - {ssl_hash_sha512, ssl_sign_ecdsa}, - {ssl_hash_sha1, ssl_sign_ecdsa}, + { ssl_hash_sha256, ssl_sign_ecdsa }, + { ssl_hash_sha384, ssl_sign_ecdsa }, + { ssl_hash_sha512, ssl_sign_ecdsa }, + { ssl_hash_sha1, ssl_sign_ecdsa }, #endif - {ssl_hash_sha256, ssl_sign_dsa}, - {ssl_hash_sha1, ssl_sign_dsa} + { ssl_hash_sha256, ssl_sign_dsa }, + { ssl_hash_sha1, ssl_sign_dsa } }; PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureAlgorithms) <= MAX_SIGNATURE_ALGORITHMS); @@ -198,7 +205,8 @@ PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureAlgorithms) <= /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order. */ #ifdef DEBUG -void ssl3_CheckCipherSuiteOrderConsistency() +void +ssl3_CheckCipherSuiteOrderConsistency() { unsigned int i; @@ -217,7 +225,7 @@ void ssl3_CheckCipherSuiteOrderConsistency() * precedence (desirability). It only includes compression methods we * implement. */ -static const /*SSLCompressionMethod*/ PRUint8 compressions [] = { +static const /*SSLCompressionMethod*/ PRUint8 compressions[] = { #ifdef NSS_SSL_ENABLE_ZLIB ssl_compression_deflate, #endif @@ -233,21 +241,21 @@ static PRBool compressionEnabled(sslSocket *ss, SSLCompressionMethod compression) { switch (compression) { - case ssl_compression_null: - return PR_TRUE; /* Always enabled */ + case ssl_compression_null: + return PR_TRUE; /* Always enabled */ #ifdef NSS_SSL_ENABLE_ZLIB - case ssl_compression_deflate: - if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { - return ss->opt.enableDeflate; - } - return PR_FALSE; + case ssl_compression_deflate: + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + return ss->opt.enableDeflate; + } + return PR_FALSE; #endif - default: - return PR_FALSE; + default: + return PR_FALSE; } } -static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = { +static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = { ct_RSA_sign, #ifndef NSS_DISABLE_ECC ct_ECDSA_sign, @@ -255,8 +263,7 @@ static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = { ct_DSS_sign, }; -#define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ - +#define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ /* This global item is used only in servers. It is is initialized by ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest(). @@ -265,6 +272,7 @@ CERTDistNames *ssl3_server_ca_list = NULL; static SSL3Statistics ssl3stats; /* indexed by SSL3BulkCipher */ +/* clang-format off */ static const ssl3BulkCipherDef bulk_cipher_defs[] = { /* |--------- Lengths --------| */ /* cipher calg k s type i b t n o */ @@ -289,6 +297,7 @@ static const ssl3BulkCipherDef bulk_cipher_defs[] = { {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0, SEC_OID_CAMELLIA_256_CBC}, {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0, SEC_OID_SEED_CBC}, {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8, SEC_OID_AES_128_GCM}, + {cipher_chacha20, calg_chacha20, 32,32, type_aead, 12, 0,16, 0, SEC_OID_CHACHA20_POLY1305}, {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0, 0}, }; @@ -320,7 +329,7 @@ static const ssl3KEADef kea_defs[] = }; /* must use ssl_LookupCipherSuiteDef to access */ -static const ssl3CipherSuiteDef cipher_suite_defs[] = +static const ssl3CipherSuiteDef cipher_suite_defs[] = { /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */ @@ -371,33 +380,33 @@ static const ssl3CipherSuiteDef cipher_suite_defs[] = /* New TLS cipher suites */ - {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa}, - {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa}, - {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss}, - {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa}, + {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa}, + {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa}, + {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss}, + {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa}, {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa}, - {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa}, - {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa}, - {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss}, - {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa}, + {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa}, + {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa}, + {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss}, + {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa}, {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa}, #if 0 - {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss}, - {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa}, - {TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon}, - {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss}, - {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa}, - {TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon}, + {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss}, + {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa}, + {TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon}, + {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss}, + {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa}, + {TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon}, #endif - {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa}, + {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa}, {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa}, {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_dhe_dss}, {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_dhe_rsa}, - {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa}, + {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa}, {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_dhe_dss}, {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, @@ -420,6 +429,10 @@ static const ssl3CipherSuiteDef cipher_suite_defs[] = {TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_dss}, {TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_dss}, + {TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_dhe_rsa}, + {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_ecdhe_rsa}, + {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_ecdhe_ecdsa}, + #ifndef NSS_DISABLE_ECC {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, @@ -456,6 +469,7 @@ static const ssl3CipherSuiteDef cipher_suite_defs[] = #endif #endif /* NSS_DISABLE_ECC */ }; +/* clang-format on */ static const CK_MECHANISM_TYPE kea_alg_defs[] = { 0x80000000L, @@ -466,34 +480,36 @@ static const CK_MECHANISM_TYPE kea_alg_defs[] = { }; typedef struct SSLCipher2MechStr { - SSLCipherAlgorithm calg; - CK_MECHANISM_TYPE cmech; + SSLCipherAlgorithm calg; + CK_MECHANISM_TYPE cmech; } SSLCipher2Mech; /* indexed by type SSLCipherAlgorithm */ static const SSLCipher2Mech alg2Mech[] = { /* calg, cmech */ - { calg_null , (CK_MECHANISM_TYPE)0x80000000L }, - { calg_rc4 , CKM_RC4 }, - { calg_rc2 , CKM_RC2_CBC }, - { calg_des , CKM_DES_CBC }, - { calg_3des , CKM_DES3_CBC }, - { calg_idea , CKM_IDEA_CBC }, - { calg_fortezza , CKM_SKIPJACK_CBC64 }, - { calg_aes , CKM_AES_CBC }, - { calg_camellia , CKM_CAMELLIA_CBC }, - { calg_seed , CKM_SEED_CBC }, - { calg_aes_gcm , CKM_AES_GCM }, -/* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ + { calg_null, (CK_MECHANISM_TYPE)0x80000000L }, + { calg_rc4, CKM_RC4 }, + { calg_rc2, CKM_RC2_CBC }, + { calg_des, CKM_DES_CBC }, + { calg_3des, CKM_DES3_CBC }, + { calg_idea, CKM_IDEA_CBC }, + { calg_fortezza, CKM_SKIPJACK_CBC64 }, + { calg_aes, CKM_AES_CBC }, + { calg_camellia, CKM_CAMELLIA_CBC }, + { calg_seed, CKM_SEED_CBC }, + { calg_aes_gcm, CKM_AES_GCM }, + { calg_chacha20, CKM_NSS_CHACHA20_POLY1305 }, + /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ }; -#define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L -#define mmech_md5 CKM_SSL3_MD5_MAC -#define mmech_sha CKM_SSL3_SHA1_MAC +#define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L +#define mmech_md5 CKM_SSL3_MD5_MAC +#define mmech_sha CKM_SSL3_SHA1_MAC #define mmech_md5_hmac CKM_MD5_HMAC #define mmech_sha_hmac CKM_SHA_1_HMAC #define mmech_sha256_hmac CKM_SHA256_HMAC +/* clang-format off */ static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ /* mac mmech pad_size mac_size */ @@ -505,9 +521,10 @@ static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH, SEC_OID_HMAC_SHA256}, { mac_aead, mmech_invalid, 0, 0, 0 }, }; +/* clang-format on */ /* indexed by SSL3BulkCipher */ -const char * const ssl3_cipherName[] = { +const char *const ssl3_cipherName[] = { "NULL", "RC4", "RC4-40", @@ -527,37 +544,37 @@ const char * const ssl3_cipherName[] = { "missing" }; -const PRUint8 tls13_downgrade_random[] = {0x44, 0x4F, 0x57, 0x4E, - 0x47, 0x52, 0x44, 0x01}; -const PRUint8 tls12_downgrade_random[] = {0x44, 0x4F, 0x57, 0x4E, - 0x47, 0x52, 0x44, 0x00}; - +const PRUint8 tls13_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, + 0x47, 0x52, 0x44, 0x01 }; +const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, + 0x47, 0x52, 0x44, 0x00 }; #ifndef NSS_DISABLE_ECC -/* The ECCWrappedKeyInfo structure defines how various pieces of - * information are laid out within wrappedSymmetricWrappingkey - * for ECDH key exchange. Since wrappedSymmetricWrappingkey is - * a 512-byte buffer (see sslimpl.h), the variable length field +/* The ECCWrappedKeyInfo structure defines how various pieces of + * information are laid out within wrappedSymmetricWrappingkey + * for ECDH key exchange. Since wrappedSymmetricWrappingkey is + * a 512-byte buffer (see sslimpl.h), the variable length field * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes. * - * XXX For now, NSS only supports named elliptic curves of size 571 bits + * XXX For now, NSS only supports named elliptic curves of size 571 bits * or smaller. The public value will fit within 145 bytes and EC params * will fit within 12 bytes. We'll need to revisit this when NSS * supports arbitrary curves. */ -#define MAX_EC_WRAPPED_KEY_BUFLEN 504 +#define MAX_EC_WRAPPED_KEY_BUFLEN 504 typedef struct ECCWrappedKeyInfoStr { - PRUint16 size; /* EC public key size in bits */ - PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */ - PRUint16 pubValueLen; /* length (in bytes) of EC public value */ - PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */ + PRUint16 size; /* EC public key size in bits */ + PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */ + PRUint16 pubValueLen; /* length (in bytes) of EC public value */ + PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */ PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */ /* EC public-key params, the EC public value and the wrapped key */ } ECCWrappedKeyInfo; #endif /* NSS_DISABLE_ECC */ -CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg) +CK_MECHANISM_TYPE +ssl3_Alg2Mech(SSLCipherAlgorithm calg) { PORT_Assert(alg2Mech[calg].calg == calg); return alg2Mech[calg].cmech; @@ -568,25 +585,49 @@ CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg) static char * ssl3_DecodeHandshakeType(int msgType) { - char * rv; + char *rv; static char line[40]; - switch(msgType) { - case hello_request: rv = "hello_request (0)"; break; - case client_hello: rv = "client_hello (1)"; break; - case server_hello: rv = "server_hello (2)"; break; - case hello_verify_request: rv = "hello_verify_request (3)"; break; - case encrypted_extensions: rv = "encrypted_extensions (8)"; break; - case certificate: rv = "certificate (11)"; break; - case server_key_exchange: rv = "server_key_exchange (12)"; break; - case certificate_request: rv = "certificate_request (13)"; break; - case server_hello_done: rv = "server_hello_done (14)"; break; - case certificate_verify: rv = "certificate_verify (15)"; break; - case client_key_exchange: rv = "client_key_exchange (16)"; break; - case finished: rv = "finished (20)"; break; - default: - sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); - rv = line; + switch (msgType) { + case hello_request: + rv = "hello_request (0)"; + break; + case client_hello: + rv = "client_hello (1)"; + break; + case server_hello: + rv = "server_hello (2)"; + break; + case hello_verify_request: + rv = "hello_verify_request (3)"; + break; + case encrypted_extensions: + rv = "encrypted_extensions (8)"; + break; + case certificate: + rv = "certificate (11)"; + break; + case server_key_exchange: + rv = "server_key_exchange (12)"; + break; + case certificate_request: + rv = "certificate_request (13)"; + break; + case server_hello_done: + rv = "server_hello_done (14)"; + break; + case certificate_verify: + rv = "certificate_verify (15)"; + break; + case client_key_exchange: + rv = "client_key_exchange (16)"; + break; + case finished: + rv = "finished (20)"; + break; + default: + sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); + rv = line; } return rv; } @@ -594,26 +635,32 @@ ssl3_DecodeHandshakeType(int msgType) static char * ssl3_DecodeContentType(int msgType) { - char * rv; + char *rv; static char line[40]; - switch(msgType) { - case content_change_cipher_spec: - rv = "change_cipher_spec (20)"; break; - case content_alert: rv = "alert (21)"; break; - case content_handshake: rv = "handshake (22)"; break; - case content_application_data: - rv = "application_data (23)"; break; - default: - sprintf(line, "*UNKNOWN* record type! (%d)", msgType); - rv = line; + switch (msgType) { + case content_change_cipher_spec: + rv = "change_cipher_spec (20)"; + break; + case content_alert: + rv = "alert (21)"; + break; + case content_handshake: + rv = "handshake (22)"; + break; + case content_application_data: + rv = "application_data (23)"; + break; + default: + sprintf(line, "*UNKNOWN* record type! (%d)", msgType); + rv = line; } return rv; } #endif -SSL3Statistics * +SSL3Statistics * SSL_GetStatistics(void) { return &ssl3stats; @@ -629,14 +676,16 @@ typedef struct tooLongStr { #endif } tooLong; -void SSL_AtomicIncrementLong(long * x) +void +SSL_AtomicIncrementLong(long *x) { if ((sizeof *x) == sizeof(PRInt32)) { PR_ATOMIC_INCREMENT((PRInt32 *)x); - } else { - tooLong * tl = (tooLong *)x; - if (PR_ATOMIC_INCREMENT(&tl->low) == 0) - PR_ATOMIC_INCREMENT(&tl->high); + } + else { + tooLong *tl = (tooLong *)x; + if (PR_ATOMIC_INCREMENT(&tl->low) == 0) + PR_ATOMIC_INCREMENT(&tl->high); } } @@ -646,67 +695,67 @@ ssl3_CipherSuiteAllowedForVersionRange( const SSLVersionRange *vrange) { switch (cipherSuite) { - /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or - * later. This set of cipher suites is similar to, but different from, the - * set of cipher suites considered exportable by SSL_IsExportCipherSuite. - */ - case TLS_RSA_EXPORT_WITH_RC4_40_MD5: - case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: - /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented - * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented - */ - return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; + /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or + * later. This set of cipher suites is similar to, but different from, the + * set of cipher suites considered exportable by SSL_IsExportCipherSuite. + */ + case TLS_RSA_EXPORT_WITH_RC4_40_MD5: + case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: + /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented + * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented + * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented + * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented + * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented + * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented + * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented + */ + return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; - case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: - case TLS_RSA_WITH_AES_256_CBC_SHA256: - case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: - case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: - case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: - case TLS_RSA_WITH_AES_128_CBC_SHA256: - case TLS_RSA_WITH_AES_128_GCM_SHA256: - case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: - case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: - case TLS_RSA_WITH_NULL_SHA256: - case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: - return vrange->max == SSL_LIBRARY_VERSION_TLS_1_2; + case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: + case TLS_RSA_WITH_AES_256_CBC_SHA256: + case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: + case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: + case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: + case TLS_RSA_WITH_AES_128_CBC_SHA256: + case TLS_RSA_WITH_AES_128_GCM_SHA256: + case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: + case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: + case TLS_RSA_WITH_NULL_SHA256: + case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: + return vrange->max == SSL_LIBRARY_VERSION_TLS_1_2; - case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: - case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: - case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: - return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2; + case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: + case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: + case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: + return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2; - /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and - * point formats.*/ - case TLS_ECDH_ECDSA_WITH_NULL_SHA: - case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: - case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: - case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: - case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: - case TLS_ECDHE_ECDSA_WITH_NULL_SHA: - case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: - case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: - case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: - case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: - case TLS_ECDH_RSA_WITH_NULL_SHA: - case TLS_ECDH_RSA_WITH_RC4_128_SHA: - case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: - case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: - case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: - case TLS_ECDHE_RSA_WITH_NULL_SHA: - case TLS_ECDHE_RSA_WITH_RC4_128_SHA: - case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: - case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: - case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: - return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 && - vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; + /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and + * point formats.*/ + case TLS_ECDH_ECDSA_WITH_NULL_SHA: + case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: + case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: + case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: + case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: + case TLS_ECDHE_ECDSA_WITH_NULL_SHA: + case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: + case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: + case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: + case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: + case TLS_ECDH_RSA_WITH_NULL_SHA: + case TLS_ECDH_RSA_WITH_RC4_128_SHA: + case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: + case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: + case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: + case TLS_ECDHE_RSA_WITH_NULL_SHA: + case TLS_ECDHE_RSA_WITH_RC4_128_SHA: + case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: + case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: + case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: + return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 && + vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; - default: - return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; + default: + return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; } } @@ -716,14 +765,14 @@ static const ssl3CipherSuiteDef * ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) { int cipher_suite_def_len = - sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); + sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); int i; for (i = 0; i < cipher_suite_def_len; i++) { - if (cipher_suite_defs[i].cipher_suite == suite) - return &cipher_suite_defs[i]; + if (cipher_suite_defs[i].cipher_suite == suite) + return &cipher_suite_defs[i]; } - PORT_Assert(PR_FALSE); /* We should never get here. */ + PORT_Assert(PR_FALSE); /* We should never get here. */ PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); return NULL; } @@ -736,15 +785,14 @@ ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) int i; for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - if (suites[i].cipher_suite == suite) - return &suites[i]; + if (suites[i].cipher_suite == suite) + return &suites[i]; } /* return NULL and let the caller handle it. */ PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); return NULL; } - /* Initialize the suite->isPresent value for config_match * Returns count of enabled ciphers supported by extant tokens, * regardless of policy or user preference. @@ -753,96 +801,94 @@ ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) int ssl3_config_match_init(sslSocket *ss) { - ssl3CipherSuiteCfg * suite; + ssl3CipherSuiteCfg *suite; const ssl3CipherSuiteDef *cipher_def; - SSLCipherAlgorithm cipher_alg; - CK_MECHANISM_TYPE cipher_mech; - SSL3KEAType exchKeyType; - int i; - int numPresent = 0; - int numEnabled = 0; - PRBool isServer; - sslServerCerts *svrAuth; + SSLCipherAlgorithm cipher_alg; + CK_MECHANISM_TYPE cipher_mech; + SSL3KEAType exchKeyType; + int i; + int numPresent = 0; + int numEnabled = 0; + PRBool isServer; + sslServerCerts *svrAuth; PORT_Assert(ss); if (!ss) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return 0; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return 0; } if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - return 0; + return 0; } isServer = (PRBool)(ss->sec.isServer != 0); for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - suite = &ss->cipherSuites[i]; - if (suite->enabled) { - ++numEnabled; - /* We need the cipher defs to see if we have a token that can handle - * this cipher. It isn't part of the static definition. - */ - cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); - if (!cipher_def) { - suite->isPresent = PR_FALSE; - continue; - } - cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; - cipher_mech = ssl3_Alg2Mech(cipher_alg); - exchKeyType = - kea_defs[cipher_def->key_exchange_alg].exchKeyType; + suite = &ss->cipherSuites[i]; + if (suite->enabled) { + ++numEnabled; + /* We need the cipher defs to see if we have a token that can handle + * this cipher. It isn't part of the static definition. + */ + cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); + if (!cipher_def) { + suite->isPresent = PR_FALSE; + continue; + } + cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; + cipher_mech = ssl3_Alg2Mech(cipher_alg); + exchKeyType = + kea_defs[cipher_def->key_exchange_alg].exchKeyType; #ifdef NSS_DISABLE_ECC - svrAuth = ss->serverCerts + exchKeyType; + svrAuth = ss->serverCerts + exchKeyType; #else - /* XXX SSLKEAType isn't really a good choice for - * indexing certificates. It doesn't work for - * (EC)DHE-* ciphers. Here we use a hack to ensure - * that the server uses an RSA cert for (EC)DHE-RSA. - */ - switch (cipher_def->key_exchange_alg) { - case kea_dhe_dss: - svrAuth = ss->serverCerts + ssl_kea_dh; - break; - case kea_ecdhe_rsa: - case kea_dhe_rsa: - svrAuth = ss->serverCerts + kt_rsa; - break; - case kea_ecdh_ecdsa: - case kea_ecdh_rsa: - /* - * XXX We ought to have different indices for - * ECDSA- and RSA-signed EC certificates so - * we could support both key exchange mechanisms - * simultaneously. For now, both of them use - * whatever is in the certificate slot for kt_ecdh - */ - case kea_dhe_dss_export: - case kea_dhe_rsa_export: - default: - svrAuth = ss->serverCerts + exchKeyType; - break; - } + /* XXX SSLKEAType isn't really a good choice for + * indexing certificates. It doesn't work for + * (EC)DHE-* ciphers. Here we use a hack to ensure + * that the server uses an RSA cert for (EC)DHE-RSA. + */ + switch (cipher_def->key_exchange_alg) { + case kea_dhe_dss: + svrAuth = ss->serverCerts + ssl_kea_dh; + break; + case kea_ecdhe_rsa: + case kea_dhe_rsa: + svrAuth = ss->serverCerts + kt_rsa; + break; + case kea_ecdh_ecdsa: + case kea_ecdh_rsa: + /* + * XXX We ought to have different indices for + * ECDSA- and RSA-signed EC certificates so + * we could support both key exchange mechanisms + * simultaneously. For now, both of them use + * whatever is in the certificate slot for kt_ecdh + */ + case kea_dhe_dss_export: + case kea_dhe_rsa_export: + default: + svrAuth = ss->serverCerts + exchKeyType; + break; + } #endif /* NSS_DISABLE_ECC */ - /* Mark the suites that are backed by real tokens, certs and keys */ - suite->isPresent = (PRBool) - (((exchKeyType == kt_null) || - ((!isServer || (svrAuth->serverKeyPair && - svrAuth->SERVERKEY && - svrAuth->serverCertChain)) && - PK11_TokenExists(kea_alg_defs[exchKeyType]))) && - ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech))); - if (suite->isPresent) - ++numPresent; - } + /* Mark the suites that are backed by real tokens, certs and keys */ + suite->isPresent = (PRBool)(((exchKeyType == kt_null) || + ((!isServer || + (svrAuth->serverKeyPair && svrAuth->SERVERKEY && + svrAuth->serverCertChain)) && + PK11_TokenExists(kea_alg_defs[exchKeyType]))) && + ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech))); + if (suite->isPresent) + ++numPresent; + } } PORT_Assert(numPresent > 0 || numEnabled == 0); if (numPresent <= 0) { - PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); + PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); } return numPresent; } - /* return PR_TRUE if suite matches policy, enabled state and is applicable to * the given version range. */ /* It would be a REALLY BAD THING (tm) if we ever permitted the use @@ -853,13 +899,13 @@ ssl3_config_match_init(sslSocket *ss) * cipher suite. */ static PRBool config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, - const SSLVersionRange *vrange, const sslSocket *ss) + const SSLVersionRange *vrange, const sslSocket *ss) { const ssl3CipherSuiteDef *cipher_def; PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE); if (policy == SSL_NOT_ALLOWED || !enabled) - return PR_FALSE; + return PR_FALSE; cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); PORT_Assert(cipher_def != NULL); @@ -867,13 +913,13 @@ config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, PORT_Assert(ss != NULL); if (ss->sec.isServer && !ss->opt.enableServerDhe && kea_defs[cipher_def->key_exchange_alg].exchKeyType == ssl_kea_dh) - return PR_FALSE; + return PR_FALSE; return (PRBool)(suite->enabled && suite->isPresent && - suite->policy != SSL_NOT_ALLOWED && - suite->policy <= policy && - ssl3_CipherSuiteAllowedForVersionRange( + suite->policy != SSL_NOT_ALLOWED && + suite->policy <= policy && + ssl3_CipherSuiteAllowedForVersionRange( suite->cipher_suite, vrange)); } @@ -886,14 +932,14 @@ count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) int i, count = 0; if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - return 0; + return 0; } for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange, ss)) - count++; + if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange, ss)) + count++; } if (count <= 0) { - PORT_SetError(SSL_ERROR_SSL_DISABLED); + PORT_SetError(SSL_ERROR_SSL_DISABLED); } return count; } @@ -904,16 +950,16 @@ count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, - const unsigned char *input, int inputLen) + const unsigned char *input, int inputLen) { if (inputLen > maxOutputLen) { - *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ + *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ PORT_SetError(SEC_ERROR_OUTPUT_LEN); return SECFailure; } *outputLen = inputLen; if (input != output) - PORT_Memcpy(output, input, inputLen); + PORT_Memcpy(output, input, inputLen); return SECSuccess; } @@ -930,17 +976,17 @@ Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, */ SECStatus ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, - PRBool allowLargerPeerVersion) + PRBool allowLargerPeerVersion) { if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - PORT_SetError(SSL_ERROR_SSL_DISABLED); - return SECFailure; + PORT_SetError(SSL_ERROR_SSL_DISABLED); + return SECFailure; } if (peerVersion < ss->vrange.min || - (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { - PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); - return SECFailure; + (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { + PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); + return SECFailure; } ss->version = PR_MIN(peerVersion, ss->vrange.max); @@ -956,203 +1002,209 @@ ssl3_GetNewRandom(SSL3Random *random) rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH); if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); } return rv; } /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ SECStatus -ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, +ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, PRBool isTLS) { - SECStatus rv = SECFailure; - PRBool doDerEncode = PR_FALSE; - int signatureLen; - SECItem hashItem; + SECStatus rv = SECFailure; + PRBool doDerEncode = PR_FALSE; + int signatureLen; + SECItem hashItem; - buf->data = NULL; + buf->data = NULL; switch (key->keyType) { - case rsaKey: - hashItem.data = hash->u.raw; - hashItem.len = hash->len; - break; - case dsaKey: - doDerEncode = isTLS; - /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. - * In that case, we use just the SHA1 part. */ - if (hash->hashAlg == ssl_hash_none) { - hashItem.data = hash->u.s.sha; - hashItem.len = sizeof(hash->u.s.sha); - } else { - hashItem.data = hash->u.raw; - hashItem.len = hash->len; - } - break; + case rsaKey: + hashItem.data = hash->u.raw; + hashItem.len = hash->len; + break; + case dsaKey: + doDerEncode = isTLS; + /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. + * In that case, we use just the SHA1 part. */ + if (hash->hashAlg == ssl_hash_none) { + hashItem.data = hash->u.s.sha; + hashItem.len = sizeof(hash->u.s.sha); + } + else { + hashItem.data = hash->u.raw; + hashItem.len = hash->len; + } + break; #ifndef NSS_DISABLE_ECC - case ecKey: - doDerEncode = PR_TRUE; - /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. - * In that case, we use just the SHA1 part. */ - if (hash->hashAlg == ssl_hash_none) { - hashItem.data = hash->u.s.sha; - hashItem.len = sizeof(hash->u.s.sha); - } else { - hashItem.data = hash->u.raw; - hashItem.len = hash->len; - } - break; + case ecKey: + doDerEncode = PR_TRUE; + /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. + * In that case, we use just the SHA1 part. */ + if (hash->hashAlg == ssl_hash_none) { + hashItem.data = hash->u.s.sha; + hashItem.len = sizeof(hash->u.s.sha); + } + else { + hashItem.data = hash->u.raw; + hashItem.len = hash->len; + } + break; #endif /* NSS_DISABLE_ECC */ - default: - PORT_SetError(SEC_ERROR_INVALID_KEY); - goto done; + default: + PORT_SetError(SEC_ERROR_INVALID_KEY); + goto done; } PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len)); if (hash->hashAlg == ssl_hash_none) { - signatureLen = PK11_SignatureLen(key); - if (signatureLen <= 0) { - PORT_SetError(SEC_ERROR_INVALID_KEY); - goto done; - } + signatureLen = PK11_SignatureLen(key); + if (signatureLen <= 0) { + PORT_SetError(SEC_ERROR_INVALID_KEY); + goto done; + } - buf->len = (unsigned)signatureLen; - buf->data = (unsigned char *)PORT_Alloc(signatureLen); - if (!buf->data) - goto done; /* error code was set. */ + buf->len = (unsigned)signatureLen; + buf->data = (unsigned char *)PORT_Alloc(signatureLen); + if (!buf->data) + goto done; /* error code was set. */ - rv = PK11_Sign(key, buf, &hashItem); - } else { + rv = PK11_Sign(key, buf, &hashItem); + } + else { SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); rv = SGN_Digest(key, hashOID, buf, &hashItem); } if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); - } else if (doDerEncode) { - SECItem derSig = {siBuffer, NULL, 0}; + ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); + } + else if (doDerEncode) { + SECItem derSig = { siBuffer, NULL, 0 }; - /* This also works for an ECDSA signature */ - rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); - if (rv == SECSuccess) { - PORT_Free(buf->data); /* discard unencoded signature. */ - *buf = derSig; /* give caller encoded signature. */ - } else if (derSig.data) { - PORT_Free(derSig.data); - } + /* This also works for an ECDSA signature */ + rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); + if (rv == SECSuccess) { + PORT_Free(buf->data); /* discard unencoded signature. */ + *buf = derSig; /* give caller encoded signature. */ + } + else if (derSig.data) { + PORT_Free(derSig.data); + } } - PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len)); + PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len)); done: if (rv != SECSuccess && buf->data) { - PORT_Free(buf->data); - buf->data = NULL; + PORT_Free(buf->data); + buf->data = NULL; } return rv; } /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ SECStatus -ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, +ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, SECItem *buf, PRBool isTLS, void *pwArg) { - SECKEYPublicKey * key; - SECItem * signature = NULL; - SECStatus rv; - SECItem hashItem; - SECOidTag encAlg; - SECOidTag hashAlg; - + SECKEYPublicKey *key; + SECItem *signature = NULL; + SECStatus rv; + SECItem hashItem; + SECOidTag encAlg; + SECOidTag hashAlg; PRINT_BUF(60, (NULL, "check signed hashes", - buf->data, buf->len)); + buf->data, buf->len)); key = CERT_ExtractPublicKey(cert); if (key == NULL) { - ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; + ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); + return SECFailure; } hashAlg = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); switch (key->keyType) { - case rsaKey: - encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; - hashItem.data = hash->u.raw; - hashItem.len = hash->len; - break; - case dsaKey: - encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; - /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. - * In that case, we use just the SHA1 part. */ - if (hash->hashAlg == ssl_hash_none) { - hashItem.data = hash->u.s.sha; - hashItem.len = sizeof(hash->u.s.sha); - } else { - hashItem.data = hash->u.raw; - hashItem.len = hash->len; - } - /* Allow DER encoded DSA signatures in SSL 3.0 */ - if (isTLS || buf->len != SECKEY_SignatureLen(key)) { - signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); - if (!signature) { - PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); - return SECFailure; - } - buf = signature; - } - break; + case rsaKey: + encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; + hashItem.data = hash->u.raw; + hashItem.len = hash->len; + break; + case dsaKey: + encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; + /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. + * In that case, we use just the SHA1 part. */ + if (hash->hashAlg == ssl_hash_none) { + hashItem.data = hash->u.s.sha; + hashItem.len = sizeof(hash->u.s.sha); + } + else { + hashItem.data = hash->u.raw; + hashItem.len = hash->len; + } + /* Allow DER encoded DSA signatures in SSL 3.0 */ + if (isTLS || buf->len != SECKEY_SignatureLen(key)) { + signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); + if (!signature) { + PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); + return SECFailure; + } + buf = signature; + } + break; #ifndef NSS_DISABLE_ECC - case ecKey: - encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; - /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. - * In that case, we use just the SHA1 part. - * ECDSA signatures always encode the integers r and s using ASN.1 - * (unlike DSA where ASN.1 encoding is used with TLS but not with - * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. - */ - if (hash->hashAlg == ssl_hash_none) { - hashAlg = SEC_OID_SHA1; - hashItem.data = hash->u.s.sha; - hashItem.len = sizeof(hash->u.s.sha); - } else { - hashItem.data = hash->u.raw; - hashItem.len = hash->len; - } - break; + case ecKey: + encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; + /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. + * In that case, we use just the SHA1 part. + * ECDSA signatures always encode the integers r and s using ASN.1 + * (unlike DSA where ASN.1 encoding is used with TLS but not with + * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. + */ + if (hash->hashAlg == ssl_hash_none) { + hashAlg = SEC_OID_SHA1; + hashItem.data = hash->u.s.sha; + hashItem.len = sizeof(hash->u.s.sha); + } + else { + hashItem.data = hash->u.raw; + hashItem.len = hash->len; + } + break; #endif /* NSS_DISABLE_ECC */ - default: - SECKEY_DestroyPublicKey(key); - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; + default: + SECKEY_DestroyPublicKey(key); + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); + return SECFailure; } PRINT_BUF(60, (NULL, "hash(es) to be verified", - hashItem.data, hashItem.len)); + hashItem.data, hashItem.len)); if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) { - /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. - * DSA signatures are DER-encoded in TLS but not in SSL3 and the code - * above always removes the DER encoding of DSA signatures when - * present. Thus DSA signatures are always verified with PK11_Verify. - */ - rv = PK11_Verify(key, buf, &hashItem, pwArg); - } else { + /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. + * DSA signatures are DER-encoded in TLS but not in SSL3 and the code + * above always removes the DER encoding of DSA signatures when + * present. Thus DSA signatures are always verified with PK11_Verify. + */ + rv = PK11_Verify(key, buf, &hashItem, pwArg); + } + else { rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg, pwArg); } SECKEY_DestroyPublicKey(key); if (signature) { - SECITEM_FreeItem(signature, PR_TRUE); + SECITEM_FreeItem(signature, PR_TRUE); } if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); + ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); } return rv; } - /* Caller must set hiLevel error code. */ /* Called from ssl3_ComputeExportRSAKeyHash * ssl3_ComputeDHKeyHash @@ -1162,7 +1214,7 @@ ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, */ SECStatus ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, - PRUint8 * hashBuf, unsigned int bufLen, + PRUint8 *hashBuf, unsigned int bufLen, SSL3Hashes *hashes, PRBool bypassPKCS11) { SECStatus rv; @@ -1171,26 +1223,32 @@ ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, #ifndef NO_PKCS11_BYPASS if (bypassPKCS11) { if (hashAlg == ssl_hash_none) { - MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen); + MD5_HashBuf(hashes->u.s.md5, hashBuf, bufLen); SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen); hashes->len = MD5_LENGTH + SHA1_LENGTH; - } else if (hashAlg == ssl_hash_sha1) { + } + else if (hashAlg == ssl_hash_sha1) { SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen); hashes->len = SHA1_LENGTH; - } else if (hashAlg == ssl_hash_sha256) { + } + else if (hashAlg == ssl_hash_sha256) { SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen); hashes->len = SHA256_LENGTH; - } else if (hashAlg == ssl_hash_sha384) { + } + else if (hashAlg == ssl_hash_sha384) { SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen); hashes->len = SHA384_LENGTH; - } else if (hashAlg == ssl_hash_sha512) { + } + else if (hashAlg == ssl_hash_sha512) { SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen); hashes->len = SHA512_LENGTH; - } else { + } + else { PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); return SECFailure; } - } else + } + else #endif { if (hashAlg == ssl_hash_none) { @@ -1205,7 +1263,8 @@ ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, return rv; } hashes->len = MD5_LENGTH + SHA1_LENGTH; - } else { + } + else { hashOID = ssl3_TLSHashAlgorithmToOID(hashAlg); hashes->len = HASH_ResultLenByOidTag(hashOID); if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) { @@ -1223,8 +1282,8 @@ ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, return SECSuccess; } -/* Caller must set hiLevel error code. -** Called from ssl3_SendServerKeyExchange and +/* Caller must set hiLevel error code. +** Called from ssl3_SendServerKeyExchange and ** ssl3_HandleServerKeyExchange. */ static SECStatus @@ -1233,54 +1292,56 @@ ssl3_ComputeExportRSAKeyHash(SSLHashType hashAlg, SSL3Random *client_rand, SSL3Random *server_rand, SSL3Hashes *hashes, PRBool bypassPKCS11) { - PRUint8 * hashBuf; - PRUint8 * pBuf; - SECStatus rv = SECSuccess; - unsigned int bufLen; - PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; + PRUint8 *hashBuf; + PRUint8 *pBuf; + SECStatus rv = SECSuccess; + unsigned int bufLen; + PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 4096 / 8 + 2 + 4096 / 8]; - bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len; + bufLen = 2 * SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len; if (bufLen <= sizeof buf) { - hashBuf = buf; - } else { - hashBuf = PORT_Alloc(bufLen); - if (!hashBuf) { - return SECFailure; - } + hashBuf = buf; + } + else { + hashBuf = PORT_Alloc(bufLen); + if (!hashBuf) { + return SECFailure; + } } - memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); - pBuf = hashBuf + SSL3_RANDOM_LENGTH; + memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); + pBuf = hashBuf + SSL3_RANDOM_LENGTH; memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); - pBuf += SSL3_RANDOM_LENGTH; - pBuf[0] = (PRUint8)(modulus.len >> 8); - pBuf[1] = (PRUint8)(modulus.len); - pBuf += 2; + pBuf += SSL3_RANDOM_LENGTH; + pBuf[0] = (PRUint8)(modulus.len >> 8); + pBuf[1] = (PRUint8)(modulus.len); + pBuf += 2; memcpy(pBuf, modulus.data, modulus.len); - pBuf += modulus.len; + pBuf += modulus.len; pBuf[0] = (PRUint8)(publicExponent.len >> 8); pBuf[1] = (PRUint8)(publicExponent.len); - pBuf += 2; + pBuf += 2; memcpy(pBuf, publicExponent.data, publicExponent.len); - pBuf += publicExponent.len; + pBuf += publicExponent.len; PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, - bypassPKCS11); + bypassPKCS11); PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen)); if (hashAlg == ssl_hash_none) { - PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", - hashes->u.s.md5, MD5_LENGTH)); - PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", - hashes->u.s.sha, SHA1_LENGTH)); - } else { - PRINT_BUF(95, (NULL, "RSAkey hash: result", - hashes->u.raw, hashes->len)); + PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", + hashes->u.s.md5, MD5_LENGTH)); + PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", + hashes->u.s.sha, SHA1_LENGTH)); + } + else { + PRINT_BUF(95, (NULL, "RSAkey hash: result", + hashes->u.raw, hashes->len)); } if (hashBuf != buf && hashBuf != NULL) - PORT_Free(hashBuf); + PORT_Free(hashBuf); return rv; } @@ -1292,59 +1353,61 @@ ssl3_ComputeDHKeyHash(SSLHashType hashAlg, SSL3Random *client_rand, SSL3Random *server_rand, SSL3Hashes *hashes, PRBool bypassPKCS11) { - PRUint8 * hashBuf; - PRUint8 * pBuf; - SECStatus rv = SECSuccess; - unsigned int bufLen; - PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; + PRUint8 *hashBuf; + PRUint8 *pBuf; + SECStatus rv = SECSuccess; + unsigned int bufLen; + PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 4096 / 8 + 2 + 4096 / 8]; - bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len; + bufLen = 2 * SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len; if (bufLen <= sizeof buf) { - hashBuf = buf; - } else { - hashBuf = PORT_Alloc(bufLen); - if (!hashBuf) { - return SECFailure; - } + hashBuf = buf; + } + else { + hashBuf = PORT_Alloc(bufLen); + if (!hashBuf) { + return SECFailure; + } } - memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); - pBuf = hashBuf + SSL3_RANDOM_LENGTH; + memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); + pBuf = hashBuf + SSL3_RANDOM_LENGTH; memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); - pBuf += SSL3_RANDOM_LENGTH; - pBuf[0] = (PRUint8)(dh_p.len >> 8); - pBuf[1] = (PRUint8)(dh_p.len); - pBuf += 2; + pBuf += SSL3_RANDOM_LENGTH; + pBuf[0] = (PRUint8)(dh_p.len >> 8); + pBuf[1] = (PRUint8)(dh_p.len); + pBuf += 2; memcpy(pBuf, dh_p.data, dh_p.len); - pBuf += dh_p.len; + pBuf += dh_p.len; pBuf[0] = (PRUint8)(dh_g.len >> 8); pBuf[1] = (PRUint8)(dh_g.len); - pBuf += 2; + pBuf += 2; memcpy(pBuf, dh_g.data, dh_g.len); - pBuf += dh_g.len; + pBuf += dh_g.len; pBuf[0] = (PRUint8)(dh_Ys.len >> 8); pBuf[1] = (PRUint8)(dh_Ys.len); - pBuf += 2; + pBuf += 2; memcpy(pBuf, dh_Ys.data, dh_Ys.len); - pBuf += dh_Ys.len; + pBuf += dh_Ys.len; PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, - bypassPKCS11); + bypassPKCS11); PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen)); if (hashAlg == ssl_hash_none) { - PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", - hashes->u.s.md5, MD5_LENGTH)); - PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", - hashes->u.s.sha, SHA1_LENGTH)); - } else { - PRINT_BUF(95, (NULL, "DHkey hash: result", - hashes->u.raw, hashes->len)); + PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", + hashes->u.s.md5, MD5_LENGTH)); + PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", + hashes->u.s.sha, SHA1_LENGTH)); + } + else { + PRINT_BUF(95, (NULL, "DHkey hash: result", + hashes->u.raw, hashes->len)); } if (hashBuf != buf && hashBuf != NULL) - PORT_Free(hashBuf); + PORT_Free(hashBuf); return rv; } @@ -1353,7 +1416,7 @@ ssl3_BumpSequenceNumber(SSL3SequenceNumber *num) { num->low++; if (num->low == 0) - num->high++; + num->high++; } /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */ @@ -1361,21 +1424,21 @@ static void ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat) { if (mat->write_key != NULL) { - PK11_FreeSymKey(mat->write_key); - mat->write_key = NULL; + PK11_FreeSymKey(mat->write_key); + mat->write_key = NULL; } if (mat->write_mac_key != NULL) { - PK11_FreeSymKey(mat->write_mac_key); - mat->write_mac_key = NULL; + PK11_FreeSymKey(mat->write_mac_key); + mat->write_mac_key = NULL; } if (mat->write_mac_context != NULL) { - PK11_DestroyContext(mat->write_mac_context, PR_TRUE); - mat->write_mac_context = NULL; + PK11_DestroyContext(mat->write_mac_context, PR_TRUE); + mat->write_mac_context = NULL; } } -/* Called from ssl3_SendChangeCipherSpecs() and -** ssl3_HandleChangeCipherSpecs() +/* Called from ssl3_SendChangeCipherSpecs() and +** ssl3_HandleChangeCipherSpecs() ** ssl3_DestroySSL3Info ** Caller must hold SpecWriteLock. */ @@ -1383,34 +1446,34 @@ void ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) { PRBool freeit = (PRBool)(!spec->bypassCiphers); -/* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */ + /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */ if (spec->destroy) { - spec->destroy(spec->encodeContext, freeit); - spec->destroy(spec->decodeContext, freeit); - spec->encodeContext = NULL; /* paranoia */ - spec->decodeContext = NULL; + spec->destroy(spec->encodeContext, freeit); + spec->destroy(spec->decodeContext, freeit); + spec->encodeContext = NULL; /* paranoia */ + spec->decodeContext = NULL; } if (spec->destroyCompressContext && spec->compressContext) { - spec->destroyCompressContext(spec->compressContext, 1); - spec->compressContext = NULL; + spec->destroyCompressContext(spec->compressContext, 1); + spec->compressContext = NULL; } if (spec->destroyDecompressContext && spec->decompressContext) { - spec->destroyDecompressContext(spec->decompressContext, 1); - spec->decompressContext = NULL; + spec->destroyDecompressContext(spec->decompressContext, 1); + spec->decompressContext = NULL; } if (freeSrvName && spec->srvVirtName.data) { SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE); } if (spec->master_secret != NULL) { - PK11_FreeSymKey(spec->master_secret); - spec->master_secret = NULL; + PK11_FreeSymKey(spec->master_secret); + spec->master_secret = NULL; } spec->msItem.data = NULL; - spec->msItem.len = 0; + spec->msItem.len = 0; ssl3_CleanupKeyMaterial(&spec->client); ssl3_CleanupKeyMaterial(&spec->server); spec->bypassCiphers = PR_FALSE; - spec->destroy=NULL; + spec->destroy = NULL; spec->destroyCompressContext = NULL; spec->destroyDecompressContext = NULL; } @@ -1424,18 +1487,18 @@ ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) SECStatus ssl3_SetupPendingCipherSpec(sslSocket *ss) { - ssl3CipherSpec * pwSpec; - ssl3CipherSpec * cwSpec; - ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; - SSL3MACAlgorithm mac; - SSL3BulkCipher cipher; - SSL3KeyExchangeAlgorithm kea; + ssl3CipherSpec *pwSpec; + ssl3CipherSpec *cwSpec; + ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; + SSL3MACAlgorithm mac; + SSL3BulkCipher cipher; + SSL3KeyExchangeAlgorithm kea; const ssl3CipherSuiteDef *suite_def; - PRBool isTLS; + PRBool isTLS; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - ssl_GetSpecWriteLock(ss); /*******************************/ + ssl_GetSpecWriteLock(ss); /*******************************/ pwSpec = ss->ssl3.pwSpec; PORT_Assert(pwSpec == ss->ssl3.prSpec); @@ -1443,48 +1506,48 @@ ssl3_SetupPendingCipherSpec(sslSocket *ss) /* This hack provides maximal interoperability with SSL 3 servers. */ cwSpec = ss->ssl3.cwSpec; if (cwSpec->mac_def->mac == mac_null) { - /* SSL records are not being MACed. */ - cwSpec->version = ss->version; + /* SSL records are not being MACed. */ + cwSpec->version = ss->version; } - pwSpec->version = ss->version; - isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); + pwSpec->version = ss->version; + isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", - SSL_GETPID(), ss->fd, suite)); + SSL_GETPID(), ss->fd, suite)); suite_def = ssl_LookupCipherSuiteDef(suite); if (suite_def == NULL) { - ssl_ReleaseSpecWriteLock(ss); - return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ + ssl_ReleaseSpecWriteLock(ss); + return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ } if (IS_DTLS(ss)) { - /* Double-check that we did not pick an RC4 suite */ - PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && - (suite_def->bulk_cipher_alg != cipher_rc4_40) && - (suite_def->bulk_cipher_alg != cipher_rc4_56)); + /* Double-check that we did not pick an RC4 suite */ + PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && + (suite_def->bulk_cipher_alg != cipher_rc4_40) && + (suite_def->bulk_cipher_alg != cipher_rc4_56)); } cipher = suite_def->bulk_cipher_alg; - kea = suite_def->key_exchange_alg; - mac = suite_def->mac_alg; + kea = suite_def->key_exchange_alg; + mac = suite_def->mac_alg; if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) - mac += 2; + mac += 2; ss->ssl3.hs.suite_def = suite_def; - ss->ssl3.hs.kea_def = &kea_defs[kea]; + ss->ssl3.hs.kea_def = &kea_defs[kea]; PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); - pwSpec->cipher_def = &bulk_cipher_defs[cipher]; + pwSpec->cipher_def = &bulk_cipher_defs[cipher]; PORT_Assert(pwSpec->cipher_def->cipher == cipher); pwSpec->mac_def = &mac_defs[mac]; PORT_Assert(pwSpec->mac_def->mac == mac); - ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; + ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB; - ss->sec.cipherType = cipher; + ss->sec.cipherType = cipher; pwSpec->encodeContext = NULL; pwSpec->decodeContext = NULL; @@ -1499,7 +1562,7 @@ ssl3_SetupPendingCipherSpec(sslSocket *ss) PORT_Assert(ss->ssl3.hs.kea_def->ephemeral); PORT_Assert(pwSpec->cipher_def->type == type_aead); } - ssl_ReleaseSpecWriteLock(ss); /*******************************/ + ssl_ReleaseSpecWriteLock(ss); /*******************************/ return SECSuccess; } @@ -1510,10 +1573,10 @@ static SECStatus ssl3_MapZlibError(int zlib_error) { switch (zlib_error) { - case Z_OK: - return SECSuccess; - default: - return SECFailure; + case Z_OK: + return SECSuccess; + default: + return SECFailure; } } @@ -1552,7 +1615,7 @@ ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len, return SECSuccess; } - context->next_in = (unsigned char*) in; + context->next_in = (unsigned char *)in; context->avail_in = inlen; context->next_out = out; context->avail_out = maxout; @@ -1581,7 +1644,7 @@ ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len, return SECSuccess; } - context->next_in = (unsigned char*) in; + context->next_in = (unsigned char *)in; context->avail_in = inlen; context->next_out = out; context->avail_out = maxout; @@ -1619,30 +1682,30 @@ ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) { /* Setup the compression functions */ switch (pwSpec->compression_method) { - case ssl_compression_null: - pwSpec->compressor = NULL; - pwSpec->decompressor = NULL; - pwSpec->compressContext = NULL; - pwSpec->decompressContext = NULL; - pwSpec->destroyCompressContext = NULL; - pwSpec->destroyDecompressContext = NULL; - break; + case ssl_compression_null: + pwSpec->compressor = NULL; + pwSpec->decompressor = NULL; + pwSpec->compressContext = NULL; + pwSpec->decompressContext = NULL; + pwSpec->destroyCompressContext = NULL; + pwSpec->destroyDecompressContext = NULL; + break; #ifdef NSS_SSL_ENABLE_ZLIB - case ssl_compression_deflate: - pwSpec->compressor = ssl3_DeflateCompress; - pwSpec->decompressor = ssl3_DeflateDecompress; - pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); - pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); - pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; - pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; - ssl3_DeflateInit(pwSpec->compressContext); - ssl3_InflateInit(pwSpec->decompressContext); - break; + case ssl_compression_deflate: + pwSpec->compressor = ssl3_DeflateCompress; + pwSpec->decompressor = ssl3_DeflateDecompress; + pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); + pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); + pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; + pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; + ssl3_DeflateInit(pwSpec->compressContext); + ssl3_InflateInit(pwSpec->decompressContext); + break; #endif /* NSS_SSL_ENABLE_ZLIB */ - default: - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + default: + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } return SECSuccess; @@ -1657,156 +1720,157 @@ ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) static SECStatus ssl3_InitPendingContextsBypass(sslSocket *ss) { - ssl3CipherSpec * pwSpec; - const ssl3BulkCipherDef *cipher_def; - void * serverContext = NULL; - void * clientContext = NULL; - BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; - int mode = 0; - unsigned int optArg1 = 0; - unsigned int optArg2 = 0; - PRBool server_encrypts = ss->sec.isServer; - SSLCipherAlgorithm calg; - SECStatus rv; + ssl3CipherSpec *pwSpec; + const ssl3BulkCipherDef *cipher_def; + void *serverContext = NULL; + void *clientContext = NULL; + BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; + int mode = 0; + unsigned int optArg1 = 0; + unsigned int optArg2 = 0; + PRBool server_encrypts = ss->sec.isServer; + SSLCipherAlgorithm calg; + SECStatus rv; PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); - pwSpec = ss->ssl3.pwSpec; - cipher_def = pwSpec->cipher_def; + pwSpec = ss->ssl3.pwSpec; + cipher_def = pwSpec->cipher_def; calg = cipher_def->calg; if (calg == ssl_calg_aes_gcm) { - pwSpec->encode = NULL; - pwSpec->decode = NULL; - pwSpec->destroy = NULL; - pwSpec->encodeContext = NULL; - pwSpec->decodeContext = NULL; - pwSpec->aead = ssl3_AESGCMBypass; - ssl3_InitCompressionContext(pwSpec); - return SECSuccess; + pwSpec->encode = NULL; + pwSpec->decode = NULL; + pwSpec->destroy = NULL; + pwSpec->encodeContext = NULL; + pwSpec->decodeContext = NULL; + pwSpec->aead = ssl3_AESGCMBypass; + ssl3_InitCompressionContext(pwSpec); + return SECSuccess; } serverContext = pwSpec->server.cipher_context; clientContext = pwSpec->client.cipher_context; switch (calg) { - case ssl_calg_null: - pwSpec->encode = Null_Cipher; - pwSpec->decode = Null_Cipher; - pwSpec->destroy = NULL; - goto success; + case ssl_calg_null: + pwSpec->encode = Null_Cipher; + pwSpec->decode = Null_Cipher; + pwSpec->destroy = NULL; + goto success; - case ssl_calg_rc4: - initFn = (BLapiInitContextFunc)RC4_InitContext; - pwSpec->encode = (SSLCipher) RC4_Encrypt; - pwSpec->decode = (SSLCipher) RC4_Decrypt; - pwSpec->destroy = (SSLDestroy) RC4_DestroyContext; - break; - case ssl_calg_rc2: - initFn = (BLapiInitContextFunc)RC2_InitContext; - mode = NSS_RC2_CBC; - optArg1 = cipher_def->key_size; - pwSpec->encode = (SSLCipher) RC2_Encrypt; - pwSpec->decode = (SSLCipher) RC2_Decrypt; - pwSpec->destroy = (SSLDestroy) RC2_DestroyContext; - break; - case ssl_calg_des: - initFn = (BLapiInitContextFunc)DES_InitContext; - mode = NSS_DES_CBC; - optArg1 = server_encrypts; - pwSpec->encode = (SSLCipher) DES_Encrypt; - pwSpec->decode = (SSLCipher) DES_Decrypt; - pwSpec->destroy = (SSLDestroy) DES_DestroyContext; - break; - case ssl_calg_3des: - initFn = (BLapiInitContextFunc)DES_InitContext; - mode = NSS_DES_EDE3_CBC; - optArg1 = server_encrypts; - pwSpec->encode = (SSLCipher) DES_Encrypt; - pwSpec->decode = (SSLCipher) DES_Decrypt; - pwSpec->destroy = (SSLDestroy) DES_DestroyContext; - break; - case ssl_calg_aes: - initFn = (BLapiInitContextFunc)AES_InitContext; - mode = NSS_AES_CBC; - optArg1 = server_encrypts; - optArg2 = AES_BLOCK_SIZE; - pwSpec->encode = (SSLCipher) AES_Encrypt; - pwSpec->decode = (SSLCipher) AES_Decrypt; - pwSpec->destroy = (SSLDestroy) AES_DestroyContext; - break; + case ssl_calg_rc4: + initFn = (BLapiInitContextFunc)RC4_InitContext; + pwSpec->encode = (SSLCipher)RC4_Encrypt; + pwSpec->decode = (SSLCipher)RC4_Decrypt; + pwSpec->destroy = (SSLDestroy)RC4_DestroyContext; + break; + case ssl_calg_rc2: + initFn = (BLapiInitContextFunc)RC2_InitContext; + mode = NSS_RC2_CBC; + optArg1 = cipher_def->key_size; + pwSpec->encode = (SSLCipher)RC2_Encrypt; + pwSpec->decode = (SSLCipher)RC2_Decrypt; + pwSpec->destroy = (SSLDestroy)RC2_DestroyContext; + break; + case ssl_calg_des: + initFn = (BLapiInitContextFunc)DES_InitContext; + mode = NSS_DES_CBC; + optArg1 = server_encrypts; + pwSpec->encode = (SSLCipher)DES_Encrypt; + pwSpec->decode = (SSLCipher)DES_Decrypt; + pwSpec->destroy = (SSLDestroy)DES_DestroyContext; + break; + case ssl_calg_3des: + initFn = (BLapiInitContextFunc)DES_InitContext; + mode = NSS_DES_EDE3_CBC; + optArg1 = server_encrypts; + pwSpec->encode = (SSLCipher)DES_Encrypt; + pwSpec->decode = (SSLCipher)DES_Decrypt; + pwSpec->destroy = (SSLDestroy)DES_DestroyContext; + break; + case ssl_calg_aes: + initFn = (BLapiInitContextFunc)AES_InitContext; + mode = NSS_AES_CBC; + optArg1 = server_encrypts; + optArg2 = AES_BLOCK_SIZE; + pwSpec->encode = (SSLCipher)AES_Encrypt; + pwSpec->decode = (SSLCipher)AES_Decrypt; + pwSpec->destroy = (SSLDestroy)AES_DestroyContext; + break; - case ssl_calg_camellia: - initFn = (BLapiInitContextFunc)Camellia_InitContext; - mode = NSS_CAMELLIA_CBC; - optArg1 = server_encrypts; - optArg2 = CAMELLIA_BLOCK_SIZE; - pwSpec->encode = (SSLCipher) Camellia_Encrypt; - pwSpec->decode = (SSLCipher) Camellia_Decrypt; - pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext; - break; + case ssl_calg_camellia: + initFn = (BLapiInitContextFunc)Camellia_InitContext; + mode = NSS_CAMELLIA_CBC; + optArg1 = server_encrypts; + optArg2 = CAMELLIA_BLOCK_SIZE; + pwSpec->encode = (SSLCipher)Camellia_Encrypt; + pwSpec->decode = (SSLCipher)Camellia_Decrypt; + pwSpec->destroy = (SSLDestroy)Camellia_DestroyContext; + break; - case ssl_calg_seed: - initFn = (BLapiInitContextFunc)SEED_InitContext; - mode = NSS_SEED_CBC; - optArg1 = server_encrypts; - optArg2 = SEED_BLOCK_SIZE; - pwSpec->encode = (SSLCipher) SEED_Encrypt; - pwSpec->decode = (SSLCipher) SEED_Decrypt; - pwSpec->destroy = (SSLDestroy) SEED_DestroyContext; - break; + case ssl_calg_seed: + initFn = (BLapiInitContextFunc)SEED_InitContext; + mode = NSS_SEED_CBC; + optArg1 = server_encrypts; + optArg2 = SEED_BLOCK_SIZE; + pwSpec->encode = (SSLCipher)SEED_Encrypt; + pwSpec->decode = (SSLCipher)SEED_Decrypt; + pwSpec->destroy = (SSLDestroy)SEED_DestroyContext; + break; - case ssl_calg_idea: - case ssl_calg_fortezza : - default: - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto bail_out; + case ssl_calg_idea: + case ssl_calg_fortezza: + default: + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + goto bail_out; } rv = (*initFn)(serverContext, - pwSpec->server.write_key_item.data, - pwSpec->server.write_key_item.len, - pwSpec->server.write_iv_item.data, - mode, optArg1, optArg2); + pwSpec->server.write_key_item.data, + pwSpec->server.write_key_item.len, + pwSpec->server.write_iv_item.data, + mode, optArg1, optArg2); if (rv != SECSuccess) { - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto bail_out; + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + goto bail_out; } switch (calg) { - case ssl_calg_des: - case ssl_calg_3des: - case ssl_calg_aes: - case ssl_calg_camellia: - case ssl_calg_seed: - /* For block ciphers, if the server is encrypting, then the client - * is decrypting, and vice versa. - */ - optArg1 = !optArg1; - break; - /* kill warnings. */ - case ssl_calg_null: - case ssl_calg_rc4: - case ssl_calg_rc2: - case ssl_calg_idea: - case ssl_calg_fortezza: - case ssl_calg_aes_gcm: - break; + case ssl_calg_des: + case ssl_calg_3des: + case ssl_calg_aes: + case ssl_calg_camellia: + case ssl_calg_seed: + /* For block ciphers, if the server is encrypting, then the client + * is decrypting, and vice versa. + */ + optArg1 = !optArg1; + break; + /* kill warnings. */ + case ssl_calg_null: + case ssl_calg_rc4: + case ssl_calg_rc2: + case ssl_calg_idea: + case ssl_calg_fortezza: + case ssl_calg_aes_gcm: + case ssl_calg_chacha20: + break; } rv = (*initFn)(clientContext, - pwSpec->client.write_key_item.data, - pwSpec->client.write_key_item.len, - pwSpec->client.write_iv_item.data, - mode, optArg1, optArg2); + pwSpec->client.write_key_item.data, + pwSpec->client.write_key_item.len, + pwSpec->client.write_iv_item.data, + mode, optArg1, optArg2); if (rv != SECSuccess) { - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto bail_out; + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + goto bail_out; } pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; @@ -1822,24 +1886,25 @@ bail_out: } #endif -/* This function should probably be moved to pk11wrap and be named +/* This function should probably be moved to pk11wrap and be named * PK11_ParamFromIVAndEffectiveKeyBits */ static SECItem * ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) { - SECItem * param = PK11_ParamFromIV(mtype, iv); - if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { - switch (mtype) { - case CKM_RC2_KEY_GEN: - case CKM_RC2_ECB: - case CKM_RC2_CBC: - case CKM_RC2_MAC: - case CKM_RC2_MAC_GENERAL: - case CKM_RC2_CBC_PAD: - *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; - default: break; - } + SECItem *param = PK11_ParamFromIV(mtype, iv); + if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { + switch (mtype) { + case CKM_RC2_KEY_GEN: + case CKM_RC2_ECB: + case CKM_RC2_CBC: + case CKM_RC2_MAC: + case CKM_RC2_MAC_GENERAL: + case CKM_RC2_CBC_PAD: + *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; + default: + break; + } } return param; } @@ -1858,40 +1923,41 @@ ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) */ static unsigned int ssl3_BuildRecordPseudoHeader(unsigned char *out, - SSL3SequenceNumber seq_num, - SSL3ContentType type, - PRBool includesVersion, - SSL3ProtocolVersion version, - PRBool isDTLS, - int length) + SSL3SequenceNumber seq_num, + SSL3ContentType type, + PRBool includesVersion, + SSL3ProtocolVersion version, + PRBool isDTLS, + int length) { out[0] = (unsigned char)(seq_num.high >> 24); out[1] = (unsigned char)(seq_num.high >> 16); - out[2] = (unsigned char)(seq_num.high >> 8); - out[3] = (unsigned char)(seq_num.high >> 0); - out[4] = (unsigned char)(seq_num.low >> 24); - out[5] = (unsigned char)(seq_num.low >> 16); - out[6] = (unsigned char)(seq_num.low >> 8); - out[7] = (unsigned char)(seq_num.low >> 0); + out[2] = (unsigned char)(seq_num.high >> 8); + out[3] = (unsigned char)(seq_num.high >> 0); + out[4] = (unsigned char)(seq_num.low >> 24); + out[5] = (unsigned char)(seq_num.low >> 16); + out[6] = (unsigned char)(seq_num.low >> 8); + out[7] = (unsigned char)(seq_num.low >> 0); out[8] = type; /* SSL3 MAC doesn't include the record's version field. */ if (!includesVersion) { - out[9] = MSB(length); - out[10] = LSB(length); - return 11; + out[9] = MSB(length); + out[10] = LSB(length); + return 11; } /* TLS MAC and AEAD additional data include version. */ if (isDTLS) { - SSL3ProtocolVersion dtls_version; + SSL3ProtocolVersion dtls_version; - dtls_version = dtls_TLSVersionToDTLSVersion(version); - out[9] = MSB(dtls_version); - out[10] = LSB(dtls_version); - } else { - out[9] = MSB(version); - out[10] = LSB(version); + dtls_version = dtls_TLSVersionToDTLSVersion(version); + out[9] = MSB(dtls_version); + out[10] = LSB(dtls_version); + } + else { + out[9] = MSB(version); + out[10] = LSB(version); } out[11] = MSB(length); out[12] = LSB(length); @@ -1900,62 +1966,65 @@ ssl3_BuildRecordPseudoHeader(unsigned char *out, static SECStatus ssl3_AESGCM(ssl3KeyMaterial *keys, - PRBool doDecrypt, - unsigned char *out, - int *outlen, - int maxout, - const unsigned char *in, - int inlen, - const unsigned char *additionalData, - int additionalDataLen) + PRBool doDecrypt, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen, + const unsigned char *additionalData, + int additionalDataLen) { - SECItem param; - SECStatus rv = SECFailure; - unsigned char nonce[12]; - unsigned int uOutLen; - CK_GCM_PARAMS gcmParams; + SECItem param; + SECStatus rv = SECFailure; + unsigned char nonce[12]; + unsigned int uOutLen; + CK_GCM_PARAMS gcmParams; - static const int tagSize = 16; - static const int explicitNonceLen = 8; + const int tagSize = bulk_cipher_defs[cipher_aes_128_gcm].tag_size; + const int explicitNonceLen = + bulk_cipher_defs[cipher_aes_128_gcm].explicit_nonce_size; /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the * nonce is formed. */ memcpy(nonce, keys->write_iv, 4); if (doDecrypt) { - memcpy(nonce + 4, in, explicitNonceLen); - in += explicitNonceLen; - inlen -= explicitNonceLen; - *outlen = 0; - } else { - if (maxout < explicitNonceLen) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - return SECFailure; + memcpy(nonce + 4, in, explicitNonceLen); + in += explicitNonceLen; + inlen -= explicitNonceLen; + *outlen = 0; + } + else { + if (maxout < explicitNonceLen) { + PORT_SetError(SEC_ERROR_INPUT_LEN); + return SECFailure; } - /* Use the 64-bit sequence number as the explicit nonce. */ - memcpy(nonce + 4, additionalData, explicitNonceLen); - memcpy(out, additionalData, explicitNonceLen); - out += explicitNonceLen; - maxout -= explicitNonceLen; - *outlen = explicitNonceLen; + /* Use the 64-bit sequence number as the explicit nonce. */ + memcpy(nonce + 4, additionalData, explicitNonceLen); + memcpy(out, additionalData, explicitNonceLen); + out += explicitNonceLen; + maxout -= explicitNonceLen; + *outlen = explicitNonceLen; } param.type = siBuffer; - param.data = (unsigned char *) &gcmParams; + param.data = (unsigned char *)&gcmParams; param.len = sizeof(gcmParams); gcmParams.pIv = nonce; gcmParams.ulIvLen = sizeof(nonce); - gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ + gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ gcmParams.ulAADLen = additionalDataLen; gcmParams.ulTagBits = tagSize * 8; if (doDecrypt) { - rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); - } else { - rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); + rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, + maxout, in, inlen); } - *outlen += (int) uOutLen; + else { + rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, + maxout, in, inlen); + } + *outlen += (int)uOutLen; return rv; } @@ -1963,76 +2032,129 @@ ssl3_AESGCM(ssl3KeyMaterial *keys, #ifndef NO_PKCS11_BYPASS static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, - PRBool doDecrypt, - unsigned char *out, - int *outlen, - int maxout, - const unsigned char *in, - int inlen, - const unsigned char *additionalData, - int additionalDataLen) + PRBool doDecrypt, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen, + const unsigned char *additionalData, + int additionalDataLen) { - SECStatus rv = SECFailure; - unsigned char nonce[12]; - unsigned int uOutLen; - AESContext *cx; - CK_GCM_PARAMS gcmParams; + SECStatus rv = SECFailure; + unsigned char nonce[12]; + unsigned int uOutLen; + AESContext *cx; + CK_GCM_PARAMS gcmParams; - static const int tagSize = 16; - static const int explicitNonceLen = 8; + const int tagSize = bulk_cipher_defs[cipher_aes_128_gcm].tag_size; + const int explicitNonceLen = + bulk_cipher_defs[cipher_aes_128_gcm].explicit_nonce_size; /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the * nonce is formed. */ PORT_Assert(keys->write_iv_item.len == 4); if (keys->write_iv_item.len != 4) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } memcpy(nonce, keys->write_iv_item.data, 4); if (doDecrypt) { - memcpy(nonce + 4, in, explicitNonceLen); - in += explicitNonceLen; - inlen -= explicitNonceLen; - *outlen = 0; - } else { - if (maxout < explicitNonceLen) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - return SECFailure; + memcpy(nonce + 4, in, explicitNonceLen); + in += explicitNonceLen; + inlen -= explicitNonceLen; + *outlen = 0; + } + else { + if (maxout < explicitNonceLen) { + PORT_SetError(SEC_ERROR_INPUT_LEN); + return SECFailure; } - /* Use the 64-bit sequence number as the explicit nonce. */ - memcpy(nonce + 4, additionalData, explicitNonceLen); - memcpy(out, additionalData, explicitNonceLen); - out += explicitNonceLen; - maxout -= explicitNonceLen; - *outlen = explicitNonceLen; + /* Use the 64-bit sequence number as the explicit nonce. */ + memcpy(nonce + 4, additionalData, explicitNonceLen); + memcpy(out, additionalData, explicitNonceLen); + out += explicitNonceLen; + maxout -= explicitNonceLen; + *outlen = explicitNonceLen; } gcmParams.pIv = nonce; gcmParams.ulIvLen = sizeof(nonce); - gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ + gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ gcmParams.ulAADLen = additionalDataLen; gcmParams.ulTagBits = tagSize * 8; cx = (AESContext *)keys->cipher_context; rv = AES_InitContext(cx, keys->write_key_item.data, - keys->write_key_item.len, - (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, - AES_BLOCK_SIZE); + keys->write_key_item.len, + (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, + AES_BLOCK_SIZE); if (rv != SECSuccess) { - return rv; + return rv; } if (doDecrypt) { - rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); - } else { - rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); + rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); + } + else { + rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); } AES_DestroyContext(cx, PR_FALSE); - *outlen += (int) uOutLen; + *outlen += (int)uOutLen; return rv; } #endif +static SECStatus +ssl3_ChaCha20Poly1305(ssl3KeyMaterial *keys, PRBool doDecrypt, + unsigned char *out, int *outlen, int maxout, + const unsigned char *in, int inlen, + const unsigned char *additionalData, + int additionalDataLen) +{ + size_t i; + SECItem param; + SECStatus rv = SECFailure; + unsigned int uOutLen; + unsigned char nonce[12]; + CK_NSS_AEAD_PARAMS aeadParams; + + const int tagSize = bulk_cipher_defs[cipher_chacha20].tag_size; + + /* See + * https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2 + * for details of how the nonce is formed. */ + PORT_Memcpy(nonce, keys->write_iv, 12); + + /* XOR the last 8 bytes of the IV with the sequence number. */ + PORT_Assert(additionalDataLen >= 8); + for (i = 0; i < 8; ++i) { + nonce[4 + i] ^= additionalData[i]; + } + + param.type = siBuffer; + param.len = sizeof(aeadParams); + param.data = (unsigned char *)&aeadParams; + memset(&aeadParams, 0, sizeof(aeadParams)); + aeadParams.pNonce = nonce; + aeadParams.ulNonceLen = sizeof(nonce); + aeadParams.pAAD = (unsigned char *)additionalData; + aeadParams.ulAADLen = additionalDataLen; + aeadParams.ulTagLen = tagSize; + + if (doDecrypt) { + rv = PK11_Decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, + out, &uOutLen, maxout, in, inlen); + } + else { + rv = PK11_Encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, + out, &uOutLen, maxout, in, inlen); + } + *outlen = (int)uOutLen; + + return rv; +} + /* Initialize encryption and MAC contexts for pending spec. * Master Secret already is derived. * Caller holds Spec write lock. @@ -2040,74 +2162,84 @@ ssl3_AESGCMBypass(ssl3KeyMaterial *keys, static SECStatus ssl3_InitPendingContextsPKCS11(sslSocket *ss) { - ssl3CipherSpec * pwSpec; - const ssl3BulkCipherDef *cipher_def; - PK11Context * serverContext = NULL; - PK11Context * clientContext = NULL; - SECItem * param; - CK_MECHANISM_TYPE mechanism; - CK_MECHANISM_TYPE mac_mech; - CK_ULONG macLength; - CK_ULONG effKeyBits; - SECItem iv; - SECItem mac_param; - SSLCipherAlgorithm calg; + ssl3CipherSpec *pwSpec; + const ssl3BulkCipherDef *cipher_def; + PK11Context *serverContext = NULL; + PK11Context *clientContext = NULL; + SECItem *param; + CK_MECHANISM_TYPE mechanism; + CK_MECHANISM_TYPE mac_mech; + CK_ULONG macLength; + CK_ULONG effKeyBits; + SECItem iv; + SECItem mac_param; + SSLCipherAlgorithm calg; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); - pwSpec = ss->ssl3.pwSpec; - cipher_def = pwSpec->cipher_def; - macLength = pwSpec->mac_size; - calg = cipher_def->calg; + pwSpec = ss->ssl3.pwSpec; + cipher_def = pwSpec->cipher_def; + macLength = pwSpec->mac_size; + calg = cipher_def->calg; PORT_Assert(alg2Mech[calg].calg == calg); pwSpec->client.write_mac_context = NULL; pwSpec->server.write_mac_context = NULL; - if (calg == calg_aes_gcm) { - pwSpec->encode = NULL; - pwSpec->decode = NULL; - pwSpec->destroy = NULL; - pwSpec->encodeContext = NULL; - pwSpec->decodeContext = NULL; - pwSpec->aead = ssl3_AESGCM; - return SECSuccess; + if (cipher_def->type == type_aead) { + pwSpec->encode = NULL; + pwSpec->decode = NULL; + pwSpec->destroy = NULL; + pwSpec->encodeContext = NULL; + pwSpec->decodeContext = NULL; + switch (calg) { + case calg_aes_gcm: + pwSpec->aead = ssl3_AESGCM; + break; + case calg_chacha20: + pwSpec->aead = ssl3_ChaCha20Poly1305; + break; + default: + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + return SECSuccess; } - /* - ** Now setup the MAC contexts, + /* + ** Now setup the MAC contexts, ** crypto contexts are setup below. */ - mac_mech = pwSpec->mac_def->mmech; + mac_mech = pwSpec->mac_def->mmech; mac_param.data = (unsigned char *)&macLength; - mac_param.len = sizeof(macLength); + mac_param.len = sizeof(macLength); mac_param.type = 0; pwSpec->client.write_mac_context = PK11_CreateContextBySymKey( - mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); - if (pwSpec->client.write_mac_context == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); + if (pwSpec->client.write_mac_context == NULL) { + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } pwSpec->server.write_mac_context = PK11_CreateContextBySymKey( - mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); + mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); if (pwSpec->server.write_mac_context == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } - /* + /* ** Now setup the crypto contexts. */ if (calg == calg_null) { - pwSpec->encode = Null_Cipher; - pwSpec->decode = Null_Cipher; - pwSpec->destroy = NULL; - return SECSuccess; + pwSpec->encode = Null_Cipher; + pwSpec->decode = Null_Cipher; + pwSpec->destroy = NULL; + return SECSuccess; } mechanism = ssl3_Alg2Mech(calg); effKeyBits = cipher_def->key_size * BPB; @@ -2116,49 +2248,51 @@ ssl3_InitPendingContextsPKCS11(sslSocket *ss) * build the server context */ iv.data = pwSpec->server.write_iv; - iv.len = cipher_def->iv_size; + iv.len = cipher_def->iv_size; param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); if (param == NULL) { - ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); + goto fail; } serverContext = PK11_CreateContextBySymKey(mechanism, - (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT), - pwSpec->server.write_key, param); + (ss->sec.isServer ? CKA_ENCRYPT + : CKA_DECRYPT), + pwSpec->server.write_key, param); iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); if (iv.data) - PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); + PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); SECITEM_FreeItem(param, PR_TRUE); if (serverContext == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } /* * build the client context */ iv.data = pwSpec->client.write_iv; - iv.len = cipher_def->iv_size; + iv.len = cipher_def->iv_size; param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); if (param == NULL) { - ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); + goto fail; } clientContext = PK11_CreateContextBySymKey(mechanism, - (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT), - pwSpec->client.write_key, param); + (ss->sec.isServer ? CKA_DECRYPT + : CKA_ENCRYPT), + pwSpec->client.write_key, param); iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); if (iv.data) - PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); - SECITEM_FreeItem(param,PR_TRUE); + PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); + SECITEM_FreeItem(param, PR_TRUE); if (clientContext == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } - pwSpec->encode = (SSLCipher) PK11_CipherOp; - pwSpec->decode = (SSLCipher) PK11_CipherOp; - pwSpec->destroy = (SSLDestroy) PK11_DestroyContext; + pwSpec->encode = (SSLCipher)PK11_CipherOp; + pwSpec->decode = (SSLCipher)PK11_CipherOp; + pwSpec->destroy = (SSLDestroy)PK11_DestroyContext; pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; @@ -2171,26 +2305,43 @@ ssl3_InitPendingContextsPKCS11(sslSocket *ss) return SECSuccess; fail: - if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE); - if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE); + if (serverContext != NULL) + PK11_DestroyContext(serverContext, PR_TRUE); + if (clientContext != NULL) + PK11_DestroyContext(clientContext, PR_TRUE); if (pwSpec->client.write_mac_context != NULL) { - PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE); - pwSpec->client.write_mac_context = NULL; + PK11_DestroyContext(pwSpec->client.write_mac_context, PR_TRUE); + pwSpec->client.write_mac_context = NULL; } if (pwSpec->server.write_mac_context != NULL) { - PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE); - pwSpec->server.write_mac_context = NULL; + PK11_DestroyContext(pwSpec->server.write_mac_context, PR_TRUE); + pwSpec->server.write_mac_context = NULL; } return SECFailure; } +/* Returns whether we can bypass PKCS#11 for a given cipher algorithm. + * + * We do not support PKCS#11 bypass for ChaCha20/Poly1305. + */ +static PRBool +ssl3_CanBypassCipher(SSLCipherAlgorithm calg) +{ + switch (calg) { + case calg_chacha20: + return PR_FALSE; + default: + return PR_TRUE; + } +} + /* Complete the initialization of all keys, ciphers, MACs and their contexts * for the pending Cipher Spec. - * Called from: ssl3_SendClientKeyExchange (for Full handshake) - * ssl3_HandleRSAClientKeyExchange (for Full handshake) - * ssl3_HandleServerHello (for session restart) - * ssl3_HandleClientHello (for session restart) + * Called from: ssl3_SendClientKeyExchange (for Full handshake) + * ssl3_HandleRSAClientKeyExchange (for Full handshake) + * ssl3_HandleServerHello (for session restart) + * ssl3_HandleClientHello (for session restart) * Sets error code, but caller probably should override to disambiguate. * NULL pms means re-use old master_secret. * @@ -2204,89 +2355,93 @@ fail: SECStatus ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms) { - ssl3CipherSpec * pwSpec; - ssl3CipherSpec * cwSpec; - SECStatus rv; + ssl3CipherSpec *pwSpec; + ssl3CipherSpec *cwSpec; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - ssl_GetSpecWriteLock(ss); /**************************************/ + ssl_GetSpecWriteLock(ss); /**************************************/ PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); - pwSpec = ss->ssl3.pwSpec; - cwSpec = ss->ssl3.cwSpec; + pwSpec = ss->ssl3.pwSpec; + cwSpec = ss->ssl3.cwSpec; if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) { - rv = ssl3_DeriveMasterSecret(ss, pms); - if (rv != SECSuccess) { - goto done; /* err code set by ssl3_DeriveMasterSecret */ - } + rv = ssl3_DeriveMasterSecret(ss, pms); + if (rv != SECSuccess) { + goto done; /* err code set by ssl3_DeriveMasterSecret */ + } } #ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) { - /* Double Bypass succeeded in extracting the master_secret */ - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - PRBool isTLS = (PRBool)(kea_def->tls_keygen || + if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data && + ssl3_CanBypassCipher(ss->ssl3.pwSpec->cipher_def->calg)) { + /* Double Bypass succeeded in extracting the master_secret */ + const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; + PRBool isTLS = (PRBool)(kea_def->tls_keygen || (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); - pwSpec->bypassCiphers = PR_TRUE; - rv = ssl3_KeyAndMacDeriveBypass( pwSpec, - (const unsigned char *)&ss->ssl3.hs.client_random, - (const unsigned char *)&ss->ssl3.hs.server_random, - isTLS, - (PRBool)(kea_def->is_limited)); - if (rv == SECSuccess) { - rv = ssl3_InitPendingContextsBypass(ss); - } - } else + pwSpec->bypassCiphers = PR_TRUE; + rv = ssl3_KeyAndMacDeriveBypass(pwSpec, + (const unsigned char *)&ss->ssl3.hs.client_random, + (const unsigned char *)&ss->ssl3.hs.server_random, + isTLS, + (PRBool)(kea_def->is_limited)); + if (rv == SECSuccess) { + rv = ssl3_InitPendingContextsBypass(ss); + } + } + else #endif - if (pwSpec->master_secret) { - rv = ssl3_DeriveConnectionKeysPKCS11(ss); - if (rv == SECSuccess) { - rv = ssl3_InitPendingContextsPKCS11(ss); - } - } else { - PORT_Assert(pwSpec->master_secret); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - rv = SECFailure; + if (pwSpec->master_secret) { + rv = ssl3_DeriveConnectionKeysPKCS11(ss); + if (rv == SECSuccess) { + rv = ssl3_InitPendingContextsPKCS11(ss); + } + } + else { + PORT_Assert(pwSpec->master_secret); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + rv = SECFailure; } if (rv != SECSuccess) { - goto done; + goto done; } /* Generic behaviors -- common to all crypto methods */ if (!IS_DTLS(ss)) { - pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; - } else { - if (cwSpec->epoch == PR_UINT16_MAX) { - /* The problem here is that we have rehandshaked too many - * times (you are not allowed to wrap the epoch). The - * spec says you should be discarding the connection - * and start over, so not much we can do here. */ - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - rv = SECFailure; - goto done; - } - /* The sequence number has the high 16 bits as the epoch. */ - pwSpec->epoch = cwSpec->epoch + 1; - pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = - pwSpec->epoch << 16; + pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; + } + else { + if (cwSpec->epoch == PR_UINT16_MAX) { + /* The problem here is that we have rehandshaked too many + * times (you are not allowed to wrap the epoch). The + * spec says you should be discarding the connection + * and start over, so not much we can do here. */ + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + rv = SECFailure; + goto done; + } + /* The sequence number has the high 16 bits as the epoch. */ + pwSpec->epoch = cwSpec->epoch + 1; + pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = + pwSpec->epoch << 16; - dtls_InitRecvdRecords(&pwSpec->recvdRecords); + dtls_InitRecvdRecords(&pwSpec->recvdRecords); } pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0; done: - ssl_ReleaseSpecWriteLock(ss); /******************************/ + ssl_ReleaseSpecWriteLock(ss); /******************************/ if (rv != SECSuccess) - ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); + ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return rv; } /* * 60 bytes is 3 times the maximum length MAC size that is supported. */ -static const unsigned char mac_pad_1 [60] = { +static const unsigned char mac_pad_1[60] = { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, @@ -2296,7 +2451,7 @@ static const unsigned char mac_pad_1 [60] = { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36 }; -static const unsigned char mac_pad_2 [60] = { +static const unsigned char mac_pad_2[60] = { 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, @@ -2312,126 +2467,129 @@ static const unsigned char mac_pad_2 [60] = { */ static SECStatus ssl3_ComputeRecordMAC( - ssl3CipherSpec * spec, - PRBool useServerMacKey, + ssl3CipherSpec *spec, + PRBool useServerMacKey, const unsigned char *header, - unsigned int headerLen, - const SSL3Opaque * input, - int inputLength, - unsigned char * outbuf, - unsigned int * outLength) + unsigned int headerLen, + const SSL3Opaque *input, + int inputLength, + unsigned char *outbuf, + unsigned int *outLength) { - const ssl3MACDef * mac_def; - SECStatus rv; + const ssl3MACDef *mac_def; + SECStatus rv; PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); mac_def = spec->mac_def; if (mac_def->mac == mac_null) { - *outLength = 0; - return SECSuccess; + *outLength = 0; + return SECSuccess; } #ifndef NO_PKCS11_BYPASS if (spec->bypassCiphers) { - /* bypass version */ - const SECHashObject *hashObj = NULL; - unsigned int pad_bytes = 0; - PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; + /* bypass version */ + const SECHashObject *hashObj = NULL; + unsigned int pad_bytes = 0; + PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; - switch (mac_def->mac) { - case ssl_mac_null: - *outLength = 0; - return SECSuccess; - case ssl_mac_md5: - pad_bytes = 48; - hashObj = HASH_GetRawHashObject(HASH_AlgMD5); - break; - case ssl_mac_sha: - pad_bytes = 40; - hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); - break; - case ssl_hmac_md5: /* used with TLS */ - hashObj = HASH_GetRawHashObject(HASH_AlgMD5); - break; - case ssl_hmac_sha: /* used with TLS */ - hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); - break; - case ssl_hmac_sha256: /* used with TLS */ - hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); - break; - default: - break; - } - if (!hashObj) { - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } + switch (mac_def->mac) { + case ssl_mac_null: + *outLength = 0; + return SECSuccess; + case ssl_mac_md5: + pad_bytes = 48; + hashObj = HASH_GetRawHashObject(HASH_AlgMD5); + break; + case ssl_mac_sha: + pad_bytes = 40; + hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); + break; + case ssl_hmac_md5: /* used with TLS */ + hashObj = HASH_GetRawHashObject(HASH_AlgMD5); + break; + case ssl_hmac_sha: /* used with TLS */ + hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); + break; + case ssl_hmac_sha256: /* used with TLS */ + hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); + break; + default: + break; + } + if (!hashObj) { + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } - if (spec->version <= SSL_LIBRARY_VERSION_3_0) { - unsigned int tempLen; - unsigned char temp[MAX_MAC_LENGTH]; + if (spec->version <= SSL_LIBRARY_VERSION_3_0) { + unsigned int tempLen; + unsigned char temp[MAX_MAC_LENGTH]; - /* compute "inner" part of SSL3 MAC */ - hashObj->begin(write_mac_context); - if (useServerMacKey) - hashObj->update(write_mac_context, - spec->server.write_mac_key_item.data, - spec->server.write_mac_key_item.len); - else - hashObj->update(write_mac_context, - spec->client.write_mac_key_item.data, - spec->client.write_mac_key_item.len); - hashObj->update(write_mac_context, mac_pad_1, pad_bytes); - hashObj->update(write_mac_context, header, headerLen); - hashObj->update(write_mac_context, input, inputLength); - hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); + /* compute "inner" part of SSL3 MAC */ + hashObj->begin(write_mac_context); + if (useServerMacKey) + hashObj->update(write_mac_context, + spec->server.write_mac_key_item.data, + spec->server.write_mac_key_item.len); + else + hashObj->update(write_mac_context, + spec->client.write_mac_key_item.data, + spec->client.write_mac_key_item.len); + hashObj->update(write_mac_context, mac_pad_1, pad_bytes); + hashObj->update(write_mac_context, header, headerLen); + hashObj->update(write_mac_context, input, inputLength); + hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); - /* compute "outer" part of SSL3 MAC */ - hashObj->begin(write_mac_context); - if (useServerMacKey) - hashObj->update(write_mac_context, - spec->server.write_mac_key_item.data, - spec->server.write_mac_key_item.len); - else - hashObj->update(write_mac_context, - spec->client.write_mac_key_item.data, - spec->client.write_mac_key_item.len); - hashObj->update(write_mac_context, mac_pad_2, pad_bytes); - hashObj->update(write_mac_context, temp, tempLen); - hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); - rv = SECSuccess; - } else { /* is TLS */ + /* compute "outer" part of SSL3 MAC */ + hashObj->begin(write_mac_context); + if (useServerMacKey) + hashObj->update(write_mac_context, + spec->server.write_mac_key_item.data, + spec->server.write_mac_key_item.len); + else + hashObj->update(write_mac_context, + spec->client.write_mac_key_item.data, + spec->client.write_mac_key_item.len); + hashObj->update(write_mac_context, mac_pad_2, pad_bytes); + hashObj->update(write_mac_context, temp, tempLen); + hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); + rv = SECSuccess; + } + else { /* is TLS */ #define cx ((HMACContext *)write_mac_context) - if (useServerMacKey) { - rv = HMAC_Init(cx, hashObj, - spec->server.write_mac_key_item.data, - spec->server.write_mac_key_item.len, PR_FALSE); - } else { - rv = HMAC_Init(cx, hashObj, - spec->client.write_mac_key_item.data, - spec->client.write_mac_key_item.len, PR_FALSE); - } - if (rv == SECSuccess) { - HMAC_Begin(cx); - HMAC_Update(cx, header, headerLen); - HMAC_Update(cx, input, inputLength); - rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); - HMAC_Destroy(cx, PR_FALSE); - } + if (useServerMacKey) { + rv = HMAC_Init(cx, hashObj, + spec->server.write_mac_key_item.data, + spec->server.write_mac_key_item.len, PR_FALSE); + } + else { + rv = HMAC_Init(cx, hashObj, + spec->client.write_mac_key_item.data, + spec->client.write_mac_key_item.len, PR_FALSE); + } + if (rv == SECSuccess) { + HMAC_Begin(cx); + HMAC_Update(cx, header, headerLen); + HMAC_Update(cx, input, inputLength); + rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); + HMAC_Destroy(cx, PR_FALSE); + } #undef cx - } - } else + } + } + else #endif { - PK11Context *mac_context = - (useServerMacKey ? spec->server.write_mac_context - : spec->client.write_mac_context); - rv = PK11_DigestBegin(mac_context); - rv |= PK11_DigestOp(mac_context, header, headerLen); - rv |= PK11_DigestOp(mac_context, input, inputLength); - rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); + PK11Context *mac_context = + (useServerMacKey ? spec->server.write_mac_context + : spec->client.write_mac_context); + rv = PK11_DigestBegin(mac_context); + rv |= PK11_DigestOp(mac_context, header, headerLen); + rv |= PK11_DigestOp(mac_context, input, inputLength); + rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); } PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size); @@ -2439,8 +2597,8 @@ ssl3_ComputeRecordMAC( PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength)); if (rv != SECSuccess) { - rv = SECFailure; - ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); + rv = SECFailure; + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); } return rv; } @@ -2453,51 +2611,51 @@ ssl3_ComputeRecordMAC( */ static SECStatus ssl3_ComputeRecordMACConstantTime( - ssl3CipherSpec * spec, - PRBool useServerMacKey, + ssl3CipherSpec *spec, + PRBool useServerMacKey, const unsigned char *header, - unsigned int headerLen, - const SSL3Opaque * input, - int inputLen, - int originalLen, - unsigned char * outbuf, - unsigned int * outLen) + unsigned int headerLen, + const SSL3Opaque *input, + int inputLen, + int originalLen, + unsigned char *outbuf, + unsigned int *outLen) { - CK_MECHANISM_TYPE macType; + CK_MECHANISM_TYPE macType; CK_NSS_MAC_CONSTANT_TIME_PARAMS params; - SECItem param, inputItem, outputItem; - SECStatus rv; - PK11SymKey * key; + SECItem param, inputItem, outputItem; + SECStatus rv; + PK11SymKey *key; PORT_Assert(inputLen >= spec->mac_size); PORT_Assert(originalLen >= inputLen); if (spec->bypassCiphers) { - /* This function doesn't support PKCS#11 bypass. We fallback on the - * non-constant time version. */ - goto fallback; + /* This function doesn't support PKCS#11 bypass. We fallback on the + * non-constant time version. */ + goto fallback; } if (spec->mac_def->mac == mac_null) { - *outLen = 0; - return SECSuccess; + *outLen = 0; + return SECSuccess; } macType = CKM_NSS_HMAC_CONSTANT_TIME; if (spec->version <= SSL_LIBRARY_VERSION_3_0) { - macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; + macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; } params.macAlg = spec->mac_def->mmech; params.ulBodyTotalLen = originalLen; - params.pHeader = (unsigned char *) header; /* const cast */ + params.pHeader = (unsigned char *)header; /* const cast */ params.ulHeaderLen = headerLen; - param.data = (unsigned char*) ¶ms; + param.data = (unsigned char *)¶ms; param.len = sizeof(params); param.type = 0; - inputItem.data = (unsigned char *) input; + inputItem.data = (unsigned char *)input; inputItem.len = inputLen; inputItem.type = 0; @@ -2507,19 +2665,19 @@ ssl3_ComputeRecordMACConstantTime( key = spec->server.write_mac_key; if (!useServerMacKey) { - key = spec->client.write_mac_key; + key = spec->client.write_mac_key; } rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { - goto fallback; - } + if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { + goto fallback; + } - *outLen = 0; - rv = SECFailure; - ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); - return rv; + *outLen = 0; + rv = SECFailure; + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); + return rv; } PORT_Assert(outputItem.len == (unsigned)spec->mac_size); @@ -2532,243 +2690,249 @@ fallback: * length already. */ inputLen -= spec->mac_size; return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen, - input, inputLen, outbuf, outLen); + input, inputLen, outbuf, outLen); } static PRBool -ssl3_ClientAuthTokenPresent(sslSessionID *sid) { +ssl3_ClientAuthTokenPresent(sslSessionID *sid) +{ PK11SlotInfo *slot = NULL; PRBool isPresent = PR_TRUE; /* we only care if we are doing client auth */ if (!sid || !sid->u.ssl3.clAuthValid) { - return PR_TRUE; + return PR_TRUE; } /* get the slot */ slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, - sid->u.ssl3.clAuthSlotID); + sid->u.ssl3.clAuthSlotID); if (slot == NULL || - !PK11_IsPresent(slot) || - sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || - sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || - sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || - (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { - isPresent = PR_FALSE; - } + !PK11_IsPresent(slot) || + sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || + sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || + sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || + (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { + isPresent = PR_FALSE; + } if (slot) { - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); } return isPresent; } /* Caller must hold the spec read lock. */ SECStatus -ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, - PRBool isServer, - PRBool isDTLS, - PRBool capRecordVersion, - SSL3ContentType type, - const SSL3Opaque * pIn, - PRUint32 contentLen, - sslBuffer * wrBuf) +ssl3_CompressMACEncryptRecord(ssl3CipherSpec *cwSpec, + PRBool isServer, + PRBool isDTLS, + PRBool capRecordVersion, + SSL3ContentType type, + const SSL3Opaque *pIn, + PRUint32 contentLen, + sslBuffer *wrBuf) { - const ssl3BulkCipherDef * cipher_def; - SECStatus rv; - PRUint32 macLen = 0; - PRUint32 fragLen; - PRUint32 p1Len, p2Len, oddLen = 0; - PRUint16 headerLen; + const ssl3BulkCipherDef *cipher_def; + SECStatus rv; + PRUint32 macLen = 0; + PRUint32 fragLen; + PRUint32 p1Len, p2Len, oddLen = 0; + PRUint16 headerLen; unsigned int ivLen = 0; - int cipherBytes = 0; - unsigned char pseudoHeader[13]; - unsigned int pseudoHeaderLen; + int cipherBytes = 0; + unsigned char pseudoHeader[13]; + unsigned int pseudoHeaderLen; cipher_def = cwSpec->cipher_def; headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; if (cipher_def->type == type_block && - cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { - /* Prepend the per-record explicit IV using technique 2b from - * RFC 4346 section 6.2.3.2: The IV is a cryptographically - * strong random number XORed with the CBC residue from the previous - * record. - */ - ivLen = cipher_def->iv_size; - if (ivLen > wrBuf->space - headerLen) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); - return rv; - } - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen, - &cipherBytes, /* output and actual outLen */ - ivLen, /* max outlen */ - wrBuf->buf + headerLen, - ivLen); /* input and inputLen*/ - if (rv != SECSuccess || cipherBytes != ivLen) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } + cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { + /* Prepend the per-record explicit IV using technique 2b from + * RFC 4346 section 6.2.3.2: The IV is a cryptographically + * strong random number XORed with the CBC residue from the previous + * record. + */ + ivLen = cipher_def->iv_size; + if (ivLen > wrBuf->space - headerLen) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); + return rv; + } + rv = cwSpec->encode(cwSpec->encodeContext, + wrBuf->buf + headerLen, + &cipherBytes, /* output and actual outLen */ + ivLen, /* max outlen */ + wrBuf->buf + headerLen, + ivLen); /* input and inputLen*/ + if (rv != SECSuccess || cipherBytes != ivLen) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } } if (cwSpec->compressor) { - int outlen; - rv = cwSpec->compressor( - cwSpec->compressContext, - wrBuf->buf + headerLen + ivLen, &outlen, - wrBuf->space - headerLen - ivLen, pIn, contentLen); - if (rv != SECSuccess) - return rv; - pIn = wrBuf->buf + headerLen + ivLen; - contentLen = outlen; + int outlen; + rv = cwSpec->compressor( + cwSpec->compressContext, + wrBuf->buf + headerLen + ivLen, &outlen, + wrBuf->space - headerLen - ivLen, pIn, contentLen); + if (rv != SECSuccess) + return rv; + pIn = wrBuf->buf + headerLen + ivLen; + contentLen = outlen; } pseudoHeaderLen = ssl3_BuildRecordPseudoHeader( - pseudoHeader, cwSpec->write_seq_num, type, - cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, - isDTLS, contentLen); + pseudoHeader, cwSpec->write_seq_num, type, + cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, + isDTLS, contentLen); PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader)); if (cipher_def->type == type_aead) { - const int nonceLen = cipher_def->explicit_nonce_size; - const int tagLen = cipher_def->tag_size; + const int nonceLen = cipher_def->explicit_nonce_size; + const int tagLen = cipher_def->tag_size; - if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } + if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } - cipherBytes = contentLen; - rv = cwSpec->aead( - isServer ? &cwSpec->server : &cwSpec->client, - PR_FALSE, /* do encrypt */ - wrBuf->buf + headerLen, /* output */ - &cipherBytes, /* out len */ - wrBuf->space - headerLen, /* max out */ - pIn, contentLen, /* input */ - pseudoHeader, pseudoHeaderLen); - if (rv != SECSuccess) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } - } else { - /* - * Add the MAC - */ - rv = ssl3_ComputeRecordMAC(cwSpec, isServer, - pseudoHeader, pseudoHeaderLen, pIn, contentLen, - wrBuf->buf + headerLen + ivLen + contentLen, &macLen); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); - return SECFailure; - } - p1Len = contentLen; - p2Len = macLen; - fragLen = contentLen + macLen; /* needs to be encrypted */ - PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); + cipherBytes = contentLen; + rv = cwSpec->aead( + isServer ? &cwSpec->server : &cwSpec->client, + PR_FALSE, /* do encrypt */ + wrBuf->buf + headerLen, /* output */ + &cipherBytes, /* out len */ + wrBuf->space - headerLen, /* max out */ + pIn, contentLen, /* input */ + pseudoHeader, pseudoHeaderLen); + if (rv != SECSuccess) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } + } + else { + /* + * Add the MAC + */ + rv = ssl3_ComputeRecordMAC(cwSpec, isServer, + pseudoHeader, pseudoHeaderLen, pIn, contentLen, + wrBuf->buf + headerLen + ivLen + contentLen, + &macLen); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); + return SECFailure; + } + p1Len = contentLen; + p2Len = macLen; + fragLen = contentLen + macLen; /* needs to be encrypted */ + PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); - /* - * Pad the text (if we're doing a block cipher) - * then Encrypt it - */ - if (cipher_def->type == type_block) { - unsigned char * pBuf; - int padding_length; - int i; + /* + * Pad the text (if we're doing a block cipher) + * then Encrypt it + */ + if (cipher_def->type == type_block) { + unsigned char *pBuf; + int padding_length; + int i; - oddLen = contentLen % cipher_def->block_size; - /* Assume blockSize is a power of two */ - padding_length = cipher_def->block_size - 1 - - ((fragLen) & (cipher_def->block_size - 1)); - fragLen += padding_length + 1; - PORT_Assert((fragLen % cipher_def->block_size) == 0); + oddLen = contentLen % cipher_def->block_size; + /* Assume blockSize is a power of two */ + padding_length = cipher_def->block_size - 1 - ((fragLen) & (cipher_def->block_size - 1)); + fragLen += padding_length + 1; + PORT_Assert((fragLen % cipher_def->block_size) == 0); - /* Pad according to TLS rules (also acceptable to SSL3). */ - pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; - for (i = padding_length + 1; i > 0; --i) { - *pBuf-- = padding_length; - } - /* now, if contentLen is not a multiple of block size, fix it */ - p2Len = fragLen - p1Len; - } - if (p1Len < 256) { - oddLen = p1Len; - p1Len = 0; - } else { - p1Len -= oddLen; - } - if (oddLen) { - p2Len += oddLen; - PORT_Assert( (cipher_def->block_size < 2) || \ - (p2Len % cipher_def->block_size) == 0); - memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, - oddLen); - } - if (p1Len > 0) { - int cipherBytesPart1 = -1; - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen + ivLen, /* output */ - &cipherBytesPart1, /* actual outlen */ - p1Len, /* max outlen */ - pIn, p1Len); /* input, and inputlen */ - PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); - if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } - cipherBytes += cipherBytesPart1; - } - if (p2Len > 0) { - int cipherBytesPart2 = -1; - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen + ivLen + p1Len, - &cipherBytesPart2, /* output and actual outLen */ - p2Len, /* max outlen */ - wrBuf->buf + headerLen + ivLen + p1Len, - p2Len); /* input and inputLen*/ - PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); - if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } - cipherBytes += cipherBytesPart2; - } + /* Pad according to TLS rules (also acceptable to SSL3). */ + pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; + for (i = padding_length + 1; i > 0; --i) { + *pBuf-- = padding_length; + } + /* now, if contentLen is not a multiple of block size, fix it */ + p2Len = fragLen - p1Len; + } + if (p1Len < 256) { + oddLen = p1Len; + p1Len = 0; + } + else { + p1Len -= oddLen; + } + if (oddLen) { + p2Len += oddLen; + PORT_Assert((cipher_def->block_size < 2) || + (p2Len % cipher_def->block_size) == 0); + memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, + oddLen); + } + if (p1Len > 0) { + int cipherBytesPart1 = -1; + rv = cwSpec->encode(cwSpec->encodeContext, + wrBuf->buf + headerLen + ivLen, /* output */ + &cipherBytesPart1, /* actual outlen */ + p1Len, /* max outlen */ + pIn, + p1Len); /* input, and inputlen */ + PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int)p1Len); + if (rv != SECSuccess || cipherBytesPart1 != (int)p1Len) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } + cipherBytes += cipherBytesPart1; + } + if (p2Len > 0) { + int cipherBytesPart2 = -1; + rv = cwSpec->encode(cwSpec->encodeContext, + wrBuf->buf + headerLen + ivLen + p1Len, + &cipherBytesPart2, /* output and actual outLen */ + p2Len, /* max outlen */ + wrBuf->buf + headerLen + ivLen + p1Len, + p2Len); /* input and inputLen*/ + PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int)p2Len); + if (rv != SECSuccess || cipherBytesPart2 != (int)p2Len) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } + cipherBytes += cipherBytesPart2; + } } PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); - wrBuf->len = cipherBytes + headerLen; + wrBuf->len = cipherBytes + headerLen; wrBuf->buf[0] = type; if (isDTLS) { - SSL3ProtocolVersion version; + SSL3ProtocolVersion version; - version = dtls_TLSVersionToDTLSVersion(cwSpec->version); - wrBuf->buf[1] = MSB(version); - wrBuf->buf[2] = LSB(version); - wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); - wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); - wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); - wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); - wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); - wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); - wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); - wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); - wrBuf->buf[11] = MSB(cipherBytes); - wrBuf->buf[12] = LSB(cipherBytes); - } else { - SSL3ProtocolVersion version = cwSpec->version; + version = dtls_TLSVersionToDTLSVersion(cwSpec->version); + wrBuf->buf[1] = MSB(version); + wrBuf->buf[2] = LSB(version); + wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); + wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); + wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); + wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); + wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); + wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); + wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); + wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); + wrBuf->buf[11] = MSB(cipherBytes); + wrBuf->buf[12] = LSB(cipherBytes); + } + else { + SSL3ProtocolVersion version = cwSpec->version; - if (capRecordVersion) { - version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); - } - wrBuf->buf[1] = MSB(version); - wrBuf->buf[2] = LSB(version); - wrBuf->buf[3] = MSB(cipherBytes); - wrBuf->buf[4] = LSB(cipherBytes); + if (capRecordVersion || version >= SSL_LIBRARY_VERSION_TLS_1_3) { + version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); + } + + wrBuf->buf[1] = MSB(version); + wrBuf->buf[2] = LSB(version); + wrBuf->buf[3] = MSB(cipherBytes); + wrBuf->buf[4] = LSB(cipherBytes); } ssl3_BumpSequenceNumber(&cwSpec->write_seq_num); @@ -2778,8 +2942,8 @@ ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, /* Process the plain text before sending it. * Returns the number of bytes of plaintext that were successfully sent - * plus the number of bytes of plaintext that were copied into the - * output (write) buffer. + * plus the number of bytes of plaintext that were copied into the + * output (write) buffer. * Returns SECFailure on a hard IO error, memory error, or crypto error. * Does NOT return SECWouldBlock. * @@ -2808,24 +2972,24 @@ ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, * flag to work around such servers. */ PRInt32 -ssl3_SendRecord( sslSocket * ss, - DTLSEpoch epoch, /* DTLS only */ - SSL3ContentType type, - const SSL3Opaque * pIn, /* input buffer */ - PRInt32 nIn, /* bytes of input */ - PRInt32 flags) +ssl3_SendRecord(sslSocket *ss, + DTLSEpoch epoch, /* DTLS only */ + SSL3ContentType type, + const SSL3Opaque *pIn, /* input buffer */ + PRInt32 nIn, /* bytes of input */ + PRInt32 flags) { - sslBuffer * wrBuf = &ss->sec.writeBuf; - SECStatus rv; - PRInt32 totalSent = 0; - PRBool capRecordVersion; + sslBuffer *wrBuf = &ss->sec.writeBuf; + SECStatus rv; + PRInt32 totalSent = 0; + PRBool capRecordVersion; SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", - SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), - nIn)); + SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), + nIn)); PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); if (ss->ssl3.fatalAlertSent) { SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent", @@ -2836,93 +3000,96 @@ ssl3_SendRecord( sslSocket * ss, capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0); if (capRecordVersion) { - /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the - * TLS initial ClientHello. */ - PORT_Assert(!IS_DTLS(ss)); - PORT_Assert(!ss->firstHsDone); - PORT_Assert(type == content_handshake); - PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); + /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the + * TLS initial ClientHello. */ + PORT_Assert(!IS_DTLS(ss)); + PORT_Assert(!ss->firstHsDone); + PORT_Assert(type == content_handshake); + PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); } if (ss->ssl3.initialized == PR_FALSE) { - /* This can happen on a server if the very first incoming record - ** looks like a defective ssl3 record (e.g. too long), and we're - ** trying to send an alert. - */ - PR_ASSERT(type == content_alert); - rv = ssl3_InitState(ss); - if (rv != SECSuccess) { - return SECFailure; /* ssl3_InitState has set the error code. */ - } + /* This can happen on a server if the very first incoming record + ** looks like a defective ssl3 record (e.g. too long), and we're + ** trying to send an alert. + */ + PR_ASSERT(type == content_alert); + rv = ssl3_InitState(ss); + if (rv != SECSuccess) { + return SECFailure; /* ssl3_InitState has set the error code. */ + } } /* check for Token Presence */ if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; } while (nIn > 0) { - PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); - unsigned int spaceNeeded; - unsigned int numRecords; + PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); + unsigned int spaceNeeded; + unsigned int numRecords; - ssl_GetSpecReadLock(ss); /********************************/ + ssl_GetSpecReadLock(ss); /********************************/ - if (nIn > 1 && ss->opt.cbcRandomIV && - ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && - type == content_application_data && - ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { - /* We will split the first byte of the record into its own record, - * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h - */ - numRecords = 2; - } else { - numRecords = 1; - } + if (nIn > 1 && ss->opt.cbcRandomIV && + ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && + type == content_application_data && + ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { + /* We will split the first byte of the record into its own record, + * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h + */ + numRecords = 2; + } + else { + numRecords = 1; + } - spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); - if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && - ss->ssl3.cwSpec->cipher_def->type == type_block) { - spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; - } - if (spaceNeeded > wrBuf->space) { - rv = sslBuffer_Grow(wrBuf, spaceNeeded); - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", - SSL_GETPID(), ss->fd, spaceNeeded)); - goto spec_locked_loser; /* sslBuffer_Grow set error code. */ - } - } + spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); + if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && + ss->ssl3.cwSpec->cipher_def->type == type_block) { + spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; + } + if (spaceNeeded > wrBuf->space) { + rv = sslBuffer_Grow(wrBuf, spaceNeeded); + if (rv != SECSuccess) { + SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", + SSL_GETPID(), ss->fd, spaceNeeded)); + goto spec_locked_loser; /* sslBuffer_Grow set error code. */ + } + } - if (numRecords == 2) { - sslBuffer secondRecord; - rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, - ss->sec.isServer, IS_DTLS(ss), - capRecordVersion, type, pIn, - 1, wrBuf); - if (rv != SECSuccess) - goto spec_locked_loser; + if (numRecords == 2) { + sslBuffer secondRecord; + rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, + ss->sec.isServer, IS_DTLS(ss), + capRecordVersion, type, pIn, + 1, wrBuf); + if (rv != SECSuccess) + goto spec_locked_loser; - PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", - wrBuf->buf, wrBuf->len)); + PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", + wrBuf->buf, wrBuf->len)); - secondRecord.buf = wrBuf->buf + wrBuf->len; - secondRecord.len = 0; - secondRecord.space = wrBuf->space - wrBuf->len; + secondRecord.buf = wrBuf->buf + wrBuf->len; + secondRecord.len = 0; + secondRecord.space = wrBuf->space - wrBuf->len; - rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, - ss->sec.isServer, IS_DTLS(ss), - capRecordVersion, type, - pIn + 1, contentLen - 1, - &secondRecord); - if (rv == SECSuccess) { - PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", - secondRecord.buf, secondRecord.len)); - wrBuf->len += secondRecord.len; - } - } else { - if (!IS_DTLS(ss)) { + rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, + ss->sec.isServer, IS_DTLS(ss), + capRecordVersion, type, + pIn + 1, + contentLen - 1, + &secondRecord); + if (rv == SECSuccess) { + PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", + secondRecord.buf, secondRecord.len)); + wrBuf->len += secondRecord.len; + } + } + else { + if (!IS_DTLS(ss)) { if (ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3) { rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, ss->sec.isServer, @@ -2930,92 +3097,95 @@ ssl3_SendRecord( sslSocket * ss, capRecordVersion, type, pIn, contentLen, wrBuf); - } else { + } + else { rv = tls13_ProtectRecord(ss, type, pIn, contentLen, wrBuf); } - } else { + } + else { /* TLS <= 1.2 and TLS 1.3 cases are both handled in * dtls_CompressMACEncryptRecord. */ - rv = dtls_CompressMACEncryptRecord(ss, epoch, - !!(flags & ssl_SEND_FLAG_USE_EPOCH), - type, pIn, - contentLen, wrBuf); - } + rv = dtls_CompressMACEncryptRecord(ss, epoch, + !!(flags & ssl_SEND_FLAG_USE_EPOCH), + type, pIn, + contentLen, wrBuf); + } - if (rv == SECSuccess) { - PRINT_BUF(50, (ss, "send (encrypted) record data:", - wrBuf->buf, wrBuf->len)); - } - } + if (rv == SECSuccess) { + PRINT_BUF(50, (ss, "send (encrypted) record data:", + wrBuf->buf, wrBuf->len)); + } + } -spec_locked_loser: - ssl_ReleaseSpecReadLock(ss); /************************************/ + spec_locked_loser: + ssl_ReleaseSpecReadLock(ss); /************************************/ - if (rv != SECSuccess) - return SECFailure; + if (rv != SECSuccess) + return SECFailure; - pIn += contentLen; - nIn -= contentLen; - PORT_Assert( nIn >= 0 ); + pIn += contentLen; + nIn -= contentLen; + PORT_Assert(nIn >= 0); - /* If there's still some previously saved ciphertext, - * or the caller doesn't want us to send the data yet, - * then add all our new ciphertext to the amount previously saved. - */ - if ((ss->pendingBuf.len > 0) || - (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { + /* If there's still some previously saved ciphertext, + * or the caller doesn't want us to send the data yet, + * then add all our new ciphertext to the amount previously saved. + */ + if ((ss->pendingBuf.len > 0) || + (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { - rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len); - if (rv != SECSuccess) { - /* presumably a memory error, SEC_ERROR_NO_MEMORY */ - return SECFailure; - } - wrBuf->len = 0; /* All cipher text is saved away. */ + rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len); + if (rv != SECSuccess) { + /* presumably a memory error, SEC_ERROR_NO_MEMORY */ + return SECFailure; + } + wrBuf->len = 0; /* All cipher text is saved away. */ - if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { - PRInt32 sent; - ss->handshakeBegun = 1; - sent = ssl_SendSavedWriteData(ss); - if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { - ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); - return SECFailure; - } - if (ss->pendingBuf.len) { - flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; - } - } - } else if (wrBuf->len > 0) { - PRInt32 sent; - ss->handshakeBegun = 1; - sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, - flags & ~ssl_SEND_FLAG_MASK); - if (sent < 0) { - if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { - ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); - return SECFailure; - } - /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ - sent = 0; - } - wrBuf->len -= sent; - if (wrBuf->len) { - if (IS_DTLS(ss)) { - /* DTLS just says no in this case. No buffering */ - PR_SetError(PR_WOULD_BLOCK_ERROR, 0); - return SECFailure; - } - /* now take all the remaining unsent new ciphertext and - * append it to the buffer of previously unsent ciphertext. - */ - rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); - if (rv != SECSuccess) { - /* presumably a memory error, SEC_ERROR_NO_MEMORY */ - return SECFailure; - } - } - } - totalSent += contentLen; + if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { + PRInt32 sent; + ss->handshakeBegun = 1; + sent = ssl_SendSavedWriteData(ss); + if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { + ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); + return SECFailure; + } + if (ss->pendingBuf.len) { + flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; + } + } + } + else if (wrBuf->len > 0) { + PRInt32 sent; + ss->handshakeBegun = 1; + sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, + flags & ~ssl_SEND_FLAG_MASK); + if (sent < 0) { + if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { + ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); + return SECFailure; + } + /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ + sent = 0; + } + wrBuf->len -= sent; + if (wrBuf->len) { + if (IS_DTLS(ss)) { + /* DTLS just says no in this case. No buffering */ + PR_SetError(PR_WOULD_BLOCK_ERROR, 0); + return SECFailure; + } + /* now take all the remaining unsent new ciphertext and + * append it to the buffer of previously unsent ciphertext. + */ + rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); + if (rv != SECSuccess) { + /* presumably a memory error, SEC_ERROR_NO_MEMORY */ + return SECFailure; + } + } + } + totalSent += contentLen; } return totalSent; } @@ -3027,87 +3197,87 @@ spec_locked_loser: */ int ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, - PRInt32 len, PRInt32 flags) + PRInt32 len, PRInt32 flags) { - PRInt32 totalSent = 0; - PRInt32 discarded = 0; + PRInt32 totalSent = 0; + PRInt32 discarded = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); /* These flags for internal use only */ PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH | - ssl_SEND_FLAG_NO_RETRANSMIT))); + ssl_SEND_FLAG_NO_RETRANSMIT))); if (len < 0 || !in) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && !ssl_SocketIsBlocking(ss)) { - PORT_Assert(!ssl_SocketIsBlocking(ss)); - PORT_SetError(PR_WOULD_BLOCK_ERROR); - return SECFailure; + PORT_Assert(!ssl_SocketIsBlocking(ss)); + PORT_SetError(PR_WOULD_BLOCK_ERROR); + return SECFailure; } if (ss->appDataBuffered && len) { - PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered)); - if (in[0] != (unsigned char)(ss->appDataBuffered)) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; - } - in++; - len--; - discarded = 1; + PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered)); + if (in[0] != (unsigned char)(ss->appDataBuffered)) { + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; + } + in++; + len--; + discarded = 1; } while (len > totalSent) { - PRInt32 sent, toSend; + PRInt32 sent, toSend; - if (totalSent > 0) { - /* - * The thread yield is intended to give the reader thread a - * chance to get some cycles while the writer thread is in - * the middle of a large application data write. (See - * Bugzilla bug 127740, comment #1.) - */ - ssl_ReleaseXmitBufLock(ss); - PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */ - ssl_GetXmitBufLock(ss); - } - toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); - /* - * Note that the 0 epoch is OK because flags will never require - * its use, as guaranteed by the PORT_Assert above. - */ - sent = ssl3_SendRecord(ss, 0, content_application_data, - in + totalSent, toSend, flags); - if (sent < 0) { - if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { - PORT_Assert(ss->lastWriteBlocked); - break; - } - return SECFailure; /* error code set by ssl3_SendRecord */ - } - totalSent += sent; - if (ss->pendingBuf.len) { - /* must be a non-blocking socket */ - PORT_Assert(!ssl_SocketIsBlocking(ss)); - PORT_Assert(ss->lastWriteBlocked); - break; - } + if (totalSent > 0) { + /* + * The thread yield is intended to give the reader thread a + * chance to get some cycles while the writer thread is in + * the middle of a large application data write. (See + * Bugzilla bug 127740, comment #1.) + */ + ssl_ReleaseXmitBufLock(ss); + PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */ + ssl_GetXmitBufLock(ss); + } + toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); + /* + * Note that the 0 epoch is OK because flags will never require + * its use, as guaranteed by the PORT_Assert above. + */ + sent = ssl3_SendRecord(ss, 0, content_application_data, + in + totalSent, toSend, flags); + if (sent < 0) { + if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { + PORT_Assert(ss->lastWriteBlocked); + break; + } + return SECFailure; /* error code set by ssl3_SendRecord */ + } + totalSent += sent; + if (ss->pendingBuf.len) { + /* must be a non-blocking socket */ + PORT_Assert(!ssl_SocketIsBlocking(ss)); + PORT_Assert(ss->lastWriteBlocked); + break; + } } if (ss->pendingBuf.len) { - /* Must be non-blocking. */ - PORT_Assert(!ssl_SocketIsBlocking(ss)); - if (totalSent > 0) { - ss->appDataBuffered = 0x100 | in[totalSent - 1]; - } + /* Must be non-blocking. */ + PORT_Assert(!ssl_SocketIsBlocking(ss)); + if (totalSent > 0) { + ss->appDataBuffered = 0x100 | in[totalSent - 1]; + } - totalSent = totalSent + discarded - 1; - if (totalSent <= 0) { - PORT_SetError(PR_WOULD_BLOCK_ERROR); - totalSent = SECFailure; - } - return totalSent; - } + totalSent = totalSent + discarded - 1; + if (totalSent <= 0) { + PORT_SetError(PR_WOULD_BLOCK_ERROR); + totalSent = SECFailure; + } + return totalSent; + } ss->appDataBuffered = 0; return totalSent + discarded; } @@ -3131,7 +3301,8 @@ ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) { if (IS_DTLS(ss)) { return dtls_FlushHandshakeMessages(ss, flags); - } else { + } + else { return ssl3_FlushHandshakeMessages(ss, flags); } } @@ -3150,35 +3321,38 @@ ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) PRInt32 count = -1; SECStatus rv = SECSuccess; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len) - return rv; + return rv; /* only these flags are allowed */ PORT_Assert(!(flags & ~allowedFlags)); if ((flags & ~allowedFlags) != 0) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } else { - count = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf, - ss->sec.ci.sendBuf.len, flags); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + } + else { + count = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf, + ss->sec.ci.sendBuf.len, flags); } if (count < 0) { - int err = PORT_GetError(); - PORT_Assert(err != PR_WOULD_BLOCK_ERROR); - if (err == PR_WOULD_BLOCK_ERROR) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - } + int err = PORT_GetError(); + PORT_Assert(err != PR_WOULD_BLOCK_ERROR); + if (err == PR_WOULD_BLOCK_ERROR) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + } rv = SECFailure; - } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) { - /* short write should never happen */ - PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - rv = SECFailure; - } else { - rv = SECSuccess; + } + else if ((unsigned int)count < ss->sec.ci.sendBuf.len) { + /* short write should never happen */ + PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + rv = SECFailure; + } + else { + rv = SECSuccess; } /* Whether we succeeded or failed, toss the old handshake data. */ @@ -3196,12 +3370,12 @@ static SECStatus ssl3_HandleNoCertificate(sslSocket *ss) { if (ss->sec.peerCert != NULL) { - if (ss->sec.peerKey != NULL) { - SECKEY_DestroyPublicKey(ss->sec.peerKey); - ss->sec.peerKey = NULL; - } - CERT_DestroyCertificate(ss->sec.peerCert); - ss->sec.peerCert = NULL; + if (ss->sec.peerKey != NULL) { + SECKEY_DestroyPublicKey(ss->sec.peerKey); + ss->sec.peerKey = NULL; + } + CERT_DestroyCertificate(ss->sec.peerCert); + ss->sec.peerCert = NULL; } ssl3_CleanupPeerCerts(ss); @@ -3209,26 +3383,26 @@ ssl3_HandleNoCertificate(sslSocket *ss) * actually look at the certificate it won't know that no * certificate was presented so we shutdown the socket to ensure * an error. We only do this if we haven't already completed the - * first handshake because if we're redoing the handshake we + * first handshake because if we're redoing the handshake we * know the server is paying attention to the certificate. */ if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || - (!ss->firstHsDone && - (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { - PRFileDesc * lower; + (!ss->firstHsDone && + (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { + PRFileDesc *lower; - if (ss->sec.uncache) + if (ss->sec.uncache) ss->sec.uncache(ss->sec.ci.sid); - SSL3_SendAlert(ss, alert_fatal, bad_certificate); + SSL3_SendAlert(ss, alert_fatal, bad_certificate); - lower = ss->fd->lower; + lower = ss->fd->lower; #ifdef _WIN32 - lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); + lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); #else - lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); + lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); #endif - PORT_SetError(SSL_ERROR_NO_CERTIFICATE); - return SECFailure; + PORT_SetError(SSL_ERROR_NO_CERTIFICATE); + return SECFailure; } return SECSuccess; } @@ -3239,60 +3413,59 @@ ssl3_HandleNoCertificate(sslSocket *ss) /* ** Acquires both handshake and XmitBuf locks. -** Called from: ssl3_IllegalParameter <- -** ssl3_HandshakeFailure <- -** ssl3_HandleAlert <- ssl3_HandleRecord. +** Called from: ssl3_IllegalParameter <- +** ssl3_HandshakeFailure <- +** ssl3_HandleAlert <- ssl3_HandleRecord. ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord ** ssl3_ConsumeHandshakeVariable <- -** ssl3_HandleHelloRequest <- -** ssl3_HandleServerHello <- +** ssl3_HandleHelloRequest <- +** ssl3_HandleServerHello <- ** ssl3_HandleServerKeyExchange <- ** ssl3_HandleCertificateRequest <- ** ssl3_HandleServerHelloDone <- -** ssl3_HandleClientHello <- +** ssl3_HandleClientHello <- ** ssl3_HandleV2ClientHello <- ** ssl3_HandleCertificateVerify <- ** ssl3_HandleClientKeyExchange <- -** ssl3_HandleCertificate <- -** ssl3_HandleFinished <- +** ssl3_HandleCertificate <- +** ssl3_HandleFinished <- ** ssl3_HandleHandshakeMessage <- ** ssl3_HandlePostHelloHandshakeMessage <- -** ssl3_HandleRecord <- +** ssl3_HandleRecord <- ** */ SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) { - PRUint8 bytes[2]; - SECStatus rv; + PRUint8 bytes[2]; + SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", - SSL_GETPID(), ss->fd, level, desc)); + SSL_GETPID(), ss->fd, level, desc)); bytes[0] = level; bytes[1] = desc; ssl_GetSSL3HandshakeLock(ss); if (level == alert_fatal) { - if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { - ss->sec.uncache(ss->sec.ci.sid); - } + if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { + ss->sec.uncache(ss->sec.ci.sid); + } } ssl_GetXmitBufLock(ss); rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); if (rv == SECSuccess) { - PRInt32 sent; - sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, - desc == no_certificate - ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); - rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; + PRInt32 sent; + sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, + desc == no_certificate ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); + rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; } if (level == alert_fatal) { ss->ssl3.fatalAlertSent = PR_TRUE; } ssl_ReleaseXmitBufLock(ss); ssl_ReleaseSSL3HandshakeLock(ss); - return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ + return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ } /* @@ -3303,7 +3476,7 @@ ssl3_IllegalParameter(sslSocket *ss) { (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT - : SSL_ERROR_BAD_SERVER ); + : SSL_ERROR_BAD_SERVER); return SECFailure; } @@ -3314,56 +3487,67 @@ static SECStatus ssl3_HandshakeFailure(sslSocket *ss) { (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); - PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT - : SSL_ERROR_BAD_SERVER ); + PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT + : SSL_ERROR_BAD_SERVER); return SECFailure; } static void -ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode) +ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode) { - SSL3AlertDescription desc = bad_certificate; + SSL3AlertDescription desc = bad_certificate; PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS; switch (errCode) { - case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break; - case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break; - case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break; - case SEC_ERROR_INADEQUATE_KEY_USAGE: - case SEC_ERROR_INADEQUATE_CERT_TYPE: - desc = certificate_unknown; break; - case SEC_ERROR_UNTRUSTED_CERT: - desc = isTLS ? access_denied : certificate_unknown; break; - case SEC_ERROR_UNKNOWN_ISSUER: - case SEC_ERROR_UNTRUSTED_ISSUER: - desc = isTLS ? unknown_ca : certificate_unknown; break; - case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: - desc = isTLS ? unknown_ca : certificate_expired; break; + case SEC_ERROR_LIBRARY_FAILURE: + desc = unsupported_certificate; + break; + case SEC_ERROR_EXPIRED_CERTIFICATE: + desc = certificate_expired; + break; + case SEC_ERROR_REVOKED_CERTIFICATE: + desc = certificate_revoked; + break; + case SEC_ERROR_INADEQUATE_KEY_USAGE: + case SEC_ERROR_INADEQUATE_CERT_TYPE: + desc = certificate_unknown; + break; + case SEC_ERROR_UNTRUSTED_CERT: + desc = isTLS ? access_denied : certificate_unknown; + break; + case SEC_ERROR_UNKNOWN_ISSUER: + case SEC_ERROR_UNTRUSTED_ISSUER: + desc = isTLS ? unknown_ca : certificate_unknown; + break; + case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: + desc = isTLS ? unknown_ca : certificate_expired; + break; - case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: - case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: - case SEC_ERROR_CA_CERT_INVALID: - case SEC_ERROR_BAD_SIGNATURE: - default: desc = bad_certificate; break; + case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: + case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: + case SEC_ERROR_CA_CERT_INVALID: + case SEC_ERROR_BAD_SIGNATURE: + default: + desc = bad_certificate; + break; } SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d", - SSL_GETPID(), ss->fd, errCode)); + SSL_GETPID(), ss->fd, errCode)); - (void) SSL3_SendAlert(ss, alert_fatal, desc); + (void)SSL3_SendAlert(ss, alert_fatal, desc); } - /* * Send decode_error alert. Set generic error number. */ SECStatus ssl3_DecodeError(sslSocket *ss) { - (void)SSL3_SendAlert(ss, alert_fatal, - ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error - : illegal_parameter); - PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT - : SSL_ERROR_BAD_SERVER ); + (void)SSL3_SendAlert(ss, alert_fatal, + ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error + : illegal_parameter); + PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT + : SSL_ERROR_BAD_SERVER); return SECFailure; } @@ -3373,104 +3557,152 @@ ssl3_DecodeError(sslSocket *ss) static SECStatus ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) { - SSL3AlertLevel level; + SSL3AlertLevel level; SSL3AlertDescription desc; - int error; + int error; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd)); if (buf->len != 2) { - (void)ssl3_DecodeError(ss); - PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); - return SECFailure; + (void)ssl3_DecodeError(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); + return SECFailure; } level = (SSL3AlertLevel)buf->buf[0]; - desc = (SSL3AlertDescription)buf->buf[1]; + desc = (SSL3AlertDescription)buf->buf[1]; buf->len = 0; SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d", - SSL_GETPID(), ss->fd, level, desc)); + SSL_GETPID(), ss->fd, level, desc)); switch (desc) { - case close_notify: ss->recvdCloseNotify = 1; - error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break; - case unexpected_message: error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; - break; - case bad_record_mac: error = SSL_ERROR_BAD_MAC_ALERT; break; - case decryption_failed_RESERVED: - error = SSL_ERROR_DECRYPTION_FAILED_ALERT; - break; - case record_overflow: error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break; - case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; - break; - case handshake_failure: error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; - break; - case no_certificate: error = SSL_ERROR_NO_CERTIFICATE; break; - case bad_certificate: error = SSL_ERROR_BAD_CERT_ALERT; break; - case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break; - case certificate_revoked: error = SSL_ERROR_REVOKED_CERT_ALERT; break; - case certificate_expired: error = SSL_ERROR_EXPIRED_CERT_ALERT; break; - case certificate_unknown: error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; - break; - case illegal_parameter: error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break; - case inappropriate_fallback: - error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; - break; + case close_notify: + ss->recvdCloseNotify = 1; + error = SSL_ERROR_CLOSE_NOTIFY_ALERT; + break; + case unexpected_message: + error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; + break; + case bad_record_mac: + error = SSL_ERROR_BAD_MAC_ALERT; + break; + case decryption_failed_RESERVED: + error = SSL_ERROR_DECRYPTION_FAILED_ALERT; + break; + case record_overflow: + error = SSL_ERROR_RECORD_OVERFLOW_ALERT; + break; + case decompression_failure: + error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; + break; + case handshake_failure: + error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; + break; + case no_certificate: + error = SSL_ERROR_NO_CERTIFICATE; + break; + case bad_certificate: + error = SSL_ERROR_BAD_CERT_ALERT; + break; + case unsupported_certificate: + error = SSL_ERROR_UNSUPPORTED_CERT_ALERT; + break; + case certificate_revoked: + error = SSL_ERROR_REVOKED_CERT_ALERT; + break; + case certificate_expired: + error = SSL_ERROR_EXPIRED_CERT_ALERT; + break; + case certificate_unknown: + error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; + break; + case illegal_parameter: + error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT; + break; + case inappropriate_fallback: + error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; + break; - /* All alerts below are TLS only. */ - case unknown_ca: error = SSL_ERROR_UNKNOWN_CA_ALERT; break; - case access_denied: error = SSL_ERROR_ACCESS_DENIED_ALERT; break; - case decode_error: error = SSL_ERROR_DECODE_ERROR_ALERT; break; - case decrypt_error: error = SSL_ERROR_DECRYPT_ERROR_ALERT; break; - case export_restriction: error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; - break; - case protocol_version: error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break; - case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; - break; - case internal_error: error = SSL_ERROR_INTERNAL_ERROR_ALERT; break; - case user_canceled: error = SSL_ERROR_USER_CANCELED_ALERT; break; - case no_renegotiation: error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break; + /* All alerts below are TLS only. */ + case unknown_ca: + error = SSL_ERROR_UNKNOWN_CA_ALERT; + break; + case access_denied: + error = SSL_ERROR_ACCESS_DENIED_ALERT; + break; + case decode_error: + error = SSL_ERROR_DECODE_ERROR_ALERT; + break; + case decrypt_error: + error = SSL_ERROR_DECRYPT_ERROR_ALERT; + break; + case export_restriction: + error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; + break; + case protocol_version: + error = SSL_ERROR_PROTOCOL_VERSION_ALERT; + break; + case insufficient_security: + error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; + break; + case internal_error: + error = SSL_ERROR_INTERNAL_ERROR_ALERT; + break; + case user_canceled: + error = SSL_ERROR_USER_CANCELED_ALERT; + break; + case no_renegotiation: + error = SSL_ERROR_NO_RENEGOTIATION_ALERT; + break; - /* Alerts for TLS client hello extensions */ - case missing_extension: - error = SSL_ERROR_MISSING_EXTENSION_ALERT; break; - case unsupported_extension: - error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break; - case certificate_unobtainable: - error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break; - case unrecognized_name: - error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break; - case bad_certificate_status_response: - error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break; - case bad_certificate_hash_value: - error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break; - default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break; + /* Alerts for TLS client hello extensions */ + case missing_extension: + error = SSL_ERROR_MISSING_EXTENSION_ALERT; + break; + case unsupported_extension: + error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; + break; + case certificate_unobtainable: + error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; + break; + case unrecognized_name: + error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; + break; + case bad_certificate_status_response: + error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; + break; + case bad_certificate_hash_value: + error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; + break; + default: + error = SSL_ERROR_RX_UNKNOWN_ALERT; + break; } if (level == alert_fatal) { - if (!ss->opt.noCache) { - if (ss->sec.uncache) + if (!ss->opt.noCache) { + if (ss->sec.uncache) ss->sec.uncache(ss->sec.ci.sid); - } - if ((ss->ssl3.hs.ws == wait_server_hello) && - (desc == handshake_failure)) { - /* XXX This is a hack. We're assuming that any handshake failure - * XXX on the client hello is a failure to match ciphers. - */ - error = SSL_ERROR_NO_CYPHER_OVERLAP; - } - PORT_SetError(error); - return SECFailure; + } + if ((ss->ssl3.hs.ws == wait_server_hello) && + (desc == handshake_failure)) { + /* XXX This is a hack. We're assuming that any handshake failure + * XXX on the client hello is a failure to match ciphers. + */ + error = SSL_ERROR_NO_CYPHER_OVERLAP; + } + PORT_SetError(error); + return SECFailure; } if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) { - /* I'm a server. I've requested a client cert. He hasn't got one. */ - SECStatus rv; + /* I'm a server. I've requested a client cert. He hasn't got one. */ + SECStatus rv; - PORT_Assert(ss->sec.isServer); - ss->ssl3.hs.ws = wait_client_key; - rv = ssl3_HandleNoCertificate(ss); - return rv; + PORT_Assert(ss->sec.isServer); + ss->ssl3.hs.ws = wait_client_key; + rv = ssl3_HandleNoCertificate(ss); + return rv; } return SECSuccess; } @@ -3488,57 +3720,59 @@ ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) static SECStatus ssl3_SendChangeCipherSpecs(sslSocket *ss) { - PRUint8 change = change_cipher_spec_choice; - ssl3CipherSpec * pwSpec; - SECStatus rv; - PRInt32 sent; + PRUint8 change = change_cipher_spec_choice; + ssl3CipherSpec *pwSpec; + SECStatus rv; + PRInt32 sent; SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + return rv; /* error code set by ssl3_FlushHandshake */ } if (!IS_DTLS(ss)) { - sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, - ssl_SEND_FLAG_FORCE_INTO_BUFFER); - if (sent < 0) { - return (SECStatus)sent; /* error code set by ssl3_SendRecord */ - } - } else { - rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); - if (rv != SECSuccess) { - return rv; - } + sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, + ssl_SEND_FLAG_FORCE_INTO_BUFFER); + if (sent < 0) { + return (SECStatus)sent; /* error code set by ssl3_SendRecord */ + } + } + else { + rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); + if (rv != SECSuccess) { + return rv; + } } /* swap the pending and current write specs. */ - ssl_GetSpecWriteLock(ss); /**************************************/ - pwSpec = ss->ssl3.pwSpec; + ssl_GetSpecWriteLock(ss); /**************************************/ + pwSpec = ss->ssl3.pwSpec; ss->ssl3.pwSpec = ss->ssl3.cwSpec; ss->ssl3.cwSpec = pwSpec; SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", - SSL_GETPID(), ss->fd )); + SSL_GETPID(), ss->fd)); /* We need to free up the contexts, keys and certs ! */ /* If we are really through with the old cipher spec * (Both the read and write sides have changed) destroy it. */ if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { - if (!IS_DTLS(ss)) { - ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/); - } else { - /* With DTLS, we need to set a holddown timer in case the final - * message got lost */ - ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; - dtls_StartTimer(ss, dtls_FinishedTimerCb); - } + if (!IS_DTLS(ss)) { + ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE /*freeSrvName*/); + } + else { + /* With DTLS, we need to set a holddown timer in case the final + * message got lost */ + ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; + dtls_StartTimer(ss, dtls_FinishedTimerCb); + } } ssl_ReleaseSpecWriteLock(ss); /**************************************/ @@ -3554,62 +3788,62 @@ ssl3_SendChangeCipherSpecs(sslSocket *ss) static SECStatus ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) { - ssl3CipherSpec * prSpec; - SSL3WaitState ws = ss->ssl3.hs.ws; + ssl3CipherSpec *prSpec; + SSL3WaitState ws = ss->ssl3.hs.ws; SSL3ChangeCipherSpecChoice change; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); if (ws != wait_change_cipher) { - if (IS_DTLS(ss)) { - /* Ignore this because it's out of order. */ - SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " - "DTLS change_cipher_spec", - SSL_GETPID(), ss->fd)); - buf->len = 0; - return SECSuccess; - } - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); - return SECFailure; + if (IS_DTLS(ss)) { + /* Ignore this because it's out of order. */ + SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " + "DTLS change_cipher_spec", + SSL_GETPID(), ss->fd)); + buf->len = 0; + return SECSuccess; + } + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); + return SECFailure; } - if(buf->len != 1) { - (void)ssl3_DecodeError(ss); - PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); - return SECFailure; + if (buf->len != 1) { + (void)ssl3_DecodeError(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); + return SECFailure; } change = (SSL3ChangeCipherSpecChoice)buf->buf[0]; if (change != change_cipher_spec_choice) { - /* illegal_parameter is correct here for both SSL3 and TLS. */ - (void)ssl3_IllegalParameter(ss); - PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); - return SECFailure; + /* illegal_parameter is correct here for both SSL3 and TLS. */ + (void)ssl3_IllegalParameter(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); + return SECFailure; } buf->len = 0; /* Swap the pending and current read specs. */ - ssl_GetSpecWriteLock(ss); /*************************************/ - prSpec = ss->ssl3.prSpec; + ssl_GetSpecWriteLock(ss); /*************************************/ + prSpec = ss->ssl3.prSpec; - ss->ssl3.prSpec = ss->ssl3.crSpec; - ss->ssl3.crSpec = prSpec; - ss->ssl3.hs.ws = wait_finished; + ss->ssl3.prSpec = ss->ssl3.crSpec; + ss->ssl3.crSpec = prSpec; + ss->ssl3.hs.ws = wait_finished; SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", - SSL_GETPID(), ss->fd )); + SSL_GETPID(), ss->fd)); /* If we are really through with the old cipher prSpec * (Both the read and write sides have changed) destroy it. */ if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { - ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/); + ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE /*freeSrvName*/); } - ssl_ReleaseSpecWriteLock(ss); /*************************************/ + ssl_ReleaseSpecWriteLock(ss); /*************************************/ return SECSuccess; } @@ -3662,7 +3896,8 @@ ssl3_ComputeMasterSecretFinish(sslSocket *ss, if (msp) { *msp = ms; - } else { + } + else { PK11_FreeSymKey(ms); } @@ -3678,67 +3913,76 @@ static SECStatus ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms, PK11SymKey **msp) { - ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; - const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def; - unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; - unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; - PRBool isTLS = (PRBool)(kea_def->tls_keygen || - (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); - PRBool isTLS12= - (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; + const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; + unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; + unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; + PRBool isTLS = (PRBool)(kea_def->tls_keygen || + (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); + PRBool isTLS12 = + (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); /* * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size * data into a 48-byte value, and does not expect to return the version. */ - PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || - (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); + PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || + (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); CK_MECHANISM_TYPE master_derive; CK_MECHANISM_TYPE key_derive; - SECItem params; - CK_FLAGS keyFlags; - CK_VERSION pms_version; - CK_VERSION *pms_version_ptr = NULL; + SECItem params; + CK_FLAGS keyFlags; + CK_VERSION pms_version; + CK_VERSION *pms_version_ptr = NULL; /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */ CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params; - unsigned int master_params_len; + unsigned int master_params_len; if (isTLS12) { - if(isDH) master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH; - else master_derive = CKM_TLS12_MASTER_KEY_DERIVE; - key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; - keyFlags = CKF_SIGN | CKF_VERIFY; - } else 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_TLS12_MASTER_KEY_DERIVE_DH; + else + master_derive = CKM_TLS12_MASTER_KEY_DERIVE; + key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; + keyFlags = CKF_SIGN | CKF_VERIFY; + } + else 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) { pms_version_ptr = &pms_version; } - master_params.pVersion = pms_version_ptr; - master_params.RandomInfo.pClientRandom = cr; + master_params.pVersion = pms_version_ptr; + master_params.RandomInfo.pClientRandom = cr; master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; - master_params.RandomInfo.pServerRandom = sr; + master_params.RandomInfo.pServerRandom = sr; master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; if (isTLS12) { master_params.prfHashMechanism = CKM_SHA256; master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS); - } else { + } + else { /* prfHashMechanism is not relevant with this PRF */ master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS); } - params.data = (unsigned char *) &master_params; - params.len = master_params_len; + params.data = (unsigned char *)&master_params; + params.len = master_params_len; return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, pms_version_ptr, ¶ms, @@ -3762,9 +4006,9 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, */ /* * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion - * mode. Bug 1198298 */ - PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || - (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); + * mode. Bug 1198298 */ + PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || + (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); CK_MECHANISM_TYPE master_derive; CK_MECHANISM_TYPE key_derive; SECItem params; @@ -3775,14 +4019,15 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0); if (rv != SECSuccess) { - PORT_Assert(0); /* Should never fail */ + PORT_Assert(0); /* Should never fail */ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return SECFailure; } if (isDH) { master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH; - } else { + } + else { master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE; pms_version_ptr = &pms_version; } @@ -3791,17 +4036,18 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, /* TLS 1.2 */ extended_master_params.prfHashMechanism = CKM_SHA256; key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; - } else { + } + else { /* TLS < 1.2 */ extended_master_params.prfHashMechanism = CKM_TLS_PRF; - key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; + key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; } extended_master_params.pVersion = pms_version_ptr; extended_master_params.pSessionHash = hashes.u.raw; extended_master_params.ulSessionHashLen = hashes.len; - params.data = (unsigned char *) &extended_master_params; + params.data = (unsigned char *)&extended_master_params; params.len = sizeof extended_master_params; return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, @@ -3809,7 +4055,6 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, keyFlags, pms, msp); } - /* Wrapper method to compute the master secret and return it in |*msp|. ** ** Called from ssl3_ComputeMasterSecret @@ -3824,7 +4069,8 @@ ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms, if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { return tls_ComputeExtendedMasterSecretInt(ss, pms, msp); - } else { + } + else { return ssl3_ComputeMasterSecretInt(ss, pms, msp); } } @@ -3842,11 +4088,11 @@ static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) { SECStatus rv; - PK11SymKey* ms = NULL; + PK11SymKey *ms = NULL; ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); if (pms) { @@ -3858,34 +4104,35 @@ ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { - SECItem * keydata; - /* In hope of doing a "double bypass", - * need to extract the master secret's value from the key object - * and store it raw in the sslSocket struct. - */ - rv = PK11_ExtractKeyValue(pwSpec->master_secret); - if (rv != SECSuccess) { - return rv; + SECItem *keydata; + /* In hope of doing a "double bypass", + * need to extract the master secret's value from the key object + * and store it raw in the sslSocket struct. + */ + rv = PK11_ExtractKeyValue(pwSpec->master_secret); + if (rv != SECSuccess) { + return rv; + } + /* This returns the address of the secItem inside the key struct, + * not a copy or a reference. So, there's no need to free it. + */ + keydata = PK11_GetKeyData(pwSpec->master_secret); + if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { + memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); + pwSpec->msItem.data = pwSpec->raw_master_secret; + pwSpec->msItem.len = keydata->len; + } + else { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } - /* This returns the address of the secItem inside the key struct, - * not a copy or a reference. So, there's no need to free it. - */ - keydata = PK11_GetKeyData(pwSpec->master_secret); - if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { - memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = keydata->len; - } else { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } } #endif return SECSuccess; } -/* +/* * Derive encryption and MAC Keys (and IVs) from master secret * Sets a useful error code when returning SECFailure. * @@ -3903,137 +4150,139 @@ ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) { - ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; - unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; - PRBool isTLS = (PRBool)(kea_def->tls_keygen || - (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); - PRBool isTLS12= - (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; + const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; + unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; + unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; + PRBool isTLS = (PRBool)(kea_def->tls_keygen || + (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); + PRBool isTLS12 = + (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); /* following variables used in PKCS11 path */ const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; - PK11SlotInfo * slot = NULL; - PK11SymKey * symKey = NULL; - void * pwArg = ss->pkcs11PinArg; - int keySize; + PK11SlotInfo *slot = NULL; + PK11SymKey *symKey = NULL; + void *pwArg = ss->pkcs11PinArg; + int keySize; CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a - * CK_SSL3_KEY_MAT_PARAMS */ - unsigned int key_material_params_len; - CK_SSL3_KEY_MAT_OUT returnedKeys; - CK_MECHANISM_TYPE key_derive; - CK_MECHANISM_TYPE bulk_mechanism; - SSLCipherAlgorithm calg; - SECItem params; - PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null); + * CK_SSL3_KEY_MAT_PARAMS */ + unsigned int key_material_params_len; + CK_SSL3_KEY_MAT_OUT returnedKeys; + CK_MECHANISM_TYPE key_derive; + CK_MECHANISM_TYPE bulk_mechanism; + SSLCipherAlgorithm calg; + SECItem params; + PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); if (!pwSpec->master_secret) { - PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); - return SECFailure; + PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); + return SECFailure; } /* * generate the key material */ - key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; - key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB; - key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; + key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; + key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB; + key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; 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. */ - key_material_params.ulIVSizeInBits = 0; - memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); - memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); + pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { + /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ + key_material_params.ulIVSizeInBits = 0; + memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); + memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); } key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); - key_material_params.RandomInfo.pClientRandom = cr; + key_material_params.RandomInfo.pClientRandom = cr; key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; - key_material_params.RandomInfo.pServerRandom = sr; + key_material_params.RandomInfo.pServerRandom = sr; key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; - key_material_params.pReturnedKeyMaterial = &returnedKeys; + key_material_params.pReturnedKeyMaterial = &returnedKeys; returnedKeys.pIVClient = pwSpec->client.write_iv; returnedKeys.pIVServer = pwSpec->server.write_iv; - keySize = cipher_def->key_size; + keySize = cipher_def->key_size; if (skipKeysAndIVs) { - keySize = 0; + keySize = 0; key_material_params.ulKeySizeInBits = 0; - key_material_params.ulIVSizeInBits = 0; - returnedKeys.pIVClient = NULL; - returnedKeys.pIVServer = NULL; + key_material_params.ulIVSizeInBits = 0; + returnedKeys.pIVClient = NULL; + returnedKeys.pIVServer = NULL; } calg = cipher_def->calg; bulk_mechanism = ssl3_Alg2Mech(calg); if (isTLS12) { - key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; - key_material_params.prfHashMechanism = CKM_SHA256; - key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS); - } else if (isTLS) { - key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; - key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); - } else { - key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; - key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); + key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; + key_material_params.prfHashMechanism = CKM_SHA256; + key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS); + } + else if (isTLS) { + key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; + key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); + } + else { + key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; + key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); } params.data = (unsigned char *)&key_material_params; - params.len = key_material_params_len; + params.len = key_material_params_len; /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and * DERIVE by DEFAULT */ symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms, bulk_mechanism, CKA_ENCRYPT, keySize); if (!symKey) { - ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); - return SECFailure; + ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); + return SECFailure; } /* we really should use the actual mac'ing mechanism here, but we * don't because these types are used to map keytype anyway and both * mac's map to the same keytype. */ - slot = PK11_GetSlotFromKey(symKey); + slot = PK11_GetSlotFromKey(symKey); PK11_FreeSlot(slot); /* slot is held until the key is freed */ pwSpec->client.write_mac_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); - if (pwSpec->client.write_mac_key == NULL ) { - goto loser; /* loser sets err */ + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); + if (pwSpec->client.write_mac_key == NULL) { + goto loser; /* loser sets err */ } pwSpec->server.write_mac_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); - if (pwSpec->server.write_mac_key == NULL ) { - goto loser; /* loser sets err */ + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); + if (pwSpec->server.write_mac_key == NULL) { + goto loser; /* loser sets err */ } if (!skipKeysAndIVs) { - pwSpec->client.write_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); - if (pwSpec->client.write_key == NULL ) { - goto loser; /* loser sets err */ - } - pwSpec->server.write_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); - if (pwSpec->server.write_key == NULL ) { - goto loser; /* loser sets err */ - } + pwSpec->client.write_key = + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); + if (pwSpec->client.write_key == NULL) { + goto loser; /* loser sets err */ + } + pwSpec->server.write_key = + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); + if (pwSpec->server.write_key == NULL) { + goto loser; /* loser sets err */ + } } PK11_FreeSymKey(symKey); return SECSuccess; - loser: - if (symKey) PK11_FreeSymKey(symKey); + if (symKey) + PK11_FreeSymKey(symKey); ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return SECFailure; } @@ -4043,123 +4292,126 @@ loser: static SECStatus ssl3_InitHandshakeHashes(sslSocket *ss) { - SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); + SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { - PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); - if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); - if (!ss->ssl3.hs.sha_obj) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - return SECFailure; - } - ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; - ss->ssl3.hs.hashType = handshake_hash_single; - ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); - } else { - ss->ssl3.hs.hashType = handshake_hash_combo; - MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); - SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); - } - } else + PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 + * then this will need to be updated. */ + ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); + if (!ss->ssl3.hs.sha_obj) { + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + return SECFailure; + } + ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; + ss->ssl3.hs.hashType = handshake_hash_single; + ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); + } + else { + ss->ssl3.hs.hashType = handshake_hash_combo; + MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); + SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); + } + } + else #endif { - PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); - /* - * note: We should probably lookup an SSL3 slot for these - * handshake hashes in hopes that we wind up with the same slots - * that the master secret will wind up in ... - */ - if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); - if (ss->ssl3.hs.sha == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return SECFailure; - } - ss->ssl3.hs.hashType = handshake_hash_single; + PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); + /* + * note: We should probably lookup an SSL3 slot for these + * handshake hashes in hopes that we wind up with the same slots + * that the master secret will wind up in ... + */ + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 + * then this will need to be updated. */ + ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); + if (ss->ssl3.hs.sha == NULL) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return SECFailure; + } + ss->ssl3.hs.hashType = handshake_hash_single; - if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - return SECFailure; - } + if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + return SECFailure; + } - /* Create a backup SHA-1 hash for a potential client auth - * signature. - * - * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the - * handshake hash function (SHA-256). If the server or the client - * does not support SHA-256 as a signature hash, we can either - * maintain a backup SHA-1 handshake hash or buffer all handshake - * messages. - */ - if (!ss->sec.isServer) { - ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); - if (ss->ssl3.hs.backupHash == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return SECFailure; - } + /* Create a backup SHA-1 hash for a potential client auth + * signature. + * + * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the + * handshake hash function (SHA-256). If the server or the client + * does not support SHA-256 as a signature hash, we can either + * maintain a backup SHA-1 handshake hash or buffer all handshake + * messages. + */ + if (!ss->sec.isServer) { + ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); + if (ss->ssl3.hs.backupHash == NULL) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return SECFailure; + } - if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return SECFailure; - } - } - } else { - /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or - * created successfully. */ - ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); - if (ss->ssl3.hs.md5 == NULL) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - return SECFailure; - } - ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); - if (ss->ssl3.hs.sha == NULL) { - PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); - ss->ssl3.hs.md5 = NULL; - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return SECFailure; - } - ss->ssl3.hs.hashType = handshake_hash_combo; + if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return SECFailure; + } + } + } + else { + /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or + * created successfully. */ + ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); + if (ss->ssl3.hs.md5 == NULL) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + return SECFailure; + } + ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); + if (ss->ssl3.hs.sha == NULL) { + PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); + ss->ssl3.hs.md5 = NULL; + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return SECFailure; + } + ss->ssl3.hs.hashType = handshake_hash_combo; - if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - return SECFailure; - } - if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return SECFailure; - } - } + if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + return SECFailure; + } + if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return SECFailure; + } + } } if (ss->ssl3.hs.messages.len > 0) { - if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, - ss->ssl3.hs.messages.len) != - SECSuccess) { - return SECFailure; - } - PORT_Free(ss->ssl3.hs.messages.buf); - ss->ssl3.hs.messages.buf = NULL; - ss->ssl3.hs.messages.len = 0; - ss->ssl3.hs.messages.space = 0; + if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, + ss->ssl3.hs.messages.len) != + SECSuccess) { + return SECFailure; + } + PORT_Free(ss->ssl3.hs.messages.buf); + ss->ssl3.hs.messages.buf = NULL; + ss->ssl3.hs.messages.len = 0; + ss->ssl3.hs.messages.space = 0; } return SECSuccess; } -static SECStatus +static SECStatus ssl3_RestartHandshakeHashes(sslSocket *ss) { SECStatus rv = SECSuccess; - SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes", - SSL_GETPID(), ss->fd )); + SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes", + SSL_GETPID(), ss->fd)); ss->ssl3.hs.hashType = handshake_hash_unknown; ss->ssl3.hs.messages.len = 0; #ifndef NO_PKCS11_BYPASS @@ -4167,12 +4419,12 @@ ssl3_RestartHandshakeHashes(sslSocket *ss) ss->ssl3.hs.sha_clone = NULL; #endif if (ss->ssl3.hs.md5) { - PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); - ss->ssl3.hs.md5 = NULL; + PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); + ss->ssl3.hs.md5 = NULL; } if (ss->ssl3.hs.sha) { - PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); - ss->ssl3.hs.sha = NULL; + PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); + ss->ssl3.hs.sha = NULL; } return rv; } @@ -4180,64 +4432,66 @@ ssl3_RestartHandshakeHashes(sslSocket *ss) /* * Handshake messages */ -/* Called from ssl3_InitHandshakeHashes() -** ssl3_AppendHandshake() -** ssl3_StartHandshakeHash() -** ssl3_HandleV2ClientHello() -** ssl3_HandleHandshakeMessage() +/* Called from ssl3_InitHandshakeHashes() +** ssl3_AppendHandshake() +** ssl3_StartHandshakeHash() +** ssl3_HandleV2ClientHello() +** ssl3_HandleHandshakeMessage() ** Caller must hold the ssl3Handshake lock. */ static SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, - unsigned int l) + unsigned int l) { - SECStatus rv = SECSuccess; + SECStatus rv = SECSuccess; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* We need to buffer the handshake messages until we have established * which handshake hash function to use. */ if (ss->ssl3.hs.hashType == handshake_hash_unknown) { - return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); + return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); } PRINT_BUF(90, (NULL, "handshake hash input:", b, l)); #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { - if (ss->ssl3.hs.hashType == handshake_hash_single) { - ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); - } else { - MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); - SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); - } - return rv; + if (ss->ssl3.hs.hashType == handshake_hash_single) { + ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); + } + else { + MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); + SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); + } + return rv; } #endif if (ss->ssl3.hs.hashType == handshake_hash_single) { - rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - return rv; - } - if (ss->ssl3.hs.backupHash) { - rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return rv; - } - } - } else { - rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - return rv; - } - rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return rv; - } + rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + return rv; + } + if (ss->ssl3.hs.backupHash) { + rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return rv; + } + } + } + else { + rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + return rv; + } + rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + return rv; + } } return rv; } @@ -4250,40 +4504,40 @@ ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes) { - unsigned char * src = (unsigned char *)void_src; - int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; - SECStatus rv; + unsigned char *src = (unsigned char *)void_src; + int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */ + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* protects sendBuf. */ if (!bytes) - return SECSuccess; + return SECSuccess; if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) { - rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH, - PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes))); - if (rv != SECSuccess) - return rv; /* sslBuffer_Grow has set a memory error code. */ - room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; + rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH, + PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes))); + if (rv != SECSuccess) + return rv; /* sslBuffer_Grow has set a memory error code. */ + room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; } - PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes)); + PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char *)void_src, bytes)); rv = ssl3_UpdateHandshakeHashes(ss, src, bytes); if (rv != SECSuccess) - return rv; /* error code set by ssl3_UpdateHandshakeHashes */ + return rv; /* error code set by ssl3_UpdateHandshakeHashes */ while (bytes > room) { - if (room > 0) - PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, - room); - ss->sec.ci.sendBuf.len += room; - rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); - if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ - } - bytes -= room; - src += room; - room = ss->sec.ci.sendBuf.space; - PORT_Assert(ss->sec.ci.sendBuf.len == 0); + if (room > 0) + PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, + room); + ss->sec.ci.sendBuf.len += room; + rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); + if (rv != SECSuccess) { + return rv; /* error code set by ssl3_FlushHandshake */ + } + bytes -= room; + src += room; + room = ss->sec.ci.sendBuf.space; + PORT_Assert(ss->sec.ci.sendBuf.len == 0); } PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes); ss->sec.ci.sendBuf.len += bytes; @@ -4294,8 +4548,8 @@ SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) { SECStatus rv; - PRUint8 b[4]; - PRUint8 * p = b; + PRUint8 b[4]; + PRUint8 *p = b; PORT_Assert(lenSize <= 4 && lenSize > 0); if (lenSize < 4 && num >= (1L << (lenSize * 8))) { @@ -4304,18 +4558,18 @@ ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) } switch (lenSize) { - case 4: - *p++ = (num >> 24) & 0xff; - case 3: - *p++ = (num >> 16) & 0xff; - case 2: - *p++ = (num >> 8) & 0xff; - case 1: - *p = num & 0xff; + case 4: + *p++ = (num >> 24) & 0xff; + case 3: + *p++ = (num >> 16) & 0xff; + case 2: + *p++ = (num >> 8) & 0xff; + case 1: + *p = num & 0xff; } SSL_TRC(60, ("%d: number:", SSL_GETPID())); rv = ssl3_AppendHandshake(ss, &b[0], lenSize); - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } SECStatus @@ -4324,18 +4578,18 @@ ssl3_AppendHandshakeVariable( { SECStatus rv; - PORT_Assert((bytes < (1<<8) && lenSize == 1) || - (bytes < (1L<<16) && lenSize == 2) || - (bytes < (1L<<24) && lenSize == 3)); + PORT_Assert((bytes < (1 << 8) && lenSize == 1) || + (bytes < (1L << 16) && lenSize == 2) || + (bytes < (1L << 24) && lenSize == 3)); - SSL_TRC(60,("%d: append variable:", SSL_GETPID())); + SSL_TRC(60, ("%d: append variable:", SSL_GETPID())); rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } SSL_TRC(60, ("data:")); rv = ssl3_AppendHandshake(ss, src, bytes); - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } SECStatus @@ -4348,54 +4602,54 @@ ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length) * dtls_StageHandshakeMessage to mark the message boundary. */ if (IS_DTLS(ss)) { - rv = dtls_StageHandshakeMessage(ss); - if (rv != SECSuccess) { - return rv; - } + rv = dtls_StageHandshakeMessage(ss); + if (rv != SECSuccess) { + return rv; + } } - SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s", - SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); + SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s", + SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); rv = ssl3_AppendHandshakeNumber(ss, t, 1); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } rv = ssl3_AppendHandshakeNumber(ss, length, 3); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } if (IS_DTLS(ss)) { - /* Note that we make an unfragmented message here. We fragment in the - * transmission code, if necessary */ - rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2); - if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake, if applicable. */ - } - ss->ssl3.hs.sendMessageSeq++; + /* Note that we make an unfragmented message here. We fragment in the + * transmission code, if necessary */ + rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2); + if (rv != SECSuccess) { + return rv; /* error code set by AppendHandshake, if applicable. */ + } + ss->ssl3.hs.sendMessageSeq++; - /* 0 is the fragment offset, because it's not fragmented yet */ - rv = ssl3_AppendHandshakeNumber(ss, 0, 3); - if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake, if applicable. */ - } + /* 0 is the fragment offset, because it's not fragmented yet */ + rv = ssl3_AppendHandshakeNumber(ss, 0, 3); + if (rv != SECSuccess) { + return rv; /* error code set by AppendHandshake, if applicable. */ + } - /* Fragment length -- set to the packet length because not fragmented */ - rv = ssl3_AppendHandshakeNumber(ss, length, 3); - if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake, if applicable. */ - } + /* Fragment length -- set to the packet length because not fragmented */ + rv = ssl3_AppendHandshakeNumber(ss, length, 3); + if (rv != SECSuccess) { + return rv; /* error code set by AppendHandshake, if applicable. */ + } } - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of * |sigAndHash| to the current handshake message. */ SECStatus ssl3_AppendSignatureAndHashAlgorithm( - sslSocket *ss, const SSLSignatureAndHashAlg* sigAndHash) + sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash) { PRUint8 serialized[2]; @@ -4422,17 +4676,17 @@ ssl3_AppendSignatureAndHashAlgorithm( */ SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, - PRUint32 *length) + PRUint32 *length) { - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if ((PRUint32)bytes > *length) { - return ssl3_DecodeError(ss); + return ssl3_DecodeError(ss); } PORT_Memcpy(v, *b, bytes); PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); - *b += bytes; + *b += bytes; *length -= bytes; return SECSuccess; } @@ -4450,24 +4704,24 @@ ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, */ PRInt32 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, - PRUint32 *length) + PRUint32 *length) { - PRUint8 *buf = *b; - int i; - PRInt32 num = 0; + PRUint8 *buf = *b; + int i; + PRInt32 num = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( bytes <= sizeof num); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(bytes <= sizeof num); if ((PRUint32)bytes > *length) { - return ssl3_DecodeError(ss); + return ssl3_DecodeError(ss); } PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); for (i = 0; i < bytes; i++) - num = (num << 8) + buf[i]; - *b += bytes; + num = (num << 8) + buf[i]; + *b += bytes; *length -= bytes; return num; } @@ -4481,33 +4735,33 @@ ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, * Returns SECFailure (-1) on failure. * On error, an alert has been sent, and a generic error code has been set. * - * RADICAL CHANGE for NSS 3.11. All callers of this function make copies + * RADICAL CHANGE for NSS 3.11. All callers of this function make copies * of the data returned in the SECItem *i, so making a copy of it here - * is simply wasteful. So, This function now just sets SECItem *i to + * is simply wasteful. So, This function now just sets SECItem *i to * point to the values in the buffer **b. */ SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes, - SSL3Opaque **b, PRUint32 *length) + SSL3Opaque **b, PRUint32 *length) { - PRInt32 count; + PRInt32 count; PORT_Assert(bytes <= 3); - i->len = 0; + i->len = 0; i->data = NULL; i->type = siBuffer; count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length); - if (count < 0) { /* Can't test for SECSuccess here. */ - return SECFailure; + if (count < 0) { /* Can't test for SECSuccess here. */ + return SECFailure; } if (count > 0) { - if ((PRUint32)count > *length) { - return ssl3_DecodeError(ss); - } - i->data = *b; - i->len = count; - *b += count; - *length -= count; + if ((PRUint32)count > *length) { + return ssl3_DecodeError(ss); + } + i->data = *b; + i->len = count; + *b += count; + *length -= count; } return SECSuccess; } @@ -4534,9 +4788,9 @@ ssl3_TLSHashAlgorithmToOID(SSLHashType hashFunc) unsigned int i; for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { - if (hashFunc == tlsHashOIDMap[i].tlsHash) { - return tlsHashOIDMap[i].oid; - } + if (hashFunc == tlsHashOIDMap[i].tlsHash) { + return tlsHashOIDMap[i].oid; + } } return SEC_OID_UNKNOWN; } @@ -4547,18 +4801,18 @@ static SECStatus ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, SSLSignType *out) { switch (keyType) { - case rsaKey: - *out = ssl_sign_rsa; - return SECSuccess; - case dsaKey: - *out = ssl_sign_dsa; - return SECSuccess; - case ecKey: - *out = ssl_sign_ecdsa; - return SECSuccess; - default: - PORT_SetError(SEC_ERROR_INVALID_KEY); - return SECFailure; + case rsaKey: + *out = ssl_sign_rsa; + return SECSuccess; + case dsaKey: + *out = ssl_sign_dsa; + return SECSuccess; + case ecKey: + *out = ssl_sign_ecdsa; + return SECSuccess; + default: + PORT_SetError(SEC_ERROR_INVALID_KEY); + return SECFailure; } } @@ -4590,7 +4844,7 @@ ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert, SECStatus ssl3_CheckSignatureAndHashAlgorithmConsistency( sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash, - CERTCertificate* cert) + CERTCertificate *cert) { SECStatus rv; SSLSignType sigAlg; @@ -4704,21 +4958,21 @@ ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, * * Caller must hold the SSL3HandshakeLock. * Caller must hold a read or write lock on the Spec R/W lock. - * (There is presently no way to assert on a Read lock.) + * (There is presently no way to assert on a Read lock.) */ SECStatus -ssl3_ComputeHandshakeHashes(sslSocket * ss, - ssl3CipherSpec *spec, /* uses ->master_secret */ - SSL3Hashes * hashes, /* output goes here. */ - PRUint32 sender) +ssl3_ComputeHandshakeHashes(sslSocket *ss, + ssl3CipherSpec *spec, /* uses ->master_secret */ + SSL3Hashes *hashes, /* output goes here. */ + PRUint32 sender) { - SECStatus rv = SECSuccess; - PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); - unsigned int outLength; - SSL3Opaque md5_inner[MAX_MAC_LENGTH]; - SSL3Opaque sha_inner[MAX_MAC_LENGTH]; + SECStatus rv = SECSuccess; + PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); + unsigned int outLength; + SSL3Opaque md5_inner[MAX_MAC_LENGTH]; + SSL3Opaque sha_inner[MAX_MAC_LENGTH]; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->ssl3.hs.hashType == handshake_hash_unknown) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; @@ -4728,170 +4982,173 @@ ssl3_ComputeHandshakeHashes(sslSocket * ss, #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11 && - ss->ssl3.hs.hashType == handshake_hash_single) { - /* compute them without PKCS11 */ - PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; + ss->ssl3.hs.hashType == handshake_hash_single) { + /* compute them without PKCS11 */ + PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; - ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); - ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, - sizeof(hashes->u.raw)); + ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); + ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, + sizeof(hashes->u.raw)); - PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); + PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - hashes->hashAlg = ssl_hash_sha256; - rv = SECSuccess; - } else if (ss->opt.bypassPKCS11) { - /* compute them without PKCS11 */ - PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; - PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 + * then this will need to be updated. */ + hashes->hashAlg = ssl_hash_sha256; + rv = SECSuccess; + } + else if (ss->opt.bypassPKCS11) { + /* compute them without PKCS11 */ + PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; + PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; #define md5cx ((MD5Context *)md5_cx) #define shacx ((SHA1Context *)sha_cx) - MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); - SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); + MD5_Clone(md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); + SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); - if (!isTLS) { - /* compute hashes for SSL3. */ - unsigned char s[4]; + if (!isTLS) { + /* compute hashes for SSL3. */ + unsigned char s[4]; if (!spec->msItem.data) { PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); return SECFailure; } - s[0] = (unsigned char)(sender >> 24); - s[1] = (unsigned char)(sender >> 16); - s[2] = (unsigned char)(sender >> 8); - s[3] = (unsigned char)sender; + s[0] = (unsigned char)(sender >> 24); + s[1] = (unsigned char)(sender >> 16); + s[2] = (unsigned char)(sender >> 8); + s[3] = (unsigned char)sender; - if (sender != 0) { - MD5_Update(md5cx, s, 4); - PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); - } + if (sender != 0) { + MD5_Update(md5cx, s, 4); + PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); + } - PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, - mac_defs[mac_md5].pad_size)); + PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, + mac_defs[mac_md5].pad_size)); - MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); - MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); - MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); + MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); + MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); + MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); - PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); + PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); - if (sender != 0) { - SHA1_Update(shacx, s, 4); - PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); - } + if (sender != 0) { + SHA1_Update(shacx, s, 4); + PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); + } - PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, - mac_defs[mac_sha].pad_size)); + PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, + mac_defs[mac_sha].pad_size)); - SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); - SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); - SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); + SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); + SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); + SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); - PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); - PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, - mac_defs[mac_md5].pad_size)); - PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); + PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); + PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, + mac_defs[mac_md5].pad_size)); + PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); - MD5_Begin(md5cx); - MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); - MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); - MD5_Update(md5cx, md5_inner, MD5_LENGTH); - } - MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); + MD5_Begin(md5cx); + MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); + MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); + MD5_Update(md5cx, md5_inner, MD5_LENGTH); + } + MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); - PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); + PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); - if (!isTLS) { - PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, - mac_defs[mac_sha].pad_size)); - PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); + if (!isTLS) { + PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, + mac_defs[mac_sha].pad_size)); + PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); - SHA1_Begin(shacx); - SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); - SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); - SHA1_Update(shacx, sha_inner, SHA1_LENGTH); - } - SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); + SHA1_Begin(shacx); + SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); + SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); + SHA1_Update(shacx, sha_inner, SHA1_LENGTH); + } + SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); - PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); + PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); - hashes->len = MD5_LENGTH + SHA1_LENGTH; - rv = SECSuccess; + hashes->len = MD5_LENGTH + SHA1_LENGTH; + rv = SECSuccess; #undef md5cx #undef shacx - } else + } + else #endif - if (ss->ssl3.hs.hashType == handshake_hash_single) { - /* compute hashes with PKCS11 */ - PK11Context *h; - unsigned int stateLen; - unsigned char stackBuf[1024]; - unsigned char *stateBuf = NULL; + if (ss->ssl3.hs.hashType == handshake_hash_single) { + /* compute hashes with PKCS11 */ + PK11Context *h; + unsigned int stateLen; + unsigned char stackBuf[1024]; + unsigned char *stateBuf = NULL; - h = ss->ssl3.hs.sha; - stateBuf = PK11_SaveContextAlloc(h, stackBuf, - sizeof(stackBuf), &stateLen); - if (stateBuf == NULL) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - goto tls12_loser; - } - rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, - sizeof(hashes->u.raw)); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - rv = SECFailure; - goto tls12_loser; - } - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - hashes->hashAlg = ssl_hash_sha256; - rv = SECSuccess; + h = ss->ssl3.hs.sha; + stateBuf = PK11_SaveContextAlloc(h, stackBuf, + sizeof(stackBuf), &stateLen); + if (stateBuf == NULL) { + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + goto tls12_loser; + } + rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, + sizeof(hashes->u.raw)); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + rv = SECFailure; + goto tls12_loser; + } + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 + * then this will need to be updated. */ + hashes->hashAlg = ssl_hash_sha256; + rv = SECSuccess; -tls12_loser: - if (stateBuf) { - if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - rv = SECFailure; - } - if (stateBuf != stackBuf) { - PORT_ZFree(stateBuf, stateLen); - } - } - } else { - /* compute hashes with PKCS11 */ - PK11Context * md5; - PK11Context * sha = NULL; - unsigned char *md5StateBuf = NULL; - unsigned char *shaStateBuf = NULL; - unsigned int md5StateLen, shaStateLen; - unsigned char md5StackBuf[256]; - unsigned char shaStackBuf[512]; + tls12_loser: + if (stateBuf) { + if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); + rv = SECFailure; + } + if (stateBuf != stackBuf) { + PORT_ZFree(stateBuf, stateLen); + } + } + } + else { + /* compute hashes with PKCS11 */ + PK11Context *md5; + PK11Context *sha = NULL; + unsigned char *md5StateBuf = NULL; + unsigned char *shaStateBuf = NULL; + unsigned int md5StateLen, shaStateLen; + unsigned char md5StackBuf[256]; + unsigned char shaStackBuf[512]; - md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, - sizeof md5StackBuf, &md5StateLen); - if (md5StateBuf == NULL) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - goto loser; - } - md5 = ss->ssl3.hs.md5; + md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, + sizeof md5StackBuf, &md5StateLen); + if (md5StateBuf == NULL) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + goto loser; + } + md5 = ss->ssl3.hs.md5; - shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, - sizeof shaStackBuf, &shaStateLen); - if (shaStateBuf == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - goto loser; - } - sha = ss->ssl3.hs.sha; + shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, + sizeof shaStackBuf, &shaStateLen); + if (shaStateBuf == NULL) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + goto loser; + } + sha = ss->ssl3.hs.sha; - if (!isTLS) { - /* compute hashes for SSL3. */ - unsigned char s[4]; + if (!isTLS) { + /* compute hashes for SSL3. */ + unsigned char s[4]; if (!spec->master_secret) { PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); @@ -4899,136 +5156,134 @@ tls12_loser: goto loser; } - s[0] = (unsigned char)(sender >> 24); - s[1] = (unsigned char)(sender >> 16); - s[2] = (unsigned char)(sender >> 8); - s[3] = (unsigned char)sender; + s[0] = (unsigned char)(sender >> 24); + s[1] = (unsigned char)(sender >> 16); + s[2] = (unsigned char)(sender >> 8); + s[3] = (unsigned char)sender; - if (sender != 0) { - rv |= PK11_DigestOp(md5, s, 4); - PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); - } + if (sender != 0) { + rv |= PK11_DigestOp(md5, s, 4); + PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); + } - PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, - mac_defs[mac_md5].pad_size)); + PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, + mac_defs[mac_md5].pad_size)); - rv |= PK11_DigestKey(md5,spec->master_secret); - rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); - rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); - PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - rv = SECFailure; - goto loser; - } + rv |= PK11_DigestKey(md5, spec->master_secret); + rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); + rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); + PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + rv = SECFailure; + goto loser; + } - PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); + PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); - if (sender != 0) { - rv |= PK11_DigestOp(sha, s, 4); - PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); - } + if (sender != 0) { + rv |= PK11_DigestOp(sha, s, 4); + PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); + } - PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, - mac_defs[mac_sha].pad_size)); + PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, + mac_defs[mac_sha].pad_size)); - rv |= PK11_DigestKey(sha, spec->master_secret); - rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); - rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); - PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - rv = SECFailure; - goto loser; - } + rv |= PK11_DigestKey(sha, spec->master_secret); + rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); + rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); + PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + rv = SECFailure; + goto loser; + } - PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); + PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); - PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, - mac_defs[mac_md5].pad_size)); - PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); + PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, + mac_defs[mac_md5].pad_size)); + PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); - rv |= PK11_DigestBegin(md5); - rv |= PK11_DigestKey(md5, spec->master_secret); - rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); - rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); - } - rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); - PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - rv = SECFailure; - goto loser; - } + rv |= PK11_DigestBegin(md5); + rv |= PK11_DigestKey(md5, spec->master_secret); + rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); + rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); + } + rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); + PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + rv = SECFailure; + goto loser; + } - PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); + PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); - if (!isTLS) { - PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, - mac_defs[mac_sha].pad_size)); - PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); + if (!isTLS) { + PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, + mac_defs[mac_sha].pad_size)); + PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); - rv |= PK11_DigestBegin(sha); - rv |= PK11_DigestKey(sha,spec->master_secret); - rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); - rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); - } - rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); - PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - rv = SECFailure; - goto loser; - } + rv |= PK11_DigestBegin(sha); + rv |= PK11_DigestKey(sha, spec->master_secret); + rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); + rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); + } + rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); + PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + rv = SECFailure; + goto loser; + } - PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); + PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); - hashes->len = MD5_LENGTH + SHA1_LENGTH; - rv = SECSuccess; + hashes->len = MD5_LENGTH + SHA1_LENGTH; + rv = SECSuccess; loser: - if (md5StateBuf) { - if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) - != SECSuccess) - { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - rv = SECFailure; - } - if (md5StateBuf != md5StackBuf) { - PORT_ZFree(md5StateBuf, md5StateLen); - } - } - if (shaStateBuf) { - if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) - != SECSuccess) - { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - rv = SECFailure; - } - if (shaStateBuf != shaStackBuf) { - PORT_ZFree(shaStateBuf, shaStateLen); - } - } + if (md5StateBuf) { + if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) != + SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + rv = SECFailure; + } + if (md5StateBuf != md5StackBuf) { + PORT_ZFree(md5StateBuf, md5StateLen); + } + } + if (shaStateBuf) { + if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) != + SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + rv = SECFailure; + } + if (shaStateBuf != shaStackBuf) { + PORT_ZFree(shaStateBuf, shaStateLen); + } + } } return rv; } static SECStatus -ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, - SSL3Hashes * hashes) /* output goes here. */ +ssl3_ComputeBackupHandshakeHashes(sslSocket *ss, + SSL3Hashes *hashes) /* output goes here. */ { SECStatus rv = SECSuccess; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( !ss->sec.isServer ); - PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(!ss->sec.isServer); + PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single); rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len, - sizeof(hashes->u.raw)); + sizeof(hashes->u.raw)); if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - rv = SECFailure; - goto loser; + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + rv = SECFailure; + goto loser; } hashes->hashAlg = ssl_hash_sha1; @@ -5045,32 +5300,32 @@ loser: * Called from ssl2_BeginClientHandshake() in sslcon.c */ SECStatus -ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length) +ssl3_StartHandshakeHash(sslSocket *ss, unsigned char *buf, int length) { SECStatus rv; - ssl_GetSSL3HandshakeLock(ss); /**************************************/ + ssl_GetSSL3HandshakeLock(ss); /**************************************/ rv = ssl3_InitState(ss); if (rv != SECSuccess) { - goto done; /* ssl3_InitState has set the error code. */ + goto done; /* ssl3_InitState has set the error code. */ } rv = ssl3_RestartHandshakeHashes(ss); if (rv != SECSuccess) { - goto done; + goto done; } PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); PORT_Memcpy( - &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES], - &ss->sec.ci.clientChallenge, - SSL_CHALLENGE_BYTES); + &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES], + &ss->sec.ci.clientChallenge, + SSL_CHALLENGE_BYTES); rv = ssl3_UpdateHandshakeHashes(ss, buf, length); /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */ done: - ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ + ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ return rv; } @@ -5087,29 +5342,29 @@ done: SECStatus ssl3_SendClientHello(sslSocket *ss, PRBool resending) { - sslSessionID * sid; - ssl3CipherSpec * cwSpec; - SECStatus rv; - int i; - int length; - int num_suites; - int actual_count = 0; - PRBool isTLS = PR_FALSE; - PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; - PRInt32 total_exten_len = 0; - unsigned paddingExtensionLen; - unsigned numCompressionMethods; - PRInt32 flags; + sslSessionID *sid; + ssl3CipherSpec *cwSpec; + SECStatus rv; + int i; + int length; + int num_suites; + int actual_count = 0; + PRBool isTLS = PR_FALSE; + PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; + PRInt32 total_exten_len = 0; + unsigned paddingExtensionLen; + unsigned numCompressionMethods; + PRInt32 flags; SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(), - ss->fd)); + ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); rv = ssl3_InitState(ss); if (rv != SECSuccess) { - return rv; /* ssl3_InitState has set the error code. */ + return rv; /* ssl3_InitState has set the error code. */ } /* These must be reset every handshake. */ ss->ssl3.hs.sendingSCSV = PR_FALSE; @@ -5126,7 +5381,7 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) rv = ssl3_RestartHandshakeHashes(ss); if (rv != SECSuccess) { - return rv; + return rv; } /* @@ -5134,16 +5389,16 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) * work around a Windows SChannel bug. Ensure that it is still enabled. */ if (ss->firstHsDone) { - if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - PORT_SetError(SSL_ERROR_SSL_DISABLED); - return SECFailure; - } + if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { + PORT_SetError(SSL_ERROR_SSL_DISABLED); + return SECFailure; + } - if (ss->clientHelloVersion < ss->vrange.min || - ss->clientHelloVersion > ss->vrange.max) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; - } + if (ss->clientHelloVersion < ss->vrange.min || + ss->clientHelloVersion > ss->vrange.max) { + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return SECFailure; + } } /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup @@ -5152,7 +5407,7 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) * this lookup is duplicative and wasteful. */ sid = (ss->opt.noCache) ? NULL - : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url); + : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url); /* We can't resume based on a different token. If the sid exists, * make sure the token that holds the master secret still exists ... @@ -5160,122 +5415,129 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) * the private key still exists, is logged in, hasn't been removed, etc. */ if (sid) { - PRBool sidOK = PR_TRUE; - if (sid->u.ssl3.keys.msIsWrapped) { - /* Session key was wrapped, which means it was using PKCS11, */ - PK11SlotInfo *slot = NULL; - if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { - slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, - sid->u.ssl3.masterSlotID); - } - if (slot == NULL) { - sidOK = PR_FALSE; - } else { - PK11SymKey *wrapKey = NULL; - if (!PK11_IsPresent(slot) || - ((wrapKey = PK11_GetWrapKey(slot, - sid->u.ssl3.masterWrapIndex, - sid->u.ssl3.masterWrapMech, - sid->u.ssl3.masterWrapSeries, - ss->pkcs11PinArg)) == NULL) ) { - sidOK = PR_FALSE; - } - if (wrapKey) PK11_FreeSymKey(wrapKey); - PK11_FreeSlot(slot); - slot = NULL; - } - } - /* If we previously did client-auth, make sure that the token that - ** holds the private key still exists, is logged in, hasn't been - ** removed, etc. - */ - if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { - sidOK = PR_FALSE; - } + PRBool sidOK = PR_TRUE; + if (sid->u.ssl3.keys.msIsWrapped) { + /* Session key was wrapped, which means it was using PKCS11, */ + PK11SlotInfo *slot = NULL; + if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { + slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, + sid->u.ssl3.masterSlotID); + } + if (slot == NULL) { + sidOK = PR_FALSE; + } + else { + PK11SymKey *wrapKey = NULL; + if (!PK11_IsPresent(slot) || + ((wrapKey = PK11_GetWrapKey(slot, + sid->u.ssl3.masterWrapIndex, + sid->u.ssl3.masterWrapMech, + sid->u.ssl3.masterWrapSeries, + ss->pkcs11PinArg)) == NULL)) { + sidOK = PR_FALSE; + } + if (wrapKey) + PK11_FreeSymKey(wrapKey); + PK11_FreeSlot(slot); + slot = NULL; + } + } + /* If we previously did client-auth, make sure that the token that + ** holds the private key still exists, is logged in, hasn't been + ** removed, etc. + */ + if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { + sidOK = PR_FALSE; + } - if (sidOK) { + if (sidOK) { /* Set ss->version based on the session cache */ - if (ss->firstHsDone) { - /* - * Windows SChannel compares the client_version inside the RSA - * EncryptedPreMasterSecret of a renegotiation with the - * client_version of the initial ClientHello rather than the - * ClientHello in the renegotiation. To work around this bug, we - * continue to use the client_version used in the initial - * ClientHello when renegotiating. - * - * The client_version of the initial ClientHello is still - * available in ss->clientHelloVersion. Ensure that - * sid->version is bounded within - * [ss->vrange.min, ss->clientHelloVersion], otherwise we - * can't use sid. - */ - if (sid->version >= ss->vrange.min && - sid->version <= ss->clientHelloVersion) { - ss->version = ss->clientHelloVersion; - } else { - sidOK = PR_FALSE; - } - } else { + if (ss->firstHsDone) { + /* + * Windows SChannel compares the client_version inside the RSA + * EncryptedPreMasterSecret of a renegotiation with the + * client_version of the initial ClientHello rather than the + * ClientHello in the renegotiation. To work around this bug, we + * continue to use the client_version used in the initial + * ClientHello when renegotiating. + * + * The client_version of the initial ClientHello is still + * available in ss->clientHelloVersion. Ensure that + * sid->version is bounded within + * [ss->vrange.min, ss->clientHelloVersion], otherwise we + * can't use sid. + */ + if (sid->version >= ss->vrange.min && + sid->version <= ss->clientHelloVersion) { + ss->version = ss->clientHelloVersion; + } + else { + sidOK = PR_FALSE; + } + } + else { /* * Check sid->version is OK first. * Previously, we would cap the version based on sid->version, * but that prevents negotiation of a higher version if the * previous session was reduced (e.g., with version fallback) */ - if (sid->version < ss->vrange.min || + if (sid->version < ss->vrange.min || sid->version > ss->vrange.max) { - sidOK = PR_FALSE; - } else { - rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, + sidOK = PR_FALSE; + } + else { + rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, PR_TRUE); - if (rv != SECSuccess) { - return rv; /* error code was set */ + if (rv != SECSuccess) { + return rv; /* error code was set */ } - } - } - } + } + } + } - if (!sidOK) { - SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok ); - if (ss->sec.uncache) + if (!sidOK) { + SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok); + if (ss->sec.uncache) (*ss->sec.uncache)(sid); - ssl_FreeSID(sid); - sid = NULL; - } + ssl_FreeSID(sid); + sid = NULL; + } } if (sid) { - requestingResume = PR_TRUE; - SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits ); + requestingResume = PR_TRUE; + SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits); - PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, - sid->u.ssl3.sessionIDLength)); + PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, + sid->u.ssl3.sessionIDLength)); - ss->ssl3.policy = sid->u.ssl3.policy; - } else { - SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses ); + ss->ssl3.policy = sid->u.ssl3.policy; + } + else { + SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses); - /* - * Windows SChannel compares the client_version inside the RSA - * EncryptedPreMasterSecret of a renegotiation with the - * client_version of the initial ClientHello rather than the - * ClientHello in the renegotiation. To work around this bug, we - * continue to use the client_version used in the initial - * ClientHello when renegotiating. - */ - if (ss->firstHsDone) { - ss->version = ss->clientHelloVersion; - } else { - rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, - PR_TRUE); - if (rv != SECSuccess) - return rv; /* error code was set */ - } + /* + * Windows SChannel compares the client_version inside the RSA + * EncryptedPreMasterSecret of a renegotiation with the + * client_version of the initial ClientHello rather than the + * ClientHello in the renegotiation. To work around this bug, we + * continue to use the client_version used in the initial + * ClientHello when renegotiating. + */ + if (ss->firstHsDone) { + ss->version = ss->clientHelloVersion; + } + else { + rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, + PR_TRUE); + if (rv != SECSuccess) + return rv; /* error code was set */ + } - sid = ssl3_NewSessionID(ss, PR_FALSE); - if (!sid) { - return SECFailure; /* memory error is set */ + sid = ssl3_NewSessionID(ss, PR_FALSE); + if (!sid) { + return SECFailure; /* memory error is set */ } } @@ -5289,13 +5551,13 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) ssl_GetSpecWriteLock(ss); cwSpec = ss->ssl3.cwSpec; if (cwSpec->mac_def->mac == mac_null) { - /* SSL records are not being MACed. */ - cwSpec->version = ss->version; + /* SSL records are not being MACed. */ + cwSpec->version = ss->version; } ssl_ReleaseSpecWriteLock(ss); if (ss->sec.ci.sid != NULL) { - ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ + ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ } ss->sec.ci.sid = sid; @@ -5303,24 +5565,24 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) /* shouldn't get here if SSL3 is disabled, but ... */ if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); - PORT_SetError(SSL_ERROR_SSL_DISABLED); - return SECFailure; + PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); + PORT_SetError(SSL_ERROR_SSL_DISABLED); + return SECFailure; } /* how many suites does our PKCS11 support (regardless of policy)? */ num_suites = ssl3_config_match_init(ss); if (!num_suites) - return SECFailure; /* ssl3_config_match_init has set error code. */ + return SECFailure; /* ssl3_config_match_init has set error code. */ /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV, * only if TLS is disabled. */ if (!ss->firstHsDone && !isTLS) { - /* Must set this before calling Hello Extension Senders, - * to suppress sending of empty RI extension. - */ - ss->ssl3.hs.sendingSCSV = PR_TRUE; + /* Must set this before calling Hello Extension Senders, + * to suppress sending of empty RI extension. + */ + ss->ssl3.hs.sendingSCSV = PR_TRUE; } /* When we attempt session resumption (only), we must lock the sid to @@ -5335,61 +5597,65 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) } if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { - PRUint32 maxBytes = 65535; /* 2^16 - 1 */ - PRInt32 extLen; + PRUint32 maxBytes = 65535; /* 2^16 - 1 */ + PRInt32 extLen; - extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); - if (extLen < 0) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; - } - total_exten_len += extLen; + extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); + if (extLen < 0) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; + } + total_exten_len += extLen; - if (total_exten_len > 0) - total_exten_len += 2; + if (total_exten_len > 0) + total_exten_len += 2; } #ifndef NSS_DISABLE_ECC if (!total_exten_len || !isTLS) { - /* not sending the elliptic_curves and ec_point_formats extensions */ - ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ + /* not sending the elliptic_curves and ec_point_formats extensions */ + ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ } #endif /* NSS_DISABLE_ECC */ if (IS_DTLS(ss)) { - ssl3_DisableNonDTLSSuites(ss); + ssl3_DisableNonDTLSSuites(ss); } /* how many suites are permitted by policy and user preference? */ num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); if (!num_suites) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; /* count_cipher_suites has set error code. */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; /* count_cipher_suites has set error code. */ } fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume || - ss->version < sid->version); + ss->version < sid->version); /* make room for SCSV */ if (ss->ssl3.hs.sendingSCSV) { - ++num_suites; + ++num_suites; } if (fallbackSCSV) { - ++num_suites; + ++num_suites; } /* count compression methods */ numCompressionMethods = 0; for (i = 0; i < compressionMethodsCount; i++) { - if (compressionEnabled(ss, compressions[i])) - numCompressionMethods++; + if (compressionEnabled(ss, compressions[i])) + numCompressionMethods++; } length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + - 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + - 2 + num_suites*sizeof(ssl3CipherSuite) + - 1 + numCompressionMethods + total_exten_len; + 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + + 2 + num_suites * sizeof(ssl3CipherSuite) + + 1 + numCompressionMethods + total_exten_len; if (IS_DTLS(ss)) { - length += 1 + ss->ssl3.hs.cookieLen; + length += 1 + ss->ssl3.hs.cookieLen; } /* A padding extension may be included to ensure that the record containing @@ -5402,163 +5668,199 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length); total_exten_len += paddingExtensionLen; length += paddingExtensionLen; - } else { + } + else { paddingExtensionLen = 0; } rv = ssl3_AppendHandshakeHeader(ss, client_hello, length); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (ss->firstHsDone) { - /* The client hello version must stay unchanged to work around - * the Windows SChannel bug described above. */ - PORT_Assert(ss->version == ss->clientHelloVersion); + /* The client hello version must stay unchanged to work around + * the Windows SChannel bug described above. */ + PORT_Assert(ss->version == ss->clientHelloVersion); } ss->clientHelloVersion = ss->version; if (IS_DTLS(ss)) { - PRUint16 version; + PRUint16 version; - version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); - rv = ssl3_AppendHandshakeNumber(ss, version, 2); - } else { - rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); + version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); + rv = ssl3_AppendHandshakeNumber(ss, version, 2); + } + else { + rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); } if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */ - rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by GetNewRandom. */ - } + rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by GetNewRandom. */ + } } rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (sid) - rv = ssl3_AppendHandshakeVariable( - ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); + rv = ssl3_AppendHandshakeVariable( + ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); else - rv = ssl3_AppendHandshakeNumber(ss, 0, 1); + rv = ssl3_AppendHandshakeNumber(ss, 0, 1); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (IS_DTLS(ss)) { - rv = ssl3_AppendHandshakeVariable( - ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } + rv = ssl3_AppendHandshakeVariable( + ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } } - rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2); + rv = ssl3_AppendHandshakeNumber(ss, num_suites * sizeof(ssl3CipherSuite), 2); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (ss->ssl3.hs.sendingSCSV) { - /* Add the actual SCSV */ - rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } - actual_count++; + /* Add the actual SCSV */ + rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } + actual_count++; } if (fallbackSCSV) { - rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } - actual_count++; + rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } + actual_count++; } for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; - if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange, ss)) { - actual_count++; - if (actual_count > num_suites) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - /* set error card removal/insertion error */ - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; - } - rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } - } + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; + if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange, ss)) { + actual_count++; + if (actual_count > num_suites) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + /* set error card removal/insertion error */ + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; + } + rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } + } } /* if cards were removed or inserted between count_cipher_suites and * generating our list, detect the error here rather than send it off to * the server.. */ if (actual_count != num_suites) { - /* Card removal/insertion error */ - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; + /* Card removal/insertion error */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; } rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } for (i = 0; i < compressionMethodsCount; i++) { - if (!compressionEnabled(ss, compressions[i])) - continue; - rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } + if (!compressionEnabled(ss, compressions[i])) + continue; + rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } } if (total_exten_len) { - PRUint32 maxBytes = total_exten_len - 2; - PRInt32 extLen; + PRUint32 maxBytes = total_exten_len - 2; + PRInt32 extLen; - rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by AppendHandshake. */ + } - extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); - if (extLen < 0) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; - } - maxBytes -= extLen; + extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); + if (extLen < 0) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; + } + maxBytes -= extLen; - extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); - if (extLen < 0) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; - } - maxBytes -= extLen; + extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); + if (extLen < 0) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; + } + maxBytes -= extLen; - PORT_Assert(!maxBytes); - } + PORT_Assert(!maxBytes); + } if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); @@ -5569,26 +5871,25 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) } if (ss->ssl3.hs.sendingSCSV) { - /* Since we sent the SCSV, pretend we sent empty RI extension. */ - TLSExtensionData *xtnData = &ss->xtnData; - xtnData->advertised[xtnData->numAdvertised++] = - ssl_renegotiation_info_xtn; + /* Since we sent the SCSV, pretend we sent empty RI extension. */ + TLSExtensionData *xtnData = &ss->xtnData; + xtnData->advertised[xtnData->numAdvertised++] = + ssl_renegotiation_info_xtn; } flags = 0; if (!ss->firstHsDone && !IS_DTLS(ss)) { - flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; + flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; } rv = ssl3_FlushHandshake(ss, flags); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + return rv; /* error code set by ssl3_FlushHandshake */ } ss->ssl3.hs.ws = wait_server_hello; return rv; } - /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a * complete ssl3 Hello Request. * Caller must hold Handshake and RecvBuf locks. @@ -5597,37 +5898,37 @@ static SECStatus ssl3_HandleHelloRequest(sslSocket *ss) { sslSessionID *sid = ss->sec.ci.sid; - SECStatus rv; + SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: handle hello_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) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); if (ss->ssl3.hs.ws == wait_server_hello) - return SECSuccess; + return SECSuccess; if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); - return SECFailure; + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); + return SECFailure; } if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { - (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation); - PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); - return SECFailure; + (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation); + PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); + return SECFailure; } if (sid) { - if (ss->sec.uncache) + if (ss->sec.uncache) ss->sec.uncache(sid); - ssl_FreeSID(sid); - ss->sec.ci.sid = NULL; + ssl_FreeSID(sid); + ss->sec.ci.sid = NULL; } if (IS_DTLS(ss)) { - dtls_RehandshakeCleanup(ss); + dtls_RehandshakeCleanup(ss); } ssl_GetXmitBufLock(ss); @@ -5664,7 +5965,7 @@ ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) const CK_MECHANISM_TYPE *pMech = wrapMechanismList; while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) { - ++pMech; + ++pMech; } return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1 : (pMech - wrapMechanismList); @@ -5672,97 +5973,97 @@ ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) static PK11SymKey * ssl_UnwrapSymWrappingKey( - SSLWrappedSymWrappingKey *pWswk, - SECKEYPrivateKey * svrPrivKey, - SSL3KEAType exchKeyType, - CK_MECHANISM_TYPE masterWrapMech, - void * pwArg) + SSLWrappedSymWrappingKey *pWswk, + SECKEYPrivateKey *svrPrivKey, + SSL3KEAType exchKeyType, + CK_MECHANISM_TYPE masterWrapMech, + void *pwArg) { - PK11SymKey * unwrappedWrappingKey = NULL; - SECItem wrappedKey; + PK11SymKey *unwrappedWrappingKey = NULL; + SECItem wrappedKey; #ifndef NSS_DISABLE_ECC - PK11SymKey * Ks; - SECKEYPublicKey pubWrapKey; - ECCWrappedKeyInfo *ecWrapped; + PK11SymKey *Ks; + SECKEYPublicKey pubWrapKey; + ECCWrappedKeyInfo *ecWrapped; #endif /* NSS_DISABLE_ECC */ /* found the wrapping key on disk. */ PORT_Assert(pWswk->symWrapMechanism == masterWrapMech); - PORT_Assert(pWswk->exchKeyType == exchKeyType); + PORT_Assert(pWswk->exchKeyType == exchKeyType); if (pWswk->symWrapMechanism != masterWrapMech || - pWswk->exchKeyType != exchKeyType) { - goto loser; + pWswk->exchKeyType != exchKeyType) { + goto loser; } wrappedKey.type = siBuffer; wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; - wrappedKey.len = pWswk->wrappedSymKeyLen; + wrappedKey.len = pWswk->wrappedSymKeyLen; PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); switch (exchKeyType) { - case kt_rsa: - unwrappedWrappingKey = - PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, - masterWrapMech, CKA_UNWRAP, 0); - break; + case kt_rsa: + unwrappedWrappingKey = + PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, + masterWrapMech, CKA_UNWRAP, 0); + break; #ifndef NSS_DISABLE_ECC - case kt_ecdh: - /* - * For kt_ecdh, we first create an EC public key based on - * data stored with the wrappedSymmetricWrappingkey. Next, - * we do an ECDH computation involving this public key and - * the SSL server's (long-term) EC private key. The resulting - * shared secret is treated the same way as Fortezza's Ks, i.e., - * it is used to recover the symmetric wrapping key. - * - * The data in wrappedSymmetricWrappingkey is laid out as defined - * in the ECCWrappedKeyInfo structure. - */ - ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey; + case kt_ecdh: + /* + * For kt_ecdh, we first create an EC public key based on + * data stored with the wrappedSymmetricWrappingkey. Next, + * we do an ECDH computation involving this public key and + * the SSL server's (long-term) EC private key. The resulting + * shared secret is treated the same way as Fortezza's Ks, i.e., + * it is used to recover the symmetric wrapping key. + * + * The data in wrappedSymmetricWrappingkey is laid out as defined + * in the ECCWrappedKeyInfo structure. + */ + ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey; - PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + - ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN); + PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + + ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN); - if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + - ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto loser; - } + if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + + ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + goto loser; + } - pubWrapKey.keyType = ecKey; - pubWrapKey.u.ec.size = ecWrapped->size; - pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; - pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; - pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; - pubWrapKey.u.ec.publicValue.data = ecWrapped->var + - ecWrapped->encodedParamLen; + pubWrapKey.keyType = ecKey; + pubWrapKey.u.ec.size = ecWrapped->size; + pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; + pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; + pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; + pubWrapKey.u.ec.publicValue.data = ecWrapped->var + + ecWrapped->encodedParamLen; - wrappedKey.len = ecWrapped->wrappedKeyLen; - wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + - ecWrapped->pubValueLen; - - /* Derive Ks using ECDH */ - Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL, - NULL, CKM_ECDH1_DERIVE, masterWrapMech, - CKA_DERIVE, 0, CKD_NULL, NULL, NULL); - if (Ks == NULL) { - goto loser; - } + wrappedKey.len = ecWrapped->wrappedKeyLen; + wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + + ecWrapped->pubValueLen; - /* Use Ks to unwrap the wrapping key */ - unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, - &wrappedKey, masterWrapMech, - CKA_UNWRAP, 0); - PK11_FreeSymKey(Ks); - - break; + /* Derive Ks using ECDH */ + Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL, + NULL, CKM_ECDH1_DERIVE, masterWrapMech, + CKA_DERIVE, 0, CKD_NULL, NULL, NULL); + if (Ks == NULL) { + goto loser; + } + + /* Use Ks to unwrap the wrapping key */ + unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, + &wrappedKey, masterWrapMech, + CKA_UNWRAP, 0); + PK11_FreeSymKey(Ks); + + break; #endif - default: - /* Assert? */ - SET_ERROR_CODE - goto loser; + default: + /* Assert? */ + SET_ERROR_CODE + goto loser; } loser: return unwrappedWrappingKey; @@ -5775,13 +6076,14 @@ loser: */ typedef struct { - PK11SymKey * symWrapKey[kt_kea_size]; + PK11SymKey *symWrapKey[kt_kea_size]; } ssl3SymWrapKey; -static PZLock * symWrapKeysLock = NULL; -static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; +static PZLock *symWrapKeysLock = NULL; +static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; -SECStatus ssl_FreeSymWrapKeysLock(void) +SECStatus +ssl_FreeSymWrapKeysLock(void) { if (symWrapKeysLock) { PZ_DestroyLock(symWrapKeysLock); @@ -5795,21 +6097,21 @@ SECStatus ssl_FreeSymWrapKeysLock(void) SECStatus SSL3_ShutdownServerCache(void) { - int i, j; + int i, j; if (!symWrapKeysLock) - return SECSuccess; /* lock was never initialized */ + return SECSuccess; /* lock was never initialized */ PZ_Lock(symWrapKeysLock); /* get rid of all symWrapKeys */ for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { - for (j = 0; j < kt_kea_size; ++j) { - PK11SymKey ** pSymWrapKey; - pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; - if (*pSymWrapKey) { - PK11_FreeSymKey(*pSymWrapKey); - *pSymWrapKey = NULL; - } - } + for (j = 0; j < kt_kea_size; ++j) { + PK11SymKey **pSymWrapKey; + pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; + if (*pSymWrapKey) { + PK11_FreeSymKey(*pSymWrapKey); + *pSymWrapKey = NULL; + } + } } PZ_Unlock(symWrapKeysLock); @@ -5817,7 +6119,8 @@ SSL3_ShutdownServerCache(void) return SECSuccess; } -SECStatus ssl_InitSymWrapKeysLock(void) +SECStatus +ssl_InitSymWrapKeysLock(void) { symWrapKeysLock = PZ_NewLock(nssILockOther); return symWrapKeysLock ? SECSuccess : SECFailure; @@ -5829,39 +6132,39 @@ SECStatus ssl_InitSymWrapKeysLock(void) * Put the new key in the in-memory array. */ static PK11SymKey * -getWrappingKey( sslSocket * ss, - PK11SlotInfo * masterSecretSlot, - SSL3KEAType exchKeyType, - CK_MECHANISM_TYPE masterWrapMech, - void * pwArg) +getWrappingKey(sslSocket *ss, + PK11SlotInfo *masterSecretSlot, + SSL3KEAType exchKeyType, + CK_MECHANISM_TYPE masterWrapMech, + void *pwArg) { - SECKEYPrivateKey * svrPrivKey; - SECKEYPublicKey * svrPubKey = NULL; - PK11SymKey * unwrappedWrappingKey = NULL; - PK11SymKey ** pSymWrapKey; - CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; - int length; - int symWrapMechIndex; - SECStatus rv; - SECItem wrappedKey; + SECKEYPrivateKey *svrPrivKey; + SECKEYPublicKey *svrPubKey = NULL; + PK11SymKey *unwrappedWrappingKey = NULL; + PK11SymKey **pSymWrapKey; + CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; + int length; + int symWrapMechIndex; + SECStatus rv; + SECItem wrappedKey; SSLWrappedSymWrappingKey wswk; #ifndef NSS_DISABLE_ECC - PK11SymKey * Ks = NULL; - SECKEYPublicKey *pubWrapKey = NULL; - SECKEYPrivateKey *privWrapKey = NULL; + PK11SymKey *Ks = NULL; + SECKEYPublicKey *pubWrapKey = NULL; + SECKEYPrivateKey *privWrapKey = NULL; ECCWrappedKeyInfo *ecWrapped; #endif /* NSS_DISABLE_ECC */ - svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; + svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; PORT_Assert(svrPrivKey != NULL); if (!svrPrivKey) { - return NULL; /* why are we here?!? */ + return NULL; /* why are we here?!? */ } symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech); PORT_Assert(symWrapMechIndex >= 0); if (symWrapMechIndex < 0) - return NULL; /* invalid masterWrapMech. */ + return NULL; /* invalid masterWrapMech. */ pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType]; @@ -5871,29 +6174,29 @@ getWrappingKey( sslSocket * ss, unwrappedWrappingKey = *pSymWrapKey; if (unwrappedWrappingKey != NULL) { - if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { - unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); - goto done; - } - /* slot series has changed, so this key is no good any more. */ - PK11_FreeSymKey(unwrappedWrappingKey); - *pSymWrapKey = unwrappedWrappingKey = NULL; + if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { + unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); + goto done; + } + /* slot series has changed, so this key is no good any more. */ + PK11_FreeSymKey(unwrappedWrappingKey); + *pSymWrapKey = unwrappedWrappingKey = NULL; } /* Try to get wrapped SymWrapping key out of the (disk) cache. */ /* Following call fills in wswk on success. */ if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) { - /* found the wrapped sym wrapping key on disk. */ - unwrappedWrappingKey = - ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, + /* found the wrapped sym wrapping key on disk. */ + unwrappedWrappingKey = + ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, masterWrapMech, pwArg); - if (unwrappedWrappingKey) { - goto install; - } + if (unwrappedWrappingKey) { + goto install; + } } - if (!masterSecretSlot) /* caller doesn't want to create a new one. */ - goto loser; + if (!masterSecretSlot) /* caller doesn't want to create a new one. */ + goto loser; length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech); /* Zero length means fixed key length algorithm, or error. @@ -5902,163 +6205,166 @@ getWrappingKey( sslSocket * ss, unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, length, pwArg); if (!unwrappedWrappingKey) { - goto loser; + goto loser; } /* Prepare the buffer to receive the wrappedWrappingKey, * the symmetric wrapping key wrapped using the server's pub key. */ - PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ + PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ if (ss->serverCerts[exchKeyType].serverKeyPair) { - svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; + svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; } if (svrPubKey == NULL) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto loser; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + goto loser; } wrappedKey.type = siBuffer; - wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); + wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); wrappedKey.data = wswk.wrappedSymmetricWrappingkey; PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) - goto loser; + goto loser; /* wrap symmetric wrapping key in server's public key. */ switch (exchKeyType) { - case kt_rsa: - asymWrapMechanism = CKM_RSA_PKCS; - rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, - unwrappedWrappingKey, &wrappedKey); - break; + case kt_rsa: + asymWrapMechanism = CKM_RSA_PKCS; + rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, + unwrappedWrappingKey, &wrappedKey); + break; #ifndef NSS_DISABLE_ECC - case kt_ecdh: - /* - * We generate an ephemeral EC key pair. Perform an ECDH - * computation involving this ephemeral EC public key and - * the SSL server's (long-term) EC private key. The resulting - * shared secret is treated in the same way as Fortezza's Ks, - * i.e., it is used to wrap the wrapping key. To facilitate - * unwrapping in ssl_UnwrapWrappingKey, we also store all - * relevant info about the ephemeral EC public key in - * wswk.wrappedSymmetricWrappingkey and lay it out as - * described in the ECCWrappedKeyInfo structure. - */ - PORT_Assert(svrPubKey->keyType == ecKey); - if (svrPubKey->keyType != ecKey) { - /* something is wrong in sslsecur.c if this isn't an ecKey */ - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - rv = SECFailure; - goto ec_cleanup; - } + case kt_ecdh: + /* + * We generate an ephemeral EC key pair. Perform an ECDH + * computation involving this ephemeral EC public key and + * the SSL server's (long-term) EC private key. The resulting + * shared secret is treated in the same way as Fortezza's Ks, + * i.e., it is used to wrap the wrapping key. To facilitate + * unwrapping in ssl_UnwrapWrappingKey, we also store all + * relevant info about the ephemeral EC public key in + * wswk.wrappedSymmetricWrappingkey and lay it out as + * described in the ECCWrappedKeyInfo structure. + */ + PORT_Assert(svrPubKey->keyType == ecKey); + if (svrPubKey->keyType != ecKey) { + /* something is wrong in sslsecur.c if this isn't an ecKey */ + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + rv = SECFailure; + goto ec_cleanup; + } - privWrapKey = SECKEY_CreateECPrivateKey( - &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); - if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { - rv = SECFailure; - goto ec_cleanup; - } - - /* Set the key size in bits */ - if (pubWrapKey->u.ec.size == 0) { - pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey); - } + privWrapKey = SECKEY_CreateECPrivateKey( + &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); + if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { + rv = SECFailure; + goto ec_cleanup; + } - PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + - pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN); - if (pubWrapKey->u.ec.DEREncodedParams.len + - pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) { - PORT_SetError(SEC_ERROR_INVALID_KEY); - rv = SECFailure; - goto ec_cleanup; - } + /* Set the key size in bits */ + if (pubWrapKey->u.ec.size == 0) { + pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey); + } - /* Derive Ks using ECDH */ - Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, - NULL, CKM_ECDH1_DERIVE, masterWrapMech, - CKA_DERIVE, 0, CKD_NULL, NULL, NULL); - if (Ks == NULL) { - rv = SECFailure; - goto ec_cleanup; - } + PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + + pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN); + if (pubWrapKey->u.ec.DEREncodedParams.len + + pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) { + PORT_SetError(SEC_ERROR_INVALID_KEY); + rv = SECFailure; + goto ec_cleanup; + } - ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey); - ecWrapped->size = pubWrapKey->u.ec.size; - ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; - PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, - pubWrapKey->u.ec.DEREncodedParams.len); + /* Derive Ks using ECDH */ + Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, + NULL, CKM_ECDH1_DERIVE, masterWrapMech, + CKA_DERIVE, 0, CKD_NULL, NULL, NULL); + if (Ks == NULL) { + rv = SECFailure; + goto ec_cleanup; + } - ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; - PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, - pubWrapKey->u.ec.publicValue.data, - pubWrapKey->u.ec.publicValue.len); + ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey); + ecWrapped->size = pubWrapKey->u.ec.size; + ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; + PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, + pubWrapKey->u.ec.DEREncodedParams.len); - wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - - (ecWrapped->encodedParamLen + ecWrapped->pubValueLen); - wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + - ecWrapped->pubValueLen; + ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; + PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, + pubWrapKey->u.ec.publicValue.data, + pubWrapKey->u.ec.publicValue.len); - /* wrap symmetricWrapping key with the local Ks */ - rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, - unwrappedWrappingKey, &wrappedKey); + wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - + (ecWrapped->encodedParamLen + ecWrapped->pubValueLen); + wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + + ecWrapped->pubValueLen; - if (rv != SECSuccess) { - goto ec_cleanup; - } + /* wrap symmetricWrapping key with the local Ks */ + rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, + unwrappedWrappingKey, &wrappedKey); - /* Write down the length of wrapped key in the buffer - * wswk.wrappedSymmetricWrappingkey at the appropriate offset - */ - ecWrapped->wrappedKeyLen = wrappedKey.len; + if (rv != SECSuccess) { + goto ec_cleanup; + } -ec_cleanup: - if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey); - if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey); - if (Ks) PK11_FreeSymKey(Ks); - asymWrapMechanism = masterWrapMech; - break; + /* Write down the length of wrapped key in the buffer + * wswk.wrappedSymmetricWrappingkey at the appropriate offset + */ + ecWrapped->wrappedKeyLen = wrappedKey.len; + + ec_cleanup: + if (privWrapKey) + SECKEY_DestroyPrivateKey(privWrapKey); + if (pubWrapKey) + SECKEY_DestroyPublicKey(pubWrapKey); + if (Ks) + PK11_FreeSymKey(Ks); + asymWrapMechanism = masterWrapMech; + break; #endif /* NSS_DISABLE_ECC */ - default: - rv = SECFailure; - break; + default: + rv = SECFailure; + break; } if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); - wswk.symWrapMechanism = masterWrapMech; - wswk.symWrapMechIndex = symWrapMechIndex; + wswk.symWrapMechanism = masterWrapMech; + wswk.symWrapMechIndex = symWrapMechIndex; wswk.asymWrapMechanism = asymWrapMechanism; - wswk.exchKeyType = exchKeyType; - wswk.wrappedSymKeyLen = wrappedKey.len; + wswk.exchKeyType = exchKeyType; + wswk.wrappedSymKeyLen = wrappedKey.len; /* put it on disk. */ - /* If the wrapping key for this KEA type has already been set, - * then abandon the value we just computed and + /* If the wrapping key for this KEA type has already been set, + * then abandon the value we just computed and * use the one we got from the disk. */ if (ssl_SetWrappingKey(&wswk)) { - /* somebody beat us to it. The original contents of our wswk - * has been replaced with the content on disk. Now, discard - * the key we just created and unwrap this new one. - */ - PK11_FreeSymKey(unwrappedWrappingKey); + /* somebody beat us to it. The original contents of our wswk + * has been replaced with the content on disk. Now, discard + * the key we just created and unwrap this new one. + */ + PK11_FreeSymKey(unwrappedWrappingKey); - unwrappedWrappingKey = - ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, + unwrappedWrappingKey = + ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, masterWrapMech, pwArg); } install: if (unwrappedWrappingKey) { - *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); + *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); } loser: @@ -6076,23 +6382,23 @@ hexEncode(char *out, const unsigned char *in, unsigned int length) unsigned int i; for (i = 0; i < length; i++) { - *(out++) = hextable[in[i] >> 4]; - *(out++) = hextable[in[i] & 15]; + *(out++) = hextable[in[i] >> 4]; + *(out++) = hextable[in[i] & 15]; } } /* Called from ssl3_SendClientKeyExchange(). */ /* Presently, this always uses PKCS11. There is no bypass for this. */ static SECStatus -sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) +sendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) { - PK11SymKey * pms = NULL; - SECStatus rv = SECFailure; - SECItem enc_pms = {siBuffer, NULL, 0}; - PRBool isTLS; + PK11SymKey *pms = NULL; + SECStatus rv = SECFailure; + SECItem enc_pms = { siBuffer, NULL, 0 }; + PRBool isTLS; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); /* Generate the pre-master secret ... */ ssl_GetSpecWriteLock(ss); @@ -6101,68 +6407,70 @@ sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); ssl_ReleaseSpecWriteLock(ss); if (pms == NULL) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } /* Get the wrapped (encrypted) pre-master secret, enc_pms */ - enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); - enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len); + enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); + enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len); if (enc_pms.data == NULL) { - goto loser; /* err set by PORT_Alloc */ + goto loser; /* err set by PORT_Alloc */ } /* wrap pre-master secret in server's public key. */ rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms); if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } if (ssl_keylog_iob) { - SECStatus extractRV = PK11_ExtractKeyValue(pms); - if (extractRV == SECSuccess) { - SECItem * keyData = PK11_GetKeyData(pms); - if (keyData && keyData->data && keyData->len) { + SECStatus extractRV = PK11_ExtractKeyValue(pms); + if (extractRV == SECSuccess) { + SECItem *keyData = PK11_GetKeyData(pms); + if (keyData && keyData->data && keyData->len) { #ifdef TRACE - if (ssl_trace >= 100) { - ssl_PrintBuf(ss, "Pre-Master Secret", - keyData->data, keyData->len); - } + if (ssl_trace >= 100) { + ssl_PrintBuf(ss, "Pre-Master Secret", + keyData->data, keyData->len); + } #endif - if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { - /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ + if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { + /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ - /* There could be multiple, concurrent writers to the - * keylog, so we have to do everything in a single call to - * fwrite. */ - char buf[4 + 8*2 + 1 + 48*2 + 1]; + /* There could be multiple, concurrent writers to the + * keylog, so we have to do everything in a single call to + * fwrite. */ + char buf[4 + 8 * 2 + 1 + 48 * 2 + 1]; - strcpy(buf, "RSA "); - hexEncode(buf + 4, enc_pms.data, 8); - buf[20] = ' '; - hexEncode(buf + 21, keyData->data, 48); - buf[sizeof(buf) - 1] = '\n'; + strcpy(buf, "RSA "); + hexEncode(buf + 4, enc_pms.data, 8); + buf[20] = ' '; + hexEncode(buf + 21, keyData->data, 48); + buf[sizeof(buf) - 1] = '\n'; - fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); - fflush(ssl_keylog_iob); - } - } - } + fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); + fflush(ssl_keylog_iob); + } + } + } } - rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, - isTLS ? enc_pms.len + 2 : enc_pms.len); + rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, + isTLS ? enc_pms.len + 2 + : enc_pms.len); if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } if (isTLS) { - rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); - } else { - rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); + rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); + } + else { + rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); } if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } rv = ssl3_InitPendingCipherSpec(ss, pms); @@ -6170,18 +6478,18 @@ sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) pms = NULL; if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } rv = SECSuccess; loser: if (enc_pms.data != NULL) { - PORT_Free(enc_pms.data); + PORT_Free(enc_pms.data); } if (pms != NULL) { - PK11_FreeSymKey(pms); + PK11_FreeSymKey(pms); } return rv; } @@ -6189,27 +6497,27 @@ loser: /* Called from ssl3_SendClientKeyExchange(). */ /* Presently, this always uses PKCS11. There is no bypass for this. */ static SECStatus -sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) +sendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) { - PK11SymKey * pms = NULL; - SECStatus rv = SECFailure; - PRBool isTLS; - CK_MECHANISM_TYPE target; + PK11SymKey *pms = NULL; + SECStatus rv = SECFailure; + PRBool isTLS; + CK_MECHANISM_TYPE target; - SECKEYDHParams dhParam; /* DH parameters */ - SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ - SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ + SECKEYDHParams dhParam; /* DH parameters */ + SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ + SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); /* Copy DH parameters from server key */ if (svrPubKey->keyType != dhKey) { - PORT_SetError(SEC_ERROR_BAD_KEY); - goto loser; + PORT_SetError(SEC_ERROR_BAD_KEY); + goto loser; } dhParam.prime.data = svrPubKey->u.dh.prime.data; dhParam.prime.len = svrPubKey->u.dh.prime.len; @@ -6219,43 +6527,45 @@ sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) /* Generate ephemeral DH keypair */ privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); if (!privKey || !pubKey) { - ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - goto loser; + ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); + rv = SECFailure; + goto loser; } PRINT_BUF(50, (ss, "DH public value:", - pubKey->u.dh.publicValue.data, - pubKey->u.dh.publicValue.len)); + pubKey->u.dh.publicValue.data, + pubKey->u.dh.publicValue.len)); - if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH; - else target = CKM_SSL3_MASTER_KEY_DERIVE_DH; + if (isTLS) + target = CKM_TLS_MASTER_KEY_DERIVE_DH; + else + target = CKM_SSL3_MASTER_KEY_DERIVE_DH; /* Determine the PMS */ pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL, - CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); + CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); if (pms == NULL) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } SECKEY_DestroyPrivateKey(privKey); privKey = NULL; - rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, - pubKey->u.dh.publicValue.len + 2); + rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, + pubKey->u.dh.publicValue.len + 2); if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } - rv = ssl3_AppendHandshakeVariable(ss, - pubKey->u.dh.publicValue.data, - pubKey->u.dh.publicValue.len, 2); + rv = ssl3_AppendHandshakeVariable(ss, + pubKey->u.dh.publicValue.data, + pubKey->u.dh.publicValue.len, 2); SECKEY_DestroyPublicKey(pubKey); pubKey = NULL; if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } rv = ssl3_InitPendingCipherSpec(ss, pms); @@ -6263,47 +6573,47 @@ sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) pms = NULL; if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } rv = SECSuccess; loser: - if(pms) PK11_FreeSymKey(pms); - if(privKey) SECKEY_DestroyPrivateKey(privKey); - if(pubKey) SECKEY_DestroyPublicKey(pubKey); + if (pms) + PK11_FreeSymKey(pms); + if (privKey) + SECKEY_DestroyPrivateKey(privKey); + if (pubKey) + SECKEY_DestroyPublicKey(pubKey); return rv; } - - - - /* Called from ssl3_HandleServerHelloDone(). */ static SECStatus ssl3_SendClientKeyExchange(sslSocket *ss) { - SECKEYPublicKey * serverKey = NULL; - SECStatus rv = SECFailure; - PRBool isTLS; + SECKEYPublicKey *serverKey = NULL; + SECStatus rv = SECFailure; + PRBool isTLS; SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->sec.peerKey == NULL) { - serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); - if (serverKey == NULL) { - ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; - } - } else { - serverKey = ss->sec.peerKey; - ss->sec.peerKey = NULL; /* we're done with it now */ + serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); + if (serverKey == NULL) { + ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); + return SECFailure; + } + } + else { + serverKey = ss->sec.peerKey; + ss->sec.peerKey = NULL; /* we're done with it now */ } isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); @@ -6312,73 +6622,73 @@ ssl3_SendClientKeyExchange(sslSocket *ss) unsigned int keyLen = SECKEY_PublicKeyStrengthInBits(serverKey); if (keyLen > ss->ssl3.hs.kea_def->key_size_limit) { - if (isTLS) - (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); - else - (void)ssl3_HandshakeFailure(ss); - PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); - goto loser; - } + if (isTLS) + (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); + else + (void)ssl3_HandshakeFailure(ss); + PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); + goto loser; + } } - ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); switch (ss->ssl3.hs.kea_def->exchKeyType) { - case kt_rsa: - rv = sendRSAClientKeyExchange(ss, serverKey); - break; + case kt_rsa: + rv = sendRSAClientKeyExchange(ss, serverKey); + break; - case kt_dh: - rv = sendDHClientKeyExchange(ss, serverKey); - break; + case kt_dh: + rv = sendDHClientKeyExchange(ss, serverKey); + break; #ifndef NSS_DISABLE_ECC - case kt_ecdh: - rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); - break; + case kt_ecdh: + rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); + break; #endif /* NSS_DISABLE_ECC */ - default: - /* got an unknown or unsupported Key Exchange Algorithm. */ - SEND_ALERT - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - break; + default: + /* got an unknown or unsupported Key Exchange Algorithm. */ + SEND_ALERT + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); + break; } SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); loser: - if (serverKey) - SECKEY_DestroyPublicKey(serverKey); - return rv; /* err code already set. */ + if (serverKey) + SECKEY_DestroyPublicKey(serverKey); + return rv; /* err code already set. */ } /* Called from ssl3_HandleServerHelloDone(). */ SECStatus ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey) { - SECStatus rv = SECFailure; - PRBool isTLS; - PRBool isTLS12; - PRBool isTLS13; - SECItem buf = {siBuffer, NULL, 0}; - SSL3Hashes hashes; - KeyType keyType; - unsigned int len; + SECStatus rv = SECFailure; + PRBool isTLS; + PRBool isTLS12; + PRBool isTLS13; + SECItem buf = { siBuffer, NULL, 0 }; + SSL3Hashes hashes; + KeyType keyType; + unsigned int len; SSLSignatureAndHashAlg sigAndHash; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); ssl_GetSpecReadLock(ss); if (ss->ssl3.hs.hashType == handshake_hash_single && - ss->ssl3.hs.backupHash) { + ss->ssl3.hs.backupHash) { PORT_Assert(!ss->ssl3.hs.backupHash); PORT_Assert(!isTLS13); /* TODO(ekr@rtfm.com): The backup hash here contains a SHA-1 hash @@ -6394,16 +6704,19 @@ ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey) if (isTLS13) { /* rv is already set to SECFailure */ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - } else { + } + else { rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); } - } else { + } + else { ssl3CipherSpec *spec; if (isTLS13) { /* In TLS 1.3, we are already encrypted. */ spec = ss->ssl3.cwSpec; - } else { + } + else { spec = ss->ssl3.pwSpec; } @@ -6411,13 +6724,13 @@ ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey) } ssl_ReleaseSpecReadLock(ss); if (rv != SECSuccess) { - goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ + goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ } if (isTLS13) { rv = tls13_AddContextToHashes(ss, &hashes, tls13_GetHash(ss), PR_TRUE); if (rv != SECSuccess) { - goto done; /* err code was set by tls13_AddContextToHashes */ + goto done; /* err code was set by tls13_AddContextToHashes */ } } @@ -6428,50 +6741,50 @@ ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey) rv = ssl3_SignHashes(&hashes, privKey, &buf, isTLS); if (rv == SECSuccess && !ss->sec.isServer) { /* Remember the info about the slot that did the signing. - ** Later, when doing an SSL restart handshake, verify this. - ** These calls are mere accessors, and can't fail. - */ + ** Later, when doing an SSL restart handshake, verify this. + ** These calls are mere accessors, and can't fail. + */ PK11SlotInfo *slot; sslSessionID *sid = ss->sec.ci.sid; slot = PK11_GetSlotFromPrivateKey(privKey); - sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); - sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); - sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); - sid->u.ssl3.clAuthValid = PR_TRUE; + sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); + sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); + sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); + sid->u.ssl3.clAuthValid = PR_TRUE; PK11_FreeSlot(slot); } if (rv != SECSuccess) { - goto done; /* err code was set by ssl3_SignHashes */ + goto done; /* err code was set by ssl3_SignHashes */ } len = buf.len + 2 + (isTLS12 ? 2 : 0); rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len); if (rv != SECSuccess) { - goto done; /* error code set by AppendHandshake */ + goto done; /* error code set by AppendHandshake */ } if (isTLS12) { - rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, + rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, &sigAndHash.sigAlg); - if (rv != SECSuccess) { - goto done; - } + if (rv != SECSuccess) { + goto done; + } sigAndHash.hashAlg = hashes.hashAlg; - rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); - if (rv != SECSuccess) { - goto done; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); + if (rv != SECSuccess) { + goto done; /* err set by AppendHandshake. */ + } } rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2); if (rv != SECSuccess) { - goto done; /* error code set by AppendHandshake */ + goto done; /* error code set by AppendHandshake */ } done: if (buf.data) - PORT_Free(buf.data); + PORT_Free(buf.data); return rv; } @@ -6482,89 +6795,89 @@ done: static SECStatus ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - sslSessionID *sid = ss->sec.ci.sid; - PRInt32 temp; /* allow for consume number failure */ - PRBool suite_found = PR_FALSE; - int i; - int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; - SECStatus rv; - SECItem sidBytes = {siBuffer, NULL, 0}; - PRBool sid_match; - PRBool isTLS = PR_FALSE; - SSL3AlertDescription desc = illegal_parameter; + sslSessionID *sid = ss->sec.ci.sid; + PRInt32 temp; /* allow for consume number failure */ + PRBool suite_found = PR_FALSE; + int i; + int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; + SECStatus rv; + SECItem sidBytes = { siBuffer, NULL, 0 }; + PRBool sid_match; + PRBool isTLS = PR_FALSE; + SSL3AlertDescription desc = illegal_parameter; SSL3ProtocolVersion version; SSL3ProtocolVersion downgradeCheckVersion; SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake", - SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->ssl3.initialized ); + SSL_GETPID(), ss->fd)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.initialized); if (ss->ssl3.hs.ws != wait_server_hello) { errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; - desc = unexpected_message; - goto alert_loser; + desc = unexpected_message; + goto alert_loser; } /* clean up anything left from previous handshake. */ if (ss->ssl3.clientCertChain != NULL) { - CERT_DestroyCertificateList(ss->ssl3.clientCertChain); - ss->ssl3.clientCertChain = NULL; + CERT_DestroyCertificateList(ss->ssl3.clientCertChain); + ss->ssl3.clientCertChain = NULL; } if (ss->ssl3.clientCertificate != NULL) { - CERT_DestroyCertificate(ss->ssl3.clientCertificate); - ss->ssl3.clientCertificate = NULL; + CERT_DestroyCertificate(ss->ssl3.clientCertificate); + ss->ssl3.clientCertificate = NULL; } if (ss->ssl3.clientPrivateKey != NULL) { - SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); - ss->ssl3.clientPrivateKey = NULL; + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + ss->ssl3.clientPrivateKey = NULL; } temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); if (temp < 0) { - goto loser; /* alert has been sent */ + goto loser; /* alert has been sent */ } version = (SSL3ProtocolVersion)temp; if (IS_DTLS(ss)) { - /* RFC 4347 required that you verify that the server versions - * match (Section 4.2.1) in the HelloVerifyRequest and the - * ServerHello. - * - * RFC 6347 suggests (SHOULD) that servers always use 1.0 - * in HelloVerifyRequest and allows the versions not to match, - * especially when 1.2 is being negotiated. - * - * Therefore we do not check for matching here. - */ - version = dtls_DTLSVersionToTLSVersion(version); - if (version == 0) { /* Insane version number */ + /* RFC 4347 required that you verify that the server versions + * match (Section 4.2.1) in the HelloVerifyRequest and the + * ServerHello. + * + * RFC 6347 suggests (SHOULD) that servers always use 1.0 + * in HelloVerifyRequest and allows the versions not to match, + * especially when 1.2 is being negotiated. + * + * Therefore we do not check for matching here. + */ + version = dtls_DTLSVersionToTLSVersion(version); + if (version == 0) { /* Insane version number */ goto alert_loser; - } + } } rv = ssl3_NegotiateVersion(ss, version, PR_FALSE); if (rv != SECSuccess) { - desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version - : handshake_failure; - errCode = SSL_ERROR_UNSUPPORTED_VERSION; - goto alert_loser; + desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version + : handshake_failure; + errCode = SSL_ERROR_UNSUPPORTED_VERSION; + goto alert_loser; } ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); rv = ssl3_InitHandshakeHashes(ss); if (rv != SECSuccess) { - desc = internal_error; - errCode = PORT_GetError(); - goto alert_loser; + desc = internal_error; + errCode = PORT_GetError(); + goto alert_loser; } rv = ssl3_ConsumeHandshake( - ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); + ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); if (rv != SECSuccess) { - goto loser; /* alert has been sent */ + goto loser; /* alert has been sent */ } /* Check the ServerHello.random per @@ -6576,8 +6889,8 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * indicates TLS 1.1 or below. If a match is found the client MUST * abort the handshake with a fatal "illegal_parameter" alert. */ - downgradeCheckVersion = ss->ssl3.downgradeCheckVersion ? - ss->ssl3.downgradeCheckVersion : ss->vrange.max; + downgradeCheckVersion = ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion + : ss->vrange.max; if (downgradeCheckVersion >= SSL_LIBRARY_VERSION_TLS_1_2 && downgradeCheckVersion > ss->version) { @@ -6587,64 +6900,64 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) !PORT_Memcmp(ss->ssl3.hs.server_random.rand, tls12_downgrade_random, sizeof(tls12_downgrade_random))) { - desc = illegal_parameter; - errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; - goto alert_loser; - } + desc = illegal_parameter; + errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; + goto alert_loser; + } } if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); if (rv != SECSuccess) { - goto loser; /* alert has been sent */ + goto loser; /* alert has been sent */ } if (sidBytes.len > SSL3_SESSIONID_BYTES) { if (isTLS) desc = decode_error; - goto alert_loser; /* malformed. */ + goto alert_loser; /* malformed. */ } } /* find selected cipher suite in our list. */ temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); if (temp < 0) { - goto loser; /* alert has been sent */ + goto loser; /* alert has been sent */ } ssl3_config_match_init(ss); for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; - if (temp == suite->cipher_suite) { - SSLVersionRange vrange = {ss->version, ss->version}; - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { - /* config_match already checks whether the cipher suite is - * acceptable for the version, but the check is repeated here - * in order to give a more precise error code. */ - if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) { - desc = handshake_failure; - errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; - goto alert_loser; - } + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; + if (temp == suite->cipher_suite) { + SSLVersionRange vrange = { ss->version, ss->version }; + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { + /* config_match already checks whether the cipher suite is + * acceptable for the version, but the check is repeated here + * in order to give a more precise error code. */ + if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) { + desc = handshake_failure; + errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; + goto alert_loser; + } - break; /* failure */ - } - - suite_found = PR_TRUE; - break; /* success */ - } + break; /* failure */ + } + + suite_found = PR_TRUE; + break; /* success */ + } } if (!suite_found) { - desc = handshake_failure; - errCode = SSL_ERROR_NO_CYPHER_OVERLAP; - goto alert_loser; + desc = handshake_failure; + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; + goto alert_loser; } ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp; - ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); + ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; PORT_Assert(ss->ssl3.hs.suite_def); if (!ss->ssl3.hs.suite_def) { - errCode = SEC_ERROR_LIBRARY_FAILURE; - PORT_SetError(errCode); - goto loser; /* we don't send alerts for our screw-ups. */ + errCode = SEC_ERROR_LIBRARY_FAILURE; + PORT_SetError(errCode); + goto loser; /* we don't send alerts for our screw-ups. */ } ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; @@ -6653,25 +6966,26 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) /* find selected compression method in our list. */ temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); if (temp < 0) { - goto loser; /* alert has been sent */ + goto loser; /* alert has been sent */ } suite_found = PR_FALSE; for (i = 0; i < compressionMethodsCount; i++) { if (temp == compressions[i]) { if (!compressionEnabled(ss, compressions[i])) { - break; /* failure */ + break; /* failure */ } suite_found = PR_TRUE; - break; /* success */ + break; /* success */ } } if (!suite_found) { - desc = handshake_failure; + desc = handshake_failure; errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; goto alert_loser; } ss->ssl3.hs.compression = (SSLCompressionMethod)temp; - } else { + } + else { ss->ssl3.hs.compression = ssl_compression_null; } @@ -6685,36 +6999,38 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * extension in SSL 3.0. */ if (length != 0) { - SECItem extensions; - rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); - if (rv != SECSuccess || length != 0) { - if (isTLS) - goto alert_loser; - } else { - rv = ssl3_HandleHelloExtensions(ss, &extensions.data, + SECItem extensions; + rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); + if (rv != SECSuccess || length != 0) { + if (isTLS) + goto alert_loser; + } + else { + rv = ssl3_HandleHelloExtensions(ss, &extensions.data, &extensions.len, server_hello); - if (rv != SECSuccess) - goto alert_loser; - } + if (rv != SECSuccess) + goto alert_loser; + } } - if ((ss->opt.requireSafeNegotiation || + if ((ss->opt.requireSafeNegotiation || (ss->firstHsDone && (ss->peerRequestedProtection || - ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) && - !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { - desc = handshake_failure; - errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED - : SSL_ERROR_UNSAFE_NEGOTIATION; - goto alert_loser; + ss->opt.enableRenegotiation == + SSL_RENEGOTIATE_REQUIRES_XTN))) && + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { + desc = handshake_failure; + errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED + : SSL_ERROR_UNSAFE_NEGOTIATION; + goto alert_loser; } /* Any errors after this point are not "malformed" errors. */ - desc = handshake_failure; + desc = handshake_failure; /* we need to call ssl3_SetupPendingCipherSpec here so we can check the * key exchange algorithm. */ rv = ssl3_SetupPendingCipherSpec(ss); if (rv != SECSuccess) { - goto alert_loser; /* error code is set. */ + goto alert_loser; /* error code is set. */ } /* We may or may not have sent a session id, we may get one back or @@ -6723,155 +7039,160 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * Don't consider failure to find a matching SID an error. */ sid_match = (PRBool)(sidBytes.len > 0 && - sidBytes.len == sid->u.ssl3.sessionIDLength && - !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len)); + sidBytes.len == + sid->u.ssl3.sessionIDLength && + !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len)); if (sid_match && - sid->version == ss->version && - sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do { - ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; + sid->version == ss->version && + sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) + do { + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; - SECItem wrappedMS; /* wrapped master secret. */ + SECItem wrappedMS; /* wrapped master secret. */ - /* [draft-ietf-tls-session-hash-06; Section 5.3] - * - * o If the original session did not use the "extended_master_secret" - * extension but the new ServerHello contains the extension, the - * client MUST abort the handshake. - */ - if (!sid->u.ssl3.keys.extendedMasterSecretUsed && - ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { - errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET; - goto alert_loser; - } + /* [draft-ietf-tls-session-hash-06; Section 5.3] + * + * o If the original session did not use the "extended_master_secret" + * extension but the new ServerHello contains the extension, the + * client MUST abort the handshake. + */ + if (!sid->u.ssl3.keys.extendedMasterSecretUsed && + ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { + errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET; + goto alert_loser; + } - /* - * o If the original session used an extended master secret but the new - * ServerHello does not contain the "extended_master_secret" - * extension, the client SHOULD abort the handshake. - * - * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not - * used at all (bug 1176526). - */ - if (sid->u.ssl3.keys.extendedMasterSecretUsed && - !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { - errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; - goto alert_loser; - } + /* + * o If the original session used an extended master secret but the new + * ServerHello does not contain the "extended_master_secret" + * extension, the client SHOULD abort the handshake. + * + * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not + * used at all (bug 1176526). + */ + if (sid->u.ssl3.keys.extendedMasterSecretUsed && + !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { + errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; + goto alert_loser; + } - ss->sec.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; + ss->sec.authAlgorithm = sid->authAlgorithm; + ss->sec.authKeyBits = sid->authKeyBits; + ss->sec.keaType = sid->keaType; + ss->sec.keaKeyBits = sid->keaKeyBits; - /* 3 cases here: - * a) key is wrapped (implies using PKCS11) - * b) key is unwrapped, but we're still using PKCS11 - * c) key is unwrapped, and we're bypassing PKCS11. - */ - if (sid->u.ssl3.keys.msIsWrapped) { - PK11SlotInfo *slot; - PK11SymKey * wrapKey; /* wrapping key */ - CK_FLAGS keyFlags = 0; + /* 3 cases here: + * a) key is wrapped (implies using PKCS11) + * b) key is unwrapped, but we're still using PKCS11 + * c) key is unwrapped, and we're bypassing PKCS11. + */ + if (sid->u.ssl3.keys.msIsWrapped) { + PK11SlotInfo *slot; + PK11SymKey *wrapKey; /* wrapping key */ + CK_FLAGS keyFlags = 0; #ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - /* we cannot restart a non-bypass session in a - ** bypass socket. - */ - break; - } + if (ss->opt.bypassPKCS11) { + /* we cannot restart a non-bypass session in a + ** bypass socket. + */ + break; + } #endif - /* unwrap master secret with PKCS11 */ - slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, - sid->u.ssl3.masterSlotID); - if (slot == NULL) { - break; /* not considered an error. */ - } - if (!PK11_IsPresent(slot)) { - PK11_FreeSlot(slot); - break; /* not considered an error. */ - } - wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, - sid->u.ssl3.masterWrapMech, - sid->u.ssl3.masterWrapSeries, - ss->pkcs11PinArg); - PK11_FreeSlot(slot); - if (wrapKey == NULL) { - break; /* not considered an error. */ - } + /* unwrap master secret with PKCS11 */ + slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, + sid->u.ssl3.masterSlotID); + if (slot == NULL) { + break; /* not considered an error. */ + } + if (!PK11_IsPresent(slot)) { + PK11_FreeSlot(slot); + break; /* not considered an error. */ + } + wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, + sid->u.ssl3.masterWrapMech, + sid->u.ssl3.masterWrapSeries, + ss->pkcs11PinArg); + PK11_FreeSlot(slot); + if (wrapKey == NULL) { + break; /* not considered an error. */ + } - if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ - keyFlags = CKF_SIGN | CKF_VERIFY; - } + if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ + keyFlags = + CKF_SIGN | CKF_VERIFY; + } - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - pwSpec->master_secret = - PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, - NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, - CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); - errCode = PORT_GetError(); - PK11_FreeSymKey(wrapKey); - if (pwSpec->master_secret == NULL) { - break; /* errorCode set just after call to UnwrapSymKey. */ - } + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + pwSpec->master_secret = + PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, + NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, + CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); + errCode = PORT_GetError(); + PK11_FreeSymKey(wrapKey); + if (pwSpec->master_secret == NULL) { + break; /* errorCode set just after call to UnwrapSymKey. */ + } #ifndef NO_PKCS11_BYPASS - } else if (ss->opt.bypassPKCS11) { - /* MS is not wrapped */ - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = wrappedMS.len; + } + else if (ss->opt.bypassPKCS11) { + /* MS is not wrapped */ + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); + pwSpec->msItem.data = pwSpec->raw_master_secret; + pwSpec->msItem.len = wrappedMS.len; #endif - } else { - /* We CAN restart a bypass session in a non-bypass socket. */ - /* need to import the raw master secret to session object */ - PK11SlotInfo *slot = PK11_GetInternalSlot(); - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - pwSpec->master_secret = - PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, - PK11_OriginUnwrap, CKA_ENCRYPT, - &wrappedMS, NULL); - PK11_FreeSlot(slot); - if (pwSpec->master_secret == NULL) { - break; - } - } + } + else { + /* We CAN restart a bypass session in a non-bypass socket. */ + /* need to import the raw master secret to session object */ + PK11SlotInfo *slot = PK11_GetInternalSlot(); + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + pwSpec->master_secret = + PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, + PK11_OriginUnwrap, CKA_ENCRYPT, + &wrappedMS, NULL); + PK11_FreeSlot(slot); + if (pwSpec->master_secret == NULL) { + break; + } + } - /* Got a Match */ - SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits ); + /* Got a Match */ + SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits); - /* If we sent a session ticket, then this is a stateless resume. */ - if (ss->xtnData.sentSessionTicketInClientHello) - SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes ); + /* If we sent a session ticket, then this is a stateless resume. */ + if (ss->xtnData.sentSessionTicketInClientHello) + SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes); - if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) - ss->ssl3.hs.ws = wait_new_session_ticket; - else - ss->ssl3.hs.ws = wait_change_cipher; + if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) + ss->ssl3.hs.ws = wait_new_session_ticket; + else + ss->ssl3.hs.ws = wait_change_cipher; - ss->ssl3.hs.isResuming = PR_TRUE; + ss->ssl3.hs.isResuming = PR_TRUE; - /* copy the peer cert from the SID */ - if (sid->peerCert != NULL) { - ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); - } + /* copy the peer cert from the SID */ + if (sid->peerCert != NULL) { + ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); + } - /* NULL value for PMS because we are reusing the old MS */ - rv = ssl3_InitPendingCipherSpec(ss, NULL); - if (rv != SECSuccess) { - goto alert_loser; /* err code was set */ - } - return SECSuccess; - } while (0); + /* NULL value for PMS because we are reusing the old MS */ + rv = ssl3_InitPendingCipherSpec(ss, NULL); + if (rv != SECSuccess) { + goto alert_loser; /* err code was set */ + } + return SECSuccess; + } while (0); if (sid_match) - SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok ); + SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok); else - SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses ); + SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses); /* throw the old one away */ sid->u.ssl3.keys.resumable = PR_FALSE; @@ -6882,7 +7203,7 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) /* get a new sid */ ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE); if (sid == NULL) { - goto alert_loser; /* memory error is set. */ + goto alert_loser; /* memory error is set. */ } sid->version = ss->version; @@ -6890,7 +7211,7 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len); sid->u.ssl3.keys.extendedMasterSecretUsed = - ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); + ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); /* Copy Signed Certificate Timestamps, if any. */ if (ss->xtnData.signedCertTimestamps.data) { @@ -6909,11 +7230,13 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) if (rv != SECSuccess) goto alert_loser; TLS13_SET_HS_STATE(ss, wait_encrypted_extensions); - } else if (ss->ssl3.hs.kea_def->signKeyType != ssl_sign_null) { + } + else if (ss->ssl3.hs.kea_def->signKeyType != ssl_sign_null) { /* All current cipher suites other than those with ssl_sign_null (i.e., * (EC)DH_anon_* suites) require a certificate, so use that signal. */ ss->ssl3.hs.ws = wait_server_cert; - } else { + } + else { /* All the remaining cipher suites must be (EC)DH_anon_* and so * must be ephemeral. Note, if we ever add PSK this might * change. */ @@ -6933,7 +7256,6 @@ loser: return SECFailure; } - /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a * complete ssl3 ServerKeyExchange message. * Caller must hold Handshake and RecvBuf locks. @@ -6941,22 +7263,22 @@ loser: static SECStatus ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - PLArenaPool * arena = NULL; - SECKEYPublicKey *peerKey = NULL; - PRBool isTLS, isTLS12; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; - SSL3AlertDescription desc = illegal_parameter; - SSL3Hashes hashes; - SECItem signature = {siBuffer, NULL, 0}; + PLArenaPool *arena = NULL; + SECKEYPublicKey *peerKey = NULL; + PRBool isTLS, isTLS12; + SECStatus rv; + int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; + SSL3AlertDescription desc = illegal_parameter; + SSL3Hashes hashes; + SECItem signature = { siBuffer, NULL, 0 }; SSLSignatureAndHashAlg sigAndHash; sigAndHash.hashAlg = ssl_hash_none; SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake", - SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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_key) { errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; @@ -6969,228 +7291,228 @@ ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) switch (ss->ssl3.hs.kea_def->exchKeyType) { - case kt_rsa: { - SECItem modulus = {siBuffer, NULL, 0}; - SECItem exponent = {siBuffer, NULL, 0}; + case kt_rsa: { + SECItem modulus = { siBuffer, NULL, 0 }; + SECItem exponent = { siBuffer, NULL, 0 }; - rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - /* This exchange method is only used by export cipher suites. - * Those are broken and so this code will eventually be removed. */ - if (SECKEY_BigIntegerBitLength(&modulus) < 512) { - desc = isTLS ? insufficient_security : illegal_parameter; - goto alert_loser; + rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } + /* This exchange method is only used by export cipher suites. + * Those are broken and so this code will eventually be removed. */ + if (SECKEY_BigIntegerBitLength(&modulus) < 512) { + desc = isTLS ? insufficient_security : illegal_parameter; + goto alert_loser; + } + rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } + if (isTLS12) { + rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, + &sigAndHash); + if (rv != SECSuccess) { + goto loser; /* malformed or unsupported. */ + } + rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, + &sigAndHash, ss->sec.peerCert); + if (rv != SECSuccess) { + goto loser; + } + } + rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } + if (length != 0) { + if (isTLS) + desc = + decode_error; + goto alert_loser; /* malformed. */ + } + + /* failures after this point are not malformed handshakes. */ + /* TLS: send decrypt_error if signature failed. */ + desc = isTLS ? decrypt_error : handshake_failure; + + /* + * check to make sure the hash is signed by right guy + */ + rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent, + &ss->ssl3.hs.client_random, + &ss->ssl3.hs.server_random, + &hashes, ss->opt.bypassPKCS11); + if (rv != SECSuccess) { + errCode = + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + goto alert_loser; + } + rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, + isTLS, ss->pkcs11PinArg); + if (rv != SECSuccess) { + errCode = + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + goto alert_loser; + } + + /* + * we really need to build a new key here because we can no longer + * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate + * pkcs11 slots and ID's. + */ + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (arena == NULL) { + goto no_memory; + } + + peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); + if (peerKey == NULL) { + goto no_memory; + } + + peerKey->arena = arena; + peerKey->keyType = rsaKey; + peerKey->pkcs11Slot = NULL; + peerKey->pkcs11ID = CK_INVALID_HANDLE; + if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || + SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent)) { + goto no_memory; + } + ss->sec.peerKey = peerKey; + ss->ssl3.hs.ws = wait_cert_request; + return SECSuccess; } - rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - if (isTLS12) { - rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, - &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* malformed or unsupported. */ - } - rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, - &sigAndHash, ss->sec.peerCert); - if (rv != SECSuccess) { - goto loser; - } - } - rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - if (length != 0) { - if (isTLS) - desc = decode_error; - goto alert_loser; /* malformed. */ - } - /* failures after this point are not malformed handshakes. */ - /* TLS: send decrypt_error if signature failed. */ - desc = isTLS ? decrypt_error : handshake_failure; + case kt_dh: { + SECItem dh_p = { siBuffer, NULL, 0 }; + SECItem dh_g = { siBuffer, NULL, 0 }; + SECItem dh_Ys = { siBuffer, NULL, 0 }; + unsigned dh_p_bits; + unsigned dh_g_bits; + unsigned dh_Ys_bits; + PRInt32 minDH; - /* - * check to make sure the hash is signed by right guy - */ - rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent, - &ss->ssl3.hs.client_random, - &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); - if (rv != SECSuccess) { - errCode = - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto alert_loser; - } - rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, - isTLS, ss->pkcs11PinArg); - if (rv != SECSuccess) { - errCode = - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto alert_loser; - } + rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } - /* - * we really need to build a new key here because we can no longer - * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate - * pkcs11 slots and ID's. - */ - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - goto no_memory; - } + rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH); + if (rv != SECSuccess) { + minDH = SSL_DH_MIN_P_BITS; + } + dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p); + if (dh_p_bits < minDH) { + errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; + goto alert_loser; + } + rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } + /* Abort if dh_g is 0, 1, or obviously too big. */ + dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g); + if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) + goto alert_loser; + rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } + dh_Ys_bits = SECKEY_BigIntegerBitLength(&dh_Ys); + if (dh_Ys_bits > dh_p_bits || dh_Ys_bits <= 1) + goto alert_loser; + if (isTLS12) { + rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, + &sigAndHash); + if (rv != SECSuccess) { + goto loser; /* malformed or unsupported. */ + } + rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, + &sigAndHash, ss->sec.peerCert); + if (rv != SECSuccess) { + goto loser; + } + } + rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } + if (length != 0) { + if (isTLS) + desc = + decode_error; + goto alert_loser; /* malformed. */ + } - peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); - if (peerKey == NULL) { - goto no_memory; - } + PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len)); + PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len)); + PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len)); - peerKey->arena = arena; - peerKey->keyType = rsaKey; - peerKey->pkcs11Slot = NULL; - peerKey->pkcs11ID = CK_INVALID_HANDLE; - if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || - SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent)) - { - goto no_memory; + /* failures after this point are not malformed handshakes. */ + /* TLS: send decrypt_error if signature failed. */ + desc = isTLS ? decrypt_error : handshake_failure; + + /* + * check to make sure the hash is signed by right guy + */ + rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys, + &ss->ssl3.hs.client_random, + &ss->ssl3.hs.server_random, + &hashes, ss->opt.bypassPKCS11); + if (rv != SECSuccess) { + errCode = + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + goto alert_loser; + } + rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, + isTLS, ss->pkcs11PinArg); + if (rv != SECSuccess) { + errCode = + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + goto alert_loser; + } + + /* + * we really need to build a new key here because we can no longer + * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate + * pkcs11 slots and ID's. + */ + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (arena == NULL) { + goto no_memory; + } + + peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); + if (peerKey == NULL) { + goto no_memory; + } + + peerKey->arena = arena; + peerKey->keyType = dhKey; + peerKey->pkcs11Slot = NULL; + peerKey->pkcs11ID = CK_INVALID_HANDLE; + + if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) || + SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) || + SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) { + goto no_memory; + } + ss->sec.peerKey = peerKey; + ss->ssl3.hs.ws = wait_cert_request; + return SECSuccess; } - ss->sec.peerKey = peerKey; - ss->ssl3.hs.ws = wait_cert_request; - return SECSuccess; - } - - case kt_dh: { - SECItem dh_p = {siBuffer, NULL, 0}; - SECItem dh_g = {siBuffer, NULL, 0}; - SECItem dh_Ys = {siBuffer, NULL, 0}; - unsigned dh_p_bits; - unsigned dh_g_bits; - unsigned dh_Ys_bits; - PRInt32 minDH; - - rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - - rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH); - if (rv != SECSuccess) { - minDH = SSL_DH_MIN_P_BITS; - } - dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p); - if (dh_p_bits < minDH) { - errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; - goto alert_loser; - } - rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - /* Abort if dh_g is 0, 1, or obviously too big. */ - dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g); - if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) - goto alert_loser; - rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - dh_Ys_bits = SECKEY_BigIntegerBitLength(&dh_Ys); - if (dh_Ys_bits > dh_p_bits || dh_Ys_bits <= 1) - goto alert_loser; - if (isTLS12) { - rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, - &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* malformed or unsupported. */ - } - rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, - &sigAndHash, ss->sec.peerCert); - if (rv != SECSuccess) { - goto loser; - } - } - rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - if (length != 0) { - if (isTLS) - desc = decode_error; - goto alert_loser; /* malformed. */ - } - - PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len)); - PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len)); - PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len)); - - /* failures after this point are not malformed handshakes. */ - /* TLS: send decrypt_error if signature failed. */ - desc = isTLS ? decrypt_error : handshake_failure; - - /* - * check to make sure the hash is signed by right guy - */ - rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys, - &ss->ssl3.hs.client_random, - &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); - if (rv != SECSuccess) { - errCode = - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto alert_loser; - } - rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, - isTLS, ss->pkcs11PinArg); - if (rv != SECSuccess) { - errCode = - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto alert_loser; - } - - /* - * we really need to build a new key here because we can no longer - * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate - * pkcs11 slots and ID's. - */ - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - goto no_memory; - } - - peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); - if (peerKey == NULL) { - goto no_memory; - } - - peerKey->arena = arena; - peerKey->keyType = dhKey; - peerKey->pkcs11Slot = NULL; - peerKey->pkcs11ID = CK_INVALID_HANDLE; - - if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) || - SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) || - SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) - { - goto no_memory; - } - ss->sec.peerKey = peerKey; - ss->ssl3.hs.ws = wait_cert_request; - return SECSuccess; - } #ifndef NSS_DISABLE_ECC - case kt_ecdh: - rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); - return rv; + case kt_ecdh: + rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); + return rv; #endif /* NSS_DISABLE_ECC */ - default: - desc = handshake_failure; - errCode = SEC_ERROR_UNSUPPORTED_KEYALG; - break; /* goto alert_loser; */ + default: + desc = handshake_failure; + errCode = SEC_ERROR_UNSUPPORTED_KEYALG; + break; /* goto alert_loser; */ } alert_loser: @@ -7199,10 +7521,10 @@ loser: if (arena) { PORT_FreeArena(arena, PR_FALSE); } - PORT_SetError( errCode ); + PORT_SetError(errCode); return SECFailure; -no_memory: /* no-memory error has already been set. */ +no_memory: /* no-memory error has already been set. */ if (arena) { PORT_FreeArena(arena, PR_FALSE); } @@ -7216,21 +7538,21 @@ no_memory: /* no-memory error has already been set. */ */ static SECStatus ssl3_ExtractClientKeyInfo(sslSocket *ss, - SSLSignType *sigAlg, - PRBool *preferSha1) + SSLSignType *sigAlg, + PRBool *preferSha1) { SECStatus rv = SECSuccess; SECKEYPublicKey *pubk; pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); if (pubk == NULL) { - rv = SECFailure; - goto done; + rv = SECFailure; + goto done; } rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg); if (rv != SECSuccess) { - goto done; + goto done; } /* If the key is a 1024-bit RSA or DSA key, assume conservatively that @@ -7240,14 +7562,15 @@ ssl3_ExtractClientKeyInfo(sslSocket *ss, * be SHA-1. */ if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { - *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; - } else { - *preferSha1 = PR_FALSE; + *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; + } + else { + *preferSha1 = PR_FALSE; } done: if (pubk) - SECKEY_DestroyPublicKey(pubk); + SECKEY_DestroyPublicKey(pubk); return rv; } @@ -7257,7 +7580,7 @@ done: * to determine whether to use SHA-1 or SHA-256. */ static void ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, - const SECItem *algorithms) + const SECItem *algorithms) { SECStatus rv; SSLSignType sigAlg; @@ -7270,8 +7593,8 @@ ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, #ifndef NO_PKCS11_BYPASS /* Backup handshake hash is not supported in PKCS #11 bypass mode. */ if (ss->opt.bypassPKCS11) { - PORT_Assert(!ss->ssl3.hs.backupHash); - return; + PORT_Assert(!ss->ssl3.hs.backupHash); + return; } #endif PORT_Assert(ss->ssl3.hs.backupHash); @@ -7279,36 +7602,37 @@ ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, /* Determine the key's signature algorithm and whether it prefers SHA-1. */ rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1); if (rv != SECSuccess) { - goto done; + goto done; } /* Determine the server's hash support for that signature algorithm. */ for (i = 0; i < algorithms->len; i += 2) { - if (algorithms->data[i+1] == sigAlg) { - if (algorithms->data[i] == ssl_hash_sha1) { - supportsSha1 = PR_TRUE; - } else if (algorithms->data[i] == ssl_hash_sha256) { - supportsSha256 = PR_TRUE; - } - } + if (algorithms->data[i + 1] == sigAlg) { + if (algorithms->data[i] == ssl_hash_sha1) { + supportsSha1 = PR_TRUE; + } + else if (algorithms->data[i] == ssl_hash_sha256) { + supportsSha256 = PR_TRUE; + } + } } /* If either the server does not support SHA-256 or the client key prefers * SHA-1, leave the backup hash. */ if (supportsSha1 && (preferSha1 || !supportsSha256)) { - needBackupHash = PR_TRUE; + needBackupHash = PR_TRUE; } done: if (!needBackupHash) { - PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); - ss->ssl3.hs.backupHash = NULL; + PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); + ss->ssl3.hs.backupHash = NULL; } } typedef struct dnameNode { struct dnameNode *next; - SECItem name; + SECItem name; } dnameNode; /* @@ -7329,7 +7653,7 @@ ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, remaining = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); if (remaining < 0) - return SECFailure; /* malformed, alert has been sent */ + return SECFailure; /* malformed, alert has been sent */ if ((PRUint32)remaining > *length) goto alert_loser; @@ -7346,7 +7670,7 @@ ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); if (len <= 0) - return SECFailure; /* malformed, alert has been sent */ + return SECFailure; /* malformed, alert has been sent */ remaining -= 2; if (remaining < len) @@ -7358,7 +7682,7 @@ ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, remaining -= len; nnames++; if (remaining <= 0) - break; /* success */ + break; /* success */ node->next = PORT_ArenaZNew(arena, dnameNode); node = node->next; @@ -7367,13 +7691,13 @@ ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, } ca_list->nnames = nnames; - ca_list->names = PORT_ArenaNewArray(arena, SECItem, nnames); + ca_list->names = PORT_ArenaNewArray(arena, SECItem, nnames); if (nnames > 0 && ca_list->names == NULL) goto no_mem; - for(i = 0, node = (dnameNode*)ca_list->head; - i < nnames; - i++, node = node->next) { + for (i = 0, node = (dnameNode *)ca_list->head; + i < nnames; + i++, node = node->next) { ca_list->names[i] = node->name; } @@ -7385,8 +7709,8 @@ no_mem: alert_loser: (void)SSL3_SendAlert(ss, alert_fatal, - ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? - illegal_parameter : decode_error); + ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter + : decode_error); PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST); return SECFailure; } @@ -7398,20 +7722,20 @@ alert_loser: static SECStatus ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - PLArenaPool * arena = NULL; - PRBool isTLS = PR_FALSE; - PRBool isTLS12 = PR_FALSE; - int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; - SECStatus rv; - SSL3AlertDescription desc = illegal_parameter; - SECItem cert_types = {siBuffer, NULL, 0}; - SECItem algorithms = {siBuffer, NULL, 0}; - CERTDistNames ca_list; + PLArenaPool *arena = NULL; + PRBool isTLS = PR_FALSE; + PRBool isTLS12 = PR_FALSE; + int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; + SECStatus rv; + SSL3AlertDescription desc = illegal_parameter; + SECItem cert_types = { siBuffer, NULL, 0 }; + SECItem algorithms = { siBuffer, NULL, 0 }; + CERTDistNames ca_list; SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake", - SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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_cert_request) { desc = unexpected_message; @@ -7427,30 +7751,30 @@ ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length); if (rv != SECSuccess) - goto loser; /* malformed, alert has been sent */ + goto loser; /* malformed, alert has been sent */ if (isTLS12) { - rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); - if (rv != SECSuccess) - goto loser; /* malformed, alert has been sent */ - /* An empty or odd-length value is invalid. - * SignatureAndHashAlgorithm - * supported_signature_algorithms<2..2^16-2>; - */ - if (algorithms.len == 0 || (algorithms.len & 1) != 0) - goto alert_loser; + rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); + if (rv != SECSuccess) + goto loser; /* malformed, alert has been sent */ + /* An empty or odd-length value is invalid. + * SignatureAndHashAlgorithm + * supported_signature_algorithms<2..2^16-2>; + */ + if (algorithms.len == 0 || (algorithms.len & 1) != 0) + goto alert_loser; } arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) - goto no_mem; + goto no_mem; rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, arena, &ca_list); if (rv != SECSuccess) - goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */ + goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */ if (length != 0) - goto alert_loser; /* malformed */ + goto alert_loser; /* malformed */ desc = no_certificate; @@ -7472,14 +7796,14 @@ no_mem: alert_loser: if (isTLS && desc == illegal_parameter) - desc = decode_error; + desc = decode_error; (void)SSL3_SendAlert(ss, alert_fatal, desc); loser: PORT_SetError(errCode); rv = SECFailure; done: if (arena != NULL) - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return rv; } @@ -7492,63 +7816,65 @@ ssl3_CompleteHandleCertificateRequest(sslSocket *ss, SECItem *algorithms, if (ss->getClientAuthData != NULL) { PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all); - /* XXX Should pass cert_types and algorithms in this call!! */ - rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg, - ss->fd, ca_list, - &ss->ssl3.clientCertificate, - &ss->ssl3.clientPrivateKey); - } else { - rv = SECFailure; /* force it to send a no_certificate alert */ + /* XXX Should pass cert_types and algorithms in this call!! */ + rv = (SECStatus) (*ss->getClientAuthData)(ss->getClientAuthDataArg, + ss->fd, ca_list, + &ss->ssl3.clientCertificate, + &ss->ssl3.clientPrivateKey); + } + else { + rv = SECFailure; /* force it to send a no_certificate alert */ } switch (rv) { - case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ - ssl3_SetAlwaysBlock(ss); - break; /* not an error */ + case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ + ssl3_SetAlwaysBlock(ss); + break; /* not an error */ - case SECSuccess: - /* check what the callback function returned */ - if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { - /* we are missing either the key or cert */ - if (ss->ssl3.clientCertificate) { - /* got a cert, but no key - free it */ + case SECSuccess: + /* check what the callback function returned */ + if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { + /* we are missing either the key or cert */ + if (ss->ssl3.clientCertificate) { + /* got a cert, but no key - free it */ + CERT_DestroyCertificate(ss->ssl3.clientCertificate); + ss->ssl3.clientCertificate = NULL; + } + if (ss->ssl3.clientPrivateKey) { + /* got a key, but no cert - free it */ + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + ss->ssl3.clientPrivateKey = NULL; + } + goto send_no_certificate; + } + /* Setting ssl3.clientCertChain non-NULL will cause + * ssl3_HandleServerHelloDone to call SendCertificate. + */ + ss->ssl3.clientCertChain = CERT_CertChainFromCert( + ss->ssl3.clientCertificate, + certUsageSSLClient, PR_FALSE); + if (ss->ssl3.clientCertChain == NULL) { CERT_DestroyCertificate(ss->ssl3.clientCertificate); ss->ssl3.clientCertificate = NULL; - } - if (ss->ssl3.clientPrivateKey) { - /* got a key, but no cert - free it */ SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); ss->ssl3.clientPrivateKey = NULL; + goto send_no_certificate; } - goto send_no_certificate; - } - /* Setting ssl3.clientCertChain non-NULL will cause - * ssl3_HandleServerHelloDone to call SendCertificate. - */ - ss->ssl3.clientCertChain = CERT_CertChainFromCert( - ss->ssl3.clientCertificate, - certUsageSSLClient, PR_FALSE); - if (ss->ssl3.clientCertChain == NULL) { - CERT_DestroyCertificate(ss->ssl3.clientCertificate); - ss->ssl3.clientCertificate = NULL; - SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); - ss->ssl3.clientPrivateKey = NULL; - goto send_no_certificate; - } - if (ss->ssl3.hs.hashType == handshake_hash_single) { - ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, algorithms); - } - break; /* not an error */ + if (ss->ssl3.hs.hashType == handshake_hash_single) { + ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, algorithms); + } + break; /* not an error */ - case SECFailure: - default: -send_no_certificate: - if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { - ss->ssl3.sendEmptyCert = PR_TRUE; - } else { - (void)SSL3_SendAlert(ss, alert_warning, no_certificate); - } - rv = SECSuccess; - break; + case SECFailure: + default: + send_no_certificate: + if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { + ss->ssl3.sendEmptyCert = PR_TRUE; + } + else { + (void)SSL3_SendAlert(ss, alert_warning, no_certificate); + } + rv = SECSuccess; + break; } return rv; @@ -7557,45 +7883,50 @@ send_no_certificate: static SECStatus ssl3_CheckFalseStart(sslSocket *ss) { - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( !ss->ssl3.hs.authCertificatePending ); - PORT_Assert( !ss->ssl3.hs.canFalseStart ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(!ss->ssl3.hs.authCertificatePending); + PORT_Assert(!ss->ssl3.hs.canFalseStart); if (!ss->canFalseStartCallback) { - SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", - SSL_GETPID(), ss->fd)); - } else { - PRBool maybeFalseStart; - SECStatus rv; + SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", + SSL_GETPID(), ss->fd)); + } + else { + PRBool maybeFalseStart; + SECStatus rv; - /* An attacker can control the selected ciphersuite so we only wish to - * do False Start in the case that the selected ciphersuite is - * sufficiently strong that the attack can gain no advantage. - * Therefore we always require an 80-bit cipher. */ + /* An attacker can control the selected ciphersuite so we only wish to + * do False Start in the case that the selected ciphersuite is + * sufficiently strong that the attack can gain no advantage. + * Therefore we always require an 80-bit cipher. */ ssl_GetSpecReadLock(ss); maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10; ssl_ReleaseSpecReadLock(ss); - if (!maybeFalseStart) { - SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", - SSL_GETPID(), ss->fd)); - } else { + if (!maybeFalseStart) { + SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", + SSL_GETPID(), ss->fd)); + } + else { PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == ssl_preinfo_all); - rv = (ss->canFalseStartCallback)(ss->fd, - ss->canFalseStartCallbackData, - &ss->ssl3.hs.canFalseStart); - if (rv == SECSuccess) { - SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", - SSL_GETPID(), ss->fd, - ss->ssl3.hs.canFalseStart ? "TRUE" : "FALSE")); - } else { - SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", - SSL_GETPID(), ss->fd, - PR_ErrorToName(PR_GetError()))); - } - return rv; - } + rv = (ss->canFalseStartCallback)(ss->fd, + ss->canFalseStartCallbackData, + &ss->ssl3.hs.canFalseStart); + if (rv == SECSuccess) { + SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", + SSL_GETPID(), ss->fd, + ss->ssl3.hs.canFalseStart ? + "TRUE" + : "FALSE")); + } + else { + SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", + SSL_GETPID(), ss->fd, + PR_ErrorToName(PR_GetError()))); + } + return rv; + } } ss->ssl3.hs.canFalseStart = PR_FALSE; @@ -7607,17 +7938,17 @@ ssl3_WaitingForServerSecondRound(sslSocket *ss) { PRBool result; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); switch (ss->ssl3.hs.ws) { - case wait_new_session_ticket: - case wait_change_cipher: - case wait_finished: - result = PR_TRUE; - break; - default: - result = PR_FALSE; - break; + case wait_new_session_ticket: + case wait_change_cipher: + case wait_finished: + result = PR_TRUE; + break; + default: + result = PR_FALSE; + break; } return result; @@ -7632,20 +7963,20 @@ static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); static SECStatus ssl3_HandleServerHelloDone(sslSocket *ss) { - SECStatus rv; - SSL3WaitState ws = ss->ssl3.hs.ws; + SECStatus rv; + SSL3WaitState ws = ss->ssl3.hs.ws; SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake", - SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + SSL_GETPID(), ss->fd)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* Skipping CertificateRequest is always permitted. */ - if (ws != wait_hello_done && - ws != wait_cert_request) { - SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); - return SECFailure; + if (ws != wait_hello_done && + ws != wait_cert_request) { + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); + return SECFailure; } rv = ssl3_SendClientSecondRound(ss); @@ -7663,19 +7994,19 @@ ssl3_SendClientSecondRound(sslSocket *ss) SECStatus rv; PRBool sendClientCert; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); sendClientCert = !ss->ssl3.sendEmptyCert && - ss->ssl3.clientCertChain != NULL && - ss->ssl3.clientPrivateKey != NULL; + ss->ssl3.clientCertChain != NULL && + ss->ssl3.clientPrivateKey != NULL; if (!sendClientCert && - ss->ssl3.hs.hashType == handshake_hash_single && - ss->ssl3.hs.backupHash) { - /* Don't need the backup handshake hash. */ - PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); - ss->ssl3.hs.backupHash = NULL; + ss->ssl3.hs.hashType == handshake_hash_single && + ss->ssl3.hs.backupHash) { + /* Don't need the backup handshake hash. */ + PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); + ss->ssl3.hs.backupHash = NULL; } /* We must wait for the server's certificate to be authenticated before @@ -7703,52 +8034,53 @@ ssl3_SendClientSecondRound(sslSocket *ss) * application data. */ if (ss->ssl3.hs.restartTarget) { - PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } if (ss->ssl3.hs.authCertificatePending && - (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) { - SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" - " certificate authentication is still pending.", - SSL_GETPID(), ss->fd)); - ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; - return SECWouldBlock; + (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) { + SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" + " certificate authentication is still pending.", + SSL_GETPID(), ss->fd)); + ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; + return SECWouldBlock; } - ssl_GetXmitBufLock(ss); /*******************************/ + ssl_GetXmitBufLock(ss); /*******************************/ if (ss->ssl3.sendEmptyCert) { - ss->ssl3.sendEmptyCert = PR_FALSE; - rv = ssl3_SendEmptyCertificate(ss); - /* Don't send verify */ - if (rv != SECSuccess) { - goto loser; /* error code is set. */ - } - } else if (sendClientCert) { - rv = ssl3_SendCertificate(ss); - if (rv != SECSuccess) { - goto loser; /* error code is set. */ - } + ss->ssl3.sendEmptyCert = PR_FALSE; + rv = ssl3_SendEmptyCertificate(ss); + /* Don't send verify */ + if (rv != SECSuccess) { + goto loser; /* error code is set. */ + } + } + else if (sendClientCert) { + rv = ssl3_SendCertificate(ss); + if (rv != SECSuccess) { + goto loser; /* error code is set. */ + } } rv = ssl3_SendClientKeyExchange(ss); if (rv != SECSuccess) { - goto loser; /* err is set. */ + goto loser; /* err is set. */ } if (sendClientCert) { - rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey); + rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey); SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); ss->ssl3.clientPrivateKey = NULL; - if (rv != SECSuccess) { - goto loser; /* err is set. */ + if (rv != SECSuccess) { + goto loser; /* err is set. */ } } rv = ssl3_SendChangeCipherSpecs(ss); if (rv != SECSuccess) { - goto loser; /* err code was set. */ + goto loser; /* err code was set. */ } /* This must be done after we've set ss->ssl3.cwSpec in @@ -7760,54 +8092,55 @@ ssl3_SendClientSecondRound(sslSocket *ss) ss->enoughFirstHsDone = PR_TRUE; if (!ss->firstHsDone) { - /* XXX: If the server's certificate hasn't been authenticated by this - * point, then we may be leaking this NPN message to an attacker. - */ - rv = ssl3_SendNextProto(ss); - if (rv != SECSuccess) { - goto loser; /* err code was set. */ - } + /* XXX: If the server's certificate hasn't been authenticated by this + * point, then we may be leaking this NPN message to an attacker. + */ + rv = ssl3_SendNextProto(ss); + if (rv != SECSuccess) { + goto loser; /* err code was set. */ + } - if (ss->opt.enableFalseStart) { - if (!ss->ssl3.hs.authCertificatePending) { - /* When we fix bug 589047, we will need to know whether we are - * false starting before we try to flush the client second - * round to the network. With that in mind, we purposefully - * call ssl3_CheckFalseStart before calling ssl3_SendFinished, - * which includes a call to ssl3_FlushHandshake, so that - * no application develops a reliance on such flushing being - * done before its false start callback is called. - */ - ssl_ReleaseXmitBufLock(ss); - rv = ssl3_CheckFalseStart(ss); - ssl_GetXmitBufLock(ss); - if (rv != SECSuccess) { - goto loser; - } - } else { - /* The certificate authentication and the server's Finished - * message are racing each other. If the certificate - * authentication wins, then we will try to false start in - * ssl3_AuthCertificateComplete. - */ - SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" - " certificate authentication is still pending.", - SSL_GETPID(), ss->fd)); - } - } + if (ss->opt.enableFalseStart) { + if (!ss->ssl3.hs.authCertificatePending) { + /* When we fix bug 589047, we will need to know whether we are + * false starting before we try to flush the client second + * round to the network. With that in mind, we purposefully + * call ssl3_CheckFalseStart before calling ssl3_SendFinished, + * which includes a call to ssl3_FlushHandshake, so that + * no application develops a reliance on such flushing being + * done before its false start callback is called. + */ + ssl_ReleaseXmitBufLock(ss); + rv = ssl3_CheckFalseStart(ss); + ssl_GetXmitBufLock(ss); + if (rv != SECSuccess) { + goto loser; + } + } + else { + /* The certificate authentication and the server's Finished + * message are racing each other. If the certificate + * authentication wins, then we will try to false start in + * ssl3_AuthCertificateComplete. + */ + SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" + " certificate authentication is still pending.", + SSL_GETPID(), ss->fd)); + } + } } rv = ssl3_SendFinished(ss, 0); if (rv != SECSuccess) { - goto loser; /* err code was set. */ + goto loser; /* err code was set. */ } - ssl_ReleaseXmitBufLock(ss); /*******************************/ + ssl_ReleaseXmitBufLock(ss); /*******************************/ if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) - ss->ssl3.hs.ws = wait_new_session_ticket; + ss->ssl3.hs.ws = wait_new_session_ticket; else - ss->ssl3.hs.ws = wait_change_cipher; + ss->ssl3.hs.ws = wait_change_cipher; PORT_Assert(ssl3_WaitingForServerSecondRound(ss)); @@ -7827,18 +8160,18 @@ ssl3_SendHelloRequest(sslSocket *ss) SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), - ss->fd)); + ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake */ + return rv; /* err set by AppendHandshake */ } rv = ssl3_FlushHandshake(ss, 0); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + return rv; /* error code set by ssl3_FlushHandshake */ } ss->ssl3.hs.ws = wait_client_hello; return SECSuccess; @@ -7846,7 +8179,7 @@ ssl3_SendHelloRequest(sslSocket *ss) /* * Called from: - * ssl3_HandleClientHello() + * ssl3_HandleClientHello() */ static SECComparison ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) @@ -7865,10 +8198,10 @@ ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) /* Sets memory error when returning NULL. * Called from: - * ssl3_SendClientHello() - * ssl3_HandleServerHello() - * ssl3_HandleClientHello() - * ssl3_HandleV2ClientHello() + * ssl3_SendClientHello() + * ssl3_HandleServerHello() + * ssl3_HandleClientHello() + * ssl3_HandleV2ClientHello() */ sslSessionID * ssl3_NewSessionID(sslSocket *ss, PRBool is_server) @@ -7877,13 +8210,13 @@ ssl3_NewSessionID(sslSocket *ss, PRBool is_server) sid = PORT_ZNew(sslSessionID); if (sid == NULL) - return sid; + return sid; if (is_server) { - const SECItem * srvName; - SECStatus rv = SECSuccess; + const SECItem *srvName; + SECStatus rv = SECSuccess; - ssl_GetSpecReadLock(ss); /********************************/ + ssl_GetSpecReadLock(ss); /********************************/ srvName = &ss->ssl3.prSpec->srvVirtName; if (srvName->len && srvName->data) { rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); @@ -7894,34 +8227,34 @@ ssl3_NewSessionID(sslSocket *ss, PRBool is_server) return NULL; } } - sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); - sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); - sid->addr = ss->sec.ci.peer; - sid->port = ss->sec.ci.port; - sid->references = 1; - sid->cached = never_cached; - sid->version = ss->version; + sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); + sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); + sid->addr = ss->sec.ci.peer; + sid->port = ss->sec.ci.port; + sid->references = 1; + sid->cached = never_cached; + sid->version = ss->version; sid->u.ssl3.keys.resumable = PR_TRUE; - sid->u.ssl3.policy = SSL_ALLOWED; + sid->u.ssl3.policy = SSL_ALLOWED; sid->u.ssl3.clientWriteKey = NULL; sid->u.ssl3.serverWriteKey = NULL; sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE; if (is_server) { - SECStatus rv; - int pid = SSL_GETPID(); + SECStatus rv; + int pid = SSL_GETPID(); - sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; - sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; - sid->u.ssl3.sessionID[1] = pid & 0xff; - rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, - SSL3_SESSIONID_BYTES -2); - if (rv != SECSuccess) { - ssl_FreeSID(sid); - ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); - return NULL; - } + sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; + sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; + sid->u.ssl3.sessionID[1] = pid & 0xff; + rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, + SSL3_SESSIONID_BYTES - 2); + if (rv != SECSuccess) { + ssl_FreeSID(sid); + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); + return NULL; + } } return sid; } @@ -7931,25 +8264,25 @@ static SECStatus ssl3_SendServerHelloSequence(sslSocket *ss) { const ssl3KEADef *kea_def; - SECStatus rv; + SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); rv = ssl3_SendServerHello(ss); if (rv != SECSuccess) { - return rv; /* err code is set. */ + return rv; /* err code is set. */ } rv = ssl3_SendCertificate(ss); if (rv != SECSuccess) { - return rv; /* error code is set. */ + return rv; /* error code is set. */ } rv = ssl3_SendCertificateStatus(ss); if (rv != SECSuccess) { - return rv; /* error code is set. */ + return rv; /* error code is set. */ } /* We have to do this after the call to ssl3_SendServerHello, * because kea_def is set up by ssl3_SendServerHello(). @@ -7958,67 +8291,70 @@ ssl3_SendServerHelloSequence(sslSocket *ss) ss->ssl3.hs.usedStepDownKey = PR_FALSE; if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) { - /* see if we can legally use the key in the cert. */ - unsigned int keyLen; /* bytes */ + /* see if we can legally use the key in the cert. */ + unsigned int keyLen; /* bytes */ - keyLen = PK11_GetPrivateModulusLen( - ss->serverCerts[kea_def->exchKeyType].SERVERKEY); + keyLen = PK11_GetPrivateModulusLen( + ss->serverCerts[kea_def->exchKeyType].SERVERKEY); - if (keyLen > 0 && - keyLen * BPB <= kea_def->key_size_limit ) { - /* XXX AND cert is not signing only!! */ - /* just fall through and use it. */ - } else if (ss->stepDownKeyPair != NULL) { - ss->ssl3.hs.usedStepDownKey = PR_TRUE; - rv = ssl3_SendServerKeyExchange(ss); - if (rv != SECSuccess) { - return rv; /* err code was set. */ - } - } else { + if (keyLen > 0 && + keyLen * BPB <= kea_def->key_size_limit) { + /* XXX AND cert is not signing only!! */ + /* just fall through and use it. */ + } + else if (ss->stepDownKeyPair != NULL) { + ss->ssl3.hs.usedStepDownKey = PR_TRUE; + rv = ssl3_SendServerKeyExchange(ss); + if (rv != SECSuccess) { + return rv; /* err code was set. */ + } + } + else { #ifndef HACKED_EXPORT_SERVER - PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); - return rv; + PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); + return rv; #endif - } - } else if (kea_def->ephemeral) { + } + } + else if (kea_def->ephemeral) { rv = ssl3_SendServerKeyExchange(ss); if (rv != SECSuccess) { - return rv; /* err code was set. */ + return rv; /* err code was set. */ } } if (ss->opt.requestCertificate) { - rv = ssl3_SendCertificateRequest(ss); - if (rv != SECSuccess) { - return rv; /* err code is set. */ - } + rv = ssl3_SendCertificateRequest(ss); + if (rv != SECSuccess) { + return rv; /* err code is set. */ + } } rv = ssl3_SendServerHelloDone(ss); if (rv != SECSuccess) { - return rv; /* err code is set. */ + return rv; /* err code is set. */ } ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert - : wait_client_key; + : wait_client_key; return SECSuccess; } /* An empty TLS Renegotiation Info (RI) extension */ -static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00}; +static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 }; static PRBool ssl3_KEAAllowsSessionTicket(SSL3KeyExchangeAlgorithm kea) { switch (kea) { - case kea_dhe_dss: - case kea_dhe_dss_export: - case kea_dh_dss_export: - case kea_dh_dss: - /* TODO: Fix session tickets for DSS. The server code rejects the - * session ticket received from the client. Bug 1174677 */ - return PR_FALSE; - default: - return PR_TRUE; + case kea_dhe_dss: + case kea_dhe_dss_export: + case kea_dh_dss_export: + case kea_dh_dss: + /* TODO: Fix session tickets for DSS. The server code rejects the + * session ticket received from the client. Bug 1174677 */ + return PR_FALSE; + default: + return PR_TRUE; }; } @@ -8029,30 +8365,30 @@ ssl3_KEAAllowsSessionTicket(SSL3KeyExchangeAlgorithm kea) static SECStatus ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - sslSessionID * sid = NULL; - PRInt32 tmp; - unsigned int i; - int j; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; - SSL3AlertDescription desc = illegal_parameter; - SSL3AlertLevel level = alert_fatal; + sslSessionID *sid = NULL; + PRInt32 tmp; + unsigned int i; + int j; + SECStatus rv; + int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; + SSL3AlertDescription desc = illegal_parameter; + SSL3AlertLevel level = alert_fatal; SSL3ProtocolVersion version; - SECItem sidBytes = {siBuffer, NULL, 0}; - SECItem cookieBytes = {siBuffer, NULL, 0}; - SECItem suites = {siBuffer, NULL, 0}; - SECItem comps = {siBuffer, NULL, 0}; - PRBool haveSpecWriteLock = PR_FALSE; - PRBool haveXmitBufLock = PR_FALSE; - PRBool canOfferSessionTicket = PR_FALSE; - PRBool isTLS13 = PR_FALSE; + SECItem sidBytes = { siBuffer, NULL, 0 }; + SECItem cookieBytes = { siBuffer, NULL, 0 }; + SECItem suites = { siBuffer, NULL, 0 }; + SECItem comps = { siBuffer, NULL, 0 }; + PRBool haveSpecWriteLock = PR_FALSE; + PRBool haveXmitBufLock = PR_FALSE; + PRBool canOfferSessionTicket = PR_FALSE; + PRBool isTLS13 = PR_FALSE; SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello 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)); - PORT_Assert( ss->ssl3.initialized ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.initialized); ss->ssl3.hs.preliminaryInfo = 0; if (!ss->sec.isServer || @@ -8079,7 +8415,7 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) /* Get peer name of client */ rv = ssl_GetPeerInfo(ss); if (rv != SECSuccess) { - return rv; /* error code is set. */ + return rv; /* error code is set. */ } /* Clearing the handshake pointers so that ssl_Do1stHandshake won't @@ -8092,8 +8428,8 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * and need to reset these values here. */ if (IS_DTLS(ss)) { - ss->nextHandshake = 0; - ss->securityHandshake = 0; + ss->nextHandshake = 0; + ss->securityHandshake = 0; } /* We might be starting session renegotiation in which case we should @@ -8103,36 +8439,37 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ss->statelessResume = PR_FALSE; if (IS_DTLS(ss)) { - dtls_RehandshakeCleanup(ss); + dtls_RehandshakeCleanup(ss); } tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); if (tmp < 0) - goto loser; /* malformed, alert already sent */ + goto loser; /* malformed, alert already sent */ /* Translate the version */ if (IS_DTLS(ss)) { - ss->clientHelloVersion = version = - dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); - } else { - ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; + ss->clientHelloVersion = version = + dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); + } + else { + ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; } rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); if (rv != SECSuccess) { - desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version - : handshake_failure; - errCode = SSL_ERROR_UNSUPPORTED_VERSION; - goto alert_loser; + desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version + : handshake_failure; + errCode = SSL_ERROR_UNSUPPORTED_VERSION; + goto alert_loser; } isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; rv = ssl3_InitHandshakeHashes(ss); if (rv != SECSuccess) { - desc = internal_error; - errCode = PORT_GetError(); - goto alert_loser; + desc = internal_error; + errCode = PORT_GetError(); + goto alert_loser; } /* Generate the Server Random now so it is available @@ -8181,48 +8518,48 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) /* grab the client random data. */ rv = ssl3_ConsumeHandshake( - ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); + ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + goto loser; /* malformed */ } /* grab the client's SID, if present. */ rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + goto loser; /* malformed */ } /* grab the client's cookie, if present. */ if (IS_DTLS(ss)) { - rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed */ - } + rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed */ + } } /* grab the list of cipher suites. */ rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + goto loser; /* malformed */ } /* If the ClientHello version is less than our maximum version, check for a * TLS_FALLBACK_SCSV and reject the connection if found. */ if (ss->vrange.max > ss->clientHelloVersion) { - for (i = 0; i + 1 < suites.len; i += 2) { - PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; - if (suite_i != TLS_FALLBACK_SCSV) - continue; - desc = inappropriate_fallback; - errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; - goto alert_loser; - } + for (i = 0; i + 1 < suites.len; i += 2) { + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; + if (suite_i != TLS_FALLBACK_SCSV) + continue; + desc = inappropriate_fallback; + errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; + goto alert_loser; + } } /* grab the list of compression methods. */ rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + goto loser; /* malformed */ } /* TLS 1.3 requires that compression be empty */ @@ -8241,51 +8578,51 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) */ if (length) { - /* Get length of hello extensions */ - PRInt32 extension_length; - extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); - if (extension_length < 0) { - goto loser; /* alert already sent */ - } - if (extension_length != length) { - ssl3_DecodeError(ss); /* send alert */ - goto loser; - } - rv = ssl3_HandleHelloExtensions(ss, &b, &length, client_hello); - if (rv != SECSuccess) { - goto loser; /* malformed */ - } + /* Get length of hello extensions */ + PRInt32 extension_length; + extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); + if (extension_length < 0) { + goto loser; /* alert already sent */ + } + if (extension_length != length) { + ssl3_DecodeError(ss); /* send alert */ + goto loser; + } + rv = ssl3_HandleHelloExtensions(ss, &b, &length, client_hello); + if (rv != SECSuccess) { + goto loser; /* malformed */ + } } if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { - /* If we didn't receive an RI extension, look for the SCSV, - * and if found, treat it just like an empty RI extension - * by processing a local copy of an empty RI extension. - */ - for (i = 0; i + 1 < suites.len; i += 2) { - PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; - if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { - SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; - PRUint32 L2 = sizeof emptyRIext; - (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello); - break; - } - } + /* If we didn't receive an RI extension, look for the SCSV, + * and if found, treat it just like an empty RI extension + * by processing a local copy of an empty RI extension. + */ + for (i = 0; i + 1 < suites.len; i += 2) { + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; + if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { + SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext; + PRUint32 L2 = sizeof emptyRIext; + (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello); + break; + } + } } if (ss->firstHsDone && (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN || - ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && - !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { - desc = no_renegotiation; - level = alert_warning; - errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; - goto alert_loser; + ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { + desc = no_renegotiation; + level = alert_warning; + errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; + goto alert_loser; } - if ((ss->opt.requireSafeNegotiation || + if ((ss->opt.requireSafeNegotiation || (ss->firstHsDone && ss->peerRequestedProtection)) && - !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { - desc = handshake_failure; - errCode = SSL_ERROR_UNSAFE_NEGOTIATION; - goto alert_loser; + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { + desc = handshake_failure; + errCode = SSL_ERROR_UNSAFE_NEGOTIATION; + goto alert_loser; } /* We do stateful resumes only if either of the following @@ -8294,37 +8631,40 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * ticket extension, but sent an empty ticket. */ if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) || - ss->xtnData.emptySessionTicket) { - if (sidBytes.len > 0 && !ss->opt.noCache) { - SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x", - SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], - ss->sec.ci.peer.pr_s6_addr32[1], - ss->sec.ci.peer.pr_s6_addr32[2], - ss->sec.ci.peer.pr_s6_addr32[3])); - if (ssl_sid_lookup) { - sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, - sidBytes.len, ss->dbHandle); - } else { - errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; - goto loser; - } - } - } else if (ss->statelessResume) { - /* Fill in the client's session ID if doing a stateless resume. - * (When doing stateless resumes, server echos client's SessionID.) - */ - sid = ss->sec.ci.sid; - PORT_Assert(sid != NULL); /* Should have already been filled in.*/ + ss->xtnData.emptySessionTicket) { + if (sidBytes.len > 0 && !ss->opt.noCache) { + SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x", + SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], + ss->sec.ci.peer.pr_s6_addr32[1], + ss->sec.ci.peer.pr_s6_addr32[2], + ss->sec.ci.peer.pr_s6_addr32[3])); + if (ssl_sid_lookup) { + sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, + sidBytes.len, ss->dbHandle); + } + else { + errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; + goto loser; + } + } + } + else if (ss->statelessResume) { + /* Fill in the client's session ID if doing a stateless resume. + * (When doing stateless resumes, server echos client's SessionID.) + */ + sid = ss->sec.ci.sid; + PORT_Assert(sid != NULL); /* Should have already been filled in.*/ - if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { - sid->u.ssl3.sessionIDLength = sidBytes.len; - PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, - sidBytes.len); - sid->u.ssl3.sessionIDLength = sidBytes.len; - } else { - sid->u.ssl3.sessionIDLength = 0; - } - ss->sec.ci.sid = NULL; + if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { + sid->u.ssl3.sessionIDLength = sidBytes.len; + PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, + sidBytes.len); + sid->u.ssl3.sessionIDLength = sidBytes.len; + } + else { + sid->u.ssl3.sessionIDLength = 0; + } + ss->sec.ci.sid = NULL; } /* We only send a session ticket extension if the client supports @@ -8338,28 +8678,28 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * resuming.) */ if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) { - canOfferSessionTicket = PR_TRUE; + canOfferSessionTicket = PR_TRUE; } if (sid != NULL) { - /* We've found a session cache entry for this client. - * Now, if we're going to require a client-auth cert, - * and we don't already have this client's cert in the session cache, - * and this is the first handshake on this connection (not a redo), - * then drop this old cache entry and start a new session. - */ - if ((sid->peerCert == NULL) && ss->opt.requestCertificate && - ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || - (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || - ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) - && !ss->firstHsDone))) { + /* We've found a session cache entry for this client. + * Now, if we're going to require a client-auth cert, + * and we don't already have this client's cert in the session cache, + * and this is the first handshake on this connection (not a redo), + * then drop this old cache entry and start a new session. + */ + if ((sid->peerCert == NULL) && ss->opt.requestCertificate && + ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || + (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || + ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) && + !ss->firstHsDone))) { - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); - if (ss->sec.uncache) + SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok); + if (ss->sec.uncache) ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; - } + ssl_FreeSID(sid); + sid = NULL; + } } #ifndef NSS_DISABLE_ECC @@ -8368,15 +8708,15 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) #endif if (IS_DTLS(ss)) { - ssl3_DisableNonDTLSSuites(ss); + ssl3_DisableNonDTLSSuites(ss); } #ifdef PARANOID /* Look for a matching cipher suite. */ j = ssl3_config_match_init(ss); - if (j <= 0) { /* no ciphers are working/supported by PK11 */ - errCode = PORT_GetError(); /* error code is already set. */ - goto alert_loser; + if (j <= 0) { /* no ciphers are working/supported by PK11 */ + errCode = PORT_GetError(); /* error code is already set. */ + goto alert_loser; } #endif @@ -8384,71 +8724,74 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ** same cipher suite and compression method we picked before. ** This is not a loop, despite appearances. */ - if (sid) do { - ssl3CipherSuiteCfg *suite; + if (sid) + do { + ssl3CipherSuiteCfg *suite; #ifdef PARANOID - SSLVersionRange vrange = {ss->version, ss->version}; + SSLVersionRange vrange = { ss->version, ss->version }; #endif - /* Check that the cached compression method is still enabled. */ - if (!compressionEnabled(ss, sid->u.ssl3.compression)) - break; + /* Check that the cached compression method is still enabled. */ + if (!compressionEnabled(ss, sid->u.ssl3.compression)) + break; - /* Check that the cached compression method is in the client's list */ - for (i = 0; i < comps.len; i++) { - if (comps.data[i] == sid->u.ssl3.compression) - break; - } - if (i == comps.len) - break; + /* Check that the cached compression method is in the client's list */ + for (i = 0; i < comps.len; i++) { + if (comps.data[i] == sid->u.ssl3.compression) + break; + } + if (i == comps.len) + break; - suite = ss->cipherSuites; - /* Find the entry for the cipher suite used in the cached session. */ - for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { - if (suite->cipher_suite == sid->u.ssl3.cipherSuite) - break; - } - PORT_Assert(j > 0); - if (j <= 0) - break; + suite = ss->cipherSuites; + /* Find the entry for the cipher suite used in the cached session. */ + for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { + if (suite->cipher_suite == sid->u.ssl3.cipherSuite) + break; + } + PORT_Assert(j > 0); + if (j <= 0) + break; #ifdef PARANOID - /* Double check that the cached cipher suite is still enabled, - * implemented, and allowed by policy. Might have been disabled. - * The product policy won't change during the process lifetime. - * Implemented ("isPresent") shouldn't change for servers. - */ - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) - break; + /* Double check that the cached cipher suite is still enabled, + * implemented, and allowed by policy. Might have been disabled. + * The product policy won't change during the process lifetime. + * Implemented ("isPresent") shouldn't change for servers. + */ + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) + break; #else - if (!suite->enabled) - break; + if (!suite->enabled) + break; #endif - /* Double check that the cached cipher suite is in the client's list */ - for (i = 0; i + 1 < suites.len; i += 2) { - PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; - if (suite_i == suite->cipher_suite) { - ss->ssl3.hs.cipher_suite = suite->cipher_suite; - ss->ssl3.hs.suite_def = - ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); - ss->ssl3.hs.kea_def = - &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; - ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; + /* Double check that the cached cipher suite is in the client's list */ + for (i = 0; i + 1 < suites.len; i += 2) { + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; + if (suite_i == suite->cipher_suite) { + ss->ssl3.hs.cipher_suite = + suite->cipher_suite; + ss->ssl3.hs.suite_def = + ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); + ss->ssl3.hs.kea_def = + &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; + ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; - /* Use the cached compression method. */ - ss->ssl3.hs.compression = sid->u.ssl3.compression; - goto compression_found; - } - } - } while (0); + /* Use the cached compression method. */ + ss->ssl3.hs.compression = + sid->u.ssl3.compression; + goto compression_found; + } + } + } while (0); - /* START A NEW SESSION */ +/* START A NEW SESSION */ #ifndef PARANOID /* Look for a matching cipher suite. */ j = ssl3_config_match_init(ss); - if (j <= 0) { /* no ciphers are working/supported by PK11 */ - errCode = PORT_GetError(); /* error code is already set. */ - goto alert_loser; + if (j <= 0) { /* no ciphers are working/supported by PK11 */ + errCode = PORT_GetError(); /* error code is already set. */ + goto alert_loser; } #endif @@ -8467,51 +8810,51 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ** (the server) have TLS 1.1 support enabled. */ for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; - SSLVersionRange vrange = {ss->version, ss->version}; - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { - continue; - } - for (i = 0; i + 1 < suites.len; i += 2) { - PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; - if (suite_i == suite->cipher_suite) { - ss->ssl3.hs.cipher_suite = suite->cipher_suite; - ss->ssl3.hs.suite_def = - ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; + SSLVersionRange vrange = { ss->version, ss->version }; + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { + continue; + } + for (i = 0; i + 1 < suites.len; i += 2) { + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; + if (suite_i == suite->cipher_suite) { + ss->ssl3.hs.cipher_suite = suite->cipher_suite; + ss->ssl3.hs.suite_def = + ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; - goto suite_found; - } - } + goto suite_found; + } + } } errCode = SSL_ERROR_NO_CYPHER_OVERLAP; goto alert_loser; suite_found: if (canOfferSessionTicket) - canOfferSessionTicket = ssl3_KEAAllowsSessionTicket( - ss->ssl3.hs.suite_def->key_exchange_alg); + canOfferSessionTicket = ssl3_KEAAllowsSessionTicket( + ss->ssl3.hs.suite_def->key_exchange_alg); if (canOfferSessionTicket) { - ssl3_RegisterServerHelloExtensionSender(ss, - ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn); + ssl3_RegisterServerHelloExtensionSender(ss, + ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn); } /* Select a compression algorithm. */ for (i = 0; i < comps.len; i++) { - if (!compressionEnabled(ss, comps.data[i])) - continue; - for (j = 0; j < compressionMethodsCount; j++) { - if (comps.data[i] == compressions[j]) { - ss->ssl3.hs.compression = - (SSLCompressionMethod)compressions[j]; - goto compression_found; - } - } + if (!compressionEnabled(ss, comps.data[i])) + continue; + for (j = 0; j < compressionMethodsCount; j++) { + if (comps.data[i] == compressions[j]) { + ss->ssl3.hs.compression = + (SSLCompressionMethod)compressions[j]; + goto compression_found; + } + } } errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; - /* null compression must be supported */ + /* null compression must be supported */ goto alert_loser; compression_found: @@ -8526,332 +8869,343 @@ compression_found: * The exception here is attempts to resume extended_master_secret * sessions without the extension, which causes an alert. */ - if (sid != NULL) do { - ssl3CipherSpec *pwSpec; - SECItem wrappedMS; /* wrapped key */ + if (sid != NULL) + do { + ssl3CipherSpec *pwSpec; + SECItem wrappedMS; /* wrapped key */ - if (sid->version != ss->version || - sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || - sid->u.ssl3.compression != ss->ssl3.hs.compression) { - break; /* not an error */ - } - - /* [draft-ietf-tls-session-hash-06; Section 5.3] - * o If the original session did not use the "extended_master_secret" - * extension but the new ClientHello contains the extension, then the - * server MUST NOT perform the abbreviated handshake. Instead, it - * SHOULD continue with a full handshake (as described in - * Section 5.2) to negotiate a new session. - * - * o If the original session used the "extended_master_secret" - * extension but the new ClientHello does not contain the extension, - * the server MUST abort the abbreviated handshake. - */ - if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { - if (!sid->u.ssl3.keys.extendedMasterSecretUsed) { - break; /* not an error */ + if (sid->version != ss->version || + sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || + sid->u.ssl3.compression != ss->ssl3.hs.compression) { + break; /* not an error */ } - } else { - if (sid->u.ssl3.keys.extendedMasterSecretUsed) { - /* Note: we do not destroy the session */ - desc = handshake_failure; - errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; - goto alert_loser; + + /* [draft-ietf-tls-session-hash-06; Section 5.3] + * o If the original session did not use the "extended_master_secret" + * extension but the new ClientHello contains the extension, then the + * server MUST NOT perform the abbreviated handshake. Instead, it + * SHOULD continue with a full handshake (as described in + * Section 5.2) to negotiate a new session. + * + * o If the original session used the "extended_master_secret" + * extension but the new ClientHello does not contain the extension, + * the server MUST abort the abbreviated handshake. + */ + if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { + if (!sid->u.ssl3.keys.extendedMasterSecretUsed) { + break; /* not an error */ + } + } + else { + if (sid->u.ssl3.keys.extendedMasterSecretUsed) { + /* Note: we do not destroy the session */ + desc = handshake_failure; + errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; + goto alert_loser; + } } - } - if (ss->sec.ci.sid) { - if (ss->sec.uncache) - ss->sec.uncache(ss->sec.ci.sid); - PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */ - if (ss->sec.ci.sid != sid) { - ssl_FreeSID(ss->sec.ci.sid); - } - ss->sec.ci.sid = NULL; - } - /* we need to resurrect the master secret.... */ + if (ss->sec.ci.sid) { + if (ss->sec.uncache) + ss->sec.uncache(ss->sec.ci.sid); + PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */ + if (ss->sec.ci.sid != sid) { + ssl_FreeSID(ss->sec.ci.sid); + } + ss->sec.ci.sid = NULL; + } + /* we need to resurrect the master secret.... */ - ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE; - pwSpec = ss->ssl3.pwSpec; - if (sid->u.ssl3.keys.msIsWrapped) { - PK11SymKey * wrapKey; /* wrapping key */ - CK_FLAGS keyFlags = 0; + ssl_GetSpecWriteLock(ss); + haveSpecWriteLock = PR_TRUE; + pwSpec = ss->ssl3.pwSpec; + if (sid->u.ssl3.keys.msIsWrapped) { + PK11SymKey *wrapKey; /* wrapping key */ + CK_FLAGS keyFlags = 0; #ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - /* we cannot restart a non-bypass session in a - ** bypass socket. - */ - break; - } + if (ss->opt.bypassPKCS11) { + /* we cannot restart a non-bypass session in a + ** bypass socket. + */ + break; + } #endif - wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, - sid->u.ssl3.masterWrapMech, - ss->pkcs11PinArg); - if (!wrapKey) { - /* we have a SID cache entry, but no wrapping key for it??? */ - break; - } + wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, + sid->u.ssl3.masterWrapMech, + ss->pkcs11PinArg); + if (!wrapKey) { + /* we have a SID cache entry, but no wrapping key for it??? */ + break; + } - if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ - keyFlags = CKF_SIGN | CKF_VERIFY; - } + if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ + keyFlags = + CKF_SIGN | CKF_VERIFY; + } - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - /* unwrap the master secret. */ - pwSpec->master_secret = - PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, - NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, - CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); - PK11_FreeSymKey(wrapKey); - if (pwSpec->master_secret == NULL) { - break; /* not an error */ - } + /* unwrap the master secret. */ + pwSpec->master_secret = + PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, + NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, + CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); + PK11_FreeSymKey(wrapKey); + if (pwSpec->master_secret == NULL) { + break; /* not an error */ + } #ifndef NO_PKCS11_BYPASS - } else if (ss->opt.bypassPKCS11) { - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = wrappedMS.len; -#endif - } else { - /* We CAN restart a bypass session in a non-bypass socket. */ - /* need to import the raw master secret to session object */ - PK11SlotInfo * slot; - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - slot = PK11_GetInternalSlot(); - pwSpec->master_secret = - PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, - PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, - NULL); - PK11_FreeSlot(slot); - if (pwSpec->master_secret == NULL) { - break; /* not an error */ - } - } - ss->sec.ci.sid = sid; - if (sid->peerCert != NULL) { - ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); - } - - /* - * Old SID passed all tests, so resume this old session. - * - * XXX make sure compression still matches - */ - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits ); - if (ss->statelessResume) - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes ); - ss->ssl3.hs.isResuming = PR_TRUE; - - ss->sec.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; - - /* server sids don't remember the server cert we previously sent, - ** but they do remember the kea type we originally used, so we - ** can locate it again, provided that the current ssl socket - ** has had its server certs configured the same as the previous one. - */ - ss->sec.localCert = - CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert); - - /* Copy cached name in to pending spec */ - if (sid != NULL && - sid->version > SSL_LIBRARY_VERSION_3_0 && - sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { - /* Set server name from sid */ - SECItem *sidName = &sid->u.ssl3.srvName; - SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName; - if (pwsName->data) { - SECITEM_FreeItem(pwsName, PR_FALSE); } - rv = SECITEM_CopyItem(NULL, pwsName, sidName); + else if (ss->opt.bypassPKCS11) { + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); + pwSpec->msItem.data = pwSpec->raw_master_secret; + pwSpec->msItem.len = wrappedMS.len; +#endif + } + else { + /* We CAN restart a bypass session in a non-bypass socket. */ + /* need to import the raw master secret to session object */ + PK11SlotInfo *slot; + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + slot = PK11_GetInternalSlot(); + pwSpec->master_secret = + PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, + PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, + NULL); + PK11_FreeSlot(slot); + if (pwSpec->master_secret == NULL) { + break; /* not an error */ + } + } + ss->sec.ci.sid = sid; + if (sid->peerCert != NULL) { + ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); + } + + /* + * Old SID passed all tests, so resume this old session. + * + * XXX make sure compression still matches + */ + SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits); + if (ss->statelessResume) + SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes); + ss->ssl3.hs.isResuming = PR_TRUE; + + ss->sec.authAlgorithm = sid->authAlgorithm; + ss->sec.authKeyBits = sid->authKeyBits; + ss->sec.keaType = sid->keaType; + ss->sec.keaKeyBits = sid->keaKeyBits; + + /* server sids don't remember the server cert we previously sent, + ** but they do remember the kea type we originally used, so we + ** can locate it again, provided that the current ssl socket + ** has had its server certs configured the same as the previous one. + */ + ss->sec.localCert = + CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert); + + /* Copy cached name in to pending spec */ + if (sid != NULL && + sid->version > SSL_LIBRARY_VERSION_3_0 && + sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { + /* Set server name from sid */ + SECItem *sidName = &sid->u.ssl3.srvName; + SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName; + if (pwsName->data) { + SECITEM_FreeItem(pwsName, PR_FALSE); + } + rv = SECITEM_CopyItem(NULL, pwsName, sidName); + if (rv != SECSuccess) { + errCode = PORT_GetError(); + desc = internal_error; + goto alert_loser; + } + } + + /* Clean up sni name array */ + if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && + ss->xtnData.sniNameArr) { + PORT_Free(ss->xtnData.sniNameArr); + ss->xtnData.sniNameArr = NULL; + ss->xtnData.sniNameArrSize = 0; + } + + ssl_GetXmitBufLock(ss); + haveXmitBufLock = PR_TRUE; + + rv = ssl3_SendServerHello(ss); if (rv != SECSuccess) { errCode = PORT_GetError(); - desc = internal_error; - goto alert_loser; + goto loser; } - } - /* Clean up sni name array */ - if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && - ss->xtnData.sniNameArr) { - PORT_Free(ss->xtnData.sniNameArr); - ss->xtnData.sniNameArr = NULL; - ss->xtnData.sniNameArrSize = 0; - } + if (haveSpecWriteLock) { + ssl_ReleaseSpecWriteLock(ss); + haveSpecWriteLock = PR_FALSE; + } - ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE; + /* NULL value for PMS because we are re-using the old MS */ + rv = ssl3_InitPendingCipherSpec(ss, NULL); + if (rv != SECSuccess) { + errCode = PORT_GetError(); + goto loser; + } - rv = ssl3_SendServerHello(ss); - if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; - } + rv = ssl3_SendChangeCipherSpecs(ss); + if (rv != SECSuccess) { + errCode = PORT_GetError(); + goto loser; + } + rv = ssl3_SendFinished(ss, 0); + ss->ssl3.hs.ws = wait_change_cipher; + if (rv != SECSuccess) { + errCode = PORT_GetError(); + goto loser; + } - if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; - } + if (haveXmitBufLock) { + ssl_ReleaseXmitBufLock(ss); + haveXmitBufLock = PR_FALSE; + } - /* NULL value for PMS because we are re-using the old MS */ - rv = ssl3_InitPendingCipherSpec(ss, NULL); - if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; - } - - rv = ssl3_SendChangeCipherSpecs(ss); - if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; - } - rv = ssl3_SendFinished(ss, 0); - ss->ssl3.hs.ws = wait_change_cipher; - if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; - } - - if (haveXmitBufLock) { - ssl_ReleaseXmitBufLock(ss); - haveXmitBufLock = PR_FALSE; - } - - return SECSuccess; - } while (0); + return SECSuccess; + } while (0); if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; + ssl_ReleaseSpecWriteLock(ss); + haveSpecWriteLock = PR_FALSE; } - if (sid) { /* we had a sid, but it's no longer valid, free it */ - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); - if (ss->sec.uncache) + if (sid) { /* we had a sid, but it's no longer valid, free it */ + SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok); + if (ss->sec.uncache) ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; + ssl_FreeSID(sid); + sid = NULL; } - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); + SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses); if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { int ret = 0; - if (ss->sniSocketConfig) do { /* not a loop */ - PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == - ssl_preinfo_all); + if (ss->sniSocketConfig) + do { /* not a loop */ + PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == + ssl_preinfo_all); - ret = SSL_SNI_SEND_ALERT; - /* If extension is negotiated, the len of names should > 0. */ - if (ss->xtnData.sniNameArrSize) { - /* Calling client callback to reconfigure the socket. */ - ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd, - ss->xtnData.sniNameArr, - ss->xtnData.sniNameArrSize, - ss->sniSocketConfigArg); - } - if (ret <= SSL_SNI_SEND_ALERT) { - /* Application does not know the name or was not able to - * properly reconfigure the socket. */ - errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; - desc = unrecognized_name; - break; - } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { - SECStatus rv = SECSuccess; - SECItem * cwsName, *pwsName; - - ssl_GetSpecWriteLock(ss); /*******************************/ - pwsName = &ss->ssl3.pwSpec->srvVirtName; - cwsName = &ss->ssl3.cwSpec->srvVirtName; -#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS - /* not allow name change on the 2d HS */ - if (ss->firstHsDone) { - if (ssl3_ServerNameCompare(pwsName, cwsName)) { - ssl_ReleaseSpecWriteLock(ss); /******************/ - errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; - desc = handshake_failure; - ret = SSL_SNI_SEND_ALERT; - break; - } - } -#endif - if (pwsName->data) { - SECITEM_FreeItem(pwsName, PR_FALSE); - } - if (cwsName->data) { - rv = SECITEM_CopyItem(NULL, pwsName, cwsName); - } - ssl_ReleaseSpecWriteLock(ss); /**************************/ - if (rv != SECSuccess) { - errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; - desc = internal_error; - ret = SSL_SNI_SEND_ALERT; - break; - } - } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) { - /* Application has configured new socket info. Lets check it - * and save the name. */ - SECStatus rv; - SECItem * name = &ss->xtnData.sniNameArr[ret]; - int configedCiphers; - SECItem * pwsName; - - /* get rid of the old name and save the newly picked. */ - /* This code is protected by ssl3HandshakeLock. */ - ssl_GetSpecWriteLock(ss); /*******************************/ -#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS - /* not allow name change on the 2d HS */ - if (ss->firstHsDone) { - SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName; - if (ssl3_ServerNameCompare(name, cwsName)) { - ssl_ReleaseSpecWriteLock(ss); /******************/ - errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; - desc = handshake_failure; - ret = SSL_SNI_SEND_ALERT; - break; - } - } -#endif - pwsName = &ss->ssl3.pwSpec->srvVirtName; - if (pwsName->data) { - SECITEM_FreeItem(pwsName, PR_FALSE); - } - rv = SECITEM_CopyItem(NULL, pwsName, name); - ssl_ReleaseSpecWriteLock(ss); /***************************/ - if (rv != SECSuccess) { - errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; - desc = internal_error; - ret = SSL_SNI_SEND_ALERT; - break; - } - configedCiphers = ssl3_config_match_init(ss); - if (configedCiphers <= 0) { - /* no ciphers are working/supported */ - errCode = PORT_GetError(); - desc = handshake_failure; - ret = SSL_SNI_SEND_ALERT; - break; - } - /* Need to tell the client that application has picked - * the name from the offered list and reconfigured the socket. - */ - ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn, - ssl3_SendServerNameXtn); - } else { - /* Callback returned index outside of the boundary. */ - PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize); - errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; - desc = internal_error; ret = SSL_SNI_SEND_ALERT; - break; - } - } while (0); + /* If extension is negotiated, the len of names should > 0. */ + if (ss->xtnData.sniNameArrSize) { + /* Calling client callback to reconfigure the socket. */ + ret = (SECStatus) (*ss->sniSocketConfig)(ss->fd, + ss->xtnData.sniNameArr, + ss->xtnData.sniNameArrSize, + ss->sniSocketConfigArg); + } + if (ret <= SSL_SNI_SEND_ALERT) { + /* Application does not know the name or was not able to + * properly reconfigure the socket. */ + errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; + desc = unrecognized_name; + break; + } + else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { + SECStatus rv = SECSuccess; + SECItem *cwsName, *pwsName; + + ssl_GetSpecWriteLock(ss); /*******************************/ + pwsName = &ss->ssl3.pwSpec->srvVirtName; + cwsName = &ss->ssl3.cwSpec->srvVirtName; +#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS + /* not allow name change on the 2d HS */ + if (ss->firstHsDone) { + if (ssl3_ServerNameCompare(pwsName, cwsName)) { + ssl_ReleaseSpecWriteLock(ss); /******************/ + errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; + desc = handshake_failure; + ret = SSL_SNI_SEND_ALERT; + break; + } + } +#endif + if (pwsName->data) { + SECITEM_FreeItem(pwsName, PR_FALSE); + } + if (cwsName->data) { + rv = SECITEM_CopyItem(NULL, pwsName, cwsName); + } + ssl_ReleaseSpecWriteLock(ss); /**************************/ + if (rv != SECSuccess) { + errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; + desc = internal_error; + ret = SSL_SNI_SEND_ALERT; + break; + } + } + else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) { + /* Application has configured new socket info. Lets check it + * and save the name. */ + SECStatus rv; + SECItem *name = &ss->xtnData.sniNameArr[ret]; + int configedCiphers; + SECItem *pwsName; + + /* get rid of the old name and save the newly picked. */ + /* This code is protected by ssl3HandshakeLock. */ + ssl_GetSpecWriteLock(ss); /*******************************/ +#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS + /* not allow name change on the 2d HS */ + if (ss->firstHsDone) { + SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName; + if (ssl3_ServerNameCompare(name, cwsName)) { + ssl_ReleaseSpecWriteLock(ss); /******************/ + errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; + desc = handshake_failure; + ret = SSL_SNI_SEND_ALERT; + break; + } + } +#endif + pwsName = &ss->ssl3.pwSpec->srvVirtName; + if (pwsName->data) { + SECITEM_FreeItem(pwsName, PR_FALSE); + } + rv = SECITEM_CopyItem(NULL, pwsName, name); + ssl_ReleaseSpecWriteLock(ss); /***************************/ + if (rv != SECSuccess) { + errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; + desc = internal_error; + ret = SSL_SNI_SEND_ALERT; + break; + } + configedCiphers = ssl3_config_match_init(ss); + if (configedCiphers <= 0) { + /* no ciphers are working/supported */ + errCode = PORT_GetError(); + desc = handshake_failure; + ret = SSL_SNI_SEND_ALERT; + break; + } + /* Need to tell the client that application has picked + * the name from the offered list and reconfigured the socket. + */ + ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn, + ssl3_SendServerNameXtn); + } + else { + /* Callback returned index outside of the boundary. */ + PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize); + errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; + desc = internal_error; + ret = SSL_SNI_SEND_ALERT; + break; + } + } while (0); /* Free sniNameArr. The data that each SECItem in the array * points into is the data from the input buffer "b". It will * not be available outside the scope of this or it's child @@ -8871,11 +9225,11 @@ compression_found: /* Check that we don't have the name is current spec * if this extension was not negotiated on the 2d hs. */ PRBool passed = PR_TRUE; - ssl_GetSpecReadLock(ss); /*******************************/ + ssl_GetSpecReadLock(ss); /*******************************/ if (ss->ssl3.cwSpec->srvVirtName.data) { passed = PR_FALSE; } - ssl_ReleaseSpecReadLock(ss); /***************************/ + ssl_ReleaseSpecReadLock(ss); /***************************/ if (!passed) { errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; desc = handshake_failure; @@ -8897,19 +9251,20 @@ compression_found: sid = ssl3_NewSessionID(ss, PR_TRUE); if (sid == NULL) { - errCode = PORT_GetError(); - goto loser; /* memory error is set. */ + errCode = PORT_GetError(); + goto loser; /* memory error is set. */ } ss->sec.ci.sid = sid; sid->u.ssl3.keys.extendedMasterSecretUsed = - ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); + ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); ss->ssl3.hs.isResuming = PR_FALSE; ssl_GetXmitBufLock(ss); if (isTLS13) { rv = tls13_SendServerHelloSequence(ss); - } else { + } + else { rv = ssl3_SendServerHelloSequence(ss); } ssl_ReleaseXmitBufLock(ss); @@ -8920,28 +9275,28 @@ compression_found: } if (haveXmitBufLock) { - ssl_ReleaseXmitBufLock(ss); - haveXmitBufLock = PR_FALSE; + ssl_ReleaseXmitBufLock(ss); + haveXmitBufLock = PR_FALSE; } return SECSuccess; alert_loser: if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; + ssl_ReleaseSpecWriteLock(ss); + haveSpecWriteLock = PR_FALSE; } (void)SSL3_SendAlert(ss, level, desc); - /* FALLTHRU */ +/* FALLTHRU */ loser: if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; + ssl_ReleaseSpecWriteLock(ss); + haveSpecWriteLock = PR_FALSE; } if (haveXmitBufLock) { - ssl_ReleaseXmitBufLock(ss); - haveXmitBufLock = PR_FALSE; + ssl_ReleaseXmitBufLock(ss); + haveXmitBufLock = PR_FALSE; } PORT_SetError(errCode); @@ -8956,22 +9311,22 @@ loser: SECStatus ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) { - sslSessionID * sid = NULL; - unsigned char * suites; - unsigned char * random; + sslSessionID *sid = NULL; + unsigned char *suites; + unsigned char *random; SSL3ProtocolVersion version; - SECStatus rv; - int i; - int j; - int sid_length; - int suite_length; - int rand_length; - int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; - SSL3AlertDescription desc = handshake_failure; + SECStatus rv; + int i; + int j; + int sid_length; + int suite_length; + int rand_length; + int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; + SSL3AlertDescription desc = handshake_failure; SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); ssl_GetSSL3HandshakeLock(ss); @@ -8979,25 +9334,25 @@ ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) rv = ssl3_InitState(ss); if (rv != SECSuccess) { - ssl_ReleaseSSL3HandshakeLock(ss); - return rv; /* ssl3_InitState has set the error code. */ + ssl_ReleaseSSL3HandshakeLock(ss); + return rv; /* ssl3_InitState has set the error code. */ } rv = ssl3_RestartHandshakeHashes(ss); if (rv != SECSuccess) { - ssl_ReleaseSSL3HandshakeLock(ss); - return rv; + ssl_ReleaseSSL3HandshakeLock(ss); + return rv; } if (ss->ssl3.hs.ws != wait_client_hello) { - desc = unexpected_message; - errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; - goto loser; /* alert_loser */ + desc = unexpected_message; + errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; + goto loser; /* alert_loser */ } - version = (buffer[1] << 8) | buffer[2]; + version = (buffer[1] << 8) | buffer[2]; suite_length = (buffer[3] << 8) | buffer[4]; - sid_length = (buffer[5] << 8) | buffer[6]; - rand_length = (buffer[7] << 8) | buffer[8]; + sid_length = (buffer[5] << 8) | buffer[6]; + rand_length = (buffer[7] << 8) | buffer[8]; ss->clientHelloVersion = version; if (version >= SSL_LIBRARY_VERSION_TLS_1_3) { @@ -9010,56 +9365,56 @@ ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); if (rv != SECSuccess) { - /* send back which ever alert client will understand. */ - desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version - : handshake_failure; - errCode = SSL_ERROR_UNSUPPORTED_VERSION; - goto alert_loser; + /* send back which ever alert client will understand. */ + desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version + : handshake_failure; + errCode = SSL_ERROR_UNSUPPORTED_VERSION; + goto alert_loser; } ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; rv = ssl3_InitHandshakeHashes(ss); if (rv != SECSuccess) { - desc = internal_error; - errCode = PORT_GetError(); - goto alert_loser; + desc = internal_error; + errCode = PORT_GetError(); + goto alert_loser; } /* if we get a non-zero SID, just ignore it. */ if (length != SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) { - SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", - SSL_GETPID(), ss->fd, length, - SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + - rand_length)); - goto loser; /* malformed */ /* alert_loser */ + SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", + SSL_GETPID(), ss->fd, length, + SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + + rand_length)); + goto loser; /* malformed */ /* alert_loser */ } suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES; random = suites + suite_length + sid_length; if (rand_length < SSL_MIN_CHALLENGE_BYTES || - rand_length > SSL_MAX_CHALLENGE_BYTES) { - goto loser; /* malformed */ /* alert_loser */ + rand_length > SSL_MAX_CHALLENGE_BYTES) { + goto loser; /* malformed */ /* alert_loser */ } PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH); PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); PORT_Memcpy( - &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], - random, rand_length); + &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], + random, rand_length); PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0], - SSL3_RANDOM_LENGTH)); + SSL3_RANDOM_LENGTH)); #ifndef NSS_DISABLE_ECC /* Disable any ECC cipher suites for which we have no cert. */ ssl3_FilterECCipherSuitesByServerCerts(ss); #endif i = ssl3_config_match_init(ss); if (i <= 0) { - errCode = PORT_GetError(); /* error code is already set. */ - goto alert_loser; + errCode = PORT_GetError(); /* error code is already set. */ + goto alert_loser; } /* Select a cipher suite. @@ -9070,58 +9425,58 @@ ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) ** See the comments about export cipher suites in ssl3_HandleClientHello(). */ for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; - SSLVersionRange vrange = {ss->version, ss->version}; - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { - continue; - } - for (i = 0; i+2 < suite_length; i += 3) { - PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2]; - if (suite_i == suite->cipher_suite) { - ss->ssl3.hs.cipher_suite = suite->cipher_suite; - ss->ssl3.hs.suite_def = - ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; + SSLVersionRange vrange = { ss->version, ss->version }; + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { + continue; + } + for (i = 0; i + 2 < suite_length; i += 3) { + PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2]; + if (suite_i == suite->cipher_suite) { + ss->ssl3.hs.cipher_suite = suite->cipher_suite; + ss->ssl3.hs.suite_def = + ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; - goto suite_found; - } - } + goto suite_found; + } + } } errCode = SSL_ERROR_NO_CYPHER_OVERLAP; goto alert_loser; suite_found: - /* Look for the SCSV, and if found, treat it just like an empty RI + /* Look for the SCSV, and if found, treat it just like an empty RI * extension by processing a local copy of an empty RI extension. */ - for (i = 0; i+2 < suite_length; i += 3) { - PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2]; - if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { - SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; - PRUint32 L2 = sizeof emptyRIext; - (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello); - break; - } + for (i = 0; i + 2 < suite_length; i += 3) { + PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2]; + if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { + SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext; + PRUint32 L2 = sizeof emptyRIext; + (void)ssl3_HandleHelloExtensions(ss, &b2, &L2, client_hello); + break; + } } if (ss->opt.requireSafeNegotiation && - !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { - desc = handshake_failure; - errCode = SSL_ERROR_UNSAFE_NEGOTIATION; - goto alert_loser; + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { + desc = handshake_failure; + errCode = SSL_ERROR_UNSAFE_NEGOTIATION; + goto alert_loser; } ss->ssl3.hs.compression = ssl_compression_null; - ss->sec.send = ssl3_SendApplicationData; + ss->sec.send = ssl3_SendApplicationData; /* we don't even search for a cache hit here. It's just a miss. */ - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); + SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses); sid = ssl3_NewSessionID(ss, PR_TRUE); if (sid == NULL) { - errCode = PORT_GetError(); - goto loser; /* memory error is set. */ + errCode = PORT_GetError(); + goto loser; /* memory error is set. */ } ss->sec.ci.sid = sid; /* do not worry about memory leak of sid since it now belongs to ci */ @@ -9129,23 +9484,23 @@ suite_found: /* We have to update the handshake hashes before we can send stuff */ rv = ssl3_UpdateHandshakeHashes(ss, buffer, length); if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; + errCode = PORT_GetError(); + goto loser; } ssl_GetXmitBufLock(ss); rv = ssl3_SendServerHelloSequence(ss); ssl_ReleaseXmitBufLock(ss); if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; + errCode = PORT_GetError(); + goto loser; } - /* XXX_1 The call stack to here is: + /* XXX_1 The call stack to here is: * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here. * ssl2_HandleClientHelloMessage returns whatever we return here. * ssl_Do1stHandshake will continue looping if it gets back either - * SECSuccess or SECWouldBlock. + * SECSuccess or SECWouldBlock. * SECSuccess is preferable here. See XXX_1 in sslgathr.c. */ ssl_ReleaseSSL3HandshakeLock(ss); @@ -9162,39 +9517,40 @@ loser: /* The negotiated version number has been already placed in ss->version. ** ** Called from: ssl3_HandleClientHello (resuming session), -** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), -** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) +** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), +** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) */ SECStatus ssl3_SendServerHello(sslSocket *ss) { sslSessionID *sid; - SECStatus rv; - PRUint32 maxBytes = 65535; - PRUint32 length; - PRInt32 extensions_len = 0; + SECStatus rv; + PRUint32 maxBytes = 65535; + PRUint32 length; + PRInt32 extensions_len = 0; SSL3ProtocolVersion version; SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), - ss->fd)); + ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (!IS_DTLS(ss)) { - PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); + PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); - if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; - } - } else { - PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); + if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return SECFailure; + } + } + else { + PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); - if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; - } + if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return SECFailure; + } } sid = ss->sec.ci.sid; @@ -9202,13 +9558,13 @@ ssl3_SendServerHello(sslSocket *ss) extensions_len = ssl3_CallHelloExtensionSenders( ss, PR_FALSE, maxBytes, &ss->xtnData.serverHelloSenders[0]); if (extensions_len > 0) - extensions_len += 2; /* Add sizeof total extension length */ + extensions_len += 2; /* Add sizeof total extension length */ /* TLS 1.3 doesn't use the session_id or compression_method * fields in the ServerHello. */ length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH; if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { - length += 1 + ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength); + length += 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength); } length += sizeof(ssl3CipherSuite); if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { @@ -9218,67 +9574,69 @@ ssl3_SendServerHello(sslSocket *ss) rv = ssl3_AppendHandshakeHeader(ss, server_hello, length); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (IS_DTLS(ss)) { - version = dtls_TLSVersionToDTLSVersion(ss->version); - } else { - version = ss->version; + version = dtls_TLSVersionToDTLSVersion(ss->version); + } + else { + version = ss->version; } rv = ssl3_AppendHandshakeNumber(ss, version, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } /* Random already generated in ssl3_HandleClientHello */ rv = ssl3_AppendHandshake( - ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); + ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { if (sid) { rv = ssl3_AppendHandshakeVariable( ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); - } else { + } + else { rv = ssl3_AppendHandshakeNumber(ss, 0, 1); } if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } } rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } } if (extensions_len) { - PRInt32 sent_len; + PRInt32 sent_len; - extensions_len -= 2; - rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); - if (rv != SECSuccess) - return rv; /* err set by ssl3_AppendHandshakeNumber */ - sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, - &ss->xtnData.serverHelloSenders[0]); + extensions_len -= 2; + rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); + if (rv != SECSuccess) + return rv; /* err set by ssl3_AppendHandshakeNumber */ + sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, + &ss->xtnData.serverHelloSenders[0]); PORT_Assert(sent_len == extensions_len); - if (sent_len != extensions_len) { - if (sent_len >= 0) - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } + if (sent_len != extensions_len) { + if (sent_len >= 0) + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } } rv = ssl3_SetupPendingCipherSpec(ss); if (rv != SECSuccess) { - return rv; /* err set by ssl3_SetupPendingCipherSpec */ + return rv; /* err set by ssl3_SetupPendingCipherSpec */ } return SECSuccess; @@ -9286,30 +9644,30 @@ ssl3_SendServerHello(sslSocket *ss) static SECStatus ssl3_PickSignatureHashAlgorithm(sslSocket *ss, - SSLSignatureAndHashAlg* out); + SSLSignatureAndHashAlg *out); static SECStatus ssl3_SendDHServerKeyExchange(sslSocket *ss) { - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - SECStatus rv = SECFailure; - int length; - PRBool isTLS; - SECItem signed_hash = {siBuffer, NULL, 0}; - SSL3Hashes hashes; + const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; + SECStatus rv = SECFailure; + int length; + PRBool isTLS; + SECItem signed_hash = { siBuffer, NULL, 0 }; + SSL3Hashes hashes; SSLSignatureAndHashAlg sigAndHash; SECKEYDHParams dhParam; ssl3KeyPair *keyPair = NULL; - SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ + SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ int certIndex = -1; if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) { - /* TODO: Support DH_anon. It might be sufficient to drop the signature. - See bug 1170510. */ - PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - return SECFailure; + /* TODO: Support DH_anon. It might be sufficient to drop the signature. + See bug 1170510. */ + PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + return SECFailure; } dhParam.prime.data = ss->dheParams->prime.data; @@ -9368,55 +9726,55 @@ ssl3_SendDHServerKeyExchange(sslSocket *ss) rv = ssl3_SignHashes(&hashes, ss->serverCerts[certIndex].SERVERKEY, &signed_hash, isTLS); if (rv != SECSuccess) { - goto loser; /* ssl3_SignHashes has set err. */ + goto loser; /* ssl3_SignHashes has set err. */ } if (signed_hash.data == NULL) { PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); goto loser; } length = 2 + pubKey->u.dh.prime.len + - 2 + pubKey->u.dh.base.len + - 2 + pubKey->u.dh.publicValue.len + - 2 + signed_hash.len; + 2 + pubKey->u.dh.base.len + + 2 + pubKey->u.dh.publicValue.len + + 2 + signed_hash.len; if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - length += 2; + length += 2; } rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data, pubKey->u.dh.prime.len, 2); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data, pubKey->u.dh.base.len, 2); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.publicValue.data, pubKey->u.dh.publicValue.len, 2); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); + if (rv != SECSuccess) { + goto loser; /* err set by AppendHandshake. */ + } } rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, signed_hash.len, 2); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } PORT_Free(signed_hash.data); ss->dheKeyPair = keyPair; @@ -9439,7 +9797,7 @@ loser: * hash combinations. */ static SECStatus ssl3_PickSignatureHashAlgorithm(sslSocket *ss, - SSLSignatureAndHashAlg* out) + SSLSignatureAndHashAlg *out) { PRUint32 policy; unsigned int i, j; @@ -9465,17 +9823,17 @@ ssl3_PickSignatureHashAlgorithm(sslSocket *ss, * indicated support for in their signature_algorithms extension. */ for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { const SSLSignatureAndHashAlg *serverPref = - &ss->ssl3.signatureAlgorithms[i]; - SECOidTag hashOID; + &ss->ssl3.signatureAlgorithms[i]; + SECOidTag hashOID; if (serverPref->sigAlg != out->sigAlg) { continue; } hashOID = ssl3_TLSHashAlgorithmToOID(serverPref->hashAlg); - if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) - && !(policy & NSS_USE_ALG_IN_SSL_KX)) { - /* we ignore hashes we don't support */ - continue; - } + if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) && + !(policy & NSS_USE_ALG_IN_SSL_KX)) { + /* we ignore hashes we don't support */ + continue; + } for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) { const SSLSignatureAndHashAlg *clientPref = &ss->ssl3.hs.clientSigAndHash[j]; @@ -9491,121 +9849,120 @@ ssl3_PickSignatureHashAlgorithm(sslSocket *ss, return SECFailure; } - static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss) { - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - SECStatus rv = SECFailure; - int length; - PRBool isTLS; - SECItem signed_hash = {siBuffer, NULL, 0}; - SSL3Hashes hashes; - SECKEYPublicKey * sdPub; /* public key for step-down */ + const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; + SECStatus rv = SECFailure; + int length; + PRBool isTLS; + SECItem signed_hash = { siBuffer, NULL, 0 }; + SSL3Hashes hashes; + SECKEYPublicKey *sdPub; /* public key for step-down */ SSLSignatureAndHashAlg sigAndHash; SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { - return SECFailure; + return SECFailure; } switch (kea_def->exchKeyType) { - case kt_rsa: - /* Perform SSL Step-Down here. */ - sdPub = ss->stepDownKeyPair->pubKey; - PORT_Assert(sdPub != NULL); - if (!sdPub) { - PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - return SECFailure; - } - rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, - sdPub->u.rsa.modulus, - sdPub->u.rsa.publicExponent, - &ss->ssl3.hs.client_random, - &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - return rv; - } + case kt_rsa: + /* Perform SSL Step-Down here. */ + sdPub = ss->stepDownKeyPair->pubKey; + PORT_Assert(sdPub != NULL); + if (!sdPub) { + PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + return SECFailure; + } + rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, + sdPub->u.rsa.modulus, + sdPub->u.rsa.publicExponent, + &ss->ssl3.hs.client_random, + &ss->ssl3.hs.server_random, + &hashes, ss->opt.bypassPKCS11); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + return rv; + } - isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); - rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, - &signed_hash, isTLS); - if (rv != SECSuccess) { - goto loser; /* ssl3_SignHashes has set err. */ - } - if (signed_hash.data == NULL) { - /* how can this happen and rv == SECSuccess ?? */ - PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto loser; - } - length = 2 + sdPub->u.rsa.modulus.len + - 2 + sdPub->u.rsa.publicExponent.len + - 2 + signed_hash.len; + isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); + rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, + &signed_hash, isTLS); + if (rv != SECSuccess) { + goto loser; /* ssl3_SignHashes has set err. */ + } + if (signed_hash.data == NULL) { + /* how can this happen and rv == SECSuccess ?? */ + PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + goto loser; + } + length = 2 + sdPub->u.rsa.modulus.len + + 2 + sdPub->u.rsa.publicExponent.len + + 2 + signed_hash.len; - if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - length += 2; - } + if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { + length += 2; + } - rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); + if (rv != SECSuccess) { + goto loser; /* err set by AppendHandshake. */ + } - rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, - sdPub->u.rsa.modulus.len, 2); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, + sdPub->u.rsa.modulus.len, 2); + if (rv != SECSuccess) { + goto loser; /* err set by AppendHandshake. */ + } - rv = ssl3_AppendHandshakeVariable( - ss, sdPub->u.rsa.publicExponent.data, - sdPub->u.rsa.publicExponent.len, 2); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendHandshakeVariable( + ss, sdPub->u.rsa.publicExponent.data, + sdPub->u.rsa.publicExponent.len, 2); + if (rv != SECSuccess) { + goto loser; /* err set by AppendHandshake. */ + } - if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } - } + if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { + rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); + if (rv != SECSuccess) { + goto loser; /* err set by AppendHandshake. */ + } + } - rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, - signed_hash.len, 2); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } - PORT_Free(signed_hash.data); - return SECSuccess; + rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, + signed_hash.len, 2); + if (rv != SECSuccess) { + goto loser; /* err set by AppendHandshake. */ + } + PORT_Free(signed_hash.data); + return SECSuccess; - case ssl_kea_dh: { - rv = ssl3_SendDHServerKeyExchange(ss); - return rv; - } + case ssl_kea_dh: { + rv = ssl3_SendDHServerKeyExchange(ss); + return rv; + } #ifndef NSS_DISABLE_ECC - case kt_ecdh: { - rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); - return rv; - } + case kt_ecdh: { + rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); + return rv; + } #endif /* NSS_DISABLE_ECC */ - case kt_null: - default: - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - break; + case kt_null: + default: + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); + break; } loser: - if (signed_hash.data != NULL) - PORT_Free(signed_hash.data); + if (signed_hash.data != NULL) + PORT_Free(signed_hash.data); return SECFailure; } @@ -9655,45 +10012,45 @@ ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calen, SECItem **names, /* ssl3.ca_list is initialized to NULL, and never changed. */ ca_list = ss->ssl3.ca_list; if (!ca_list) { - ca_list = ssl3_server_ca_list; + ca_list = ssl3_server_ca_list; } if (ca_list != NULL) { - *names = ca_list->names; - *nnames = ca_list->nnames; + *names = ca_list->names; + *nnames = ca_list->nnames; } for (i = 0, name = *names; i < *nnames; i++, name++) { - *calen += 2 + name->len; + *calen += 2 + name->len; } } static SECStatus ssl3_SendCertificateRequest(sslSocket *ss) { - PRBool isTLS12; + PRBool isTLS12; const PRUint8 *certTypes; - SECStatus rv; - int length; - SECItem * names; - int calen; - int nnames; - SECItem * name; - int i; - int certTypesLength; - PRUint8 sigAlgs[MAX_SIGNATURE_ALGORITHMS * 2]; - unsigned int sigAlgsLength = 0; + SECStatus rv; + int length; + SECItem *names; + int calen; + int nnames; + SECItem *name; + int i; + int certTypesLength; + PRUint8 sigAlgs[MAX_SIGNATURE_ALGORITHMS * 2]; + unsigned int sigAlgsLength = 0; SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames); - certTypes = certificate_types; + certTypes = certificate_types; certTypesLength = sizeof certificate_types; length = 1 + certTypesLength + 2 + calen; @@ -9708,27 +10065,27 @@ ssl3_SendCertificateRequest(sslSocket *ss) rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (isTLS12) { - rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); - if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } } rv = ssl3_AppendHandshakeNumber(ss, calen, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } for (i = 0, name = names; i < nnames; i++, name++) { - rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); - if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } } return SECSuccess; @@ -9740,18 +10097,18 @@ ssl3_SendServerHelloDone(sslSocket *ss) SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_FlushHandshake(ss, 0); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + return rv; /* error code set by ssl3_FlushHandshake */ } return SECSuccess; } @@ -9762,78 +10119,78 @@ ssl3_SendServerHelloDone(sslSocket *ss) */ static SECStatus ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length, - SSL3Hashes *hashes) + SSL3Hashes *hashes) { - SECItem signed_hash = {siBuffer, NULL, 0}; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; - SSL3AlertDescription desc = handshake_failure; - PRBool isTLS, isTLS12; + SECItem signed_hash = { siBuffer, NULL, 0 }; + SECStatus rv; + int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; + SSL3AlertDescription desc = handshake_failure; + PRBool isTLS, isTLS12; SSLSignatureAndHashAlg sigAndHash; SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake", - SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + SSL_GETPID(), ss->fd)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); if (ss->ssl3.hs.ws != wait_cert_verify) { - desc = unexpected_message; - errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; - goto alert_loser; + desc = unexpected_message; + errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; + goto alert_loser; } if (!hashes) { PORT_Assert(0); - desc = internal_error; - errCode = SEC_ERROR_LIBRARY_FAILURE; - goto alert_loser; + desc = internal_error; + errCode = SEC_ERROR_LIBRARY_FAILURE; + goto alert_loser; } if (isTLS12) { - rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, - &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* malformed or unsupported. */ - } - rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( + rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, + &sigAndHash); + if (rv != SECSuccess) { + goto loser; /* malformed or unsupported. */ + } + rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( ss, &sigAndHash, ss->sec.peerCert); - if (rv != SECSuccess) { - errCode = PORT_GetError(); - desc = decrypt_error; - goto alert_loser; - } + if (rv != SECSuccess) { + errCode = PORT_GetError(); + desc = decrypt_error; + goto alert_loser; + } - /* We only support CertificateVerify messages that use the handshake - * hash. */ + /* We only support CertificateVerify messages that use the handshake + * hash. */ if (sigAndHash.hashAlg != hashes->hashAlg) { - errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; - desc = decrypt_error; - goto alert_loser; - } + errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; + desc = decrypt_error; + goto alert_loser; + } } rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed. */ + goto loser; /* malformed. */ } /* XXX verify that the key & kea match */ rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash, - isTLS, ss->pkcs11PinArg); + isTLS, ss->pkcs11PinArg); if (rv != SECSuccess) { - errCode = PORT_GetError(); - desc = isTLS ? decrypt_error : handshake_failure; - goto alert_loser; + errCode = PORT_GetError(); + desc = isTLS ? decrypt_error : handshake_failure; + goto alert_loser; } signed_hash.data = NULL; if (length != 0) { - desc = isTLS ? decode_error : illegal_parameter; - goto alert_loser; /* malformed */ + desc = isTLS ? decode_error : illegal_parameter; + goto alert_loser; /* malformed */ } ss->ssl3.hs.ws = wait_change_cipher; return SECSuccess; @@ -9845,77 +10202,77 @@ loser: return SECFailure; } - /* find a slot that is able to generate a PMS and wrap it with RSA. * Then generate and return the PMS. * If the serverKeySlot parameter is non-null, this function will use * that slot to do the job, otherwise it will find a slot. * * Called from ssl3_DeriveConnectionKeysPKCS11() (above) - * sendRSAClientKeyExchange() (above) - * ssl3_HandleRSAClientKeyExchange() (below) + * sendRSAClientKeyExchange() (above) + * ssl3_HandleRSAClientKeyExchange() (below) * Caller must hold the SpecWriteLock, the SSL3HandshakeLock */ static PK11SymKey * ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, - PK11SlotInfo * serverKeySlot) + PK11SlotInfo *serverKeySlot) { - PK11SymKey * pms = NULL; - PK11SlotInfo * slot = serverKeySlot; - void * pwArg = ss->pkcs11PinArg; - SECItem param; - CK_VERSION version; + PK11SymKey *pms = NULL; + PK11SlotInfo *slot = serverKeySlot; + void *pwArg = ss->pkcs11PinArg; + SECItem param; + CK_VERSION version; CK_MECHANISM_TYPE mechanism_array[3]; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (slot == NULL) { - SSLCipherAlgorithm calg; - /* The specReadLock would suffice here, but we cannot assert on - ** read locks. Also, all the callers who call with a non-null - ** slot already hold the SpecWriteLock. - */ - PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); - PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); + SSLCipherAlgorithm calg; + /* The specReadLock would suffice here, but we cannot assert on + ** read locks. Also, all the callers who call with a non-null + ** slot already hold the SpecWriteLock. + */ + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); calg = spec->cipher_def->calg; - /* First get an appropriate slot. */ - mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; - mechanism_array[1] = CKM_RSA_PKCS; - mechanism_array[2] = ssl3_Alg2Mech(calg); + /* First get an appropriate slot. */ + mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; + mechanism_array[1] = CKM_RSA_PKCS; + mechanism_array[2] = ssl3_Alg2Mech(calg); - slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); - if (slot == NULL) { - /* can't find a slot with all three, find a slot with the minimum */ - slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); - if (slot == NULL) { - PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); - return pms; /* which is NULL */ - } - } + slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); + if (slot == NULL) { + /* can't find a slot with all three, find a slot with the minimum */ + slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); + if (slot == NULL) { + PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); + return pms; /* which is NULL */ + } + } } /* Generate the pre-master secret ... */ if (IS_DTLS(ss)) { - SSL3ProtocolVersion temp; + SSL3ProtocolVersion temp; - temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); - version.major = MSB(temp); - version.minor = LSB(temp); - } else { - version.major = MSB(ss->clientHelloVersion); - version.minor = LSB(ss->clientHelloVersion); + temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); + version.major = MSB(temp); + version.minor = LSB(temp); + } + else { + version.major = MSB(ss->clientHelloVersion); + version.minor = LSB(ss->clientHelloVersion); } param.data = (unsigned char *)&version; - param.len = sizeof version; + param.len = sizeof version; pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); if (!serverKeySlot) - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); if (pms == NULL) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); } return pms; } @@ -9935,48 +10292,49 @@ ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, static SECStatus ssl3_HandleRSAClientKeyExchange(sslSocket *ss, SSL3Opaque *b, - PRUint32 length, - SECKEYPrivateKey *serverKey) + PRUint32 length, + SECKEYPrivateKey *serverKey) { #ifndef NO_PKCS11_BYPASS - unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; - unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; - ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; - unsigned int outLen = 0; - PRBool isTLS = PR_FALSE; - SECItem pmsItem = {siBuffer, NULL, 0}; - unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; + unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; + unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; + unsigned int outLen = 0; + PRBool isTLS = PR_FALSE; + SECItem pmsItem = { siBuffer, NULL, 0 }; + unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; #endif - SECStatus rv; - SECItem enc_pms; + SECStatus rv; + SECItem enc_pms; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); enc_pms.data = b; - enc_pms.len = length; + enc_pms.len = length; #ifndef NO_PKCS11_BYPASS pmsItem.data = rsaPmsBuf; - pmsItem.len = sizeof rsaPmsBuf; + pmsItem.len = sizeof rsaPmsBuf; #endif if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ - PRInt32 kLen; - kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); - if (kLen < 0) { - PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - return SECFailure; - } - if ((unsigned)kLen < enc_pms.len) { - enc_pms.len = kLen; - } + PRInt32 kLen; + kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); + if (kLen < 0) { + PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + return SECFailure; + } + if ((unsigned)kLen < enc_pms.len) { + enc_pms.len = kLen; + } #ifndef NO_PKCS11_BYPASS - isTLS = PR_TRUE; + isTLS = PR_TRUE; #endif - } else { + } + else { #ifndef NO_PKCS11_BYPASS - isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); + isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); #endif } @@ -9989,54 +10347,56 @@ ssl3_HandleRSAClientKeyExchange(sslSocket *ss, PORT_Assert( !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)); - /* TRIPLE BYPASS, get PMS directly from RSA decryption. - * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, - * then, check for version rollback attack, then - * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in - * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with - * ss and NULL, so that it will use the MS we've already derived here. - */ + /* TRIPLE BYPASS, get PMS directly from RSA decryption. + * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, + * then, check for version rollback attack, then + * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in + * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with + * ss and NULL, so that it will use the MS we've already derived here. + */ - rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, - sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); - if (rv != SECSuccess) { - /* triple bypass failed. Let's try for a double bypass. */ - goto double_bypass; - } else if (ss->opt.detectRollBack) { - SSL3ProtocolVersion client_version = - (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; + rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, + sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); + if (rv != SECSuccess) { + /* triple bypass failed. Let's try for a double bypass. */ + goto double_bypass; + } + else if (ss->opt.detectRollBack) { + SSL3ProtocolVersion client_version = + (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; - if (IS_DTLS(ss)) { - client_version = dtls_DTLSVersionToTLSVersion(client_version); - } + if (IS_DTLS(ss)) { + client_version = dtls_DTLSVersionToTLSVersion(client_version); + } - if (client_version != ss->clientHelloVersion) { - /* Version roll-back detected. ensure failure. */ - rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); - } - } - /* have PMS, build MS without PKCS11 */ - rv = ssl3_MasterSecretDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, + if (client_version != ss->clientHelloVersion) { + /* Version roll-back detected. ensure failure. */ + rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); + } + } + /* have PMS, build MS without PKCS11 */ + rv = ssl3_MasterSecretDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, PR_TRUE); - if (rv != SECSuccess) { - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; - PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); - } - rv = ssl3_InitPendingCipherSpec(ss, NULL); - } else + if (rv != SECSuccess) { + pwSpec->msItem.data = pwSpec->raw_master_secret; + pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; + PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); + } + rv = ssl3_InitPendingCipherSpec(ss, NULL); + } + else #endif { - PK11SymKey *tmpPms[2] = {NULL, NULL}; + PK11SymKey *tmpPms[2] = { NULL, NULL }; PK11SlotInfo *slot; int useFauxPms = 0; #define currentPms tmpPms[!useFauxPms] -#define unusedPms tmpPms[useFauxPms] -#define realPms tmpPms[1] -#define fauxPms tmpPms[0] +#define unusedPms tmpPms[useFauxPms] +#define realPms tmpPms[1] +#define fauxPms tmpPms[0] #ifndef NO_PKCS11_BYPASS -double_bypass: + double_bypass: #endif /* @@ -10083,18 +10443,18 @@ double_bypass: PK11_FreeSlot(slot); if (fauxPms == NULL) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - return SECFailure; - } + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + return SECFailure; + } - /* - * unwrap pms out of the incoming buffer - * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do - * the unwrap. Rather, it is the mechanism with which the - * unwrapped pms will be used. - */ - realPms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, - CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); + /* + * unwrap pms out of the incoming buffer + * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do + * the unwrap. Rather, it is the mechanism with which the + * unwrapped pms will be used. + */ + realPms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, + CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); /* Temporarily use the PMS if unwrapping the real PMS fails. */ useFauxPms |= (realPms == NULL); @@ -10113,14 +10473,14 @@ double_bypass: PK11_FreeSymKey(unusedPms); } - /* This step will derive the MS from the PMS, among other things. */ + /* This step will derive the MS from the PMS, among other things. */ rv = ssl3_InitPendingCipherSpec(ss, currentPms); PK11_FreeSymKey(currentPms); } if (rv != SECSuccess) { - SEND_ALERT - return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ + SEND_ALERT + return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ } #undef currentPms @@ -10138,15 +10498,15 @@ ssl3_HandleDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *srvrPubKey, SECKEYPrivateKey *serverKey) { - PK11SymKey *pms; - SECStatus rv; - SECKEYPublicKey clntPubKey; - CK_MECHANISM_TYPE target; - PRBool isTLS; + PK11SymKey *pms; + SECStatus rv; + SECKEYPublicKey clntPubKey; + CK_MECHANISM_TYPE target; + PRBool isTLS; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( srvrPubKey ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(srvrPubKey); clntPubKey.keyType = dhKey; clntPubKey.u.dh.prime.len = srvrPubKey->u.dh.prime.len; @@ -10155,26 +10515,29 @@ ssl3_HandleDHClientKeyExchange(sslSocket *ss, clntPubKey.u.dh.base.data = srvrPubKey->u.dh.base.data; rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue, - 2, &b, &length); + 2, &b, &length); if (rv != SECSuccess) { - goto loser; + goto loser; } isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); - if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH; - else target = CKM_SSL3_MASTER_KEY_DERIVE_DH; + if (isTLS) + target = CKM_TLS_MASTER_KEY_DERIVE_DH; + else + target = CKM_SSL3_MASTER_KEY_DERIVE_DH; /* Determine the PMS */ pms = PK11_PubDerive(serverKey, &clntPubKey, PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); if (pms == NULL) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } - rv = ssl3_InitPendingCipherSpec(ss, pms); - PK11_FreeSymKey(pms); pms = NULL; + rv = ssl3_InitPendingCipherSpec(ss, pms); + PK11_FreeSymKey(pms); + pms = NULL; loser: if (ss->dheKeyPair) { @@ -10184,7 +10547,6 @@ loser: return rv; } - /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered * a complete ssl3 ClientKeyExchange message from the remote client * Caller must hold Handshake and RecvBuf locks. @@ -10192,40 +10554,42 @@ loser: static SECStatus ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - SECKEYPrivateKey *serverKey = NULL; - SECStatus rv; + SECKEYPrivateKey *serverKey = NULL; + SECStatus rv; const ssl3KEADef *kea_def; - ssl3KeyPair *serverKeyPair = NULL; - SECKEYPublicKey *serverPubKey = NULL; + ssl3KeyPair *serverKeyPair = NULL; + SECKEYPublicKey *serverPubKey = NULL; SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange 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) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->ssl3.hs.ws != wait_client_key) { - SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); - return SECFailure; + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); + return SECFailure; } - kea_def = ss->ssl3.hs.kea_def; + kea_def = ss->ssl3.hs.kea_def; if (ss->ssl3.hs.usedStepDownKey) { - PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ - && kea_def->exchKeyType == kt_rsa - && ss->stepDownKeyPair != NULL); - if (!kea_def->is_limited || - kea_def->exchKeyType != kt_rsa || - ss->stepDownKeyPair == NULL) { - /* shouldn't happen, don't use step down if it does */ - goto skip; - } - serverKeyPair = ss->stepDownKeyPair; - ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; - } else -skip: + PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ + && + kea_def->exchKeyType == kt_rsa && + ss->stepDownKeyPair != NULL); + if (!kea_def->is_limited || + kea_def->exchKeyType != kt_rsa || + ss->stepDownKeyPair == NULL) { + /* shouldn't happen, don't use step down if it does */ + goto skip; + } + serverKeyPair = ss->stepDownKeyPair; + ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; + } + else + skip: if (kea_def->kea == kea_dhe_dss || kea_def->kea == kea_dhe_rsa) { if (ss->dheKeyPair) { @@ -10235,104 +10599,105 @@ skip: SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); } } - } else + } + else #ifndef NSS_DISABLE_ECC - /* XXX Using SSLKEAType to index server certifiates - * does not work for (EC)DHE ciphers. Until we have - * an indexing mechanism general enough for all key - * exchange algorithms, we'll need to deal with each - * one seprately. - */ - if ((kea_def->kea == kea_ecdhe_rsa) || - (kea_def->kea == kea_ecdhe_ecdsa)) { - if (ss->ephemeralECDHKeyPair != NULL) { - serverKeyPair = ss->ephemeralECDHKeyPair; - if (serverKeyPair->pubKey) { - ss->sec.keaKeyBits = - SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); - } - } - } else + /* XXX Using SSLKEAType to index server certifiates + * does not work for (EC)DHE ciphers. Until we have + * an indexing mechanism general enough for all key + * exchange algorithms, we'll need to deal with each + * one seprately. + */ + if ((kea_def->kea == kea_ecdhe_rsa) || + (kea_def->kea == kea_ecdhe_ecdsa)) { + if (ss->ephemeralECDHKeyPair != NULL) { + serverKeyPair = ss->ephemeralECDHKeyPair; + if (serverKeyPair->pubKey) { + ss->sec.keaKeyBits = + SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); + } + } + } + else #endif { - sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType; - serverKeyPair = sc->serverKeyPair; - ss->sec.keaKeyBits = sc->serverKeyBits; + sslServerCerts *sc = ss->serverCerts + kea_def->exchKeyType; + serverKeyPair = sc->serverKeyPair; + ss->sec.keaKeyBits = sc->serverKeyBits; } if (serverKeyPair) { - serverKey = serverKeyPair->privKey; + serverKey = serverKeyPair->privKey; } if (serverKey == NULL) { - SEND_ALERT - PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); - return SECFailure; + SEND_ALERT + PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); + return SECFailure; } - ss->sec.keaType = kea_def->exchKeyType; + ss->sec.keaType = kea_def->exchKeyType; switch (kea_def->exchKeyType) { - case kt_rsa: - rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); - if (rv != SECSuccess) { - SEND_ALERT - return SECFailure; /* error code set */ - } - break; + case kt_rsa: + rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); + if (rv != SECSuccess) { + SEND_ALERT + return SECFailure; /* error code set */ + } + break; - case ssl_kea_dh: - if (ss->dheKeyPair && ss->dheKeyPair->pubKey) { - serverPubKey = ss->dheKeyPair->pubKey; - } - if (!serverPubKey) { - PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; - } - rv = ssl3_HandleDHClientKeyExchange(ss, b, length, - serverPubKey, serverKey); - if (rv != SECSuccess) { - SSL3_SendAlert(ss, alert_fatal, handshake_failure); - return SECFailure; /* error code set */ - } - break; + case ssl_kea_dh: + if (ss->dheKeyPair && ss->dheKeyPair->pubKey) { + serverPubKey = ss->dheKeyPair->pubKey; + } + if (!serverPubKey) { + PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); + return SECFailure; + } + rv = ssl3_HandleDHClientKeyExchange(ss, b, length, + serverPubKey, serverKey); + if (rv != SECSuccess) { + SSL3_SendAlert(ss, alert_fatal, handshake_failure); + return SECFailure; /* error code set */ + } + break; #ifndef NSS_DISABLE_ECC - case kt_ecdh: - /* XXX We really ought to be able to store multiple - * EC certs (a requirement if we wish to support both - * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). - * When we make that change, we'll need an index other - * than kt_ecdh to pick the right EC certificate. - */ - if (serverKeyPair) { - serverPubKey = serverKeyPair->pubKey; - } - if (serverPubKey == NULL) { - /* XXX Is this the right error code? */ - PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; - } - rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, - serverPubKey, serverKey); - if (ss->ephemeralECDHKeyPair) { - ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair); - ss->ephemeralECDHKeyPair = NULL; - } - if (rv != SECSuccess) { - return SECFailure; /* error code set */ - } - break; + case kt_ecdh: + /* XXX We really ought to be able to store multiple + * EC certs (a requirement if we wish to support both + * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). + * When we make that change, we'll need an index other + * than kt_ecdh to pick the right EC certificate. + */ + if (serverKeyPair) { + serverPubKey = serverKeyPair->pubKey; + } + if (serverPubKey == NULL) { + /* XXX Is this the right error code? */ + PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); + return SECFailure; + } + rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, + serverPubKey, serverKey); + if (ss->ephemeralECDHKeyPair) { + ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair); + ss->ephemeralECDHKeyPair = NULL; + } + if (rv != SECSuccess) { + return SECFailure; /* error code set */ + } + break; #endif /* NSS_DISABLE_ECC */ - default: - (void) ssl3_HandshakeFailure(ss); - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; + default: + (void)ssl3_HandshakeFailure(ss); + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); + return SECFailure; } ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; return SECSuccess; - } /* This is TLS's equivalent of sending a no_certificate alert. */ @@ -10371,18 +10736,18 @@ ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) SECItem ticketData; SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket 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) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket); if (ss->ssl3.hs.ws != wait_new_session_ticket) { - SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); - return SECFailure; + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); + return SECFailure; } /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid @@ -10391,28 +10756,28 @@ ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) */ ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(); if (length < 4) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); - return SECFailure; + (void)SSL3_SendAlert(ss, alert_fatal, decode_error); + PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); + return SECFailure; } ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = - (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); + (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length); if (rv != SECSuccess || length != 0) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); - return SECFailure; /* malformed */ + (void)SSL3_SendAlert(ss, alert_fatal, decode_error); + PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); + return SECFailure; /* malformed */ } /* If the server sent a zero-length ticket, ignore it and keep the * existing ticket. */ if (ticketData.len != 0) { - rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, - &ticketData); - if (rv != SECSuccess) { - return rv; - } - ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; + rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, + &ticketData); + if (rv != SECSuccess) { + return rv; + } + ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; } ss->ssl3.hs.ws = wait_change_cipher; @@ -10422,54 +10787,54 @@ ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) #ifdef NISCC_TEST static PRInt32 connNum = 0; -static SECStatus +static SECStatus get_fake_cert(SECItem *pCertItem, int *pIndex) { PRFileDesc *cf; - char * testdir; - char * startat; - char * stopat; + char *testdir; + char *startat; + char *stopat; const char *extension; - int fileNum; - PRInt32 numBytes = 0; - PRStatus prStatus; - PRFileInfo info; - char cfn[100]; + int fileNum; + PRInt32 numBytes = 0; + PRStatus prStatus; + PRFileInfo info; + char cfn[100]; pCertItem->data = 0; if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) { - return SECSuccess; + return SECSuccess; } - *pIndex = (NULL != strstr(testdir, "root")); + *pIndex = (NULL != strstr(testdir, "root")); extension = (strstr(testdir, "simple") ? "" : ".der"); - fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; + fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; if ((startat = PR_GetEnvSecure("START_AT")) != NULL) { - fileNum += atoi(startat); + fileNum += atoi(startat); } - if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL && - fileNum >= atoi(stopat)) { - *pIndex = -1; - return SECSuccess; + if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL && + fileNum >= atoi(stopat)) { + *pIndex = -1; + return SECSuccess; } sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension); cf = PR_Open(cfn, PR_RDONLY, 0); if (!cf) { - goto loser; + goto loser; } prStatus = PR_GetOpenFileInfo(cf, &info); if (prStatus != PR_SUCCESS) { - PR_Close(cf); - goto loser; + PR_Close(cf); + goto loser; } pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); if (pCertItem) { - numBytes = PR_Read(cf, pCertItem->data, info.size); + numBytes = PR_Read(cf, pCertItem->data, info.size); } PR_Close(cf); if (numBytes != info.size) { - SECITEM_FreeItem(pCertItem, PR_FALSE); - PORT_SetError(SEC_ERROR_IO); - goto loser; + SECITEM_FreeItem(pCertItem, PR_FALSE); + PORT_SetError(SEC_ERROR_IO); + goto loser; } fprintf(stderr, "using %s\n", cfn); return SECSuccess; @@ -10488,51 +10853,53 @@ loser: SECStatus ssl3_SendCertificate(sslSocket *ss) { - SECStatus rv; + SECStatus rv; CERTCertificateList *certChain; - int certChainLen = 0; - int i; - SSL3KEAType certIndex; + int certChainLen = 0; + int i; + SSL3KEAType certIndex; #ifdef NISCC_TEST - SECItem fakeCert; - int ndex = -1; + SECItem fakeCert; + int ndex = -1; #endif - PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; - unsigned int contextLen = 0; + PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; + unsigned int contextLen = 0; SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->sec.localCert) - CERT_DestroyCertificate(ss->sec.localCert); + CERT_DestroyCertificate(ss->sec.localCert); if (ss->sec.isServer) { - sslServerCerts * sc = NULL; + sslServerCerts *sc = NULL; - /* XXX SSLKEAType isn't really a good choice for - * indexing certificates (it breaks when we deal - * with (EC)DHE-* cipher suites. This hack ensures - * the RSA cert is picked for (EC)DHE-RSA. - * Revisit this when we add server side support - * for ECDHE-ECDSA or client-side authentication - * using EC certificates. - */ - if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || - (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { - certIndex = kt_rsa; - } else { - certIndex = ss->ssl3.hs.kea_def->exchKeyType; - } - sc = ss->serverCerts + certIndex; - certChain = sc->serverCertChain; - ss->sec.authKeyBits = sc->serverKeyBits; - ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; - ss->sec.localCert = CERT_DupCertificate(sc->serverCert); - } else { - certChain = ss->ssl3.clientCertChain; - ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); + /* XXX SSLKEAType isn't really a good choice for + * indexing certificates (it breaks when we deal + * with (EC)DHE-* cipher suites. This hack ensures + * the RSA cert is picked for (EC)DHE-RSA. + * Revisit this when we add server side support + * for ECDHE-ECDSA or client-side authentication + * using EC certificates. + */ + if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || + (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { + certIndex = kt_rsa; + } + else { + certIndex = ss->ssl3.hs.kea_def->exchKeyType; + } + sc = ss->serverCerts + certIndex; + certChain = sc->serverCertChain; + ss->sec.authKeyBits = sc->serverKeyBits; + ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; + ss->sec.localCert = CERT_DupCertificate(sc->serverCert); + } + else { + certChain = ss->ssl3.clientCertChain; + ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); } #ifdef NISCC_TEST @@ -10540,47 +10907,49 @@ ssl3_SendCertificate(sslSocket *ss) #endif if (isTLS13) { - contextLen = 1; /* Length of the context */ + contextLen = 1; /* Length of the context */ if (!ss->sec.isServer) { contextLen += ss->ssl3.hs.certReqContextLen; } } if (certChain) { - for (i = 0; i < certChain->len; i++) { + for (i = 0; i < certChain->len; i++) { #ifdef NISCC_TEST - if (fakeCert.len > 0 && i == ndex) { - certChainLen += fakeCert.len + 3; - } else { - certChainLen += certChain->certs[i].len + 3; - } + if (fakeCert.len > 0 && i == ndex) { + certChainLen += fakeCert.len + 3; + } + else { + certChainLen += certChain->certs[i].len + 3; + } #else - certChainLen += certChain->certs[i].len + 3; + certChainLen += certChain->certs[i].len + 3; #endif - } + } } rv = ssl3_AppendHandshakeHeader(ss, certificate, contextLen + certChainLen + 3); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (isTLS13) { if (ss->sec.isServer) { rv = ssl3_AppendHandshakeNumber(ss, 0, 1); - } else { + } + else { rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.hs.certReqContext, ss->ssl3.hs.certReqContextLen, 1); } if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } } rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (certChain) { for (i = 0; i < certChain->len; i++) { @@ -10589,7 +10958,8 @@ ssl3_SendCertificate(sslSocket *ss) rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data, fakeCert.len, 3); SECITEM_FreeItem(&fakeCert, PR_FALSE); - } else { + } + else { rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, certChain->certs[i].len, 3); } @@ -10598,7 +10968,7 @@ ssl3_SendCertificate(sslSocket *ss) certChain->certs[i].len, 3); #endif if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } } } @@ -10619,45 +10989,46 @@ ssl3_SendCertificateStatus(sslSocket *ss) SSL3KEAType certIndex; SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->sec.isServer); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->sec.isServer); if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) - return SECSuccess; + return SECSuccess; /* Use certStatus based on the cert being used. */ if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || - (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { - certIndex = kt_rsa; - } else { - certIndex = ss->ssl3.hs.kea_def->exchKeyType; + (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { + certIndex = kt_rsa; + } + else { + certIndex = ss->ssl3.hs.kea_def->exchKeyType; } if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) { - statusToSend = ss->certStatusArray[certIndex]; + statusToSend = ss->certStatusArray[certIndex]; } if (!statusToSend) - return SECSuccess; + return SECSuccess; /* Use the array's first item only (single stapling) */ len = 1 + statusToSend->items[0].len + 3; rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); if (rv != SECSuccess) - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ rv = ssl3_AppendHandshakeVariable(ss, - statusToSend->items[0].data, - statusToSend->items[0].len, - 3); + statusToSend->items[0].data, + statusToSend->items[0].len, + 3); if (rv != SECSuccess) - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ return SECSuccess; } @@ -10668,13 +11039,14 @@ ssl3_SendCertificateStatus(sslSocket *ss) static void ssl3_CleanupPeerCerts(sslSocket *ss) { - PLArenaPool * arena = ss->ssl3.peerCertArena; + PLArenaPool *arena = ss->ssl3.peerCertArena; ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain; for (; certs; certs = certs->next) { - CERT_DestroyCertificate(certs->cert); + CERT_DestroyCertificate(certs->cert); } - if (arena) PORT_FreeArena(arena, PR_FALSE); + if (arena) + PORT_FreeArena(arena, PR_FALSE); ss->ssl3.peerCertArena = NULL; ss->ssl3.peerCertChain = NULL; } @@ -10710,23 +11082,23 @@ ssl3_CompleteHandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, /* Consume the CertificateStatusType enum */ status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); if (status != 1 /* ocsp */) { - goto format_loser; + goto format_loser; } len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); if (len != length) { - goto format_loser; + goto format_loser; } -#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ +#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ if (length > MAX_CERTSTATUS_LEN) - goto format_loser; + goto format_loser; #undef MAX_CERTSTATUS_LEN /* Array size 1, because we currently implement single-stapling only */ SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1); if (!ss->sec.ci.sid->peerCertStatus.items) - return SECFailure; + return SECFailure; ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length); @@ -10753,9 +11125,9 @@ static SECStatus ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake", - SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + SSL_GETPID(), ss->fd)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) || (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) { @@ -10772,24 +11144,24 @@ ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) SECStatus ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - ssl3CertNode * c; - ssl3CertNode * lastCert = NULL; - PRInt32 remaining = 0; - PRInt32 size; - SECStatus rv; - PRBool isServer = (PRBool)(!!ss->sec.isServer); - PRBool isTLS; + ssl3CertNode *c; + ssl3CertNode *lastCert = NULL; + PRInt32 remaining = 0; + PRInt32 size; + SECStatus rv; + PRBool isServer = (PRBool)(!!ss->sec.isServer); + PRBool isTLS; SSL3AlertDescription desc; - int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; - SECItem certItem; + int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; + SECItem certItem; if (ss->sec.peerCert != NULL) { - if (ss->sec.peerKey) { - SECKEY_DestroyPublicKey(ss->sec.peerKey); - ss->sec.peerKey = NULL; - } - CERT_DestroyCertificate(ss->sec.peerCert); - ss->sec.peerCert = NULL; + if (ss->sec.peerKey) { + SECKEY_DestroyPublicKey(ss->sec.peerKey); + ss->sec.peerKey = NULL; + } + CERT_DestroyCertificate(ss->sec.peerCert); + ss->sec.peerCert = NULL; } ssl3_CleanupPeerCerts(ss); @@ -10800,29 +11172,30 @@ ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ** normal no_certificates message to maximize interoperability. */ if (length) { - remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); - if (remaining < 0) - goto loser; /* fatal alert already sent by ConsumeHandshake. */ - if ((PRUint32)remaining > length) - goto decode_loser; + remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); + if (remaining < 0) + goto loser; /* fatal alert already sent by ConsumeHandshake. */ + if ((PRUint32)remaining > length) + goto decode_loser; } if (!remaining) { - if (!(isTLS && isServer)) { - desc = bad_certificate; - goto alert_loser; - } - /* This is TLS's version of a no_certificate alert. */ - /* I'm a server. I've requested a client cert. He hasn't got one. */ - rv = ssl3_HandleNoCertificate(ss); - if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; - } + if (!(isTLS && isServer)) { + desc = bad_certificate; + goto alert_loser; + } + /* This is TLS's version of a no_certificate alert. */ + /* I'm a server. I've requested a client cert. He hasn't got one. */ + rv = ssl3_HandleNoCertificate(ss); + if (rv != SECSuccess) { + errCode = PORT_GetError(); + goto loser; + } if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { ss->ssl3.hs.ws = wait_client_key; - } else { + } + else { TLS13_SET_HS_STATE(ss, wait_finished); } return SECSuccess; @@ -10830,73 +11203,74 @@ ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (ss->ssl3.peerCertArena == NULL) { - goto loser; /* don't send alerts on memory errors */ + goto loser; /* don't send alerts on memory errors */ } /* First get the peer cert. */ remaining -= 3; if (remaining < 0) - goto decode_loser; + goto decode_loser; size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); if (size <= 0) - goto loser; /* fatal alert already sent by ConsumeHandshake. */ + goto loser; /* fatal alert already sent by ConsumeHandshake. */ if (remaining < size) - goto decode_loser; + goto decode_loser; certItem.data = b; certItem.len = size; - b += size; + b += size; length -= size; remaining -= size; ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, - PR_FALSE, PR_TRUE); + PR_FALSE, PR_TRUE); if (ss->sec.peerCert == NULL) { - /* We should report an alert if the cert was bad, but not if the - * problem was just some local problem, like memory error. - */ - goto ambiguous_err; + /* We should report an alert if the cert was bad, but not if the + * problem was just some local problem, like memory error. + */ + goto ambiguous_err; } /* Now get all of the CA certs. */ while (remaining > 0) { - remaining -= 3; - if (remaining < 0) - goto decode_loser; + remaining -= 3; + if (remaining < 0) + goto decode_loser; - size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); - if (size <= 0) - goto loser; /* fatal alert already sent by ConsumeHandshake. */ + size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); + if (size <= 0) + goto loser; /* fatal alert already sent by ConsumeHandshake. */ - if (remaining < size) - goto decode_loser; + if (remaining < size) + goto decode_loser; - certItem.data = b; - certItem.len = size; - b += size; - length -= size; - remaining -= size; + certItem.data = b; + certItem.len = size; + b += size; + length -= size; + remaining -= size; - c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); - if (c == NULL) { - goto loser; /* don't send alerts on memory errors */ - } + c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); + if (c == NULL) { + goto loser; /* don't send alerts on memory errors */ + } - c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, - PR_FALSE, PR_TRUE); - if (c->cert == NULL) { - goto ambiguous_err; - } + c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, + PR_FALSE, PR_TRUE); + if (c->cert == NULL) { + goto ambiguous_err; + } - c->next = NULL; - if (lastCert) { - lastCert->next = c; - } else { - ss->ssl3.peerCertChain = c; - } - lastCert = c; + c->next = NULL; + if (lastCert) { + lastCert->next = c; + } + else { + ss->ssl3.peerCertChain = c; + } + lastCert = c; } if (remaining != 0) @@ -10905,10 +11279,11 @@ ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) SECKEY_UpdateCertPQG(ss->sec.peerCert); if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { - ss->ssl3.hs.ws = wait_certificate_status; - rv = SECSuccess; - } else { - rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ + ss->ssl3.hs.ws = wait_certificate_status; + rv = SECSuccess; + } + else { + rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ } return rv; @@ -10916,14 +11291,14 @@ ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ambiguous_err: errCode = PORT_GetError(); switch (errCode) { - case PR_OUT_OF_MEMORY_ERROR: - case SEC_ERROR_BAD_DATABASE: - case SEC_ERROR_NO_MEMORY: - if (isTLS) { - desc = internal_error; - goto alert_loser; - } - goto loser; + case PR_OUT_OF_MEMORY_ERROR: + case SEC_ERROR_BAD_DATABASE: + case SEC_ERROR_NO_MEMORY: + if (isTLS) { + desc = internal_error; + goto alert_loser; + } + goto loser; } ssl3_SendAlertForCertError(ss, errCode); goto loser; @@ -10942,9 +11317,9 @@ loser: static SECStatus ssl3_AuthCertificate(sslSocket *ss) { - SECStatus rv; - PRBool isServer = (PRBool)(!!ss->sec.isServer); - int errCode; + SECStatus rv; + PRBool isServer = (PRBool)(!!ss->sec.isServer); + int errCode; ss->ssl3.hs.authCertificatePending = PR_FALSE; @@ -10953,37 +11328,37 @@ ssl3_AuthCertificate(sslSocket *ss) /* * Ask caller-supplied callback function to validate cert chain. */ - rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, - PR_TRUE, isServer); + rv = (SECStatus) (*ss->authCertificate)(ss->authCertificateArg, ss->fd, + PR_TRUE, isServer); if (rv != SECSuccess) { - errCode = PORT_GetError(); - if (rv != SECWouldBlock) { - if (ss->handleBadCert) { - rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); - } - } + errCode = PORT_GetError(); + if (rv != SECWouldBlock) { + if (ss->handleBadCert) { + rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); + } + } - if (rv == SECWouldBlock) { - if (ss->sec.isServer) { - errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; - rv = SECFailure; - goto loser; - } + if (rv == SECWouldBlock) { + if (ss->sec.isServer) { + errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; + rv = SECFailure; + goto loser; + } /* TODO(ekr@rtfm.com): Reenable for TLS 1.3 */ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION; rv = SECFailure; - goto loser; + goto loser; } - ss->ssl3.hs.authCertificatePending = PR_TRUE; - rv = SECSuccess; - } + ss->ssl3.hs.authCertificatePending = PR_TRUE; + rv = SECSuccess; + } - if (rv != SECSuccess) { - ssl3_SendAlertForCertError(ss, errCode); - goto loser; - } + if (rv != SECSuccess) { + ssl3_SendAlertForCertError(ss, errCode); + goto loser; + } } ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); @@ -10991,63 +11366,73 @@ ssl3_AuthCertificate(sslSocket *ss) if (!ss->sec.isServer) { CERTCertificate *cert = ss->sec.peerCert; - /* set the server authentication type and size from the value + /* set the server authentication type and size from the value ** in the cert. */ - SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert); - ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; - ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; - if (pubKey) { - KeyType pubKeyType; - PRInt32 minKey; + SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(cert); + ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; + if (pubKey) { + KeyType pubKeyType; + PRInt32 minKey; /* This partly fixes Bug 124230 and may cause problems for * callers which depend on the old (wrong) behavior. */ ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey); pubKeyType = SECKEY_GetPublicKeyType(pubKey); - minKey = ss->sec.authKeyBits; - switch (pubKeyType) { - case rsaKey: - case rsaPssKey: - case rsaOaepKey: - rv = NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minKey); - if (rv != SECSuccess) { - minKey = SSL_RSA_MIN_MODULUS_BITS; - } - break; - case dsaKey: - rv = NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minKey); - if (rv != SECSuccess) { - minKey = SSL_DSA_MIN_P_BITS; - } - break; - case dhKey: - rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minKey); - if (rv != SECSuccess) { - minKey = SSL_DH_MIN_P_BITS; - } - break; - default: - break; - } + minKey = ss->sec.authKeyBits; + switch (pubKeyType) { + case rsaKey: + case rsaPssKey: + case rsaOaepKey: + rv = + NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minKey); + if (rv != + SECSuccess) { + minKey = + SSL_RSA_MIN_MODULUS_BITS; + } + break; + case dsaKey: + rv = + NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minKey); + if (rv != + SECSuccess) { + minKey = + SSL_DSA_MIN_P_BITS; + } + break; + case dhKey: + rv = + NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minKey); + if (rv != + SECSuccess) { + minKey = + SSL_DH_MIN_P_BITS; + } + break; + default: + break; + } /* Too small: not good enough. Send a fatal alert. */ /* We aren't checking EC here on the understanding that we only * support curves we like, a decision that might need revisiting. */ - if ( ss->sec.authKeyBits < minKey) { + if (ss->sec.authKeyBits < minKey) { PORT_SetError(SSL_ERROR_WEAK_SERVER_CERT_KEY); (void)SSL3_SendAlert(ss, alert_fatal, ss->version >= SSL_LIBRARY_VERSION_TLS_1_0 - ? insufficient_security - : illegal_parameter); + ? insufficient_security + : illegal_parameter); SECKEY_DestroyPublicKey(pubKey); return SECFailure; } - SECKEY_DestroyPublicKey(pubKey); - pubKey = NULL; - } + SECKEY_DestroyPublicKey(pubKey); + pubKey = NULL; + } if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { TLS13_SET_HS_STATE(ss, wait_cert_verify); - } else { + } + else { /* Ephemeral suites require ServerKeyExchange. Export cipher suites * with RSA key exchange also require ServerKeyExchange if the * authentication key exceeds the key size limit. */ @@ -11057,7 +11442,8 @@ ssl3_AuthCertificate(sslSocket *ss) ss->sec.authKeyBits > ss->ssl3.hs.kea_def->key_size_limit)) { /* require server_key_exchange */ ss->ssl3.hs.ws = wait_server_key; - } else { + } + else { /* disallow server_key_exchange */ ss->ssl3.hs.ws = wait_cert_request; /* This is static RSA key exchange so set the key bits to @@ -11065,20 +11451,22 @@ ssl3_AuthCertificate(sslSocket *ss) ss->sec.keaKeyBits = ss->sec.authKeyBits; } } - } else { + } + else { /* Server */ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { ss->ssl3.hs.ws = wait_client_key; - } else { + } + else { TLS13_SET_HS_STATE(ss, wait_cert_verify); } } PORT_Assert(rv == SECSuccess); if (rv != SECSuccess) { - errCode = SEC_ERROR_LIBRARY_FAILURE; - rv = SECFailure; - goto loser; + errCode = SEC_ERROR_LIBRARY_FAILURE; + rv = SECFailure; + goto loser; } return rv; @@ -11091,7 +11479,7 @@ loser: static SECStatus ssl3_FinishHandshake(sslSocket *ss); static SECStatus -ssl3_AlwaysFail(sslSocket * ss) +ssl3_AlwaysFail(sslSocket *ss) { PORT_SetError(PR_INVALID_STATE_ERROR); return SECFailure; @@ -11107,61 +11495,66 @@ ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); if (ss->sec.isServer) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); - return SECFailure; + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); + return SECFailure; } ssl_GetRecvBufLock(ss); ssl_GetSSL3HandshakeLock(ss); if (!ss->ssl3.hs.authCertificatePending) { - PORT_SetError(PR_INVALID_STATE_ERROR); - rv = SECFailure; - goto done; + PORT_SetError(PR_INVALID_STATE_ERROR); + rv = SECFailure; + goto done; } ss->ssl3.hs.authCertificatePending = PR_FALSE; if (error != 0) { - ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; - ssl3_SendAlertForCertError(ss, error); - rv = SECSuccess; - } else if (ss->ssl3.hs.restartTarget != NULL) { - sslRestartTarget target = ss->ssl3.hs.restartTarget; - ss->ssl3.hs.restartTarget = NULL; + ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; + ssl3_SendAlertForCertError(ss, error); + rv = SECSuccess; + } + else if (ss->ssl3.hs.restartTarget != NULL) { + sslRestartTarget target = ss->ssl3.hs.restartTarget; + ss->ssl3.hs.restartTarget = NULL; - if (target == ssl3_FinishHandshake) { - SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race" - " with peer's finished message", SSL_GETPID(), ss->fd)); - } + if (target == ssl3_FinishHandshake) { + SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race" + " with peer's finished message", + SSL_GETPID(), ss->fd)); + } - rv = target(ss); - /* Even if we blocked here, we have accomplished enough to claim - * success. Any remaining work will be taken care of by subsequent - * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. - */ - if (rv == SECWouldBlock) { - rv = SECSuccess; - } - } else { - SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" - " peer's finished message", SSL_GETPID(), ss->fd)); + rv = target(ss); + /* Even if we blocked here, we have accomplished enough to claim + * success. Any remaining work will be taken care of by subsequent + * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. + */ + if (rv == SECWouldBlock) { + rv = SECSuccess; + } + } + else { + SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" + " peer's finished message", + SSL_GETPID(), ss->fd)); - PORT_Assert(!ss->ssl3.hs.isResuming); - PORT_Assert(ss->ssl3.hs.ws != idle_handshake); + PORT_Assert(!ss->ssl3.hs.isResuming); + PORT_Assert(ss->ssl3.hs.ws != idle_handshake); - if (ss->opt.enableFalseStart && - !ss->firstHsDone && - !ss->ssl3.hs.isResuming && - ssl3_WaitingForServerSecondRound(ss)) { - /* ssl3_SendClientSecondRound deferred the false start check because - * certificate authentication was pending, so we do it now if we still - * haven't received all of the server's second round yet. - */ - rv = ssl3_CheckFalseStart(ss); - } else { - rv = SECSuccess; - } + if (ss->opt.enableFalseStart && + !ss->firstHsDone && + !ss->ssl3.hs.isResuming && + ssl3_WaitingForServerSecondRound(ss)) { + /* ssl3_SendClientSecondRound deferred the false start check because + * certificate authentication was pending, so we do it now if we still + * haven't received all of the server's second round yet. + */ + rv = ssl3_CheckFalseStart(ss); + } + else { + rv = SECSuccess; + } } done: @@ -11173,43 +11566,44 @@ done: static SECStatus ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, - PRBool isServer, - const SSL3Hashes * hashes, - TLSFinished * tlsFinished) + PRBool isServer, + const SSL3Hashes *hashes, + TLSFinished *tlsFinished) { SECStatus rv; CK_TLS_MAC_PARAMS tls_mac_params; - SECItem param = {siBuffer, NULL, 0}; + SECItem param = { siBuffer, NULL, 0 }; PK11Context *prf_context; unsigned int retLen; if (!spec->master_secret || spec->bypassCiphers) { - const char *label = isServer ? "server finished" : "client finished"; - unsigned int len = 15; + const char *label = isServer ? "server finished" : "client finished"; + unsigned int len = 15; - return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, - hashes->len, tlsFinished->verify_data, - sizeof tlsFinished->verify_data); + return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, + hashes->len, tlsFinished->verify_data, + sizeof tlsFinished->verify_data); } if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) { - tls_mac_params.prfMechanism = CKM_TLS_PRF; - } else { - tls_mac_params.prfMechanism = CKM_SHA256; + tls_mac_params.prfMechanism = CKM_TLS_PRF; + } + else { + tls_mac_params.prfMechanism = CKM_SHA256; } tls_mac_params.ulMacLength = 12; tls_mac_params.ulServerOrClient = isServer ? 1 : 2; param.data = (unsigned char *)&tls_mac_params; param.len = sizeof(tls_mac_params); prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN, - spec->master_secret, ¶m); + spec->master_secret, ¶m); if (!prf_context) - return SECFailure; + return SECFailure; - rv = PK11_DigestBegin(prf_context); + rv = PK11_DigestBegin(prf_context); rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len); rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen, - sizeof tlsFinished->verify_data); + sizeof tlsFinished->verify_data); PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data); PK11_DestroyContext(prf_context, PR_TRUE); @@ -11223,54 +11617,56 @@ ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, */ SECStatus ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, - unsigned int labelLen, const unsigned char *val, unsigned int valLen, - unsigned char *out, unsigned int outLen) + unsigned int labelLen, const unsigned char *val, unsigned int valLen, + unsigned char *out, unsigned int outLen) { SECStatus rv = SECSuccess; if (spec->master_secret && !spec->bypassCiphers) { - SECItem param = {siBuffer, NULL, 0}; - CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; - PK11Context *prf_context; - unsigned int retLen; + SECItem param = { siBuffer, NULL, 0 }; + CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; + PK11Context *prf_context; + unsigned int retLen; - if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; - } - prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, - spec->master_secret, ¶m); - if (!prf_context) - return SECFailure; + if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { + mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; + } + prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, + spec->master_secret, ¶m); + if (!prf_context) + return SECFailure; - rv = PK11_DigestBegin(prf_context); - rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen); - rv |= PK11_DigestOp(prf_context, val, valLen); - rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); - PORT_Assert(rv != SECSuccess || retLen == outLen); + rv = PK11_DigestBegin(prf_context); + rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen); + rv |= PK11_DigestOp(prf_context, val, valLen); + rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); + PORT_Assert(rv != SECSuccess || retLen == outLen); - PK11_DestroyContext(prf_context, PR_TRUE); - } else { - /* bypass PKCS11 */ + PK11_DestroyContext(prf_context, PR_TRUE); + } + else { +/* bypass PKCS11 */ #ifdef NO_PKCS11_BYPASS - PORT_Assert(spec->master_secret); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - rv = SECFailure; + PORT_Assert(spec->master_secret); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + rv = SECFailure; #else - SECItem inData = { siBuffer }; - SECItem outData = { siBuffer }; - PRBool isFIPS = PR_FALSE; + SECItem inData = { siBuffer }; + SECItem outData = { siBuffer }; + PRBool isFIPS = PR_FALSE; - inData.data = (unsigned char *) val; - inData.len = valLen; - outData.data = out; - outData.len = outLen; - if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, - &outData, isFIPS); - } else { - rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); - } - PORT_Assert(rv != SECSuccess || outData.len == outLen); + inData.data = (unsigned char *)val; + inData.len = valLen; + outData.data = out; + outData.len = outLen; + if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { + rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, + &outData, isFIPS); + } + else { + rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); + } + PORT_Assert(rv != SECSuccess || outData.len == outLen); #endif } return rv; @@ -11284,31 +11680,32 @@ ssl3_SendNextProto(sslSocket *ss) { SECStatus rv; int padding_len; - static const unsigned char padding[32] = {0}; + static const unsigned char padding[32] = { 0 }; if (ss->ssl3.nextProto.len == 0 || - ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { - return SECSuccess; + ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { + return SECSuccess; } - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32); rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len + - 2 + padding_len); + 2 + + padding_len); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshakeHeader */ + return rv; /* error code set by AppendHandshakeHeader */ } rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, - ss->ssl3.nextProto.len, 1); + ss->ssl3.nextProto.len, 1); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake */ + return rv; /* error code set by AppendHandshake */ } rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake */ + return rv; /* error code set by AppendHandshake */ } return rv; } @@ -11323,28 +11720,28 @@ ssl3_RecordKeyLog(sslSocket *ss) SECStatus rv; SECItem *keyData; char buf[14 /* "CLIENT_RANDOM " */ + - SSL3_RANDOM_LENGTH*2 /* client_random */ + - 1 /* " " */ + - 48*2 /* master secret */ + + SSL3_RANDOM_LENGTH * 2 /* client_random */ + + 1 /* " " */ + + 48 * 2 /* master secret */ + 1 /* new line */]; unsigned int j; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (!ssl_keylog_iob) - return; + return; rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret); if (rv != SECSuccess) - return; + return; ssl_GetSpecReadLock(ss); /* keyData does not need to be freed. */ keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret); if (!keyData || !keyData->data || keyData->len != 48) { - ssl_ReleaseSpecReadLock(ss); - return; + ssl_ReleaseSpecReadLock(ss); + return; } /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ @@ -11356,10 +11753,10 @@ ssl3_RecordKeyLog(sslSocket *ss) memcpy(buf, "CLIENT_RANDOM ", 14); j = 14; hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); - j += SSL3_RANDOM_LENGTH*2; + j += SSL3_RANDOM_LENGTH * 2; buf[j++] = ' '; hexEncode(buf + j, keyData->data, 48); - j += 48*2; + j += 48 * 2; buf[j++] = '\n'; PORT_Assert(j == sizeof(buf)); @@ -11380,59 +11777,60 @@ static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags) { ssl3CipherSpec *cwSpec; - PRBool isTLS; - PRBool isServer = ss->sec.isServer; - SECStatus rv; - SSL3Sender sender = isServer ? sender_server : sender_client; - SSL3Hashes hashes; - TLSFinished tlsFinished; + PRBool isTLS; + PRBool isServer = ss->sec.isServer; + SECStatus rv; + SSL3Sender sender = isServer ? sender_server : sender_client; + SSL3Hashes hashes; + TLSFinished tlsFinished; SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); ssl_GetSpecReadLock(ss); cwSpec = ss->ssl3.cwSpec; isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0); rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender); if (isTLS && rv == SECSuccess) { - rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished); + rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished); } ssl_ReleaseSpecReadLock(ss); if (rv != SECSuccess) { - goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ + goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ } if (isTLS) { - if (isServer) - ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; - else - ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; - ss->ssl3.hs.finishedBytes = sizeof tlsFinished; - rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished); - if (rv != SECSuccess) - goto fail; /* err set by AppendHandshake. */ - rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); - if (rv != SECSuccess) - goto fail; /* err set by AppendHandshake. */ - } else { - if (isServer) - ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; - else - ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; - PORT_Assert(hashes.len == sizeof hashes.u.s); - ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; - rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s); - if (rv != SECSuccess) - goto fail; /* err set by AppendHandshake. */ - rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); - if (rv != SECSuccess) - goto fail; /* err set by AppendHandshake. */ + if (isServer) + ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; + else + ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; + ss->ssl3.hs.finishedBytes = sizeof tlsFinished; + rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished); + if (rv != SECSuccess) + goto fail; /* err set by AppendHandshake. */ + rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); + if (rv != SECSuccess) + goto fail; /* err set by AppendHandshake. */ + } + else { + if (isServer) + ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; + else + ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; + PORT_Assert(hashes.len == sizeof hashes.u.s); + ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; + rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s); + if (rv != SECSuccess) + goto fail; /* err set by AppendHandshake. */ + rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); + if (rv != SECSuccess) + goto fail; /* err set by AppendHandshake. */ } rv = ssl3_FlushHandshake(ss, flags); if (rv != SECSuccess) { - goto fail; /* error code set by ssl3_FlushHandshake */ + goto fail; /* error code set by ssl3_FlushHandshake */ } ssl3_RecordKeyLog(ss); @@ -11448,80 +11846,82 @@ fail: */ SECStatus ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, - ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType) + ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType) { - PK11SymKey * wrappingKey = NULL; - PK11SlotInfo * symKeySlot; - void * pwArg = ss->pkcs11PinArg; - SECStatus rv = SECFailure; - PRBool isServer = ss->sec.isServer; - CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; + PK11SymKey *wrappingKey = NULL; + PK11SlotInfo *symKeySlot; + void *pwArg = ss->pkcs11PinArg; + SECStatus rv = SECFailure; + PRBool isServer = ss->sec.isServer; + CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; symKeySlot = PK11_GetSlotFromKey(spec->master_secret); if (!isServer) { - int wrapKeyIndex; - int incarnation; + int wrapKeyIndex; + int incarnation; - /* these next few functions are mere accessors and don't fail. */ - sid->u.ssl3.masterWrapIndex = wrapKeyIndex = - PK11_GetCurrentWrapIndex(symKeySlot); - PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */ + /* these next few functions are mere accessors and don't fail. */ + sid->u.ssl3.masterWrapIndex = wrapKeyIndex = + PK11_GetCurrentWrapIndex(symKeySlot); + PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */ - sid->u.ssl3.masterWrapSeries = incarnation = - PK11_GetSlotSeries(symKeySlot); - sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); - sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); - sid->u.ssl3.masterValid = PR_TRUE; - /* Get the default wrapping key, for wrapping the master secret before - * placing it in the SID cache entry. */ - wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, - CKM_INVALID_MECHANISM, incarnation, - pwArg); - if (wrappingKey) { - mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ - } else { - int keyLength; - /* if the wrappingKey doesn't exist, attempt to create it. - * Note: we intentionally ignore errors here. If we cannot - * generate a wrapping key, it is not fatal to this SSL connection, - * but we will not be able to restart this session. - */ - mechanism = PK11_GetBestWrapMechanism(symKeySlot); - keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); - /* Zero length means fixed key length algorithm, or error. - * It's ambiguous. - */ - wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, - keyLength, pwArg); - if (wrappingKey) { - PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); - } - } - } else { - /* server socket using session cache. */ - mechanism = PK11_GetBestWrapMechanism(symKeySlot); - if (mechanism != CKM_INVALID_MECHANISM) { - wrappingKey = - getWrappingKey(ss, symKeySlot, effectiveExchKeyType, - mechanism, pwArg); - if (wrappingKey) { - mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ - } - } + sid->u.ssl3.masterWrapSeries = incarnation = + PK11_GetSlotSeries(symKeySlot); + sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); + sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); + sid->u.ssl3.masterValid = PR_TRUE; + /* Get the default wrapping key, for wrapping the master secret before + * placing it in the SID cache entry. */ + wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, + CKM_INVALID_MECHANISM, incarnation, + pwArg); + if (wrappingKey) { + mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ + } + else { + int keyLength; + /* if the wrappingKey doesn't exist, attempt to create it. + * Note: we intentionally ignore errors here. If we cannot + * generate a wrapping key, it is not fatal to this SSL connection, + * but we will not be able to restart this session. + */ + mechanism = PK11_GetBestWrapMechanism(symKeySlot); + keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); + /* Zero length means fixed key length algorithm, or error. + * It's ambiguous. + */ + wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, + keyLength, pwArg); + if (wrappingKey) { + PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); + } + } + } + else { + /* server socket using session cache. */ + mechanism = PK11_GetBestWrapMechanism(symKeySlot); + if (mechanism != CKM_INVALID_MECHANISM) { + wrappingKey = + getWrappingKey(ss, symKeySlot, effectiveExchKeyType, + mechanism, pwArg); + if (wrappingKey) { + mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ + } + } } sid->u.ssl3.masterWrapMech = mechanism; PK11_FreeSlot(symKeySlot); if (wrappingKey) { - SECItem wmsItem; + SECItem wmsItem; - wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; - wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; - rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, - spec->master_secret, &wmsItem); - /* rv is examined below. */ - sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; - PK11_FreeSymKey(wrappingKey); + wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; + wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; + rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, + spec->master_secret, &wmsItem); + /* rv is examined below. */ + sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; + PK11_FreeSymKey(wrappingKey); } return rv; } @@ -11532,196 +11932,199 @@ ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, */ static SECStatus ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, - const SSL3Hashes *hashes) + const SSL3Hashes *hashes) { - sslSessionID * sid = ss->sec.ci.sid; - SECStatus rv = SECSuccess; - PRBool isServer = ss->sec.isServer; - PRBool isTLS; - SSL3KEAType effectiveExchKeyType; + sslSessionID *sid = ss->sec.ci.sid; + SECStatus rv = SECSuccess; + PRBool isServer = ss->sec.isServer; + PRBool isTLS; + SSL3KEAType effectiveExchKeyType; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); if (ss->ssl3.hs.ws != wait_finished) { - SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); - return SECFailure; + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); + return SECFailure; } if (!hashes) { PORT_Assert(0); - SSL3_SendAlert(ss, alert_fatal, internal_error); + SSL3_SendAlert(ss, alert_fatal, internal_error); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); if (isTLS) { - TLSFinished tlsFinished; + TLSFinished tlsFinished; - if (length != sizeof tlsFinished) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); - return SECFailure; - } - rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, - hashes, &tlsFinished); - if (!isServer) - ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; - else - ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; - ss->ssl3.hs.finishedBytes = sizeof tlsFinished; - if (rv != SECSuccess || - 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) { - (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); - PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); - return SECFailure; - } - } else { - if (length != sizeof(SSL3Finished)) { - (void)ssl3_IllegalParameter(ss); - PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); - return SECFailure; - } + if (length != sizeof tlsFinished) { + (void)SSL3_SendAlert(ss, alert_fatal, decode_error); + PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); + return SECFailure; + } + rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, + hashes, &tlsFinished); + if (!isServer) + ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; + else + ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; + ss->ssl3.hs.finishedBytes = sizeof tlsFinished; + if (rv != SECSuccess || + 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) { + (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); + PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); + return SECFailure; + } + } + else { + if (length != sizeof(SSL3Finished)) { + (void)ssl3_IllegalParameter(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); + return SECFailure; + } - if (!isServer) - ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s; - else - ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s; - PORT_Assert(hashes->len == sizeof hashes->u.s); - ss->ssl3.hs.finishedBytes = sizeof hashes->u.s; - if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) { - (void)ssl3_HandshakeFailure(ss); - PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); - return SECFailure; - } + if (!isServer) + ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s; + else + ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s; + PORT_Assert(hashes->len == sizeof hashes->u.s); + ss->ssl3.hs.finishedBytes = sizeof hashes->u.s; + if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) { + (void)ssl3_HandshakeFailure(ss); + PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); + return SECFailure; + } } - ssl_GetXmitBufLock(ss); /*************************************/ + ssl_GetXmitBufLock(ss); /*************************************/ if ((isServer && !ss->ssl3.hs.isResuming) || - (!isServer && ss->ssl3.hs.isResuming)) { - PRInt32 flags = 0; + (!isServer && ss->ssl3.hs.isResuming)) { + PRInt32 flags = 0; - /* Send a NewSessionTicket message if the client sent us - * either an empty session ticket, or one that did not verify. - * (Note that if either of these conditions was met, then the - * server has sent a SessionTicket extension in the - * ServerHello message.) - */ - if (isServer && !ss->ssl3.hs.isResuming && - ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && - ssl3_KEAAllowsSessionTicket(ss->ssl3.hs.suite_def->key_exchange_alg)) { - /* RFC 5077 Section 3.3: "In the case of a full handshake, the - * server MUST verify the client's Finished message before sending - * the ticket." Presumably, this also means that the client's - * certificate, if any, must be verified beforehand too. - */ - rv = ssl3_SendNewSessionTicket(ss); - if (rv != SECSuccess) { - goto xmit_loser; - } - } + /* Send a NewSessionTicket message if the client sent us + * either an empty session ticket, or one that did not verify. + * (Note that if either of these conditions was met, then the + * server has sent a SessionTicket extension in the + * ServerHello message.) + */ + if (isServer && !ss->ssl3.hs.isResuming && + ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && + ssl3_KEAAllowsSessionTicket(ss->ssl3.hs.suite_def->key_exchange_alg)) { + /* RFC 5077 Section 3.3: "In the case of a full handshake, the + * server MUST verify the client's Finished message before sending + * the ticket." Presumably, this also means that the client's + * certificate, if any, must be verified beforehand too. + */ + rv = ssl3_SendNewSessionTicket(ss); + if (rv != SECSuccess) { + goto xmit_loser; + } + } - rv = ssl3_SendChangeCipherSpecs(ss); - if (rv != SECSuccess) { - goto xmit_loser; /* err is set. */ - } - /* If this thread is in SSL_SecureSend (trying to write some data) - ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the - ** last two handshake messages (change cipher spec and finished) - ** will be sent in the same send/write call as the application data. - */ - if (ss->writerThread == PR_GetCurrentThread()) { - flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; - } + rv = ssl3_SendChangeCipherSpecs(ss); + if (rv != SECSuccess) { + goto xmit_loser; /* err is set. */ + } + /* If this thread is in SSL_SecureSend (trying to write some data) + ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the + ** last two handshake messages (change cipher spec and finished) + ** will be sent in the same send/write call as the application data. + */ + if (ss->writerThread == PR_GetCurrentThread()) { + flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; + } - if (!isServer && !ss->firstHsDone) { - rv = ssl3_SendNextProto(ss); - if (rv != SECSuccess) { - goto xmit_loser; /* err code was set. */ - } - } + if (!isServer && !ss->firstHsDone) { + rv = ssl3_SendNextProto(ss); + if (rv != SECSuccess) { + goto xmit_loser; /* err code was set. */ + } + } - if (IS_DTLS(ss)) { - flags |= ssl_SEND_FLAG_NO_RETRANSMIT; - } + if (IS_DTLS(ss)) { + flags |= ssl_SEND_FLAG_NO_RETRANSMIT; + } - rv = ssl3_SendFinished(ss, flags); - if (rv != SECSuccess) { - goto xmit_loser; /* err is set. */ - } + rv = ssl3_SendFinished(ss, flags); + if (rv != SECSuccess) { + goto xmit_loser; /* err is set. */ + } } xmit_loser: - ssl_ReleaseXmitBufLock(ss); /*************************************/ + ssl_ReleaseXmitBufLock(ss); /*************************************/ if (rv != SECSuccess) { return rv; } if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { - effectiveExchKeyType = kt_rsa; - } else { - effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; + effectiveExchKeyType = kt_rsa; + } + else { + effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; } if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) { - /* fill in the sid */ - sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; - sid->u.ssl3.compression = ss->ssl3.hs.compression; - sid->u.ssl3.policy = ss->ssl3.policy; + /* fill in the sid */ + sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; + sid->u.ssl3.compression = ss->ssl3.hs.compression; + sid->u.ssl3.policy = ss->ssl3.policy; #ifndef NSS_DISABLE_ECC - sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; + sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; #endif - sid->u.ssl3.exchKeyType = effectiveExchKeyType; - sid->version = ss->version; - sid->authAlgorithm = ss->sec.authAlgorithm; - sid->authKeyBits = ss->sec.authKeyBits; - sid->keaType = ss->sec.keaType; - sid->keaKeyBits = ss->sec.keaKeyBits; - sid->lastAccessTime = sid->creationTime = ssl_Time(); - sid->expirationTime = sid->creationTime + ssl3_sid_timeout; - sid->localCert = CERT_DupCertificate(ss->sec.localCert); + sid->u.ssl3.exchKeyType = effectiveExchKeyType; + sid->version = ss->version; + sid->authAlgorithm = ss->sec.authAlgorithm; + sid->authKeyBits = ss->sec.authKeyBits; + sid->keaType = ss->sec.keaType; + sid->keaKeyBits = ss->sec.keaKeyBits; + sid->lastAccessTime = sid->creationTime = ssl_Time(); + sid->expirationTime = sid->creationTime + ssl3_sid_timeout; + sid->localCert = CERT_DupCertificate(ss->sec.localCert); - ssl_GetSpecReadLock(ss); /*************************************/ + ssl_GetSpecReadLock(ss); /*************************************/ - /* Copy the master secret (wrapped or unwrapped) into the sid */ - if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { - sid->u.ssl3.keys.wrapped_master_secret_len = - ss->ssl3.crSpec->msItem.len; - memcpy(sid->u.ssl3.keys.wrapped_master_secret, - ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); - sid->u.ssl3.masterValid = PR_TRUE; - sid->u.ssl3.keys.msIsWrapped = PR_FALSE; - rv = SECSuccess; - } else { - rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, - ss->ssl3.crSpec, - effectiveExchKeyType); - sid->u.ssl3.keys.msIsWrapped = PR_TRUE; - } - ssl_ReleaseSpecReadLock(ss); /*************************************/ + /* Copy the master secret (wrapped or unwrapped) into the sid */ + if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { + sid->u.ssl3.keys.wrapped_master_secret_len = + ss->ssl3.crSpec->msItem.len; + memcpy(sid->u.ssl3.keys.wrapped_master_secret, + ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); + sid->u.ssl3.masterValid = PR_TRUE; + sid->u.ssl3.keys.msIsWrapped = PR_FALSE; + rv = SECSuccess; + } + else { + rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, + ss->ssl3.crSpec, + effectiveExchKeyType); + sid->u.ssl3.keys.msIsWrapped = PR_TRUE; + } + ssl_ReleaseSpecReadLock(ss); /*************************************/ - /* If the wrap failed, we don't cache the sid. - * The connection continues normally however. - */ - ss->ssl3.hs.cacheSID = rv == SECSuccess; + /* If the wrap failed, we don't cache the sid. + * The connection continues normally however. + */ + ss->ssl3.hs.cacheSID = rv == SECSuccess; } if (ss->ssl3.hs.authCertificatePending) { - if (ss->ssl3.hs.restartTarget) { - PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } + if (ss->ssl3.hs.restartTarget) { + PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } - ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; - return SECWouldBlock; + ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; + return SECWouldBlock; } rv = ssl3_FinishHandshake(ss); @@ -11732,14 +12135,14 @@ xmit_loser: * to have type sslRestartTarget. */ SECStatus -ssl3_FinishHandshake(sslSocket * ss) +ssl3_FinishHandshake(sslSocket *ss) { - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->ssl3.hs.restartTarget == NULL ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.hs.restartTarget == NULL); /* The first handshake is now completed. */ - ss->handshake = NULL; + ss->handshake = NULL; /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid * until it has verified the server's Finished message." When the server @@ -11753,17 +12156,17 @@ ssl3_FinishHandshake(sslSocket * ss) * ssl3_SetSIDSessionTicket. */ if (ss->ssl3.hs.receivedNewSessionTicket) { - PORT_Assert(!ss->sec.isServer); - ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); - /* The sid took over the ticket data */ - PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); + PORT_Assert(!ss->sec.isServer); + ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); + /* The sid took over the ticket data */ + PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; } if (ss->ssl3.hs.cacheSID) { - PORT_Assert(ss->sec.ci.sid->cached == never_cached); - (*ss->sec.cache)(ss->sec.ci.sid); - ss->ssl3.hs.cacheSID = PR_FALSE; + PORT_Assert(ss->sec.ci.sid->cached == never_cached); + (*ss->sec.cache)(ss->sec.ci.sid); + ss->ssl3.hs.cacheSID = PR_FALSE; } ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ @@ -11781,104 +12184,111 @@ ssl3_FinishHandshake(sslSocket * ss) SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - SECStatus rv = SECSuccess; - SSL3HandshakeType type = ss->ssl3.hs.msg_type; - SSL3Hashes hashes; /* computed hashes are put here. */ - SSL3Hashes *hashesPtr = NULL; /* Set when hashes are computed */ - PRUint8 hdr[4]; - PRUint8 dtlsData[8]; - PRBool computeHashes = PR_FALSE; + SECStatus rv = SECSuccess; + SSL3HandshakeType type = ss->ssl3.hs.msg_type; + SSL3Hashes hashes; /* computed hashes are put here. */ + SSL3Hashes *hashesPtr = NULL; /* Set when hashes are computed */ + PRUint8 hdr[4]; + PRUint8 dtlsData[8]; + PRBool computeHashes = PR_FALSE; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* * We have to compute the hashes before we update them with the * current message. */ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { - if(((type == finished) && (ss->ssl3.hs.ws == wait_finished)) || - ((type == certificate_verify) && - (ss->ssl3.hs.ws == wait_cert_verify))) { + if (((type == finished) && (ss->ssl3.hs.ws == wait_finished)) || + ((type == certificate_verify) && + (ss->ssl3.hs.ws == wait_cert_verify))) { computeHashes = PR_TRUE; } - } else { + } + else { if (type == certificate_verify) { computeHashes = - TLS13_IN_HS_STATE(ss, wait_cert_verify); - } else if (type == finished) { + TLS13_IN_HS_STATE(ss, wait_cert_verify); + } + else if (type == finished) { computeHashes = - TLS13_IN_HS_STATE(ss, wait_cert_request, wait_finished); + TLS13_IN_HS_STATE(ss, wait_cert_request, wait_finished); } } - ssl_GetSpecReadLock(ss); /************************************/ + ssl_GetSpecReadLock(ss); /************************************/ if (computeHashes) { - SSL3Sender sender = (SSL3Sender)0; - ssl3CipherSpec *rSpec = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ? - ss->ssl3.crSpec : ss->ssl3.prSpec; + SSL3Sender sender = (SSL3Sender)0; + ssl3CipherSpec *rSpec = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ? + ss->ssl3.crSpec + : + ss->ssl3.prSpec; - if (type == finished) { - sender = ss->sec.isServer ? sender_client : sender_server; - rSpec = ss->ssl3.crSpec; - } - rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); + if (type == finished) { + sender = ss->sec.isServer ? sender_client : sender_server; + rSpec = ss->ssl3.crSpec; + } + rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); if (rv == SECSuccess) { hashesPtr = &hashes; } } ssl_ReleaseSpecReadLock(ss); /************************************/ if (rv != SECSuccess) { - return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ + return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ } - SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), - ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); + SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), + ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); hdr[0] = (PRUint8)ss->ssl3.hs.msg_type; hdr[1] = (PRUint8)(length >> 16); - hdr[2] = (PRUint8)(length >> 8); - hdr[3] = (PRUint8)(length ); + hdr[2] = (PRUint8)(length >> 8); + hdr[3] = (PRUint8)(length); /* Start new handshake hashes when we start a new handshake */ if (ss->ssl3.hs.msg_type == client_hello) { - rv = ssl3_RestartHandshakeHashes(ss); - if (rv != SECSuccess) { - return rv; - } + rv = ssl3_RestartHandshakeHashes(ss); + if (rv != SECSuccess) { + return rv; + } } /* We should not include hello_request and hello_verify_request messages * in the handshake hashes */ if ((ss->ssl3.hs.msg_type != hello_request) && - (ss->ssl3.hs.msg_type != hello_verify_request)) { - rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4); - if (rv != SECSuccess) return rv; /* err code already set. */ + (ss->ssl3.hs.msg_type != hello_verify_request)) { + rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)hdr, 4); + if (rv != SECSuccess) + return rv; /* err code already set. */ - /* Extra data to simulate a complete DTLS handshake fragment */ - if (IS_DTLS(ss)) { - /* Sequence number */ - dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq); - dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); + /* Extra data to simulate a complete DTLS handshake fragment */ + if (IS_DTLS(ss)) { + /* Sequence number */ + dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq); + dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); - /* Fragment offset */ - dtlsData[2] = 0; - dtlsData[3] = 0; - dtlsData[4] = 0; + /* Fragment offset */ + dtlsData[2] = 0; + dtlsData[3] = 0; + dtlsData[4] = 0; - /* Fragment length */ - dtlsData[5] = (PRUint8)(length >> 16); - dtlsData[6] = (PRUint8)(length >> 8); - dtlsData[7] = (PRUint8)(length ); + /* Fragment length */ + dtlsData[5] = (PRUint8)(length >> 16); + dtlsData[6] = (PRUint8)(length >> 8); + dtlsData[7] = (PRUint8)(length); - rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData, - sizeof(dtlsData)); - if (rv != SECSuccess) return rv; /* err code already set. */ - } + rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)dtlsData, + sizeof(dtlsData)); + if (rv != SECSuccess) + return rv; /* err code already set. */ + } - /* The message body */ - rv = ssl3_UpdateHandshakeHashes(ss, b, length); - if (rv != SECSuccess) return rv; /* err code already set. */ + /* The message body */ + rv = ssl3_UpdateHandshakeHashes(ss, b, length); + if (rv != SECSuccess) + return rv; /* err code already set. */ } - PORT_SetError(0); /* each message starts with no error. */ + PORT_SetError(0); /* each message starts with no error. */ if (ss->ssl3.hs.ws == wait_certificate_status && ss->ssl3.hs.msg_type != certificate_status) { @@ -11897,35 +12307,36 @@ ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) } switch (ss->ssl3.hs.msg_type) { - case client_hello: - if (!ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); - return SECFailure; - } - rv = ssl3_HandleClientHello(ss, b, length); - break; - case server_hello: - if (ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO); - return SECFailure; - } - rv = ssl3_HandleServerHello(ss, b, length); - break; - default: - if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { - rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length, hashesPtr); - } else { - rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length, - hashesPtr); - } - break; + case client_hello: + if (!ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); + return SECFailure; + } + rv = ssl3_HandleClientHello(ss, b, length); + break; + case server_hello: + if (ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO); + return SECFailure; + } + rv = ssl3_HandleServerHello(ss, b, length); + break; + default: + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length, hashesPtr); + } + else { + rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length, + hashesPtr); + } + break; } if (IS_DTLS(ss) && (rv != SECFailure)) { - /* Increment the expected sequence number */ - ss->ssl3.hs.recvMessageSeq++; + /* Increment the expected sequence number */ + ss->ssl3.hs.recvMessageSeq++; } return rv; } @@ -11938,93 +12349,93 @@ ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); switch (ss->ssl3.hs.msg_type) { - case hello_request: - if (length != 0) { - (void)ssl3_DecodeError(ss); - PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); - return SECFailure; - } - if (ss->sec.isServer) { + case hello_request: + if (length != 0) { + (void)ssl3_DecodeError(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); + return SECFailure; + } + if (ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); + return SECFailure; + } + rv = ssl3_HandleHelloRequest(ss); + break; + case hello_verify_request: + if (!IS_DTLS(ss) || ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST); + return SECFailure; + } + rv = dtls_HandleHelloVerifyRequest(ss, b, length); + break; + case certificate: + rv = ssl3_HandleCertificate(ss, b, length); + break; + case certificate_status: + rv = ssl3_HandleCertificateStatus(ss, b, length); + break; + case server_key_exchange: + if (ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); + return SECFailure; + } + rv = ssl3_HandleServerKeyExchange(ss, b, length); + break; + case certificate_request: + if (ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST); + return SECFailure; + } + rv = ssl3_HandleCertificateRequest(ss, b, length); + break; + case server_hello_done: + if (length != 0) { + (void)ssl3_DecodeError(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE); + return SECFailure; + } + if (ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); + return SECFailure; + } + rv = ssl3_HandleServerHelloDone(ss); + break; + case certificate_verify: + if (!ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY); + return SECFailure; + } + rv = ssl3_HandleCertificateVerify(ss, b, length, hashesPtr); + break; + case client_key_exchange: + if (!ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); + return SECFailure; + } + rv = ssl3_HandleClientKeyExchange(ss, b, length); + break; + case new_session_ticket: + if (ss->sec.isServer) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); + return SECFailure; + } + rv = ssl3_HandleNewSessionTicket(ss, b, length); + break; + case finished: + rv = ssl3_HandleFinished(ss, b, length, hashesPtr); + break; + default: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); - return SECFailure; - } - rv = ssl3_HandleHelloRequest(ss); - break; - case hello_verify_request: - if (!IS_DTLS(ss) || ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST); - return SECFailure; - } - rv = dtls_HandleHelloVerifyRequest(ss, b, length); - break; - case certificate: - rv = ssl3_HandleCertificate(ss, b, length); - break; - case certificate_status: - rv = ssl3_HandleCertificateStatus(ss, b, length); - break; - case server_key_exchange: - if (ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); - return SECFailure; - } - rv = ssl3_HandleServerKeyExchange(ss, b, length); - break; - case certificate_request: - if (ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST); - return SECFailure; - } - rv = ssl3_HandleCertificateRequest(ss, b, length); - break; - case server_hello_done: - if (length != 0) { - (void)ssl3_DecodeError(ss); - PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE); - return SECFailure; - } - if (ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); - return SECFailure; - } - rv = ssl3_HandleServerHelloDone(ss); - break; - case certificate_verify: - if (!ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY); - return SECFailure; - } - rv = ssl3_HandleCertificateVerify(ss, b, length, hashesPtr); - break; - case client_key_exchange: - if (!ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); - return SECFailure; - } - rv = ssl3_HandleClientKeyExchange(ss, b, length); - break; - case new_session_ticket: - if (ss->sec.isServer) { - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); - return SECFailure; - } - rv = ssl3_HandleNewSessionTicket(ss, b, length); - break; - case finished: - rv = ssl3_HandleFinished(ss, b, length, hashesPtr); - break; - default: - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); - rv = SECFailure; + PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); + rv = SECFailure; } return rv; @@ -12048,109 +12459,111 @@ ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */ SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (buf->buf == NULL) { - *buf = *origBuf; + *buf = *origBuf; } while (buf->len > 0) { - if (ss->ssl3.hs.header_bytes < 4) { - PRUint8 t; - t = *(buf->buf++); - buf->len--; - if (ss->ssl3.hs.header_bytes++ == 0) - ss->ssl3.hs.msg_type = (SSL3HandshakeType)t; - else - ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; - if (ss->ssl3.hs.header_bytes < 4) - continue; + if (ss->ssl3.hs.header_bytes < 4) { + PRUint8 t; + t = *(buf->buf++); + buf->len--; + if (ss->ssl3.hs.header_bytes++ == 0) + ss->ssl3.hs.msg_type = (SSL3HandshakeType)t; + else + ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; + if (ss->ssl3.hs.header_bytes < 4) + continue; -#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */ - if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { - (void)ssl3_DecodeError(ss); - PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE); - return SECFailure; - } +#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */ + if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { + (void)ssl3_DecodeError(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE); + return SECFailure; + } #undef MAX_HANDSHAKE_MSG_LEN - /* If msg_len is zero, be sure we fall through, - ** even if buf->len is zero. - */ - if (ss->ssl3.hs.msg_len > 0) - continue; - } + /* If msg_len is zero, be sure we fall through, + ** even if buf->len is zero. + */ + if (ss->ssl3.hs.msg_len > 0) + continue; + } - /* - * Header has been gathered and there is at least one byte of new - * data available for this message. If it can be done right out - * of the original buffer, then use it from there. - */ - if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) { - /* handle it from input buffer */ - rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len); - if (rv == SECFailure) { - /* This test wants to fall through on either - * SECSuccess or SECWouldBlock. - * ssl3_HandleHandshakeMessage MUST set the error code. - */ - return rv; - } - buf->buf += ss->ssl3.hs.msg_len; - buf->len -= ss->ssl3.hs.msg_len; - ss->ssl3.hs.msg_len = 0; - ss->ssl3.hs.header_bytes = 0; - if (rv != SECSuccess) { /* return if SECWouldBlock. */ - return rv; - } - } else { - /* must be copied to msg_body and dealt with from there */ - unsigned int bytes; + /* + * Header has been gathered and there is at least one byte of new + * data available for this message. If it can be done right out + * of the original buffer, then use it from there. + */ + if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) { + /* handle it from input buffer */ + rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len); + if (rv == SECFailure) { + /* This test wants to fall through on either + * SECSuccess or SECWouldBlock. + * ssl3_HandleHandshakeMessage MUST set the error code. + */ + return rv; + } + buf->buf += ss->ssl3.hs.msg_len; + buf->len -= ss->ssl3.hs.msg_len; + ss->ssl3.hs.msg_len = 0; + ss->ssl3.hs.header_bytes = 0; + if (rv != SECSuccess) { /* return if SECWouldBlock. */ + return rv; + } + } + else { + /* must be copied to msg_body and dealt with from there */ + unsigned int bytes; - PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); - bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len); + PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); + bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len); - /* Grow the buffer if needed */ - rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); - if (rv != SECSuccess) { - /* sslBuffer_Grow has set a memory error code. */ - return SECFailure; - } + /* Grow the buffer if needed */ + rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); + if (rv != SECSuccess) { + /* sslBuffer_Grow has set a memory error code. */ + return SECFailure; + } - PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, - buf->buf, bytes); - ss->ssl3.hs.msg_body.len += bytes; - buf->buf += bytes; - buf->len -= bytes; + PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, + buf->buf, bytes); + ss->ssl3.hs.msg_body.len += bytes; + buf->buf += bytes; + buf->len -= bytes; - PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); + PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); - /* if we have a whole message, do it */ - if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { - rv = ssl3_HandleHandshakeMessage( - ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len); - if (rv == SECFailure) { - /* This test wants to fall through on either - * SECSuccess or SECWouldBlock. - * ssl3_HandleHandshakeMessage MUST set error code. - */ - return rv; - } - ss->ssl3.hs.msg_body.len = 0; - ss->ssl3.hs.msg_len = 0; - ss->ssl3.hs.header_bytes = 0; - if (rv != SECSuccess) { /* return if SECWouldBlock. */ - return rv; - } - } else { - PORT_Assert(buf->len == 0); - break; - } - } - } /* end loop */ + /* if we have a whole message, do it */ + if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { + rv = ssl3_HandleHandshakeMessage( + ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len); + if (rv == SECFailure) { + /* This test wants to fall through on either + * SECSuccess or SECWouldBlock. + * ssl3_HandleHandshakeMessage MUST set error code. + */ + return rv; + } + ss->ssl3.hs.msg_body.len = 0; + ss->ssl3.hs.msg_len = 0; + ss->ssl3.hs.header_bytes = 0; + if (rv != SECSuccess) { /* return if SECWouldBlock. */ + return rv; + } + } + else { + PORT_Assert(buf->len == 0); + break; + } + } + } /* end loop */ - origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ - buf->buf = NULL; /* not a leak. */ + origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ + buf->buf = NULL; /* not a leak. */ return SECSuccess; } @@ -12158,7 +12571,7 @@ ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * bits. They use the fact that arithmetic shift shifts-in the sign bit. * However, this is not ensured by the C standard so you may need to replace * them with something else for odd compilers. */ -#define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) ) +#define DUPLICATE_MSB_TO_ALL(x) ((unsigned)((int)(x) >> (sizeof(int) * 8 - 1))) #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x))) /* SECStatusToMask returns, in constant time, a mask value of all ones if @@ -12193,8 +12606,8 @@ ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) static SECStatus ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, - unsigned int blockSize, - unsigned int macSize) + unsigned int blockSize, + unsigned int macSize) { unsigned int paddingLength, good, t; const unsigned int overhead = 1 /* padding length byte */ + macSize; @@ -12202,19 +12615,19 @@ ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, /* These lengths are all public so we can test them in non-constant * time. */ if (overhead > plaintext->len) { - return SECFailure; + return SECFailure; } - paddingLength = plaintext->buf[plaintext->len-1]; + paddingLength = plaintext->buf[plaintext->len - 1]; /* SSLv3 padding bytes are random and cannot be checked. */ t = plaintext->len; - t -= paddingLength+overhead; + t -= paddingLength + overhead; /* If len >= paddingLength+overhead then the MSB of t is zero. */ good = DUPLICATE_MSB_TO_ALL(~t); /* SSLv3 requires that the padding is minimal. */ - t = blockSize - (paddingLength+1); + t = blockSize - (paddingLength + 1); good &= DUPLICATE_MSB_TO_ALL(~t); - plaintext->len -= good & (paddingLength+1); + plaintext->len -= good & (paddingLength + 1); return (good & SECSuccess) | (~good & SECFailure); } @@ -12227,12 +12640,12 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) /* These lengths are all public so we can test them in non-constant * time. */ if (overhead > plaintext->len) { - return SECFailure; + return SECFailure; } - paddingLength = plaintext->buf[plaintext->len-1]; + paddingLength = plaintext->buf[plaintext->len - 1]; t = plaintext->len; - t -= paddingLength+overhead; + t -= paddingLength + overhead; /* If len >= paddingLength+overhead then the MSB of t is zero. */ good = DUPLICATE_MSB_TO_ALL(~t); @@ -12246,19 +12659,19 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) * amount of padding possible. (Again, the length of the record is * public information so we can use it.) */ toCheck = 255; /* maximum amount of padding. */ - if (toCheck > plaintext->len-1) { - toCheck = plaintext->len-1; + if (toCheck > plaintext->len - 1) { + toCheck = plaintext->len - 1; } for (i = 0; i < toCheck; i++) { - unsigned int t = paddingLength - i; - /* If i <= paddingLength then the MSB of t is zero and mask is - * 0xff. Otherwise, mask is 0. */ - unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); - unsigned char b = plaintext->buf[plaintext->len-1-i]; - /* The final |paddingLength+1| bytes should all have the value - * |paddingLength|. Therefore the XOR should be zero. */ - good &= ~(mask&(paddingLength ^ b)); + unsigned int t = paddingLength - i; + /* If i <= paddingLength then the MSB of t is zero and mask is + * 0xff. Otherwise, mask is 0. */ + unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); + unsigned char b = plaintext->buf[plaintext->len - 1 - i]; + /* The final |paddingLength+1| bytes should all have the value + * |paddingLength|. Therefore the XOR should be zero. */ + good &= ~(mask & (paddingLength ^ b)); } /* If any of the final |paddingLength+1| bytes had the wrong value, @@ -12268,10 +12681,10 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) good &= good >> 4; good &= good >> 2; good &= good >> 1; - good <<= sizeof(good)*8-1; + good <<= sizeof(good) * 8 - 1; good = DUPLICATE_MSB_TO_ALL(good); - plaintext->len -= good & (paddingLength+1); + plaintext->len -= good & (paddingLength + 1); return (good & SECSuccess) | (~good & SECFailure); } @@ -12282,9 +12695,9 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) */ static void ssl_CBCExtractMAC(sslBuffer *plaintext, - unsigned int originalLength, - SSL3Opaque* out, - unsigned int macSize) + unsigned int originalLength, + SSL3Opaque *out, + unsigned int macSize) { unsigned char rotatedMac[MAX_MAC_LENGTH]; /* macEnd is the index of |plaintext->buf| just after the end of the @@ -12298,7 +12711,7 @@ ssl_CBCExtractMAC(sslBuffer *plaintext, unsigned char rotateOffset; if (originalLength > macSize + 255 + 1) - scanStart = originalLength - (macSize + 255 + 1); + scanStart = originalLength - (macSize + 255 + 1); /* divSpoiler contains a multiple of macSize that is used to cause the * modulo operation to be constant time. Without this, the time varies @@ -12308,29 +12721,29 @@ ssl_CBCExtractMAC(sslBuffer *plaintext, * figure out that it can remove divSpoiler as that would require it * to prove that macSize is always even, which I hope is beyond it. */ divSpoiler = macSize >> 1; - divSpoiler <<= (sizeof(divSpoiler)-1)*8; + divSpoiler <<= (sizeof(divSpoiler) - 1) * 8; rotateOffset = (divSpoiler + macStart - scanStart) % macSize; memset(rotatedMac, 0, macSize); for (i = scanStart; i < originalLength;) { - for (j = 0; j < macSize && i < originalLength; i++, j++) { - unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); - unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); - unsigned char b = 0; - b = plaintext->buf[i]; - rotatedMac[j] |= b & macStarted & ~macEnded; - } + for (j = 0; j < macSize && i < originalLength; i++, j++) { + unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); + unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); + unsigned char b = 0; + b = plaintext->buf[i]; + rotatedMac[j] |= b & macStarted & ~macEnded; + } } /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line * we could line-align |rotatedMac| and rotate in place. */ memset(out, 0, macSize); for (i = 0; i < macSize; i++) { - unsigned char offset = - (divSpoiler + macSize - rotateOffset + i) % macSize; - for (j = 0; j < macSize; j++) { - out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); - } + unsigned char offset = + (divSpoiler + macSize - rotateOffset + i) % macSize; + for (j = 0; j < macSize; j++) { + out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); + } } } @@ -12367,165 +12780,169 @@ ssl3_UnprotectRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *plaintext, good = ~0U; minLength = crSpec->mac_size; if (cipher_def->type == type_block) { - /* CBC records have a padding length byte at the end. */ - minLength++; - if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { - /* With >= TLS 1.1, CBC records have an explicit IV. */ - minLength += cipher_def->iv_size; - } - } else if (cipher_def->type == type_aead) { - minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; + /* CBC records have a padding length byte at the end. */ + minLength++; + if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { + /* With >= TLS 1.1, CBC records have an explicit IV. */ + minLength += cipher_def->iv_size; + } + } + else if (cipher_def->type == type_aead) { + minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; } /* We can perform this test in variable time because the record's total * length and the ciphersuite are both public knowledge. */ if (cText->buf->len < minLength) { - goto decrypt_loser; + goto decrypt_loser; } if (cipher_def->type == type_block && - crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { - /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states - * "The receiver decrypts the entire GenericBlockCipher structure and - * then discards the first cipher block corresponding to the IV - * component." Instead, we decrypt the first cipher block and then - * discard it before decrypting the rest. - */ - SSL3Opaque iv[MAX_IV_LENGTH]; - int decoded; + crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { + /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states + * "The receiver decrypts the entire GenericBlockCipher structure and + * then discards the first cipher block corresponding to the IV + * component." Instead, we decrypt the first cipher block and then + * discard it before decrypting the rest. + */ + SSL3Opaque iv[MAX_IV_LENGTH]; + int decoded; - ivLen = cipher_def->iv_size; - if (ivLen < 8 || ivLen > sizeof(iv)) { + ivLen = cipher_def->iv_size; + if (ivLen < 8 || ivLen > sizeof(iv)) { *alert = internal_error; - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } - PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen)); + PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen)); - /* The decryption result is garbage, but since we just throw away - * the block it doesn't matter. The decryption of the next block - * depends only on the ciphertext of the IV block. - */ - rv = crSpec->decode(crSpec->decodeContext, iv, &decoded, - sizeof(iv), cText->buf->buf, ivLen); + /* The decryption result is garbage, but since we just throw away + * the block it doesn't matter. The decryption of the next block + * depends only on the ciphertext of the IV block. + */ + rv = crSpec->decode(crSpec->decodeContext, iv, &decoded, + sizeof(iv), cText->buf->buf, ivLen); - good &= SECStatusToMask(rv); + good &= SECStatusToMask(rv); } PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, - cText->buf->len - ivLen)); + cText->buf->len - ivLen)); isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { *alert = record_overflow; - PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); - return SECFailure; + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); + return SECFailure; } rType = cText->type; if (cipher_def->type == type_aead) { - /* XXX For many AEAD ciphers, the plaintext is shorter than the - * ciphertext by a fixed byte count, but it is not true in general. - * Each AEAD cipher should provide a function that returns the - * plaintext length for a given ciphertext. */ - unsigned int decryptedLen = - cText->buf->len - cipher_def->explicit_nonce_size - - cipher_def->tag_size; - headerLen = ssl3_BuildRecordPseudoHeader( - header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, - rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); - PORT_Assert(headerLen <= sizeof(header)); - rv = crSpec->aead( - ss->sec.isServer ? &crSpec->client : &crSpec->server, - PR_TRUE, /* do decrypt */ - plaintext->buf, /* out */ - (int*) &plaintext->len, /* outlen */ - plaintext->space, /* maxout */ - cText->buf->buf, /* in */ - cText->buf->len, /* inlen */ - header, headerLen); - if (rv != SECSuccess) { - good = 0; - } - } else { - if (cipher_def->type == type_block && - ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { - goto decrypt_loser; - } + /* XXX For many AEAD ciphers, the plaintext is shorter than the + * ciphertext by a fixed byte count, but it is not true in general. + * Each AEAD cipher should provide a function that returns the + * plaintext length for a given ciphertext. */ + unsigned int decryptedLen = + cText->buf->len - cipher_def->explicit_nonce_size - + cipher_def->tag_size; + headerLen = ssl3_BuildRecordPseudoHeader( + header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, + rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); + PORT_Assert(headerLen <= sizeof(header)); + rv = crSpec->aead( + ss->sec.isServer ? &crSpec->client : &crSpec->server, + PR_TRUE, /* do decrypt */ + plaintext->buf, /* out */ + (int *)&plaintext->len, /* outlen */ + plaintext->space, /* maxout */ + cText->buf->buf, /* in */ + cText->buf->len, /* inlen */ + header, headerLen); + if (rv != SECSuccess) { + good = 0; + } + } + else { + if (cipher_def->type == type_block && + ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { + goto decrypt_loser; + } - /* decrypt from cText buf to plaintext. */ - rv = crSpec->decode( - crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, - plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); - if (rv != SECSuccess) { - goto decrypt_loser; - } + /* decrypt from cText buf to plaintext. */ + rv = crSpec->decode( + crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, + plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); + if (rv != SECSuccess) { + goto decrypt_loser; + } - PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); + PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); - originalLen = plaintext->len; + originalLen = plaintext->len; - /* If it's a block cipher, check and strip the padding. */ - if (cipher_def->type == type_block) { - const unsigned int blockSize = cipher_def->block_size; - const unsigned int macSize = crSpec->mac_size; + /* If it's a block cipher, check and strip the padding. */ + if (cipher_def->type == type_block) { + const unsigned int blockSize = cipher_def->block_size; + const unsigned int macSize = crSpec->mac_size; - if (!isTLS) { - good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( - plaintext, blockSize, macSize)); - } else { - good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( - plaintext, macSize)); - } - } + if (!isTLS) { + good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( + plaintext, blockSize, macSize)); + } + else { + good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( + plaintext, macSize)); + } + } - /* compute the MAC */ - headerLen = ssl3_BuildRecordPseudoHeader( - header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, - rType, isTLS, cText->version, IS_DTLS(ss), - plaintext->len - crSpec->mac_size); - PORT_Assert(headerLen <= sizeof(header)); - if (cipher_def->type == type_block) { - rv = ssl3_ComputeRecordMACConstantTime( - crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, - plaintext->buf, plaintext->len, originalLen, - hash, &hashBytes); + /* compute the MAC */ + headerLen = ssl3_BuildRecordPseudoHeader( + header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, + rType, isTLS, cText->version, IS_DTLS(ss), + plaintext->len - crSpec->mac_size); + PORT_Assert(headerLen <= sizeof(header)); + if (cipher_def->type == type_block) { + rv = ssl3_ComputeRecordMACConstantTime( + crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, + plaintext->buf, plaintext->len, originalLen, + hash, &hashBytes); - ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, - crSpec->mac_size); - givenHash = givenHashBuf; + ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, + crSpec->mac_size); + givenHash = givenHashBuf; - /* plaintext->len will always have enough space to remove the MAC - * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust - * plaintext->len if the result has enough space for the MAC and we - * tested the unadjusted size against minLength, above. */ - plaintext->len -= crSpec->mac_size; - } else { - /* This is safe because we checked the minLength above. */ - plaintext->len -= crSpec->mac_size; + /* plaintext->len will always have enough space to remove the MAC + * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust + * plaintext->len if the result has enough space for the MAC and we + * tested the unadjusted size against minLength, above. */ + plaintext->len -= crSpec->mac_size; + } + else { + /* This is safe because we checked the minLength above. */ + plaintext->len -= crSpec->mac_size; - rv = ssl3_ComputeRecordMAC( - crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, - plaintext->buf, plaintext->len, hash, &hashBytes); + rv = ssl3_ComputeRecordMAC( + crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, + plaintext->buf, plaintext->len, hash, &hashBytes); - /* We can read the MAC directly from the record because its location - * is public when a stream cipher is used. */ - givenHash = plaintext->buf + plaintext->len; - } + /* We can read the MAC directly from the record because its location + * is public when a stream cipher is used. */ + givenHash = plaintext->buf + plaintext->len; + } - good &= SECStatusToMask(rv); + good &= SECStatusToMask(rv); - if (hashBytes != (unsigned)crSpec->mac_size || - NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { - /* We're allowed to leak whether or not the MAC check was correct */ - good = 0; - } + if (hashBytes != (unsigned)crSpec->mac_size || + NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { + /* We're allowed to leak whether or not the MAC check was correct */ + good = 0; + } } if (good == 0) { -decrypt_loser: + decrypt_loser: /* always log mac error, in case attacker can read server logs. */ PORT_SetError(SSL_ERROR_BAD_MAC_READ); *alert = bad_record_mac; @@ -12559,29 +12976,29 @@ decrypt_loser: SECStatus ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) { - SECStatus rv; - PRBool isTLS; - PRUint64 dtls_seq_num = 0; - ssl3CipherSpec *crSpec; - SSL3ContentType rType; - sslBuffer *plaintext; - sslBuffer temp_buf; + SECStatus rv; + PRBool isTLS; + PRUint64 dtls_seq_num = 0; + ssl3CipherSpec *crSpec; + SSL3ContentType rType; + sslBuffer *plaintext; + sslBuffer temp_buf; SSL3AlertDescription alert; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); if (!ss->ssl3.initialized) { - ssl_GetSSL3HandshakeLock(ss); - rv = ssl3_InitState(ss); - ssl_ReleaseSSL3HandshakeLock(ss); - if (rv != SECSuccess) { - return rv; /* ssl3_InitState has set the error code. */ - } + ssl_GetSSL3HandshakeLock(ss); + rv = ssl3_InitState(ss); + ssl_ReleaseSSL3HandshakeLock(ss); + if (rv != SECSuccess) { + return rv; /* ssl3_InitState has set the error code. */ + } } /* check for Token Presence */ if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; } /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX(). @@ -12589,10 +13006,10 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) * message. */ if (cText == NULL) { - SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", - SSL_GETPID(), ss->fd)); - rType = content_handshake; - goto process_it; + SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", + SSL_GETPID(), ss->fd)); + rType = content_handshake; + goto process_it; } ssl_GetSpecReadLock(ss); /******************************************/ @@ -12601,34 +13018,35 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) if (IS_DTLS(ss)) { if (!dtls_IsRelevant(ss, crSpec, cText, &dtls_seq_num)) { - ssl_ReleaseSpecReadLock(ss); - /* Silently drop the packet */ + ssl_ReleaseSpecReadLock(ss); + /* Silently drop the packet */ databuf->len = 0; /* Needed to ensure data not left around */ - return SECSuccess; + return SECSuccess; } } /* If we will be decompressing the buffer we need to decrypt somewhere * other than into databuf */ if (crSpec->decompressor) { - temp_buf.buf = NULL; - temp_buf.space = 0; - plaintext = &temp_buf; - } else { - plaintext = databuf; + temp_buf.buf = NULL; + temp_buf.space = 0; + plaintext = &temp_buf; + } + else { + plaintext = databuf; } plaintext->len = 0; /* filled in by Unprotect call below. */ if (plaintext->space < MAX_FRAGMENT_LENGTH) { - rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); - if (rv != SECSuccess) { - ssl_ReleaseSpecReadLock(ss); - SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", - SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); - /* sslBuffer_Grow has set a memory error code. */ - /* Perhaps we should send an alert. (but we have no memory!) */ - return SECFailure; - } + rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); + if (rv != SECSuccess) { + ssl_ReleaseSpecReadLock(ss); + SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", + SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); + /* sslBuffer_Grow has set a memory error code. */ + /* Perhaps we should send an alert. (but we have no memory!) */ + return SECFailure; + } } /* IMPORTANT: Unprotect functions MUST NOT send alerts @@ -12638,34 +13056,37 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) crSpec->cipher_def->calg == ssl_calg_null) { /* Unencrypted TLS 1.3 records use the pre-TLS 1.3 format. */ rv = ssl3_UnprotectRecord(ss, cText, plaintext, &alert); - } else { + } + else { rv = tls13_UnprotectRecord(ss, cText, plaintext, &alert); } if (rv != SECSuccess) { - ssl_ReleaseSpecReadLock(ss); + ssl_ReleaseSpecReadLock(ss); - SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); + SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); - if (!IS_DTLS(ss)) { + if (!IS_DTLS(ss)) { int errCode = PORT_GetError(); - SSL3_SendAlert(ss, alert_fatal, alert); + SSL3_SendAlert(ss, alert_fatal, alert); /* Reset the error code in case SSL3_SendAlert called * PORT_SetError(). */ PORT_SetError(errCode); - return SECFailure; - } else { - /* Silently drop the packet */ + return SECFailure; + } + else { + /* Silently drop the packet */ databuf->len = 0; /* Needed to ensure data not left around */ - return SECSuccess; - } + return SECSuccess; + } } /* SECSuccess */ if (!IS_DTLS(ss)) { - ssl3_BumpSequenceNumber(&crSpec->read_seq_num); - } else { - dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); + ssl3_BumpSequenceNumber(&crSpec->read_seq_num); + } + else { + dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); } ssl_ReleaseSpecReadLock(ss); /*****************************************/ @@ -12673,85 +13094,88 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) /* * The decrypted data is now in plaintext. */ - rType = cText->type; /* This must go after decryption because TLS 1.3 - * has encrypted content types. */ + rType = cText->type; /* This must go after decryption because TLS 1.3 + * has encrypted content types. */ /* possibly decompress the record. If we aren't using compression then * plaintext == databuf and so the uncompressed data is already in * databuf. */ if (crSpec->decompressor) { - if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { - rv = sslBuffer_Grow( - databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", - SSL_GETPID(), ss->fd, - plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION)); - /* sslBuffer_Grow has set a memory error code. */ - /* Perhaps we should send an alert. (but we have no memory!) */ - PORT_Free(plaintext->buf); - return SECFailure; - } - } + if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { + rv = sslBuffer_Grow( + databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); + if (rv != SECSuccess) { + SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", + SSL_GETPID(), ss->fd, + plaintext->len + + SSL3_COMPRESSION_MAX_EXPANSION)); + /* sslBuffer_Grow has set a memory error code. */ + /* Perhaps we should send an alert. (but we have no memory!) */ + PORT_Free(plaintext->buf); + return SECFailure; + } + } - rv = crSpec->decompressor(crSpec->decompressContext, - databuf->buf, - (int*) &databuf->len, - databuf->space, - plaintext->buf, - plaintext->len); + rv = crSpec->decompressor(crSpec->decompressContext, + databuf->buf, + (int *)&databuf->len, + databuf->space, + plaintext->buf, + plaintext->len); - if (rv != SECSuccess) { - int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); - SSL3_SendAlert(ss, alert_fatal, - isTLS ? decompression_failure : bad_record_mac); + if (rv != SECSuccess) { + int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); + SSL3_SendAlert(ss, alert_fatal, + isTLS ? + decompression_failure + : bad_record_mac); - /* There appears to be a bug with (at least) Apache + OpenSSL where - * resumed SSLv3 connections don't actually use compression. See - * comments 93-95 of - * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 - * - * So, if we get a decompression error, and the record appears to - * be already uncompressed, then we return a more specific error - * code to hopefully save somebody some debugging time in the - * future. - */ - if (plaintext->len >= 4) { - unsigned int len = ((unsigned int) plaintext->buf[1] << 16) | - ((unsigned int) plaintext->buf[2] << 8) | - (unsigned int) plaintext->buf[3]; - if (len == plaintext->len - 4) { - /* This appears to be uncompressed already */ - err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; - } - } + /* There appears to be a bug with (at least) Apache + OpenSSL where + * resumed SSLv3 connections don't actually use compression. See + * comments 93-95 of + * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 + * + * So, if we get a decompression error, and the record appears to + * be already uncompressed, then we return a more specific error + * code to hopefully save somebody some debugging time in the + * future. + */ + if (plaintext->len >= 4) { + unsigned int len = ((unsigned int)plaintext->buf[1] << 16) | + ((unsigned int)plaintext->buf[2] << 8) | + (unsigned int)plaintext->buf[3]; + if (len == plaintext->len - 4) { + /* This appears to be uncompressed already */ + err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; + } + } - PORT_Free(plaintext->buf); - PORT_SetError(err); - return SECFailure; - } + PORT_Free(plaintext->buf); + PORT_SetError(err); + return SECFailure; + } - PORT_Free(plaintext->buf); + PORT_Free(plaintext->buf); } /* - ** Having completed the decompression, check the length again. + ** Having completed the decompression, check the length again. */ if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) { - SSL3_SendAlert(ss, alert_fatal, record_overflow); - PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); - return SECFailure; + SSL3_SendAlert(ss, alert_fatal, record_overflow); + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); + return SECFailure; } /* Application data records are processed by the caller of this ** function, not by this function. */ if (rType == content_application_data) { - if (ss->firstHsDone) - return SECSuccess; - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); - return SECFailure; + if (ss->firstHsDone) + return SECSuccess; + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); + return SECFailure; } /* It's a record that must be handled by ssl itself, not the application. @@ -12766,29 +13190,30 @@ process_it: ** they return SECFailure or SECWouldBlock. */ switch (rType) { - case content_change_cipher_spec: - rv = ssl3_HandleChangeCipherSpecs(ss, databuf); - break; - case content_alert: - rv = ssl3_HandleAlert(ss, databuf); - break; - case content_handshake: - if (!IS_DTLS(ss)) { - rv = ssl3_HandleHandshake(ss, databuf); - } else { - rv = dtls_HandleHandshake(ss, databuf); - } - break; - /* - case content_application_data is handled before this switch - */ - default: - SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", - SSL_GETPID(), ss->fd, cText->type)); - /* XXX Send an alert ??? */ - PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); - rv = SECFailure; - break; + case content_change_cipher_spec: + rv = ssl3_HandleChangeCipherSpecs(ss, databuf); + break; + case content_alert: + rv = ssl3_HandleAlert(ss, databuf); + break; + case content_handshake: + if (!IS_DTLS(ss)) { + rv = ssl3_HandleHandshake(ss, databuf); + } + else { + rv = dtls_HandleHandshake(ss, databuf); + } + break; + /* + case content_application_data is handled before this switch + */ + default: + SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", + SSL_GETPID(), ss->fd, cText->type)); + /* XXX Send an alert ??? */ + PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); + rv = SECFailure; + break; } ssl_ReleaseSSL3HandshakeLock(ss); @@ -12804,49 +13229,49 @@ process_it: static void ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) { - spec->cipher_def = &bulk_cipher_defs[cipher_null]; + spec->cipher_def = &bulk_cipher_defs[cipher_null]; PORT_Assert(spec->cipher_def->cipher == cipher_null); - spec->mac_def = &mac_defs[mac_null]; + spec->mac_def = &mac_defs[mac_null]; PORT_Assert(spec->mac_def->mac == mac_null); - spec->encode = Null_Cipher; - spec->decode = Null_Cipher; - spec->destroy = NULL; - spec->compressor = NULL; - spec->decompressor = NULL; - spec->destroyCompressContext = NULL; + spec->encode = Null_Cipher; + spec->decode = Null_Cipher; + spec->destroy = NULL; + spec->compressor = NULL; + spec->decompressor = NULL; + spec->destroyCompressContext = NULL; spec->destroyDecompressContext = NULL; - spec->mac_size = 0; - spec->master_secret = NULL; - spec->bypassCiphers = PR_FALSE; + spec->mac_size = 0; + spec->master_secret = NULL; + spec->bypassCiphers = PR_FALSE; - spec->msItem.data = NULL; - spec->msItem.len = 0; + spec->msItem.data = NULL; + spec->msItem.len = 0; - spec->client.write_key = NULL; - spec->client.write_mac_key = NULL; + spec->client.write_key = NULL; + spec->client.write_mac_key = NULL; spec->client.write_mac_context = NULL; - spec->server.write_key = NULL; - spec->server.write_mac_key = NULL; + spec->server.write_key = NULL; + spec->server.write_mac_key = NULL; spec->server.write_mac_context = NULL; - spec->write_seq_num.high = 0; - spec->write_seq_num.low = 0; + spec->write_seq_num.high = 0; + spec->write_seq_num.low = 0; - spec->read_seq_num.high = 0; - spec->read_seq_num.low = 0; + spec->read_seq_num.high = 0; + spec->read_seq_num.low = 0; - spec->epoch = 0; + spec->epoch = 0; dtls_InitRecvdRecords(&spec->recvdRecords); - spec->version = ss->vrange.max; + spec->version = ss->vrange.max; } -/* Called from: ssl3_SendRecord -** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() -** ssl3_SendClientHello() -** ssl3_HandleV2ClientHello() -** ssl3_HandleRecord() +/* Called from: ssl3_SendRecord +** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() +** ssl3_SendClientHello() +** ssl3_HandleV2ClientHello() +** ssl3_HandleRecord() ** ** This function should perhaps acquire and release the SpecWriteLock. ** @@ -12855,10 +13280,10 @@ ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) static SECStatus ssl3_InitState(sslSocket *ss) { - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->ssl3.initialized) - return SECSuccess; /* Function should be idempotent */ + return SECSuccess; /* Function should be idempotent */ ss->ssl3.policy = SSL_ALLOWED; @@ -12879,13 +13304,13 @@ ssl3_InitState(sslSocket *ss) PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); if (IS_DTLS(ss)) { - ss->ssl3.hs.sendMessageSeq = 0; - ss->ssl3.hs.recvMessageSeq = 0; - ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; - ss->ssl3.hs.rtRetries = 0; - ss->ssl3.hs.recvdHighWater = -1; - PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); - dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ + ss->ssl3.hs.sendMessageSeq = 0; + ss->ssl3.hs.recvMessageSeq = 0; + ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; + ss->ssl3.hs.rtRetries = 0; + ss->ssl3.hs.recvdHighWater = -1; + PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); + dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ } PR_INIT_CLIST(&ss->ssl3.hs.remoteKeyShares); @@ -12902,7 +13327,7 @@ ssl3_InitState(sslSocket *ss) ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, - sizeof(ss->ssl3.hs.newSessionTicket)); + sizeof(ss->ssl3.hs.newSessionTicket)); ss->ssl3.initialized = PR_TRUE; return SECSuccess; @@ -12913,40 +13338,40 @@ ssl3_InitState(sslSocket *ss) * Uses the keys in the pair as input. */ ssl3KeyPair * -ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey) +ssl3_NewKeyPair(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey) { - ssl3KeyPair * pair; + ssl3KeyPair *pair; if (!privKey || !pubKey) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return NULL; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return NULL; } pair = PORT_ZNew(ssl3KeyPair); if (!pair) - return NULL; /* error code is set. */ + return NULL; /* error code is set. */ pair->refCount = 1; - pair->privKey = privKey; - pair->pubKey = pubKey; - return pair; /* success */ + pair->privKey = privKey; + pair->pubKey = pubKey; + return pair; /* success */ } ssl3KeyPair * -ssl3_GetKeyPairRef(ssl3KeyPair * keyPair) +ssl3_GetKeyPairRef(ssl3KeyPair *keyPair) { PR_ATOMIC_INCREMENT(&keyPair->refCount); return keyPair; } void -ssl3_FreeKeyPair(ssl3KeyPair * keyPair) +ssl3_FreeKeyPair(ssl3KeyPair *keyPair) { - PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); + PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); if (!newCount) { - if (keyPair->privKey) - SECKEY_DestroyPrivateKey(keyPair->privKey); - if (keyPair->pubKey) - SECKEY_DestroyPublicKey( keyPair->pubKey); - PORT_Free(keyPair); + if (keyPair->privKey) + SECKEY_DestroyPrivateKey(keyPair->privKey); + if (keyPair->pubKey) + SECKEY_DestroyPublicKey(keyPair->pubKey); + PORT_Free(keyPair); } } @@ -12957,25 +13382,25 @@ ssl3_FreeKeyPair(ssl3KeyPair * keyPair) SECStatus ssl3_CreateRSAStepDownKeys(sslSocket *ss) { - SECStatus rv = SECSuccess; - SECKEYPrivateKey * privKey; /* RSA step down key */ - SECKEYPublicKey * pubKey; /* RSA step down key */ + SECStatus rv = SECSuccess; + SECKEYPrivateKey *privKey; /* RSA step down key */ + SECKEYPublicKey *pubKey; /* RSA step down key */ if (ss->stepDownKeyPair) - ssl3_FreeKeyPair(ss->stepDownKeyPair); + ssl3_FreeKeyPair(ss->stepDownKeyPair); ss->stepDownKeyPair = NULL; #ifndef HACKED_EXPORT_SERVER /* Sigh, should have a get key strength call for private keys */ if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) > - EXPORT_RSA_KEY_LENGTH) { - /* need to ask for the key size in bits */ - privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, - &pubKey, NULL); - if (!privKey || !pubKey || - !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { - ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - } + EXPORT_RSA_KEY_LENGTH) { + /* need to ask for the key size in bits */ + privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, + &pubKey, NULL); + if (!privKey || !pubKey || + !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { + ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); + rv = SECFailure; + } } #endif return rv; @@ -12989,7 +13414,7 @@ ssl3_SetPolicy(ssl3CipherSuite which, int policy) suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); if (suite == NULL) { - return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ } suite->policy = policy; @@ -13000,16 +13425,17 @@ SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) { ssl3CipherSuiteCfg *suite; - PRInt32 policy; - SECStatus rv; + PRInt32 policy; + SECStatus rv; suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); if (suite) { - policy = suite->policy; - rv = SECSuccess; - } else { - policy = SSL_NOT_ALLOWED; - rv = SECFailure; /* err code was set by Lookup. */ + policy = suite->policy; + rv = SECSuccess; + } + else { + policy = SSL_NOT_ALLOWED; + rv = SECFailure; /* err code was set by Lookup. */ } *oPolicy = policy; return rv; @@ -13023,7 +13449,7 @@ ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); if (suite == NULL) { - return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ } suite->enabled = enabled; return SECSuccess; @@ -13034,16 +13460,17 @@ SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) { ssl3CipherSuiteCfg *suite; - PRBool pref; - SECStatus rv; + PRBool pref; + SECStatus rv; suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); if (suite) { - pref = suite->enabled; - rv = SECSuccess; - } else { - pref = SSL_NOT_ALLOWED; - rv = SECFailure; /* err code was set by Lookup. */ + pref = suite->enabled; + rv = SECSuccess; + } + else { + pref = SSL_NOT_ALLOWED; + rv = SECFailure; /* err code was set by Lookup. */ } *enabled = pref; return rv; @@ -13056,7 +13483,7 @@ ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); if (suite == NULL) { - return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ } suite->enabled = enabled; return SECSuccess; @@ -13066,16 +13493,17 @@ SECStatus ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) { ssl3CipherSuiteCfg *suite; - PRBool pref; - SECStatus rv; + PRBool pref; + SECStatus rv; suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); if (suite) { - pref = suite->enabled; - rv = SECSuccess; - } else { - pref = SSL_NOT_ALLOWED; - rv = SECFailure; /* err code was set by Lookup. */ + pref = suite->enabled; + rv = SECSuccess; + } + else { + pref = SSL_NOT_ALLOWED; + rv = SECFailure; /* err code was set by Lookup. */ } *enabled = pref; return rv; @@ -13111,7 +13539,7 @@ SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms, } ss->ssl3.signatureAlgorithms[ss->ssl3.signatureAlgorithmCount++] = - algorithms[i]; + algorithms[i]; } if (ss->ssl3.signatureAlgorithmCount == 0) { @@ -13143,14 +13571,15 @@ SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms, } requiredSpace = - ss->ssl3.signatureAlgorithmCount * sizeof(SSLSignatureAndHashAlg); + ss->ssl3.signatureAlgorithmCount * sizeof(SSLSignatureAndHashAlg); PORT_Memcpy(algorithms, ss->ssl3.signatureAlgorithms, requiredSpace); *count = ss->ssl3.signatureAlgorithmCount; return SECSuccess; } unsigned int -SSL_SignatureMaxCount() { +SSL_SignatureMaxCount() +{ return MAX_SIGNATURE_ALGORITHMS; } @@ -13174,36 +13603,36 @@ ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) PORT_Assert(ss != 0); if (!ss) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - *size = 0; - return SECSuccess; + *size = 0; + return SECSuccess; } if (cs == NULL) { - *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); - return SECSuccess; + *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); + return SECSuccess; } /* ssl3_config_match_init was called by the caller of this function. */ for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; - if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange, ss)) { - if (cs != NULL) { - *cs++ = 0x00; - *cs++ = (suite->cipher_suite >> 8) & 0xFF; - *cs++ = suite->cipher_suite & 0xFF; - } - count++; - } + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; + if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange, ss)) { + if (cs != NULL) { + *cs++ = 0x00; + *cs++ = (suite->cipher_suite >> 8) & 0xFF; + *cs++ = suite->cipher_suite & 0xFF; + } + count++; + } } *size = count; return SECSuccess; } /* -** If ssl3 socket has completed the first handshake, and is in idle state, +** If ssl3 socket has completed the first handshake, and is in idle state, ** then start a new handshake. ** If flushCache is true, the SID cache will be flushed first, forcing a ** "Full" handshake (not a session restart handshake), to be done. @@ -13213,41 +13642,41 @@ ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) { - sslSessionID * sid = ss->sec.ci.sid; - SECStatus rv; + sslSessionID *sid = ss->sec.ci.sid; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (!ss->firstHsDone || ((ss->version >= SSL_LIBRARY_VERSION_3_0) && - ss->ssl3.initialized && - (ss->ssl3.hs.ws != idle_handshake))) { - PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); - return SECFailure; + ss->ssl3.initialized && + (ss->ssl3.hs.ws != idle_handshake))) { + PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); + return SECFailure; } if (IS_DTLS(ss)) { - dtls_RehandshakeCleanup(ss); + dtls_RehandshakeCleanup(ss); } if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { - PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); - return SECFailure; + PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); + return SECFailure; } if (sid && flushCache) { if (ss->sec.uncache) ss->sec.uncache(sid); /* remove it from whichever cache it's in. */ - ssl_FreeSID(sid); /* dec ref count and free if zero. */ - ss->sec.ci.sid = NULL; + ssl_FreeSID(sid); /* dec ref count and free if zero. */ + ss->sec.ci.sid = NULL; } - ssl_GetXmitBufLock(ss); /**************************************/ + ssl_GetXmitBufLock(ss); /**************************************/ /* start off a new handshake. */ rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss) : ssl3_SendClientHello(ss, PR_FALSE); - ssl_ReleaseXmitBufLock(ss); /**************************************/ + ssl_ReleaseXmitBufLock(ss); /**************************************/ return rv; } @@ -13257,44 +13686,45 @@ ssl3_DestroySSL3Info(sslSocket *ss) { if (ss->ssl3.clientCertificate != NULL) - CERT_DestroyCertificate(ss->ssl3.clientCertificate); + CERT_DestroyCertificate(ss->ssl3.clientCertificate); if (ss->ssl3.clientPrivateKey != NULL) - SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); if (ss->ssl3.peerCertArena != NULL) - ssl3_CleanupPeerCerts(ss); + ssl3_CleanupPeerCerts(ss); if (ss->ssl3.clientCertChain != NULL) { - CERT_DestroyCertificateList(ss->ssl3.clientCertChain); - ss->ssl3.clientCertChain = NULL; + CERT_DestroyCertificateList(ss->ssl3.clientCertChain); + ss->ssl3.clientCertChain = NULL; } - /* clean up handshake */ +/* clean up handshake */ #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { - if (ss->ssl3.hs.hashType == handshake_hash_combo) { - SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); - MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); - } else if (ss->ssl3.hs.hashType == handshake_hash_single) { - ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); - } + if (ss->ssl3.hs.hashType == handshake_hash_combo) { + SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); + MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); + } + else if (ss->ssl3.hs.hashType == handshake_hash_single) { + ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); + } } #endif if (ss->ssl3.hs.md5) { - PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); + PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); } if (ss->ssl3.hs.sha) { - PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); + PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); } if (ss->ssl3.hs.clientSigAndHash) { - PORT_Free(ss->ssl3.hs.clientSigAndHash); + PORT_Free(ss->ssl3.hs.clientSigAndHash); } if (ss->ssl3.hs.messages.buf) { - PORT_Free(ss->ssl3.hs.messages.buf); - ss->ssl3.hs.messages.buf = NULL; - ss->ssl3.hs.messages.len = 0; - ss->ssl3.hs.messages.space = 0; + PORT_Free(ss->ssl3.hs.messages.buf); + ss->ssl3.hs.messages.buf = NULL; + ss->ssl3.hs.messages.len = 0; + ss->ssl3.hs.messages.space = 0; } /* free the SSL3Buffer (msg_body) */ @@ -13303,15 +13733,15 @@ ssl3_DestroySSL3Info(sslSocket *ss) SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); /* free up the CipherSpecs */ - ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/); - ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/); + ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE /*freeSrvName*/); + ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE /*freeSrvName*/); /* Destroy the DTLS data */ if (IS_DTLS(ss)) { - dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); - if (ss->ssl3.hs.recvdFragments.buf) { - PORT_Free(ss->ssl3.hs.recvdFragments.buf); - } + dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); + if (ss->ssl3.hs.recvdFragments.buf) { + PORT_Free(ss->ssl3.hs.recvdFragments.buf); + } } /* Destroy TLS 1.3 handshake shares */ @@ -13330,7 +13760,7 @@ ssl3_DestroySSL3Info(sslSocket *ss) PK11_FreeSymKey(ss->ssl3.hs.serverFinishedSecret); if (ss->ssl3.dheGroups) { - PORT_Free(ss->ssl3.dheGroups); + PORT_Free(ss->ssl3.dheGroups); } ss->ssl3.initialized = PR_FALSE; @@ -13338,50 +13768,51 @@ ssl3_DestroySSL3Info(sslSocket *ss) SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); } -#define MAP_NULL(x) (((x)!=0)?(x):SEC_OID_NULL_CIPHER) +#define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER) -SECStatus ssl3_ApplyNSSPolicy(void) - { +SECStatus +ssl3_ApplyNSSPolicy(void) +{ unsigned i; SECStatus rv; PRUint32 policy = 0; rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy); if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) { - return SECSuccess; /* do nothing */ + return SECSuccess; /* do nothing */ } /* disable every ciphersuite */ for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) { const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i]; - SECOidTag policyOid; + SECOidTag policyOid; - policyOid=MAP_NULL(kea_defs[suite->key_exchange_alg].oid); + policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid); rv = NSS_GetAlgorithmPolicy(policyOid, &policy); if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL_KX)) { - ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); - ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); - continue; - } + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); + continue; + } - policyOid=MAP_NULL(bulk_cipher_defs[suite->bulk_cipher_alg].oid); + policyOid = MAP_NULL(bulk_cipher_defs[suite->bulk_cipher_alg].oid); rv = NSS_GetAlgorithmPolicy(policyOid, &policy); if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { - ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); - ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); - continue; - } + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); + continue; + } - if (bulk_cipher_defs[suite->bulk_cipher_alg].type != type_aead) { - policyOid=MAP_NULL(mac_defs[suite->mac_alg].oid); - rv = NSS_GetAlgorithmPolicy(policyOid, &policy); - if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { - ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); - ssl_CipherPolicySet(suite->cipher_suite, - SSL_NOT_ALLOWED); - continue; - } - } + if (bulk_cipher_defs[suite->bulk_cipher_alg].type != type_aead) { + policyOid = MAP_NULL(mac_defs[suite->mac_alg].oid); + rv = NSS_GetAlgorithmPolicy(policyOid, &policy); + if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, + SSL_NOT_ALLOWED); + continue; + } + } } rv = ssl3_ConstrainRangeByPolicy(); diff --git a/security/nss/lib/ssl/ssl3ecc.c b/security/nss/lib/ssl/ssl3ecc.c index 1a9bb2e2ccb2..e26a556db604 100644 --- a/security/nss/lib/ssl/ssl3ecc.c +++ b/security/nss/lib/ssl/ssl3ecc.c @@ -11,7 +11,7 @@ #include "nss.h" #include "cert.h" #include "ssl.h" -#include "cryptohi.h" /* for DSAU_ stuff */ +#include "cryptohi.h" /* for DSAU_ stuff */ #include "keyhi.h" #include "secder.h" #include "secitem.h" @@ -34,21 +34,21 @@ #ifndef NSS_DISABLE_ECC #ifndef PK11_SETATTRS -#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ - (x)->pValue=(v); (x)->ulValueLen = (l); +#define PK11_SETATTRS(x, id, v, l) \ + (x)->type = (id); \ + (x)->pValue = (v); \ + (x)->ulValueLen = (l); #endif -#define SSL_GET_SERVER_PUBLIC_KEY(sock, type) \ - (ss->serverCerts[type].serverKeyPair ? \ - ss->serverCerts[type].serverKeyPair->pubKey : NULL) +#define SSL_GET_SERVER_PUBLIC_KEY(sock, type) \ + (ss->serverCerts[type].serverKeyPair ? ss->serverCerts[type].serverKeyPair->pubKey \ + : NULL) #define SSL_IS_CURVE_NEGOTIATED(curvemsk, curveName) \ - ((curveName > ec_noName) && \ - (curveName < ec_pastLastName) && \ + ((curveName > ec_noName) && \ + (curveName < ec_pastLastName) && \ ((1UL << curveName) & curvemsk) != 0) - - static SECStatus ssl3_CreateECDHEphemeralKeys(sslSocket *ss, ECName ec_curve); #define supportedCurve(x) (((x) > ec_noName) && ((x) < ec_pastLastName)) @@ -57,101 +57,101 @@ static SECStatus ssl3_CreateECDHEphemeralKeys(sslSocket *ss, ECName ec_curve); * ECC-TLS IETF draft. */ static const SECOidTag ecName2OIDTag[] = { - 0, - SEC_OID_SECG_EC_SECT163K1, /* 1 */ - SEC_OID_SECG_EC_SECT163R1, /* 2 */ - SEC_OID_SECG_EC_SECT163R2, /* 3 */ - SEC_OID_SECG_EC_SECT193R1, /* 4 */ - SEC_OID_SECG_EC_SECT193R2, /* 5 */ - SEC_OID_SECG_EC_SECT233K1, /* 6 */ - SEC_OID_SECG_EC_SECT233R1, /* 7 */ - SEC_OID_SECG_EC_SECT239K1, /* 8 */ - SEC_OID_SECG_EC_SECT283K1, /* 9 */ - SEC_OID_SECG_EC_SECT283R1, /* 10 */ - SEC_OID_SECG_EC_SECT409K1, /* 11 */ - SEC_OID_SECG_EC_SECT409R1, /* 12 */ - SEC_OID_SECG_EC_SECT571K1, /* 13 */ - SEC_OID_SECG_EC_SECT571R1, /* 14 */ - SEC_OID_SECG_EC_SECP160K1, /* 15 */ - SEC_OID_SECG_EC_SECP160R1, /* 16 */ - SEC_OID_SECG_EC_SECP160R2, /* 17 */ - SEC_OID_SECG_EC_SECP192K1, /* 18 */ - SEC_OID_SECG_EC_SECP192R1, /* 19 */ - SEC_OID_SECG_EC_SECP224K1, /* 20 */ - SEC_OID_SECG_EC_SECP224R1, /* 21 */ - SEC_OID_SECG_EC_SECP256K1, /* 22 */ - SEC_OID_SECG_EC_SECP256R1, /* 23 */ - SEC_OID_SECG_EC_SECP384R1, /* 24 */ - SEC_OID_SECG_EC_SECP521R1, /* 25 */ + 0, + SEC_OID_SECG_EC_SECT163K1, /* 1 */ + SEC_OID_SECG_EC_SECT163R1, /* 2 */ + SEC_OID_SECG_EC_SECT163R2, /* 3 */ + SEC_OID_SECG_EC_SECT193R1, /* 4 */ + SEC_OID_SECG_EC_SECT193R2, /* 5 */ + SEC_OID_SECG_EC_SECT233K1, /* 6 */ + SEC_OID_SECG_EC_SECT233R1, /* 7 */ + SEC_OID_SECG_EC_SECT239K1, /* 8 */ + SEC_OID_SECG_EC_SECT283K1, /* 9 */ + SEC_OID_SECG_EC_SECT283R1, /* 10 */ + SEC_OID_SECG_EC_SECT409K1, /* 11 */ + SEC_OID_SECG_EC_SECT409R1, /* 12 */ + SEC_OID_SECG_EC_SECT571K1, /* 13 */ + SEC_OID_SECG_EC_SECT571R1, /* 14 */ + SEC_OID_SECG_EC_SECP160K1, /* 15 */ + SEC_OID_SECG_EC_SECP160R1, /* 16 */ + SEC_OID_SECG_EC_SECP160R2, /* 17 */ + SEC_OID_SECG_EC_SECP192K1, /* 18 */ + SEC_OID_SECG_EC_SECP192R1, /* 19 */ + SEC_OID_SECG_EC_SECP224K1, /* 20 */ + SEC_OID_SECG_EC_SECP224R1, /* 21 */ + SEC_OID_SECG_EC_SECP256K1, /* 22 */ + SEC_OID_SECG_EC_SECP256R1, /* 23 */ + SEC_OID_SECG_EC_SECP384R1, /* 24 */ + SEC_OID_SECG_EC_SECP521R1, /* 25 */ }; static const PRUint16 curve2bits[] = { - 0, /* ec_noName = 0, */ - 163, /* ec_sect163k1 = 1, */ - 163, /* ec_sect163r1 = 2, */ - 163, /* ec_sect163r2 = 3, */ - 193, /* ec_sect193r1 = 4, */ - 193, /* ec_sect193r2 = 5, */ - 233, /* ec_sect233k1 = 6, */ - 233, /* ec_sect233r1 = 7, */ - 239, /* ec_sect239k1 = 8, */ - 283, /* ec_sect283k1 = 9, */ - 283, /* ec_sect283r1 = 10, */ - 409, /* ec_sect409k1 = 11, */ - 409, /* ec_sect409r1 = 12, */ - 571, /* ec_sect571k1 = 13, */ - 571, /* ec_sect571r1 = 14, */ - 160, /* ec_secp160k1 = 15, */ - 160, /* ec_secp160r1 = 16, */ - 160, /* ec_secp160r2 = 17, */ - 192, /* ec_secp192k1 = 18, */ - 192, /* ec_secp192r1 = 19, */ - 224, /* ec_secp224k1 = 20, */ - 224, /* ec_secp224r1 = 21, */ - 256, /* ec_secp256k1 = 22, */ - 256, /* ec_secp256r1 = 23, */ - 384, /* ec_secp384r1 = 24, */ - 521, /* ec_secp521r1 = 25, */ - 65535 /* ec_pastLastName */ + 0, /* ec_noName = 0, */ + 163, /* ec_sect163k1 = 1, */ + 163, /* ec_sect163r1 = 2, */ + 163, /* ec_sect163r2 = 3, */ + 193, /* ec_sect193r1 = 4, */ + 193, /* ec_sect193r2 = 5, */ + 233, /* ec_sect233k1 = 6, */ + 233, /* ec_sect233r1 = 7, */ + 239, /* ec_sect239k1 = 8, */ + 283, /* ec_sect283k1 = 9, */ + 283, /* ec_sect283r1 = 10, */ + 409, /* ec_sect409k1 = 11, */ + 409, /* ec_sect409r1 = 12, */ + 571, /* ec_sect571k1 = 13, */ + 571, /* ec_sect571r1 = 14, */ + 160, /* ec_secp160k1 = 15, */ + 160, /* ec_secp160r1 = 16, */ + 160, /* ec_secp160r2 = 17, */ + 192, /* ec_secp192k1 = 18, */ + 192, /* ec_secp192r1 = 19, */ + 224, /* ec_secp224k1 = 20, */ + 224, /* ec_secp224r1 = 21, */ + 256, /* ec_secp256k1 = 22, */ + 256, /* ec_secp256r1 = 23, */ + 384, /* ec_secp384r1 = 24, */ + 521, /* ec_secp521r1 = 25, */ + 65535 /* ec_pastLastName */ }; typedef struct Bits2CurveStr { - PRUint16 bits; - ECName curve; + PRUint16 bits; + ECName curve; } Bits2Curve; -static const Bits2Curve bits2curve [] = { - { 192, ec_secp192r1 /* = 19, fast */ }, - { 160, ec_secp160r2 /* = 17, fast */ }, - { 160, ec_secp160k1 /* = 15, */ }, - { 160, ec_secp160r1 /* = 16, */ }, - { 163, ec_sect163k1 /* = 1, */ }, - { 163, ec_sect163r1 /* = 2, */ }, - { 163, ec_sect163r2 /* = 3, */ }, - { 192, ec_secp192k1 /* = 18, */ }, - { 193, ec_sect193r1 /* = 4, */ }, - { 193, ec_sect193r2 /* = 5, */ }, - { 224, ec_secp224r1 /* = 21, fast */ }, - { 224, ec_secp224k1 /* = 20, */ }, - { 233, ec_sect233k1 /* = 6, */ }, - { 233, ec_sect233r1 /* = 7, */ }, - { 239, ec_sect239k1 /* = 8, */ }, - { 256, ec_secp256r1 /* = 23, fast */ }, - { 256, ec_secp256k1 /* = 22, */ }, - { 283, ec_sect283k1 /* = 9, */ }, - { 283, ec_sect283r1 /* = 10, */ }, - { 384, ec_secp384r1 /* = 24, fast */ }, - { 409, ec_sect409k1 /* = 11, */ }, - { 409, ec_sect409r1 /* = 12, */ }, - { 521, ec_secp521r1 /* = 25, fast */ }, - { 571, ec_sect571k1 /* = 13, */ }, - { 571, ec_sect571r1 /* = 14, */ }, - { 65535, ec_noName } +static const Bits2Curve bits2curve[] = { + { 192, ec_secp192r1 /* = 19, fast */ }, + { 160, ec_secp160r2 /* = 17, fast */ }, + { 160, ec_secp160k1 /* = 15, */ }, + { 160, ec_secp160r1 /* = 16, */ }, + { 163, ec_sect163k1 /* = 1, */ }, + { 163, ec_sect163r1 /* = 2, */ }, + { 163, ec_sect163r2 /* = 3, */ }, + { 192, ec_secp192k1 /* = 18, */ }, + { 193, ec_sect193r1 /* = 4, */ }, + { 193, ec_sect193r2 /* = 5, */ }, + { 224, ec_secp224r1 /* = 21, fast */ }, + { 224, ec_secp224k1 /* = 20, */ }, + { 233, ec_sect233k1 /* = 6, */ }, + { 233, ec_sect233r1 /* = 7, */ }, + { 239, ec_sect239k1 /* = 8, */ }, + { 256, ec_secp256r1 /* = 23, fast */ }, + { 256, ec_secp256k1 /* = 22, */ }, + { 283, ec_sect283k1 /* = 9, */ }, + { 283, ec_sect283r1 /* = 10, */ }, + { 384, ec_secp384r1 /* = 24, fast */ }, + { 409, ec_sect409k1 /* = 11, */ }, + { 409, ec_sect409r1 /* = 12, */ }, + { 521, ec_secp521r1 /* = 25, fast */ }, + { 571, ec_sect571k1 /* = 13, */ }, + { 571, ec_sect571r1 /* = 14, */ }, + { 65535, ec_noName } }; typedef struct ECDHEKeyPairStr { - ssl3KeyPair * pair; - int error; /* error code of the call-once function */ + ssl3KeyPair *pair; + int error; /* error code of the call-once function */ PRCallOnceType once; } ECDHEKeyPair; @@ -159,7 +159,7 @@ typedef struct ECDHEKeyPairStr { static ECDHEKeyPair gECDHEKeyPairs[ec_pastLastName]; SECStatus -ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params) +ssl3_ECName2Params(PLArenaPool *arena, ECName curve, SECKEYECParams *params) { SECOidData *oidData = NULL; PRUint32 policyFlags = 0; @@ -170,10 +170,11 @@ ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params) return SECFailure; } - if ( (NSS_GetAlgorithmPolicy(ecName2OIDTag[curve], &policyFlags) - == SECSuccess) && !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { + if ((NSS_GetAlgorithmPolicy(ecName2OIDTag[curve], &policyFlags) == + SECSuccess) && + !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - return SECFailure; + return SECFailure; } SECITEM_AllocItem(arena, params, (2 + oidData->oid.len)); @@ -192,7 +193,7 @@ ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params) ECName ssl3_PubKey2ECName(SECKEYPublicKey *pubKey) { - SECItem oid = { siBuffer, NULL, 0}; + SECItem oid = { siBuffer, NULL, 0 }; SECOidData *oidData = NULL; PRUint32 policyFlags = 0; ECName i; @@ -210,13 +211,16 @@ ssl3_PubKey2ECName(SECKEYPublicKey *pubKey) * representing a named curve. Here, we strip away everything * before the actual OID and use the OID to look up a named curve. */ - if (params->data[0] != SEC_ASN1_OBJECT_ID) return ec_noName; + if (params->data[0] != SEC_ASN1_OBJECT_ID) + return ec_noName; oid.len = params->len - 2; oid.data = params->data + 2; - if ((oidData = SECOID_FindOID(&oid)) == NULL) return ec_noName; - if ((NSS_GetAlgorithmPolicy(oidData->offset, &policyFlags) - == SECSuccess) && !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { - return ec_noName; + if ((oidData = SECOID_FindOID(&oid)) == NULL) + return ec_noName; + if ((NSS_GetAlgorithmPolicy(oidData->offset, &policyFlags) == + SECSuccess) && + !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { + return ec_noName; } for (i = ec_noName + 1; i < ec_pastLastName; i++) { if (ecName2OIDTag[i] == oidData->offset) @@ -233,22 +237,23 @@ ssl3_ComputeECDHKeyHash(SSLHashType hashAlg, SSL3Random *client_rand, SSL3Random *server_rand, SSL3Hashes *hashes, PRBool bypassPKCS11) { - PRUint8 * hashBuf; - PRUint8 * pBuf; - SECStatus rv = SECSuccess; - unsigned int bufLen; + PRUint8 *hashBuf; + PRUint8 *pBuf; + SECStatus rv = SECSuccess; + unsigned int bufLen; /* * XXX For now, we only support named curves (the appropriate * checks are made before this method is called) so ec_params * takes up only two bytes. ECPoint needs to fit in 256 bytes * (because the spec says the length must fit in one byte) */ - PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 1 + 256]; + PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 1 + 256]; - bufLen = 2*SSL3_RANDOM_LENGTH + ec_params.len + 1 + server_ecpoint.len; + bufLen = 2 * SSL3_RANDOM_LENGTH + ec_params.len + 1 + server_ecpoint.len; if (bufLen <= sizeof buf) { hashBuf = buf; - } else { + } + else { hashBuf = PORT_Alloc(bufLen); if (!hashBuf) { return SECFailure; @@ -256,15 +261,15 @@ ssl3_ComputeECDHKeyHash(SSLHashType hashAlg, } memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); - pBuf = hashBuf + SSL3_RANDOM_LENGTH; + pBuf = hashBuf + SSL3_RANDOM_LENGTH; memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); - pBuf += SSL3_RANDOM_LENGTH; + pBuf += SSL3_RANDOM_LENGTH; memcpy(pBuf, ec_params.data, ec_params.len); - pBuf += ec_params.len; + pBuf += ec_params.len; pBuf[0] = (PRUint8)(server_ecpoint.len); pBuf += 1; memcpy(pBuf, server_ecpoint.data, server_ecpoint.len); - pBuf += server_ecpoint.len; + pBuf += server_ecpoint.len; PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, @@ -272,29 +277,28 @@ ssl3_ComputeECDHKeyHash(SSLHashType hashAlg, PRINT_BUF(95, (NULL, "ECDHkey hash: ", hashBuf, bufLen)); PRINT_BUF(95, (NULL, "ECDHkey hash: MD5 result", - hashes->u.s.md5, MD5_LENGTH)); + hashes->u.s.md5, MD5_LENGTH)); PRINT_BUF(95, (NULL, "ECDHkey hash: SHA1 result", - hashes->u.s.sha, SHA1_LENGTH)); + hashes->u.s.sha, SHA1_LENGTH)); if (hashBuf != buf) PORT_Free(hashBuf); return rv; } - /* Called from ssl3_SendClientKeyExchange(). */ SECStatus -ssl3_SendECDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) +ssl3_SendECDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) { - PK11SymKey * pms = NULL; - SECStatus rv = SECFailure; - PRBool isTLS, isTLS12; - CK_MECHANISM_TYPE target; - SECKEYPublicKey *pubKey = NULL; /* Ephemeral ECDH key */ - SECKEYPrivateKey *privKey = NULL; /* Ephemeral ECDH key */ + PK11SymKey *pms = NULL; + SECStatus rv = SECFailure; + PRBool isTLS, isTLS12; + CK_MECHANISM_TYPE target; + SECKEYPublicKey *pubKey = NULL; /* Ephemeral ECDH key */ + SECKEYPrivateKey *privKey = NULL; /* Ephemeral ECDH key */ - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); @@ -308,29 +312,31 @@ ssl3_SendECDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) privKey = SECKEY_CreateECPrivateKey(&svrPubKey->u.ec.DEREncodedParams, &pubKey, ss->pkcs11PinArg); if (!privKey || !pubKey) { - ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - goto loser; + ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); + rv = SECFailure; + goto loser; } PRINT_BUF(50, (ss, "ECDH public value:", - pubKey->u.ec.publicValue.data, - pubKey->u.ec.publicValue.len)); + pubKey->u.ec.publicValue.data, + pubKey->u.ec.publicValue.len)); if (isTLS12) { target = CKM_TLS12_MASTER_KEY_DERIVE_DH; - } else if (isTLS) { + } + else if (isTLS) { target = CKM_TLS_MASTER_KEY_DERIVE_DH; - } else { + } + else { target = CKM_SSL3_MASTER_KEY_DERIVE_DH; } /* Determine the PMS */ pms = PK11_PubDeriveWithKDF(privKey, svrPubKey, PR_FALSE, NULL, NULL, - CKM_ECDH1_DERIVE, target, CKA_DERIVE, 0, - CKD_NULL, NULL, NULL); + CKM_ECDH1_DERIVE, target, CKA_DERIVE, 0, + CKD_NULL, NULL, NULL); if (pms == NULL) { - SSL3AlertDescription desc = illegal_parameter; + SSL3AlertDescription desc = illegal_parameter; (void)SSL3_SendAlert(ss, alert_fatal, desc); ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); goto loser; @@ -340,23 +346,24 @@ ssl3_SendECDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) privKey = NULL; rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, - pubKey->u.ec.publicValue.len + 1); + pubKey->u.ec.publicValue.len + 1); if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } rv = ssl3_AppendHandshakeVariable(ss, - pubKey->u.ec.publicValue.data, - pubKey->u.ec.publicValue.len, 1); + pubKey->u.ec.publicValue.data, + pubKey->u.ec.publicValue.len, 1); SECKEY_DestroyPublicKey(pubKey); pubKey = NULL; if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } - rv = ssl3_InitPendingCipherSpec(ss, pms); - PK11_FreeSymKey(pms); pms = NULL; + rv = ssl3_InitPendingCipherSpec(ss, pms); + PK11_FreeSymKey(pms); + pms = NULL; if (rv != SECSuccess) { ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); @@ -366,13 +373,15 @@ ssl3_SendECDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) rv = SECSuccess; loser: - if(pms) PK11_FreeSymKey(pms); - if(privKey) SECKEY_DestroyPrivateKey(privKey); - if(pubKey) SECKEY_DestroyPublicKey(pubKey); + if (pms) + PK11_FreeSymKey(pms); + if (privKey) + SECKEY_DestroyPrivateKey(privKey); + if (pubKey) + SECKEY_DestroyPublicKey(pubKey); return rv; } - ECName tls13_GroupForECDHEKeyShare(ssl3KeyPair *pair) { @@ -395,8 +404,8 @@ tls13_EncodeECDHEKeyShareKEX(sslSocket *ss, ssl3KeyPair *pair) { const SECItem *publicValue; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); publicValue = &pair->pubKey->u.ec.publicValue; @@ -413,14 +422,14 @@ ssl3_HandleECDHClientKeyExchange(sslSocket *ss, SSL3Opaque *b, SECKEYPublicKey *srvrPubKey, SECKEYPrivateKey *srvrPrivKey) { - PK11SymKey * pms; - SECStatus rv; - SECKEYPublicKey clntPubKey; - CK_MECHANISM_TYPE target; + PK11SymKey *pms; + SECStatus rv; + SECKEYPublicKey clntPubKey; + CK_MECHANISM_TYPE target; PRBool isTLS, isTLS12; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); clntPubKey.keyType = ecKey; clntPubKey.u.ec.DEREncodedParams.len = @@ -432,7 +441,7 @@ ssl3_HandleECDHClientKeyExchange(sslSocket *ss, SSL3Opaque *b, 1, &b, &length); if (rv != SECSuccess) { SEND_ALERT - return SECFailure; /* XXX Who sets the error code?? */ + return SECFailure; /* XXX Who sets the error code?? */ } isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); @@ -440,16 +449,18 @@ ssl3_HandleECDHClientKeyExchange(sslSocket *ss, SSL3Opaque *b, if (isTLS12) { target = CKM_TLS12_MASTER_KEY_DERIVE_DH; - } else if (isTLS) { + } + else if (isTLS) { target = CKM_TLS_MASTER_KEY_DERIVE_DH; - } else { + } + else { target = CKM_SSL3_MASTER_KEY_DERIVE_DH; } /* Determine the PMS */ pms = PK11_PubDeriveWithKDF(srvrPrivKey, &clntPubKey, PR_FALSE, NULL, NULL, - CKM_ECDH1_DERIVE, target, CKA_DERIVE, 0, - CKD_NULL, NULL, NULL); + CKM_ECDH1_DERIVE, target, CKA_DERIVE, 0, + CKD_NULL, NULL, NULL); if (pms == NULL) { /* last gasp. */ @@ -457,7 +468,7 @@ ssl3_HandleECDHClientKeyExchange(sslSocket *ss, SSL3Opaque *b, return SECFailure; } - rv = ssl3_InitPendingCipherSpec(ss, pms); + rv = ssl3_InitPendingCipherSpec(ss, pms); PK11_FreeSymKey(pms); if (rv != SECSuccess) { SEND_ALERT @@ -474,13 +485,13 @@ SECKEYPublicKey * tls13_ImportECDHKeyShare(sslSocket *ss, SSL3Opaque *b, PRUint32 length, ECName curve) { - PLArenaPool * arena = NULL; + PLArenaPool *arena = NULL; SECKEYPublicKey *peerKey = NULL; SECStatus rv; - SECItem ecPoint = {siBuffer, NULL, 0}; + SECItem ecPoint = { siBuffer, NULL, 0 }; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = ssl3_ConsumeHandshakeVariable(ss, &ecPoint, 1, &b, &length); if (rv != SECSuccess) { @@ -529,18 +540,18 @@ tls13_ImportECDHKeyShare(sslSocket *ss, SSL3Opaque *b, return peerKey; -no_memory: /* no-memory error has already been set. */ +no_memory: /* no-memory error has already been set. */ PORT_FreeArena(arena, PR_FALSE); ssl_MapLowLevelError(SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE); return NULL; } PK11SymKey * -tls13_ComputeECDHSharedKey(sslSocket* ss, +tls13_ComputeECDHSharedKey(sslSocket *ss, SECKEYPrivateKey *myPrivKey, SECKEYPublicKey *peerKey) { - PK11SymKey* shared; + PK11SymKey *shared; /* Determine the PMS */ shared = PK11_PubDeriveWithKDF(myPrivKey, peerKey, PR_FALSE, NULL, NULL, @@ -559,9 +570,9 @@ tls13_ComputeECDHSharedKey(sslSocket* ss, ECName ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits) { - int i; + int i; - for ( i = 0; bits2curve[i].curve != ec_noName; i++) { + for (i = 0; bits2curve[i].curve != ec_noName; i++) { if (bits2curve[i].bits < requiredECCbits) continue; if (SSL_IS_CURVE_NEGOTIATED(curvemsk, bits2curve[i].curve)) { @@ -578,10 +589,10 @@ ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits) ECName ssl3_GetCurveNameForServerSocket(sslSocket *ss) { - SECKEYPublicKey * svrPublicKey = NULL; + SECKEYPublicKey *svrPublicKey = NULL; ECName ec_curve = ec_noName; - int signatureKeyStrength = 521; - int requiredECCbits = ss->sec.secretKeyBits * 2; + int signatureKeyStrength = 521; + int requiredECCbits = ss->sec.secretKeyBits * 2; if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa) { svrPublicKey = SSL_GET_SERVER_PUBLIC_KEY(ss, kt_ecdh); @@ -591,8 +602,9 @@ ssl3_GetCurveNameForServerSocket(sslSocket *ss) PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); return ec_noName; } - signatureKeyStrength = curve2bits[ ec_curve ]; - } else { + signatureKeyStrength = curve2bits[ec_curve]; + } + else { /* RSA is our signing cert */ int serverKeyStrengthInBits; @@ -613,8 +625,8 @@ ssl3_GetCurveNameForServerSocket(sslSocket *ss) signatureKeyStrength = SSL_RSASTRENGTH_TO_ECSTRENGTH(serverKeyStrengthInBits); } - if ( requiredECCbits > signatureKeyStrength ) - requiredECCbits = signatureKeyStrength; + if (requiredECCbits > signatureKeyStrength) + requiredECCbits = signatureKeyStrength; return ssl3_GetCurveWithECKeyStrength(ss->ssl3.hs.negotiatedECCurves, requiredECCbits); @@ -627,7 +639,7 @@ ssl3_ShutdownECDHECurves(void *appData, void *nssData) int i; ECDHEKeyPair *keyPair = &gECDHEKeyPairs[0]; - for (i=0; i < ec_pastLastName; i++, keyPair++) { + for (i = 0; i < ec_pastLastName; i++, keyPair++) { if (keyPair->pair) { ssl3_FreeKeyPair(keyPair->pair); } @@ -649,11 +661,11 @@ ssl3_ECRegister(void) /* Create an ECDHE key pair for a given curve */ SECStatus -ssl3_CreateECDHEphemeralKeyPair(ECName ec_curve, ssl3KeyPair** keyPair) +ssl3_CreateECDHEphemeralKeyPair(ECName ec_curve, ssl3KeyPair **keyPair) { - SECKEYPrivateKey * privKey = NULL; - SECKEYPublicKey * pubKey = NULL; - SECKEYECParams ecParams = { siBuffer, NULL, 0 }; + SECKEYPrivateKey *privKey = NULL; + SECKEYPublicKey *pubKey = NULL; + SECKEYECParams ecParams = { siBuffer, NULL, 0 }; if (ssl3_ECName2Params(NULL, ec_curve, &ecParams) != SECSuccess) { return SECFailure; @@ -677,10 +689,10 @@ ssl3_CreateECDHEphemeralKeyPair(ECName ec_curve, ssl3KeyPair** keyPair) /* CallOnce function, called once for each named curve. */ static PRStatus -ssl3_CreateECDHEphemeralKeyPairOnce(void * arg) +ssl3_CreateECDHEphemeralKeyPairOnce(void *arg) { - ECName ec_curve = (ECName)arg; - ssl3KeyPair * keyPair = NULL; + ECName ec_curve = (ECName)arg; + ssl3KeyPair *keyPair = NULL; PORT_Assert(gECDHEKeyPairs[ec_curve].pair == NULL); @@ -706,7 +718,7 @@ ssl3_CreateECDHEphemeralKeyPairOnce(void * arg) static SECStatus ssl3_CreateECDHEphemeralKeys(sslSocket *ss, ECName ec_curve) { - ssl3KeyPair * keyPair = NULL; + ssl3KeyPair *keyPair = NULL; /* if there's no global key for this curve, make one. */ if (gECDHEKeyPairs[ec_curve].pair == NULL) { @@ -738,18 +750,18 @@ ssl3_CreateECDHEphemeralKeys(sslSocket *ss, ECName ec_curve) SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - PLArenaPool * arena = NULL; - SECKEYPublicKey *peerKey = NULL; - PRBool isTLS, isTLS12; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; - SSL3AlertDescription desc = illegal_parameter; - SSL3Hashes hashes; - SECItem signature = {siBuffer, NULL, 0}; + PLArenaPool *arena = NULL; + SECKEYPublicKey *peerKey = NULL; + PRBool isTLS, isTLS12; + SECStatus rv; + int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; + SSL3AlertDescription desc = illegal_parameter; + SSL3Hashes hashes; + SECItem signature = { siBuffer, NULL, 0 }; - SECItem ec_params = {siBuffer, NULL, 0}; - SECItem ec_point = {siBuffer, NULL, 0}; - unsigned char paramBuf[3]; /* only for curve_type == named_curve */ + SECItem ec_params = { siBuffer, NULL, 0 }; + SECItem ec_point = { siBuffer, NULL, 0 }; + unsigned char paramBuf[3]; /* only for curve_type == named_curve */ SSLSignatureAndHashAlg sigAndHash; sigAndHash.hashAlg = ssl_hash_none; @@ -760,38 +772,38 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) /* XXX This works only for named curves, revisit this when * we support generic curves. */ - ec_params.len = sizeof paramBuf; + ec_params.len = sizeof paramBuf; ec_params.data = paramBuf; rv = ssl3_ConsumeHandshake(ss, ec_params.data, ec_params.len, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed. */ + goto loser; /* malformed. */ } /* Fail if the curve is not a named curve */ if ((ec_params.data[0] != ec_type_named) || (ec_params.data[1] != 0) || !supportedCurve(ec_params.data[2])) { - errCode = SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE; - desc = handshake_failure; - goto alert_loser; + errCode = SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE; + desc = handshake_failure; + goto alert_loser; } rv = ssl3_ConsumeHandshakeVariable(ss, &ec_point, 1, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed. */ + goto loser; /* malformed. */ } /* Fail if the ec point uses compressed representation */ if (ec_point.data[0] != EC_POINT_FORM_UNCOMPRESSED) { - errCode = SEC_ERROR_UNSUPPORTED_EC_POINT_FORM; - desc = handshake_failure; - goto alert_loser; + errCode = SEC_ERROR_UNSUPPORTED_EC_POINT_FORM; + desc = handshake_failure; + goto alert_loser; } if (isTLS12) { rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, &sigAndHash); if (rv != SECSuccess) { - goto loser; /* malformed or unsupported. */ + goto loser; /* malformed or unsupported. */ } rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( ss, &sigAndHash, ss->sec.peerCert); @@ -802,17 +814,17 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed. */ + goto loser; /* malformed. */ } if (length != 0) { if (isTLS) desc = decode_error; - goto alert_loser; /* malformed. */ + goto alert_loser; /* malformed. */ } PRINT_BUF(60, (NULL, "Server EC params", ec_params.data, - ec_params.len)); + ec_params.len)); PRINT_BUF(60, (NULL, "Server EC point", ec_point.data, ec_point.len)); /* failures after this point are not malformed handshakes. */ @@ -833,8 +845,8 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) goto alert_loser; } rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, - isTLS, ss->pkcs11PinArg); - if (rv != SECSuccess) { + isTLS, ss->pkcs11PinArg); + if (rv != SECSuccess) { errCode = ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); goto alert_loser; @@ -850,12 +862,13 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) goto no_memory; } - peerKey->arena = arena; - peerKey->keyType = ecKey; + peerKey->arena = arena; + peerKey->keyType = ecKey; /* set up EC parameters in peerKey */ if (ssl3_ECName2Params(arena, ec_params.data[2], - &peerKey->u.ec.DEREncodedParams) != SECSuccess) { + &peerKey->u.ec.DEREncodedParams) != + SECSuccess) { /* we should never get here since we already * checked that we are dealing with a supported curve */ @@ -864,12 +877,11 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) } /* copy publicValue in peerKey */ - if (SECITEM_CopyItem(arena, &peerKey->u.ec.publicValue, &ec_point)) - { + if (SECITEM_CopyItem(arena, &peerKey->u.ec.publicValue, &ec_point)) { goto no_memory; } - peerKey->pkcs11Slot = NULL; - peerKey->pkcs11ID = CK_INVALID_HANDLE; + peerKey->pkcs11Slot = NULL; + peerKey->pkcs11ID = CK_INVALID_HANDLE; ss->sec.peerKey = peerKey; ss->ssl3.hs.ws = wait_cert_request; @@ -882,10 +894,10 @@ loser: if (arena) { PORT_FreeArena(arena, PR_FALSE); } - PORT_SetError( errCode ); + PORT_SetError(errCode); return SECFailure; -no_memory: /* no-memory error has already been set. */ +no_memory: /* no-memory error has already been set. */ if (arena) { PORT_FreeArena(arena, PR_FALSE); } @@ -898,18 +910,18 @@ ssl3_SendECDHServerKeyExchange( sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash) { - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - SECStatus rv = SECFailure; - int length; - PRBool isTLS, isTLS12; - SECItem signed_hash = {siBuffer, NULL, 0}; - SSL3Hashes hashes; + const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; + SECStatus rv = SECFailure; + int length; + PRBool isTLS, isTLS12; + SECItem signed_hash = { siBuffer, NULL, 0 }; + SSL3Hashes hashes; - SECKEYPublicKey * ecdhePub; - SECItem ec_params = {siBuffer, NULL, 0}; - unsigned char paramBuf[3]; - ECName curve; - SSL3KEAType certIndex; + SECKEYPublicKey *ecdhePub; + SECItem ec_params = { siBuffer, NULL, 0 }; + unsigned char paramBuf[3]; + ECName curve; + SSL3KEAType certIndex; /* Generate ephemeral ECDH key pair and send the public key */ curve = ssl3_GetCurveNameForServerSocket(ss); @@ -919,7 +931,8 @@ ssl3_SendECDHServerKeyExchange( if (ss->opt.reuseServerECDHEKey) { rv = ssl3_CreateECDHEphemeralKeys(ss, curve); - } else { + } + else { rv = ssl3_CreateECDHEphemeralKeyPair(curve, &ss->ephemeralECDHKeyPair); } if (rv != SECSuccess) { @@ -933,14 +946,15 @@ ssl3_SendECDHServerKeyExchange( return SECFailure; } - ec_params.len = sizeof paramBuf; + ec_params.len = sizeof paramBuf; ec_params.data = paramBuf; curve = ssl3_PubKey2ECName(ecdhePub); if (curve != ec_noName) { ec_params.data[0] = ec_type_named; ec_params.data[1] = 0x00; ec_params.data[2] = curve; - } else { + } + else { PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); goto loser; } @@ -971,7 +985,7 @@ ssl3_SendECDHServerKeyExchange( rv = ssl3_SignHashes(&hashes, ss->serverCerts[certIndex].SERVERKEY, &signed_hash, isTLS); if (rv != SECSuccess) { - goto loser; /* ssl3_SignHashes has set err. */ + goto loser; /* ssl3_SignHashes has set err. */ } if (signed_hash.data == NULL) { /* how can this happen and rv == SECSuccess ?? */ @@ -985,31 +999,31 @@ ssl3_SendECDHServerKeyExchange( rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshake(ss, ec_params.data, ec_params.len); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, ecdhePub->u.ec.publicValue.data, ecdhePub->u.ec.publicValue.len, 1); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } if (isTLS12) { rv = ssl3_AppendSignatureAndHashAlgorithm(ss, sigAndHash); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } } rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, signed_hash.len, 2); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } PORT_Free(signed_hash.data); @@ -1061,6 +1075,7 @@ static const ssl3CipherSuite ecdhe_ecdsa_suites[] = { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 0 /* end of list marker */ @@ -1072,6 +1087,7 @@ static const ssl3CipherSuite ecdhe_rsa_suites[] = { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_NULL_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, 0 /* end of list marker */ @@ -1084,6 +1100,7 @@ static const ssl3CipherSuite ecSuites[] = { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, @@ -1091,6 +1108,7 @@ static const ssl3CipherSuite ecSuites[] = { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_RSA_WITH_NULL_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, @@ -1108,7 +1126,7 @@ static const ssl3CipherSuite ecSuites[] = { /* On this socket, Disable the ECC cipher suites in the argument's list */ SECStatus -ssl3_DisableECCSuites(sslSocket * ss, const ssl3CipherSuite * suite) +ssl3_DisableECCSuites(sslSocket *ss, const ssl3CipherSuite *suite) { if (!suite) suite = ecSuites; @@ -1122,9 +1140,9 @@ ssl3_DisableECCSuites(sslSocket * ss, const ssl3CipherSuite * suite) * ECC cipher suites that are not supported by those certs. */ void -ssl3_FilterECCipherSuitesByServerCerts(sslSocket * ss) +ssl3_FilterECCipherSuitesByServerCerts(sslSocket *ss) { - CERTCertificate * svrCert; + CERTCertificate *svrCert; svrCert = ss->serverCerts[kt_rsa].serverCert; if (!svrCert) { @@ -1135,33 +1153,34 @@ ssl3_FilterECCipherSuitesByServerCerts(sslSocket * ss) if (!svrCert) { ssl3_DisableECCSuites(ss, ecdh_suites); ssl3_DisableECCSuites(ss, ecdhe_ecdsa_suites); - } else { + } + else { SECOidTag sigTag = SECOID_GetAlgorithmTag(&svrCert->signature); switch (sigTag) { - case SEC_OID_PKCS1_RSA_ENCRYPTION: - case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: - case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: - ssl3_DisableECCSuites(ss, ecdh_ecdsa_suites); - break; - case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: - case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST: - case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST: - ssl3_DisableECCSuites(ss, ecdh_rsa_suites); - break; - default: - ssl3_DisableECCSuites(ss, ecdh_suites); - break; + case SEC_OID_PKCS1_RSA_ENCRYPTION: + case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION: + case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION: + ssl3_DisableECCSuites(ss, ecdh_ecdsa_suites); + break; + case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE: + case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST: + case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST: + ssl3_DisableECCSuites(ss, ecdh_rsa_suites); + break; + default: + ssl3_DisableECCSuites(ss, ecdh_suites); + break; } } } @@ -1169,13 +1188,13 @@ ssl3_FilterECCipherSuitesByServerCerts(sslSocket * ss) /* Ask: is ANY ECC cipher suite enabled on this socket? */ /* Order(N^2). Yuk. Also, this ignores export policy. */ PRBool -ssl3_IsECCEnabled(sslSocket * ss) +ssl3_IsECCEnabled(sslSocket *ss) { - const ssl3CipherSuite * suite; + const ssl3CipherSuite *suite; PK11SlotInfo *slot; /* make sure we can do ECC */ - slot = PK11_GetBestSlot(CKM_ECDH1_DERIVE, ss->pkcs11PinArg); + slot = PK11_GetBestSlot(CKM_ECDH1_DERIVE, ss->pkcs11PinArg); if (!slot) { return PR_FALSE; } @@ -1183,8 +1202,8 @@ ssl3_IsECCEnabled(sslSocket * ss) /* make sure an ECC cipher is enabled */ for (suite = ecSuites; *suite; ++suite) { - PRBool enabled = PR_FALSE; - SECStatus rv = ssl3_CipherPrefGet(ss, *suite, &enabled); + PRBool enabled = PR_FALSE; + SECStatus rv = ssl3_CipherPrefGet(ss, *suite, &enabled); PORT_Assert(rv == SECSuccess); /* else is coding error */ if (rv == SECSuccess && enabled) @@ -1213,10 +1232,10 @@ static const PRUint8 tlsECList[] = { }; static const PRUint8 ecPtFmt[6] = { - BE(11), /* Extension type */ - BE( 2), /* octets that follow */ - 1, /* octets that follow */ - 0 /* uncompressed type only */ + BE(11), /* Extension type */ + BE(2), /* octets that follow */ + 1, /* octets that follow */ + 0 /* uncompressed type only */ }; /* This function already presumes we can do ECC, ssl3_IsECCEnabled must be @@ -1243,11 +1262,12 @@ ssl3_SuiteBOnly(sslSocket *ss) return PR_FALSE; } -#define APPEND_CURVE(CURVE_ID) \ - if ((NSS_GetAlgorithmPolicy(ecName2OIDTag[CURVE_ID], &policy) \ - == SECFailure) || (policy & NSS_USE_ALG_IN_SSL_KX)) { \ - enabledCurves[pos++] = 0; \ - enabledCurves[pos++] = CURVE_ID; \ +#define APPEND_CURVE(CURVE_ID) \ + if ((NSS_GetAlgorithmPolicy(ecName2OIDTag[CURVE_ID], &policy) == \ + SECFailure) || \ + (policy & NSS_USE_ALG_IN_SSL_KX)) { \ + enabledCurves[pos++] = 0; \ + enabledCurves[pos++] = CURVE_ID; \ } /* Send our "canned" (precompiled) Supported Elliptic Curves extension, @@ -1255,9 +1275,9 @@ ssl3_SuiteBOnly(sslSocket *ss) */ PRInt32 ssl3_SendSupportedCurvesXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) + sslSocket *ss, + PRBool append, + PRUint32 maxBytes) { unsigned char enabledCurves[64]; PRUint32 policy; @@ -1269,40 +1289,40 @@ ssl3_SendSupportedCurvesXtn( if (!ss || !ssl3_IsECCEnabled(ss)) return 0; - PORT_Assert(sizeof(enabledCurves) > sizeof(tlsECList)*2); + PORT_Assert(sizeof(enabledCurves) > sizeof(tlsECList) * 2); if (ssl3_SuiteBOnly(ss)) { - for (i=0; i < sizeof(suiteBECList); i++) { - APPEND_CURVE(suiteBECList[i]); - } + for (i = 0; i < sizeof(suiteBECList); i++) { + APPEND_CURVE(suiteBECList[i]); + } ecListSize = pos; - } else { - for (i=0; i < sizeof(tlsECList); i++) { - APPEND_CURVE(tlsECList[i]); - } + } + else { + for (i = 0; i < sizeof(tlsECList); i++) { + APPEND_CURVE(tlsECList[i]); + } ecListSize = pos; } extension_length = - 2 /* extension type */ + - 2 /* extension length */ + - 2 /* elliptic curves length */ + - ecListSize; - + 2 /* extension type */ + + 2 /* extension length */ + + 2 /* elliptic curves length */ + + ecListSize; if (maxBytes < (PRUint32)extension_length) { return 0; } - + if (append) { - SECStatus rv; - rv = ssl3_AppendHandshakeNumber(ss, ssl_elliptic_curves_xtn, 2); - if (rv != SECSuccess) - return -1; - rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); - if (rv != SECSuccess) - return -1; - rv = ssl3_AppendHandshakeVariable(ss, enabledCurves,ecListSize, 2); - if (rv != SECSuccess) - return -1; + SECStatus rv; + rv = ssl3_AppendHandshakeNumber(ss, ssl_elliptic_curves_xtn, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_AppendHandshakeVariable(ss, enabledCurves, ecListSize, 2); + if (rv != SECSuccess) + return -1; if (!ss->sec.isServer) { TLSExtensionData *xtnData = &ss->xtnData; xtnData->advertised[xtnData->numAdvertised++] = @@ -1316,28 +1336,28 @@ PRUint32 ssl3_GetSupportedECCurveMask(sslSocket *ss) { int i; - PRUint32 curves = 0; + PRUint32 curves = 0; PRUint32 policyFlags = 0; - PORT_Assert(ec_pastLastName < sizeof(PRUint32)*8); - + PORT_Assert(ec_pastLastName < sizeof(PRUint32) * 8); + if (ssl3_SuiteBOnly(ss)) { curves = SSL3_SUITE_B_SUPPORTED_CURVES_MASK; - } else { - curves = SSL3_ALL_SUPPORTED_CURVES_MASK; + } + else { + curves = SSL3_ALL_SUPPORTED_CURVES_MASK; } - for (i= ec_noName+1; i < ec_pastLastName; i++) { - PRUint32 curve_bit = (1U << i); - if ((curves & curve_bit) && - (NSS_GetAlgorithmPolicy(ecName2OIDTag[i], &policyFlags) - == SECSuccess) && - !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { - curves &= ~curve_bit; - } + for (i = ec_noName + 1; i < ec_pastLastName; i++) { + PRUint32 curve_bit = (1U << i); + if ((curves & curve_bit) && + (NSS_GetAlgorithmPolicy(ecName2OIDTag[i], &policyFlags) == + SECSuccess) && + !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) { + curves &= ~curve_bit; + } } return curves; - } /* Send our "canned" (precompiled) Supported Point Formats extension, @@ -1345,9 +1365,9 @@ ssl3_GetSupportedECCurveMask(sslSocket *ss) */ PRInt32 ssl3_SendSupportedPointFormatsXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) + sslSocket *ss, + PRBool append, + PRUint32 maxBytes) { if (!ss || !ssl3_IsECCEnabled(ss)) return 0; @@ -1377,12 +1397,12 @@ ssl3_HandleSupportedPointFormatsXtn(sslSocket *ss, PRUint16 ex_type, data->len != (unsigned int)data->data[0] + 1) { return ssl3_DecodeError(ss); } - for (i = data->len; --i > 0; ) { + for (i = data->len; --i > 0;) { if (data->data[i] == 0) { /* indicate that we should send a reply */ SECStatus rv; rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type, - &ssl3_SendSupportedPointFormatsXtn); + &ssl3_SendSupportedPointFormatsXtn); return rv; } } @@ -1392,16 +1412,16 @@ ssl3_HandleSupportedPointFormatsXtn(sslSocket *ss, PRUint16 ex_type, return SECSuccess; } - -#define SSL3_GET_SERVER_PUBLICKEY(sock, type) \ - (ss->serverCerts[type].serverKeyPair ? \ - ss->serverCerts[type].serverKeyPair->pubKey : NULL) +#define SSL3_GET_SERVER_PUBLICKEY(sock, type) \ + (ss->serverCerts[type].serverKeyPair ? ss->serverCerts[type].serverKeyPair->pubKey \ + : NULL) /* Extract the TLS curve name for the public key in our EC server cert. */ -ECName ssl3_GetSvrCertCurveName(sslSocket *ss) +ECName +ssl3_GetSvrCertCurveName(sslSocket *ss) { - SECKEYPublicKey *srvPublicKey; - ECName ec_curve = ec_noName; + SECKEYPublicKey *srvPublicKey; + ECName ec_curve = ec_noName; srvPublicKey = SSL3_GET_SERVER_PUBLICKEY(ss, kt_ecdh); if (srvPublicKey) { @@ -1416,8 +1436,8 @@ ECName ssl3_GetSvrCertCurveName(sslSocket *ss) SECStatus ssl3_HandleSupportedCurvesXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { - PRInt32 list_len; - PRUint32 peerCurves = 0; + PRInt32 list_len; + PRUint32 peerCurves = 0; PRUint32 mutualCurves = 0; PRUint16 svrCertCurveName; @@ -1435,7 +1455,7 @@ ssl3_HandleSupportedCurvesXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) /* build bit vector of peer's supported curve names */ while (data->len) { PRInt32 curve_name = - ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); if (curve_name < 0) { return SECFailure; /* fatal alert already sent */ } diff --git a/security/nss/lib/ssl/ssl3ext.c b/security/nss/lib/ssl/ssl3ext.c index 0f0885f62308..32ce5d86edc3 100644 --- a/security/nss/lib/ssl/ssl3ext.c +++ b/security/nss/lib/ssl/ssl3ext.c @@ -21,42 +21,42 @@ #endif #include "prinit.h" -static unsigned char key_name[SESS_TICKET_KEY_NAME_LEN]; -static PK11SymKey *session_ticket_enc_key_pkcs11 = NULL; -static PK11SymKey *session_ticket_mac_key_pkcs11 = NULL; +static unsigned char key_name[SESS_TICKET_KEY_NAME_LEN]; +static PK11SymKey *session_ticket_enc_key_pkcs11 = NULL; +static PK11SymKey *session_ticket_mac_key_pkcs11 = NULL; #ifndef NO_PKCS11_BYPASS -static unsigned char session_ticket_enc_key[AES_256_KEY_LENGTH]; -static unsigned char session_ticket_mac_key[SHA256_LENGTH]; +static unsigned char session_ticket_enc_key[AES_256_KEY_LENGTH]; +static unsigned char session_ticket_mac_key[SHA256_LENGTH]; -static PRBool session_ticket_keys_initialized = PR_FALSE; +static PRBool session_ticket_keys_initialized = PR_FALSE; #endif static PRCallOnceType generate_session_keys_once; /* forward static function declarations */ static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss, - SECItem *data, EncryptedSessionTicket *enc_session_ticket); + SECItem *data, EncryptedSessionTicket *enc_session_ticket); static SECStatus ssl3_AppendToItem(SECItem *item, const unsigned char *buf, - PRUint32 bytes); + PRUint32 bytes); static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, - PRInt32 lenSize); + PRInt32 lenSize); static SECStatus ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, - PK11SymKey **aes_key, PK11SymKey **mac_key); + PK11SymKey **aes_key, PK11SymKey **mac_key); #ifndef NO_PKCS11_BYPASS static SECStatus ssl3_GetSessionTicketKeys(const unsigned char **aes_key, - PRUint32 *aes_key_length, const unsigned char **mac_key, - PRUint32 *mac_key_length); + PRUint32 *aes_key_length, const unsigned char **mac_key, + PRUint32 *mac_key_length); #endif -static PRInt32 ssl3_SendRenegotiationInfoXtn(sslSocket * ss, - PRBool append, PRUint32 maxBytes); +static PRInt32 ssl3_SendRenegotiationInfoXtn(sslSocket *ss, + PRBool append, PRUint32 maxBytes); static SECStatus ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); + PRUint16 ex_type, SECItem *data); static SECStatus ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); + PRUint16 ex_type, SECItem *data); static SECStatus ssl3_ClientHandleAppProtoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); + PRUint16 ex_type, SECItem *data); static SECStatus ssl3_ServerHandleNextProtoNegoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); + PRUint16 ex_type, SECItem *data); static SECStatus ssl3_ServerHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data); static PRInt32 ssl3_ClientSendNextProtoNegoXtn(sslSocket *ss, PRBool append, @@ -69,18 +69,18 @@ static PRInt32 ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes); static PRInt32 ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes); -static SECStatus ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, +static SECStatus ssl3_ClientHandleUseSRTPXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data); -static SECStatus ssl3_ServerHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, +static SECStatus ssl3_ServerHandleUseSRTPXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data); -static PRInt32 ssl3_ServerSendStatusRequestXtn(sslSocket * ss, - PRBool append, PRUint32 maxBytes); +static PRInt32 ssl3_ServerSendStatusRequestXtn(sslSocket *ss, + PRBool append, PRUint32 maxBytes); static SECStatus ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); + PRUint16 ex_type, SECItem *data); static SECStatus ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data); -static PRInt32 ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append, +static PRInt32 ssl3_ClientSendStatusRequestXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes); static PRInt32 ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes); @@ -93,7 +93,7 @@ static PRInt32 ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss, static SECStatus ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data); -static PRInt32 ssl3_ServerSendSignedCertTimestampXtn(sslSocket * ss, +static PRInt32 ssl3_ServerSendSignedCertTimestampXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes); static SECStatus ssl3_ServerHandleSignedCertTimestampXtn(sslSocket *ss, @@ -143,24 +143,25 @@ static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize) { SECStatus rv; - PRUint8 b[4]; - PRUint8 * p = b; + PRUint8 b[4]; + PRUint8 *p = b; switch (lenSize) { - case 4: - *p++ = (PRUint8) (num >> 24); - case 3: - *p++ = (PRUint8) (num >> 16); - case 2: - *p++ = (PRUint8) (num >> 8); - case 1: - *p = (PRUint8) num; + case 4: + *p++ = (PRUint8)(num >> 24); + case 3: + *p++ = (PRUint8)(num >> 16); + case 2: + *p++ = (PRUint8)(num >> 8); + case 1: + *p = (PRUint8)num; } rv = ssl3_AppendToItem(item, &b[0], lenSize); return rv; } -static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData) +static SECStatus +ssl3_SessionTicketShutdown(void *appData, void *nssData) { if (session_ticket_enc_key_pkcs11) { PK11_FreeSymKey(session_ticket_enc_key_pkcs11); @@ -171,11 +172,10 @@ static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData) session_ticket_mac_key_pkcs11 = NULL; } PORT_Memset(&generate_session_keys_once, 0, - sizeof(generate_session_keys_once)); + sizeof(generate_session_keys_once)); return SECSuccess; } - static PRStatus ssl3_GenerateSessionTicketKeysPKCS11(void *data) { @@ -186,16 +186,16 @@ ssl3_GenerateSessionTicketKeysPKCS11(void *data) if (svrPrivKey == NULL || svrPubKey == NULL) { SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); goto loser; } /* Get a copy of the session keys from shared memory. */ PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX, - sizeof(SESS_TICKET_KEY_NAME_PREFIX)); + sizeof(SESS_TICKET_KEY_NAME_PREFIX)); if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey, - ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], - &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11)) + ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], + &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11)) return PR_FAILURE; rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL); @@ -214,7 +214,8 @@ ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key, PK11SymKey **mac_key) { if (PR_CallOnceWithArg(&generate_session_keys_once, - ssl3_GenerateSessionTicketKeysPKCS11, ss) != PR_SUCCESS) + ssl3_GenerateSessionTicketKeysPKCS11, ss) != + PR_SUCCESS) return SECFailure; if (session_ticket_enc_key_pkcs11 == NULL || @@ -231,10 +232,10 @@ static PRStatus ssl3_GenerateSessionTicketKeys(void) { PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX, - sizeof(SESS_TICKET_KEY_NAME_PREFIX)); + sizeof(SESS_TICKET_KEY_NAME_PREFIX)); if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], - session_ticket_enc_key, session_ticket_mac_key)) + session_ticket_enc_key, session_ticket_mac_key)) return PR_FAILURE; session_ticket_keys_initialized = PR_TRUE; @@ -243,11 +244,11 @@ ssl3_GenerateSessionTicketKeys(void) static SECStatus ssl3_GetSessionTicketKeys(const unsigned char **aes_key, - PRUint32 *aes_key_length, const unsigned char **mac_key, - PRUint32 *mac_key_length) + PRUint32 *aes_key_length, const unsigned char **mac_key, + PRUint32 *mac_key_length) { if (PR_CallOnce(&generate_session_keys_once, - ssl3_GenerateSessionTicketKeys) != PR_SUCCESS) + ssl3_GenerateSessionTicketKeys) != PR_SUCCESS) return SECFailure; if (!session_ticket_keys_initialized) @@ -268,17 +269,17 @@ ssl3_GetSessionTicketKeys(const unsigned char **aes_key, */ /* This table is used by the server, to handle client hello extensions. */ static const ssl3HelloExtensionHandler clientHelloHandlers[] = { - { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, + { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, #ifndef NSS_DISABLE_ECC - { ssl_elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn }, - { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn }, + { ssl_elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn }, + { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn }, #endif - { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn }, + { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn }, { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn }, - { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn }, + { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn }, { ssl_app_layer_protocol_xtn, &ssl3_ServerHandleAppProtoXtn }, - { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn }, - { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn }, + { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn }, + { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn }, { ssl_signature_algorithms_xtn, &ssl3_ServerHandleSigAlgsXtn }, { ssl_tls13_draft_version_xtn, &ssl3_ServerHandleDraftVersionXtn }, { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn }, @@ -290,17 +291,17 @@ static const ssl3HelloExtensionHandler clientHelloHandlers[] = { /* These two tables are used by the client, to handle server hello * extensions. */ static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = { - { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, + { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, /* TODO: add a handler for ssl_ec_point_formats_xtn */ - { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn }, + { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn }, { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn }, - { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn }, + { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn }, { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn }, - { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn }, - { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn }, + { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn }, + { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn }, { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn }, { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn }, - { ssl_tls13_key_share_xtn, &tls13_ClientHandleKeyShareXtn }, + { ssl_tls13_key_share_xtn, &tls13_ClientHandleKeyShareXtn }, { -1, NULL } }; @@ -315,32 +316,32 @@ static const ssl3HelloExtensionHandler serverHelloHandlersSSL3[] = { * The server's table of hello senders is dynamic, in the socket struct, * and sender functions are registered there. */ -static const -ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = { - { ssl_server_name_xtn, &ssl3_SendServerNameXtn }, - { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }, +static const ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = + { + { ssl_server_name_xtn, &ssl3_SendServerNameXtn }, + { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }, #ifndef NSS_DISABLE_ECC - { ssl_elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn }, - { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn }, + { ssl_elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn }, + { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn }, #endif - { ssl_session_ticket_xtn, &ssl3_SendSessionTicketXtn }, - { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn }, - { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn }, - { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn }, - { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn }, - { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn }, - { ssl_tls13_draft_version_xtn, &ssl3_ClientSendDraftVersionXtn }, - { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn}, - { ssl_signed_cert_timestamp_xtn, &ssl3_ClientSendSignedCertTimestampXtn }, - { ssl_tls13_key_share_xtn, &tls13_ClientSendKeyShareXtn }, - /* any extra entries will appear as { 0, NULL } */ -}; + { ssl_session_ticket_xtn, &ssl3_SendSessionTicketXtn }, + { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn }, + { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn }, + { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn }, + { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn }, + { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn }, + { ssl_tls13_draft_version_xtn, &ssl3_ClientSendDraftVersionXtn }, + { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn }, + { ssl_signed_cert_timestamp_xtn, &ssl3_ClientSendSignedCertTimestampXtn }, + { ssl_tls13_key_share_xtn, &tls13_ClientSendKeyShareXtn }, + /* any extra entries will appear as { 0, NULL } */ + }; -static const -ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = { - { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn } - /* any extra entries will appear as { 0, NULL } */ -}; +static const ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = + { + { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn } + /* any extra entries will appear as { 0, NULL } */ + }; static PRBool arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type) @@ -354,14 +355,16 @@ arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type) } PRBool -ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) { +ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) +{ TLSExtensionData *xtnData = &ss->xtnData; return arrayContainsExtension(xtnData->negotiated, xtnData->numNegotiated, ex_type); } static PRBool -ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) { +ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) +{ TLSExtensionData *xtnData = &ss->xtnData; return arrayContainsExtension(xtnData->advertised, xtnData->numAdvertised, ex_type); @@ -372,7 +375,7 @@ ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) { * Used by client and server. */ PRInt32 -ssl3_SendServerNameXtn(sslSocket * ss, PRBool append, +ssl3_SendServerNameXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { SECStatus rv; @@ -390,23 +393,28 @@ ssl3_SendServerNameXtn(sslSocket * ss, PRBool append, /* is an IP address (v4 or v6) */ return 0; } - len = PORT_Strlen(ss->url); + len = PORT_Strlen(ss->url); if (append && maxBytes >= len + 9) { /* extension_type */ rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* length of extension_data */ rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* length of server_name_list */ rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* Name Type (sni_host_name) */ - rv = ssl3_AppendHandshake(ss, "\0", 1); - if (rv != SECSuccess) return -1; + rv = ssl3_AppendHandshake(ss, "\0", 1); + if (rv != SECSuccess) + return -1; /* HostName (length and value) */ rv = ssl3_AppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; if (!ss->sec.isServer) { TLSExtensionData *xtnData = &ss->xtnData; xtnData->advertised[xtnData->numAdvertised++] = @@ -418,23 +426,25 @@ ssl3_SendServerNameXtn(sslSocket * ss, PRBool append, /* Server side */ if (append && maxBytes >= 4) { rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* length of extension_data */ rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; } return 4; } /* handle an incoming SNI extension, by ignoring it. */ SECStatus -ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +ssl3_HandleServerNameXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { SECItem *names = NULL; PRUint32 listCount = 0, namesPos = 0, i; TLSExtensionData *xtnData = &ss->xtnData; - SECItem ldata; - PRInt32 listLenBytes = 0; + SECItem ldata; + PRInt32 listLenBytes = 0; if (!ss->sec.isServer) { return SECSuccess; /* ignore extension */ @@ -481,15 +491,15 @@ ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) if (!names) { return SECFailure; } - for (i = 0;i < listCount;i++) { + for (i = 0; i < listCount; i++) { unsigned int j; - PRInt32 type; + PRInt32 type; SECStatus rv; PRBool nametypePresent = PR_FALSE; /* Name Type (sni_host_name) */ type = ssl3_ConsumeHandshakeNumber(ss, 1, &data->data, &data->len); /* Check if we have such type in the list */ - for (j = 0;j < listCount && names[j].data;j++) { + for (j = 0; j < listCount && names[j].data; j++) { /* TODO bug 998524: .type is not assigned a value */ if (names[j].type == type) { nametypePresent = PR_TRUE; @@ -526,9 +536,9 @@ ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) */ PRInt32 ssl3_SendSessionTicketXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) + sslSocket *ss, + PRBool append, + PRUint32 maxBytes) { PRInt32 extension_length; NewSessionTicket *session_ticket = NULL; @@ -560,10 +570,12 @@ ssl3_SendSessionTicketXtn( if (session_ticket->ticket.data) { if (ss->xtnData.ticketTimestampVerified) { extension_length += session_ticket->ticket.len; - } else if (!append && - (session_ticket->ticket_lifetime_hint == 0 || - (session_ticket->ticket_lifetime_hint + - session_ticket->received_timestamp > ssl_Time()))) { + } + else if (!append && + (session_ticket->ticket_lifetime_hint == 0 || + (session_ticket->ticket_lifetime_hint + + session_ticket->received_timestamp > + ssl_Time()))) { extension_length += session_ticket->ticket.len; ss->xtnData.ticketTimestampVerified = PR_TRUE; } @@ -583,10 +595,11 @@ ssl3_SendSessionTicketXtn( if (session_ticket && session_ticket->ticket.data && ss->xtnData.ticketTimestampVerified) { rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data, - session_ticket->ticket.len, 2); + session_ticket->ticket.len, 2); ss->xtnData.ticketTimestampVerified = PR_FALSE; ss->xtnData.sentSessionTicketInClientHello = PR_TRUE; - } else { + } + else { rv = ssl3_AppendHandshakeNumber(ss, 0, 2); } if (rv != SECSuccess) @@ -600,14 +613,14 @@ ssl3_SendSessionTicketXtn( } return extension_length; - loser: +loser: ss->xtnData.ticketTimestampVerified = PR_FALSE; return -1; } /* handle an incoming Next Protocol Negotiation extension. */ static SECStatus -ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type, +ssl3_ServerHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { if (ss->firstHsDone || data->len != 0) { @@ -629,12 +642,12 @@ ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type, * of the lengths may be 0 and the sum of the lengths must equal the length of * the block. */ SECStatus -ssl3_ValidateNextProtoNego(const unsigned char* data, unsigned int length) +ssl3_ValidateNextProtoNego(const unsigned char *data, unsigned int length) { unsigned int offset = 0; while (offset < length) { - unsigned int newOffset = offset + 1 + (unsigned int) data[offset]; + unsigned int newOffset = offset + 1 + (unsigned int)data[offset]; /* Reject embedded nulls to protect against buggy applications that * store protocol identifiers in null-terminated strings. */ @@ -730,7 +743,7 @@ ssl3_ServerHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) rv = ssl3_SelectAppProtocol(ss, ex_type, data); if (rv != SECSuccess) { - return rv; + return rv; } /* prepare to send back a response, if we negotiated */ @@ -824,7 +837,7 @@ ssl3_ClientHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) } static PRInt32 -ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss, PRBool append, +ssl3_ClientSendNextProtoNegoXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { PRInt32 extension_length; @@ -848,7 +861,7 @@ ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss, PRBool append, if (rv != SECSuccess) goto loser; ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_next_proto_nego_xtn; + ssl_next_proto_nego_xtn; } return extension_length; @@ -858,7 +871,7 @@ loser: } static PRInt32 -ssl3_ClientSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) +ssl3_ClientSendAppProtoXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { PRInt32 extension_length; unsigned char *alpn_protos = NULL; @@ -893,7 +906,8 @@ ssl3_ClientSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) if (i <= len) { memcpy(alpn_protos, &ss->opt.nextProtoNego.data[i], len - i); memcpy(alpn_protos + len - i, ss->opt.nextProtoNego.data, i); - } else { + } + else { /* This seems to be invalid data so we'll send as-is. */ memcpy(alpn_protos, ss->opt.nextProtoNego.data, len); } @@ -914,7 +928,7 @@ ssl3_ClientSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) goto loser; } ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_app_layer_protocol_xtn; + ssl_app_layer_protocol_xtn; } return extension_length; @@ -927,7 +941,7 @@ loser: } static PRInt32 -ssl3_ServerSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) +ssl3_ServerSendAppProtoXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { PRInt32 extension_length; @@ -971,11 +985,11 @@ ssl3_ServerSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) static SECStatus ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data) + SECItem *data) { /* The echoed extension must be empty. */ if (data->len != 0) { - return SECSuccess; /* Ignore the extension. */ + return SECSuccess; /* Ignore the extension. */ } /* Keep track of negotiated extensions. */ @@ -986,9 +1000,9 @@ ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type, static PRInt32 ssl3_ServerSendStatusRequestXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) + sslSocket *ss, + PRBool append, + PRUint32 maxBytes) { PRInt32 extension_length; SSLKEAType effectiveExchKeyType; @@ -1001,7 +1015,8 @@ ssl3_ServerSendStatusRequestXtn( if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { effectiveExchKeyType = ssl_kea_rsa; - } else { + } + else { effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; } @@ -1032,13 +1047,13 @@ ssl3_ServerSendStatusRequestXtn( /* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the * client side. See RFC 4366 section 3.6. */ static PRInt32 -ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append, - PRUint32 maxBytes) +ssl3_ClientSendStatusRequestXtn(sslSocket *ss, PRBool append, + PRUint32 maxBytes) { PRInt32 extension_length; if (!ss->opt.enableOCSPStapling) - return 0; + return 0; /* extension_type (2-bytes) + * length(extension_data) (2-bytes) + @@ -1049,37 +1064,37 @@ ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append, extension_length = 9; if (maxBytes < (PRUint32)extension_length) { - PORT_Assert(0); - return 0; + PORT_Assert(0); + return 0; } if (append) { - SECStatus rv; - TLSExtensionData *xtnData; + SECStatus rv; + TLSExtensionData *xtnData; - /* extension_type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); - if (rv != SECSuccess) - return -1; - rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); - if (rv != SECSuccess) - return -1; - rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1); - if (rv != SECSuccess) - return -1; - /* A zero length responder_id_list means that the responders are - * implicitly known to the server. */ - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) - return -1; - /* A zero length request_extensions means that there are no extensions. - * Specifically, we don't set the id-pkix-ocsp-nonce extension. This - * means that the server can replay a cached OCSP response to us. */ - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) - return -1; + /* extension_type */ + rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1); + if (rv != SECSuccess) + return -1; + /* A zero length responder_id_list means that the responders are + * implicitly known to the server. */ + rv = ssl3_AppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + /* A zero length request_extensions means that there are no extensions. + * Specifically, we don't set the id-pkix-ocsp-nonce extension. This + * means that the server can replay a cached OCSP response to us. */ + rv = ssl3_AppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; - xtnData = &ss->xtnData; - xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn; + xtnData = &ss->xtnData; + xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn; } return extension_length; } @@ -1092,52 +1107,52 @@ SECStatus ssl3_SendNewSessionTicket(sslSocket *ss) { PRUint32 i; - SECStatus rv; - NewSessionTicket ticket; - SECItem plaintext; - SECItem plaintext_item = {0, NULL, 0}; - SECItem ciphertext = {0, NULL, 0}; - PRUint32 ciphertext_length; - PRBool ms_is_wrapped; - unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH]; - SECItem ms_item = {0, NULL, 0}; - SSL3KEAType effectiveExchKeyType = ssl_kea_null; - PRUint32 padding_length; - PRUint32 message_length; - PRUint32 cert_length = 0; - PRUint8 length_buf[4]; - PRUint32 now; - PK11SymKey *aes_key_pkcs11; - PK11SymKey *mac_key_pkcs11; + SECStatus rv; + NewSessionTicket ticket; + SECItem plaintext; + SECItem plaintext_item = { 0, NULL, 0 }; + SECItem ciphertext = { 0, NULL, 0 }; + PRUint32 ciphertext_length; + PRBool ms_is_wrapped; + unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH]; + SECItem ms_item = { 0, NULL, 0 }; + SSL3KEAType effectiveExchKeyType = ssl_kea_null; + PRUint32 padding_length; + PRUint32 message_length; + PRUint32 cert_length = 0; + PRUint8 length_buf[4]; + PRUint32 now; + PK11SymKey *aes_key_pkcs11; + PK11SymKey *mac_key_pkcs11; #ifndef NO_PKCS11_BYPASS const unsigned char *aes_key; const unsigned char *mac_key; - PRUint32 aes_key_length; - PRUint32 mac_key_length; - PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; - AESContext *aes_ctx; + PRUint32 aes_key_length; + PRUint32 mac_key_length; + PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; + AESContext *aes_ctx; const SECHashObject *hashObj = NULL; - PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; - HMACContext *hmac_ctx; + PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; + HMACContext *hmac_ctx; #endif - CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; - PK11Context *aes_ctx_pkcs11; - CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; - PK11Context *hmac_ctx_pkcs11 = NULL; - unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; - unsigned int computed_mac_length; - unsigned char iv[AES_BLOCK_SIZE]; - SECItem ivItem; - SECItem *srvName = NULL; - PRUint32 srvNameLen = 0; - CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value, + CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; + PK11Context *aes_ctx_pkcs11; + CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; + PK11Context *hmac_ctx_pkcs11 = NULL; + unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; + unsigned int computed_mac_length; + unsigned char iv[AES_BLOCK_SIZE]; + SECItem ivItem; + SECItem *srvName = NULL; + PRUint32 srvNameLen = 0; + CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value, * must be >= 0 */ SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT; if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) { @@ -1148,26 +1163,30 @@ ssl3_SendNewSessionTicket(sslSocket *ss) ivItem.data = iv; ivItem.len = sizeof(iv); rv = PK11_GenerateRandom(iv, sizeof(iv)); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length, - &mac_key, &mac_key_length); - } else + &mac_key, &mac_key_length); + } + else #endif { rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11, - &mac_key_pkcs11); + &mac_key_pkcs11); } - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) { /* The master secret is available unwrapped. */ ms_item.data = ss->ssl3.pwSpec->msItem.data; ms_item.len = ss->ssl3.pwSpec->msItem.len; ms_is_wrapped = PR_FALSE; - } else { + } + else { /* Extract the master secret wrapped. */ sslSessionID sid; PORT_Memset(&sid, 0, sizeof(sslSessionID)); @@ -1175,21 +1194,23 @@ ssl3_SendNewSessionTicket(sslSocket *ss) if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { effectiveExchKeyType = kt_rsa; - } else { + } + else { effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; } rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec, - effectiveExchKeyType); + effectiveExchKeyType); if (rv == SECSuccess) { if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms)) goto loser; memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret, - sid.u.ssl3.keys.wrapped_master_secret_len); + sid.u.ssl3.keys.wrapped_master_secret_len); ms_item.data = wrapped_ms; ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len; msWrapMech = sid.u.ssl3.masterWrapMech; - } else { + } + else { /* TODO: else send an empty ticket. */ goto loser; } @@ -1202,34 +1223,35 @@ ssl3_SendNewSessionTicket(sslSocket *ss) } ciphertext_length = - sizeof(PRUint16) /* ticket_version */ - + sizeof(SSL3ProtocolVersion) /* ssl_version */ - + sizeof(ssl3CipherSuite) /* ciphersuite */ - + 1 /* compression */ - + 10 /* cipher spec parameters */ - + 1 /* SessionTicket.ms_is_wrapped */ - + 1 /* effectiveExchKeyType */ - + 4 /* msWrapMech */ - + 2 /* master_secret.length */ - + ms_item.len /* master_secret */ - + 1 /* client_auth_type */ - + cert_length /* cert */ - + 1 /* server name type */ - + srvNameLen /* name len + length field */ - + 1 /* extendedMasterSecretUsed */ + sizeof(PRUint16) /* ticket_version */ + + sizeof(SSL3ProtocolVersion) /* ssl_version */ + + sizeof(ssl3CipherSuite) /* ciphersuite */ + + 1 /* compression */ + + 10 /* cipher spec parameters */ + + 1 /* SessionTicket.ms_is_wrapped */ + + 1 /* effectiveExchKeyType */ + + 4 /* msWrapMech */ + + 2 /* master_secret.length */ + + ms_item.len /* master_secret */ + + 1 /* client_auth_type */ + + cert_length /* cert */ + + 1 /* server name type */ + + srvNameLen /* name len + length field */ + + 1 /* extendedMasterSecretUsed */ + sizeof(ticket.ticket_lifetime_hint); - padding_length = AES_BLOCK_SIZE - - (ciphertext_length % AES_BLOCK_SIZE); + padding_length = AES_BLOCK_SIZE - + (ciphertext_length % + AES_BLOCK_SIZE); ciphertext_length += padding_length; message_length = - sizeof(ticket.ticket_lifetime_hint) /* ticket_lifetime_hint */ - + 2 /* length field for NewSessionTicket.ticket */ - + SESS_TICKET_KEY_NAME_LEN /* key_name */ - + AES_BLOCK_SIZE /* iv */ - + 2 /* length field for NewSessionTicket.ticket.encrypted_state */ - + ciphertext_length /* encrypted_state */ - + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */ + sizeof(ticket.ticket_lifetime_hint) /* ticket_lifetime_hint */ + + 2 /* length field for NewSessionTicket.ticket */ + + SESS_TICKET_KEY_NAME_LEN /* key_name */ + + AES_BLOCK_SIZE /* iv */ + + 2 /* length field for NewSessionTicket.ticket.encrypted_state */ + + ciphertext_length /* encrypted_state */ + + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */ if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL) goto loser; @@ -1238,87 +1260,111 @@ ssl3_SendNewSessionTicket(sslSocket *ss) /* ticket_version */ rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION, - sizeof(PRUint16)); - if (rv != SECSuccess) goto loser; + sizeof(PRUint16)); + if (rv != SECSuccess) + goto loser; /* ssl_version */ rv = ssl3_AppendNumberToItem(&plaintext, ss->version, - sizeof(SSL3ProtocolVersion)); - if (rv != SECSuccess) goto loser; + sizeof(SSL3ProtocolVersion)); + if (rv != SECSuccess) + goto loser; /* ciphersuite */ rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) goto loser; + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) + goto loser; /* compression */ rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; /* cipher spec parameters */ rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; /* master_secret */ rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; /* client_identity */ if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) { rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendNumberToItem(&plaintext, - ss->sec.ci.sid->peerCert->derCert.len, 3); - if (rv != SECSuccess) goto loser; + ss->sec.ci.sid->peerCert->derCert.len, 3); + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendToItem(&plaintext, - ss->sec.ci.sid->peerCert->derCert.data, - ss->sec.ci.sid->peerCert->derCert.len); - if (rv != SECSuccess) goto loser; - } else { + ss->sec.ci.sid->peerCert->derCert.data, + ss->sec.ci.sid->peerCert->derCert.len); + if (rv != SECSuccess) + goto loser; + } + else { rv = ssl3_AppendNumberToItem(&plaintext, 0, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; } /* timestamp */ now = ssl_Time(); rv = ssl3_AppendNumberToItem(&plaintext, now, - sizeof(ticket.ticket_lifetime_hint)); - if (rv != SECSuccess) goto loser; + sizeof(ticket.ticket_lifetime_hint)); + if (rv != SECSuccess) + goto loser; if (srvNameLen) { /* Name Type (sni_host_name) */ rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; /* HostName (length and value) */ rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len); - if (rv != SECSuccess) goto loser; - } else { + if (rv != SECSuccess) + goto loser; + } + else { /* No Name */ - rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME, - 1); - if (rv != SECSuccess) goto loser; + rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME, 1); + if (rv != SECSuccess) + goto loser; } /* extendedMasterSecretUsed */ rv = ssl3_AppendNumberToItem( &plaintext, ss->sec.ci.sid->u.ssl3.keys.extendedMasterSecretUsed, 1); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; PORT_Assert(plaintext.len == padding_length); for (i = 0; i < padding_length; i++) @@ -1329,45 +1375,49 @@ ssl3_SendNewSessionTicket(sslSocket *ss) goto loser; } - /* Generate encrypted portion of ticket. */ +/* Generate encrypted portion of ticket. */ #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { aes_ctx = (AESContext *)aes_ctx_buf; rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv, - NSS_AES_CBC, 1, AES_BLOCK_SIZE); - if (rv != SECSuccess) goto loser; + NSS_AES_CBC, 1, AES_BLOCK_SIZE); + if (rv != SECSuccess) + goto loser; rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len, - ciphertext.len, plaintext_item.data, - plaintext_item.len); - if (rv != SECSuccess) goto loser; - } else + ciphertext.len, plaintext_item.data, + plaintext_item.len); + if (rv != SECSuccess) + goto loser; + } + else #endif { aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech, - CKA_ENCRYPT, aes_key_pkcs11, &ivItem); + CKA_ENCRYPT, aes_key_pkcs11, &ivItem); if (!aes_ctx_pkcs11) goto loser; rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data, - (int *)&ciphertext.len, ciphertext.len, - plaintext_item.data, plaintext_item.len); + (int *)&ciphertext.len, ciphertext.len, + plaintext_item.data, plaintext_item.len); PK11_Finalize(aes_ctx_pkcs11); PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; } /* Convert ciphertext length to network order. */ length_buf[0] = (ciphertext.len >> 8) & 0xff; - length_buf[1] = (ciphertext.len ) & 0xff; + length_buf[1] = (ciphertext.len) & 0xff; - /* Compute MAC. */ +/* Compute MAC. */ #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { hmac_ctx = (HMACContext *)hmac_ctx_buf; hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); if (HMAC_Init(hmac_ctx, hashObj, mac_key, - mac_key_length, PR_FALSE) != SECSuccess) + mac_key_length, PR_FALSE) != SECSuccess) goto loser; HMAC_Begin(hmac_ctx); @@ -1376,57 +1426,72 @@ ssl3_SendNewSessionTicket(sslSocket *ss) HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2); HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len); HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length, - sizeof(computed_mac)); - } else + sizeof(computed_mac)); + } + else #endif { SECItem macParam; macParam.data = NULL; macParam.len = 0; hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech, - CKA_SIGN, mac_key_pkcs11, &macParam); + CKA_SIGN, mac_key_pkcs11, &macParam); if (!hmac_ctx_pkcs11) goto loser; rv = PK11_DigestBegin(hmac_ctx_pkcs11); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name, - SESS_TICKET_KEY_NAME_LEN); - if (rv != SECSuccess) goto loser; + SESS_TICKET_KEY_NAME_LEN); + if (rv != SECSuccess) + goto loser; rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv)); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac, - &computed_mac_length, sizeof(computed_mac)); - if (rv != SECSuccess) goto loser; + &computed_mac_length, sizeof(computed_mac)); + if (rv != SECSuccess) + goto loser; } /* Serialize the handshake message. */ rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint, - sizeof(ticket.ticket_lifetime_hint)); - if (rv != SECSuccess) goto loser; + sizeof(ticket.ticket_lifetime_hint)); + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendHandshakeNumber(ss, - message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2); - if (rv != SECSuccess) goto loser; + message_length - sizeof(ticket.ticket_lifetime_hint) - 2, + 2); + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendHandshake(ss, iv, sizeof(iv)); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; loser: if (hmac_ctx_pkcs11) @@ -1447,7 +1512,7 @@ ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { if (data->len != 0) { - return SECSuccess; /* Ignore the extension. */ + return SECSuccess; /* Ignore the extension. */ } /* Keep track of negotiated extensions. */ @@ -1479,36 +1544,37 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, */ if (data->len == 0) { ss->xtnData.emptySessionTicket = PR_TRUE; - } else { + } + else { PRUint32 i; - SECItem extension_data; + SECItem extension_data; EncryptedSessionTicket enc_session_ticket; - unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; - unsigned int computed_mac_length; + unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; + unsigned int computed_mac_length; #ifndef NO_PKCS11_BYPASS - const SECHashObject *hashObj; - const unsigned char *aes_key; - const unsigned char *mac_key; - PRUint32 aes_key_length; - PRUint32 mac_key_length; - PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; - HMACContext *hmac_ctx; - PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; - AESContext *aes_ctx; + const SECHashObject *hashObj; + const unsigned char *aes_key; + const unsigned char *mac_key; + PRUint32 aes_key_length; + PRUint32 mac_key_length; + PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; + HMACContext *hmac_ctx; + PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; + AESContext *aes_ctx; #endif - PK11SymKey *aes_key_pkcs11; - PK11SymKey *mac_key_pkcs11; - PK11Context *hmac_ctx_pkcs11; - CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; - PK11Context *aes_ctx_pkcs11; - CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; - unsigned char * padding; - PRUint32 padding_length; - unsigned char *buffer; - unsigned int buffer_len; - PRInt32 temp; - SECItem cert_item; - PRInt8 nameType = TLS_STE_NO_SERVER_NAME; + PK11SymKey *aes_key_pkcs11; + PK11SymKey *mac_key_pkcs11; + PK11Context *hmac_ctx_pkcs11; + CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; + PK11Context *aes_ctx_pkcs11; + CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; + unsigned char *padding; + PRUint32 padding_length; + unsigned char *buffer; + unsigned int buffer_len; + PRInt32 temp; + SECItem cert_item; + PRInt8 nameType = TLS_STE_NO_SERVER_NAME; /* Turn off stateless session resumption if the client sends a * SessionTicket extension, even if the extension turns out to be @@ -1525,25 +1591,26 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, extension_data.data = data->data; /* Keep a copy for future use. */ extension_data.len = data->len; - if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket) - != SECSuccess) { + if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket) != + SECSuccess) { return SECSuccess; /* Pretend it isn't there */ } - /* Get session ticket keys. */ +/* Get session ticket keys. */ #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length, - &mac_key, &mac_key_length); - } else + &mac_key, &mac_key_length); + } + else #endif { rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11, - &mac_key_pkcs11); + &mac_key_pkcs11); } if (rv != SECSuccess) { SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); goto loser; } @@ -1551,9 +1618,9 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, * from the one we have, bypass ticket processing. */ if (PORT_Memcmp(enc_session_ticket.key_name, key_name, - SESS_TICKET_KEY_NAME_LEN) != 0) { + SESS_TICKET_KEY_NAME_LEN) != 0) { SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); goto no_ticket; } @@ -1565,47 +1632,51 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, hmac_ctx = (HMACContext *)hmac_ctx_buf; hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); if (HMAC_Init(hmac_ctx, hashObj, mac_key, - sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess) + sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess) goto no_ticket; HMAC_Begin(hmac_ctx); HMAC_Update(hmac_ctx, extension_data.data, - extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH); + extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH); if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length, - sizeof(computed_mac)) != SECSuccess) + sizeof(computed_mac)) != SECSuccess) goto no_ticket; - } else + } + else #endif { SECItem macParam; macParam.data = NULL; macParam.len = 0; hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech, - CKA_SIGN, mac_key_pkcs11, &macParam); + CKA_SIGN, mac_key_pkcs11, &macParam); if (!hmac_ctx_pkcs11) { SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.", - SSL_GETPID(), ss->fd, PORT_GetError())); + SSL_GETPID(), ss->fd, PORT_GetError())); goto no_ticket; - } else { + } + else { SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); } rv = PK11_DigestBegin(hmac_ctx_pkcs11); rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data, - extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH); + extension_data.len - + TLS_EX_SESS_TICKET_MAC_LENGTH); if (rv != SECSuccess) { PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); goto no_ticket; } rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac, - &computed_mac_length, sizeof(computed_mac)); + &computed_mac_length, sizeof(computed_mac)); PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); if (rv != SECSuccess) goto no_ticket; } if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac, - computed_mac_length) != 0) { + computed_mac_length) != + 0) { SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); goto no_ticket; } @@ -1617,44 +1688,45 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, /* Plaintext is shorter than the ciphertext due to padding. */ decrypted_state = SECITEM_AllocItem(NULL, NULL, - enc_session_ticket.encrypted_state.len); + enc_session_ticket.encrypted_state.len); #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11) { aes_ctx = (AESContext *)aes_ctx_buf; rv = AES_InitContext(aes_ctx, aes_key, - sizeof(session_ticket_enc_key), enc_session_ticket.iv, - NSS_AES_CBC, 0,AES_BLOCK_SIZE); + sizeof(session_ticket_enc_key), enc_session_ticket.iv, + NSS_AES_CBC, 0, AES_BLOCK_SIZE); if (rv != SECSuccess) { SSL_DBG(("%d: SSL[%d]: Unable to create AES context.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); goto no_ticket; } rv = AES_Decrypt(aes_ctx, decrypted_state->data, - &decrypted_state->len, decrypted_state->len, - enc_session_ticket.encrypted_state.data, - enc_session_ticket.encrypted_state.len); + &decrypted_state->len, decrypted_state->len, + enc_session_ticket.encrypted_state.data, + enc_session_ticket.encrypted_state.len); if (rv != SECSuccess) goto no_ticket; - } else + } + else #endif { SECItem ivItem; ivItem.data = enc_session_ticket.iv; ivItem.len = AES_BLOCK_SIZE; aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech, - CKA_DECRYPT, aes_key_pkcs11, &ivItem); + CKA_DECRYPT, aes_key_pkcs11, &ivItem); if (!aes_ctx_pkcs11) { SSL_DBG(("%d: SSL[%d]: Unable to create AES context.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); goto no_ticket; } rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data, - (int *)&decrypted_state->len, decrypted_state->len, - enc_session_ticket.encrypted_state.data, - enc_session_ticket.encrypted_state.len); + (int *)&decrypted_state->len, decrypted_state->len, + enc_session_ticket.encrypted_state.data, + enc_session_ticket.encrypted_state.len); PK11_Finalize(aes_ctx_pkcs11); PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE); if (rv != SECSuccess) @@ -1685,65 +1757,77 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, /* Read ticket_version and reject if the version is wrong */ temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp != TLS_EX_SESS_TICKET_VERSION) goto no_ticket; + if (temp != TLS_EX_SESS_TICKET_VERSION) + goto no_ticket; parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp; /* Read SSLVersion. */ temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp; /* Read cipher_suite. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp; /* Read compression_method. */ temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->compression_method = (SSLCompressionMethod)temp; /* Read cipher spec parameters. */ temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->authAlgorithm = (SSLSignType)temp; temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->authKeyBits = (PRUint32)temp; temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->keaType = (SSLKEAType)temp; temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->keaKeyBits = (PRUint32)temp; /* Read wrapped master_secret. */ temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->ms_is_wrapped = (PRBool)temp; temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->exchKeyType = (SSL3KEAType)temp; temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp; temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; + if (temp < 0) + goto no_ticket; parsed_session_ticket->ms_length = (PRUint16)temp; - if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */ + if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */ parsed_session_ticket->ms_length > - sizeof(parsed_session_ticket->master_secret)) + sizeof(parsed_session_ticket->master_secret)) goto no_ticket; /* Allow for the wrapped master secret to be longer. */ if (buffer_len < parsed_session_ticket->ms_length) goto no_ticket; PORT_Memcpy(parsed_session_ticket->master_secret, buffer, - parsed_session_ticket->ms_length); + parsed_session_ticket->ms_length); buffer += parsed_session_ticket->ms_length; buffer_len -= parsed_session_ticket->ms_length; @@ -1753,16 +1837,18 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, goto no_ticket; parsed_session_ticket->client_identity.client_auth_type = (ClientAuthenticationType)temp; - switch(parsed_session_ticket->client_identity.client_auth_type) { + switch (parsed_session_ticket->client_identity.client_auth_type) { case CLIENT_AUTH_ANONYMOUS: break; case CLIENT_AUTH_CERTIFICATE: rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3, - &buffer, &buffer_len); - if (rv != SECSuccess) goto no_ticket; + &buffer, &buffer_len); + if (rv != SECSuccess) + goto no_ticket; rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert, - &cert_item); - if (rv != SECSuccess) goto no_ticket; + &cert_item); + if (rv != SECSuccess) + goto no_ticket; break; default: goto no_ticket; @@ -1775,15 +1861,17 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, /* Read server name */ nameType = - ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); if (nameType != TLS_STE_NO_SERVER_NAME) { SECItem name_item; rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer, &buffer_len); - if (rv != SECSuccess) goto no_ticket; + if (rv != SECSuccess) + goto no_ticket; rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName, &name_item); - if (rv != SECSuccess) goto no_ticket; + if (rv != SECSuccess) + goto no_ticket; parsed_session_ticket->srvName.type = nameType; } @@ -1803,7 +1891,8 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, */ if (parsed_session_ticket->timestamp != 0 && parsed_session_ticket->timestamp + - TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) { + TLS_EX_SESS_TICKET_LIFETIME_HINT > + ssl_Time()) { sid = ssl3_NewSessionID(ss, PR_TRUE); if (sid == NULL) { @@ -1820,35 +1909,34 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, sid->keaType = parsed_session_ticket->keaType; sid->keaKeyBits = parsed_session_ticket->keaKeyBits; - /* Copy master secret. */ +/* Copy master secret. */ #ifndef NO_PKCS11_BYPASS if (ss->opt.bypassPKCS11 && - parsed_session_ticket->ms_is_wrapped) + parsed_session_ticket->ms_is_wrapped) goto no_ticket; #endif if (parsed_session_ticket->ms_length > - sizeof(sid->u.ssl3.keys.wrapped_master_secret)) + sizeof(sid->u.ssl3.keys.wrapped_master_secret)) goto no_ticket; PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret, - parsed_session_ticket->master_secret, - parsed_session_ticket->ms_length); + parsed_session_ticket->master_secret, + parsed_session_ticket->ms_length); sid->u.ssl3.keys.wrapped_master_secret_len = parsed_session_ticket->ms_length; sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType; sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech; sid->u.ssl3.keys.msIsWrapped = parsed_session_ticket->ms_is_wrapped; - sid->u.ssl3.masterValid = PR_TRUE; + sid->u.ssl3.masterValid = PR_TRUE; sid->u.ssl3.keys.resumable = PR_TRUE; - sid->u.ssl3.keys.extendedMasterSecretUsed = parsed_session_ticket-> - extendedMasterSecretUsed; + sid->u.ssl3.keys.extendedMasterSecretUsed = parsed_session_ticket->extendedMasterSecretUsed; /* Copy over client cert from session ticket if there is one. */ if (parsed_session_ticket->peer_cert.data != NULL) { if (sid->peerCert != NULL) CERT_DestroyCertificate(sid->peerCert); sid->peerCert = CERT_NewTempCertificate(ss->dbHandle, - &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE); + &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE); if (sid->peerCert == NULL) { rv = SECFailure; goto loser; @@ -1863,22 +1951,22 @@ ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, } if (0) { -no_ticket: + no_ticket: SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); ssl3stats = SSL_GetStatistics(); - SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures ); + SSL_AtomicIncrementLong(&ssl3stats->hch_sid_ticket_parse_failures); } rv = SECSuccess; loser: - /* ss->sec.ci.sid == sid if it did NOT come here via goto statement - * in that case do not free sid - */ - if (sid && (ss->sec.ci.sid != sid)) { - ssl_FreeSID(sid); - sid = NULL; - } + /* ss->sec.ci.sid == sid if it did NOT come here via goto statement + * in that case do not free sid + */ + if (sid && (ss->sec.ci.sid != sid)) { + ssl_FreeSID(sid); + sid = NULL; + } if (decrypted_state != NULL) { SECITEM_FreeItem(decrypted_state, PR_TRUE); decrypted_state = NULL; @@ -1916,18 +2004,22 @@ ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data, EncryptedSessionTicket *enc_session_ticket) { if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name, - SESS_TICKET_KEY_NAME_LEN) != SECSuccess) + SESS_TICKET_KEY_NAME_LEN) != + SECSuccess) return SECFailure; if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv, - AES_BLOCK_SIZE) != SECSuccess) + AES_BLOCK_SIZE) != + SECSuccess) return SECFailure; if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state, - 2, &data->data, &data->len) != SECSuccess) + 2, &data->data, &data->len) != + SECSuccess) return SECFailure; if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac, - TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess) + TLS_EX_SESS_TICKET_MAC_LENGTH) != + SECSuccess) return SECFailure; - if (data->len != 0) /* Make sure that we have consumed all bytes. */ + if (data->len != 0) /* Make sure that we have consumed all bytes. */ return SECFailure; return SECSuccess; @@ -1945,7 +2037,7 @@ SECStatus ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, SSL3HandshakeType handshakeMessage) { - const ssl3HelloExtensionHandler * handlers; + const ssl3HelloExtensionHandler *handlers; PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; switch (handshakeMessage) { @@ -1954,11 +2046,12 @@ ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, break; case encrypted_extensions: PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); - /* fall through */ + /* fall through */ case server_hello: if (ss->version > SSL_LIBRARY_VERSION_3_0) { handlers = serverHelloHandlersTLS; - } else { + } + else { handlers = serverHelloHandlersSSL3; } break; @@ -1969,15 +2062,15 @@ ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, } while (*length) { - const ssl3HelloExtensionHandler * handler; + const ssl3HelloExtensionHandler *handler; SECStatus rv; - PRInt32 extension_type; - SECItem extension_data; + PRInt32 extension_type; + SECItem extension_data; /* Get the extension's type field */ extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); - if (extension_type < 0) /* failure to decode extension_type */ - return SECFailure; /* alert already sent */ + if (extension_type < 0) /* failure to decode extension_type */ + return SECFailure; /* alert already sent */ /* get the data for this extension, so we can pass it or skip it. */ rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length); @@ -1987,7 +2080,7 @@ ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, /* Check whether the server sent an extension which was not advertised * in the ClientHello */ if (!ss->sec.isServer && - !ssl3_ClientExtensionAdvertised(ss,extension_type)) { + !ssl3_ClientExtensionAdvertised(ss, extension_type)) { (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension); return SECFailure; } @@ -1999,8 +2092,7 @@ ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, } /* Check that this is a legal extension in TLS 1.3 */ - if (isTLS13 && !tls13_ExtensionAllowed(extension_type, - handshakeMessage)) { + if (isTLS13 && !tls13_ExtensionAllowed(extension_type, handshakeMessage)) { if (handshakeMessage == client_hello) { /* Skip extensions not used in TLS 1.3 */ continue; @@ -2015,7 +2107,7 @@ ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, /* if found, call this handler */ if (handler->ex_type == extension_type) { rv = (*handler->ex_handler)(ss, (PRUint16)extension_type, - &extension_data); + &extension_data); if (rv != SECSuccess) { if (!ss->ssl3.fatalAlertSent) { /* send a generic alert if the handler didn't already */ @@ -2039,11 +2131,13 @@ ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type, ssl3HelloExtensionSender *sender; if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { sender = &ss->xtnData.serverHelloSenders[0]; - } else { + } + else { if (tls13_ExtensionAllowed(ex_type, server_hello)) { PORT_Assert(!tls13_ExtensionAllowed(ex_type, encrypted_extensions)); sender = &ss->xtnData.serverHelloSenders[0]; - } else { + } + else { PORT_Assert(tls13_ExtensionAllowed(ex_type, encrypted_extensions)); sender = &ss->xtnData.encryptedExtensionsSenders[0]; } @@ -2051,7 +2145,7 @@ ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type, for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) { if (!sender->ex_sender) { - sender->ex_type = ex_type; + sender->ex_type = ex_type; sender->ex_sender = cb; return SECSuccess; } @@ -2078,7 +2172,8 @@ ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, if (!sender) { if (ss->version > SSL_LIBRARY_VERSION_3_0) { sender = &clientHelloSendersTLS[0]; - } else { + } + else { sender = &clientHelloSendersSSL3[0]; } } @@ -2088,14 +2183,13 @@ ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes); if (extLen < 0) return -1; - maxBytes -= extLen; + maxBytes -= extLen; total_exten_len += extLen; } } return total_exten_len; } - /* Extension format: * Extension number: 2 bytes * Extension length: 2 bytes @@ -2105,9 +2199,9 @@ ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, */ static PRInt32 ssl3_SendRenegotiationInfoXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) + sslSocket *ss, + PRBool append, + PRUint32 maxBytes) { PRInt32 len = 0; PRInt32 needed; @@ -2130,18 +2224,21 @@ ssl3_SendRenegotiationInfoXtn( SECStatus rv; /* extension_type */ rv = ssl3_AppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* length of extension_data */ rv = ssl3_AppendHandshakeNumber(ss, len + 1, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* verify_Data from previous Finished message(s) */ rv = ssl3_AppendHandshakeVariable(ss, - ss->ssl3.hs.finishedMsgs.data, len, 1); - if (rv != SECSuccess) return -1; + ss->ssl3.hs.finishedMsgs.data, len, 1); + if (rv != SECSuccess) + return -1; if (!ss->sec.isServer) { TLSExtensionData *xtnData = &ss->xtnData; xtnData->advertised[xtnData->numAdvertised++] = - ssl_renegotiation_info_xtn; + ssl_renegotiation_info_xtn; } } return needed; @@ -2158,7 +2255,7 @@ ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type, PORT_Assert(ss->sec.isServer); /* prepare to send back the appropriate response */ rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type, - ssl3_ServerSendStatusRequestXtn); + ssl3_ServerSendStatusRequestXtn); return rv; } @@ -2173,7 +2270,7 @@ ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes : ss->ssl3.hs.finishedBytes * 2; } - if (data->len != 1 + len || data->data[0] != len ) { + if (data->len != 1 + len || data->data[0] != len) { (void)ssl3_DecodeError(ss); return SECFailure; } @@ -2205,22 +2302,25 @@ ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) return 0; if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) - return 0; /* Not relevant */ + return 0; /* Not relevant */ ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1; if (append && maxBytes >= 4 + ext_data_len) { /* Extension type */ rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* Length of extension data */ rv = ssl3_AppendHandshakeNumber(ss, ext_data_len, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* Length of the SRTP cipher list */ rv = ssl3_AppendHandshakeNumber(ss, 2 * ss->ssl3.dtlsSRTPCipherCount, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* The SRTP ciphers */ for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) { rv = ssl3_AppendHandshakeNumber(ss, @@ -2231,7 +2331,7 @@ ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_use_srtp_xtn; + ssl_use_srtp_xtn; } return 4 + ext_data_len; @@ -2249,16 +2349,20 @@ ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) /* Extension type */ rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* Length of extension data */ rv = ssl3_AppendHandshakeNumber(ss, 5, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* Length of the SRTP cipher list */ rv = ssl3_AppendHandshakeNumber(ss, 2, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* The selected cipher */ rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.dtlsSRTPCipherSuite, 2); - if (rv != SECSuccess) return -1; + if (rv != SECSuccess) + return -1; /* Empty MKI value */ ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); @@ -2266,10 +2370,10 @@ ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) } static SECStatus -ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +ssl3_ClientHandleUseSRTPXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { SECStatus rv; - SECItem ciphers = {siBuffer, NULL, 0}; + SECItem ciphers = { siBuffer, NULL, 0 }; PRUint16 i; PRUint16 cipher = 0; PRBool found = PR_FALSE; @@ -2284,7 +2388,7 @@ ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) rv = ssl3_ConsumeHandshakeVariable(ss, &ciphers, 2, &data->data, &data->len); if (rv != SECSuccess) { - return SECFailure; /* fatal alert already sent */ + return SECFailure; /* fatal alert already sent */ } /* Now check that the server has picked just 1 (i.e., len = 2) */ if (ciphers.len != 2) { @@ -2336,10 +2440,10 @@ ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) } static SECStatus -ssl3_ServerHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +ssl3_ServerHandleUseSRTPXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { SECStatus rv; - SECItem ciphers = {siBuffer, NULL, 0}; + SECItem ciphers = { siBuffer, NULL, 0 }; PRUint16 i; unsigned int j; PRUint16 cipher = 0; @@ -2410,7 +2514,7 @@ ssl3_ServerHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) * from a client. * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ static SECStatus -ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +ssl3_ServerHandleSigAlgsXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { SECStatus rv; SECItem algorithms; @@ -2434,7 +2538,7 @@ ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) return SECFailure; } - numAlgorithms = algorithms.len/2; + numAlgorithms = algorithms.len / 2; /* We don't care to process excessive numbers of algorithms. */ if (numAlgorithms > 512) { @@ -2442,7 +2546,7 @@ ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) } ss->ssl3.hs.clientSigAndHash = - PORT_NewArray(SSLSignatureAndHashAlg, numAlgorithms); + PORT_NewArray(SSLSignatureAndHashAlg, numAlgorithms); if (!ss->ssl3.hs.clientSigAndHash) { (void)SSL3_SendAlert(ss, alert_fatal, internal_error); PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); @@ -2455,8 +2559,8 @@ ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) for (i = 0; i < numAlgorithms; i++) { SSLSignatureAndHashAlg *sigAndHash = &ss->ssl3.hs.clientSigAndHash[ss->ssl3.hs.numClientSigAndHash]; - sigAndHash->hashAlg = (SSLHashType)*(b++); - sigAndHash->sigAlg = (SSLSignType)*(b++); + sigAndHash->hashAlg = (SSLHashType) * (b++); + sigAndHash->sigAlg = (SSLSignType) * (b++); if (ssl3_IsSupportedSignatureAlgorithm(sigAndHash)) { ++ss->ssl3.hs.numClientSigAndHash; } @@ -2481,7 +2585,7 @@ ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { PRInt32 extension_length; unsigned int i; - PRInt32 pos=0; + PRInt32 pos = 0; PRUint32 policy; PRUint8 buf[MAX_SIGNATURE_ALGORITHMS * 2]; @@ -2489,14 +2593,14 @@ ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) return 0; } - for (i=0; i < ss->ssl3.signatureAlgorithmCount; i++) { - SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID( - ss->ssl3.signatureAlgorithms[i].hashAlg); - if ((NSS_GetAlgorithmPolicy(hashOID, & policy) != SECSuccess) || - (policy & NSS_USE_ALG_IN_SSL_KX)) { - buf[pos++] = ss->ssl3.signatureAlgorithms[i].hashAlg; - buf[pos++] = ss->ssl3.signatureAlgorithms[i].sigAlg; - } + for (i = 0; i < ss->ssl3.signatureAlgorithmCount; i++) { + SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID( + ss->ssl3.signatureAlgorithms[i].hashAlg); + if ((NSS_GetAlgorithmPolicy(hashOID, &policy) != SECSuccess) || + (policy & NSS_USE_ALG_IN_SSL_KX)) { + buf[pos++] = ss->ssl3.signatureAlgorithms[i].hashAlg; + buf[pos++] = ss->ssl3.signatureAlgorithms[i].sigAlg; + } } extension_length = @@ -2527,7 +2631,7 @@ ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) } ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_signature_algorithms_xtn; + ssl_signature_algorithms_xtn; } return extension_length; @@ -2589,7 +2693,7 @@ ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen, * version extension. * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */ static PRInt32 -ssl3_ClientSendDraftVersionXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) +ssl3_ClientSendDraftVersionXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { PRInt32 extension_length; @@ -2597,7 +2701,7 @@ ssl3_ClientSendDraftVersionXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) return 0; } - extension_length = 6; /* Type + length + number */ + extension_length = 6; /* Type + length + number */ if (maxBytes < (PRUint32)extension_length) { PORT_Assert(0); return 0; @@ -2614,7 +2718,7 @@ ssl3_ClientSendDraftVersionXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) if (rv != SECSuccess) goto loser; ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_tls13_draft_version_xtn; + ssl_tls13_draft_version_xtn; } return extension_length; @@ -2627,7 +2731,7 @@ loser: * version extension. * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */ static SECStatus -ssl3_ServerHandleDraftVersionXtn(sslSocket * ss, PRUint16 ex_type, +ssl3_ServerHandleDraftVersionXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { PRInt32 draft_version; @@ -2668,7 +2772,7 @@ ssl3_ServerHandleDraftVersionXtn(sslSocket * ss, PRUint16 ex_type, } static PRInt32 -ssl3_SendExtendedMasterSecretXtn(sslSocket * ss, PRBool append, +ssl3_SendExtendedMasterSecretXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { PRInt32 extension_length; @@ -2689,7 +2793,7 @@ ssl3_SendExtendedMasterSecretXtn(sslSocket * ss, PRBool append, /* Always send the extension in this function, since the * client always sends it and this function is only called on * the server if we negotiated the extension. */ - extension_length = 4; /* Type + length (0) */ + extension_length = 4; /* Type + length (0) */ if (maxBytes < extension_length) { PORT_Assert(0); return 0; @@ -2704,7 +2808,7 @@ ssl3_SendExtendedMasterSecretXtn(sslSocket * ss, PRBool append, if (rv != SECSuccess) goto loser; ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_extended_master_secret_xtn; + ssl_extended_master_secret_xtn; } return extension_length; @@ -2713,9 +2817,8 @@ loser: return -1; } - static SECStatus -ssl3_HandleExtendedMasterSecretXtn(sslSocket * ss, PRUint16 ex_type, +ssl3_HandleExtendedMasterSecretXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) { if (ss->version < SSL_LIBRARY_VERSION_TLS_1_0) { @@ -2781,7 +2884,8 @@ ssl3_ClientSendSignedCertTimestampXtn(sslSocket *ss, PRBool append, goto loser; ss->xtnData.advertised[ss->xtnData.numAdvertised++] = ssl_signed_cert_timestamp_xtn; - } else if (maxBytes < extension_length) { + } + else if (maxBytes < extension_length) { PORT_Assert(0); return 0; } @@ -2817,7 +2921,7 @@ ssl3_ClientHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type, } static PRInt32 -ssl3_ServerSendSignedCertTimestampXtn(sslSocket * ss, +ssl3_ServerSendSignedCertTimestampXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { @@ -2828,7 +2932,8 @@ ssl3_ServerSendSignedCertTimestampXtn(sslSocket * ss, if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { effectiveExchKeyType = ssl_kea_rsa; - } else { + } + else { effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; } @@ -2853,10 +2958,12 @@ ssl3_ServerSendSignedCertTimestampXtn(sslSocket * ss, rv = ssl3_AppendHandshakeNumber(ss, ssl_signed_cert_timestamp_xtn, 2); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; /* extension_data */ rv = ssl3_AppendHandshakeVariable(ss, scts->data, scts->len, 2); - if (rv != SECSuccess) goto loser; + if (rv != SECSuccess) + goto loser; } return extension_length; @@ -2872,7 +2979,7 @@ ssl3_ServerHandleSignedCertTimestampXtn(sslSocket *ss, PRUint16 ex_type, ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; PORT_Assert(ss->sec.isServer); return ssl3_RegisterServerHelloExtensionSender(ss, ex_type, - ssl3_ServerSendSignedCertTimestampXtn); + ssl3_ServerSendSignedCertTimestampXtn); } /* @@ -2927,7 +3034,7 @@ tls13_EncodeKeyShareEntry(sslSocket *ss, ssl3KeyPair *pair) } static PRInt32 -tls13_ClientSendKeyShareXtn(sslSocket * ss, PRBool append, +tls13_ClientSendKeyShareXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) { SECStatus rv; @@ -2959,7 +3066,7 @@ tls13_ClientSendKeyShareXtn(sslSocket * ss, PRBool append, rv = ssl3_AppendHandshakeNumber(ss, entry_length + 2, 2); /* Extension length */ if (rv != SECSuccess) goto loser; - rv = ssl3_AppendHandshakeNumber(ss, entry_length, 2); /* Vector length */ + rv = ssl3_AppendHandshakeNumber(ss, entry_length, 2); /* Vector length */ if (rv != SECSuccess) goto loser; rv = tls13_EncodeKeyShareEntry(ss, ss->ephemeralECDHKeyPair); @@ -2967,7 +3074,7 @@ tls13_ClientSendKeyShareXtn(sslSocket * ss, PRBool append, goto loser; ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_tls13_key_share_xtn; + ssl_tls13_key_share_xtn; } return extension_length; @@ -2981,7 +3088,7 @@ tls13_HandleKeyShareEntry(sslSocket *ss, SECItem *data) { SECStatus rv; PRInt32 group; - TLS13KeyShareEntry* ks = NULL; + TLS13KeyShareEntry *ks = NULL; SECItem share = { siBuffer, NULL, 0 }; group = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); @@ -3031,7 +3138,7 @@ tls13_ClientHandleKeyShareXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) } SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); rv = tls13_HandleKeyShareEntry(ss, data); if (rv != SECSuccess) { @@ -3062,7 +3169,7 @@ tls13_ServerHandleKeyShareXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) } SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); /* Redundant length because of TLS encoding (this vector consumes * the entire extension.) */ @@ -3098,17 +3205,17 @@ tls13_ServerSendKeyShareXtn(sslSocket *ss, PRBool append, switch (ss->ssl3.hs.kea_def->exchKeyType) { #ifndef NSS_DISABLE_ECC - case ssl_kea_ecdh: - PORT_Assert(ss->ephemeralECDHKeyPair); - break; + case ssl_kea_ecdh: + PORT_Assert(ss->ephemeralECDHKeyPair); + break; #endif - default: - /* got an unknown or unsupported Key Exchange Algorithm. - * Can't happen because tls13_HandleClientKeyShare - * enforces that we are ssl_kea_ecdh. */ - PORT_Assert(0); - tls13_FatalError(ss, SEC_ERROR_UNSUPPORTED_KEYALG, internal_error); - return SECFailure; + default: + /* got an unknown or unsupported Key Exchange Algorithm. + * Can't happen because tls13_HandleClientKeyShare + * enforces that we are ssl_kea_ecdh. */ + PORT_Assert(0); + tls13_FatalError(ss, SEC_ERROR_UNSUPPORTED_KEYALG, internal_error); + return SECFailure; } entry_length = tls13_SizeOfKeyShareEntry(ss->ephemeralECDHKeyPair); @@ -3137,4 +3244,3 @@ tls13_ServerSendKeyShareXtn(sslSocket *ss, PRBool append, loser: return -1; } - diff --git a/security/nss/lib/ssl/ssl3gthr.c b/security/nss/lib/ssl/ssl3gthr.c index 87e6a00bbbf0..5ba5b7cf7aaf 100644 --- a/security/nss/lib/ssl/ssl3gthr.c +++ b/security/nss/lib/ssl/ssl3gthr.c @@ -1,5 +1,5 @@ /* - * Gather (Read) entire SSL3 records from socket into buffer. + * Gather (Read) entire SSL3 records from socket into buffer. * * 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 @@ -10,15 +10,15 @@ #include "sslimpl.h" #include "ssl3prot.h" -/* +/* * Attempt to read in an entire SSL3 record. - * Blocks here for blocking sockets, otherwise returns -1 with - * PR_WOULD_BLOCK_ERROR when socket would block. + * Blocks here for blocking sockets, otherwise returns -1 with + * PR_WOULD_BLOCK_ERROR when socket would block. * * returns 1 if received a complete SSL3 record. * returns 0 if recv returns EOF - * returns -1 if recv returns < 0 - * (The error value may have already been set to PR_WOULD_BLOCK_ERROR) + * returns -1 if recv returns < 0 + * (The error value may have already been set to PR_WOULD_BLOCK_ERROR) * * Caller must hold the recv buf lock. * @@ -28,108 +28,109 @@ * * This loop returns when either * (a) an error or EOF occurs, - * (b) PR_WOULD_BLOCK_ERROR, - * (c) data (entire SSL3 record) has been received. + * (b) PR_WOULD_BLOCK_ERROR, + * (c) data (entire SSL3 record) has been received. */ static int ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags) { unsigned char *bp; unsigned char *lbp; - int nb; - int err; - int rv = 1; + int nb; + int err; + int rv = 1; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); if (gs->state == GS_INIT) { - gs->state = GS_HEADER; - gs->remainder = 5; - gs->offset = 0; - gs->writeOffset = 0; - gs->readOffset = 0; - gs->inbuf.len = 0; + gs->state = GS_HEADER; + gs->remainder = 5; + gs->offset = 0; + gs->writeOffset = 0; + gs->readOffset = 0; + gs->inbuf.len = 0; } - + lbp = gs->inbuf.buf; - for(;;) { - SSL_TRC(30, ("%d: SSL3[%d]: gather state %d (need %d more)", - SSL_GETPID(), ss->fd, gs->state, gs->remainder)); - bp = ((gs->state != GS_HEADER) ? lbp : gs->hdr) + gs->offset; - nb = ssl_DefRecv(ss, bp, gs->remainder, flags); + for (;;) { + SSL_TRC(30, ("%d: SSL3[%d]: gather state %d (need %d more)", + SSL_GETPID(), ss->fd, gs->state, gs->remainder)); + bp = ((gs->state != GS_HEADER) ? lbp : gs->hdr) + gs->offset; + nb = ssl_DefRecv(ss, bp, gs->remainder, flags); - if (nb > 0) { - PRINT_BUF(60, (ss, "raw gather data:", bp, nb)); - } else if (nb == 0) { - /* EOF */ - SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd)); - rv = 0; - break; - } else /* if (nb < 0) */ { - SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd, - PR_GetError())); - rv = SECFailure; - break; - } + if (nb > 0) { + PRINT_BUF(60, (ss, "raw gather data:", bp, nb)); + } + else if (nb == 0) { + /* EOF */ + SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd)); + rv = 0; + break; + } + else /* if (nb < 0) */ { + SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd, + PR_GetError())); + rv = SECFailure; + break; + } - PORT_Assert( (unsigned int)nb <= gs->remainder ); - if ((unsigned int)nb > gs->remainder) { - /* ssl_DefRecv is misbehaving! this error is fatal to SSL. */ - gs->state = GS_INIT; /* so we don't crash next time */ - rv = SECFailure; - break; - } + PORT_Assert((unsigned int)nb <= gs->remainder); + if ((unsigned int)nb > gs->remainder) { + /* ssl_DefRecv is misbehaving! this error is fatal to SSL. */ + gs->state = GS_INIT; /* so we don't crash next time */ + rv = SECFailure; + break; + } - gs->offset += nb; - gs->remainder -= nb; - if (gs->state == GS_DATA) - gs->inbuf.len += nb; + gs->offset += nb; + gs->remainder -= nb; + if (gs->state == GS_DATA) + gs->inbuf.len += nb; - /* if there's more to go, read some more. */ - if (gs->remainder > 0) { - continue; - } + /* if there's more to go, read some more. */ + if (gs->remainder > 0) { + continue; + } - /* have received entire record header, or entire record. */ - switch (gs->state) { - case GS_HEADER: - /* - ** Have received SSL3 record header in gs->hdr. - ** Now extract the length of the following encrypted data, - ** and then read in the rest of the SSL3 record into gs->inbuf. - */ - gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4]; + /* have received entire record header, or entire record. */ + switch (gs->state) { + case GS_HEADER: + /* + ** Have received SSL3 record header in gs->hdr. + ** Now extract the length of the following encrypted data, + ** and then read in the rest of the SSL3 record into gs->inbuf. + */ + gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4]; - /* This is the max fragment length for an encrypted fragment - ** plus the size of the record header. - */ - if(gs->remainder > (MAX_FRAGMENT_LENGTH + 2048 + 5)) { - SSL3_SendAlert(ss, alert_fatal, unexpected_message); - gs->state = GS_INIT; - PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); - return SECFailure; - } + /* This is the max fragment length for an encrypted fragment + ** plus the size of the record header. + */ + if (gs->remainder > (MAX_FRAGMENT_LENGTH + 2048 + 5)) { + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + gs->state = GS_INIT; + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); + return SECFailure; + } - gs->state = GS_DATA; - gs->offset = 0; - gs->inbuf.len = 0; + gs->state = GS_DATA; + gs->offset = 0; + gs->inbuf.len = 0; - if (gs->remainder > gs->inbuf.space) { - err = sslBuffer_Grow(&gs->inbuf, gs->remainder); - if (err) { /* realloc has set error code to no mem. */ - return err; - } - lbp = gs->inbuf.buf; - } - break; /* End this case. Continue around the loop. */ + if (gs->remainder > gs->inbuf.space) { + err = sslBuffer_Grow(&gs->inbuf, gs->remainder); + if (err) { /* realloc has set error code to no mem. */ + return err; + } + lbp = gs->inbuf.buf; + } + break; /* End this case. Continue around the loop. */ - - case GS_DATA: - /* - ** SSL3 record has been completely received. - */ - gs->state = GS_INIT; - return 1; - } + case GS_DATA: + /* + ** SSL3 record has been completely received. + */ + gs->state = GS_INIT; + return 1; + } } return rv; @@ -139,7 +140,7 @@ ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags) * Read in an entire DTLS record. * * Blocks here for blocking sockets, otherwise returns -1 with - * PR_WOULD_BLOCK_ERROR when socket would block. + * PR_WOULD_BLOCK_ERROR when socket would block. * * This is simpler than SSL because we are reading on a datagram socket * and datagrams must contain >=1 complete records. @@ -147,43 +148,43 @@ ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags) * returns 1 if received a complete DTLS record. * returns 0 if recv returns EOF * returns -1 if recv returns < 0 - * (The error value may have already been set to PR_WOULD_BLOCK_ERROR) + * (The error value may have already been set to PR_WOULD_BLOCK_ERROR) * * Caller must hold the recv buf lock. * * This loop returns when either * (a) an error or EOF occurs, - * (b) PR_WOULD_BLOCK_ERROR, - * (c) data (entire DTLS record) has been received. + * (b) PR_WOULD_BLOCK_ERROR, + * (c) data (entire DTLS record) has been received. */ static int dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) { - int nb; - int err; - int rv = 1; + int nb; + int err; + int rv = 1; SSL_TRC(30, ("dtls_GatherData")); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); gs->state = GS_HEADER; gs->offset = 0; - if (gs->dtlsPacketOffset == gs->dtlsPacket.len) { /* No data left */ + if (gs->dtlsPacketOffset == gs->dtlsPacket.len) { /* No data left */ gs->dtlsPacketOffset = 0; gs->dtlsPacket.len = 0; /* Resize to the maximum possible size so we can fit a full datagram */ - /* This is the max fragment length for an encrypted fragment - ** plus the size of the record header. - ** This magic constant is copied from ssl3_GatherData, with 5 changed - ** to 13 (the size of the record header). - */ + /* This is the max fragment length for an encrypted fragment + ** plus the size of the record header. + ** This magic constant is copied from ssl3_GatherData, with 5 changed + ** to 13 (the size of the record header). + */ if (gs->dtlsPacket.space < MAX_FRAGMENT_LENGTH + 2048 + 13) { err = sslBuffer_Grow(&gs->dtlsPacket, - MAX_FRAGMENT_LENGTH + 2048 + 13); - if (err) { /* realloc has set error code to no mem. */ + MAX_FRAGMENT_LENGTH + 2048 + 13); + if (err) { /* realloc has set error code to no mem. */ return err; } } @@ -193,12 +194,14 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) if (nb > 0) { PRINT_BUF(60, (ss, "raw gather data:", gs->dtlsPacket.buf, nb)); - } else if (nb == 0) { + } + else if (nb == 0) { /* EOF */ SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd)); rv = 0; return rv; - } else /* if (nb < 0) */ { + } + else /* if (nb < 0) */ { SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd, PR_GetError())); rv = SECFailure; @@ -213,7 +216,8 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) */ if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < 13) { SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet " - "too short to contain header", SSL_GETPID(), ss->fd)); + "too short to contain header", + SSL_GETPID(), ss->fd)); PR_SetError(PR_WOULD_BLOCK_ERROR, 0); gs->dtlsPacketOffset = 0; gs->dtlsPacket.len = 0; @@ -228,7 +232,8 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < gs->remainder) { SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet too short " - "to contain rest of body", SSL_GETPID(), ss->fd)); + "to contain rest of body", + SSL_GETPID(), ss->fd)); PR_SetError(PR_WOULD_BLOCK_ERROR, 0); gs->dtlsPacketOffset = 0; gs->dtlsPacket.len = 0; @@ -238,14 +243,14 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) /* OK, we have at least one complete packet, copy into inbuf */ if (gs->remainder > gs->inbuf.space) { - err = sslBuffer_Grow(&gs->inbuf, gs->remainder); - if (err) { /* realloc has set error code to no mem. */ - return err; - } + err = sslBuffer_Grow(&gs->inbuf, gs->remainder); + if (err) { /* realloc has set error code to no mem. */ + return err; + } } memcpy(gs->inbuf.buf, gs->dtlsPacket.buf + gs->dtlsPacketOffset, - gs->remainder); + gs->remainder); gs->inbuf.len = gs->remainder; gs->offset = gs->remainder; gs->dtlsPacketOffset += gs->remainder; @@ -255,16 +260,16 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) } /* Gather in a record and when complete, Handle that record. - * Repeat this until the handshake is complete, + * Repeat this until the handshake is complete, * or until application data is available. * - * Returns 1 when the handshake is completed without error, or + * Returns 1 when the handshake is completed without error, or * application data is available. * Returns 0 if ssl3_GatherData hits EOF. * Returns -1 on read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error. * Returns -2 on SECWouldBlock return from ssl3_HandleRecord. * - * Called from ssl_GatherRecord1stHandshake in sslcon.c, + * Called from ssl_GatherRecord1stHandshake in sslcon.c, * and from SSL_ForceHandshake in sslsecur.c * and from ssl3_GatherAppDataRecord below (<- DoRecv in sslsecur.c). * @@ -274,8 +279,8 @@ int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags) { SSL3Ciphertext cText; - int rv; - PRBool keepGoing = PR_TRUE; + int rv; + PRBool keepGoing = PR_TRUE; SSL_TRC(30, ("ssl3_GatherCompleteHandshake")); @@ -283,143 +288,150 @@ ssl3_GatherCompleteHandshake(sslSocket *ss, int flags) * which requires the 1stHandshakeLock, which must be acquired before the * RecvBufLock. */ - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); do { - PRBool handleRecordNow = PR_FALSE; + PRBool handleRecordNow = PR_FALSE; - ssl_GetSSL3HandshakeLock(ss); + ssl_GetSSL3HandshakeLock(ss); - /* Without this, we may end up wrongly reporting - * SSL_ERROR_RX_UNEXPECTED_* errors if we receive any records from the - * peer while we are waiting to be restarted. - */ - if (ss->ssl3.hs.restartTarget) { - ssl_ReleaseSSL3HandshakeLock(ss); - PORT_SetError(PR_WOULD_BLOCK_ERROR); - return (int) SECFailure; - } + /* Without this, we may end up wrongly reporting + * SSL_ERROR_RX_UNEXPECTED_* errors if we receive any records from the + * peer while we are waiting to be restarted. + */ + if (ss->ssl3.hs.restartTarget) { + ssl_ReleaseSSL3HandshakeLock(ss); + PORT_SetError(PR_WOULD_BLOCK_ERROR); + return (int)SECFailure; + } - /* Treat an empty msgState like a NULL msgState. (Most of the time - * when ssl3_HandleHandshake returns SECWouldBlock, it leaves - * behind a non-NULL but zero-length msgState). - * Test: async_cert_restart_server_sends_hello_request_first_in_separate_record - */ - if (ss->ssl3.hs.msgState.buf) { - if (ss->ssl3.hs.msgState.len == 0) { - ss->ssl3.hs.msgState.buf = NULL; - } else { - handleRecordNow = PR_TRUE; - } - } + /* Treat an empty msgState like a NULL msgState. (Most of the time + * when ssl3_HandleHandshake returns SECWouldBlock, it leaves + * behind a non-NULL but zero-length msgState). + * Test: async_cert_restart_server_sends_hello_request_first_in_separate_record + */ + if (ss->ssl3.hs.msgState.buf) { + if (ss->ssl3.hs.msgState.len == 0) { + ss->ssl3.hs.msgState.buf = NULL; + } + else { + handleRecordNow = PR_TRUE; + } + } - ssl_ReleaseSSL3HandshakeLock(ss); + ssl_ReleaseSSL3HandshakeLock(ss); - if (handleRecordNow) { - /* ssl3_HandleHandshake previously returned SECWouldBlock and the - * as-yet-unprocessed plaintext of that previous handshake record. - * We need to process it now before we overwrite it with the next - * handshake record. - */ - rv = ssl3_HandleRecord(ss, NULL, &ss->gs.buf); - } else { - /* bring in the next sslv3 record. */ - if (ss->recvdCloseNotify) { - /* RFC 5246 Section 7.2.1: - * Any data received after a closure alert is ignored. - */ - return 0; - } - if (!IS_DTLS(ss)) { - rv = ssl3_GatherData(ss, &ss->gs, flags); - } else { - rv = dtls_GatherData(ss, &ss->gs, flags); - - /* If we got a would block error, that means that no data was - * available, so we check the timer to see if it's time to - * retransmit */ - if (rv == SECFailure && - (PORT_GetError() == PR_WOULD_BLOCK_ERROR)) { - ssl_GetSSL3HandshakeLock(ss); - dtls_CheckTimer(ss); - ssl_ReleaseSSL3HandshakeLock(ss); - /* Restore the error in case something succeeded */ - PORT_SetError(PR_WOULD_BLOCK_ERROR); - } - } + if (handleRecordNow) { + /* ssl3_HandleHandshake previously returned SECWouldBlock and the + * as-yet-unprocessed plaintext of that previous handshake record. + * We need to process it now before we overwrite it with the next + * handshake record. + */ + rv = ssl3_HandleRecord(ss, NULL, &ss->gs.buf); + } + else { + /* bring in the next sslv3 record. */ + if (ss->recvdCloseNotify) { + /* RFC 5246 Section 7.2.1: + * Any data received after a closure alert is ignored. + */ + return 0; + } + if (!IS_DTLS(ss)) { + rv = ssl3_GatherData(ss, &ss->gs, flags); + } + else { + rv = dtls_GatherData(ss, &ss->gs, flags); - if (rv <= 0) { - return rv; - } + /* If we got a would block error, that means that no data was + * available, so we check the timer to see if it's time to + * retransmit */ + if (rv == SECFailure && + (PORT_GetError() == PR_WOULD_BLOCK_ERROR)) { + ssl_GetSSL3HandshakeLock(ss); + dtls_CheckTimer(ss); + ssl_ReleaseSSL3HandshakeLock(ss); + /* Restore the error in case something succeeded */ + PORT_SetError(PR_WOULD_BLOCK_ERROR); + } + } - /* decipher it, and handle it if it's a handshake. - * If it's application data, ss->gs.buf will not be empty upon return. - * If it's a change cipher spec, alert, or handshake message, - * ss->gs.buf.len will be 0 when ssl3_HandleRecord returns SECSuccess. - */ - cText.type = (SSL3ContentType)ss->gs.hdr[0]; - cText.version = (ss->gs.hdr[1] << 8) | ss->gs.hdr[2]; + if (rv <= 0) { + return rv; + } - if (IS_DTLS(ss)) { - int i; + /* decipher it, and handle it if it's a handshake. + * If it's application data, ss->gs.buf will not be empty upon return. + * If it's a change cipher spec, alert, or handshake message, + * ss->gs.buf.len will be 0 when ssl3_HandleRecord returns SECSuccess. + */ + cText.type = (SSL3ContentType)ss->gs.hdr[0]; + cText.version = (ss->gs.hdr[1] << 8) | ss->gs.hdr[2]; - cText.version = dtls_DTLSVersionToTLSVersion(cText.version); - /* DTLS sequence number */ - cText.seq_num.high = 0; cText.seq_num.low = 0; - for (i = 0; i < 4; i++) { - cText.seq_num.high <<= 8; cText.seq_num.low <<= 8; - cText.seq_num.high |= ss->gs.hdr[3 + i]; - cText.seq_num.low |= ss->gs.hdr[7 + i]; - } - } + if (IS_DTLS(ss)) { + int i; - cText.buf = &ss->gs.inbuf; - rv = ssl3_HandleRecord(ss, &cText, &ss->gs.buf); - } - if (rv < 0) { - return ss->recvdCloseNotify ? 0 : rv; - } - if (ss->gs.buf.len > 0) { - /* We have application data to return to the application. This - * prioritizes returning application data to the application over - * completing any renegotiation handshake we may be doing. - */ - PORT_Assert(ss->firstHsDone); - PORT_Assert(cText.type == content_application_data); - break; - } + cText.version = dtls_DTLSVersionToTLSVersion(cText.version); + /* DTLS sequence number */ + cText.seq_num.high = 0; + cText.seq_num.low = 0; + for (i = 0; i < 4; i++) { + cText.seq_num.high <<= 8; + cText.seq_num.low <<= 8; + cText.seq_num.high |= ss->gs.hdr[3 + i]; + cText.seq_num.low |= ss->gs.hdr[7 + i]; + } + } - PORT_Assert(keepGoing); - ssl_GetSSL3HandshakeLock(ss); - if (ss->ssl3.hs.ws == idle_handshake) { - /* We are done with the current handshake so stop trying to - * handshake. Note that it would be safe to test ss->firstHsDone - * instead of ss->ssl3.hs.ws. By testing ss->ssl3.hs.ws instead, - * we prioritize completing a renegotiation handshake over sending - * application data. - */ - PORT_Assert(ss->firstHsDone); - PORT_Assert(!ss->ssl3.hs.canFalseStart); - keepGoing = PR_FALSE; - } else if (ss->ssl3.hs.canFalseStart) { - /* Prioritize sending application data over trying to complete - * the handshake if we're false starting. - * - * If we were to do this check at the beginning of the loop instead - * of here, then this function would become be a no-op after - * receiving the ServerHelloDone in the false start case, and we - * would never complete the handshake. - */ - PORT_Assert(!ss->firstHsDone); + cText.buf = &ss->gs.inbuf; + rv = ssl3_HandleRecord(ss, &cText, &ss->gs.buf); + } + if (rv < 0) { + return ss->recvdCloseNotify ? 0 : rv; + } + if (ss->gs.buf.len > 0) { + /* We have application data to return to the application. This + * prioritizes returning application data to the application over + * completing any renegotiation handshake we may be doing. + */ + PORT_Assert(ss->firstHsDone); + PORT_Assert(cText.type == content_application_data); + break; + } - if (ssl3_WaitingForServerSecondRound(ss)) { - keepGoing = PR_FALSE; - } else { - ss->ssl3.hs.canFalseStart = PR_FALSE; - } - } - ssl_ReleaseSSL3HandshakeLock(ss); + PORT_Assert(keepGoing); + ssl_GetSSL3HandshakeLock(ss); + if (ss->ssl3.hs.ws == idle_handshake) { + /* We are done with the current handshake so stop trying to + * handshake. Note that it would be safe to test ss->firstHsDone + * instead of ss->ssl3.hs.ws. By testing ss->ssl3.hs.ws instead, + * we prioritize completing a renegotiation handshake over sending + * application data. + */ + PORT_Assert(ss->firstHsDone); + PORT_Assert(!ss->ssl3.hs.canFalseStart); + keepGoing = PR_FALSE; + } + else if (ss->ssl3.hs.canFalseStart) { + /* Prioritize sending application data over trying to complete + * the handshake if we're false starting. + * + * If we were to do this check at the beginning of the loop instead + * of here, then this function would become be a no-op after + * receiving the ServerHelloDone in the false start case, and we + * would never complete the handshake. + */ + PORT_Assert(!ss->firstHsDone); + + if (ssl3_WaitingForServerSecondRound(ss)) { + keepGoing = PR_FALSE; + } + else { + ss->ssl3.hs.canFalseStart = PR_FALSE; + } + } + ssl_ReleaseSSL3HandshakeLock(ss); } while (keepGoing); ss->gs.readOffset = 0; @@ -441,14 +453,14 @@ ssl3_GatherCompleteHandshake(sslSocket *ss, int flags) int ssl3_GatherAppDataRecord(sslSocket *ss, int flags) { - int rv; + int rv; /* ssl3_GatherCompleteHandshake requires both of these locks. */ - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); do { - rv = ssl3_GatherCompleteHandshake(ss, flags); + rv = ssl3_GatherCompleteHandshake(ss, flags); } while (rv > 0 && ss->gs.buf.len == 0); return rv; diff --git a/security/nss/lib/ssl/ssl3prot.h b/security/nss/lib/ssl/ssl3prot.h index 3c44c3682515..e637d11ff85e 100644 --- a/security/nss/lib/ssl/ssl3prot.h +++ b/security/nss/lib/ssl/ssl3prot.h @@ -17,57 +17,57 @@ typedef PRUint16 SSL3ProtocolVersion; /* The TLS 1.3 draft version. Used to avoid negotiating * between incompatible pre-standard TLS 1.3 drafts. * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */ -#define TLS_1_3_DRAFT_VERSION 11 +#define TLS_1_3_DRAFT_VERSION 11 typedef PRUint16 ssl3CipherSuite; /* The cipher suites are defined in sslproto.h */ -#define MAX_CERT_TYPES 10 -#define MAX_COMPRESSION_METHODS 10 -#define MAX_MAC_LENGTH 64 -#define MAX_PADDING_LENGTH 64 -#define MAX_KEY_LENGTH 64 -#define EXPORT_KEY_LENGTH 5 -#define SSL3_RANDOM_LENGTH 32 +#define MAX_CERT_TYPES 10 +#define MAX_COMPRESSION_METHODS 10 +#define MAX_MAC_LENGTH 64 +#define MAX_PADDING_LENGTH 64 +#define MAX_KEY_LENGTH 64 +#define EXPORT_KEY_LENGTH 5 +#define SSL3_RANDOM_LENGTH 32 -#define SSL3_RECORD_HEADER_LENGTH 5 +#define SSL3_RECORD_HEADER_LENGTH 5 /* SSL3_RECORD_HEADER_LENGTH + epoch/sequence_number */ -#define DTLS_RECORD_HEADER_LENGTH 13 +#define DTLS_RECORD_HEADER_LENGTH 13 -#define MAX_FRAGMENT_LENGTH 16384 +#define MAX_FRAGMENT_LENGTH 16384 typedef enum { content_change_cipher_spec = 20, - content_alert = 21, - content_handshake = 22, - content_application_data = 23 + content_alert = 21, + content_handshake = 22, + content_application_data = 23 } SSL3ContentType; typedef struct { - SSL3ContentType type; + SSL3ContentType type; SSL3ProtocolVersion version; - PRUint16 length; - SECItem fragment; + PRUint16 length; + SECItem fragment; } SSL3Plaintext; typedef struct { - SSL3ContentType type; + SSL3ContentType type; SSL3ProtocolVersion version; - PRUint16 length; - SECItem fragment; + PRUint16 length; + SECItem fragment; } SSL3Compressed; typedef struct { - SECItem content; + SECItem content; SSL3Opaque MAC[MAX_MAC_LENGTH]; } SSL3GenericStreamCipher; typedef struct { - SECItem content; + SECItem content; SSL3Opaque MAC[MAX_MAC_LENGTH]; - PRUint8 padding[MAX_PADDING_LENGTH]; - PRUint8 padding_length; + PRUint8 padding[MAX_PADDING_LENGTH]; + PRUint8 padding_length; } SSL3GenericBlockCipher; typedef enum { change_cipher_spec_choice = 1 } SSL3ChangeCipherSpecChoice; @@ -76,70 +76,71 @@ typedef struct { SSL3ChangeCipherSpecChoice choice; } SSL3ChangeCipherSpec; -typedef enum { alert_warning = 1, alert_fatal = 2 } SSL3AlertLevel; +typedef enum { alert_warning = 1, + alert_fatal = 2 } SSL3AlertLevel; typedef enum { - close_notify = 0, - unexpected_message = 10, - bad_record_mac = 20, - decryption_failed_RESERVED = 21, /* do not send; see RFC 5246 */ - record_overflow = 22, /* TLS only */ - decompression_failure = 30, - handshake_failure = 40, - no_certificate = 41, /* SSL3 only, NOT TLS */ - bad_certificate = 42, + close_notify = 0, + unexpected_message = 10, + bad_record_mac = 20, + decryption_failed_RESERVED = 21, /* do not send; see RFC 5246 */ + record_overflow = 22, /* TLS only */ + decompression_failure = 30, + handshake_failure = 40, + no_certificate = 41, /* SSL3 only, NOT TLS */ + bad_certificate = 42, unsupported_certificate = 43, - certificate_revoked = 44, - certificate_expired = 45, - certificate_unknown = 46, - illegal_parameter = 47, + certificate_revoked = 44, + certificate_expired = 45, + certificate_unknown = 46, + illegal_parameter = 47, -/* All alerts below are TLS only. */ - unknown_ca = 48, - access_denied = 49, - decode_error = 50, - decrypt_error = 51, - export_restriction = 60, - protocol_version = 70, - insufficient_security = 71, - internal_error = 80, - inappropriate_fallback = 86, /* could also be sent for SSLv3 */ - user_canceled = 90, - no_renegotiation = 100, + /* All alerts below are TLS only. */ + unknown_ca = 48, + access_denied = 49, + decode_error = 50, + decrypt_error = 51, + export_restriction = 60, + protocol_version = 70, + insufficient_security = 71, + internal_error = 80, + inappropriate_fallback = 86, /* could also be sent for SSLv3 */ + user_canceled = 90, + no_renegotiation = 100, -/* Alerts for client hello extensions */ - missing_extension = 109, - unsupported_extension = 110, - certificate_unobtainable = 111, - unrecognized_name = 112, + /* Alerts for client hello extensions */ + missing_extension = 109, + unsupported_extension = 110, + certificate_unobtainable = 111, + unrecognized_name = 112, bad_certificate_status_response = 113, - bad_certificate_hash_value = 114, - no_application_protocol = 120 + bad_certificate_hash_value = 114, + no_application_protocol = 120 } SSL3AlertDescription; typedef struct { - SSL3AlertLevel level; + SSL3AlertLevel level; SSL3AlertDescription description; } SSL3Alert; typedef enum { - hello_request = 0, - client_hello = 1, - server_hello = 2, + hello_request = 0, + client_hello = 1, + server_hello = 2, hello_verify_request = 3, - new_session_ticket = 4, + new_session_ticket = 4, hello_retry_request = 6, encrypted_extensions = 8, - certificate = 11, + certificate = 11, server_key_exchange = 12, certificate_request = 13, - server_hello_done = 14, - certificate_verify = 15, + server_hello_done = 14, + certificate_verify = 15, client_key_exchange = 16, - finished = 20, - certificate_status = 22, - next_proto = 67 + finished = 20, + certificate_status = 22, + next_proto = 67 } SSL3HandshakeType; typedef struct { @@ -156,20 +157,20 @@ typedef struct { } SSL3SessionID; typedef struct { - SSL3ProtocolVersion client_version; - SSL3Random random; - SSL3SessionID session_id; - SECItem cipher_suites; - PRUint8 cm_count; - SSLCompressionMethod compression_methods[MAX_COMPRESSION_METHODS]; + SSL3ProtocolVersion client_version; + SSL3Random random; + SSL3SessionID session_id; + SECItem cipher_suites; + PRUint8 cm_count; + SSLCompressionMethod compression_methods[MAX_COMPRESSION_METHODS]; } SSL3ClientHello; -typedef struct { - SSL3ProtocolVersion server_version; - SSL3Random random; - SSL3SessionID session_id; - ssl3CipherSuite cipher_suite; - SSLCompressionMethod compression_method; +typedef struct { + SSL3ProtocolVersion server_version; + SSL3Random random; + SSL3SessionID session_id; + ssl3CipherSuite cipher_suite; + SSLCompressionMethod compression_method; } SSL3ServerHello; typedef struct { @@ -247,15 +248,15 @@ typedef struct { } SSL3ServerKeyExchange; typedef enum { - ct_RSA_sign = 1, - ct_DSS_sign = 2, - ct_RSA_fixed_DH = 3, - ct_DSS_fixed_DH = 4, - ct_RSA_ephemeral_DH = 5, - ct_DSS_ephemeral_DH = 6, - ct_ECDSA_sign = 64, - ct_RSA_fixed_ECDH = 65, - ct_ECDSA_fixed_ECDH = 66 + ct_RSA_sign = 1, + ct_DSS_sign = 2, + ct_RSA_fixed_DH = 3, + ct_DSS_fixed_DH = 4, + ct_RSA_ephemeral_DH = 5, + ct_DSS_ephemeral_DH = 6, + ct_ECDSA_sign = 64, + ct_RSA_fixed_ECDH = 65, + ct_ECDSA_fixed_ECDH = 66 } SSL3ClientCertificateType; @@ -287,11 +288,11 @@ typedef struct { typedef struct { PRUint32 received_timestamp; PRUint32 ticket_lifetime_hint; - SECItem ticket; + SECItem ticket; } NewSessionTicket; typedef enum { - CLIENT_AUTH_ANONYMOUS = 0, + CLIENT_AUTH_ANONYMOUS = 0, CLIENT_AUTH_CERTIFICATE = 1 } ClientAuthenticationType; @@ -302,10 +303,10 @@ typedef struct { } identity; } ClientIdentity; -#define SESS_TICKET_KEY_NAME_LEN 16 -#define SESS_TICKET_KEY_NAME_PREFIX "NSS!" +#define SESS_TICKET_KEY_NAME_LEN 16 +#define SESS_TICKET_KEY_NAME_PREFIX "NSS!" #define SESS_TICKET_KEY_NAME_PREFIX_LEN 4 -#define SESS_TICKET_KEY_VAR_NAME_LEN 12 +#define SESS_TICKET_KEY_VAR_NAME_LEN 12 typedef struct { unsigned char *key_name; @@ -316,6 +317,6 @@ typedef struct { #define TLS_EX_SESS_TICKET_MAC_LENGTH 32 -#define TLS_STE_NO_SERVER_NAME -1 +#define TLS_STE_NO_SERVER_NAME -1 #endif /* __ssl3proto_h_ */ diff --git a/security/nss/lib/ssl/sslauth.c b/security/nss/lib/ssl/sslauth.c index b144336db762..356979e5d428 100644 --- a/security/nss/lib/ssl/sslauth.c +++ b/security/nss/lib/ssl/sslauth.c @@ -17,12 +17,12 @@ SSL_PeerCertificate(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate", - SSL_GETPID(), fd)); - return 0; + SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate", + SSL_GETPID(), fd)); + return 0; } if (ss->opt.useSecurity && ss->sec.peerCert) { - return CERT_DupCertificate(ss->sec.peerCert); + return CERT_DupCertificate(ss->sec.peerCert); } return 0; } @@ -38,27 +38,27 @@ SSL_PeerCertificateChain(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificateChain", - SSL_GETPID(), fd)); - return NULL; + SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificateChain", + SSL_GETPID(), fd)); + return NULL; } if (!ss->opt.useSecurity || !ss->sec.peerCert) { - PORT_SetError(SSL_ERROR_NO_CERTIFICATE); - return NULL; + PORT_SetError(SSL_ERROR_NO_CERTIFICATE); + return NULL; } chain = CERT_NewCertList(); if (!chain) { - return NULL; + return NULL; } cert = CERT_DupCertificate(ss->sec.peerCert); if (CERT_AddCertToListTail(chain, cert) != SECSuccess) { - goto loser; + goto loser; } for (cur = ss->ssl3.peerCertChain; cur; cur = cur->next) { - cert = CERT_DupCertificate(cur->cert); - if (CERT_AddCertToListTail(chain, cert) != SECSuccess) { - goto loser; - } + cert = CERT_DupCertificate(cur->cert); + if (CERT_AddCertToListTail(chain, cert) != SECSuccess) { + goto loser; + } } return chain; @@ -75,27 +75,25 @@ SSL_LocalCertificate(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate", - SSL_GETPID(), fd)); - return NULL; + SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate", + SSL_GETPID(), fd)); + return NULL; } if (ss->opt.useSecurity) { - if (ss->sec.localCert) { - return CERT_DupCertificate(ss->sec.localCert); - } - if (ss->sec.ci.sid && ss->sec.ci.sid->localCert) { - return CERT_DupCertificate(ss->sec.ci.sid->localCert); - } + if (ss->sec.localCert) { + return CERT_DupCertificate(ss->sec.localCert); + } + if (ss->sec.ci.sid && ss->sec.ci.sid->localCert) { + return CERT_DupCertificate(ss->sec.ci.sid->localCert); + } } return NULL; } - - /* NEED LOCKS IN HERE. */ SECStatus SSL_SecurityStatus(PRFileDesc *fd, int *op, char **cp, int *kp0, int *kp1, - char **ip, char **sp) + char **ip, char **sp) { sslSocket *ss; const char *cipherName; @@ -103,74 +101,85 @@ SSL_SecurityStatus(PRFileDesc *fd, int *op, char **cp, int *kp0, int *kp1, ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SecurityStatus", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SecurityStatus", + SSL_GETPID(), fd)); + return SECFailure; } - if (cp) *cp = 0; - if (kp0) *kp0 = 0; - if (kp1) *kp1 = 0; - if (ip) *ip = 0; - if (sp) *sp = 0; + if (cp) + *cp = 0; + if (kp0) + *kp0 = 0; + if (kp1) + *kp1 = 0; + if (ip) + *ip = 0; + if (sp) + *sp = 0; if (op) { - *op = SSL_SECURITY_STATUS_OFF; + *op = SSL_SECURITY_STATUS_OFF; } if (ss->opt.useSecurity && ss->enoughFirstHsDone) { - if (ss->version < SSL_LIBRARY_VERSION_3_0) { - cipherName = ssl_cipherName[ss->sec.cipherType]; - } else { - cipherName = ssl3_cipherName[ss->sec.cipherType]; - } - PORT_Assert(cipherName); - if (cipherName) { - if (PORT_Strstr(cipherName, "DES")) isDes = PR_TRUE; + if (ss->version < SSL_LIBRARY_VERSION_3_0) { + cipherName = ssl_cipherName[ss->sec.cipherType]; + } + else { + cipherName = ssl3_cipherName[ss->sec.cipherType]; + } + PORT_Assert(cipherName); + if (cipherName) { + if (PORT_Strstr(cipherName, "DES")) + isDes = PR_TRUE; if (cp) { *cp = PORT_Strdup(cipherName); } } - if (kp0) { - *kp0 = ss->sec.keyBits; - if (isDes) *kp0 = (*kp0 * 7) / 8; - } - if (kp1) { - *kp1 = ss->sec.secretKeyBits; - if (isDes) *kp1 = (*kp1 * 7) / 8; - } - if (op) { - if (ss->sec.keyBits == 0) { - *op = SSL_SECURITY_STATUS_OFF; - } else if (ss->sec.secretKeyBits < 90) { - *op = SSL_SECURITY_STATUS_ON_LOW; + if (kp0) { + *kp0 = ss->sec.keyBits; + if (isDes) + *kp0 = (*kp0 * 7) / 8; + } + if (kp1) { + *kp1 = ss->sec.secretKeyBits; + if (isDes) + *kp1 = (*kp1 * 7) / 8; + } + if (op) { + if (ss->sec.keyBits == 0) { + *op = SSL_SECURITY_STATUS_OFF; + } + else if (ss->sec.secretKeyBits < 90) { + *op = SSL_SECURITY_STATUS_ON_LOW; + } + else { + *op = SSL_SECURITY_STATUS_ON_HIGH; + } + } - } else { - *op = SSL_SECURITY_STATUS_ON_HIGH; - } - } + if (ip || sp) { + CERTCertificate *cert; - if (ip || sp) { - CERTCertificate *cert; - - cert = ss->sec.peerCert; - if (cert) { - if (ip) { - *ip = CERT_NameToAscii(&cert->issuer); - } - if (sp) { - *sp = CERT_NameToAscii(&cert->subject); - } - } else { - if (ip) { - *ip = PORT_Strdup("no certificate"); - } - if (sp) { - *sp = PORT_Strdup("no certificate"); - } - } - } + cert = ss->sec.peerCert; + if (cert) { + if (ip) { + *ip = CERT_NameToAscii(&cert->issuer); + } + if (sp) { + *sp = CERT_NameToAscii(&cert->subject); + } + } + else { + if (ip) { + *ip = PORT_Strdup("no certificate"); + } + if (sp) { + *sp = PORT_Strdup("no certificate"); + } + } + } } return SECSuccess; @@ -186,9 +195,9 @@ SSL_AuthCertificateHook(PRFileDesc *s, SSLAuthCertificate func, void *arg) ss = ssl_FindSocket(s); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in AuthCertificateHook", - SSL_GETPID(), s)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in AuthCertificateHook", + SSL_GETPID(), s)); + return SECFailure; } ss->authCertificate = func; @@ -198,17 +207,17 @@ SSL_AuthCertificateHook(PRFileDesc *s, SSLAuthCertificate func, void *arg) } /* NEED LOCKS IN HERE. */ -SECStatus +SECStatus SSL_GetClientAuthDataHook(PRFileDesc *s, SSLGetClientAuthData func, - void *arg) + void *arg) { sslSocket *ss; ss = ssl_FindSocket(s); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook", - SSL_GETPID(), s)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook", + SSL_GETPID(), s)); + return SECFailure; } ss->getClientAuthData = func; @@ -217,77 +226,76 @@ SSL_GetClientAuthDataHook(PRFileDesc *s, SSLGetClientAuthData func, } /* NEED LOCKS IN HERE. */ -SECStatus +SECStatus SSL_SetPKCS11PinArg(PRFileDesc *s, void *arg) { sslSocket *ss; ss = ssl_FindSocket(s); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook", - SSL_GETPID(), s)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook", + SSL_GETPID(), s)); + return SECFailure; } ss->pkcs11PinArg = arg; return SECSuccess; } - -/* This is the "default" authCert callback function. It is called when a +/* This is the "default" authCert callback function. It is called when a * certificate message is received from the peer and the local application * has not registered an authCert callback function. */ SECStatus SSL_AuthCertificate(void *arg, PRFileDesc *fd, PRBool checkSig, PRBool isServer) { - SECStatus rv; - CERTCertDBHandle * handle; - sslSocket * ss; - SECCertUsage certUsage; - const char * hostname = NULL; - PRTime now = PR_Now(); - SECItemArray * certStatusArray; - + SECStatus rv; + CERTCertDBHandle *handle; + sslSocket *ss; + SECCertUsage certUsage; + const char *hostname = NULL; + PRTime now = PR_Now(); + SECItemArray *certStatusArray; + ss = ssl_FindSocket(fd); PORT_Assert(ss != NULL); if (!ss) { - return SECFailure; + return SECFailure; } handle = (CERTCertDBHandle *)arg; certStatusArray = &ss->sec.ci.sid->peerCertStatus; if (certStatusArray->len) { - PORT_SetError(0); - if (CERT_CacheOCSPResponseFromSideChannel(handle, ss->sec.peerCert, now, - &certStatusArray->items[0], - ss->pkcs11PinArg) - != SECSuccess) { - PORT_Assert(PR_GetError() != 0); - } + PORT_SetError(0); + if (CERT_CacheOCSPResponseFromSideChannel(handle, ss->sec.peerCert, now, + &certStatusArray->items[0], + ss->pkcs11PinArg) != + SECSuccess) { + PORT_Assert(PR_GetError() != 0); + } } /* this may seem backwards, but isn't. */ certUsage = isServer ? certUsageSSLClient : certUsageSSLServer; rv = CERT_VerifyCert(handle, ss->sec.peerCert, checkSig, certUsage, - now, ss->pkcs11PinArg, NULL); + now, ss->pkcs11PinArg, NULL); + + if (rv != SECSuccess || isServer) + return rv; - if ( rv != SECSuccess || isServer ) - return rv; - /* cert is OK. This is the client side of an SSL connection. * Now check the name field in the cert against the desired hostname. * NB: This is our only defense against Man-In-The-Middle (MITM) attacks! */ hostname = ss->url; if (hostname && hostname[0]) - rv = CERT_VerifyCertName(ss->sec.peerCert, hostname); - else - rv = SECFailure; + rv = CERT_VerifyCertName(ss->sec.peerCert, hostname); + else + rv = SECFailure; if (rv != SECSuccess) - PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); + PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); return rv; } diff --git a/security/nss/lib/ssl/sslcon.c b/security/nss/lib/ssl/sslcon.c index 8cc8f954f84b..5055e6136bbd 100644 --- a/security/nss/lib/ssl/sslcon.c +++ b/security/nss/lib/ssl/sslcon.c @@ -1,4 +1,4 @@ -/* +/* * SSL v2 handshake functions, and functions common to SSL2 and SSL3. * * This Source Code Form is subject to the terms of the Mozilla Public @@ -9,8 +9,8 @@ #include "cert.h" #include "secitem.h" #include "sechash.h" -#include "cryptohi.h" /* for SGN_ funcs */ -#include "keyhi.h" /* for SECKEY_ high level functions. */ +#include "cryptohi.h" /* for SGN_ funcs */ +#include "keyhi.h" /* for SECKEY_ high level functions. */ #include "ssl.h" #include "sslimpl.h" #include "sslproto.h" @@ -18,75 +18,78 @@ #include "sslerr.h" #include "pk11func.h" #include "prinit.h" -#include "prtime.h" /* for PR_Now() */ +#include "prtime.h" /* for PR_Now() */ static PRBool policyWasSet; #define ssl2_NUM_SUITES_IMPLEMENTED 6 -/* This list is sent back to the client when the client-hello message +/* This list is sent back to the client when the client-hello message * contains no overlapping ciphers, so the client can report what ciphers * are supported by the server. Unlike allCipherSuites (above), this list - * is sorted by descending preference, not by cipherSuite number. + * is sorted by descending preference, not by cipherSuite number. */ +/* clang-format off */ static const PRUint8 implementedCipherSuites[ssl2_NUM_SUITES_IMPLEMENTED * 3] = { - SSL_CK_RC4_128_WITH_MD5, 0x00, 0x80, - SSL_CK_RC2_128_CBC_WITH_MD5, 0x00, 0x80, - SSL_CK_DES_192_EDE3_CBC_WITH_MD5, 0x00, 0xC0, - SSL_CK_DES_64_CBC_WITH_MD5, 0x00, 0x40, - SSL_CK_RC4_128_EXPORT40_WITH_MD5, 0x00, 0x80, - SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5, 0x00, 0x80 + SSL_CK_RC4_128_WITH_MD5, 0x00, 0x80, + SSL_CK_RC2_128_CBC_WITH_MD5, 0x00, 0x80, + SSL_CK_DES_192_EDE3_CBC_WITH_MD5, 0x00, 0xC0, + SSL_CK_DES_64_CBC_WITH_MD5, 0x00, 0x40, + SSL_CK_RC4_128_EXPORT40_WITH_MD5, 0x00, 0x80, + SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5, 0x00, 0x80 }; + typedef struct ssl2SpecsStr { - PRUint8 nkm; /* do this many hashes to generate key material. */ - PRUint8 nkd; /* size of readKey and writeKey in bytes. */ - PRUint8 blockSize; - PRUint8 blockShift; + PRUint8 nkm; /* do this many hashes to generate key material. */ + PRUint8 nkd; /* size of readKey and writeKey in bytes. */ + PRUint8 blockSize; + PRUint8 blockShift; CK_MECHANISM_TYPE mechanism; - PRUint8 keyLen; /* cipher symkey size in bytes. */ - PRUint8 pubLen; /* publicly reveal this many bytes of key. */ - PRUint8 ivLen; /* length of IV data at *ca. */ + PRUint8 keyLen; /* cipher symkey size in bytes. */ + PRUint8 pubLen; /* publicly reveal this many bytes of key. */ + PRUint8 ivLen; /* length of IV data at *ca. */ } ssl2Specs; static const ssl2Specs ssl_Specs[] = { -/* NONE */ - { 0, 0, 0, 0 }, -/* SSL_CK_RC4_128_WITH_MD5 */ - { 2, 16, 1, 0, CKM_RC4, 16, 0, 0 }, -/* SSL_CK_RC4_128_EXPORT40_WITH_MD5 */ - { 2, 16, 1, 0, CKM_RC4, 16, 11, 0 }, -/* SSL_CK_RC2_128_CBC_WITH_MD5 */ - { 2, 16, 8, 3, CKM_RC2_CBC, 16, 0, 8 }, -/* SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 */ - { 2, 16, 8, 3, CKM_RC2_CBC, 16, 11, 8 }, -/* SSL_CK_IDEA_128_CBC_WITH_MD5 */ - { 0, 0, 0, 0 }, -/* SSL_CK_DES_64_CBC_WITH_MD5 */ - { 1, 8, 8, 3, CKM_DES_CBC, 8, 0, 8 }, -/* SSL_CK_DES_192_EDE3_CBC_WITH_MD5 */ - { 3, 24, 8, 3, CKM_DES3_CBC, 24, 0, 8 }, + /* NONE */ + { 0, 0, 0, 0 }, + /* SSL_CK_RC4_128_WITH_MD5 */ + { 2, 16, 1, 0, CKM_RC4, 16, 0, 0 }, + /* SSL_CK_RC4_128_EXPORT40_WITH_MD5 */ + { 2, 16, 1, 0, CKM_RC4, 16, 11, 0 }, + /* SSL_CK_RC2_128_CBC_WITH_MD5 */ + { 2, 16, 8, 3, CKM_RC2_CBC, 16, 0, 8 }, + /* SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 */ + { 2, 16, 8, 3, CKM_RC2_CBC, 16, 11, 8 }, + /* SSL_CK_IDEA_128_CBC_WITH_MD5 */ + { 0, 0, 0, 0 }, + /* SSL_CK_DES_64_CBC_WITH_MD5 */ + { 1, 8, 8, 3, CKM_DES_CBC, 8, 0, 8 }, + /* SSL_CK_DES_192_EDE3_CBC_WITH_MD5 */ + { 3, 24, 8, 3, CKM_DES3_CBC, 24, 0, 8 }, }; +/* clang-format on */ -#define SET_ERROR_CODE /* reminder */ -#define TEST_FOR_FAILURE /* reminder */ +#define SET_ERROR_CODE /* reminder */ +#define TEST_FOR_FAILURE /* reminder */ /* ** Put a string tag in the library so that we can examine an executable ** and see what kind of security it supports. */ const char *ssl_version = "SECURITY_VERSION:" - " +us" - " +export" + " +us" + " +export" #ifdef TRACE - " +trace" + " +trace" #endif #ifdef DEBUG - " +debug" + " +debug" #endif - ; + ; -const char * const ssl_cipherName[] = { +const char *const ssl_cipherName[] = { "unknown", "RC4", "RC4-Export", @@ -99,100 +102,100 @@ const char * const ssl_cipherName[] = { "unknown", /* was fortezza, NO LONGER USED */ }; - /* bit-masks, showing which SSLv2 suites are allowed. * lsb corresponds to first cipher suite in allCipherSuites[]. */ -static PRUint16 allowedByPolicy; /* all off by default */ -static PRUint16 maybeAllowedByPolicy; /* all off by default */ -static PRUint16 chosenPreference = 0xff; /* all on by default */ +static PRUint16 allowedByPolicy; /* all off by default */ +static PRUint16 maybeAllowedByPolicy; /* all off by default */ +static PRUint16 chosenPreference = 0xff; /* all on by default */ /* bit values for the above two bit masks */ -#define SSL_CB_RC4_128_WITH_MD5 (1 << SSL_CK_RC4_128_WITH_MD5) -#define SSL_CB_RC4_128_EXPORT40_WITH_MD5 (1 << SSL_CK_RC4_128_EXPORT40_WITH_MD5) -#define SSL_CB_RC2_128_CBC_WITH_MD5 (1 << SSL_CK_RC2_128_CBC_WITH_MD5) +#define SSL_CB_RC4_128_WITH_MD5 (1 << SSL_CK_RC4_128_WITH_MD5) +#define SSL_CB_RC4_128_EXPORT40_WITH_MD5 (1 << SSL_CK_RC4_128_EXPORT40_WITH_MD5) +#define SSL_CB_RC2_128_CBC_WITH_MD5 (1 << SSL_CK_RC2_128_CBC_WITH_MD5) #define SSL_CB_RC2_128_CBC_EXPORT40_WITH_MD5 (1 << SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5) -#define SSL_CB_IDEA_128_CBC_WITH_MD5 (1 << SSL_CK_IDEA_128_CBC_WITH_MD5) -#define SSL_CB_DES_64_CBC_WITH_MD5 (1 << SSL_CK_DES_64_CBC_WITH_MD5) -#define SSL_CB_DES_192_EDE3_CBC_WITH_MD5 (1 << SSL_CK_DES_192_EDE3_CBC_WITH_MD5) -#define SSL_CB_IMPLEMENTED \ - (SSL_CB_RC4_128_WITH_MD5 | \ - SSL_CB_RC4_128_EXPORT40_WITH_MD5 | \ - SSL_CB_RC2_128_CBC_WITH_MD5 | \ - SSL_CB_RC2_128_CBC_EXPORT40_WITH_MD5 | \ - SSL_CB_DES_64_CBC_WITH_MD5 | \ - SSL_CB_DES_192_EDE3_CBC_WITH_MD5) - +#define SSL_CB_IDEA_128_CBC_WITH_MD5 (1 << SSL_CK_IDEA_128_CBC_WITH_MD5) +#define SSL_CB_DES_64_CBC_WITH_MD5 (1 << SSL_CK_DES_64_CBC_WITH_MD5) +#define SSL_CB_DES_192_EDE3_CBC_WITH_MD5 (1 << SSL_CK_DES_192_EDE3_CBC_WITH_MD5) +#define SSL_CB_IMPLEMENTED \ + (SSL_CB_RC4_128_WITH_MD5 | \ + SSL_CB_RC4_128_EXPORT40_WITH_MD5 | \ + SSL_CB_RC2_128_CBC_WITH_MD5 | \ + SSL_CB_RC2_128_CBC_EXPORT40_WITH_MD5 | \ + SSL_CB_DES_64_CBC_WITH_MD5 | \ + SSL_CB_DES_192_EDE3_CBC_WITH_MD5) /* Construct a socket's list of cipher specs from the global default values. */ static SECStatus -ssl2_ConstructCipherSpecs(sslSocket *ss) +ssl2_ConstructCipherSpecs(sslSocket *ss) { - PRUint8 * cs = NULL; - unsigned int allowed; - unsigned int count; - int ssl3_count = 0; - int final_count; - int i; - SECStatus rv; + PRUint8 *cs = NULL; + unsigned int allowed; + unsigned int count; + int ssl3_count = 0; + int final_count; + int i; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); count = 0; PORT_Assert(ss != 0); allowed = !ss->opt.enableSSL2 ? 0 : - (ss->allowedByPolicy & ss->chosenPreference & SSL_CB_IMPLEMENTED); + (ss->allowedByPolicy & + ss->chosenPreference & SSL_CB_IMPLEMENTED); while (allowed) { - if (allowed & 1) - ++count; - allowed >>= 1; + if (allowed & 1) + ++count; + allowed >>= 1; } - /* Call ssl3_config_match_init() once here, + /* Call ssl3_config_match_init() once here, * instead of inside ssl3_ConstructV2CipherSpecsHack(), - * because the latter gets called twice below, + * because the latter gets called twice below, * and then again in ssl2_BeginClientHandshake(). */ ssl3_config_match_init(ss); /* ask SSL3 how many cipher suites it has. */ rv = ssl3_ConstructV2CipherSpecsHack(ss, NULL, &ssl3_count); - if (rv < 0) - return rv; + if (rv < 0) + return rv; count += ssl3_count; /* Allocate memory to hold cipher specs */ if (count > 0) - cs = (PRUint8*) PORT_Alloc(count * 3); + cs = (PRUint8 *)PORT_Alloc(count * 3); else - PORT_SetError(SSL_ERROR_SSL_DISABLED); + PORT_SetError(SSL_ERROR_SSL_DISABLED); if (cs == NULL) - return SECFailure; + return SECFailure; if (ss->cipherSpecs != NULL) { - PORT_Free(ss->cipherSpecs); + PORT_Free(ss->cipherSpecs); } - ss->cipherSpecs = cs; + ss->cipherSpecs = cs; ss->sizeCipherSpecs = count * 3; /* fill in cipher specs for SSL2 cipher suites */ allowed = !ss->opt.enableSSL2 ? 0 : - (ss->allowedByPolicy & ss->chosenPreference & SSL_CB_IMPLEMENTED); + (ss->allowedByPolicy & + ss->chosenPreference & SSL_CB_IMPLEMENTED); for (i = 0; i < ssl2_NUM_SUITES_IMPLEMENTED * 3; i += 3) { - const PRUint8 * hs = implementedCipherSuites + i; - int ok = allowed & (1U << hs[0]); - if (ok) { - cs[0] = hs[0]; - cs[1] = hs[1]; - cs[2] = hs[2]; - cs += 3; - } + const PRUint8 *hs = implementedCipherSuites + i; + int ok = allowed & (1U << hs[0]); + if (ok) { + cs[0] = hs[0]; + cs[1] = hs[1]; + cs[2] = hs[2]; + cs += 3; + } } /* now have SSL3 add its suites onto the end */ rv = ssl3_ConstructV2CipherSpecsHack(ss, cs, &final_count); - + /* adjust for any difference between first pass and second pass */ ss->sizeCipherSpecs -= (ssl3_count - final_count) * 3; @@ -202,7 +205,7 @@ ssl2_ConstructCipherSpecs(sslSocket *ss) /* This function is called immediately after ssl2_ConstructCipherSpecs() ** at the beginning of a handshake. It detects cases where a protocol ** (e.g. SSL2 or SSL3) is logically enabled, but all its cipher suites -** for that protocol have been disabled. If such cases, it clears the +** for that protocol have been disabled. If such cases, it clears the ** enable bit for the protocol. If no protocols remain enabled, or ** if no cipher suites are found, it sets the error code and returns ** SECFailure, otherwise it returns SECSuccess. @@ -210,69 +213,71 @@ ssl2_ConstructCipherSpecs(sslSocket *ss) static SECStatus ssl2_CheckConfigSanity(sslSocket *ss) { - unsigned int allowed; - int ssl3CipherCount = 0; - SECStatus rv; + unsigned int allowed; + int ssl3CipherCount = 0; + SECStatus rv; /* count the SSL2 and SSL3 enabled ciphers. * if either is zero, clear the socket's enable for that protocol. */ if (!ss->cipherSpecs) - goto disabled; + goto disabled; allowed = ss->allowedByPolicy & ss->chosenPreference; - if (! allowed) - ss->opt.enableSSL2 = PR_FALSE; /* not really enabled if no ciphers */ + if (!allowed) + ss->opt.enableSSL2 = PR_FALSE; /* not really enabled if no ciphers */ /* ssl3_config_match_init was called in ssl2_ConstructCipherSpecs(). */ /* Ask how many ssl3 CipherSuites were enabled. */ rv = ssl3_ConstructV2CipherSpecsHack(ss, NULL, &ssl3CipherCount); if (rv != SECSuccess || ssl3CipherCount <= 0) { - /* SSL3/TLS not really enabled if no ciphers */ - ss->vrange.min = SSL_LIBRARY_VERSION_NONE; - ss->vrange.max = SSL_LIBRARY_VERSION_NONE; + /* SSL3/TLS not really enabled if no ciphers */ + ss->vrange.min = SSL_LIBRARY_VERSION_NONE; + ss->vrange.max = SSL_LIBRARY_VERSION_NONE; } if (!ss->opt.enableSSL2 && SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - SSL_DBG(("%d: SSL[%d]: Can't handshake! all versions disabled.", - SSL_GETPID(), ss->fd)); -disabled: - PORT_SetError(SSL_ERROR_SSL_DISABLED); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: Can't handshake! all versions disabled.", + SSL_GETPID(), ss->fd)); + disabled: + PORT_SetError(SSL_ERROR_SSL_DISABLED); + return SECFailure; } return SECSuccess; } -/* +/* * Since this is a global (not per-socket) setting, we cannot use the * HandshakeLock to protect this. Probably want a global lock. */ SECStatus ssl2_SetPolicy(PRInt32 which, PRInt32 policy) { - PRUint32 bitMask; - SECStatus rv = SECSuccess; + PRUint32 bitMask; + SECStatus rv = SECSuccess; which &= 0x000f; bitMask = 1 << which; if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - return SECFailure; + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); + return SECFailure; } if (policy == SSL_ALLOWED) { - allowedByPolicy |= bitMask; - maybeAllowedByPolicy |= bitMask; - } else if (policy == SSL_RESTRICTED) { - allowedByPolicy &= ~bitMask; - maybeAllowedByPolicy |= bitMask; - } else { - allowedByPolicy &= ~bitMask; - maybeAllowedByPolicy &= ~bitMask; + allowedByPolicy |= bitMask; + maybeAllowedByPolicy |= bitMask; } - allowedByPolicy &= SSL_CB_IMPLEMENTED; - maybeAllowedByPolicy &= SSL_CB_IMPLEMENTED; + else if (policy == SSL_RESTRICTED) { + allowedByPolicy &= ~bitMask; + maybeAllowedByPolicy |= bitMask; + } + else { + allowedByPolicy &= ~bitMask; + maybeAllowedByPolicy &= ~bitMask; + } + allowedByPolicy &= SSL_CB_IMPLEMENTED; + maybeAllowedByPolicy &= SSL_CB_IMPLEMENTED; policyWasSet = PR_TRUE; return rv; @@ -281,70 +286,71 @@ ssl2_SetPolicy(PRInt32 which, PRInt32 policy) SECStatus ssl2_GetPolicy(PRInt32 which, PRInt32 *oPolicy) { - PRUint32 bitMask; - PRInt32 policy; + PRUint32 bitMask; + PRInt32 policy; which &= 0x000f; bitMask = 1 << which; /* Caller assures oPolicy is not null. */ if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - *oPolicy = SSL_NOT_ALLOWED; - return SECFailure; + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); + *oPolicy = SSL_NOT_ALLOWED; + return SECFailure; } if (maybeAllowedByPolicy & bitMask) { - policy = (allowedByPolicy & bitMask) ? SSL_ALLOWED : SSL_RESTRICTED; - } else { - policy = SSL_NOT_ALLOWED; + policy = (allowedByPolicy & bitMask) ? SSL_ALLOWED : SSL_RESTRICTED; + } + else { + policy = SSL_NOT_ALLOWED; } *oPolicy = policy; return SECSuccess; } -/* +/* * Since this is a global (not per-socket) setting, we cannot use the * HandshakeLock to protect this. Probably want a global lock. * Called from SSL_CipherPrefSetDefault in sslsock.c - * These changes have no effect on any sslSockets already created. + * These changes have no effect on any sslSockets already created. */ SECStatus ssl2_CipherPrefSetDefault(PRInt32 which, PRBool enabled) { - PRUint32 bitMask; - + PRUint32 bitMask; + which &= 0x000f; bitMask = 1 << which; if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - return SECFailure; + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); + return SECFailure; } if (enabled) - chosenPreference |= bitMask; + chosenPreference |= bitMask; else - chosenPreference &= ~bitMask; + chosenPreference &= ~bitMask; chosenPreference &= SSL_CB_IMPLEMENTED; return SECSuccess; } -SECStatus +SECStatus ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) { - PRBool rv = PR_FALSE; - PRUint32 bitMask; + PRBool rv = PR_FALSE; + PRUint32 bitMask; which &= 0x000f; bitMask = 1 << which; if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - *enabled = PR_FALSE; - return SECFailure; + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); + *enabled = PR_FALSE; + return SECFailure; } rv = (PRBool)((chosenPreference & bitMask) != 0); @@ -352,41 +358,41 @@ ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) return SECSuccess; } -SECStatus +SECStatus ssl2_CipherPrefSet(sslSocket *ss, PRInt32 which, PRBool enabled) { - PRUint32 bitMask; - + PRUint32 bitMask; + which &= 0x000f; bitMask = 1 << which; if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - return SECFailure; + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); + return SECFailure; } if (enabled) - ss->chosenPreference |= bitMask; + ss->chosenPreference |= bitMask; else - ss->chosenPreference &= ~bitMask; + ss->chosenPreference &= ~bitMask; ss->chosenPreference &= SSL_CB_IMPLEMENTED; return SECSuccess; } -SECStatus +SECStatus ssl2_CipherPrefGet(sslSocket *ss, PRInt32 which, PRBool *enabled) { - PRBool rv = PR_FALSE; - PRUint32 bitMask; + PRBool rv = PR_FALSE; + PRUint32 bitMask; which &= 0x000f; bitMask = 1 << which; if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - *enabled = PR_FALSE; - return SECFailure; + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); + *enabled = PR_FALSE; + return SECFailure; } rv = (PRBool)((ss->chosenPreference & bitMask) != 0); @@ -394,51 +400,49 @@ ssl2_CipherPrefGet(sslSocket *ss, PRInt32 which, PRBool *enabled) return SECSuccess; } - /* copy global default policy into socket. */ -void +void ssl2_InitSocketPolicy(sslSocket *ss) { - ss->allowedByPolicy = allowedByPolicy; - ss->maybeAllowedByPolicy = maybeAllowedByPolicy; - ss->chosenPreference = chosenPreference; + ss->allowedByPolicy = allowedByPolicy; + ss->maybeAllowedByPolicy = maybeAllowedByPolicy; + ss->chosenPreference = chosenPreference; } - /************************************************************************/ /* Called from ssl2_CreateSessionCypher(), which already holds handshake lock. */ static SECStatus -ssl2_CreateMAC(sslSecurityInfo *sec, SECItem *readKey, SECItem *writeKey, - int cipherChoice) +ssl2_CreateMAC(sslSecurityInfo *sec, SECItem *readKey, SECItem *writeKey, + int cipherChoice) { switch (cipherChoice) { - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_WITH_MD5: - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC4_128_WITH_MD5: - case SSL_CK_DES_64_CBC_WITH_MD5: - case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: - sec->hash = HASH_GetHashObject(HASH_AlgMD5); - if (SECITEM_CopyItem(0, &sec->sendSecret, writeKey) || - SECITEM_CopyItem(0, &sec->rcvSecret, readKey)) { - return SECFailure; - } - break; + case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: + case SSL_CK_RC2_128_CBC_WITH_MD5: + case SSL_CK_RC4_128_EXPORT40_WITH_MD5: + case SSL_CK_RC4_128_WITH_MD5: + case SSL_CK_DES_64_CBC_WITH_MD5: + case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: + sec->hash = HASH_GetHashObject(HASH_AlgMD5); + if (SECITEM_CopyItem(0, &sec->sendSecret, writeKey) || + SECITEM_CopyItem(0, &sec->rcvSecret, readKey)) { + return SECFailure; + } + break; - default: - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; + default: + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return SECFailure; } sec->hashcx = (*sec->hash->create)(); if (sec->hashcx == NULL) - return SECFailure; + return SECFailure; return SECSuccess; } /************************************************************************ - * All the Send functions below must acquire and release the socket's + * All the Send functions below must acquire and release the socket's * xmitBufLock. */ @@ -451,115 +455,115 @@ ssl2_GetSendBuffer(sslSocket *ss, unsigned int len) PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); if (len < 128) { - len = 128; + len = 128; } if (len > ss->sec.ci.sendBuf.space) { - rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, len); - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL[%d]: ssl2_GetSendBuffer failed, tried to get %d bytes", - SSL_GETPID(), ss->fd, len)); - rv = SECFailure; - } + rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, len); + if (rv != SECSuccess) { + SSL_DBG(("%d: SSL[%d]: ssl2_GetSendBuffer failed, tried to get %d bytes", + SSL_GETPID(), ss->fd, len)); + rv = SECFailure; + } } return rv; } /* Called from: - * ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage() - * ssl2_HandleRequestCertificate() <- ssl2_HandleMessage() <- - ssl_Do1stHandshake() - * ssl2_HandleMessage() <- ssl_Do1stHandshake() - * ssl2_HandleServerHelloMessage() <- ssl_Do1stHandshake() - after ssl2_BeginClientHandshake() - * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake() - after ssl2_BeginServerHandshake() - * + * ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage() + * ssl2_HandleRequestCertificate() <- ssl2_HandleMessage() + <- ssl_Do1stHandshake() + * ssl2_HandleMessage() <- ssl_Do1stHandshake() + * ssl2_HandleServerHelloMessage() <- ssl_Do1stHandshake() + after ssl2_BeginClientHandshake() + * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake() + after ssl2_BeginServerHandshake() + * * Acquires and releases the socket's xmitBufLock. - */ + */ int ssl2_SendErrorMessage(sslSocket *ss, int error) { int rv; PRUint8 msg[SSL_HL_ERROR_HBYTES]; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); msg[0] = SSL_MT_ERROR; msg[1] = MSB(error); msg[2] = LSB(error); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ SSL_TRC(3, ("%d: SSL[%d]: sending error %d", SSL_GETPID(), ss->fd, error)); ss->handshakeBegun = 1; rv = (*ss->sec.send)(ss, msg, sizeof(msg), 0); if (rv >= 0) { - rv = SECSuccess; + rv = SECSuccess; } - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ return rv; } -/* Called from ssl2_TryToFinish(). +/* Called from ssl2_TryToFinish(). * Acquires and releases the socket's xmitBufLock. */ static SECStatus ssl2_SendClientFinishedMessage(sslSocket *ss) { - SECStatus rv = SECSuccess; - int sent; - PRUint8 msg[1 + SSL_CONNECTIONID_BYTES]; + SECStatus rv = SECSuccess; + int sent; + PRUint8 msg[1 + SSL_CONNECTIONID_BYTES]; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ if (ss->sec.ci.sentFinished == 0) { - ss->sec.ci.sentFinished = 1; + ss->sec.ci.sentFinished = 1; - SSL_TRC(3, ("%d: SSL[%d]: sending client-finished", - SSL_GETPID(), ss->fd)); + SSL_TRC(3, ("%d: SSL[%d]: sending client-finished", + SSL_GETPID(), ss->fd)); - msg[0] = SSL_MT_CLIENT_FINISHED; - PORT_Memcpy(msg+1, ss->sec.ci.connectionID, - sizeof(ss->sec.ci.connectionID)); + msg[0] = SSL_MT_CLIENT_FINISHED; + PORT_Memcpy(msg + 1, ss->sec.ci.connectionID, + sizeof(ss->sec.ci.connectionID)); - DUMP_MSG(29, (ss, msg, 1 + sizeof(ss->sec.ci.connectionID))); - sent = (*ss->sec.send)(ss, msg, 1 + sizeof(ss->sec.ci.connectionID), 0); - rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; + DUMP_MSG(29, (ss, msg, 1 + sizeof(ss->sec.ci.connectionID))); + sent = (*ss->sec.send)(ss, msg, 1 + sizeof(ss->sec.ci.connectionID), 0); + rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; } - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ return rv; } -/* Called from +/* Called from * ssl2_HandleClientSessionKeyMessage() <- ssl2_HandleClientHelloMessage() - * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake() - after ssl2_BeginServerHandshake() + * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake() + after ssl2_BeginServerHandshake() * Acquires and releases the socket's xmitBufLock. */ static SECStatus ssl2_SendServerVerifyMessage(sslSocket *ss) { - PRUint8 * msg; - int sendLen; - int sent; - SECStatus rv; + PRUint8 *msg; + int sendLen; + int sent; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ sendLen = 1 + SSL_CHALLENGE_BYTES; rv = ssl2_GetSendBuffer(ss, sendLen); if (rv != SECSuccess) { - goto done; + goto done; } msg = ss->sec.ci.sendBuf.buf; msg[0] = SSL_MT_SERVER_VERIFY; - PORT_Memcpy(msg+1, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES); + PORT_Memcpy(msg + 1, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES); DUMP_MSG(29, (ss, msg, sendLen)); sent = (*ss->sec.send)(ss, msg, sendLen, 0); @@ -567,93 +571,93 @@ ssl2_SendServerVerifyMessage(sslSocket *ss) rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ return rv; } -/* Called from ssl2_TryToFinish(). +/* Called from ssl2_TryToFinish(). * Acquires and releases the socket's xmitBufLock. */ static SECStatus ssl2_SendServerFinishedMessage(sslSocket *ss) { - sslSessionID * sid; - PRUint8 * msg; - int sendLen, sent; - SECStatus rv = SECSuccess; + sslSessionID *sid; + PRUint8 *msg; + int sendLen, sent; + SECStatus rv = SECSuccess; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ if (ss->sec.ci.sentFinished == 0) { - ss->sec.ci.sentFinished = 1; - PORT_Assert(ss->sec.ci.sid != 0); - sid = ss->sec.ci.sid; + ss->sec.ci.sentFinished = 1; + PORT_Assert(ss->sec.ci.sid != 0); + sid = ss->sec.ci.sid; - SSL_TRC(3, ("%d: SSL[%d]: sending server-finished", - SSL_GETPID(), ss->fd)); + SSL_TRC(3, ("%d: SSL[%d]: sending server-finished", + SSL_GETPID(), ss->fd)); - sendLen = 1 + sizeof(sid->u.ssl2.sessionID); - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) { - goto done; - } + sendLen = 1 + sizeof(sid->u.ssl2.sessionID); + rv = ssl2_GetSendBuffer(ss, sendLen); + if (rv != SECSuccess) { + goto done; + } - msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_SERVER_FINISHED; - PORT_Memcpy(msg+1, sid->u.ssl2.sessionID, - sizeof(sid->u.ssl2.sessionID)); + msg = ss->sec.ci.sendBuf.buf; + msg[0] = SSL_MT_SERVER_FINISHED; + PORT_Memcpy(msg + 1, sid->u.ssl2.sessionID, + sizeof(sid->u.ssl2.sessionID)); - DUMP_MSG(29, (ss, msg, sendLen)); - sent = (*ss->sec.send)(ss, msg, sendLen, 0); + DUMP_MSG(29, (ss, msg, sendLen)); + sent = (*ss->sec.send)(ss, msg, sendLen, 0); - if (sent < 0) { - /* If send failed, it is now a bogus session-id */ - if (ss->sec.uncache) - (*ss->sec.uncache)(sid); - rv = (SECStatus)sent; - } else if (!ss->opt.noCache) { - if (sid->cached == never_cached) { - (*ss->sec.cache)(sid); - } - rv = SECSuccess; - } - ssl_FreeSID(sid); - ss->sec.ci.sid = 0; + if (sent < 0) { + /* If send failed, it is now a bogus session-id */ + if (ss->sec.uncache) + (*ss->sec.uncache)(sid); + rv = (SECStatus)sent; + } + else if (!ss->opt.noCache) { + if (sid->cached == never_cached) { + (*ss->sec.cache)(sid); + } + rv = SECSuccess; + } + ssl_FreeSID(sid); + ss->sec.ci.sid = 0; } done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ return rv; } -/* Called from ssl2_ClientSetupSessionCypher() <- - * ssl2_HandleServerHelloMessage() - * after ssl2_BeginClientHandshake() +/* Called from ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage() + * after ssl2_BeginClientHandshake() * Acquires and releases the socket's xmitBufLock. */ static SECStatus ssl2_SendSessionKeyMessage(sslSocket *ss, int cipher, int keySize, - PRUint8 *ca, int caLen, - PRUint8 *ck, int ckLen, - PRUint8 *ek, int ekLen) + PRUint8 *ca, int caLen, + PRUint8 *ck, int ckLen, + PRUint8 *ek, int ekLen) { - PRUint8 * msg; - int sendLen; - int sent; - SECStatus rv; + PRUint8 *msg; + int sendLen; + int sent; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ sendLen = SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen + caLen; rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) - goto done; + if (rv != SECSuccess) + goto done; SSL_TRC(3, ("%d: SSL[%d]: sending client-session-key", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); msg = ss->sec.ci.sendBuf.buf; msg[0] = SSL_MT_CLIENT_MASTER_KEY; @@ -666,40 +670,40 @@ ssl2_SendSessionKeyMessage(sslSocket *ss, int cipher, int keySize, msg[7] = LSB(ekLen); msg[8] = MSB(caLen); msg[9] = LSB(caLen); - PORT_Memcpy(msg+SSL_HL_CLIENT_MASTER_KEY_HBYTES, ck, ckLen); - PORT_Memcpy(msg+SSL_HL_CLIENT_MASTER_KEY_HBYTES+ckLen, ek, ekLen); - PORT_Memcpy(msg+SSL_HL_CLIENT_MASTER_KEY_HBYTES+ckLen+ekLen, ca, caLen); + PORT_Memcpy(msg + SSL_HL_CLIENT_MASTER_KEY_HBYTES, ck, ckLen); + PORT_Memcpy(msg + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen, ek, ekLen); + PORT_Memcpy(msg + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen, ca, caLen); DUMP_MSG(29, (ss, msg, sendLen)); sent = (*ss->sec.send)(ss, msg, sendLen, 0); rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ return rv; } -/* Called from ssl2_TriggerNextMessage() <- ssl2_HandleMessage() +/* Called from ssl2_TriggerNextMessage() <- ssl2_HandleMessage() * Acquires and releases the socket's xmitBufLock. */ static SECStatus ssl2_SendCertificateRequestMessage(sslSocket *ss) { - PRUint8 * msg; - int sent; - int sendLen; - SECStatus rv; + PRUint8 *msg; + int sent; + int sendLen; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ sendLen = SSL_HL_REQUEST_CERTIFICATE_HBYTES + SSL_CHALLENGE_BYTES; rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) - goto done; + if (rv != SECSuccess) + goto done; SSL_TRC(3, ("%d: SSL[%d]: sending certificate request", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); /* Generate random challenge for client to encrypt */ PK11_GenerateRandom(ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES); @@ -707,14 +711,14 @@ ssl2_SendCertificateRequestMessage(sslSocket *ss) msg = ss->sec.ci.sendBuf.buf; msg[0] = SSL_MT_REQUEST_CERTIFICATE; msg[1] = SSL_AT_MD5_WITH_RSA_ENCRYPTION; - PORT_Memcpy(msg + SSL_HL_REQUEST_CERTIFICATE_HBYTES, + PORT_Memcpy(msg + SSL_HL_REQUEST_CERTIFICATE_HBYTES, ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES); DUMP_MSG(29, (ss, msg, sendLen)); sent = (*ss->sec.send)(ss, msg, sendLen, 0); rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ return rv; } @@ -722,23 +726,23 @@ done: * Acquires and releases the socket's xmitBufLock. */ static int -ssl2_SendCertificateResponseMessage(sslSocket *ss, SECItem *cert, +ssl2_SendCertificateResponseMessage(sslSocket *ss, SECItem *cert, SECItem *encCode) { PRUint8 *msg; int rv, sendLen; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ sendLen = SSL_HL_CLIENT_CERTIFICATE_HBYTES + encCode->len + cert->len; rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv) - goto done; + if (rv) + goto done; SSL_TRC(3, ("%d: SSL[%d]: sending certificate response", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); msg = ss->sec.ci.sendBuf.buf; msg[0] = SSL_MT_CLIENT_CERTIFICATE; @@ -749,46 +753,46 @@ ssl2_SendCertificateResponseMessage(sslSocket *ss, SECItem *cert, msg[5] = LSB(encCode->len); PORT_Memcpy(msg + SSL_HL_CLIENT_CERTIFICATE_HBYTES, cert->data, cert->len); PORT_Memcpy(msg + SSL_HL_CLIENT_CERTIFICATE_HBYTES + cert->len, - encCode->data, encCode->len); + encCode->data, encCode->len); DUMP_MSG(29, (ss, msg, sendLen)); rv = (*ss->sec.send)(ss, msg, sendLen, 0); if (rv >= 0) { - rv = SECSuccess; + rv = SECSuccess; } done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ return rv; } /******************************************************************** -** Send functions above this line must aquire & release the socket's -** xmitBufLock. +** Send functions above this line must aquire & release the socket's +** xmitBufLock. ** All the ssl2_Send functions below this line are called vis ss->sec.send -** and require that the caller hold the xmitBufLock. +** and require that the caller hold the xmitBufLock. */ /* ** Called from ssl2_SendStream, ssl2_SendBlock, but not from ssl2_SendClear. */ static SECStatus -ssl2_CalcMAC(PRUint8 * result, - sslSecurityInfo * sec, - const PRUint8 * data, - unsigned int dataLen, - unsigned int paddingLen) +ssl2_CalcMAC(PRUint8 *result, + sslSecurityInfo *sec, + const PRUint8 *data, + unsigned int dataLen, + unsigned int paddingLen) { - const PRUint8 * secret = sec->sendSecret.data; - unsigned int secretLen = sec->sendSecret.len; - unsigned long sequenceNumber = sec->sendSequence; - unsigned int nout; - PRUint8 seq[4]; - PRUint8 padding[32];/* XXX max blocksize? */ + const PRUint8 *secret = sec->sendSecret.data; + unsigned int secretLen = sec->sendSecret.len; + unsigned long sequenceNumber = sec->sendSequence; + unsigned int nout; + PRUint8 seq[4]; + PRUint8 padding[32]; /* XXX max blocksize? */ if (!sec->hash || !sec->hash->length) - return SECSuccess; + return SECSuccess; if (!sec->hashcx) - return SECFailure; + return SECFailure; /* Reset hash function */ (*sec->hash->begin)(sec->hashcx); @@ -799,10 +803,10 @@ ssl2_CalcMAC(PRUint8 * result, PORT_Memset(padding, paddingLen, paddingLen); (*sec->hash->update)(sec->hashcx, padding, paddingLen); - seq[0] = (PRUint8) (sequenceNumber >> 24); - seq[1] = (PRUint8) (sequenceNumber >> 16); - seq[2] = (PRUint8) (sequenceNumber >> 8); - seq[3] = (PRUint8) (sequenceNumber); + seq[0] = (PRUint8)(sequenceNumber >> 24); + seq[1] = (PRUint8)(sequenceNumber >> 16); + seq[2] = (PRUint8)(sequenceNumber >> 8); + seq[3] = (PRUint8)(sequenceNumber); PRINT_BUF(60, (0, "calc-mac secret:", secret, secretLen)); PRINT_BUF(60, (0, "calc-mac data:", data, dataLen)); @@ -823,76 +827,78 @@ ssl2_CalcMAC(PRUint8 * result, ** assuming the MAC is 16 bytes long and the padding is a max of 7 bytes ** long. This gives an additional 9 bytes of slop to work within. */ -#define MAX_STREAM_CYPHER_LEN 0x7fe0 -#define MAX_BLOCK_CYPHER_LEN 0x3fe0 +#define MAX_STREAM_CYPHER_LEN 0x7fe0 +#define MAX_BLOCK_CYPHER_LEN 0x3fe0 /* -** Send some data in the clear. +** Send some data in the clear. ** Package up data with the length header and send it. ** ** Return count of bytes successfully written, or negative number (failure). */ -static PRInt32 +static PRInt32 ssl2_SendClear(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags) { - PRUint8 * out; - int rv; + PRUint8 *out; + int rv; unsigned int amount; - int count = 0; + int count = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes in the clear", - SSL_GETPID(), ss->fd, len)); - PRINT_BUF(50, (ss, "clear data:", (PRUint8*) in, len)); + SSL_GETPID(), ss->fd, len)); + PRINT_BUF(50, (ss, "clear data:", (PRUint8 *)in, len)); while (len) { - amount = PR_MIN( len, MAX_STREAM_CYPHER_LEN ); - if (amount + 2 > ss->sec.writeBuf.space) { - rv = sslBuffer_Grow(&ss->sec.writeBuf, amount + 2); - if (rv != SECSuccess) { - count = rv; - break; - } - } - out = ss->sec.writeBuf.buf; + amount = PR_MIN(len, MAX_STREAM_CYPHER_LEN); + if (amount + 2 > ss->sec.writeBuf.space) { + rv = sslBuffer_Grow(&ss->sec.writeBuf, amount + 2); + if (rv != SECSuccess) { + count = rv; + break; + } + } + out = ss->sec.writeBuf.buf; - /* - ** Construct message. - */ - out[0] = 0x80 | MSB(amount); - out[1] = LSB(amount); - PORT_Memcpy(&out[2], in, amount); + /* + ** Construct message. + */ + out[0] = 0x80 | MSB(amount); + out[1] = LSB(amount); + PORT_Memcpy(&out[2], in, amount); - /* Now send the data */ - rv = ssl_DefSend(ss, out, amount + 2, flags & ~ssl_SEND_FLAG_MASK); - if (rv < 0) { - if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { - rv = 0; - } else { - /* Return short write if some data already went out... */ - if (count == 0) - count = rv; - break; - } - } + /* Now send the data */ + rv = ssl_DefSend(ss, out, amount + 2, flags & ~ssl_SEND_FLAG_MASK); + if (rv < 0) { + if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { + rv = 0; + } + else { + /* Return short write if some data already went out... */ + if (count == 0) + count = rv; + break; + } + } - if ((unsigned)rv < (amount + 2)) { - /* Short write. Save the data and return. */ - if (ssl_SaveWriteData(ss, out + rv, amount + 2 - rv) - == SECFailure) { - count = SECFailure; - } else { - count += amount; - ss->sec.sendSequence++; - } - break; - } + if ((unsigned)rv < (amount + 2)) { + /* Short write. Save the data and return. */ + if (ssl_SaveWriteData(ss, out + rv, amount + 2 - rv) == + SECFailure) { + count = SECFailure; + } + else { + count += amount; + ss->sec.sendSequence++; + } + break; + } - ss->sec.sendSequence++; - in += amount; - count += amount; - len -= amount; + ss->sec.sendSequence++; + in += amount; + count += amount; + len -= amount; } return count; @@ -903,92 +909,97 @@ ssl2_SendClear(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags) ** block size of 1. Package up the data with the length header ** and send it. */ -static PRInt32 +static PRInt32 ssl2_SendStream(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags) { - PRUint8 * out; - int rv; - int count = 0; + PRUint8 *out; + int rv; + int count = 0; - int amount; - PRUint8 macLen; - int nout; + int amount; + PRUint8 macLen; + int nout; unsigned int buflen; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes using stream cipher", - SSL_GETPID(), ss->fd, len)); - PRINT_BUF(50, (ss, "clear data:", (PRUint8*) in, len)); + SSL_GETPID(), ss->fd, len)); + PRINT_BUF(50, (ss, "clear data:", (PRUint8 *)in, len)); while (len) { - ssl_GetSpecReadLock(ss); /*************************************/ + ssl_GetSpecReadLock(ss); /*************************************/ - macLen = ss->sec.hash->length; - amount = PR_MIN( len, MAX_STREAM_CYPHER_LEN ); - buflen = amount + 2 + macLen; - if (buflen > ss->sec.writeBuf.space) { - rv = sslBuffer_Grow(&ss->sec.writeBuf, buflen); - if (rv != SECSuccess) { - goto loser; - } - } - out = ss->sec.writeBuf.buf; - nout = amount + macLen; - out[0] = 0x80 | MSB(nout); - out[1] = LSB(nout); + macLen = ss->sec.hash->length; + amount = PR_MIN(len, MAX_STREAM_CYPHER_LEN); + buflen = amount + 2 + macLen; + if (buflen > ss->sec.writeBuf.space) { + rv = sslBuffer_Grow(&ss->sec.writeBuf, buflen); + if (rv != SECSuccess) { + goto loser; + } + } + out = ss->sec.writeBuf.buf; + nout = amount + macLen; + out[0] = 0x80 | MSB(nout); + out[1] = LSB(nout); - /* Calculate MAC */ - rv = ssl2_CalcMAC(out+2, /* put MAC here */ - &ss->sec, - in, amount, /* input addr & length */ - 0); /* no padding */ - if (rv != SECSuccess) - goto loser; + /* Calculate MAC */ + rv = ssl2_CalcMAC(out + 2, /* put MAC here */ + &ss->sec, + in, amount, /* input addr & length */ + 0); /* no padding */ + if (rv != SECSuccess) + goto loser; - /* Encrypt MAC */ - rv = (*ss->sec.enc)(ss->sec.writecx, out+2, &nout, macLen, out+2, macLen); - if (rv) goto loser; + /* Encrypt MAC */ + rv = (*ss->sec.enc)(ss->sec.writecx, out + 2, &nout, macLen, out + 2, macLen); + if (rv) + goto loser; - /* Encrypt data from caller */ - rv = (*ss->sec.enc)(ss->sec.writecx, out+2+macLen, &nout, amount, in, amount); - if (rv) goto loser; + /* Encrypt data from caller */ + rv = (*ss->sec.enc)(ss->sec.writecx, out + 2 + macLen, &nout, amount, in, amount); + if (rv) + goto loser; - ssl_ReleaseSpecReadLock(ss); /*************************************/ + ssl_ReleaseSpecReadLock(ss); /*************************************/ - PRINT_BUF(50, (ss, "encrypted data:", out, buflen)); + PRINT_BUF(50, (ss, "encrypted data:", out, buflen)); - rv = ssl_DefSend(ss, out, buflen, flags & ~ssl_SEND_FLAG_MASK); - if (rv < 0) { - if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { - SSL_TRC(50, ("%d: SSL[%d]: send stream would block, " - "saving data", SSL_GETPID(), ss->fd)); - rv = 0; - } else { - SSL_TRC(10, ("%d: SSL[%d]: send stream error %d", - SSL_GETPID(), ss->fd, PORT_GetError())); - /* Return short write if some data already went out... */ - if (count == 0) - count = rv; - goto done; - } - } + rv = ssl_DefSend(ss, out, buflen, flags & ~ssl_SEND_FLAG_MASK); + if (rv < 0) { + if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { + SSL_TRC(50, ("%d: SSL[%d]: send stream would block, " + "saving data", + SSL_GETPID(), ss->fd)); + rv = 0; + } + else { + SSL_TRC(10, ("%d: SSL[%d]: send stream error %d", + SSL_GETPID(), ss->fd, PORT_GetError())); + /* Return short write if some data already went out... */ + if (count == 0) + count = rv; + goto done; + } + } - if ((unsigned)rv < buflen) { - /* Short write. Save the data and return. */ - if (ssl_SaveWriteData(ss, out + rv, buflen - rv) == SECFailure) { - count = SECFailure; - } else { - count += amount; - ss->sec.sendSequence++; - } - goto done; - } + if ((unsigned)rv < buflen) { + /* Short write. Save the data and return. */ + if (ssl_SaveWriteData(ss, out + rv, buflen - rv) == SECFailure) { + count = SECFailure; + } + else { + count += amount; + ss->sec.sendSequence++; + } + goto done; + } - ss->sec.sendSequence++; - in += amount; - count += amount; - len -= amount; + ss->sec.sendSequence++; + in += amount; + count += amount; + len -= amount; } done: @@ -1007,116 +1018,120 @@ loser: static PRInt32 ssl2_SendBlock(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags) { - PRUint8 * out; /* begining of output buffer. */ - PRUint8 * op; /* next output byte goes here. */ - int rv; /* value from funcs we called. */ - int count = 0; /* this function's return value. */ + PRUint8 *out; /* begining of output buffer. */ + PRUint8 *op; /* next output byte goes here. */ + int rv; /* value from funcs we called. */ + int count = 0; /* this function's return value. */ - unsigned int hlen; /* output record hdr len, 2 or 3 */ - unsigned int macLen; /* MAC is this many bytes long. */ - int amount; /* of plaintext to go in record. */ - unsigned int padding; /* add this many padding byte. */ - int nout; /* ciphertext size after header. */ - unsigned int buflen; /* size of generated record. */ + unsigned int hlen; /* output record hdr len, 2 or 3 */ + unsigned int macLen; /* MAC is this many bytes long. */ + int amount; /* of plaintext to go in record. */ + unsigned int padding; /* add this many padding byte. */ + int nout; /* ciphertext size after header. */ + unsigned int buflen; /* size of generated record. */ - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes using block cipher", - SSL_GETPID(), ss->fd, len)); + SSL_GETPID(), ss->fd, len)); PRINT_BUF(50, (ss, "clear data:", in, len)); while (len) { - ssl_GetSpecReadLock(ss); /*************************************/ + ssl_GetSpecReadLock(ss); /*************************************/ - macLen = ss->sec.hash->length; - /* Figure out how much to send, including mac and padding */ - amount = PR_MIN( len, MAX_BLOCK_CYPHER_LEN ); - nout = amount + macLen; - padding = nout & (ss->sec.blockSize - 1); - if (padding) { - hlen = 3; - padding = ss->sec.blockSize - padding; - nout += padding; - } else { - hlen = 2; - } - buflen = hlen + nout; - if (buflen > ss->sec.writeBuf.space) { - rv = sslBuffer_Grow(&ss->sec.writeBuf, buflen); - if (rv != SECSuccess) { - goto loser; - } - } - out = ss->sec.writeBuf.buf; + macLen = ss->sec.hash->length; + /* Figure out how much to send, including mac and padding */ + amount = PR_MIN(len, MAX_BLOCK_CYPHER_LEN); + nout = amount + macLen; + padding = nout & (ss->sec.blockSize - 1); + if (padding) { + hlen = 3; + padding = ss->sec.blockSize - padding; + nout += padding; + } + else { + hlen = 2; + } + buflen = hlen + nout; + if (buflen > ss->sec.writeBuf.space) { + rv = sslBuffer_Grow(&ss->sec.writeBuf, buflen); + if (rv != SECSuccess) { + goto loser; + } + } + out = ss->sec.writeBuf.buf; - /* Construct header */ - op = out; - if (padding) { - *op++ = MSB(nout); - *op++ = LSB(nout); - *op++ = padding; - } else { - *op++ = 0x80 | MSB(nout); - *op++ = LSB(nout); - } + /* Construct header */ + op = out; + if (padding) { + *op++ = MSB(nout); + *op++ = LSB(nout); + *op++ = padding; + } + else { + *op++ = 0x80 | MSB(nout); + *op++ = LSB(nout); + } - /* Calculate MAC */ - rv = ssl2_CalcMAC(op, /* MAC goes here. */ - &ss->sec, - in, amount, /* intput addr, len */ - padding); - if (rv != SECSuccess) - goto loser; - op += macLen; + /* Calculate MAC */ + rv = ssl2_CalcMAC(op, /* MAC goes here. */ + &ss->sec, + in, amount, /* intput addr, len */ + padding); + if (rv != SECSuccess) + goto loser; + op += macLen; - /* Copy in the input data */ - /* XXX could eliminate the copy by folding it into the encryption */ - PORT_Memcpy(op, in, amount); - op += amount; - if (padding) { - PORT_Memset(op, padding, padding); - op += padding; - } + /* Copy in the input data */ + /* XXX could eliminate the copy by folding it into the encryption */ + PORT_Memcpy(op, in, amount); + op += amount; + if (padding) { + PORT_Memset(op, padding, padding); + op += padding; + } - /* Encrypt result */ - rv = (*ss->sec.enc)(ss->sec.writecx, out+hlen, &nout, buflen-hlen, - out+hlen, op - (out + hlen)); - if (rv) - goto loser; + /* Encrypt result */ + rv = (*ss->sec.enc)(ss->sec.writecx, out + hlen, &nout, buflen - hlen, + out + hlen, op - (out + hlen)); + if (rv) + goto loser; - ssl_ReleaseSpecReadLock(ss); /*************************************/ + ssl_ReleaseSpecReadLock(ss); /*************************************/ - PRINT_BUF(50, (ss, "final xmit data:", out, op - out)); + PRINT_BUF(50, (ss, "final xmit data:", out, op - out)); - rv = ssl_DefSend(ss, out, op - out, flags & ~ssl_SEND_FLAG_MASK); - if (rv < 0) { - if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { - rv = 0; - } else { - SSL_TRC(10, ("%d: SSL[%d]: send block error %d", - SSL_GETPID(), ss->fd, PORT_GetError())); - /* Return short write if some data already went out... */ - if (count == 0) - count = rv; - goto done; - } - } + rv = ssl_DefSend(ss, out, op - out, flags & ~ssl_SEND_FLAG_MASK); + if (rv < 0) { + if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { + rv = 0; + } + else { + SSL_TRC(10, ("%d: SSL[%d]: send block error %d", + SSL_GETPID(), ss->fd, PORT_GetError())); + /* Return short write if some data already went out... */ + if (count == 0) + count = rv; + goto done; + } + } - if (rv < (op - out)) { - /* Short write. Save the data and return. */ - if (ssl_SaveWriteData(ss, out + rv, op - out - rv) == SECFailure) { - count = SECFailure; - } else { - count += amount; - ss->sec.sendSequence++; - } - goto done; - } + if (rv < (op - out)) { + /* Short write. Save the data and return. */ + if (ssl_SaveWriteData(ss, out + rv, op - out - rv) == SECFailure) { + count = SECFailure; + } + else { + count += amount; + ss->sec.sendSequence++; + } + goto done; + } - ss->sec.sendSequence++; - in += amount; - count += amount; - len -= amount; + ss->sec.sendSequence++; + in += amount; + count += amount; + len -= amount; } done: @@ -1131,7 +1146,7 @@ loser: ** Called from: ssl2_HandleServerHelloMessage, ** ssl2_HandleClientSessionKeyMessage, ** ssl2_HandleClientHelloMessage, -** +** */ static void ssl2_UseEncryptedSendFunc(sslSocket *ss) @@ -1154,12 +1169,12 @@ ssl2_UseClearSendFunc(sslSocket *ss) } /************************************************************************ -** END of Send functions. * +** END of Send functions. * *************************************************************************/ /*********************************************************************** - * For SSL3, this gathers in and handles records/messages until either - * the handshake is complete or application data is available. + * For SSL3, this gathers in and handles records/messages until either + * the handshake is complete or application data is available. * * For SSL2, this gathers in only the next SSLV2 record. * @@ -1169,37 +1184,37 @@ ssl2_UseClearSendFunc(sslSocket *ss) * * returns SECSuccess for success. * returns SECWouldBlock when that value is returned by ssl2_GatherRecord() or - * ssl3_GatherCompleteHandshake(). + * ssl3_GatherCompleteHandshake(). * returns SECFailure on all other errors. * - * The gather functions called by ssl_GatherRecord1stHandshake are expected - * to return values interpreted as follows: + * The gather functions called by ssl_GatherRecord1stHandshake are expected + * to return values interpreted as follows: * 1 : the function completed without error. * 0 : the function read EOF. * -1 : read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error. - * -2 : the function wants ssl_GatherRecord1stHandshake to be called again - * immediately, by ssl_Do1stHandshake. + * -2 : the function wants ssl_GatherRecord1stHandshake to be called again + * immediately, by ssl_Do1stHandshake. * * This code is similar to, and easily confused with, DoRecv() in sslsecur.c * - * This function is called from ssl_Do1stHandshake(). + * This function is called from ssl_Do1stHandshake(). * The following functions put ssl_GatherRecord1stHandshake into ss->handshake: - * ssl2_HandleMessage - * ssl2_HandleVerifyMessage - * ssl2_HandleServerHelloMessage - * ssl2_BeginClientHandshake - * ssl2_HandleClientSessionKeyMessage - * ssl3_RestartHandshakeAfterCertReq - * ssl3_RestartHandshakeAfterServerCert - * ssl2_HandleClientHelloMessage - * ssl2_BeginServerHandshake + * ssl2_HandleMessage + * ssl2_HandleVerifyMessage + * ssl2_HandleServerHelloMessage + * ssl2_BeginClientHandshake + * ssl2_HandleClientSessionKeyMessage + * ssl3_RestartHandshakeAfterCertReq + * ssl3_RestartHandshakeAfterServerCert + * ssl2_HandleClientHelloMessage + * ssl2_BeginServerHandshake */ SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss) { int rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); ssl_GetRecvBufLock(ss); @@ -1209,35 +1224,36 @@ ssl_GatherRecord1stHandshake(sslSocket *ss) * SSL3 version. */ if ((ss->version >= SSL_LIBRARY_VERSION_3_0) || IS_DTLS(ss)) { - /* Wait for handshake to complete, or application data to arrive. */ - rv = ssl3_GatherCompleteHandshake(ss, 0); - } else { - /* See if we have a complete record */ - rv = ssl2_GatherRecord(ss, 0); + /* Wait for handshake to complete, or application data to arrive. */ + rv = ssl3_GatherCompleteHandshake(ss, 0); + } + else { + /* See if we have a complete record */ + rv = ssl2_GatherRecord(ss, 0); } SSL_TRC(10, ("%d: SSL[%d]: handshake gathering, rv=%d", - SSL_GETPID(), ss->fd, rv)); + SSL_GETPID(), ss->fd, rv)); ssl_ReleaseRecvBufLock(ss); if (rv <= 0) { - if (rv == SECWouldBlock) { - /* Progress is blocked waiting for callback completion. */ - SSL_TRC(10, ("%d: SSL[%d]: handshake blocked (need %d)", - SSL_GETPID(), ss->fd, ss->gs.remainder)); - return SECWouldBlock; - } - if (rv == 0) { - /* EOF. Loser */ - PORT_SetError(PR_END_OF_FILE_ERROR); - } - return SECFailure; /* rv is < 0 here. */ + if (rv == SECWouldBlock) { + /* Progress is blocked waiting for callback completion. */ + SSL_TRC(10, ("%d: SSL[%d]: handshake blocked (need %d)", + SSL_GETPID(), ss->fd, ss->gs.remainder)); + return SECWouldBlock; + } + if (rv == 0) { + /* EOF. Loser */ + PORT_SetError(PR_END_OF_FILE_ERROR); + } + return SECFailure; /* rv is < 0 here. */ } SSL_TRC(10, ("%d: SSL[%d]: got handshake record of %d bytes", - SSL_GETPID(), ss->fd, ss->gs.recordLen)); + SSL_GETPID(), ss->fd, ss->gs.recordLen)); - ss->handshake = 0; /* makes ssl_Do1stHandshake call ss->nextHandshake.*/ + ss->handshake = 0; /* makes ssl_Do1stHandshake call ss->nextHandshake.*/ return SECSuccess; } @@ -1247,18 +1263,18 @@ ssl_GatherRecord1stHandshake(sslSocket *ss) * ssl2_ClientSetupSessionCypher() */ static SECStatus -ssl2_FillInSID(sslSessionID * sid, - int cipher, - PRUint8 *keyData, - int keyLen, - PRUint8 *ca, - int caLen, - int keyBits, - int secretKeyBits, - SSLSignType authAlgorithm, - PRUint32 authKeyBits, - SSLKEAType keaType, - PRUint32 keaKeyBits) +ssl2_FillInSID(sslSessionID *sid, + int cipher, + PRUint8 *keyData, + int keyLen, + PRUint8 *ca, + int caLen, + int keyBits, + int secretKeyBits, + SSLSignType authAlgorithm, + PRUint32 authKeyBits, + SSLKEAType keaType, + PRUint32 keaKeyBits) { PORT_Assert(sid->references == 1); PORT_Assert(sid->cached == never_cached); @@ -1268,28 +1284,28 @@ ssl2_FillInSID(sslSessionID * sid, sid->version = SSL_LIBRARY_VERSION_2; sid->u.ssl2.cipherType = cipher; - sid->u.ssl2.masterKey.data = (PRUint8*) PORT_Alloc(keyLen); + sid->u.ssl2.masterKey.data = (PRUint8 *)PORT_Alloc(keyLen); if (!sid->u.ssl2.masterKey.data) { - return SECFailure; + return SECFailure; } PORT_Memcpy(sid->u.ssl2.masterKey.data, keyData, keyLen); sid->u.ssl2.masterKey.len = keyLen; - sid->u.ssl2.keyBits = keyBits; + sid->u.ssl2.keyBits = keyBits; sid->u.ssl2.secretKeyBits = secretKeyBits; - sid->authAlgorithm = authAlgorithm; - sid->authKeyBits = authKeyBits; - sid->keaType = keaType; - sid->keaKeyBits = keaKeyBits; + sid->authAlgorithm = authAlgorithm; + sid->authKeyBits = authKeyBits; + sid->keaType = keaType; + sid->keaKeyBits = keaKeyBits; sid->lastAccessTime = sid->creationTime = ssl_Time(); sid->expirationTime = sid->creationTime + ssl_sid_timeout; if (caLen) { - sid->u.ssl2.cipherArg.data = (PRUint8*) PORT_Alloc(caLen); - if (!sid->u.ssl2.cipherArg.data) { - return SECFailure; - } - sid->u.ssl2.cipherArg.len = caLen; - PORT_Memcpy(sid->u.ssl2.cipherArg.data, ca, caLen); + sid->u.ssl2.cipherArg.data = (PRUint8 *)PORT_Alloc(caLen); + if (!sid->u.ssl2.cipherArg.data) { + return SECFailure; + } + sid->u.ssl2.cipherArg.len = caLen; + PORT_Memcpy(sid->u.ssl2.cipherArg.data, ca, caLen); } return SECSuccess; } @@ -1301,68 +1317,68 @@ ssl2_FillInSID(sslSessionID * sid, ** Called from ssl2_CreateSessionCypher() <- */ static SECStatus -ssl2_ProduceKeys(sslSocket * ss, - SECItem * readKey, - SECItem * writeKey, - SECItem * masterKey, - PRUint8 * challenge, - PRUint8 * nonce, - int cipherType) +ssl2_ProduceKeys(sslSocket *ss, + SECItem *readKey, + SECItem *writeKey, + SECItem *masterKey, + PRUint8 *challenge, + PRUint8 *nonce, + int cipherType) { - PK11Context * cx = 0; - unsigned nkm = 0; /* number of hashes to generate key mat. */ - unsigned nkd = 0; /* size of readKey and writeKey. */ - unsigned part; - unsigned i; - unsigned off; - SECStatus rv; - PRUint8 countChar; - PRUint8 km[3*16]; /* buffer for key material. */ + PK11Context *cx = 0; + unsigned nkm = 0; /* number of hashes to generate key mat. */ + unsigned nkd = 0; /* size of readKey and writeKey. */ + unsigned part; + unsigned i; + unsigned off; + SECStatus rv; + PRUint8 countChar; + PRUint8 km[3 * 16]; /* buffer for key material. */ readKey->data = 0; writeKey->data = 0; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); rv = SECSuccess; cx = PK11_CreateDigestContext(SEC_OID_MD5); if (cx == NULL) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - return SECFailure; + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + return SECFailure; } nkm = ssl_Specs[cipherType].nkm; nkd = ssl_Specs[cipherType].nkd; - readKey->data = (PRUint8*) PORT_Alloc(nkd); - if (!readKey->data) - goto loser; + readKey->data = (PRUint8 *)PORT_Alloc(nkd); + if (!readKey->data) + goto loser; readKey->len = nkd; - writeKey->data = (PRUint8*) PORT_Alloc(nkd); - if (!writeKey->data) - goto loser; + writeKey->data = (PRUint8 *)PORT_Alloc(nkd); + if (!writeKey->data) + goto loser; writeKey->len = nkd; /* Produce key material */ countChar = '0'; for (i = 0, off = 0; i < nkm; i++, off += 16) { - rv = PK11_DigestBegin(cx); - rv |= PK11_DigestOp(cx, masterKey->data, masterKey->len); - rv |= PK11_DigestOp(cx, &countChar, 1); - rv |= PK11_DigestOp(cx, challenge, SSL_CHALLENGE_BYTES); - rv |= PK11_DigestOp(cx, nonce, SSL_CONNECTIONID_BYTES); - rv |= PK11_DigestFinal(cx, km+off, &part, MD5_LENGTH); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - rv = SECFailure; - goto loser; - } - countChar++; + rv = PK11_DigestBegin(cx); + rv |= PK11_DigestOp(cx, masterKey->data, masterKey->len); + rv |= PK11_DigestOp(cx, &countChar, 1); + rv |= PK11_DigestOp(cx, challenge, SSL_CHALLENGE_BYTES); + rv |= PK11_DigestOp(cx, nonce, SSL_CONNECTIONID_BYTES); + rv |= PK11_DigestFinal(cx, km + off, &part, MD5_LENGTH); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + rv = SECFailure; + goto loser; + } + countChar++; } /* Produce keys */ - PORT_Memcpy(readKey->data, km, nkd); + PORT_Memcpy(readKey->data, km, nkd); PORT_Memcpy(writeKey->data, km + nkd, nkd); loser: @@ -1370,62 +1386,62 @@ loser: return rv; } -/* Called from ssl2_ServerSetupSessionCypher() +/* Called from ssl2_ServerSetupSessionCypher() ** <- ssl2_HandleClientSessionKeyMessage() ** <- ssl2_HandleClientHelloMessage() -** and from ssl2_ClientSetupSessionCypher() +** and from ssl2_ClientSetupSessionCypher() ** <- ssl2_HandleServerHelloMessage() */ static SECStatus ssl2_CreateSessionCypher(sslSocket *ss, sslSessionID *sid, PRBool isClient) { - SECItem * rk = NULL; - SECItem * wk = NULL; - SECItem * param; - SECStatus rv; - int cipherType = sid->u.ssl2.cipherType; - PK11SlotInfo * slot = NULL; + SECItem *rk = NULL; + SECItem *wk = NULL; + SECItem *param; + SECStatus rv; + int cipherType = sid->u.ssl2.cipherType; + PK11SlotInfo *slot = NULL; CK_MECHANISM_TYPE mechanism; - SECItem readKey; - SECItem writeKey; + SECItem readKey; + SECItem writeKey; void *readcx = 0; void *writecx = 0; readKey.data = 0; writeKey.data = 0; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); if (ss->sec.ci.sid == 0) - goto sec_loser; /* don't crash if asserts are off */ + goto sec_loser; /* don't crash if asserts are off */ /* Trying to cut down on all these switch statements that should be tables. - * So, test cipherType once, here, and then use tables below. + * So, test cipherType once, here, and then use tables below. */ switch (cipherType) { - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC4_128_WITH_MD5: - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_WITH_MD5: - case SSL_CK_DES_64_CBC_WITH_MD5: - case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: - break; + case SSL_CK_RC4_128_EXPORT40_WITH_MD5: + case SSL_CK_RC4_128_WITH_MD5: + case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: + case SSL_CK_RC2_128_CBC_WITH_MD5: + case SSL_CK_DES_64_CBC_WITH_MD5: + case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: + break; - default: - SSL_DBG(("%d: SSL[%d]: ssl2_CreateSessionCypher: unknown cipher=%d", - SSL_GETPID(), ss->fd, cipherType)); - PORT_SetError(isClient ? SSL_ERROR_BAD_SERVER : SSL_ERROR_BAD_CLIENT); - goto sec_loser; + default: + SSL_DBG(("%d: SSL[%d]: ssl2_CreateSessionCypher: unknown cipher=%d", + SSL_GETPID(), ss->fd, cipherType)); + PORT_SetError(isClient ? SSL_ERROR_BAD_SERVER : SSL_ERROR_BAD_CLIENT); + goto sec_loser; } - - rk = isClient ? &readKey : &writeKey; + + rk = isClient ? &readKey : &writeKey; wk = isClient ? &writeKey : &readKey; /* Produce the keys for this session */ rv = ssl2_ProduceKeys(ss, &readKey, &writeKey, &sid->u.ssl2.masterKey, - ss->sec.ci.clientChallenge, ss->sec.ci.connectionID, - cipherType); - if (rv != SECSuccess) - goto loser; + ss->sec.ci.clientChallenge, ss->sec.ci.connectionID, + cipherType); + if (rv != SECSuccess) + goto loser; PRINT_BUF(7, (ss, "Session read-key: ", rk->data, rk->len)); PRINT_BUF(7, (ss, "Session write-key: ", wk->data, wk->len)); @@ -1435,73 +1451,75 @@ ssl2_CreateSessionCypher(sslSocket *ss, sslSessionID *sid, PRBool isClient) /* Setup the MAC */ rv = ssl2_CreateMAC(&ss->sec, rk, wk, cipherType); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; /* First create the session key object */ SSL_TRC(3, ("%d: SSL[%d]: using %s", SSL_GETPID(), ss->fd, - ssl_cipherName[cipherType])); + ssl_cipherName[cipherType])); - - mechanism = ssl_Specs[cipherType].mechanism; + mechanism = ssl_Specs[cipherType].mechanism; /* set destructer before we call loser... */ - ss->sec.destroy = (void (*)(void*, PRBool)) PK11_DestroyContext; + ss->sec.destroy = (void (*)(void *, PRBool))PK11_DestroyContext; slot = PK11_GetBestSlot(mechanism, ss->pkcs11PinArg); if (slot == NULL) - goto loser; + goto loser; param = PK11_ParamFromIV(mechanism, &sid->u.ssl2.cipherArg); if (param == NULL) - goto loser; + goto loser; readcx = PK11_CreateContextByRawKey(slot, mechanism, PK11_OriginUnwrap, - CKA_DECRYPT, rk, param, - ss->pkcs11PinArg); + CKA_DECRYPT, rk, param, + ss->pkcs11PinArg); SECITEM_FreeItem(param, PR_TRUE); if (readcx == NULL) - goto loser; + goto loser; /* build the client context */ param = PK11_ParamFromIV(mechanism, &sid->u.ssl2.cipherArg); if (param == NULL) - goto loser; + goto loser; writecx = PK11_CreateContextByRawKey(slot, mechanism, PK11_OriginUnwrap, - CKA_ENCRYPT, wk, param, - ss->pkcs11PinArg); - SECITEM_FreeItem(param,PR_TRUE); + CKA_ENCRYPT, wk, param, + ss->pkcs11PinArg); + SECITEM_FreeItem(param, PR_TRUE); if (writecx == NULL) - goto loser; + goto loser; PK11_FreeSlot(slot); rv = SECSuccess; - ss->sec.enc = (SSLCipher) PK11_CipherOp; - ss->sec.dec = (SSLCipher) PK11_CipherOp; - ss->sec.readcx = (void *) readcx; - ss->sec.writecx = (void *) writecx; - ss->sec.blockSize = ssl_Specs[cipherType].blockSize; - ss->sec.blockShift = ssl_Specs[cipherType].blockShift; - ss->sec.cipherType = sid->u.ssl2.cipherType; - ss->sec.keyBits = sid->u.ssl2.keyBits; + ss->sec.enc = (SSLCipher)PK11_CipherOp; + ss->sec.dec = (SSLCipher)PK11_CipherOp; + ss->sec.readcx = (void *)readcx; + ss->sec.writecx = (void *)writecx; + ss->sec.blockSize = ssl_Specs[cipherType].blockSize; + ss->sec.blockShift = ssl_Specs[cipherType].blockShift; + ss->sec.cipherType = sid->u.ssl2.cipherType; + ss->sec.keyBits = sid->u.ssl2.keyBits; ss->sec.secretKeyBits = sid->u.ssl2.secretKeyBits; goto done; - loser: +loser: if (ss->sec.destroy) { - if (readcx) (*ss->sec.destroy)(readcx, PR_TRUE); - if (writecx) (*ss->sec.destroy)(writecx, PR_TRUE); + if (readcx) + (*ss->sec.destroy)(readcx, PR_TRUE); + if (writecx) + (*ss->sec.destroy)(writecx, PR_TRUE); } ss->sec.destroy = NULL; - if (slot) PK11_FreeSlot(slot); + if (slot) + PK11_FreeSlot(slot); - sec_loser: +sec_loser: rv = SECFailure; - done: +done: if (rk) { - SECITEM_ZfreeItem(rk, PR_FALSE); + SECITEM_ZfreeItem(rk, PR_FALSE); } if (wk) { - SECITEM_ZfreeItem(wk, PR_FALSE); + SECITEM_ZfreeItem(wk, PR_FALSE); } return rv; } @@ -1509,15 +1527,15 @@ ssl2_CreateSessionCypher(sslSocket *ss, sslSessionID *sid, PRBool isClient) /* ** Setup the server ciphers given information from a CLIENT-MASTER-KEY ** message. -** "ss" pointer to the ssl-socket object -** "cipher" the cipher type to use -** "keyBits" the size of the final cipher key -** "ck" the clear-key data -** "ckLen" the number of bytes of clear-key data -** "ek" the encrypted-key data -** "ekLen" the number of bytes of encrypted-key data -** "ca" the cipher-arg data -** "caLen" the number of bytes of cipher-arg data +** "ss" pointer to the ssl-socket object +** "cipher" the cipher type to use +** "keyBits" the size of the final cipher key +** "ck" the clear-key data +** "ckLen" the number of bytes of clear-key data +** "ek" the encrypted-key data +** "ekLen" the number of bytes of encrypted-key data +** "ca" the cipher-arg data +** "caLen" the number of bytes of cipher-arg data ** ** The MASTER-KEY is constructed by first decrypting the encrypted-key ** data. This produces the SECRET-KEY-DATA. The MASTER-KEY is composed by @@ -1530,171 +1548,171 @@ ssl2_CreateSessionCypher(sslSocket *ss, sslSessionID *sid, PRBool isClient) */ static SECStatus ssl2_ServerSetupSessionCypher(sslSocket *ss, int cipher, unsigned int keyBits, - PRUint8 *ck, unsigned int ckLen, - PRUint8 *ek, unsigned int ekLen, - PRUint8 *ca, unsigned int caLen) + PRUint8 *ck, unsigned int ckLen, + PRUint8 *ek, unsigned int ekLen, + PRUint8 *ca, unsigned int caLen) { - PRUint8 * dk = NULL; /* decrypted master key */ - sslSessionID * sid; - sslServerCerts * sc = ss->serverCerts + kt_rsa; - PRUint8 * kbuf = 0; /* buffer for RSA decrypted data. */ - unsigned int ddLen; /* length of RSA decrypted data in kbuf */ - unsigned int keySize; - unsigned int dkLen; /* decrypted key length in bytes */ + PRUint8 *dk = NULL; /* decrypted master key */ + sslSessionID *sid; + sslServerCerts *sc = ss->serverCerts + kt_rsa; + PRUint8 *kbuf = 0; /* buffer for RSA decrypted data. */ + unsigned int ddLen; /* length of RSA decrypted data in kbuf */ + unsigned int keySize; + unsigned int dkLen; /* decrypted key length in bytes */ int modulusLen; - SECStatus rv; - PRUint16 allowed; /* cipher kinds enabled and allowed by policy */ - PRUint8 mkbuf[SSL_MAX_MASTER_KEY_BYTES]; + SECStatus rv; + PRUint16 allowed; /* cipher kinds enabled and allowed by policy */ + PRUint8 mkbuf[SSL_MAX_MASTER_KEY_BYTES]; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); PORT_Assert((sc->SERVERKEY != 0)); PORT_Assert((ss->sec.ci.sid != 0)); sid = ss->sec.ci.sid; /* Trying to cut down on all these switch statements that should be tables. - * So, test cipherType once, here, and then use tables below. + * So, test cipherType once, here, and then use tables below. */ switch (cipher) { - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC4_128_WITH_MD5: - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_WITH_MD5: - case SSL_CK_DES_64_CBC_WITH_MD5: - case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: - break; + case SSL_CK_RC4_128_EXPORT40_WITH_MD5: + case SSL_CK_RC4_128_WITH_MD5: + case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: + case SSL_CK_RC2_128_CBC_WITH_MD5: + case SSL_CK_DES_64_CBC_WITH_MD5: + case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: + break; - default: - SSL_DBG(("%d: SSL[%d]: ssl2_ServerSetupSessionCypher: unknown cipher=%d", - SSL_GETPID(), ss->fd, cipher)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; + default: + SSL_DBG(("%d: SSL[%d]: ssl2_ServerSetupSessionCypher: unknown cipher=%d", + SSL_GETPID(), ss->fd, cipher)); + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto loser; } allowed = ss->allowedByPolicy & ss->chosenPreference & SSL_CB_IMPLEMENTED; if (!(allowed & (1 << cipher))) { - /* client chose a kind we don't allow! */ - SSL_DBG(("%d: SSL[%d]: disallowed cipher=%d", - SSL_GETPID(), ss->fd, cipher)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; + /* client chose a kind we don't allow! */ + SSL_DBG(("%d: SSL[%d]: disallowed cipher=%d", + SSL_GETPID(), ss->fd, cipher)); + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto loser; } keySize = ssl_Specs[cipher].keyLen; if (keyBits != keySize * BPB) { - SSL_DBG(("%d: SSL[%d]: invalid master secret key length=%d (bits)!", - SSL_GETPID(), ss->fd, keyBits)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; + SSL_DBG(("%d: SSL[%d]: invalid master secret key length=%d (bits)!", + SSL_GETPID(), ss->fd, keyBits)); + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto loser; } if (ckLen != ssl_Specs[cipher].pubLen) { - SSL_DBG(("%d: SSL[%d]: invalid clear key length, ckLen=%d (bytes)!", - SSL_GETPID(), ss->fd, ckLen)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; + SSL_DBG(("%d: SSL[%d]: invalid clear key length, ckLen=%d (bytes)!", + SSL_GETPID(), ss->fd, ckLen)); + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto loser; } if (caLen != ssl_Specs[cipher].ivLen) { - SSL_DBG(("%d: SSL[%d]: invalid key args length, caLen=%d (bytes)!", - SSL_GETPID(), ss->fd, caLen)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; + SSL_DBG(("%d: SSL[%d]: invalid key args length, caLen=%d (bytes)!", + SSL_GETPID(), ss->fd, caLen)); + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto loser; } modulusLen = PK11_GetPrivateModulusLen(sc->SERVERKEY); if (modulusLen < 0) { - /* XXX If the key is bad, then PK11_PubDecryptRaw will fail below. */ - modulusLen = ekLen; + /* XXX If the key is bad, then PK11_PubDecryptRaw will fail below. */ + modulusLen = ekLen; } if (ekLen > (unsigned int)modulusLen || ekLen + ckLen < keySize) { - SSL_DBG(("%d: SSL[%d]: invalid encrypted key length, ekLen=%d (bytes)!", - SSL_GETPID(), ss->fd, ekLen)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; + SSL_DBG(("%d: SSL[%d]: invalid encrypted key length, ekLen=%d (bytes)!", + SSL_GETPID(), ss->fd, ekLen)); + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto loser; } /* allocate the buffer to hold the decrypted portion of the key. */ - kbuf = (PRUint8*)PORT_Alloc(modulusLen); + kbuf = (PRUint8 *)PORT_Alloc(modulusLen); if (!kbuf) { - goto loser; + goto loser; } dkLen = keySize - ckLen; - dk = kbuf + modulusLen - dkLen; + dk = kbuf + modulusLen - dkLen; - /* Decrypt encrypted half of the key. + /* Decrypt encrypted half of the key. ** NOTE: PK11_PubDecryptRaw will barf on a non-RSA key. This is ** desired behavior here. */ rv = PK11_PubDecryptRaw(sc->SERVERKEY, kbuf, &ddLen, modulusLen, ek, ekLen); - if (rv != SECSuccess) - goto hide_loser; + if (rv != SECSuccess) + goto hide_loser; /* Is the length of the decrypted data (ddLen) the expected value? */ - if (modulusLen != ddLen) - goto hide_loser; + if (modulusLen != ddLen) + goto hide_loser; /* Cheaply verify that PKCS#1 was used to format the encryption block */ if ((kbuf[0] != 0x00) || (kbuf[1] != 0x02) || (dk[-1] != 0x00)) { - SSL_DBG(("%d: SSL[%d]: strange encryption block", - SSL_GETPID(), ss->fd)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto hide_loser; + SSL_DBG(("%d: SSL[%d]: strange encryption block", + SSL_GETPID(), ss->fd)); + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto hide_loser; } /* Make sure we're not subject to a version rollback attack. */ if (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - static const PRUint8 threes[8] = { 0x03, 0x03, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03 }; - - if (PORT_Memcmp(dk - 8 - 1, threes, 8) == 0) { - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto hide_loser; - } + static const PRUint8 threes[8] = { 0x03, 0x03, 0x03, 0x03, + 0x03, 0x03, 0x03, 0x03 }; + + if (PORT_Memcmp(dk - 8 - 1, threes, 8) == 0) { + PORT_SetError(SSL_ERROR_BAD_CLIENT); + goto hide_loser; + } } if (0) { -hide_loser: - /* Defense against the Bleichenbacher attack. - * Provide the client with NO CLUES that the decrypted master key - * was erroneous. Don't send any error messages. - * Instead, Generate a completely bogus master key . - */ - PK11_GenerateRandom(dk, dkLen); + hide_loser: + /* Defense against the Bleichenbacher attack. + * Provide the client with NO CLUES that the decrypted master key + * was erroneous. Don't send any error messages. + * Instead, Generate a completely bogus master key . + */ + PK11_GenerateRandom(dk, dkLen); } /* ** Construct master key out of the pieces. */ if (ckLen) { - PORT_Memcpy(mkbuf, ck, ckLen); + PORT_Memcpy(mkbuf, ck, ckLen); } PORT_Memcpy(mkbuf + ckLen, dk, dkLen); /* Fill in session-id */ rv = ssl2_FillInSID(sid, cipher, mkbuf, keySize, ca, caLen, - keyBits, keyBits - (ckLen<<3), - ss->sec.authAlgorithm, ss->sec.authKeyBits, - ss->sec.keaType, ss->sec.keaKeyBits); + keyBits, keyBits - (ckLen << 3), + ss->sec.authAlgorithm, ss->sec.authKeyBits, + ss->sec.keaType, ss->sec.keaKeyBits); if (rv != SECSuccess) { - goto loser; + goto loser; } /* Create session ciphers */ rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE); if (rv != SECSuccess) { - goto loser; + goto loser; } SSL_TRC(1, ("%d: SSL[%d]: server, using %s cipher, clear=%d total=%d", - SSL_GETPID(), ss->fd, ssl_cipherName[cipher], - ckLen<<3, keySize<<3)); + SSL_GETPID(), ss->fd, ssl_cipherName[cipher], + ckLen << 3, keySize << 3)); rv = SECSuccess; goto done; - loser: +loser: rv = SECFailure; - done: +done: PORT_Free(kbuf); return rv; } @@ -1705,54 +1723,54 @@ hide_loser: ** Rewrite the incoming cipher specs, comparing to list of specs we support, ** (ss->cipherSpecs) and eliminating anything we don't support ** -* Note: Our list may contain SSL v3 ciphers. -* We MUST NOT match on any of those. +* Note: Our list may contain SSL v3 ciphers. +* We MUST NOT match on any of those. * Fortunately, this is easy to detect because SSLv3 ciphers have zero * in the first byte, and none of the SSLv2 ciphers do. * * Called from ssl2_HandleClientHelloMessage(). -* Returns the number of bytes of "qualified cipher specs", +* Returns the number of bytes of "qualified cipher specs", * which is typically a multiple of 3, but will be zero if there are none. */ static int -ssl2_QualifyCypherSpecs(sslSocket *ss, - PRUint8 * cs, /* cipher specs in client hello msg. */ - int csLen) +ssl2_QualifyCypherSpecs(sslSocket *ss, + PRUint8 *cs, /* cipher specs in client hello msg. */ + int csLen) { - PRUint8 * ms; - PRUint8 * hs; - PRUint8 * qs; - int mc; - int hc; - PRUint8 qualifiedSpecs[ssl2_NUM_SUITES_IMPLEMENTED * 3]; + PRUint8 *ms; + PRUint8 *hs; + PRUint8 *qs; + int mc; + int hc; + PRUint8 qualifiedSpecs[ssl2_NUM_SUITES_IMPLEMENTED * 3]; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); if (!ss->cipherSpecs) { - SECStatus rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess || !ss->cipherSpecs) - return 0; + SECStatus rv = ssl2_ConstructCipherSpecs(ss); + if (rv != SECSuccess || !ss->cipherSpecs) + return 0; } PRINT_BUF(10, (ss, "specs from client:", cs, csLen)); qs = qualifiedSpecs; ms = ss->cipherSpecs; for (mc = ss->sizeCipherSpecs; mc > 0; mc -= 3, ms += 3) { - if (ms[0] == 0) - continue; - for (hs = cs, hc = csLen; hc > 0; hs += 3, hc -= 3) { - if ((hs[0] == ms[0]) && - (hs[1] == ms[1]) && - (hs[2] == ms[2])) { - /* Copy this cipher spec into the "keep" section */ - qs[0] = hs[0]; - qs[1] = hs[1]; - qs[2] = hs[2]; - qs += 3; - break; - } - } + if (ms[0] == 0) + continue; + for (hs = cs, hc = csLen; hc > 0; hs += 3, hc -= 3) { + if ((hs[0] == ms[0]) && + (hs[1] == ms[1]) && + (hs[2] == ms[2])) { + /* Copy this cipher spec into the "keep" section */ + qs[0] = hs[0]; + qs[1] = hs[1]; + qs[2] = hs[2]; + qs += 3; + break; + } + } } hc = qs - qualifiedSpecs; PRINT_BUF(10, (ss, "qualified specs from client:", qualifiedSpecs, hc)); @@ -1766,158 +1784,160 @@ ssl2_QualifyCypherSpecs(sslSocket *ss, ** If successful, stores the master key size (bytes) in *pKeyLen. ** ** This is correct only for the client side, but presently -** this function is only called from -** ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage() +** this function is only called from +** ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage() ** -** Note that most servers only return a single cipher suite in their +** Note that most servers only return a single cipher suite in their ** ServerHello messages. So, the code below for finding the "best" cipher -** suite usually has only one choice. The client and server should send +** suite usually has only one choice. The client and server should send ** their cipher suite lists sorted in descending order by preference. */ static int -ssl2_ChooseSessionCypher(sslSocket *ss, - int hc, /* number of cs's in hs. */ - PRUint8 * hs, /* server hello's cipher suites. */ - int * pKeyLen) /* out: sym key size in bytes. */ +ssl2_ChooseSessionCypher(sslSocket *ss, + int hc, /* number of cs's in hs. */ + PRUint8 *hs, /* server hello's cipher suites. */ + int *pKeyLen) /* out: sym key size in bytes. */ { - PRUint8 * ms; - unsigned int i; - int bestKeySize; - int bestRealKeySize; - int bestCypher; - int keySize; - int realKeySize; - PRUint8 * ohs = hs; - const PRUint8 * preferred; + PRUint8 *ms; + unsigned int i; + int bestKeySize; + int bestRealKeySize; + int bestCypher; + int keySize; + int realKeySize; + PRUint8 *ohs = hs; + const PRUint8 *preferred; static const PRUint8 noneSuch[3] = { 0, 0, 0 }; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); if (!ss->cipherSpecs) { - SECStatus rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess || !ss->cipherSpecs) - goto loser; + SECStatus rv = ssl2_ConstructCipherSpecs(ss); + if (rv != SECSuccess || !ss->cipherSpecs) + goto loser; } if (!ss->preferredCipher) { - unsigned int allowed = ss->allowedByPolicy & ss->chosenPreference & - SSL_CB_IMPLEMENTED; - if (allowed) { - preferred = implementedCipherSuites; - for (i = ssl2_NUM_SUITES_IMPLEMENTED; i > 0; --i) { - if (0 != (allowed & (1U << preferred[0]))) { - ss->preferredCipher = preferred; - break; - } - preferred += 3; - } - } + unsigned int allowed = ss->allowedByPolicy & ss->chosenPreference & + SSL_CB_IMPLEMENTED; + if (allowed) { + preferred = implementedCipherSuites; + for (i = ssl2_NUM_SUITES_IMPLEMENTED; i > 0; --i) { + if (0 != (allowed & (1U << preferred[0]))) { + ss->preferredCipher = preferred; + break; + } + preferred += 3; + } + } } preferred = ss->preferredCipher ? ss->preferredCipher : noneSuch; /* ** Scan list of ciphers received from peer and look for a match in - ** our list. - * Note: Our list may contain SSL v3 ciphers. - * We MUST NOT match on any of those. + ** our list. + * Note: Our list may contain SSL v3 ciphers. + * We MUST NOT match on any of those. * Fortunately, this is easy to detect because SSLv3 ciphers have zero * in the first byte, and none of the SSLv2 ciphers do. */ bestKeySize = bestRealKeySize = 0; bestCypher = -1; while (--hc >= 0) { - for (i = 0, ms = ss->cipherSpecs; i < ss->sizeCipherSpecs; i += 3, ms += 3) { - if ((hs[0] == preferred[0]) && - (hs[1] == preferred[1]) && - (hs[2] == preferred[2]) && - hs[0] != 0) { - /* Pick this cipher immediately! */ - *pKeyLen = (((hs[1] << 8) | hs[2]) + 7) >> 3; - return hs[0]; - } - if ((hs[0] == ms[0]) && (hs[1] == ms[1]) && (hs[2] == ms[2]) && - hs[0] != 0) { - /* Found a match */ + for (i = 0, ms = ss->cipherSpecs; i < ss->sizeCipherSpecs; i += 3, ms += 3) { + if ((hs[0] == preferred[0]) && + (hs[1] == preferred[1]) && + (hs[2] == preferred[2]) && + hs[0] != 0) { + /* Pick this cipher immediately! */ + *pKeyLen = (((hs[1] << 8) | hs[2]) + 7) >> 3; + return hs[0]; + } + if ((hs[0] == ms[0]) && (hs[1] == ms[1]) && (hs[2] == ms[2]) && + hs[0] != 0) { + /* Found a match */ - /* Use secret keySize to determine which cipher is best */ - realKeySize = (hs[1] << 8) | hs[2]; - switch (hs[0]) { - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - keySize = 40; - break; - default: - keySize = realKeySize; - break; - } - if (keySize > bestKeySize) { - bestCypher = hs[0]; - bestKeySize = keySize; - bestRealKeySize = realKeySize; - } - } - } - hs += 3; + /* Use secret keySize to determine which cipher is best */ + realKeySize = (hs[1] << 8) | hs[2]; + switch (hs[0]) { + case SSL_CK_RC4_128_EXPORT40_WITH_MD5: + case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: + keySize = 40; + break; + default: + keySize = realKeySize; + break; + } + if (keySize > bestKeySize) { + bestCypher = hs[0]; + bestKeySize = keySize; + bestRealKeySize = realKeySize; + } + } + } + hs += 3; } if (bestCypher < 0) { - /* - ** No overlap between server and client. Re-examine server list - ** to see what kind of ciphers it does support so that we can set - ** the error code appropriately. - */ - if ((ohs[0] == SSL_CK_RC4_128_WITH_MD5) || - (ohs[0] == SSL_CK_RC2_128_CBC_WITH_MD5)) { - PORT_SetError(SSL_ERROR_US_ONLY_SERVER); - } else if ((ohs[0] == SSL_CK_RC4_128_EXPORT40_WITH_MD5) || - (ohs[0] == SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5)) { - PORT_SetError(SSL_ERROR_EXPORT_ONLY_SERVER); - } else { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - } - SSL_DBG(("%d: SSL[%d]: no cipher overlap", SSL_GETPID(), ss->fd)); - goto loser; + /* + ** No overlap between server and client. Re-examine server list + ** to see what kind of ciphers it does support so that we can set + ** the error code appropriately. + */ + if ((ohs[0] == SSL_CK_RC4_128_WITH_MD5) || + (ohs[0] == SSL_CK_RC2_128_CBC_WITH_MD5)) { + PORT_SetError(SSL_ERROR_US_ONLY_SERVER); + } + else if ((ohs[0] == SSL_CK_RC4_128_EXPORT40_WITH_MD5) || + (ohs[0] == SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5)) { + PORT_SetError(SSL_ERROR_EXPORT_ONLY_SERVER); + } + else { + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + } + SSL_DBG(("%d: SSL[%d]: no cipher overlap", SSL_GETPID(), ss->fd)); + goto loser; } *pKeyLen = (bestRealKeySize + 7) >> 3; return bestCypher; - loser: +loser: return -1; } static SECStatus ssl2_ClientHandleServerCert(sslSocket *ss, PRUint8 *certData, int certLen) { - CERTCertificate *cert = NULL; - SECItem certItem; + CERTCertificate *cert = NULL; + SECItem certItem; certItem.data = certData; - certItem.len = certLen; + certItem.len = certLen; /* decode the certificate */ cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, - PR_FALSE, PR_TRUE); - + PR_FALSE, PR_TRUE); + if (cert == NULL) { - SSL_DBG(("%d: SSL[%d]: decode of server certificate fails", - SSL_GETPID(), ss->fd)); - PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: decode of server certificate fails", + SSL_GETPID(), ss->fd)); + PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); + return SECFailure; } #ifdef TRACE { - if (ssl_trace >= 1) { - char *issuer; - char *subject; - issuer = CERT_NameToAscii(&cert->issuer); - subject = CERT_NameToAscii(&cert->subject); - SSL_TRC(1,("%d: server certificate issuer: '%s'", - SSL_GETPID(), issuer ? issuer : "OOPS")); - SSL_TRC(1,("%d: server name: '%s'", - SSL_GETPID(), subject ? subject : "OOPS")); - PORT_Free(issuer); - PORT_Free(subject); - } + if (ssl_trace >= 1) { + char *issuer; + char *subject; + issuer = CERT_NameToAscii(&cert->issuer); + subject = CERT_NameToAscii(&cert->subject); + SSL_TRC(1, ("%d: server certificate issuer: '%s'", + SSL_GETPID(), issuer ? issuer : "OOPS")); + SSL_TRC(1, ("%d: server name: '%s'", + SSL_GETPID(), subject ? subject : "OOPS")); + PORT_Free(issuer); + PORT_Free(subject); + } } #endif @@ -1925,16 +1945,15 @@ ssl2_ClientHandleServerCert(sslSocket *ss, PRUint8 *certData, int certLen) return SECSuccess; } - /* * Format one block of data for public/private key encryption using * the rules defined in PKCS #1. SSL2 does this itself to handle the * rollback detection. */ -#define RSA_BLOCK_MIN_PAD_LEN 8 -#define RSA_BLOCK_FIRST_OCTET 0x00 -#define RSA_BLOCK_AFTER_PAD_OCTET 0x00 -#define RSA_BLOCK_PUBLIC_OCTET 0x02 +#define RSA_BLOCK_MIN_PAD_LEN 8 +#define RSA_BLOCK_FIRST_OCTET 0x00 +#define RSA_BLOCK_AFTER_PAD_OCTET 0x00 +#define RSA_BLOCK_PUBLIC_OCTET 0x02 unsigned char * ssl_FormatSSL2Block(unsigned modulusLen, SECItem *data) { @@ -1945,18 +1964,18 @@ ssl_FormatSSL2Block(unsigned modulusLen, SECItem *data) int i; if (modulusLen < data->len + (3 + RSA_BLOCK_MIN_PAD_LEN)) { - PORT_SetError(SEC_ERROR_BAD_KEY); - return NULL; + PORT_SetError(SEC_ERROR_BAD_KEY); + return NULL; } - block = (unsigned char *) PORT_Alloc(modulusLen); + block = (unsigned char *)PORT_Alloc(modulusLen); if (block == NULL) - return NULL; + return NULL; bp = block; /* * All RSA blocks start with two octets: - * 0x00 || BlockType + * 0x00 || BlockType */ *bp++ = RSA_BLOCK_FIRST_OCTET; *bp++ = RSA_BLOCK_PUBLIC_OCTET; @@ -1967,23 +1986,26 @@ ssl_FormatSSL2Block(unsigned modulusLen, SECItem *data) * Pad is all non-zero random bytes. */ padLen = modulusLen - data->len - 3; - PORT_Assert (padLen >= RSA_BLOCK_MIN_PAD_LEN); + PORT_Assert(padLen >= RSA_BLOCK_MIN_PAD_LEN); rv = PK11_GenerateRandom(bp, padLen); - if (rv == SECFailure) goto loser; + if (rv == SECFailure) + goto loser; /* replace all the 'zero' bytes */ for (i = 0; i < padLen; i++) { - while (bp[i] == RSA_BLOCK_AFTER_PAD_OCTET) { - rv = PK11_GenerateRandom(bp+i, 1); - if (rv == SECFailure) goto loser; - } + while (bp[i] == RSA_BLOCK_AFTER_PAD_OCTET) { + rv = PK11_GenerateRandom(bp + i, 1); + if (rv == SECFailure) + goto loser; + } } bp += padLen; *bp++ = RSA_BLOCK_AFTER_PAD_OCTET; - PORT_Memcpy (bp, data->data, data->len); + PORT_Memcpy(bp, data->data, data->len); return block; loser: - if (block) PORT_Free(block); + if (block) + PORT_Free(block); return NULL; } @@ -1998,26 +2020,26 @@ loser: static SECStatus ssl2_ClientSetupSessionCypher(sslSocket *ss, PRUint8 *cs, int csLen) { - sslSessionID * sid; - PRUint8 * ca; /* points to iv data, or NULL if none. */ - PRUint8 * ekbuf = 0; - CERTCertificate * cert = 0; - SECKEYPublicKey * serverKey = 0; - unsigned modulusLen = 0; - SECStatus rv; - int cipher; - int keyLen; /* cipher symkey size in bytes. */ - int ckLen; /* publicly reveal this many bytes of key. */ - int caLen; /* length of IV data at *ca. */ - int nc; + sslSessionID *sid; + PRUint8 *ca; /* points to iv data, or NULL if none. */ + PRUint8 *ekbuf = 0; + CERTCertificate *cert = 0; + SECKEYPublicKey *serverKey = 0; + unsigned modulusLen = 0; + SECStatus rv; + int cipher; + int keyLen; /* cipher symkey size in bytes. */ + int ckLen; /* publicly reveal this many bytes of key. */ + int caLen; /* length of IV data at *ca. */ + int nc; - unsigned char *eblock; /* holds unencrypted PKCS#1 formatted key. */ - SECItem rek; /* holds portion of symkey to be encrypted. */ + unsigned char *eblock; /* holds unencrypted PKCS#1 formatted key. */ + SECItem rek; /* holds portion of symkey to be encrypted. */ - PRUint8 keyData[SSL_MAX_MASTER_KEY_BYTES]; - PRUint8 iv [8]; + PRUint8 keyData[SSL_MAX_MASTER_KEY_BYTES]; + PRUint8 iv[8]; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); eblock = NULL; @@ -2025,28 +2047,28 @@ ssl2_ClientSetupSessionCypher(sslSocket *ss, PRUint8 *cs, int csLen) PORT_Assert(sid != 0); cert = ss->sec.peerCert; - + serverKey = CERT_ExtractPublicKey(cert); if (!serverKey) { - SSL_DBG(("%d: SSL[%d]: extract public key failed: error=%d", - SSL_GETPID(), ss->fd, PORT_GetError())); - PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); - rv = SECFailure; - goto loser2; + SSL_DBG(("%d: SSL[%d]: extract public key failed: error=%d", + SSL_GETPID(), ss->fd, PORT_GetError())); + PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); + rv = SECFailure; + goto loser2; } ss->sec.authAlgorithm = ssl_sign_rsa; - ss->sec.keaType = ssl_kea_rsa; - ss->sec.keaKeyBits = \ - ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); + ss->sec.keaType = ssl_kea_rsa; + ss->sec.keaKeyBits = + ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); /* Choose a compatible cipher with the server */ nc = csLen / 3; cipher = ssl2_ChooseSessionCypher(ss, nc, cs, &keyLen); if (cipher < 0) { - /* ssl2_ChooseSessionCypher has set error code. */ - ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS); - goto loser; + /* ssl2_ChooseSessionCypher has set error code. */ + ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS); + goto loser; } /* Generate the random keys */ @@ -2061,79 +2083,79 @@ ssl2_ClientSetupSessionCypher(sslSocket *ss, PRUint8 *cs, int csLen) */ ca = 0; - /* We know that cipher is a legit value here, because + /* We know that cipher is a legit value here, because * ssl2_ChooseSessionCypher doesn't return bogus values. */ - ckLen = ssl_Specs[cipher].pubLen; /* cleartext key length. */ - caLen = ssl_Specs[cipher].ivLen; /* IV length. */ + ckLen = ssl_Specs[cipher].pubLen; /* cleartext key length. */ + caLen = ssl_Specs[cipher].ivLen; /* IV length. */ if (caLen) { - PORT_Assert(sizeof iv >= caLen); - PK11_GenerateRandom(iv, caLen); - ca = iv; + PORT_Assert(sizeof iv >= caLen); + PK11_GenerateRandom(iv, caLen); + ca = iv; } /* Fill in session-id */ rv = ssl2_FillInSID(sid, cipher, keyData, keyLen, - ca, caLen, keyLen << 3, (keyLen - ckLen) << 3, - ss->sec.authAlgorithm, ss->sec.authKeyBits, - ss->sec.keaType, ss->sec.keaKeyBits); + ca, caLen, keyLen << 3, (keyLen - ckLen) << 3, + ss->sec.authAlgorithm, ss->sec.authKeyBits, + ss->sec.keaType, ss->sec.keaKeyBits); if (rv != SECSuccess) { - goto loser; + goto loser; } SSL_TRC(1, ("%d: SSL[%d]: client, using %s cipher, clear=%d total=%d", - SSL_GETPID(), ss->fd, ssl_cipherName[cipher], - ckLen<<3, keyLen<<3)); + SSL_GETPID(), ss->fd, ssl_cipherName[cipher], + ckLen << 3, keyLen << 3)); /* Now setup read and write ciphers */ rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE); if (rv != SECSuccess) { - goto loser; + goto loser; } /* - ** Fill in the encryption buffer with some random bytes. Then + ** Fill in the encryption buffer with some random bytes. Then ** copy in the portion of the session key we are encrypting. */ modulusLen = SECKEY_PublicKeyStrength(serverKey); - rek.data = keyData + ckLen; - rek.len = keyLen - ckLen; + rek.data = keyData + ckLen; + rek.len = keyLen - ckLen; eblock = ssl_FormatSSL2Block(modulusLen, &rek); - if (eblock == NULL) - goto loser; + if (eblock == NULL) + goto loser; /* Set up the padding for version 2 rollback detection. */ /* XXX We should really use defines here */ if (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - PORT_Assert((modulusLen - rek.len) > 12); - PORT_Memset(eblock + modulusLen - rek.len - 8 - 1, 0x03, 8); + PORT_Assert((modulusLen - rek.len) > 12); + PORT_Memset(eblock + modulusLen - rek.len - 8 - 1, 0x03, 8); } - ekbuf = (PRUint8*) PORT_Alloc(modulusLen); - if (!ekbuf) - goto loser; + ekbuf = (PRUint8 *)PORT_Alloc(modulusLen); + if (!ekbuf) + goto loser; PRINT_BUF(10, (ss, "master key encryption block:", - eblock, modulusLen)); + eblock, modulusLen)); /* Encrypt ekitem */ rv = PK11_PubEncryptRaw(serverKey, ekbuf, eblock, modulusLen, - ss->pkcs11PinArg); - if (rv) - goto loser; + ss->pkcs11PinArg); + if (rv) + goto loser; /* Now we have everything ready to send */ rv = ssl2_SendSessionKeyMessage(ss, cipher, keyLen << 3, ca, caLen, - keyData, ckLen, ekbuf, modulusLen); + keyData, ckLen, ekbuf, modulusLen); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SECSuccess; goto done; - loser: +loser: rv = SECFailure; - loser2: - done: +loser2: +done: PORT_Memset(keyData, 0, sizeof(keyData)); PORT_ZFree(ekbuf, modulusLen); PORT_ZFree(eblock, modulusLen); @@ -2143,7 +2165,7 @@ ssl2_ClientSetupSessionCypher(sslSocket *ss, PRUint8 *cs, int csLen) /************************************************************************/ -/* +/* * Called from ssl2_HandleMessage in response to SSL_MT_SERVER_FINISHED message. * Caller holds recvBufLock and handshakeLock */ @@ -2154,27 +2176,26 @@ ssl2_ClientRegSessionID(sslSocket *ss, PRUint8 *s) /* Record entry in nonce cache */ if (sid->peerCert == NULL) { - PORT_Memcpy(sid->u.ssl2.sessionID, s, sizeof(sid->u.ssl2.sessionID)); - sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); - + PORT_Memcpy(sid->u.ssl2.sessionID, s, sizeof(sid->u.ssl2.sessionID)); + sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); } if (!ss->opt.noCache && sid->cached == never_cached) - (*ss->sec.cache)(sid); + (*ss->sec.cache)(sid); } /* Called from ssl2_HandleMessage() */ static SECStatus ssl2_TriggerNextMessage(sslSocket *ss) { - SECStatus rv; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); if ((ss->sec.ci.requiredElements & CIS_HAVE_CERTIFICATE) && - !(ss->sec.ci.sentElements & CIS_HAVE_CERTIFICATE)) { - ss->sec.ci.sentElements |= CIS_HAVE_CERTIFICATE; - rv = ssl2_SendCertificateRequestMessage(ss); - return rv; + !(ss->sec.ci.sentElements & CIS_HAVE_CERTIFICATE)) { + ss->sec.ci.sentElements |= CIS_HAVE_CERTIFICATE; + rv = ssl2_SendCertificateRequestMessage(ss); + return rv; } return SECSuccess; } @@ -2184,36 +2205,37 @@ ssl2_TriggerNextMessage(sslSocket *ss) ** Returns SECSuccess unless anything goes wrong. ** ** Called from ssl2_HandleMessage, -** ssl2_HandleVerifyMessage +** ssl2_HandleVerifyMessage ** ssl2_HandleServerHelloMessage ** ssl2_HandleClientSessionKeyMessage */ static SECStatus ssl2_TryToFinish(sslSocket *ss) { - SECStatus rv; - char e, ef; + SECStatus rv; + char e, ef; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); e = ss->sec.ci.elements; ef = e | CIS_HAVE_FINISHED; if ((ef & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) { - if (ss->sec.isServer) { - /* Send server finished message if we already didn't */ - rv = ssl2_SendServerFinishedMessage(ss); - } else { - /* Send client finished message if we already didn't */ - rv = ssl2_SendClientFinishedMessage(ss); - } - if (rv != SECSuccess) { - return rv; - } - if ((e & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) { - /* Totally finished */ - ss->handshake = 0; - return SECSuccess; - } + if (ss->sec.isServer) { + /* Send server finished message if we already didn't */ + rv = ssl2_SendServerFinishedMessage(ss); + } + else { + /* Send client finished message if we already didn't */ + rv = ssl2_SendClientFinishedMessage(ss); + } + if (rv != SECSuccess) { + return rv; + } + if ((e & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) { + /* Totally finished */ + ss->handshake = 0; + return SECSuccess; + } } return SECSuccess; } @@ -2223,42 +2245,42 @@ ssl2_TryToFinish(sslSocket *ss) */ static SECStatus ssl2_SignResponse(sslSocket *ss, - SECKEYPrivateKey *key, - SECItem *response) + SECKEYPrivateKey *key, + SECItem *response) { - SGNContext * sgn = NULL; - PRUint8 * challenge; - unsigned int len; - SECStatus rv = SECFailure; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + SGNContext *sgn = NULL; + PRUint8 *challenge; + unsigned int len; + SECStatus rv = SECFailure; + + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); challenge = ss->sec.ci.serverChallenge; len = ss->sec.ci.serverChallengeLen; - + /* Sign the expected data... */ - sgn = SGN_NewContext(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,key); - if (!sgn) - goto done; + sgn = SGN_NewContext(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, key); + if (!sgn) + goto done; rv = SGN_Begin(sgn); - if (rv != SECSuccess) - goto done; + if (rv != SECSuccess) + goto done; rv = SGN_Update(sgn, ss->sec.ci.readKey, ss->sec.ci.keySize); - if (rv != SECSuccess) - goto done; + if (rv != SECSuccess) + goto done; rv = SGN_Update(sgn, ss->sec.ci.writeKey, ss->sec.ci.keySize); - if (rv != SECSuccess) - goto done; + if (rv != SECSuccess) + goto done; rv = SGN_Update(sgn, challenge, len); - if (rv != SECSuccess) - goto done; - rv = SGN_Update(sgn, ss->sec.peerCert->derCert.data, - ss->sec.peerCert->derCert.len); - if (rv != SECSuccess) - goto done; + if (rv != SECSuccess) + goto done; + rv = SGN_Update(sgn, ss->sec.peerCert->derCert.data, + ss->sec.peerCert->derCert.len); + if (rv != SECSuccess) + goto done; rv = SGN_End(sgn, response); - if (rv != SECSuccess) - goto done; + if (rv != SECSuccess) + goto done; done: SGN_DestroyContext(sgn, PR_TRUE); @@ -2268,20 +2290,19 @@ done: /* ** Try to handle a request-certificate message. Get client's certificate ** and private key and sign a message for the server to see. -** Caller must hold handshakeLock +** Caller must hold handshakeLock ** ** Called from ssl2_HandleMessage(). */ static int ssl2_HandleRequestCertificate(sslSocket *ss) { - CERTCertificate * cert = NULL; /* app-selected client cert. */ - SECKEYPrivateKey *key = NULL; /* priv key for cert. */ - SECStatus rv; - SECItem response; - int ret = 0; - PRUint8 authType; - + CERTCertificate *cert = NULL; /* app-selected client cert. */ + SECKEYPrivateKey *key = NULL; /* priv key for cert. */ + SECStatus rv; + SECItem response; + int ret = 0; + PRUint8 authType; /* * These things all need to be initialized before we can "goto loser". @@ -2292,27 +2313,27 @@ ssl2_HandleRequestCertificate(sslSocket *ss) authType = ss->sec.ci.authType; if (authType != SSL_AT_MD5_WITH_RSA_ENCRYPTION) { - SSL_TRC(7, ("%d: SSL[%d]: unsupported auth type 0x%x", SSL_GETPID(), - ss->fd, authType)); - goto no_cert_error; + SSL_TRC(7, ("%d: SSL[%d]: unsupported auth type 0x%x", SSL_GETPID(), + ss->fd, authType)); + goto no_cert_error; } /* Get certificate and private-key from client */ if (!ss->getClientAuthData) { - SSL_TRC(7, ("%d: SSL[%d]: client doesn't support client-auth", - SSL_GETPID(), ss->fd)); - goto no_cert_error; + SSL_TRC(7, ("%d: SSL[%d]: client doesn't support client-auth", + SSL_GETPID(), ss->fd)); + goto no_cert_error; } ret = (*ss->getClientAuthData)(ss->getClientAuthDataArg, ss->fd, - NULL, &cert, &key); - if ( ret == SECWouldBlock ) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - ret = -1; - goto loser; + NULL, &cert, &key); + if (ret == SECWouldBlock) { + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); + ret = -1; + goto loser; } if (ret) { - goto no_cert_error; + goto no_cert_error; } /* check what the callback function returned */ @@ -2332,9 +2353,9 @@ ssl2_HandleRequestCertificate(sslSocket *ss) } rv = ssl2_SignResponse(ss, key, &response); - if ( rv != SECSuccess ) { - ret = -1; - goto loser; + if (rv != SECSuccess) { + ret = -1; + goto loser; } /* Send response message */ @@ -2342,35 +2363,35 @@ ssl2_HandleRequestCertificate(sslSocket *ss) /* Now, remember the cert we sent. But first, forget any previous one. */ if (ss->sec.localCert) { - CERT_DestroyCertificate(ss->sec.localCert); + CERT_DestroyCertificate(ss->sec.localCert); } ss->sec.localCert = CERT_DupCertificate(cert); PORT_Assert(!ss->sec.ci.sid->localCert); if (ss->sec.ci.sid->localCert) { - CERT_DestroyCertificate(ss->sec.ci.sid->localCert); + CERT_DestroyCertificate(ss->sec.ci.sid->localCert); } ss->sec.ci.sid->localCert = cert; cert = NULL; goto done; - no_cert_error: +no_cert_error: SSL_TRC(7, ("%d: SSL[%d]: no certificate (ret=%d)", SSL_GETPID(), - ss->fd, ret)); + ss->fd, ret)); ret = ssl2_SendErrorMessage(ss, SSL_PE_NO_CERTIFICATE); - loser: - done: - if ( cert ) { - CERT_DestroyCertificate(cert); +loser: +done: + if (cert) { + CERT_DestroyCertificate(cert); } - if ( key ) { - SECKEY_DestroyPrivateKey(key); + if (key) { + SECKEY_DestroyPrivateKey(key); } - if ( response.data ) { - PORT_Free(response.data); + if (response.data) { + PORT_Free(response.data); } - + return ret; } @@ -2380,32 +2401,32 @@ ssl2_HandleRequestCertificate(sslSocket *ss) ** are contained in the gathered input data. */ static SECStatus -ssl2_HandleClientCertificate(sslSocket * ss, - PRUint8 certType, /* XXX unused */ - PRUint8 * cd, - unsigned int cdLen, - PRUint8 * response, - unsigned int responseLen) +ssl2_HandleClientCertificate(sslSocket *ss, + PRUint8 certType, /* XXX unused */ + PRUint8 *cd, + unsigned int cdLen, + PRUint8 *response, + unsigned int responseLen) { - CERTCertificate *cert = NULL; - SECKEYPublicKey *pubKey = NULL; - VFYContext * vfy = NULL; - SECItem * derCert; - SECStatus rv = SECFailure; - SECItem certItem; - SECItem rep; + CERTCertificate *cert = NULL; + SECKEYPublicKey *pubKey = NULL; + VFYContext *vfy = NULL; + SECItem *derCert; + SECStatus rv = SECFailure; + SECItem certItem; + SECItem rep; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); /* Extract the certificate */ certItem.data = cd; - certItem.len = cdLen; + certItem.len = cdLen; cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, - PR_FALSE, PR_TRUE); + PR_FALSE, PR_TRUE); if (cert == NULL) { - goto loser; + goto loser; } /* save the certificate, since the auth routine will need it */ @@ -2413,46 +2434,46 @@ ssl2_HandleClientCertificate(sslSocket * ss, /* Extract the public key */ pubKey = CERT_ExtractPublicKey(cert); - if (!pubKey) - goto loser; - + if (!pubKey) + goto loser; + /* Verify the response data... */ rep.data = response; rep.len = responseLen; /* SSL 2.0 only supports RSA certs, so we don't have to worry about * DSA here. */ vfy = VFY_CreateContext(pubKey, &rep, SEC_OID_PKCS1_RSA_ENCRYPTION, - ss->pkcs11PinArg); - if (!vfy) - goto loser; + ss->pkcs11PinArg); + if (!vfy) + goto loser; rv = VFY_Begin(vfy); - if (rv) - goto loser; + if (rv) + goto loser; rv = VFY_Update(vfy, ss->sec.ci.readKey, ss->sec.ci.keySize); - if (rv) - goto loser; + if (rv) + goto loser; rv = VFY_Update(vfy, ss->sec.ci.writeKey, ss->sec.ci.keySize); - if (rv) - goto loser; + if (rv) + goto loser; rv = VFY_Update(vfy, ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES); - if (rv) - goto loser; + if (rv) + goto loser; derCert = &ss->serverCerts[kt_rsa].serverCert->derCert; rv = VFY_Update(vfy, derCert->data, derCert->len); - if (rv) - goto loser; + if (rv) + goto loser; rv = VFY_End(vfy); - if (rv) - goto loser; + if (rv) + goto loser; /* Now ask the server application if it likes the certificate... */ rv = (SECStatus) (*ss->authCertificate)(ss->authCertificateArg, - ss->fd, PR_TRUE, PR_TRUE); + ss->fd, PR_TRUE, PR_TRUE); /* Hey, it liked it. */ - if (SECSuccess == rv) - goto done; + if (SECSuccess == rv) + goto done; loser: ss->sec.peerCert = NULL; @@ -2467,200 +2488,201 @@ done: /* ** Handle remaining messages between client/server. Process finished ** messages from either side and any authentication requests. -** This should only be called for SSLv2 handshake messages, +** This should only be called for SSLv2 handshake messages, ** not for application data records. ** Caller must hold handshake lock. ** ** Called from ssl_Do1stHandshake(). -** +** */ static SECStatus ssl2_HandleMessage(sslSocket *ss) { - PRUint8 * data; - PRUint8 * cid; - unsigned len, certType, certLen, responseLen; - int rv; + PRUint8 *data; + PRUint8 *cid; + unsigned len, certType, certLen, responseLen; + int rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); ssl_GetRecvBufLock(ss); data = ss->gs.buf.buf + ss->gs.recordOffset; if (ss->gs.recordLen < 1) { - goto bad_peer; + goto bad_peer; } SSL_TRC(3, ("%d: SSL[%d]: received %d message", - SSL_GETPID(), ss->fd, data[0])); + SSL_GETPID(), ss->fd, data[0])); DUMP_MSG(29, (ss, data, ss->gs.recordLen)); switch (data[0]) { - case SSL_MT_CLIENT_FINISHED: - if (ss->sec.ci.elements & CIS_HAVE_FINISHED) { - SSL_DBG(("%d: SSL[%d]: dup client-finished message", - SSL_GETPID(), ss->fd)); - goto bad_peer; - } + case SSL_MT_CLIENT_FINISHED: + if (ss->sec.ci.elements & CIS_HAVE_FINISHED) { + SSL_DBG(("%d: SSL[%d]: dup client-finished message", + SSL_GETPID(), ss->fd)); + goto bad_peer; + } - /* See if nonce matches */ - len = ss->gs.recordLen - 1; - cid = data + 1; - if ((len != sizeof(ss->sec.ci.connectionID)) || - (PORT_Memcmp(ss->sec.ci.connectionID, cid, len) != 0)) { - SSL_DBG(("%d: SSL[%d]: bad connection-id", SSL_GETPID(), ss->fd)); - PRINT_BUF(5, (ss, "sent connection-id", - ss->sec.ci.connectionID, - sizeof(ss->sec.ci.connectionID))); - PRINT_BUF(5, (ss, "rcvd connection-id", cid, len)); - goto bad_peer; - } + /* See if nonce matches */ + len = ss->gs.recordLen - 1; + cid = data + 1; + if ((len != sizeof(ss->sec.ci.connectionID)) || + (PORT_Memcmp(ss->sec.ci.connectionID, cid, len) != 0)) { + SSL_DBG(("%d: SSL[%d]: bad connection-id", SSL_GETPID(), ss->fd)); + PRINT_BUF(5, (ss, "sent connection-id", + ss->sec.ci.connectionID, + sizeof(ss->sec.ci.connectionID))); + PRINT_BUF(5, (ss, "rcvd connection-id", cid, len)); + goto bad_peer; + } - SSL_TRC(5, ("%d: SSL[%d]: got client finished, waiting for 0x%d", - SSL_GETPID(), ss->fd, - ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); - ss->sec.ci.elements |= CIS_HAVE_FINISHED; - break; + SSL_TRC(5, ("%d: SSL[%d]: got client finished, waiting for 0x%d", + SSL_GETPID(), ss->fd, + ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); + ss->sec.ci.elements |= CIS_HAVE_FINISHED; + break; - case SSL_MT_SERVER_FINISHED: - if (ss->sec.ci.elements & CIS_HAVE_FINISHED) { - SSL_DBG(("%d: SSL[%d]: dup server-finished message", - SSL_GETPID(), ss->fd)); - goto bad_peer; - } + case SSL_MT_SERVER_FINISHED: + if (ss->sec.ci.elements & CIS_HAVE_FINISHED) { + SSL_DBG(("%d: SSL[%d]: dup server-finished message", + SSL_GETPID(), ss->fd)); + goto bad_peer; + } - if (ss->gs.recordLen - 1 != SSL2_SESSIONID_BYTES) { - SSL_DBG(("%d: SSL[%d]: bad server-finished message, len=%d", - SSL_GETPID(), ss->fd, ss->gs.recordLen)); - goto bad_peer; - } - ssl2_ClientRegSessionID(ss, data+1); - SSL_TRC(5, ("%d: SSL[%d]: got server finished, waiting for 0x%d", - SSL_GETPID(), ss->fd, - ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); - ss->sec.ci.elements |= CIS_HAVE_FINISHED; - break; + if (ss->gs.recordLen - 1 != SSL2_SESSIONID_BYTES) { + SSL_DBG(("%d: SSL[%d]: bad server-finished message, len=%d", + SSL_GETPID(), ss->fd, ss->gs.recordLen)); + goto bad_peer; + } + ssl2_ClientRegSessionID(ss, data + 1); + SSL_TRC(5, ("%d: SSL[%d]: got server finished, waiting for 0x%d", + SSL_GETPID(), ss->fd, + ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); + ss->sec.ci.elements |= CIS_HAVE_FINISHED; + break; - case SSL_MT_REQUEST_CERTIFICATE: - len = ss->gs.recordLen - 2; - if ((len < SSL_MIN_CHALLENGE_BYTES) || - (len > SSL_MAX_CHALLENGE_BYTES)) { - /* Bad challenge */ - SSL_DBG(("%d: SSL[%d]: bad cert request message: code len=%d", - SSL_GETPID(), ss->fd, len)); - goto bad_peer; - } - - /* save auth request info */ - ss->sec.ci.authType = data[1]; - ss->sec.ci.serverChallengeLen = len; - PORT_Memcpy(ss->sec.ci.serverChallenge, data + 2, len); - - rv = ssl2_HandleRequestCertificate(ss); - if (rv == SECWouldBlock) { - SSL_TRC(3, ("%d: SSL[%d]: async cert request", - SSL_GETPID(), ss->fd)); - /* someone is handling this asynchronously */ - ssl_ReleaseRecvBufLock(ss); - return SECWouldBlock; - } - if (rv) { - SET_ERROR_CODE - goto loser; - } - break; + case SSL_MT_REQUEST_CERTIFICATE: + len = ss->gs.recordLen - 2; + if ((len < SSL_MIN_CHALLENGE_BYTES) || + (len > SSL_MAX_CHALLENGE_BYTES)) { + /* Bad challenge */ + SSL_DBG(("%d: SSL[%d]: bad cert request message: code len=%d", + SSL_GETPID(), ss->fd, len)); + goto bad_peer; + } - case SSL_MT_CLIENT_CERTIFICATE: - if (!ss->authCertificate) { - /* Server asked for authentication and can't handle it */ - PORT_SetError(SSL_ERROR_BAD_SERVER); - goto loser; - } - if (ss->gs.recordLen < SSL_HL_CLIENT_CERTIFICATE_HBYTES) { - SET_ERROR_CODE - goto loser; - } - certType = data[1]; - certLen = (data[2] << 8) | data[3]; - responseLen = (data[4] << 8) | data[5]; - if (certType != SSL_CT_X509_CERTIFICATE) { - PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE); - goto loser; - } - if (certLen + responseLen + SSL_HL_CLIENT_CERTIFICATE_HBYTES - > ss->gs.recordLen) { - /* prevent overflow crash. */ - rv = SECFailure; - } else - rv = ssl2_HandleClientCertificate(ss, data[1], - data + SSL_HL_CLIENT_CERTIFICATE_HBYTES, - certLen, - data + SSL_HL_CLIENT_CERTIFICATE_HBYTES + certLen, - responseLen); - if (rv) { - (void)ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); - SET_ERROR_CODE - goto loser; - } - ss->sec.ci.elements |= CIS_HAVE_CERTIFICATE; - break; + /* save auth request info */ + ss->sec.ci.authType = data[1]; + ss->sec.ci.serverChallengeLen = len; + PORT_Memcpy(ss->sec.ci.serverChallenge, data + 2, len); - case SSL_MT_ERROR: - rv = (data[1] << 8) | data[2]; - SSL_TRC(2, ("%d: SSL[%d]: got error message, error=0x%x", - SSL_GETPID(), ss->fd, rv)); + rv = ssl2_HandleRequestCertificate(ss); + if (rv == SECWouldBlock) { + SSL_TRC(3, ("%d: SSL[%d]: async cert request", + SSL_GETPID(), ss->fd)); + /* someone is handling this asynchronously */ + ssl_ReleaseRecvBufLock(ss); + return SECWouldBlock; + } + if (rv) { + SET_ERROR_CODE + goto loser; + } + break; - /* Convert protocol error number into API error number */ - switch (rv) { - case SSL_PE_NO_CYPHERS: - rv = SSL_ERROR_NO_CYPHER_OVERLAP; - break; - case SSL_PE_NO_CERTIFICATE: - rv = SSL_ERROR_NO_CERTIFICATE; - break; - case SSL_PE_BAD_CERTIFICATE: - rv = SSL_ERROR_BAD_CERTIFICATE; - break; - case SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE: - rv = SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE; - break; - default: - goto bad_peer; - } - /* XXX make certificate-request optionally fail... */ - PORT_SetError(rv); - goto loser; + case SSL_MT_CLIENT_CERTIFICATE: + if (!ss->authCertificate) { + /* Server asked for authentication and can't handle it */ + PORT_SetError(SSL_ERROR_BAD_SERVER); + goto loser; + } + if (ss->gs.recordLen < SSL_HL_CLIENT_CERTIFICATE_HBYTES) { + SET_ERROR_CODE + goto loser; + } + certType = data[1]; + certLen = (data[2] << 8) | data[3]; + responseLen = (data[4] << 8) | data[5]; + if (certType != SSL_CT_X509_CERTIFICATE) { + PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE); + goto loser; + } + if (certLen + responseLen + SSL_HL_CLIENT_CERTIFICATE_HBYTES > + ss->gs.recordLen) { + /* prevent overflow crash. */ + rv = SECFailure; + } + else + rv = ssl2_HandleClientCertificate(ss, data[1], + data + SSL_HL_CLIENT_CERTIFICATE_HBYTES, + certLen, + data + SSL_HL_CLIENT_CERTIFICATE_HBYTES + certLen, + responseLen); + if (rv) { + (void)ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); + SET_ERROR_CODE + goto loser; + } + ss->sec.ci.elements |= CIS_HAVE_CERTIFICATE; + break; - default: - SSL_DBG(("%d: SSL[%d]: unknown message %d", - SSL_GETPID(), ss->fd, data[0])); - goto loser; + case SSL_MT_ERROR: + rv = (data[1] << 8) | data[2]; + SSL_TRC(2, ("%d: SSL[%d]: got error message, error=0x%x", + SSL_GETPID(), ss->fd, rv)); + + /* Convert protocol error number into API error number */ + switch (rv) { + case SSL_PE_NO_CYPHERS: + rv = SSL_ERROR_NO_CYPHER_OVERLAP; + break; + case SSL_PE_NO_CERTIFICATE: + rv = SSL_ERROR_NO_CERTIFICATE; + break; + case SSL_PE_BAD_CERTIFICATE: + rv = SSL_ERROR_BAD_CERTIFICATE; + break; + case SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE: + rv = SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE; + break; + default: + goto bad_peer; + } + /* XXX make certificate-request optionally fail... */ + PORT_SetError(rv); + goto loser; + + default: + SSL_DBG(("%d: SSL[%d]: unknown message %d", + SSL_GETPID(), ss->fd, data[0])); + goto loser; } SSL_TRC(3, ("%d: SSL[%d]: handled %d message, required=0x%x got=0x%x", - SSL_GETPID(), ss->fd, data[0], - ss->sec.ci.requiredElements, ss->sec.ci.elements)); + SSL_GETPID(), ss->fd, data[0], + ss->sec.ci.requiredElements, ss->sec.ci.elements)); rv = ssl2_TryToFinish(ss); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; ss->gs.recordLen = 0; ssl_ReleaseRecvBufLock(ss); if (ss->handshake == 0) { - return SECSuccess; + return SECSuccess; } - ss->handshake = ssl_GatherRecord1stHandshake; + ss->handshake = ssl_GatherRecord1stHandshake; ss->nextHandshake = ssl2_HandleMessage; return ssl2_TriggerNextMessage(ss); - bad_peer: +bad_peer: PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT : SSL_ERROR_BAD_SERVER); - /* FALL THROUGH */ +/* FALL THROUGH */ - loser: +loser: ssl_ReleaseRecvBufLock(ss); return SECFailure; } @@ -2672,67 +2694,66 @@ ssl2_HandleMessage(sslSocket *ss) static SECStatus ssl2_HandleVerifyMessage(sslSocket *ss) { - PRUint8 * data; - SECStatus rv; + PRUint8 *data; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); ssl_GetRecvBufLock(ss); data = ss->gs.buf.buf + ss->gs.recordOffset; DUMP_MSG(29, (ss, data, ss->gs.recordLen)); if ((ss->gs.recordLen != 1 + SSL_CHALLENGE_BYTES) || - (data[0] != SSL_MT_SERVER_VERIFY) || - NSS_SecureMemcmp(data+1, ss->sec.ci.clientChallenge, - SSL_CHALLENGE_BYTES)) { - /* Bad server */ - PORT_SetError(SSL_ERROR_BAD_SERVER); - goto loser; + (data[0] != SSL_MT_SERVER_VERIFY) || + NSS_SecureMemcmp(data + 1, ss->sec.ci.clientChallenge, + SSL_CHALLENGE_BYTES)) { + /* Bad server */ + PORT_SetError(SSL_ERROR_BAD_SERVER); + goto loser; } ss->sec.ci.elements |= CIS_HAVE_VERIFY; SSL_TRC(5, ("%d: SSL[%d]: got server-verify, required=0x%d got=0x%x", - SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements, - ss->sec.ci.elements)); + SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements, + ss->sec.ci.elements)); rv = ssl2_TryToFinish(ss); - if (rv) - goto loser; + if (rv) + goto loser; ss->gs.recordLen = 0; ssl_ReleaseRecvBufLock(ss); if (ss->handshake == 0) { - return SECSuccess; + return SECSuccess; } - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleMessage; + ss->handshake = ssl_GatherRecord1stHandshake; + ss->nextHandshake = ssl2_HandleMessage; return SECSuccess; - - loser: +loser: ssl_ReleaseRecvBufLock(ss); return SECFailure; } /* Not static because ssl2_GatherData() tests ss->nextHandshake for this value. - * ICK! + * ICK! * Called from ssl_Do1stHandshake after ssl2_BeginClientHandshake() */ SECStatus ssl2_HandleServerHelloMessage(sslSocket *ss) { - sslSessionID * sid; - PRUint8 * cert; - PRUint8 * cs; - PRUint8 * data; - SECStatus rv; + sslSessionID *sid; + PRUint8 *cert; + PRUint8 *cs; + PRUint8 *data; + SECStatus rv; unsigned int needed, sidHit, certLen, csLen, cidLen, certType, err; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); if (!ss->opt.enableSSL2) { - PORT_SetError(SSL_ERROR_SSL2_DISABLED); - return SECFailure; + PORT_SetError(SSL_ERROR_SSL2_DISABLED); + return SECFailure; } ssl_GetRecvBufLock(ss); @@ -2744,51 +2765,52 @@ ssl2_HandleServerHelloMessage(sslSocket *ss) DUMP_MSG(29, (ss, data, ss->gs.recordLen)); /* Make sure first message has some data and is the server hello message */ - if ((ss->gs.recordLen < SSL_HL_SERVER_HELLO_HBYTES) - || (data[0] != SSL_MT_SERVER_HELLO)) { - if ((data[0] == SSL_MT_ERROR) && (ss->gs.recordLen == 3)) { - err = (data[1] << 8) | data[2]; - if (err == SSL_PE_NO_CYPHERS) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - goto loser; - } - } - goto bad_server; + if ((ss->gs.recordLen < SSL_HL_SERVER_HELLO_HBYTES) || + (data[0] != SSL_MT_SERVER_HELLO)) { + if ((data[0] == SSL_MT_ERROR) && (ss->gs.recordLen == 3)) { + err = (data[1] << 8) | data[2]; + if (err == SSL_PE_NO_CYPHERS) { + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + goto loser; + } + } + goto bad_server; } - sidHit = data[1]; - certType = data[2]; + sidHit = data[1]; + certType = data[2]; ss->version = (data[3] << 8) | data[4]; - certLen = (data[5] << 8) | data[6]; - csLen = (data[7] << 8) | data[8]; - cidLen = (data[9] << 8) | data[10]; - cert = data + SSL_HL_SERVER_HELLO_HBYTES; - cs = cert + certLen; + certLen = (data[5] << 8) | data[6]; + csLen = (data[7] << 8) | data[8]; + cidLen = (data[9] << 8) | data[10]; + cert = data + SSL_HL_SERVER_HELLO_HBYTES; + cs = cert + certLen; SSL_TRC(5, - ("%d: SSL[%d]: server-hello, hit=%d vers=%x certLen=%d csLen=%d cidLen=%d", - SSL_GETPID(), ss->fd, sidHit, ss->version, certLen, - csLen, cidLen)); + ("%d: SSL[%d]: server-hello, hit=%d vers=%x certLen=%d csLen=%d cidLen=%d", + SSL_GETPID(), ss->fd, sidHit, ss->version, certLen, + csLen, cidLen)); if (ss->version != SSL_LIBRARY_VERSION_2) { if (ss->version < SSL_LIBRARY_VERSION_2) { - SSL_TRC(3, ("%d: SSL[%d]: demoting self (%x) to server version (%x)", - SSL_GETPID(), ss->fd, SSL_LIBRARY_VERSION_2, - ss->version)); - } else { - SSL_TRC(1, ("%d: SSL[%d]: server version is %x (we are %x)", - SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2)); - /* server claims to be newer but does not follow protocol */ - PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); - goto loser; - } + SSL_TRC(3, ("%d: SSL[%d]: demoting self (%x) to server version (%x)", + SSL_GETPID(), ss->fd, SSL_LIBRARY_VERSION_2, + ss->version)); + } + else { + SSL_TRC(1, ("%d: SSL[%d]: server version is %x (we are %x)", + SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2)); + /* server claims to be newer but does not follow protocol */ + PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); + goto loser; + } } - if ((SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen + cidLen - > ss->gs.recordLen) - || (csLen % 3) != 0 - /* || cidLen < SSL_CONNECTIONID_BYTES || cidLen > 32 */ - ) { - goto bad_server; + if ((SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen + cidLen > + ss->gs.recordLen) || + (csLen % 3) != 0 + /* || cidLen < SSL_CONNECTIONID_BYTES || cidLen > 32 */ + ) { + goto bad_server; } /* Save connection-id. @@ -2796,117 +2818,121 @@ ssl2_HandleServerHelloMessage(sslSocket *ss) ** If the connectionID is shorter than 16 bytes, it is zero-padded. */ if (cidLen < sizeof ss->sec.ci.connectionID) - memset(ss->sec.ci.connectionID, 0, sizeof ss->sec.ci.connectionID); + memset(ss->sec.ci.connectionID, 0, sizeof ss->sec.ci.connectionID); cidLen = PR_MIN(cidLen, sizeof ss->sec.ci.connectionID); PORT_Memcpy(ss->sec.ci.connectionID, cs + csLen, cidLen); /* See if session-id hit */ needed = CIS_HAVE_MASTER_KEY | CIS_HAVE_FINISHED | CIS_HAVE_VERIFY; if (sidHit) { - if (certLen || csLen) { - /* Uh oh - bogus server */ - SSL_DBG(("%d: SSL[%d]: client, huh? hit=%d certLen=%d csLen=%d", - SSL_GETPID(), ss->fd, sidHit, certLen, csLen)); - goto bad_server; - } + if (certLen || csLen) { + /* Uh oh - bogus server */ + SSL_DBG(("%d: SSL[%d]: client, huh? hit=%d certLen=%d csLen=%d", + SSL_GETPID(), ss->fd, sidHit, certLen, csLen)); + goto bad_server; + } - /* Total winner. */ - SSL_TRC(1, ("%d: SSL[%d]: client, using nonce for peer=0x%08x " - "port=0x%04x", - SSL_GETPID(), ss->fd, ss->sec.ci.peer, ss->sec.ci.port)); - ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); + /* Total winner. */ + SSL_TRC(1, ("%d: SSL[%d]: client, using nonce for peer=0x%08x " + "port=0x%04x", + SSL_GETPID(), ss->fd, ss->sec.ci.peer, ss->sec.ci.port)); + ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); ss->sec.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; - rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE); - if (rv != SECSuccess) { - goto loser; - } - } else { - if (certType != SSL_CT_X509_CERTIFICATE) { - PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE); - goto loser; - } - if (csLen == 0) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - SSL_DBG(("%d: SSL[%d]: no cipher overlap", - SSL_GETPID(), ss->fd)); - goto loser; - } - if (certLen == 0) { - SSL_DBG(("%d: SSL[%d]: client, huh? certLen=%d csLen=%d", - SSL_GETPID(), ss->fd, certLen, csLen)); - goto bad_server; - } + ss->sec.authKeyBits = sid->authKeyBits; + ss->sec.keaType = sid->keaType; + ss->sec.keaKeyBits = sid->keaKeyBits; + rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE); + if (rv != SECSuccess) { + goto loser; + } + } + else { + if (certType != SSL_CT_X509_CERTIFICATE) { + PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE); + goto loser; + } + if (csLen == 0) { + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + SSL_DBG(("%d: SSL[%d]: no cipher overlap", + SSL_GETPID(), ss->fd)); + goto loser; + } + if (certLen == 0) { + SSL_DBG(("%d: SSL[%d]: client, huh? certLen=%d csLen=%d", + SSL_GETPID(), ss->fd, certLen, csLen)); + goto bad_server; + } - if (sid->cached != never_cached) { - /* Forget our session-id - server didn't like it */ - SSL_TRC(7, ("%d: SSL[%d]: server forgot me, uncaching session-id", - SSL_GETPID(), ss->fd)); - if (ss->sec.uncache) - (*ss->sec.uncache)(sid); - ssl_FreeSID(sid); - ss->sec.ci.sid = sid = PORT_ZNew(sslSessionID); - if (!sid) { - goto loser; - } - sid->references = 1; - sid->addr = ss->sec.ci.peer; - sid->port = ss->sec.ci.port; - } + if (sid->cached != never_cached) { + /* Forget our session-id - server didn't like it */ + SSL_TRC(7, ("%d: SSL[%d]: server forgot me, uncaching session-id", + SSL_GETPID(), ss->fd)); + if (ss->sec.uncache) + (*ss->sec.uncache)(sid); + ssl_FreeSID(sid); + ss->sec.ci.sid = sid = PORT_ZNew(sslSessionID); + if (!sid) { + goto loser; + } + sid->references = 1; + sid->addr = ss->sec.ci.peer; + sid->port = ss->sec.ci.port; + } - /* decode the server's certificate */ - rv = ssl2_ClientHandleServerCert(ss, cert, certLen); - if (rv != SECSuccess) { - if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) { - (void) ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); - } - goto loser; - } + /* decode the server's certificate */ + rv = ssl2_ClientHandleServerCert(ss, cert, certLen); + if (rv != SECSuccess) { + if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) { + (void)ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); + } + goto loser; + } - /* Setup new session cipher */ - rv = ssl2_ClientSetupSessionCypher(ss, cs, csLen); - if (rv != SECSuccess) { - if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) { - (void) ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); - } - goto loser; - } + /* Setup new session cipher */ + rv = ssl2_ClientSetupSessionCypher(ss, cs, csLen); + if (rv != SECSuccess) { + if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) { + (void)ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); + } + goto loser; + } } /* Build up final list of required elements */ - ss->sec.ci.elements = CIS_HAVE_MASTER_KEY; + ss->sec.ci.elements = CIS_HAVE_MASTER_KEY; ss->sec.ci.requiredElements = needed; - if (!sidHit) { - /* verify the server's certificate. if sidHit, don't check signatures */ - rv = (* ss->authCertificate)(ss->authCertificateArg, ss->fd, - (PRBool)(!sidHit), PR_FALSE); - if (rv) { - if (ss->handleBadCert) { - rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); - if ( rv ) { - if ( rv == SECWouldBlock ) { - SSL_DBG(("%d: SSL[%d]: SSL2 bad cert handler returned " - "SECWouldBlock", SSL_GETPID(), ss->fd)); - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - rv = SECFailure; - } else { - /* cert is bad */ - SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d", - SSL_GETPID(), ss->fd, PORT_GetError())); - } - goto loser; - } - /* cert is good */ - } else { - SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d", - SSL_GETPID(), ss->fd, PORT_GetError())); - goto loser; - } + if (!sidHit) { + /* verify the server's certificate. if sidHit, don't check signatures */ + rv = (*ss->authCertificate)(ss->authCertificateArg, ss->fd, + (PRBool)(!sidHit), PR_FALSE); + if (rv) { + if (ss->handleBadCert) { + rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); + if (rv) { + if (rv == SECWouldBlock) { + SSL_DBG(("%d: SSL[%d]: SSL2 bad cert handler returned " + "SECWouldBlock", + SSL_GETPID(), ss->fd)); + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); + rv = SECFailure; + } + else { + /* cert is bad */ + SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d", + SSL_GETPID(), ss->fd, PORT_GetError())); + } + goto loser; + } + /* cert is good */ + } + else { + SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d", + SSL_GETPID(), ss->fd, PORT_GetError())); + goto loser; + } + } } - } /* ** At this point we have a completed session key and our session ** cipher is setup and ready to go. Switch to encrypted write routine @@ -2915,29 +2941,29 @@ ssl2_HandleServerHelloMessage(sslSocket *ss) ssl2_UseEncryptedSendFunc(ss); rv = ssl2_TryToFinish(ss); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; ss->gs.recordLen = 0; ssl_ReleaseRecvBufLock(ss); if (ss->handshake == 0) { - return SECSuccess; + return SECSuccess; } SSL_TRC(5, ("%d: SSL[%d]: got server-hello, required=0x%d got=0x%x", - SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements, - ss->sec.ci.elements)); - ss->handshake = ssl_GatherRecord1stHandshake; + SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements, + ss->sec.ci.elements)); + ss->handshake = ssl_GatherRecord1stHandshake; ss->nextHandshake = ssl2_HandleVerifyMessage; return SECSuccess; - bad_server: +bad_server: PORT_SetError(SSL_ERROR_BAD_SERVER); - /* FALL THROUGH */ +/* FALL THROUGH */ - loser: +loser: ssl_ReleaseRecvBufLock(ss); return SECFailure; } @@ -2948,27 +2974,27 @@ ssl2_HandleServerHelloMessage(sslSocket *ss) SECStatus ssl2_BeginClientHandshake(sslSocket *ss) { - sslSessionID *sid; - PRUint8 *msg; - PRUint8 *cp; - PRUint8 *localCipherSpecs = NULL; - unsigned int localCipherSize; - unsigned int i; - int sendLen, sidLen = 0; - SECStatus rv; - TLSExtensionData *xtnData; + sslSessionID *sid; + PRUint8 *msg; + PRUint8 *cp; + PRUint8 *localCipherSpecs = NULL; + unsigned int localCipherSize; + unsigned int i; + int sendLen, sidLen = 0; + SECStatus rv; + TLSExtensionData *xtnData; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ss->sec.isServer = 0; + ss->sec.isServer = 0; ss->sec.sendSequence = 0; - ss->sec.rcvSequence = 0; + ss->sec.rcvSequence = 0; ssl_ChooseSessionIDProcs(&ss->sec); if (!ss->cipherSpecs) { - rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess) - goto loser; + rv = ssl2_ConstructCipherSpecs(ss); + if (rv != SECSuccess) + goto loser; } /* count the SSL2 and SSL3 enabled ciphers. @@ -2976,7 +3002,7 @@ ssl2_BeginClientHandshake(sslSocket *ss) */ rv = ssl2_CheckConfigSanity(ss); if (rv != SECSuccess) - goto loser; + goto loser; /* Get peer name of server */ rv = ssl_GetPeerInfo(ss); @@ -2990,14 +3016,14 @@ ssl2_BeginClientHandshake(sslSocket *ss) */ if (PR_GetError() == PR_NOT_CONNECTED_ERROR) { char dummy; - (void) PR_Write(ss->fd->lower, &dummy, 0); + (void)PR_Write(ss->fd->lower, &dummy, 0); rv = ssl_GetPeerInfo(ss); if (rv < 0) { goto loser; } } #else - goto loser; + goto loser; #endif } @@ -3005,125 +3031,126 @@ ssl2_BeginClientHandshake(sslSocket *ss) /* Try to find server in our session-id cache */ if (ss->opt.noCache) { - sid = NULL; - } else { - sid = ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, - ss->url); + sid = NULL; } - while (sid) { /* this isn't really a loop */ - PRBool sidVersionEnabled = - (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) && - sid->version >= ss->vrange.min && - sid->version <= ss->vrange.max) || - (sid->version < SSL_LIBRARY_VERSION_3_0 && ss->opt.enableSSL2); + else { + sid = ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, + ss->url); + } + while (sid) { /* this isn't really a loop */ + PRBool sidVersionEnabled = + (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) && + sid->version >= ss->vrange.min && + sid->version <= ss->vrange.max) || + (sid->version < SSL_LIBRARY_VERSION_3_0 && ss->opt.enableSSL2); - /* if we're not doing this SID's protocol any more, drop it. */ - if (!sidVersionEnabled) { - if (ss->sec.uncache) - ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; - break; - } - if (sid->version < SSL_LIBRARY_VERSION_3_0) { - /* If the cipher in this sid is not enabled, drop it. */ - for (i = 0; i < ss->sizeCipherSpecs; i += 3) { - if (ss->cipherSpecs[i] == sid->u.ssl2.cipherType) - break; - } - if (i >= ss->sizeCipherSpecs) { - if (ss->sec.uncache) - ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; - break; - } - } - sidLen = sizeof(sid->u.ssl2.sessionID); - PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl2.sessionID, - sidLen)); - ss->version = sid->version; - PORT_Assert(!ss->sec.localCert); - if (ss->sec.localCert) { - CERT_DestroyCertificate(ss->sec.localCert); - } - ss->sec.localCert = CERT_DupCertificate(sid->localCert); - break; /* this isn't really a loop */ - } + /* if we're not doing this SID's protocol any more, drop it. */ + if (!sidVersionEnabled) { + if (ss->sec.uncache) + ss->sec.uncache(sid); + ssl_FreeSID(sid); + sid = NULL; + break; + } + if (sid->version < SSL_LIBRARY_VERSION_3_0) { + /* If the cipher in this sid is not enabled, drop it. */ + for (i = 0; i < ss->sizeCipherSpecs; i += 3) { + if (ss->cipherSpecs[i] == sid->u.ssl2.cipherType) + break; + } + if (i >= ss->sizeCipherSpecs) { + if (ss->sec.uncache) + ss->sec.uncache(sid); + ssl_FreeSID(sid); + sid = NULL; + break; + } + } + sidLen = sizeof(sid->u.ssl2.sessionID); + PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl2.sessionID, + sidLen)); + ss->version = sid->version; + PORT_Assert(!ss->sec.localCert); + if (ss->sec.localCert) { + CERT_DestroyCertificate(ss->sec.localCert); + } + ss->sec.localCert = CERT_DupCertificate(sid->localCert); + break; /* this isn't really a loop */ + } if (!sid) { - sidLen = 0; - sid = PORT_ZNew(sslSessionID); - if (!sid) { - goto loser; - } - sid->references = 1; - sid->cached = never_cached; - sid->addr = ss->sec.ci.peer; - sid->port = ss->sec.ci.port; - if (ss->peerID != NULL) { - sid->peerID = PORT_Strdup(ss->peerID); - } - if (ss->url != NULL) { - sid->urlSvrName = PORT_Strdup(ss->url); - } + sidLen = 0; + sid = PORT_ZNew(sslSessionID); + if (!sid) { + goto loser; + } + sid->references = 1; + sid->cached = never_cached; + sid->addr = ss->sec.ci.peer; + sid->port = ss->sec.ci.port; + if (ss->peerID != NULL) { + sid->peerID = PORT_Strdup(ss->peerID); + } + if (ss->url != NULL) { + sid->urlSvrName = PORT_Strdup(ss->url); + } } ss->sec.ci.sid = sid; PORT_Assert(sid != NULL); if ((sid->version >= SSL_LIBRARY_VERSION_3_0 || !ss->opt.v2CompatibleHello) && - !SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - ss->gs.state = GS_INIT; - ss->handshake = ssl_GatherRecord1stHandshake; + !SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { + ss->gs.state = GS_INIT; + ss->handshake = ssl_GatherRecord1stHandshake; - /* ssl3_SendClientHello will override this if it succeeds. */ - ss->version = SSL_LIBRARY_VERSION_3_0; + /* ssl3_SendClientHello will override this if it succeeds. */ + ss->version = SSL_LIBRARY_VERSION_3_0; - ssl_GetSSL3HandshakeLock(ss); - ssl_GetXmitBufLock(ss); - rv = ssl3_SendClientHello(ss, PR_FALSE); - ssl_ReleaseXmitBufLock(ss); - ssl_ReleaseSSL3HandshakeLock(ss); + ssl_GetSSL3HandshakeLock(ss); + ssl_GetXmitBufLock(ss); + rv = ssl3_SendClientHello(ss, PR_FALSE); + ssl_ReleaseXmitBufLock(ss); + ssl_ReleaseSSL3HandshakeLock(ss); - return rv; + return rv; } #ifndef NSS_DISABLE_ECC /* ensure we don't neogtiate ECC cipher suites with SSL2 hello */ ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ if (ss->cipherSpecs != NULL) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; + PORT_Free(ss->cipherSpecs); + ss->cipherSpecs = NULL; + ss->sizeCipherSpecs = 0; } #endif /* NSS_DISABLE_ECC */ if (!ss->cipherSpecs) { rv = ssl2_ConstructCipherSpecs(ss); - if (rv < 0) { - return rv; - } + if (rv < 0) { + return rv; + } } localCipherSpecs = ss->cipherSpecs; - localCipherSize = ss->sizeCipherSpecs; + localCipherSize = ss->sizeCipherSpecs; /* Add 3 for SCSV */ sendLen = SSL_HL_CLIENT_HELLO_HBYTES + localCipherSize + 3 + sidLen + - SSL_CHALLENGE_BYTES; + SSL_CHALLENGE_BYTES; /* Generate challenge bytes for server */ PK11_GenerateRandom(ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES); - ssl_GetXmitBufLock(ss); /***************************************/ + ssl_GetXmitBufLock(ss); /***************************************/ rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv) - goto unlock_loser; + if (rv) + goto unlock_loser; /* Construct client-hello message */ cp = msg = ss->sec.ci.sendBuf.buf; msg[0] = SSL_MT_CLIENT_HELLO; - ss->clientHelloVersion = SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) ? - SSL_LIBRARY_VERSION_2 : ss->vrange.max; + ss->clientHelloVersion = SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) ? SSL_LIBRARY_VERSION_2 + : ss->vrange.max; msg[1] = MSB(ss->clientHelloVersion); msg[2] = LSB(ss->clientHelloVersion); @@ -3148,8 +3175,8 @@ ssl2_BeginClientHandshake(sslSocket *ss) cp[2] = 0xff; cp += 3; if (sidLen) { - PORT_Memcpy(cp, sid->u.ssl2.sessionID, sidLen); - cp += sidLen; + PORT_Memcpy(cp, sid->u.ssl2.sessionID, sidLen); + cp += sidLen; } PORT_Memcpy(cp, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES); @@ -3158,15 +3185,15 @@ ssl2_BeginClientHandshake(sslSocket *ss) ss->handshakeBegun = 1; rv = (*ss->sec.send)(ss, msg, sendLen, 0); - ssl_ReleaseXmitBufLock(ss); /***************************************/ + ssl_ReleaseXmitBufLock(ss); /***************************************/ if (rv < 0) { - goto loser; + goto loser; } rv = ssl3_StartHandshakeHash(ss, msg, sendLen); if (rv < 0) { - goto loser; + goto loser; } /* @@ -3182,7 +3209,7 @@ ssl2_BeginClientHandshake(sslSocket *ss) ss->gs.recordLen = 0; ssl_ReleaseRecvBufLock(ss); - ss->handshake = ssl_GatherRecord1stHandshake; + ss->handshake = ssl_GatherRecord1stHandshake; ss->nextHandshake = ssl2_HandleServerHelloMessage; return SECSuccess; @@ -3194,86 +3221,88 @@ loser: /************************************************************************/ -/* Handle the CLIENT-MASTER-KEY message. +/* Handle the CLIENT-MASTER-KEY message. ** Acquires and releases RecvBufLock. -** Called from ssl2_HandleClientHelloMessage(). +** Called from ssl2_HandleClientHelloMessage(). */ static SECStatus ssl2_HandleClientSessionKeyMessage(sslSocket *ss) { - PRUint8 * data; - unsigned int caLen; - unsigned int ckLen; - unsigned int ekLen; - unsigned int keyBits; - int cipher; - SECStatus rv; - + PRUint8 *data; + unsigned int caLen; + unsigned int ckLen; + unsigned int ekLen; + unsigned int keyBits; + int cipher; + SECStatus rv; ssl_GetRecvBufLock(ss); data = ss->gs.buf.buf + ss->gs.recordOffset; DUMP_MSG(29, (ss, data, ss->gs.recordLen)); - if ((ss->gs.recordLen < SSL_HL_CLIENT_MASTER_KEY_HBYTES) - || (data[0] != SSL_MT_CLIENT_MASTER_KEY)) { - goto bad_client; + if ((ss->gs.recordLen < SSL_HL_CLIENT_MASTER_KEY_HBYTES) || + (data[0] != SSL_MT_CLIENT_MASTER_KEY)) { + goto bad_client; } - cipher = data[1]; + cipher = data[1]; keyBits = (data[2] << 8) | data[3]; - ckLen = (data[4] << 8) | data[5]; - ekLen = (data[6] << 8) | data[7]; - caLen = (data[8] << 8) | data[9]; + ckLen = (data[4] << 8) | data[5]; + ekLen = (data[6] << 8) | data[7]; + caLen = (data[8] << 8) | data[9]; SSL_TRC(5, ("%d: SSL[%d]: session-key, cipher=%d keyBits=%d ckLen=%d ekLen=%d caLen=%d", - SSL_GETPID(), ss->fd, cipher, keyBits, ckLen, ekLen, caLen)); + SSL_GETPID(), ss->fd, cipher, keyBits, ckLen, ekLen, caLen)); - if (ss->gs.recordLen < - SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen + caLen) { - SSL_DBG(("%d: SSL[%d]: protocol size mismatch dataLen=%d", - SSL_GETPID(), ss->fd, ss->gs.recordLen)); - goto bad_client; + if (ss->gs.recordLen < + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen + caLen) { + SSL_DBG(("%d: SSL[%d]: protocol size mismatch dataLen=%d", + SSL_GETPID(), ss->fd, ss->gs.recordLen)); + goto bad_client; } /* Use info from client to setup session key */ rv = ssl2_ServerSetupSessionCypher(ss, cipher, keyBits, - data + SSL_HL_CLIENT_MASTER_KEY_HBYTES, ckLen, - data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen, ekLen, - data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen, caLen); - ss->gs.recordLen = 0; /* we're done with this record. */ + data + SSL_HL_CLIENT_MASTER_KEY_HBYTES, + ckLen, + data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen, + ekLen, + data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen, + caLen); + ss->gs.recordLen = 0; /* we're done with this record. */ ssl_ReleaseRecvBufLock(ss); if (rv != SECSuccess) { - goto loser; + goto loser; } ss->sec.ci.elements |= CIS_HAVE_MASTER_KEY; ssl2_UseEncryptedSendFunc(ss); /* Send server verify message now that keys are established */ rv = ssl2_SendServerVerifyMessage(ss); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; rv = ssl2_TryToFinish(ss); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; if (ss->handshake == 0) { - return SECSuccess; + return SECSuccess; } SSL_TRC(5, ("%d: SSL[%d]: server: waiting for elements=0x%d", - SSL_GETPID(), ss->fd, - ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleMessage; + SSL_GETPID(), ss->fd, + ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); + ss->handshake = ssl_GatherRecord1stHandshake; + ss->nextHandshake = ssl2_HandleMessage; return ssl2_TriggerNextMessage(ss); bad_client: ssl_ReleaseRecvBufLock(ss); PORT_SetError(SSL_ERROR_BAD_CLIENT); - /* FALLTHROUGH */ +/* FALLTHROUGH */ loser: return SECFailure; @@ -3287,75 +3316,74 @@ loser: SECStatus ssl2_HandleClientHelloMessage(sslSocket *ss) { - sslSessionID *sid; - sslServerCerts * sc; + sslSessionID *sid; + sslServerCerts *sc; CERTCertificate *serverCert; - PRUint8 *msg; - PRUint8 *data; - PRUint8 *cs; - PRUint8 *sd; - PRUint8 *cert = NULL; - PRUint8 *challenge; - unsigned int challengeLen; - SECStatus rv; - int csLen; - int sendLen; - int sdLen; - int certLen; - int pid; - int sent; - int gotXmitBufLock = 0; + PRUint8 *msg; + PRUint8 *data; + PRUint8 *cs; + PRUint8 *sd; + PRUint8 *cert = NULL; + PRUint8 *challenge; + unsigned int challengeLen; + SECStatus rv; + int csLen; + int sendLen; + int sdLen; + int certLen; + int pid; + int sent; + int gotXmitBufLock = 0; #if defined(SOLARIS) && defined(i386) volatile PRUint8 hit; #else - int hit; + int hit; #endif - PRUint8 csImpl[sizeof implementedCipherSuites]; + PRUint8 csImpl[sizeof implementedCipherSuites]; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); sc = ss->serverCerts + kt_rsa; serverCert = sc->serverCert; ssl_GetRecvBufLock(ss); - data = ss->gs.buf.buf + ss->gs.recordOffset; DUMP_MSG(29, (ss, data, ss->gs.recordLen)); /* Make sure first message has some data and is the client hello message */ - if ((ss->gs.recordLen < SSL_HL_CLIENT_HELLO_HBYTES) - || (data[0] != SSL_MT_CLIENT_HELLO)) { - goto bad_client; + if ((ss->gs.recordLen < SSL_HL_CLIENT_HELLO_HBYTES) || + (data[0] != SSL_MT_CLIENT_HELLO)) { + goto bad_client; } /* Get peer name of client */ rv = ssl_GetPeerInfo(ss); if (rv != SECSuccess) { - goto loser; + goto loser; } /* Examine version information */ /* * See if this might be a V2 client hello asking to use the V3 protocol */ - if ((data[0] == SSL_MT_CLIENT_HELLO) && - (data[1] >= MSB(SSL_LIBRARY_VERSION_3_0)) && - !SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - rv = ssl3_HandleV2ClientHello(ss, data, ss->gs.recordLen); - if (rv != SECFailure) { /* Success */ - ss->handshake = NULL; - ss->nextHandshake = ssl_GatherRecord1stHandshake; - ss->securityHandshake = NULL; - ss->gs.state = GS_INIT; + if ((data[0] == SSL_MT_CLIENT_HELLO) && + (data[1] >= MSB(SSL_LIBRARY_VERSION_3_0)) && + !SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { + rv = ssl3_HandleV2ClientHello(ss, data, ss->gs.recordLen); + if (rv != SECFailure) { /* Success */ + ss->handshake = NULL; + ss->nextHandshake = ssl_GatherRecord1stHandshake; + ss->securityHandshake = NULL; + ss->gs.state = GS_INIT; - /* ssl3_HandleV3ClientHello has set ss->version, - ** and has gotten us a brand new sid. - */ - ss->sec.ci.sid->version = ss->version; - } - ssl_ReleaseRecvBufLock(ss); - return rv; + /* ssl3_HandleV3ClientHello has set ss->version, + ** and has gotten us a brand new sid. + */ + ss->sec.ci.sid->version = ss->version; + } + ssl_ReleaseRecvBufLock(ss); + return rv; } /* Previously, there was a test here to see if SSL2 was enabled. ** If not, an error code was set, and SECFailure was returned, @@ -3372,64 +3400,65 @@ ssl2_HandleClientHelloMessage(sslSocket *ss) /* If some client thinks ssl v2 is 2.0 instead of 0.2, we'll allow it. */ if (ss->version >= SSL_LIBRARY_VERSION_3_0) { - ss->version = SSL_LIBRARY_VERSION_2; + ss->version = SSL_LIBRARY_VERSION_2; } - - csLen = (data[3] << 8) | data[4]; - sdLen = (data[5] << 8) | data[6]; + + csLen = (data[3] << 8) | data[4]; + sdLen = (data[5] << 8) | data[6]; challengeLen = (data[7] << 8) | data[8]; - cs = data + SSL_HL_CLIENT_HELLO_HBYTES; - sd = cs + csLen; - challenge = sd + sdLen; + cs = data + SSL_HL_CLIENT_HELLO_HBYTES; + sd = cs + csLen; + challenge = sd + sdLen; PRINT_BUF(7, (ss, "server, client session-id value:", sd, sdLen)); - if (!csLen || (csLen % 3) != 0 || + if (!csLen || (csLen % 3) != 0 || (sdLen != 0 && sdLen != SSL2_SESSIONID_BYTES) || - challengeLen < SSL_MIN_CHALLENGE_BYTES || - challengeLen > SSL_MAX_CHALLENGE_BYTES || - (unsigned)ss->gs.recordLen != + challengeLen < SSL_MIN_CHALLENGE_BYTES || + challengeLen > SSL_MAX_CHALLENGE_BYTES || + (unsigned)ss->gs.recordLen != SSL_HL_CLIENT_HELLO_HBYTES + csLen + sdLen + challengeLen) { - SSL_DBG(("%d: SSL[%d]: bad client hello message, len=%d should=%d", - SSL_GETPID(), ss->fd, ss->gs.recordLen, - SSL_HL_CLIENT_HELLO_HBYTES+csLen+sdLen+challengeLen)); - goto bad_client; + SSL_DBG(("%d: SSL[%d]: bad client hello message, len=%d should=%d", + SSL_GETPID(), ss->fd, ss->gs.recordLen, + SSL_HL_CLIENT_HELLO_HBYTES + csLen + sdLen + challengeLen)); + goto bad_client; } SSL_TRC(3, ("%d: SSL[%d]: client version is %x", - SSL_GETPID(), ss->fd, ss->version)); + SSL_GETPID(), ss->fd, ss->version)); if (ss->version != SSL_LIBRARY_VERSION_2) { - if (ss->version > SSL_LIBRARY_VERSION_2) { - /* - ** Newer client than us. Things are ok because new clients - ** are required to be backwards compatible with old servers. - ** Change version number to our version number so that client - ** knows whats up. - */ - ss->version = SSL_LIBRARY_VERSION_2; - } else { - SSL_TRC(1, ("%d: SSL[%d]: client version is %x (we are %x)", - SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2)); - PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); - goto loser; - } + if (ss->version > SSL_LIBRARY_VERSION_2) { + /* + ** Newer client than us. Things are ok because new clients + ** are required to be backwards compatible with old servers. + ** Change version number to our version number so that client + ** knows whats up. + */ + ss->version = SSL_LIBRARY_VERSION_2; + } + else { + SSL_TRC(1, ("%d: SSL[%d]: client version is %x (we are %x)", + SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2)); + PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); + goto loser; + } } /* Qualify cipher specs before returning them to client */ csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen); if (csLen == 0) { - /* no overlap, send client our list of supported SSL v2 ciphers. */ - cs = csImpl; - csLen = sizeof implementedCipherSuites; - PORT_Memcpy(cs, implementedCipherSuites, csLen); - csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen); - if (csLen == 0) { - /* We don't support any SSL v2 ciphers! */ - ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS); - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - goto loser; - } - /* Since this handhsake is going to fail, don't cache it. */ - ss->opt.noCache = 1; + /* no overlap, send client our list of supported SSL v2 ciphers. */ + cs = csImpl; + csLen = sizeof implementedCipherSuites; + PORT_Memcpy(cs, implementedCipherSuites, csLen); + csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen); + if (csLen == 0) { + /* We don't support any SSL v2 ciphers! */ + ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS); + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + goto loser; + } + /* Since this handhsake is going to fail, don't cache it. */ + ss->opt.noCache = 1; } /* Squirrel away the challenge for later */ @@ -3438,104 +3467,107 @@ ssl2_HandleClientHelloMessage(sslSocket *ss) /* Examine message and see if session-id is good */ ss->sec.ci.elements = 0; if (sdLen > 0 && !ss->opt.noCache) { - SSL_TRC(7, ("%d: SSL[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x", - SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], - ss->sec.ci.peer.pr_s6_addr32[1], - ss->sec.ci.peer.pr_s6_addr32[2], - ss->sec.ci.peer.pr_s6_addr32[3])); - sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sd, sdLen, ss->dbHandle); - } else { - sid = NULL; + SSL_TRC(7, ("%d: SSL[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x", + SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], + ss->sec.ci.peer.pr_s6_addr32[1], + ss->sec.ci.peer.pr_s6_addr32[2], + ss->sec.ci.peer.pr_s6_addr32[3])); + sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sd, sdLen, ss->dbHandle); + } + else { + sid = NULL; } if (sid) { - /* Got a good session-id. Short cut! */ - SSL_TRC(1, ("%d: SSL[%d]: server, using session-id for 0x%08x (age=%d)", - SSL_GETPID(), ss->fd, ss->sec.ci.peer, - ssl_Time() - sid->creationTime)); - PRINT_BUF(1, (ss, "session-id value:", sd, sdLen)); - ss->sec.ci.sid = sid; - ss->sec.ci.elements = CIS_HAVE_MASTER_KEY; - hit = 1; - certLen = 0; - csLen = 0; + /* Got a good session-id. Short cut! */ + SSL_TRC(1, ("%d: SSL[%d]: server, using session-id for 0x%08x (age=%d)", + SSL_GETPID(), ss->fd, ss->sec.ci.peer, + ssl_Time() - sid->creationTime)); + PRINT_BUF(1, (ss, "session-id value:", sd, sdLen)); + ss->sec.ci.sid = sid; + ss->sec.ci.elements = CIS_HAVE_MASTER_KEY; + hit = 1; + certLen = 0; + csLen = 0; ss->sec.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; + ss->sec.authKeyBits = sid->authKeyBits; + ss->sec.keaType = sid->keaType; + ss->sec.keaKeyBits = sid->keaKeyBits; - rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE); - if (rv != SECSuccess) { - goto loser; - } - } else { - SECItem * derCert = &serverCert->derCert; + rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE); + if (rv != SECSuccess) { + goto loser; + } + } + else { + SECItem *derCert = &serverCert->derCert; - SSL_TRC(7, ("%d: SSL[%d]: server, lookup nonce missed", - SSL_GETPID(), ss->fd)); - if (!serverCert) { - SET_ERROR_CODE - goto loser; - } - hit = 0; - sid = PORT_ZNew(sslSessionID); - if (!sid) { - goto loser; - } - sid->references = 1; - sid->addr = ss->sec.ci.peer; - sid->port = ss->sec.ci.port; + SSL_TRC(7, ("%d: SSL[%d]: server, lookup nonce missed", + SSL_GETPID(), ss->fd)); + if (!serverCert) { + SET_ERROR_CODE + goto loser; + } + hit = 0; + sid = PORT_ZNew(sslSessionID); + if (!sid) { + goto loser; + } + sid->references = 1; + sid->addr = ss->sec.ci.peer; + sid->port = ss->sec.ci.port; - /* Invent a session-id */ - ss->sec.ci.sid = sid; - PK11_GenerateRandom(sid->u.ssl2.sessionID+2, SSL2_SESSIONID_BYTES-2); + /* Invent a session-id */ + ss->sec.ci.sid = sid; + PK11_GenerateRandom(sid->u.ssl2.sessionID + 2, SSL2_SESSIONID_BYTES - 2); - pid = SSL_GETPID(); - sid->u.ssl2.sessionID[0] = MSB(pid); - sid->u.ssl2.sessionID[1] = LSB(pid); - cert = derCert->data; - certLen = derCert->len; + pid = SSL_GETPID(); + sid->u.ssl2.sessionID[0] = MSB(pid); + sid->u.ssl2.sessionID[1] = LSB(pid); + cert = derCert->data; + certLen = derCert->len; - /* pretend that server sids remember the local cert. */ - PORT_Assert(!sid->localCert); - if (sid->localCert) { - CERT_DestroyCertificate(sid->localCert); - } - sid->localCert = CERT_DupCertificate(serverCert); + /* pretend that server sids remember the local cert. */ + PORT_Assert(!sid->localCert); + if (sid->localCert) { + CERT_DestroyCertificate(sid->localCert); + } + sid->localCert = CERT_DupCertificate(serverCert); - ss->sec.authAlgorithm = ssl_sign_rsa; - ss->sec.keaType = ssl_kea_rsa; - ss->sec.keaKeyBits = \ - ss->sec.authKeyBits = ss->serverCerts[kt_rsa].serverKeyBits; + ss->sec.authAlgorithm = ssl_sign_rsa; + ss->sec.keaType = ssl_kea_rsa; + ss->sec.keaKeyBits = + ss->sec.authKeyBits = ss->serverCerts[kt_rsa].serverKeyBits; } /* server sids don't remember the local cert, so whether we found ** a sid or not, just "remember" we used the rsa server cert. */ if (ss->sec.localCert) { - CERT_DestroyCertificate(ss->sec.localCert); + CERT_DestroyCertificate(ss->sec.localCert); } - ss->sec.localCert = CERT_DupCertificate(serverCert); + ss->sec.localCert = CERT_DupCertificate(serverCert); /* Build up final list of required elements */ ss->sec.ci.requiredElements = CIS_HAVE_MASTER_KEY | CIS_HAVE_FINISHED; if (ss->opt.requestCertificate) { - ss->sec.ci.requiredElements |= CIS_HAVE_CERTIFICATE; + ss->sec.ci.requiredElements |= CIS_HAVE_CERTIFICATE; } ss->sec.ci.sentElements = 0; /* Send hello message back to client */ - sendLen = SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen - + SSL_CONNECTIONID_BYTES; + sendLen = SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen + + SSL_CONNECTIONID_BYTES; - ssl_GetXmitBufLock(ss); gotXmitBufLock = 1; + ssl_GetXmitBufLock(ss); + gotXmitBufLock = 1; rv = ssl2_GetSendBuffer(ss, sendLen); if (rv != SECSuccess) { - goto loser; + goto loser; } SSL_TRC(3, ("%d: SSL[%d]: sending server-hello (%d)", - SSL_GETPID(), ss->fd, sendLen)); + SSL_GETPID(), ss->fd, sendLen)); msg = ss->sec.ci.sendBuf.buf; msg[0] = SSL_MT_SERVER_HELLO; @@ -3550,12 +3582,12 @@ ssl2_HandleClientHelloMessage(sslSocket *ss) msg[9] = MSB(SSL_CONNECTIONID_BYTES); msg[10] = LSB(SSL_CONNECTIONID_BYTES); if (certLen) { - PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES, cert, certLen); + PORT_Memcpy(msg + SSL_HL_SERVER_HELLO_HBYTES, cert, certLen); } if (csLen) { - PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen, cs, csLen); + PORT_Memcpy(msg + SSL_HL_SERVER_HELLO_HBYTES + certLen, cs, csLen); } - PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen+csLen, + PORT_Memcpy(msg + SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen, ss->sec.ci.connectionID, SSL_CONNECTIONID_BYTES); DUMP_MSG(29, (ss, msg, sendLen)); @@ -3563,40 +3595,42 @@ ssl2_HandleClientHelloMessage(sslSocket *ss) ss->handshakeBegun = 1; sent = (*ss->sec.send)(ss, msg, sendLen, 0); if (sent < 0) { - goto loser; + goto loser; } - ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0; + ssl_ReleaseXmitBufLock(ss); + gotXmitBufLock = 0; ss->gs.recordLen = 0; ss->handshake = ssl_GatherRecord1stHandshake; if (hit) { - /* Old SID Session key is good. Go encrypted */ - ssl2_UseEncryptedSendFunc(ss); + /* Old SID Session key is good. Go encrypted */ + ssl2_UseEncryptedSendFunc(ss); - /* Send server verify message now that keys are established */ - rv = ssl2_SendServerVerifyMessage(ss); - if (rv != SECSuccess) - goto loser; + /* Send server verify message now that keys are established */ + rv = ssl2_SendServerVerifyMessage(ss); + if (rv != SECSuccess) + goto loser; - ss->nextHandshake = ssl2_HandleMessage; - ssl_ReleaseRecvBufLock(ss); - rv = ssl2_TriggerNextMessage(ss); - return rv; + ss->nextHandshake = ssl2_HandleMessage; + ssl_ReleaseRecvBufLock(ss); + rv = ssl2_TriggerNextMessage(ss); + return rv; } ss->nextHandshake = ssl2_HandleClientSessionKeyMessage; ssl_ReleaseRecvBufLock(ss); return SECSuccess; - bad_client: +bad_client: PORT_SetError(SSL_ERROR_BAD_CLIENT); - /* FALLTHROUGH */ +/* FALLTHROUGH */ - loser: +loser: if (gotXmitBufLock) { - ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0; + ssl_ReleaseXmitBufLock(ss); + gotXmitBufLock = 0; } SSL_TRC(10, ("%d: SSL[%d]: server, wait for client-hello lossage", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); ssl_ReleaseRecvBufLock(ss); return SECFailure; } @@ -3604,8 +3638,8 @@ ssl2_HandleClientHelloMessage(sslSocket *ss) SECStatus ssl2_BeginServerHandshake(sslSocket *ss) { - SECStatus rv; - sslServerCerts * rsaAuth = ss->serverCerts + kt_rsa; + SECStatus rv; + sslServerCerts *rsaAuth = ss->serverCerts + kt_rsa; ss->sec.isServer = 1; ssl_ChooseSessionIDProcs(&ss->sec); @@ -3613,15 +3647,15 @@ ssl2_BeginServerHandshake(sslSocket *ss) ss->sec.rcvSequence = 0; /* don't turn on SSL2 if we don't have an RSA key and cert */ - if (!rsaAuth->serverKeyPair || !rsaAuth->SERVERKEY || + if (!rsaAuth->serverKeyPair || !rsaAuth->SERVERKEY || !rsaAuth->serverCert) { - ss->opt.enableSSL2 = PR_FALSE; + ss->opt.enableSSL2 = PR_FALSE; } if (!ss->cipherSpecs) { - rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess) - goto loser; + rv = ssl2_ConstructCipherSpecs(ss); + if (rv != SECSuccess) + goto loser; } /* count the SSL2 and SSL3 enabled ciphers. @@ -3629,18 +3663,18 @@ ssl2_BeginServerHandshake(sslSocket *ss) */ rv = ssl2_CheckConfigSanity(ss); if (rv != SECSuccess) - goto loser; + goto loser; /* ** Generate connection-id. Always do this, even if things fail ** immediately. This way the random number generator is always ** rolling around, every time we get a connection. */ - PK11_GenerateRandom(ss->sec.ci.connectionID, + PK11_GenerateRandom(ss->sec.ci.connectionID, sizeof(ss->sec.ci.connectionID)); ss->gs.recordLen = 0; - ss->handshake = ssl_GatherRecord1stHandshake; + ss->handshake = ssl_GatherRecord1stHandshake; ss->nextHandshake = ssl2_HandleClientHelloMessage; return SECSuccess; @@ -3649,7 +3683,7 @@ loser: } /* This function doesn't really belong in this file. -** It's here to keep AIX compilers from optimizing it away, +** It's here to keep AIX compilers from optimizing it away, ** and not including it in the DSO. */ diff --git a/security/nss/lib/ssl/ssldef.c b/security/nss/lib/ssl/ssldef.c index cc3ecc8bf142..385ad5edf204 100644 --- a/security/nss/lib/ssl/ssldef.c +++ b/security/nss/lib/ssl/ssldef.c @@ -10,14 +10,18 @@ #include "sslimpl.h" #if defined(WIN32) -#define MAP_ERROR(from,to) if (err == from) { PORT_SetError(to); } -#define DEFINE_ERROR PRErrorCode err = PR_GetError(); +#define MAP_ERROR(from, to) \ + if (err == from) { \ + PORT_SetError(to); \ + } +#define DEFINE_ERROR PRErrorCode err = PR_GetError(); #else -#define MAP_ERROR(from,to) +#define MAP_ERROR(from, to) #define DEFINE_ERROR #endif -int ssl_DefConnect(sslSocket *ss, const PRNetAddr *sa) +int +ssl_DefConnect(sslSocket *ss, const PRNetAddr *sa) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -26,7 +30,8 @@ int ssl_DefConnect(sslSocket *ss, const PRNetAddr *sa) return rv; } -int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr) +int +ssl_DefBind(sslSocket *ss, const PRNetAddr *addr) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -35,7 +40,8 @@ int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr) return rv; } -int ssl_DefListen(sslSocket *ss, int backlog) +int +ssl_DefListen(sslSocket *ss, int backlog) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -44,7 +50,8 @@ int ssl_DefListen(sslSocket *ss, int backlog) return rv; } -int ssl_DefShutdown(sslSocket *ss, int how) +int +ssl_DefShutdown(sslSocket *ss, int how) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -53,19 +60,21 @@ int ssl_DefShutdown(sslSocket *ss, int how) return rv; } -int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags) +int +ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags) { PRFileDesc *lower = ss->fd->lower; int rv; rv = lower->methods->recv(lower, (void *)buf, len, flags, ss->rTimeout); if (rv < 0) { - DEFINE_ERROR - MAP_ERROR(PR_SOCKET_SHUTDOWN_ERROR, PR_CONNECT_RESET_ERROR) - } else if (rv > len) { - PORT_Assert(rv <= len); - PORT_SetError(PR_BUFFER_OVERFLOW_ERROR); - rv = SECFailure; + DEFINE_ERROR + MAP_ERROR(PR_SOCKET_SHUTDOWN_ERROR, PR_CONNECT_RESET_ERROR) + } + else if (rv > len) { + PORT_Assert(rv <= len); + PORT_SetError(PR_BUFFER_OVERFLOW_ERROR); + rv = SECFailure; } return rv; } @@ -73,87 +82,91 @@ int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags) /* Default (unencrypted) send. * For blocking sockets, always returns len or SECFailure, no short writes. * For non-blocking sockets: - * Returns positive count if any data was written, else returns SECFailure. + * Returns positive count if any data was written, else returns SECFailure. * Short writes may occur. Does not return SECWouldBlock. */ -int ssl_DefSend(sslSocket *ss, const unsigned char *buf, int len, int flags) +int +ssl_DefSend(sslSocket *ss, const unsigned char *buf, int len, int flags) { PRFileDesc *lower = ss->fd->lower; int sent = 0; #if NSS_DISABLE_NAGLE_DELAYS - /* Although this is overkill, we disable Nagle delays completely for + /* Although this is overkill, we disable Nagle delays completely for ** SSL sockets. */ if (ss->opt.useSecurity && !ss->delayDisabled) { - ssl_EnableNagleDelay(ss, PR_FALSE); /* ignore error */ - ss->delayDisabled = 1; + ssl_EnableNagleDelay(ss, PR_FALSE); /* ignore error */ + ss->delayDisabled = 1; } #endif do { - int rv = lower->methods->send(lower, (const void *)(buf + sent), - len - sent, flags, ss->wTimeout); - if (rv < 0) { - PRErrorCode err = PR_GetError(); - if (err == PR_WOULD_BLOCK_ERROR) { - ss->lastWriteBlocked = 1; - return sent ? sent : SECFailure; - } - ss->lastWriteBlocked = 0; - MAP_ERROR(PR_CONNECT_ABORTED_ERROR, PR_CONNECT_RESET_ERROR) - /* Loser */ - return rv; - } - sent += rv; - - if (IS_DTLS(ss) && (len > sent)) { - /* We got a partial write so just return it */ - return sent; - } + int rv = lower->methods->send(lower, (const void *)(buf + sent), + len - sent, flags, ss->wTimeout); + if (rv < 0) { + PRErrorCode err = PR_GetError(); + if (err == PR_WOULD_BLOCK_ERROR) { + ss->lastWriteBlocked = 1; + return sent ? sent : SECFailure; + } + ss->lastWriteBlocked = 0; + MAP_ERROR(PR_CONNECT_ABORTED_ERROR, PR_CONNECT_RESET_ERROR) + /* Loser */ + return rv; + } + sent += rv; + + if (IS_DTLS(ss) && (len > sent)) { + /* We got a partial write so just return it */ + return sent; + } } while (len > sent); ss->lastWriteBlocked = 0; return sent; } -int ssl_DefRead(sslSocket *ss, unsigned char *buf, int len) +int +ssl_DefRead(sslSocket *ss, unsigned char *buf, int len) { PRFileDesc *lower = ss->fd->lower; int rv; rv = lower->methods->read(lower, (void *)buf, len); if (rv < 0) { - DEFINE_ERROR - MAP_ERROR(PR_SOCKET_SHUTDOWN_ERROR, PR_CONNECT_RESET_ERROR) + DEFINE_ERROR + MAP_ERROR(PR_SOCKET_SHUTDOWN_ERROR, PR_CONNECT_RESET_ERROR) } return rv; } -int ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len) +int +ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len) { PRFileDesc *lower = ss->fd->lower; int sent = 0; do { - int rv = lower->methods->write(lower, (const void *)(buf + sent), - len - sent); - if (rv < 0) { - PRErrorCode err = PR_GetError(); - if (err == PR_WOULD_BLOCK_ERROR) { - ss->lastWriteBlocked = 1; - return sent ? sent : SECFailure; - } - ss->lastWriteBlocked = 0; - MAP_ERROR(PR_CONNECT_ABORTED_ERROR, PR_CONNECT_RESET_ERROR) - /* Loser */ - return rv; - } - sent += rv; + int rv = lower->methods->write(lower, (const void *)(buf + sent), + len - sent); + if (rv < 0) { + PRErrorCode err = PR_GetError(); + if (err == PR_WOULD_BLOCK_ERROR) { + ss->lastWriteBlocked = 1; + return sent ? sent : SECFailure; + } + ss->lastWriteBlocked = 0; + MAP_ERROR(PR_CONNECT_ABORTED_ERROR, PR_CONNECT_RESET_ERROR) + /* Loser */ + return rv; + } + sent += rv; } while (len > sent); ss->lastWriteBlocked = 0; return sent; } -int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name) +int +ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -162,7 +175,8 @@ int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name) return rv; } -int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name) +int +ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -171,22 +185,23 @@ int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name) return rv; } -int ssl_DefClose(sslSocket *ss) +int +ssl_DefClose(sslSocket *ss) { PRFileDesc *fd; PRFileDesc *popped; - int rv; + int rv; - fd = ss->fd; + fd = ss->fd; - /* First, remove the SSL layer PRFileDesc from the socket's stack, + /* First, remove the SSL layer PRFileDesc from the socket's stack, ** then invoke the SSL layer's PRFileDesc destructor. ** This must happen before the next layer down is closed. */ PORT_Assert(fd->higher == NULL); if (fd->higher) { - PORT_SetError(PR_BAD_DESCRIPTOR_ERROR); - return SECFailure; + PORT_SetError(PR_BAD_DESCRIPTOR_ERROR); + return SECFailure; } ss->fd = NULL; @@ -194,17 +209,17 @@ int ssl_DefClose(sslSocket *ss) ** the stack, and then remove the second one. This way, the address ** of the PRFileDesc on the top of the stack doesn't change. */ - popped = PR_PopIOLayer(fd, PR_TOP_IO_LAYER); + popped = PR_PopIOLayer(fd, PR_TOP_IO_LAYER); popped->dtor(popped); /* fd is now the PRFileDesc for the next layer down. - ** Now close the underlying socket. + ** Now close the underlying socket. */ rv = fd->methods->close(fd); ssl_FreeSocket(ss); SSL_TRC(5, ("%d: SSL[%d]: closing, rv=%d errno=%d", - SSL_GETPID(), fd, rv, PORT_GetError())); + SSL_GETPID(), fd, rv, PORT_GetError())); return rv; } diff --git a/security/nss/lib/ssl/sslenum.c b/security/nss/lib/ssl/sslenum.c index f69aed2df41b..d362b74ee042 100644 --- a/security/nss/lib/ssl/sslenum.c +++ b/security/nss/lib/ssl/sslenum.c @@ -50,6 +50,8 @@ const PRUint16 SSL_ImplementedCiphers[] = { #ifndef NSS_DISABLE_ECC TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA must appear before * TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA to work around bug 946147. */ @@ -66,6 +68,7 @@ const PRUint16 SSL_ImplementedCiphers[] = { #endif /* NSS_DISABLE_ECC */ TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, + TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, @@ -121,7 +124,7 @@ const PRUint16 SSL_ImplementedCiphers[] = { TLS_RSA_EXPORT_WITH_RC4_40_MD5, TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - /* ciphersuites with no encryption */ +/* ciphersuites with no encryption */ #ifndef NSS_DISABLE_ECC TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS_ECDHE_RSA_WITH_NULL_SHA, @@ -135,7 +138,7 @@ const PRUint16 SSL_ImplementedCiphers[] = { /* SSL2 cipher suites. */ SSL_EN_RC4_128_WITH_MD5, SSL_EN_RC2_128_CBC_WITH_MD5, - SSL_EN_DES_192_EDE3_CBC_WITH_MD5, /* actually 112, not 192 */ + SSL_EN_DES_192_EDE3_CBC_WITH_MD5, /* actually 112, not 192 */ SSL_EN_DES_64_CBC_WITH_MD5, SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, @@ -144,10 +147,10 @@ const PRUint16 SSL_ImplementedCiphers[] = { }; -const PRUint16 SSL_NumImplementedCiphers = +const PRUint16 SSL_NumImplementedCiphers = (sizeof SSL_ImplementedCiphers) / (sizeof SSL_ImplementedCiphers[0]) - 1; -const PRUint16 * +const PRUint16* SSL_GetImplementedCiphers(void) { return SSL_ImplementedCiphers; diff --git a/security/nss/lib/ssl/sslerr.c b/security/nss/lib/ssl/sslerr.c index f827221aee29..edb941257d5d 100644 --- a/security/nss/lib/ssl/sslerr.c +++ b/security/nss/lib/ssl/sslerr.c @@ -1,5 +1,5 @@ /* - * Function to set error code only when meaningful error has not already + * Function to set error code only when meaningful error has not already * been set. * * This Source Code Form is subject to the terms of the Mozilla Public @@ -12,30 +12,30 @@ #include "seccomon.h" /* look at the current value of PR_GetError, and evaluate it to see - * if it is meaningful or meaningless (out of context). + * if it is meaningful or meaningless (out of context). * If it is meaningless, replace it with the hiLevelError. * Returns the chosen error value. */ int ssl_MapLowLevelError(int hiLevelError) { - int oldErr = PORT_GetError(); + int oldErr = PORT_GetError(); switch (oldErr) { - case 0: - case PR_IO_ERROR: - case SEC_ERROR_IO: - case SEC_ERROR_BAD_DATA: - case SEC_ERROR_LIBRARY_FAILURE: - case SEC_ERROR_EXTENSION_NOT_FOUND: - case SSL_ERROR_BAD_CLIENT: - case SSL_ERROR_BAD_SERVER: - case SSL_ERROR_SESSION_NOT_FOUND: - PORT_SetError(hiLevelError); - return hiLevelError; + case 0: + case PR_IO_ERROR: + case SEC_ERROR_IO: + case SEC_ERROR_BAD_DATA: + case SEC_ERROR_LIBRARY_FAILURE: + case SEC_ERROR_EXTENSION_NOT_FOUND: + case SSL_ERROR_BAD_CLIENT: + case SSL_ERROR_BAD_SERVER: + case SSL_ERROR_SESSION_NOT_FOUND: + PORT_SetError(hiLevelError); + return hiLevelError; - default: /* leave the majority of error codes alone. */ - return oldErr; + default: /* leave the majority of error codes alone. */ + return oldErr; } } diff --git a/security/nss/lib/ssl/sslerr.h b/security/nss/lib/ssl/sslerr.h index 95411c258ec5..f806359c0d01 100644 --- a/security/nss/lib/ssl/sslerr.h +++ b/security/nss/lib/ssl/sslerr.h @@ -7,6 +7,7 @@ #ifndef __SSL_ERR_H_ #define __SSL_ERR_H_ +/* clang-format off */ #define SSL_ERROR_BASE (-0x3000) #define SSL_ERROR_LIMIT (SSL_ERROR_BASE + 1000) @@ -16,211 +17,213 @@ #ifndef NO_SECURITY_ERROR_ENUM typedef enum { -SSL_ERROR_EXPORT_ONLY_SERVER = (SSL_ERROR_BASE + 0), -SSL_ERROR_US_ONLY_SERVER = (SSL_ERROR_BASE + 1), -SSL_ERROR_NO_CYPHER_OVERLAP = (SSL_ERROR_BASE + 2), -/* - * Received an alert reporting what we did wrong. (more alerts below) - */ -SSL_ERROR_NO_CERTIFICATE /*_ALERT */ = (SSL_ERROR_BASE + 3), -SSL_ERROR_BAD_CERTIFICATE = (SSL_ERROR_BASE + 4), -SSL_ERROR_UNUSED_5 = (SSL_ERROR_BASE + 5), - /* error 5 is obsolete */ -SSL_ERROR_BAD_CLIENT = (SSL_ERROR_BASE + 6), -SSL_ERROR_BAD_SERVER = (SSL_ERROR_BASE + 7), -SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE = (SSL_ERROR_BASE + 8), -SSL_ERROR_UNSUPPORTED_VERSION = (SSL_ERROR_BASE + 9), -SSL_ERROR_UNUSED_10 = (SSL_ERROR_BASE + 10), - /* error 10 is obsolete */ -SSL_ERROR_WRONG_CERTIFICATE = (SSL_ERROR_BASE + 11), -SSL_ERROR_BAD_CERT_DOMAIN = (SSL_ERROR_BASE + 12), -SSL_ERROR_POST_WARNING = (SSL_ERROR_BASE + 13), -SSL_ERROR_SSL2_DISABLED = (SSL_ERROR_BASE + 14), -SSL_ERROR_BAD_MAC_READ = (SSL_ERROR_BASE + 15), -/* - * Received an alert reporting what we did wrong. - * (two more alerts above, and many more below) - */ -SSL_ERROR_BAD_MAC_ALERT = (SSL_ERROR_BASE + 16), -SSL_ERROR_BAD_CERT_ALERT = (SSL_ERROR_BASE + 17), -SSL_ERROR_REVOKED_CERT_ALERT = (SSL_ERROR_BASE + 18), -SSL_ERROR_EXPIRED_CERT_ALERT = (SSL_ERROR_BASE + 19), + SSL_ERROR_EXPORT_ONLY_SERVER = (SSL_ERROR_BASE + 0), + SSL_ERROR_US_ONLY_SERVER = (SSL_ERROR_BASE + 1), + SSL_ERROR_NO_CYPHER_OVERLAP = (SSL_ERROR_BASE + 2), + /* + * Received an alert reporting what we did wrong. (more alerts below) + */ + SSL_ERROR_NO_CERTIFICATE /*_ALERT */ = (SSL_ERROR_BASE + 3), + SSL_ERROR_BAD_CERTIFICATE = (SSL_ERROR_BASE + 4), + SSL_ERROR_UNUSED_5 = (SSL_ERROR_BASE + 5), + /* error 5 is obsolete */ + SSL_ERROR_BAD_CLIENT = (SSL_ERROR_BASE + 6), + SSL_ERROR_BAD_SERVER = (SSL_ERROR_BASE + 7), + SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE = (SSL_ERROR_BASE + 8), + SSL_ERROR_UNSUPPORTED_VERSION = (SSL_ERROR_BASE + 9), + SSL_ERROR_UNUSED_10 = (SSL_ERROR_BASE + 10), + /* error 10 is obsolete */ + SSL_ERROR_WRONG_CERTIFICATE = (SSL_ERROR_BASE + 11), + SSL_ERROR_BAD_CERT_DOMAIN = (SSL_ERROR_BASE + 12), + SSL_ERROR_POST_WARNING = (SSL_ERROR_BASE + 13), + SSL_ERROR_SSL2_DISABLED = (SSL_ERROR_BASE + 14), + SSL_ERROR_BAD_MAC_READ = (SSL_ERROR_BASE + 15), + /* + * Received an alert reporting what we did wrong. + * (two more alerts above, and many more below) + */ + SSL_ERROR_BAD_MAC_ALERT = (SSL_ERROR_BASE + 16), + SSL_ERROR_BAD_CERT_ALERT = (SSL_ERROR_BASE + 17), + SSL_ERROR_REVOKED_CERT_ALERT = (SSL_ERROR_BASE + 18), + SSL_ERROR_EXPIRED_CERT_ALERT = (SSL_ERROR_BASE + 19), -SSL_ERROR_SSL_DISABLED = (SSL_ERROR_BASE + 20), -SSL_ERROR_FORTEZZA_PQG = (SSL_ERROR_BASE + 21), -SSL_ERROR_UNKNOWN_CIPHER_SUITE = (SSL_ERROR_BASE + 22), -SSL_ERROR_NO_CIPHERS_SUPPORTED = (SSL_ERROR_BASE + 23), -SSL_ERROR_BAD_BLOCK_PADDING = (SSL_ERROR_BASE + 24), -SSL_ERROR_RX_RECORD_TOO_LONG = (SSL_ERROR_BASE + 25), -SSL_ERROR_TX_RECORD_TOO_LONG = (SSL_ERROR_BASE + 26), -/* - * Received a malformed (too long or short) SSL handshake. - */ -SSL_ERROR_RX_MALFORMED_HELLO_REQUEST = (SSL_ERROR_BASE + 27), -SSL_ERROR_RX_MALFORMED_CLIENT_HELLO = (SSL_ERROR_BASE + 28), -SSL_ERROR_RX_MALFORMED_SERVER_HELLO = (SSL_ERROR_BASE + 29), -SSL_ERROR_RX_MALFORMED_CERTIFICATE = (SSL_ERROR_BASE + 30), -SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH = (SSL_ERROR_BASE + 31), -SSL_ERROR_RX_MALFORMED_CERT_REQUEST = (SSL_ERROR_BASE + 32), -SSL_ERROR_RX_MALFORMED_HELLO_DONE = (SSL_ERROR_BASE + 33), -SSL_ERROR_RX_MALFORMED_CERT_VERIFY = (SSL_ERROR_BASE + 34), -SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH = (SSL_ERROR_BASE + 35), -SSL_ERROR_RX_MALFORMED_FINISHED = (SSL_ERROR_BASE + 36), -/* - * Received a malformed (too long or short) SSL record. - */ -SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER = (SSL_ERROR_BASE + 37), -SSL_ERROR_RX_MALFORMED_ALERT = (SSL_ERROR_BASE + 38), -SSL_ERROR_RX_MALFORMED_HANDSHAKE = (SSL_ERROR_BASE + 39), -SSL_ERROR_RX_MALFORMED_APPLICATION_DATA = (SSL_ERROR_BASE + 40), -/* - * 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. - */ -SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST = (SSL_ERROR_BASE + 41), -SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO = (SSL_ERROR_BASE + 42), -SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO = (SSL_ERROR_BASE + 43), -SSL_ERROR_RX_UNEXPECTED_CERTIFICATE = (SSL_ERROR_BASE + 44), -SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH = (SSL_ERROR_BASE + 45), -SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST = (SSL_ERROR_BASE + 46), -SSL_ERROR_RX_UNEXPECTED_HELLO_DONE = (SSL_ERROR_BASE + 47), -SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY = (SSL_ERROR_BASE + 48), -SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH = (SSL_ERROR_BASE + 49), -SSL_ERROR_RX_UNEXPECTED_FINISHED = (SSL_ERROR_BASE + 50), -/* - * Received an SSL record that was inappropriate for the state we're in. - */ -SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER = (SSL_ERROR_BASE + 51), -SSL_ERROR_RX_UNEXPECTED_ALERT = (SSL_ERROR_BASE + 52), -SSL_ERROR_RX_UNEXPECTED_HANDSHAKE = (SSL_ERROR_BASE + 53), -SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA = (SSL_ERROR_BASE + 54), -/* - * Received record/message with unknown discriminant. - */ -SSL_ERROR_RX_UNKNOWN_RECORD_TYPE = (SSL_ERROR_BASE + 55), -SSL_ERROR_RX_UNKNOWN_HANDSHAKE = (SSL_ERROR_BASE + 56), -SSL_ERROR_RX_UNKNOWN_ALERT = (SSL_ERROR_BASE + 57), -/* - * Received an alert reporting what we did wrong. (more alerts above) - */ -SSL_ERROR_CLOSE_NOTIFY_ALERT = (SSL_ERROR_BASE + 58), -SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT = (SSL_ERROR_BASE + 59), -SSL_ERROR_DECOMPRESSION_FAILURE_ALERT = (SSL_ERROR_BASE + 60), -SSL_ERROR_HANDSHAKE_FAILURE_ALERT = (SSL_ERROR_BASE + 61), -SSL_ERROR_ILLEGAL_PARAMETER_ALERT = (SSL_ERROR_BASE + 62), -SSL_ERROR_UNSUPPORTED_CERT_ALERT = (SSL_ERROR_BASE + 63), -SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT = (SSL_ERROR_BASE + 64), + SSL_ERROR_SSL_DISABLED = (SSL_ERROR_BASE + 20), + SSL_ERROR_FORTEZZA_PQG = (SSL_ERROR_BASE + 21), + SSL_ERROR_UNKNOWN_CIPHER_SUITE = (SSL_ERROR_BASE + 22), + SSL_ERROR_NO_CIPHERS_SUPPORTED = (SSL_ERROR_BASE + 23), + SSL_ERROR_BAD_BLOCK_PADDING = (SSL_ERROR_BASE + 24), + SSL_ERROR_RX_RECORD_TOO_LONG = (SSL_ERROR_BASE + 25), + SSL_ERROR_TX_RECORD_TOO_LONG = (SSL_ERROR_BASE + 26), + /* + * Received a malformed (too long or short) SSL handshake. + */ + SSL_ERROR_RX_MALFORMED_HELLO_REQUEST = (SSL_ERROR_BASE + 27), + SSL_ERROR_RX_MALFORMED_CLIENT_HELLO = (SSL_ERROR_BASE + 28), + SSL_ERROR_RX_MALFORMED_SERVER_HELLO = (SSL_ERROR_BASE + 29), + SSL_ERROR_RX_MALFORMED_CERTIFICATE = (SSL_ERROR_BASE + 30), + SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH = (SSL_ERROR_BASE + 31), + SSL_ERROR_RX_MALFORMED_CERT_REQUEST = (SSL_ERROR_BASE + 32), + SSL_ERROR_RX_MALFORMED_HELLO_DONE = (SSL_ERROR_BASE + 33), + SSL_ERROR_RX_MALFORMED_CERT_VERIFY = (SSL_ERROR_BASE + 34), + SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH = (SSL_ERROR_BASE + 35), + SSL_ERROR_RX_MALFORMED_FINISHED = (SSL_ERROR_BASE + 36), + /* + * Received a malformed (too long or short) SSL record. + */ + SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER = (SSL_ERROR_BASE + 37), + SSL_ERROR_RX_MALFORMED_ALERT = (SSL_ERROR_BASE + 38), + SSL_ERROR_RX_MALFORMED_HANDSHAKE = (SSL_ERROR_BASE + 39), + SSL_ERROR_RX_MALFORMED_APPLICATION_DATA = (SSL_ERROR_BASE + 40), + /* + * 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. + */ + SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST = (SSL_ERROR_BASE + 41), + SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO = (SSL_ERROR_BASE + 42), + SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO = (SSL_ERROR_BASE + 43), + SSL_ERROR_RX_UNEXPECTED_CERTIFICATE = (SSL_ERROR_BASE + 44), + SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH = (SSL_ERROR_BASE + 45), + SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST = (SSL_ERROR_BASE + 46), + SSL_ERROR_RX_UNEXPECTED_HELLO_DONE = (SSL_ERROR_BASE + 47), + SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY = (SSL_ERROR_BASE + 48), + SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH = (SSL_ERROR_BASE + 49), + SSL_ERROR_RX_UNEXPECTED_FINISHED = (SSL_ERROR_BASE + 50), + /* + * Received an SSL record that was inappropriate for the state we're in. + */ + SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER = (SSL_ERROR_BASE + 51), + SSL_ERROR_RX_UNEXPECTED_ALERT = (SSL_ERROR_BASE + 52), + SSL_ERROR_RX_UNEXPECTED_HANDSHAKE = (SSL_ERROR_BASE + 53), + SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA = (SSL_ERROR_BASE + 54), + /* + * Received record/message with unknown discriminant. + */ + SSL_ERROR_RX_UNKNOWN_RECORD_TYPE = (SSL_ERROR_BASE + 55), + SSL_ERROR_RX_UNKNOWN_HANDSHAKE = (SSL_ERROR_BASE + 56), + SSL_ERROR_RX_UNKNOWN_ALERT = (SSL_ERROR_BASE + 57), + /* + * Received an alert reporting what we did wrong. (more alerts above) + */ + SSL_ERROR_CLOSE_NOTIFY_ALERT = (SSL_ERROR_BASE + 58), + SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT = (SSL_ERROR_BASE + 59), + SSL_ERROR_DECOMPRESSION_FAILURE_ALERT = (SSL_ERROR_BASE + 60), + SSL_ERROR_HANDSHAKE_FAILURE_ALERT = (SSL_ERROR_BASE + 61), + SSL_ERROR_ILLEGAL_PARAMETER_ALERT = (SSL_ERROR_BASE + 62), + SSL_ERROR_UNSUPPORTED_CERT_ALERT = (SSL_ERROR_BASE + 63), + SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT = (SSL_ERROR_BASE + 64), -SSL_ERROR_GENERATE_RANDOM_FAILURE = (SSL_ERROR_BASE + 65), -SSL_ERROR_SIGN_HASHES_FAILURE = (SSL_ERROR_BASE + 66), -SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE = (SSL_ERROR_BASE + 67), -SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 68), -SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 69), + SSL_ERROR_GENERATE_RANDOM_FAILURE = (SSL_ERROR_BASE + 65), + SSL_ERROR_SIGN_HASHES_FAILURE = (SSL_ERROR_BASE + 66), + SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE = (SSL_ERROR_BASE + 67), + SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 68), + SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 69), -SSL_ERROR_ENCRYPTION_FAILURE = (SSL_ERROR_BASE + 70), -SSL_ERROR_DECRYPTION_FAILURE = (SSL_ERROR_BASE + 71), /* don't use */ -SSL_ERROR_SOCKET_WRITE_FAILURE = (SSL_ERROR_BASE + 72), + SSL_ERROR_ENCRYPTION_FAILURE = (SSL_ERROR_BASE + 70), + SSL_ERROR_DECRYPTION_FAILURE = (SSL_ERROR_BASE + 71), /* don't use */ + SSL_ERROR_SOCKET_WRITE_FAILURE = (SSL_ERROR_BASE + 72), -SSL_ERROR_MD5_DIGEST_FAILURE = (SSL_ERROR_BASE + 73), -SSL_ERROR_SHA_DIGEST_FAILURE = (SSL_ERROR_BASE + 74), -SSL_ERROR_MAC_COMPUTATION_FAILURE = (SSL_ERROR_BASE + 75), -SSL_ERROR_SYM_KEY_CONTEXT_FAILURE = (SSL_ERROR_BASE + 76), -SSL_ERROR_SYM_KEY_UNWRAP_FAILURE = (SSL_ERROR_BASE + 77), -SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED = (SSL_ERROR_BASE + 78), -SSL_ERROR_IV_PARAM_FAILURE = (SSL_ERROR_BASE + 79), -SSL_ERROR_INIT_CIPHER_SUITE_FAILURE = (SSL_ERROR_BASE + 80), -SSL_ERROR_SESSION_KEY_GEN_FAILURE = (SSL_ERROR_BASE + 81), -SSL_ERROR_NO_SERVER_KEY_FOR_ALG = (SSL_ERROR_BASE + 82), -SSL_ERROR_TOKEN_INSERTION_REMOVAL = (SSL_ERROR_BASE + 83), -SSL_ERROR_TOKEN_SLOT_NOT_FOUND = (SSL_ERROR_BASE + 84), -SSL_ERROR_NO_COMPRESSION_OVERLAP = (SSL_ERROR_BASE + 85), -SSL_ERROR_HANDSHAKE_NOT_COMPLETED = (SSL_ERROR_BASE + 86), -SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE = (SSL_ERROR_BASE + 87), -SSL_ERROR_CERT_KEA_MISMATCH = (SSL_ERROR_BASE + 88), -/* SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA became obsolete in NSS 3.14. */ -SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA = (SSL_ERROR_BASE + 89), -SSL_ERROR_SESSION_NOT_FOUND = (SSL_ERROR_BASE + 90), + SSL_ERROR_MD5_DIGEST_FAILURE = (SSL_ERROR_BASE + 73), + SSL_ERROR_SHA_DIGEST_FAILURE = (SSL_ERROR_BASE + 74), + SSL_ERROR_MAC_COMPUTATION_FAILURE = (SSL_ERROR_BASE + 75), + SSL_ERROR_SYM_KEY_CONTEXT_FAILURE = (SSL_ERROR_BASE + 76), + SSL_ERROR_SYM_KEY_UNWRAP_FAILURE = (SSL_ERROR_BASE + 77), + SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED = (SSL_ERROR_BASE + 78), + SSL_ERROR_IV_PARAM_FAILURE = (SSL_ERROR_BASE + 79), + SSL_ERROR_INIT_CIPHER_SUITE_FAILURE = (SSL_ERROR_BASE + 80), + SSL_ERROR_SESSION_KEY_GEN_FAILURE = (SSL_ERROR_BASE + 81), + SSL_ERROR_NO_SERVER_KEY_FOR_ALG = (SSL_ERROR_BASE + 82), + SSL_ERROR_TOKEN_INSERTION_REMOVAL = (SSL_ERROR_BASE + 83), + SSL_ERROR_TOKEN_SLOT_NOT_FOUND = (SSL_ERROR_BASE + 84), + SSL_ERROR_NO_COMPRESSION_OVERLAP = (SSL_ERROR_BASE + 85), + SSL_ERROR_HANDSHAKE_NOT_COMPLETED = (SSL_ERROR_BASE + 86), + SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE = (SSL_ERROR_BASE + 87), + SSL_ERROR_CERT_KEA_MISMATCH = (SSL_ERROR_BASE + 88), + /* SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA became obsolete in NSS 3.14. */ + SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA = (SSL_ERROR_BASE + 89), + SSL_ERROR_SESSION_NOT_FOUND = (SSL_ERROR_BASE + 90), -SSL_ERROR_DECRYPTION_FAILED_ALERT = (SSL_ERROR_BASE + 91), -SSL_ERROR_RECORD_OVERFLOW_ALERT = (SSL_ERROR_BASE + 92), -SSL_ERROR_UNKNOWN_CA_ALERT = (SSL_ERROR_BASE + 93), -SSL_ERROR_ACCESS_DENIED_ALERT = (SSL_ERROR_BASE + 94), -SSL_ERROR_DECODE_ERROR_ALERT = (SSL_ERROR_BASE + 95), -SSL_ERROR_DECRYPT_ERROR_ALERT = (SSL_ERROR_BASE + 96), -SSL_ERROR_EXPORT_RESTRICTION_ALERT = (SSL_ERROR_BASE + 97), -SSL_ERROR_PROTOCOL_VERSION_ALERT = (SSL_ERROR_BASE + 98), -SSL_ERROR_INSUFFICIENT_SECURITY_ALERT = (SSL_ERROR_BASE + 99), -SSL_ERROR_INTERNAL_ERROR_ALERT = (SSL_ERROR_BASE + 100), -SSL_ERROR_USER_CANCELED_ALERT = (SSL_ERROR_BASE + 101), -SSL_ERROR_NO_RENEGOTIATION_ALERT = (SSL_ERROR_BASE + 102), + SSL_ERROR_DECRYPTION_FAILED_ALERT = (SSL_ERROR_BASE + 91), + SSL_ERROR_RECORD_OVERFLOW_ALERT = (SSL_ERROR_BASE + 92), + SSL_ERROR_UNKNOWN_CA_ALERT = (SSL_ERROR_BASE + 93), + SSL_ERROR_ACCESS_DENIED_ALERT = (SSL_ERROR_BASE + 94), + SSL_ERROR_DECODE_ERROR_ALERT = (SSL_ERROR_BASE + 95), + SSL_ERROR_DECRYPT_ERROR_ALERT = (SSL_ERROR_BASE + 96), + SSL_ERROR_EXPORT_RESTRICTION_ALERT = (SSL_ERROR_BASE + 97), + SSL_ERROR_PROTOCOL_VERSION_ALERT = (SSL_ERROR_BASE + 98), + SSL_ERROR_INSUFFICIENT_SECURITY_ALERT = (SSL_ERROR_BASE + 99), + SSL_ERROR_INTERNAL_ERROR_ALERT = (SSL_ERROR_BASE + 100), + SSL_ERROR_USER_CANCELED_ALERT = (SSL_ERROR_BASE + 101), + SSL_ERROR_NO_RENEGOTIATION_ALERT = (SSL_ERROR_BASE + 102), -SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED = (SSL_ERROR_BASE + 103), + SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED = (SSL_ERROR_BASE + 103), -SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT = (SSL_ERROR_BASE + 104), -SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT = (SSL_ERROR_BASE + 105), -SSL_ERROR_UNRECOGNIZED_NAME_ALERT = (SSL_ERROR_BASE + 106), -SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT = (SSL_ERROR_BASE + 107), -SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT = (SSL_ERROR_BASE + 108), + SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT = (SSL_ERROR_BASE + 104), + SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT = (SSL_ERROR_BASE + 105), + SSL_ERROR_UNRECOGNIZED_NAME_ALERT = (SSL_ERROR_BASE + 106), + SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT = (SSL_ERROR_BASE + 107), + SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT = (SSL_ERROR_BASE + 108), -SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET = (SSL_ERROR_BASE + 109), -SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET = (SSL_ERROR_BASE + 110), + SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET = (SSL_ERROR_BASE + 109), + SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET = (SSL_ERROR_BASE + 110), -SSL_ERROR_DECOMPRESSION_FAILURE = (SSL_ERROR_BASE + 111), -SSL_ERROR_RENEGOTIATION_NOT_ALLOWED = (SSL_ERROR_BASE + 112), -SSL_ERROR_UNSAFE_NEGOTIATION = (SSL_ERROR_BASE + 113), + SSL_ERROR_DECOMPRESSION_FAILURE = (SSL_ERROR_BASE + 111), + SSL_ERROR_RENEGOTIATION_NOT_ALLOWED = (SSL_ERROR_BASE + 112), + SSL_ERROR_UNSAFE_NEGOTIATION = (SSL_ERROR_BASE + 113), -SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD = (SSL_ERROR_BASE + 114), + SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD = (SSL_ERROR_BASE + 114), -SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY = (SSL_ERROR_BASE + 115), + SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY = (SSL_ERROR_BASE + 115), -SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID = (SSL_ERROR_BASE + 116), + SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID = (SSL_ERROR_BASE + 116), -SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2 = (SSL_ERROR_BASE + 117), -SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS = (SSL_ERROR_BASE + 118), -SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_CLIENTS = (SSL_ERROR_BASE + 119), + SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2 = (SSL_ERROR_BASE + 117), + SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS = (SSL_ERROR_BASE + 118), + SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_CLIENTS = (SSL_ERROR_BASE + 119), -SSL_ERROR_INVALID_VERSION_RANGE = (SSL_ERROR_BASE + 120), -SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION = (SSL_ERROR_BASE + 121), + SSL_ERROR_INVALID_VERSION_RANGE = (SSL_ERROR_BASE + 120), + SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION = (SSL_ERROR_BASE + 121), -SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST = (SSL_ERROR_BASE + 122), -SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST = (SSL_ERROR_BASE + 123), + SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST = (SSL_ERROR_BASE + 122), + SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST = (SSL_ERROR_BASE + 123), -SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION = (SSL_ERROR_BASE + 124), + SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION = (SSL_ERROR_BASE + 124), -SSL_ERROR_RX_UNEXPECTED_CERT_STATUS = (SSL_ERROR_BASE + 125), + SSL_ERROR_RX_UNEXPECTED_CERT_STATUS = (SSL_ERROR_BASE + 125), -SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM = (SSL_ERROR_BASE + 126), -SSL_ERROR_DIGEST_FAILURE = (SSL_ERROR_BASE + 127), -SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 128), + SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM = (SSL_ERROR_BASE + 126), + SSL_ERROR_DIGEST_FAILURE = (SSL_ERROR_BASE + 127), + SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 128), -SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK = (SSL_ERROR_BASE + 129), -SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL = (SSL_ERROR_BASE + 130), + SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK = (SSL_ERROR_BASE + 129), + SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL = (SSL_ERROR_BASE + 130), -SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT = (SSL_ERROR_BASE + 131), + SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT = (SSL_ERROR_BASE + 131), -SSL_ERROR_WEAK_SERVER_CERT_KEY = (SSL_ERROR_BASE + 132), + SSL_ERROR_WEAK_SERVER_CERT_KEY = (SSL_ERROR_BASE + 132), -SSL_ERROR_RX_SHORT_DTLS_READ = (SSL_ERROR_BASE + 133), + SSL_ERROR_RX_SHORT_DTLS_READ = (SSL_ERROR_BASE + 133), -SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 134), -SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 135), + SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 134), + SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 135), -SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET = (SSL_ERROR_BASE + 136), -SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET = (SSL_ERROR_BASE + 137), + SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET = (SSL_ERROR_BASE + 136), + SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET = (SSL_ERROR_BASE + 137), -SSL_ERROR_RX_MALFORMED_KEY_SHARE = (SSL_ERROR_BASE + 138), -SSL_ERROR_MISSING_KEY_SHARE = (SSL_ERROR_BASE + 139), -SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE = (SSL_ERROR_BASE + 140), -SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE = (SSL_ERROR_BASE + 141), + SSL_ERROR_RX_MALFORMED_KEY_SHARE = (SSL_ERROR_BASE + 138), + SSL_ERROR_MISSING_KEY_SHARE = (SSL_ERROR_BASE + 139), + SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE = (SSL_ERROR_BASE + 140), + SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE = (SSL_ERROR_BASE + 141), -SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS = (SSL_ERROR_BASE + 142), -SSL_ERROR_MISSING_EXTENSION_ALERT = (SSL_ERROR_BASE + 143), + SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS = (SSL_ERROR_BASE + 142), + SSL_ERROR_MISSING_EXTENSION_ALERT = (SSL_ERROR_BASE + 143), -SSL_ERROR_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 144), -SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION = (SSL_ERROR_BASE + 145), - -SSL_ERROR_END_OF_LIST /* let the c compiler determine the value of this. */ + SSL_ERROR_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 144), + SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION = (SSL_ERROR_BASE + 145), + SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS = (SSL_ERROR_BASE + 146), + SSL_ERROR_END_OF_LIST /* let the c compiler determine the value of this. */ } SSLErrorCodes; #endif /* NO_SECURITY_ERROR_ENUM */ +/* clang-format on */ + #endif /* __SSL_ERR_H_ */ diff --git a/security/nss/lib/ssl/sslerrstrs.c b/security/nss/lib/ssl/sslerrstrs.c index 34f4ea9b9d81..4e3db6d73c37 100644 --- a/security/nss/lib/ssl/sslerrstrs.c +++ b/security/nss/lib/ssl/sslerrstrs.c @@ -7,20 +7,21 @@ #include "nssutil.h" #include "ssl.h" -#define ER3(name, value, str) {#name, str}, +#define ER3(name, value, str) { #name, str }, static const struct PRErrorMessage ssltext[] = { #include "SSLerrs.h" - {0,0} + { 0, 0 } }; static const struct PRErrorTable ssl_et = { ssltext, "sslerr", SSL_ERROR_BASE, - (sizeof ssltext)/(sizeof ssltext[0]) + (sizeof ssltext) / (sizeof ssltext[0]) }; static PRStatus -ssl_InitializePRErrorTableOnce(void) { +ssl_InitializePRErrorTableOnce(void) +{ return PR_ErrorInstallTable(&ssl_et); } @@ -30,5 +31,6 @@ SECStatus ssl_InitializePRErrorTable(void) { return (PR_SUCCESS == PR_CallOnce(&once, ssl_InitializePRErrorTableOnce)) - ? SECSuccess : SECFailure; + ? SECSuccess + : SECFailure; } diff --git a/security/nss/lib/ssl/sslgathr.c b/security/nss/lib/ssl/sslgathr.c index bdf470b0cf0f..ff26f8bd64f2 100644 --- a/security/nss/lib/ssl/sslgathr.c +++ b/security/nss/lib/ssl/sslgathr.c @@ -1,5 +1,5 @@ /* - * Gather (Read) entire SSL2 records from socket into buffer. + * Gather (Read) entire SSL2 records from socket into buffer. * * 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 @@ -20,7 +20,7 @@ static SECStatus ssl2_HandleV3HandshakeRecord(sslSocket *ss); ** and is to be called multiple times until ss->sec.recordLen != 0. ** This function decrypts the gathered record in place, in gs_buf. * - * Caller must hold RecvBufLock. + * Caller must hold RecvBufLock. * * Returns +1 when it has gathered a complete SSLV2 record. * Returns 0 if it hits EOF. @@ -41,7 +41,7 @@ static SECStatus ssl2_HandleV3HandshakeRecord(sslSocket *ss); ** advance to one of two states, depending on whether the record ** is encrypted (GS_MAC), or unencrypted (GS_DATA). ** -** GS_MAC - The machine is in this state while waiting for the remainder +** GS_MAC - The machine is in this state while waiting for the remainder ** of the SSL2 record to be read in. When the read is completed, ** the machine checks the record for valid length, decrypts it, ** and checks and discards the MAC, then advances to GS_INIT. @@ -50,295 +50,297 @@ static SECStatus ssl2_HandleV3HandshakeRecord(sslSocket *ss); ** of the unencrypted SSL2 record to be read in. Upon completion, ** the machine advances to the GS_INIT state and returns the data. */ -int +int ssl2_GatherData(sslSocket *ss, sslGather *gs, int flags) { - unsigned char * bp; - unsigned char * pBuf; - int nb, err, rv; + unsigned char *bp; + unsigned char *pBuf; + int nb, err, rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); if (gs->state == GS_INIT) { - /* Initialize gathering engine */ - gs->state = GS_HEADER; - gs->remainder = 3; - gs->count = 3; - gs->offset = 0; - gs->recordLen = 0; - gs->recordPadding = 0; - gs->hdr[2] = 0; + /* Initialize gathering engine */ + gs->state = GS_HEADER; + gs->remainder = 3; + gs->count = 3; + gs->offset = 0; + gs->recordLen = 0; + gs->recordPadding = 0; + gs->hdr[2] = 0; - gs->writeOffset = 0; - gs->readOffset = 0; + gs->writeOffset = 0; + gs->readOffset = 0; } if (gs->encrypted) { - PORT_Assert(ss->sec.hash != 0); + PORT_Assert(ss->sec.hash != 0); } pBuf = gs->buf.buf; for (;;) { - SSL_TRC(30, ("%d: SSL[%d]: gather state %d (need %d more)", - SSL_GETPID(), ss->fd, gs->state, gs->remainder)); - bp = ((gs->state != GS_HEADER) ? pBuf : gs->hdr) + gs->offset; - nb = ssl_DefRecv(ss, bp, gs->remainder, flags); - if (nb > 0) { - PRINT_BUF(60, (ss, "raw gather data:", bp, nb)); - } - if (nb == 0) { - /* EOF */ - SSL_TRC(30, ("%d: SSL[%d]: EOF", SSL_GETPID(), ss->fd)); - rv = 0; - break; - } - if (nb < 0) { - SSL_DBG(("%d: SSL[%d]: recv error %d", SSL_GETPID(), ss->fd, - PR_GetError())); - rv = SECFailure; - break; - } + SSL_TRC(30, ("%d: SSL[%d]: gather state %d (need %d more)", + SSL_GETPID(), ss->fd, gs->state, gs->remainder)); + bp = ((gs->state != GS_HEADER) ? pBuf : gs->hdr) + gs->offset; + nb = ssl_DefRecv(ss, bp, gs->remainder, flags); + if (nb > 0) { + PRINT_BUF(60, (ss, "raw gather data:", bp, nb)); + } + if (nb == 0) { + /* EOF */ + SSL_TRC(30, ("%d: SSL[%d]: EOF", SSL_GETPID(), ss->fd)); + rv = 0; + break; + } + if (nb < 0) { + SSL_DBG(("%d: SSL[%d]: recv error %d", SSL_GETPID(), ss->fd, + PR_GetError())); + rv = SECFailure; + break; + } - gs->offset += nb; - gs->remainder -= nb; + gs->offset += nb; + gs->remainder -= nb; - if (gs->remainder > 0) { - continue; - } + if (gs->remainder > 0) { + continue; + } - /* Probably finished this piece */ - switch (gs->state) { - case GS_HEADER: - if (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) && !ss->firstHsDone) { + /* Probably finished this piece */ + switch (gs->state) { + case GS_HEADER: + if (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) && !ss->firstHsDone) { - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - /* If this looks like an SSL3 handshake record, - ** and we're expecting an SSL2 Hello message from our peer, - ** handle it here. - */ - if (gs->hdr[0] == content_handshake) { - if ((ss->nextHandshake == ssl2_HandleClientHelloMessage) || - (ss->nextHandshake == ssl2_HandleServerHelloMessage)) { - rv = ssl2_HandleV3HandshakeRecord(ss); - if (rv == SECFailure) { - return SECFailure; - } - } - /* XXX_1 The call stack to here is: - * ssl_Do1stHandshake -> ssl_GatherRecord1stHandshake -> - * ssl2_GatherRecord -> here. - * We want to return all the way out to ssl_Do1stHandshake, - * and have it call ssl_GatherRecord1stHandshake again. - * ssl_GatherRecord1stHandshake will call - * ssl3_GatherCompleteHandshake when it is called again. - * - * Returning SECWouldBlock here causes - * ssl_GatherRecord1stHandshake to return without clearing - * ss->handshake, ensuring that ssl_Do1stHandshake will - * call it again immediately. - * - * If we return 1 here, ssl_GatherRecord1stHandshake will - * clear ss->handshake before returning, and thus will not - * be called again by ssl_Do1stHandshake. - */ - return SECWouldBlock; - } else if (gs->hdr[0] == content_alert) { - if (ss->nextHandshake == ssl2_HandleServerHelloMessage) { - /* XXX This is a hack. We're assuming that any failure - * XXX on the client hello is a failure to match - * XXX ciphers. - */ - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; - } - } - } + /* If this looks like an SSL3 handshake record, + ** and we're expecting an SSL2 Hello message from our peer, + ** handle it here. + */ + if (gs->hdr[0] == content_handshake) { + if ((ss->nextHandshake == ssl2_HandleClientHelloMessage) || + (ss->nextHandshake == ssl2_HandleServerHelloMessage)) { + rv = ssl2_HandleV3HandshakeRecord(ss); + if (rv == SECFailure) { + return SECFailure; + } + } + /* XXX_1 The call stack to here is: + * ssl_Do1stHandshake -> ssl_GatherRecord1stHandshake -> + * ssl2_GatherRecord -> here. + * We want to return all the way out to ssl_Do1stHandshake, + * and have it call ssl_GatherRecord1stHandshake again. + * ssl_GatherRecord1stHandshake will call + * ssl3_GatherCompleteHandshake when it is called again. + * + * Returning SECWouldBlock here causes + * ssl_GatherRecord1stHandshake to return without clearing + * ss->handshake, ensuring that ssl_Do1stHandshake will + * call it again immediately. + * + * If we return 1 here, ssl_GatherRecord1stHandshake will + * clear ss->handshake before returning, and thus will not + * be called again by ssl_Do1stHandshake. + */ + return SECWouldBlock; + } + else if (gs->hdr[0] == content_alert) { + if (ss->nextHandshake == ssl2_HandleServerHelloMessage) { + /* XXX This is a hack. We're assuming that any failure + * XXX on the client hello is a failure to match + * XXX ciphers. + */ + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return SECFailure; + } + } + } - /* we've got the first 3 bytes. The header may be two or three. */ - if (gs->hdr[0] & 0x80) { - /* This record has a 2-byte header, and no padding */ - gs->count = ((gs->hdr[0] & 0x7f) << 8) | gs->hdr[1]; - gs->recordPadding = 0; - } else { - /* This record has a 3-byte header that is all read in now. */ - gs->count = ((gs->hdr[0] & 0x3f) << 8) | gs->hdr[1]; - /* is_escape = (gs->hdr[0] & 0x40) != 0; */ - gs->recordPadding = gs->hdr[2]; - } - if (!gs->count) { - PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); - goto cleanup; - } + /* we've got the first 3 bytes. The header may be two or three. */ + if (gs->hdr[0] & 0x80) { + /* This record has a 2-byte header, and no padding */ + gs->count = ((gs->hdr[0] & 0x7f) << 8) | gs->hdr[1]; + gs->recordPadding = 0; + } + else { + /* This record has a 3-byte header that is all read in now. */ + gs->count = ((gs->hdr[0] & 0x3f) << 8) | gs->hdr[1]; + /* is_escape = (gs->hdr[0] & 0x40) != 0; */ + gs->recordPadding = gs->hdr[2]; + } + if (!gs->count) { + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); + goto cleanup; + } - if (gs->count > gs->buf.space) { - err = sslBuffer_Grow(&gs->buf, gs->count); - if (err) { - return err; - } - pBuf = gs->buf.buf; - } + if (gs->count > gs->buf.space) { + err = sslBuffer_Grow(&gs->buf, gs->count); + if (err) { + return err; + } + pBuf = gs->buf.buf; + } + if (gs->hdr[0] & 0x80) { + /* we've already read in the first byte of the body. + ** Put it into the buffer. + */ + pBuf[0] = gs->hdr[2]; + gs->offset = 1; + gs->remainder = gs->count - 1; + } + else { + gs->offset = 0; + gs->remainder = gs->count; + } - if (gs->hdr[0] & 0x80) { - /* we've already read in the first byte of the body. - ** Put it into the buffer. - */ - pBuf[0] = gs->hdr[2]; - gs->offset = 1; - gs->remainder = gs->count - 1; - } else { - gs->offset = 0; - gs->remainder = gs->count; - } + if (gs->encrypted) { + gs->state = GS_MAC; + gs->recordLen = gs->count - gs->recordPadding - + ss->sec.hash->length; + } + else { + gs->state = GS_DATA; + gs->recordLen = gs->count; + } - if (gs->encrypted) { - gs->state = GS_MAC; - gs->recordLen = gs->count - gs->recordPadding - - ss->sec.hash->length; - } else { - gs->state = GS_DATA; - gs->recordLen = gs->count; - } + break; - break; + case GS_MAC: + /* Have read in entire rest of the ciphertext. + ** Check for valid length. + ** Decrypt it. + ** Check the MAC. + */ + PORT_Assert(gs->encrypted); + { + unsigned int macLen; + int nout; + unsigned char mac[SSL_MAX_MAC_BYTES]; - case GS_MAC: - /* Have read in entire rest of the ciphertext. - ** Check for valid length. - ** Decrypt it. - ** Check the MAC. - */ - PORT_Assert(gs->encrypted); + ssl_GetSpecReadLock(ss); /**********************************/ - { - unsigned int macLen; - int nout; - unsigned char mac[SSL_MAX_MAC_BYTES]; + /* If this is a stream cipher, blockSize will be 1, + * and this test will always be false. + * If this is a block cipher, this will detect records + * that are not a multiple of the blocksize in length. + */ + if (gs->count & (ss->sec.blockSize - 1)) { + /* This is an error. Sender is misbehaving */ + SSL_DBG(("%d: SSL[%d]: sender, count=%d blockSize=%d", + SSL_GETPID(), ss->fd, gs->count, + ss->sec.blockSize)); + PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING); + rv = SECFailure; + goto spec_locked_done; + } + PORT_Assert(gs->count == gs->offset); - ssl_GetSpecReadLock(ss); /**********************************/ + if (gs->offset == 0) { + rv = 0; /* means EOF. */ + goto spec_locked_done; + } - /* If this is a stream cipher, blockSize will be 1, - * and this test will always be false. - * If this is a block cipher, this will detect records - * that are not a multiple of the blocksize in length. - */ - if (gs->count & (ss->sec.blockSize - 1)) { - /* This is an error. Sender is misbehaving */ - SSL_DBG(("%d: SSL[%d]: sender, count=%d blockSize=%d", - SSL_GETPID(), ss->fd, gs->count, - ss->sec.blockSize)); - PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING); - rv = SECFailure; - goto spec_locked_done; - } - PORT_Assert(gs->count == gs->offset); + /* Decrypt the portion of data that we just received. + ** Decrypt it in place. + */ + rv = (*ss->sec.dec)(ss->sec.readcx, pBuf, &nout, gs->offset, + pBuf, gs->offset); + if (rv != SECSuccess) { + goto spec_locked_done; + } - if (gs->offset == 0) { - rv = 0; /* means EOF. */ - goto spec_locked_done; - } + /* Have read in all the MAC portion of record + ** + ** Prepare MAC by resetting it and feeding it the shared secret + */ + macLen = ss->sec.hash->length; + if (gs->offset >= macLen) { + PRUint32 sequenceNumber = ss->sec.rcvSequence++; + unsigned char seq[4]; - /* Decrypt the portion of data that we just received. - ** Decrypt it in place. - */ - rv = (*ss->sec.dec)(ss->sec.readcx, pBuf, &nout, gs->offset, - pBuf, gs->offset); - if (rv != SECSuccess) { - goto spec_locked_done; - } + seq[0] = (unsigned char)(sequenceNumber >> 24); + seq[1] = (unsigned char)(sequenceNumber >> 16); + seq[2] = (unsigned char)(sequenceNumber >> 8); + seq[3] = (unsigned char)(sequenceNumber); + (*ss->sec.hash->begin)(ss->sec.hashcx); + (*ss->sec.hash->update)(ss->sec.hashcx, ss->sec.rcvSecret.data, + ss->sec.rcvSecret.len); + (*ss->sec.hash->update)(ss->sec.hashcx, pBuf + macLen, + gs->offset - macLen); + (*ss->sec.hash->update)(ss->sec.hashcx, seq, 4); + (*ss->sec.hash->end)(ss->sec.hashcx, mac, &macLen, macLen); - /* Have read in all the MAC portion of record - ** - ** Prepare MAC by resetting it and feeding it the shared secret - */ - macLen = ss->sec.hash->length; - if (gs->offset >= macLen) { - PRUint32 sequenceNumber = ss->sec.rcvSequence++; - unsigned char seq[4]; + PORT_Assert(macLen == ss->sec.hash->length); - seq[0] = (unsigned char) (sequenceNumber >> 24); - seq[1] = (unsigned char) (sequenceNumber >> 16); - seq[2] = (unsigned char) (sequenceNumber >> 8); - seq[3] = (unsigned char) (sequenceNumber); + ssl_ReleaseSpecReadLock(ss); /******************************/ - (*ss->sec.hash->begin)(ss->sec.hashcx); - (*ss->sec.hash->update)(ss->sec.hashcx, ss->sec.rcvSecret.data, - ss->sec.rcvSecret.len); - (*ss->sec.hash->update)(ss->sec.hashcx, pBuf + macLen, - gs->offset - macLen); - (*ss->sec.hash->update)(ss->sec.hashcx, seq, 4); - (*ss->sec.hash->end)(ss->sec.hashcx, mac, &macLen, macLen); + if (NSS_SecureMemcmp(mac, pBuf, macLen) != 0) { + /* MAC's didn't match... */ + SSL_DBG(("%d: SSL[%d]: mac check failed, seq=%d", + SSL_GETPID(), ss->fd, ss->sec.rcvSequence)); + PRINT_BUF(1, (ss, "computed mac:", mac, macLen)); + PRINT_BUF(1, (ss, "received mac:", pBuf, macLen)); + PORT_SetError(SSL_ERROR_BAD_MAC_READ); + rv = SECFailure; + goto cleanup; + } + } + else { + ssl_ReleaseSpecReadLock(ss); /******************************/ + } - PORT_Assert(macLen == ss->sec.hash->length); + if (gs->recordPadding + macLen <= gs->offset) { + gs->recordOffset = macLen; + gs->readOffset = macLen; + gs->writeOffset = gs->offset - gs->recordPadding; + rv = 1; + } + else { + PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING); + cleanup: + /* nothing in the buffer any more. */ + gs->recordOffset = 0; + gs->readOffset = 0; + gs->writeOffset = 0; + rv = SECFailure; + } - ssl_ReleaseSpecReadLock(ss); /******************************/ + gs->recordLen = gs->writeOffset - gs->readOffset; + gs->recordPadding = 0; /* forget we did any padding. */ + gs->state = GS_INIT; - if (NSS_SecureMemcmp(mac, pBuf, macLen) != 0) { - /* MAC's didn't match... */ - SSL_DBG(("%d: SSL[%d]: mac check failed, seq=%d", - SSL_GETPID(), ss->fd, ss->sec.rcvSequence)); - PRINT_BUF(1, (ss, "computed mac:", mac, macLen)); - PRINT_BUF(1, (ss, "received mac:", pBuf, macLen)); - PORT_SetError(SSL_ERROR_BAD_MAC_READ); - rv = SECFailure; - goto cleanup; - } - } else { - ssl_ReleaseSpecReadLock(ss); /******************************/ - } + if (rv > 0) { + PRINT_BUF(50, (ss, "recv clear record:", + pBuf + gs->recordOffset, gs->recordLen)); + } + return rv; - if (gs->recordPadding + macLen <= gs->offset) { - gs->recordOffset = macLen; - gs->readOffset = macLen; - gs->writeOffset = gs->offset - gs->recordPadding; - rv = 1; - } else { - PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING); -cleanup: - /* nothing in the buffer any more. */ - gs->recordOffset = 0; - gs->readOffset = 0; - gs->writeOffset = 0; - rv = SECFailure; - } + spec_locked_done: + ssl_ReleaseSpecReadLock(ss); + return rv; + } - gs->recordLen = gs->writeOffset - gs->readOffset; - gs->recordPadding = 0; /* forget we did any padding. */ - gs->state = GS_INIT; + case GS_DATA: + /* Have read in all the DATA portion of record */ + gs->recordOffset = 0; + gs->readOffset = 0; + gs->writeOffset = gs->offset; + PORT_Assert(gs->recordLen == gs->writeOffset - gs->readOffset); + gs->recordLen = gs->offset; + gs->recordPadding = 0; + gs->state = GS_INIT; - if (rv > 0) { - PRINT_BUF(50, (ss, "recv clear record:", - pBuf + gs->recordOffset, gs->recordLen)); - } - return rv; + ++ss->sec.rcvSequence; -spec_locked_done: - ssl_ReleaseSpecReadLock(ss); - return rv; - } + PRINT_BUF(50, (ss, "recv clear record:", + pBuf + gs->recordOffset, gs->recordLen)); + return 1; - case GS_DATA: - /* Have read in all the DATA portion of record */ - - gs->recordOffset = 0; - gs->readOffset = 0; - gs->writeOffset = gs->offset; - PORT_Assert(gs->recordLen == gs->writeOffset - gs->readOffset); - gs->recordLen = gs->offset; - gs->recordPadding = 0; - gs->state = GS_INIT; - - ++ss->sec.rcvSequence; - - PRINT_BUF(50, (ss, "recv clear record:", - pBuf + gs->recordOffset, gs->recordLen)); - return 1; - - } /* end switch gs->state */ - } /* end gather loop. */ + } /* end switch gs->state */ + } /* end gather loop. */ return rv; } @@ -352,13 +354,13 @@ spec_locked_done: * Returns +1 when it has gathered a complete SSLV2 record. * Returns 0 if it hits EOF. * Returns -1 (SECFailure) on any error - * Returns -2 (SECWouldBlock) + * Returns -2 (SECWouldBlock) * - * Called by ssl_GatherRecord1stHandshake in sslcon.c, + * Called by ssl_GatherRecord1stHandshake in sslcon.c, * and by DoRecv in sslsecur.c * Caller must hold RecvBufLock. */ -int +int ssl2_GatherRecord(sslSocket *ss, int flags) { return ssl2_GatherData(ss, &ss->gs, flags); @@ -372,7 +374,7 @@ ssl_InitGather(sslGather *gs) gs->state = GS_INIT; gs->writeOffset = 0; - gs->readOffset = 0; + gs->readOffset = 0; gs->dtlsPacketOffset = 0; gs->dtlsPacket.len = 0; status = sslBuffer_Grow(&gs->buf, 4096); @@ -380,13 +382,13 @@ ssl_InitGather(sslGather *gs) } /* Caller must hold RecvBufLock. */ -void +void ssl_DestroyGather(sslGather *gs) { - if (gs) { /* the PORT_*Free functions check for NULL pointers. */ - PORT_ZFree(gs->buf.buf, gs->buf.space); - PORT_Free(gs->inbuf.buf); - PORT_Free(gs->dtlsPacket.buf); + if (gs) { /* the PORT_*Free functions check for NULL pointers. */ + PORT_ZFree(gs->buf.buf, gs->buf.space); + PORT_Free(gs->inbuf.buf); + PORT_Free(gs->dtlsPacket.buf); } } @@ -394,32 +396,32 @@ ssl_DestroyGather(sslGather *gs) static SECStatus ssl2_HandleV3HandshakeRecord(sslSocket *ss) { - SECStatus rv; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); /* We've read in 3 bytes, there are 2 more to go in an ssl3 header. */ - ss->gs.remainder = 2; - ss->gs.count = 0; + ss->gs.remainder = 2; + ss->gs.count = 0; - /* Clearing these handshake pointers ensures that + /* Clearing these handshake pointers ensures that * ssl_Do1stHandshake won't call ssl2_HandleMessage when we return. */ - ss->nextHandshake = 0; + ss->nextHandshake = 0; ss->securityHandshake = 0; - /* Setting ss->version to an SSL 3.x value will cause - ** ssl_GatherRecord1stHandshake to invoke ssl3_GatherCompleteHandshake() + /* Setting ss->version to an SSL 3.x value will cause + ** ssl_GatherRecord1stHandshake to invoke ssl3_GatherCompleteHandshake() ** the next time it is called. **/ rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, - PR_TRUE); + PR_TRUE); if (rv != SECSuccess) { - return rv; + return rv; } - ss->sec.send = ssl3_SendApplicationData; + ss->sec.send = ssl3_SendApplicationData; return SECSuccess; } diff --git a/security/nss/lib/ssl/sslimpl.h b/security/nss/lib/ssl/sslimpl.h index a7ebc9aa6a5a..bce943769578 100644 --- a/security/nss/lib/ssl/sslimpl.h +++ b/security/nss/lib/ssl/sslimpl.h @@ -36,33 +36,34 @@ ** it was necessary to prepend ssl_ to the names. ** These #defines preserve compatibility with the old code here in libssl. */ -typedef SSLKEAType SSL3KEAType; +typedef SSLKEAType SSL3KEAType; typedef SSLMACAlgorithm SSL3MACAlgorithm; -#define calg_null ssl_calg_null -#define calg_rc4 ssl_calg_rc4 -#define calg_rc2 ssl_calg_rc2 -#define calg_des ssl_calg_des -#define calg_3des ssl_calg_3des -#define calg_idea ssl_calg_idea -#define calg_fortezza ssl_calg_fortezza /* deprecated, must preserve */ -#define calg_aes ssl_calg_aes -#define calg_camellia ssl_calg_camellia -#define calg_seed ssl_calg_seed -#define calg_aes_gcm ssl_calg_aes_gcm +#define calg_null ssl_calg_null +#define calg_rc4 ssl_calg_rc4 +#define calg_rc2 ssl_calg_rc2 +#define calg_des ssl_calg_des +#define calg_3des ssl_calg_3des +#define calg_idea ssl_calg_idea +#define calg_fortezza ssl_calg_fortezza /* deprecated, must preserve */ +#define calg_aes ssl_calg_aes +#define calg_camellia ssl_calg_camellia +#define calg_seed ssl_calg_seed +#define calg_aes_gcm ssl_calg_aes_gcm +#define calg_chacha20 ssl_calg_chacha20 -#define mac_null ssl_mac_null -#define mac_md5 ssl_mac_md5 -#define mac_sha ssl_mac_sha -#define hmac_md5 ssl_hmac_md5 -#define hmac_sha ssl_hmac_sha -#define hmac_sha256 ssl_hmac_sha256 -#define mac_aead ssl_mac_aead +#define mac_null ssl_mac_null +#define mac_md5 ssl_mac_md5 +#define mac_sha ssl_mac_sha +#define hmac_md5 ssl_hmac_md5 +#define hmac_sha ssl_hmac_sha +#define hmac_sha256 ssl_hmac_sha256 +#define mac_aead ssl_mac_aead -#define SET_ERROR_CODE /* reminder */ -#define SEND_ALERT /* reminder */ -#define TEST_FOR_FAILURE /* reminder */ -#define DEAL_WITH_FAILURE /* reminder */ +#define SET_ERROR_CODE /* reminder */ +#define SEND_ALERT /* reminder */ +#define TEST_FOR_FAILURE /* reminder */ +#define DEAL_WITH_FAILURE /* reminder */ #if defined(DEBUG) || defined(TRACE) #ifdef __cplusplus @@ -79,63 +80,71 @@ extern int Debug; #endif #ifdef TRACE -#define SSL_TRC(a,b) if (ssl_trace >= (a)) ssl_Trace b -#define PRINT_BUF(a,b) if (ssl_trace >= (a)) ssl_PrintBuf b -#define DUMP_MSG(a,b) if (ssl_trace >= (a)) ssl_DumpMsg b +#define SSL_TRC(a, b) \ + if (ssl_trace >= (a)) \ + ssl_Trace b +#define PRINT_BUF(a, b) \ + if (ssl_trace >= (a)) \ + ssl_PrintBuf b +#define DUMP_MSG(a, b) \ + if (ssl_trace >= (a)) \ + ssl_DumpMsg b #else -#define SSL_TRC(a,b) -#define PRINT_BUF(a,b) -#define DUMP_MSG(a,b) +#define SSL_TRC(a, b) +#define PRINT_BUF(a, b) +#define DUMP_MSG(a, b) #endif #ifdef DEBUG -#define SSL_DBG(b) if (ssl_debug) ssl_Trace b +#define SSL_DBG(b) \ + if (ssl_debug) \ + ssl_Trace b #else #define SSL_DBG(b) #endif -#include "private/pprthred.h" /* for PR_InMonitor() */ +#include "private/pprthred.h" /* for PR_InMonitor() */ #define ssl_InMonitor(m) PZ_InMonitor(m) -#define LSB(x) ((unsigned char) ((x) & 0xff)) -#define MSB(x) ((unsigned char) (((unsigned)(x)) >> 8)) +#define LSB(x) ((unsigned char)((x)&0xff)) +#define MSB(x) ((unsigned char)(((unsigned)(x)) >> 8)) /************************************************************************/ typedef enum { SSLAppOpRead = 0, - SSLAppOpWrite, - SSLAppOpRDWR, - SSLAppOpPost, - SSLAppOpHeader + SSLAppOpWrite, + SSLAppOpRDWR, + SSLAppOpPost, + SSLAppOpHeader } SSLAppOperation; -#define SSL_MIN_MASTER_KEY_BYTES 5 -#define SSL_MAX_MASTER_KEY_BYTES 64 +#define SSL_MIN_MASTER_KEY_BYTES 5 +#define SSL_MAX_MASTER_KEY_BYTES 64 -#define SSL2_SESSIONID_BYTES 16 -#define SSL3_SESSIONID_BYTES 32 +#define SSL2_SESSIONID_BYTES 16 +#define SSL3_SESSIONID_BYTES 32 -#define SSL_MIN_CHALLENGE_BYTES 16 -#define SSL_MAX_CHALLENGE_BYTES 32 -#define SSL_CHALLENGE_BYTES 16 +#define SSL_MIN_CHALLENGE_BYTES 16 +#define SSL_MAX_CHALLENGE_BYTES 32 +#define SSL_CHALLENGE_BYTES 16 -#define SSL_CONNECTIONID_BYTES 16 +#define SSL_CONNECTIONID_BYTES 16 -#define SSL_MIN_CYPHER_ARG_BYTES 0 -#define SSL_MAX_CYPHER_ARG_BYTES 32 +#define SSL_MIN_CYPHER_ARG_BYTES 0 +#define SSL_MAX_CYPHER_ARG_BYTES 32 -#define SSL_MAX_MAC_BYTES 16 +#define SSL_MAX_MAC_BYTES 16 #define SSL3_RSA_PMS_LENGTH 48 #define SSL3_MASTER_SECRET_LENGTH 48 /* number of wrap mechanisms potentially used to wrap master secrets. */ -#define SSL_NUM_WRAP_MECHS 16 +#define SSL_NUM_WRAP_MECHS 16 /* This makes the cert cache entry exactly 4k. */ -#define SSL_MAX_CACHED_CERT_LEN 4060 +#define SSL_MAX_CACHED_CERT_LEN 4060 -#define NUM_MIXERS 9 +#define NUM_MIXERS 9 /* Mask of the 25 named curves we support. */ #define SSL3_ALL_SUPPORTED_CURVES_MASK 0x3fffffe @@ -146,77 +155,77 @@ typedef enum { SSLAppOpRead = 0, #define BPB 8 /* Bits Per Byte */ #endif -#define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ +#define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ -#define INITIAL_DTLS_TIMEOUT_MS 1000 /* Default value from RFC 4347 = 1s*/ -#define MAX_DTLS_TIMEOUT_MS 60000 /* 1 minute */ -#define DTLS_FINISHED_TIMER_MS 120000 /* Time to wait in FINISHED state */ +#define INITIAL_DTLS_TIMEOUT_MS 1000 /* Default value from RFC 4347 = 1s*/ +#define MAX_DTLS_TIMEOUT_MS 60000 /* 1 minute */ +#define DTLS_FINISHED_TIMER_MS 120000 /* Time to wait in FINISHED state */ -typedef struct sslBufferStr sslBuffer; -typedef struct sslConnectInfoStr sslConnectInfo; -typedef struct sslGatherStr sslGather; -typedef struct sslSecurityInfoStr sslSecurityInfo; -typedef struct sslSessionIDStr sslSessionID; -typedef struct sslSocketStr sslSocket; -typedef struct sslSocketOpsStr sslSocketOps; +typedef struct sslBufferStr sslBuffer; +typedef struct sslConnectInfoStr sslConnectInfo; +typedef struct sslGatherStr sslGather; +typedef struct sslSecurityInfoStr sslSecurityInfo; +typedef struct sslSessionIDStr sslSessionID; +typedef struct sslSocketStr sslSocket; +typedef struct sslSocketOpsStr sslSocketOps; -typedef struct ssl3StateStr ssl3State; -typedef struct ssl3CertNodeStr ssl3CertNode; -typedef struct ssl3BulkCipherDefStr ssl3BulkCipherDef; -typedef struct ssl3MACDefStr ssl3MACDef; -typedef struct ssl3KeyPairStr ssl3KeyPair; -typedef struct ssl3DHParamsStr ssl3DHParams; +typedef struct ssl3StateStr ssl3State; +typedef struct ssl3CertNodeStr ssl3CertNode; +typedef struct ssl3BulkCipherDefStr ssl3BulkCipherDef; +typedef struct ssl3MACDefStr ssl3MACDef; +typedef struct ssl3KeyPairStr ssl3KeyPair; +typedef struct ssl3DHParamsStr ssl3DHParams; struct ssl3CertNodeStr { struct ssl3CertNodeStr *next; - CERTCertificate * cert; + CERTCertificate *cert; }; typedef SECStatus (*sslHandshakeFunc)(sslSocket *ss); -/* This type points to the low layer send func, +/* This type points to the low layer send func, ** e.g. ssl2_SendStream or ssl3_SendPlainText. -** These functions return the same values as PR_Send, +** These functions return the same values as PR_Send, ** i.e. >= 0 means number of bytes sent, < 0 means error. */ -typedef PRInt32 (*sslSendFunc)(sslSocket *ss, const unsigned char *buf, - PRInt32 n, PRInt32 flags); +typedef PRInt32 (*sslSendFunc)(sslSocket *ss, const unsigned char *buf, + PRInt32 n, PRInt32 flags); -typedef void (*sslSessionIDCacheFunc) (sslSessionID *sid); -typedef void (*sslSessionIDUncacheFunc)(sslSessionID *sid); -typedef sslSessionID *(*sslSessionIDLookupFunc)(const PRIPv6Addr *addr, - unsigned char* sid, - unsigned int sidLen, - CERTCertDBHandle * dbHandle); +typedef void (*sslSessionIDCacheFunc)(sslSessionID *sid); +typedef void (*sslSessionIDUncacheFunc)(sslSessionID *sid); +typedef sslSessionID *(*sslSessionIDLookupFunc)(const PRIPv6Addr *addr, + unsigned char *sid, + unsigned int sidLen, + CERTCertDBHandle *dbHandle); /* registerable callback function that either appends extension to buffer * or returns length of data that it would have appended. */ typedef PRInt32 (*ssl3HelloExtensionSenderFunc)(sslSocket *ss, PRBool append, - PRUint32 maxBytes); + PRUint32 maxBytes); -/* registerable callback function that handles a received extension, +/* registerable callback function that handles a received extension, * of the given type. */ -typedef SECStatus (* ssl3HelloExtensionHandlerFunc)(sslSocket *ss, - PRUint16 ex_type, - SECItem * data); +typedef SECStatus (*ssl3HelloExtensionHandlerFunc)(sslSocket *ss, + PRUint16 ex_type, + SECItem *data); /* row in a table of hello extension senders */ typedef struct { - PRInt32 ex_type; + PRInt32 ex_type; ssl3HelloExtensionSenderFunc ex_sender; } ssl3HelloExtensionSender; /* row in a table of hello extension handlers */ typedef struct { - PRInt32 ex_type; + PRInt32 ex_type; ssl3HelloExtensionHandlerFunc ex_handler; } ssl3HelloExtensionHandler; -extern SECStatus +extern SECStatus ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type, - ssl3HelloExtensionSenderFunc cb); + ssl3HelloExtensionSenderFunc cb); extern PRInt32 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, @@ -227,44 +236,44 @@ ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength); extern PRInt32 ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen, - PRUint32 maxBytes); + PRUint32 maxBytes); /* Socket ops */ struct sslSocketOpsStr { - int (*connect) (sslSocket *, const PRNetAddr *); - PRFileDesc *(*accept) (sslSocket *, PRNetAddr *); - int (*bind) (sslSocket *, const PRNetAddr *); - int (*listen) (sslSocket *, int); - int (*shutdown)(sslSocket *, int); - int (*close) (sslSocket *); + int (*connect)(sslSocket *, const PRNetAddr *); + PRFileDesc *(*accept)(sslSocket *, PRNetAddr *); + int (*bind)(sslSocket *, const PRNetAddr *); + int (*listen)(sslSocket *, int); + int (*shutdown)(sslSocket *, int); + int (*close)(sslSocket *); - int (*recv) (sslSocket *, unsigned char *, int, int); + int (*recv)(sslSocket *, unsigned char *, int, int); /* points to the higher-layer send func, e.g. ssl_SecureSend. */ - int (*send) (sslSocket *, const unsigned char *, int, int); - int (*read) (sslSocket *, unsigned char *, int); - int (*write) (sslSocket *, const unsigned char *, int); + int (*send)(sslSocket *, const unsigned char *, int, int); + int (*read)(sslSocket *, unsigned char *, int); + int (*write)(sslSocket *, const unsigned char *, int); - int (*getpeername)(sslSocket *, PRNetAddr *); - int (*getsockname)(sslSocket *, PRNetAddr *); + int (*getpeername)(sslSocket *, PRNetAddr *); + int (*getsockname)(sslSocket *, PRNetAddr *); }; /* Flags interpreted by ssl send functions. */ -#define ssl_SEND_FLAG_FORCE_INTO_BUFFER 0x40000000 -#define ssl_SEND_FLAG_NO_BUFFER 0x20000000 -#define ssl_SEND_FLAG_USE_EPOCH 0x10000000 /* DTLS only */ -#define ssl_SEND_FLAG_NO_RETRANSMIT 0x08000000 /* DTLS only */ +#define ssl_SEND_FLAG_FORCE_INTO_BUFFER 0x40000000 +#define ssl_SEND_FLAG_NO_BUFFER 0x20000000 +#define ssl_SEND_FLAG_USE_EPOCH 0x10000000 /* DTLS only */ +#define ssl_SEND_FLAG_NO_RETRANSMIT 0x08000000 /* DTLS only */ #define ssl_SEND_FLAG_CAP_RECORD_VERSION \ - 0x04000000 /* TLS only */ -#define ssl_SEND_FLAG_MASK 0x7f000000 + 0x04000000 /* TLS only */ +#define ssl_SEND_FLAG_MASK 0x7f000000 /* ** A buffer object. */ struct sslBufferStr { - unsigned char * buf; - unsigned int len; - unsigned int space; + unsigned char *buf; + unsigned int len; + unsigned int space; }; /* @@ -272,22 +281,22 @@ struct sslBufferStr { */ typedef struct { #if !defined(_WIN32) - unsigned int cipher_suite : 16; - unsigned int policy : 8; - unsigned int enabled : 1; - unsigned int isPresent : 1; + unsigned int cipher_suite : 16; + unsigned int policy : 8; + unsigned int enabled : 1; + unsigned int isPresent : 1; #else ssl3CipherSuite cipher_suite; - PRUint8 policy; - unsigned char enabled : 1; - unsigned char isPresent : 1; + PRUint8 policy; + unsigned char enabled : 1; + unsigned char isPresent : 1; #endif } ssl3CipherSuiteCfg; #ifndef NSS_DISABLE_ECC -#define ssl_V3_SUITES_IMPLEMENTED 64 +#define ssl_V3_SUITES_IMPLEMENTED 67 #else -#define ssl_V3_SUITES_IMPLEMENTED 40 +#define ssl_V3_SUITES_IMPLEMENTED 41 #endif /* NSS_DISABLE_ECC */ #define MAX_DTLS_SRTP_CIPHER_SUITES 4 @@ -297,72 +306,73 @@ typedef struct { * doesn't allow space for combinations with MD5). */ #define MAX_SIGNATURE_ALGORITHMS 15 - +/* clang-format off */ typedef struct sslOptionsStr { /* If SSL_SetNextProtoNego has been called, then this contains the * list of supported protocols. */ SECItem nextProtoNego; - unsigned int useSecurity : 1; /* 1 */ - unsigned int useSocks : 1; /* 2 */ - unsigned int requestCertificate : 1; /* 3 */ - unsigned int requireCertificate : 2; /* 4-5 */ - unsigned int handshakeAsClient : 1; /* 6 */ - unsigned int handshakeAsServer : 1; /* 7 */ - unsigned int enableSSL2 : 1; /* 8 */ - unsigned int unusedBit9 : 1; /* 9 */ - unsigned int unusedBit10 : 1; /* 10 */ - unsigned int noCache : 1; /* 11 */ - unsigned int fdx : 1; /* 12 */ - unsigned int v2CompatibleHello : 1; /* 13 */ - unsigned int detectRollBack : 1; /* 14 */ - unsigned int noStepDown : 1; /* 15 */ - unsigned int bypassPKCS11 : 1; /* 16 */ - unsigned int noLocks : 1; /* 17 */ - unsigned int enableSessionTickets : 1; /* 18 */ - unsigned int enableDeflate : 1; /* 19 */ - unsigned int enableRenegotiation : 2; /* 20-21 */ - unsigned int requireSafeNegotiation : 1; /* 22 */ - unsigned int enableFalseStart : 1; /* 23 */ - unsigned int cbcRandomIV : 1; /* 24 */ - unsigned int enableOCSPStapling : 1; /* 25 */ - unsigned int enableNPN : 1; /* 26 */ - unsigned int enableALPN : 1; /* 27 */ - unsigned int reuseServerECDHEKey : 1; /* 28 */ - unsigned int enableFallbackSCSV : 1; /* 29 */ - unsigned int enableServerDhe : 1; /* 30 */ - unsigned int enableExtendedMS : 1; /* 31 */ + unsigned int useSecurity : 1; /* 1 */ + unsigned int useSocks : 1; /* 2 */ + unsigned int requestCertificate : 1; /* 3 */ + unsigned int requireCertificate : 2; /* 4-5 */ + unsigned int handshakeAsClient : 1; /* 6 */ + unsigned int handshakeAsServer : 1; /* 7 */ + unsigned int enableSSL2 : 1; /* 8 */ + unsigned int unusedBit9 : 1; /* 9 */ + unsigned int unusedBit10 : 1; /* 10 */ + unsigned int noCache : 1; /* 11 */ + unsigned int fdx : 1; /* 12 */ + unsigned int v2CompatibleHello : 1; /* 13 */ + unsigned int detectRollBack : 1; /* 14 */ + unsigned int noStepDown : 1; /* 15 */ + unsigned int bypassPKCS11 : 1; /* 16 */ + unsigned int noLocks : 1; /* 17 */ + unsigned int enableSessionTickets : 1; /* 18 */ + unsigned int enableDeflate : 1; /* 19 */ + unsigned int enableRenegotiation : 2; /* 20-21 */ + unsigned int requireSafeNegotiation : 1; /* 22 */ + unsigned int enableFalseStart : 1; /* 23 */ + unsigned int cbcRandomIV : 1; /* 24 */ + unsigned int enableOCSPStapling : 1; /* 25 */ + unsigned int enableNPN : 1; /* 26 */ + unsigned int enableALPN : 1; /* 27 */ + unsigned int reuseServerECDHEKey : 1; /* 28 */ + unsigned int enableFallbackSCSV : 1; /* 29 */ + unsigned int enableServerDhe : 1; /* 30 */ + unsigned int enableExtendedMS : 1; /* 31 */ unsigned int enableSignedCertTimestamps : 1; /* 32 */ } sslOptions; +/* clang-format on */ typedef enum { sslHandshakingUndetermined = 0, - sslHandshakingAsClient, - sslHandshakingAsServer + sslHandshakingAsClient, + sslHandshakingAsServer } sslHandshakingType; typedef struct sslServerCertsStr { /* Configuration state for server sockets */ - CERTCertificate * serverCert; - CERTCertificateList * serverCertChain; - ssl3KeyPair * serverKeyPair; - unsigned int serverKeyBits; + CERTCertificate *serverCert; + CERTCertificateList *serverCertChain; + ssl3KeyPair *serverKeyPair; + unsigned int serverKeyBits; } sslServerCerts; #define SERVERKEY serverKeyPair->privKey -#define SSL_LOCK_RANK_SPEC 255 -#define SSL_LOCK_RANK_GLOBAL NSS_RWLOCK_RANK_NONE +#define SSL_LOCK_RANK_SPEC 255 +#define SSL_LOCK_RANK_GLOBAL NSS_RWLOCK_RANK_NONE -/* These are the valid values for shutdownHow. +/* These are the valid values for shutdownHow. ** These values are each 1 greater than the NSPR values, and the code -** depends on that relation to efficiently convert PR_SHUTDOWN values -** into ssl_SHUTDOWN values. These values use one bit for read, and +** depends on that relation to efficiently convert PR_SHUTDOWN values +** into ssl_SHUTDOWN values. These values use one bit for read, and ** another bit for write, and can be used as bitmasks. */ -#define ssl_SHUTDOWN_NONE 0 /* NOT shutdown at all */ -#define ssl_SHUTDOWN_RCV 1 /* PR_SHUTDOWN_RCV +1 */ -#define ssl_SHUTDOWN_SEND 2 /* PR_SHUTDOWN_SEND +1 */ -#define ssl_SHUTDOWN_BOTH 3 /* PR_SHUTDOWN_BOTH +1 */ +#define ssl_SHUTDOWN_NONE 0 /* NOT shutdown at all */ +#define ssl_SHUTDOWN_RCV 1 /* PR_SHUTDOWN_RCV +1 */ +#define ssl_SHUTDOWN_SEND 2 /* PR_SHUTDOWN_SEND +1 */ +#define ssl_SHUTDOWN_BOTH 3 /* PR_SHUTDOWN_BOTH +1 */ /* ** A gather object. Used to read some data until a count has been @@ -370,85 +380,83 @@ typedef struct sslServerCertsStr { ** Everything in here is protected by the recvBufLock. */ struct sslGatherStr { - int state; /* see GS_ values below. */ /* ssl 2 & 3 */ + int state; /* see GS_ values below. */ /* ssl 2 & 3 */ /* "buf" holds received plaintext SSL records, after decrypt and MAC check. * SSL2: recv'd ciphertext records are put here, then decrypted in place. - * SSL3: recv'd ciphertext records are put in inbuf (see below), then + * SSL3: recv'd ciphertext records are put in inbuf (see below), then * decrypted into buf. */ - sslBuffer buf; /*recvBufLock*/ /* ssl 2 & 3 */ + sslBuffer buf; /*recvBufLock*/ /* ssl 2 & 3 */ - /* number of bytes previously read into hdr or buf(ssl2) or inbuf (ssl3). - ** (offset - writeOffset) is the number of ciphertext bytes read in but + /* number of bytes previously read into hdr or buf(ssl2) or inbuf (ssl3). + ** (offset - writeOffset) is the number of ciphertext bytes read in but ** not yet deciphered. */ - unsigned int offset; /* ssl 2 & 3 */ + unsigned int offset; /* ssl 2 & 3 */ /* number of bytes to read in next call to ssl_DefRecv (recv) */ - unsigned int remainder; /* ssl 2 & 3 */ + unsigned int remainder; /* ssl 2 & 3 */ /* Number of ciphertext bytes to read in after 2-byte SSL record header. */ - unsigned int count; /* ssl2 only */ + unsigned int count; /* ssl2 only */ - /* size of the final plaintext record. + /* size of the final plaintext record. ** == count - (recordPadding + MAC size) */ - unsigned int recordLen; /* ssl2 only */ + unsigned int recordLen; /* ssl2 only */ /* number of bytes of padding to be removed after decrypting. */ /* This value is taken from the record's hdr[2], which means a too large * value could crash us. */ - unsigned int recordPadding; /* ssl2 only */ + unsigned int recordPadding; /* ssl2 only */ /* plaintext DATA begins this many bytes into "buf". */ - unsigned int recordOffset; /* ssl2 only */ + unsigned int recordOffset; /* ssl2 only */ - int encrypted; /* SSL2 session is now encrypted. ssl2 only */ + int encrypted; /* SSL2 session is now encrypted. ssl2 only */ - /* These next two values are used by SSL2 and SSL3. + /* These next two values are used by SSL2 and SSL3. ** DoRecv uses them to extract application data. - ** The difference between writeOffset and readOffset is the amount of - ** data available to the application. Note that the actual offset of + ** The difference between writeOffset and readOffset is the amount of + ** data available to the application. Note that the actual offset of ** the data in "buf" is recordOffset (above), not readOffset. - ** In the current implementation, this is made available before the + ** In the current implementation, this is made available before the ** MAC is checked!! */ - unsigned int readOffset; /* Spot where DATA reader (e.g. application + unsigned int readOffset; /* Spot where DATA reader (e.g. application ** or handshake code) will read next. ** Always zero for SSl3 application data. - */ + */ /* offset in buf/inbuf/hdr into which new data will be read from socket. */ - unsigned int writeOffset; + unsigned int writeOffset; /* Buffer for ssl3 to read (encrypted) data from the socket */ - sslBuffer inbuf; /*recvBufLock*/ /* ssl3 only */ + sslBuffer inbuf; /*recvBufLock*/ /* ssl3 only */ /* The ssl[23]_GatherData functions read data into this buffer, rather - ** than into buf or inbuf, while in the GS_HEADER state. - ** The portion of the SSL record header put here always comes off the wire + ** than into buf or inbuf, while in the GS_HEADER state. + ** The portion of the SSL record header put here always comes off the wire ** as plaintext, never ciphertext. ** For SSL2, the plaintext portion is two bytes long. For SSl3 it is 5. ** For DTLS it is 13. */ - unsigned char hdr[13]; /* ssl 2 & 3 or dtls */ + unsigned char hdr[13]; /* ssl 2 & 3 or dtls */ /* Buffer for DTLS data read off the wire as a single datagram */ - sslBuffer dtlsPacket; + sslBuffer dtlsPacket; /* the start of the buffered DTLS record in dtlsPacket */ - unsigned int dtlsPacketOffset; + unsigned int dtlsPacketOffset; }; /* sslGather.state */ -#define GS_INIT 0 -#define GS_HEADER 1 -#define GS_MAC 2 -#define GS_DATA 3 -#define GS_PAD 4 - - +#define GS_INIT 0 +#define GS_HEADER 1 +#define GS_MAC 2 +#define GS_DATA 3 +#define GS_PAD 4 /* ** ssl3State and CipherSpec structs @@ -457,35 +465,38 @@ struct sslGatherStr { /* The SSL bulk cipher definition */ typedef enum { cipher_null, - cipher_rc4, + cipher_rc4, cipher_rc4_40, cipher_rc4_56, - cipher_rc2, + cipher_rc2, cipher_rc2_40, - cipher_des, - cipher_3des, + cipher_des, + cipher_3des, cipher_des40, - cipher_idea, + cipher_idea, cipher_aes_128, cipher_aes_256, cipher_camellia_128, cipher_camellia_256, cipher_seed, cipher_aes_128_gcm, - cipher_missing /* reserved for no such supported cipher */ + cipher_chacha20, + cipher_missing /* reserved for no such supported cipher */ /* This enum must match ssl3_cipherName[] in ssl3con.c. */ } SSL3BulkCipher; -typedef enum { type_stream, type_block, type_aead } CipherType; +typedef enum { type_stream, + type_block, + type_aead } CipherType; #define MAX_IV_LENGTH 24 /* - * Do not depend upon 64 bit arithmetic in the underlying machine. + * Do not depend upon 64 bit arithmetic in the underlying machine. */ typedef struct { - PRUint32 high; - PRUint32 low; + PRUint32 high; + PRUint32 low; } SSL3SequenceNumber; typedef PRUint16 DTLSEpoch; @@ -501,46 +512,46 @@ typedef void (*DTLSTimerCb)(sslSocket *); #define MAX_CIPHER_CONTEXT_LLONGS (MAX_CIPHER_CONTEXT_BYTES / 8) typedef struct { - SSL3Opaque wrapped_master_secret[48]; - PRUint16 wrapped_master_secret_len; - PRUint8 msIsWrapped; - PRUint8 resumable; - PRUint8 extendedMasterSecretUsed; + SSL3Opaque wrapped_master_secret[48]; + PRUint16 wrapped_master_secret_len; + PRUint8 msIsWrapped; + PRUint8 resumable; + PRUint8 extendedMasterSecretUsed; } ssl3SidKeys; /* 52 bytes */ typedef struct { - PK11SymKey *write_key; - PK11SymKey *write_mac_key; + PK11SymKey *write_key; + PK11SymKey *write_mac_key; PK11Context *write_mac_context; - SECItem write_key_item; - SECItem write_iv_item; - SECItem write_mac_key_item; - SSL3Opaque write_iv[MAX_IV_LENGTH]; - PRUint64 cipher_context[MAX_CIPHER_CONTEXT_LLONGS]; + SECItem write_key_item; + SECItem write_iv_item; + SECItem write_mac_key_item; + SSL3Opaque write_iv[MAX_IV_LENGTH]; + PRUint64 cipher_context[MAX_CIPHER_CONTEXT_LLONGS]; } ssl3KeyMaterial; -typedef SECStatus (*SSLCipher)(void * context, - unsigned char * out, - int * outlen, - int maxout, - const unsigned char *in, - int inlen); +typedef SECStatus (*SSLCipher)(void *context, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen); typedef SECStatus (*SSLAEADCipher)( - ssl3KeyMaterial * keys, - PRBool doDecrypt, - unsigned char * out, - int * outlen, - int maxout, - const unsigned char *in, - int inlen, - const unsigned char *additionalData, - int additionalDataLen); -typedef SECStatus (*SSLCompressor)(void * context, - unsigned char * out, - int * outlen, - int maxout, + ssl3KeyMaterial *keys, + PRBool doDecrypt, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen, + const unsigned char *additionalData, + int additionalDataLen); +typedef SECStatus (*SSLCompressor)(void *context, + unsigned char *out, + int *outlen, + int maxout, const unsigned char *in, - int inlen); + int inlen); typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit); /* The DTLS anti-replay window. Defined here because we need it in @@ -548,11 +559,11 @@ typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit); * right represent the true window, with modular arithmetic used to * map them onto the buffer. */ -#define DTLS_RECVD_RECORDS_WINDOW 1024 /* Packets; approximate - * Must be divisible by 8 - */ +#define DTLS_RECVD_RECORDS_WINDOW 1024 /* Packets; approximate \ + * Must be divisible by 8 \ + */ typedef struct DTLSRecvdRecordsStr { - unsigned char data[DTLS_RECVD_RECORDS_WINDOW/8]; + unsigned char data[DTLS_RECVD_RECORDS_WINDOW / 8]; PRUint64 left; PRUint64 right; } DTLSRecvdRecords; @@ -564,168 +575,168 @@ typedef struct DTLSRecvdRecordsStr { */ typedef struct { const ssl3BulkCipherDef *cipher_def; - const ssl3MACDef * mac_def; + const ssl3MACDef *mac_def; SSLCompressionMethod compression_method; - int mac_size; - SSLCipher encode; - SSLCipher decode; - SSLAEADCipher aead; - SSLDestroy destroy; - void * encodeContext; - void * decodeContext; - SSLCompressor compressor; /* Don't name these fields compress */ - SSLCompressor decompressor; /* and uncompress because zconf.h */ - /* may define them as macros. */ - SSLDestroy destroyCompressContext; - void * compressContext; - SSLDestroy destroyDecompressContext; - void * decompressContext; - PRBool bypassCiphers; /* did double bypass (at least) */ - PK11SymKey * master_secret; + int mac_size; + SSLCipher encode; + SSLCipher decode; + SSLAEADCipher aead; + SSLDestroy destroy; + void *encodeContext; + void *decodeContext; + SSLCompressor compressor; /* Don't name these fields compress */ + SSLCompressor decompressor; /* and uncompress because zconf.h */ + /* may define them as macros. */ + SSLDestroy destroyCompressContext; + void *compressContext; + SSLDestroy destroyDecompressContext; + void *decompressContext; + PRBool bypassCiphers; /* did double bypass (at least) */ + PK11SymKey *master_secret; SSL3SequenceNumber write_seq_num; SSL3SequenceNumber read_seq_num; SSL3ProtocolVersion version; - ssl3KeyMaterial client; - ssl3KeyMaterial server; - SECItem msItem; - unsigned char key_block[NUM_MIXERS * MD5_LENGTH]; - unsigned char raw_master_secret[56]; - SECItem srvVirtName; /* for server: name that was negotiated - * with a client. For client - is - * always set to NULL.*/ - DTLSEpoch epoch; - DTLSRecvdRecords recvdRecords; + ssl3KeyMaterial client; + ssl3KeyMaterial server; + SECItem msItem; + unsigned char key_block[NUM_MIXERS * MD5_LENGTH]; + unsigned char raw_master_secret[56]; + SECItem srvVirtName; /* for server: name that was negotiated + * with a client. For client - is + * always set to NULL.*/ + DTLSEpoch epoch; + DTLSRecvdRecords recvdRecords; } ssl3CipherSpec; -typedef enum { never_cached, - in_client_cache, - in_server_cache, - invalid_cache /* no longer in any cache. */ +typedef enum { never_cached, + in_client_cache, + in_server_cache, + invalid_cache /* no longer in any cache. */ } Cached; struct sslSessionIDStr { /* The global cache lock must be held when accessing these members when the * sid is in any cache. */ - sslSessionID * next; /* chain used for client sockets, only */ - Cached cached; - int references; - PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */ + sslSessionID *next; /* chain used for client sockets, only */ + Cached cached; + int references; + PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */ /* The rest of the members, except for the members of u.ssl3.locked, may * be modified only when the sid is not in any cache. */ - CERTCertificate * peerCert; - SECItemArray peerCertStatus; /* client only */ - const char * peerID; /* client only */ - const char * urlSvrName; /* client only */ - CERTCertificate * localCert; + CERTCertificate *peerCert; + SECItemArray peerCertStatus; /* client only */ + const char *peerID; /* client only */ + const char *urlSvrName; /* client only */ + CERTCertificate *localCert; - PRIPv6Addr addr; - PRUint16 port; + PRIPv6Addr addr; + PRUint16 port; - SSL3ProtocolVersion version; + SSL3ProtocolVersion version; - PRUint32 creationTime; /* seconds since Jan 1, 1970 */ - PRUint32 expirationTime; /* seconds since Jan 1, 1970 */ + PRUint32 creationTime; /* seconds since Jan 1, 1970 */ + PRUint32 expirationTime; /* seconds since Jan 1, 1970 */ - SSLSignType authAlgorithm; - PRUint32 authKeyBits; - SSLKEAType keaType; - PRUint32 keaKeyBits; + SSLSignType authAlgorithm; + PRUint32 authKeyBits; + SSLKEAType keaType; + PRUint32 keaKeyBits; union { - struct { - /* the V2 code depends upon the size of sessionID. */ - unsigned char sessionID[SSL2_SESSIONID_BYTES]; + struct { + /* the V2 code depends upon the size of sessionID. */ + unsigned char sessionID[SSL2_SESSIONID_BYTES]; - /* Stuff used to recreate key and read/write cipher objects */ - SECItem masterKey; /* never wrapped */ - int cipherType; - SECItem cipherArg; - int keyBits; - int secretKeyBits; - } ssl2; - struct { - /* values that are copied into the server's on-disk SID cache. */ - PRUint8 sessionIDLength; - SSL3Opaque sessionID[SSL3_SESSIONID_BYTES]; + /* Stuff used to recreate key and read/write cipher objects */ + SECItem masterKey; /* never wrapped */ + int cipherType; + SECItem cipherArg; + int keyBits; + int secretKeyBits; + } ssl2; + struct { + /* values that are copied into the server's on-disk SID cache. */ + PRUint8 sessionIDLength; + SSL3Opaque sessionID[SSL3_SESSIONID_BYTES]; - ssl3CipherSuite cipherSuite; - SSLCompressionMethod compression; - int policy; - ssl3SidKeys keys; - CK_MECHANISM_TYPE masterWrapMech; - /* mechanism used to wrap master secret */ - SSL3KEAType exchKeyType; - /* key type used in exchange algorithm, - * and to wrap the sym wrapping key. */ + ssl3CipherSuite cipherSuite; + SSLCompressionMethod compression; + int policy; + ssl3SidKeys keys; + CK_MECHANISM_TYPE masterWrapMech; + /* mechanism used to wrap master secret */ + SSL3KEAType exchKeyType; + /* key type used in exchange algorithm, + * and to wrap the sym wrapping key. */ #ifndef NSS_DISABLE_ECC - PRUint32 negotiatedECCurves; + PRUint32 negotiatedECCurves; #endif /* NSS_DISABLE_ECC */ - /* The following values are NOT restored from the server's on-disk - * session cache, but are restored from the client's cache. - */ - PK11SymKey * clientWriteKey; - PK11SymKey * serverWriteKey; + /* The following values are NOT restored from the server's on-disk + * session cache, but are restored from the client's cache. + */ + PK11SymKey *clientWriteKey; + PK11SymKey *serverWriteKey; - /* The following values pertain to the slot that wrapped the - ** master secret. (used only in client) - */ - SECMODModuleID masterModuleID; - /* what module wrapped the master secret */ - CK_SLOT_ID masterSlotID; - PRUint16 masterWrapIndex; - /* what's the key index for the wrapping key */ - PRUint16 masterWrapSeries; - /* keep track of the slot series, so we don't - * accidently try to use new keys after the - * card gets removed and replaced.*/ + /* The following values pertain to the slot that wrapped the + ** master secret. (used only in client) + */ + SECMODModuleID masterModuleID; + /* what module wrapped the master secret */ + CK_SLOT_ID masterSlotID; + PRUint16 masterWrapIndex; + /* what's the key index for the wrapping key */ + PRUint16 masterWrapSeries; + /* keep track of the slot series, so we don't + * accidently try to use new keys after the + * card gets removed and replaced.*/ - /* The following values pertain to the slot that did the signature - ** for client auth. (used only in client) - */ - SECMODModuleID clAuthModuleID; - CK_SLOT_ID clAuthSlotID; - PRUint16 clAuthSeries; + /* The following values pertain to the slot that did the signature + ** for client auth. (used only in client) + */ + SECMODModuleID clAuthModuleID; + CK_SLOT_ID clAuthSlotID; + PRUint16 clAuthSeries; - char masterValid; - char clAuthValid; + char masterValid; + char clAuthValid; - SECItem srvName; + SECItem srvName; - /* Signed certificate timestamps received in a TLS extension. - ** (used only in client). - */ - SECItem signedCertTimestamps; + /* Signed certificate timestamps received in a TLS extension. + ** (used only in client). + */ + SECItem signedCertTimestamps; - /* This lock is lazily initialized by CacheSID when a sid is first - * cached. Before then, there is no need to lock anything because - * the sid isn't being shared by anything. - */ - PRRWLock *lock; + /* This lock is lazily initialized by CacheSID when a sid is first + * cached. Before then, there is no need to lock anything because + * the sid isn't being shared by anything. + */ + PRRWLock *lock; - /* The lock must be held while reading or writing these members - * because they change while the sid is cached. - */ - struct { - /* The session ticket, if we have one, is sent as an extension - * in the ClientHello message. This field is used only by - * clients. It is protected by lock when lock is non-null - * (after the sid has been added to the client session cache). - */ - NewSessionTicket sessionTicket; - } locked; - } ssl3; + /* The lock must be held while reading or writing these members + * because they change while the sid is cached. + */ + struct { + /* The session ticket, if we have one, is sent as an extension + * in the ClientHello message. This field is used only by + * clients. It is protected by lock when lock is non-null + * (after the sid has been added to the client session cache). + */ + NewSessionTicket sessionTicket; + } locked; + } ssl3; } u; }; typedef struct ssl3CipherSuiteDefStr { - ssl3CipherSuite cipher_suite; - SSL3BulkCipher bulk_cipher_alg; - SSL3MACAlgorithm mac_alg; + ssl3CipherSuite cipher_suite; + SSL3BulkCipher bulk_cipher_alg; + SSL3MACAlgorithm mac_alg; SSL3KeyExchangeAlgorithm key_exchange_alg; } ssl3CipherSuiteDef; @@ -734,35 +745,35 @@ typedef struct ssl3CipherSuiteDefStr { */ typedef struct { SSL3KeyExchangeAlgorithm kea; - SSL3KEAType exchKeyType; + SSL3KEAType exchKeyType; SSLSignType signKeyType; /* For export cipher suites: * is_limited identifies a suite as having a limit on the key size. * key_size_limit provides the corresponding limit. */ - PRBool is_limited; + PRBool is_limited; unsigned int key_size_limit; - PRBool tls_keygen; + PRBool tls_keygen; /* True if the key exchange for the suite is ephemeral. Or to be more * precise: true if the ServerKeyExchange message is always required. */ - PRBool ephemeral; + PRBool ephemeral; /* An OID describing the key exchange */ - SECOidTag oid; + SECOidTag oid; } ssl3KEADef; /* ** There are tables of these, all const. */ struct ssl3BulkCipherDefStr { - SSL3BulkCipher cipher; + SSL3BulkCipher cipher; SSLCipherAlgorithm calg; - int key_size; - int secret_key_size; - CipherType type; - int iv_size; - int block_size; - int tag_size; /* authentication tag size for AEAD ciphers. */ - int explicit_nonce_size; /* for AEAD ciphers. */ - SECOidTag oid; + int key_size; + int secret_key_size; + CipherType type; + int iv_size; + int block_size; + int tag_size; /* authentication tag size for AEAD ciphers. */ + int explicit_nonce_size; /* for AEAD ciphers. */ + SECOidTag oid; }; /* @@ -771,23 +782,23 @@ struct ssl3BulkCipherDefStr { struct ssl3MACDefStr { SSL3MACAlgorithm mac; CK_MECHANISM_TYPE mmech; - int pad_size; - int mac_size; - SECOidTag oid; + int pad_size; + int mac_size; + SECOidTag oid; }; typedef enum { - wait_client_hello, - wait_client_cert, + wait_client_hello, + wait_client_cert, wait_client_key, - wait_cert_verify, - wait_change_cipher, + wait_cert_verify, + wait_change_cipher, wait_finished, - wait_server_hello, + wait_server_hello, wait_certificate_status, - wait_server_cert, + wait_server_cert, wait_server_key, - wait_cert_request, + wait_cert_request, wait_hello_done, wait_new_session_ticket, wait_encrypted_extensions, @@ -798,8 +809,8 @@ typedef enum { /* * TLS extension related constants and data structures. */ -typedef struct TLSExtensionDataStr TLSExtensionData; -typedef struct SessionTicketDataStr SessionTicketData; +typedef struct TLSExtensionDataStr TLSExtensionData; +typedef struct SessionTicketDataStr SessionTicketData; struct TLSExtensionDataStr { /* registered callbacks that send server hello extensions */ @@ -851,15 +862,15 @@ typedef struct DTLSQueuedMessageStr { } DTLSQueuedMessage; typedef struct TLS13KeyShareEntryStr { - PRCList link; /* The linked list link */ - PRUint16 group; /* The group for the entry */ - SECItem key_exchange; /* The share itself */ + PRCList link; /* The linked list link */ + PRUint16 group; /* The group for the entry */ + SECItem key_exchange; /* The share itself */ } TLS13KeyShareEntry; typedef enum { handshake_hash_unknown = 0, - handshake_hash_combo = 1, /* The MD5/SHA-1 combination */ - handshake_hash_single = 2 /* A single hash */ + handshake_hash_combo = 1, /* The MD5/SHA-1 combination */ + handshake_hash_single = 2 /* A single hash */ } SSL3HandshakeHashType; /* @@ -867,22 +878,22 @@ typedef enum { ** This entire struct is protected by ssl3HandshakeLock */ typedef struct SSL3HandshakeStateStr { - SSL3Random server_random; - SSL3Random client_random; - SSL3WaitState ws; /* May also contain SSL3WaitState | 0x80 for TLS 1.3 */ + SSL3Random server_random; + SSL3Random client_random; + SSL3WaitState ws; /* May also contain SSL3WaitState | 0x80 for TLS 1.3 */ /* This group of members is used for handshake running hashes. */ SSL3HandshakeHashType hashType; - sslBuffer messages; /* Accumulated handshake messages */ + sslBuffer messages; /* Accumulated handshake messages */ #ifndef NO_PKCS11_BYPASS /* Bypass mode: * SSL 3.0 - TLS 1.1 use both |md5_cx| and |sha_cx|. |md5_cx| is used for * MD5 and |sha_cx| for SHA-1. * TLS 1.2 and later use only |sha_cx|, for SHA-256. NOTE: When we support * SHA-384, increase MAX_MAC_CONTEXT_BYTES to 712. */ - PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; - PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; - const SECHashObject * sha_obj; + PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; + PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; + const SECHashObject *sha_obj; /* The function prototype of sha_obj->clone() does not match the prototype * of the freebl _Clone functions, so we need a dedicated function * pointer for the _Clone function. */ @@ -896,55 +907,55 @@ typedef struct SSL3HandshakeStateStr { * handshake hash for generating client auth signatures. Confusingly, the * backup hash function is SHA-1. */ #define backupHash md5 - PK11Context * md5; - PK11Context * sha; + PK11Context *md5; + PK11Context *sha; -const ssl3KEADef * kea_def; - ssl3CipherSuite cipher_suite; -const ssl3CipherSuiteDef *suite_def; - SSLCompressionMethod compression; - sslBuffer msg_body; /* protected by recvBufLock */ - /* partial handshake message from record layer */ - unsigned int header_bytes; - /* number of bytes consumed from handshake */ - /* message for message type and header length */ - SSL3HandshakeType msg_type; - unsigned long msg_len; - SECItem ca_list; /* used only by client */ - PRBool isResuming; /* are we resuming a session */ - PRBool usedStepDownKey; /* we did a server key exchange. */ - PRBool sendingSCSV; /* instead of empty RI */ - sslBuffer msgState; /* current state for handshake messages*/ - /* protected by recvBufLock */ + const ssl3KEADef *kea_def; + ssl3CipherSuite cipher_suite; + const ssl3CipherSuiteDef *suite_def; + SSLCompressionMethod compression; + sslBuffer msg_body; /* protected by recvBufLock */ + /* partial handshake message from record layer */ + unsigned int header_bytes; + /* number of bytes consumed from handshake */ + /* message for message type and header length */ + SSL3HandshakeType msg_type; + unsigned long msg_len; + SECItem ca_list; /* used only by client */ + PRBool isResuming; /* are we resuming a session */ + PRBool usedStepDownKey; /* we did a server key exchange. */ + PRBool sendingSCSV; /* instead of empty RI */ + sslBuffer msgState; /* current state for handshake messages*/ + /* protected by recvBufLock */ /* The session ticket received in a NewSessionTicket message is temporarily * stored in newSessionTicket until the handshake is finished; then it is * moved to the sid. */ - PRBool receivedNewSessionTicket; - NewSessionTicket newSessionTicket; + PRBool receivedNewSessionTicket; + NewSessionTicket newSessionTicket; - PRUint16 finishedBytes; /* size of single finished below */ + PRUint16 finishedBytes; /* size of single finished below */ union { - TLSFinished tFinished[2]; /* client, then server */ - SSL3Finished sFinished[2]; - SSL3Opaque data[72]; - } finishedMsgs; + TLSFinished tFinished[2]; /* client, then server */ + SSL3Finished sFinished[2]; + SSL3Opaque data[72]; + } finishedMsgs; #ifndef NSS_DISABLE_ECC - PRUint32 negotiatedECCurves; /* bit mask */ -#endif /* NSS_DISABLE_ECC */ + PRUint32 negotiatedECCurves; /* bit mask */ +#endif /* NSS_DISABLE_ECC */ - PRBool authCertificatePending; + PRBool authCertificatePending; /* Which function should SSL_RestartHandshake* call if we're blocked? * One of NULL, ssl3_SendClientSecondRound, ssl3_FinishHandshake, * or ssl3_AlwaysFail */ - sslRestartTarget restartTarget; + sslRestartTarget restartTarget; /* Shared state between ssl3_HandleFinished and ssl3_FinishHandshake */ - PRBool cacheSID; + PRBool cacheSID; - PRBool canFalseStart; /* Can/did we False Start */ + PRBool canFalseStart; /* Can/did we False Start */ /* Which preliminaryinfo values have been set. */ - PRUint32 preliminaryInfo; + PRUint32 preliminaryInfo; /* clientSigAndHash contains the contents of the signature_algorithms * extension (if any) from the client. This is only valid for TLS 1.2 @@ -953,96 +964,94 @@ const ssl3CipherSuiteDef *suite_def; unsigned int numClientSigAndHash; /* This group of values is used for DTLS */ - PRUint16 sendMessageSeq; /* The sending message sequence - * number */ - PRCList lastMessageFlight; /* The last message flight we - * sent */ - PRUint16 maxMessageSent; /* The largest message we sent */ - PRUint16 recvMessageSeq; /* The receiving message sequence - * number */ - sslBuffer recvdFragments; /* The fragments we have received in - * a bitmask */ - PRInt32 recvdHighWater; /* The high water mark for fragments - * received. -1 means no reassembly - * in progress. */ - unsigned char cookie[32]; /* The cookie */ - unsigned char cookieLen; /* The length of the cookie */ - PRIntervalTime rtTimerStarted; /* When the timer was started */ - DTLSTimerCb rtTimerCb; /* The function to call on expiry */ - PRUint32 rtTimeoutMs; /* The length of the current timeout - * used for backoff (in ms) */ - PRUint32 rtRetries; /* The retry counter */ + PRUint16 sendMessageSeq; /* The sending message sequence + * number */ + PRCList lastMessageFlight; /* The last message flight we + * sent */ + PRUint16 maxMessageSent; /* The largest message we sent */ + PRUint16 recvMessageSeq; /* The receiving message sequence + * number */ + sslBuffer recvdFragments; /* The fragments we have received in + * a bitmask */ + PRInt32 recvdHighWater; /* The high water mark for fragments + * received. -1 means no reassembly + * in progress. */ + unsigned char cookie[32]; /* The cookie */ + unsigned char cookieLen; /* The length of the cookie */ + PRIntervalTime rtTimerStarted; /* When the timer was started */ + DTLSTimerCb rtTimerCb; /* The function to call on expiry */ + PRUint32 rtTimeoutMs; /* The length of the current timeout + * used for backoff (in ms) */ + PRUint32 rtRetries; /* The retry counter */ /* This group of values is used for TLS 1.3 and above */ - PRCList remoteKeyShares; /* The other side's public keys */ - PK11SymKey *xSS; /* Extracted static secret */ - PK11SymKey *xES; /* Extracted ephemeral secret */ - PK11SymKey *trafficSecret; /* The source key to use to generate - * traffic keys */ - PK11SymKey *clientFinishedSecret; /* Used for client Finished */ - PK11SymKey *serverFinishedSecret; /* Used for server Finished */ - unsigned char certReqContext[255]; /* Ties CertificateRequest - * to Certificate */ - PRUint8 certReqContextLen; /* Length of the context - * cannot be greater than 255. */ + PRCList remoteKeyShares; /* The other side's public keys */ + PK11SymKey *xSS; /* Extracted static secret */ + PK11SymKey *xES; /* Extracted ephemeral secret */ + PK11SymKey *trafficSecret; /* The source key to use to generate + * traffic keys */ + PK11SymKey *clientFinishedSecret; /* Used for client Finished */ + PK11SymKey *serverFinishedSecret; /* Used for server Finished */ + unsigned char certReqContext[255]; /* Ties CertificateRequest + * to Certificate */ + PRUint8 certReqContextLen; /* Length of the context + * cannot be greater than 255. */ } SSL3HandshakeState; - - /* ** This is the "ssl3" struct, as in "ss->ssl3". ** note: -** usually, crSpec == cwSpec and prSpec == pwSpec. +** usually, crSpec == cwSpec and prSpec == pwSpec. ** Sometimes, crSpec == pwSpec and prSpec == cwSpec. -** But there are never more than 2 actual specs. +** But there are never more than 2 actual specs. ** No spec must ever be modified if either "current" pointer points to it. */ struct ssl3StateStr { /* - ** The following Specs and Spec pointers must be protected using the + ** The following Specs and Spec pointers must be protected using the ** Spec Lock. */ - ssl3CipherSpec * crSpec; /* current read spec. */ - ssl3CipherSpec * prSpec; /* pending read spec. */ - ssl3CipherSpec * cwSpec; /* current write spec. */ - ssl3CipherSpec * pwSpec; /* pending write spec. */ + ssl3CipherSpec *crSpec; /* current read spec. */ + ssl3CipherSpec *prSpec; /* pending read spec. */ + ssl3CipherSpec *cwSpec; /* current write spec. */ + ssl3CipherSpec *pwSpec; /* pending write spec. */ - CERTCertificate * clientCertificate; /* used by client */ - SECKEYPrivateKey * clientPrivateKey; /* used by client */ - CERTCertificateList *clientCertChain; /* used by client */ - PRBool sendEmptyCert; /* used by client */ + CERTCertificate *clientCertificate; /* used by client */ + SECKEYPrivateKey *clientPrivateKey; /* used by client */ + CERTCertificateList *clientCertChain; /* used by client */ + PRBool sendEmptyCert; /* used by client */ - int policy; - /* This says what cipher suites we can do, and should - * be either SSL_ALLOWED or SSL_RESTRICTED - */ - PLArenaPool * peerCertArena; - /* These are used to keep track of the peer CA */ - void * peerCertChain; - /* chain while we are trying to validate it. */ - CERTDistNames * ca_list; - /* used by server. trusted CAs for this socket. */ - PRBool initialized; - SSL3HandshakeState hs; - ssl3CipherSpec specs[2]; /* one is current, one is pending. */ + int policy; + /* This says what cipher suites we can do, and should + * be either SSL_ALLOWED or SSL_RESTRICTED + */ + PLArenaPool *peerCertArena; + /* These are used to keep track of the peer CA */ + void *peerCertChain; + /* chain while we are trying to validate it. */ + CERTDistNames *ca_list; + /* used by server. trusted CAs for this socket. */ + PRBool initialized; + SSL3HandshakeState hs; + ssl3CipherSpec specs[2]; /* one is current, one is pending. */ /* In a client: if the server supports Next Protocol Negotiation, then * this is the protocol that was negotiated. */ - SECItem nextProto; - SSLNextProtoState nextProtoState; + SECItem nextProto; + SSLNextProtoState nextProtoState; - PRUint16 mtu; /* Our estimate of the MTU */ + PRUint16 mtu; /* Our estimate of the MTU */ /* DTLS-SRTP cipher suite preferences (if any) */ - PRUint16 dtlsSRTPCiphers[MAX_DTLS_SRTP_CIPHER_SUITES]; - PRUint16 dtlsSRTPCipherCount; - PRUint16 dtlsSRTPCipherSuite; /* 0 if not selected */ - PRBool fatalAlertSent; - PRUint16 numDHEGroups; /* used by server */ - SSLDHEGroupType * dheGroups; /* used by server */ - PRBool dheWeakGroupEnabled; /* used by server */ + PRUint16 dtlsSRTPCiphers[MAX_DTLS_SRTP_CIPHER_SUITES]; + PRUint16 dtlsSRTPCipherCount; + PRUint16 dtlsSRTPCipherSuite; /* 0 if not selected */ + PRBool fatalAlertSent; + PRUint16 numDHEGroups; /* used by server */ + SSLDHEGroupType *dheGroups; /* used by server */ + PRBool dheWeakGroupEnabled; /* used by server */ /* TLS 1.2 introduces separate signature algorithm negotiation. * This is our preference order. */ @@ -1052,68 +1061,68 @@ struct ssl3StateStr { /* The version to check if we fell back from our highest version * of TLS. Default is 0 in which case we check against the maximum * configured version for this socket. Used only on the client. */ - SSL3ProtocolVersion downgradeCheckVersion; + SSL3ProtocolVersion downgradeCheckVersion; }; /* Ethernet MTU but without subtracting the headers, * so slightly larger than expected */ -#define DTLS_MAX_MTU 1500U +#define DTLS_MAX_MTU 1500U #define IS_DTLS(ss) (ss->protocolVariant == ssl_variant_datagram) typedef struct { - SSL3ContentType type; - SSL3ProtocolVersion version; - SSL3SequenceNumber seq_num; /* DTLS only */ - sslBuffer * buf; + SSL3ContentType type; + SSL3ProtocolVersion version; + SSL3SequenceNumber seq_num; /* DTLS only */ + sslBuffer *buf; } SSL3Ciphertext; struct ssl3KeyPairStr { - SECKEYPrivateKey * privKey; - SECKEYPublicKey * pubKey; - PRInt32 refCount; /* use PR_Atomic calls for this. */ + SECKEYPrivateKey *privKey; + SECKEYPublicKey *pubKey; + PRInt32 refCount; /* use PR_Atomic calls for this. */ }; struct ssl3DHParamsStr { SECItem prime; /* p */ - SECItem base; /* g */ + SECItem base; /* g */ }; typedef struct SSLWrappedSymWrappingKeyStr { - SSL3Opaque wrappedSymmetricWrappingkey[512]; - CK_MECHANISM_TYPE symWrapMechanism; - /* unwrapped symmetric wrapping key uses this mechanism */ - CK_MECHANISM_TYPE asymWrapMechanism; - /* mechanism used to wrap the SymmetricWrappingKey using - * server's public and/or private keys. */ - SSL3KEAType exchKeyType; /* type of keys used to wrap SymWrapKey*/ - PRInt32 symWrapMechIndex; - PRUint16 wrappedSymKeyLen; + SSL3Opaque wrappedSymmetricWrappingkey[512]; + CK_MECHANISM_TYPE symWrapMechanism; + /* unwrapped symmetric wrapping key uses this mechanism */ + CK_MECHANISM_TYPE asymWrapMechanism; + /* mechanism used to wrap the SymmetricWrappingKey using + * server's public and/or private keys. */ + SSL3KEAType exchKeyType; /* type of keys used to wrap SymWrapKey*/ + PRInt32 symWrapMechIndex; + PRUint16 wrappedSymKeyLen; } SSLWrappedSymWrappingKey; typedef struct SessionTicketStr { - PRUint16 ticket_version; - SSL3ProtocolVersion ssl_version; - ssl3CipherSuite cipher_suite; - SSLCompressionMethod compression_method; - SSLSignType authAlgorithm; - PRUint32 authKeyBits; - SSLKEAType keaType; - PRUint32 keaKeyBits; + PRUint16 ticket_version; + SSL3ProtocolVersion ssl_version; + ssl3CipherSuite cipher_suite; + SSLCompressionMethod compression_method; + SSLSignType authAlgorithm; + PRUint32 authKeyBits; + SSLKEAType keaType; + PRUint32 keaKeyBits; /* * exchKeyType and msWrapMech contain meaningful values only if * ms_is_wrapped is true. */ - PRUint8 ms_is_wrapped; - SSLKEAType exchKeyType; /* XXX(wtc): same as keaType above? */ - CK_MECHANISM_TYPE msWrapMech; - PRUint16 ms_length; - SSL3Opaque master_secret[48]; - PRBool extendedMasterSecretUsed; - ClientIdentity client_identity; - SECItem peer_cert; - PRUint32 timestamp; - SECItem srvName; /* negotiated server name */ -} SessionTicket; + PRUint8 ms_is_wrapped; + SSLKEAType exchKeyType; /* XXX(wtc): same as keaType above? */ + CK_MECHANISM_TYPE msWrapMech; + PRUint16 ms_length; + SSL3Opaque master_secret[48]; + PRBool extendedMasterSecretUsed; + ClientIdentity client_identity; + SECItem peer_cert; + PRUint32 timestamp; + SECItem srvName; /* negotiated server name */ +} SessionTicket; /* * SSL2 buffers used in SSL3. @@ -1126,112 +1135,111 @@ typedef struct SessionTicketStr { /* ** This is "ci", as in "ss->sec.ci". ** -** Protection: All the variables in here are protected by -** firstHandshakeLock AND (in ssl3) ssl3HandshakeLock +** Protection: All the variables in here are protected by +** firstHandshakeLock AND (in ssl3) ssl3HandshakeLock */ struct sslConnectInfoStr { /* outgoing handshakes appended to this. */ - sslBuffer sendBuf; /*xmitBufLock*/ /* ssl 2 & 3 */ + sslBuffer sendBuf; /*xmitBufLock*/ /* ssl 2 & 3 */ - PRIPv6Addr peer; /* ssl 2 & 3 */ - unsigned short port; /* ssl 2 & 3 */ + PRIPv6Addr peer; /* ssl 2 & 3 */ + unsigned short port; /* ssl 2 & 3 */ - sslSessionID *sid; /* ssl 2 & 3 */ + sslSessionID *sid; /* ssl 2 & 3 */ /* see CIS_HAVE defines below for the bit values in *elements. */ - char elements; /* ssl2 only */ - char requiredElements; /* ssl2 only */ - char sentElements; /* ssl2 only */ + char elements; /* ssl2 only */ + char requiredElements; /* ssl2 only */ + char sentElements; /* ssl2 only */ - char sentFinished; /* ssl2 only */ + char sentFinished; /* ssl2 only */ /* Length of server challenge. Used by client when saving challenge */ - int serverChallengeLen; /* ssl2 only */ + int serverChallengeLen; /* ssl2 only */ /* type of authentication requested by server */ - unsigned char authType; /* ssl2 only */ + unsigned char authType; /* ssl2 only */ /* Challenge sent by client to server in client-hello message */ /* SSL3 gets a copy of this. See ssl3_StartHandshakeHash(). */ - unsigned char clientChallenge[SSL_MAX_CHALLENGE_BYTES]; /* ssl 2 & 3 */ + unsigned char clientChallenge[SSL_MAX_CHALLENGE_BYTES]; /* ssl 2 & 3 */ /* Connection-id sent by server to client in server-hello message */ - unsigned char connectionID[SSL_CONNECTIONID_BYTES]; /* ssl2 only */ + unsigned char connectionID[SSL_CONNECTIONID_BYTES]; /* ssl2 only */ /* Challenge sent by server to client in request-certificate message */ - unsigned char serverChallenge[SSL_MAX_CHALLENGE_BYTES]; /* ssl2 only */ + unsigned char serverChallenge[SSL_MAX_CHALLENGE_BYTES]; /* ssl2 only */ /* Information kept to handle a request-certificate message */ - unsigned char readKey[SSL_MAX_MASTER_KEY_BYTES]; /* ssl2 only */ - unsigned char writeKey[SSL_MAX_MASTER_KEY_BYTES]; /* ssl2 only */ - unsigned keySize; /* ssl2 only */ + unsigned char readKey[SSL_MAX_MASTER_KEY_BYTES]; /* ssl2 only */ + unsigned char writeKey[SSL_MAX_MASTER_KEY_BYTES]; /* ssl2 only */ + unsigned keySize; /* ssl2 only */ }; /* bit values for ci->elements, ci->requiredElements, sentElements. */ -#define CIS_HAVE_MASTER_KEY 0x01 -#define CIS_HAVE_CERTIFICATE 0x02 -#define CIS_HAVE_FINISHED 0x04 -#define CIS_HAVE_VERIFY 0x08 +#define CIS_HAVE_MASTER_KEY 0x01 +#define CIS_HAVE_CERTIFICATE 0x02 +#define CIS_HAVE_FINISHED 0x04 +#define CIS_HAVE_VERIFY 0x08 /* Note: The entire content of this struct and whatever it points to gets * blown away by SSL_ResetHandshake(). This is "sec" as in "ss->sec". * - * Unless otherwise specified below, the contents of this struct are + * Unless otherwise specified below, the contents of this struct are * protected by firstHandshakeLock AND (in ssl3) ssl3HandshakeLock. */ struct sslSecurityInfoStr { - sslSendFunc send; /*xmitBufLock*/ /* ssl 2 & 3 */ - int isServer; /* Spec Lock?*/ /* ssl 2 & 3 */ - sslBuffer writeBuf; /*xmitBufLock*/ /* ssl 2 & 3 */ + sslSendFunc send; /*xmitBufLock*/ /* ssl 2 & 3 */ + int isServer; /* Spec Lock?*/ /* ssl 2 & 3 */ + sslBuffer writeBuf; /*xmitBufLock*/ /* ssl 2 & 3 */ - int cipherType; /* ssl 2 & 3 */ - int keyBits; /* ssl 2 & 3 */ - int secretKeyBits; /* ssl 2 & 3 */ - CERTCertificate *localCert; /* ssl 2 & 3 */ - CERTCertificate *peerCert; /* ssl 2 & 3 */ - SECKEYPublicKey *peerKey; /* ssl3 only */ + int cipherType; /* ssl 2 & 3 */ + int keyBits; /* ssl 2 & 3 */ + int secretKeyBits; /* ssl 2 & 3 */ + CERTCertificate *localCert; /* ssl 2 & 3 */ + CERTCertificate *peerCert; /* ssl 2 & 3 */ + SECKEYPublicKey *peerKey; /* ssl3 only */ - SSLSignType authAlgorithm; - PRUint32 authKeyBits; - SSLKEAType keaType; - PRUint32 keaKeyBits; + SSLSignType authAlgorithm; + PRUint32 authKeyBits; + SSLKEAType keaType; + PRUint32 keaKeyBits; /* - ** Procs used for SID cache (nonce) management. - ** Different implementations exist for clients/servers + ** Procs used for SID cache (nonce) management. + ** Different implementations exist for clients/servers ** The lookup proc is only used for servers. Baloney! */ - sslSessionIDCacheFunc cache; /* ssl 2 & 3 */ - sslSessionIDUncacheFunc uncache; /* ssl 2 & 3 */ + sslSessionIDCacheFunc cache; /* ssl 2 & 3 */ + sslSessionIDUncacheFunc uncache; /* ssl 2 & 3 */ /* ** everything below here is for ssl2 only. - ** This stuff is equivalent to SSL3's "spec", and is protected by the + ** This stuff is equivalent to SSL3's "spec", and is protected by the ** same "Spec Lock" as used for SSL3's specs. */ - PRUint32 sendSequence; /*xmitBufLock*/ /* ssl2 only */ - PRUint32 rcvSequence; /*recvBufLock*/ /* ssl2 only */ + PRUint32 sendSequence; /*xmitBufLock*/ /* ssl2 only */ + PRUint32 rcvSequence; /*recvBufLock*/ /* ssl2 only */ /* Hash information; used for one-way-hash functions (MD2, MD5, etc.) */ - const SECHashObject *hash; /* Spec Lock */ /* ssl2 only */ - void *hashcx; /* Spec Lock */ /* ssl2 only */ + const SECHashObject *hash; /* Spec Lock */ /* ssl2 only */ + void *hashcx; /* Spec Lock */ /* ssl2 only */ - SECItem sendSecret; /* Spec Lock */ /* ssl2 only */ - SECItem rcvSecret; /* Spec Lock */ /* ssl2 only */ + SECItem sendSecret; /* Spec Lock */ /* ssl2 only */ + SECItem rcvSecret; /* Spec Lock */ /* ssl2 only */ /* Session cypher contexts; one for each direction */ - void *readcx; /* Spec Lock */ /* ssl2 only */ - void *writecx; /* Spec Lock */ /* ssl2 only */ - SSLCipher enc; /* Spec Lock */ /* ssl2 only */ - SSLCipher dec; /* Spec Lock */ /* ssl2 only */ - void (*destroy)(void *, PRBool); /* Spec Lock */ /* ssl2 only */ + void *readcx; /* Spec Lock */ /* ssl2 only */ + void *writecx; /* Spec Lock */ /* ssl2 only */ + SSLCipher enc; /* Spec Lock */ /* ssl2 only */ + SSLCipher dec; /* Spec Lock */ /* ssl2 only */ + void (*destroy)(void *, PRBool); /* Spec Lock */ /* ssl2 only */ /* Blocking information for the session cypher */ - int blockShift; /* Spec Lock */ /* ssl2 only */ - int blockSize; /* Spec Lock */ /* ssl2 only */ + int blockShift; /* Spec Lock */ /* ssl2 only */ + int blockSize; /* Spec Lock */ /* ssl2 only */ /* These are used during a connection handshake */ - sslConnectInfo ci; /* ssl 2 & 3 */ - + sslConnectInfo ci; /* ssl 2 & 3 */ }; /* @@ -1240,167 +1248,165 @@ struct sslSecurityInfoStr { ** Protection: XXX */ struct sslSocketStr { - PRFileDesc * fd; + PRFileDesc *fd; /* Pointer to operations vector for this socket */ - const sslSocketOps * ops; + const sslSocketOps *ops; /* SSL socket options */ - sslOptions opt; + sslOptions opt; /* Enabled version range */ - SSLVersionRange vrange; + SSLVersionRange vrange; /* State flags */ - unsigned long clientAuthRequested; - unsigned long delayDisabled; /* Nagle delay disabled */ - unsigned long firstHsDone; /* first handshake is complete. */ - unsigned long enoughFirstHsDone; /* enough of the first handshake is - * done for callbacks to be able to - * retrieve channel security - * parameters from the SSL socket. */ - unsigned long handshakeBegun; - unsigned long lastWriteBlocked; - unsigned long recvdCloseNotify; /* received SSL EOF. */ - unsigned long TCPconnected; - unsigned long appDataBuffered; - unsigned long peerRequestedProtection; /* from old renegotiation */ + unsigned long clientAuthRequested; + unsigned long delayDisabled; /* Nagle delay disabled */ + unsigned long firstHsDone; /* first handshake is complete. */ + unsigned long enoughFirstHsDone; /* enough of the first handshake is + * done for callbacks to be able to + * retrieve channel security + * parameters from the SSL socket. */ + unsigned long handshakeBegun; + unsigned long lastWriteBlocked; + unsigned long recvdCloseNotify; /* received SSL EOF. */ + unsigned long TCPconnected; + unsigned long appDataBuffered; + unsigned long peerRequestedProtection; /* from old renegotiation */ /* version of the protocol to use */ SSL3ProtocolVersion version; SSL3ProtocolVersion clientHelloVersion; /* version sent in client hello. */ - sslSecurityInfo sec; /* not a pointer any more */ + sslSecurityInfo sec; /* not a pointer any more */ /* protected by firstHandshakeLock AND (in ssl3) ssl3HandshakeLock. */ - const char *url; /* ssl 2 & 3 */ + const char *url; /* ssl 2 & 3 */ - sslHandshakeFunc handshake; /*firstHandshakeLock*/ - sslHandshakeFunc nextHandshake; /*firstHandshakeLock*/ - sslHandshakeFunc securityHandshake; /*firstHandshakeLock*/ + sslHandshakeFunc handshake; /*firstHandshakeLock*/ + sslHandshakeFunc nextHandshake; /*firstHandshakeLock*/ + sslHandshakeFunc securityHandshake; /*firstHandshakeLock*/ /* the following variable is only used with socks or other proxies. */ - char * peerID; /* String uniquely identifies target server. */ + char *peerID; /* String uniquely identifies target server. */ - unsigned char * cipherSpecs; - unsigned int sizeCipherSpecs; -const unsigned char * preferredCipher; + unsigned char *cipherSpecs; + unsigned int sizeCipherSpecs; + const unsigned char *preferredCipher; - ssl3KeyPair * stepDownKeyPair; /* RSA step down keys */ + ssl3KeyPair *stepDownKeyPair; /* RSA step down keys */ - const ssl3DHParams *dheParams; /* DHE param */ - ssl3KeyPair * dheKeyPair; /* DHE keys */ + const ssl3DHParams *dheParams; /* DHE param */ + ssl3KeyPair *dheKeyPair; /* DHE keys */ /* Callbacks */ - SSLAuthCertificate authCertificate; - void *authCertificateArg; - SSLGetClientAuthData getClientAuthData; - void *getClientAuthDataArg; - SSLSNISocketConfig sniSocketConfig; - void *sniSocketConfigArg; - SSLBadCertHandler handleBadCert; - void *badCertArg; - SSLHandshakeCallback handshakeCallback; - void *handshakeCallbackData; - SSLCanFalseStartCallback canFalseStartCallback; - void *canFalseStartCallbackData; - void *pkcs11PinArg; - SSLNextProtoCallback nextProtoCallback; - void *nextProtoArg; + SSLAuthCertificate authCertificate; + void *authCertificateArg; + SSLGetClientAuthData getClientAuthData; + void *getClientAuthDataArg; + SSLSNISocketConfig sniSocketConfig; + void *sniSocketConfigArg; + SSLBadCertHandler handleBadCert; + void *badCertArg; + SSLHandshakeCallback handshakeCallback; + void *handshakeCallbackData; + SSLCanFalseStartCallback canFalseStartCallback; + void *canFalseStartCallbackData; + void *pkcs11PinArg; + SSLNextProtoCallback nextProtoCallback; + void *nextProtoArg; - PRIntervalTime rTimeout; /* timeout for NSPR I/O */ - PRIntervalTime wTimeout; /* timeout for NSPR I/O */ - PRIntervalTime cTimeout; /* timeout for NSPR I/O */ + PRIntervalTime rTimeout; /* timeout for NSPR I/O */ + PRIntervalTime wTimeout; /* timeout for NSPR I/O */ + PRIntervalTime cTimeout; /* timeout for NSPR I/O */ - PZLock * recvLock; /* lock against multiple reader threads. */ - PZLock * sendLock; /* lock against multiple sender threads. */ + PZLock *recvLock; /* lock against multiple reader threads. */ + PZLock *sendLock; /* lock against multiple sender threads. */ - PZMonitor * recvBufLock; /* locks low level recv buffers. */ - PZMonitor * xmitBufLock; /* locks low level xmit buffers. */ + PZMonitor *recvBufLock; /* locks low level recv buffers. */ + PZMonitor *xmitBufLock; /* locks low level xmit buffers. */ /* Only one thread may operate on the socket until the initial handshake ** is complete. This Monitor ensures that. Since SSL2 handshake is ** only done once, this is also effectively the SSL2 handshake lock. */ - PZMonitor * firstHandshakeLock; + PZMonitor *firstHandshakeLock; /* This monitor protects the ssl3 handshake state machine data. ** Only one thread (reader or writer) may be in the ssl3 handshake state ** machine at any time. */ - PZMonitor * ssl3HandshakeLock; + PZMonitor *ssl3HandshakeLock; /* reader/writer lock, protects the secret data needed to encrypt and MAC - ** outgoing records, and to decrypt and MAC check incoming ciphertext + ** outgoing records, and to decrypt and MAC check incoming ciphertext ** records. */ - NSSRWLock * specLock; + NSSRWLock *specLock; - /* handle to perm cert db (and implicitly to the temp cert db) used - ** with this socket. + /* handle to perm cert db (and implicitly to the temp cert db) used + ** with this socket. */ - CERTCertDBHandle * dbHandle; + CERTCertDBHandle *dbHandle; - PRThread * writerThread; /* thread holds SSL_LOCK_WRITER lock */ + PRThread *writerThread; /* thread holds SSL_LOCK_WRITER lock */ - PRUint16 shutdownHow; /* See ssl_SHUTDOWN defines below. */ + PRUint16 shutdownHow; /* See ssl_SHUTDOWN defines below. */ - PRUint16 allowedByPolicy; /* copy of global policy bits. */ - PRUint16 maybeAllowedByPolicy; /* copy of global policy bits. */ - PRUint16 chosenPreference; /* SSL2 cipher preferences. */ + PRUint16 allowedByPolicy; /* copy of global policy bits. */ + PRUint16 maybeAllowedByPolicy; /* copy of global policy bits. */ + PRUint16 chosenPreference; /* SSL2 cipher preferences. */ sslHandshakingType handshaking; /* Gather object used for gathering data */ - sslGather gs; /*recvBufLock*/ + sslGather gs; /*recvBufLock*/ - sslBuffer saveBuf; /*xmitBufLock*/ - sslBuffer pendingBuf; /*xmitBufLock*/ + sslBuffer saveBuf; /*xmitBufLock*/ + sslBuffer pendingBuf; /*xmitBufLock*/ /* Configuration state for server sockets */ /* server cert and key for each KEA type */ - sslServerCerts serverCerts[kt_kea_size]; + sslServerCerts serverCerts[kt_kea_size]; /* each cert needs its own status */ - SECItemArray * certStatusArray[kt_kea_size]; + SECItemArray *certStatusArray[kt_kea_size]; /* Serialized signed certificate timestamps to be sent to the client ** in a TLS extension (server only). Each certificate needs its own ** timestamps item. */ - SECItem signedCertTimestamps[kt_kea_size]; + SECItem signedCertTimestamps[kt_kea_size]; ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED]; - ssl3KeyPair * ephemeralECDHKeyPair; /* for ECDHE-* handshake */ + ssl3KeyPair *ephemeralECDHKeyPair; /* for ECDHE-* handshake */ /* SSL3 state info. Formerly was a pointer */ - ssl3State ssl3; + ssl3State ssl3; /* * TLS extension related data. */ /* True when the current session is a stateless resume. */ - PRBool statelessResume; - TLSExtensionData xtnData; + PRBool statelessResume; + TLSExtensionData xtnData; /* Whether we are doing stream or datagram mode */ - SSLProtocolVariant protocolVariant; + SSLProtocolVariant protocolVariant; }; - - -/* All the global data items declared here should be protected using the +/* All the global data items declared here should be protected using the ** ssl_global_data_lock, which is a reader/writer lock. */ -extern NSSRWLock * ssl_global_data_lock; -extern char ssl_debug; -extern char ssl_trace; -extern FILE * ssl_trace_iob; -extern FILE * ssl_keylog_iob; -extern CERTDistNames * ssl3_server_ca_list; -extern PRUint32 ssl_sid_timeout; -extern PRUint32 ssl3_sid_timeout; +extern NSSRWLock *ssl_global_data_lock; +extern char ssl_debug; +extern char ssl_trace; +extern FILE *ssl_trace_iob; +extern FILE *ssl_keylog_iob; +extern CERTDistNames *ssl3_server_ca_list; +extern PRUint32 ssl_sid_timeout; +extern PRUint32 ssl3_sid_timeout; -extern const char * const ssl_cipherName[]; -extern const char * const ssl3_cipherName[]; +extern const char *const ssl_cipherName[]; +extern const char *const ssl3_cipherName[]; -extern sslSessionIDLookupFunc ssl_sid_lookup; -extern sslSessionIDCacheFunc ssl_sid_cache; +extern sslSessionIDLookupFunc ssl_sid_lookup; +extern sslSessionIDCacheFunc ssl_sid_cache; extern sslSessionIDUncacheFunc ssl_sid_uncache; /************************************************************************/ @@ -1420,15 +1426,15 @@ extern int ssl_DefShutdown(sslSocket *ss, int how); extern int ssl_DefClose(sslSocket *ss); extern int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags); extern int ssl_DefSend(sslSocket *ss, const unsigned char *buf, - int len, int flags); + int len, int flags); extern int ssl_DefRead(sslSocket *ss, unsigned char *buf, int len); extern int ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len); extern int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name); extern int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name); extern int ssl_DefGetsockopt(sslSocket *ss, PRSockOption optname, - void *optval, PRInt32 *optlen); + void *optval, PRInt32 *optlen); extern int ssl_DefSetsockopt(sslSocket *ss, PRSockOption optname, - const void *optval, PRInt32 optlen); + const void *optval, PRInt32 optlen); /* Implementation of ops for socks only case */ extern int ssl_SocksConnect(sslSocket *ss, const PRNetAddr *addr); @@ -1438,7 +1444,7 @@ extern int ssl_SocksListen(sslSocket *ss, int backlog); extern int ssl_SocksGetsockname(sslSocket *ss, PRNetAddr *name); extern int ssl_SocksRecv(sslSocket *ss, unsigned char *buf, int len, int flags); extern int ssl_SocksSend(sslSocket *ss, const unsigned char *buf, - int len, int flags); + int len, int flags); extern int ssl_SocksRead(sslSocket *ss, unsigned char *buf, int len); extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len); @@ -1446,9 +1452,9 @@ extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len); extern int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *addr); extern PRFileDesc *ssl_SecureAccept(sslSocket *ss, PRNetAddr *addr); extern int ssl_SecureRecv(sslSocket *ss, unsigned char *buf, - int len, int flags); + int len, int flags); extern int ssl_SecureSend(sslSocket *ss, const unsigned char *buf, - int len, int flags); + int len, int flags); extern int ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len); extern int ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len); extern int ssl_SecureShutdown(sslSocket *ss, int how); @@ -1460,55 +1466,55 @@ extern PRFileDesc *ssl_SecureSocksAccept(sslSocket *ss, PRNetAddr *addr); extern PRFileDesc *ssl_FindTop(sslSocket *ss); /* Gather funcs. */ -extern sslGather * ssl_NewGather(void); -extern SECStatus ssl_InitGather(sslGather *gs); -extern void ssl_DestroyGather(sslGather *gs); -extern int ssl2_GatherData(sslSocket *ss, sslGather *gs, int flags); -extern int ssl2_GatherRecord(sslSocket *ss, int flags); -extern SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss); +extern sslGather *ssl_NewGather(void); +extern SECStatus ssl_InitGather(sslGather *gs); +extern void ssl_DestroyGather(sslGather *gs); +extern int ssl2_GatherData(sslSocket *ss, sslGather *gs, int flags); +extern int ssl2_GatherRecord(sslSocket *ss, int flags); +extern SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss); -extern SECStatus ssl2_HandleClientHelloMessage(sslSocket *ss); -extern SECStatus ssl2_HandleServerHelloMessage(sslSocket *ss); +extern SECStatus ssl2_HandleClientHelloMessage(sslSocket *ss); +extern SECStatus ssl2_HandleServerHelloMessage(sslSocket *ss); -extern SECStatus ssl_CreateSecurityInfo(sslSocket *ss); -extern SECStatus ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os); -extern void ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset); -extern void ssl_DestroySecurityInfo(sslSecurityInfo *sec); +extern SECStatus ssl_CreateSecurityInfo(sslSocket *ss); +extern SECStatus ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os); +extern void ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset); +extern void ssl_DestroySecurityInfo(sslSecurityInfo *sec); -extern void ssl_PrintBuf(sslSocket *ss, const char *msg, const void *cp, int len); -extern void ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len); +extern void ssl_PrintBuf(sslSocket *ss, const char *msg, const void *cp, int len); +extern void ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len); -extern int ssl_SendSavedWriteData(sslSocket *ss); -extern SECStatus ssl_SaveWriteData(sslSocket *ss, - const void* p, unsigned int l); +extern int ssl_SendSavedWriteData(sslSocket *ss); +extern SECStatus ssl_SaveWriteData(sslSocket *ss, + const void *p, unsigned int l); extern SECStatus ssl2_BeginClientHandshake(sslSocket *ss); extern SECStatus ssl2_BeginServerHandshake(sslSocket *ss); -extern int ssl_Do1stHandshake(sslSocket *ss); +extern int ssl_Do1stHandshake(sslSocket *ss); extern SECStatus sslBuffer_Grow(sslBuffer *b, unsigned int newLen); -extern SECStatus sslBuffer_Append(sslBuffer *b, const void * data, - unsigned int len); +extern SECStatus sslBuffer_Append(sslBuffer *b, const void *data, + unsigned int len); -extern void ssl2_UseClearSendFunc(sslSocket *ss); -extern void ssl_ChooseSessionIDProcs(sslSecurityInfo *sec); +extern void ssl2_UseClearSendFunc(sslSocket *ss); +extern void ssl_ChooseSessionIDProcs(sslSecurityInfo *sec); extern sslSessionID *ssl3_NewSessionID(sslSocket *ss, PRBool is_server); -extern sslSessionID *ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, +extern sslSessionID *ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, const char *urlSvrName); -extern void ssl_FreeSID(sslSessionID *sid); +extern void ssl_FreeSID(sslSessionID *sid); -extern int ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in, - int len, int flags); +extern int ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in, + int len, int flags); -extern PRBool ssl_FdIsBlocking(PRFileDesc *fd); +extern PRBool ssl_FdIsBlocking(PRFileDesc *fd); -extern PRBool ssl_SocketIsBlocking(sslSocket *ss); +extern PRBool ssl_SocketIsBlocking(sslSocket *ss); -extern void ssl3_SetAlwaysBlock(sslSocket *ss); +extern void ssl3_SetAlwaysBlock(sslSocket *ss); extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled); -extern void ssl_FinishHandshake(sslSocket *ss); +extern void ssl_FinishHandshake(sslSocket *ss); extern SECStatus ssl_CipherPolicySet(PRInt32 which, PRInt32 policy); @@ -1516,27 +1522,26 @@ extern SECStatus ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled); extern SECStatus ssl3_ConstrainRangeByPolicy(void); - /* Returns PR_TRUE if we are still waiting for the server to complete its * response to our client second round. Once we've received the Finished from * the server then there is no need to check false start. */ -extern PRBool ssl3_WaitingForServerSecondRound(sslSocket *ss); +extern PRBool ssl3_WaitingForServerSecondRound(sslSocket *ss); extern SECStatus -ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, - PRBool isServer, - PRBool isDTLS, - PRBool capRecordVersion, - SSL3ContentType type, - const SSL3Opaque * pIn, - PRUint32 contentLen, - sslBuffer * wrBuf); +ssl3_CompressMACEncryptRecord(ssl3CipherSpec *cwSpec, + PRBool isServer, + PRBool isDTLS, + PRBool capRecordVersion, + SSL3ContentType type, + const SSL3Opaque *pIn, + PRUint32 contentLen, + sslBuffer *wrBuf); -extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, - SSL3ContentType type, - const SSL3Opaque* pIn, PRInt32 nIn, - PRInt32 flags); +extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, + SSL3ContentType type, + const SSL3Opaque *pIn, PRInt32 nIn, + PRInt32 flags); #ifdef NSS_SSL_ENABLE_ZLIB /* @@ -1544,7 +1549,7 @@ extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, * maximum TLS record payload of 2**14 bytes, that's 29 bytes. */ #define SSL3_COMPRESSION_MAX_EXPANSION 29 -#else /* !NSS_SSL_ENABLE_ZLIB */ +#else /* !NSS_SSL_ENABLE_ZLIB */ #define SSL3_COMPRESSION_MAX_EXPANSION 0 #endif @@ -1552,68 +1557,109 @@ extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, * make sure there is room in the write buffer for padding and * other compression and cryptographic expansions. */ -#define SSL3_BUFFER_FUDGE 100 + SSL3_COMPRESSION_MAX_EXPANSION +#define SSL3_BUFFER_FUDGE 100 + SSL3_COMPRESSION_MAX_EXPANSION -#define SSL_LOCK_READER(ss) if (ss->recvLock) PZ_Lock(ss->recvLock) -#define SSL_UNLOCK_READER(ss) if (ss->recvLock) PZ_Unlock(ss->recvLock) -#define SSL_LOCK_WRITER(ss) if (ss->sendLock) PZ_Lock(ss->sendLock) -#define SSL_UNLOCK_WRITER(ss) if (ss->sendLock) PZ_Unlock(ss->sendLock) +#define SSL_LOCK_READER(ss) \ + if (ss->recvLock) \ + PZ_Lock(ss->recvLock) +#define SSL_UNLOCK_READER(ss) \ + if (ss->recvLock) \ + PZ_Unlock(ss->recvLock) +#define SSL_LOCK_WRITER(ss) \ + if (ss->sendLock) \ + PZ_Lock(ss->sendLock) +#define SSL_UNLOCK_WRITER(ss) \ + if (ss->sendLock) \ + PZ_Unlock(ss->sendLock) /* firstHandshakeLock -> recvBufLock */ -#define ssl_Get1stHandshakeLock(ss) \ - { if (!ss->opt.noLocks) { \ - PORT_Assert(PZ_InMonitor((ss)->firstHandshakeLock) || \ - !ssl_HaveRecvBufLock(ss)); \ - PZ_EnterMonitor((ss)->firstHandshakeLock); \ - } } -#define ssl_Release1stHandshakeLock(ss) \ - { if (!ss->opt.noLocks) PZ_ExitMonitor((ss)->firstHandshakeLock); } -#define ssl_Have1stHandshakeLock(ss) \ +#define ssl_Get1stHandshakeLock(ss) \ + { \ + if (!ss->opt.noLocks) { \ + PORT_Assert(PZ_InMonitor((ss)->firstHandshakeLock) || \ + !ssl_HaveRecvBufLock(ss)); \ + PZ_EnterMonitor((ss)->firstHandshakeLock); \ + } \ + } +#define ssl_Release1stHandshakeLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + PZ_ExitMonitor((ss)->firstHandshakeLock); \ + } +#define ssl_Have1stHandshakeLock(ss) \ (PZ_InMonitor((ss)->firstHandshakeLock)) /* ssl3HandshakeLock -> xmitBufLock */ -#define ssl_GetSSL3HandshakeLock(ss) \ - { if (!ss->opt.noLocks) { \ - PORT_Assert(!ssl_HaveXmitBufLock(ss)); \ - PZ_EnterMonitor((ss)->ssl3HandshakeLock); \ - } } -#define ssl_ReleaseSSL3HandshakeLock(ss) \ - { if (!ss->opt.noLocks) PZ_ExitMonitor((ss)->ssl3HandshakeLock); } -#define ssl_HaveSSL3HandshakeLock(ss) \ +#define ssl_GetSSL3HandshakeLock(ss) \ + { \ + if (!ss->opt.noLocks) { \ + PORT_Assert(!ssl_HaveXmitBufLock(ss)); \ + PZ_EnterMonitor((ss)->ssl3HandshakeLock); \ + } \ + } +#define ssl_ReleaseSSL3HandshakeLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + PZ_ExitMonitor((ss)->ssl3HandshakeLock); \ + } +#define ssl_HaveSSL3HandshakeLock(ss) \ (PZ_InMonitor((ss)->ssl3HandshakeLock)) -#define ssl_GetSpecReadLock(ss) \ - { if (!ss->opt.noLocks) NSSRWLock_LockRead((ss)->specLock); } -#define ssl_ReleaseSpecReadLock(ss) \ - { if (!ss->opt.noLocks) NSSRWLock_UnlockRead((ss)->specLock); } +#define ssl_GetSpecReadLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + NSSRWLock_LockRead((ss)->specLock); \ + } +#define ssl_ReleaseSpecReadLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + NSSRWLock_UnlockRead((ss)->specLock); \ + } /* NSSRWLock_HaveReadLock is not exported so there's no * ssl_HaveSpecReadLock macro. */ -#define ssl_GetSpecWriteLock(ss) \ - { if (!ss->opt.noLocks) NSSRWLock_LockWrite((ss)->specLock); } -#define ssl_ReleaseSpecWriteLock(ss) \ - { if (!ss->opt.noLocks) NSSRWLock_UnlockWrite((ss)->specLock); } -#define ssl_HaveSpecWriteLock(ss) \ +#define ssl_GetSpecWriteLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + NSSRWLock_LockWrite((ss)->specLock); \ + } +#define ssl_ReleaseSpecWriteLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + NSSRWLock_UnlockWrite((ss)->specLock); \ + } +#define ssl_HaveSpecWriteLock(ss) \ (NSSRWLock_HaveWriteLock((ss)->specLock)) /* recvBufLock -> ssl3HandshakeLock -> xmitBufLock */ -#define ssl_GetRecvBufLock(ss) \ - { if (!ss->opt.noLocks) { \ - PORT_Assert(!ssl_HaveSSL3HandshakeLock(ss)); \ - PORT_Assert(!ssl_HaveXmitBufLock(ss)); \ - PZ_EnterMonitor((ss)->recvBufLock); \ - } } -#define ssl_ReleaseRecvBufLock(ss) \ - { if (!ss->opt.noLocks) PZ_ExitMonitor( (ss)->recvBufLock); } -#define ssl_HaveRecvBufLock(ss) \ +#define ssl_GetRecvBufLock(ss) \ + { \ + if (!ss->opt.noLocks) { \ + PORT_Assert(!ssl_HaveSSL3HandshakeLock(ss)); \ + PORT_Assert(!ssl_HaveXmitBufLock(ss)); \ + PZ_EnterMonitor((ss)->recvBufLock); \ + } \ + } +#define ssl_ReleaseRecvBufLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + PZ_ExitMonitor((ss)->recvBufLock); \ + } +#define ssl_HaveRecvBufLock(ss) \ (PZ_InMonitor((ss)->recvBufLock)) /* xmitBufLock -> specLock */ -#define ssl_GetXmitBufLock(ss) \ - { if (!ss->opt.noLocks) PZ_EnterMonitor((ss)->xmitBufLock); } -#define ssl_ReleaseXmitBufLock(ss) \ - { if (!ss->opt.noLocks) PZ_ExitMonitor( (ss)->xmitBufLock); } -#define ssl_HaveXmitBufLock(ss) \ +#define ssl_GetXmitBufLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + PZ_EnterMonitor((ss)->xmitBufLock); \ + } +#define ssl_ReleaseXmitBufLock(ss) \ + { \ + if (!ss->opt.noLocks) \ + PZ_ExitMonitor((ss)->xmitBufLock); \ + } +#define ssl_HaveXmitBufLock(ss) \ (PZ_InMonitor((ss)->xmitBufLock)) /* Placeholder value used in version ranges when SSL 3.0 and all @@ -1621,7 +1667,7 @@ extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, */ #define SSL_LIBRARY_VERSION_NONE 0 -/* SSL_LIBRARY_VERSION_MAX_SUPPORTED is the maximum version that this version +/* SSL_LIBRARY_VERSION_MAX_SUPPORTED is the maximum version that this version * of libssl supports. Applications should use SSL_VersionRangeGetSupported at * runtime to determine which versions are supported by the version of libssl * in use. @@ -1637,26 +1683,26 @@ extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, ((vrange)->min == SSL_LIBRARY_VERSION_NONE) extern PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant, - SSL3ProtocolVersion version); + SSL3ProtocolVersion version); -extern SECStatus ssl3_KeyAndMacDeriveBypass(ssl3CipherSpec * pwSpec, - const unsigned char * cr, const unsigned char * sr, - PRBool isTLS, PRBool isExport); -extern SECStatus ssl3_MasterSecretDeriveBypass( ssl3CipherSpec * pwSpec, - const unsigned char * cr, const unsigned char * sr, - const SECItem * pms, PRBool isTLS, PRBool isRSA); +extern SECStatus ssl3_KeyAndMacDeriveBypass(ssl3CipherSpec *pwSpec, + const unsigned char *cr, const unsigned char *sr, + PRBool isTLS, PRBool isExport); +extern SECStatus ssl3_MasterSecretDeriveBypass(ssl3CipherSpec *pwSpec, + const unsigned char *cr, const unsigned char *sr, + const SECItem *pms, PRBool isTLS, PRBool isRSA); /* These functions are called from secnav, even though they're "private". */ extern int ssl2_SendErrorMessage(struct sslSocketStr *ss, int error); extern int SSL_RestartHandshakeAfterCertReq(struct sslSocketStr *ss, - CERTCertificate *cert, - SECKEYPrivateKey *key, - CERTCertificateList *certChain); + CERTCertificate *cert, + SECKEYPrivateKey *key, + CERTCertificateList *certChain); extern sslSocket *ssl_FindSocket(PRFileDesc *fd); extern void ssl_FreeSocket(struct sslSocketStr *ssl); extern SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, - SSL3AlertDescription desc); + SSL3AlertDescription desc); extern SECStatus ssl3_DecodeError(sslSocket *ss); extern SECStatus ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error); @@ -1683,7 +1729,7 @@ SECStatus ssl3_HandleRecord( int ssl3_GatherAppDataRecord(sslSocket *ss, int flags); int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags); /* - * When talking to export clients or using export cipher suites, servers + * When talking to export clients or using export cipher suites, servers * with public RSA keys larger than 512 bits need to use a 512-bit public * key, signed by the larger key. The smaller key is a "step down" key. * Generate that key pair and keep it around. @@ -1693,64 +1739,63 @@ extern SECStatus ssl3_CreateRSAStepDownKeys(sslSocket *ss); extern SECStatus ssl3_SelectDHParams(sslSocket *ss); #ifndef NSS_DISABLE_ECC -extern void ssl3_FilterECCipherSuitesByServerCerts(sslSocket *ss); -extern PRBool ssl3_IsECCEnabled(sslSocket *ss); -extern SECStatus ssl3_DisableECCSuites(sslSocket * ss, - const ssl3CipherSuite * suite); -extern PRUint32 ssl3_GetSupportedECCurveMask(sslSocket *ss); - +extern void ssl3_FilterECCipherSuitesByServerCerts(sslSocket *ss); +extern PRBool ssl3_IsECCEnabled(sslSocket *ss); +extern SECStatus ssl3_DisableECCSuites(sslSocket *ss, + const ssl3CipherSuite *suite); +extern PRUint32 ssl3_GetSupportedECCurveMask(sslSocket *ss); /* Macro for finding a curve equivalent in strength to RSA key's */ /* clang-format off */ -#define SSL_RSASTRENGTH_TO_ECSTRENGTH(s) \ - ((s <= 1024) ? 160 \ - : ((s <= 2048) ? 224 \ - : ((s <= 3072) ? 256 \ - : ((s <= 7168) ? 384 : 521 ) ) ) ) +#define SSL_RSASTRENGTH_TO_ECSTRENGTH(s) \ + ((s <= 1024) ? 160 \ + : ((s <= 2048) ? 224 \ + : ((s <= 3072) ? 256 \ + : ((s <= 7168) ? 384 \ + : 521 ) ) ) ) /* clang-format on */ /* Types and names of elliptic curves used in TLS */ -typedef enum { ec_type_explicitPrime = 1, - ec_type_explicitChar2Curve = 2, - ec_type_named +typedef enum { ec_type_explicitPrime = 1, + ec_type_explicitChar2Curve = 2, + ec_type_named } ECType; -typedef enum { ec_noName = 0, - ec_sect163k1 = 1, - ec_sect163r1 = 2, - ec_sect163r2 = 3, - ec_sect193r1 = 4, - ec_sect193r2 = 5, - ec_sect233k1 = 6, - ec_sect233r1 = 7, - ec_sect239k1 = 8, - ec_sect283k1 = 9, - ec_sect283r1 = 10, - ec_sect409k1 = 11, - ec_sect409r1 = 12, - ec_sect571k1 = 13, - ec_sect571r1 = 14, - ec_secp160k1 = 15, - ec_secp160r1 = 16, - ec_secp160r2 = 17, - ec_secp192k1 = 18, - ec_secp192r1 = 19, - ec_secp224k1 = 20, - ec_secp224r1 = 21, - ec_secp256k1 = 22, - ec_secp256r1 = 23, - ec_secp384r1 = 24, - ec_secp521r1 = 25, - ec_pastLastName +typedef enum { ec_noName = 0, + ec_sect163k1 = 1, + ec_sect163r1 = 2, + ec_sect163r2 = 3, + ec_sect193r1 = 4, + ec_sect193r2 = 5, + ec_sect233k1 = 6, + ec_sect233r1 = 7, + ec_sect239k1 = 8, + ec_sect283k1 = 9, + ec_sect283r1 = 10, + ec_sect409k1 = 11, + ec_sect409r1 = 12, + ec_sect571k1 = 13, + ec_sect571r1 = 14, + ec_secp160k1 = 15, + ec_secp160r1 = 16, + ec_secp160r2 = 17, + ec_secp192k1 = 18, + ec_secp192r1 = 19, + ec_secp224k1 = 20, + ec_secp224r1 = 21, + ec_secp256k1 = 22, + ec_secp256r1 = 23, + ec_secp384r1 = 24, + ec_secp521r1 = 25, + ec_pastLastName } ECName; extern SECStatus ssl3_ECName2Params(PLArenaPool *arena, ECName curve, - SECKEYECParams *params); + SECKEYECParams *params); ECName ssl3_PubKey2ECName(SECKEYPublicKey *pubKey); -ECName ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits); -ECName ssl3_GetCurveNameForServerSocket(sslSocket *ss); - +ECName ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits); +ECName ssl3_GetCurveNameForServerSocket(sslSocket *ss); #endif /* NSS_DISABLE_ECC */ @@ -1769,34 +1814,34 @@ extern SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *policy); extern SECStatus ssl2_SetPolicy(PRInt32 which, PRInt32 policy); extern SECStatus ssl2_GetPolicy(PRInt32 which, PRInt32 *policy); -extern void ssl2_InitSocketPolicy(sslSocket *ss); -extern void ssl3_InitSocketPolicy(sslSocket *ss); +extern void ssl2_InitSocketPolicy(sslSocket *ss); +extern void ssl3_InitSocketPolicy(sslSocket *ss); extern SECStatus ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, - unsigned char *cs, int *size); + unsigned char *cs, int *size); extern SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache); -extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, - PRUint32 length); +extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, + PRUint32 length); extern void ssl3_DestroySSL3Info(sslSocket *ss); -extern SECStatus ssl3_NegotiateVersion(sslSocket *ss, - SSL3ProtocolVersion peerVersion, - PRBool allowLargerPeerVersion); +extern SECStatus ssl3_NegotiateVersion(sslSocket *ss, + SSL3ProtocolVersion peerVersion, + PRBool allowLargerPeerVersion); extern SECStatus ssl_GetPeerInfo(sslSocket *ss); #ifndef NSS_DISABLE_ECC /* ECDH functions */ -extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket * ss, - SECKEYPublicKey * svrPubKey); -extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, - SSL3Opaque *b, PRUint32 length); -extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, - SSL3Opaque *b, PRUint32 length, - SECKEYPublicKey *srvrPubKey, - SECKEYPrivateKey *srvrPrivKey); +extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket *ss, + SECKEYPublicKey *svrPubKey); +extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, + SSL3Opaque *b, PRUint32 length); +extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, + SSL3Opaque *b, PRUint32 length, + SECKEYPublicKey *srvrPubKey, + SECKEYPrivateKey *srvrPrivKey); extern SECStatus ssl3_SendECDHServerKeyExchange( sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash); SECKEYPublicKey *tls13_ImportECDHKeyShare( @@ -1807,68 +1852,68 @@ SECStatus tls13_EncodeECDHEKeyShareKEX(sslSocket *ss, ssl3KeyPair *pair); #endif extern SECStatus ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, - PRUint8 * hashBuf, - unsigned int bufLen, SSL3Hashes *hashes, - PRBool bypassPKCS11); + PRUint8 *hashBuf, + unsigned int bufLen, SSL3Hashes *hashes, + PRBool bypassPKCS11); extern void ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName); extern SECStatus ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms); -extern SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src, - PRInt32 bytes); -extern SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss, - SSL3HandshakeType t, PRUint32 length); -extern SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, - PRInt32 lenSize); -extern SECStatus ssl3_AppendHandshakeVariable( sslSocket *ss, - const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize); +extern SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src, + PRInt32 bytes); +extern SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss, + SSL3HandshakeType t, PRUint32 length); +extern SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, + PRInt32 lenSize); +extern SECStatus ssl3_AppendHandshakeVariable(sslSocket *ss, + const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize); extern SECStatus ssl3_AppendSignatureAndHashAlgorithm( - sslSocket *ss, const SSLSignatureAndHashAlg* sigAndHash); -extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, - SSL3Opaque **b, PRUint32 *length); -extern PRInt32 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, - SSL3Opaque **b, PRUint32 *length); -extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, - PRInt32 bytes, SSL3Opaque **b, PRUint32 *length); + sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash); +extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length); +extern PRInt32 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length); +extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, + PRInt32 bytes, SSL3Opaque **b, PRUint32 *length); extern PRBool ssl3_IsSupportedSignatureAlgorithm( const SSLSignatureAndHashAlg *alg); extern SECStatus ssl3_CheckSignatureAndHashAlgorithmConsistency( sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash, - CERTCertificate* cert); + CERTCertificate *cert); extern SECStatus ssl3_ConsumeSignatureAndHashAlgorithm( sslSocket *ss, SSL3Opaque **b, PRUint32 *length, SSLSignatureAndHashAlg *out); -extern SECStatus ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, - SECItem *buf, PRBool isTLS); -extern SECStatus ssl3_VerifySignedHashes(SSL3Hashes *hash, - CERTCertificate *cert, SECItem *buf, PRBool isTLS, - void *pwArg); +extern SECStatus ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, + SECItem *buf, PRBool isTLS); +extern SECStatus ssl3_VerifySignedHashes(SSL3Hashes *hash, + CERTCertificate *cert, SECItem *buf, PRBool isTLS, + void *pwArg); extern SECStatus ssl3_CacheWrappedMasterSecret(sslSocket *ss, - sslSessionID *sid, ssl3CipherSpec *spec, - SSL3KEAType effectiveExchKeyType); + sslSessionID *sid, ssl3CipherSpec *spec, + SSL3KEAType effectiveExchKeyType); /* Functions that handle ClientHello and ServerHello extensions. */ -extern SECStatus ssl3_HandleServerNameXtn(sslSocket * ss, - PRUint16 ex_type, SECItem *data); -extern SECStatus ssl3_HandleSupportedCurvesXtn(sslSocket * ss, - PRUint16 ex_type, SECItem *data); -extern SECStatus ssl3_HandleSupportedPointFormatsXtn(sslSocket * ss, - PRUint16 ex_type, SECItem *data); +extern SECStatus ssl3_HandleServerNameXtn(sslSocket *ss, + PRUint16 ex_type, SECItem *data); +extern SECStatus ssl3_HandleSupportedCurvesXtn(sslSocket *ss, + PRUint16 ex_type, SECItem *data); +extern SECStatus ssl3_HandleSupportedPointFormatsXtn(sslSocket *ss, + PRUint16 ex_type, SECItem *data); extern SECStatus ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); + PRUint16 ex_type, SECItem *data); extern SECStatus ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); + PRUint16 ex_type, SECItem *data); /* ClientHello and ServerHello extension senders. * Note that not all extension senders are exposed here; only those that * that need exposure. */ extern PRInt32 ssl3_SendSessionTicketXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); + PRUint32 maxBytes); /* ClientHello and ServerHello extension senders. * The code is in ssl3ext.c. */ extern PRInt32 ssl3_SendServerNameXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); + PRUint32 maxBytes); /* Assigns new cert, cert chain and keys to ss->serverCerts * struct. If certChain is NULL, tries to find one. Aborts if @@ -1880,34 +1925,34 @@ extern SECStatus ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert, #ifndef NSS_DISABLE_ECC extern PRInt32 ssl3_SendSupportedCurvesXtn(sslSocket *ss, - PRBool append, PRUint32 maxBytes); + PRBool append, PRUint32 maxBytes); extern PRInt32 ssl3_SendSupportedPointFormatsXtn(sslSocket *ss, - PRBool append, PRUint32 maxBytes); + PRBool append, PRUint32 maxBytes); #endif /* call the registered extension handlers. */ -extern SECStatus ssl3_HandleHelloExtensions(sslSocket *ss, +extern SECStatus ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, SSL3HandshakeType handshakeMessage); /* Hello Extension related routines. */ extern PRBool ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type); extern void ssl3_SetSIDSessionTicket(sslSessionID *sid, - /*in/out*/ NewSessionTicket *session_ticket); + /*in/out*/ NewSessionTicket *session_ticket); extern SECStatus ssl3_SendNewSessionTicket(sslSocket *ss); extern PRBool ssl_GetSessionTicketKeys(unsigned char *keyName, - unsigned char *encKey, unsigned char *macKey); + unsigned char *encKey, unsigned char *macKey); extern PRBool ssl_GetSessionTicketKeysPKCS11(SECKEYPrivateKey *svrPrivKey, - SECKEYPublicKey *svrPubKey, void *pwArg, - unsigned char *keyName, PK11SymKey **aesKey, - PK11SymKey **macKey); + SECKEYPublicKey *svrPubKey, void *pwArg, + unsigned char *keyName, PK11SymKey **aesKey, + PK11SymKey **macKey); /* Tell clients to consider tickets valid for this long. */ -#define TLS_EX_SESS_TICKET_LIFETIME_HINT (2 * 24 * 60 * 60) /* 2 days */ -#define TLS_EX_SESS_TICKET_VERSION (0x0101) +#define TLS_EX_SESS_TICKET_LIFETIME_HINT (2 * 24 * 60 * 60) /* 2 days */ +#define TLS_EX_SESS_TICKET_VERSION (0x0101) -extern SECStatus ssl3_ValidateNextProtoNego(const unsigned char* data, - unsigned int length); +extern SECStatus ssl3_ValidateNextProtoNego(const unsigned char *data, + unsigned int length); /* Construct a new NSPR socket for the app to use */ extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd); @@ -1917,30 +1962,29 @@ extern void ssl_FreePRSocket(PRFileDesc *fd); * various ciphers */ extern int ssl3_config_match_init(sslSocket *); - /* Create a new ref counted key pair object from two keys. */ -extern ssl3KeyPair * ssl3_NewKeyPair( SECKEYPrivateKey * privKey, - SECKEYPublicKey * pubKey); +extern ssl3KeyPair *ssl3_NewKeyPair(SECKEYPrivateKey *privKey, + SECKEYPublicKey *pubKey); /* get a new reference (bump ref count) to an ssl3KeyPair. */ -extern ssl3KeyPair * ssl3_GetKeyPairRef(ssl3KeyPair * keyPair); +extern ssl3KeyPair *ssl3_GetKeyPairRef(ssl3KeyPair *keyPair); /* Decrement keypair's ref count and free if zero. */ -extern void ssl3_FreeKeyPair(ssl3KeyPair * keyPair); +extern void ssl3_FreeKeyPair(ssl3KeyPair *keyPair); /* calls for accessing wrapping keys across processes. */ extern PRBool -ssl_GetWrappingKey( PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk); +ssl_GetWrappingKey(PRInt32 symWrapMechIndex, + SSL3KEAType exchKeyType, + SSLWrappedSymWrappingKey *wswk); /* The caller passes in the new value it wants - * to set. This code tests the wrapped sym key entry in the file on disk. - * If it is uninitialized, this function writes the caller's value into - * the disk entry, and returns false. - * Otherwise, it overwrites the caller's wswk with the value obtained from - * the disk, and returns PR_TRUE. - * This is all done while holding the locks/semaphores necessary to make + * to set. This code tests the wrapped sym key entry in the file on disk. + * If it is uninitialized, this function writes the caller's value into + * the disk entry, and returns false. + * Otherwise, it overwrites the caller's wswk with the value obtained from + * the disk, and returns PR_TRUE. + * This is all done while holding the locks/semaphores necessary to make * the operation atomic. */ extern PRBool @@ -1957,7 +2001,6 @@ extern SECStatus ssl_InitSessionCacheLocks(PRBool lazyInit); extern SECStatus ssl_FreeSessionCacheLocks(void); - /**************** DTLS-specific functions **************/ extern void dtls_FreeQueuedMessage(DTLSQueuedMessage *msg); extern void dtls_FreeQueuedMessages(PRCList *lst); @@ -1965,22 +2008,22 @@ extern void dtls_FreeHandshakeMessages(PRCList *lst); extern SECStatus dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf); extern SECStatus dtls_HandleHelloVerifyRequest(sslSocket *ss, - SSL3Opaque *b, PRUint32 length); + SSL3Opaque *b, PRUint32 length); extern SECStatus dtls_StageHandshakeMessage(sslSocket *ss); extern SECStatus dtls_QueueMessage(sslSocket *ss, SSL3ContentType type, - const SSL3Opaque *pIn, PRInt32 nIn); + const SSL3Opaque *pIn, PRInt32 nIn); extern SECStatus dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); extern SECStatus dtls_CompressMACEncryptRecord(sslSocket *ss, - DTLSEpoch epoch, - PRBool use_epoch, - SSL3ContentType type, - const SSL3Opaque *pIn, - PRUint32 contentLen, - sslBuffer *wrBuf); -SECStatus ssl3_DisableNonDTLSSuites(sslSocket * ss); + DTLSEpoch epoch, + PRBool use_epoch, + SSL3ContentType type, + const SSL3Opaque *pIn, + PRUint32 contentLen, + sslBuffer *wrBuf); +SECStatus ssl3_DisableNonDTLSSuites(sslSocket *ss); extern SECStatus dtls_StartTimer(sslSocket *ss, DTLSTimerCb cb); extern SECStatus dtls_RestartTimer(sslSocket *ss, PRBool backoff, - DTLSTimerCb cb); + DTLSTimerCb cb); extern void dtls_CheckTimer(sslSocket *ss); extern void dtls_CancelTimer(sslSocket *ss); extern void dtls_FinishedTimerCb(sslSocket *ss); @@ -1996,7 +2039,6 @@ dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv); extern PRBool dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *crSpec, const SSL3Ciphertext *cText, PRUint64 *seqNum); - CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg); SECStatus ssl3_SetupPendingCipherSpec(sslSocket *ss); SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags); @@ -2006,12 +2048,12 @@ SECStatus ssl3_CompleteHandleCertificate(sslSocket *ss, SECStatus ssl3_SendEmptyCertificate(sslSocket *ss); SECStatus ssl3_SendCertificateStatus(sslSocket *ss); SECStatus ssl3_CompleteHandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, - PRUint32 length); + PRUint32 length); SECStatus ssl3_EncodeCertificateRequestSigAlgs(sslSocket *ss, PRUint8 *buf, unsigned maxLen, PRUint32 *len); void ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calenp, SECItem **namesp, int *nnamesp); -SECStatus ssl3_ParseCertificateRequestCAs(sslSocket *ss,SSL3Opaque **b, +SECStatus ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, PRUint32 *length, PLArenaPool *arena, CERTDistNames *ca_list); SECStatus ssl3_CompleteHandleCertificateRequest(sslSocket *ss, @@ -2026,12 +2068,12 @@ SECStatus ssl3_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes, PRUint32 sender); void ssl3_BumpSequenceNumber(SSL3SequenceNumber *num); -PRInt32 tls13_ServerSendKeyShareXtn(sslSocket * ss, PRBool append, +PRInt32 tls13_ServerSendKeyShareXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes); #ifndef NSS_DISABLE_ECC SECStatus ssl3_CreateECDHEphemeralKeyPair(ECName ec_curve, - ssl3KeyPair** keyPair); -PK11SymKey *tls13_ComputeECDHSharedKey(sslSocket* ss, + ssl3KeyPair **keyPair); +PK11SymKey *tls13_ComputeECDHSharedKey(sslSocket *ss, SECKEYPrivateKey *myPrivKey, SECKEYPublicKey *peerKey); #endif @@ -2049,11 +2091,11 @@ extern int ssl_MapLowLevelError(int hiLevelError); extern PRUint32 ssl_Time(void); -extern void SSL_AtomicIncrementLong(long * x); +extern void SSL_AtomicIncrementLong(long *x); SECStatus SSL_DisableDefaultExportCipherSuites(void); -SECStatus SSL_DisableExportCipherSuites(PRFileDesc * fd); -PRBool SSL_IsExportCipherSuite(PRUint16 cipherSuite); +SECStatus SSL_DisableExportCipherSuites(PRFileDesc *fd); +PRBool SSL_IsExportCipherSuite(PRUint16 cipherSuite); SECStatus ssl3_ApplyNSSPolicy(void); diff --git a/security/nss/lib/ssl/sslinfo.c b/security/nss/lib/ssl/sslinfo.c index 3208bbef3903..547d3abde74b 100644 --- a/security/nss/lib/ssl/sslinfo.c +++ b/security/nss/lib/ssl/sslinfo.c @@ -9,34 +9,37 @@ static const char * ssl_GetCompressionMethodName(SSLCompressionMethod compression) { switch (compression) { - case ssl_compression_null: - return "NULL"; + case ssl_compression_null: + return "NULL"; #ifdef NSS_ENABLE_ZLIB - case ssl_compression_deflate: - return "DEFLATE"; + case ssl_compression_deflate: + return "DEFLATE"; #endif - default: - return "???"; + default: + return "???"; } } -SECStatus +SECStatus SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len) { - sslSocket * ss; - SSLChannelInfo inf; - sslSessionID * sid; + sslSocket *ss; + SSLChannelInfo inf; + sslSessionID *sid; - if (!info || len < sizeof inf.length) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + /* Check if we can properly return the length of data written and that + * we're not asked to return more information than we know how to provide. + */ + if (!info || len < sizeof inf.length || len > sizeof inf) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetChannelInfo", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetChannelInfo", + SSL_GETPID(), fd)); + return SECFailure; } memset(&inf, 0, sizeof inf); @@ -44,45 +47,48 @@ SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len) if (ss->opt.useSecurity && ss->enoughFirstHsDone) { sid = ss->sec.ci.sid; - inf.protocolVersion = ss->version; - inf.authKeyBits = ss->sec.authKeyBits; - inf.keaKeyBits = ss->sec.keaKeyBits; - if (ss->version < SSL_LIBRARY_VERSION_3_0) { /* SSL2 */ - inf.cipherSuite = ss->sec.cipherType | 0xff00; - inf.compressionMethod = ssl_compression_null; - inf.compressionMethodName = "N/A"; - } else if (ss->ssl3.initialized) { /* SSL3 and TLS */ - ssl_GetSpecReadLock(ss); - /* XXX The cipher suite should be in the specs and this - * function should get it from cwSpec rather than from the "hs". - * See bug 275744 comment 69 and bug 766137. - */ - inf.cipherSuite = ss->ssl3.hs.cipher_suite; - inf.compressionMethod = ss->ssl3.cwSpec->compression_method; - ssl_ReleaseSpecReadLock(ss); - inf.compressionMethodName = - ssl_GetCompressionMethodName(inf.compressionMethod); - } - if (sid) { - inf.creationTime = sid->creationTime; - inf.lastAccessTime = sid->lastAccessTime; - inf.expirationTime = sid->expirationTime; + inf.protocolVersion = ss->version; + inf.authKeyBits = ss->sec.authKeyBits; + inf.keaKeyBits = ss->sec.keaKeyBits; + if (ss->version < SSL_LIBRARY_VERSION_3_0) { /* SSL2 */ + inf.cipherSuite = ss->sec.cipherType | 0xff00; + inf.compressionMethod = ssl_compression_null; + inf.compressionMethodName = "N/A"; + } + else if (ss->ssl3.initialized) { /* SSL3 and TLS */ + ssl_GetSpecReadLock(ss); + /* XXX The cipher suite should be in the specs and this + * function should get it from cwSpec rather than from the "hs". + * See bug 275744 comment 69 and bug 766137. + */ + inf.cipherSuite = ss->ssl3.hs.cipher_suite; + inf.compressionMethod = ss->ssl3.cwSpec->compression_method; + ssl_ReleaseSpecReadLock(ss); + inf.compressionMethodName = + ssl_GetCompressionMethodName(inf.compressionMethod); + } + if (sid) { + inf.creationTime = sid->creationTime; + inf.lastAccessTime = sid->lastAccessTime; + inf.expirationTime = sid->expirationTime; inf.extendedMasterSecretUsed = - (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 || - sid->u.ssl3.keys.extendedMasterSecretUsed) ? - PR_TRUE: PR_FALSE; + (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 || + sid->u.ssl3.keys.extendedMasterSecretUsed) + ? PR_TRUE + : PR_FALSE; - if (ss->version < SSL_LIBRARY_VERSION_3_0) { /* SSL2 */ - inf.sessionIDLength = SSL2_SESSIONID_BYTES; - memcpy(inf.sessionID, sid->u.ssl2.sessionID, - SSL2_SESSIONID_BYTES); - } else { - unsigned int sidLen = sid->u.ssl3.sessionIDLength; - sidLen = PR_MIN(sidLen, sizeof inf.sessionID); - inf.sessionIDLength = sidLen; - memcpy(inf.sessionID, sid->u.ssl3.sessionID, sidLen); - } - } + if (ss->version < SSL_LIBRARY_VERSION_3_0) { /* SSL2 */ + inf.sessionIDLength = SSL2_SESSIONID_BYTES; + memcpy(inf.sessionID, sid->u.ssl2.sessionID, + SSL2_SESSIONID_BYTES); + } + else { + unsigned int sidLen = sid->u.ssl3.sessionIDLength; + sidLen = PR_MIN(sidLen, sizeof inf.sessionID); + inf.sessionIDLength = sidLen; + memcpy(inf.sessionID, sid->u.ssl3.sessionID, sidLen); + } + } } memcpy(info, &inf, inf.length); @@ -98,7 +104,10 @@ SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, sslSocket *ss; SSLPreliminaryChannelInfo inf; - if (!info || len < sizeof inf.length) { + /* Check if we can properly return the length of data written and that + * we're not asked to return more information than we know how to provide. + */ + if (!info || len < sizeof inf.length || len > sizeof inf) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } @@ -126,197 +135,206 @@ SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, return SECSuccess; } - #define CS(x) x, #x #define CK(x) x | 0xff00, #x -#define S_DSA "DSA", ssl_auth_dsa -#define S_RSA "RSA", ssl_auth_rsa -#define S_KEA "KEA", ssl_auth_kea +#define S_DSA "DSA", ssl_auth_dsa +#define S_RSA "RSA", ssl_auth_rsa +#define S_KEA "KEA", ssl_auth_kea #define S_ECDSA "ECDSA", ssl_auth_ecdsa -#define K_DHE "DHE", kt_dh -#define K_RSA "RSA", kt_rsa -#define K_KEA "KEA", kt_kea -#define K_ECDH "ECDH", kt_ecdh -#define K_ECDHE "ECDHE", kt_ecdh +#define K_DHE "DHE", kt_dh +#define K_RSA "RSA", kt_rsa +#define K_KEA "KEA", kt_kea +#define K_ECDH "ECDH", kt_ecdh +#define K_ECDHE "ECDHE", kt_ecdh -#define C_SEED "SEED", calg_seed +#define C_SEED "SEED", calg_seed #define C_CAMELLIA "CAMELLIA", calg_camellia -#define C_AES "AES", calg_aes -#define C_RC4 "RC4", calg_rc4 -#define C_RC2 "RC2", calg_rc2 -#define C_DES "DES", calg_des -#define C_3DES "3DES", calg_3des -#define C_NULL "NULL", calg_null -#define C_SJ "SKIPJACK", calg_sj +#define C_AES "AES", calg_aes +#define C_RC4 "RC4", calg_rc4 +#define C_RC2 "RC2", calg_rc2 +#define C_DES "DES", calg_des +#define C_3DES "3DES", calg_3des +#define C_NULL "NULL", calg_null +#define C_SJ "SKIPJACK", calg_sj #define C_AESGCM "AES-GCM", calg_aes_gcm +#define C_CHACHA20 "CHACHA20POLY1305", calg_chacha20 -#define B_256 256, 256, 256 -#define B_128 128, 128, 128 -#define B_3DES 192, 156, 112 -#define B_SJ 96, 80, 80 -#define B_DES 64, 56, 56 -#define B_56 128, 56, 56 -#define B_40 128, 40, 40 -#define B_0 0, 0, 0 +#define B_256 256, 256, 256 +#define B_128 128, 128, 128 +#define B_3DES 192, 156, 112 +#define B_SJ 96, 80, 80 +#define B_DES 64, 56, 56 +#define B_56 128, 56, 56 +#define B_40 128, 40, 40 +#define B_0 0, 0, 0 #define M_AEAD_128 "AEAD", ssl_mac_aead, 128 #define M_SHA256 "SHA256", ssl_hmac_sha256, 256 -#define M_SHA "SHA1", ssl_mac_sha, 160 -#define M_MD5 "MD5", ssl_mac_md5, 128 -#define M_NULL "NULL", ssl_mac_null, 0 +#define M_SHA "SHA1", ssl_mac_sha, 160 +#define M_MD5 "MD5", ssl_mac_md5, 128 +#define M_NULL "NULL", ssl_mac_null, 0 +/* clang-format off */ static const SSLCipherSuiteInfo suiteInfo[] = { -/* <------ Cipher suite --------------------> */ -{0,CS(TLS_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, + /* <------ Cipher suite --------------------> */ + {0,CS(TLS_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256), S_RSA, K_DHE, C_CHACHA20, B_256, M_AEAD_128, 0, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA), S_DSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256), S_DSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, -{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_RSA, C_AES, B_256, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_RSA, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA), S_DSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256), S_DSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_256, M_SHA, 0, 0, 0 }, + {0,CS(TLS_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_RSA, C_AES, B_256, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_RSA, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256), S_DSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256), S_DSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_RSA_WITH_RC4_128_SHA), S_RSA, K_RSA, C_RC4, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_RSA_WITH_RC4_128_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0 }, -{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_RSA, C_AES, B_128, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_RSA, C_AES, B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256), S_DSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256), S_DSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_RSA_WITH_RC4_128_SHA), S_RSA, K_RSA, C_RC4, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_RSA_WITH_RC4_128_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0 }, + {0,CS(TLS_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_RSA, C_AES, B_128, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_RSA, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA), S_DSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, -{0,CS(SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 1 }, -{0,CS(TLS_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA), S_DSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, + {0,CS(SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 1 }, + {0,CS(TLS_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 0 }, -{0,CS(TLS_DHE_RSA_WITH_DES_CBC_SHA), S_RSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0 }, -{0,CS(TLS_DHE_DSS_WITH_DES_CBC_SHA), S_DSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0 }, -{0,CS(SSL_RSA_FIPS_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 1 }, -{0,CS(TLS_RSA_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 0 }, + {0,CS(TLS_DHE_RSA_WITH_DES_CBC_SHA), S_RSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0 }, + {0,CS(TLS_DHE_DSS_WITH_DES_CBC_SHA), S_DSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0 }, + {0,CS(SSL_RSA_FIPS_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 1 }, + {0,CS(TLS_RSA_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 0 }, -{0,CS(TLS_RSA_EXPORT1024_WITH_RC4_56_SHA), S_RSA, K_RSA, C_RC4, B_56, M_SHA, 0, 1, 0 }, -{0,CS(TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 1, 0 }, -{0,CS(TLS_RSA_EXPORT_WITH_RC4_40_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0 }, -{0,CS(TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0 }, -{0,CS(TLS_RSA_WITH_NULL_SHA256), S_RSA, K_RSA, C_NULL,B_0, M_SHA256, 0, 1, 0 }, -{0,CS(TLS_RSA_WITH_NULL_SHA), S_RSA, K_RSA, C_NULL,B_0, M_SHA, 0, 1, 0 }, -{0,CS(TLS_RSA_WITH_NULL_MD5), S_RSA, K_RSA, C_NULL,B_0, M_MD5, 0, 1, 0 }, + {0,CS(TLS_RSA_EXPORT1024_WITH_RC4_56_SHA), S_RSA, K_RSA, C_RC4, B_56, M_SHA, 0, 1, 0 }, + {0,CS(TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 1, 0 }, + {0,CS(TLS_RSA_EXPORT_WITH_RC4_40_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0 }, + {0,CS(TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0 }, + {0,CS(TLS_RSA_WITH_NULL_SHA256), S_RSA, K_RSA, C_NULL,B_0, M_SHA256, 0, 1, 0 }, + {0,CS(TLS_RSA_WITH_NULL_SHA), S_RSA, K_RSA, C_NULL,B_0, M_SHA, 0, 1, 0 }, + {0,CS(TLS_RSA_WITH_NULL_MD5), S_RSA, K_RSA, C_NULL,B_0, M_MD5, 0, 1, 0 }, -#ifndef NSS_DISABLE_ECC -/* ECC cipher suites */ -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, + #ifndef NSS_DISABLE_ECC + /* ECC cipher suites */ + {0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0 }, -{0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256), S_ECDSA, K_ECDHE, C_CHACHA20, B_256, M_AEAD_128, 0, 0, 0 }, -{0,CS(TLS_ECDH_RSA_WITH_NULL_SHA), S_RSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDH_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDH_RSA_WITH_NULL_SHA), S_RSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDH_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_RSA_WITH_NULL_SHA), S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDHE_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, -{0,CS(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0 }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0 }, -#endif /* NSS_DISABLE_ECC */ + {0,CS(TLS_ECDHE_RSA_WITH_NULL_SHA), S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDHE_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0 }, + {0,CS(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0 }, + {0,CS(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0 }, + {0,CS(TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256), S_RSA, K_ECDHE, C_CHACHA20, B_256, M_AEAD_128, 0, 0, 0 }, + #endif /* NSS_DISABLE_ECC */ -/* SSL 2 table */ -{0,CK(SSL_CK_RC4_128_WITH_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0 }, -{0,CK(SSL_CK_RC2_128_CBC_WITH_MD5), S_RSA, K_RSA, C_RC2, B_128, M_MD5, 0, 0, 0 }, -{0,CK(SSL_CK_DES_192_EDE3_CBC_WITH_MD5), S_RSA, K_RSA, C_3DES,B_3DES,M_MD5, 0, 0, 0 }, -{0,CK(SSL_CK_DES_64_CBC_WITH_MD5), S_RSA, K_RSA, C_DES, B_DES, M_MD5, 0, 0, 0 }, -{0,CK(SSL_CK_RC4_128_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0 }, -{0,CK(SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0 } + /* SSL 2 table */ + {0,CK(SSL_CK_RC4_128_WITH_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0 }, + {0,CK(SSL_CK_RC2_128_CBC_WITH_MD5), S_RSA, K_RSA, C_RC2, B_128, M_MD5, 0, 0, 0 }, + {0,CK(SSL_CK_DES_192_EDE3_CBC_WITH_MD5), S_RSA, K_RSA, C_3DES,B_3DES,M_MD5, 0, 0, 0 }, + {0,CK(SSL_CK_DES_64_CBC_WITH_MD5), S_RSA, K_RSA, C_DES, B_DES, M_MD5, 0, 0, 0 }, + {0,CK(SSL_CK_RC4_128_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0 }, + {0,CK(SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0 } }; +/* clang-format on */ #define NUM_SUITEINFOS ((sizeof suiteInfo) / (sizeof suiteInfo[0])) - -SECStatus SSL_GetCipherSuiteInfo(PRUint16 cipherSuite, - SSLCipherSuiteInfo *info, PRUintn len) +SECStatus +SSL_GetCipherSuiteInfo(PRUint16 cipherSuite, + SSLCipherSuiteInfo *info, PRUintn len) { unsigned int i; - len = PR_MIN(len, sizeof suiteInfo[0]); - if (!info || len < sizeof suiteInfo[0].length) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + /* Check if we can properly return the length of data written and that + * we're not asked to return more information than we know how to provide. + */ + if (!info || len < sizeof suiteInfo[0].length || + len > sizeof suiteInfo[0]) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } + len = PR_MIN(len, sizeof suiteInfo[0]); for (i = 0; i < NUM_SUITEINFOS; i++) { - if (suiteInfo[i].cipherSuite == cipherSuite) { - memcpy(info, &suiteInfo[i], len); - info->length = len; - return SECSuccess; - } + if (suiteInfo[i].cipherSuite == cipherSuite) { + memcpy(info, &suiteInfo[i], len); + info->length = len; + return SECSuccess; + } } PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } -/* This function might be a candidate to be public. +/* This function might be a candidate to be public. * Disables all export ciphers in the default set of enabled ciphers. */ -SECStatus +SECStatus SSL_DisableDefaultExportCipherSuites(void) { - const SSLCipherSuiteInfo * pInfo = suiteInfo; + const SSLCipherSuiteInfo *pInfo = suiteInfo; unsigned int i; for (i = 0; i < NUM_SUITEINFOS; ++i, ++pInfo) { - if (pInfo->isExportable) { - PORT_CheckSuccess(SSL_CipherPrefSetDefault(pInfo->cipherSuite, PR_FALSE)); - } + if (pInfo->isExportable) { + PORT_CheckSuccess(SSL_CipherPrefSetDefault(pInfo->cipherSuite, PR_FALSE)); + } } return SECSuccess; } -/* This function might be a candidate to be public, +/* This function might be a candidate to be public, * except that it takes an sslSocket pointer as an argument. * A Public version would take a PRFileDesc pointer. * Disables all export ciphers in the default set of enabled ciphers. */ -SECStatus -SSL_DisableExportCipherSuites(PRFileDesc * fd) +SECStatus +SSL_DisableExportCipherSuites(PRFileDesc *fd) { - const SSLCipherSuiteInfo * pInfo = suiteInfo; + const SSLCipherSuiteInfo *pInfo = suiteInfo; unsigned int i; for (i = 0; i < NUM_SUITEINFOS; ++i, ++pInfo) { - if (pInfo->isExportable) { - PORT_CheckSuccess(SSL_CipherPrefSet(fd, pInfo->cipherSuite, PR_FALSE)); - } + if (pInfo->isExportable) { + PORT_CheckSuccess(SSL_CipherPrefSet(fd, pInfo->cipherSuite, PR_FALSE)); + } } return SECSuccess; } -/* Tells us if the named suite is exportable +/* Tells us if the named suite is exportable * returns false for unknown suites. */ PRBool @@ -324,14 +342,14 @@ SSL_IsExportCipherSuite(PRUint16 cipherSuite) { unsigned int i; for (i = 0; i < NUM_SUITEINFOS; i++) { - if (suiteInfo[i].cipherSuite == cipherSuite) { - return (PRBool)(suiteInfo[i].isExportable); - } + if (suiteInfo[i].cipherSuite == cipherSuite) { + return (PRBool)(suiteInfo[i].isExportable); + } } return PR_FALSE; } -SECItem* +SECItem * SSL_GetNegotiatedHostInfo(PRFileDesc *fd) { SECItem *sniName = NULL; @@ -340,9 +358,9 @@ SSL_GetNegotiatedHostInfo(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNegotiatedHostInfo", - SSL_GETPID(), fd)); - return NULL; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNegotiatedHostInfo", + SSL_GETPID(), fd)); + return NULL; } if (ss->sec.isServer) { @@ -357,7 +375,7 @@ SSL_GetNegotiatedHostInfo(PRFileDesc *fd) ssl_ReleaseSpecReadLock(ss); /*----------------------------*/ } return sniName; - } + } name = SSL_RevealURL(fd); if (name) { sniName = PORT_ZNew(SECItem); @@ -365,8 +383,8 @@ SSL_GetNegotiatedHostInfo(PRFileDesc *fd) PORT_Free(name); return NULL; } - sniName->data = (void*)name; - sniName->len = PORT_Strlen(name); + sniName->data = (void *)name; + sniName->len = PORT_Strlen(name); } return sniName; } @@ -385,24 +403,24 @@ SSL_ExportKeyingMaterial(PRFileDesc *fd, ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in ExportKeyingMaterial", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in ExportKeyingMaterial", + SSL_GETPID(), fd)); + return SECFailure; } if (ss->version < SSL_LIBRARY_VERSION_3_1_TLS) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION); - return SECFailure; + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION); + return SECFailure; } /* construct PRF arguments */ valLen = SSL3_RANDOM_LENGTH * 2; if (hasContext) { - valLen += 2 /* PRUint16 length */ + contextLen; + valLen += 2 /* PRUint16 length */ + contextLen; } val = PORT_Alloc(valLen); if (!val) { - return SECFailure; + return SECFailure; } i = 0; PORT_Memcpy(val + i, &ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); @@ -410,10 +428,10 @@ SSL_ExportKeyingMaterial(PRFileDesc *fd, PORT_Memcpy(val + i, &ss->ssl3.hs.server_random.rand, SSL3_RANDOM_LENGTH); i += SSL3_RANDOM_LENGTH; if (hasContext) { - val[i++] = contextLen >> 8; - val[i++] = contextLen; - PORT_Memcpy(val + i, context, contextLen); - i += contextLen; + val[i++] = contextLen >> 8; + val[i++] = contextLen; + PORT_Memcpy(val + i, context, contextLen); + i += contextLen; } PORT_Assert(i == valLen); @@ -422,11 +440,12 @@ SSL_ExportKeyingMaterial(PRFileDesc *fd, */ ssl_GetSpecReadLock(ss); if (!ss->ssl3.cwSpec->master_secret && !ss->ssl3.cwSpec->msItem.len) { - PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); - rv = SECFailure; - } else { - rv = ssl3_TLSPRFWithMasterSecret(ss->ssl3.cwSpec, label, labelLen, val, - valLen, out, outLen); + PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); + rv = SECFailure; + } + else { + rv = ssl3_TLSPRFWithMasterSecret(ss->ssl3.cwSpec, label, labelLen, val, + valLen, out, outLen); } ssl_ReleaseSpecReadLock(ss); diff --git a/security/nss/lib/ssl/sslinit.c b/security/nss/lib/ssl/sslinit.c index d7eac6dda5bf..0f38c0b57bd4 100644 --- a/security/nss/lib/ssl/sslinit.c +++ b/security/nss/lib/ssl/sslinit.c @@ -14,7 +14,7 @@ #include "sslproto.h" static int ssl_isInited = 0; -static PRCallOnceType ssl_init = { 0 }; +static PRCallOnceType ssl_init = { 0 }; PRStatus ssl_InitCallOnce(void *arg) @@ -24,22 +24,21 @@ ssl_InitCallOnce(void *arg) rv = ssl_InitializePRErrorTable(); if (rv != SECSuccess) { - *error = SEC_ERROR_NO_MEMORY; - return PR_FAILURE; + *error = SEC_ERROR_NO_MEMORY; + return PR_FAILURE; } #ifdef DEBUG - ssl3_CheckCipherSuiteOrderConsistency(); + ssl3_CheckCipherSuiteOrderConsistency(); #endif rv = ssl3_ApplyNSSPolicy(); if (rv != SECSuccess) { - *error = PORT_GetError(); - return PR_FAILURE; + *error = PORT_GetError(); + return PR_FAILURE; } return PR_SUCCESS; } - SECStatus ssl_Init(void) { @@ -47,14 +46,14 @@ ssl_Init(void) /* short circuit test if we are already inited */ if (!ssl_isInited) { - int error; - /* only do this once at init time, block all others until we are done */ - nrv = PR_CallOnceWithArg(&ssl_init, ssl_InitCallOnce, &error); - if (nrv != PR_SUCCESS) { - PORT_SetError(error); - return SECFailure; - } - ssl_isInited = 1; + int error; + /* only do this once at init time, block all others until we are done */ + nrv = PR_CallOnceWithArg(&ssl_init, ssl_InitCallOnce, &error); + if (nrv != PR_SUCCESS) { + PORT_SetError(error); + return SECFailure; + } + ssl_isInited = 1; } return SECSuccess; } diff --git a/security/nss/lib/ssl/sslmutex.c b/security/nss/lib/ssl/sslmutex.c index af683daf5616..0e2edc9f0e57 100644 --- a/security/nss/lib/ssl/sslmutex.c +++ b/security/nss/lib/ssl/sslmutex.c @@ -4,15 +4,16 @@ #include "seccomon.h" /* This ifdef should match the one in sslsnce.c */ -#if defined(XP_UNIX) || defined(XP_WIN32) || defined (XP_OS2) || defined(XP_BEOS) +#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_OS2) || defined(XP_BEOS) #include "sslmutex.h" #include "prerr.h" -static SECStatus single_process_sslMutex_Init(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Init(sslMutex* pMutex) { - PR_ASSERT(pMutex != 0 && pMutex->u.sslLock == 0 ); - + PR_ASSERT(pMutex != 0 && pMutex->u.sslLock == 0); + pMutex->u.sslLock = PR_NewLock(); if (!pMutex->u.sslLock) { return SECFailure; @@ -20,10 +21,11 @@ static SECStatus single_process_sslMutex_Init(sslMutex* pMutex) return SECSuccess; } -static SECStatus single_process_sslMutex_Destroy(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Destroy(sslMutex* pMutex) { PR_ASSERT(pMutex != 0); - PR_ASSERT(pMutex->u.sslLock!= 0); + PR_ASSERT(pMutex->u.sslLock != 0); if (!pMutex->u.sslLock) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; @@ -32,10 +34,11 @@ static SECStatus single_process_sslMutex_Destroy(sslMutex* pMutex) return SECSuccess; } -static SECStatus single_process_sslMutex_Unlock(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Unlock(sslMutex* pMutex) { - PR_ASSERT(pMutex != 0 ); - PR_ASSERT(pMutex->u.sslLock !=0); + PR_ASSERT(pMutex != 0); + PR_ASSERT(pMutex->u.sslLock != 0); if (!pMutex->u.sslLock) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; @@ -44,10 +47,11 @@ static SECStatus single_process_sslMutex_Unlock(sslMutex* pMutex) return SECSuccess; } -static SECStatus single_process_sslMutex_Lock(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Lock(sslMutex* pMutex) { PR_ASSERT(pMutex != 0); - PR_ASSERT(pMutex->u.sslLock != 0 ); + PR_ASSERT(pMutex->u.sslLock != 0); if (!pMutex->u.sslLock) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; @@ -66,7 +70,7 @@ static SECStatus single_process_sslMutex_Lock(sslMutex* pMutex) #include "pratom.h" #define SSL_MUTEX_MAGIC 0xfeedfd -#define NONBLOCKING_POSTS 1 /* maybe this is faster */ +#define NONBLOCKING_POSTS 1 /* maybe this is faster */ #if NONBLOCKING_POSTS @@ -82,20 +86,20 @@ setNonBlocking(int fd, int nonBlocking) flags = fcntl(fd, F_GETFL, 0); if (0 > flags) - return flags; + return flags; if (nonBlocking) - flags |= FNONBLOCK; + flags |= FNONBLOCK; else - flags &= ~FNONBLOCK; + flags &= ~FNONBLOCK; err = fcntl(fd, F_SETFL, flags); return err; } #endif SECStatus -sslMutex_Init(sslMutex *pMutex, int shared) +sslMutex_Init(sslMutex* pMutex, int shared) { - int err; + int err; PR_ASSERT(pMutex); pMutex->isMultiProcess = (PRBool)(shared != 0); if (!shared) { @@ -104,17 +108,17 @@ sslMutex_Init(sslMutex *pMutex, int shared) pMutex->u.pipeStr.mPipes[0] = -1; pMutex->u.pipeStr.mPipes[1] = -1; pMutex->u.pipeStr.mPipes[2] = -1; - pMutex->u.pipeStr.nWaiters = 0; + pMutex->u.pipeStr.nWaiters = 0; err = pipe(pMutex->u.pipeStr.mPipes); if (err) { - nss_MD_unix_map_default_error(errno); - return err; + nss_MD_unix_map_default_error(errno); + return err; } #if NONBLOCKING_POSTS err = setNonBlocking(pMutex->u.pipeStr.mPipes[1], 1); if (err) - goto loser; + goto loser; #endif pMutex->u.pipeStr.mPipes[2] = SSL_MUTEX_MAGIC; @@ -135,26 +139,26 @@ loser: } SECStatus -sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) +sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal) { if (PR_FALSE == pMutex->isMultiProcess) { return single_process_sslMutex_Destroy(pMutex); } if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } close(pMutex->u.pipeStr.mPipes[0]); close(pMutex->u.pipeStr.mPipes[1]); if (processLocal) { - return SECSuccess; + return SECSuccess; } pMutex->u.pipeStr.mPipes[0] = -1; pMutex->u.pipeStr.mPipes[1] = -1; pMutex->u.pipeStr.mPipes[2] = -1; - pMutex->u.pipeStr.nWaiters = 0; + pMutex->u.pipeStr.nWaiters = 0; return SECSuccess; } @@ -164,13 +168,12 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) /* nWaiters includes the holder of the lock (if any) and the number ** threads waiting for it. After incrementing nWaiters, if the count -** is exactly 1, then you have the lock and may proceed. If the +** is exactly 1, then you have the lock and may proceed. If the ** count is greater than 1, then you must wait on the pipe. -*/ +*/ - -SECStatus -sslMutex_Unlock(sslMutex *pMutex) +SECStatus +sslMutex_Unlock(sslMutex* pMutex) { PRInt32 newValue; if (PR_FALSE == pMutex->isMultiProcess) { @@ -178,30 +181,30 @@ sslMutex_Unlock(sslMutex *pMutex) } if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } /* Do Memory Barrier here. */ newValue = PR_ATOMIC_DECREMENT(&pMutex->u.pipeStr.nWaiters); if (newValue > 0) { - int cc; - char c = 1; - do { - cc = write(pMutex->u.pipeStr.mPipes[1], &c, 1); - } while (cc < 0 && (errno == EINTR || errno == EAGAIN)); - if (cc != 1) { - if (cc < 0) - nss_MD_unix_map_default_error(errno); - else - PORT_SetError(PR_UNKNOWN_ERROR); - return SECFailure; - } + int cc; + char c = 1; + do { + cc = write(pMutex->u.pipeStr.mPipes[1], &c, 1); + } while (cc < 0 && (errno == EINTR || errno == EAGAIN)); + if (cc != 1) { + if (cc < 0) + nss_MD_unix_map_default_error(errno); + else + PORT_SetError(PR_UNKNOWN_ERROR); + return SECFailure; + } } return SECSuccess; } -SECStatus -sslMutex_Lock(sslMutex *pMutex) +SECStatus +sslMutex_Lock(sslMutex* pMutex) { PRInt32 newValue; if (PR_FALSE == pMutex->isMultiProcess) { @@ -209,88 +212,88 @@ sslMutex_Lock(sslMutex *pMutex) } if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } newValue = PR_ATOMIC_INCREMENT(&pMutex->u.pipeStr.nWaiters); /* Do Memory Barrier here. */ if (newValue > 1) { - int cc; - char c; - do { - cc = read(pMutex->u.pipeStr.mPipes[0], &c, 1); - } while (cc < 0 && errno == EINTR); - if (cc != 1) { - if (cc < 0) - nss_MD_unix_map_default_error(errno); - else - PORT_SetError(PR_UNKNOWN_ERROR); - return SECFailure; - } + int cc; + char c; + do { + cc = read(pMutex->u.pipeStr.mPipes[0], &c, 1); + } while (cc < 0 && errno == EINTR); + if (cc != 1) { + if (cc < 0) + nss_MD_unix_map_default_error(errno); + else + PORT_SetError(PR_UNKNOWN_ERROR); + return SECFailure; + } } return SECSuccess; } #else -/* Using Atomic operations requires the use of a memory barrier instruction +/* Using Atomic operations requires the use of a memory barrier instruction ** on PowerPC, Sparc, and Alpha. NSPR's PR_Atomic functions do not perform ** them, and NSPR does not provide a function that does them (e.g. PR_Barrier). -** So, we don't use them on those platforms. +** So, we don't use them on those platforms. */ -SECStatus -sslMutex_Unlock(sslMutex *pMutex) +SECStatus +sslMutex_Unlock(sslMutex* pMutex) { - int cc; - char c = 1; + int cc; + char c = 1; if (PR_FALSE == pMutex->isMultiProcess) { return single_process_sslMutex_Unlock(pMutex); } if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } do { - cc = write(pMutex->u.pipeStr.mPipes[1], &c, 1); + cc = write(pMutex->u.pipeStr.mPipes[1], &c, 1); } while (cc < 0 && (errno == EINTR || errno == EAGAIN)); if (cc != 1) { - if (cc < 0) - nss_MD_unix_map_default_error(errno); - else - PORT_SetError(PR_UNKNOWN_ERROR); - return SECFailure; + if (cc < 0) + nss_MD_unix_map_default_error(errno); + else + PORT_SetError(PR_UNKNOWN_ERROR); + return SECFailure; } return SECSuccess; } -SECStatus -sslMutex_Lock(sslMutex *pMutex) +SECStatus +sslMutex_Lock(sslMutex* pMutex) { - int cc; - char c; + int cc; + char c; if (PR_FALSE == pMutex->isMultiProcess) { return single_process_sslMutex_Lock(pMutex); } - + if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } do { - cc = read(pMutex->u.pipeStr.mPipes[0], &c, 1); + cc = read(pMutex->u.pipeStr.mPipes[0], &c, 1); } while (cc < 0 && errno == EINTR); if (cc != 1) { - if (cc < 0) - nss_MD_unix_map_default_error(errno); - else - PORT_SetError(PR_UNKNOWN_ERROR); - return SECFailure; + if (cc < 0) + nss_MD_unix_map_default_error(errno); + else + PORT_SetError(PR_UNKNOWN_ERROR); + return SECFailure; } return SECSuccess; @@ -314,7 +317,8 @@ sslMutex_Lock(sslMutex *pMutex) #ifdef WINNT -SECStatus sslMutex_2LevelInit(sslMutex *sem) +SECStatus +sslMutex_2LevelInit(sslMutex *sem) { /* the following adds a PRLock to sslMutex . This is done in each process of a multi-process server and is only needed on WINNT, if @@ -330,7 +334,8 @@ SECStatus sslMutex_2LevelInit(sslMutex *sem) return single_process_sslMutex_Init(sem); } -static SECStatus sslMutex_2LevelDestroy(sslMutex *sem) +static SECStatus +sslMutex_2LevelDestroy(sslMutex *sem) { return single_process_sslMutex_Destroy(sem); } @@ -345,26 +350,28 @@ sslMutex_Init(sslMutex *pMutex, int shared) #endif HANDLE hMutex; SECURITY_ATTRIBUTES attributes = - { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + + PR_ASSERT(pMutex != 0 && (pMutex->u.sslMutx == 0 || + pMutex->u.sslMutx == + INVALID_HANDLE_VALUE)); - PR_ASSERT(pMutex != 0 && (pMutex->u.sslMutx == 0 || - pMutex->u.sslMutx == INVALID_HANDLE_VALUE) ); - pMutex->isMultiProcess = (PRBool)(shared != 0); - + if (PR_FALSE == pMutex->isMultiProcess) { return single_process_sslMutex_Init(pMutex); } - + #ifdef WINNT /* we need a lock on WINNT for fibers in the parent process */ retvalue = sslMutex_2LevelInit(pMutex); if (SECSuccess != retvalue) return SECFailure; #endif - - if (!pMutex || ((hMutex = pMutex->u.sslMutx) != 0 && - hMutex != INVALID_HANDLE_VALUE)) { + + if (!pMutex || ((hMutex = pMutex->u.sslMutx) != 0 && + hMutex != + INVALID_HANDLE_VALUE)) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; } @@ -383,7 +390,7 @@ SECStatus sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) { HANDLE hMutex; - int rv; + int rv; int retvalue = SECSuccess; PR_ASSERT(pMutex != 0); @@ -391,20 +398,20 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) return single_process_sslMutex_Destroy(pMutex); } - /* multi-process mode */ +/* multi-process mode */ #ifdef WINNT /* on NT, get rid of the PRLock used for fibers within a process */ retvalue = sslMutex_2LevelDestroy(pMutex); #endif - - PR_ASSERT( pMutex->u.sslMutx != 0 && - pMutex->u.sslMutx != INVALID_HANDLE_VALUE); - if (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 - || hMutex == INVALID_HANDLE_VALUE) { + + PR_ASSERT(pMutex->u.sslMutx != 0 && + pMutex->u.sslMutx != INVALID_HANDLE_VALUE); + if (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 || + hMutex == INVALID_HANDLE_VALUE) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; } - + rv = CloseHandle(hMutex); /* ignore error */ if (!processLocal && rv) { pMutex->u.sslMutx = hMutex = INVALID_HANDLE_VALUE; @@ -416,18 +423,18 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) return retvalue; } -int +int sslMutex_Unlock(sslMutex *pMutex) { - BOOL success = FALSE; + BOOL success = FALSE; HANDLE hMutex; - PR_ASSERT(pMutex != 0 ); + PR_ASSERT(pMutex != 0); if (PR_FALSE == pMutex->isMultiProcess) { return single_process_sslMutex_Unlock(pMutex); } - - PR_ASSERT(pMutex->u.sslMutx != 0 && + + PR_ASSERT(pMutex->u.sslMutx != 0 && pMutex->u.sslMutx != INVALID_HANDLE_VALUE); if (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 || hMutex == INVALID_HANDLE_VALUE) { @@ -447,12 +454,12 @@ sslMutex_Unlock(sslMutex *pMutex) #endif } -int +int sslMutex_Lock(sslMutex *pMutex) { - HANDLE hMutex; - DWORD event; - DWORD lastError; + HANDLE hMutex; + DWORD event; + DWORD lastError; SECStatus rv; SECStatus retvalue = SECSuccess; PR_ASSERT(pMutex != 0); @@ -465,42 +472,42 @@ sslMutex_Lock(sslMutex *pMutex) in the same process */ retvalue = single_process_sslMutex_Lock(pMutex); #endif - PR_ASSERT(pMutex->u.sslMutx != 0 && + PR_ASSERT(pMutex->u.sslMutx != 0 && pMutex->u.sslMutx != INVALID_HANDLE_VALUE); - if (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 || + if (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 || hMutex == INVALID_HANDLE_VALUE) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; /* what else ? */ + return SECFailure; /* what else ? */ } /* acquire the mutex to be the only owner accross all other processes */ event = WaitForSingleObject(hMutex, INFINITE); switch (event) { - case WAIT_OBJECT_0: - case WAIT_ABANDONED: - rv = SECSuccess; - break; + case WAIT_OBJECT_0: + case WAIT_ABANDONED: + rv = SECSuccess; + break; - case WAIT_TIMEOUT: + case WAIT_TIMEOUT: #if defined(WAIT_IO_COMPLETION) - case WAIT_IO_COMPLETION: + case WAIT_IO_COMPLETION: #endif - default: /* should never happen. nothing we can do. */ - PR_ASSERT(!("WaitForSingleObject returned invalid value.")); - PORT_SetError(PR_UNKNOWN_ERROR); - rv = SECFailure; - break; + default: /* should never happen. nothing we can do. */ + PR_ASSERT(!("WaitForSingleObject returned invalid value.")); + PORT_SetError(PR_UNKNOWN_ERROR); + rv = SECFailure; + break; - case WAIT_FAILED: /* failure returns this */ - rv = SECFailure; - lastError = GetLastError(); /* for debugging */ - nss_MD_win32_map_default_error(lastError); - break; + case WAIT_FAILED: /* failure returns this */ + rv = SECFailure; + lastError = GetLastError(); /* for debugging */ + nss_MD_win32_map_default_error(lastError); + break; } - if (! (SECSuccess == retvalue && SECSuccess == rv)) { + if (!(SECSuccess == retvalue && SECSuccess == rv)) { return SECFailure; } - + return SECSuccess; } @@ -509,8 +516,8 @@ sslMutex_Lock(sslMutex *pMutex) #include #include "unix_err.h" -SECStatus -sslMutex_Init(sslMutex *pMutex, int shared) +SECStatus +sslMutex_Init(sslMutex* pMutex, int shared) { int rv; PR_ASSERT(pMutex); @@ -528,8 +535,8 @@ sslMutex_Init(sslMutex *pMutex, int shared) return SECSuccess; } -SECStatus -sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) +SECStatus +sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal) { int rv; if (PR_FALSE == pMutex->isMultiProcess) { @@ -538,56 +545,56 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) /* semaphores are global resources. See SEM_DESTROY(3) man page */ if (processLocal) { - return SECSuccess; + return SECSuccess; } do { - rv = sem_destroy(&pMutex->u.sem); + rv = sem_destroy(&pMutex->u.sem); } while (rv < 0 && errno == EINTR); if (rv < 0) { - nss_MD_unix_map_default_error(errno); - return SECFailure; + nss_MD_unix_map_default_error(errno); + return SECFailure; } return SECSuccess; } -SECStatus -sslMutex_Unlock(sslMutex *pMutex) +SECStatus +sslMutex_Unlock(sslMutex* pMutex) { int rv; if (PR_FALSE == pMutex->isMultiProcess) { return single_process_sslMutex_Unlock(pMutex); } do { - rv = sem_post(&pMutex->u.sem); + rv = sem_post(&pMutex->u.sem); } while (rv < 0 && errno == EINTR); if (rv < 0) { - nss_MD_unix_map_default_error(errno); - return SECFailure; + nss_MD_unix_map_default_error(errno); + return SECFailure; } return SECSuccess; } -SECStatus -sslMutex_Lock(sslMutex *pMutex) +SECStatus +sslMutex_Lock(sslMutex* pMutex) { int rv; if (PR_FALSE == pMutex->isMultiProcess) { return single_process_sslMutex_Lock(pMutex); } do { - rv = sem_wait(&pMutex->u.sem); + rv = sem_wait(&pMutex->u.sem); } while (rv < 0 && errno == EINTR); if (rv < 0) { - nss_MD_unix_map_default_error(errno); - return SECFailure; + nss_MD_unix_map_default_error(errno); + return SECFailure; } return SECSuccess; } #else -SECStatus -sslMutex_Init(sslMutex *pMutex, int shared) +SECStatus +sslMutex_Init(sslMutex* pMutex, int shared) { PR_ASSERT(pMutex); pMutex->isMultiProcess = (PRBool)(shared != 0); @@ -599,8 +606,8 @@ sslMutex_Init(sslMutex *pMutex, int shared) return SECFailure; } -SECStatus -sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) +SECStatus +sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal) { PR_ASSERT(pMutex); if (PR_FALSE == pMutex->isMultiProcess) { @@ -611,8 +618,8 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) return SECFailure; } -SECStatus -sslMutex_Unlock(sslMutex *pMutex) +SECStatus +sslMutex_Unlock(sslMutex* pMutex) { PR_ASSERT(pMutex); if (PR_FALSE == pMutex->isMultiProcess) { @@ -623,8 +630,8 @@ sslMutex_Unlock(sslMutex *pMutex) return SECFailure; } -SECStatus -sslMutex_Lock(sslMutex *pMutex) +SECStatus +sslMutex_Lock(sslMutex* pMutex) { PR_ASSERT(pMutex); if (PR_FALSE == pMutex->isMultiProcess) { diff --git a/security/nss/lib/ssl/sslmutex.h b/security/nss/lib/ssl/sslmutex.h index d374a883b732..6e2005df9f52 100644 --- a/security/nss/lib/ssl/sslmutex.h +++ b/security/nss/lib/ssl/sslmutex.h @@ -4,20 +4,20 @@ #ifndef __SSLMUTEX_H_ #define __SSLMUTEX_H_ 1 -/* What SSL really wants is portable process-shared unnamed mutexes in +/* What SSL really wants is portable process-shared unnamed mutexes in * shared memory, that have the property that if the process that holds - * them dies, they are released automatically, and that (unlike fcntl - * record locking) lock to the thread, not to the process. - * NSPR doesn't provide that. - * Windows has mutexes that meet that description, but they're not portable. - * POSIX mutexes are not automatically released when the holder dies, - * and other processes/threads cannot release the mutex on behalf of the - * dead holder. - * POSIX semaphores can be used to accomplish this on systems that implement - * process-shared unnamed POSIX semaphores, because a watchdog thread can - * discover and release semaphores that were held by a dead process. - * On systems that do not support process-shared POSIX unnamed semaphores, - * they can be emulated using pipes. + * them dies, they are released automatically, and that (unlike fcntl + * record locking) lock to the thread, not to the process. + * NSPR doesn't provide that. + * Windows has mutexes that meet that description, but they're not portable. + * POSIX mutexes are not automatically released when the holder dies, + * and other processes/threads cannot release the mutex on behalf of the + * dead holder. + * POSIX semaphores can be used to accomplish this on systems that implement + * process-shared unnamed POSIX semaphores, because a watchdog thread can + * discover and release semaphores that were held by a dead process. + * On systems that do not support process-shared POSIX unnamed semaphores, + * they can be emulated using pipes. * The performance cost of doing that is not yet measured. * * So, this API looks a lot like POSIX pthread mutexes. @@ -34,8 +34,8 @@ #include -typedef struct -{ +typedef struct + { PRBool isMultiProcess; #ifdef WINNT /* on WINNT we need both the PRLock and the Win32 mutex for fibers */ @@ -43,25 +43,25 @@ typedef struct #else union { #endif - PRLock* sslLock; + PRLock *sslLock; HANDLE sslMutx; } u; } sslMutex; -typedef int sslPID; +typedef int sslPID; #elif defined(LINUX) || defined(AIX) || defined(BEOS) || defined(BSDI) || (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD) #include #include "prtypes.h" -typedef struct { +typedef struct { PRBool isMultiProcess; union { - PRLock* sslLock; + PRLock *sslLock; struct { - int mPipes[3]; - PRInt32 nWaiters; + int mPipes[3]; + PRInt32 nWaiters; } pipeStr; } u; } sslMutex; @@ -70,15 +70,15 @@ typedef pid_t sslPID; /* other types of unix, except OS X */ #elif defined(XP_UNIX) && !defined(DARWIN) -#include /* for pid_t */ -#include /* for sem_t, and sem_* functions */ +#include /* for pid_t */ +#include /* for sem_t, and sem_* functions */ typedef struct -{ + { PRBool isMultiProcess; union { - PRLock* sslLock; - sem_t sem; + PRLock *sslLock; + sem_t sem; } u; } sslMutex; @@ -88,10 +88,10 @@ typedef pid_t sslPID; /* what platform is this ?? */ -typedef struct { +typedef struct { PRBool isMultiProcess; union { - PRLock* sslLock; + PRLock *sslLock; /* include cross-process locking mechanism here */ } u; } sslMutex; @@ -111,7 +111,7 @@ SEC_BEGIN_PROTOS extern SECStatus sslMutex_Init(sslMutex *sem, int shared); /* If processLocal is set to true, then just free resources which are *only* associated - * with the current process. Leave any shared resources (including the state of + * with the current process. Leave any shared resources (including the state of * shared memory) intact. */ extern SECStatus sslMutex_Destroy(sslMutex *sem, PRBool processLocal); diff --git a/security/nss/lib/ssl/sslnonce.c b/security/nss/lib/ssl/sslnonce.c index 07adb7a27496..8f84a4a91518 100644 --- a/security/nss/lib/ssl/sslnonce.c +++ b/security/nss/lib/ssl/sslnonce.c @@ -1,5 +1,5 @@ -/* - * This file implements the CLIENT Session ID cache. +/* + * This file implements the CLIENT Session ID cache. * * 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 @@ -22,18 +22,18 @@ PRUint32 ssl_sid_timeout = 100; PRUint32 ssl3_sid_timeout = 86400L; /* 24 hours */ static sslSessionID *cache = NULL; -static PZLock * cacheLock = NULL; +static PZLock *cacheLock = NULL; /* sids can be in one of 4 states: * - * never_cached, created, but not yet put into cache. - * in_client_cache, in the client cache's linked list. - * in_server_cache, entry came from the server's cache file. - * invalid_cache has been removed from the cache. + * never_cached, created, but not yet put into cache. + * in_client_cache, in the client cache's linked list. + * in_server_cache, entry came from the server's cache file. + * invalid_cache has been removed from the cache. */ -#define LOCK_CACHE lock_cache() -#define UNLOCK_CACHE PZ_Unlock(cacheLock) +#define LOCK_CACHE lock_cache() +#define UNLOCK_CACHE PZ_Unlock(cacheLock) static SECStatus ssl_InitClientSessionCacheLock(void) @@ -62,7 +62,7 @@ FreeSessionCacheLocks() SECStatus rv1, rv2; rv1 = ssl_FreeSymWrapKeysLock(); rv2 = ssl_FreeClientSessionCacheLock(); - if ( (SECSuccess == rv1) && (SECSuccess == rv2) ) { + if ((SECSuccess == rv1) && (SECSuccess == rv2)) { return SECSuccess; } return SECFailure; @@ -75,7 +75,7 @@ InitSessionCacheLocks(void) PRErrorCode rc; rv1 = ssl_InitSymWrapKeysLock(); rv2 = ssl_InitClientSessionCacheLock(); - if ( (SECSuccess == rv1) && (SECSuccess == rv2) ) { + if ((SECSuccess == rv1) && (SECSuccess == rv2)) { return SECSuccess; } rc = PORT_GetError(); @@ -101,7 +101,8 @@ ssl_FreeSessionCacheLocks() static PRCallOnceType lockOnce; /* free the session cache locks if they were initialized lazily */ -static SECStatus ssl_ShutdownLocks(void* appData, void* nssData) +static SECStatus +ssl_ShutdownLocks(void *appData, void *nssData) { PORT_Assert(PR_FALSE == LocksInitializedEarly); if (LocksInitializedEarly) { @@ -113,7 +114,8 @@ static SECStatus ssl_ShutdownLocks(void* appData, void* nssData) return SECSuccess; } -static PRStatus initSessionCacheLocksLazily(void) +static PRStatus +initSessionCacheLocksLazily(void) { SECStatus rv = InitSessionCacheLocks(); if (SECSuccess != rv) { @@ -139,10 +141,11 @@ ssl_InitSessionCacheLocks(PRBool lazyInit) if (lazyInit) { return (PR_SUCCESS == - PR_CallOnce(&lockOnce, initSessionCacheLocksLazily)) ? - SECSuccess : SECFailure; + PR_CallOnce(&lockOnce, initSessionCacheLocksLazily)) + ? SECSuccess + : SECFailure; } - + if (SECSuccess == InitSessionCacheLocks()) { LocksInitializedEarly = PR_TRUE; return SECSuccess; @@ -151,7 +154,7 @@ ssl_InitSessionCacheLocks(PRBool lazyInit) return SECFailure; } -static void +static void lock_cache(void) { ssl_InitSessionCacheLocks(PR_TRUE); @@ -169,9 +172,10 @@ ssl_DestroySID(sslSessionID *sid) PORT_Assert(sid->cached != in_client_cache); if (sid->version < SSL_LIBRARY_VERSION_3_0) { - SECITEM_ZfreeItem(&sid->u.ssl2.masterKey, PR_FALSE); - SECITEM_ZfreeItem(&sid->u.ssl2.cipherArg, PR_FALSE); - } else { + SECITEM_ZfreeItem(&sid->u.ssl2.masterKey, PR_FALSE); + SECITEM_ZfreeItem(&sid->u.ssl2.cipherArg, PR_FALSE); + } + else { if (sid->u.ssl3.locked.sessionTicket.ticket.data) { SECITEM_FreeItem(&sid->u.ssl3.locked.sessionTicket.ticket, PR_FALSE); @@ -189,45 +193,45 @@ ssl_DestroySID(sslSessionID *sid) } if (sid->peerID != NULL) - PORT_Free((void *)sid->peerID); /* CONST */ + PORT_Free((void *)sid->peerID); /* CONST */ if (sid->urlSvrName != NULL) - PORT_Free((void *)sid->urlSvrName); /* CONST */ + PORT_Free((void *)sid->urlSvrName); /* CONST */ - if ( sid->peerCert ) { - CERT_DestroyCertificate(sid->peerCert); + if (sid->peerCert) { + CERT_DestroyCertificate(sid->peerCert); } if (sid->peerCertStatus.items) { SECITEM_FreeArray(&sid->peerCertStatus, PR_FALSE); } - if ( sid->localCert ) { - CERT_DestroyCertificate(sid->localCert); + if (sid->localCert) { + CERT_DestroyCertificate(sid->localCert); } - + PORT_ZFree(sid, sizeof(sslSessionID)); } /* BEWARE: This function gets called for both client and server SIDs !! - * Decrement reference count, and - * free sid if ref count is zero, and sid is not in the cache. - * Does NOT remove from the cache first. + * Decrement reference count, and + * free sid if ref count is zero, and sid is not in the cache. + * Does NOT remove from the cache first. * If the sid is still in the cache, it is left there until next time * the cache list is traversed. */ -static void +static void ssl_FreeLockedSID(sslSessionID *sid) { PORT_Assert(sid->references >= 1); if (--sid->references == 0) { - ssl_DestroySID(sid); + ssl_DestroySID(sid); } } /* BEWARE: This function gets called for both client and server SIDs !! - * Decrement reference count, and - * free sid if ref count is zero, and sid is not in the cache. - * Does NOT remove from the cache first. + * Decrement reference count, and + * free sid if ref count is zero, and sid is not in the cache. + * Does NOT remove from the cache first. * These locks are necessary because the sid _might_ be in the cache list. */ void @@ -247,55 +251,56 @@ ssl_FreeSID(sslSessionID *sid) */ sslSessionID * -ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, - const char * urlSvrName) +ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, + const char *urlSvrName) { sslSessionID **sidp; - sslSessionID * sid; - PRUint32 now; + sslSessionID *sid; + PRUint32 now; if (!urlSvrName) - return NULL; + return NULL; now = ssl_Time(); LOCK_CACHE; sidp = &cache; while ((sid = *sidp) != 0) { - PORT_Assert(sid->cached == in_client_cache); - PORT_Assert(sid->references >= 1); + PORT_Assert(sid->cached == in_client_cache); + PORT_Assert(sid->references >= 1); - SSL_TRC(8, ("SSL: Lookup1: sid=0x%x", sid)); + SSL_TRC(8, ("SSL: Lookup1: sid=0x%x", sid)); - if (sid->expirationTime < now) { - /* - ** This session-id timed out. - ** Don't even care who it belongs to, blow it out of our cache. - */ - SSL_TRC(7, ("SSL: lookup1, throwing sid out, age=%d refs=%d", - now - sid->creationTime, sid->references)); + if (sid->expirationTime < now) { + /* + ** This session-id timed out. + ** Don't even care who it belongs to, blow it out of our cache. + */ + SSL_TRC(7, ("SSL: lookup1, throwing sid out, age=%d refs=%d", + now - sid->creationTime, sid->references)); - *sidp = sid->next; /* delink it from the list. */ - sid->cached = invalid_cache; /* mark not on list. */ - ssl_FreeLockedSID(sid); /* drop ref count, free. */ - } else if (!memcmp(&sid->addr, addr, sizeof(PRIPv6Addr)) && /* server IP addr matches */ - (sid->port == port) && /* server port matches */ - /* proxy (peerID) matches */ - (((peerID == NULL) && (sid->peerID == NULL)) || - ((peerID != NULL) && (sid->peerID != NULL) && - PORT_Strcmp(sid->peerID, peerID) == 0)) && - /* is cacheable */ - (sid->version < SSL_LIBRARY_VERSION_3_0 || - sid->u.ssl3.keys.resumable) && - /* server hostname matches. */ - (sid->urlSvrName != NULL) && - (0 == PORT_Strcmp(urlSvrName, sid->urlSvrName)) - ) { - /* Hit */ - sid->lastAccessTime = now; - sid->references++; - break; - } else { - sidp = &sid->next; - } + *sidp = sid->next; /* delink it from the list. */ + sid->cached = invalid_cache; /* mark not on list. */ + ssl_FreeLockedSID(sid); /* drop ref count, free. */ + } + else if (!memcmp(&sid->addr, addr, sizeof(PRIPv6Addr)) && /* server IP addr matches */ + (sid->port == port) && /* server port matches */ + /* proxy (peerID) matches */ + (((peerID == NULL) && (sid->peerID == NULL)) || + ((peerID != NULL) && (sid->peerID != NULL) && + PORT_Strcmp(sid->peerID, peerID) == 0)) && + /* is cacheable */ + (sid->version < SSL_LIBRARY_VERSION_3_0 || + sid->u.ssl3.keys.resumable) && + /* server hostname matches. */ + (sid->urlSvrName != NULL) && + (0 == PORT_Strcmp(urlSvrName, sid->urlSvrName))) { + /* Hit */ + sid->lastAccessTime = now; + sid->references++; + break; + } + else { + sidp = &sid->next; + } } UNLOCK_CACHE; return sid; @@ -305,19 +310,19 @@ ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, ** Add an sid to the cache or return a previously cached entry to the cache. ** Although this is static, it is called via ss->sec.cache(). */ -static void +static void CacheSID(sslSessionID *sid) { - PRUint32 expirationPeriod; + PRUint32 expirationPeriod; PORT_Assert(sid->cached == never_cached); SSL_TRC(8, ("SSL: Cache: sid=0x%x cached=%d addr=0x%08x%08x%08x%08x port=0x%04x " - "time=%x cached=%d", - sid, sid->cached, sid->addr.pr_s6_addr32[0], - sid->addr.pr_s6_addr32[1], sid->addr.pr_s6_addr32[2], - sid->addr.pr_s6_addr32[3], sid->port, sid->creationTime, - sid->cached)); + "time=%x cached=%d", + sid, sid->cached, sid->addr.pr_s6_addr32[0], + sid->addr.pr_s6_addr32[1], sid->addr.pr_s6_addr32[2], + sid->addr.pr_s6_addr32[3], sid->port, sid->creationTime, + sid->cached)); if (!sid->urlSvrName) { /* don't cache this SID because it can never be matched */ @@ -326,41 +331,42 @@ CacheSID(sslSessionID *sid) /* XXX should be different trace for version 2 vs. version 3 */ if (sid->version < SSL_LIBRARY_VERSION_3_0) { - expirationPeriod = ssl_sid_timeout; - PRINT_BUF(8, (0, "sessionID:", - sid->u.ssl2.sessionID, sizeof(sid->u.ssl2.sessionID))); - PRINT_BUF(8, (0, "masterKey:", - sid->u.ssl2.masterKey.data, sid->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", - sid->u.ssl2.cipherArg.data, sid->u.ssl2.cipherArg.len)); - } else { - if (sid->u.ssl3.sessionIDLength == 0 && - sid->u.ssl3.locked.sessionTicket.ticket.data == NULL) - return; + expirationPeriod = ssl_sid_timeout; + PRINT_BUF(8, (0, "sessionID:", + sid->u.ssl2.sessionID, sizeof(sid->u.ssl2.sessionID))); + PRINT_BUF(8, (0, "masterKey:", + sid->u.ssl2.masterKey.data, sid->u.ssl2.masterKey.len)); + PRINT_BUF(8, (0, "cipherArg:", + sid->u.ssl2.cipherArg.data, sid->u.ssl2.cipherArg.len)); + } + else { + if (sid->u.ssl3.sessionIDLength == 0 && + sid->u.ssl3.locked.sessionTicket.ticket.data == NULL) + return; - /* Client generates the SessionID if this was a stateless resume. */ - if (sid->u.ssl3.sessionIDLength == 0) { - SECStatus rv; - rv = PK11_GenerateRandom(sid->u.ssl3.sessionID, - SSL3_SESSIONID_BYTES); - if (rv != SECSuccess) - return; - sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; - } - expirationPeriod = ssl3_sid_timeout; - PRINT_BUF(8, (0, "sessionID:", - sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength)); + /* Client generates the SessionID if this was a stateless resume. */ + if (sid->u.ssl3.sessionIDLength == 0) { + SECStatus rv; + rv = PK11_GenerateRandom(sid->u.ssl3.sessionID, + SSL3_SESSIONID_BYTES); + if (rv != SECSuccess) + return; + sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; + } + expirationPeriod = ssl3_sid_timeout; + PRINT_BUF(8, (0, "sessionID:", + sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength)); - sid->u.ssl3.lock = PR_NewRWLock(PR_RWLOCK_RANK_NONE, NULL); - if (!sid->u.ssl3.lock) { - return; - } + sid->u.ssl3.lock = PR_NewRWLock(PR_RWLOCK_RANK_NONE, NULL); + if (!sid->u.ssl3.lock) { + return; + } } PORT_Assert(sid->creationTime != 0 && sid->expirationTime != 0); if (!sid->creationTime) - sid->lastAccessTime = sid->creationTime = ssl_Time(); + sid->lastAccessTime = sid->creationTime = ssl_Time(); if (!sid->expirationTime) - sid->expirationTime = sid->creationTime + expirationPeriod; + sid->expirationTime = sid->creationTime + expirationPeriod; /* * Put sid into the cache. Bump reference count to indicate that @@ -370,12 +376,12 @@ CacheSID(sslSessionID *sid) LOCK_CACHE; sid->references++; sid->cached = in_client_cache; - sid->next = cache; - cache = sid; + sid->next = cache; + cache = sid; UNLOCK_CACHE; } -/* +/* * If sid "zap" is in the cache, * removes sid from cache, and decrements reference count. * Caller must hold cache lock. @@ -387,43 +393,43 @@ UncacheSID(sslSessionID *zap) sslSessionID *sid; if (zap->cached != in_client_cache) { - return; + return; } - SSL_TRC(8,("SSL: Uncache: zap=0x%x cached=%d addr=0x%08x%08x%08x%08x port=0x%04x " - "time=%x cipher=%d", - zap, zap->cached, zap->addr.pr_s6_addr32[0], - zap->addr.pr_s6_addr32[1], zap->addr.pr_s6_addr32[2], - zap->addr.pr_s6_addr32[3], zap->port, zap->creationTime, - zap->u.ssl2.cipherType)); + SSL_TRC(8, ("SSL: Uncache: zap=0x%x cached=%d addr=0x%08x%08x%08x%08x port=0x%04x " + "time=%x cipher=%d", + zap, zap->cached, zap->addr.pr_s6_addr32[0], + zap->addr.pr_s6_addr32[1], zap->addr.pr_s6_addr32[2], + zap->addr.pr_s6_addr32[3], zap->port, zap->creationTime, + zap->u.ssl2.cipherType)); if (zap->version < SSL_LIBRARY_VERSION_3_0) { - PRINT_BUF(8, (0, "sessionID:", - zap->u.ssl2.sessionID, sizeof(zap->u.ssl2.sessionID))); - PRINT_BUF(8, (0, "masterKey:", - zap->u.ssl2.masterKey.data, zap->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", - zap->u.ssl2.cipherArg.data, zap->u.ssl2.cipherArg.len)); + PRINT_BUF(8, (0, "sessionID:", + zap->u.ssl2.sessionID, sizeof(zap->u.ssl2.sessionID))); + PRINT_BUF(8, (0, "masterKey:", + zap->u.ssl2.masterKey.data, zap->u.ssl2.masterKey.len)); + PRINT_BUF(8, (0, "cipherArg:", + zap->u.ssl2.cipherArg.data, zap->u.ssl2.cipherArg.len)); } /* See if it's in the cache, if so nuke it */ while ((sid = *sidp) != 0) { - if (sid == zap) { - /* - ** Bingo. Reduce reference count by one so that when - ** everyone is done with the sid we can free it up. - */ - *sidp = zap->next; - zap->cached = invalid_cache; - ssl_FreeLockedSID(zap); - return; - } - sidp = &sid->next; + if (sid == zap) { + /* + ** Bingo. Reduce reference count by one so that when + ** everyone is done with the sid we can free it up. + */ + *sidp = zap->next; + zap->cached = invalid_cache; + ssl_FreeLockedSID(zap); + return; + } + sidp = &sid->next; } } /* If sid "zap" is in the cache, * removes sid from cache, and decrements reference count. - * Although this function is static, it is called externally via + * Although this function is static, it is called externally via * ss->sec.uncache(). */ static void @@ -432,19 +438,19 @@ LockAndUncacheSID(sslSessionID *zap) LOCK_CACHE; UncacheSID(zap); UNLOCK_CACHE; - } /* choose client or server cache functions for this sslsocket. */ -void +void ssl_ChooseSessionIDProcs(sslSecurityInfo *sec) { if (sec->isServer) { - sec->cache = ssl_sid_cache; - sec->uncache = ssl_sid_uncache; - } else { - sec->cache = CacheSID; - sec->uncache = LockAndUncacheSID; + sec->cache = ssl_sid_cache; + sec->uncache = ssl_sid_uncache; + } + else { + sec->cache = CacheSID; + sec->uncache = LockAndUncacheSID; } } @@ -453,8 +459,8 @@ void SSL_ClearSessionCache(void) { LOCK_CACHE; - while(cache != NULL) - UncacheSID(cache); + while (cache != NULL) + UncacheSID(cache); UNLOCK_CACHE; } @@ -464,7 +470,7 @@ ssl_Time(void) { PRUint32 myTime; #if defined(XP_UNIX) || defined(XP_WIN) || defined(_WINDOWS) || defined(XP_BEOS) - myTime = time(NULL); /* accurate until the year 2038. */ + myTime = time(NULL); /* accurate until the year 2038. */ #else /* portable, but possibly slower */ PRTime now; @@ -493,11 +499,11 @@ ssl3_SetSIDSessionTicket(sslSessionID *sid, * yet, so no locking is needed. */ if (sid->u.ssl3.lock) { - PR_RWLock_Wlock(sid->u.ssl3.lock); - if (sid->u.ssl3.locked.sessionTicket.ticket.data) { - SECITEM_FreeItem(&sid->u.ssl3.locked.sessionTicket.ticket, - PR_FALSE); - } + PR_RWLock_Wlock(sid->u.ssl3.lock); + if (sid->u.ssl3.locked.sessionTicket.ticket.data) { + SECITEM_FreeItem(&sid->u.ssl3.locked.sessionTicket.ticket, + PR_FALSE); + } } PORT_Assert(!sid->u.ssl3.locked.sessionTicket.ticket.data); @@ -508,6 +514,6 @@ ssl3_SetSIDSessionTicket(sslSessionID *sid, newSessionTicket->ticket.len = 0; if (sid->u.ssl3.lock) { - PR_RWLock_Unlock(sid->u.ssl3.lock); + PR_RWLock_Unlock(sid->u.ssl3.lock); } } diff --git a/security/nss/lib/ssl/sslproto.h b/security/nss/lib/ssl/sslproto.h index 2db47a53eb81..4fa260d6d0b3 100644 --- a/security/nss/lib/ssl/sslproto.h +++ b/security/nss/lib/ssl/sslproto.h @@ -10,6 +10,8 @@ #ifndef __sslproto_h_ #define __sslproto_h_ +/* clang-format off */ + /* All versions less than 3_0 are treated as SSL version 2 */ #define SSL_LIBRARY_VERSION_2 0x0002 #define SSL_LIBRARY_VERSION_3_0 0x0300 @@ -260,6 +262,10 @@ #define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F #define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 +#define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 +#define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 +#define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA + /* Netscape "experimental" cipher suites. */ #define SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA 0xffe0 #define SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA 0xffe1 @@ -275,4 +281,6 @@ #define SRTP_NULL_HMAC_SHA1_80 0x0005 #define SRTP_NULL_HMAC_SHA1_32 0x0006 +/* clang-format on */ + #endif /* __sslproto_h_ */ diff --git a/security/nss/lib/ssl/sslreveal.c b/security/nss/lib/ssl/sslreveal.c index d97299885d94..4c124a1dc0c6 100644 --- a/security/nss/lib/ssl/sslreveal.c +++ b/security/nss/lib/ssl/sslreveal.c @@ -1,4 +1,4 @@ -/* +/* * Accessor functions for SSLSocket private members. * * This Source Code Form is subject to the terms of the Mozilla Public @@ -13,100 +13,98 @@ /* given PRFileDesc, returns a copy of certificate associated with the socket * the caller should delete the cert when done with SSL_DestroyCertificate */ -CERTCertificate * -SSL_RevealCert(PRFileDesc * fd) +CERTCertificate * +SSL_RevealCert(PRFileDesc *fd) { - CERTCertificate * cert = NULL; - sslSocket * sslsocket = NULL; + CERTCertificate *cert = NULL; + sslSocket *sslsocket = NULL; - sslsocket = ssl_FindSocket(fd); - - /* CERT_DupCertificate increases reference count and returns pointer to - * the same cert - */ - if (sslsocket && sslsocket->sec.peerCert) - cert = CERT_DupCertificate(sslsocket->sec.peerCert); - - return cert; + sslsocket = ssl_FindSocket(fd); + + /* CERT_DupCertificate increases reference count and returns pointer to + * the same cert + */ + if (sslsocket && sslsocket->sec.peerCert) + cert = CERT_DupCertificate(sslsocket->sec.peerCert); + + return cert; } /* given PRFileDesc, returns a pointer to PinArg associated with the socket */ -void * -SSL_RevealPinArg(PRFileDesc * fd) +void * +SSL_RevealPinArg(PRFileDesc *fd) { - sslSocket * sslsocket = NULL; - void * PinArg = NULL; - - sslsocket = ssl_FindSocket(fd); - - /* is pkcs11PinArg part of the sslSocket or sslSecurityInfo ? */ - if (sslsocket) - PinArg = sslsocket->pkcs11PinArg; - - return PinArg; -} + sslSocket *sslsocket = NULL; + void *PinArg = NULL; + sslsocket = ssl_FindSocket(fd); + + /* is pkcs11PinArg part of the sslSocket or sslSecurityInfo ? */ + if (sslsocket) + PinArg = sslsocket->pkcs11PinArg; + + return PinArg; +} /* given PRFileDesc, returns a pointer to the URL associated with the socket * the caller should free url when done */ -char * -SSL_RevealURL(PRFileDesc * fd) +char * +SSL_RevealURL(PRFileDesc *fd) { - sslSocket * sslsocket = NULL; - char * url = NULL; + sslSocket *sslsocket = NULL; + char *url = NULL; - sslsocket = ssl_FindSocket(fd); - - if (sslsocket && sslsocket->url) - url = PL_strdup(sslsocket->url); - - return url; + sslsocket = ssl_FindSocket(fd); + + if (sslsocket && sslsocket->url) + url = PL_strdup(sslsocket->url); + + return url; } - -/* given PRFileDesc, returns status information related to extensions +/* given PRFileDesc, returns status information related to extensions * negotiated with peer during the handshake. */ SECStatus -SSL_HandshakeNegotiatedExtension(PRFileDesc * socket, +SSL_HandshakeNegotiatedExtension(PRFileDesc *socket, SSLExtensionType extId, PRBool *pYes) { - /* some decisions derived from SSL_GetChannelInfo */ - sslSocket * sslsocket = NULL; + /* some decisions derived from SSL_GetChannelInfo */ + sslSocket *sslsocket = NULL; - if (!pYes) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - sslsocket = ssl_FindSocket(socket); - if (!sslsocket) { - SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeNegotiatedExtension", - SSL_GETPID(), socket)); - return SECFailure; - } - - *pYes = PR_FALSE; - - /* according to public API SSL_GetChannelInfo, this doesn't need a lock */ - if (sslsocket->opt.useSecurity) { - if (sslsocket->ssl3.initialized) { /* SSL3 and TLS */ - /* now we know this socket went through ssl3_InitState() and - * ss->xtnData got initialized, which is the only member accessed by - * ssl3_ExtensionNegotiated(); - * Member xtnData appears to get accessed in functions that handle - * the handshake (hello messages and extension sending), - * therefore the handshake lock should be sufficient. - */ - ssl_GetSSL3HandshakeLock(sslsocket); - *pYes = ssl3_ExtensionNegotiated(sslsocket, extId); - ssl_ReleaseSSL3HandshakeLock(sslsocket); + if (!pYes) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } - } - return SECSuccess; + sslsocket = ssl_FindSocket(socket); + if (!sslsocket) { + SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeNegotiatedExtension", + SSL_GETPID(), socket)); + return SECFailure; + } + + *pYes = PR_FALSE; + + /* according to public API SSL_GetChannelInfo, this doesn't need a lock */ + if (sslsocket->opt.useSecurity) { + if (sslsocket->ssl3.initialized) { /* SSL3 and TLS */ + /* now we know this socket went through ssl3_InitState() and + * ss->xtnData got initialized, which is the only member accessed by + * ssl3_ExtensionNegotiated(); + * Member xtnData appears to get accessed in functions that handle + * the handshake (hello messages and extension sending), + * therefore the handshake lock should be sufficient. + */ + ssl_GetSSL3HandshakeLock(sslsocket); + *pYes = ssl3_ExtensionNegotiated(sslsocket, extId); + ssl_ReleaseSSL3HandshakeLock(sslsocket); + } + } + + return SECSuccess; } diff --git a/security/nss/lib/ssl/sslsecur.c b/security/nss/lib/ssl/sslsecur.c index 53b488586054..f38ce9b8731b 100644 --- a/security/nss/lib/ssl/sslsecur.c +++ b/security/nss/lib/ssl/sslsecur.c @@ -10,23 +10,23 @@ #include "ssl.h" #include "sslimpl.h" #include "sslproto.h" -#include "secoid.h" /* for SECOID_GetALgorithmTag */ -#include "pk11func.h" /* for PK11_GenerateRandom */ -#include "nss.h" /* for NSS_RegisterShutdown */ -#include "prinit.h" /* for PR_CallOnceWithArg */ +#include "secoid.h" /* for SECOID_GetALgorithmTag */ +#include "pk11func.h" /* for PK11_GenerateRandom */ +#include "nss.h" /* for NSS_RegisterShutdown */ +#include "prinit.h" /* for PR_CallOnceWithArg */ -#define MAX_BLOCK_CYPHER_SIZE 32 +#define MAX_BLOCK_CYPHER_SIZE 32 -#define TEST_FOR_FAILURE /* reminder */ -#define SET_ERROR_CODE /* reminder */ +#define TEST_FOR_FAILURE /* reminder */ +#define SET_ERROR_CODE /* reminder */ -/* Returns a SECStatus: SECSuccess or SECFailure, NOT SECWouldBlock. - * +/* Returns a SECStatus: SECSuccess or SECFailure, NOT SECWouldBlock. + * * Currently, the list of functions called through ss->handshake is: - * + * * In sslsocks.c: * SocksGatherRecord - * SocksHandleReply + * SocksHandleReply * SocksStartGather * * In sslcon.c: @@ -38,88 +38,88 @@ * ssl2_BeginServerHandshake * ssl2_HandleClientHelloMessage * ssl2_HandleServerHelloMessage - * - * The ss->handshake function returns SECWouldBlock under these conditions: - * 1. ssl_GatherRecord1stHandshake called ssl2_GatherData which read in - * the beginning of an SSL v3 hello message and returned SECWouldBlock - * to switch to SSL v3 handshake processing. * - * 2. ssl2_HandleClientHelloMessage discovered version 3.0 in the incoming - * v2 client hello msg, and called ssl3_HandleV2ClientHello which - * returned SECWouldBlock. + * The ss->handshake function returns SECWouldBlock under these conditions: + * 1. ssl_GatherRecord1stHandshake called ssl2_GatherData which read in + * the beginning of an SSL v3 hello message and returned SECWouldBlock + * to switch to SSL v3 handshake processing. + * + * 2. ssl2_HandleClientHelloMessage discovered version 3.0 in the incoming + * v2 client hello msg, and called ssl3_HandleV2ClientHello which + * returned SECWouldBlock. * * 3. SECWouldBlock was returned by one of the callback functions, via - * one of these paths: - * - ssl2_HandleMessage() -> ssl2_HandleRequestCertificate() -> - * ss->getClientAuthData() + * one of these paths: + * - ssl2_HandleMessage() -> ssl2_HandleRequestCertificate() -> + * ss->getClientAuthData() * - * - ssl2_HandleServerHelloMessage() -> ss->handleBadCert() + * - ssl2_HandleServerHelloMessage() -> ss->handleBadCert() * - * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> - * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> - * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificate() -> - * ss->handleBadCert() + * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> + * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> + * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificate() -> + * ss->handleBadCert() * - * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> - * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> - * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificateRequest() -> - * ss->getClientAuthData() + * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> + * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> + * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificateRequest() -> + * ss->getClientAuthData() * - * Called from: SSL_ForceHandshake (below), - * ssl_SecureRecv (below) and - * ssl_SecureSend (below) - * from: WaitForResponse in sslsocks.c - * ssl_SocksRecv in sslsocks.c - * ssl_SocksSend in sslsocks.c + * Called from: SSL_ForceHandshake (below), + * ssl_SecureRecv (below) and + * ssl_SecureSend (below) + * from: WaitForResponse in sslsocks.c + * ssl_SocksRecv in sslsocks.c + * ssl_SocksSend in sslsocks.c * * Caller must hold the (write) handshakeLock. */ -int +int ssl_Do1stHandshake(sslSocket *ss) { - int rv = SECSuccess; + int rv = SECSuccess; int loopCount = 0; do { - PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss)); - PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss)); - PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss)); - if (ss->handshake == 0) { - /* Previous handshake finished. Switch to next one */ - ss->handshake = ss->nextHandshake; - ss->nextHandshake = 0; - } - if (ss->handshake == 0) { - /* Previous handshake finished. Switch to security handshake */ - ss->handshake = ss->securityHandshake; - ss->securityHandshake = 0; - } - if (ss->handshake == 0) { - /* for v3 this is done in ssl3_FinishHandshake */ - if (!ss->firstHsDone && ss->version < SSL_LIBRARY_VERSION_3_0) { - ssl_GetRecvBufLock(ss); - ss->gs.recordLen = 0; - ssl_FinishHandshake(ss); - ssl_ReleaseRecvBufLock(ss); - } - break; - } - rv = (*ss->handshake)(ss); - ++loopCount; - /* This code must continue to loop on SECWouldBlock, - * or any positive value. See XXX_1 comments. - */ - } while (rv != SECFailure); /* was (rv >= 0); XXX_1 */ + if (ss->handshake == 0) { + /* Previous handshake finished. Switch to next one */ + ss->handshake = ss->nextHandshake; + ss->nextHandshake = 0; + } + if (ss->handshake == 0) { + /* Previous handshake finished. Switch to security handshake */ + ss->handshake = ss->securityHandshake; + ss->securityHandshake = 0; + } + if (ss->handshake == 0) { + /* for v3 this is done in ssl3_FinishHandshake */ + if (!ss->firstHsDone && ss->version < SSL_LIBRARY_VERSION_3_0) { + ssl_GetRecvBufLock(ss); + ss->gs.recordLen = 0; + ssl_FinishHandshake(ss); + ssl_ReleaseRecvBufLock(ss); + } + break; + } + rv = (*ss->handshake)(ss); + ++loopCount; + /* This code must continue to loop on SECWouldBlock, + * or any positive value. See XXX_1 comments. + */ + } while (rv != SECFailure); /* was (rv >= 0); XXX_1 */ PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss)); PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss)); PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss)); if (rv == SECWouldBlock) { - PORT_SetError(PR_WOULD_BLOCK_ERROR); - rv = SECFailure; + PORT_SetError(PR_WOULD_BLOCK_ERROR); + rv = SECFailure; } return rv; } @@ -127,21 +127,21 @@ ssl_Do1stHandshake(sslSocket *ss) void ssl_FinishHandshake(sslSocket *ss) { - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); SSL_TRC(3, ("%d: SSL[%d]: handshake is completed", SSL_GETPID(), ss->fd)); ss->firstHsDone = PR_TRUE; ss->enoughFirstHsDone = PR_TRUE; ss->gs.writeOffset = 0; - ss->gs.readOffset = 0; + ss->gs.readOffset = 0; if (ss->handshakeCallback) { - PORT_Assert(ss->version < SSL_LIBRARY_VERSION_3_0 || - (ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == - ssl_preinfo_all); - (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData); + PORT_Assert(ss->version < SSL_LIBRARY_VERSION_3_0 || + (ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == + ssl_preinfo_all); + (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData); } } @@ -152,7 +152,7 @@ ssl_FinishHandshake(sslSocket *ss) static SECStatus ssl3_AlwaysBlock(sslSocket *ss) { - PORT_SetError(PR_WOULD_BLOCK_ERROR); /* perhaps redundant. */ + PORT_SetError(PR_WOULD_BLOCK_ERROR); /* perhaps redundant. */ return SECWouldBlock; } @@ -163,20 +163,20 @@ void ssl3_SetAlwaysBlock(sslSocket *ss) { if (!ss->firstHsDone) { - ss->handshake = ssl3_AlwaysBlock; - ss->nextHandshake = 0; + ss->handshake = ssl3_AlwaysBlock; + ss->nextHandshake = 0; } } -static SECStatus +static SECStatus ssl_SetTimeout(PRFileDesc *fd, PRIntervalTime timeout) { sslSocket *ss; ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SetTimeout", SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SetTimeout", SSL_GETPID(), fd)); + return SECFailure; } SSL_LOCK_READER(ss); ss->rTimeout = timeout; @@ -202,13 +202,13 @@ SSL_ResetHandshake(PRFileDesc *s, PRBool asServer) ss = ssl_FindSocket(s); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in ResetHandshake", SSL_GETPID(), s)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in ResetHandshake", SSL_GETPID(), s)); + return SECFailure; } /* Don't waste my time */ if (!ss->opt.useSecurity) - return SECSuccess; + return SECSuccess; SSL_LOCK_READER(ss); SSL_LOCK_WRITER(ss); @@ -218,15 +218,16 @@ SSL_ResetHandshake(PRFileDesc *s, PRBool asServer) ss->firstHsDone = PR_FALSE; ss->enoughFirstHsDone = PR_FALSE; - if ( asServer ) { - ss->handshake = ssl2_BeginServerHandshake; - ss->handshaking = sslHandshakingAsServer; - } else { - ss->handshake = ssl2_BeginClientHandshake; - ss->handshaking = sslHandshakingAsClient; + if (asServer) { + ss->handshake = ssl2_BeginServerHandshake; + ss->handshaking = sslHandshakingAsServer; } - ss->nextHandshake = 0; - ss->securityHandshake = 0; + else { + ss->handshake = ssl2_BeginClientHandshake; + ss->handshaking = sslHandshakingAsClient; + } + ss->nextHandshake = 0; + ss->securityHandshake = 0; ssl_GetRecvBufLock(ss); status = ssl_InitGather(&ss->gs); @@ -239,16 +240,16 @@ SSL_ResetHandshake(PRFileDesc *s, PRBool asServer) /* ** Blow away old security state and get a fresh setup. */ - ssl_GetXmitBufLock(ss); + ssl_GetXmitBufLock(ss); ssl_ResetSecurityInfo(&ss->sec, PR_TRUE); status = ssl_CreateSecurityInfo(ss); - ssl_ReleaseXmitBufLock(ss); + ssl_ReleaseXmitBufLock(ss); ssl_ReleaseSSL3HandshakeLock(ss); ssl_Release1stHandshakeLock(ss); if (!ss->TCPconnected) - ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr)); + ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr)); SSL_UNLOCK_WRITER(ss); SSL_UNLOCK_READER(ss); @@ -265,27 +266,28 @@ SECStatus SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache) { sslSocket *ss; - SECStatus rv; - + SECStatus rv; + ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in RedoHandshake", SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in RedoHandshake", SSL_GETPID(), fd)); + return SECFailure; } if (!ss->opt.useSecurity) - return SECSuccess; - + return SECSuccess; + ssl_Get1stHandshakeLock(ss); /* SSL v2 protocol does not support subsequent handshakes. */ if (ss->version < SSL_LIBRARY_VERSION_3_0) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - rv = SECFailure; - } else { - ssl_GetSSL3HandshakeLock(ss); - rv = ssl3_RedoHandshake(ss, flushCache); /* force full handshake. */ - ssl_ReleaseSSL3HandshakeLock(ss); + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); + rv = SECFailure; + } + else { + ssl_GetSSL3HandshakeLock(ss); + rv = ssl3_RedoHandshake(ss, flushCache); /* force full handshake. */ + ssl_ReleaseSSL3HandshakeLock(ss); } ssl_Release1stHandshakeLock(ss); @@ -296,9 +298,10 @@ SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache) /* ** Same as above, but with an I/O timeout. */ -SSL_IMPORT SECStatus SSL_ReHandshakeWithTimeout(PRFileDesc *fd, - PRBool flushCache, - PRIntervalTime timeout) +SSL_IMPORT SECStatus +SSL_ReHandshakeWithTimeout(PRFileDesc *fd, + PRBool flushCache, + PRIntervalTime timeout) { if (SECSuccess != ssl_SetTimeout(fd, timeout)) { return SECFailure; @@ -317,26 +320,26 @@ SSL_RedoHandshake(PRFileDesc *fd) */ SECStatus SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb, - void *client_data) + void *client_data) { sslSocket *ss; - + ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeCallback", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeCallback", + SSL_GETPID(), fd)); + return SECFailure; } if (!ss->opt.useSecurity) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ssl_Get1stHandshakeLock(ss); ssl_GetSSL3HandshakeLock(ss); - ss->handshakeCallback = cb; + ss->handshakeCallback = cb; ss->handshakeCallbackData = client_data; ssl_ReleaseSSL3HandshakeLock(ss); @@ -350,26 +353,26 @@ SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb, */ SECStatus SSL_SetCanFalseStartCallback(PRFileDesc *fd, SSLCanFalseStartCallback cb, - void *arg) + void *arg) { sslSocket *ss; ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetCanFalseStartCallback", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetCanFalseStartCallback", + SSL_GETPID(), fd)); + return SECFailure; } if (!ss->opt.useSecurity) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ssl_Get1stHandshakeLock(ss); ssl_GetSSL3HandshakeLock(ss); - ss->canFalseStartCallback = cb; + ss->canFalseStartCallback = cb; ss->canFalseStartCallbackData = arg; ssl_ReleaseSSL3HandshakeLock(ss); @@ -386,90 +389,94 @@ SSL_RecommendedCanFalseStart(PRFileDesc *fd, PRBool *canFalseStart) *canFalseStart = PR_FALSE; ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_RecommendedCanFalseStart", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_RecommendedCanFalseStart", + SSL_GETPID(), fd)); + return SECFailure; } if (!ss->ssl3.initialized) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } if (ss->version < SSL_LIBRARY_VERSION_3_0) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - return SECFailure; + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); + return SECFailure; } /* Require a forward-secret key exchange. */ *canFalseStart = ss->ssl3.hs.kea_def->kea == kea_dhe_dss || - ss->ssl3.hs.kea_def->kea == kea_dhe_rsa || - ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa || - ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa; + ss->ssl3.hs.kea_def->kea == kea_dhe_rsa || + ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa || + ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa; return SECSuccess; } -/* Try to make progress on an SSL handshake by attempting to read the +/* Try to make progress on an SSL handshake by attempting to read the ** next handshake from the peer, and sending any responses. -** For non-blocking sockets, returns PR_ERROR_WOULD_BLOCK if it cannot +** For non-blocking sockets, returns PR_ERROR_WOULD_BLOCK if it cannot ** read the next handshake from the underlying socket. ** For SSLv2, returns when handshake is complete or fatal error occurs. ** For SSLv3, returns when handshake is complete, or application data has -** arrived that must be taken by application before handshake can continue, +** arrived that must be taken by application before handshake can continue, ** or a fatal error occurs. -** Application should use handshake completion callback to tell which. +** Application should use handshake completion callback to tell which. */ SECStatus SSL_ForceHandshake(PRFileDesc *fd) { sslSocket *ss; - SECStatus rv = SECFailure; + SECStatus rv = SECFailure; ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in ForceHandshake", - SSL_GETPID(), fd)); - return rv; + SSL_DBG(("%d: SSL[%d]: bad socket in ForceHandshake", + SSL_GETPID(), fd)); + return rv; } /* Don't waste my time */ - if (!ss->opt.useSecurity) - return SECSuccess; + if (!ss->opt.useSecurity) + return SECSuccess; if (!ssl_SocketIsBlocking(ss)) { - ssl_GetXmitBufLock(ss); - if (ss->pendingBuf.len != 0) { - int sent = ssl_SendSavedWriteData(ss); - if ((sent < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) { - ssl_ReleaseXmitBufLock(ss); - return SECFailure; - } - } - ssl_ReleaseXmitBufLock(ss); + ssl_GetXmitBufLock(ss); + if (ss->pendingBuf.len != 0) { + int sent = ssl_SendSavedWriteData(ss); + if ((sent < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) { + ssl_ReleaseXmitBufLock(ss); + return SECFailure; + } + } + ssl_ReleaseXmitBufLock(ss); } ssl_Get1stHandshakeLock(ss); if (ss->version >= SSL_LIBRARY_VERSION_3_0) { - int gatherResult; + int gatherResult; - ssl_GetRecvBufLock(ss); - gatherResult = ssl3_GatherCompleteHandshake(ss, 0); - ssl_ReleaseRecvBufLock(ss); - if (gatherResult > 0) { - rv = SECSuccess; - } else if (gatherResult == 0) { - PORT_SetError(PR_END_OF_FILE_ERROR); - } else if (gatherResult == SECWouldBlock) { - PORT_SetError(PR_WOULD_BLOCK_ERROR); - } - } else if (!ss->firstHsDone) { - rv = ssl_Do1stHandshake(ss); - } else { - /* tried to force handshake on an SSL 2 socket that has - ** already completed the handshake. */ - rv = SECSuccess; /* just pretend we did it. */ + ssl_GetRecvBufLock(ss); + gatherResult = ssl3_GatherCompleteHandshake(ss, 0); + ssl_ReleaseRecvBufLock(ss); + if (gatherResult > 0) { + rv = SECSuccess; + } + else if (gatherResult == 0) { + PORT_SetError(PR_END_OF_FILE_ERROR); + } + else if (gatherResult == SECWouldBlock) { + PORT_SetError(PR_WOULD_BLOCK_ERROR); + } + } + else if (!ss->firstHsDone) { + rv = ssl_Do1stHandshake(ss); + } + else { + /* tried to force handshake on an SSL 2 socket that has + ** already completed the handshake. */ + rv = SECSuccess; /* just pretend we did it. */ } ssl_Release1stHandshakeLock(ss); @@ -480,8 +487,9 @@ SSL_ForceHandshake(PRFileDesc *fd) /* ** Same as above, but with an I/O timeout. */ -SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, - PRIntervalTime timeout) +SSL_IMPORT SECStatus +SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, + PRIntervalTime timeout) { if (SECSuccess != ssl_SetTimeout(fd, timeout)) { return SECFailure; @@ -489,7 +497,6 @@ SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, return SSL_ForceHandshake(fd); } - /************************************************************************/ /* @@ -502,32 +509,33 @@ sslBuffer_Grow(sslBuffer *b, unsigned int newLen) { newLen = PR_MAX(newLen, MAX_FRAGMENT_LENGTH + 2048); if (newLen > b->space) { - unsigned char *newBuf; - if (b->buf) { - newBuf = (unsigned char *) PORT_Realloc(b->buf, newLen); - } else { - newBuf = (unsigned char *) PORT_Alloc(newLen); - } - if (!newBuf) { - return SECFailure; - } - SSL_TRC(10, ("%d: SSL: grow buffer from %d to %d", - SSL_GETPID(), b->space, newLen)); - b->buf = newBuf; - b->space = newLen; + unsigned char *newBuf; + if (b->buf) { + newBuf = (unsigned char *)PORT_Realloc(b->buf, newLen); + } + else { + newBuf = (unsigned char *)PORT_Alloc(newLen); + } + if (!newBuf) { + return SECFailure; + } + SSL_TRC(10, ("%d: SSL: grow buffer from %d to %d", + SSL_GETPID(), b->space, newLen)); + b->buf = newBuf; + b->space = newLen; } return SECSuccess; } -SECStatus -sslBuffer_Append(sslBuffer *b, const void * data, unsigned int len) +SECStatus +sslBuffer_Append(sslBuffer *b, const void *data, unsigned int len) { unsigned int newLen = b->len + len; SECStatus rv; rv = sslBuffer_Grow(b, newLen); if (rv != SECSuccess) - return rv; + return rv; PORT_Memcpy(b->buf + b->len, data, len); b->len += len; return SECSuccess; @@ -539,15 +547,15 @@ sslBuffer_Append(sslBuffer *b, const void * data, unsigned int len) ** flush this data out. ** Caller must hold xmitBufLock */ -SECStatus +SECStatus ssl_SaveWriteData(sslSocket *ss, const void *data, unsigned int len) { - SECStatus rv; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); rv = sslBuffer_Append(&ss->pendingBuf, data, len); SSL_TRC(5, ("%d: SSL[%d]: saving %u bytes of data (%u total saved so far)", - SSL_GETPID(), ss->fd, len, ss->pendingBuf.len)); + SSL_GETPID(), ss->fd, len, ss->pendingBuf.len)); return rv; } @@ -557,25 +565,25 @@ ssl_SaveWriteData(sslSocket *ss, const void *data, unsigned int len) ** Returns count of the bytes sent, NOT a SECStatus. ** Caller must hold xmitBufLock */ -int +int ssl_SendSavedWriteData(sslSocket *ss) { - int rv = 0; + int rv = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); if (ss->pendingBuf.len != 0) { - SSL_TRC(5, ("%d: SSL[%d]: sending %d bytes of saved data", - SSL_GETPID(), ss->fd, ss->pendingBuf.len)); - rv = ssl_DefSend(ss, ss->pendingBuf.buf, ss->pendingBuf.len, 0); - if (rv < 0) { - return rv; - } - ss->pendingBuf.len -= rv; - if (ss->pendingBuf.len > 0 && rv > 0) { - /* UGH !! This shifts the whole buffer down by copying it */ - PORT_Memmove(ss->pendingBuf.buf, ss->pendingBuf.buf + rv, - ss->pendingBuf.len); - } + SSL_TRC(5, ("%d: SSL[%d]: sending %d bytes of saved data", + SSL_GETPID(), ss->fd, ss->pendingBuf.len)); + rv = ssl_DefSend(ss, ss->pendingBuf.buf, ss->pendingBuf.len, 0); + if (rv < 0) { + return rv; + } + ss->pendingBuf.len -= rv; + if (ss->pendingBuf.len > 0 && rv > 0) { + /* UGH !! This shifts the whole buffer down by copying it */ + PORT_Memmove(ss->pendingBuf.buf, ss->pendingBuf.buf + rv, + ss->pendingBuf.len); + } } return rv; } @@ -593,15 +601,15 @@ ssl_SendSavedWriteData(sslSocket *ss) ** For SSLv3, the call to ssl3_GatherAppDataRecord may encounter handshake ** messages from a subsequent handshake. ** -** This code is similar to, and easily confused with, +** This code is similar to, and easily confused with, ** ssl_GatherRecord1stHandshake() in sslcon.c */ -static int +static int DoRecv(sslSocket *ss, unsigned char *out, int len, int flags) { - int rv; - int amount; - int available; + int rv; + int amount; + int available; /* ssl3_GatherAppDataRecord may call ssl_FinishHandshake, which needs the * 1stHandshakeLock. */ @@ -610,51 +618,53 @@ DoRecv(sslSocket *ss, unsigned char *out, int len, int flags) available = ss->gs.writeOffset - ss->gs.readOffset; if (available == 0) { - /* Get some more data */ - if (ss->version >= SSL_LIBRARY_VERSION_3_0) { - /* Wait for application data to arrive. */ - rv = ssl3_GatherAppDataRecord(ss, 0); - } else { - /* See if we have a complete record */ - rv = ssl2_GatherRecord(ss, 0); - } - if (rv <= 0) { - if (rv == 0) { - /* EOF */ - SSL_TRC(10, ("%d: SSL[%d]: ssl_recv EOF", - SSL_GETPID(), ss->fd)); - goto done; - } - if ((rv != SECWouldBlock) && - (PR_GetError() != PR_WOULD_BLOCK_ERROR)) { - /* Some random error */ - goto done; - } + /* Get some more data */ + if (ss->version >= SSL_LIBRARY_VERSION_3_0) { + /* Wait for application data to arrive. */ + rv = ssl3_GatherAppDataRecord(ss, 0); + } + else { + /* See if we have a complete record */ + rv = ssl2_GatherRecord(ss, 0); + } + if (rv <= 0) { + if (rv == 0) { + /* EOF */ + SSL_TRC(10, ("%d: SSL[%d]: ssl_recv EOF", + SSL_GETPID(), ss->fd)); + goto done; + } + if ((rv != SECWouldBlock) && + (PR_GetError() != PR_WOULD_BLOCK_ERROR)) { + /* Some random error */ + goto done; + } - /* - ** Gather record is blocked waiting for more record data to - ** arrive. Try to process what we have already received - */ - } else { - /* Gather record has finished getting a complete record */ - } + /* + ** Gather record is blocked waiting for more record data to + ** arrive. Try to process what we have already received + */ + } + else { + /* Gather record has finished getting a complete record */ + } - /* See if any clear data is now available */ - available = ss->gs.writeOffset - ss->gs.readOffset; - if (available == 0) { - /* - ** No partial data is available. Force error code to - ** EWOULDBLOCK so that caller will try again later. Note - ** that the error code is probably EWOULDBLOCK already, - ** but if it isn't (for example, if we received a zero - ** length record) then this will force it to be correct. - */ - PORT_SetError(PR_WOULD_BLOCK_ERROR); - rv = SECFailure; - goto done; - } - SSL_TRC(30, ("%d: SSL[%d]: partial data ready, available=%d", - SSL_GETPID(), ss->fd, available)); + /* See if any clear data is now available */ + available = ss->gs.writeOffset - ss->gs.readOffset; + if (available == 0) { + /* + ** No partial data is available. Force error code to + ** EWOULDBLOCK so that caller will try again later. Note + ** that the error code is probably EWOULDBLOCK already, + ** but if it isn't (for example, if we received a zero + ** length record) then this will force it to be correct. + */ + PORT_SetError(PR_WOULD_BLOCK_ERROR); + rv = SECFailure; + goto done; + } + SSL_TRC(30, ("%d: SSL[%d]: partial data ready, available=%d", + SSL_GETPID(), ss->fd, available)); } if (IS_DTLS(ss) && (len < available)) { @@ -671,13 +681,13 @@ DoRecv(sslSocket *ss, unsigned char *out, int len, int flags) amount = PR_MIN(len, available); PORT_Memcpy(out, ss->gs.buf.buf + ss->gs.readOffset, amount); if (!(flags & PR_MSG_PEEK)) { - ss->gs.readOffset += amount; + ss->gs.readOffset += amount; } PORT_Assert(ss->gs.readOffset <= ss->gs.writeOffset); rv = amount; SSL_TRC(30, ("%d: SSL[%d]: amount=%d available=%d", - SSL_GETPID(), ss->fd, amount, available)); + SSL_GETPID(), ss->fd, amount, available)); PRINT_BUF(4, (ss, "DoRecv receiving plaintext:", out, amount)); done: @@ -692,60 +702,63 @@ done: ** Return SSLKEAType derived from cert's Public Key algorithm info. */ SSLKEAType -NSS_FindCertKEAType(CERTCertificate * cert) +NSS_FindCertKEAType(CERTCertificate *cert) { - SSLKEAType keaType = kt_null; - int tag; - - if (!cert) goto loser; - - tag = SECOID_GetAlgorithmTag(&(cert->subjectPublicKeyInfo.algorithm)); - - switch (tag) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - keaType = kt_rsa; - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: /* hah, signature, not a key? */ - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - keaType = kt_dh; - break; + SSLKEAType keaType = kt_null; + int tag; + + if (!cert) + goto loser; + + tag = SECOID_GetAlgorithmTag(&(cert->subjectPublicKeyInfo.algorithm)); + + switch (tag) { + case SEC_OID_X500_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_ENCRYPTION: + keaType = kt_rsa; + break; + case SEC_OID_ANSIX9_DSA_SIGNATURE: /* hah, signature, not a key? */ + case SEC_OID_X942_DIFFIE_HELMAN_KEY: + keaType = kt_dh; + break; #ifndef NSS_DISABLE_ECC - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - keaType = kt_ecdh; - break; + case SEC_OID_ANSIX962_EC_PUBLIC_KEY: + keaType = kt_ecdh; + break; #endif /* NSS_DISABLE_ECC */ - default: - keaType = kt_null; - } - - loser: - - return keaType; + default: + keaType = kt_null; + } + +loser: + + return keaType; } static const PRCallOnceType pristineCallOnce; -static PRCallOnceType setupServerCAListOnce; +static PRCallOnceType setupServerCAListOnce; -static SECStatus serverCAListShutdown(void* appData, void* nssData) +static SECStatus +serverCAListShutdown(void *appData, void *nssData) { PORT_Assert(ssl3_server_ca_list); if (ssl3_server_ca_list) { - CERT_FreeDistNames(ssl3_server_ca_list); - ssl3_server_ca_list = NULL; + CERT_FreeDistNames(ssl3_server_ca_list); + ssl3_server_ca_list = NULL; } setupServerCAListOnce = pristineCallOnce; return SECSuccess; } -static PRStatus serverCAListSetup(void *arg) +static PRStatus +serverCAListSetup(void *arg) { CERTCertDBHandle *dbHandle = (CERTCertDBHandle *)arg; SECStatus rv = NSS_RegisterShutdown(serverCAListShutdown, NULL); PORT_Assert(SECSuccess == rv); if (SECSuccess == rv) { - ssl3_server_ca_list = CERT_GetSSLCACerts(dbHandle); - return PR_SUCCESS; + ssl3_server_ca_list = CERT_GetSSLCACerts(dbHandle); + return PR_SUCCESS; } return PR_FAILURE; } @@ -756,18 +769,18 @@ ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert, ssl3KeyPair *keyPair, SSLKEAType kea) { CERTCertificateList *localCertChain = NULL; - sslServerCerts *sc = ss->serverCerts + kea; + sslServerCerts *sc = ss->serverCerts + kea; /* load the server certificate */ if (sc->serverCert != NULL) { - CERT_DestroyCertificate(sc->serverCert); - sc->serverCert = NULL; + CERT_DestroyCertificate(sc->serverCert); + sc->serverCert = NULL; sc->serverKeyBits = 0; } /* load the server cert chain */ if (sc->serverCertChain != NULL) { - CERT_DestroyCertificateList(sc->serverCertChain); - sc->serverCertChain = NULL; + CERT_DestroyCertificateList(sc->serverCertChain); + sc->serverCertChain = NULL; } if (cert) { sc->serverCert = CERT_DupCertificate(cert); @@ -781,11 +794,11 @@ ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert, goto loser; } sc->serverCertChain = (certChain) ? CERT_DupCertList(certChain) : - localCertChain; + localCertChain; if (!sc->serverCertChain) { goto loser; } - localCertChain = NULL; /* consumed */ + localCertChain = NULL; /* consumed */ } /* get keyPair */ @@ -798,7 +811,7 @@ ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert, sc->serverKeyPair = ssl3_GetKeyPairRef(keyPair); } if (kea == kt_rsa && cert && sc->serverKeyBits > 512 && - !ss->opt.noStepDown && !ss->stepDownKeyPair) { + !ss->opt.noStepDown && !ss->stepDownKeyPair) { if (ssl3_CreateRSAStepDownKeys(ss) != SECSuccess) { goto loser; } @@ -807,7 +820,7 @@ ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert, if (ssl3_SelectDHParams(ss) != SECSuccess) { goto loser; } - } + } return SECSuccess; loser: @@ -815,16 +828,16 @@ loser: CERT_DestroyCertificateList(localCertChain); } if (sc->serverCert != NULL) { - CERT_DestroyCertificate(sc->serverCert); - sc->serverCert = NULL; + CERT_DestroyCertificate(sc->serverCert); + sc->serverCert = NULL; } if (sc->serverCertChain != NULL) { - CERT_DestroyCertificateList(sc->serverCertChain); - sc->serverCertChain = NULL; + CERT_DestroyCertificateList(sc->serverCertChain); + sc->serverCertChain = NULL; } if (sc->serverKeyPair != NULL) { - ssl3_FreeKeyPair(sc->serverKeyPair); - sc->serverKeyPair = NULL; + ssl3_FreeKeyPair(sc->serverKeyPair); + sc->serverKeyPair = NULL; } return SECFailure; } @@ -833,7 +846,7 @@ loser: SECStatus SSL_ConfigSecureServer(PRFileDesc *fd, CERTCertificate *cert, - SECKEYPrivateKey *key, SSL3KEAType kea) + SECKEYPrivateKey *key, SSL3KEAType kea) { return SSL_ConfigSecureServerWithCertChain(fd, cert, NULL, key, kea); @@ -851,68 +864,68 @@ SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert, ss = ssl_FindSocket(fd); if (!ss) { - return SECFailure; + return SECFailure; } /* Both key and cert must have a value or be NULL */ /* Passing a value of NULL will turn off key exchange algorithms that were * previously turned on */ if (!cert != !key) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } /* make sure the key exchange is recognized */ if ((kea >= kt_kea_size) || (kea < kt_null)) { - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); + return SECFailure; } if (kea != NSS_FindCertKEAType(cert)) { - PORT_SetError(SSL_ERROR_CERT_KEA_MISMATCH); - return SECFailure; + PORT_SetError(SSL_ERROR_CERT_KEA_MISMATCH); + return SECFailure; } if (cert) { - /* get the size of the cert's public key, and remember it */ - pubKey = CERT_ExtractPublicKey(cert); - if (!pubKey) + /* get the size of the cert's public key, and remember it */ + pubKey = CERT_ExtractPublicKey(cert); + if (!pubKey) return SECFailure; } if (key) { - SECKEYPrivateKey * keyCopy = NULL; - CK_MECHANISM_TYPE keyMech = CKM_INVALID_MECHANISM; + SECKEYPrivateKey *keyCopy = NULL; + CK_MECHANISM_TYPE keyMech = CKM_INVALID_MECHANISM; - if (key->pkcs11Slot) { - PK11SlotInfo * bestSlot; - bestSlot = PK11_ReferenceSlot(key->pkcs11Slot); - if (bestSlot) { - keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key); - PK11_FreeSlot(bestSlot); - } - } - if (keyCopy == NULL) - keyMech = PK11_MapSignKeyType(key->keyType); - if (keyMech != CKM_INVALID_MECHANISM) { - PK11SlotInfo * bestSlot; - /* XXX Maybe should be bestSlotMultiple? */ - bestSlot = PK11_GetBestSlot(keyMech, NULL /* wincx */); - if (bestSlot) { - keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key); - PK11_FreeSlot(bestSlot); - } - } - if (keyCopy == NULL) - keyCopy = SECKEY_CopyPrivateKey(key); - if (keyCopy == NULL) - goto loser; + if (key->pkcs11Slot) { + PK11SlotInfo *bestSlot; + bestSlot = PK11_ReferenceSlot(key->pkcs11Slot); + if (bestSlot) { + keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key); + PK11_FreeSlot(bestSlot); + } + } + if (keyCopy == NULL) + keyMech = PK11_MapSignKeyType(key->keyType); + if (keyMech != CKM_INVALID_MECHANISM) { + PK11SlotInfo *bestSlot; + /* XXX Maybe should be bestSlotMultiple? */ + bestSlot = PK11_GetBestSlot(keyMech, NULL /* wincx */); + if (bestSlot) { + keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key); + PK11_FreeSlot(bestSlot); + } + } + if (keyCopy == NULL) + keyCopy = SECKEY_CopyPrivateKey(key); + if (keyCopy == NULL) + goto loser; keyPair = ssl3_NewKeyPair(keyCopy, pubKey); if (keyPair == NULL) { SECKEY_DestroyPrivateKey(keyCopy); goto loser; } - pubKey = NULL; /* adopted by serverKeyPair */ + pubKey = NULL; /* adopted by serverKeyPair */ } if (ssl_ConfigSecureServer(ss, cert, certChainOpt, keyPair, kea) == SECFailure) { @@ -920,7 +933,7 @@ SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert, } /* Only do this once because it's global. */ - if (PR_SUCCESS == PR_CallOnceWithArg(&setupServerCAListOnce, + if (PR_SUCCESS == PR_CallOnceWithArg(&setupServerCAListOnce, &serverCAListSetup, (void *)(ss->dbHandle))) { rv = SECSuccess; @@ -931,8 +944,8 @@ loser: ssl3_FreeKeyPair(keyPair); } if (pubKey) { - SECKEY_DestroyPublicKey(pubKey); - pubKey = NULL; + SECKEY_DestroyPublicKey(pubKey); + pubKey = NULL; } return rv; } @@ -947,12 +960,12 @@ ssl_CreateSecurityInfo(sslSocket *ss) /* initialize sslv2 socket to send data in the clear. */ ssl2_UseClearSendFunc(ss); - ss->sec.blockSize = 1; + ss->sec.blockSize = 1; ss->sec.blockShift = 0; - ssl_GetXmitBufLock(ss); + ssl_GetXmitBufLock(ss); status = sslBuffer_Grow(&ss->sec.writeBuf, 4096); - ssl_ReleaseXmitBufLock(ss); + ssl_ReleaseXmitBufLock(ss); return status; } @@ -960,50 +973,51 @@ ssl_CreateSecurityInfo(sslSocket *ss) SECStatus ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os) { - ss->sec.send = os->sec.send; - ss->sec.isServer = os->sec.isServer; - ss->sec.keyBits = os->sec.keyBits; - ss->sec.secretKeyBits = os->sec.secretKeyBits; + ss->sec.send = os->sec.send; + ss->sec.isServer = os->sec.isServer; + ss->sec.keyBits = os->sec.keyBits; + ss->sec.secretKeyBits = os->sec.secretKeyBits; - ss->sec.peerCert = CERT_DupCertificate(os->sec.peerCert); + ss->sec.peerCert = CERT_DupCertificate(os->sec.peerCert); if (os->sec.peerCert && !ss->sec.peerCert) - goto loser; + goto loser; - ss->sec.cache = os->sec.cache; - ss->sec.uncache = os->sec.uncache; + ss->sec.cache = os->sec.cache; + ss->sec.uncache = os->sec.uncache; /* we don't dup the connection info. */ - ss->sec.sendSequence = os->sec.sendSequence; - ss->sec.rcvSequence = os->sec.rcvSequence; + ss->sec.sendSequence = os->sec.sendSequence; + ss->sec.rcvSequence = os->sec.rcvSequence; if (os->sec.hash && os->sec.hashcx) { - ss->sec.hash = os->sec.hash; - ss->sec.hashcx = os->sec.hash->clone(os->sec.hashcx); - if (os->sec.hashcx && !ss->sec.hashcx) - goto loser; - } else { - ss->sec.hash = NULL; - ss->sec.hashcx = NULL; + ss->sec.hash = os->sec.hash; + ss->sec.hashcx = os->sec.hash->clone(os->sec.hashcx); + if (os->sec.hashcx && !ss->sec.hashcx) + goto loser; + } + else { + ss->sec.hash = NULL; + ss->sec.hashcx = NULL; } if (SECITEM_CopyItem(0, &ss->sec.sendSecret, &os->sec.sendSecret)) - goto loser; - if (SECITEM_CopyItem(0, &ss->sec.rcvSecret, &os->sec.rcvSecret)) - goto loser; + goto loser; + if (SECITEM_CopyItem(0, &ss->sec.rcvSecret, &os->sec.rcvSecret)) + goto loser; /* XXX following code is wrong if either cx != 0 */ - PORT_Assert(os->sec.readcx == 0); + PORT_Assert(os->sec.readcx == 0); PORT_Assert(os->sec.writecx == 0); - ss->sec.readcx = os->sec.readcx; - ss->sec.writecx = os->sec.writecx; - ss->sec.destroy = 0; + ss->sec.readcx = os->sec.readcx; + ss->sec.writecx = os->sec.writecx; + ss->sec.destroy = 0; - ss->sec.enc = os->sec.enc; - ss->sec.dec = os->sec.dec; + ss->sec.enc = os->sec.enc; + ss->sec.dec = os->sec.dec; - ss->sec.blockShift = os->sec.blockShift; - ss->sec.blockSize = os->sec.blockSize; + ss->sec.blockShift = os->sec.blockShift; + ss->sec.blockSize = os->sec.blockSize; return SECSuccess; @@ -1014,61 +1028,61 @@ loser: /* Reset sec back to its initial state. ** Caller holds any relevant locks. */ -void +void ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset) { /* Destroy MAC */ if (sec->hash && sec->hashcx) { - (*sec->hash->destroy)(sec->hashcx, PR_TRUE); - sec->hashcx = NULL; - sec->hash = NULL; + (*sec->hash->destroy)(sec->hashcx, PR_TRUE); + sec->hashcx = NULL; + sec->hash = NULL; } SECITEM_ZfreeItem(&sec->sendSecret, PR_FALSE); SECITEM_ZfreeItem(&sec->rcvSecret, PR_FALSE); /* Destroy ciphers */ if (sec->destroy) { - (*sec->destroy)(sec->readcx, PR_TRUE); - (*sec->destroy)(sec->writecx, PR_TRUE); - sec->readcx = NULL; - sec->writecx = NULL; - } else { - PORT_Assert(sec->readcx == 0); - PORT_Assert(sec->writecx == 0); + (*sec->destroy)(sec->readcx, PR_TRUE); + (*sec->destroy)(sec->writecx, PR_TRUE); + sec->readcx = NULL; + sec->writecx = NULL; + } + else { + PORT_Assert(sec->readcx == 0); + PORT_Assert(sec->writecx == 0); } sec->readcx = 0; sec->writecx = 0; if (sec->localCert) { - CERT_DestroyCertificate(sec->localCert); - sec->localCert = NULL; + CERT_DestroyCertificate(sec->localCert); + sec->localCert = NULL; } if (sec->peerCert) { - CERT_DestroyCertificate(sec->peerCert); - sec->peerCert = NULL; + CERT_DestroyCertificate(sec->peerCert); + sec->peerCert = NULL; } if (sec->peerKey) { - SECKEY_DestroyPublicKey(sec->peerKey); - sec->peerKey = NULL; + SECKEY_DestroyPublicKey(sec->peerKey); + sec->peerKey = NULL; } /* cleanup the ci */ if (sec->ci.sid != NULL) { - ssl_FreeSID(sec->ci.sid); + ssl_FreeSID(sec->ci.sid); } PORT_ZFree(sec->ci.sendBuf.buf, sec->ci.sendBuf.space); if (doMemset) { memset(&sec->ci, 0, sizeof sec->ci); } - } /* -** Called from SSL_ResetHandshake (above), and +** Called from SSL_ResetHandshake (above), and ** from ssl_FreeSocket in sslsock.c ** Caller should hold relevant locks (e.g. XmitBufLock) */ -void +void ssl_DestroySecurityInfo(sslSecurityInfo *sec) { ssl_ResetSecurityInfo(sec, PR_FALSE); @@ -1081,35 +1095,37 @@ ssl_DestroySecurityInfo(sslSecurityInfo *sec) /************************************************************************/ -int +int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *sa) { PRFileDesc *osfd = ss->fd->lower; int rv; - if ( ss->opt.handshakeAsServer ) { - ss->securityHandshake = ssl2_BeginServerHandshake; - ss->handshaking = sslHandshakingAsServer; - } else { - ss->securityHandshake = ssl2_BeginClientHandshake; - ss->handshaking = sslHandshakingAsClient; + if (ss->opt.handshakeAsServer) { + ss->securityHandshake = ssl2_BeginServerHandshake; + ss->handshaking = sslHandshakingAsServer; + } + else { + ss->securityHandshake = ssl2_BeginClientHandshake; + ss->handshaking = sslHandshakingAsClient; } /* connect to server */ rv = osfd->methods->connect(osfd, sa, ss->cTimeout); if (rv == PR_SUCCESS) { - ss->TCPconnected = 1; - } else { - int err = PR_GetError(); - SSL_DBG(("%d: SSL[%d]: connect failed, errno=%d", - SSL_GETPID(), ss->fd, err)); - if (err == PR_IS_CONNECTED_ERROR) { - ss->TCPconnected = 1; - } + ss->TCPconnected = 1; + } + else { + int err = PR_GetError(); + SSL_DBG(("%d: SSL[%d]: connect failed, errno=%d", + SSL_GETPID(), ss->fd, err)); + if (err == PR_IS_CONNECTED_ERROR) { + ss->TCPconnected = 1; + } } SSL_TRC(5, ("%d: SSL[%d]: secure connect completed, rv == %d", - SSL_GETPID(), ss->fd, rv)); + SSL_GETPID(), ss->fd, rv)); return rv; } @@ -1142,19 +1158,19 @@ ssl_SecureClose(sslSocket *ss) { int rv; - if (ss->version >= SSL_LIBRARY_VERSION_3_0 && - !(ss->shutdownHow & ssl_SHUTDOWN_SEND) && - ss->firstHsDone && - !ss->recvdCloseNotify && - ss->ssl3.initialized) { + if (ss->version >= SSL_LIBRARY_VERSION_3_0 && + !(ss->shutdownHow & ssl_SHUTDOWN_SEND) && + ss->firstHsDone && + !ss->recvdCloseNotify && + ss->ssl3.initialized) { - /* We don't want the final alert to be Nagle delayed. */ - if (!ss->delayDisabled) { - ssl_EnableNagleDelay(ss, PR_FALSE); - ss->delayDisabled = 1; - } + /* We don't want the final alert to be Nagle delayed. */ + if (!ss->delayDisabled) { + ssl_EnableNagleDelay(ss, PR_FALSE); + ss->delayDisabled = 1; + } - (void) SSL3_SendAlert(ss, alert_warning, close_notify); + (void)SSL3_SendAlert(ss, alert_warning, close_notify); } rv = ssl_DefClose(ss); return rv; @@ -1165,22 +1181,22 @@ int ssl_SecureShutdown(sslSocket *ss, int nsprHow) { PRFileDesc *osfd = ss->fd->lower; - int rv; - PRIntn sslHow = nsprHow + 1; + int rv; + PRIntn sslHow = nsprHow + 1; if ((unsigned)nsprHow > PR_SHUTDOWN_BOTH) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return PR_FAILURE; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return PR_FAILURE; } - if ((sslHow & ssl_SHUTDOWN_SEND) != 0 && - ss->version >= SSL_LIBRARY_VERSION_3_0 && - !(ss->shutdownHow & ssl_SHUTDOWN_SEND) && - ss->firstHsDone && - !ss->recvdCloseNotify && - ss->ssl3.initialized) { + if ((sslHow & ssl_SHUTDOWN_SEND) != 0 && + ss->version >= SSL_LIBRARY_VERSION_3_0 && + !(ss->shutdownHow & ssl_SHUTDOWN_SEND) && + ss->firstHsDone && + !ss->recvdCloseNotify && + ss->ssl3.initialized) { - (void) SSL3_SendAlert(ss, alert_warning, close_notify); + (void)SSL3_SendAlert(ss, alert_warning, close_notify); } rv = osfd->methods->shutdown(osfd, nsprHow); @@ -1192,51 +1208,51 @@ ssl_SecureShutdown(sslSocket *ss, int nsprHow) /************************************************************************/ - int ssl_SecureRecv(sslSocket *ss, unsigned char *buf, int len, int flags) { - int rv = 0; + int rv = 0; if (ss->shutdownHow & ssl_SHUTDOWN_RCV) { - PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); - return PR_FAILURE; + PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); + return PR_FAILURE; } if (flags & ~PR_MSG_PEEK) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return PR_FAILURE; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return PR_FAILURE; } if (!ssl_SocketIsBlocking(ss) && !ss->opt.fdx) { - ssl_GetXmitBufLock(ss); - if (ss->pendingBuf.len != 0) { - rv = ssl_SendSavedWriteData(ss); - if ((rv < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) { - ssl_ReleaseXmitBufLock(ss); - return SECFailure; - } - } - ssl_ReleaseXmitBufLock(ss); + ssl_GetXmitBufLock(ss); + if (ss->pendingBuf.len != 0) { + rv = ssl_SendSavedWriteData(ss); + if ((rv < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) { + ssl_ReleaseXmitBufLock(ss); + return SECFailure; + } + } + ssl_ReleaseXmitBufLock(ss); } - + rv = 0; /* If any of these is non-zero, the initial handshake is not done. */ if (!ss->firstHsDone) { - ssl_Get1stHandshakeLock(ss); - if (ss->handshake || ss->nextHandshake || ss->securityHandshake) { - rv = ssl_Do1stHandshake(ss); - } - ssl_Release1stHandshakeLock(ss); + ssl_Get1stHandshakeLock(ss); + if (ss->handshake || ss->nextHandshake || ss->securityHandshake) { + rv = ssl_Do1stHandshake(ss); + } + ssl_Release1stHandshakeLock(ss); } if (rv < 0) { - return rv; + return rv; } - if (len == 0) return 0; + if (len == 0) + return 0; - rv = DoRecv(ss, (unsigned char*) buf, len, flags); + rv = DoRecv(ss, (unsigned char *)buf, len, flags); SSL_TRC(2, ("%d: SSL[%d]: recving %d bytes securely (errno=%d)", - SSL_GETPID(), ss->fd, rv, PORT_GetError())); + SSL_GETPID(), ss->fd, rv, PORT_GetError())); return rv; } @@ -1253,84 +1269,84 @@ ssl_SecureSend(sslSocket *ss, const unsigned char *buf, int len, int flags) int rv = 0; SSL_TRC(2, ("%d: SSL[%d]: SecureSend: sending %d bytes", - SSL_GETPID(), ss->fd, len)); + SSL_GETPID(), ss->fd, len)); if (ss->shutdownHow & ssl_SHUTDOWN_SEND) { - PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); - rv = PR_FAILURE; - goto done; + PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); + rv = PR_FAILURE; + goto done; } if (flags) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - rv = PR_FAILURE; - goto done; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + rv = PR_FAILURE; + goto done; } ssl_GetXmitBufLock(ss); if (ss->pendingBuf.len != 0) { - PORT_Assert(ss->pendingBuf.len > 0); - rv = ssl_SendSavedWriteData(ss); - if (rv >= 0 && ss->pendingBuf.len != 0) { - PORT_Assert(ss->pendingBuf.len > 0); - PORT_SetError(PR_WOULD_BLOCK_ERROR); - rv = SECFailure; - } + PORT_Assert(ss->pendingBuf.len > 0); + rv = ssl_SendSavedWriteData(ss); + if (rv >= 0 && ss->pendingBuf.len != 0) { + PORT_Assert(ss->pendingBuf.len > 0); + PORT_SetError(PR_WOULD_BLOCK_ERROR); + rv = SECFailure; + } } ssl_ReleaseXmitBufLock(ss); if (rv < 0) { - goto done; + goto done; } - if (len > 0) - ss->writerThread = PR_GetCurrentThread(); + if (len > 0) + ss->writerThread = PR_GetCurrentThread(); /* If any of these is non-zero, the initial handshake is not done. */ if (!ss->firstHsDone) { - PRBool falseStart = PR_FALSE; - ssl_Get1stHandshakeLock(ss); - if (ss->opt.enableFalseStart && - ss->version >= SSL_LIBRARY_VERSION_3_0) { - ssl_GetSSL3HandshakeLock(ss); - falseStart = ss->ssl3.hs.canFalseStart; - ssl_ReleaseSSL3HandshakeLock(ss); - } - if (!falseStart && - (ss->handshake || ss->nextHandshake || ss->securityHandshake)) { - rv = ssl_Do1stHandshake(ss); - } - ssl_Release1stHandshakeLock(ss); + PRBool falseStart = PR_FALSE; + ssl_Get1stHandshakeLock(ss); + if (ss->opt.enableFalseStart && + ss->version >= SSL_LIBRARY_VERSION_3_0) { + ssl_GetSSL3HandshakeLock(ss); + falseStart = ss->ssl3.hs.canFalseStart; + ssl_ReleaseSSL3HandshakeLock(ss); + } + if (!falseStart && + (ss->handshake || ss->nextHandshake || ss->securityHandshake)) { + rv = ssl_Do1stHandshake(ss); + } + ssl_Release1stHandshakeLock(ss); } if (rv < 0) { - ss->writerThread = NULL; - goto done; + ss->writerThread = NULL; + goto done; } /* Check for zero length writes after we do housekeeping so we make forward * progress. */ if (len == 0) { - rv = 0; - goto done; + rv = 0; + goto done; } PORT_Assert(buf != NULL); if (!buf) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - rv = PR_FAILURE; - goto done; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + rv = PR_FAILURE; + goto done; } if (!ss->firstHsDone) { - PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_3_0); + PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_3_0); #ifdef DEBUG - ssl_GetSSL3HandshakeLock(ss); - PORT_Assert(ss->ssl3.hs.canFalseStart); - ssl_ReleaseSSL3HandshakeLock(ss); + ssl_GetSSL3HandshakeLock(ss); + PORT_Assert(ss->ssl3.hs.canFalseStart); + ssl_ReleaseSSL3HandshakeLock(ss); #endif - SSL_TRC(3, ("%d: SSL[%d]: SecureSend: sending data due to false start", - SSL_GETPID(), ss->fd)); + SSL_TRC(3, ("%d: SSL[%d]: SecureSend: sending data due to false start", + SSL_GETPID(), ss->fd)); } /* Send out the data using one of these functions: - * ssl2_SendClear, ssl2_SendStream, ssl2_SendBlock, + * ssl2_SendClear, ssl2_SendStream, ssl2_SendBlock, * ssl3_SendApplicationData */ ssl_GetXmitBufLock(ss); @@ -1339,11 +1355,12 @@ ssl_SecureSend(sslSocket *ss, const unsigned char *buf, int len, int flags) ss->writerThread = NULL; done: if (rv < 0) { - SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count, error %d", - SSL_GETPID(), ss->fd, rv, PORT_GetError())); - } else { - SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count", - SSL_GETPID(), ss->fd, rv)); + SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count, error %d", + SSL_GETPID(), ss->fd, rv, PORT_GetError())); + } + else { + SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count", + SSL_GETPID(), ss->fd, rv)); } return rv; } @@ -1358,12 +1375,12 @@ SECStatus SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, void *arg) { sslSocket *ss; - + ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSLBadCertHook", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSLBadCertHook", + SSL_GETPID(), fd)); + return SECFailure; } ss->handleBadCert = f; @@ -1380,24 +1397,24 @@ SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, void *arg) SECStatus SSL_SetURL(PRFileDesc *fd, const char *url) { - sslSocket * ss = ssl_FindSocket(fd); - SECStatus rv = SECSuccess; + sslSocket *ss = ssl_FindSocket(fd); + SECStatus rv = SECSuccess; if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSLSetURL", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSLSetURL", + SSL_GETPID(), fd)); + return SECFailure; } ssl_Get1stHandshakeLock(ss); ssl_GetSSL3HandshakeLock(ss); - if ( ss->url ) { - PORT_Free((void *)ss->url); /* CONST */ + if (ss->url) { + PORT_Free((void *)ss->url); /* CONST */ } ss->url = (const char *)PORT_Strdup(url); - if ( ss->url == NULL ) { - rv = SECFailure; + if (ss->url == NULL) { + rv = SECFailure; } ssl_ReleaseSSL3HandshakeLock(ss); @@ -1412,7 +1429,7 @@ SSL_SetURL(PRFileDesc *fd, const char *url) SECStatus SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *certList) { - sslSocket * ss = ssl_FindSocket(fd); + sslSocket *ss = ssl_FindSocket(fd); CERTDistNames *names = NULL; if (!certList) { @@ -1420,9 +1437,9 @@ SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *certList) return SECFailure; } if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTrustAnchors", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTrustAnchors", + SSL_GETPID(), fd)); + return SECFailure; } names = CERT_DistNamesFromCertList(certList); @@ -1449,14 +1466,14 @@ int SSL_DataPending(PRFileDesc *fd) { sslSocket *ss; - int rv = 0; + int rv = 0; ss = ssl_FindSocket(fd); if (ss && ss->opt.useSecurity) { - ssl_GetRecvBufLock(ss); - rv = ss->gs.writeOffset - ss->gs.readOffset; - ssl_ReleaseRecvBufLock(ss); + ssl_GetRecvBufLock(ss); + rv = ss->gs.writeOffset - ss->gs.readOffset; + ssl_ReleaseRecvBufLock(ss); } return rv; @@ -1465,20 +1482,20 @@ SSL_DataPending(PRFileDesc *fd) SECStatus SSL_InvalidateSession(PRFileDesc *fd) { - sslSocket * ss = ssl_FindSocket(fd); - SECStatus rv = SECFailure; + sslSocket *ss = ssl_FindSocket(fd); + SECStatus rv = SECFailure; if (ss) { - ssl_Get1stHandshakeLock(ss); - ssl_GetSSL3HandshakeLock(ss); + ssl_Get1stHandshakeLock(ss); + ssl_GetSSL3HandshakeLock(ss); - if (ss->sec.ci.sid && ss->sec.uncache) { - ss->sec.uncache(ss->sec.ci.sid); - rv = SECSuccess; - } + if (ss->sec.ci.sid && ss->sec.uncache) { + ss->sec.uncache(ss->sec.ci.sid); + rv = SECSuccess; + } - ssl_ReleaseSSL3HandshakeLock(ss); - ssl_Release1stHandshakeLock(ss); + ssl_ReleaseSSL3HandshakeLock(ss); + ssl_Release1stHandshakeLock(ss); } return rv; } @@ -1486,32 +1503,33 @@ SSL_InvalidateSession(PRFileDesc *fd) SECItem * SSL_GetSessionID(PRFileDesc *fd) { - sslSocket * ss; - SECItem * item = NULL; + sslSocket *ss; + SECItem *item = NULL; ss = ssl_FindSocket(fd); if (ss) { - ssl_Get1stHandshakeLock(ss); - ssl_GetSSL3HandshakeLock(ss); + ssl_Get1stHandshakeLock(ss); + ssl_GetSSL3HandshakeLock(ss); - if (ss->opt.useSecurity && ss->firstHsDone && ss->sec.ci.sid) { - item = (SECItem *)PORT_Alloc(sizeof(SECItem)); - if (item) { - sslSessionID * sid = ss->sec.ci.sid; - if (sid->version < SSL_LIBRARY_VERSION_3_0) { - item->len = SSL2_SESSIONID_BYTES; - item->data = (unsigned char*)PORT_Alloc(item->len); - PORT_Memcpy(item->data, sid->u.ssl2.sessionID, item->len); - } else { - item->len = sid->u.ssl3.sessionIDLength; - item->data = (unsigned char*)PORT_Alloc(item->len); - PORT_Memcpy(item->data, sid->u.ssl3.sessionID, item->len); - } - } - } + if (ss->opt.useSecurity && ss->firstHsDone && ss->sec.ci.sid) { + item = (SECItem *)PORT_Alloc(sizeof(SECItem)); + if (item) { + sslSessionID *sid = ss->sec.ci.sid; + if (sid->version < SSL_LIBRARY_VERSION_3_0) { + item->len = SSL2_SESSIONID_BYTES; + item->data = (unsigned char *)PORT_Alloc(item->len); + PORT_Memcpy(item->data, sid->u.ssl2.sessionID, item->len); + } + else { + item->len = sid->u.ssl3.sessionIDLength; + item->data = (unsigned char *)PORT_Alloc(item->len); + PORT_Memcpy(item->data, sid->u.ssl3.sessionID, item->len); + } + } + } - ssl_ReleaseSSL3HandshakeLock(ss); - ssl_Release1stHandshakeLock(ss); + ssl_ReleaseSSL3HandshakeLock(ss); + ssl_Release1stHandshakeLock(ss); } return item; } @@ -1519,14 +1537,14 @@ SSL_GetSessionID(PRFileDesc *fd) SECStatus SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle) { - sslSocket * ss; + sslSocket *ss; ss = ssl_FindSocket(fd); if (!ss) - return SECFailure; + return SECFailure; if (!dbHandle) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ss->dbHandle = dbHandle; return SECSuccess; @@ -1536,10 +1554,10 @@ SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle) * this implementation exists to maintain link-time compatibility. */ int -SSL_RestartHandshakeAfterCertReq(sslSocket * ss, - CERTCertificate * cert, - SECKEYPrivateKey * key, - CERTCertificateList *certChain) +SSL_RestartHandshakeAfterCertReq(sslSocket *ss, + CERTCertificate *cert, + SECKEYPrivateKey *key, + CERTCertificateList *certChain) { PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); return -1; @@ -1549,7 +1567,7 @@ SSL_RestartHandshakeAfterCertReq(sslSocket * ss, * this implementation exists to maintain link-time compatibility. */ int -SSL_RestartHandshakeAfterServerCert(sslSocket * ss) +SSL_RestartHandshakeAfterServerCert(sslSocket *ss) { PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); return -1; @@ -1563,21 +1581,23 @@ SSL_AuthCertificateComplete(PRFileDesc *fd, PRErrorCode error) sslSocket *ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_AuthCertificateComplete", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_AuthCertificateComplete", + SSL_GETPID(), fd)); + return SECFailure; } ssl_Get1stHandshakeLock(ss); if (!ss->ssl3.initialized) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } else if (ss->version < SSL_LIBRARY_VERSION_3_0) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - rv = SECFailure; - } else { - rv = ssl3_AuthCertificateComplete(ss, error); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + } + else if (ss->version < SSL_LIBRARY_VERSION_3_0) { + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); + rv = SECFailure; + } + else { + rv = ssl3_AuthCertificateComplete(ss, error); } ssl_Release1stHandshakeLock(ss); @@ -1586,7 +1606,7 @@ SSL_AuthCertificateComplete(PRFileDesc *fd, PRErrorCode error) } /* For more info see ssl.h */ -SECStatus +SECStatus SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig func, void *arg) { @@ -1594,9 +1614,9 @@ SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig func, ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SNISocketConfigHook", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SNISocketConfigHook", + SSL_GETPID(), fd)); + return SECFailure; } ss->sniSocketConfig = func; diff --git a/security/nss/lib/ssl/sslsnce.c b/security/nss/lib/ssl/sslsnce.c index acad15dd7684..4f07b995b3f4 100644 --- a/security/nss/lib/ssl/sslsnce.c +++ b/security/nss/lib/ssl/sslsnce.c @@ -1,23 +1,23 @@ -/* This file implements the SERVER Session ID cache. +/* This file implements the SERVER Session ID cache. * NOTE: The contents of this file are NOT used by the client. * * 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/. */ -/* Note: ssl_FreeSID() in sslnonce.c gets used for both client and server +/* Note: ssl_FreeSID() in sslnonce.c gets used for both client and server * cache sids! * * About record locking among different server processes: * - * All processes that are part of the same conceptual server (serving on - * the same address and port) MUST share a common SSL session cache. + * All processes that are part of the same conceptual server (serving on + * the same address and port) MUST share a common SSL session cache. * This code makes the content of the shared cache accessible to all * processes on the same "server". This code works on Unix and Win32 only. * * We use NSPR anonymous shared memory and move data to & from shared memory. * We must do explicit locking of the records for all reads and writes. - * The set of Cache entries are divided up into "sets" of 128 entries. + * The set of Cache entries are divided up into "sets" of 128 entries. * Each set is protected by a lock. There may be one or more sets protected * by each lock. That is, locks to sets are 1:N. * There is one lock for the entire cert cache. @@ -44,7 +44,7 @@ */ #include "seccomon.h" -#if defined(XP_UNIX) || defined(XP_WIN32) || defined (XP_OS2) || defined(XP_BEOS) +#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_OS2) || defined(XP_BEOS) #include "cert.h" #include "ssl.h" @@ -78,7 +78,7 @@ #include "win32err.h" #endif -#endif +#endif #include #define SET_ERROR_CODE /* reminder */ @@ -88,146 +88,146 @@ /* ** Format of a cache entry in the shared memory. -*/ +*/ struct sidCacheEntryStr { -/* 16 */ PRIPv6Addr addr; /* client's IP address */ -/* 4 */ PRUint32 creationTime; -/* 4 */ PRUint32 lastAccessTime; -/* 4 */ PRUint32 expirationTime; -/* 2 */ PRUint16 version; -/* 1 */ PRUint8 valid; -/* 1 */ PRUint8 sessionIDLength; -/* 32 */ PRUint8 sessionID[SSL3_SESSIONID_BYTES]; -/* 2 */ PRUint16 authAlgorithm; -/* 2 */ PRUint16 authKeyBits; -/* 2 */ PRUint16 keaType; -/* 2 */ PRUint16 keaKeyBits; -/* 72 - common header total */ + /* 16 */ PRIPv6Addr addr; /* client's IP address */ + /* 4 */ PRUint32 creationTime; + /* 4 */ PRUint32 lastAccessTime; + /* 4 */ PRUint32 expirationTime; + /* 2 */ PRUint16 version; + /* 1 */ PRUint8 valid; + /* 1 */ PRUint8 sessionIDLength; + /* 32 */ PRUint8 sessionID[SSL3_SESSIONID_BYTES]; + /* 2 */ PRUint16 authAlgorithm; + /* 2 */ PRUint16 authKeyBits; + /* 2 */ PRUint16 keaType; + /* 2 */ PRUint16 keaKeyBits; + /* 72 - common header total */ union { - struct { -/* 64 */ PRUint8 masterKey[SSL_MAX_MASTER_KEY_BYTES]; -/* 32 */ PRUint8 cipherArg[SSL_MAX_CYPHER_ARG_BYTES]; + struct { + /* 64 */ PRUint8 masterKey[SSL_MAX_MASTER_KEY_BYTES]; + /* 32 */ PRUint8 cipherArg[SSL_MAX_CYPHER_ARG_BYTES]; -/* 1 */ PRUint8 cipherType; -/* 1 */ PRUint8 masterKeyLen; -/* 1 */ PRUint8 keyBits; -/* 1 */ PRUint8 secretKeyBits; -/* 1 */ PRUint8 cipherArgLen; + /* 1 */ PRUint8 cipherType; + /* 1 */ PRUint8 masterKeyLen; + /* 1 */ PRUint8 keyBits; + /* 1 */ PRUint8 secretKeyBits; + /* 1 */ PRUint8 cipherArgLen; /*101 */} ssl2; - struct { -/* 2 */ ssl3CipherSuite cipherSuite; -/* 2 */ PRUint16 compression; /* SSLCompressionMethod */ +struct { + /* 2 */ ssl3CipherSuite cipherSuite; + /* 2 */ PRUint16 compression; /* SSLCompressionMethod */ -/* 54 */ ssl3SidKeys keys; /* keys, wrapped as needed. */ + /* 54 */ ssl3SidKeys keys; /* keys, wrapped as needed. */ -/* 4 */ PRUint32 masterWrapMech; -/* 4 */ SSL3KEAType exchKeyType; -/* 4 */ PRInt32 certIndex; -/* 4 */ PRInt32 srvNameIndex; -/* 32 */ PRUint8 srvNameHash[SHA256_LENGTH]; /* SHA256 name hash */ + /* 4 */ PRUint32 masterWrapMech; + /* 4 */ SSL3KEAType exchKeyType; + /* 4 */ PRInt32 certIndex; + /* 4 */ PRInt32 srvNameIndex; + /* 32 */ PRUint8 srvNameHash[SHA256_LENGTH]; /* SHA256 name hash */ /*108 */} ssl3; + /* force sizeof(sidCacheEntry) to be a multiple of cache line size */ - struct { -/*120 */ PRUint8 filler[120]; /* 72+120==192, a multiple of 16 */ - } forceSize; +struct { + /*120 */ PRUint8 filler[120]; /* 72+120==192, a multiple of 16 */ +} forceSize; } u; }; typedef struct sidCacheEntryStr sidCacheEntry; /* The length of this struct is supposed to be a power of 2, e.g. 4KB */ struct certCacheEntryStr { - PRUint16 certLength; /* 2 */ - PRUint16 sessionIDLength; /* 2 */ - PRUint8 sessionID[SSL3_SESSIONID_BYTES]; /* 32 */ - PRUint8 cert[SSL_MAX_CACHED_CERT_LEN]; /* 4060 */ -}; /* total 4096 */ + PRUint16 certLength; /* 2 */ + PRUint16 sessionIDLength; /* 2 */ + PRUint8 sessionID[SSL3_SESSIONID_BYTES]; /* 32 */ + PRUint8 cert[SSL_MAX_CACHED_CERT_LEN]; /* 4060 */ +}; /* total 4096 */ typedef struct certCacheEntryStr certCacheEntry; struct sidCacheLockStr { - PRUint32 timeStamp; - sslMutex mutex; - sslPID pid; + PRUint32 timeStamp; + sslMutex mutex; + sslPID pid; }; typedef struct sidCacheLockStr sidCacheLock; struct sidCacheSetStr { - PRIntn next; + PRIntn next; }; typedef struct sidCacheSetStr sidCacheSet; struct encKeyCacheEntryStr { - PRUint8 bytes[512]; - PRInt32 length; + PRUint8 bytes[512]; + PRInt32 length; }; typedef struct encKeyCacheEntryStr encKeyCacheEntry; -#define SSL_MAX_DNS_HOST_NAME 1024 +#define SSL_MAX_DNS_HOST_NAME 1024 struct srvNameCacheEntryStr { - PRUint16 type; /* 2 */ - PRUint16 nameLen; /* 2 */ - PRUint8 name[SSL_MAX_DNS_HOST_NAME + 12]; /* 1034 */ - PRUint8 nameHash[SHA256_LENGTH]; /* 32 */ - /* 1072 */ + PRUint16 type; /* 2 */ + PRUint16 nameLen; /* 2 */ + PRUint8 name[SSL_MAX_DNS_HOST_NAME + 12]; /* 1034 */ + PRUint8 nameHash[SHA256_LENGTH]; /* 32 */ + /* 1072 */ }; typedef struct srvNameCacheEntryStr srvNameCacheEntry; - struct cacheDescStr { - PRUint32 cacheMemSize; + PRUint32 cacheMemSize; - PRUint32 numSIDCacheLocks; - PRUint32 numSIDCacheSets; - PRUint32 numSIDCacheSetsPerLock; + PRUint32 numSIDCacheLocks; + PRUint32 numSIDCacheSets; + PRUint32 numSIDCacheSetsPerLock; - PRUint32 numSIDCacheEntries; - PRUint32 sidCacheSize; + PRUint32 numSIDCacheEntries; + PRUint32 sidCacheSize; - PRUint32 numCertCacheEntries; - PRUint32 certCacheSize; + PRUint32 numCertCacheEntries; + PRUint32 certCacheSize; - PRUint32 numKeyCacheEntries; - PRUint32 keyCacheSize; + PRUint32 numKeyCacheEntries; + PRUint32 keyCacheSize; - PRUint32 numSrvNameCacheEntries; - PRUint32 srvNameCacheSize; + PRUint32 numSrvNameCacheEntries; + PRUint32 srvNameCacheSize; - PRUint32 ssl2Timeout; - PRUint32 ssl3Timeout; + PRUint32 ssl2Timeout; + PRUint32 ssl3Timeout; - PRUint32 numSIDCacheLocksInitialized; + PRUint32 numSIDCacheLocksInitialized; /* These values are volatile, and are accessed through sharedCache-> */ - PRUint32 nextCertCacheEntry; /* certCacheLock protects */ - PRBool stopPolling; - PRBool everInherited; + PRUint32 nextCertCacheEntry; /* certCacheLock protects */ + PRBool stopPolling; + PRBool everInherited; /* The private copies of these values are pointers into shared mem */ /* The copies of these values in shared memory are merely offsets */ - sidCacheLock * sidCacheLocks; - sidCacheLock * keyCacheLock; - sidCacheLock * certCacheLock; - sidCacheLock * srvNameCacheLock; - sidCacheSet * sidCacheSets; - sidCacheEntry * sidCacheData; - certCacheEntry * certCacheData; - SSLWrappedSymWrappingKey * keyCacheData; - PRUint8 * ticketKeyNameSuffix; - encKeyCacheEntry * ticketEncKey; - encKeyCacheEntry * ticketMacKey; - PRUint32 * ticketKeysValid; - srvNameCacheEntry * srvNameCacheData; + sidCacheLock *sidCacheLocks; + sidCacheLock *keyCacheLock; + sidCacheLock *certCacheLock; + sidCacheLock *srvNameCacheLock; + sidCacheSet *sidCacheSets; + sidCacheEntry *sidCacheData; + certCacheEntry *certCacheData; + SSLWrappedSymWrappingKey *keyCacheData; + PRUint8 *ticketKeyNameSuffix; + encKeyCacheEntry *ticketEncKey; + encKeyCacheEntry *ticketMacKey; + PRUint32 *ticketKeysValid; + srvNameCacheEntry *srvNameCacheData; /* Only the private copies of these pointers are valid */ - char * cacheMem; - struct cacheDescStr * sharedCache; /* shared copy of this struct */ - PRFileMap * cacheMemMap; - PRThread * poller; - PRUint32 mutexTimeout; - PRBool shared; + char *cacheMem; + struct cacheDescStr *sharedCache; /* shared copy of this struct */ + PRFileMap *cacheMemMap; + PRThread *poller; + PRUint32 mutexTimeout; + PRBool shared; }; typedef struct cacheDescStr cacheDesc; @@ -235,48 +235,45 @@ static cacheDesc globalCache; static const char envVarName[] = { SSL_ENV_VAR_NAME }; -static PRBool isMultiProcess = PR_FALSE; +static PRBool isMultiProcess = PR_FALSE; - -#define DEF_SID_CACHE_ENTRIES 10000 +#define DEF_SID_CACHE_ENTRIES 10000 #define DEF_CERT_CACHE_ENTRIES 250 #define MIN_CERT_CACHE_ENTRIES 125 /* the effective size in old releases. */ -#define DEF_KEY_CACHE_ENTRIES 250 -#define DEF_NAME_CACHE_ENTRIES 1000 +#define DEF_KEY_CACHE_ENTRIES 250 +#define DEF_NAME_CACHE_ENTRIES 1000 -#define SID_CACHE_ENTRIES_PER_SET 128 -#define SID_ALIGNMENT 16 +#define SID_CACHE_ENTRIES_PER_SET 128 +#define SID_ALIGNMENT 16 -#define DEF_SSL2_TIMEOUT 100 /* seconds */ -#define MAX_SSL2_TIMEOUT 100 /* seconds */ -#define MIN_SSL2_TIMEOUT 5 /* seconds */ +#define DEF_SSL2_TIMEOUT 100 /* seconds */ +#define MAX_SSL2_TIMEOUT 100 /* seconds */ +#define MIN_SSL2_TIMEOUT 5 /* seconds */ -#define DEF_SSL3_TIMEOUT 86400L /* 24 hours */ -#define MAX_SSL3_TIMEOUT 86400L /* 24 hours */ -#define MIN_SSL3_TIMEOUT 5 /* seconds */ +#define DEF_SSL3_TIMEOUT 86400L /* 24 hours */ +#define MAX_SSL3_TIMEOUT 86400L /* 24 hours */ +#define MIN_SSL3_TIMEOUT 5 /* seconds */ #if defined(AIX) || defined(LINUX) || defined(NETBSD) || defined(OPENBSD) -#define MAX_SID_CACHE_LOCKS 8 /* two FDs per lock */ +#define MAX_SID_CACHE_LOCKS 8 /* two FDs per lock */ #elif defined(OSF1) -#define MAX_SID_CACHE_LOCKS 16 /* one FD per lock */ +#define MAX_SID_CACHE_LOCKS 16 /* one FD per lock */ #else #define MAX_SID_CACHE_LOCKS 256 #endif -#define SID_HOWMANY(val, size) (((val) + ((size) - 1)) / (size)) -#define SID_ROUNDUP(val, size) ((size) * SID_HOWMANY((val), (size))) - +#define SID_HOWMANY(val, size) (((val) + ((size)-1)) / (size)) +#define SID_ROUNDUP(val, size) ((size)*SID_HOWMANY((val), (size))) static sslPID myPid; -static PRUint32 ssl_max_sid_cache_locks = MAX_SID_CACHE_LOCKS; +static PRUint32 ssl_max_sid_cache_locks = MAX_SID_CACHE_LOCKS; /* forward static function declarations */ -static PRUint32 SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, +static PRUint32 SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl); static SECStatus LaunchLockPoller(cacheDesc *cache); static SECStatus StopLockPoller(cacheDesc *cache); - struct inheritanceStr { PRUint32 cacheMemSize; PRUint32 fmStrLen; @@ -296,29 +293,28 @@ typedef struct inheritanceStr inheritance; #endif /* XP_UNIX || XP_BEOS */ - /************************************************************************/ static PRUint32 LockSidCacheLock(sidCacheLock *lock, PRUint32 now) { - SECStatus rv = sslMutex_Lock(&lock->mutex); + SECStatus rv = sslMutex_Lock(&lock->mutex); if (rv != SECSuccess) - return 0; + return 0; if (!now) - now = ssl_Time(); + now = ssl_Time(); lock->timeStamp = now; - lock->pid = myPid; + lock->pid = myPid; return now; } static SECStatus UnlockSidCacheLock(sidCacheLock *lock) { - SECStatus rv; + SECStatus rv; lock->pid = 0; - rv = sslMutex_Unlock(&lock->mutex); + rv = sslMutex_Unlock(&lock->mutex); return rv; } @@ -326,8 +322,8 @@ UnlockSidCacheLock(sidCacheLock *lock) static PRUint32 LockSet(cacheDesc *cache, PRUint32 set, PRUint32 now) { - PRUint32 lockNum = set % cache->numSIDCacheLocks; - sidCacheLock * lock = cache->sidCacheLocks + lockNum; + PRUint32 lockNum = set % cache->numSIDCacheLocks; + sidCacheLock *lock = cache->sidCacheLocks + lockNum; return LockSidCacheLock(lock, now); } @@ -335,28 +331,27 @@ LockSet(cacheDesc *cache, PRUint32 set, PRUint32 now) static SECStatus UnlockSet(cacheDesc *cache, PRUint32 set) { - PRUint32 lockNum = set % cache->numSIDCacheLocks; - sidCacheLock * lock = cache->sidCacheLocks + lockNum; + PRUint32 lockNum = set % cache->numSIDCacheLocks; + sidCacheLock *lock = cache->sidCacheLocks + lockNum; return UnlockSidCacheLock(lock); } /************************************************************************/ - /* Put a certificate in the cache. Update the cert index in the sce. */ static PRUint32 -CacheCert(cacheDesc * cache, CERTCertificate *cert, sidCacheEntry *sce) +CacheCert(cacheDesc *cache, CERTCertificate *cert, sidCacheEntry *sce) { - PRUint32 now; - certCacheEntry cce; + PRUint32 now; + certCacheEntry cce; if ((cert->derCert.len > SSL_MAX_CACHED_CERT_LEN) || (cert->derCert.len <= 0) || - (cert->derCert.data == NULL)) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return 0; + (cert->derCert.data == NULL)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return 0; } cce.sessionIDLength = sce->sessionIDLength; @@ -369,24 +364,23 @@ CacheCert(cacheDesc * cache, CERTCertificate *cert, sidCacheEntry *sce) now = LockSidCacheLock(cache->certCacheLock, 0); if (now) { - /* Find where to place the next cert cache entry. */ - cacheDesc * sharedCache = cache->sharedCache; - PRUint32 ndx = sharedCache->nextCertCacheEntry; + /* Find where to place the next cert cache entry. */ + cacheDesc *sharedCache = cache->sharedCache; + PRUint32 ndx = sharedCache->nextCertCacheEntry; - /* write the entry */ - cache->certCacheData[ndx] = cce; + /* write the entry */ + cache->certCacheData[ndx] = cce; - /* remember where we put it. */ - sce->u.ssl3.certIndex = ndx; + /* remember where we put it. */ + sce->u.ssl3.certIndex = ndx; - /* update the "next" cache entry index */ - sharedCache->nextCertCacheEntry = - (ndx + 1) % cache->numCertCacheEntries; + /* update the "next" cache entry index */ + sharedCache->nextCertCacheEntry = + (ndx + 1) % cache->numCertCacheEntries; - UnlockSidCacheLock(cache->certCacheLock); + UnlockSidCacheLock(cache->certCacheLock); } return now; - } /* Server configuration hash tables need to account the SECITEM.type @@ -395,9 +389,9 @@ static PLHashNumber Get32BitNameHash(const SECItem *name) { PLHashNumber rv = SECITEM_Hash(name); - + PRUint8 *rvc = (PRUint8 *)&rv; - rvc[ name->len % sizeof(rv) ] ^= name->type; + rvc[name->len % sizeof(rv)] ^= name->type; return rv; } @@ -405,16 +399,16 @@ Get32BitNameHash(const SECItem *name) /* Put a name in the cache. Update the cert index in the sce. */ static PRUint32 -CacheSrvName(cacheDesc * cache, SECItem *name, sidCacheEntry *sce) +CacheSrvName(cacheDesc *cache, SECItem *name, sidCacheEntry *sce) { - PRUint32 now; - PRUint32 ndx; - srvNameCacheEntry snce; + PRUint32 now; + PRUint32 ndx; + srvNameCacheEntry snce; if (!name || name->len <= 0 || name->len > SSL_MAX_DNS_HOST_NAME) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return 0; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return 0; } snce.type = name->type; @@ -423,7 +417,7 @@ CacheSrvName(cacheDesc * cache, SECItem *name, sidCacheEntry *sce) #ifdef NO_PKCS11_BYPASS HASH_HashBuf(HASH_AlgSHA256, snce.nameHash, name->data, name->len); #else - SHA256_HashBuf(snce.nameHash, (unsigned char*)name->data, + SHA256_HashBuf(snce.nameHash, (unsigned char *)name->data, name->len); #endif /* get index of the next name */ @@ -441,7 +435,7 @@ CacheSrvName(cacheDesc * cache, SECItem *name, sidCacheEntry *sce) /* Copy hash into sid hash */ PORT_Memcpy(sce->u.ssl3.srvNameHash, snce.nameHash, SHA256_LENGTH); } - UnlockSidCacheLock(cache->srvNameCacheLock); + UnlockSidCacheLock(cache->srvNameCacheLock); } return now; } @@ -449,72 +443,74 @@ CacheSrvName(cacheDesc * cache, SECItem *name, sidCacheEntry *sce) /* ** Convert local SID to shared memory one */ -static void +static void ConvertFromSID(sidCacheEntry *to, sslSessionID *from) { - to->valid = 1; + to->valid = 1; to->version = from->version; - to->addr = from->addr; - to->creationTime = from->creationTime; - to->lastAccessTime = from->lastAccessTime; - to->expirationTime = from->expirationTime; - to->authAlgorithm = from->authAlgorithm; - to->authKeyBits = from->authKeyBits; - to->keaType = from->keaType; - to->keaKeyBits = from->keaKeyBits; + to->addr = from->addr; + to->creationTime = from->creationTime; + to->lastAccessTime = from->lastAccessTime; + to->expirationTime = from->expirationTime; + to->authAlgorithm = from->authAlgorithm; + to->authKeyBits = from->authKeyBits; + to->keaType = from->keaType; + to->keaKeyBits = from->keaKeyBits; if (from->version < SSL_LIBRARY_VERSION_3_0) { - if ((from->u.ssl2.masterKey.len > SSL_MAX_MASTER_KEY_BYTES) || - (from->u.ssl2.cipherArg.len > SSL_MAX_CYPHER_ARG_BYTES)) { - SSL_DBG(("%d: SSL: masterKeyLen=%d cipherArgLen=%d", - myPid, from->u.ssl2.masterKey.len, - from->u.ssl2.cipherArg.len)); - to->valid = 0; - return; - } + if ((from->u.ssl2.masterKey.len > SSL_MAX_MASTER_KEY_BYTES) || + (from->u.ssl2.cipherArg.len > SSL_MAX_CYPHER_ARG_BYTES)) { + SSL_DBG(("%d: SSL: masterKeyLen=%d cipherArgLen=%d", + myPid, from->u.ssl2.masterKey.len, + from->u.ssl2.cipherArg.len)); + to->valid = 0; + return; + } - to->u.ssl2.cipherType = from->u.ssl2.cipherType; - to->u.ssl2.masterKeyLen = from->u.ssl2.masterKey.len; - to->u.ssl2.cipherArgLen = from->u.ssl2.cipherArg.len; - to->u.ssl2.keyBits = from->u.ssl2.keyBits; - to->u.ssl2.secretKeyBits = from->u.ssl2.secretKeyBits; - to->sessionIDLength = SSL2_SESSIONID_BYTES; - PORT_Memcpy(to->sessionID, from->u.ssl2.sessionID, SSL2_SESSIONID_BYTES); - PORT_Memcpy(to->u.ssl2.masterKey, from->u.ssl2.masterKey.data, - from->u.ssl2.masterKey.len); - PORT_Memcpy(to->u.ssl2.cipherArg, from->u.ssl2.cipherArg.data, - from->u.ssl2.cipherArg.len); + to->u.ssl2.cipherType = from->u.ssl2.cipherType; + to->u.ssl2.masterKeyLen = from->u.ssl2.masterKey.len; + to->u.ssl2.cipherArgLen = from->u.ssl2.cipherArg.len; + to->u.ssl2.keyBits = from->u.ssl2.keyBits; + to->u.ssl2.secretKeyBits = from->u.ssl2.secretKeyBits; + to->sessionIDLength = SSL2_SESSIONID_BYTES; + PORT_Memcpy(to->sessionID, from->u.ssl2.sessionID, SSL2_SESSIONID_BYTES); + PORT_Memcpy(to->u.ssl2.masterKey, from->u.ssl2.masterKey.data, + from->u.ssl2.masterKey.len); + PORT_Memcpy(to->u.ssl2.cipherArg, from->u.ssl2.cipherArg.data, + from->u.ssl2.cipherArg.len); #ifdef DEBUG - PORT_Memset(to->u.ssl2.masterKey+from->u.ssl2.masterKey.len, 0, - sizeof(to->u.ssl2.masterKey) - from->u.ssl2.masterKey.len); - PORT_Memset(to->u.ssl2.cipherArg+from->u.ssl2.cipherArg.len, 0, - sizeof(to->u.ssl2.cipherArg) - from->u.ssl2.cipherArg.len); + PORT_Memset(to->u.ssl2.masterKey + from->u.ssl2.masterKey.len, 0, + sizeof(to->u.ssl2.masterKey) - from->u.ssl2.masterKey.len); + PORT_Memset(to->u.ssl2.cipherArg + from->u.ssl2.cipherArg.len, 0, + sizeof(to->u.ssl2.cipherArg) - from->u.ssl2.cipherArg.len); #endif - SSL_TRC(8, ("%d: SSL: ConvertSID: masterKeyLen=%d cipherArgLen=%d " - "time=%d addr=0x%08x%08x%08x%08x cipherType=%d", myPid, - to->u.ssl2.masterKeyLen, to->u.ssl2.cipherArgLen, - to->creationTime, to->addr.pr_s6_addr32[0], - to->addr.pr_s6_addr32[1], to->addr.pr_s6_addr32[2], - to->addr.pr_s6_addr32[3], to->u.ssl2.cipherType)); - } else { - /* This is an SSL v3 session */ + SSL_TRC(8, ("%d: SSL: ConvertSID: masterKeyLen=%d cipherArgLen=%d " + "time=%d addr=0x%08x%08x%08x%08x cipherType=%d", + myPid, + to->u.ssl2.masterKeyLen, to->u.ssl2.cipherArgLen, + to->creationTime, to->addr.pr_s6_addr32[0], + to->addr.pr_s6_addr32[1], to->addr.pr_s6_addr32[2], + to->addr.pr_s6_addr32[3], to->u.ssl2.cipherType)); + } + else { + /* This is an SSL v3 session */ - to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; - to->u.ssl3.compression = (PRUint16)from->u.ssl3.compression; - to->u.ssl3.keys = from->u.ssl3.keys; - to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech; - to->u.ssl3.exchKeyType = from->u.ssl3.exchKeyType; - to->sessionIDLength = from->u.ssl3.sessionIDLength; - to->u.ssl3.certIndex = -1; - to->u.ssl3.srvNameIndex = -1; - PORT_Memcpy(to->sessionID, from->u.ssl3.sessionID, - to->sessionIDLength); + to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; + to->u.ssl3.compression = (PRUint16)from->u.ssl3.compression; + to->u.ssl3.keys = from->u.ssl3.keys; + to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech; + to->u.ssl3.exchKeyType = from->u.ssl3.exchKeyType; + to->sessionIDLength = from->u.ssl3.sessionIDLength; + to->u.ssl3.certIndex = -1; + to->u.ssl3.srvNameIndex = -1; + PORT_Memcpy(to->sessionID, from->u.ssl3.sessionID, + to->sessionIDLength); - SSL_TRC(8, ("%d: SSL3: ConvertSID: time=%d addr=0x%08x%08x%08x%08x " - "cipherSuite=%d", - myPid, to->creationTime, to->addr.pr_s6_addr32[0], - to->addr.pr_s6_addr32[1], to->addr.pr_s6_addr32[2], - to->addr.pr_s6_addr32[3], to->u.ssl3.cipherSuite)); + SSL_TRC(8, ("%d: SSL3: ConvertSID: time=%d addr=0x%08x%08x%08x%08x " + "cipherSuite=%d", + myPid, to->creationTime, to->addr.pr_s6_addr32[0], + to->addr.pr_s6_addr32[1], to->addr.pr_s6_addr32[2], + to->addr.pr_s6_addr32[3], to->u.ssl3.cipherSuite)); } } @@ -523,144 +519,144 @@ ConvertFromSID(sidCacheEntry *to, sslSessionID *from) ** This is only called from ServerSessionIDLookup(). */ static sslSessionID * -ConvertToSID(sidCacheEntry * from, - certCacheEntry * pcce, +ConvertToSID(sidCacheEntry *from, + certCacheEntry *pcce, srvNameCacheEntry *psnce, - CERTCertDBHandle * dbHandle) + CERTCertDBHandle *dbHandle) { sslSessionID *to; PRUint16 version = from->version; to = PORT_ZNew(sslSessionID); if (!to) { - return 0; + return 0; } if (version < SSL_LIBRARY_VERSION_3_0) { - /* This is an SSL v2 session */ - to->u.ssl2.masterKey.data = - (unsigned char*) PORT_Alloc(from->u.ssl2.masterKeyLen); - if (!to->u.ssl2.masterKey.data) { - goto loser; - } - if (from->u.ssl2.cipherArgLen) { - to->u.ssl2.cipherArg.data = - (unsigned char*)PORT_Alloc(from->u.ssl2.cipherArgLen); - if (!to->u.ssl2.cipherArg.data) { - goto loser; - } - PORT_Memcpy(to->u.ssl2.cipherArg.data, from->u.ssl2.cipherArg, - from->u.ssl2.cipherArgLen); - } + /* This is an SSL v2 session */ + to->u.ssl2.masterKey.data = + (unsigned char *)PORT_Alloc(from->u.ssl2.masterKeyLen); + if (!to->u.ssl2.masterKey.data) { + goto loser; + } + if (from->u.ssl2.cipherArgLen) { + to->u.ssl2.cipherArg.data = + (unsigned char *)PORT_Alloc(from->u.ssl2.cipherArgLen); + if (!to->u.ssl2.cipherArg.data) { + goto loser; + } + PORT_Memcpy(to->u.ssl2.cipherArg.data, from->u.ssl2.cipherArg, + from->u.ssl2.cipherArgLen); + } - to->u.ssl2.cipherType = from->u.ssl2.cipherType; - to->u.ssl2.masterKey.len = from->u.ssl2.masterKeyLen; - to->u.ssl2.cipherArg.len = from->u.ssl2.cipherArgLen; - to->u.ssl2.keyBits = from->u.ssl2.keyBits; - to->u.ssl2.secretKeyBits = from->u.ssl2.secretKeyBits; -/* to->sessionIDLength = SSL2_SESSIONID_BYTES; */ - PORT_Memcpy(to->u.ssl2.sessionID, from->sessionID, SSL2_SESSIONID_BYTES); - PORT_Memcpy(to->u.ssl2.masterKey.data, from->u.ssl2.masterKey, - from->u.ssl2.masterKeyLen); + to->u.ssl2.cipherType = from->u.ssl2.cipherType; + to->u.ssl2.masterKey.len = from->u.ssl2.masterKeyLen; + to->u.ssl2.cipherArg.len = from->u.ssl2.cipherArgLen; + to->u.ssl2.keyBits = from->u.ssl2.keyBits; + to->u.ssl2.secretKeyBits = from->u.ssl2.secretKeyBits; + /* to->sessionIDLength = SSL2_SESSIONID_BYTES; */ + PORT_Memcpy(to->u.ssl2.sessionID, from->sessionID, SSL2_SESSIONID_BYTES); + PORT_Memcpy(to->u.ssl2.masterKey.data, from->u.ssl2.masterKey, + from->u.ssl2.masterKeyLen); - SSL_TRC(8, ("%d: SSL: ConvertToSID: masterKeyLen=%d cipherArgLen=%d " - "time=%d addr=0x%08x%08x%08x%08x cipherType=%d", - myPid, to->u.ssl2.masterKey.len, - to->u.ssl2.cipherArg.len, to->creationTime, - to->addr.pr_s6_addr32[0], to->addr.pr_s6_addr32[1], - to->addr.pr_s6_addr32[2], to->addr.pr_s6_addr32[3], - to->u.ssl2.cipherType)); - } else { - /* This is an SSL v3 session */ + SSL_TRC(8, ("%d: SSL: ConvertToSID: masterKeyLen=%d cipherArgLen=%d " + "time=%d addr=0x%08x%08x%08x%08x cipherType=%d", + myPid, to->u.ssl2.masterKey.len, + to->u.ssl2.cipherArg.len, to->creationTime, + to->addr.pr_s6_addr32[0], to->addr.pr_s6_addr32[1], + to->addr.pr_s6_addr32[2], to->addr.pr_s6_addr32[3], + to->u.ssl2.cipherType)); + } + else { + /* This is an SSL v3 session */ - to->u.ssl3.sessionIDLength = from->sessionIDLength; - to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; - to->u.ssl3.compression = (SSLCompressionMethod)from->u.ssl3.compression; - to->u.ssl3.keys = from->u.ssl3.keys; - to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech; - to->u.ssl3.exchKeyType = from->u.ssl3.exchKeyType; - if (from->u.ssl3.srvNameIndex != -1 && psnce) { + to->u.ssl3.sessionIDLength = from->sessionIDLength; + to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; + to->u.ssl3.compression = (SSLCompressionMethod)from->u.ssl3.compression; + to->u.ssl3.keys = from->u.ssl3.keys; + to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech; + to->u.ssl3.exchKeyType = from->u.ssl3.exchKeyType; + if (from->u.ssl3.srvNameIndex != -1 && psnce) { SECItem name; SECStatus rv; - name.type = psnce->type; - name.len = psnce->nameLen; - name.data = psnce->name; + name.type = psnce->type; + name.len = psnce->nameLen; + name.data = psnce->name; rv = SECITEM_CopyItem(NULL, &to->u.ssl3.srvName, &name); if (rv != SECSuccess) { goto loser; } } - PORT_Memcpy(to->u.ssl3.sessionID, from->sessionID, from->sessionIDLength); + PORT_Memcpy(to->u.ssl3.sessionID, from->sessionID, from->sessionIDLength); - /* the portions of the SID that are only restored on the client - * are set to invalid values on the server. - */ - to->u.ssl3.clientWriteKey = NULL; - to->u.ssl3.serverWriteKey = NULL; + /* the portions of the SID that are only restored on the client + * are set to invalid values on the server. + */ + to->u.ssl3.clientWriteKey = NULL; + to->u.ssl3.serverWriteKey = NULL; - to->urlSvrName = NULL; + to->urlSvrName = NULL; - to->u.ssl3.masterModuleID = (SECMODModuleID)-1; /* invalid value */ - to->u.ssl3.masterSlotID = (CK_SLOT_ID)-1; /* invalid value */ - to->u.ssl3.masterWrapIndex = 0; - to->u.ssl3.masterWrapSeries = 0; - to->u.ssl3.masterValid = PR_FALSE; + to->u.ssl3.masterModuleID = (SECMODModuleID)-1; /* invalid value */ + to->u.ssl3.masterSlotID = (CK_SLOT_ID)-1; /* invalid value */ + to->u.ssl3.masterWrapIndex = 0; + to->u.ssl3.masterWrapSeries = 0; + to->u.ssl3.masterValid = PR_FALSE; - to->u.ssl3.clAuthModuleID = (SECMODModuleID)-1; /* invalid value */ - to->u.ssl3.clAuthSlotID = (CK_SLOT_ID)-1; /* invalid value */ - to->u.ssl3.clAuthSeries = 0; - to->u.ssl3.clAuthValid = PR_FALSE; + to->u.ssl3.clAuthModuleID = (SECMODModuleID)-1; /* invalid value */ + to->u.ssl3.clAuthSlotID = (CK_SLOT_ID)-1; /* invalid value */ + to->u.ssl3.clAuthSeries = 0; + to->u.ssl3.clAuthValid = PR_FALSE; - if (from->u.ssl3.certIndex != -1 && pcce) { - SECItem derCert; + if (from->u.ssl3.certIndex != -1 && pcce) { + SECItem derCert; - derCert.len = pcce->certLength; - derCert.data = pcce->cert; + derCert.len = pcce->certLength; + derCert.data = pcce->cert; - to->peerCert = CERT_NewTempCertificate(dbHandle, &derCert, NULL, - PR_FALSE, PR_TRUE); - if (to->peerCert == NULL) - goto loser; - } + to->peerCert = CERT_NewTempCertificate(dbHandle, &derCert, NULL, + PR_FALSE, PR_TRUE); + if (to->peerCert == NULL) + goto loser; + } } - to->version = from->version; - to->creationTime = from->creationTime; - to->lastAccessTime = from->lastAccessTime; - to->expirationTime = from->expirationTime; - to->cached = in_server_cache; - to->addr = from->addr; - to->references = 1; - to->authAlgorithm = from->authAlgorithm; - to->authKeyBits = from->authKeyBits; - to->keaType = from->keaType; - to->keaKeyBits = from->keaKeyBits; + to->version = from->version; + to->creationTime = from->creationTime; + to->lastAccessTime = from->lastAccessTime; + to->expirationTime = from->expirationTime; + to->cached = in_server_cache; + to->addr = from->addr; + to->references = 1; + to->authAlgorithm = from->authAlgorithm; + to->authKeyBits = from->authKeyBits; + to->keaType = from->keaType; + to->keaKeyBits = from->keaKeyBits; return to; - loser: +loser: if (to) { - if (version < SSL_LIBRARY_VERSION_3_0) { - if (to->u.ssl2.masterKey.data) - PORT_Free(to->u.ssl2.masterKey.data); - if (to->u.ssl2.cipherArg.data) - PORT_Free(to->u.ssl2.cipherArg.data); - } else { + if (version < SSL_LIBRARY_VERSION_3_0) { + if (to->u.ssl2.masterKey.data) + PORT_Free(to->u.ssl2.masterKey.data); + if (to->u.ssl2.cipherArg.data) + PORT_Free(to->u.ssl2.cipherArg.data); + } + else { SECITEM_FreeItem(&to->u.ssl3.srvName, PR_FALSE); } - PORT_Free(to); + PORT_Free(to); } return NULL; } - - /* ** Perform some mumbo jumbo on the ip-address and the session-id value to ** compute a hash value. */ -static PRUint32 +static PRUint32 SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl) { PRUint32 rv; @@ -668,18 +664,16 @@ SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl) memset(x, 0, sizeof x); if (nl > sizeof x) - nl = sizeof x; + nl = sizeof x; memcpy(x, s, nl); rv = (addr->pr_s6_addr32[0] ^ addr->pr_s6_addr32[1] ^ - addr->pr_s6_addr32[2] ^ addr->pr_s6_addr32[3] ^ - x[0] ^ x[1] ^ x[2] ^ x[3] ^ x[4] ^ x[5] ^ x[6] ^ x[7]) - % cache->numSIDCacheSets; + addr->pr_s6_addr32[2] ^ addr->pr_s6_addr32[3] ^ + x[0] ^ x[1] ^ x[2] ^ x[3] ^ x[4] ^ x[5] ^ x[6] ^ x[7]) % + cache->numSIDCacheSets; return rv; } - - /* ** Look something up in the cache. This will invalidate old entries ** in the process. Caller has locked the cache set! @@ -688,45 +682,45 @@ SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl) static sidCacheEntry * FindSID(cacheDesc *cache, PRUint32 setNum, PRUint32 now, const PRIPv6Addr *addr, unsigned char *sessionID, - unsigned sessionIDLength) + unsigned sessionIDLength) { - PRUint32 ndx = cache->sidCacheSets[setNum].next; - int i; + PRUint32 ndx = cache->sidCacheSets[setNum].next; + int i; - sidCacheEntry * set = cache->sidCacheData + - (setNum * SID_CACHE_ENTRIES_PER_SET); + sidCacheEntry *set = cache->sidCacheData + + (setNum * SID_CACHE_ENTRIES_PER_SET); for (i = SID_CACHE_ENTRIES_PER_SET; i > 0; --i) { - sidCacheEntry * sce; + sidCacheEntry *sce; - ndx = (ndx - 1) % SID_CACHE_ENTRIES_PER_SET; - sce = set + ndx; + ndx = (ndx - 1) % SID_CACHE_ENTRIES_PER_SET; + sce = set + ndx; - if (!sce->valid) - continue; + if (!sce->valid) + continue; - if (now > sce->expirationTime) { - /* SessionID has timed out. Invalidate the entry. */ - SSL_TRC(7, ("%d: timed out sid entry addr=%08x%08x%08x%08x now=%x " - "time+=%x", - myPid, sce->addr.pr_s6_addr32[0], - sce->addr.pr_s6_addr32[1], sce->addr.pr_s6_addr32[2], - sce->addr.pr_s6_addr32[3], now, - sce->expirationTime )); - sce->valid = 0; - continue; - } + if (now > sce->expirationTime) { + /* SessionID has timed out. Invalidate the entry. */ + SSL_TRC(7, ("%d: timed out sid entry addr=%08x%08x%08x%08x now=%x " + "time+=%x", + myPid, sce->addr.pr_s6_addr32[0], + sce->addr.pr_s6_addr32[1], sce->addr.pr_s6_addr32[2], + sce->addr.pr_s6_addr32[3], now, + sce->expirationTime)); + sce->valid = 0; + continue; + } - /* - ** Next, examine specific session-id/addr data to see if the cache - ** entry matches our addr+session-id value - */ - if (sessionIDLength == sce->sessionIDLength && - !memcmp(&sce->addr, addr, sizeof(PRIPv6Addr)) && - !memcmp(sce->sessionID, sessionID, sessionIDLength)) { - /* Found it */ - return sce; - } + /* + ** Next, examine specific session-id/addr data to see if the cache + ** entry matches our addr+session-id value + */ + if (sessionIDLength == sce->sessionIDLength && + !memcmp(&sce->addr, addr, sizeof(PRIPv6Addr)) && + !memcmp(sce->sessionID, sessionID, sessionIDLength)) { + /* Found it */ + return sce; + } } PORT_SetError(SSL_ERROR_SESSION_NOT_FOUND); @@ -736,56 +730,58 @@ FindSID(cacheDesc *cache, PRUint32 setNum, PRUint32 now, /************************************************************************/ /* This is the primary function for finding entries in the server's sid cache. - * Although it is static, this function is called via the global function + * Although it is static, this function is called via the global function * pointer ssl_sid_lookup. */ static sslSessionID * ServerSessionIDLookup(const PRIPv6Addr *addr, - unsigned char *sessionID, - unsigned int sessionIDLength, - CERTCertDBHandle * dbHandle) + unsigned char *sessionID, + unsigned int sessionIDLength, + CERTCertDBHandle *dbHandle) { - sslSessionID * sid = 0; - sidCacheEntry * psce; - certCacheEntry *pcce = 0; + sslSessionID *sid = 0; + sidCacheEntry *psce; + certCacheEntry *pcce = 0; srvNameCacheEntry *psnce = 0; - cacheDesc * cache = &globalCache; - PRUint32 now; - PRUint32 set; - PRInt32 cndx; - sidCacheEntry sce; - certCacheEntry cce; + cacheDesc *cache = &globalCache; + PRUint32 now; + PRUint32 set; + PRInt32 cndx; + sidCacheEntry sce; + certCacheEntry cce; srvNameCacheEntry snce; set = SIDindex(cache, addr, sessionID, sessionIDLength); now = LockSet(cache, set, 0); if (!now) - return NULL; + return NULL; psce = FindSID(cache, set, now, addr, sessionID, sessionIDLength); if (psce) { - if (psce->version >= SSL_LIBRARY_VERSION_3_0) { - if ((cndx = psce->u.ssl3.certIndex) != -1) { - + if (psce->version >= SSL_LIBRARY_VERSION_3_0) { + if ((cndx = psce->u.ssl3.certIndex) != -1) { + PRUint32 gotLock = LockSidCacheLock(cache->certCacheLock, now); if (gotLock) { pcce = &cache->certCacheData[cndx]; - + /* See if the cert's session ID matches the sce cache. */ if ((pcce->sessionIDLength == psce->sessionIDLength) && - !PORT_Memcmp(pcce->sessionID, psce->sessionID, + !PORT_Memcmp(pcce->sessionID, psce->sessionID, pcce->sessionIDLength)) { cce = *pcce; - } else { - /* The cert doesen't match the SID cache entry, - ** so invalidate the SID cache entry. + } + else { + /* The cert doesen't match the SID cache entry, + ** so invalidate the SID cache entry. */ psce->valid = 0; psce = 0; pcce = 0; } UnlockSidCacheLock(cache->certCacheLock); - } else { + } + else { /* what the ??. Didn't get the cert cache lock. ** Don't invalidate the SID cache entry, but don't find it. */ @@ -799,20 +795,22 @@ ServerSessionIDLookup(const PRIPv6Addr *addr, now); if (gotLock) { psnce = &cache->srvNameCacheData[cndx]; - - if (!PORT_Memcmp(psnce->nameHash, psce->u.ssl3.srvNameHash, + + if (!PORT_Memcmp(psnce->nameHash, psce->u.ssl3.srvNameHash, SHA256_LENGTH)) { snce = *psnce; - } else { - /* The name doesen't match the SID cache entry, - ** so invalidate the SID cache entry. + } + else { + /* The name doesen't match the SID cache entry, + ** so invalidate the SID cache entry. */ psce->valid = 0; psce = 0; psnce = 0; } UnlockSidCacheLock(cache->srvNameCacheLock); - } else { + } + else { /* what the ??. Didn't get the cert cache lock. ** Don't invalidate the SID cache entry, but don't find it. */ @@ -820,80 +818,81 @@ ServerSessionIDLookup(const PRIPv6Addr *addr, psce = 0; psnce = 0; } - } } - if (psce) { - psce->lastAccessTime = now; - sce = *psce; /* grab a copy while holding the lock */ - } + if (psce) { + psce->lastAccessTime = now; + sce = *psce; /* grab a copy while holding the lock */ + } } UnlockSet(cache, set); if (psce) { - /* sce conains a copy of the cache entry. - ** Convert shared memory format to local format - */ - sid = ConvertToSID(&sce, pcce ? &cce : 0, psnce ? &snce : 0, dbHandle); + /* sce conains a copy of the cache entry. + ** Convert shared memory format to local format + */ + sid = ConvertToSID(&sce, pcce ? &cce : 0, psnce ? &snce : 0, dbHandle); } return sid; } /* -** Place a sid into the cache, if it isn't already there. +** Place a sid into the cache, if it isn't already there. */ -static void +static void ServerSessionIDCache(sslSessionID *sid) { sidCacheEntry sce; - PRUint32 now = 0; - PRUint16 version = sid->version; - cacheDesc * cache = &globalCache; + PRUint32 now = 0; + PRUint16 version = sid->version; + cacheDesc *cache = &globalCache; if ((version >= SSL_LIBRARY_VERSION_3_0) && - (sid->u.ssl3.sessionIDLength == 0)) { - return; + (sid->u.ssl3.sessionIDLength == 0)) { + return; } if (sid->cached == never_cached || sid->cached == invalid_cache) { - PRUint32 set; + PRUint32 set; - PORT_Assert(sid->creationTime != 0); - if (!sid->creationTime) - sid->lastAccessTime = sid->creationTime = ssl_Time(); - if (version < SSL_LIBRARY_VERSION_3_0) { - /* override caller's expiration time, which uses client timeout - * duration, not server timeout duration. - */ - sid->expirationTime = sid->creationTime + cache->ssl2Timeout; - SSL_TRC(8, ("%d: SSL: CacheMT: cached=%d addr=0x%08x%08x%08x%08x time=%x " - "cipher=%d", myPid, sid->cached, - sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], - sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], - sid->creationTime, sid->u.ssl2.cipherType)); - PRINT_BUF(8, (0, "sessionID:", sid->u.ssl2.sessionID, - SSL2_SESSIONID_BYTES)); - PRINT_BUF(8, (0, "masterKey:", sid->u.ssl2.masterKey.data, - sid->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", sid->u.ssl2.cipherArg.data, - sid->u.ssl2.cipherArg.len)); + PORT_Assert(sid->creationTime != 0); + if (!sid->creationTime) + sid->lastAccessTime = sid->creationTime = ssl_Time(); + if (version < SSL_LIBRARY_VERSION_3_0) { + /* override caller's expiration time, which uses client timeout + * duration, not server timeout duration. + */ + sid->expirationTime = sid->creationTime + cache->ssl2Timeout; + SSL_TRC(8, ("%d: SSL: CacheMT: cached=%d addr=0x%08x%08x%08x%08x time=%x " + "cipher=%d", + myPid, sid->cached, + sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], + sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], + sid->creationTime, sid->u.ssl2.cipherType)); + PRINT_BUF(8, (0, "sessionID:", sid->u.ssl2.sessionID, + SSL2_SESSIONID_BYTES)); + PRINT_BUF(8, (0, "masterKey:", sid->u.ssl2.masterKey.data, + sid->u.ssl2.masterKey.len)); + PRINT_BUF(8, (0, "cipherArg:", sid->u.ssl2.cipherArg.data, + sid->u.ssl2.cipherArg.len)); + } + else { + /* override caller's expiration time, which uses client timeout + * duration, not server timeout duration. + */ + sid->expirationTime = sid->creationTime + cache->ssl3Timeout; + SSL_TRC(8, ("%d: SSL: CacheMT: cached=%d addr=0x%08x%08x%08x%08x time=%x " + "cipherSuite=%d", + myPid, sid->cached, + sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], + sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], + sid->creationTime, sid->u.ssl3.cipherSuite)); + PRINT_BUF(8, (0, "sessionID:", sid->u.ssl3.sessionID, + sid->u.ssl3.sessionIDLength)); + } - } else { - /* override caller's expiration time, which uses client timeout - * duration, not server timeout duration. - */ - sid->expirationTime = sid->creationTime + cache->ssl3Timeout; - SSL_TRC(8, ("%d: SSL: CacheMT: cached=%d addr=0x%08x%08x%08x%08x time=%x " - "cipherSuite=%d", myPid, sid->cached, - sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], - sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], - sid->creationTime, sid->u.ssl3.cipherSuite)); - PRINT_BUF(8, (0, "sessionID:", sid->u.ssl3.sessionID, - sid->u.ssl3.sessionIDLength)); - } + ConvertFromSID(&sce, sid); - ConvertFromSID(&sce, sid); - - if (version >= SSL_LIBRARY_VERSION_3_0) { + if (version >= SSL_LIBRARY_VERSION_3_0) { SECItem *name = &sid->u.ssl3.srvName; if (name->len && name->data) { now = CacheSrvName(cache, name, &sce); @@ -901,80 +900,83 @@ ServerSessionIDCache(sslSessionID *sid) if (sid->peerCert != NULL) { now = CacheCert(cache, sid->peerCert, &sce); } - } + } - set = SIDindex(cache, &sce.addr, sce.sessionID, sce.sessionIDLength); - now = LockSet(cache, set, now); - if (now) { - PRUint32 next = cache->sidCacheSets[set].next; - PRUint32 ndx = set * SID_CACHE_ENTRIES_PER_SET + next; + set = SIDindex(cache, &sce.addr, sce.sessionID, sce.sessionIDLength); + now = LockSet(cache, set, now); + if (now) { + PRUint32 next = cache->sidCacheSets[set].next; + PRUint32 ndx = set * SID_CACHE_ENTRIES_PER_SET + next; - /* Write out new cache entry */ - cache->sidCacheData[ndx] = sce; + /* Write out new cache entry */ + cache->sidCacheData[ndx] = sce; - cache->sidCacheSets[set].next = - (next + 1) % SID_CACHE_ENTRIES_PER_SET; + cache->sidCacheSets[set].next = + (next + 1) % SID_CACHE_ENTRIES_PER_SET; - UnlockSet(cache, set); - sid->cached = in_server_cache; - } + UnlockSet(cache, set); + sid->cached = in_server_cache; + } } } /* ** Although this is static, it is called from ssl via global function pointer -** ssl_sid_uncache. This invalidates the referenced cache entry. +** ssl_sid_uncache. This invalidates the referenced cache entry. */ -static void +static void ServerSessionIDUncache(sslSessionID *sid) { - cacheDesc * cache = &globalCache; - PRUint8 * sessionID; - unsigned int sessionIDLength; - PRErrorCode err; - PRUint32 set; - PRUint32 now; + cacheDesc *cache = &globalCache; + PRUint8 *sessionID; + unsigned int sessionIDLength; + PRErrorCode err; + PRUint32 set; + PRUint32 now; sidCacheEntry *psce; - if (sid == NULL) - return; - - /* Uncaching a SID should never change the error code. + if (sid == NULL) + return; + + /* Uncaching a SID should never change the error code. ** So save it here and restore it before exiting. */ err = PR_GetError(); if (sid->version < SSL_LIBRARY_VERSION_3_0) { - sessionID = sid->u.ssl2.sessionID; - sessionIDLength = SSL2_SESSIONID_BYTES; - SSL_TRC(8, ("%d: SSL: UncacheMT: valid=%d addr=0x%08x%08x%08x%08x time=%x " - "cipher=%d", myPid, sid->cached, - sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], - sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], - sid->creationTime, sid->u.ssl2.cipherType)); - PRINT_BUF(8, (0, "sessionID:", sessionID, sessionIDLength)); - PRINT_BUF(8, (0, "masterKey:", sid->u.ssl2.masterKey.data, - sid->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", sid->u.ssl2.cipherArg.data, - sid->u.ssl2.cipherArg.len)); - } else { - sessionID = sid->u.ssl3.sessionID; - sessionIDLength = sid->u.ssl3.sessionIDLength; - SSL_TRC(8, ("%d: SSL3: UncacheMT: valid=%d addr=0x%08x%08x%08x%08x time=%x " - "cipherSuite=%d", myPid, sid->cached, - sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], - sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], - sid->creationTime, sid->u.ssl3.cipherSuite)); - PRINT_BUF(8, (0, "sessionID:", sessionID, sessionIDLength)); + sessionID = sid->u.ssl2.sessionID; + sessionIDLength = SSL2_SESSIONID_BYTES; + SSL_TRC(8, ("%d: SSL: UncacheMT: valid=%d addr=0x%08x%08x%08x%08x time=%x " + "cipher=%d", + myPid, sid->cached, + sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], + sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], + sid->creationTime, sid->u.ssl2.cipherType)); + PRINT_BUF(8, (0, "sessionID:", sessionID, sessionIDLength)); + PRINT_BUF(8, (0, "masterKey:", sid->u.ssl2.masterKey.data, + sid->u.ssl2.masterKey.len)); + PRINT_BUF(8, (0, "cipherArg:", sid->u.ssl2.cipherArg.data, + sid->u.ssl2.cipherArg.len)); + } + else { + sessionID = sid->u.ssl3.sessionID; + sessionIDLength = sid->u.ssl3.sessionIDLength; + SSL_TRC(8, ("%d: SSL3: UncacheMT: valid=%d addr=0x%08x%08x%08x%08x time=%x " + "cipherSuite=%d", + myPid, sid->cached, + sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1], + sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3], + sid->creationTime, sid->u.ssl3.cipherSuite)); + PRINT_BUF(8, (0, "sessionID:", sessionID, sessionIDLength)); } set = SIDindex(cache, &sid->addr, sessionID, sessionIDLength); now = LockSet(cache, set, 0); if (now) { - psce = FindSID(cache, set, now, &sid->addr, sessionID, sessionIDLength); - if (psce) { - psce->valid = 0; - } - UnlockSet(cache, set); + psce = FindSID(cache, set, now, &sid->addr, sessionID, sessionIDLength); + if (psce) { + psce->valid = 0; + } + UnlockSet(cache, set); } sid->cached = invalid_cache; PORT_SetError(err); @@ -985,7 +987,8 @@ ServerSessionIDUncache(sslSessionID *sid) #define INCL_DOSPROCESS #include -long gettid(void) +long +gettid(void) { PTIB ptib; PPIB ppib; @@ -1000,59 +1003,60 @@ CloseCache(cacheDesc *cache) int locks_initialized = cache->numSIDCacheLocksInitialized; if (cache->cacheMem) { - if (cache->sharedCache) { - sidCacheLock *pLock = cache->sidCacheLocks; - for (; locks_initialized > 0; --locks_initialized, ++pLock ) { - /* If everInherited is true, this shared cache was (and may - ** still be) in use by multiple processes. We do not wish to - ** destroy the mutexes while they are still in use, but we do - ** want to free mutex resources associated with this process. - */ - sslMutex_Destroy(&pLock->mutex, - cache->sharedCache->everInherited); - } - } - if (cache->shared) { - PR_MemUnmap(cache->cacheMem, cache->cacheMemSize); - } else { - PORT_Free(cache->cacheMem); - } - cache->cacheMem = NULL; + if (cache->sharedCache) { + sidCacheLock *pLock = cache->sidCacheLocks; + for (; locks_initialized > 0; --locks_initialized, ++pLock) { + /* If everInherited is true, this shared cache was (and may + ** still be) in use by multiple processes. We do not wish to + ** destroy the mutexes while they are still in use, but we do + ** want to free mutex resources associated with this process. + */ + sslMutex_Destroy(&pLock->mutex, + cache->sharedCache->everInherited); + } + } + if (cache->shared) { + PR_MemUnmap(cache->cacheMem, cache->cacheMemSize); + } + else { + PORT_Free(cache->cacheMem); + } + cache->cacheMem = NULL; } if (cache->cacheMemMap) { - PR_CloseFileMap(cache->cacheMemMap); - cache->cacheMemMap = NULL; + PR_CloseFileMap(cache->cacheMemMap); + cache->cacheMemMap = NULL; } memset(cache, 0, sizeof *cache); } static SECStatus InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, - int maxSrvNameCacheEntries, PRUint32 ssl2_timeout, + int maxSrvNameCacheEntries, PRUint32 ssl2_timeout, PRUint32 ssl3_timeout, const char *directory, PRBool shared) { - ptrdiff_t ptr; + ptrdiff_t ptr; sidCacheLock *pLock; - char * cacheMem; - PRFileMap * cacheMemMap; - char * cfn = NULL; /* cache file name */ - int locks_initialized = 0; - int locks_to_initialize = 0; - PRUint32 init_time; + char *cacheMem; + PRFileMap *cacheMemMap; + char *cfn = NULL; /* cache file name */ + int locks_initialized = 0; + int locks_to_initialize = 0; + PRUint32 init_time; - if ( (!cache) || (maxCacheEntries < 0) || (!directory) ) { + if ((!cache) || (maxCacheEntries < 0) || (!directory)) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } if (cache->cacheMem) { - /* Already done */ - return SECSuccess; + /* Already done */ + return SECSuccess; } /* make sure loser can clean up properly */ cache->shared = shared; - cache->cacheMem = cacheMem = NULL; + cache->cacheMem = cacheMem = NULL; cache->cacheMemMap = cacheMemMap = NULL; cache->sharedCache = (cacheDesc *)0; @@ -1063,71 +1067,71 @@ InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, cache->poller = NULL; cache->mutexTimeout = 0; - cache->numSIDCacheEntries = maxCacheEntries ? maxCacheEntries + cache->numSIDCacheEntries = maxCacheEntries ? maxCacheEntries : DEF_SID_CACHE_ENTRIES; - cache->numSIDCacheSets = - SID_HOWMANY(cache->numSIDCacheEntries, SID_CACHE_ENTRIES_PER_SET); + cache->numSIDCacheSets = + SID_HOWMANY(cache->numSIDCacheEntries, SID_CACHE_ENTRIES_PER_SET); - cache->numSIDCacheEntries = - cache->numSIDCacheSets * SID_CACHE_ENTRIES_PER_SET; + cache->numSIDCacheEntries = + cache->numSIDCacheSets * SID_CACHE_ENTRIES_PER_SET; - cache->numSIDCacheLocks = - PR_MIN(cache->numSIDCacheSets, ssl_max_sid_cache_locks); + cache->numSIDCacheLocks = + PR_MIN(cache->numSIDCacheSets, ssl_max_sid_cache_locks); - cache->numSIDCacheSetsPerLock = - SID_HOWMANY(cache->numSIDCacheSets, cache->numSIDCacheLocks); + cache->numSIDCacheSetsPerLock = + SID_HOWMANY(cache->numSIDCacheSets, cache->numSIDCacheLocks); - cache->numCertCacheEntries = (maxCertCacheEntries > 0) ? - maxCertCacheEntries : 0; - cache->numSrvNameCacheEntries = (maxSrvNameCacheEntries >= 0) ? - maxSrvNameCacheEntries : DEF_NAME_CACHE_ENTRIES; + cache->numCertCacheEntries = (maxCertCacheEntries > 0) ? maxCertCacheEntries + : 0; + cache->numSrvNameCacheEntries = (maxSrvNameCacheEntries >= 0) ? maxSrvNameCacheEntries + : DEF_NAME_CACHE_ENTRIES; /* compute size of shared memory, and offsets of all pointers */ ptr = 0; - cache->cacheMem = (char *)ptr; + cache->cacheMem = (char *)ptr; ptr += SID_ROUNDUP(sizeof(cacheDesc), SID_ALIGNMENT); cache->sidCacheLocks = (sidCacheLock *)ptr; - cache->keyCacheLock = cache->sidCacheLocks + cache->numSIDCacheLocks; - cache->certCacheLock = cache->keyCacheLock + 1; - cache->srvNameCacheLock = cache->certCacheLock + 1; + cache->keyCacheLock = cache->sidCacheLocks + cache->numSIDCacheLocks; + cache->certCacheLock = cache->keyCacheLock + 1; + cache->srvNameCacheLock = cache->certCacheLock + 1; ptr = (ptrdiff_t)(cache->srvNameCacheLock + 1); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); - cache->sidCacheSets = (sidCacheSet *)ptr; + cache->sidCacheSets = (sidCacheSet *)ptr; ptr = (ptrdiff_t)(cache->sidCacheSets + cache->numSIDCacheSets); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); - cache->sidCacheData = (sidCacheEntry *)ptr; + cache->sidCacheData = (sidCacheEntry *)ptr; ptr = (ptrdiff_t)(cache->sidCacheData + cache->numSIDCacheEntries); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); cache->certCacheData = (certCacheEntry *)ptr; - cache->sidCacheSize = - (char *)cache->certCacheData - (char *)cache->sidCacheData; + cache->sidCacheSize = + (char *)cache->certCacheData - (char *)cache->sidCacheData; if (cache->numCertCacheEntries < MIN_CERT_CACHE_ENTRIES) { /* This is really a poor way to computer this! */ cache->numCertCacheEntries = cache->sidCacheSize / sizeof(certCacheEntry); if (cache->numCertCacheEntries < MIN_CERT_CACHE_ENTRIES) - cache->numCertCacheEntries = MIN_CERT_CACHE_ENTRIES; + cache->numCertCacheEntries = MIN_CERT_CACHE_ENTRIES; } ptr = (ptrdiff_t)(cache->certCacheData + cache->numCertCacheEntries); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); - cache->keyCacheData = (SSLWrappedSymWrappingKey *)ptr; - cache->certCacheSize = - (char *)cache->keyCacheData - (char *)cache->certCacheData; + cache->keyCacheData = (SSLWrappedSymWrappingKey *)ptr; + cache->certCacheSize = + (char *)cache->keyCacheData - (char *)cache->certCacheData; cache->numKeyCacheEntries = kt_kea_size * SSL_NUM_WRAP_MECHS; ptr = (ptrdiff_t)(cache->keyCacheData + cache->numKeyCacheEntries); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); - cache->keyCacheSize = (char *)ptr - (char *)cache->keyCacheData; + cache->keyCacheSize = (char *)ptr - (char *)cache->keyCacheData; cache->ticketKeyNameSuffix = (PRUint8 *)ptr; ptr = (ptrdiff_t)(cache->ticketKeyNameSuffix + - SESS_TICKET_KEY_VAR_NAME_LEN); + SESS_TICKET_KEY_VAR_NAME_LEN); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); cache->ticketEncKey = (encKeyCacheEntry *)ptr; @@ -1150,66 +1154,69 @@ InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, cache->cacheMemSize = ptr; - if (ssl2_timeout) { - if (ssl2_timeout > MAX_SSL2_TIMEOUT) { - ssl2_timeout = MAX_SSL2_TIMEOUT; - } - if (ssl2_timeout < MIN_SSL2_TIMEOUT) { - ssl2_timeout = MIN_SSL2_TIMEOUT; - } - cache->ssl2Timeout = ssl2_timeout; - } else { - cache->ssl2Timeout = DEF_SSL2_TIMEOUT; + if (ssl2_timeout) { + if (ssl2_timeout > MAX_SSL2_TIMEOUT) { + ssl2_timeout = MAX_SSL2_TIMEOUT; + } + if (ssl2_timeout < MIN_SSL2_TIMEOUT) { + ssl2_timeout = MIN_SSL2_TIMEOUT; + } + cache->ssl2Timeout = ssl2_timeout; + } + else { + cache->ssl2Timeout = DEF_SSL2_TIMEOUT; } - if (ssl3_timeout) { - if (ssl3_timeout > MAX_SSL3_TIMEOUT) { - ssl3_timeout = MAX_SSL3_TIMEOUT; - } - if (ssl3_timeout < MIN_SSL3_TIMEOUT) { - ssl3_timeout = MIN_SSL3_TIMEOUT; - } - cache->ssl3Timeout = ssl3_timeout; - } else { - cache->ssl3Timeout = DEF_SSL3_TIMEOUT; + if (ssl3_timeout) { + if (ssl3_timeout > MAX_SSL3_TIMEOUT) { + ssl3_timeout = MAX_SSL3_TIMEOUT; + } + if (ssl3_timeout < MIN_SSL3_TIMEOUT) { + ssl3_timeout = MIN_SSL3_TIMEOUT; + } + cache->ssl3Timeout = ssl3_timeout; + } + else { + cache->ssl3Timeout = DEF_SSL3_TIMEOUT; } if (shared) { - /* Create file names */ + /* Create file names */ #if defined(XP_UNIX) || defined(XP_BEOS) - /* there's some confusion here about whether PR_OpenAnonFileMap wants - ** a directory name or a file name for its first argument. - cfn = PR_smprintf("%s/.sslsvrcache.%d", directory, myPid); - */ - cfn = PR_smprintf("%s", directory); + /* there's some confusion here about whether PR_OpenAnonFileMap wants + ** a directory name or a file name for its first argument. + cfn = PR_smprintf("%s/.sslsvrcache.%d", directory, myPid); + */ + cfn = PR_smprintf("%s", directory); #elif defined(XP_WIN32) - cfn = PR_smprintf("%s/svrcache_%d_%x.ssl", directory, myPid, - GetCurrentThreadId()); + cfn = PR_smprintf("%s/svrcache_%d_%x.ssl", directory, myPid, + GetCurrentThreadId()); #elif defined(XP_OS2) - cfn = PR_smprintf("%s/svrcache_%d_%x.ssl", directory, myPid, - gettid()); + cfn = PR_smprintf("%s/svrcache_%d_%x.ssl", directory, myPid, + gettid()); #else #error "Don't know how to create file name for this platform!" #endif - if (!cfn) { - goto loser; - } + if (!cfn) { + goto loser; + } - /* Create cache */ - cacheMemMap = PR_OpenAnonFileMap(cfn, cache->cacheMemSize, - PR_PROT_READWRITE); + /* Create cache */ + cacheMemMap = PR_OpenAnonFileMap(cfn, cache->cacheMemSize, + PR_PROT_READWRITE); - PR_smprintf_free(cfn); - if(!cacheMemMap) { - goto loser; - } + PR_smprintf_free(cfn); + if (!cacheMemMap) { + goto loser; + } cacheMem = PR_MemMap(cacheMemMap, 0, cache->cacheMemSize); - } else { + } + else { cacheMem = PORT_Alloc(cache->cacheMemSize); } - - if (! cacheMem) { + + if (!cacheMem) { goto loser; } @@ -1221,53 +1228,40 @@ InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, /* save private copies of these values */ cache->cacheMemMap = cacheMemMap; - cache->cacheMem = cacheMem; + cache->cacheMem = cacheMem; cache->sharedCache = (cacheDesc *)cacheMem; - /* Fix pointers in our private copy of cache descriptor to point to - ** spaces in shared memory + /* Fix pointers in our private copy of cache descriptor to point to + ** spaces in shared memory */ - cache->sidCacheLocks = (sidCacheLock *) - (cache->cacheMem + (ptrdiff_t)cache->sidCacheLocks); - cache->keyCacheLock = (sidCacheLock *) - (cache->cacheMem + (ptrdiff_t)cache->keyCacheLock); - cache->certCacheLock = (sidCacheLock *) - (cache->cacheMem + (ptrdiff_t)cache->certCacheLock); - cache->srvNameCacheLock = (sidCacheLock *) - (cache->cacheMem + (ptrdiff_t)cache->srvNameCacheLock); - cache->sidCacheSets = (sidCacheSet *) - (cache->cacheMem + (ptrdiff_t)cache->sidCacheSets); - cache->sidCacheData = (sidCacheEntry *) - (cache->cacheMem + (ptrdiff_t)cache->sidCacheData); - cache->certCacheData = (certCacheEntry *) - (cache->cacheMem + (ptrdiff_t)cache->certCacheData); - cache->keyCacheData = (SSLWrappedSymWrappingKey *) - (cache->cacheMem + (ptrdiff_t)cache->keyCacheData); - cache->ticketKeyNameSuffix = (PRUint8 *) - (cache->cacheMem + (ptrdiff_t)cache->ticketKeyNameSuffix); - cache->ticketEncKey = (encKeyCacheEntry *) - (cache->cacheMem + (ptrdiff_t)cache->ticketEncKey); - cache->ticketMacKey = (encKeyCacheEntry *) - (cache->cacheMem + (ptrdiff_t)cache->ticketMacKey); - cache->ticketKeysValid = (PRUint32 *) - (cache->cacheMem + (ptrdiff_t)cache->ticketKeysValid); - cache->srvNameCacheData = (srvNameCacheEntry *) - (cache->cacheMem + (ptrdiff_t)cache->srvNameCacheData); + cache->sidCacheLocks = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->sidCacheLocks); + cache->keyCacheLock = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->keyCacheLock); + cache->certCacheLock = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->certCacheLock); + cache->srvNameCacheLock = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->srvNameCacheLock); + cache->sidCacheSets = (sidCacheSet *)(cache->cacheMem + (ptrdiff_t)cache->sidCacheSets); + cache->sidCacheData = (sidCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->sidCacheData); + cache->certCacheData = (certCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->certCacheData); + cache->keyCacheData = (SSLWrappedSymWrappingKey *)(cache->cacheMem + (ptrdiff_t)cache->keyCacheData); + cache->ticketKeyNameSuffix = (PRUint8 *)(cache->cacheMem + (ptrdiff_t)cache->ticketKeyNameSuffix); + cache->ticketEncKey = (encKeyCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->ticketEncKey); + cache->ticketMacKey = (encKeyCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->ticketMacKey); + cache->ticketKeysValid = (PRUint32 *)(cache->cacheMem + (ptrdiff_t)cache->ticketKeysValid); + cache->srvNameCacheData = (srvNameCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->srvNameCacheData); /* initialize the locks */ init_time = ssl_Time(); pLock = cache->sidCacheLocks; for (locks_to_initialize = cache->numSIDCacheLocks + 3; - locks_initialized < locks_to_initialize; - ++locks_initialized, ++pLock ) { + locks_initialized < locks_to_initialize; + ++locks_initialized, ++pLock) { - SECStatus err = sslMutex_Init(&pLock->mutex, shared); - if (err) { - cache->numSIDCacheLocksInitialized = locks_initialized; - goto loser; - } + SECStatus err = sslMutex_Init(&pLock->mutex, shared); + if (err) { + cache->numSIDCacheLocksInitialized = locks_initialized; + goto loser; + } pLock->timeStamp = init_time; - pLock->pid = 0; + pLock->pid = 0; } cache->numSIDCacheLocksInitialized = locks_initialized; @@ -1294,8 +1288,8 @@ SSL_SetMaxServerCacheLocks(PRUint32 maxLocks) ** the maximum, other than trial and error. */ if (maxLocks < 3) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ssl_max_sid_cache_locks = maxLocks - 2; /* The extra two are the cert cache lock and the key cache lock. */ @@ -1305,12 +1299,12 @@ SSL_SetMaxServerCacheLocks(PRUint32 maxLocks) static SECStatus ssl_ConfigServerSessionIDCacheInstanceWithOpt(cacheDesc *cache, PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, + PRUint32 ssl3_timeout, + const char *directory, PRBool shared, - int maxCacheEntries, - int maxCertCacheEntries, - int maxSrvNameCacheEntries) + int maxCacheEntries, + int maxCertCacheEntries, + int maxSrvNameCacheEntries) { SECStatus rv; @@ -1320,52 +1314,52 @@ ssl_ConfigServerSessionIDCacheInstanceWithOpt(cacheDesc *cache, rv = ssl_Init(); if (rv != SECSuccess) { - return rv; + return rv; } myPid = SSL_GETPID(); if (!directory) { - directory = DEFAULT_CACHE_DIRECTORY; + directory = DEFAULT_CACHE_DIRECTORY; } rv = InitCache(cache, maxCacheEntries, maxCertCacheEntries, - maxSrvNameCacheEntries, ssl2_timeout, ssl3_timeout, + maxSrvNameCacheEntries, ssl2_timeout, ssl3_timeout, directory, shared); if (rv) { - SET_ERROR_CODE - return SECFailure; + SET_ERROR_CODE + return SECFailure; } - ssl_sid_lookup = ServerSessionIDLookup; - ssl_sid_cache = ServerSessionIDCache; + ssl_sid_lookup = ServerSessionIDLookup; + ssl_sid_cache = ServerSessionIDCache; ssl_sid_uncache = ServerSessionIDUncache; return SECSuccess; } SECStatus -SSL_ConfigServerSessionIDCacheInstance( cacheDesc *cache, - int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, PRBool shared) +SSL_ConfigServerSessionIDCacheInstance(cacheDesc *cache, + int maxCacheEntries, + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory, PRBool shared) { return ssl_ConfigServerSessionIDCacheInstanceWithOpt(cache, ssl2_timeout, ssl3_timeout, directory, shared, - maxCacheEntries, + maxCacheEntries, -1, -1); } SECStatus -SSL_ConfigServerSessionIDCache( int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory) +SSL_ConfigServerSessionIDCache(int maxCacheEntries, + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory) { ssl_InitSessionCacheLocks(PR_FALSE); - return SSL_ConfigServerSessionIDCacheInstance(&globalCache, - maxCacheEntries, ssl2_timeout, ssl3_timeout, directory, PR_FALSE); + return SSL_ConfigServerSessionIDCacheInstance(&globalCache, + maxCacheEntries, ssl2_timeout, ssl3_timeout, directory, PR_FALSE); } SECStatus @@ -1390,49 +1384,49 @@ SSL_ShutdownServerSessionIDCache(void) * if the cache will be shared by multiple processes. */ static SECStatus -ssl_ConfigMPServerSIDCacheWithOpt( PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, - int maxCacheEntries, - int maxCertCacheEntries, - int maxSrvNameCacheEntries) +ssl_ConfigMPServerSIDCacheWithOpt(PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory, + int maxCacheEntries, + int maxCertCacheEntries, + int maxSrvNameCacheEntries) { - char * envValue; - char * inhValue; - cacheDesc * cache = &globalCache; - PRUint32 fmStrLen; - SECStatus result; - PRStatus prStatus; - SECStatus putEnvFailed; + char *envValue; + char *inhValue; + cacheDesc *cache = &globalCache; + PRUint32 fmStrLen; + SECStatus result; + PRStatus prStatus; + SECStatus putEnvFailed; inheritance inherit; - char fmString[PR_FILEMAP_STRING_BUFSIZE]; + char fmString[PR_FILEMAP_STRING_BUFSIZE]; isMultiProcess = PR_TRUE; result = ssl_ConfigServerSessionIDCacheInstanceWithOpt(cache, - ssl2_timeout, ssl3_timeout, directory, PR_TRUE, - maxCacheEntries, maxCacheEntries, maxSrvNameCacheEntries); - if (result != SECSuccess) + ssl2_timeout, ssl3_timeout, directory, PR_TRUE, + maxCacheEntries, maxCacheEntries, maxSrvNameCacheEntries); + if (result != SECSuccess) return result; - prStatus = PR_ExportFileMapAsString(cache->cacheMemMap, + prStatus = PR_ExportFileMapAsString(cache->cacheMemMap, sizeof fmString, fmString); if ((prStatus != PR_SUCCESS) || !(fmStrLen = strlen(fmString))) { - SET_ERROR_CODE - return SECFailure; + SET_ERROR_CODE + return SECFailure; } - inherit.cacheMemSize = cache->cacheMemSize; - inherit.fmStrLen = fmStrLen; + inherit.cacheMemSize = cache->cacheMemSize; + inherit.fmStrLen = fmStrLen; inhValue = BTOA_DataToAscii((unsigned char *)&inherit, sizeof inherit); if (!inhValue || !strlen(inhValue)) { - SET_ERROR_CODE - return SECFailure; + SET_ERROR_CODE + return SECFailure; } envValue = PR_smprintf("%s,%s", inhValue, fmString); if (!envValue || !strlen(envValue)) { - SET_ERROR_CODE - return SECFailure; + SET_ERROR_CODE + return SECFailure; } PORT_Free(inhValue); @@ -1454,10 +1448,10 @@ ssl_ConfigMPServerSIDCacheWithOpt( PRUint32 ssl2_timeout, * if the cache will be shared by multiple processes. */ SECStatus -SSL_ConfigMPServerSIDCache( int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory) +SSL_ConfigMPServerSIDCache(int maxCacheEntries, + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory) { return ssl_ConfigMPServerSIDCacheWithOpt(ssl2_timeout, ssl3_timeout, @@ -1468,44 +1462,45 @@ SSL_ConfigMPServerSIDCache( int maxCacheEntries, SECStatus SSL_ConfigServerSessionIDCacheWithOpt( - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, - int maxCacheEntries, - int maxCertCacheEntries, - int maxSrvNameCacheEntries, - PRBool enableMPCache) + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory, + int maxCacheEntries, + int maxCertCacheEntries, + int maxSrvNameCacheEntries, + PRBool enableMPCache) { if (!enableMPCache) { ssl_InitSessionCacheLocks(PR_FALSE); - return ssl_ConfigServerSessionIDCacheInstanceWithOpt(&globalCache, - ssl2_timeout, ssl3_timeout, directory, PR_FALSE, - maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries); - } else { + return ssl_ConfigServerSessionIDCacheInstanceWithOpt(&globalCache, + ssl2_timeout, ssl3_timeout, directory, PR_FALSE, + maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries); + } + else { return ssl_ConfigMPServerSIDCacheWithOpt(ssl2_timeout, ssl3_timeout, - directory, maxCacheEntries, maxCertCacheEntries, + directory, maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries); } } SECStatus -SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) +SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char *envString) { - unsigned char * decoString = NULL; - char * fmString = NULL; - char * myEnvString = NULL; - unsigned int decoLen; - inheritance inherit; - cacheDesc my; + unsigned char *decoString = NULL; + char *fmString = NULL; + char *myEnvString = NULL; + unsigned int decoLen; + inheritance inherit; + cacheDesc my; #ifdef WINNT - sidCacheLock* newLocks; - int locks_initialized = 0; - int locks_to_initialize = 0; + sidCacheLock *newLocks; + int locks_initialized = 0; + int locks_to_initialize = 0; #endif - SECStatus status = ssl_Init(); + SECStatus status = ssl_Init(); if (status != SECSuccess) { - return status; + return status; } myPid = SSL_GETPID(); @@ -1515,110 +1510,97 @@ SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) ** If not, we'll set it below. */ if (isMultiProcess) { - if (cache && cache->sharedCache) { - cache->sharedCache->everInherited = PR_TRUE; - } - return SECSuccess; /* already done. */ + if (cache && cache->sharedCache) { + cache->sharedCache->everInherited = PR_TRUE; + } + return SECSuccess; /* already done. */ } ssl_InitSessionCacheLocks(PR_FALSE); - ssl_sid_lookup = ServerSessionIDLookup; - ssl_sid_cache = ServerSessionIDCache; + ssl_sid_lookup = ServerSessionIDLookup; + ssl_sid_cache = ServerSessionIDCache; ssl_sid_uncache = ServerSessionIDUncache; if (!envString) { - envString = PR_GetEnvSecure(envVarName); - if (!envString) { - SET_ERROR_CODE - return SECFailure; - } + envString = PR_GetEnvSecure(envVarName); + if (!envString) { + SET_ERROR_CODE + return SECFailure; + } } myEnvString = PORT_Strdup(envString); - if (!myEnvString) - return SECFailure; + if (!myEnvString) + return SECFailure; fmString = strchr(myEnvString, ','); - if (!fmString) - goto loser; + if (!fmString) + goto loser; *fmString++ = 0; decoString = ATOB_AsciiToData(myEnvString, &decoLen); if (!decoString) { - SET_ERROR_CODE - goto loser; + SET_ERROR_CODE + goto loser; } if (decoLen != sizeof inherit) { - SET_ERROR_CODE - goto loser; + SET_ERROR_CODE + goto loser; } PORT_Memcpy(&inherit, decoString, sizeof inherit); - if (strlen(fmString) != inherit.fmStrLen ) { - goto loser; + if (strlen(fmString) != inherit.fmStrLen) { + goto loser; } memset(cache, 0, sizeof *cache); - cache->cacheMemSize = inherit.cacheMemSize; + cache->cacheMemSize = inherit.cacheMemSize; /* Create cache */ cache->cacheMemMap = PR_ImportFileMapFromString(fmString); - if(! cache->cacheMemMap) { - goto loser; + if (!cache->cacheMemMap) { + goto loser; } cache->cacheMem = PR_MemMap(cache->cacheMemMap, 0, cache->cacheMemSize); - if (! cache->cacheMem) { - goto loser; + if (!cache->cacheMem) { + goto loser; } - cache->sharedCache = (cacheDesc *)cache->cacheMem; + cache->sharedCache = (cacheDesc *)cache->cacheMem; if (cache->sharedCache->cacheMemSize != cache->cacheMemSize) { - SET_ERROR_CODE - goto loser; + SET_ERROR_CODE + goto loser; } - /* We're now going to overwrite the local cache instance with the - ** shared copy of the cache struct, then update several values in - ** the local cache using the values for cache->cacheMemMap and - ** cache->cacheMem computed just above. So, we copy cache into + /* We're now going to overwrite the local cache instance with the + ** shared copy of the cache struct, then update several values in + ** the local cache using the values for cache->cacheMemMap and + ** cache->cacheMem computed just above. So, we copy cache into ** the automatic variable "my", to preserve the variables while ** cache is overwritten. */ - my = *cache; /* save values computed above. */ + my = *cache; /* save values computed above. */ memcpy(cache, cache->sharedCache, sizeof *cache); /* overwrite */ - /* Fix pointers in our private copy of cache descriptor to point to + /* Fix pointers in our private copy of cache descriptor to point to ** spaces in shared memory, whose address is now in "my". */ - cache->sidCacheLocks = (sidCacheLock *) - (my.cacheMem + (ptrdiff_t)cache->sidCacheLocks); - cache->keyCacheLock = (sidCacheLock *) - (my.cacheMem + (ptrdiff_t)cache->keyCacheLock); - cache->certCacheLock = (sidCacheLock *) - (my.cacheMem + (ptrdiff_t)cache->certCacheLock); - cache->srvNameCacheLock = (sidCacheLock *) - (my.cacheMem + (ptrdiff_t)cache->srvNameCacheLock); - cache->sidCacheSets = (sidCacheSet *) - (my.cacheMem + (ptrdiff_t)cache->sidCacheSets); - cache->sidCacheData = (sidCacheEntry *) - (my.cacheMem + (ptrdiff_t)cache->sidCacheData); - cache->certCacheData = (certCacheEntry *) - (my.cacheMem + (ptrdiff_t)cache->certCacheData); - cache->keyCacheData = (SSLWrappedSymWrappingKey *) - (my.cacheMem + (ptrdiff_t)cache->keyCacheData); - cache->ticketKeyNameSuffix = (PRUint8 *) - (my.cacheMem + (ptrdiff_t)cache->ticketKeyNameSuffix); - cache->ticketEncKey = (encKeyCacheEntry *) - (my.cacheMem + (ptrdiff_t)cache->ticketEncKey); - cache->ticketMacKey = (encKeyCacheEntry *) - (my.cacheMem + (ptrdiff_t)cache->ticketMacKey); - cache->ticketKeysValid = (PRUint32 *) - (my.cacheMem + (ptrdiff_t)cache->ticketKeysValid); - cache->srvNameCacheData = (srvNameCacheEntry *) - (my.cacheMem + (ptrdiff_t)cache->srvNameCacheData); + cache->sidCacheLocks = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->sidCacheLocks); + cache->keyCacheLock = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->keyCacheLock); + cache->certCacheLock = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->certCacheLock); + cache->srvNameCacheLock = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->srvNameCacheLock); + cache->sidCacheSets = (sidCacheSet *)(my.cacheMem + (ptrdiff_t)cache->sidCacheSets); + cache->sidCacheData = (sidCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->sidCacheData); + cache->certCacheData = (certCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->certCacheData); + cache->keyCacheData = (SSLWrappedSymWrappingKey *)(my.cacheMem + (ptrdiff_t)cache->keyCacheData); + cache->ticketKeyNameSuffix = (PRUint8 *)(my.cacheMem + (ptrdiff_t)cache->ticketKeyNameSuffix); + cache->ticketEncKey = (encKeyCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->ticketEncKey); + cache->ticketMacKey = (encKeyCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->ticketMacKey); + cache->ticketKeysValid = (PRUint32 *)(my.cacheMem + (ptrdiff_t)cache->ticketKeysValid); + cache->srvNameCacheData = (srvNameCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->srvNameCacheData); cache->cacheMemMap = my.cacheMemMap; - cache->cacheMem = my.cacheMem; + cache->cacheMem = my.cacheMem; cache->sharedCache = (cacheDesc *)cache->cacheMem; #ifdef WINNT @@ -1633,34 +1615,34 @@ SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) ** copies of sidCacheLocks before modifying the sslMutex with our own ** PRLock */ - + /* note from jpierre : this should be free'd in child processes when - ** a function is added to delete the SSL session cache in the future. + ** a function is added to delete the SSL session cache in the future. */ locks_to_initialize = cache->numSIDCacheLocks + 3; newLocks = PORT_NewArray(sidCacheLock, locks_to_initialize); if (!newLocks) - goto loser; + goto loser; /* copy the old locks */ - memcpy(newLocks, cache->sidCacheLocks, + memcpy(newLocks, cache->sidCacheLocks, locks_to_initialize * sizeof(sidCacheLock)); cache->sidCacheLocks = newLocks; - /* fix the locks */ + /* fix the locks */ for (; locks_initialized < locks_to_initialize; ++locks_initialized) { /* now, make a local PRLock in this sslMutex for this child process */ - SECStatus err; + SECStatus err; err = sslMutex_2LevelInit(&newLocks[locks_initialized].mutex); - if (err != SECSuccess) { - cache->numSIDCacheLocksInitialized = locks_initialized; - goto loser; - } + if (err != SECSuccess) { + cache->numSIDCacheLocksInitialized = locks_initialized; + goto loser; + } } cache->numSIDCacheLocksInitialized = locks_initialized; /* also fix the key and cert cache which use the last 2 lock entries */ - cache->keyCacheLock = cache->sidCacheLocks + cache->numSIDCacheLocks; - cache->certCacheLock = cache->keyCacheLock + 1; - cache->srvNameCacheLock = cache->certCacheLock + 1; + cache->keyCacheLock = cache->sidCacheLocks + cache->numSIDCacheLocks; + cache->certCacheLock = cache->keyCacheLock + 1; + cache->srvNameCacheLock = cache->certCacheLock + 1; #endif PORT_Free(myEnvString); @@ -1674,112 +1656,112 @@ SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) loser: PORT_Free(myEnvString); - if (decoString) - PORT_Free(decoString); + if (decoString) + PORT_Free(decoString); CloseCache(cache); return SECFailure; } SECStatus -SSL_InheritMPServerSIDCache(const char * envString) +SSL_InheritMPServerSIDCache(const char *envString) { return SSL_InheritMPServerSIDCacheInstance(&globalCache, envString); } #if defined(XP_UNIX) || defined(XP_BEOS) -#define SID_LOCK_EXPIRATION_TIMEOUT 30 /* seconds */ +#define SID_LOCK_EXPIRATION_TIMEOUT 30 /* seconds */ static void -LockPoller(void * arg) +LockPoller(void *arg) { - cacheDesc * cache = (cacheDesc *)arg; - cacheDesc * sharedCache = cache->sharedCache; - sidCacheLock * pLock; + cacheDesc *cache = (cacheDesc *)arg; + cacheDesc *sharedCache = cache->sharedCache; + sidCacheLock *pLock; PRIntervalTime timeout; - PRUint32 now; - PRUint32 then; - int locks_polled = 0; - int locks_to_poll = cache->numSIDCacheLocks + 2; - PRUint32 expiration = cache->mutexTimeout; + PRUint32 now; + PRUint32 then; + int locks_polled = 0; + int locks_to_poll = cache->numSIDCacheLocks + 2; + PRUint32 expiration = cache->mutexTimeout; timeout = PR_SecondsToInterval(expiration); - while(!sharedCache->stopPolling) { - PR_Sleep(timeout); - if (sharedCache->stopPolling) - break; + while (!sharedCache->stopPolling) { + PR_Sleep(timeout); + if (sharedCache->stopPolling) + break; - now = ssl_Time(); - then = now - expiration; - for (pLock = cache->sidCacheLocks, locks_polled = 0; - locks_to_poll > locks_polled && !sharedCache->stopPolling; - ++locks_polled, ++pLock ) { - pid_t pid; + now = ssl_Time(); + then = now - expiration; + for (pLock = cache->sidCacheLocks, locks_polled = 0; + locks_to_poll > locks_polled && !sharedCache->stopPolling; + ++locks_polled, ++pLock) { + pid_t pid; - if (pLock->timeStamp < then && - pLock->timeStamp != 0 && - (pid = pLock->pid) != 0) { + if (pLock->timeStamp < then && + pLock->timeStamp != 0 && + (pid = pLock->pid) != 0) { - /* maybe we should try the lock? */ - int result = kill(pid, 0); - if (result < 0 && errno == ESRCH) { - SECStatus rv; - /* No process exists by that pid any more. - ** Treat this mutex as abandoned. - */ - pLock->timeStamp = now; - pLock->pid = 0; - rv = sslMutex_Unlock(&pLock->mutex); - if (rv != SECSuccess) { - /* Now what? */ - } - } - } - } /* end of loop over locks */ - } /* end of entire polling loop */ + /* maybe we should try the lock? */ + int result = kill(pid, 0); + if (result < 0 && errno == ESRCH) { + SECStatus rv; + /* No process exists by that pid any more. + ** Treat this mutex as abandoned. + */ + pLock->timeStamp = now; + pLock->pid = 0; + rv = sslMutex_Unlock(&pLock->mutex); + if (rv != SECSuccess) { + /* Now what? */ + } + } + } + } /* end of loop over locks */ + } /* end of entire polling loop */ } /* Launch thread to poll cache for expired locks */ -static SECStatus +static SECStatus LaunchLockPoller(cacheDesc *cache) { - const char * timeoutString; - PRThread * pollerThread; + const char *timeoutString; + PRThread *pollerThread; cache->mutexTimeout = SID_LOCK_EXPIRATION_TIMEOUT; - timeoutString = PR_GetEnvSecure("NSS_SSL_SERVER_CACHE_MUTEX_TIMEOUT"); + timeoutString = PR_GetEnvSecure("NSS_SSL_SERVER_CACHE_MUTEX_TIMEOUT"); if (timeoutString) { - long newTime = strtol(timeoutString, 0, 0); - if (newTime == 0) - return SECSuccess; /* application doesn't want poller thread */ - if (newTime > 0) - cache->mutexTimeout = (PRUint32)newTime; - /* if error (newTime < 0) ignore it and use default */ + long newTime = strtol(timeoutString, 0, 0); + if (newTime == 0) + return SECSuccess; /* application doesn't want poller thread */ + if (newTime > 0) + cache->mutexTimeout = (PRUint32)newTime; + /* if error (newTime < 0) ignore it and use default */ } - pollerThread = - PR_CreateThread(PR_USER_THREAD, LockPoller, cache, PR_PRIORITY_NORMAL, - PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); + pollerThread = + PR_CreateThread(PR_USER_THREAD, LockPoller, cache, PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (!pollerThread) { - return SECFailure; + return SECFailure; } cache->poller = pollerThread; return SECSuccess; } /* Stop the thread that polls cache for expired locks */ -static SECStatus +static SECStatus StopLockPoller(cacheDesc *cache) { if (!cache->poller) { - return SECSuccess; + return SECSuccess; } cache->sharedCache->stopPolling = PR_TRUE; if (PR_Interrupt(cache->poller) != PR_SUCCESS) { - return SECFailure; + return SECFailure; } if (PR_JoinThread(cache->poller) != PR_SUCCESS) { - return SECFailure; + return SECFailure; } cache->poller = NULL; return SECSuccess; @@ -1790,58 +1772,59 @@ StopLockPoller(cacheDesc *cache) * Code dealing with shared wrapped symmetric wrapping keys below * ************************************************************************/ -/* If now is zero, it implies that the lock is not held, and must be -** aquired here. +/* If now is zero, it implies that the lock is not held, and must be +** aquired here. */ static PRBool -getSvrWrappingKey(PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk, - cacheDesc * cache, - PRUint32 lockTime) +getSvrWrappingKey(PRInt32 symWrapMechIndex, + SSL3KEAType exchKeyType, + SSLWrappedSymWrappingKey *wswk, + cacheDesc *cache, + PRUint32 lockTime) { - PRUint32 ndx = (exchKeyType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex; - SSLWrappedSymWrappingKey * pwswk = cache->keyCacheData + ndx; - PRUint32 now = 0; - PRBool rv = PR_FALSE; + PRUint32 ndx = (exchKeyType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex; + SSLWrappedSymWrappingKey *pwswk = cache->keyCacheData + ndx; + PRUint32 now = 0; + PRBool rv = PR_FALSE; if (!cache->cacheMem) { /* cache is uninitialized */ - PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); - return rv; + PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); + return rv; } if (!lockTime) { - lockTime = now = LockSidCacheLock(cache->keyCacheLock, now); - if (!lockTime) { - return rv; - } + lockTime = now = LockSidCacheLock(cache->keyCacheLock, now); + if (!lockTime) { + return rv; + } } - if (pwswk->exchKeyType == exchKeyType && - pwswk->symWrapMechIndex == symWrapMechIndex && - pwswk->wrappedSymKeyLen != 0) { - *wswk = *pwswk; - rv = PR_TRUE; + if (pwswk->exchKeyType == exchKeyType && + pwswk->symWrapMechIndex == symWrapMechIndex && + pwswk->wrappedSymKeyLen != 0) { + *wswk = *pwswk; + rv = PR_TRUE; } if (now) { - UnlockSidCacheLock(cache->keyCacheLock); + UnlockSidCacheLock(cache->keyCacheLock); } return rv; } PRBool -ssl_GetWrappingKey( PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk) +ssl_GetWrappingKey(PRInt32 symWrapMechIndex, + SSL3KEAType exchKeyType, + SSLWrappedSymWrappingKey *wswk) { PRBool rv; - PORT_Assert( (unsigned)exchKeyType < kt_kea_size); - PORT_Assert( (unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); + PORT_Assert((unsigned)exchKeyType < kt_kea_size); + PORT_Assert((unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); if ((unsigned)exchKeyType < kt_kea_size && (unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS) { - rv = getSvrWrappingKey(symWrapMechIndex, exchKeyType, wswk, - &globalCache, 0); - } else { - rv = PR_FALSE; + rv = getSvrWrappingKey(symWrapMechIndex, exchKeyType, wswk, + &globalCache, 0); + } + else { + rv = PR_FALSE; } return rv; @@ -1850,21 +1833,21 @@ ssl_GetWrappingKey( PRInt32 symWrapMechIndex, /* Wrap and cache a session ticket key. */ static PRBool WrapTicketKey(SECKEYPublicKey *svrPubKey, PK11SymKey *symKey, - const char *keyName, encKeyCacheEntry* cacheEntry) + const char *keyName, encKeyCacheEntry *cacheEntry) { - SECItem wrappedKey = {siBuffer, NULL, 0}; + SECItem wrappedKey = { siBuffer, NULL, 0 }; wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); PORT_Assert(wrappedKey.len <= sizeof(cacheEntry->bytes)); if (wrappedKey.len > sizeof(cacheEntry->bytes)) - return PR_FALSE; + return PR_FALSE; wrappedKey.data = cacheEntry->bytes; - if (PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, symKey, &wrappedKey) - != SECSuccess) { - SSL_DBG(("%d: SSL[%s]: Unable to wrap session ticket %s.", - SSL_GETPID(), "unknown", keyName)); - return PR_FALSE; + if (PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, symKey, &wrappedKey) != + SECSuccess) { + SSL_DBG(("%d: SSL[%s]: Unable to wrap session ticket %s.", + SSL_GETPID(), "unknown", keyName)); + return PR_FALSE; } cacheEntry->length = wrappedKey.len; return PR_TRUE; @@ -1885,15 +1868,17 @@ GenerateTicketKeys(void *pwArg, unsigned char *keyName, PK11SymKey **aesKey, if (!cache->cacheMem) { /* cache is not initalized. Use stack buffer */ ticketKeyNameSuffix = ticketKeyNameSuffixLocal; - } else { + } + else { ticketKeyNameSuffix = cache->ticketKeyNameSuffix; } if (PK11_GenerateRandom(ticketKeyNameSuffix, - SESS_TICKET_KEY_VAR_NAME_LEN) != SECSuccess) { - SSL_DBG(("%d: SSL[%s]: Unable to generate random key name bytes.", - SSL_GETPID(), "unknown")); - goto loser; + SESS_TICKET_KEY_VAR_NAME_LEN) != + SECSuccess) { + SSL_DBG(("%d: SSL[%s]: Unable to generate random key name bytes.", + SSL_GETPID(), "unknown")); + goto loser; } mechanismArray[0] = CKM_AES_CBC; @@ -1901,17 +1886,17 @@ GenerateTicketKeys(void *pwArg, unsigned char *keyName, PK11SymKey **aesKey, slot = PK11_GetBestSlotMultiple(mechanismArray, 2, pwArg); if (slot) { - aesKeyTmp = PK11_KeyGen(slot, mechanismArray[0], NULL, + aesKeyTmp = PK11_KeyGen(slot, mechanismArray[0], NULL, AES_256_KEY_LENGTH, pwArg); - macKeyTmp = PK11_KeyGen(slot, mechanismArray[1], NULL, + macKeyTmp = PK11_KeyGen(slot, mechanismArray[1], NULL, SHA256_LENGTH, pwArg); - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); } if (aesKeyTmp == NULL || macKeyTmp == NULL) { - SSL_DBG(("%d: SSL[%s]: Unable to generate session ticket keys.", - SSL_GETPID(), "unknown")); - goto loser; + SSL_DBG(("%d: SSL[%s]: Unable to generate session ticket keys.", + SSL_GETPID(), "unknown")); + goto loser; } PORT_Memcpy(keyName, ticketKeyNameSuffix, SESS_TICKET_KEY_VAR_NAME_LEN); *aesKey = aesKeyTmp; @@ -1920,9 +1905,9 @@ GenerateTicketKeys(void *pwArg, unsigned char *keyName, PK11SymKey **aesKey, loser: if (aesKeyTmp) - PK11_FreeSymKey(aesKeyTmp); + PK11_FreeSymKey(aesKeyTmp); if (macKeyTmp) - PK11_FreeSymKey(macKeyTmp); + PK11_FreeSymKey(macKeyTmp); return PR_FALSE; } @@ -1952,9 +1937,9 @@ GenerateAndWrapTicketKeys(SECKEYPublicKey *svrPubKey, void *pwArg, loser: if (aesKeyTmp) - PK11_FreeSymKey(aesKeyTmp); + PK11_FreeSymKey(aesKeyTmp); if (macKeyTmp) - PK11_FreeSymKey(macKeyTmp); + PK11_FreeSymKey(macKeyTmp); return PR_FALSE; } @@ -1962,7 +1947,7 @@ static PRBool UnwrapCachedTicketKeys(SECKEYPrivateKey *svrPrivKey, unsigned char *keyName, PK11SymKey **aesKey, PK11SymKey **macKey) { - SECItem wrappedKey = {siBuffer, NULL, 0}; + SECItem wrappedKey = { siBuffer, NULL, 0 }; PK11SymKey *aesKeyTmp = NULL; PK11SymKey *macKeyTmp = NULL; cacheDesc *cache = &globalCache; @@ -1971,33 +1956,33 @@ UnwrapCachedTicketKeys(SECKEYPrivateKey *svrPrivKey, unsigned char *keyName, wrappedKey.len = cache->ticketEncKey->length; PORT_Assert(wrappedKey.len <= sizeof(cache->ticketEncKey->bytes)); aesKeyTmp = PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, - CKM_AES_CBC, CKA_DECRYPT, 0); + CKM_AES_CBC, CKA_DECRYPT, 0); wrappedKey.data = cache->ticketMacKey->bytes; wrappedKey.len = cache->ticketMacKey->length; PORT_Assert(wrappedKey.len <= sizeof(cache->ticketMacKey->bytes)); macKeyTmp = PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, - CKM_SHA256_HMAC, CKA_SIGN, 0); + CKM_SHA256_HMAC, CKA_SIGN, 0); if (aesKeyTmp == NULL || macKeyTmp == NULL) { - SSL_DBG(("%d: SSL[%s]: Unable to unwrap session ticket keys.", - SSL_GETPID(), "unknown")); - goto loser; + SSL_DBG(("%d: SSL[%s]: Unable to unwrap session ticket keys.", + SSL_GETPID(), "unknown")); + goto loser; } SSL_DBG(("%d: SSL[%s]: Successfully unwrapped session ticket keys.", - SSL_GETPID(), "unknown")); + SSL_GETPID(), "unknown")); PORT_Memcpy(keyName, cache->ticketKeyNameSuffix, - SESS_TICKET_KEY_VAR_NAME_LEN); + SESS_TICKET_KEY_VAR_NAME_LEN); *aesKey = aesKeyTmp; *macKey = macKeyTmp; return PR_TRUE; loser: if (aesKeyTmp) - PK11_FreeSymKey(aesKeyTmp); + PK11_FreeSymKey(aesKeyTmp); if (macKeyTmp) - PK11_FreeSymKey(macKeyTmp); + PK11_FreeSymKey(macKeyTmp); return PR_FALSE; } @@ -2020,23 +2005,23 @@ ssl_GetSessionTicketKeysPKCS11(SECKEYPrivateKey *svrPrivKey, now = LockSidCacheLock(cache->keyCacheLock, now); if (!now) - return rv; + return rv; if (!*(cache->ticketKeysValid)) { - /* Keys do not exist, create them. */ - if (!GenerateAndWrapTicketKeys(svrPubKey, pwArg, keyName, - aesKey, macKey)) - goto loser; - keysGenerated = PR_TRUE; - *(cache->ticketKeysValid) = 1; + /* Keys do not exist, create them. */ + if (!GenerateAndWrapTicketKeys(svrPubKey, pwArg, keyName, + aesKey, macKey)) + goto loser; + keysGenerated = PR_TRUE; + *(cache->ticketKeysValid) = 1; } rv = PR_TRUE; - loser: +loser: UnlockSidCacheLock(cache->keyCacheLock); if (rv && !keysGenerated) - rv = UnwrapCachedTicketKeys(svrPrivKey, keyName, aesKey, macKey); + rv = UnwrapCachedTicketKeys(svrPrivKey, keyName, aesKey, macKey); return rv; } @@ -2057,7 +2042,8 @@ ssl_GetSessionTicketKeys(unsigned char *keyName, unsigned char *encKey, ticketKeyNameSuffix = ticketKeyNameSuffixLocal; ticketEncKeyPtr = ticketEncKey; ticketMacKeyPtr = ticketMacKey; - } else { + } + else { /* these values have constant memory locations in the cache. * Ok to reference them without holding the lock. */ ticketKeyNameSuffix = cache->ticketKeyNameSuffix; @@ -2074,15 +2060,16 @@ ssl_GetSessionTicketKeys(unsigned char *keyName, unsigned char *encKey, /* Going to regenerate keys on every call if cache was not * initialized. */ if (!cacheIsEnabled || !*(cache->ticketKeysValid)) { - if (PK11_GenerateRandom(ticketKeyNameSuffix, - SESS_TICKET_KEY_VAR_NAME_LEN) != SECSuccess) - goto loser; - if (PK11_GenerateRandom(ticketEncKeyPtr, + if (PK11_GenerateRandom(ticketKeyNameSuffix, + SESS_TICKET_KEY_VAR_NAME_LEN) != + SECSuccess) + goto loser; + if (PK11_GenerateRandom(ticketEncKeyPtr, AES_256_KEY_LENGTH) != SECSuccess) - goto loser; - if (PK11_GenerateRandom(ticketMacKeyPtr, + goto loser; + if (PK11_GenerateRandom(ticketMacKeyPtr, SHA256_LENGTH) != SECSuccess) - goto loser; + goto loser; if (cacheIsEnabled) { *(cache->ticketKeysValid) = 1; } @@ -2090,73 +2077,74 @@ ssl_GetSessionTicketKeys(unsigned char *keyName, unsigned char *encKey, rv = PR_TRUE; - loser: +loser: if (cacheIsEnabled) { UnlockSidCacheLock(cache->keyCacheLock); } if (rv) { - PORT_Memcpy(keyName, ticketKeyNameSuffix, + PORT_Memcpy(keyName, ticketKeyNameSuffix, SESS_TICKET_KEY_VAR_NAME_LEN); - PORT_Memcpy(encKey, ticketEncKeyPtr, AES_256_KEY_LENGTH); - PORT_Memcpy(macKey, ticketMacKeyPtr, SHA256_LENGTH); + PORT_Memcpy(encKey, ticketEncKeyPtr, AES_256_KEY_LENGTH); + PORT_Memcpy(macKey, ticketMacKeyPtr, SHA256_LENGTH); } return rv; } /* The caller passes in the new value it wants * to set. This code tests the wrapped sym key entry in the shared memory. - * If it is uninitialized, this function writes the caller's value into - * the disk entry, and returns false. - * Otherwise, it overwrites the caller's wswk with the value obtained from - * the disk, and returns PR_TRUE. - * This is all done while holding the locks/mutexes necessary to make + * If it is uninitialized, this function writes the caller's value into + * the disk entry, and returns false. + * Otherwise, it overwrites the caller's wswk with the value obtained from + * the disk, and returns PR_TRUE. + * This is all done while holding the locks/mutexes necessary to make * the operation atomic. */ PRBool ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk) { - cacheDesc * cache = &globalCache; - PRBool rv = PR_FALSE; - SSL3KEAType exchKeyType = wswk->exchKeyType; - /* type of keys used to wrap SymWrapKey*/ - PRInt32 symWrapMechIndex = wswk->symWrapMechIndex; - PRUint32 ndx; - PRUint32 now = 0; + cacheDesc *cache = &globalCache; + PRBool rv = PR_FALSE; + SSL3KEAType exchKeyType = wswk->exchKeyType; + /* type of keys used to wrap SymWrapKey*/ + PRInt32 symWrapMechIndex = wswk->symWrapMechIndex; + PRUint32 ndx; + PRUint32 now = 0; SSLWrappedSymWrappingKey myWswk; if (!cache->cacheMem) { /* cache is uninitialized */ - PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); - return 0; + PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); + return 0; } - PORT_Assert( (unsigned)exchKeyType < kt_kea_size); + PORT_Assert((unsigned)exchKeyType < kt_kea_size); if ((unsigned)exchKeyType >= kt_kea_size) - return 0; + return 0; - PORT_Assert( (unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); - if ((unsigned)symWrapMechIndex >= SSL_NUM_WRAP_MECHS) - return 0; + PORT_Assert((unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); + if ((unsigned)symWrapMechIndex >= SSL_NUM_WRAP_MECHS) + return 0; ndx = (exchKeyType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex; - PORT_Memset(&myWswk, 0, sizeof myWswk); /* eliminate UMRs. */ + PORT_Memset(&myWswk, 0, sizeof myWswk); /* eliminate UMRs. */ now = LockSidCacheLock(cache->keyCacheLock, now); if (now) { - rv = getSvrWrappingKey(wswk->symWrapMechIndex, wswk->exchKeyType, - &myWswk, cache, now); - if (rv) { - /* we found it on disk, copy it out to the caller. */ - PORT_Memcpy(wswk, &myWswk, sizeof *wswk); - } else { - /* Wasn't on disk, and we're still holding the lock, so write it. */ - cache->keyCacheData[ndx] = *wswk; - } - UnlockSidCacheLock(cache->keyCacheLock); + rv = getSvrWrappingKey(wswk->symWrapMechIndex, wswk->exchKeyType, + &myWswk, cache, now); + if (rv) { + /* we found it on disk, copy it out to the caller. */ + PORT_Memcpy(wswk, &myWswk, sizeof *wswk); + } + else { + /* Wasn't on disk, and we're still holding the lock, so write it. */ + cache->keyCacheData[ndx] = *wswk; + } + UnlockSidCacheLock(cache->keyCacheLock); } return rv; } -#else /* MAC version or other platform */ +#else /* MAC version or other platform */ #include "seccomon.h" #include "cert.h" @@ -2164,67 +2152,67 @@ ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk) #include "sslimpl.h" SECStatus -SSL_ConfigServerSessionIDCache( int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory) +SSL_ConfigServerSessionIDCache(int maxCacheEntries, + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory) { - PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_ConfigServerSessionIDCache)"); + PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_ConfigServerSessionIDCache)"); return SECFailure; } SECStatus -SSL_ConfigMPServerSIDCache( int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory) +SSL_ConfigMPServerSIDCache(int maxCacheEntries, + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory) { - PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_ConfigMPServerSIDCache)"); + PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_ConfigMPServerSIDCache)"); return SECFailure; } SECStatus -SSL_InheritMPServerSIDCache(const char * envString) +SSL_InheritMPServerSIDCache(const char *envString) { - PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_InheritMPServerSIDCache)"); + PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_InheritMPServerSIDCache)"); return SECFailure; } PRBool -ssl_GetWrappingKey( PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk) +ssl_GetWrappingKey(PRInt32 symWrapMechIndex, + SSL3KEAType exchKeyType, + SSLWrappedSymWrappingKey *wswk) { PRBool rv = PR_FALSE; - PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_GetWrappingKey)"); + PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_GetWrappingKey)"); return rv; } /* This is a kind of test-and-set. The caller passes in the new value it wants * to set. This code tests the wrapped sym key entry in the shared memory. - * If it is uninitialized, this function writes the caller's value into - * the disk entry, and returns false. - * Otherwise, it overwrites the caller's wswk with the value obtained from - * the disk, and returns PR_TRUE. - * This is all done while holding the locks/mutexes necessary to make + * If it is uninitialized, this function writes the caller's value into + * the disk entry, and returns false. + * Otherwise, it overwrites the caller's wswk with the value obtained from + * the disk, and returns PR_TRUE. + * This is all done while holding the locks/mutexes necessary to make * the operation atomic. */ PRBool ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk) { - PRBool rv = PR_FALSE; + PRBool rv = PR_FALSE; PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_SetWrappingKey)"); return rv; } -PRUint32 +PRUint32 SSL_GetMaxServerCacheLocks(void) { PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_GetMaxServerCacheLocks)"); return -1; } -SECStatus +SECStatus SSL_SetMaxServerCacheLocks(PRUint32 maxLocks) { PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_SetMaxServerCacheLocks)"); diff --git a/security/nss/lib/ssl/sslsock.c b/security/nss/lib/ssl/sslsock.c index 5179060a5229..7bd6530dedc4 100644 --- a/security/nss/lib/ssl/sslsock.c +++ b/security/nss/lib/ssl/sslsock.c @@ -20,36 +20,36 @@ #include "nss.h" #include "pk11pqg.h" -#define SET_ERROR_CODE /* reminder */ +#define SET_ERROR_CODE /* reminder */ -static const sslSocketOps ssl_default_ops = { /* No SSL. */ - ssl_DefConnect, - NULL, - ssl_DefBind, - ssl_DefListen, - ssl_DefShutdown, - ssl_DefClose, - ssl_DefRecv, - ssl_DefSend, - ssl_DefRead, - ssl_DefWrite, - ssl_DefGetpeername, - ssl_DefGetsockname +static const sslSocketOps ssl_default_ops = { /* No SSL. */ + ssl_DefConnect, + NULL, + ssl_DefBind, + ssl_DefListen, + ssl_DefShutdown, + ssl_DefClose, + ssl_DefRecv, + ssl_DefSend, + ssl_DefRead, + ssl_DefWrite, + ssl_DefGetpeername, + ssl_DefGetsockname }; -static const sslSocketOps ssl_secure_ops = { /* SSL. */ - ssl_SecureConnect, - NULL, - ssl_DefBind, - ssl_DefListen, - ssl_SecureShutdown, - ssl_SecureClose, - ssl_SecureRecv, - ssl_SecureSend, - ssl_SecureRead, - ssl_SecureWrite, - ssl_DefGetpeername, - ssl_DefGetsockname +static const sslSocketOps ssl_secure_ops = { /* SSL. */ + ssl_SecureConnect, + NULL, + ssl_DefBind, + ssl_DefListen, + ssl_SecureShutdown, + ssl_SecureClose, + ssl_SecureRecv, + ssl_SecureSend, + ssl_SecureRead, + ssl_SecureWrite, + ssl_DefGetpeername, + ssl_DefGetsockname }; /* @@ -57,36 +57,38 @@ static const sslSocketOps ssl_secure_ops = { /* SSL. */ */ static sslOptions ssl_defaults = { { siBuffer, NULL, 0 }, /* nextProtoNego */ - PR_TRUE, /* useSecurity */ - PR_FALSE, /* useSocks */ - PR_FALSE, /* requestCertificate */ - 2, /* requireCertificate */ - PR_FALSE, /* handshakeAsClient */ - PR_FALSE, /* handshakeAsServer */ - PR_FALSE, /* enableSSL2 */ /* now defaults to off in NSS 3.13 */ - PR_FALSE, /* unusedBit9 */ - PR_FALSE, /* unusedBit10 */ - PR_FALSE, /* noCache */ - PR_FALSE, /* fdx */ - PR_FALSE, /* v2CompatibleHello */ /* now defaults to off in NSS 3.13 */ - PR_TRUE, /* detectRollBack */ - PR_FALSE, /* noStepDown */ - PR_FALSE, /* bypassPKCS11 */ - PR_FALSE, /* noLocks */ - PR_FALSE, /* enableSessionTickets */ - PR_FALSE, /* enableDeflate */ - 2, /* enableRenegotiation (default: requires extension) */ - PR_FALSE, /* requireSafeNegotiation */ - PR_FALSE, /* enableFalseStart */ - PR_TRUE, /* cbcRandomIV */ - PR_FALSE, /* enableOCSPStapling */ - PR_TRUE, /* enableNPN */ - PR_FALSE, /* enableALPN */ - PR_TRUE, /* reuseServerECDHEKey */ - PR_FALSE, /* enableFallbackSCSV */ - PR_TRUE, /* enableServerDhe */ - PR_FALSE, /* enableExtendedMS */ - PR_FALSE, /* enableSignedCertTimestamps */ + PR_TRUE, /* useSecurity */ + PR_FALSE, /* useSocks */ + PR_FALSE, /* requestCertificate */ + 2, /* requireCertificate */ + PR_FALSE, /* handshakeAsClient */ + PR_FALSE, /* handshakeAsServer */ + PR_FALSE, + /* enableSSL2 */ /* now defaults to off in NSS 3.13 */ + PR_FALSE, /* unusedBit9 */ + PR_FALSE, /* unusedBit10 */ + PR_FALSE, /* noCache */ + PR_FALSE, /* fdx */ + PR_FALSE, + /* v2CompatibleHello */ /* now defaults to off in NSS 3.13 */ + PR_TRUE, /* detectRollBack */ + PR_FALSE, /* noStepDown */ + PR_FALSE, /* bypassPKCS11 */ + PR_FALSE, /* noLocks */ + PR_FALSE, /* enableSessionTickets */ + PR_FALSE, /* enableDeflate */ + 2, /* enableRenegotiation (default: requires extension) */ + PR_FALSE, /* requireSafeNegotiation */ + PR_FALSE, /* enableFalseStart */ + PR_TRUE, /* cbcRandomIV */ + PR_FALSE, /* enableOCSPStapling */ + PR_TRUE, /* enableNPN */ + PR_FALSE, /* enableALPN */ + PR_TRUE, /* reuseServerECDHEKey */ + PR_FALSE, /* enableFallbackSCSV */ + PR_TRUE, /* enableServerDhe */ + PR_FALSE, /* enableExtendedMS */ + PR_FALSE, /* enableSignedCertTimestamps */ }; /* @@ -102,30 +104,30 @@ static SSLVersionRange versions_defaults_datagram = { SSL_LIBRARY_VERSION_TLS_1_2 }; -#define VERSIONS_DEFAULTS(variant) \ +#define VERSIONS_DEFAULTS(variant) \ (variant == ssl_variant_stream ? &versions_defaults_stream : \ - &versions_defaults_datagram) -#define VERSIONS_POLICY_MIN(variant) \ + &versions_defaults_datagram) +#define VERSIONS_POLICY_MIN(variant) \ (variant == ssl_variant_stream ? NSS_TLS_VERSION_MIN_POLICY : \ - NSS_DTLS_VERSION_MIN_POLICY) -#define VERSIONS_POLICY_MAX(variant) \ + NSS_DTLS_VERSION_MIN_POLICY) +#define VERSIONS_POLICY_MAX(variant) \ (variant == ssl_variant_stream ? NSS_TLS_VERSION_MAX_POLICY : \ - NSS_DTLS_VERSION_MAX_POLICY) + NSS_DTLS_VERSION_MAX_POLICY) -sslSessionIDLookupFunc ssl_sid_lookup; -sslSessionIDCacheFunc ssl_sid_cache; +sslSessionIDLookupFunc ssl_sid_lookup; +sslSessionIDCacheFunc ssl_sid_cache; sslSessionIDUncacheFunc ssl_sid_uncache; static PRBool ssl_inited = PR_FALSE; static PRDescIdentity ssl_layer_id; -PRBool locksEverDisabled; /* implicitly PR_FALSE */ -PRBool ssl_force_locks; /* implicitly PR_FALSE */ -int ssl_lock_readers = 1; /* default true. */ -char ssl_debug; -char ssl_trace; -FILE * ssl_trace_iob; -FILE * ssl_keylog_iob; +PRBool locksEverDisabled; /* implicitly PR_FALSE */ +PRBool ssl_force_locks; /* implicitly PR_FALSE */ +int ssl_lock_readers = 1; /* default true. */ +char ssl_debug; +char ssl_trace; +FILE *ssl_trace_iob; +FILE *ssl_keylog_iob; char lockStatus[] = "Locks are ENABLED. "; #define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */ @@ -138,10 +140,10 @@ static const PRUint16 srtpCiphers[] = { /* forward declarations. */ static sslSocket *ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant variant); -static SECStatus ssl_MakeLocks(sslSocket *ss); -static void ssl_SetDefaultsFromEnvironment(void); -static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, - PRDescIdentity id); +static SECStatus ssl_MakeLocks(sslSocket *ss); +static void ssl_SetDefaultsFromEnvironment(void); +static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, + PRDescIdentity id); /************************************************************************/ @@ -213,30 +215,30 @@ ssl_DupSocket(sslSocket *os) ss = ssl_NewSocket((PRBool)(!os->opt.noLocks), os->protocolVariant); if (ss) { - ss->opt = os->opt; - ss->opt.useSocks = PR_FALSE; - ss->vrange = os->vrange; + ss->opt = os->opt; + ss->opt.useSocks = PR_FALSE; + ss->vrange = os->vrange; - ss->peerID = !os->peerID ? NULL : PORT_Strdup(os->peerID); - ss->url = !os->url ? NULL : PORT_Strdup(os->url); + ss->peerID = !os->peerID ? NULL : PORT_Strdup(os->peerID); + ss->url = !os->url ? NULL : PORT_Strdup(os->url); - ss->ops = os->ops; + ss->ops = os->ops; ss->rTimeout = os->rTimeout; ss->wTimeout = os->wTimeout; ss->cTimeout = os->cTimeout; ss->dbHandle = os->dbHandle; /* copy ssl2&3 policy & prefs, even if it's not selected (yet) */ - ss->allowedByPolicy = os->allowedByPolicy; - ss->maybeAllowedByPolicy= os->maybeAllowedByPolicy; - ss->chosenPreference = os->chosenPreference; + ss->allowedByPolicy = os->allowedByPolicy; + ss->maybeAllowedByPolicy = os->maybeAllowedByPolicy; + ss->chosenPreference = os->chosenPreference; PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites); PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, os->ssl3.dtlsSRTPCiphers, sizeof(PRUint16) * os->ssl3.dtlsSRTPCipherCount); ss->ssl3.dtlsSRTPCipherCount = os->ssl3.dtlsSRTPCipherCount; PORT_Memcpy(ss->ssl3.signatureAlgorithms, os->ssl3.signatureAlgorithms, sizeof(ss->ssl3.signatureAlgorithms[0]) * - os->ssl3.signatureAlgorithmCount); + os->ssl3.signatureAlgorithmCount); ss->ssl3.signatureAlgorithmCount = os->ssl3.signatureAlgorithmCount; ss->ssl3.downgradeCheckVersion = os->ssl3.downgradeCheckVersion; @@ -250,73 +252,77 @@ ssl_DupSocket(sslSocket *os) } PORT_Memcpy(ss->ssl3.dheGroups, os->ssl3.dheGroups, sizeof(SSLDHEGroupType) * os->ssl3.numDHEGroups); - } else { + } + else { ss->ssl3.dheGroups = NULL; } if (os->cipherSpecs) { - ss->cipherSpecs = (unsigned char*)PORT_Alloc(os->sizeCipherSpecs); + ss->cipherSpecs = (unsigned char *)PORT_Alloc(os->sizeCipherSpecs); if (ss->cipherSpecs) PORT_Memcpy(ss->cipherSpecs, os->cipherSpecs, os->sizeCipherSpecs); - ss->sizeCipherSpecs = os->sizeCipherSpecs; - ss->preferredCipher = os->preferredCipher; - } else { - ss->cipherSpecs = NULL; /* produced lazily */ - ss->sizeCipherSpecs = 0; - ss->preferredCipher = NULL; + ss->sizeCipherSpecs = os->sizeCipherSpecs; + ss->preferredCipher = os->preferredCipher; + } + else { + ss->cipherSpecs = NULL; /* produced lazily */ + ss->sizeCipherSpecs = 0; + ss->preferredCipher = NULL; } if (ss->opt.useSecurity) { /* This int should be SSLKEAType, but CC on Irix complains, * during the for loop. */ int i; - sslServerCerts * oc = os->serverCerts; - sslServerCerts * sc = ss->serverCerts; + sslServerCerts *oc = os->serverCerts; + sslServerCerts *sc = ss->serverCerts; - for (i=kt_null; i < kt_kea_size; i++, oc++, sc++) { + for (i = kt_null; i < kt_kea_size; i++, oc++, sc++) { if (oc->serverCert && oc->serverCertChain) { - sc->serverCert = CERT_DupCertificate(oc->serverCert); + sc->serverCert = CERT_DupCertificate(oc->serverCert); sc->serverCertChain = CERT_DupCertList(oc->serverCertChain); if (!sc->serverCertChain) goto loser; - } else { - sc->serverCert = NULL; + } + else { + sc->serverCert = NULL; sc->serverCertChain = NULL; } sc->serverKeyPair = oc->serverKeyPair ? - ssl3_GetKeyPairRef(oc->serverKeyPair) : NULL; + ssl3_GetKeyPairRef(oc->serverKeyPair) + : NULL; if (oc->serverKeyPair && !sc->serverKeyPair) goto loser; sc->serverKeyBits = oc->serverKeyBits; ss->certStatusArray[i] = !os->certStatusArray[i] ? NULL : - SECITEM_DupArray(NULL, os->certStatusArray[i]); + SECITEM_DupArray(NULL, os->certStatusArray[i]); } ss->stepDownKeyPair = !os->stepDownKeyPair ? NULL : - ssl3_GetKeyPairRef(os->stepDownKeyPair); + ssl3_GetKeyPairRef(os->stepDownKeyPair); ss->ephemeralECDHKeyPair = !os->ephemeralECDHKeyPair ? NULL : - ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair); + ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair); ss->dheKeyPair = !os->dheKeyPair ? NULL : - ssl3_GetKeyPairRef(os->dheKeyPair); + ssl3_GetKeyPairRef(os->dheKeyPair); ss->dheParams = os->dheParams; -/* - * XXX the preceding CERT_ and SECKEY_ functions can fail and return NULL. - * XXX We should detect this, and not just march on with NULL pointers. - */ - ss->authCertificate = os->authCertificate; - ss->authCertificateArg = os->authCertificateArg; - ss->getClientAuthData = os->getClientAuthData; - ss->getClientAuthDataArg = os->getClientAuthDataArg; - ss->sniSocketConfig = os->sniSocketConfig; - ss->sniSocketConfigArg = os->sniSocketConfigArg; - ss->handleBadCert = os->handleBadCert; - ss->badCertArg = os->badCertArg; - ss->handshakeCallback = os->handshakeCallback; + /* + * XXX the preceding CERT_ and SECKEY_ functions can fail and return NULL. + * XXX We should detect this, and not just march on with NULL pointers. + */ + ss->authCertificate = os->authCertificate; + ss->authCertificateArg = os->authCertificateArg; + ss->getClientAuthData = os->getClientAuthData; + ss->getClientAuthDataArg = os->getClientAuthDataArg; + ss->sniSocketConfig = os->sniSocketConfig; + ss->sniSocketConfigArg = os->sniSocketConfigArg; + ss->handleBadCert = os->handleBadCert; + ss->badCertArg = os->badCertArg; + ss->handshakeCallback = os->handshakeCallback; ss->handshakeCallbackData = os->handshakeCallbackData; ss->canFalseStartCallback = os->canFalseStartCallback; ss->canFalseStartCallbackData = os->canFalseStartCallbackData; - ss->pkcs11PinArg = os->pkcs11PinArg; + ss->pkcs11PinArg = os->pkcs11PinArg; /* Create security data */ rv = ssl_CopySecurityInfo(ss, os); @@ -374,7 +380,7 @@ ssl_DestroySocketContents(sslSocket *ss) /* "i" should be of type SSLKEAType, but CC on IRIX complains during * the for loop. */ - int i; + int i; /* Free up socket */ ssl_DestroySecurityInfo(&ss->sec); @@ -388,16 +394,16 @@ ssl_DestroySocketContents(sslSocket *ss) if (ss->peerID != NULL) PORT_Free(ss->peerID); if (ss->url != NULL) - PORT_Free((void *)ss->url); /* CONST */ + PORT_Free((void *)ss->url); /* CONST */ if (ss->cipherSpecs) { PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; + ss->cipherSpecs = NULL; ss->sizeCipherSpecs = 0; } /* Clean up server configuration */ - for (i=kt_null; i < kt_kea_size; i++) { - sslServerCerts * sc = ss->serverCerts + i; + for (i = kt_null; i < kt_kea_size; i++) { + sslServerCerts *sc = ss->serverCerts + i; if (sc->serverCert != NULL) CERT_DestroyCertificate(sc->serverCert); if (sc->serverCertChain != NULL) @@ -437,11 +443,11 @@ ssl_DestroySocketContents(sslSocket *ss) void ssl_FreeSocket(sslSocket *ss) { -/* Get every lock you can imagine! -** Caller already holds these: -** SSL_LOCK_READER(ss); -** SSL_LOCK_WRITER(ss); -*/ + /* Get every lock you can imagine! + ** Caller already holds these: + ** SSL_LOCK_READER(ss); + ** SSL_LOCK_WRITER(ss); + */ ssl_Get1stHandshakeLock(ss); ssl_GetRecvBufLock(ss); ssl_GetSSL3HandshakeLock(ss); @@ -472,16 +478,17 @@ ssl_FreeSocket(sslSocket *ss) SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled) { - PRFileDesc * osfd = ss->fd->lower; - SECStatus rv = SECFailure; + PRFileDesc *osfd = ss->fd->lower; + SECStatus rv = SECFailure; PRSocketOptionData opt; - opt.option = PR_SockOpt_NoDelay; + opt.option = PR_SockOpt_NoDelay; opt.value.no_delay = (PRBool)!enabled; if (osfd->methods->setsocketoption) { - rv = (SECStatus) osfd->methods->setsocketoption(osfd, &opt); - } else { + rv = (SECStatus)osfd->methods->setsocketoption(osfd, &opt); + } + else { PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); } @@ -498,7 +505,7 @@ ssl_ChooseOps(sslSocket *ss) static SECStatus PrepareSocket(sslSocket *ss) { - SECStatus rv = SECSuccess; + SECStatus rv = SECSuccess; ssl_ChooseOps(ss); return rv; @@ -514,7 +521,8 @@ SSL_Enable(PRFileDesc *fd, int which, PRBool on) static const PRCallOnceType pristineCallOnce; static PRCallOnceType setupBypassOnce; -static SECStatus SSL_BypassShutdown(void* appData, void* nssData) +static SECStatus +SSL_BypassShutdown(void *appData, void *nssData) { /* unload freeBL shared library from memory */ BL_Unload(); @@ -522,7 +530,8 @@ static SECStatus SSL_BypassShutdown(void* appData, void* nssData) return SECSuccess; } -static PRStatus SSL_BypassRegisterShutdown(void) +static PRStatus +SSL_BypassRegisterShutdown(void) { SECStatus rv = NSS_RegisterShutdown(SSL_BypassShutdown, NULL); PORT_Assert(SECSuccess == rv); @@ -530,7 +539,8 @@ static PRStatus SSL_BypassRegisterShutdown(void) } #endif -static PRStatus SSL_BypassSetup(void) +static PRStatus +SSL_BypassSetup(void) { #ifdef NO_PKCS11_BYPASS /* Guarantee binary compatibility */ @@ -541,7 +551,7 @@ static PRStatus SSL_BypassSetup(void) } static PRBool ssl_VersionIsSupportedByPolicy( - SSLProtocolVariant protocolVariant, SSL3ProtocolVersion version); + SSLProtocolVariant protocolVariant, SSL3ProtocolVersion version); /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_TLS, on) described in * ssl.h in the section "SSL version range setting API". @@ -549,13 +559,13 @@ static PRBool ssl_VersionIsSupportedByPolicy( static void ssl_EnableTLS(SSLVersionRange *vrange, PRBool on) { - if (on) { + if (on) { /* don't turn it on if tls1.0 disallowed by by policy */ if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, SSL_LIBRARY_VERSION_TLS_1_0)) { return; } - } + } if (SSL3_ALL_VERSIONS_DISABLED(vrange)) { if (on) { vrange->min = SSL_LIBRARY_VERSION_TLS_1_0; @@ -568,11 +578,13 @@ ssl_EnableTLS(SSLVersionRange *vrange, PRBool on) /* Expand the range of enabled version to include TLS 1.0 */ vrange->min = PR_MIN(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0); vrange->max = PR_MAX(vrange->max, SSL_LIBRARY_VERSION_TLS_1_0); - } else { + } + else { /* Disable all TLS versions, leaving only SSL 3.0 if it was enabled */ if (vrange->min == SSL_LIBRARY_VERSION_3_0) { vrange->max = SSL_LIBRARY_VERSION_3_0; - } else { + } + else { /* Only TLS was enabled, so now no versions are. */ vrange->min = SSL_LIBRARY_VERSION_NONE; vrange->max = SSL_LIBRARY_VERSION_NONE; @@ -586,14 +598,14 @@ ssl_EnableTLS(SSLVersionRange *vrange, PRBool on) static void ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on) { - if (on) { + if (on) { /* don't turn it on if ssl3 disallowed by by policy */ if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, SSL_LIBRARY_VERSION_3_0)) { return; } - } - if (SSL3_ALL_VERSIONS_DISABLED(vrange)) { + } + if (SSL3_ALL_VERSIONS_DISABLED(vrange)) { if (on) { vrange->min = SSL_LIBRARY_VERSION_3_0; vrange->max = SSL_LIBRARY_VERSION_3_0; @@ -601,17 +613,19 @@ ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on) return; } - if (on) { + if (on) { /* Expand the range of enabled versions to include SSL 3.0. We know * SSL 3.0 or some version of TLS is already enabled at this point, so * we don't need to change vrange->max. */ vrange->min = SSL_LIBRARY_VERSION_3_0; - } else { + } + else { /* Disable SSL 3.0, leaving TLS unaffected. */ if (vrange->max > SSL_LIBRARY_VERSION_3_0) { vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0); - } else { + } + else { /* Only SSL 3.0 was enabled, so now no versions are. */ vrange->min = SSL_LIBRARY_VERSION_NONE; vrange->max = SSL_LIBRARY_VERSION_NONE; @@ -623,8 +637,8 @@ SECStatus SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on) { sslSocket *ss = ssl_FindSocket(fd); - SECStatus rv = SECSuccess; - PRBool holdingLocks; + SECStatus rv = SECSuccess; + PRBool holdingLocks; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd)); @@ -636,242 +650,246 @@ SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on) ssl_GetSSL3HandshakeLock(ss); switch (which) { - case SSL_SOCKS: - ss->opt.useSocks = PR_FALSE; - rv = PrepareSocket(ss); - if (on) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } - break; - - case SSL_SECURITY: - ss->opt.useSecurity = on; - rv = PrepareSocket(ss); - break; - - case SSL_REQUEST_CERTIFICATE: - ss->opt.requestCertificate = on; - break; - - case SSL_REQUIRE_CERTIFICATE: - ss->opt.requireCertificate = on; - break; - - case SSL_HANDSHAKE_AS_CLIENT: - if ( ss->opt.handshakeAsServer && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - break; - } - ss->opt.handshakeAsClient = on; - break; - - case SSL_HANDSHAKE_AS_SERVER: - if ( ss->opt.handshakeAsClient && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - break; - } - ss->opt.handshakeAsServer = on; - break; - - case SSL_ENABLE_TLS: - if (IS_DTLS(ss)) { + case SSL_SOCKS: + ss->opt.useSocks = PR_FALSE; + rv = PrepareSocket(ss); if (on) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ + rv = SECFailure; } break; - } - ssl_EnableTLS(&ss->vrange, on); - ss->preferredCipher = NULL; - if (ss->cipherSpecs) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } - break; - case SSL_ENABLE_SSL3: - if (IS_DTLS(ss)) { - if (on) { + case SSL_SECURITY: + ss->opt.useSecurity = on; + rv = PrepareSocket(ss); + break; + + case SSL_REQUEST_CERTIFICATE: + ss->opt.requestCertificate = on; + break; + + case SSL_REQUIRE_CERTIFICATE: + ss->opt.requireCertificate = on; + break; + + case SSL_HANDSHAKE_AS_CLIENT: + if (ss->opt.handshakeAsServer && on) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ + rv = SECFailure; + break; } + ss->opt.handshakeAsClient = on; break; - } - ssl_EnableSSL3(&ss->vrange, on); - ss->preferredCipher = NULL; - if (ss->cipherSpecs) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } - break; - case SSL_ENABLE_SSL2: - if (IS_DTLS(ss)) { - if (on) { + case SSL_HANDSHAKE_AS_SERVER: + if (ss->opt.handshakeAsClient && on) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ + rv = SECFailure; + break; } + ss->opt.handshakeAsServer = on; break; - } - if (on) { - /* don't turn it on if ssl2 disallowed by by policy */ - if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, - SSL_LIBRARY_VERSION_2)) { - break; - } - } - ss->opt.enableSSL2 = on; - if (on) { - ss->opt.v2CompatibleHello = on; - } - ss->preferredCipher = NULL; - if (ss->cipherSpecs) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } - break; - case SSL_NO_CACHE: - ss->opt.noCache = on; - break; - - case SSL_ENABLE_FDX: - if (on && ss->opt.noLocks) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } - ss->opt.fdx = on; - break; - - case SSL_V2_COMPATIBLE_HELLO: - if (IS_DTLS(ss)) { - if (on) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ - } - break; - } - ss->opt.v2CompatibleHello = on; - if (!on) { - ss->opt.enableSSL2 = on; - } - break; - - case SSL_ROLLBACK_DETECTION: - ss->opt.detectRollBack = on; - break; - - case SSL_NO_STEP_DOWN: - ss->opt.noStepDown = on; - if (on) - SSL_DisableExportCipherSuites(fd); - break; - - case SSL_BYPASS_PKCS11: - if (ss->handshakeBegun) { - PORT_SetError(PR_INVALID_STATE_ERROR); - rv = SECFailure; - } else { - if (PR_FALSE != on) { - if (PR_SUCCESS == SSL_BypassSetup() ) { -#ifdef NO_PKCS11_BYPASS - ss->opt.bypassPKCS11 = PR_FALSE; -#else - ss->opt.bypassPKCS11 = on; -#endif - } else { - rv = SECFailure; + case SSL_ENABLE_TLS: + if (IS_DTLS(ss)) { + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; /* not allowed */ } - } else { - ss->opt.bypassPKCS11 = PR_FALSE; + break; } - } - break; + ssl_EnableTLS(&ss->vrange, on); + ss->preferredCipher = NULL; + if (ss->cipherSpecs) { + PORT_Free(ss->cipherSpecs); + ss->cipherSpecs = NULL; + ss->sizeCipherSpecs = 0; + } + break; - case SSL_NO_LOCKS: - if (on && ss->opt.fdx) { + case SSL_ENABLE_SSL3: + if (IS_DTLS(ss)) { + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; /* not allowed */ + } + break; + } + ssl_EnableSSL3(&ss->vrange, on); + ss->preferredCipher = NULL; + if (ss->cipherSpecs) { + PORT_Free(ss->cipherSpecs); + ss->cipherSpecs = NULL; + ss->sizeCipherSpecs = 0; + } + break; + + case SSL_ENABLE_SSL2: + if (IS_DTLS(ss)) { + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; /* not allowed */ + } + break; + } + if (on) { + /* don't turn it on if ssl2 disallowed by by policy */ + if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, + SSL_LIBRARY_VERSION_2)) { + break; + } + } + ss->opt.enableSSL2 = on; + if (on) { + ss->opt.v2CompatibleHello = on; + } + ss->preferredCipher = NULL; + if (ss->cipherSpecs) { + PORT_Free(ss->cipherSpecs); + ss->cipherSpecs = NULL; + ss->sizeCipherSpecs = 0; + } + break; + + case SSL_NO_CACHE: + ss->opt.noCache = on; + break; + + case SSL_ENABLE_FDX: + if (on && ss->opt.noLocks) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + } + ss->opt.fdx = on; + break; + + case SSL_V2_COMPATIBLE_HELLO: + if (IS_DTLS(ss)) { + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; /* not allowed */ + } + break; + } + ss->opt.v2CompatibleHello = on; + if (!on) { + ss->opt.enableSSL2 = on; + } + break; + + case SSL_ROLLBACK_DETECTION: + ss->opt.detectRollBack = on; + break; + + case SSL_NO_STEP_DOWN: + ss->opt.noStepDown = on; + if (on) + SSL_DisableExportCipherSuites(fd); + break; + + case SSL_BYPASS_PKCS11: + if (ss->handshakeBegun) { + PORT_SetError(PR_INVALID_STATE_ERROR); + rv = SECFailure; + } + else { + if (PR_FALSE != on) { + if (PR_SUCCESS == SSL_BypassSetup()) { +#ifdef NO_PKCS11_BYPASS + ss->opt.bypassPKCS11 = PR_FALSE; +#else + ss->opt.bypassPKCS11 = on; +#endif + } + else { + rv = SECFailure; + } + } + else { + ss->opt.bypassPKCS11 = PR_FALSE; + } + } + break; + + case SSL_NO_LOCKS: + if (on && ss->opt.fdx) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + } + if (on && ssl_force_locks) + on = PR_FALSE; /* silent override */ + ss->opt.noLocks = on; + if (on) { + locksEverDisabled = PR_TRUE; + strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); + } + else if (!holdingLocks) { + rv = ssl_MakeLocks(ss); + if (rv != SECSuccess) { + ss->opt.noLocks = PR_TRUE; + } + } + break; + + case SSL_ENABLE_SESSION_TICKETS: + ss->opt.enableSessionTickets = on; + break; + + case SSL_ENABLE_DEFLATE: + ss->opt.enableDeflate = on; + break; + + case SSL_ENABLE_RENEGOTIATION: + ss->opt.enableRenegotiation = on; + break; + + case SSL_REQUIRE_SAFE_NEGOTIATION: + ss->opt.requireSafeNegotiation = on; + break; + + case SSL_ENABLE_FALSE_START: + ss->opt.enableFalseStart = on; + break; + + case SSL_CBC_RANDOM_IV: + ss->opt.cbcRandomIV = on; + break; + + case SSL_ENABLE_OCSP_STAPLING: + ss->opt.enableOCSPStapling = on; + break; + + case SSL_ENABLE_NPN: + ss->opt.enableNPN = on; + break; + + case SSL_ENABLE_ALPN: + ss->opt.enableALPN = on; + break; + + case SSL_REUSE_SERVER_ECDHE_KEY: + ss->opt.reuseServerECDHEKey = on; + break; + + case SSL_ENABLE_FALLBACK_SCSV: + ss->opt.enableFallbackSCSV = on; + break; + + case SSL_ENABLE_SERVER_DHE: + ss->opt.enableServerDhe = on; + break; + + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + ss->opt.enableExtendedMS = on; + break; + + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + ss->opt.enableSignedCertTimestamps = on; + break; + + default: PORT_SetError(SEC_ERROR_INVALID_ARGS); rv = SECFailure; - } - if (on && ssl_force_locks) - on = PR_FALSE; /* silent override */ - ss->opt.noLocks = on; - if (on) { - locksEverDisabled = PR_TRUE; - strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); - } else if (!holdingLocks) { - rv = ssl_MakeLocks(ss); - if (rv != SECSuccess) { - ss->opt.noLocks = PR_TRUE; - } - } - break; - - case SSL_ENABLE_SESSION_TICKETS: - ss->opt.enableSessionTickets = on; - break; - - case SSL_ENABLE_DEFLATE: - ss->opt.enableDeflate = on; - break; - - case SSL_ENABLE_RENEGOTIATION: - ss->opt.enableRenegotiation = on; - break; - - case SSL_REQUIRE_SAFE_NEGOTIATION: - ss->opt.requireSafeNegotiation = on; - break; - - case SSL_ENABLE_FALSE_START: - ss->opt.enableFalseStart = on; - break; - - case SSL_CBC_RANDOM_IV: - ss->opt.cbcRandomIV = on; - break; - - case SSL_ENABLE_OCSP_STAPLING: - ss->opt.enableOCSPStapling = on; - break; - - case SSL_ENABLE_NPN: - ss->opt.enableNPN = on; - break; - - case SSL_ENABLE_ALPN: - ss->opt.enableALPN = on; - break; - - case SSL_REUSE_SERVER_ECDHE_KEY: - ss->opt.reuseServerECDHEKey = on; - break; - - case SSL_ENABLE_FALLBACK_SCSV: - ss->opt.enableFallbackSCSV = on; - break; - - case SSL_ENABLE_SERVER_DHE: - ss->opt.enableServerDhe = on; - break; - - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - ss->opt.enableExtendedMS = on; - break; - - case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: - ss->opt.enableSignedCertTimestamps = on; - break; - - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; } /* We can't use the macros for releasing the locks here, @@ -891,8 +909,8 @@ SECStatus SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn) { sslSocket *ss = ssl_FindSocket(fd); - SECStatus rv = SECSuccess; - PRBool on = PR_FALSE; + SECStatus rv = SECSuccess; + PRBool on = PR_FALSE; if (!pOn) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -908,52 +926,100 @@ SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn) ssl_GetSSL3HandshakeLock(ss); switch (which) { - case SSL_SOCKS: on = PR_FALSE; break; - case SSL_SECURITY: on = ss->opt.useSecurity; break; - case SSL_REQUEST_CERTIFICATE: on = ss->opt.requestCertificate; break; - case SSL_REQUIRE_CERTIFICATE: on = ss->opt.requireCertificate; break; - case SSL_HANDSHAKE_AS_CLIENT: on = ss->opt.handshakeAsClient; break; - case SSL_HANDSHAKE_AS_SERVER: on = ss->opt.handshakeAsServer; break; - case SSL_ENABLE_TLS: - on = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0; - break; - case SSL_ENABLE_SSL3: - on = ss->vrange.min == SSL_LIBRARY_VERSION_3_0; - break; - case SSL_ENABLE_SSL2: on = ss->opt.enableSSL2; break; - case SSL_NO_CACHE: on = ss->opt.noCache; break; - case SSL_ENABLE_FDX: on = ss->opt.fdx; break; - case SSL_V2_COMPATIBLE_HELLO: on = ss->opt.v2CompatibleHello; break; - case SSL_ROLLBACK_DETECTION: on = ss->opt.detectRollBack; break; - case SSL_NO_STEP_DOWN: on = ss->opt.noStepDown; break; - case SSL_BYPASS_PKCS11: on = ss->opt.bypassPKCS11; break; - case SSL_NO_LOCKS: on = ss->opt.noLocks; break; - case SSL_ENABLE_SESSION_TICKETS: - on = ss->opt.enableSessionTickets; - break; - case SSL_ENABLE_DEFLATE: on = ss->opt.enableDeflate; break; - case SSL_ENABLE_RENEGOTIATION: - on = ss->opt.enableRenegotiation; break; - case SSL_REQUIRE_SAFE_NEGOTIATION: - on = ss->opt.requireSafeNegotiation; break; - case SSL_ENABLE_FALSE_START: on = ss->opt.enableFalseStart; break; - case SSL_CBC_RANDOM_IV: on = ss->opt.cbcRandomIV; break; - case SSL_ENABLE_OCSP_STAPLING: on = ss->opt.enableOCSPStapling; break; - case SSL_ENABLE_NPN: on = ss->opt.enableNPN; break; - case SSL_ENABLE_ALPN: on = ss->opt.enableALPN; break; - case SSL_REUSE_SERVER_ECDHE_KEY: - on = ss->opt.reuseServerECDHEKey; break; - case SSL_ENABLE_FALLBACK_SCSV: on = ss->opt.enableFallbackSCSV; break; - case SSL_ENABLE_SERVER_DHE: on = ss->opt.enableServerDhe; break; - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - on = ss->opt.enableExtendedMS; break; - case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: - on = ss->opt.enableSignedCertTimestamps; - break; + case SSL_SOCKS: + on = PR_FALSE; + break; + case SSL_SECURITY: + on = ss->opt.useSecurity; + break; + case SSL_REQUEST_CERTIFICATE: + on = ss->opt.requestCertificate; + break; + case SSL_REQUIRE_CERTIFICATE: + on = ss->opt.requireCertificate; + break; + case SSL_HANDSHAKE_AS_CLIENT: + on = ss->opt.handshakeAsClient; + break; + case SSL_HANDSHAKE_AS_SERVER: + on = ss->opt.handshakeAsServer; + break; + case SSL_ENABLE_TLS: + on = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0; + break; + case SSL_ENABLE_SSL3: + on = ss->vrange.min == SSL_LIBRARY_VERSION_3_0; + break; + case SSL_ENABLE_SSL2: + on = ss->opt.enableSSL2; + break; + case SSL_NO_CACHE: + on = ss->opt.noCache; + break; + case SSL_ENABLE_FDX: + on = ss->opt.fdx; + break; + case SSL_V2_COMPATIBLE_HELLO: + on = ss->opt.v2CompatibleHello; + break; + case SSL_ROLLBACK_DETECTION: + on = ss->opt.detectRollBack; + break; + case SSL_NO_STEP_DOWN: + on = ss->opt.noStepDown; + break; + case SSL_BYPASS_PKCS11: + on = ss->opt.bypassPKCS11; + break; + case SSL_NO_LOCKS: + on = ss->opt.noLocks; + break; + case SSL_ENABLE_SESSION_TICKETS: + on = ss->opt.enableSessionTickets; + break; + case SSL_ENABLE_DEFLATE: + on = ss->opt.enableDeflate; + break; + case SSL_ENABLE_RENEGOTIATION: + on = ss->opt.enableRenegotiation; + break; + case SSL_REQUIRE_SAFE_NEGOTIATION: + on = ss->opt.requireSafeNegotiation; + break; + case SSL_ENABLE_FALSE_START: + on = ss->opt.enableFalseStart; + break; + case SSL_CBC_RANDOM_IV: + on = ss->opt.cbcRandomIV; + break; + case SSL_ENABLE_OCSP_STAPLING: + on = ss->opt.enableOCSPStapling; + break; + case SSL_ENABLE_NPN: + on = ss->opt.enableNPN; + break; + case SSL_ENABLE_ALPN: + on = ss->opt.enableALPN; + break; + case SSL_REUSE_SERVER_ECDHE_KEY: + on = ss->opt.reuseServerECDHEKey; + break; + case SSL_ENABLE_FALLBACK_SCSV: + on = ss->opt.enableFallbackSCSV; + break; + case SSL_ENABLE_SERVER_DHE: + on = ss->opt.enableServerDhe; + break; + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + on = ss->opt.enableExtendedMS; + break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + on = ss->opt.enableSignedCertTimestamps; + break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; } ssl_ReleaseSSL3HandshakeLock(ss); @@ -966,8 +1032,8 @@ SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn) SECStatus SSL_OptionGetDefault(PRInt32 which, PRBool *pOn) { - SECStatus rv = SECSuccess; - PRBool on = PR_FALSE; + SECStatus rv = SECSuccess; + PRBool on = PR_FALSE; if (!pOn) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -977,61 +1043,100 @@ SSL_OptionGetDefault(PRInt32 which, PRBool *pOn) ssl_SetDefaultsFromEnvironment(); switch (which) { - case SSL_SOCKS: on = PR_FALSE; break; - case SSL_SECURITY: on = ssl_defaults.useSecurity; break; - case SSL_REQUEST_CERTIFICATE: on = ssl_defaults.requestCertificate; break; - case SSL_REQUIRE_CERTIFICATE: on = ssl_defaults.requireCertificate; break; - case SSL_HANDSHAKE_AS_CLIENT: on = ssl_defaults.handshakeAsClient; break; - case SSL_HANDSHAKE_AS_SERVER: on = ssl_defaults.handshakeAsServer; break; - case SSL_ENABLE_TLS: - on = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0; - break; - case SSL_ENABLE_SSL3: - on = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0; - break; - case SSL_ENABLE_SSL2: on = ssl_defaults.enableSSL2; break; - case SSL_NO_CACHE: on = ssl_defaults.noCache; break; - case SSL_ENABLE_FDX: on = ssl_defaults.fdx; break; - case SSL_V2_COMPATIBLE_HELLO: on = ssl_defaults.v2CompatibleHello; break; - case SSL_ROLLBACK_DETECTION: on = ssl_defaults.detectRollBack; break; - case SSL_NO_STEP_DOWN: on = ssl_defaults.noStepDown; break; - case SSL_BYPASS_PKCS11: on = ssl_defaults.bypassPKCS11; break; - case SSL_NO_LOCKS: on = ssl_defaults.noLocks; break; - case SSL_ENABLE_SESSION_TICKETS: - on = ssl_defaults.enableSessionTickets; - break; - case SSL_ENABLE_DEFLATE: on = ssl_defaults.enableDeflate; break; - case SSL_ENABLE_RENEGOTIATION: - on = ssl_defaults.enableRenegotiation; break; - case SSL_REQUIRE_SAFE_NEGOTIATION: - on = ssl_defaults.requireSafeNegotiation; - break; - case SSL_ENABLE_FALSE_START: on = ssl_defaults.enableFalseStart; break; - case SSL_CBC_RANDOM_IV: on = ssl_defaults.cbcRandomIV; break; - case SSL_ENABLE_OCSP_STAPLING: - on = ssl_defaults.enableOCSPStapling; - break; - case SSL_ENABLE_NPN: on = ssl_defaults.enableNPN; break; - case SSL_ENABLE_ALPN: on = ssl_defaults.enableALPN; break; - case SSL_REUSE_SERVER_ECDHE_KEY: - on = ssl_defaults.reuseServerECDHEKey; - break; - case SSL_ENABLE_FALLBACK_SCSV: - on = ssl_defaults.enableFallbackSCSV; - break; - case SSL_ENABLE_SERVER_DHE: - on = ssl_defaults.enableServerDhe; - break; - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - on = ssl_defaults.enableExtendedMS; - break; - case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: - on = ssl_defaults.enableSignedCertTimestamps; - break; + case SSL_SOCKS: + on = PR_FALSE; + break; + case SSL_SECURITY: + on = ssl_defaults.useSecurity; + break; + case SSL_REQUEST_CERTIFICATE: + on = ssl_defaults.requestCertificate; + break; + case SSL_REQUIRE_CERTIFICATE: + on = ssl_defaults.requireCertificate; + break; + case SSL_HANDSHAKE_AS_CLIENT: + on = ssl_defaults.handshakeAsClient; + break; + case SSL_HANDSHAKE_AS_SERVER: + on = ssl_defaults.handshakeAsServer; + break; + case SSL_ENABLE_TLS: + on = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0; + break; + case SSL_ENABLE_SSL3: + on = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0; + break; + case SSL_ENABLE_SSL2: + on = ssl_defaults.enableSSL2; + break; + case SSL_NO_CACHE: + on = ssl_defaults.noCache; + break; + case SSL_ENABLE_FDX: + on = ssl_defaults.fdx; + break; + case SSL_V2_COMPATIBLE_HELLO: + on = ssl_defaults.v2CompatibleHello; + break; + case SSL_ROLLBACK_DETECTION: + on = ssl_defaults.detectRollBack; + break; + case SSL_NO_STEP_DOWN: + on = ssl_defaults.noStepDown; + break; + case SSL_BYPASS_PKCS11: + on = ssl_defaults.bypassPKCS11; + break; + case SSL_NO_LOCKS: + on = ssl_defaults.noLocks; + break; + case SSL_ENABLE_SESSION_TICKETS: + on = ssl_defaults.enableSessionTickets; + break; + case SSL_ENABLE_DEFLATE: + on = ssl_defaults.enableDeflate; + break; + case SSL_ENABLE_RENEGOTIATION: + on = ssl_defaults.enableRenegotiation; + break; + case SSL_REQUIRE_SAFE_NEGOTIATION: + on = ssl_defaults.requireSafeNegotiation; + break; + case SSL_ENABLE_FALSE_START: + on = ssl_defaults.enableFalseStart; + break; + case SSL_CBC_RANDOM_IV: + on = ssl_defaults.cbcRandomIV; + break; + case SSL_ENABLE_OCSP_STAPLING: + on = ssl_defaults.enableOCSPStapling; + break; + case SSL_ENABLE_NPN: + on = ssl_defaults.enableNPN; + break; + case SSL_ENABLE_ALPN: + on = ssl_defaults.enableALPN; + break; + case SSL_REUSE_SERVER_ECDHE_KEY: + on = ssl_defaults.reuseServerECDHEKey; + break; + case SSL_ENABLE_FALLBACK_SCSV: + on = ssl_defaults.enableFallbackSCSV; + break; + case SSL_ENABLE_SERVER_DHE: + on = ssl_defaults.enableServerDhe; + break; + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + on = ssl_defaults.enableExtendedMS; + break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + on = ssl_defaults.enableSignedCertTimestamps; + break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; } *pOn = on; @@ -1057,182 +1162,184 @@ SSL_OptionSetDefault(PRInt32 which, PRBool on) ssl_SetDefaultsFromEnvironment(); switch (which) { - case SSL_SOCKS: - ssl_defaults.useSocks = PR_FALSE; - if (on) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - break; - - case SSL_SECURITY: - ssl_defaults.useSecurity = on; - break; - - case SSL_REQUEST_CERTIFICATE: - ssl_defaults.requestCertificate = on; - break; - - case SSL_REQUIRE_CERTIFICATE: - ssl_defaults.requireCertificate = on; - break; - - case SSL_HANDSHAKE_AS_CLIENT: - if ( ssl_defaults.handshakeAsServer && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - ssl_defaults.handshakeAsClient = on; - break; - - case SSL_HANDSHAKE_AS_SERVER: - if ( ssl_defaults.handshakeAsClient && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - ssl_defaults.handshakeAsServer = on; - break; - - case SSL_ENABLE_TLS: - ssl_EnableTLS(&versions_defaults_stream, on); - break; - - case SSL_ENABLE_SSL3: - ssl_EnableSSL3(&versions_defaults_stream, on); - break; - - case SSL_ENABLE_SSL2: - if (on) { - /* don't turn it on if ssl2 disallowed by by policy */ - if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, - SSL_LIBRARY_VERSION_2)) { - break; - } - } - ssl_defaults.enableSSL2 = on; - if (on) { - ssl_defaults.v2CompatibleHello = on; - } - break; - - case SSL_NO_CACHE: - ssl_defaults.noCache = on; - break; - - case SSL_ENABLE_FDX: - if (on && ssl_defaults.noLocks) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - ssl_defaults.fdx = on; - break; - - case SSL_V2_COMPATIBLE_HELLO: - ssl_defaults.v2CompatibleHello = on; - if (!on) { - ssl_defaults.enableSSL2 = on; - } - break; - - case SSL_ROLLBACK_DETECTION: - ssl_defaults.detectRollBack = on; - break; - - case SSL_NO_STEP_DOWN: - ssl_defaults.noStepDown = on; - if (on) - SSL_DisableDefaultExportCipherSuites(); - break; - - case SSL_BYPASS_PKCS11: - if (PR_FALSE != on) { - if (PR_SUCCESS == SSL_BypassSetup()) { -#ifdef NO_PKCS11_BYPASS - ssl_defaults.bypassPKCS11 = PR_FALSE; -#else - ssl_defaults.bypassPKCS11 = on; -#endif - } else { + case SSL_SOCKS: + ssl_defaults.useSocks = PR_FALSE; + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - } else { - ssl_defaults.bypassPKCS11 = PR_FALSE; - } - break; + break; - case SSL_NO_LOCKS: - if (on && ssl_defaults.fdx) { + case SSL_SECURITY: + ssl_defaults.useSecurity = on; + break; + + case SSL_REQUEST_CERTIFICATE: + ssl_defaults.requestCertificate = on; + break; + + case SSL_REQUIRE_CERTIFICATE: + ssl_defaults.requireCertificate = on; + break; + + case SSL_HANDSHAKE_AS_CLIENT: + if (ssl_defaults.handshakeAsServer && on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + ssl_defaults.handshakeAsClient = on; + break; + + case SSL_HANDSHAKE_AS_SERVER: + if (ssl_defaults.handshakeAsClient && on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + ssl_defaults.handshakeAsServer = on; + break; + + case SSL_ENABLE_TLS: + ssl_EnableTLS(&versions_defaults_stream, on); + break; + + case SSL_ENABLE_SSL3: + ssl_EnableSSL3(&versions_defaults_stream, on); + break; + + case SSL_ENABLE_SSL2: + if (on) { + /* don't turn it on if ssl2 disallowed by by policy */ + if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream, + SSL_LIBRARY_VERSION_2)) { + break; + } + } + ssl_defaults.enableSSL2 = on; + if (on) { + ssl_defaults.v2CompatibleHello = on; + } + break; + + case SSL_NO_CACHE: + ssl_defaults.noCache = on; + break; + + case SSL_ENABLE_FDX: + if (on && ssl_defaults.noLocks) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + ssl_defaults.fdx = on; + break; + + case SSL_V2_COMPATIBLE_HELLO: + ssl_defaults.v2CompatibleHello = on; + if (!on) { + ssl_defaults.enableSSL2 = on; + } + break; + + case SSL_ROLLBACK_DETECTION: + ssl_defaults.detectRollBack = on; + break; + + case SSL_NO_STEP_DOWN: + ssl_defaults.noStepDown = on; + if (on) + SSL_DisableDefaultExportCipherSuites(); + break; + + case SSL_BYPASS_PKCS11: + if (PR_FALSE != on) { + if (PR_SUCCESS == SSL_BypassSetup()) { +#ifdef NO_PKCS11_BYPASS + ssl_defaults.bypassPKCS11 = PR_FALSE; +#else + ssl_defaults.bypassPKCS11 = on; +#endif + } + else { + return SECFailure; + } + } + else { + ssl_defaults.bypassPKCS11 = PR_FALSE; + } + break; + + case SSL_NO_LOCKS: + if (on && ssl_defaults.fdx) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + if (on && ssl_force_locks) + on = PR_FALSE; /* silent override */ + ssl_defaults.noLocks = on; + if (on) { + locksEverDisabled = PR_TRUE; + strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); + } + break; + + case SSL_ENABLE_SESSION_TICKETS: + ssl_defaults.enableSessionTickets = on; + break; + + case SSL_ENABLE_DEFLATE: + ssl_defaults.enableDeflate = on; + break; + + case SSL_ENABLE_RENEGOTIATION: + ssl_defaults.enableRenegotiation = on; + break; + + case SSL_REQUIRE_SAFE_NEGOTIATION: + ssl_defaults.requireSafeNegotiation = on; + break; + + case SSL_ENABLE_FALSE_START: + ssl_defaults.enableFalseStart = on; + break; + + case SSL_CBC_RANDOM_IV: + ssl_defaults.cbcRandomIV = on; + break; + + case SSL_ENABLE_OCSP_STAPLING: + ssl_defaults.enableOCSPStapling = on; + break; + + case SSL_ENABLE_NPN: + ssl_defaults.enableNPN = on; + break; + + case SSL_ENABLE_ALPN: + ssl_defaults.enableALPN = on; + break; + + case SSL_REUSE_SERVER_ECDHE_KEY: + ssl_defaults.reuseServerECDHEKey = on; + break; + + case SSL_ENABLE_FALLBACK_SCSV: + ssl_defaults.enableFallbackSCSV = on; + break; + + case SSL_ENABLE_SERVER_DHE: + ssl_defaults.enableServerDhe = on; + break; + + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + ssl_defaults.enableExtendedMS = on; + break; + + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + ssl_defaults.enableSignedCertTimestamps = on; + break; + + default: PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; - } - if (on && ssl_force_locks) - on = PR_FALSE; /* silent override */ - ssl_defaults.noLocks = on; - if (on) { - locksEverDisabled = PR_TRUE; - strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); - } - break; - - case SSL_ENABLE_SESSION_TICKETS: - ssl_defaults.enableSessionTickets = on; - break; - - case SSL_ENABLE_DEFLATE: - ssl_defaults.enableDeflate = on; - break; - - case SSL_ENABLE_RENEGOTIATION: - ssl_defaults.enableRenegotiation = on; - break; - - case SSL_REQUIRE_SAFE_NEGOTIATION: - ssl_defaults.requireSafeNegotiation = on; - break; - - case SSL_ENABLE_FALSE_START: - ssl_defaults.enableFalseStart = on; - break; - - case SSL_CBC_RANDOM_IV: - ssl_defaults.cbcRandomIV = on; - break; - - case SSL_ENABLE_OCSP_STAPLING: - ssl_defaults.enableOCSPStapling = on; - break; - - case SSL_ENABLE_NPN: - ssl_defaults.enableNPN = on; - break; - - case SSL_ENABLE_ALPN: - ssl_defaults.enableALPN = on; - break; - - case SSL_REUSE_SERVER_ECDHE_KEY: - ssl_defaults.reuseServerECDHEKey = on; - break; - - case SSL_ENABLE_FALLBACK_SCSV: - ssl_defaults.enableFallbackSCSV = on; - break; - - case SSL_ENABLE_SERVER_DHE: - ssl_defaults.enableServerDhe = on; - break; - - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - ssl_defaults.enableExtendedMS = on; - break; - - case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: - ssl_defaults.enableSignedCertTimestamps = on; - break; - - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; } return SECSuccess; } @@ -1242,12 +1349,12 @@ static PRBool ssl_IsRemovedCipherSuite(PRInt32 suite) { switch (suite) { - case SSL_FORTEZZA_DMS_WITH_NULL_SHA: - case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA: - case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA: - return PR_TRUE; - default: - return PR_FALSE; + case SSL_FORTEZZA_DMS_WITH_NULL_SHA: + case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA: + case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA: + return PR_TRUE; + default: + return PR_FALSE; } } @@ -1277,9 +1384,11 @@ ssl_CipherPolicySet(PRInt32 which, PRInt32 policy) if (ssl_IsRemovedCipherSuite(which)) { rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { + } + else if (SSL_IS_SSL2_CIPHER(which)) { rv = ssl2_SetPolicy(which, policy); - } else { + } + else { rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy); } return rv; @@ -1307,9 +1416,11 @@ SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy) if (ssl_IsRemovedCipherSuite(which)) { *oPolicy = SSL_NOT_ALLOWED; rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { + } + else if (SSL_IS_SSL2_CIPHER(which)) { rv = ssl2_GetPolicy(which, oPolicy); - } else { + } + else { rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy); } return rv; @@ -1348,7 +1459,8 @@ ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled) } if (SSL_IS_SSL2_CIPHER(which)) { rv = ssl2_CipherPrefSetDefault(which, enabled); - } else { + } + else { rv = ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled); } return rv; @@ -1368,7 +1480,7 @@ SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled) SECStatus SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) { - SECStatus rv; + SECStatus rv; if (!enabled) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -1377,9 +1489,11 @@ SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) if (ssl_IsRemovedCipherSuite(which)) { *enabled = PR_FALSE; rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { + } + else if (SSL_IS_SSL2_CIPHER(which)) { rv = ssl2_CipherPrefGetDefault(which, enabled); - } else { + } + else { rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled); } return rv; @@ -1403,7 +1517,8 @@ SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled) } if (SSL_IS_SSL2_CIPHER(which)) { rv = ssl2_CipherPrefSet(ss, which, enabled); - } else { + } + else { rv = ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled); } return rv; @@ -1412,7 +1527,7 @@ SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled) SECStatus SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled) { - SECStatus rv; + SECStatus rv; sslSocket *ss = ssl_FindSocket(fd); if (!enabled) { @@ -1427,9 +1542,11 @@ SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled) if (ssl_IsRemovedCipherSuite(which)) { *enabled = PR_FALSE; rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { + } + else if (SSL_IS_SSL2_CIPHER(which)) { rv = ssl2_CipherPrefGet(ss, which, enabled); - } else { + } + else { rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled); } return rv; @@ -1438,7 +1555,7 @@ SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled) SECStatus NSS_SetDomesticPolicy(void) { - SECStatus status = SECSuccess; + SECStatus status = SECSuccess; const PRUint16 *cipher; SECStatus rv; PRUint32 policy; @@ -1505,7 +1622,6 @@ SSL_DHEGroupPrefSet(PRFileDesc *fd, return SECSuccess; } - PRCallOnceType gWeakDHParamsRegisterOnce; int gWeakDHParamsRegisterError; @@ -1534,7 +1650,7 @@ ssl3_CreateWeakDHParams(void) rv = PK11_PQG_VerifyParams(gWeakParamsPQG, vfy, &passed); if (rv != SECSuccess || passed != SECSuccess) { SSL_DBG(("%d: PK11_PQG_VerifyParams failed in ssl3_CreateWeakDHParams", - SSL_GETPID())); + SSL_GETPID())); gWeakDHParamsError = PORT_GetError(); return PR_FAILURE; } @@ -1647,14 +1763,16 @@ ssl3_SelectDHParams(sslSocket *ss) if (ss->ssl3.dheWeakGroupEnabled) { ss->dheParams = gWeakDHParams; - } else { + } + else { if (ss->ssl3.dheGroups) { selectedGroup = selectDHEGroup(ss, ss->ssl3.dheGroups, - ss->ssl3.numDHEGroups); - } else { + ss->ssl3.numDHEGroups); + } + else { size_t number_of_default_groups = PR_ARRAY_SIZE(ssl_default_dhe_groups); selectedGroup = selectDHEGroup(ss, ssl_default_dhe_groups, - number_of_default_groups); + number_of_default_groups); } if (selectedGroup == ssl_dhe_group_none || @@ -1672,10 +1790,10 @@ ssl3_SelectDHParams(sslSocket *ss) static PRFileDesc * ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant) { - sslSocket * ns = NULL; - PRStatus rv; - PRNetAddr addr; - SECStatus status = ssl_Init(); + sslSocket *ns = NULL; + PRStatus rv; + PRNetAddr addr; + SECStatus status = ssl_Init(); if (status != SECSuccess) { return NULL; @@ -1684,11 +1802,12 @@ ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant) if (model == NULL) { /* Just create a default socket if we're given NULL for the model */ ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks), variant); - } else { - sslSocket * ss = ssl_FindSocket(model); + } + else { + sslSocket *ss = ssl_FindSocket(model); if (ss == NULL || ss->protocolVariant != variant) { SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD", - SSL_GETPID(), model)); + SSL_GETPID(), model)); return NULL; } ns = ssl_DupSocket(ss); @@ -1704,7 +1823,7 @@ ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant) } #if defined(DEBUG) || defined(FORCE_PR_ASSERT) { - sslSocket * ss = ssl_FindSocket(fd); + sslSocket *ss = ssl_FindSocket(fd); PORT_Assert(ss == ns); } #endif @@ -1769,11 +1888,11 @@ ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd, } /* For each protocol in server preference, see if we support it. */ - for (i = 0; i < protos_len; ) { - for (j = 0; j < ss->opt.nextProtoNego.len; ) { + for (i = 0; i < protos_len;) { + for (j = 0; j < ss->opt.nextProtoNego.len;) { if (protos[i] == ss->opt.nextProtoNego.data[j] && - PORT_Memcmp(&protos[i+1], &ss->opt.nextProtoNego.data[j+1], - protos[i]) == 0) { + PORT_Memcmp(&protos[i + 1], &ss->opt.nextProtoNego.data[j + 1], + protos[i]) == 0) { /* We found a match. */ ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED; result = &protos[i]; @@ -1807,7 +1926,7 @@ SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data, { sslSocket *ss; SECStatus rv; - SECItem dataItem = { siBuffer, (unsigned char *) data, length }; + SECItem dataItem = { siBuffer, (unsigned char *)data, length }; ss = ssl_FindSocket(fd); if (!ss) { @@ -1857,16 +1976,18 @@ SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf, } PORT_Memcpy(buf, ss->ssl3.nextProto.data, ss->ssl3.nextProto.len); *bufLen = ss->ssl3.nextProto.len; - } else { + } + else { *bufLen = 0; } return SECSuccess; } -SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, - const PRUint16 *ciphers, - unsigned int numCiphers) +SECStatus +SSL_SetSRTPCiphers(PRFileDesc *fd, + const PRUint16 *ciphers, + unsigned int numCiphers) { sslSocket *ss; unsigned int i; @@ -1896,10 +2017,12 @@ SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, if (*srtpCipher) { ss->ssl3.dtlsSRTPCiphers[ss->ssl3.dtlsSRTPCipherCount++] = ciphers[i]; - } else { + } + else { SSL_DBG(("%d: SSL[%d]: invalid or unimplemented SRTP cipher " - "suite specified: 0x%04hx", SSL_GETPID(), fd, - ciphers[i])); + "suite specified: 0x%04hx", + SSL_GETPID(), fd, + ciphers[i])); } } @@ -1914,7 +2037,7 @@ SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, SECStatus SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher) { - sslSocket * ss; + sslSocket *ss; ss = ssl_FindSocket(fd); if (!ss) { @@ -1936,10 +2059,10 @@ SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher) PRFileDesc * SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) { - sslSocket * sm = NULL, *ss = NULL; + sslSocket *sm = NULL, *ss = NULL; int i; - sslServerCerts * mc = NULL; - sslServerCerts * sc = NULL; + sslServerCerts *mc = NULL; + sslServerCerts *sc = NULL; if (model == NULL) { PR_SetError(SEC_ERROR_INVALID_ARGS, 0); @@ -1958,7 +2081,7 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) return NULL; } - ss->opt = sm->opt; + ss->opt = sm->opt; ss->vrange = sm->vrange; PORT_Memcpy(ss->cipherSuites, sm->cipherSuites, sizeof sm->cipherSuites); PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, sm->ssl3.dtlsSRTPCiphers, @@ -1966,7 +2089,7 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) ss->ssl3.dtlsSRTPCipherCount = sm->ssl3.dtlsSRTPCipherCount; PORT_Memcpy(ss->ssl3.signatureAlgorithms, sm->ssl3.signatureAlgorithms, sizeof(ss->ssl3.signatureAlgorithms[0]) * - sm->ssl3.signatureAlgorithmCount); + sm->ssl3.signatureAlgorithmCount); ss->ssl3.signatureAlgorithmCount = sm->ssl3.signatureAlgorithmCount; ss->ssl3.downgradeCheckVersion = sm->ssl3.downgradeCheckVersion; @@ -1977,14 +2100,14 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) /* This int should be SSLKEAType, but CC on Irix complains, * during the for loop. */ - for (i=kt_null; i < kt_kea_size; i++) { + for (i = kt_null; i < kt_kea_size; i++) { mc = &(sm->serverCerts[i]); sc = &(ss->serverCerts[i]); if (mc->serverCert && mc->serverCertChain) { if (sc->serverCert) { CERT_DestroyCertificate(sc->serverCert); } - sc->serverCert = CERT_DupCertificate(mc->serverCert); + sc->serverCert = CERT_DupCertificate(mc->serverCert); if (sc->serverCertChain) { CERT_DestroyCertificateList(sc->serverCertChain); } @@ -2005,8 +2128,9 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) SECITEM_FreeItem(&ss->signedCertTimestamps[i], PR_FALSE); } if (SECITEM_CopyItem(NULL, - &ss->signedCertTimestamps[i], - &sm->signedCertTimestamps[i]) != SECSuccess) { + &ss->signedCertTimestamps[i], + &sm->signedCertTimestamps[i]) != + SECSuccess) { goto loser; } } @@ -2044,27 +2168,27 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) } if (sm->authCertificate) - ss->authCertificate = sm->authCertificate; + ss->authCertificate = sm->authCertificate; if (sm->authCertificateArg) - ss->authCertificateArg = sm->authCertificateArg; + ss->authCertificateArg = sm->authCertificateArg; if (sm->getClientAuthData) - ss->getClientAuthData = sm->getClientAuthData; + ss->getClientAuthData = sm->getClientAuthData; if (sm->getClientAuthDataArg) - ss->getClientAuthDataArg = sm->getClientAuthDataArg; + ss->getClientAuthDataArg = sm->getClientAuthDataArg; if (sm->sniSocketConfig) - ss->sniSocketConfig = sm->sniSocketConfig; + ss->sniSocketConfig = sm->sniSocketConfig; if (sm->sniSocketConfigArg) - ss->sniSocketConfigArg = sm->sniSocketConfigArg; + ss->sniSocketConfigArg = sm->sniSocketConfigArg; if (sm->handleBadCert) - ss->handleBadCert = sm->handleBadCert; + ss->handleBadCert = sm->handleBadCert; if (sm->badCertArg) - ss->badCertArg = sm->badCertArg; + ss->badCertArg = sm->badCertArg; if (sm->handshakeCallback) - ss->handshakeCallback = sm->handshakeCallback; + ss->handshakeCallback = sm->handshakeCallback; if (sm->handshakeCallbackData) ss->handshakeCallbackData = sm->handshakeCallbackData; if (sm->pkcs11PinArg) - ss->pkcs11PinArg = sm->pkcs11PinArg; + ss->pkcs11PinArg = sm->pkcs11PinArg; return fd; loser: return NULL; @@ -2085,16 +2209,16 @@ ssl3_GetRangePolicy(SSLProtocolVariant protocolVariant, SSLVersionRange *prange) if ((rv != SECSuccess) || !(policy & NSS_USE_POLICY_IN_SSL)) { return SECFailure; } - rv=NSS_OptionGet(VERSIONS_POLICY_MIN(protocolVariant),&option); + rv = NSS_OptionGet(VERSIONS_POLICY_MIN(protocolVariant), &option); if (rv != SECSuccess) { return rv; } - prange->min = (PRUint16) option; - rv=NSS_OptionGet(VERSIONS_POLICY_MAX(protocolVariant),&option); + prange->min = (PRUint16)option; + rv = NSS_OptionGet(VERSIONS_POLICY_MAX(protocolVariant), &option); if (rv != SECSuccess) { return rv; } - prange->max = (PRUint16) option; + prange->max = (PRUint16)option; if (prange->max < prange->min) { return SECFailure; /* don't accept an invalid policy */ } @@ -2114,16 +2238,17 @@ ssl3_ConstrainVariantRangeByPolicy(SSLProtocolVariant protocolVariant) vrange = *VERSIONS_DEFAULTS(protocolVariant); rv = ssl3_GetRangePolicy(protocolVariant, &pvrange); if (rv != SECSuccess) { - return SECSuccess; /* we don't have any policy */ + return SECSuccess; /* we don't have any policy */ } vrange.min = PR_MAX(vrange.min, pvrange.min); vrange.max = PR_MIN(vrange.max, pvrange.max); if (vrange.max >= vrange.min) { *VERSIONS_DEFAULTS(protocolVariant) = vrange; - } else { - /* there was no overlap, turn off range altogether */ - pvrange.min = pvrange.max = SSL_LIBRARY_VERSION_NONE; - *VERSIONS_DEFAULTS(protocolVariant) = pvrange; + } + else { + /* there was no overlap, turn off range altogether */ + pvrange.min = pvrange.max = SSL_LIBRARY_VERSION_NONE; + *VERSIONS_DEFAULTS(protocolVariant) = pvrange; } return SECSuccess; } @@ -2171,16 +2296,16 @@ ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant, return PR_FALSE; } switch (protocolVariant) { - case ssl_variant_stream: - return (version >= SSL_LIBRARY_VERSION_3_0 && - version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); - case ssl_variant_datagram: - return (version >= SSL_LIBRARY_VERSION_TLS_1_1 && - version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); - default: - /* Can't get here */ - PORT_Assert(PR_FALSE); - return PR_FALSE; + case ssl_variant_stream: + return (version >= SSL_LIBRARY_VERSION_3_0 && + version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); + case ssl_variant_datagram: + return (version >= SSL_LIBRARY_VERSION_TLS_1_1 && + version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); + default: + /* Can't get here */ + PORT_Assert(PR_FALSE); + return PR_FALSE; } } @@ -2204,7 +2329,7 @@ SSL_PeerSignedCertTimestamps(PRFileDesc *fd) if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerSignedCertTimestamps", - SSL_GETPID(), fd)); + SSL_GETPID(), fd)); return NULL; } @@ -2230,17 +2355,17 @@ SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant, } switch (protocolVariant) { - case ssl_variant_stream: - vrange->min = SSL_LIBRARY_VERSION_3_0; - vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; - break; - case ssl_variant_datagram: - vrange->min = SSL_LIBRARY_VERSION_TLS_1_1; - vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + case ssl_variant_stream: + vrange->min = SSL_LIBRARY_VERSION_3_0; + vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; + break; + case ssl_variant_datagram: + vrange->min = SSL_LIBRARY_VERSION_TLS_1_1; + vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } return SECSuccess; @@ -2251,7 +2376,8 @@ SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant, SSLVersionRange *vrange) { if ((protocolVariant != ssl_variant_stream && - protocolVariant != ssl_variant_datagram) || !vrange) { + protocolVariant != ssl_variant_datagram) || + !vrange) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } @@ -2282,7 +2408,7 @@ SSL_VersionRangeGet(PRFileDesc *fd, SSLVersionRange *vrange) if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeGet", - SSL_GETPID(), fd)); + SSL_GETPID(), fd)); return SECFailure; } @@ -2309,7 +2435,7 @@ SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange) if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeSet", - SSL_GETPID(), fd)); + SSL_GETPID(), fd)); return SECFailure; } @@ -2345,7 +2471,7 @@ SSL_SetDowngradeCheckVersion(PRFileDesc *fd, PRUint16 version) if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetDowngradeCheckVersion", - SSL_GETPID(), fd)); + SSL_GETPID(), fd)); return SECFailure; } @@ -2377,14 +2503,14 @@ SSL_PeerStapledOCSPResponses(PRFileDesc *fd) sslSocket *ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerStapledOCSPResponses", - SSL_GETPID(), fd)); - return NULL; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerStapledOCSPResponses", + SSL_GETPID(), fd)); + return NULL; } if (!ss->sec.ci.sid) { - PORT_SetError(SEC_ERROR_NOT_INITIALIZED); - return NULL; + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); + return NULL; } return &ss->sec.ci.sid->peerCertStatus; @@ -2395,14 +2521,14 @@ SSL_PeerStapledOCSPResponses(PRFileDesc *fd) ** They all get called through the NSPRIOMethods table below. */ -static PRFileDesc * PR_CALLBACK +static PRFileDesc *PR_CALLBACK ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout) { - sslSocket *ss; - sslSocket *ns = NULL; - PRFileDesc *newfd = NULL; + sslSocket *ss; + sslSocket *ns = NULL; + PRFileDesc *newfd = NULL; PRFileDesc *osfd; - PRStatus status; + PRStatus status; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2425,7 +2551,8 @@ ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout) if (newfd == NULL) { SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d", SSL_GETPID(), ss->fd, PORT_GetError())); - } else { + } + else { /* Create ssl module */ ns = ssl_DupSocket(ss); } @@ -2433,7 +2560,7 @@ ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout) ssl_ReleaseSSL3HandshakeLock(ss); ssl_Release1stHandshakeLock(ss); SSL_UNLOCK_WRITER(ss); - SSL_UNLOCK_READER(ss); /* ss isn't used below here. */ + SSL_UNLOCK_READER(ss); /* ss isn't used below here. */ if (ns == NULL) goto loser; @@ -2446,11 +2573,12 @@ ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout) /* Now start server connection handshake with client. ** Don't need locks here because nobody else has a reference to ns yet. */ - if ( ns->opt.useSecurity ) { - if ( ns->opt.handshakeAsClient ) { + if (ns->opt.useSecurity) { + if (ns->opt.handshakeAsClient) { ns->handshake = ssl2_BeginClientHandshake; ss->handshaking = sslHandshakingAsClient; - } else { + } + else { ns->handshake = ssl2_BeginServerHandshake; ss->handshaking = sslHandshakingAsServer; } @@ -2470,7 +2598,7 @@ static PRStatus PR_CALLBACK ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout) { sslSocket *ss; - PRStatus rv; + PRStatus rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2483,7 +2611,7 @@ ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout) SSL_LOCK_WRITER(ss); ss->cTimeout = timeout; - rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr); + rv = (PRStatus) (*ss->ops->connect)(ss, sockaddr); SSL_UNLOCK_WRITER(ss); SSL_UNLOCK_READER(ss); @@ -2494,8 +2622,8 @@ ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout) static PRStatus PR_CALLBACK ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr) { - sslSocket * ss = ssl_GetPrivate(fd); - PRStatus rv; + sslSocket *ss = ssl_GetPrivate(fd); + PRStatus rv; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd)); @@ -2504,7 +2632,7 @@ ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr) SSL_LOCK_READER(ss); SSL_LOCK_WRITER(ss); - rv = (PRStatus)(*ss->ops->bind)(ss, addr); + rv = (PRStatus) (*ss->ops->bind)(ss, addr); SSL_UNLOCK_WRITER(ss); SSL_UNLOCK_READER(ss); @@ -2514,8 +2642,8 @@ ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr) static PRStatus PR_CALLBACK ssl_Listen(PRFileDesc *fd, PRIntn backlog) { - sslSocket * ss = ssl_GetPrivate(fd); - PRStatus rv; + sslSocket *ss = ssl_GetPrivate(fd); + PRStatus rv; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd)); @@ -2524,7 +2652,7 @@ ssl_Listen(PRFileDesc *fd, PRIntn backlog) SSL_LOCK_READER(ss); SSL_LOCK_WRITER(ss); - rv = (PRStatus)(*ss->ops->listen)(ss, backlog); + rv = (PRStatus) (*ss->ops->listen)(ss, backlog); SSL_UNLOCK_WRITER(ss); SSL_UNLOCK_READER(ss); @@ -2534,8 +2662,8 @@ ssl_Listen(PRFileDesc *fd, PRIntn backlog) static PRStatus PR_CALLBACK ssl_Shutdown(PRFileDesc *fd, PRIntn how) { - sslSocket * ss = ssl_GetPrivate(fd); - PRStatus rv; + sslSocket *ss = ssl_GetPrivate(fd); + PRStatus rv; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd)); @@ -2548,7 +2676,7 @@ ssl_Shutdown(PRFileDesc *fd, PRIntn how) SSL_LOCK_WRITER(ss); } - rv = (PRStatus)(*ss->ops->shutdown)(ss, how); + rv = (PRStatus) (*ss->ops->shutdown)(ss, how); if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) { SSL_UNLOCK_WRITER(ss); @@ -2563,7 +2691,7 @@ static PRStatus PR_CALLBACK ssl_Close(PRFileDesc *fd) { sslSocket *ss; - PRStatus rv; + PRStatus rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2581,7 +2709,7 @@ ssl_Close(PRFileDesc *fd) ** where the LOCK calls and the corresponding UNLOCK calls are not in ** the same function scope. The unlock calls are in ssl_FreeSocket(). */ - rv = (PRStatus)(*ss->ops->close)(ss); + rv = (PRStatus) (*ss->ops->close)(ss); return rv; } @@ -2591,7 +2719,7 @@ ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags, PRIntervalTime timeout) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2602,7 +2730,7 @@ ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags, ss->rTimeout = timeout; if (!ss->opt.fdx) ss->wTimeout = timeout; - rv = (*ss->ops->recv)(ss, (unsigned char*)buf, len, flags); + rv = (*ss->ops->recv)(ss, (unsigned char *)buf, len, flags); SSL_UNLOCK_READER(ss); return rv; } @@ -2612,7 +2740,7 @@ ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags, PRIntervalTime timeout) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2623,7 +2751,7 @@ ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags, ss->wTimeout = timeout; if (!ss->opt.fdx) ss->rTimeout = timeout; - rv = (*ss->ops->send)(ss, (const unsigned char*)buf, len, flags); + rv = (*ss->ops->send)(ss, (const unsigned char *)buf, len, flags); SSL_UNLOCK_WRITER(ss); return rv; } @@ -2632,7 +2760,7 @@ static int PR_CALLBACK ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2643,7 +2771,7 @@ ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len) ss->rTimeout = PR_INTERVAL_NO_TIMEOUT; if (!ss->opt.fdx) ss->wTimeout = PR_INTERVAL_NO_TIMEOUT; - rv = (*ss->ops->read)(ss, (unsigned char*)buf, len); + rv = (*ss->ops->read)(ss, (unsigned char *)buf, len); SSL_UNLOCK_READER(ss); return rv; } @@ -2652,7 +2780,7 @@ static int PR_CALLBACK ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2663,7 +2791,7 @@ ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len) ss->wTimeout = PR_INTERVAL_NO_TIMEOUT; if (!ss->opt.fdx) ss->rTimeout = PR_INTERVAL_NO_TIMEOUT; - rv = (*ss->ops->write)(ss, (const unsigned char*)buf, len); + rv = (*ss->ops->write)(ss, (const unsigned char *)buf, len); SSL_UNLOCK_WRITER(ss); return rv; } @@ -2678,7 +2806,7 @@ ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr) SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd)); return PR_FAILURE; } - return (PRStatus)(*ss->ops->getpeername)(ss, addr); + return (PRStatus) (*ss->ops->getpeername)(ss, addr); } /* @@ -2686,9 +2814,9 @@ ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr) SECStatus ssl_GetPeerInfo(sslSocket *ss) { - PRFileDesc * osfd; - int rv; - PRNetAddr sin; + PRFileDesc *osfd; + int rv; + PRNetAddr sin; osfd = ss->fd->lower; @@ -2701,10 +2829,12 @@ ssl_GetPeerInfo(sslSocket *ss) if (sin.inet.family == PR_AF_INET) { PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer); ss->sec.ci.port = sin.inet.port; - } else if (sin.ipv6.family == PR_AF_INET6) { + } + else if (sin.ipv6.family == PR_AF_INET6) { ss->sec.ci.peer = sin.ipv6.ip; ss->sec.ci.port = sin.ipv6.port; - } else { + } + else { PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR); return SECFailure; } @@ -2721,7 +2851,7 @@ ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name) SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd)); return PR_FAILURE; } - return (PRStatus)(*ss->ops->getsockname)(ss, name); + return (PRStatus) (*ss->ops->getsockname)(ss, name); } SECStatus @@ -2737,7 +2867,7 @@ SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, return SECFailure; } - if ( kea <= 0 || kea >= kt_kea_size) { + if (kea <= 0 || kea >= kt_kea_size) { SSL_DBG(("%d: SSL[%d]: invalid key type in SSL_SetStapledOCSPResponses", SSL_GETPID(), fd)); return SECFailure; @@ -2809,15 +2939,15 @@ static PRInt16 PR_CALLBACK ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) { sslSocket *ss; - PRInt16 new_flags = how_flags; /* should select on these flags. */ - PRNetAddr addr; + PRInt16 new_flags = how_flags; /* should select on these flags. */ + PRNetAddr addr; *p_out_flags = 0; ss = ssl_GetPrivate(fd); if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll", SSL_GETPID(), fd)); - return 0; /* don't poll on this socket */ + return 0; /* don't poll on this socket */ } if (ss->opt.useSecurity && @@ -2839,40 +2969,45 @@ ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) new_flags &= ~PR_POLL_RW; if (ss->handshaking == sslHandshakingAsClient) { new_flags |= PR_POLL_WRITE; - } else { /* handshaking as server */ + } + else { /* handshaking as server */ new_flags |= PR_POLL_READ; } - } else - /* First handshake is in progress */ - if (ss->lastWriteBlocked) { + } + else + /* First handshake is in progress */ + if (ss->lastWriteBlocked) { if (new_flags & PR_POLL_READ) { /* The caller is waiting for data to be received, ** but the initial handshake is blocked on write, or the ** client's first handshake record has not been written. ** The code should select on write, not read. */ - new_flags ^= PR_POLL_READ; /* don't select on read. */ - new_flags |= PR_POLL_WRITE; /* do select on write. */ + new_flags ^= PR_POLL_READ; /* don't select on read. */ + new_flags |= PR_POLL_WRITE; /* do select on write. */ } - } else if (new_flags & PR_POLL_WRITE) { - /* The caller is trying to write, but the handshake is - ** blocked waiting for data to read, and the first - ** handshake has been sent. So do NOT to poll on write - ** unless we did false start. - */ - if (!(ss->version >= SSL_LIBRARY_VERSION_3_0 && - ss->ssl3.hs.canFalseStart)) { - new_flags ^= PR_POLL_WRITE; /* don't select on write. */ - } - new_flags |= PR_POLL_READ; /* do select on read. */ + } + else if (new_flags & PR_POLL_WRITE) { + /* The caller is trying to write, but the handshake is + ** blocked waiting for data to read, and the first + ** handshake has been sent. So do NOT to poll on write + ** unless we did false start. + */ + if (!(ss->version >= SSL_LIBRARY_VERSION_3_0 && + ss->ssl3.hs.canFalseStart)) { + new_flags ^= PR_POLL_WRITE; /* don't select on write. */ + } + new_flags |= PR_POLL_READ; /* do select on read. */ } } - } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) { - *p_out_flags = PR_POLL_READ; /* it's ready already. */ + } + else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) { + *p_out_flags = PR_POLL_READ; /* it's ready already. */ return new_flags; - } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) && - (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */ - new_flags |= PR_POLL_WRITE; /* also select on write. */ + } + else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) && + (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */ + new_flags |= PR_POLL_WRITE; /* also select on write. */ } if (ss->version >= SSL_LIBRARY_VERSION_3_0 && @@ -2889,7 +3024,8 @@ ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) * of the application spinning. */ new_flags &= (PR_POLL_WRITE | PR_POLL_EXCEPT); - } else { + } + else { /* Unfortunately, clearing new_flags will make it impossible for * the application to detect errors that it would otherwise be * able to detect with PR_POLL_EXCEPT, until the asynchronous @@ -2904,8 +3040,8 @@ ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) } if (new_flags && (fd->lower->methods->poll != NULL)) { - PRInt16 lower_out_flags = 0; - PRInt16 lower_new_flags; + PRInt16 lower_out_flags = 0; + PRInt16 lower_new_flags; lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags, &lower_out_flags); if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) { @@ -2916,9 +3052,10 @@ ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) out_flags |= PR_POLL_READ; *p_out_flags = out_flags; new_flags = how_flags; - } else { + } + else { *p_out_flags = lower_out_flags; - new_flags = lower_new_flags; + new_flags = lower_new_flags; } } @@ -2943,14 +3080,13 @@ ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd, return sd->methods->sendfile(sd, &sfd, flags, timeout); } - PRBool ssl_FdIsBlocking(PRFileDesc *fd) { PRSocketOptionData opt; - PRStatus status; + PRStatus status; - opt.option = PR_SockOpt_Nonblocking; + opt.option = PR_SockOpt_Nonblocking; opt.value.non_blocking = PR_FALSE; status = PR_GetSocketOption(fd, &opt); if (status != PR_SUCCESS) @@ -2964,23 +3100,23 @@ ssl_SocketIsBlocking(sslSocket *ss) return ssl_FdIsBlocking(ss->fd); } -PRInt32 sslFirstBufSize = 8 * 1024; -PRInt32 sslCopyLimit = 1024; +PRInt32 sslFirstBufSize = 8 * 1024; +PRInt32 sslCopyLimit = 1024; static PRInt32 PR_CALLBACK ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, PRIntervalTime timeout) { - PRInt32 i; - PRInt32 bufLen; - PRInt32 left; - PRInt32 rv; - PRInt32 sent = 0; - const PRInt32 first_len = sslFirstBufSize; - const PRInt32 limit = sslCopyLimit; - PRBool blocking; - PRIOVec myIov = { 0, 0 }; - char buf[MAX_FRAGMENT_LENGTH]; + PRInt32 i; + PRInt32 bufLen; + PRInt32 left; + PRInt32 rv; + PRInt32 sent = 0; + const PRInt32 first_len = sslFirstBufSize; + const PRInt32 limit = sslCopyLimit; + PRBool blocking; + PRIOVec myIov = { 0, 0 }; + char buf[MAX_FRAGMENT_LENGTH]; if (vectors < 0) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); @@ -2999,28 +3135,38 @@ ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, blocking = ssl_FdIsBlocking(fd); #define K16 sizeof(buf) -#define KILL_VECTORS while (vectors && !iov->iov_len) { ++iov; --vectors; } -#define GET_VECTOR do { myIov = *iov++; --vectors; KILL_VECTORS } while (0) -#define HANDLE_ERR(rv, len) \ - if (rv != len) { \ - if (rv < 0) { \ - if (!blocking \ - && (PR_GetError() == PR_WOULD_BLOCK_ERROR) \ - && (sent > 0)) { \ - return sent; \ - } else { \ - return -1; \ - } \ - } \ - /* Only a nonblocking socket can have partial sends */ \ - PR_ASSERT(!blocking); \ - return sent + rv; \ +#define KILL_VECTORS \ + while (vectors && !iov->iov_len) { \ + ++iov; \ + --vectors; \ } -#define SEND(bfr, len) \ - do { \ +#define GET_VECTOR \ + do { \ + myIov = *iov++; \ + --vectors; \ + KILL_VECTORS \ + } while (0) +#define HANDLE_ERR(rv, len) \ + if (rv != len) { \ + if (rv < 0) { \ + if (!blocking && \ + (PR_GetError() == PR_WOULD_BLOCK_ERROR) && \ + (sent > 0)) { \ + return sent; \ + } \ + else { \ + return -1; \ + } \ + } \ + /* Only a nonblocking socket can have partial sends */ \ + PR_ASSERT(!blocking); \ + return sent + rv; \ + } +#define SEND(bfr, len) \ + do { \ rv = ssl_Send(fd, bfr, len, 0, timeout); \ - HANDLE_ERR(rv, len) \ - sent += len; \ + HANDLE_ERR(rv, len) \ + sent += len; \ } while (0) /* Make sure the first write is at least 8 KB, if possible. */ @@ -3040,39 +3186,42 @@ ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, GET_VECTOR; toCopy = PR_MIN(left, myIov.iov_len); PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy); - bufLen += toCopy; - left -= toCopy; + bufLen += toCopy; + left -= toCopy; myIov.iov_base += toCopy; - myIov.iov_len -= toCopy; + myIov.iov_len -= toCopy; } - SEND( buf, bufLen ); + SEND(buf, bufLen); } while (vectors || myIov.iov_len) { - PRInt32 addLen; + PRInt32 addLen; if (!myIov.iov_len) { GET_VECTOR; } while (myIov.iov_len >= K16) { SEND(myIov.iov_base, K16); myIov.iov_base += K16; - myIov.iov_len -= K16; + myIov.iov_len -= K16; } if (!myIov.iov_len) continue; if (!vectors || myIov.iov_len > limit) { addLen = 0; - } else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) { + } + else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) { /* Addlen is already computed. */; - } else if (vectors > 1 && - iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) { - addLen = limit - myIov.iov_len; - } else + } + else if (vectors > 1 && + iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) { + addLen = limit - myIov.iov_len; + } + else addLen = 0; if (!addLen) { - SEND( myIov.iov_base, myIov.iov_len ); + SEND(myIov.iov_base, myIov.iov_len); myIov.iov_len = 0; continue; } @@ -3082,25 +3231,27 @@ ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, GET_VECTOR; PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen); myIov.iov_base += addLen; - myIov.iov_len -= addLen; - bufLen += addLen; + myIov.iov_len -= addLen; + bufLen += addLen; - left = PR_MIN( limit, K16 - bufLen); - if (!vectors /* no more left */ - || myIov.iov_len > 0 /* we didn't use that one all up */ - || bufLen >= K16 /* it's full. */ - ) { + left = PR_MIN(limit, K16 - bufLen); + if (!vectors /* no more left */ + || myIov.iov_len > 0 /* we didn't use that one all up */ + || bufLen >= K16 /* it's full. */ ) { addLen = 0; - } else if ((addLen = iov->iov_len % K16) <= left) { + } + else if ((addLen = iov->iov_len % K16) <= left) { /* Addlen is already computed. */; - } else if (vectors > 1 && - iov[1].iov_len % K16 + addLen <= left + limit) { - addLen = left; - } else + } + else if (vectors > 1 && + iov[1].iov_len % K16 + addLen <= left + limit) { + addLen = left; + } + else addLen = 0; } while (addLen); - SEND( buf, bufLen ); + SEND(buf, bufLen); } return sent; } @@ -3137,14 +3288,16 @@ ssl_FSync(PRFileDesc *fd) } static PRInt32 PR_CALLBACK -ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) { +ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) +{ PORT_Assert(0); PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); return SECFailure; } static PRInt64 PR_CALLBACK -ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) { +ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) +{ PRInt64 res; PORT_Assert(0); @@ -3189,85 +3342,83 @@ ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags, static const PRIOMethods ssl_methods = { PR_DESC_LAYERED, - ssl_Close, /* close */ - ssl_Read, /* read */ - ssl_Write, /* write */ - ssl_Available, /* available */ - ssl_Available64, /* available64 */ - ssl_FSync, /* fsync */ - ssl_Seek, /* seek */ - ssl_Seek64, /* seek64 */ - ssl_FileInfo, /* fileInfo */ - ssl_FileInfo64, /* fileInfo64 */ - ssl_WriteV, /* writev */ - ssl_Connect, /* connect */ - ssl_Accept, /* accept */ - ssl_Bind, /* bind */ - ssl_Listen, /* listen */ - ssl_Shutdown, /* shutdown */ - ssl_Recv, /* recv */ - ssl_Send, /* send */ - ssl_RecvFrom, /* recvfrom */ - ssl_SendTo, /* sendto */ - ssl_Poll, /* poll */ - PR_EmulateAcceptRead, /* acceptread */ - ssl_TransmitFile, /* transmitfile */ - ssl_GetSockName, /* getsockname */ - ssl_GetPeerName, /* getpeername */ - NULL, /* getsockopt OBSOLETE */ - NULL, /* setsockopt OBSOLETE */ - NULL, /* getsocketoption */ - NULL, /* setsocketoption */ - PR_EmulateSendFile, /* Send a (partial) file with header/trailer*/ - NULL, /* reserved for future use */ - NULL, /* reserved for future use */ - NULL, /* reserved for future use */ - NULL, /* reserved for future use */ - NULL /* reserved for future use */ + ssl_Close, /* close */ + ssl_Read, /* read */ + ssl_Write, /* write */ + ssl_Available, /* available */ + ssl_Available64, /* available64 */ + ssl_FSync, /* fsync */ + ssl_Seek, /* seek */ + ssl_Seek64, /* seek64 */ + ssl_FileInfo, /* fileInfo */ + ssl_FileInfo64, /* fileInfo64 */ + ssl_WriteV, /* writev */ + ssl_Connect, /* connect */ + ssl_Accept, /* accept */ + ssl_Bind, /* bind */ + ssl_Listen, /* listen */ + ssl_Shutdown, /* shutdown */ + ssl_Recv, /* recv */ + ssl_Send, /* send */ + ssl_RecvFrom, /* recvfrom */ + ssl_SendTo, /* sendto */ + ssl_Poll, /* poll */ + PR_EmulateAcceptRead, /* acceptread */ + ssl_TransmitFile, /* transmitfile */ + ssl_GetSockName, /* getsockname */ + ssl_GetPeerName, /* getpeername */ + NULL, /* getsockopt OBSOLETE */ + NULL, /* setsockopt OBSOLETE */ + NULL, /* getsocketoption */ + NULL, /* setsocketoption */ + PR_EmulateSendFile, /* Send a (partial) file with header/trailer*/ + NULL, /* reserved for future use */ + NULL, /* reserved for future use */ + NULL, /* reserved for future use */ + NULL, /* reserved for future use */ + NULL /* reserved for future use */ }; - static PRIOMethods combined_methods; static void ssl_SetupIOMethods(void) { - PRIOMethods *new_methods = &combined_methods; + PRIOMethods *new_methods = &combined_methods; const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods(); - const PRIOMethods *my_methods = &ssl_methods; + const PRIOMethods *my_methods = &ssl_methods; *new_methods = *nspr_methods; - new_methods->file_type = my_methods->file_type; - new_methods->close = my_methods->close; - new_methods->read = my_methods->read; - new_methods->write = my_methods->write; - new_methods->available = my_methods->available; - new_methods->available64 = my_methods->available64; - new_methods->fsync = my_methods->fsync; - new_methods->seek = my_methods->seek; - new_methods->seek64 = my_methods->seek64; - new_methods->fileInfo = my_methods->fileInfo; - new_methods->fileInfo64 = my_methods->fileInfo64; - new_methods->writev = my_methods->writev; - new_methods->connect = my_methods->connect; - new_methods->accept = my_methods->accept; - new_methods->bind = my_methods->bind; - new_methods->listen = my_methods->listen; - new_methods->shutdown = my_methods->shutdown; - new_methods->recv = my_methods->recv; - new_methods->send = my_methods->send; - new_methods->recvfrom = my_methods->recvfrom; - new_methods->sendto = my_methods->sendto; - new_methods->poll = my_methods->poll; - new_methods->acceptread = my_methods->acceptread; - new_methods->transmitfile = my_methods->transmitfile; - new_methods->getsockname = my_methods->getsockname; - new_methods->getpeername = my_methods->getpeername; -/* new_methods->getsocketoption = my_methods->getsocketoption; */ -/* new_methods->setsocketoption = my_methods->setsocketoption; */ - new_methods->sendfile = my_methods->sendfile; - + new_methods->file_type = my_methods->file_type; + new_methods->close = my_methods->close; + new_methods->read = my_methods->read; + new_methods->write = my_methods->write; + new_methods->available = my_methods->available; + new_methods->available64 = my_methods->available64; + new_methods->fsync = my_methods->fsync; + new_methods->seek = my_methods->seek; + new_methods->seek64 = my_methods->seek64; + new_methods->fileInfo = my_methods->fileInfo; + new_methods->fileInfo64 = my_methods->fileInfo64; + new_methods->writev = my_methods->writev; + new_methods->connect = my_methods->connect; + new_methods->accept = my_methods->accept; + new_methods->bind = my_methods->bind; + new_methods->listen = my_methods->listen; + new_methods->shutdown = my_methods->shutdown; + new_methods->recv = my_methods->recv; + new_methods->send = my_methods->send; + new_methods->recvfrom = my_methods->recvfrom; + new_methods->sendto = my_methods->sendto; + new_methods->poll = my_methods->poll; + new_methods->acceptread = my_methods->acceptread; + new_methods->transmitfile = my_methods->transmitfile; + new_methods->getsockname = my_methods->getsockname; + new_methods->getpeername = my_methods->getpeername; + /* new_methods->getsocketoption = my_methods->getsocketoption; */ + /* new_methods->setsocketoption = my_methods->setsocketoption; */ + new_methods->sendfile = my_methods->sendfile; } static PRCallOnceType initIoLayerOnce; @@ -3284,8 +3435,8 @@ ssl_InitIOLayer(void) static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id) { - PRFileDesc *layer = NULL; - PRStatus status; + PRFileDesc *layer = NULL; + PRStatus status; if (!ssl_inited) { status = PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer); @@ -3333,24 +3484,24 @@ ssl_MakeLocks(sslSocket *ss) ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL); if (!ss->firstHandshakeLock) goto loser; - ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL); + ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL); if (!ss->ssl3HandshakeLock) goto loser; - ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL); + ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL); if (!ss->specLock) goto loser; - ss->recvBufLock = PZ_NewMonitor(nssILockSSL); + ss->recvBufLock = PZ_NewMonitor(nssILockSSL); if (!ss->recvBufLock) goto loser; - ss->xmitBufLock = PZ_NewMonitor(nssILockSSL); + ss->xmitBufLock = PZ_NewMonitor(nssILockSSL); if (!ss->xmitBufLock) goto loser; - ss->writerThread = NULL; + ss->writerThread = NULL; if (ssl_lock_readers) { - ss->recvLock = PZ_NewLock(nssILockSSL); + ss->recvLock = PZ_NewLock(nssILockSSL); if (!ss->recvLock) goto loser; - ss->sendLock = PZ_NewLock(nssILockSSL); + ss->sendLock = PZ_NewLock(nssILockSSL); if (!ss->sendLock) goto loser; } @@ -3364,16 +3515,16 @@ loser: #define NSS_HAVE_GETENV 1 #endif -#define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */ +#define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */ static void ssl_SetDefaultsFromEnvironment(void) { -#if defined( NSS_HAVE_GETENV ) +#if defined(NSS_HAVE_GETENV) static int firsttime = 1; if (firsttime) { - char * ev; + char *ev; firsttime = 0; #ifdef DEBUG ev = PR_GetEnvSecure("SSLDEBUGFILE"); @@ -3401,7 +3552,8 @@ ssl_SetDefaultsFromEnvironment(void) ssl_keylog_iob = fopen(ev, "a"); if (!ssl_keylog_iob) { SSL_TRACE(("SSL: failed to open key log file")); - } else { + } + else { if (ftell(ssl_keylog_iob) == 0) { fputs("# SSL/TLS secrets log file, generated by NSS\n", ssl_keylog_iob); @@ -3413,8 +3565,8 @@ ssl_SetDefaultsFromEnvironment(void) ev = PR_GetEnvSecure("SSLBYPASS"); if (ev && ev[0]) { ssl_defaults.bypassPKCS11 = (ev[0] == '1'); - SSL_TRACE(("SSL: bypass default set to %d", \ - ssl_defaults.bypassPKCS11)); + SSL_TRACE(("SSL: bypass default set to %d", + ssl_defaults.bypassPKCS11)); } #endif /* NO_PKCS11_BYPASS */ ev = PR_GetEnvSecure("SSLFORCELOCKS"); @@ -3441,7 +3593,7 @@ ssl_SetDefaultsFromEnvironment(void) if (ev && ev[0] == '1') { ssl_defaults.requireSafeNegotiation = PR_TRUE; SSL_TRACE(("SSL: requireSafeNegotiation set to %d", - PR_TRUE)); + PR_TRUE)); } ev = PR_GetEnvSecure("NSS_SSL_CBC_RANDOM_IV"); if (ev && ev[0] == '0') { @@ -3466,7 +3618,7 @@ ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant) makeLocks = PR_TRUE; /* Make a new socket and get it ready */ - ss = (sslSocket*) PORT_ZAlloc(sizeof(sslSocket)); + ss = (sslSocket *)PORT_ZAlloc(sizeof(sslSocket)); if (ss) { /* This should be of type SSLKEAType, but CC on IRIX * complains during the for loop. @@ -3474,45 +3626,45 @@ ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant) int i; SECStatus status; - ss->opt = ssl_defaults; - ss->opt.useSocks = PR_FALSE; - ss->opt.noLocks = !makeLocks; - ss->vrange = *VERSIONS_DEFAULTS(protocolVariant); - ss->protocolVariant = protocolVariant; + ss->opt = ssl_defaults; + ss->opt.useSocks = PR_FALSE; + ss->opt.noLocks = !makeLocks; + ss->vrange = *VERSIONS_DEFAULTS(protocolVariant); + ss->protocolVariant = protocolVariant; - ss->peerID = NULL; - ss->rTimeout = PR_INTERVAL_NO_TIMEOUT; - ss->wTimeout = PR_INTERVAL_NO_TIMEOUT; - ss->cTimeout = PR_INTERVAL_NO_TIMEOUT; - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; /* produced lazily */ - ss->preferredCipher = NULL; - ss->url = NULL; + ss->peerID = NULL; + ss->rTimeout = PR_INTERVAL_NO_TIMEOUT; + ss->wTimeout = PR_INTERVAL_NO_TIMEOUT; + ss->cTimeout = PR_INTERVAL_NO_TIMEOUT; + ss->cipherSpecs = NULL; + ss->sizeCipherSpecs = 0; /* produced lazily */ + ss->preferredCipher = NULL; + ss->url = NULL; - for (i=kt_null; i < kt_kea_size; i++) { - sslServerCerts * sc = ss->serverCerts + i; - sc->serverCert = NULL; + for (i = kt_null; i < kt_kea_size; i++) { + sslServerCerts *sc = ss->serverCerts + i; + sc->serverCert = NULL; sc->serverCertChain = NULL; - sc->serverKeyPair = NULL; - sc->serverKeyBits = 0; + sc->serverKeyPair = NULL; + sc->serverKeyBits = 0; ss->certStatusArray[i] = NULL; } - ss->stepDownKeyPair = NULL; + ss->stepDownKeyPair = NULL; ss->dheParams = NULL; ss->dheKeyPair = NULL; - ss->dbHandle = CERT_GetDefaultCertDB(); + ss->dbHandle = CERT_GetDefaultCertDB(); /* Provide default implementation of hooks */ - ss->authCertificate = SSL_AuthCertificate; + ss->authCertificate = SSL_AuthCertificate; ss->authCertificateArg = (void *)ss->dbHandle; - ss->sniSocketConfig = NULL; + ss->sniSocketConfig = NULL; ss->sniSocketConfigArg = NULL; - ss->getClientAuthData = NULL; - ss->handleBadCert = NULL; - ss->badCertArg = NULL; - ss->pkcs11PinArg = NULL; + ss->getClientAuthData = NULL; + ss->handleBadCert = NULL; + ss->badCertArg = NULL; + ss->pkcs11PinArg = NULL; ss->ephemeralECDHKeyPair = NULL; ssl_ChooseOps(ss); @@ -3531,7 +3683,7 @@ ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant) goto loser; status = ssl_InitGather(&ss->gs); if (status != SECSuccess) { -loser: + loser: ssl_DestroySocketContents(ss); ssl_DestroyLocks(ss); PORT_Free(ss); diff --git a/security/nss/lib/ssl/sslt.h b/security/nss/lib/ssl/sslt.h index 1035ab9a0ad0..bf722b5c0ef3 100644 --- a/security/nss/lib/ssl/sslt.h +++ b/security/nss/lib/ssl/sslt.h @@ -36,12 +36,12 @@ typedef struct SSL3StatisticsStr { /* Key Exchange algorithm values */ typedef enum { - ssl_kea_null = 0, - ssl_kea_rsa = 1, - ssl_kea_dh = 2, - ssl_kea_fortezza = 3, /* deprecated, now unused */ - ssl_kea_ecdh = 4, - ssl_kea_size /* number of ssl_kea_ algorithms */ + ssl_kea_null = 0, + ssl_kea_rsa = 1, + ssl_kea_dh = 2, + ssl_kea_fortezza = 3, /* deprecated, now unused */ + ssl_kea_ecdh = 4, + ssl_kea_size /* number of ssl_kea_ algorithms */ } SSLKEAType; /* The following defines are for backwards compatibility. @@ -49,21 +49,20 @@ typedef enum { ** programs that use the kt_ symbols should convert to the ssl_kt_ symbols ** soon. */ -#define kt_null ssl_kea_null -#define kt_rsa ssl_kea_rsa -#define kt_dh ssl_kea_dh -#define kt_fortezza ssl_kea_fortezza /* deprecated, now unused */ -#define kt_ecdh ssl_kea_ecdh -#define kt_kea_size ssl_kea_size - +#define kt_null ssl_kea_null +#define kt_rsa ssl_kea_rsa +#define kt_dh ssl_kea_dh +#define kt_fortezza ssl_kea_fortezza /* deprecated, now unused */ +#define kt_ecdh ssl_kea_ecdh +#define kt_kea_size ssl_kea_size /* Values of this enum match the SignatureAlgorithm enum from * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ typedef enum { - ssl_sign_null = 0, /* "anonymous" in TLS */ - ssl_sign_rsa = 1, - ssl_sign_dsa = 2, - ssl_sign_ecdsa = 3 + ssl_sign_null = 0, /* "anonymous" in TLS */ + ssl_sign_rsa = 1, + ssl_sign_dsa = 2, + ssl_sign_ecdsa = 3 } SSLSignType; /* Values of this enum match the HashAlgorithm enum from @@ -86,80 +85,86 @@ typedef struct SSLSignatureAndHashAlgStr { } SSLSignatureAndHashAlg; typedef enum { - ssl_auth_null = 0, - ssl_auth_rsa = 1, - ssl_auth_dsa = 2, - ssl_auth_kea = 3, - ssl_auth_ecdsa = 4 + ssl_auth_null = 0, + ssl_auth_rsa = 1, + ssl_auth_dsa = 2, + ssl_auth_kea = 3, + ssl_auth_ecdsa = 4 } SSLAuthType; typedef enum { - ssl_calg_null = 0, - ssl_calg_rc4 = 1, - ssl_calg_rc2 = 2, - ssl_calg_des = 3, - ssl_calg_3des = 4, - ssl_calg_idea = 5, - ssl_calg_fortezza = 6, /* deprecated, now unused */ - ssl_calg_aes = 7, + ssl_calg_null = 0, + ssl_calg_rc4 = 1, + ssl_calg_rc2 = 2, + ssl_calg_des = 3, + ssl_calg_3des = 4, + ssl_calg_idea = 5, + ssl_calg_fortezza = 6, /* deprecated, now unused */ + ssl_calg_aes = 7, ssl_calg_camellia = 8, - ssl_calg_seed = 9, - ssl_calg_aes_gcm = 10 + ssl_calg_seed = 9, + ssl_calg_aes_gcm = 10, + ssl_calg_chacha20 = 11 } SSLCipherAlgorithm; -typedef enum { - ssl_mac_null = 0, - ssl_mac_md5 = 1, - ssl_mac_sha = 2, - ssl_hmac_md5 = 3, /* TLS HMAC version of mac_md5 */ - ssl_hmac_sha = 4, /* TLS HMAC version of mac_sha */ - ssl_hmac_sha256 = 5, - ssl_mac_aead = 6 +typedef enum { + ssl_mac_null = 0, + ssl_mac_md5 = 1, + ssl_mac_sha = 2, + ssl_hmac_md5 = 3, /* TLS HMAC version of mac_md5 */ + ssl_hmac_sha = 4, /* TLS HMAC version of mac_sha */ + ssl_hmac_sha256 = 5, + ssl_mac_aead = 6 } SSLMACAlgorithm; typedef enum { ssl_compression_null = 0, - ssl_compression_deflate = 1 /* RFC 3749 */ + ssl_compression_deflate = 1 /* RFC 3749 */ } SSLCompressionMethod; typedef struct SSLChannelInfoStr { - PRUint32 length; - PRUint16 protocolVersion; - PRUint16 cipherSuite; + /* |length| is obsolete. On return, SSL_GetChannelInfo sets |length| to the + * smaller of the |len| argument and the length of the struct. The caller + * may ignore |length|. */ + PRUint32 length; + PRUint16 protocolVersion; + PRUint16 cipherSuite; /* server authentication info */ - PRUint32 authKeyBits; + PRUint32 authKeyBits; /* key exchange algorithm info */ - PRUint32 keaKeyBits; + PRUint32 keaKeyBits; /* session info */ - PRUint32 creationTime; /* seconds since Jan 1, 1970 */ - PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */ - PRUint32 expirationTime; /* seconds since Jan 1, 1970 */ - PRUint32 sessionIDLength; /* up to 32 */ - PRUint8 sessionID [32]; + PRUint32 creationTime; /* seconds since Jan 1, 1970 */ + PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */ + PRUint32 expirationTime; /* seconds since Jan 1, 1970 */ + PRUint32 sessionIDLength; /* up to 32 */ + PRUint8 sessionID[32]; /* The following fields are added in NSS 3.12.5. */ /* compression method info */ - const char * compressionMethodName; + const char* compressionMethodName; SSLCompressionMethod compressionMethod; /* The following fields are added in NSS 3.21. * This field only has meaning in TLS < 1.3 and will be set to * PR_FALSE in TLS 1.3. */ - PRBool extendedMasterSecretUsed; + PRBool extendedMasterSecretUsed; } SSLChannelInfo; /* Preliminary channel info */ #define ssl_preinfo_version (1U << 0) #define ssl_preinfo_cipher_suite (1U << 1) -#define ssl_preinfo_all (ssl_preinfo_version|ssl_preinfo_cipher_suite) +#define ssl_preinfo_all (ssl_preinfo_version | ssl_preinfo_cipher_suite) typedef struct SSLPreliminaryChannelInfoStr { - /* This is set to the length of the struct. */ + /* |length| is obsolete. On return, SSL_GetPreliminaryChannelInfo sets + * |length| to the smaller of the |len| argument and the length of the + * struct. The caller may ignore |length|. */ PRUint32 length; /* A bitfield over SSLPreliminaryValueSet that describes which * preliminary values are set (see ssl_preinfo_*). */ @@ -171,39 +176,42 @@ typedef struct SSLPreliminaryChannelInfoStr { } SSLPreliminaryChannelInfo; typedef struct SSLCipherSuiteInfoStr { - PRUint16 length; - PRUint16 cipherSuite; + /* |length| is obsolete. On return, SSL_GetCipherSuitelInfo sets |length| + * to the smaller of the |len| argument and the length of the struct. The + * caller may ignore |length|. */ + PRUint16 length; + PRUint16 cipherSuite; /* Cipher Suite Name */ - const char * cipherSuiteName; + const char* cipherSuiteName; /* server authentication info */ - const char * authAlgorithmName; - SSLAuthType authAlgorithm; + const char* authAlgorithmName; + SSLAuthType authAlgorithm; /* key exchange algorithm info */ - const char * keaTypeName; - SSLKEAType keaType; + const char* keaTypeName; + SSLKEAType keaType; /* symmetric encryption info */ - const char * symCipherName; - SSLCipherAlgorithm symCipher; - PRUint16 symKeyBits; - PRUint16 symKeySpace; - PRUint16 effectiveKeyBits; + const char* symCipherName; + SSLCipherAlgorithm symCipher; + PRUint16 symKeyBits; + PRUint16 symKeySpace; + PRUint16 effectiveKeyBits; /* MAC info */ /* AEAD ciphers don't have a MAC. For an AEAD cipher, macAlgorithmName * is "AEAD", macAlgorithm is ssl_mac_aead, and macBits is the length in * bits of the authentication tag. */ - const char * macAlgorithmName; - SSLMACAlgorithm macAlgorithm; - PRUint16 macBits; + const char* macAlgorithmName; + SSLMACAlgorithm macAlgorithm; + PRUint16 macBits; - PRUintn isFIPS : 1; - PRUintn isExportable : 1; - PRUintn nonStandard : 1; - PRUintn reservedBits :29; + PRUintn isFIPS : 1; + PRUintn isExportable : 1; + PRUintn nonStandard : 1; + PRUintn reservedBits : 29; } SSLCipherSuiteInfo; @@ -218,34 +226,34 @@ typedef struct SSLVersionRangeStr { } SSLVersionRange; typedef enum { - SSL_sni_host_name = 0, + SSL_sni_host_name = 0, SSL_sni_type_total } SSLSniNameType; /* Supported extensions. */ /* Update SSL_MAX_EXTENSIONS whenever a new extension type is added. */ typedef enum { - ssl_server_name_xtn = 0, - ssl_cert_status_xtn = 5, + ssl_server_name_xtn = 0, + ssl_cert_status_xtn = 5, #ifndef NSS_DISABLE_ECC - ssl_elliptic_curves_xtn = 10, - ssl_ec_point_formats_xtn = 11, + ssl_elliptic_curves_xtn = 10, + ssl_ec_point_formats_xtn = 11, #endif - ssl_signature_algorithms_xtn = 13, - ssl_use_srtp_xtn = 14, - ssl_app_layer_protocol_xtn = 16, + ssl_signature_algorithms_xtn = 13, + ssl_use_srtp_xtn = 14, + ssl_app_layer_protocol_xtn = 16, /* signed_certificate_timestamp extension, RFC 6962 */ - ssl_signed_cert_timestamp_xtn = 18, - ssl_padding_xtn = 21, - ssl_extended_master_secret_xtn = 23, - ssl_session_ticket_xtn = 35, - ssl_tls13_key_share_xtn = 40, /* unofficial TODO(ekr) */ - ssl_next_proto_nego_xtn = 13172, - ssl_renegotiation_info_xtn = 0xff01, - ssl_tls13_draft_version_xtn = 0xff02 /* experimental number */ + ssl_signed_cert_timestamp_xtn = 18, + ssl_padding_xtn = 21, + ssl_extended_master_secret_xtn = 23, + ssl_session_ticket_xtn = 35, + ssl_tls13_key_share_xtn = 40, /* unofficial TODO(ekr) */ + ssl_next_proto_nego_xtn = 13172, + ssl_renegotiation_info_xtn = 0xff01, + ssl_tls13_draft_version_xtn = 0xff02 /* experimental number */ } SSLExtensionType; -#define SSL_MAX_EXTENSIONS 14 /* doesn't include ssl_padding_xtn. */ +#define SSL_MAX_EXTENSIONS 14 /* doesn't include ssl_padding_xtn. */ typedef enum { ssl_dhe_group_none = 0, diff --git a/security/nss/lib/ssl/ssltrace.c b/security/nss/lib/ssl/ssltrace.c index ee540d587512..eb00e54ce1eb 100644 --- a/security/nss/lib/ssl/ssltrace.c +++ b/security/nss/lib/ssl/ssltrace.c @@ -15,25 +15,26 @@ static const char *hex = "0123456789abcdef"; static const char printable[257] = { - "................" /* 0x */ - "................" /* 1x */ - " !\"#$%&'()*+,-./" /* 2x */ - "0123456789:;<=>?" /* 3x */ - "@ABCDEFGHIJKLMNO" /* 4x */ - "PQRSTUVWXYZ[\\]^_" /* 5x */ - "`abcdefghijklmno" /* 6x */ - "pqrstuvwxyz{|}~." /* 7x */ - "................" /* 8x */ - "................" /* 9x */ - "................" /* ax */ - "................" /* bx */ - "................" /* cx */ - "................" /* dx */ - "................" /* ex */ - "................" /* fx */ + "................" /* 0x */ + "................" /* 1x */ + " !\"#$%&'()*+,-./" /* 2x */ + "0123456789:;<=>?" /* 3x */ + "@ABCDEFGHIJKLMNO" /* 4x */ + "PQRSTUVWXYZ[\\]^_" /* 5x */ + "`abcdefghijklmno" /* 6x */ + "pqrstuvwxyz{|}~." /* 7x */ + "................" /* 8x */ + "................" /* 9x */ + "................" /* ax */ + "................" /* bx */ + "................" /* cx */ + "................" /* dx */ + "................" /* ex */ + "................" /* fx */ }; -void ssl_PrintBuf(sslSocket *ss, const char *msg, const void *vp, int len) +void +ssl_PrintBuf(sslSocket *ss, const char *msg, const void *vp, int len) { const unsigned char *cp = (const unsigned char *)vp; char buf[80]; @@ -41,53 +42,56 @@ void ssl_PrintBuf(sslSocket *ss, const char *msg, const void *vp, int len) char *ap; if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s [Len: %d]", SSL_GETPID(), ss->fd, - msg, len)); - } else { - SSL_TRACE(("%d: SSL: %s [Len: %d]", SSL_GETPID(), msg, len)); + SSL_TRACE(("%d: SSL[%d]: %s [Len: %d]", SSL_GETPID(), ss->fd, + msg, len)); + } + else { + SSL_TRACE(("%d: SSL: %s [Len: %d]", SSL_GETPID(), msg, len)); } memset(buf, ' ', sizeof buf); bp = buf; ap = buf + 50; while (--len >= 0) { - unsigned char ch = *cp++; - *bp++ = hex[(ch >> 4) & 0xf]; - *bp++ = hex[ch & 0xf]; - *bp++ = ' '; - *ap++ = printable[ch]; - if (ap - buf >= 66) { - *ap = 0; - SSL_TRACE((" %s", buf)); - memset(buf, ' ', sizeof buf); - bp = buf; - ap = buf + 50; - } + unsigned char ch = *cp++; + *bp++ = hex[(ch >> 4) & 0xf]; + *bp++ = hex[ch & 0xf]; + *bp++ = ' '; + *ap++ = printable[ch]; + if (ap - buf >= 66) { + *ap = 0; + SSL_TRACE((" %s", buf)); + memset(buf, ' ', sizeof buf); + bp = buf; + ap = buf + 50; + } } if (bp > buf) { - *ap = 0; - SSL_TRACE((" %s", buf)); + *ap = 0; + SSL_TRACE((" %s", buf)); } } -#define LEN(cp) (((cp)[0] << 8) | ((cp)[1])) +#define LEN(cp) (((cp)[0] << 8) | ((cp)[1])) -static void PrintType(sslSocket *ss, char *msg) +static void +PrintType(sslSocket *ss, char *msg) { if (ss) { - SSL_TRACE(("%d: SSL[%d]: dump-msg: %s", SSL_GETPID(), ss->fd, - msg)); - } else { - SSL_TRACE(("%d: SSL: dump-msg: %s", SSL_GETPID(), msg)); + SSL_TRACE(("%d: SSL[%d]: dump-msg: %s", SSL_GETPID(), ss->fd, msg)); + } + else { + SSL_TRACE(("%d: SSL: dump-msg: %s", SSL_GETPID(), msg)); } } -static void PrintInt(sslSocket *ss, char *msg, unsigned v) +static void +PrintInt(sslSocket *ss, char *msg, unsigned v) { if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s=%u", SSL_GETPID(), ss->fd, - msg, v)); - } else { - SSL_TRACE(("%d: SSL: %s=%u", SSL_GETPID(), msg, v)); + SSL_TRACE(("%d: SSL[%d]: %s=%u", SSL_GETPID(), ss->fd, msg, v)); + } + else { + SSL_TRACE(("%d: SSL: %s=%u", SSL_GETPID(), msg, v)); } } @@ -95,149 +99,146 @@ static void PrintInt(sslSocket *ss, char *msg, unsigned v) * a) It prefixes each line of the buffer with "XX: SSL[xxx] " * b) It dumps only hex, not ASCII. */ -static void PrintBuf(sslSocket *ss, char *msg, unsigned char *cp, int len) +static void +PrintBuf(sslSocket *ss, char *msg, unsigned char *cp, int len) { char buf[80]; char *bp; if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s [Len: %d]", - SSL_GETPID(), ss->fd, msg, len)); - } else { - SSL_TRACE(("%d: SSL: %s [Len: %d]", - SSL_GETPID(), msg, len)); + SSL_TRACE(("%d: SSL[%d]: %s [Len: %d]", + SSL_GETPID(), ss->fd, msg, len)); + } + else { + SSL_TRACE(("%d: SSL: %s [Len: %d]", + SSL_GETPID(), msg, len)); } bp = buf; while (--len >= 0) { - unsigned char ch = *cp++; - *bp++ = hex[(ch >> 4) & 0xf]; - *bp++ = hex[ch & 0xf]; - *bp++ = ' '; - if (bp + 4 > buf + 50) { - *bp = 0; - if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s", - SSL_GETPID(), ss->fd, buf)); - } else { - SSL_TRACE(("%d: SSL: %s", SSL_GETPID(), buf)); - } - bp = buf; - } + unsigned char ch = *cp++; + *bp++ = hex[(ch >> 4) & 0xf]; + *bp++ = hex[ch & 0xf]; + *bp++ = ' '; + if (bp + 4 > buf + 50) { + *bp = 0; + if (ss) { + SSL_TRACE(("%d: SSL[%d]: %s", + SSL_GETPID(), ss->fd, buf)); + } + else { + SSL_TRACE(("%d: SSL: %s", SSL_GETPID(), buf)); + } + bp = buf; + } } if (bp > buf) { - *bp = 0; - if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s", - SSL_GETPID(), ss->fd, buf)); - } else { - SSL_TRACE(("%d: SSL: %s", SSL_GETPID(), buf)); - } - } -} - -void ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len) -{ - switch (bp[0]) { - case SSL_MT_ERROR: - PrintType(ss, "Error"); - PrintInt(ss, "error", LEN(bp+1)); - break; - - case SSL_MT_CLIENT_HELLO: - { - unsigned lcs = LEN(bp+3); - unsigned ls = LEN(bp+5); - unsigned lc = LEN(bp+7); - - PrintType(ss, "Client-Hello"); - - PrintInt(ss, "version (Major)", bp[1]); - PrintInt(ss, "version (minor)", bp[2]); - - PrintBuf(ss, "cipher-specs", bp+9, lcs); - PrintBuf(ss, "session-id", bp+9+lcs, ls); - PrintBuf(ss, "challenge", bp+9+lcs+ls, lc); - } - break; - case SSL_MT_CLIENT_MASTER_KEY: - { - unsigned lck = LEN(bp+4); - unsigned lek = LEN(bp+6); - unsigned lka = LEN(bp+8); - - PrintType(ss, "Client-Master-Key"); - - PrintInt(ss, "cipher-choice", bp[1]); - PrintInt(ss, "key-length", LEN(bp+2)); - - PrintBuf(ss, "clear-key", bp+10, lck); - PrintBuf(ss, "encrypted-key", bp+10+lck, lek); - PrintBuf(ss, "key-arg", bp+10+lck+lek, lka); - } - break; - case SSL_MT_CLIENT_FINISHED: - PrintType(ss, "Client-Finished"); - PrintBuf(ss, "connection-id", bp+1, len-1); - break; - case SSL_MT_SERVER_HELLO: - { - unsigned lc = LEN(bp+5); - unsigned lcs = LEN(bp+7); - unsigned lci = LEN(bp+9); - - PrintType(ss, "Server-Hello"); - - PrintInt(ss, "session-id-hit", bp[1]); - PrintInt(ss, "certificate-type", bp[2]); - PrintInt(ss, "version (Major)", bp[3]); - PrintInt(ss, "version (minor)", bp[3]); - PrintBuf(ss, "certificate", bp+11, lc); - PrintBuf(ss, "cipher-specs", bp+11+lc, lcs); - PrintBuf(ss, "connection-id", bp+11+lc+lcs, lci); - } - break; - case SSL_MT_SERVER_VERIFY: - PrintType(ss, "Server-Verify"); - PrintBuf(ss, "challenge", bp+1, len-1); - break; - case SSL_MT_SERVER_FINISHED: - PrintType(ss, "Server-Finished"); - PrintBuf(ss, "session-id", bp+1, len-1); - break; - case SSL_MT_REQUEST_CERTIFICATE: - PrintType(ss, "Request-Certificate"); - PrintInt(ss, "authentication-type", bp[1]); - PrintBuf(ss, "certificate-challenge", bp+2, len-2); - break; - case SSL_MT_CLIENT_CERTIFICATE: - { - unsigned lc = LEN(bp+2); - unsigned lr = LEN(bp+4); - PrintType(ss, "Client-Certificate"); - PrintInt(ss, "certificate-type", bp[1]); - PrintBuf(ss, "certificate", bp+6, lc); - PrintBuf(ss, "response", bp+6+lc, lr); - } - break; - default: - ssl_PrintBuf(ss, "sending *unknown* message type", bp, len); - return; + *bp = 0; + if (ss) { + SSL_TRACE(("%d: SSL[%d]: %s", + SSL_GETPID(), ss->fd, buf)); + } + else { + SSL_TRACE(("%d: SSL: %s", SSL_GETPID(), buf)); + } } } void -ssl_Trace(const char *format, ... ) +ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len) { - char buf[2000]; + switch (bp[0]) { + case SSL_MT_ERROR: + PrintType(ss, "Error"); + PrintInt(ss, "error", LEN(bp + 1)); + break; + + case SSL_MT_CLIENT_HELLO: { + unsigned lcs = LEN(bp + 3); + unsigned ls = LEN(bp + 5); + unsigned lc = LEN(bp + 7); + + PrintType(ss, "Client-Hello"); + + PrintInt(ss, "version (Major)", bp[1]); + PrintInt(ss, "version (minor)", bp[2]); + + PrintBuf(ss, "cipher-specs", bp + 9, lcs); + PrintBuf(ss, "session-id", bp + 9 + lcs, ls); + PrintBuf(ss, "challenge", bp + 9 + lcs + ls, lc); + } break; + case SSL_MT_CLIENT_MASTER_KEY: { + unsigned lck = LEN(bp + 4); + unsigned lek = LEN(bp + 6); + unsigned lka = LEN(bp + 8); + + PrintType(ss, "Client-Master-Key"); + + PrintInt(ss, "cipher-choice", bp[1]); + PrintInt(ss, "key-length", LEN(bp + 2)); + + PrintBuf(ss, "clear-key", bp + 10, lck); + PrintBuf(ss, "encrypted-key", bp + 10 + lck, lek); + PrintBuf(ss, "key-arg", bp + 10 + lck + lek, lka); + } break; + case SSL_MT_CLIENT_FINISHED: + PrintType(ss, "Client-Finished"); + PrintBuf(ss, "connection-id", bp + 1, len - 1); + break; + case SSL_MT_SERVER_HELLO: { + unsigned lc = LEN(bp + 5); + unsigned lcs = LEN(bp + 7); + unsigned lci = LEN(bp + 9); + + PrintType(ss, "Server-Hello"); + + PrintInt(ss, "session-id-hit", bp[1]); + PrintInt(ss, "certificate-type", bp[2]); + PrintInt(ss, "version (Major)", bp[3]); + PrintInt(ss, "version (minor)", bp[3]); + PrintBuf(ss, "certificate", bp + 11, lc); + PrintBuf(ss, "cipher-specs", bp + 11 + lc, lcs); + PrintBuf(ss, "connection-id", bp + 11 + lc + lcs, lci); + } break; + case SSL_MT_SERVER_VERIFY: + PrintType(ss, "Server-Verify"); + PrintBuf(ss, "challenge", bp + 1, len - 1); + break; + case SSL_MT_SERVER_FINISHED: + PrintType(ss, "Server-Finished"); + PrintBuf(ss, "session-id", bp + 1, len - 1); + break; + case SSL_MT_REQUEST_CERTIFICATE: + PrintType(ss, "Request-Certificate"); + PrintInt(ss, "authentication-type", bp[1]); + PrintBuf(ss, "certificate-challenge", bp + 2, len - 2); + break; + case SSL_MT_CLIENT_CERTIFICATE: { + unsigned lc = LEN(bp + 2); + unsigned lr = LEN(bp + 4); + PrintType(ss, "Client-Certificate"); + PrintInt(ss, "certificate-type", bp[1]); + PrintBuf(ss, "certificate", bp + 6, lc); + PrintBuf(ss, "response", bp + 6 + lc, lr); + } break; + default: + ssl_PrintBuf(ss, "sending *unknown* message type", bp, len); + return; + } +} + +void +ssl_Trace(const char *format, ...) +{ + char buf[2000]; va_list args; if (ssl_trace_iob) { - va_start(args, format); - PR_vsnprintf(buf, sizeof(buf), format, args); - va_end(args); + va_start(args, format); + PR_vsnprintf(buf, sizeof(buf), format, args); + va_end(args); - fputs(buf, ssl_trace_iob); - fputs("\n", ssl_trace_iob); + fputs(buf, ssl_trace_iob); + fputs("\n", ssl_trace_iob); } } #endif diff --git a/security/nss/lib/ssl/tls13con.c b/security/nss/lib/ssl/tls13con.c index 04fa58873454..41b65a4638da 100644 --- a/security/nss/lib/ssl/tls13con.c +++ b/security/nss/lib/ssl/tls13con.c @@ -55,7 +55,7 @@ static SECStatus tls13_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, static SECStatus tls13_HandleCertificateVerify( sslSocket *ss, SSL3Opaque *b, PRUint32 length, SSL3Hashes *hashes); -static SECStatus tls13_HkdfExtractSharedKey(sslSocket *ss, PK11SymKey* key, +static SECStatus tls13_HkdfExtractSharedKey(sslSocket *ss, PK11SymKey *key, SharedSecretType keyType); static SECStatus tls13_SendFinished(sslSocket *ss); static SECStatus tls13_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, @@ -92,33 +92,38 @@ const char kServerFinishedLabel[] = "server finished"; const SSL3ProtocolVersion kRecordVersion = 0x0301U; -#define FATAL_ERROR(ss, prError, desc) do { \ - SSL_TRC(3, ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)", \ - SSL_GETPID(), ss->fd, prError, __func__, __FILE__, __LINE__)); \ - tls13_FatalError(ss, prError, desc); \ -} while(0) +#define FATAL_ERROR(ss, prError, desc) \ + do { \ + SSL_TRC(3, ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)", \ + SSL_GETPID(), ss->fd, prError, __func__, __FILE__, __LINE__)); \ + tls13_FatalError(ss, prError, desc); \ + } while (0) -#define UNIMPLEMENTED() do { \ - SSL_TRC(3, ("%d: TLS13[%d]: unimplemented feature in %s (%s:%d)", \ - SSL_GETPID(), ss->fd, __func__, __FILE__, __LINE__)); \ - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); \ - PORT_Assert(0); \ -} while(0) +#define UNIMPLEMENTED() \ + do { \ + SSL_TRC(3, ("%d: TLS13[%d]: unimplemented feature in %s (%s:%d)", \ + SSL_GETPID(), ss->fd, __func__, __FILE__, __LINE__)); \ + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); \ + PORT_Assert(0); \ + return SECFailure; \ + } while (0) void tls13_FatalError(sslSocket *ss, PRErrorCode prError, SSL3AlertDescription desc) { - PORT_Assert(desc != internal_error); /* These should never happen */ + PORT_Assert(desc != internal_error); /* These should never happen */ (void)SSL3_SendAlert(ss, alert_fatal, desc); PORT_SetError(prError); } #ifdef TRACE -#define STATE_CASE(a) case a: return #a +#define STATE_CASE(a) \ + case a: \ + return #a static char * tls13_HandshakeState(SSL3WaitState st) { - switch(st) { + switch (st) { STATE_CASE(wait_client_hello); STATE_CASE(wait_client_cert); STATE_CASE(wait_cert_verify); @@ -141,9 +146,8 @@ tls13_HandshakeState(SSL3WaitState st) #define TLS13_BASE_WAIT_STATE(ws) (ws & ~TLS13_WAIT_STATE_MASK) /* We don't mask idle_handshake because other parts of the code use it*/ -#define TLS13_WAIT_STATE(ws) (ws == idle_handshake ? ws :\ - ws | TLS13_WAIT_STATE_MASK) -#define TLS13_CHECK_HS_STATE(ss, err, ...) \ +#define TLS13_WAIT_STATE(ws) (ws == idle_handshake ? ws : ws | TLS13_WAIT_STATE_MASK) +#define TLS13_CHECK_HS_STATE(ss, err, ...) \ tls13_CheckHsState(ss, err, #err, __func__, __FILE__, __LINE__, \ __VA_ARGS__, \ wait_invalid) @@ -153,7 +157,7 @@ tls13_SetHsState(sslSocket *ss, SSL3WaitState ws, { #ifdef TRACE const char *new_state_name = - tls13_HandshakeState(ws); + tls13_HandshakeState(ws); SSL_TRC(3, ("%d: TLS13[%d]: state change from %s->%s in %s (%s:%d)", SSL_GETPID(), ss->fd, @@ -170,7 +174,7 @@ tls13_InHsStateV(sslSocket *ss, va_list ap) { SSL3WaitState ws; - while ((ws = va_arg(ap, SSL3WaitState)) != wait_invalid ) { + while ((ws = va_arg(ap, SSL3WaitState)) != wait_invalid) { if (ws == TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)) { return PR_TRUE; } @@ -244,8 +248,8 @@ tls13_SetupClientHello(sslSocket *ss) /* TODO(ekr@rtfm.com): Handle multiple curves here. */ ECName curves_to_try[] = { ec_secp256r1 }; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); PORT_Assert(!ss->ephemeralECDHKeyPair); @@ -257,10 +261,11 @@ tls13_SetupClientHello(sslSocket *ss) return SECSuccess; } -static SECStatus tls13_HandleECDHEKeyShare(sslSocket *ss, - TLS13KeyShareEntry *entry, - SECKEYPrivateKey *privKey, - SharedSecretType type) +static SECStatus +tls13_HandleECDHEKeyShare(sslSocket *ss, + TLS13KeyShareEntry *entry, + SECKEYPrivateKey *privKey, + SharedSecretType type) { SECStatus rv; SECKEYPublicKey *peerKey; @@ -270,13 +275,13 @@ static SECStatus tls13_HandleECDHEKeyShare(sslSocket *ss, entry->key_exchange.len, entry->group); if (!peerKey) - return SECFailure; /* Error code set already. */ + return SECFailure; /* Error code set already. */ /* Compute shared key. */ shared = tls13_ComputeECDHSharedKey(ss, privKey, peerKey); SECKEY_DestroyPublicKey(peerKey); if (!shared) { - return SECFailure; /* Error code set already. */ + return SECFailure; /* Error code set already. */ } /* Extract key. */ @@ -288,34 +293,34 @@ static SECStatus tls13_HandleECDHEKeyShare(sslSocket *ss, SECStatus tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b, - PRUint32 length, SSL3Hashes *hashesPtr) + PRUint32 length, SSL3Hashes *hashesPtr) { /* TODO(ekr@rtfm.com): Would it be better to check all the states here? */ switch (ss->ssl3.hs.msg_type) { - case certificate: - return tls13_HandleCertificate(ss, b, length); + case certificate: + return tls13_HandleCertificate(ss, b, length); - case certificate_status: - return tls13_HandleCertificateStatus(ss, b, length); + case certificate_status: + return tls13_HandleCertificateStatus(ss, b, length); - case certificate_request: - return tls13_HandleCertificateRequest(ss, b, length); + case certificate_request: + return tls13_HandleCertificateRequest(ss, b, length); - case certificate_verify: - return tls13_HandleCertificateVerify(ss, b, length, hashesPtr); + case certificate_verify: + return tls13_HandleCertificateVerify(ss, b, length, hashesPtr); - case encrypted_extensions: - return tls13_HandleEncryptedExtensions(ss, b, length); + case encrypted_extensions: + return tls13_HandleEncryptedExtensions(ss, b, length); - case new_session_ticket: - return tls13_HandleNewSessionTicket(ss, b, length); + case new_session_ticket: + return tls13_HandleNewSessionTicket(ss, b, length); - case finished: - return tls13_HandleFinished(ss, b, length, hashesPtr); + case finished: + return tls13_HandleFinished(ss, b, length, hashesPtr); - default: - FATAL_ERROR(ss, SSL_ERROR_RX_UNKNOWN_HANDSHAKE, unexpected_message); - return SECFailure; + default: + FATAL_ERROR(ss, SSL_ERROR_RX_UNKNOWN_HANDSHAKE, unexpected_message); + return SECFailure; } PORT_Assert(0); /* Unreached */ @@ -331,14 +336,14 @@ tls13_HandleClientKeyShare(sslSocket *ss) { ECName expectedGroup; SECStatus rv; - TLS13KeyShareEntry* found = NULL; + TLS13KeyShareEntry *found = NULL; PRCList *cur_p; SSL_TRC(3, ("%d: TLS13[%d]: handle client_key_share handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = ssl3_SetupPendingCipherSpec(ss); if (rv != SECSuccess) @@ -347,27 +352,27 @@ tls13_HandleClientKeyShare(sslSocket *ss) /* Figure out what group we expect */ switch (ss->ssl3.hs.kea_def->exchKeyType) { #ifndef NSS_DISABLE_ECC - case ssl_kea_ecdh: - expectedGroup = ssl3_GetCurveNameForServerSocket(ss); - if (!expectedGroup) { - FATAL_ERROR(ss, SSL_ERROR_NO_CYPHER_OVERLAP, - handshake_failure); - return SECFailure; - } - break; + case ssl_kea_ecdh: + expectedGroup = ssl3_GetCurveNameForServerSocket(ss); + if (!expectedGroup) { + FATAL_ERROR(ss, SSL_ERROR_NO_CYPHER_OVERLAP, + handshake_failure); + return SECFailure; + } + break; #endif - default: - /* Got an unknown or unsupported Key Exchange Algorithm. - * Can't happen. */ - FATAL_ERROR(ss, SEC_ERROR_UNSUPPORTED_KEYALG, - internal_error); - return SECFailure; + default: + /* Got an unknown or unsupported Key Exchange Algorithm. + * Can't happen. */ + FATAL_ERROR(ss, SEC_ERROR_UNSUPPORTED_KEYALG, + internal_error); + return SECFailure; } /* Now walk through the keys until we find one for our group */ cur_p = PR_NEXT_LINK(&ss->ssl3.hs.remoteKeyShares); while (cur_p != &ss->ssl3.hs.remoteKeyShares) { - TLS13KeyShareEntry *offer = (TLS13KeyShareEntry*)cur_p; + TLS13KeyShareEntry *offer = (TLS13KeyShareEntry *)cur_p; if (offer->group == expectedGroup) { found = offer; @@ -390,7 +395,7 @@ tls13_HandleClientKeyShare(sslSocket *ss) if (rv != SECSuccess) return rv; - ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits( ss->ephemeralECDHKeyPair->pubKey); @@ -398,18 +403,17 @@ tls13_HandleClientKeyShare(sslSocket *ss) rv = ssl3_RegisterServerHelloExtensionSender(ss, ssl_tls13_key_share_xtn, tls13_ServerSendKeyShareXtn); if (rv != SECSuccess) - return SECFailure; /* Error code set below */ + return SECFailure; /* Error code set below */ rv = tls13_HandleECDHEKeyShare(ss, found, ss->ephemeralECDHKeyPair->privKey, EphemeralSharedSecret); if (rv != SECSuccess) - return SECFailure; /* Error code set below */ + return SECFailure; /* Error code set below */ return SECSuccess; } - /* * [draft-ietf-tls-tls13-11] Section 6.3.3.2 * @@ -444,7 +448,6 @@ tls13_SendCertificateRequest(sslSocket *ss) SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request", SSL_GETPID(), ss->fd)); - /* Fixed context value. */ ss->ssl3.hs.certReqContext[0] = 0; ss->ssl3.hs.certReqContextLen = 1; @@ -456,35 +459,35 @@ tls13_SendCertificateRequest(sslSocket *ss) } ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames); - length = 1 + ss->ssl3.hs.certReqContextLen - + 2 + sigAlgsLength + 2 + calen + 2; + length = 1 + ss->ssl3.hs.certReqContextLen + + 2 + sigAlgsLength + 2 + calen + 2; rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.hs.certReqContext, ss->ssl3.hs.certReqContextLen, 1); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeNumber(ss, calen, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } for (i = 0, name = names; i < nnames; i++, name++) { rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } } rv = ssl3_AppendHandshakeNumber(ss, 0, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } return SECSuccess; @@ -494,8 +497,8 @@ static SECStatus tls13_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { SECStatus rv; - SECItem context = {siBuffer, NULL, 0}; - SECItem algorithms = {siBuffer, NULL, 0}; + SECItem context = { siBuffer, NULL, 0 }; + SECItem algorithms = { siBuffer, NULL, 0 }; PLArenaPool *arena; CERTDistNames ca_list; PRInt32 extensionsLength; @@ -503,8 +506,8 @@ tls13_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_request sequence", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* Client */ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, wait_cert_request); @@ -602,37 +605,37 @@ tls13_SendServerHelloSequence(sslSocket *ss) SSL_TRC(3, ("%d: TLS13[%d]: begin send server_hello sequence", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); rv = ssl3_SendServerHello(ss); if (rv != SECSuccess) { - return rv; /* err code is set. */ + return rv; /* err code is set. */ } rv = tls13_InitializeHandshakeEncryption(ss); if (rv != SECSuccess) { - return SECFailure; /* error code is set. */ + return SECFailure; /* error code is set. */ } rv = tls13_SendEncryptedExtensions(ss); if (rv != SECSuccess) { - return SECFailure; /* error code is set. */ + return SECFailure; /* error code is set. */ } if (ss->opt.requestCertificate) { rv = tls13_SendCertificateRequest(ss); if (rv != SECSuccess) { - return SECFailure; /* error code is set. */ + return SECFailure; /* error code is set. */ } } rv = ssl3_SendCertificate(ss); if (rv != SECSuccess) { - return SECFailure; /* error code is set. */ + return SECFailure; /* error code is set. */ } rv = ssl3_SendCertificateStatus(ss); if (rv != SECSuccess) { - return SECFailure; /* error code is set. */ + return SECFailure; /* error code is set. */ } /* This was copied from: ssl3_SendCertificate. @@ -642,12 +645,13 @@ tls13_SendServerHelloSequence(sslSocket *ss) if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { certIndex = kt_rsa; - } else { + } + else { certIndex = ss->ssl3.hs.kea_def->exchKeyType; } rv = ssl3_SendCertificateVerify(ss, ss->serverCerts[certIndex].SERVERKEY); if (rv != SECSuccess) { - return rv; /* err code is set. */ + return rv; /* err code is set. */ } /* Compute the rest of the secrets except for the resumption @@ -660,11 +664,11 @@ tls13_SendServerHelloSequence(sslSocket *ss) rv = tls13_SendFinished(ss); if (rv != SECSuccess) { - return rv; /* error code is set. */ + return rv; /* error code is set. */ } - TLS13_SET_HS_STATE(ss, ss->opt.requestCertificate ? - wait_client_cert : wait_finished); + TLS13_SET_HS_STATE(ss, ss->opt.requestCertificate ? wait_client_cert + : wait_finished); return SECSuccess; } @@ -684,18 +688,18 @@ tls13_HandleServerKeyShare(sslSocket *ss) SSL_TRC(3, ("%d: TLS13[%d]: handle server_key_share handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); switch (ss->ssl3.hs.kea_def->exchKeyType) { #ifndef NSS_DISABLE_ECC - case ssl_kea_ecdh: - expectedGroup = ssl3_PubKey2ECName(ss->ephemeralECDHKeyPair->pubKey); - break; + case ssl_kea_ecdh: + expectedGroup = ssl3_PubKey2ECName(ss->ephemeralECDHKeyPair->pubKey); + break; #endif /* NSS_DISABLE_ECC */ - default: - FATAL_ERROR(ss, SEC_ERROR_UNSUPPORTED_KEYALG, handshake_failure); - return SECFailure; + default: + FATAL_ERROR(ss, SEC_ERROR_UNSUPPORTED_KEYALG, handshake_failure); + return SECFailure; } /* This list should have one entry. */ @@ -706,7 +710,7 @@ tls13_HandleServerKeyShare(sslSocket *ss) } PORT_Assert(PR_NEXT_LINK(cur_p) == &ss->ssl3.hs.remoteKeyShares); - entry = (TLS13KeyShareEntry*)cur_p; + entry = (TLS13KeyShareEntry *)cur_p; if (entry->group != expectedGroup) { FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_SHARE, illegal_parameter); return SECFailure; @@ -716,12 +720,12 @@ tls13_HandleServerKeyShare(sslSocket *ss) ss->ephemeralECDHKeyPair->privKey, EphemeralSharedSecret); - ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits( ss->ephemeralECDHKeyPair->pubKey); if (rv != SECSuccess) - return SECFailure; /* Error code set below */ + return SECFailure; /* Error code set below */ return tls13_InitializeHandshakeEncryption(ss); } @@ -734,17 +738,18 @@ static SECStatus tls13_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { SECStatus rv; - SECItem context = {siBuffer, NULL, 0}; + SECItem context = { siBuffer, NULL, 0 }; SSL_TRC(3, ("%d: TLS13[%d]: handle certificate handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->sec.isServer) { rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, wait_client_cert); - } else { + } + else { rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, wait_cert_request, wait_server_cert); } @@ -762,7 +767,8 @@ tls13_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) illegal_parameter); return SECFailure; } - } else { + } + else { if (!context.len || context.len != ss->ssl3.hs.certReqContextLen || (NSS_SecureMemcmp(ss->ssl3.hs.certReqContext, context.data, context.len) != 0)) { @@ -773,7 +779,6 @@ tls13_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) context.len = 0; /* Belt and suspenders. Zero out the context. */ } - return ssl3_CompleteHandleCertificate(ss, b, length); } @@ -805,31 +810,27 @@ tls13_InstallCipherSpec(sslSocket *ss, InstallCipherSpecDirection direction) SSL_GETPID(), ss->fd, direction == InstallCipherSpecRead ? "read" : "write")); - PORT_Assert(!IS_DTLS(ss)); /* TODO(ekr@rtfm.com): Update for DTLS */ + PORT_Assert(!IS_DTLS(ss)); /* TODO(ekr@rtfm.com): Update for DTLS */ /* TODO(ekr@rtfm.com): Holddown timer for DTLS. */ - ssl_GetSpecWriteLock(ss); /**************************************/ + ssl_GetSpecWriteLock(ss); /**************************************/ /* Flush out any old stuff in the handshake buffers */ switch (direction) { - case InstallCipherSpecWrite: - { - ssl3CipherSpec *pwSpec; - pwSpec = ss->ssl3.pwSpec; + case InstallCipherSpecWrite: { + ssl3CipherSpec *pwSpec; + pwSpec = ss->ssl3.pwSpec; - ss->ssl3.pwSpec = ss->ssl3.cwSpec; - ss->ssl3.cwSpec = pwSpec; - break; - } + ss->ssl3.pwSpec = ss->ssl3.cwSpec; + ss->ssl3.cwSpec = pwSpec; break; - case InstallCipherSpecRead: - { - ssl3CipherSpec *prSpec; + } break; + case InstallCipherSpecRead: { + ssl3CipherSpec *prSpec; - prSpec = ss->ssl3.prSpec; - ss->ssl3.prSpec = ss->ssl3.crSpec; - ss->ssl3.crSpec = prSpec; - } - break; + prSpec = ss->ssl3.prSpec; + ss->ssl3.prSpec = ss->ssl3.crSpec; + ss->ssl3.crSpec = prSpec; + } break; default: PORT_Assert(0); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); @@ -841,7 +842,7 @@ tls13_InstallCipherSpec(sslSocket *ss, InstallCipherSpecDirection direction) * (Both the read and write sides have changed) destroy it. */ if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { - ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/); + ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE /*freeSrvName*/); } ssl_ReleaseSpecWriteLock(ss); /**************************************/ @@ -855,7 +856,7 @@ tls13_AddContextToHashes(sslSocket *ss, SSL3Hashes *hashes /* IN/OUT */, SSLHashType algorithm, PRBool sending) { SECStatus rv = SECSuccess; - PK11Context* ctx; + PK11Context *ctx; const unsigned char context_padding[] = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, @@ -868,8 +869,8 @@ tls13_AddContextToHashes(sslSocket *ss, SSL3Hashes *hashes /* IN/OUT */, }; const char *client_cert_verify_string = "TLS 1.3, client CertificateVerify"; const char *server_cert_verify_string = "TLS 1.3, server CertificateVerify"; - const char *context_string = (sending ^ ss->sec.isServer) ? - client_cert_verify_string : server_cert_verify_string; + const char *context_string = (sending ^ ss->sec.isServer) ? client_cert_verify_string + : server_cert_verify_string; unsigned int hashlength; /* Double check that we are doing SHA-256 for the handshake hash.*/ @@ -913,12 +914,12 @@ loser: } static SECStatus -tls13_HkdfExtractSharedKey(sslSocket *ss, PK11SymKey* key, +tls13_HkdfExtractSharedKey(sslSocket *ss, PK11SymKey *key, SharedSecretType keyType) { - PK11SymKey** destp; + PK11SymKey **destp; - switch(keyType) { + switch (keyType) { case EphemeralSharedSecret: destp = &ss->ssl3.hs.xES; break; @@ -941,9 +942,9 @@ tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *pwSpec, { size_t keySize = pwSpec->cipher_def->key_size; size_t ivSize = pwSpec->cipher_def->iv_size + - pwSpec->cipher_def->explicit_nonce_size; /* This isn't always going to - * work, but it does for - * AES-GCM */ + pwSpec->cipher_def->explicit_nonce_size; /* This isn't always going to + * work, but it does for + * AES-GCM */ CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(pwSpec->cipher_def->calg); SSL3Hashes hashes; PK11SymKey *prk = NULL; @@ -951,27 +952,28 @@ tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *pwSpec, char label[256]; /* Arbitrary buffer large enough to hold the label */ SECStatus rv; -#define FORMAT_LABEL(phase_, purpose_) do { \ +#define FORMAT_LABEL(phase_, purpose_) \ + do { \ PRUint32 n = PR_snprintf(label, sizeof(label), "%s, %s", phase_, purpose_); \ - /* Check for getting close. */ \ - if ((n+1) >= sizeof(label)) { \ - PORT_Assert(0); \ - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); \ - goto loser; \ - } \ - } while(0) -#define EXPAND_TRAFFIC_KEY(purpose_, target_) \ - do { \ - FORMAT_LABEL(phase, purpose_); \ - rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss), \ - hashes.u.raw, hashes.len, \ - label, strlen(label), \ + /* Check for getting close. */ \ + if ((n + 1) >= sizeof(label)) { \ + PORT_Assert(0); \ + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); \ + goto loser; \ + } \ + } while (0) +#define EXPAND_TRAFFIC_KEY(purpose_, target_) \ + do { \ + FORMAT_LABEL(phase, purpose_); \ + rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss), \ + hashes.u.raw, hashes.len, \ + label, strlen(label), \ bulkAlgorithm, keySize, &pwSpec->target_); \ - if (rv != SECSuccess) { \ - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); \ - PORT_Assert(0); \ - goto loser; \ - } \ + if (rv != SECSuccess) { \ + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); \ + PORT_Assert(0); \ + goto loser; \ + } \ } while (0) #define EXPAND_TRAFFIC_IV(purpose_, target_) \ @@ -988,14 +990,13 @@ tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *pwSpec, } \ } while (0) - PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0); if (rv != SECSuccess) { - PORT_Assert(0); /* Should never fail */ + PORT_Assert(0); /* Should never fail */ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return SECFailure; } @@ -1040,7 +1041,7 @@ tls13_InitCipherSpec(sslSocket *ss, TrafficKeyType type, InstallCipherSpecDirect ssl3CipherSpec *pwSpec; ssl3CipherSpec *cwSpec; SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (install == InstallCipherSpecWrite || install == InstallCipherSpecBoth) { @@ -1053,14 +1054,14 @@ tls13_InitCipherSpec(sslSocket *ss, TrafficKeyType type, InstallCipherSpecDirect } } - ssl_GetSpecWriteLock(ss); /**************************************/ + ssl_GetSpecWriteLock(ss); /**************************************/ PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); pwSpec = ss->ssl3.pwSpec; cwSpec = ss->ssl3.cwSpec; - switch(pwSpec->cipher_def->calg) { + switch (pwSpec->cipher_def->calg) { case calg_aes_gcm: pwSpec->aead = tls13_AESGCM; break; @@ -1073,7 +1074,8 @@ tls13_InitCipherSpec(sslSocket *ss, TrafficKeyType type, InstallCipherSpecDirect /* Generic behaviors -- common to all crypto methods */ if (!IS_DTLS(ss)) { pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; - } else { + } + else { if (cwSpec->epoch == PR_UINT16_MAX) { /* The problem here is that we have rehandshaked too many * times (you are not allowed to wrap the epoch). The @@ -1109,12 +1111,12 @@ tls13_InitCipherSpec(sslSocket *ss, TrafficKeyType type, InstallCipherSpecDirect goto loser; } } - ssl_ReleaseSpecWriteLock(ss); /**************************************/ + ssl_ReleaseSpecWriteLock(ss); /**************************************/ return SECSuccess; loser: - ssl_ReleaseSpecWriteLock(ss); /**************************************/ + ssl_ReleaseSpecWriteLock(ss); /**************************************/ PORT_SetError(SSL_ERROR_INIT_CIPHER_SUITE_FAILURE); return SECFailure; } @@ -1130,12 +1132,12 @@ tls13_ComputeSecrets1(sslSocket *ss) rv = ssl3_SetupPendingCipherSpec(ss); if (rv != SECSuccess) { - return rv; /* error code set below. */ + return rv; /* error code set below. */ } rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); if (rv != SECSuccess) { - PORT_Assert(0); /* Should never fail */ + PORT_Assert(0); /* Should never fail */ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return SECFailure; } @@ -1208,7 +1210,9 @@ tls13_ComputeSecrets1(sslSocket *ss) loser: PK11_FreeSymKey(ss->ssl3.hs.xSS); + ss->ssl3.hs.xSS = NULL; PK11_FreeSymKey(ss->ssl3.hs.xES); + ss->ssl3.hs.xES = NULL; if (mSS) { PK11_FreeSymKey(mSS); @@ -1290,12 +1294,12 @@ tls13_AESGCM(ssl3KeyMaterial *keys, * */ memcpy(nonce, keys->write_iv, sizeof(nonce)); - for (i=0; i < 8; ++i) { + for (i = 0; i < 8; ++i) { nonce[4 + i] ^= seqNumBuf[i]; } param.type = siBuffer; - param.data = (unsigned char *) &gcmParams; + param.data = (unsigned char *)&gcmParams; param.len = sizeof(gcmParams); gcmParams.pIv = nonce; gcmParams.ulIvLen = sizeof(nonce); @@ -1306,7 +1310,8 @@ tls13_AESGCM(ssl3KeyMaterial *keys, if (doDecrypt) { rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, maxout, in, inlen); - } else { + } + else { rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, maxout, in, inlen); } @@ -1319,12 +1324,13 @@ static SECStatus tls13_HandleEncryptedExtensions(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { SECStatus rv; + PRInt32 innerLength; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS, wait_encrypted_extensions); @@ -1332,9 +1338,19 @@ tls13_HandleEncryptedExtensions(sslSocket *ss, SSL3Opaque *b, PRUint32 length) return SECFailure; } + innerLength = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); + if (innerLength < 0) { + return SECFailure; /* Alert already sent. */ + } + if (innerLength != length) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS, + illegal_parameter); + return SECFailure; + } + rv = ssl3_HandleHelloExtensions(ss, &b, &length, encrypted_extensions); if (rv != SECSuccess) { - return SECFailure; /* Error code set below */ + return SECFailure; /* Error code set below */ } TLS13_SET_HS_STATE(ss, wait_cert_request); @@ -1352,20 +1368,26 @@ tls13_SendEncryptedExtensions(sslSocket *ss) SSL_TRC(3, ("%d: TLS13[%d]: send encrypted extensions handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); extensions_len = ssl3_CallHelloExtensionSenders( ss, PR_FALSE, maxBytes, &ss->xtnData.encryptedExtensionsSenders[0]); - rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions, extensions_len); + rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions, + extensions_len + 2); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); if (rv != SECSuccess) { FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); return SECFailure; } - sent_len = ssl3_CallHelloExtensionSenders( - ss, PR_TRUE, extensions_len, &ss->xtnData.encryptedExtensionsSenders[0]); + ss, PR_TRUE, extensions_len, + &ss->xtnData.encryptedExtensionsSenders[0]); PORT_Assert(sent_len == extensions_len); if (sent_len != extensions_len) { PORT_Assert(sent_len == 0); @@ -1384,14 +1406,14 @@ SECStatus tls13_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length, SSL3Hashes *hashes) { - SECItem signed_hash = {siBuffer, NULL, 0}; - SECStatus rv; + SECItem signed_hash = { siBuffer, NULL, 0 }; + SECStatus rv; SSLSignatureAndHashAlg sigAndHash; SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_verify handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY, wait_cert_verify); @@ -1478,8 +1500,8 @@ tls13_ComputeFinished(sslSocket *ss, const SSL3Hashes *hashes, PRBool sending, CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanism(ss); SECItem param = { siBuffer, NULL, 0 }; unsigned int outputLenUint; - PK11SymKey *secret = (ss->sec.isServer ^ sending) ? - ss->ssl3.hs.clientFinishedSecret : ss->ssl3.hs.serverFinishedSecret; + PK11SymKey *secret = (ss->sec.isServer ^ sending) ? ss->ssl3.hs.clientFinishedSecret + : ss->ssl3.hs.serverFinishedSecret; PORT_Assert(secret); PRINT_BUF(90, (NULL, "Handshake hash", hashes->u.raw, hashes->len)); @@ -1527,8 +1549,8 @@ tls13_SendFinished(sslSocket *ss) SSL_TRC(3, ("%d: TLS13[%d]: send finished handshake", SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0); if (rv != SECSuccess) { @@ -1563,13 +1585,15 @@ tls13_SendFinished(sslSocket *ss) goto alert_loser; } - if (!ss->sec.isServer) { + if (ss->sec.isServer) { rv = tls13_InitCipherSpec(ss, TrafficKeyApplicationData, - InstallCipherSpecBoth); - if (rv != SECSuccess) { - errCode = PR_GetError(); - goto alert_loser; - } + InstallCipherSpecWrite); + } else { + rv = tls13_InstallCipherSpec(ss, InstallCipherSpecWrite); + } + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } /* TODO(ekr@rtfm.com): Record key log */ @@ -1577,7 +1601,7 @@ tls13_SendFinished(sslSocket *ss) alert_loser: (void)SSL3_SendAlert(ss, alert_fatal, internal_error); - PORT_SetError(errCode); /* Restore error code */ + PORT_SetError(errCode); /* Restore error code */ return rv; } @@ -1589,11 +1613,11 @@ tls13_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, PRUint8 finishedBuf[MAX_FINISHED_SIZE]; unsigned int finishedLen; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); SSL_TRC(3, ("%d: TLS13[%d]: handle finished handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED, wait_finished); if (rv != SECSuccess) { @@ -1629,24 +1653,31 @@ tls13_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, */ /* TODO(ekr@rtfm.com): Send NewSession Ticket if server. */ if (ss->sec.isServer) { - rv = tls13_InitCipherSpec(ss, TrafficKeyApplicationData, - InstallCipherSpecBoth); + rv = tls13_InstallCipherSpec(ss, InstallCipherSpecRead); if (rv != SECSuccess) { FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); return SECFailure; } rv = tls13_FinishHandshake(ss); - } else { + } + else { if (ss->ssl3.hs.authCertificatePending) { /* TODO(ekr@rtfm.com): Handle pending auth */ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); PORT_Assert(0); return SECFailure; } + rv = tls13_InitCipherSpec(ss, TrafficKeyApplicationData, + InstallCipherSpecRead); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + rv = tls13_SendClientSecondRound(ss); if (rv != SECSuccess) - return SECFailure; /* Error code and alerts handled below */ + return SECFailure; /* Error code and alerts handled below */ } return rv; @@ -1655,12 +1686,12 @@ tls13_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, static SECStatus tls13_FinishHandshake(sslSocket *ss) { - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->ssl3.hs.restartTarget == NULL ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.hs.restartTarget == NULL); /* The first handshake is now completed. */ - ss->handshake = NULL; + ss->handshake = NULL; TLS13_SET_HS_STATE(ss, idle_handshake); @@ -1675,11 +1706,11 @@ tls13_SendClientSecondRound(sslSocket *ss) SECStatus rv; PRBool sendClientCert; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); sendClientCert = !ss->ssl3.sendEmptyCert && - ss->ssl3.clientCertChain != NULL && + ss->ssl3.clientCertChain != NULL && ss->ssl3.clientPrivateKey != NULL; /* Defer client authentication sending if we are still @@ -1700,18 +1731,19 @@ tls13_SendClientSecondRound(sslSocket *ss) return SECWouldBlock; } - ssl_GetXmitBufLock(ss); /*******************************/ + ssl_GetXmitBufLock(ss); /*******************************/ if (ss->ssl3.sendEmptyCert) { ss->ssl3.sendEmptyCert = PR_FALSE; rv = ssl3_SendEmptyCertificate(ss); /* Don't send verify */ if (rv != SECSuccess) { - goto loser; /* error code is set. */ + goto loser; /* error code is set. */ } - } else if (sendClientCert) { + } + else if (sendClientCert) { rv = ssl3_SendCertificate(ss); if (rv != SECSuccess) { - goto loser; /* error code is set. */ + goto loser; /* error code is set. */ } } @@ -1720,21 +1752,21 @@ tls13_SendClientSecondRound(sslSocket *ss) SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); ss->ssl3.clientPrivateKey = NULL; if (rv != SECSuccess) { - goto loser; /* err is set. */ + goto loser; /* err is set. */ } } rv = tls13_SendFinished(ss); if (rv != SECSuccess) { - goto loser; /* err code was set. */ + goto loser; /* err code was set. */ } - ssl_ReleaseXmitBufLock(ss); /*******************************/ + ssl_ReleaseXmitBufLock(ss); /*******************************/ /* The handshake is now finished */ return tls13_FinishHandshake(ss); loser: - ssl_ReleaseXmitBufLock(ss); /*******************************/ + ssl_ReleaseXmitBufLock(ss); /*******************************/ return SECFailure; } @@ -1755,77 +1787,49 @@ tls13_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) return SECSuccess; } - typedef enum { ExtensionNotUsed, ExtensionClientOnly, ExtensionSendClear, ExtensionSendEncrypted, - ExtensionUnknown, } Tls13ExtensionStatus; static const struct { SSLExtensionType ex_value; Tls13ExtensionStatus status; } KnownExtensions[] = { - { - ssl_server_name_xtn, - ExtensionSendEncrypted - }, + { ssl_server_name_xtn, + ExtensionSendEncrypted }, { ssl_cert_status_xtn, ExtensionNotUsed /* TODO(ekr@rtfm.com): Disabled because broken in TLS 1.3. */ /* ExtensionSendEncrypted */ }, - { - ssl_elliptic_curves_xtn, - ExtensionSendClear - }, - { - ssl_ec_point_formats_xtn, - ExtensionNotUsed - }, - { - ssl_signature_algorithms_xtn, - ExtensionClientOnly - }, - { - ssl_use_srtp_xtn, - ExtensionSendEncrypted - }, - { - ssl_app_layer_protocol_xtn, - ExtensionSendEncrypted - }, - { - ssl_padding_xtn, - ExtensionNotUsed - }, - { - ssl_extended_master_secret_xtn, - ExtensionNotUsed - }, - { - ssl_session_ticket_xtn, - ExtensionClientOnly - }, - { - ssl_tls13_key_share_xtn, - ExtensionSendClear - }, - { - ssl_next_proto_nego_xtn, - ExtensionNotUsed - }, - { - ssl_renegotiation_info_xtn, - ExtensionNotUsed - }, - { - ssl_tls13_draft_version_xtn, - ExtensionClientOnly - } + { ssl_elliptic_curves_xtn, + ExtensionSendClear }, + { ssl_ec_point_formats_xtn, + ExtensionNotUsed }, + { ssl_signature_algorithms_xtn, + ExtensionClientOnly }, + { ssl_use_srtp_xtn, + ExtensionSendEncrypted }, + { ssl_app_layer_protocol_xtn, + ExtensionSendEncrypted }, + { ssl_padding_xtn, + ExtensionNotUsed }, + { ssl_extended_master_secret_xtn, + ExtensionNotUsed }, + { ssl_session_ticket_xtn, + ExtensionClientOnly }, + { ssl_tls13_key_share_xtn, + ExtensionSendClear }, + { ssl_next_proto_nego_xtn, + ExtensionNotUsed }, + { ssl_renegotiation_info_xtn, + ExtensionNotUsed }, + { ssl_tls13_draft_version_xtn, + ExtensionClientOnly } }; PRBool @@ -1838,24 +1842,26 @@ tls13_ExtensionAllowed(PRUint16 extension, SSL3HandshakeType message) (message == encrypted_extensions)); for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions); i++) { - if (KnownExtensions[i].ex_value == extension) { + if (KnownExtensions[i].ex_value == extension) break; - } + } + if (i == PR_ARRAY_SIZE(KnownExtensions)) { + /* We have never heard of this extension which is OK on + * the server but not the client. */ + return message == client_hello; } - switch(KnownExtensions[i].status) { + switch (KnownExtensions[i].status) { case ExtensionNotUsed: return PR_FALSE; case ExtensionClientOnly: return message == client_hello; case ExtensionSendClear: return message == client_hello || - message == server_hello; + message == server_hello; case ExtensionSendEncrypted: return message == client_hello || - message == encrypted_extensions; - case ExtensionUnknown: - return PR_TRUE; + message == encrypted_extensions; } PORT_Assert(0); @@ -1873,7 +1879,7 @@ tls13_EncodeUintX(PRUint32 value, unsigned int bytes, unsigned char *to) PORT_Assert(bytes > 0 && bytes <= 4); encoded = PR_htonl(value); - memcpy(to, ((unsigned char *)(&encoded)) + (4-bytes), bytes); + memcpy(to, ((unsigned char *)(&encoded)) + (4 - bytes), bytes); return to + bytes; } @@ -1902,7 +1908,7 @@ tls13_ProtectRecord(sslSocket *ss, sslBuffer *wrBuf) { ssl3CipherSpec *cwSpec = ss->ssl3.cwSpec; - const ssl3BulkCipherDef* cipher_def = cwSpec->cipher_def; + const ssl3BulkCipherDef *cipher_def = cwSpec->cipher_def; SECStatus rv; PRUint16 headerLen; int cipherBytes = 0; @@ -1911,8 +1917,7 @@ tls13_ProtectRecord(sslSocket *ss, SSL_TRC(3, ("%d: TLS13[%d]: protect record of length %u, seq=0x%0x%0x", SSL_GETPID(), ss->fd, contentLen, cwSpec->write_seq_num.high, - cwSpec->write_seq_num.low - )); + cwSpec->write_seq_num.low)); headerLen = IS_DTLS(ss) ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; @@ -1928,7 +1933,8 @@ tls13_ProtectRecord(sslSocket *ss, if (cipher_def->calg == ssl_calg_null) { /* Shortcut for plaintext */ cipherBytes = contentLen; - } else { + } + else { unsigned char aad[8]; PORT_Assert(cipher_def->type == type_aead); @@ -1943,11 +1949,11 @@ tls13_ProtectRecord(sslSocket *ss, cipherBytes = contentLen + 1; /* Room for the content type on the end. */ rv = cwSpec->aead( ss->sec.isServer ? &cwSpec->server : &cwSpec->client, - PR_FALSE, /* do encrypt */ - wrBuf->buf + headerLen, /* output */ - &cipherBytes, /* out len */ - wrBuf->space - headerLen, /* max out */ - wrBuf->buf + headerLen, contentLen + 1, /* input */ + PR_FALSE, /* do encrypt */ + wrBuf->buf + headerLen, /* output */ + &cipherBytes, /* out len */ + wrBuf->space - headerLen, /* max out */ + wrBuf->buf + headerLen, contentLen + 1, /* input */ aad, sizeof(aad)); if (rv != SECSuccess) { PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); @@ -1962,11 +1968,12 @@ tls13_ProtectRecord(sslSocket *ss, if (IS_DTLS(ss)) { (void)tls13_EncodeUintX(2, dtls_TLSVersionToDTLSVersion(kRecordVersion), - &wrBuf->buf[1]); + &wrBuf->buf[1]); (void)tls13_EncodeUintX(cwSpec->write_seq_num.high, 4, &wrBuf->buf[3]); (void)tls13_EncodeUintX(cwSpec->write_seq_num.low, 4, &wrBuf->buf[7]); (void)tls13_EncodeUintX(cipherBytes, 2, &wrBuf->buf[11]); - } else { + } + else { (void)tls13_EncodeUintX(kRecordVersion, 2, &wrBuf->buf[1]); (void)tls13_EncodeUintX(cipherBytes, 2, &wrBuf->buf[3]); } @@ -1975,7 +1982,6 @@ tls13_ProtectRecord(sslSocket *ss, return SECSuccess; } - /* Unprotect a TLS 1.3 record and leave the result in plaintext. * * Called by ssl3_HandleRecord. Caller must hold the spec read lock. @@ -1986,8 +1992,8 @@ tls13_ProtectRecord(sslSocket *ss, * 2. Call PORT_SetError() witn an appropriate code. */ SECStatus -tls13_UnprotectRecord(sslSocket* ss, SSL3Ciphertext *cText, sslBuffer *plaintext, - SSL3AlertDescription* alert) +tls13_UnprotectRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *plaintext, + SSL3AlertDescription *alert) { ssl3CipherSpec *crSpec = ss->ssl3.crSpec; const ssl3BulkCipherDef *cipher_def = crSpec->cipher_def; @@ -2006,6 +2012,13 @@ tls13_UnprotectRecord(sslSocket* ss, SSL3Ciphertext *cText, sslBuffer *plaintext return SECFailure; } + /* Verify that the content type is right, even though we overwrite it. */ + if (cText->type != content_application_data) { + /* Do we need a better error here? */ + PORT_SetError(SSL_ERROR_BAD_MAC_READ); + return SECFailure; + } + /* Check the version number in the record */ if (cText->version != kRecordVersion) { /* Do we need a better error here? */ @@ -2017,16 +2030,17 @@ tls13_UnprotectRecord(sslSocket* ss, SSL3Ciphertext *cText, sslBuffer *plaintext PORT_Assert(cipher_def->type == type_aead); tls13_FormatAdditionalData(aad, sizeof(aad), IS_DTLS(ss) ? - cText->seq_num : - crSpec->read_seq_num); + cText->seq_num + : + crSpec->read_seq_num); rv = crSpec->aead( ss->sec.isServer ? &crSpec->client : &crSpec->server, - PR_TRUE, /* do decrypt */ - plaintext->buf, /* out */ - (int*) &plaintext->len, /* outlen */ - plaintext->space, /* maxout */ - cText->buf->buf, /* in */ - cText->buf->len, /* inlen */ + PR_TRUE, /* do decrypt */ + plaintext->buf, /* out */ + (int *)&plaintext->len, /* outlen */ + plaintext->space, /* maxout */ + cText->buf->buf, /* in */ + cText->buf->len, /* inlen */ aad, sizeof(aad)); if (rv != SECSuccess) { PORT_SetError(SSL_ERROR_BAD_MAC_READ); @@ -2036,7 +2050,7 @@ tls13_UnprotectRecord(sslSocket* ss, SSL3Ciphertext *cText, sslBuffer *plaintext /* The record is right-padded with 0s, followed by the true * content type, so read from the right until we receive a * nonzero byte. */ - while (plaintext->len > 0 && !(plaintext->buf[plaintext->len-1])) { + while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) { --plaintext->len; } @@ -2049,7 +2063,7 @@ tls13_UnprotectRecord(sslSocket* ss, SSL3Ciphertext *cText, sslBuffer *plaintext } /* Record the type. */ - cText->type = plaintext->buf[plaintext->len-1]; + cText->type = plaintext->buf[plaintext->len - 1]; --plaintext->len; return SECSuccess; diff --git a/security/nss/lib/ssl/tls13con.h b/security/nss/lib/ssl/tls13con.h index 1d25944347a8..a96d3236794e 100644 --- a/security/nss/lib/ssl/tls13con.h +++ b/security/nss/lib/ssl/tls13con.h @@ -15,7 +15,7 @@ typedef enum { } SharedSecretType; SECStatus tls13_UnprotectRecord( - sslSocket* ss, SSL3Ciphertext *cText, sslBuffer *plaintext, + sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *plaintext, SSL3AlertDescription *alert); unsigned char * tls13_EncodeUintX(PRUint32 value, unsigned int bytes, unsigned char *to); diff --git a/security/nss/lib/ssl/tls13hkdf.c b/security/nss/lib/ssl/tls13hkdf.c index fdcbfa2db660..637970b14226 100644 --- a/security/nss/lib/ssl/tls13hkdf.c +++ b/security/nss/lib/ssl/tls13hkdf.c @@ -32,7 +32,7 @@ static const struct { }; SECStatus -tls13_HkdfExtract(PK11SymKey* ikm1, PK11SymKey* ikm2, SSLHashType baseHash, +tls13_HkdfExtract(PK11SymKey *ikm1, PK11SymKey *ikm2, SSLHashType baseHash, PK11SymKey **prkp) { CK_NSS_HKDFParams params; @@ -60,7 +60,8 @@ tls13_HkdfExtract(PK11SymKey* ikm1, PK11SymKey* ikm2, SSLHashType baseHash, params.pSalt = salt->data; params.ulSaltLen = salt->len; PORT_Assert(salt->len > 0); - } else { + } + else { /* Per documentation for CKM_NSS_HKDF_*: * * If the optional salt is given, it is used; otherwise, the salt is @@ -74,7 +75,7 @@ tls13_HkdfExtract(PK11SymKey* ikm1, PK11SymKey* ikm2, SSLHashType baseHash, PORT_Assert(kTlsHkdfInfo[baseHash].pkcs11Mech); PORT_Assert(kTlsHkdfInfo[baseHash].hashSize); - PORT_Assert(kTlsHkdfInfo[baseHash].hash==baseHash); + PORT_Assert(kTlsHkdfInfo[baseHash].hash == baseHash); prk = PK11_Derive(ikm2, kTlsHkdfInfo[baseHash].pkcs11Mech, ¶msi, kTlsHkdfInfo[baseHash].pkcs11Mech, CKA_DERIVE, kTlsHkdfInfo[baseHash].hashSize); @@ -86,14 +87,14 @@ tls13_HkdfExtract(PK11SymKey* ikm1, PK11SymKey* ikm2, SSLHashType baseHash, } SECStatus -tls13_HkdfExpandLabel(PK11SymKey* prk, SSLHashType baseHash, +tls13_HkdfExpandLabel(PK11SymKey *prk, SSLHashType baseHash, const PRUint8 *handshakeHash, unsigned int handshakeHashLen, const char *label, unsigned int labelLen, CK_MECHANISM_TYPE algorithm, unsigned int keySize, PK11SymKey **keyp) { CK_NSS_HKDFParams params; - SECItem paramsi = {siBuffer, NULL, 0}; + SECItem paramsi = { siBuffer, NULL, 0 }; PRUint8 info[100]; PRUint8 *ptr = info; unsigned int infoLen; @@ -103,7 +104,8 @@ tls13_HkdfExpandLabel(PK11SymKey* prk, SSLHashType baseHash, if (handshakeHash) { PORT_Assert(handshakeHashLen == kTlsHkdfInfo[baseHash].hashSize); - } else { + } + else { PORT_Assert(!handshakeHashLen); } @@ -169,9 +171,8 @@ abort: return SECFailure; } - SECStatus -tls13_HkdfExpandLabelRaw(PK11SymKey* prk, SSLHashType baseHash, +tls13_HkdfExpandLabelRaw(PK11SymKey *prk, SSLHashType baseHash, const PRUint8 *handshakeHash, unsigned int handshakeHashLen, const char *label, unsigned int labelLen, unsigned char *output, unsigned int outputLen) diff --git a/security/nss/lib/ssl/tls13hkdf.h b/security/nss/lib/ssl/tls13hkdf.h index 055c6e9f0637..78347a11dc2e 100644 --- a/security/nss/lib/ssl/tls13hkdf.h +++ b/security/nss/lib/ssl/tls13hkdf.h @@ -17,15 +17,15 @@ extern "C" { #endif SECStatus tls13_HkdfExtract( - PK11SymKey* ikm1, PK11SymKey* ikm2, SSLHashType baseHash, + PK11SymKey *ikm1, PK11SymKey *ikm2, SSLHashType baseHash, PK11SymKey **prkp); SECStatus tls13_HkdfExpandLabelRaw( - PK11SymKey* prk, SSLHashType baseHash, + PK11SymKey *prk, SSLHashType baseHash, const PRUint8 *handshakeHash, unsigned int handshakeHashLen, const char *label, unsigned int labelLen, unsigned char *output, unsigned int outputLen); SECStatus tls13_HkdfExpandLabel( - PK11SymKey* prk, SSLHashType baseHash, + PK11SymKey *prk, SSLHashType baseHash, const PRUint8 *handshakeHash, unsigned int handshakeHashLen, const char *label, unsigned int labelLen, CK_MECHANISM_TYPE algorithm, unsigned int keySize, diff --git a/security/nss/lib/ssl/unix_err.c b/security/nss/lib/ssl/unix_err.c index 1857cfefc70a..ca0b0507b27e 100644 --- a/security/nss/lib/ssl/unix_err.c +++ b/security/nss/lib/ssl/unix_err.c @@ -1,12 +1,12 @@ /* -*- 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/. */ @@ -18,7 +18,7 @@ #include "prerror.h" #endif -#if defined (__bsdi__) || defined(NTO) || defined(DARWIN) || defined(BEOS) +#if defined(__bsdi__) || defined(NTO) || defined(DARWIN) || defined(BEOS) #undef _PR_POLL_AVAILABLE #endif @@ -30,357 +30,547 @@ /* forward declarations. */ void nss_MD_unix_map_default_error(int err); -void nss_MD_unix_map_opendir_error(int err) +void +nss_MD_unix_map_opendir_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_closedir_error(int err) +void +nss_MD_unix_map_closedir_error(int err) { PRErrorCode prError; switch (err) { - case EINVAL: prError = PR_BAD_DESCRIPTOR_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EINVAL: + prError = PR_BAD_DESCRIPTOR_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_readdir_error(int err) +void +nss_MD_unix_readdir_error(int err) { PRErrorCode prError; switch (err) { - case ENOENT: prError = PR_NO_MORE_FILES_ERROR; break; + case ENOENT: + prError = PR_NO_MORE_FILES_ERROR; + break; #ifdef EOVERFLOW - case EOVERFLOW: prError = PR_IO_ERROR; break; + case EOVERFLOW: + prError = PR_IO_ERROR; + break; #endif - case EINVAL: prError = PR_IO_ERROR; break; - case ENXIO: prError = PR_IO_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EINVAL: + prError = PR_IO_ERROR; + break; + case ENXIO: + prError = PR_IO_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_unlink_error(int err) +void +nss_MD_unix_map_unlink_error(int err) { PRErrorCode prError; switch (err) { - case EPERM: prError = PR_IS_DIRECTORY_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EPERM: + prError = PR_IS_DIRECTORY_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_stat_error(int err) +void +nss_MD_unix_map_stat_error(int err) { PRErrorCode prError; switch (err) { - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_fstat_error(int err) +void +nss_MD_unix_map_fstat_error(int err) { PRErrorCode prError; switch (err) { - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_rename_error(int err) +void +nss_MD_unix_map_rename_error(int err) { PRErrorCode prError; switch (err) { - case EEXIST: prError = PR_DIRECTORY_NOT_EMPTY_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EEXIST: + prError = PR_DIRECTORY_NOT_EMPTY_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_access_error(int err) +void +nss_MD_unix_map_access_error(int err) { PRErrorCode prError; switch (err) { - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_mkdir_error(int err) +void +nss_MD_unix_map_mkdir_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_rmdir_error(int err) +void +nss_MD_unix_map_rmdir_error(int err) { PRErrorCode prError; switch (err) { - case EEXIST: prError = PR_DIRECTORY_NOT_EMPTY_ERROR; break; - case EINVAL: prError = PR_DIRECTORY_NOT_EMPTY_ERROR; break; - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EEXIST: + prError = PR_DIRECTORY_NOT_EMPTY_ERROR; + break; + case EINVAL: + prError = PR_DIRECTORY_NOT_EMPTY_ERROR; + break; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_read_error(int err) +void +nss_MD_unix_map_read_error(int err) { PRErrorCode prError; switch (err) { - case EINVAL: prError = PR_INVALID_METHOD_ERROR; break; - case ENXIO: prError = PR_INVALID_ARGUMENT_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EINVAL: + prError = PR_INVALID_METHOD_ERROR; + break; + case ENXIO: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_write_error(int err) +void +nss_MD_unix_map_write_error(int err) { PRErrorCode prError; switch (err) { - case EINVAL: prError = PR_INVALID_METHOD_ERROR; break; - case ENXIO: prError = PR_INVALID_METHOD_ERROR; break; - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EINVAL: + prError = PR_INVALID_METHOD_ERROR; + break; + case ENXIO: + prError = PR_INVALID_METHOD_ERROR; + break; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_lseek_error(int err) +void +nss_MD_unix_map_lseek_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_fsync_error(int err) +void +nss_MD_unix_map_fsync_error(int err) { PRErrorCode prError; switch (err) { - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - case EINVAL: prError = PR_INVALID_METHOD_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + case EINVAL: + prError = PR_INVALID_METHOD_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_close_error(int err) +void +nss_MD_unix_map_close_error(int err) { PRErrorCode prError; switch (err) { - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_socket_error(int err) +void +nss_MD_unix_map_socket_error(int err) { PRErrorCode prError; switch (err) { - case ENOMEM: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ENOMEM: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_socketavailable_error(int err) +void +nss_MD_unix_map_socketavailable_error(int err) { PR_SetError(PR_BAD_DESCRIPTOR_ERROR, err); } -void nss_MD_unix_map_recv_error(int err) +void +nss_MD_unix_map_recv_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_recvfrom_error(int err) +void +nss_MD_unix_map_recvfrom_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_send_error(int err) +void +nss_MD_unix_map_send_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_sendto_error(int err) +void +nss_MD_unix_map_sendto_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_writev_error(int err) +void +nss_MD_unix_map_writev_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_accept_error(int err) +void +nss_MD_unix_map_accept_error(int err) { PRErrorCode prError; switch (err) { - case ENODEV: prError = PR_NOT_TCP_SOCKET_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ENODEV: + prError = PR_NOT_TCP_SOCKET_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_connect_error(int err) +void +nss_MD_unix_map_connect_error(int err) { PRErrorCode prError; switch (err) { - case EACCES: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; + case EACCES: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; #if defined(UNIXWARE) || defined(SNI) || defined(NEC) - /* - * On some platforms, if we connect to a port on the local host - * (the loopback address) that no process is listening on, we get - * EIO instead of ECONNREFUSED. - */ - case EIO: prError = PR_CONNECT_REFUSED_ERROR; break; -#endif - case ELOOP: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case ENOENT: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case ENXIO: prError = PR_IO_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; - } - PR_SetError(prError, err); -} - -void nss_MD_unix_map_bind_error(int err) -{ - PRErrorCode prError; - switch (err) { - case EINVAL: prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; break; /* - * UNIX domain sockets are not supported in NSPR + * On some platforms, if we connect to a port on the local host + * (the loopback address) that no process is listening on, we get + * EIO instead of ECONNREFUSED. */ - case EIO: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case EISDIR: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case ELOOP: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case ENOENT: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case ENOTDIR: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case EROFS: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EIO: + prError = PR_CONNECT_REFUSED_ERROR; + break; +#endif + case ELOOP: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case ENOENT: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case ENXIO: + prError = PR_IO_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_listen_error(int err) +void +nss_MD_unix_map_bind_error(int err) +{ + PRErrorCode prError; + switch (err) { + case EINVAL: + prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; + break; + /* + * UNIX domain sockets are not supported in NSPR + */ + case EIO: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case EISDIR: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case ELOOP: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case ENOENT: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case ENOTDIR: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case EROFS: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; + } + PR_SetError(prError, err); +} + +void +nss_MD_unix_map_listen_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_shutdown_error(int err) +void +nss_MD_unix_map_shutdown_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_socketpair_error(int err) +void +nss_MD_unix_map_socketpair_error(int err) { PRErrorCode prError; switch (err) { - case ENOMEM: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ENOMEM: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_getsockname_error(int err) +void +nss_MD_unix_map_getsockname_error(int err) { PRErrorCode prError; switch (err) { - case ENOMEM: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ENOMEM: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_getpeername_error(int err) +void +nss_MD_unix_map_getpeername_error(int err) { PRErrorCode prError; switch (err) { - case ENOMEM: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case ENOMEM: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_getsockopt_error(int err) +void +nss_MD_unix_map_getsockopt_error(int err) { PRErrorCode prError; switch (err) { - case EINVAL: prError = PR_BUFFER_OVERFLOW_ERROR; break; - case ENOMEM: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EINVAL: + prError = PR_BUFFER_OVERFLOW_ERROR; + break; + case ENOMEM: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_setsockopt_error(int err) +void +nss_MD_unix_map_setsockopt_error(int err) { PRErrorCode prError; switch (err) { - case EINVAL: prError = PR_BUFFER_OVERFLOW_ERROR; break; - case ENOMEM: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EINVAL: + prError = PR_BUFFER_OVERFLOW_ERROR; + break; + case ENOMEM: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_open_error(int err) +void +nss_MD_unix_map_open_error(int err) { PRErrorCode prError; switch (err) { - case EAGAIN: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case EBUSY: prError = PR_IO_ERROR; break; - case ENODEV: prError = PR_FILE_NOT_FOUND_ERROR; break; - case ENOMEM: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case ETIMEDOUT: prError = PR_REMOTE_FILE_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EAGAIN: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case EBUSY: + prError = PR_IO_ERROR; + break; + case ENODEV: + prError = PR_FILE_NOT_FOUND_ERROR; + break; + case ENOMEM: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case ETIMEDOUT: + prError = PR_REMOTE_FILE_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_mmap_error(int err) +void +nss_MD_unix_map_mmap_error(int err) { PRErrorCode prError; switch (err) { - case EAGAIN: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case EMFILE: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case ENODEV: prError = PR_OPERATION_NOT_SUPPORTED_ERROR; break; - case ENXIO: prError = PR_INVALID_ARGUMENT_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EAGAIN: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case EMFILE: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case ENODEV: + prError = PR_OPERATION_NOT_SUPPORTED_ERROR; + break; + case ENXIO: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_gethostname_error(int err) +void +nss_MD_unix_map_gethostname_error(int err) { nss_MD_unix_map_default_error(err); } -void nss_MD_unix_map_select_error(int err) +void +nss_MD_unix_map_select_error(int err) { nss_MD_unix_map_default_error(err); } #ifdef _PR_POLL_AVAILABLE -void nss_MD_unix_map_poll_error(int err) +void +nss_MD_unix_map_poll_error(int err) { PRErrorCode prError; switch (err) { - case EAGAIN: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EAGAIN: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_poll_revents_error(int err) +void +nss_MD_unix_map_poll_revents_error(int err) { if (err & POLLNVAL) PR_SetError(PR_BAD_DESCRIPTOR_ERROR, EBADF); @@ -393,125 +583,255 @@ void nss_MD_unix_map_poll_revents_error(int err) } #endif /* _PR_POLL_AVAILABLE */ - -void nss_MD_unix_map_flock_error(int err) +void +nss_MD_unix_map_flock_error(int err) { PRErrorCode prError; switch (err) { - case EINVAL: prError = PR_BAD_DESCRIPTOR_ERROR; break; - case EWOULDBLOCK: prError = PR_FILE_IS_LOCKED_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EINVAL: + prError = PR_BAD_DESCRIPTOR_ERROR; + break; + case EWOULDBLOCK: + prError = PR_FILE_IS_LOCKED_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_unix_map_lockf_error(int err) +void +nss_MD_unix_map_lockf_error(int err) { PRErrorCode prError; switch (err) { - case EACCES: prError = PR_FILE_IS_LOCKED_ERROR; break; - case EDEADLK: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - default: nss_MD_unix_map_default_error(err); return; + case EACCES: + prError = PR_FILE_IS_LOCKED_ERROR; + break; + case EDEADLK: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + default: + nss_MD_unix_map_default_error(err); + return; } PR_SetError(prError, err); } #ifdef HPUX11 -void nss_MD_hpux_map_sendfile_error(int err) +void +nss_MD_hpux_map_sendfile_error(int err) { nss_MD_unix_map_default_error(err); } #endif /* HPUX11 */ - -void nss_MD_unix_map_default_error(int err) +void +nss_MD_unix_map_default_error(int err) { PRErrorCode prError; - switch (err ) { - case EACCES: prError = PR_NO_ACCESS_RIGHTS_ERROR; break; - case EADDRINUSE: prError = PR_ADDRESS_IN_USE_ERROR; break; - case EADDRNOTAVAIL: prError = PR_ADDRESS_NOT_AVAILABLE_ERROR; break; - case EAFNOSUPPORT: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case EAGAIN: prError = PR_WOULD_BLOCK_ERROR; break; + switch (err) { + case EACCES: + prError = PR_NO_ACCESS_RIGHTS_ERROR; + break; + case EADDRINUSE: + prError = PR_ADDRESS_IN_USE_ERROR; + break; + case EADDRNOTAVAIL: + prError = PR_ADDRESS_NOT_AVAILABLE_ERROR; + break; + case EAFNOSUPPORT: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case EAGAIN: + prError = PR_WOULD_BLOCK_ERROR; + break; /* * On QNX and Neutrino, EALREADY is defined as EBUSY. */ #if EALREADY != EBUSY - case EALREADY: prError = PR_ALREADY_INITIATED_ERROR; break; + case EALREADY: + prError = PR_ALREADY_INITIATED_ERROR; + break; #endif - case EBADF: prError = PR_BAD_DESCRIPTOR_ERROR; break; + case EBADF: + prError = PR_BAD_DESCRIPTOR_ERROR; + break; #ifdef EBADMSG - case EBADMSG: prError = PR_IO_ERROR; break; + case EBADMSG: + prError = PR_IO_ERROR; + break; #endif - case EBUSY: prError = PR_FILESYSTEM_MOUNTED_ERROR; break; - case ECONNREFUSED: prError = PR_CONNECT_REFUSED_ERROR; break; - case ECONNRESET: prError = PR_CONNECT_RESET_ERROR; break; - case EDEADLK: prError = PR_DEADLOCK_ERROR; break; + case EBUSY: + prError = PR_FILESYSTEM_MOUNTED_ERROR; + break; + case ECONNREFUSED: + prError = PR_CONNECT_REFUSED_ERROR; + break; + case ECONNRESET: + prError = PR_CONNECT_RESET_ERROR; + break; + case EDEADLK: + prError = PR_DEADLOCK_ERROR; + break; #ifdef EDIRCORRUPTED - case EDIRCORRUPTED: prError = PR_DIRECTORY_CORRUPTED_ERROR; break; + case EDIRCORRUPTED: + prError = PR_DIRECTORY_CORRUPTED_ERROR; + break; #endif #ifdef EDQUOT - case EDQUOT: prError = PR_NO_DEVICE_SPACE_ERROR; break; + case EDQUOT: + prError = PR_NO_DEVICE_SPACE_ERROR; + break; #endif - case EEXIST: prError = PR_FILE_EXISTS_ERROR; break; - case EFAULT: prError = PR_ACCESS_FAULT_ERROR; break; - case EFBIG: prError = PR_FILE_TOO_BIG_ERROR; break; - case EINPROGRESS: prError = PR_IN_PROGRESS_ERROR; break; - case EINTR: prError = PR_PENDING_INTERRUPT_ERROR; break; - case EINVAL: prError = PR_INVALID_ARGUMENT_ERROR; break; - case EIO: prError = PR_IO_ERROR; break; - case EISCONN: prError = PR_IS_CONNECTED_ERROR; break; - case EISDIR: prError = PR_IS_DIRECTORY_ERROR; break; - case ELOOP: prError = PR_LOOP_ERROR; break; - case EMFILE: prError = PR_PROC_DESC_TABLE_FULL_ERROR; break; - case EMLINK: prError = PR_MAX_DIRECTORY_ENTRIES_ERROR; break; - case EMSGSIZE: prError = PR_INVALID_ARGUMENT_ERROR; break; + case EEXIST: + prError = PR_FILE_EXISTS_ERROR; + break; + case EFAULT: + prError = PR_ACCESS_FAULT_ERROR; + break; + case EFBIG: + prError = PR_FILE_TOO_BIG_ERROR; + break; + case EINPROGRESS: + prError = PR_IN_PROGRESS_ERROR; + break; + case EINTR: + prError = PR_PENDING_INTERRUPT_ERROR; + break; + case EINVAL: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case EIO: + prError = PR_IO_ERROR; + break; + case EISCONN: + prError = PR_IS_CONNECTED_ERROR; + break; + case EISDIR: + prError = PR_IS_DIRECTORY_ERROR; + break; + case ELOOP: + prError = PR_LOOP_ERROR; + break; + case EMFILE: + prError = PR_PROC_DESC_TABLE_FULL_ERROR; + break; + case EMLINK: + prError = PR_MAX_DIRECTORY_ENTRIES_ERROR; + break; + case EMSGSIZE: + prError = PR_INVALID_ARGUMENT_ERROR; + break; #ifdef EMULTIHOP - case EMULTIHOP: prError = PR_REMOTE_FILE_ERROR; break; + case EMULTIHOP: + prError = PR_REMOTE_FILE_ERROR; + break; #endif - case ENAMETOOLONG: prError = PR_NAME_TOO_LONG_ERROR; break; - case ENETUNREACH: prError = PR_NETWORK_UNREACHABLE_ERROR; break; - case ENFILE: prError = PR_SYS_DESC_TABLE_FULL_ERROR; break; + case ENAMETOOLONG: + prError = PR_NAME_TOO_LONG_ERROR; + break; + case ENETUNREACH: + prError = PR_NETWORK_UNREACHABLE_ERROR; + break; + case ENFILE: + prError = PR_SYS_DESC_TABLE_FULL_ERROR; + break; #if !defined(SCO) - case ENOBUFS: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; + case ENOBUFS: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; #endif - case ENODEV: prError = PR_FILE_NOT_FOUND_ERROR; break; - case ENOENT: prError = PR_FILE_NOT_FOUND_ERROR; break; - case ENOLCK: prError = PR_FILE_IS_LOCKED_ERROR; break; -#ifdef ENOLINK - case ENOLINK: prError = PR_REMOTE_FILE_ERROR; break; + case ENODEV: + prError = PR_FILE_NOT_FOUND_ERROR; + break; + case ENOENT: + prError = PR_FILE_NOT_FOUND_ERROR; + break; + case ENOLCK: + prError = PR_FILE_IS_LOCKED_ERROR; + break; +#ifdef ENOLINK + case ENOLINK: + prError = PR_REMOTE_FILE_ERROR; + break; #endif - case ENOMEM: prError = PR_OUT_OF_MEMORY_ERROR; break; - case ENOPROTOOPT: prError = PR_INVALID_ARGUMENT_ERROR; break; - case ENOSPC: prError = PR_NO_DEVICE_SPACE_ERROR; break; -#ifdef ENOSR - case ENOSR: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; + case ENOMEM: + prError = PR_OUT_OF_MEMORY_ERROR; + break; + case ENOPROTOOPT: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case ENOSPC: + prError = PR_NO_DEVICE_SPACE_ERROR; + break; +#ifdef ENOSR + case ENOSR: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; #endif - case ENOTCONN: prError = PR_NOT_CONNECTED_ERROR; break; - case ENOTDIR: prError = PR_NOT_DIRECTORY_ERROR; break; - case ENOTSOCK: prError = PR_NOT_SOCKET_ERROR; break; - case ENXIO: prError = PR_FILE_NOT_FOUND_ERROR; break; - case EOPNOTSUPP: prError = PR_NOT_TCP_SOCKET_ERROR; break; + case ENOTCONN: + prError = PR_NOT_CONNECTED_ERROR; + break; + case ENOTDIR: + prError = PR_NOT_DIRECTORY_ERROR; + break; + case ENOTSOCK: + prError = PR_NOT_SOCKET_ERROR; + break; + case ENXIO: + prError = PR_FILE_NOT_FOUND_ERROR; + break; + case EOPNOTSUPP: + prError = PR_NOT_TCP_SOCKET_ERROR; + break; #ifdef EOVERFLOW - case EOVERFLOW: prError = PR_BUFFER_OVERFLOW_ERROR; break; + case EOVERFLOW: + prError = PR_BUFFER_OVERFLOW_ERROR; + break; #endif - case EPERM: prError = PR_NO_ACCESS_RIGHTS_ERROR; break; - case EPIPE: prError = PR_CONNECT_RESET_ERROR; break; + case EPERM: + prError = PR_NO_ACCESS_RIGHTS_ERROR; + break; + case EPIPE: + prError = PR_CONNECT_RESET_ERROR; + break; #ifdef EPROTO - case EPROTO: prError = PR_IO_ERROR; break; + case EPROTO: + prError = PR_IO_ERROR; + break; #endif - case EPROTONOSUPPORT: prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR; break; - case EPROTOTYPE: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case ERANGE: prError = PR_INVALID_METHOD_ERROR; break; - case EROFS: prError = PR_READ_ONLY_FILESYSTEM_ERROR; break; - case ESPIPE: prError = PR_INVALID_METHOD_ERROR; break; - case ETIMEDOUT: prError = PR_IO_TIMEOUT_ERROR; break; + case EPROTONOSUPPORT: + prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR; + break; + case EPROTOTYPE: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case ERANGE: + prError = PR_INVALID_METHOD_ERROR; + break; + case EROFS: + prError = PR_READ_ONLY_FILESYSTEM_ERROR; + break; + case ESPIPE: + prError = PR_INVALID_METHOD_ERROR; + break; + case ETIMEDOUT: + prError = PR_IO_TIMEOUT_ERROR; + break; #if EWOULDBLOCK != EAGAIN - case EWOULDBLOCK: prError = PR_WOULD_BLOCK_ERROR; break; + case EWOULDBLOCK: + prError = PR_WOULD_BLOCK_ERROR; + break; #endif - case EXDEV: prError = PR_NOT_SAME_DEVICE_ERROR; break; + case EXDEV: + prError = PR_NOT_SAME_DEVICE_ERROR; + break; - default: prError = PR_UNKNOWN_ERROR; break; + default: + prError = PR_UNKNOWN_ERROR; + break; } PR_SetError(prError, err); } diff --git a/security/nss/lib/ssl/unix_err.h b/security/nss/lib/ssl/unix_err.h index be7fe2921781..5d7d547bfb64 100644 --- a/security/nss/lib/ssl/unix_err.h +++ b/security/nss/lib/ssl/unix_err.h @@ -1,11 +1,11 @@ /* * 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/. */ diff --git a/security/nss/lib/ssl/win32err.c b/security/nss/lib/ssl/win32err.c index a70010d370a5..caa12b956e15 100644 --- a/security/nss/lib/ssl/win32err.c +++ b/security/nss/lib/ssl/win32err.c @@ -1,12 +1,12 @@ /* -*- 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/. */ @@ -33,79 +33,94 @@ /* forward declaration. */ void nss_MD_win32_map_default_error(PRInt32 err); -void nss_MD_win32_map_opendir_error(PRInt32 err) +void +nss_MD_win32_map_opendir_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_closedir_error(PRInt32 err) +void +nss_MD_win32_map_closedir_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_readdir_error(PRInt32 err) +void +nss_MD_win32_map_readdir_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_delete_error(PRInt32 err) +void +nss_MD_win32_map_delete_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } /* The error code for stat() is in errno. */ -void nss_MD_win32_map_stat_error(PRInt32 err) +void +nss_MD_win32_map_stat_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_fstat_error(PRInt32 err) +void +nss_MD_win32_map_fstat_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_rename_error(PRInt32 err) +void +nss_MD_win32_map_rename_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } /* The error code for access() is in errno. */ -void nss_MD_win32_map_access_error(PRInt32 err) +void +nss_MD_win32_map_access_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_mkdir_error(PRInt32 err) +void +nss_MD_win32_map_mkdir_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_rmdir_error(PRInt32 err) +void +nss_MD_win32_map_rmdir_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_read_error(PRInt32 err) +void +nss_MD_win32_map_read_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_transmitfile_error(PRInt32 err) +void +nss_MD_win32_map_transmitfile_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_write_error(PRInt32 err) +void +nss_MD_win32_map_write_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_lseek_error(PRInt32 err) +void +nss_MD_win32_map_lseek_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_fsync_error(PRInt32 err) +void +nss_MD_win32_map_fsync_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } @@ -113,231 +128,423 @@ void nss_MD_win32_map_fsync_error(PRInt32 err) /* * For both CloseHandle() and closesocket(). */ -void nss_MD_win32_map_close_error(PRInt32 err) +void +nss_MD_win32_map_close_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_socket_error(PRInt32 err) +void +nss_MD_win32_map_socket_error(PRInt32 err) { PR_ASSERT(err != WSANOTINITIALISED); nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_recv_error(PRInt32 err) +void +nss_MD_win32_map_recv_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_recvfrom_error(PRInt32 err) +void +nss_MD_win32_map_recvfrom_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_send_error(PRInt32 err) +void +nss_MD_win32_map_send_error(PRInt32 err) { PRErrorCode prError; switch (err) { - case WSAEMSGSIZE: prError = PR_INVALID_ARGUMENT_ERROR; break; - default: nss_MD_win32_map_default_error(err); return; + case WSAEMSGSIZE: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + default: + nss_MD_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_sendto_error(PRInt32 err) +void +nss_MD_win32_map_sendto_error(PRInt32 err) { PRErrorCode prError; switch (err) { - case WSAEMSGSIZE: prError = PR_INVALID_ARGUMENT_ERROR; break; - default: nss_MD_win32_map_default_error(err); return; + case WSAEMSGSIZE: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + default: + nss_MD_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_accept_error(PRInt32 err) +void +nss_MD_win32_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_win32_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_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_acceptex_error(PRInt32 err) +void +nss_MD_win32_map_acceptex_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_connect_error(PRInt32 err) +void +nss_MD_win32_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_win32_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_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_bind_error(PRInt32 err) +void +nss_MD_win32_map_bind_error(PRInt32 err) { PRErrorCode prError; switch (err) { - case WSAEINVAL: prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; break; - default: nss_MD_win32_map_default_error(err); return; + case WSAEINVAL: + prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; + break; + default: + nss_MD_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_listen_error(PRInt32 err) +void +nss_MD_win32_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_win32_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_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_shutdown_error(PRInt32 err) +void +nss_MD_win32_map_shutdown_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_getsockname_error(PRInt32 err) +void +nss_MD_win32_map_getsockname_error(PRInt32 err) { PRErrorCode prError; switch (err) { - case WSAEINVAL: prError = PR_INVALID_STATE_ERROR; break; - default: nss_MD_win32_map_default_error(err); return; + case WSAEINVAL: + prError = PR_INVALID_STATE_ERROR; + break; + default: + nss_MD_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_getpeername_error(PRInt32 err) +void +nss_MD_win32_map_getpeername_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_getsockopt_error(PRInt32 err) +void +nss_MD_win32_map_getsockopt_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_setsockopt_error(PRInt32 err) +void +nss_MD_win32_map_setsockopt_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_open_error(PRInt32 err) +void +nss_MD_win32_map_open_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } -void nss_MD_win32_map_gethostname_error(PRInt32 err) +void +nss_MD_win32_map_gethostname_error(PRInt32 err) { nss_MD_win32_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_win32_map_select_error(PRInt32 err) +void +nss_MD_win32_map_select_error(PRInt32 err) { PRErrorCode prError; switch (err) { - case WSAENOTSOCK: prError = PR_BAD_DESCRIPTOR_ERROR; break; - default: nss_MD_win32_map_default_error(err); return; + case WSAENOTSOCK: + prError = PR_BAD_DESCRIPTOR_ERROR; + break; + default: + nss_MD_win32_map_default_error(err); + return; } PR_SetError(prError, err); } -void nss_MD_win32_map_lockf_error(PRInt32 err) +void +nss_MD_win32_map_lockf_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } - - -void nss_MD_win32_map_default_error(PRInt32 err) +void +nss_MD_win32_map_default_error(PRInt32 err) { PRErrorCode prError; switch (err) { - case EACCES: prError = PR_NO_ACCESS_RIGHTS_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_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 EACCES: + prError = PR_NO_ACCESS_RIGHTS_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_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; #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 - case ERROR_HANDLE_DISK_FULL: prError = PR_NO_DEVICE_SPACE_ERROR; break; - case ERROR_INVALID_ADDRESS: prError = PR_ACCESS_FAULT_ERROR; break; - case ERROR_INVALID_HANDLE: prError = PR_BAD_DESCRIPTOR_ERROR; break; - case ERROR_INVALID_NAME: prError = PR_INVALID_ARGUMENT_ERROR; break; - case ERROR_INVALID_PARAMETER: prError = PR_INVALID_ARGUMENT_ERROR; break; - case ERROR_INVALID_USER_BUFFER: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case ERROR_LOCKED: prError = PR_FILE_IS_LOCKED_ERROR; break; - case ERROR_NETNAME_DELETED: prError = PR_CONNECT_RESET_ERROR; break; - case ERROR_NOACCESS: prError = PR_ACCESS_FAULT_ERROR; break; - case ERROR_NOT_ENOUGH_MEMORY: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case ERROR_NOT_ENOUGH_QUOTA: prError = PR_OUT_OF_MEMORY_ERROR; break; - case ERROR_NOT_READY: prError = PR_IO_ERROR; break; - case ERROR_NO_MORE_FILES: prError = PR_NO_MORE_FILES_ERROR; break; - case ERROR_OPEN_FAILED: prError = PR_IO_ERROR; break; - case ERROR_OPEN_FILES: prError = PR_IO_ERROR; break; - case ERROR_OUTOFMEMORY: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case ERROR_PATH_BUSY: prError = PR_IO_ERROR; break; - case ERROR_PATH_NOT_FOUND: prError = PR_FILE_NOT_FOUND_ERROR; break; - case ERROR_SEEK_ON_DEVICE: prError = PR_IO_ERROR; break; - case ERROR_SHARING_VIOLATION: prError = PR_FILE_IS_BUSY_ERROR; break; - case ERROR_STACK_OVERFLOW: prError = PR_ACCESS_FAULT_ERROR; break; - case ERROR_TOO_MANY_OPEN_FILES: prError = PR_SYS_DESC_TABLE_FULL_ERROR; break; - case ERROR_WRITE_PROTECT: prError = PR_NO_ACCESS_RIGHTS_ERROR; break; - case WSAEACCES: prError = PR_NO_ACCESS_RIGHTS_ERROR; break; - case WSAEADDRINUSE: prError = PR_ADDRESS_IN_USE_ERROR; break; - case WSAEADDRNOTAVAIL: prError = PR_ADDRESS_NOT_AVAILABLE_ERROR; break; - case WSAEAFNOSUPPORT: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; - case WSAEALREADY: prError = PR_ALREADY_INITIATED_ERROR; break; - case WSAEBADF: prError = PR_BAD_DESCRIPTOR_ERROR; break; - case WSAECONNABORTED: prError = PR_CONNECT_ABORTED_ERROR; break; - case WSAECONNREFUSED: prError = PR_CONNECT_REFUSED_ERROR; break; - case WSAECONNRESET: prError = PR_CONNECT_RESET_ERROR; break; - case WSAEDESTADDRREQ: prError = PR_INVALID_ARGUMENT_ERROR; break; - case WSAEFAULT: prError = PR_ACCESS_FAULT_ERROR; break; - case WSAEHOSTUNREACH: prError = PR_HOST_UNREACHABLE_ERROR; break; - case WSAEINVAL: prError = PR_INVALID_ARGUMENT_ERROR; break; - case WSAEISCONN: prError = PR_IS_CONNECTED_ERROR; break; - case WSAEMFILE: prError = PR_PROC_DESC_TABLE_FULL_ERROR; break; - case WSAEMSGSIZE: prError = PR_BUFFER_OVERFLOW_ERROR; break; - case WSAENETDOWN: prError = PR_NETWORK_DOWN_ERROR; break; - case WSAENETRESET: prError = PR_CONNECT_ABORTED_ERROR; break; - case WSAENETUNREACH: prError = PR_NETWORK_UNREACHABLE_ERROR; break; - case WSAENOBUFS: prError = PR_INSUFFICIENT_RESOURCES_ERROR; break; - case WSAENOPROTOOPT: prError = PR_INVALID_ARGUMENT_ERROR; break; - case WSAENOTCONN: prError = PR_NOT_CONNECTED_ERROR; break; - case WSAENOTSOCK: prError = PR_NOT_SOCKET_ERROR; break; - case WSAEOPNOTSUPP: prError = PR_OPERATION_NOT_SUPPORTED_ERROR; break; - case WSAEPROTONOSUPPORT: prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR; break; - case WSAEPROTOTYPE: prError = PR_INVALID_ARGUMENT_ERROR; break; - case WSAESHUTDOWN: prError = PR_SOCKET_SHUTDOWN_ERROR; break; - case WSAESOCKTNOSUPPORT: prError = PR_INVALID_ARGUMENT_ERROR; break; - case WSAETIMEDOUT: prError = PR_CONNECT_ABORTED_ERROR; break; - case WSAEWOULDBLOCK: prError = PR_WOULD_BLOCK_ERROR; break; - default: prError = PR_UNKNOWN_ERROR; break; + case ERROR_HANDLE_DISK_FULL: + prError = PR_NO_DEVICE_SPACE_ERROR; + break; + case ERROR_INVALID_ADDRESS: + prError = PR_ACCESS_FAULT_ERROR; + break; + case ERROR_INVALID_HANDLE: + prError = PR_BAD_DESCRIPTOR_ERROR; + break; + case ERROR_INVALID_NAME: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case ERROR_INVALID_PARAMETER: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case ERROR_INVALID_USER_BUFFER: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case ERROR_LOCKED: + prError = PR_FILE_IS_LOCKED_ERROR; + break; + case ERROR_NETNAME_DELETED: + prError = PR_CONNECT_RESET_ERROR; + break; + case ERROR_NOACCESS: + prError = PR_ACCESS_FAULT_ERROR; + break; + case ERROR_NOT_ENOUGH_MEMORY: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case ERROR_NOT_ENOUGH_QUOTA: + prError = PR_OUT_OF_MEMORY_ERROR; + break; + case ERROR_NOT_READY: + prError = PR_IO_ERROR; + break; + case ERROR_NO_MORE_FILES: + prError = PR_NO_MORE_FILES_ERROR; + break; + case ERROR_OPEN_FAILED: + prError = PR_IO_ERROR; + break; + case ERROR_OPEN_FILES: + prError = PR_IO_ERROR; + break; + case ERROR_OUTOFMEMORY: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case ERROR_PATH_BUSY: + prError = PR_IO_ERROR; + break; + case ERROR_PATH_NOT_FOUND: + prError = PR_FILE_NOT_FOUND_ERROR; + break; + case ERROR_SEEK_ON_DEVICE: + prError = PR_IO_ERROR; + break; + case ERROR_SHARING_VIOLATION: + prError = PR_FILE_IS_BUSY_ERROR; + break; + case ERROR_STACK_OVERFLOW: + prError = PR_ACCESS_FAULT_ERROR; + break; + case ERROR_TOO_MANY_OPEN_FILES: + prError = PR_SYS_DESC_TABLE_FULL_ERROR; + break; + case ERROR_WRITE_PROTECT: + prError = PR_NO_ACCESS_RIGHTS_ERROR; + break; + case WSAEACCES: + prError = PR_NO_ACCESS_RIGHTS_ERROR; + break; + case WSAEADDRINUSE: + prError = PR_ADDRESS_IN_USE_ERROR; + break; + case WSAEADDRNOTAVAIL: + prError = PR_ADDRESS_NOT_AVAILABLE_ERROR; + break; + case WSAEAFNOSUPPORT: + prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; + break; + case WSAEALREADY: + prError = PR_ALREADY_INITIATED_ERROR; + break; + case WSAEBADF: + prError = PR_BAD_DESCRIPTOR_ERROR; + break; + case WSAECONNABORTED: + prError = PR_CONNECT_ABORTED_ERROR; + break; + case WSAECONNREFUSED: + prError = PR_CONNECT_REFUSED_ERROR; + break; + case WSAECONNRESET: + prError = PR_CONNECT_RESET_ERROR; + break; + case WSAEDESTADDRREQ: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case WSAEFAULT: + prError = PR_ACCESS_FAULT_ERROR; + break; + case WSAEHOSTUNREACH: + prError = PR_HOST_UNREACHABLE_ERROR; + break; + case WSAEINVAL: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case WSAEISCONN: + prError = PR_IS_CONNECTED_ERROR; + break; + case WSAEMFILE: + prError = PR_PROC_DESC_TABLE_FULL_ERROR; + break; + case WSAEMSGSIZE: + prError = PR_BUFFER_OVERFLOW_ERROR; + break; + case WSAENETDOWN: + prError = PR_NETWORK_DOWN_ERROR; + break; + case WSAENETRESET: + prError = PR_CONNECT_ABORTED_ERROR; + break; + case WSAENETUNREACH: + prError = PR_NETWORK_UNREACHABLE_ERROR; + break; + case WSAENOBUFS: + prError = PR_INSUFFICIENT_RESOURCES_ERROR; + break; + case WSAENOPROTOOPT: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case WSAENOTCONN: + prError = PR_NOT_CONNECTED_ERROR; + break; + case WSAENOTSOCK: + prError = PR_NOT_SOCKET_ERROR; + break; + case WSAEOPNOTSUPP: + prError = PR_OPERATION_NOT_SUPPORTED_ERROR; + break; + case WSAEPROTONOSUPPORT: + prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR; + break; + case WSAEPROTOTYPE: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case WSAESHUTDOWN: + prError = PR_SOCKET_SHUTDOWN_ERROR; + break; + case WSAESOCKTNOSUPPORT: + prError = PR_INVALID_ARGUMENT_ERROR; + break; + case WSAETIMEDOUT: + prError = PR_CONNECT_ABORTED_ERROR; + break; + case WSAEWOULDBLOCK: + prError = PR_WOULD_BLOCK_ERROR; + break; + default: + prError = PR_UNKNOWN_ERROR; + break; } PR_SetError(prError, err); } - diff --git a/security/nss/lib/ssl/win32err.h b/security/nss/lib/ssl/win32err.h index 8ce588ec5a19..a698849061cc 100644 --- a/security/nss/lib/ssl/win32err.h +++ b/security/nss/lib/ssl/win32err.h @@ -1,11 +1,11 @@ /* * 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/. */ diff --git a/security/nss/lib/util/pkcs11n.h b/security/nss/lib/util/pkcs11n.h index 5e137849df59..5fc8992e4da1 100644 --- a/security/nss/lib/util/pkcs11n.h +++ b/security/nss/lib/util/pkcs11n.h @@ -51,6 +51,8 @@ #define CKK_NSS_JPAKE_ROUND1 (CKK_NSS + 2) #define CKK_NSS_JPAKE_ROUND2 (CKK_NSS + 3) +#define CKK_NSS_CHACHA20 (CKK_NSS + 4) + /* * NSS-defined certificate types * @@ -218,6 +220,9 @@ #define CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE (CKM_NSS + 25) #define CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH (CKM_NSS + 26) +#define CKM_NSS_CHACHA20_KEY_GEN (CKM_NSS + 27) +#define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 28) + /* * HISTORICAL: * Do not attempt to use these. They are only used by NETSCAPE's internal @@ -285,6 +290,14 @@ typedef struct CK_NSS_MAC_CONSTANT_TIME_PARAMS { CK_ULONG ulHeaderLen; /* in */ } CK_NSS_MAC_CONSTANT_TIME_PARAMS; +typedef struct CK_NSS_AEAD_PARAMS { + CK_BYTE_PTR pNonce; + CK_ULONG ulNonceLen; + CK_BYTE_PTR pAAD; + CK_ULONG ulAADLen; + CK_ULONG ulTagLen; +} CK_NSS_AEAD_PARAMS; + /* * NSS-defined return values * diff --git a/security/nss/lib/util/secasn1d.c b/security/nss/lib/util/secasn1d.c index 7a5bcfd03a16..7628d65a55f0 100644 --- a/security/nss/lib/util/secasn1d.c +++ b/security/nss/lib/util/secasn1d.c @@ -14,6 +14,8 @@ #define PR_Assert sec_asn1d_Assert #endif +#include + #include "secasn1.h" #include "secerr.h" @@ -1593,6 +1595,7 @@ sec_asn1d_parse_leaf (sec_asn1d_state *state, item = (SECItem *)(state->dest); if (item != NULL && item->data != NULL) { + unsigned long offset; /* Strip leading zeroes when target is unsigned integer */ if (state->underlying_kind == SEC_ASN1_INTEGER && /* INTEGER */ item->len == 0 && /* MSB */ @@ -1603,8 +1606,42 @@ sec_asn1d_parse_leaf (sec_asn1d_state *state, len--; } } - PORT_Memcpy (item->data + item->len, buf, len); - item->len += len; + offset = item->len; + if (state->underlying_kind == SEC_ASN1_BIT_STRING) { + // The previous bit string must have no unused bits. + if (item->len & 0x7) { + PORT_SetError (SEC_ERROR_BAD_DER); + state->top->status = decodeError; + return 0; + } + // If this is a bit string, the length is bits, not bytes. + offset = item->len >> 3; + } + if (state->underlying_kind == SEC_ASN1_BIT_STRING) { + unsigned long len_in_bits; + // Protect against overflow during the bytes-to-bits conversion. + if (len >= (ULONG_MAX >> 3) + 1) { + PORT_SetError (SEC_ERROR_BAD_DER); + state->top->status = decodeError; + return 0; + } + len_in_bits = (len << 3) - state->bit_string_unused_bits; + // Protect against overflow when computing the total length in bits. + if (UINT_MAX - item->len < len_in_bits) { + PORT_SetError (SEC_ERROR_BAD_DER); + state->top->status = decodeError; + return 0; + } + item->len += len_in_bits; + } else { + if (UINT_MAX - item->len < len) { + PORT_SetError (SEC_ERROR_BAD_DER); + state->top->status = decodeError; + return 0; + } + item->len += len; + } + PORT_Memcpy (item->data + offset, buf, len); } state->pending -= bufLen; if (state->pending == 0) @@ -1671,14 +1708,6 @@ sec_asn1d_parse_more_bit_string (sec_asn1d_state *state, } len = sec_asn1d_parse_leaf (state, buf, len); - if (state->place == beforeEndOfContents && state->dest != NULL) { - SECItem *item; - - item = (SECItem *)(state->dest); - if (item->len) - item->len = (item->len << 3) - state->bit_string_unused_bits; - } - return len; } @@ -2208,7 +2237,7 @@ sec_asn1d_concat_substrings (sec_asn1d_state *state) * All bit-string substrings except the last one should be * a clean multiple of 8 bits. */ - if (is_bit_string && (substring->next == NULL) + if (is_bit_string && (substring->next != NULL) && (substring->len & 0x7)) { PORT_SetError (SEC_ERROR_BAD_DER); state->top->status = decodeError; diff --git a/security/nss/lib/util/secoid.c b/security/nss/lib/util/secoid.c index 6f2edb1ae19a..4f16ed386598 100644 --- a/security/nss/lib/util/secoid.c +++ b/security/nss/lib/util/secoid.c @@ -1652,7 +1652,6 @@ const static SECOidData oids[SEC_OID_TOTAL] = { OD( x520Name, SEC_OID_AVA_NAME, "X520 Name", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), - OD( aes128_GCM, SEC_OID_AES_128_GCM, "AES-128-GCM", CKM_AES_GCM, INVALID_CERT_EXTENSION ), OD( aes192_GCM, SEC_OID_AES_192_GCM, @@ -1710,6 +1709,8 @@ const static SECOidData oids[SEC_OID_TOTAL] = { "TLS DH-ANON-EXPORT key exchange", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), ODE( SEC_OID_APPLY_SSL_POLICY, "Apply SSL policy (pseudo-OID)", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION ), + ODE( SEC_OID_CHACHA20_POLY1305, + "ChaCha20-Poly1305", CKM_NSS_CHACHA20_POLY1305, INVALID_CERT_EXTENSION ), }; diff --git a/security/nss/lib/util/secoidt.h b/security/nss/lib/util/secoidt.h index 0b4bfc4a4e93..d9386a75a1a7 100644 --- a/security/nss/lib/util/secoidt.h +++ b/security/nss/lib/util/secoidt.h @@ -479,6 +479,8 @@ typedef enum { SEC_OID_TLS_DH_ANON_EXPORT = 344, SEC_OID_APPLY_SSL_POLICY = 345, + SEC_OID_CHACHA20_POLY1305 = 346, + SEC_OID_TOTAL } SECOidTag; diff --git a/security/nss/lib/util/utf8.c b/security/nss/lib/util/utf8.c index bb89bc5bccc8..04ef24111bab 100644 --- a/security/nss/lib/util/utf8.c +++ b/security/nss/lib/util/utf8.c @@ -321,8 +321,8 @@ sec_port_ucs2_utf8_conversion_function for( i = 0; i < inBufLen; i += 2 ) { if( (inBuf[i+H_0] == 0x00) && ((inBuf[i+H_1] & 0x80) == 0x00) ) len += 1; else if( inBuf[i+H_0] < 0x08 ) len += 2; - else if( ((inBuf[i+0+H_0] & 0xDC) == 0xD8) ) { - if( ((inBufLen - i) > 2) && ((inBuf[i+2+H_0] & 0xDC) == 0xDC) ) { + else if( ((inBuf[i+0+H_0] & 0xFC) == 0xD8) ) { + if( ((inBufLen - i) > 2) && ((inBuf[i+2+H_0] & 0xFC) == 0xDC) ) { i += 2; len += 4; } else { @@ -356,10 +356,10 @@ sec_port_ucs2_utf8_conversion_function outBuf[len+1] = 0x80 | ((inBuf[i+H_1] & 0x3F) >> 0); len += 2; - } else if( (inBuf[i+H_0] & 0xDC) == 0xD8 ) { + } else if( (inBuf[i+H_0] & 0xFC) == 0xD8 ) { int abcde, BCDE; - PORT_Assert(((inBufLen - i) > 2) && ((inBuf[i+2+H_0] & 0xDC) == 0xDC) ); + PORT_Assert(((inBufLen - i) > 2) && ((inBuf[i+2+H_0] & 0xFC) == 0xDC) ); /* D800-DBFF DC00-DFFF -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ /* 110110BC DEfghijk 110111lm nopqrstu -> @@ -852,6 +852,7 @@ struct ucs2 ucs2[] = { { 0x9000, "\xE9\x80\x80" }, { 0xA000, "\xEA\x80\x80" }, { 0xC000, "\xEC\x80\x80" }, + { 0xFB01, "\xEF\xAC\x81" }, { 0xFFFF, "\xEF\xBF\xBF" } }; @@ -1161,6 +1162,8 @@ uint16_t utf16_bad[][3] = { { 0xD800, 0xfe, 0 }, { 0xD800, 0x3bb, 0 }, { 0xD800, 0xD800, 0 }, + { 0xD800, 0xFEFF, 0 }, + { 0xD800, 0xFFFD, 0 }, }; static void diff --git a/security/nss/tests/cipher/cipher.txt b/security/nss/tests/cipher/cipher.txt index 6728d1799c7f..447a3ebd6da9 100644 --- a/security/nss/tests/cipher/cipher.txt +++ b/security/nss/tests/cipher/cipher.txt @@ -31,6 +31,8 @@ 0 seed_ecb_-D SEED_ECB_Decrypt 0 seed_cbc_-E SEED_CBC_Encrypt 0 seed_cbc_-D SEED_CBC_Decrypt + 0 chacha20_poly1305_-E ChaCha20_Poly1305_Encrypt + 0 chacha20_poly1305_-D ChaCha20_Poly1305_Decrypt 0 rc2_ecb_-E RC2_ECB_Encrypt 0 rc2_ecb_-D RC2_ECB_Decrypt 0 rc2_cbc_-E RC2_CBC_Encrypt diff --git a/security/nss/tests/ssl/ssl.sh b/security/nss/tests/ssl/ssl.sh index 35b56ffc610d..125ad59ccda3 100755 --- a/security/nss/tests/ssl/ssl.sh +++ b/security/nss/tests/ssl/ssl.sh @@ -85,12 +85,14 @@ ssl_init() if [ -z "$NSS_DISABLE_ECC" ] ; then ECC_STRING=" - with ECC" + # List of cipher suites to test, including ECC cipher suites. + CIPHER_SUITES="-c ABCDEF:C001:C002:C003:C004:C005:C006:C007:C008:C009:C00A:C00B:C00C:C00D:C00E:C00F:C010:C011:C012:C013:C014:C023:C027:C02B:C02F:CCA8:CCA9:CCAA:0016:0032:0033:0038:0039:003B:003C:003D:0040:0041:0067:006A:006B:0084:009C:009E:00A2cdefgijklmnvyz" else ECC_STRING="" + # List of cipher suites to test, excluding ECC cipher suites. + CIPHER_SUITES="-c ABCDEF:0016:0032:0033:0038:0039:003B:003C:003D:0040:0041:0067:006A:006B:0084:009C:009E:00A2:CCAAcdefgijklmnvyz" fi - CSHORT="-c ABCDEF:0016:0032:0033:0038:0039:003B:003C:003D:0040:0041:0067:006A:006B:0084:009C:009E:00A2cdefgijklmnvyz" - CLONG="-c ABCDEF:C001:C002:C003:C004:C005:C006:C007:C008:C009:C00A:C00B:C00C:C00D:C00E:C00F:C010:C011:C012:C013:C014:C023:C027:C02B:C02F:0016:0032:0033:0038:0039:003B:003C:003D:0040:0041:0067:006A:006B:0084:009C:009E:00A2cdefgijklmnvyz" if [ "${OS_ARCH}" != "WINNT" ]; then ulimit -n 1000 # make sure we have enough file descriptors @@ -260,11 +262,7 @@ ssl_cov() html_head "SSL Cipher Coverage $NORM_EXT - server $SERVER_MODE/client $CLIENT_MODE $ECC_STRING" testname="" - if [ -z "$NSS_DISABLE_ECC" ] ; then - sparam="$CLONG" - else - sparam="$CSHORT" - fi + sparam="$CIPHER_SUITES" mixed=0 start_selfserv # Launch the server @@ -731,11 +729,7 @@ ssl_policy() html_head "SSL POLICY $NORM_EXT - server $SERVER_MODE/client $CLIENT_MODE $ECC_STRING" testname="" - if [ -z "$NSS_DISABLE_ECC" ] ; then - sparam="$CLONG" - else - sparam="$CSHORT" - fi + sparam="$CIPHER_SUITES" if [ ! -f "${P_R_CLIENTDIR}/pkcs11.txt" ] ; then return; diff --git a/security/nss/tests/ssl/sslcov.txt b/security/nss/tests/ssl/sslcov.txt index c050dd8b442d..da6f23e76293 100644 --- a/security/nss/tests/ssl/sslcov.txt +++ b/security/nss/tests/ssl/sslcov.txt @@ -101,6 +101,7 @@ noECC TLS12 :009C TLS12_RSA_WITH_AES_128_GCM_SHA256 noECC TLS12 :009E TLS12_DHE_RSA_WITH_AES_128_GCM_SHA256 noECC TLS12 :00A2 TLS12_DHE_DSS_WITH_AES_128_GCM_SHA256 + noECC TLS12 :CCAA TLS12_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 # # ECC ciphers (TLS) # @@ -170,3 +171,5 @@ ECC TLS12 :C027 TLS12_ECDHE_RSA_WITH_AES_128_CBC_SHA256 ECC TLS12 :C02B TLS12_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ECC TLS12 :C02F TLS12_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + ECC TLS12 :CCA8 TLS12_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 + ECC TLS12 :CCA9 TLS12_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256