michael@0: /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ michael@0: /* michael@0: * SSL3 Protocol michael@0: * michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */ michael@0: michael@0: #include "cert.h" michael@0: #include "ssl.h" michael@0: #include "cryptohi.h" /* for DSAU_ stuff */ michael@0: #include "keyhi.h" michael@0: #include "secder.h" michael@0: #include "secitem.h" michael@0: #include "sechash.h" michael@0: michael@0: #include "sslimpl.h" michael@0: #include "sslproto.h" michael@0: #include "sslerr.h" michael@0: #include "prtime.h" michael@0: #include "prinrval.h" michael@0: #include "prerror.h" michael@0: #include "pratom.h" michael@0: #include "prthread.h" michael@0: michael@0: #include "pk11func.h" michael@0: #include "secmod.h" michael@0: #ifndef NO_PKCS11_BYPASS michael@0: #include "blapi.h" michael@0: #endif michael@0: michael@0: #include michael@0: #ifdef NSS_ENABLE_ZLIB michael@0: #include "zlib.h" michael@0: #endif michael@0: michael@0: #ifndef PK11_SETATTRS michael@0: #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ michael@0: (x)->pValue=(v); (x)->ulValueLen = (l); michael@0: #endif michael@0: michael@0: static SECStatus ssl3_AuthCertificate(sslSocket *ss); michael@0: static void ssl3_CleanupPeerCerts(sslSocket *ss); michael@0: static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, michael@0: PK11SlotInfo * serverKeySlot); michael@0: static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms); michael@0: static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss); michael@0: static SECStatus ssl3_HandshakeFailure( sslSocket *ss); michael@0: static SECStatus ssl3_InitState( sslSocket *ss); michael@0: static SECStatus ssl3_SendCertificate( sslSocket *ss); michael@0: static SECStatus ssl3_SendCertificateStatus( sslSocket *ss); michael@0: static SECStatus ssl3_SendEmptyCertificate( sslSocket *ss); michael@0: static SECStatus ssl3_SendCertificateRequest(sslSocket *ss); michael@0: static SECStatus ssl3_SendNextProto( sslSocket *ss); michael@0: static SECStatus ssl3_SendFinished( sslSocket *ss, PRInt32 flags); michael@0: static SECStatus ssl3_SendServerHello( sslSocket *ss); michael@0: static SECStatus ssl3_SendServerHelloDone( sslSocket *ss); michael@0: static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss); michael@0: static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss, michael@0: const unsigned char *b, michael@0: unsigned int l); michael@0: static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); michael@0: static int ssl3_OIDToTLSHashAlgorithm(SECOidTag oid); michael@0: michael@0: static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, michael@0: int maxOutputLen, const unsigned char *input, michael@0: int inputLen); michael@0: #ifndef NO_PKCS11_BYPASS michael@0: static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, michael@0: unsigned char *out, int *outlen, int maxout, michael@0: const unsigned char *in, int inlen, michael@0: const unsigned char *additionalData, michael@0: int additionalDataLen); michael@0: #endif michael@0: michael@0: #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ michael@0: #define MIN_SEND_BUF_LENGTH 4000 michael@0: michael@0: /* This list of SSL3 cipher suites is sorted in descending order of michael@0: * precedence (desirability). It only includes cipher suites we implement. michael@0: * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites michael@0: * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c) michael@0: * michael@0: * Important: See bug 946147 before enabling, reordering, or adding any cipher michael@0: * suites to this list. michael@0: */ michael@0: static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { michael@0: /* cipher_suite policy enabled isPresent */ michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around michael@0: * bug 946147. michael@0: */ michael@0: { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: /* RSA */ michael@0: { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: { TLS_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE}, michael@0: michael@0: /* 56-bit DES "domestic" cipher suites */ michael@0: { TLS_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: michael@0: /* export ciphersuites with 1024-bit public key exchange keys */ michael@0: { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: michael@0: /* export ciphersuites with 512-bit public key exchange keys */ michael@0: { TLS_RSA_EXPORT_WITH_RC4_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: michael@0: /* ciphersuites with no encryption */ michael@0: #ifndef NSS_DISABLE_ECC michael@0: { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, michael@0: }; michael@0: michael@0: /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order. michael@0: */ michael@0: #ifdef DEBUG michael@0: void ssl3_CheckCipherSuiteOrderConsistency() michael@0: { michael@0: unsigned int i; michael@0: michael@0: /* Note that SSL_ImplementedCiphers has more elements than cipherSuites michael@0: * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites. michael@0: */ michael@0: PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites)); michael@0: michael@0: for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) { michael@0: PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: /* This list of SSL3 compression methods is sorted in descending order of michael@0: * precedence (desirability). It only includes compression methods we michael@0: * implement. michael@0: */ michael@0: static const /*SSLCompressionMethod*/ PRUint8 compressions [] = { michael@0: #ifdef NSS_ENABLE_ZLIB michael@0: ssl_compression_deflate, michael@0: #endif michael@0: ssl_compression_null michael@0: }; michael@0: michael@0: static const int compressionMethodsCount = michael@0: sizeof(compressions) / sizeof(compressions[0]); michael@0: michael@0: /* compressionEnabled returns true iff the compression algorithm is enabled michael@0: * for the given SSL socket. */ michael@0: static PRBool michael@0: compressionEnabled(sslSocket *ss, SSLCompressionMethod compression) michael@0: { michael@0: switch (compression) { michael@0: case ssl_compression_null: michael@0: return PR_TRUE; /* Always enabled */ michael@0: #ifdef NSS_ENABLE_ZLIB michael@0: case ssl_compression_deflate: michael@0: return ss->opt.enableDeflate; michael@0: #endif michael@0: default: michael@0: return PR_FALSE; michael@0: } michael@0: } michael@0: michael@0: static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = { michael@0: ct_RSA_sign, michael@0: #ifndef NSS_DISABLE_ECC michael@0: ct_ECDSA_sign, michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: ct_DSS_sign, michael@0: }; michael@0: michael@0: /* This block is the contents of the supported_signature_algorithms field of michael@0: * our TLS 1.2 CertificateRequest message, in wire format. See michael@0: * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 michael@0: * michael@0: * This block contains only sha256 entries because we only support TLS 1.2 michael@0: * CertificateVerify messages that use the handshake hash. */ michael@0: static const PRUint8 supported_signature_algorithms[] = { michael@0: tls_hash_sha256, tls_sig_rsa, michael@0: #ifndef NSS_DISABLE_ECC michael@0: tls_hash_sha256, tls_sig_ecdsa, michael@0: #endif michael@0: tls_hash_sha256, tls_sig_dsa, michael@0: }; michael@0: michael@0: #define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ michael@0: michael@0: michael@0: /* This global item is used only in servers. It is is initialized by michael@0: ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest(). michael@0: */ michael@0: CERTDistNames *ssl3_server_ca_list = NULL; michael@0: static SSL3Statistics ssl3stats; michael@0: michael@0: /* indexed by SSL3BulkCipher */ michael@0: static const ssl3BulkCipherDef bulk_cipher_defs[] = { michael@0: /* |--------- Lengths --------| */ michael@0: /* cipher calg k s type i b t n */ michael@0: /* e e v l a o */ michael@0: /* y c | o g n */ michael@0: /* | r | c | c */ michael@0: /* | e | k | e */ michael@0: /* | t | | | | */ michael@0: {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, michael@0: {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, michael@0: {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, michael@0: {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, michael@0: {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, michael@0: {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, michael@0: {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, michael@0: {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, michael@0: {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, michael@0: {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, michael@0: {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, michael@0: {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, michael@0: {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, michael@0: {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, michael@0: {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, michael@0: {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, michael@0: {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, michael@0: }; michael@0: michael@0: static const ssl3KEADef kea_defs[] = michael@0: { /* indexed by SSL3KeyExchangeAlgorithm */ michael@0: /* kea exchKeyType signKeyType is_limited limit tls_keygen */ michael@0: {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE}, michael@0: {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE}, michael@0: {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE}, michael@0: {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE}, michael@0: {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE}, michael@0: {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE}, michael@0: {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE}, michael@0: {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE }, michael@0: #ifndef NSS_DISABLE_ECC michael@0: {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE}, michael@0: {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE}, michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: }; michael@0: michael@0: /* must use ssl_LookupCipherSuiteDef to access */ michael@0: static const ssl3CipherSuiteDef cipher_suite_defs[] = michael@0: { michael@0: /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */ michael@0: michael@0: {TLS_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null}, michael@0: {TLS_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa}, michael@0: {TLS_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa}, michael@0: {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa}, michael@0: {TLS_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export}, michael@0: {TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa}, michael@0: {TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa}, michael@0: {TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, michael@0: cipher_rc2_40, mac_md5, kea_rsa_export}, michael@0: #if 0 /* not implemented */ michael@0: {TLS_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa}, michael@0: {TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, michael@0: cipher_des40, mac_sha, kea_rsa_export}, michael@0: #endif michael@0: {TLS_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa}, michael@0: {TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa}, michael@0: {TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss}, michael@0: {TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, michael@0: cipher_3des, mac_sha, kea_dhe_dss}, michael@0: {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss}, michael@0: #if 0 /* not implemented */ michael@0: {TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, michael@0: cipher_des40, mac_sha, kea_dh_dss_export}, michael@0: {TLS_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss}, michael@0: {TLS_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss}, michael@0: {TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, michael@0: cipher_des40, mac_sha, kea_dh_rsa_export}, michael@0: {TLS_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa}, michael@0: {TLS_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa}, michael@0: {TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, michael@0: cipher_des40, mac_sha, kea_dh_dss_export}, michael@0: {TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, michael@0: cipher_des40, mac_sha, kea_dh_rsa_export}, michael@0: #endif michael@0: {TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa}, michael@0: {TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, michael@0: cipher_3des, mac_sha, kea_dhe_rsa}, michael@0: #if 0 michael@0: {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export}, michael@0: {TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, michael@0: cipher_des40, mac_sha, kea_dh_anon_export}, michael@0: {TLS_DH_anon_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon}, michael@0: {TLS_DH_anon_WITH_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon}, michael@0: #endif michael@0: michael@0: michael@0: /* New TLS cipher suites */ michael@0: {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa}, michael@0: {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa}, michael@0: {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss}, michael@0: {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa}, michael@0: {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa}, michael@0: {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa}, michael@0: {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa}, michael@0: {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss}, michael@0: {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa}, michael@0: {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa}, michael@0: #if 0 michael@0: {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss}, michael@0: {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa}, michael@0: {TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon}, michael@0: {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss}, michael@0: {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa}, michael@0: {TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon}, michael@0: #endif michael@0: michael@0: {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa}, michael@0: michael@0: {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa}, michael@0: {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, michael@0: cipher_camellia_128, mac_sha, kea_dhe_dss}, michael@0: {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, michael@0: cipher_camellia_128, mac_sha, kea_dhe_rsa}, michael@0: {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa}, michael@0: {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, michael@0: cipher_camellia_256, mac_sha, kea_dhe_dss}, michael@0: {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, michael@0: cipher_camellia_256, mac_sha, kea_dhe_rsa}, michael@0: michael@0: {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, michael@0: cipher_des, mac_sha,kea_rsa_export_1024}, michael@0: {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, michael@0: cipher_rc4_56, mac_sha,kea_rsa_export_1024}, michael@0: michael@0: {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, michael@0: {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, michael@0: michael@0: {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa}, michael@0: {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa}, michael@0: {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa}, michael@0: {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa}, michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, michael@0: {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, michael@0: {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa}, michael@0: {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa}, michael@0: {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa}, michael@0: michael@0: {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa}, michael@0: {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa}, michael@0: {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa}, michael@0: {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa}, michael@0: {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa}, michael@0: {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa}, michael@0: michael@0: {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa}, michael@0: {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa}, michael@0: {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa}, michael@0: {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa}, michael@0: {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa}, michael@0: michael@0: {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa}, michael@0: {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa}, michael@0: {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa}, michael@0: {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa}, michael@0: {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa}, michael@0: {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa}, michael@0: michael@0: #if 0 michael@0: {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon}, michael@0: {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon}, michael@0: {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon}, michael@0: {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon}, michael@0: {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon}, michael@0: #endif michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: }; michael@0: michael@0: static const CK_MECHANISM_TYPE kea_alg_defs[] = { michael@0: 0x80000000L, michael@0: CKM_RSA_PKCS, michael@0: CKM_DH_PKCS_DERIVE, michael@0: CKM_KEA_KEY_DERIVE, michael@0: CKM_ECDH1_DERIVE michael@0: }; michael@0: michael@0: typedef struct SSLCipher2MechStr { michael@0: SSLCipherAlgorithm calg; michael@0: CK_MECHANISM_TYPE cmech; michael@0: } SSLCipher2Mech; michael@0: michael@0: /* indexed by type SSLCipherAlgorithm */ michael@0: static const SSLCipher2Mech alg2Mech[] = { michael@0: /* calg, cmech */ michael@0: { calg_null , (CK_MECHANISM_TYPE)0x80000000L }, michael@0: { calg_rc4 , CKM_RC4 }, michael@0: { calg_rc2 , CKM_RC2_CBC }, michael@0: { calg_des , CKM_DES_CBC }, michael@0: { calg_3des , CKM_DES3_CBC }, michael@0: { calg_idea , CKM_IDEA_CBC }, michael@0: { calg_fortezza , CKM_SKIPJACK_CBC64 }, michael@0: { calg_aes , CKM_AES_CBC }, michael@0: { calg_camellia , CKM_CAMELLIA_CBC }, michael@0: { calg_seed , CKM_SEED_CBC }, michael@0: { calg_aes_gcm , CKM_AES_GCM }, michael@0: /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ michael@0: }; michael@0: michael@0: #define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L michael@0: #define mmech_md5 CKM_SSL3_MD5_MAC michael@0: #define mmech_sha CKM_SSL3_SHA1_MAC michael@0: #define mmech_md5_hmac CKM_MD5_HMAC michael@0: #define mmech_sha_hmac CKM_SHA_1_HMAC michael@0: #define mmech_sha256_hmac CKM_SHA256_HMAC michael@0: michael@0: static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ michael@0: /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ michael@0: /* mac mmech pad_size mac_size */ michael@0: { mac_null, mmech_invalid, 0, 0 }, michael@0: { mac_md5, mmech_md5, 48, MD5_LENGTH }, michael@0: { mac_sha, mmech_sha, 40, SHA1_LENGTH}, michael@0: {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH }, michael@0: {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH}, michael@0: {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH}, michael@0: { mac_aead, mmech_invalid, 0, 0 }, michael@0: }; michael@0: michael@0: /* indexed by SSL3BulkCipher */ michael@0: const char * const ssl3_cipherName[] = { michael@0: "NULL", michael@0: "RC4", michael@0: "RC4-40", michael@0: "RC4-56", michael@0: "RC2-CBC", michael@0: "RC2-CBC-40", michael@0: "DES-CBC", michael@0: "3DES-EDE-CBC", michael@0: "DES-CBC-40", michael@0: "IDEA-CBC", michael@0: "AES-128", michael@0: "AES-256", michael@0: "Camellia-128", michael@0: "Camellia-256", michael@0: "SEED-CBC", michael@0: "AES-128-GCM", michael@0: "missing" michael@0: }; michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: /* The ECCWrappedKeyInfo structure defines how various pieces of michael@0: * information are laid out within wrappedSymmetricWrappingkey michael@0: * for ECDH key exchange. Since wrappedSymmetricWrappingkey is michael@0: * a 512-byte buffer (see sslimpl.h), the variable length field michael@0: * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes. michael@0: * michael@0: * XXX For now, NSS only supports named elliptic curves of size 571 bits michael@0: * or smaller. The public value will fit within 145 bytes and EC params michael@0: * will fit within 12 bytes. We'll need to revisit this when NSS michael@0: * supports arbitrary curves. michael@0: */ michael@0: #define MAX_EC_WRAPPED_KEY_BUFLEN 504 michael@0: michael@0: typedef struct ECCWrappedKeyInfoStr { michael@0: PRUint16 size; /* EC public key size in bits */ michael@0: PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */ michael@0: PRUint16 pubValueLen; /* length (in bytes) of EC public value */ michael@0: PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */ michael@0: PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */ michael@0: /* EC public-key params, the EC public value and the wrapped key */ michael@0: } ECCWrappedKeyInfo; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: #if defined(TRACE) michael@0: michael@0: static char * michael@0: ssl3_DecodeHandshakeType(int msgType) michael@0: { michael@0: char * rv; michael@0: static char line[40]; michael@0: michael@0: switch(msgType) { michael@0: case hello_request: rv = "hello_request (0)"; break; michael@0: case client_hello: rv = "client_hello (1)"; break; michael@0: case server_hello: rv = "server_hello (2)"; break; michael@0: case hello_verify_request: rv = "hello_verify_request (3)"; break; michael@0: case certificate: rv = "certificate (11)"; break; michael@0: case server_key_exchange: rv = "server_key_exchange (12)"; break; michael@0: case certificate_request: rv = "certificate_request (13)"; break; michael@0: case server_hello_done: rv = "server_hello_done (14)"; break; michael@0: case certificate_verify: rv = "certificate_verify (15)"; break; michael@0: case client_key_exchange: rv = "client_key_exchange (16)"; break; michael@0: case finished: rv = "finished (20)"; break; michael@0: default: michael@0: sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); michael@0: rv = line; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: static char * michael@0: ssl3_DecodeContentType(int msgType) michael@0: { michael@0: char * rv; michael@0: static char line[40]; michael@0: michael@0: switch(msgType) { michael@0: case content_change_cipher_spec: michael@0: rv = "change_cipher_spec (20)"; break; michael@0: case content_alert: rv = "alert (21)"; break; michael@0: case content_handshake: rv = "handshake (22)"; break; michael@0: case content_application_data: michael@0: rv = "application_data (23)"; break; michael@0: default: michael@0: sprintf(line, "*UNKNOWN* record type! (%d)", msgType); michael@0: rv = line; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: #endif michael@0: michael@0: SSL3Statistics * michael@0: SSL_GetStatistics(void) michael@0: { michael@0: return &ssl3stats; michael@0: } michael@0: michael@0: typedef struct tooLongStr { michael@0: #if defined(IS_LITTLE_ENDIAN) michael@0: PRInt32 low; michael@0: PRInt32 high; michael@0: #else michael@0: PRInt32 high; michael@0: PRInt32 low; michael@0: #endif michael@0: } tooLong; michael@0: michael@0: void SSL_AtomicIncrementLong(long * x) michael@0: { michael@0: if ((sizeof *x) == sizeof(PRInt32)) { michael@0: PR_ATOMIC_INCREMENT((PRInt32 *)x); michael@0: } else { michael@0: tooLong * tl = (tooLong *)x; michael@0: if (PR_ATOMIC_INCREMENT(&tl->low) == 0) michael@0: PR_ATOMIC_INCREMENT(&tl->high); michael@0: } michael@0: } michael@0: michael@0: static PRBool michael@0: ssl3_CipherSuiteAllowedForVersionRange( michael@0: ssl3CipherSuite cipherSuite, michael@0: const SSLVersionRange *vrange) michael@0: { michael@0: switch (cipherSuite) { michael@0: /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or michael@0: * later. This set of cipher suites is similar to, but different from, the michael@0: * set of cipher suites considered exportable by SSL_IsExportCipherSuite. michael@0: */ michael@0: case TLS_RSA_EXPORT_WITH_RC4_40_MD5: michael@0: case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: michael@0: /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented michael@0: * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented michael@0: * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented michael@0: * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented michael@0: * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented michael@0: * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented michael@0: * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented michael@0: */ michael@0: return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; michael@0: michael@0: case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: michael@0: case TLS_RSA_WITH_AES_256_CBC_SHA256: michael@0: case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: michael@0: case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: michael@0: case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: michael@0: case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: michael@0: case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: michael@0: case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: michael@0: case TLS_RSA_WITH_AES_128_CBC_SHA256: michael@0: case TLS_RSA_WITH_AES_128_GCM_SHA256: michael@0: case TLS_RSA_WITH_NULL_SHA256: michael@0: return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2; michael@0: michael@0: /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and michael@0: * point formats.*/ michael@0: case TLS_ECDH_ECDSA_WITH_NULL_SHA: michael@0: case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: michael@0: case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: michael@0: case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: michael@0: case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: michael@0: case TLS_ECDHE_ECDSA_WITH_NULL_SHA: michael@0: case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: michael@0: case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: michael@0: case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: michael@0: case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: michael@0: case TLS_ECDH_RSA_WITH_NULL_SHA: michael@0: case TLS_ECDH_RSA_WITH_RC4_128_SHA: michael@0: case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: michael@0: case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: michael@0: case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: michael@0: case TLS_ECDHE_RSA_WITH_NULL_SHA: michael@0: case TLS_ECDHE_RSA_WITH_RC4_128_SHA: michael@0: case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: michael@0: case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: michael@0: case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: michael@0: return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0; michael@0: michael@0: default: michael@0: return PR_TRUE; michael@0: } michael@0: } michael@0: michael@0: /* return pointer to ssl3CipherSuiteDef for suite, or NULL */ michael@0: /* XXX This does a linear search. A binary search would be better. */ michael@0: static const ssl3CipherSuiteDef * michael@0: ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) michael@0: { michael@0: int cipher_suite_def_len = michael@0: sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); michael@0: int i; michael@0: michael@0: for (i = 0; i < cipher_suite_def_len; i++) { michael@0: if (cipher_suite_defs[i].cipher_suite == suite) michael@0: return &cipher_suite_defs[i]; michael@0: } michael@0: PORT_Assert(PR_FALSE); /* We should never get here. */ michael@0: PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); michael@0: return NULL; michael@0: } michael@0: michael@0: /* Find the cipher configuration struct associate with suite */ michael@0: /* XXX This does a linear search. A binary search would be better. */ michael@0: static ssl3CipherSuiteCfg * michael@0: ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) michael@0: { michael@0: int i; michael@0: michael@0: for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { michael@0: if (suites[i].cipher_suite == suite) michael@0: return &suites[i]; michael@0: } michael@0: /* return NULL and let the caller handle it. */ michael@0: PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); michael@0: return NULL; michael@0: } michael@0: michael@0: michael@0: /* Initialize the suite->isPresent value for config_match michael@0: * Returns count of enabled ciphers supported by extant tokens, michael@0: * regardless of policy or user preference. michael@0: * If this returns zero, the user cannot do SSL v3. michael@0: */ michael@0: int michael@0: ssl3_config_match_init(sslSocket *ss) michael@0: { michael@0: ssl3CipherSuiteCfg * suite; michael@0: const ssl3CipherSuiteDef *cipher_def; michael@0: SSLCipherAlgorithm cipher_alg; michael@0: CK_MECHANISM_TYPE cipher_mech; michael@0: SSL3KEAType exchKeyType; michael@0: int i; michael@0: int numPresent = 0; michael@0: int numEnabled = 0; michael@0: PRBool isServer; michael@0: sslServerCerts *svrAuth; michael@0: michael@0: PORT_Assert(ss); michael@0: if (!ss) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return 0; michael@0: } michael@0: if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { michael@0: return 0; michael@0: } michael@0: isServer = (PRBool)(ss->sec.isServer != 0); michael@0: michael@0: for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { michael@0: suite = &ss->cipherSuites[i]; michael@0: if (suite->enabled) { michael@0: ++numEnabled; michael@0: /* We need the cipher defs to see if we have a token that can handle michael@0: * this cipher. It isn't part of the static definition. michael@0: */ michael@0: cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); michael@0: if (!cipher_def) { michael@0: suite->isPresent = PR_FALSE; michael@0: continue; michael@0: } michael@0: cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; michael@0: PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg); michael@0: cipher_mech = alg2Mech[cipher_alg].cmech; michael@0: exchKeyType = michael@0: kea_defs[cipher_def->key_exchange_alg].exchKeyType; michael@0: #ifdef NSS_DISABLE_ECC michael@0: svrAuth = ss->serverCerts + exchKeyType; michael@0: #else michael@0: /* XXX SSLKEAType isn't really a good choice for michael@0: * indexing certificates. It doesn't work for michael@0: * (EC)DHE-* ciphers. Here we use a hack to ensure michael@0: * that the server uses an RSA cert for (EC)DHE-RSA. michael@0: */ michael@0: switch (cipher_def->key_exchange_alg) { michael@0: case kea_ecdhe_rsa: michael@0: #if NSS_SERVER_DHE_IMPLEMENTED michael@0: /* XXX NSS does not yet implement the server side of _DHE_ michael@0: * cipher suites. Correcting the computation for svrAuth, michael@0: * as the case below does, causes NSS SSL servers to begin to michael@0: * negotiate cipher suites they do not implement. So, until michael@0: * server side _DHE_ is implemented, keep this disabled. michael@0: */ michael@0: case kea_dhe_rsa: michael@0: #endif michael@0: svrAuth = ss->serverCerts + kt_rsa; michael@0: break; michael@0: case kea_ecdh_ecdsa: michael@0: case kea_ecdh_rsa: michael@0: /* michael@0: * XXX We ought to have different indices for michael@0: * ECDSA- and RSA-signed EC certificates so michael@0: * we could support both key exchange mechanisms michael@0: * simultaneously. For now, both of them use michael@0: * whatever is in the certificate slot for kt_ecdh michael@0: */ michael@0: default: michael@0: svrAuth = ss->serverCerts + exchKeyType; michael@0: break; michael@0: } michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: /* Mark the suites that are backed by real tokens, certs and keys */ michael@0: suite->isPresent = (PRBool) michael@0: (((exchKeyType == kt_null) || michael@0: ((!isServer || (svrAuth->serverKeyPair && michael@0: svrAuth->SERVERKEY && michael@0: svrAuth->serverCertChain)) && michael@0: PK11_TokenExists(kea_alg_defs[exchKeyType]))) && michael@0: ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech))); michael@0: if (suite->isPresent) michael@0: ++numPresent; michael@0: } michael@0: } michael@0: PORT_Assert(numPresent > 0 || numEnabled == 0); michael@0: if (numPresent <= 0) { michael@0: PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); michael@0: } michael@0: return numPresent; michael@0: } michael@0: michael@0: michael@0: /* return PR_TRUE if suite matches policy, enabled state and is applicable to michael@0: * the given version range. */ michael@0: /* It would be a REALLY BAD THING (tm) if we ever permitted the use michael@0: ** of a cipher that was NOT_ALLOWED. So, if this is ever called with michael@0: ** policy == SSL_NOT_ALLOWED, report no match. michael@0: */ michael@0: /* adjust suite enabled to the availability of a token that can do the michael@0: * cipher suite. */ michael@0: static PRBool michael@0: config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, michael@0: const SSLVersionRange *vrange) michael@0: { michael@0: PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE); michael@0: if (policy == SSL_NOT_ALLOWED || !enabled) michael@0: return PR_FALSE; michael@0: return (PRBool)(suite->enabled && michael@0: suite->isPresent && michael@0: suite->policy != SSL_NOT_ALLOWED && michael@0: suite->policy <= policy && michael@0: ssl3_CipherSuiteAllowedForVersionRange( michael@0: suite->cipher_suite, vrange)); michael@0: } michael@0: michael@0: /* return number of cipher suites that match policy, enabled state and are michael@0: * applicable for the configured protocol version range. */ michael@0: /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */ michael@0: static int michael@0: count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) michael@0: { michael@0: int i, count = 0; michael@0: michael@0: if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { michael@0: return 0; michael@0: } michael@0: for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { michael@0: if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange)) michael@0: count++; michael@0: } michael@0: if (count <= 0) { michael@0: PORT_SetError(SSL_ERROR_SSL_DISABLED); michael@0: } michael@0: return count; michael@0: } michael@0: michael@0: /* michael@0: * Null compression, mac and encryption functions michael@0: */ michael@0: michael@0: static SECStatus michael@0: Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, michael@0: const unsigned char *input, int inputLen) michael@0: { michael@0: if (inputLen > maxOutputLen) { michael@0: *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ michael@0: PORT_SetError(SEC_ERROR_OUTPUT_LEN); michael@0: return SECFailure; michael@0: } michael@0: *outputLen = inputLen; michael@0: if (input != output) michael@0: PORT_Memcpy(output, input, inputLen); michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* michael@0: * SSL3 Utility functions michael@0: */ michael@0: michael@0: /* allowLargerPeerVersion controls whether the function will select the michael@0: * highest enabled SSL version or fail when peerVersion is greater than the michael@0: * highest enabled version. michael@0: * michael@0: * If allowLargerPeerVersion is true, peerVersion is the peer's highest michael@0: * enabled version rather than the peer's selected version. michael@0: */ michael@0: SECStatus michael@0: ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, michael@0: PRBool allowLargerPeerVersion) michael@0: { michael@0: if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { michael@0: PORT_SetError(SSL_ERROR_SSL_DISABLED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (peerVersion < ss->vrange.min || michael@0: (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { michael@0: PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); michael@0: return SECFailure; michael@0: } michael@0: michael@0: ss->version = PR_MIN(peerVersion, ss->vrange.max); michael@0: PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version)); michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_GetNewRandom(SSL3Random *random) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: /* first 4 bytes are reserverd for time */ michael@0: rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ michael@0: SECStatus michael@0: ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, michael@0: PRBool isTLS) michael@0: { michael@0: SECStatus rv = SECFailure; michael@0: PRBool doDerEncode = PR_FALSE; michael@0: int signatureLen; michael@0: SECItem hashItem; michael@0: michael@0: buf->data = NULL; michael@0: michael@0: switch (key->keyType) { michael@0: case rsaKey: michael@0: hashItem.data = hash->u.raw; michael@0: hashItem.len = hash->len; michael@0: break; michael@0: case dsaKey: michael@0: doDerEncode = isTLS; michael@0: /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. michael@0: * In that case, we use just the SHA1 part. */ michael@0: if (hash->hashAlg == SEC_OID_UNKNOWN) { michael@0: hashItem.data = hash->u.s.sha; michael@0: hashItem.len = sizeof(hash->u.s.sha); michael@0: } else { michael@0: hashItem.data = hash->u.raw; michael@0: hashItem.len = hash->len; michael@0: } michael@0: break; michael@0: #ifndef NSS_DISABLE_ECC michael@0: case ecKey: michael@0: doDerEncode = PR_TRUE; michael@0: /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. michael@0: * In that case, we use just the SHA1 part. */ michael@0: if (hash->hashAlg == SEC_OID_UNKNOWN) { michael@0: hashItem.data = hash->u.s.sha; michael@0: hashItem.len = sizeof(hash->u.s.sha); michael@0: } else { michael@0: hashItem.data = hash->u.raw; michael@0: hashItem.len = hash->len; michael@0: } michael@0: break; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: default: michael@0: PORT_SetError(SEC_ERROR_INVALID_KEY); michael@0: goto done; michael@0: } michael@0: PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len)); michael@0: michael@0: if (hash->hashAlg == SEC_OID_UNKNOWN) { michael@0: signatureLen = PK11_SignatureLen(key); michael@0: if (signatureLen <= 0) { michael@0: PORT_SetError(SEC_ERROR_INVALID_KEY); michael@0: goto done; michael@0: } michael@0: michael@0: buf->len = (unsigned)signatureLen; michael@0: buf->data = (unsigned char *)PORT_Alloc(signatureLen); michael@0: if (!buf->data) michael@0: goto done; /* error code was set. */ michael@0: michael@0: rv = PK11_Sign(key, buf, &hashItem); michael@0: } else { michael@0: rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem); michael@0: } michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); michael@0: } else if (doDerEncode) { michael@0: SECItem derSig = {siBuffer, NULL, 0}; michael@0: michael@0: /* This also works for an ECDSA signature */ michael@0: rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); michael@0: if (rv == SECSuccess) { michael@0: PORT_Free(buf->data); /* discard unencoded signature. */ michael@0: *buf = derSig; /* give caller encoded signature. */ michael@0: } else if (derSig.data) { michael@0: PORT_Free(derSig.data); michael@0: } michael@0: } michael@0: michael@0: PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len)); michael@0: done: michael@0: if (rv != SECSuccess && buf->data) { michael@0: PORT_Free(buf->data); michael@0: buf->data = NULL; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ michael@0: SECStatus michael@0: ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, michael@0: SECItem *buf, PRBool isTLS, void *pwArg) michael@0: { michael@0: SECKEYPublicKey * key; michael@0: SECItem * signature = NULL; michael@0: SECStatus rv; michael@0: SECItem hashItem; michael@0: SECOidTag encAlg; michael@0: SECOidTag hashAlg; michael@0: michael@0: michael@0: PRINT_BUF(60, (NULL, "check signed hashes", michael@0: buf->data, buf->len)); michael@0: michael@0: key = CERT_ExtractPublicKey(cert); michael@0: if (key == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: hashAlg = hash->hashAlg; michael@0: switch (key->keyType) { michael@0: case rsaKey: michael@0: encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; michael@0: hashItem.data = hash->u.raw; michael@0: hashItem.len = hash->len; michael@0: break; michael@0: case dsaKey: michael@0: encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; michael@0: /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. michael@0: * In that case, we use just the SHA1 part. */ michael@0: if (hash->hashAlg == SEC_OID_UNKNOWN) { michael@0: hashItem.data = hash->u.s.sha; michael@0: hashItem.len = sizeof(hash->u.s.sha); michael@0: } else { michael@0: hashItem.data = hash->u.raw; michael@0: hashItem.len = hash->len; michael@0: } michael@0: /* Allow DER encoded DSA signatures in SSL 3.0 */ michael@0: if (isTLS || buf->len != SECKEY_SignatureLen(key)) { michael@0: signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); michael@0: if (!signature) { michael@0: PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); michael@0: return SECFailure; michael@0: } michael@0: buf = signature; michael@0: } michael@0: break; michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: case ecKey: michael@0: encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; michael@0: /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. michael@0: * In that case, we use just the SHA1 part. michael@0: * ECDSA signatures always encode the integers r and s using ASN.1 michael@0: * (unlike DSA where ASN.1 encoding is used with TLS but not with michael@0: * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. michael@0: */ michael@0: if (hash->hashAlg == SEC_OID_UNKNOWN) { michael@0: hashAlg = SEC_OID_SHA1; michael@0: hashItem.data = hash->u.s.sha; michael@0: hashItem.len = sizeof(hash->u.s.sha); michael@0: } else { michael@0: hashItem.data = hash->u.raw; michael@0: hashItem.len = hash->len; michael@0: } michael@0: break; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: default: michael@0: SECKEY_DestroyPublicKey(key); michael@0: PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); michael@0: return SECFailure; michael@0: } michael@0: michael@0: PRINT_BUF(60, (NULL, "hash(es) to be verified", michael@0: hashItem.data, hashItem.len)); michael@0: michael@0: if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) { michael@0: /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. michael@0: * DSA signatures are DER-encoded in TLS but not in SSL3 and the code michael@0: * above always removes the DER encoding of DSA signatures when michael@0: * present. Thus DSA signatures are always verified with PK11_Verify. michael@0: */ michael@0: rv = PK11_Verify(key, buf, &hashItem, pwArg); michael@0: } else { michael@0: rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg, michael@0: pwArg); michael@0: } michael@0: SECKEY_DestroyPublicKey(key); michael@0: if (signature) { michael@0: SECITEM_FreeItem(signature, PR_TRUE); michael@0: } michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: michael@0: /* Caller must set hiLevel error code. */ michael@0: /* Called from ssl3_ComputeExportRSAKeyHash michael@0: * ssl3_ComputeDHKeyHash michael@0: * which are called from ssl3_HandleServerKeyExchange. michael@0: * michael@0: * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify michael@0: * the pre-1.2, MD5/SHA1 combination hash. michael@0: */ michael@0: SECStatus michael@0: ssl3_ComputeCommonKeyHash(SECOidTag hashAlg, michael@0: PRUint8 * hashBuf, unsigned int bufLen, michael@0: SSL3Hashes *hashes, PRBool bypassPKCS11) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (bypassPKCS11) { michael@0: if (hashAlg == SEC_OID_UNKNOWN) { michael@0: MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen); michael@0: SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen); michael@0: hashes->len = MD5_LENGTH + SHA1_LENGTH; michael@0: } else if (hashAlg == SEC_OID_SHA1) { michael@0: SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen); michael@0: hashes->len = SHA1_LENGTH; michael@0: } else if (hashAlg == SEC_OID_SHA256) { michael@0: SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen); michael@0: hashes->len = SHA256_LENGTH; michael@0: } else if (hashAlg == SEC_OID_SHA384) { michael@0: SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen); michael@0: hashes->len = SHA384_LENGTH; michael@0: } else if (hashAlg == SEC_OID_SHA512) { michael@0: SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen); michael@0: hashes->len = SHA512_LENGTH; michael@0: } else { michael@0: PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); michael@0: return SECFailure; michael@0: } michael@0: } else michael@0: #endif michael@0: { michael@0: if (hashAlg == SEC_OID_UNKNOWN) { michael@0: rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: goto done; michael@0: } michael@0: michael@0: rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: } michael@0: hashes->len = MD5_LENGTH + SHA1_LENGTH; michael@0: } else { michael@0: hashes->len = HASH_ResultLenByOidTag(hashAlg); michael@0: if (hashes->len > sizeof(hashes->u.raw)) { michael@0: ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); michael@0: rv = SECFailure; michael@0: goto done; michael@0: } michael@0: rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: } michael@0: } michael@0: } michael@0: hashes->hashAlg = hashAlg; michael@0: michael@0: done: michael@0: return rv; michael@0: } michael@0: michael@0: /* Caller must set hiLevel error code. michael@0: ** Called from ssl3_SendServerKeyExchange and michael@0: ** ssl3_HandleServerKeyExchange. michael@0: */ michael@0: static SECStatus michael@0: ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg, michael@0: SECItem modulus, SECItem publicExponent, michael@0: SSL3Random *client_rand, SSL3Random *server_rand, michael@0: SSL3Hashes *hashes, PRBool bypassPKCS11) michael@0: { michael@0: PRUint8 * hashBuf; michael@0: PRUint8 * pBuf; michael@0: SECStatus rv = SECSuccess; michael@0: unsigned int bufLen; michael@0: PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; michael@0: michael@0: bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len; michael@0: if (bufLen <= sizeof buf) { michael@0: hashBuf = buf; michael@0: } else { michael@0: hashBuf = PORT_Alloc(bufLen); michael@0: if (!hashBuf) { michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); michael@0: pBuf = hashBuf + SSL3_RANDOM_LENGTH; michael@0: memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); michael@0: pBuf += SSL3_RANDOM_LENGTH; michael@0: pBuf[0] = (PRUint8)(modulus.len >> 8); michael@0: pBuf[1] = (PRUint8)(modulus.len); michael@0: pBuf += 2; michael@0: memcpy(pBuf, modulus.data, modulus.len); michael@0: pBuf += modulus.len; michael@0: pBuf[0] = (PRUint8)(publicExponent.len >> 8); michael@0: pBuf[1] = (PRUint8)(publicExponent.len); michael@0: pBuf += 2; michael@0: memcpy(pBuf, publicExponent.data, publicExponent.len); michael@0: pBuf += publicExponent.len; michael@0: PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); michael@0: michael@0: rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, michael@0: bypassPKCS11); michael@0: michael@0: PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen)); michael@0: if (hashAlg == SEC_OID_UNKNOWN) { michael@0: PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", michael@0: hashes->u.s.md5, MD5_LENGTH)); michael@0: PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", michael@0: hashes->u.s.sha, SHA1_LENGTH)); michael@0: } else { michael@0: PRINT_BUF(95, (NULL, "RSAkey hash: result", michael@0: hashes->u.raw, hashes->len)); michael@0: } michael@0: michael@0: if (hashBuf != buf && hashBuf != NULL) michael@0: PORT_Free(hashBuf); michael@0: return rv; michael@0: } michael@0: michael@0: /* Caller must set hiLevel error code. */ michael@0: /* Called from ssl3_HandleServerKeyExchange. */ michael@0: static SECStatus michael@0: ssl3_ComputeDHKeyHash(SECOidTag hashAlg, michael@0: SECItem dh_p, SECItem dh_g, SECItem dh_Ys, michael@0: SSL3Random *client_rand, SSL3Random *server_rand, michael@0: SSL3Hashes *hashes, PRBool bypassPKCS11) michael@0: { michael@0: PRUint8 * hashBuf; michael@0: PRUint8 * pBuf; michael@0: SECStatus rv = SECSuccess; michael@0: unsigned int bufLen; michael@0: PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; michael@0: michael@0: bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len; michael@0: if (bufLen <= sizeof buf) { michael@0: hashBuf = buf; michael@0: } else { michael@0: hashBuf = PORT_Alloc(bufLen); michael@0: if (!hashBuf) { michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); michael@0: pBuf = hashBuf + SSL3_RANDOM_LENGTH; michael@0: memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); michael@0: pBuf += SSL3_RANDOM_LENGTH; michael@0: pBuf[0] = (PRUint8)(dh_p.len >> 8); michael@0: pBuf[1] = (PRUint8)(dh_p.len); michael@0: pBuf += 2; michael@0: memcpy(pBuf, dh_p.data, dh_p.len); michael@0: pBuf += dh_p.len; michael@0: pBuf[0] = (PRUint8)(dh_g.len >> 8); michael@0: pBuf[1] = (PRUint8)(dh_g.len); michael@0: pBuf += 2; michael@0: memcpy(pBuf, dh_g.data, dh_g.len); michael@0: pBuf += dh_g.len; michael@0: pBuf[0] = (PRUint8)(dh_Ys.len >> 8); michael@0: pBuf[1] = (PRUint8)(dh_Ys.len); michael@0: pBuf += 2; michael@0: memcpy(pBuf, dh_Ys.data, dh_Ys.len); michael@0: pBuf += dh_Ys.len; michael@0: PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); michael@0: michael@0: rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, michael@0: bypassPKCS11); michael@0: michael@0: PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen)); michael@0: if (hashAlg == SEC_OID_UNKNOWN) { michael@0: PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", michael@0: hashes->u.s.md5, MD5_LENGTH)); michael@0: PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", michael@0: hashes->u.s.sha, SHA1_LENGTH)); michael@0: } else { michael@0: PRINT_BUF(95, (NULL, "DHkey hash: result", michael@0: hashes->u.raw, hashes->len)); michael@0: } michael@0: michael@0: if (hashBuf != buf && hashBuf != NULL) michael@0: PORT_Free(hashBuf); michael@0: return rv; michael@0: } michael@0: michael@0: static void michael@0: ssl3_BumpSequenceNumber(SSL3SequenceNumber *num) michael@0: { michael@0: num->low++; michael@0: if (num->low == 0) michael@0: num->high++; michael@0: } michael@0: michael@0: /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */ michael@0: static void michael@0: ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat) michael@0: { michael@0: if (mat->write_key != NULL) { michael@0: PK11_FreeSymKey(mat->write_key); michael@0: mat->write_key = NULL; michael@0: } michael@0: if (mat->write_mac_key != NULL) { michael@0: PK11_FreeSymKey(mat->write_mac_key); michael@0: mat->write_mac_key = NULL; michael@0: } michael@0: if (mat->write_mac_context != NULL) { michael@0: PK11_DestroyContext(mat->write_mac_context, PR_TRUE); michael@0: mat->write_mac_context = NULL; michael@0: } michael@0: } michael@0: michael@0: /* Called from ssl3_SendChangeCipherSpecs() and michael@0: ** ssl3_HandleChangeCipherSpecs() michael@0: ** ssl3_DestroySSL3Info michael@0: ** Caller must hold SpecWriteLock. michael@0: */ michael@0: void michael@0: ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) michael@0: { michael@0: PRBool freeit = (PRBool)(!spec->bypassCiphers); michael@0: /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */ michael@0: if (spec->destroy) { michael@0: spec->destroy(spec->encodeContext, freeit); michael@0: spec->destroy(spec->decodeContext, freeit); michael@0: spec->encodeContext = NULL; /* paranoia */ michael@0: spec->decodeContext = NULL; michael@0: } michael@0: if (spec->destroyCompressContext && spec->compressContext) { michael@0: spec->destroyCompressContext(spec->compressContext, 1); michael@0: spec->compressContext = NULL; michael@0: } michael@0: if (spec->destroyDecompressContext && spec->decompressContext) { michael@0: spec->destroyDecompressContext(spec->decompressContext, 1); michael@0: spec->decompressContext = NULL; michael@0: } michael@0: if (freeSrvName && spec->srvVirtName.data) { michael@0: SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE); michael@0: } michael@0: if (spec->master_secret != NULL) { michael@0: PK11_FreeSymKey(spec->master_secret); michael@0: spec->master_secret = NULL; michael@0: } michael@0: spec->msItem.data = NULL; michael@0: spec->msItem.len = 0; michael@0: ssl3_CleanupKeyMaterial(&spec->client); michael@0: ssl3_CleanupKeyMaterial(&spec->server); michael@0: spec->bypassCiphers = PR_FALSE; michael@0: spec->destroy=NULL; michael@0: spec->destroyCompressContext = NULL; michael@0: spec->destroyDecompressContext = NULL; michael@0: } michael@0: michael@0: /* Fill in the pending cipher spec with info from the selected ciphersuite. michael@0: ** This is as much initialization as we can do without having key material. michael@0: ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello() michael@0: ** Caller must hold the ssl3 handshake lock. michael@0: ** Acquires & releases SpecWriteLock. michael@0: */ michael@0: static SECStatus michael@0: ssl3_SetupPendingCipherSpec(sslSocket *ss) michael@0: { michael@0: ssl3CipherSpec * pwSpec; michael@0: ssl3CipherSpec * cwSpec; michael@0: ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; michael@0: SSL3MACAlgorithm mac; michael@0: SSL3BulkCipher cipher; michael@0: SSL3KeyExchangeAlgorithm kea; michael@0: const ssl3CipherSuiteDef *suite_def; michael@0: PRBool isTLS; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: ssl_GetSpecWriteLock(ss); /*******************************/ michael@0: michael@0: pwSpec = ss->ssl3.pwSpec; michael@0: PORT_Assert(pwSpec == ss->ssl3.prSpec); michael@0: michael@0: /* This hack provides maximal interoperability with SSL 3 servers. */ michael@0: cwSpec = ss->ssl3.cwSpec; michael@0: if (cwSpec->mac_def->mac == mac_null) { michael@0: /* SSL records are not being MACed. */ michael@0: cwSpec->version = ss->version; michael@0: } michael@0: michael@0: pwSpec->version = ss->version; michael@0: isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", michael@0: SSL_GETPID(), ss->fd, suite)); michael@0: michael@0: suite_def = ssl_LookupCipherSuiteDef(suite); michael@0: if (suite_def == NULL) { michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: /* Double-check that we did not pick an RC4 suite */ michael@0: PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && michael@0: (suite_def->bulk_cipher_alg != cipher_rc4_40) && michael@0: (suite_def->bulk_cipher_alg != cipher_rc4_56)); michael@0: } michael@0: michael@0: cipher = suite_def->bulk_cipher_alg; michael@0: kea = suite_def->key_exchange_alg; michael@0: mac = suite_def->mac_alg; michael@0: if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) michael@0: mac += 2; michael@0: michael@0: ss->ssl3.hs.suite_def = suite_def; michael@0: ss->ssl3.hs.kea_def = &kea_defs[kea]; michael@0: PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); michael@0: michael@0: pwSpec->cipher_def = &bulk_cipher_defs[cipher]; michael@0: PORT_Assert(pwSpec->cipher_def->cipher == cipher); michael@0: michael@0: pwSpec->mac_def = &mac_defs[mac]; michael@0: PORT_Assert(pwSpec->mac_def->mac == mac); michael@0: michael@0: ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; michael@0: ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB; michael@0: ss->sec.cipherType = cipher; michael@0: michael@0: pwSpec->encodeContext = NULL; michael@0: pwSpec->decodeContext = NULL; michael@0: michael@0: pwSpec->mac_size = pwSpec->mac_def->mac_size; michael@0: michael@0: pwSpec->compression_method = ss->ssl3.hs.compression; michael@0: pwSpec->compressContext = NULL; michael@0: pwSpec->decompressContext = NULL; michael@0: michael@0: ssl_ReleaseSpecWriteLock(ss); /*******************************/ michael@0: return SECSuccess; michael@0: } michael@0: michael@0: #ifdef NSS_ENABLE_ZLIB michael@0: #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream) michael@0: michael@0: static SECStatus michael@0: ssl3_MapZlibError(int zlib_error) michael@0: { michael@0: switch (zlib_error) { michael@0: case Z_OK: michael@0: return SECSuccess; michael@0: default: michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_DeflateInit(void *void_context) michael@0: { michael@0: z_stream *context = void_context; michael@0: context->zalloc = NULL; michael@0: context->zfree = NULL; michael@0: context->opaque = NULL; michael@0: michael@0: return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION)); michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_InflateInit(void *void_context) michael@0: { michael@0: z_stream *context = void_context; michael@0: context->zalloc = NULL; michael@0: context->zfree = NULL; michael@0: context->opaque = NULL; michael@0: context->next_in = NULL; michael@0: context->avail_in = 0; michael@0: michael@0: return ssl3_MapZlibError(inflateInit(context)); michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len, michael@0: int maxout, const unsigned char *in, int inlen) michael@0: { michael@0: z_stream *context = void_context; michael@0: michael@0: if (!inlen) { michael@0: *out_len = 0; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: context->next_in = (unsigned char*) in; michael@0: context->avail_in = inlen; michael@0: context->next_out = out; michael@0: context->avail_out = maxout; michael@0: if (deflate(context, Z_SYNC_FLUSH) != Z_OK) { michael@0: return SECFailure; michael@0: } michael@0: if (context->avail_out == 0) { michael@0: /* We ran out of space! */ michael@0: SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing", michael@0: SSL_GETPID())); michael@0: return SECFailure; michael@0: } michael@0: michael@0: *out_len = maxout - context->avail_out; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len, michael@0: int maxout, const unsigned char *in, int inlen) michael@0: { michael@0: z_stream *context = void_context; michael@0: michael@0: if (!inlen) { michael@0: *out_len = 0; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: context->next_in = (unsigned char*) in; michael@0: context->avail_in = inlen; michael@0: context->next_out = out; michael@0: context->avail_out = maxout; michael@0: if (inflate(context, Z_SYNC_FLUSH) != Z_OK) { michael@0: PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: *out_len = maxout - context->avail_out; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_DestroyCompressContext(void *void_context, PRBool unused) michael@0: { michael@0: deflateEnd(void_context); michael@0: PORT_Free(void_context); michael@0: return SECSuccess; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_DestroyDecompressContext(void *void_context, PRBool unused) michael@0: { michael@0: inflateEnd(void_context); michael@0: PORT_Free(void_context); michael@0: return SECSuccess; michael@0: } michael@0: michael@0: #endif /* NSS_ENABLE_ZLIB */ michael@0: michael@0: /* Initialize the compression functions and contexts for the given michael@0: * CipherSpec. */ michael@0: static SECStatus michael@0: ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) michael@0: { michael@0: /* Setup the compression functions */ michael@0: switch (pwSpec->compression_method) { michael@0: case ssl_compression_null: michael@0: pwSpec->compressor = NULL; michael@0: pwSpec->decompressor = NULL; michael@0: pwSpec->compressContext = NULL; michael@0: pwSpec->decompressContext = NULL; michael@0: pwSpec->destroyCompressContext = NULL; michael@0: pwSpec->destroyDecompressContext = NULL; michael@0: break; michael@0: #ifdef NSS_ENABLE_ZLIB michael@0: case ssl_compression_deflate: michael@0: pwSpec->compressor = ssl3_DeflateCompress; michael@0: pwSpec->decompressor = ssl3_DeflateDecompress; michael@0: pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); michael@0: pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); michael@0: pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; michael@0: pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; michael@0: ssl3_DeflateInit(pwSpec->compressContext); michael@0: ssl3_InflateInit(pwSpec->decompressContext); michael@0: break; michael@0: #endif /* NSS_ENABLE_ZLIB */ michael@0: default: michael@0: PORT_Assert(0); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: /* Initialize encryption contexts for pending spec. michael@0: * MAC contexts are set up when computing the mac, not here. michael@0: * Master Secret already is derived in spec->msItem michael@0: * Caller holds Spec write lock. michael@0: */ michael@0: static SECStatus michael@0: ssl3_InitPendingContextsBypass(sslSocket *ss) michael@0: { michael@0: ssl3CipherSpec * pwSpec; michael@0: const ssl3BulkCipherDef *cipher_def; michael@0: void * serverContext = NULL; michael@0: void * clientContext = NULL; michael@0: BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; michael@0: int mode = 0; michael@0: unsigned int optArg1 = 0; michael@0: unsigned int optArg2 = 0; michael@0: PRBool server_encrypts = ss->sec.isServer; michael@0: SSLCipherAlgorithm calg; michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); michael@0: PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); michael@0: michael@0: pwSpec = ss->ssl3.pwSpec; michael@0: cipher_def = pwSpec->cipher_def; michael@0: michael@0: calg = cipher_def->calg; michael@0: michael@0: if (calg == ssl_calg_aes_gcm) { michael@0: pwSpec->encode = NULL; michael@0: pwSpec->decode = NULL; michael@0: pwSpec->destroy = NULL; michael@0: pwSpec->encodeContext = NULL; michael@0: pwSpec->decodeContext = NULL; michael@0: pwSpec->aead = ssl3_AESGCMBypass; michael@0: ssl3_InitCompressionContext(pwSpec); michael@0: return SECSuccess; michael@0: } michael@0: michael@0: serverContext = pwSpec->server.cipher_context; michael@0: clientContext = pwSpec->client.cipher_context; michael@0: michael@0: switch (calg) { michael@0: case ssl_calg_null: michael@0: pwSpec->encode = Null_Cipher; michael@0: pwSpec->decode = Null_Cipher; michael@0: pwSpec->destroy = NULL; michael@0: goto success; michael@0: michael@0: case ssl_calg_rc4: michael@0: initFn = (BLapiInitContextFunc)RC4_InitContext; michael@0: pwSpec->encode = (SSLCipher) RC4_Encrypt; michael@0: pwSpec->decode = (SSLCipher) RC4_Decrypt; michael@0: pwSpec->destroy = (SSLDestroy) RC4_DestroyContext; michael@0: break; michael@0: case ssl_calg_rc2: michael@0: initFn = (BLapiInitContextFunc)RC2_InitContext; michael@0: mode = NSS_RC2_CBC; michael@0: optArg1 = cipher_def->key_size; michael@0: pwSpec->encode = (SSLCipher) RC2_Encrypt; michael@0: pwSpec->decode = (SSLCipher) RC2_Decrypt; michael@0: pwSpec->destroy = (SSLDestroy) RC2_DestroyContext; michael@0: break; michael@0: case ssl_calg_des: michael@0: initFn = (BLapiInitContextFunc)DES_InitContext; michael@0: mode = NSS_DES_CBC; michael@0: optArg1 = server_encrypts; michael@0: pwSpec->encode = (SSLCipher) DES_Encrypt; michael@0: pwSpec->decode = (SSLCipher) DES_Decrypt; michael@0: pwSpec->destroy = (SSLDestroy) DES_DestroyContext; michael@0: break; michael@0: case ssl_calg_3des: michael@0: initFn = (BLapiInitContextFunc)DES_InitContext; michael@0: mode = NSS_DES_EDE3_CBC; michael@0: optArg1 = server_encrypts; michael@0: pwSpec->encode = (SSLCipher) DES_Encrypt; michael@0: pwSpec->decode = (SSLCipher) DES_Decrypt; michael@0: pwSpec->destroy = (SSLDestroy) DES_DestroyContext; michael@0: break; michael@0: case ssl_calg_aes: michael@0: initFn = (BLapiInitContextFunc)AES_InitContext; michael@0: mode = NSS_AES_CBC; michael@0: optArg1 = server_encrypts; michael@0: optArg2 = AES_BLOCK_SIZE; michael@0: pwSpec->encode = (SSLCipher) AES_Encrypt; michael@0: pwSpec->decode = (SSLCipher) AES_Decrypt; michael@0: pwSpec->destroy = (SSLDestroy) AES_DestroyContext; michael@0: break; michael@0: michael@0: case ssl_calg_camellia: michael@0: initFn = (BLapiInitContextFunc)Camellia_InitContext; michael@0: mode = NSS_CAMELLIA_CBC; michael@0: optArg1 = server_encrypts; michael@0: optArg2 = CAMELLIA_BLOCK_SIZE; michael@0: pwSpec->encode = (SSLCipher) Camellia_Encrypt; michael@0: pwSpec->decode = (SSLCipher) Camellia_Decrypt; michael@0: pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext; michael@0: break; michael@0: michael@0: case ssl_calg_seed: michael@0: initFn = (BLapiInitContextFunc)SEED_InitContext; michael@0: mode = NSS_SEED_CBC; michael@0: optArg1 = server_encrypts; michael@0: optArg2 = SEED_BLOCK_SIZE; michael@0: pwSpec->encode = (SSLCipher) SEED_Encrypt; michael@0: pwSpec->decode = (SSLCipher) SEED_Decrypt; michael@0: pwSpec->destroy = (SSLDestroy) SEED_DestroyContext; michael@0: break; michael@0: michael@0: case ssl_calg_idea: michael@0: case ssl_calg_fortezza : michael@0: default: michael@0: PORT_Assert(0); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: goto bail_out; michael@0: } michael@0: rv = (*initFn)(serverContext, michael@0: pwSpec->server.write_key_item.data, michael@0: pwSpec->server.write_key_item.len, michael@0: pwSpec->server.write_iv_item.data, michael@0: mode, optArg1, optArg2); michael@0: if (rv != SECSuccess) { michael@0: PORT_Assert(0); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: goto bail_out; michael@0: } michael@0: michael@0: switch (calg) { michael@0: case ssl_calg_des: michael@0: case ssl_calg_3des: michael@0: case ssl_calg_aes: michael@0: case ssl_calg_camellia: michael@0: case ssl_calg_seed: michael@0: /* For block ciphers, if the server is encrypting, then the client michael@0: * is decrypting, and vice versa. michael@0: */ michael@0: optArg1 = !optArg1; michael@0: break; michael@0: /* kill warnings. */ michael@0: case ssl_calg_null: michael@0: case ssl_calg_rc4: michael@0: case ssl_calg_rc2: michael@0: case ssl_calg_idea: michael@0: case ssl_calg_fortezza: michael@0: case ssl_calg_aes_gcm: michael@0: break; michael@0: } michael@0: michael@0: rv = (*initFn)(clientContext, michael@0: pwSpec->client.write_key_item.data, michael@0: pwSpec->client.write_key_item.len, michael@0: pwSpec->client.write_iv_item.data, michael@0: mode, optArg1, optArg2); michael@0: if (rv != SECSuccess) { michael@0: PORT_Assert(0); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: goto bail_out; michael@0: } michael@0: michael@0: pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; michael@0: pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; michael@0: michael@0: ssl3_InitCompressionContext(pwSpec); michael@0: michael@0: success: michael@0: return SECSuccess; michael@0: michael@0: bail_out: michael@0: return SECFailure; michael@0: } michael@0: #endif michael@0: michael@0: /* This function should probably be moved to pk11wrap and be named michael@0: * PK11_ParamFromIVAndEffectiveKeyBits michael@0: */ michael@0: static SECItem * michael@0: ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) michael@0: { michael@0: SECItem * param = PK11_ParamFromIV(mtype, iv); michael@0: if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { michael@0: switch (mtype) { michael@0: case CKM_RC2_KEY_GEN: michael@0: case CKM_RC2_ECB: michael@0: case CKM_RC2_CBC: michael@0: case CKM_RC2_MAC: michael@0: case CKM_RC2_MAC_GENERAL: michael@0: case CKM_RC2_CBC_PAD: michael@0: *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; michael@0: default: break; michael@0: } michael@0: } michael@0: return param; michael@0: } michael@0: michael@0: /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data michael@0: * which is included in the MAC or AEAD additional data) to |out| and returns michael@0: * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the michael@0: * definition of the AEAD additional data. michael@0: * michael@0: * TLS pseudo-header includes the record's version field, SSL's doesn't. Which michael@0: * pseudo-header defintiion to use should be decided based on the version of michael@0: * the protocol that was negotiated when the cipher spec became current, NOT michael@0: * based on the version value in the record itself, and the decision is passed michael@0: * to this function as the |includesVersion| argument. But, the |version| michael@0: * argument should be the record's version value. michael@0: */ michael@0: static unsigned int michael@0: ssl3_BuildRecordPseudoHeader(unsigned char *out, michael@0: SSL3SequenceNumber seq_num, michael@0: SSL3ContentType type, michael@0: PRBool includesVersion, michael@0: SSL3ProtocolVersion version, michael@0: PRBool isDTLS, michael@0: int length) michael@0: { michael@0: out[0] = (unsigned char)(seq_num.high >> 24); michael@0: out[1] = (unsigned char)(seq_num.high >> 16); michael@0: out[2] = (unsigned char)(seq_num.high >> 8); michael@0: out[3] = (unsigned char)(seq_num.high >> 0); michael@0: out[4] = (unsigned char)(seq_num.low >> 24); michael@0: out[5] = (unsigned char)(seq_num.low >> 16); michael@0: out[6] = (unsigned char)(seq_num.low >> 8); michael@0: out[7] = (unsigned char)(seq_num.low >> 0); michael@0: out[8] = type; michael@0: michael@0: /* SSL3 MAC doesn't include the record's version field. */ michael@0: if (!includesVersion) { michael@0: out[9] = MSB(length); michael@0: out[10] = LSB(length); michael@0: return 11; michael@0: } michael@0: michael@0: /* TLS MAC and AEAD additional data include version. */ michael@0: if (isDTLS) { michael@0: SSL3ProtocolVersion dtls_version; michael@0: michael@0: dtls_version = dtls_TLSVersionToDTLSVersion(version); michael@0: out[9] = MSB(dtls_version); michael@0: out[10] = LSB(dtls_version); michael@0: } else { michael@0: out[9] = MSB(version); michael@0: out[10] = LSB(version); michael@0: } michael@0: out[11] = MSB(length); michael@0: out[12] = LSB(length); michael@0: return 13; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_AESGCM(ssl3KeyMaterial *keys, michael@0: PRBool doDecrypt, michael@0: unsigned char *out, michael@0: int *outlen, michael@0: int maxout, michael@0: const unsigned char *in, michael@0: int inlen, michael@0: const unsigned char *additionalData, michael@0: int additionalDataLen) michael@0: { michael@0: SECItem param; michael@0: SECStatus rv = SECFailure; michael@0: unsigned char nonce[12]; michael@0: unsigned int uOutLen; michael@0: CK_GCM_PARAMS gcmParams; michael@0: michael@0: static const int tagSize = 16; michael@0: static const int explicitNonceLen = 8; michael@0: michael@0: /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the michael@0: * nonce is formed. */ michael@0: memcpy(nonce, keys->write_iv, 4); michael@0: if (doDecrypt) { michael@0: memcpy(nonce + 4, in, explicitNonceLen); michael@0: in += explicitNonceLen; michael@0: inlen -= explicitNonceLen; michael@0: *outlen = 0; michael@0: } else { michael@0: if (maxout < explicitNonceLen) { michael@0: PORT_SetError(SEC_ERROR_INPUT_LEN); michael@0: return SECFailure; michael@0: } michael@0: /* Use the 64-bit sequence number as the explicit nonce. */ michael@0: memcpy(nonce + 4, additionalData, explicitNonceLen); michael@0: memcpy(out, additionalData, explicitNonceLen); michael@0: out += explicitNonceLen; michael@0: maxout -= explicitNonceLen; michael@0: *outlen = explicitNonceLen; michael@0: } michael@0: michael@0: param.type = siBuffer; michael@0: param.data = (unsigned char *) &gcmParams; michael@0: param.len = sizeof(gcmParams); michael@0: gcmParams.pIv = nonce; michael@0: gcmParams.ulIvLen = sizeof(nonce); michael@0: gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ michael@0: gcmParams.ulAADLen = additionalDataLen; michael@0: gcmParams.ulTagBits = tagSize * 8; michael@0: michael@0: if (doDecrypt) { michael@0: rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, michael@0: maxout, in, inlen); michael@0: } else { michael@0: rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, michael@0: maxout, in, inlen); michael@0: } michael@0: *outlen += (int) uOutLen; michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: static SECStatus michael@0: ssl3_AESGCMBypass(ssl3KeyMaterial *keys, michael@0: PRBool doDecrypt, michael@0: unsigned char *out, michael@0: int *outlen, michael@0: int maxout, michael@0: const unsigned char *in, michael@0: int inlen, michael@0: const unsigned char *additionalData, michael@0: int additionalDataLen) michael@0: { michael@0: SECStatus rv = SECFailure; michael@0: unsigned char nonce[12]; michael@0: unsigned int uOutLen; michael@0: AESContext *cx; michael@0: CK_GCM_PARAMS gcmParams; michael@0: michael@0: static const int tagSize = 16; michael@0: static const int explicitNonceLen = 8; michael@0: michael@0: /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the michael@0: * nonce is formed. */ michael@0: PORT_Assert(keys->write_iv_item.len == 4); michael@0: if (keys->write_iv_item.len != 4) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: memcpy(nonce, keys->write_iv_item.data, 4); michael@0: if (doDecrypt) { michael@0: memcpy(nonce + 4, in, explicitNonceLen); michael@0: in += explicitNonceLen; michael@0: inlen -= explicitNonceLen; michael@0: *outlen = 0; michael@0: } else { michael@0: if (maxout < explicitNonceLen) { michael@0: PORT_SetError(SEC_ERROR_INPUT_LEN); michael@0: return SECFailure; michael@0: } michael@0: /* Use the 64-bit sequence number as the explicit nonce. */ michael@0: memcpy(nonce + 4, additionalData, explicitNonceLen); michael@0: memcpy(out, additionalData, explicitNonceLen); michael@0: out += explicitNonceLen; michael@0: maxout -= explicitNonceLen; michael@0: *outlen = explicitNonceLen; michael@0: } michael@0: michael@0: gcmParams.pIv = nonce; michael@0: gcmParams.ulIvLen = sizeof(nonce); michael@0: gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ michael@0: gcmParams.ulAADLen = additionalDataLen; michael@0: gcmParams.ulTagBits = tagSize * 8; michael@0: michael@0: cx = (AESContext *)keys->cipher_context; michael@0: rv = AES_InitContext(cx, keys->write_key_item.data, michael@0: keys->write_key_item.len, michael@0: (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, michael@0: AES_BLOCK_SIZE); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: if (doDecrypt) { michael@0: rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); michael@0: } else { michael@0: rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); michael@0: } michael@0: AES_DestroyContext(cx, PR_FALSE); michael@0: *outlen += (int) uOutLen; michael@0: michael@0: return rv; michael@0: } michael@0: #endif michael@0: michael@0: /* Initialize encryption and MAC contexts for pending spec. michael@0: * Master Secret already is derived. michael@0: * Caller holds Spec write lock. michael@0: */ michael@0: static SECStatus michael@0: ssl3_InitPendingContextsPKCS11(sslSocket *ss) michael@0: { michael@0: ssl3CipherSpec * pwSpec; michael@0: const ssl3BulkCipherDef *cipher_def; michael@0: PK11Context * serverContext = NULL; michael@0: PK11Context * clientContext = NULL; michael@0: SECItem * param; michael@0: CK_MECHANISM_TYPE mechanism; michael@0: CK_MECHANISM_TYPE mac_mech; michael@0: CK_ULONG macLength; michael@0: CK_ULONG effKeyBits; michael@0: SECItem iv; michael@0: SECItem mac_param; michael@0: SSLCipherAlgorithm calg; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); michael@0: PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); michael@0: michael@0: pwSpec = ss->ssl3.pwSpec; michael@0: cipher_def = pwSpec->cipher_def; michael@0: macLength = pwSpec->mac_size; michael@0: calg = cipher_def->calg; michael@0: PORT_Assert(alg2Mech[calg].calg == calg); michael@0: michael@0: pwSpec->client.write_mac_context = NULL; michael@0: pwSpec->server.write_mac_context = NULL; michael@0: michael@0: if (calg == calg_aes_gcm) { michael@0: pwSpec->encode = NULL; michael@0: pwSpec->decode = NULL; michael@0: pwSpec->destroy = NULL; michael@0: pwSpec->encodeContext = NULL; michael@0: pwSpec->decodeContext = NULL; michael@0: pwSpec->aead = ssl3_AESGCM; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* michael@0: ** Now setup the MAC contexts, michael@0: ** crypto contexts are setup below. michael@0: */ michael@0: michael@0: mac_mech = pwSpec->mac_def->mmech; michael@0: mac_param.data = (unsigned char *)&macLength; michael@0: mac_param.len = sizeof(macLength); michael@0: mac_param.type = 0; michael@0: michael@0: pwSpec->client.write_mac_context = PK11_CreateContextBySymKey( michael@0: mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); michael@0: if (pwSpec->client.write_mac_context == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); michael@0: goto fail; michael@0: } michael@0: pwSpec->server.write_mac_context = PK11_CreateContextBySymKey( michael@0: mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); michael@0: if (pwSpec->server.write_mac_context == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); michael@0: goto fail; michael@0: } michael@0: michael@0: /* michael@0: ** Now setup the crypto contexts. michael@0: */ michael@0: michael@0: if (calg == calg_null) { michael@0: pwSpec->encode = Null_Cipher; michael@0: pwSpec->decode = Null_Cipher; michael@0: pwSpec->destroy = NULL; michael@0: return SECSuccess; michael@0: } michael@0: mechanism = alg2Mech[calg].cmech; michael@0: effKeyBits = cipher_def->key_size * BPB; michael@0: michael@0: /* michael@0: * build the server context michael@0: */ michael@0: iv.data = pwSpec->server.write_iv; michael@0: iv.len = cipher_def->iv_size; michael@0: param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); michael@0: if (param == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); michael@0: goto fail; michael@0: } michael@0: serverContext = PK11_CreateContextBySymKey(mechanism, michael@0: (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT), michael@0: pwSpec->server.write_key, param); michael@0: iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); michael@0: if (iv.data) michael@0: PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); michael@0: SECITEM_FreeItem(param, PR_TRUE); michael@0: if (serverContext == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); michael@0: goto fail; michael@0: } michael@0: michael@0: /* michael@0: * build the client context michael@0: */ michael@0: iv.data = pwSpec->client.write_iv; michael@0: iv.len = cipher_def->iv_size; michael@0: michael@0: param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); michael@0: if (param == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); michael@0: goto fail; michael@0: } michael@0: clientContext = PK11_CreateContextBySymKey(mechanism, michael@0: (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT), michael@0: pwSpec->client.write_key, param); michael@0: iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); michael@0: if (iv.data) michael@0: PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); michael@0: SECITEM_FreeItem(param,PR_TRUE); michael@0: if (clientContext == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); michael@0: goto fail; michael@0: } michael@0: pwSpec->encode = (SSLCipher) PK11_CipherOp; michael@0: pwSpec->decode = (SSLCipher) PK11_CipherOp; michael@0: pwSpec->destroy = (SSLDestroy) PK11_DestroyContext; michael@0: michael@0: pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; michael@0: pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; michael@0: michael@0: serverContext = NULL; michael@0: clientContext = NULL; michael@0: michael@0: ssl3_InitCompressionContext(pwSpec); michael@0: michael@0: return SECSuccess; michael@0: michael@0: fail: michael@0: if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE); michael@0: if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE); michael@0: if (pwSpec->client.write_mac_context != NULL) { michael@0: PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE); michael@0: pwSpec->client.write_mac_context = NULL; michael@0: } michael@0: if (pwSpec->server.write_mac_context != NULL) { michael@0: PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE); michael@0: pwSpec->server.write_mac_context = NULL; michael@0: } michael@0: michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* Complete the initialization of all keys, ciphers, MACs and their contexts michael@0: * for the pending Cipher Spec. michael@0: * Called from: ssl3_SendClientKeyExchange (for Full handshake) michael@0: * ssl3_HandleRSAClientKeyExchange (for Full handshake) michael@0: * ssl3_HandleServerHello (for session restart) michael@0: * ssl3_HandleClientHello (for session restart) michael@0: * Sets error code, but caller probably should override to disambiguate. michael@0: * NULL pms means re-use old master_secret. michael@0: * michael@0: * This code is common to the bypass and PKCS11 execution paths. michael@0: * For the bypass case, pms is NULL. michael@0: */ michael@0: SECStatus michael@0: ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms) michael@0: { michael@0: ssl3CipherSpec * pwSpec; michael@0: ssl3CipherSpec * cwSpec; michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: ssl_GetSpecWriteLock(ss); /**************************************/ michael@0: michael@0: PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); michael@0: michael@0: pwSpec = ss->ssl3.pwSpec; michael@0: cwSpec = ss->ssl3.cwSpec; michael@0: michael@0: if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) { michael@0: rv = ssl3_DeriveMasterSecret(ss, pms); michael@0: if (rv != SECSuccess) { michael@0: goto done; /* err code set by ssl3_DeriveMasterSecret */ michael@0: } michael@0: } michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) { michael@0: /* Double Bypass succeeded in extracting the master_secret */ michael@0: const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; michael@0: PRBool isTLS = (PRBool)(kea_def->tls_keygen || michael@0: (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); michael@0: pwSpec->bypassCiphers = PR_TRUE; michael@0: rv = ssl3_KeyAndMacDeriveBypass( pwSpec, michael@0: (const unsigned char *)&ss->ssl3.hs.client_random, michael@0: (const unsigned char *)&ss->ssl3.hs.server_random, michael@0: isTLS, michael@0: (PRBool)(kea_def->is_limited)); michael@0: if (rv == SECSuccess) { michael@0: rv = ssl3_InitPendingContextsBypass(ss); michael@0: } michael@0: } else michael@0: #endif michael@0: if (pwSpec->master_secret) { michael@0: rv = ssl3_DeriveConnectionKeysPKCS11(ss); michael@0: if (rv == SECSuccess) { michael@0: rv = ssl3_InitPendingContextsPKCS11(ss); michael@0: } michael@0: } else { michael@0: PORT_Assert(pwSpec->master_secret); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: rv = SECFailure; michael@0: } michael@0: if (rv != SECSuccess) { michael@0: goto done; michael@0: } michael@0: michael@0: /* Generic behaviors -- common to all crypto methods */ michael@0: if (!IS_DTLS(ss)) { michael@0: pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; michael@0: } else { michael@0: if (cwSpec->epoch == PR_UINT16_MAX) { michael@0: /* The problem here is that we have rehandshaked too many michael@0: * times (you are not allowed to wrap the epoch). The michael@0: * spec says you should be discarding the connection michael@0: * and start over, so not much we can do here. */ michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: rv = SECFailure; michael@0: goto done; michael@0: } michael@0: /* The sequence number has the high 16 bits as the epoch. */ michael@0: pwSpec->epoch = cwSpec->epoch + 1; michael@0: pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = michael@0: pwSpec->epoch << 16; michael@0: michael@0: dtls_InitRecvdRecords(&pwSpec->recvdRecords); michael@0: } michael@0: pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0; michael@0: michael@0: done: michael@0: ssl_ReleaseSpecWriteLock(ss); /******************************/ michael@0: if (rv != SECSuccess) michael@0: ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * 60 bytes is 3 times the maximum length MAC size that is supported. michael@0: */ michael@0: static const unsigned char mac_pad_1 [60] = { michael@0: 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, michael@0: 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, michael@0: 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, michael@0: 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, michael@0: 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, michael@0: 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, michael@0: 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, michael@0: 0x36, 0x36, 0x36, 0x36 michael@0: }; michael@0: static const unsigned char mac_pad_2 [60] = { michael@0: 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, michael@0: 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, michael@0: 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, michael@0: 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, michael@0: 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, michael@0: 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, michael@0: 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, michael@0: 0x5c, 0x5c, 0x5c, 0x5c michael@0: }; michael@0: michael@0: /* Called from: ssl3_SendRecord() michael@0: ** Caller must already hold the SpecReadLock. (wish we could assert that!) michael@0: */ michael@0: static SECStatus michael@0: ssl3_ComputeRecordMAC( michael@0: ssl3CipherSpec * spec, michael@0: PRBool useServerMacKey, michael@0: const unsigned char *header, michael@0: unsigned int headerLen, michael@0: const SSL3Opaque * input, michael@0: int inputLength, michael@0: unsigned char * outbuf, michael@0: unsigned int * outLength) michael@0: { michael@0: const ssl3MACDef * mac_def; michael@0: SECStatus rv; michael@0: michael@0: PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); michael@0: PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); michael@0: michael@0: mac_def = spec->mac_def; michael@0: if (mac_def->mac == mac_null) { michael@0: *outLength = 0; michael@0: return SECSuccess; michael@0: } michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (spec->bypassCiphers) { michael@0: /* bypass version */ michael@0: const SECHashObject *hashObj = NULL; michael@0: unsigned int pad_bytes = 0; michael@0: PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; michael@0: michael@0: switch (mac_def->mac) { michael@0: case ssl_mac_null: michael@0: *outLength = 0; michael@0: return SECSuccess; michael@0: case ssl_mac_md5: michael@0: pad_bytes = 48; michael@0: hashObj = HASH_GetRawHashObject(HASH_AlgMD5); michael@0: break; michael@0: case ssl_mac_sha: michael@0: pad_bytes = 40; michael@0: hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); michael@0: break; michael@0: case ssl_hmac_md5: /* used with TLS */ michael@0: hashObj = HASH_GetRawHashObject(HASH_AlgMD5); michael@0: break; michael@0: case ssl_hmac_sha: /* used with TLS */ michael@0: hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); michael@0: break; michael@0: case ssl_hmac_sha256: /* used with TLS */ michael@0: hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: if (!hashObj) { michael@0: PORT_Assert(0); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (spec->version <= SSL_LIBRARY_VERSION_3_0) { michael@0: unsigned int tempLen; michael@0: unsigned char temp[MAX_MAC_LENGTH]; michael@0: michael@0: /* compute "inner" part of SSL3 MAC */ michael@0: hashObj->begin(write_mac_context); michael@0: if (useServerMacKey) michael@0: hashObj->update(write_mac_context, michael@0: spec->server.write_mac_key_item.data, michael@0: spec->server.write_mac_key_item.len); michael@0: else michael@0: hashObj->update(write_mac_context, michael@0: spec->client.write_mac_key_item.data, michael@0: spec->client.write_mac_key_item.len); michael@0: hashObj->update(write_mac_context, mac_pad_1, pad_bytes); michael@0: hashObj->update(write_mac_context, header, headerLen); michael@0: hashObj->update(write_mac_context, input, inputLength); michael@0: hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); michael@0: michael@0: /* compute "outer" part of SSL3 MAC */ michael@0: hashObj->begin(write_mac_context); michael@0: if (useServerMacKey) michael@0: hashObj->update(write_mac_context, michael@0: spec->server.write_mac_key_item.data, michael@0: spec->server.write_mac_key_item.len); michael@0: else michael@0: hashObj->update(write_mac_context, michael@0: spec->client.write_mac_key_item.data, michael@0: spec->client.write_mac_key_item.len); michael@0: hashObj->update(write_mac_context, mac_pad_2, pad_bytes); michael@0: hashObj->update(write_mac_context, temp, tempLen); michael@0: hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); michael@0: rv = SECSuccess; michael@0: } else { /* is TLS */ michael@0: #define cx ((HMACContext *)write_mac_context) michael@0: if (useServerMacKey) { michael@0: rv = HMAC_Init(cx, hashObj, michael@0: spec->server.write_mac_key_item.data, michael@0: spec->server.write_mac_key_item.len, PR_FALSE); michael@0: } else { michael@0: rv = HMAC_Init(cx, hashObj, michael@0: spec->client.write_mac_key_item.data, michael@0: spec->client.write_mac_key_item.len, PR_FALSE); michael@0: } michael@0: if (rv == SECSuccess) { michael@0: HMAC_Begin(cx); michael@0: HMAC_Update(cx, header, headerLen); michael@0: HMAC_Update(cx, input, inputLength); michael@0: rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); michael@0: HMAC_Destroy(cx, PR_FALSE); michael@0: } michael@0: #undef cx michael@0: } michael@0: } else michael@0: #endif michael@0: { michael@0: PK11Context *mac_context = michael@0: (useServerMacKey ? spec->server.write_mac_context michael@0: : spec->client.write_mac_context); michael@0: rv = PK11_DigestBegin(mac_context); michael@0: rv |= PK11_DigestOp(mac_context, header, headerLen); michael@0: rv |= PK11_DigestOp(mac_context, input, inputLength); michael@0: rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); michael@0: } michael@0: michael@0: PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size); michael@0: michael@0: PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength)); michael@0: michael@0: if (rv != SECSuccess) { michael@0: rv = SECFailure; michael@0: ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* Called from: ssl3_HandleRecord() michael@0: * Caller must already hold the SpecReadLock. (wish we could assert that!) michael@0: * michael@0: * On entry: michael@0: * originalLen >= inputLen >= MAC size michael@0: */ michael@0: static SECStatus michael@0: ssl3_ComputeRecordMACConstantTime( michael@0: ssl3CipherSpec * spec, michael@0: PRBool useServerMacKey, michael@0: const unsigned char *header, michael@0: unsigned int headerLen, michael@0: const SSL3Opaque * input, michael@0: int inputLen, michael@0: int originalLen, michael@0: unsigned char * outbuf, michael@0: unsigned int * outLen) michael@0: { michael@0: CK_MECHANISM_TYPE macType; michael@0: CK_NSS_MAC_CONSTANT_TIME_PARAMS params; michael@0: SECItem param, inputItem, outputItem; michael@0: SECStatus rv; michael@0: PK11SymKey * key; michael@0: michael@0: PORT_Assert(inputLen >= spec->mac_size); michael@0: PORT_Assert(originalLen >= inputLen); michael@0: michael@0: if (spec->bypassCiphers) { michael@0: /* This function doesn't support PKCS#11 bypass. We fallback on the michael@0: * non-constant time version. */ michael@0: goto fallback; michael@0: } michael@0: michael@0: if (spec->mac_def->mac == mac_null) { michael@0: *outLen = 0; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: macType = CKM_NSS_HMAC_CONSTANT_TIME; michael@0: if (spec->version <= SSL_LIBRARY_VERSION_3_0) { michael@0: macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; michael@0: } michael@0: michael@0: params.macAlg = spec->mac_def->mmech; michael@0: params.ulBodyTotalLen = originalLen; michael@0: params.pHeader = (unsigned char *) header; /* const cast */ michael@0: params.ulHeaderLen = headerLen; michael@0: michael@0: param.data = (unsigned char*) ¶ms; michael@0: param.len = sizeof(params); michael@0: param.type = 0; michael@0: michael@0: inputItem.data = (unsigned char *) input; michael@0: inputItem.len = inputLen; michael@0: inputItem.type = 0; michael@0: michael@0: outputItem.data = outbuf; michael@0: outputItem.len = *outLen; michael@0: outputItem.type = 0; michael@0: michael@0: key = spec->server.write_mac_key; michael@0: if (!useServerMacKey) { michael@0: key = spec->client.write_mac_key; michael@0: } michael@0: michael@0: rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem); michael@0: if (rv != SECSuccess) { michael@0: if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { michael@0: goto fallback; michael@0: } michael@0: michael@0: *outLen = 0; michael@0: rv = SECFailure; michael@0: ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); michael@0: return rv; michael@0: } michael@0: michael@0: PORT_Assert(outputItem.len == (unsigned)spec->mac_size); michael@0: *outLen = outputItem.len; michael@0: michael@0: return rv; michael@0: michael@0: fallback: michael@0: /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the michael@0: * length already. */ michael@0: inputLen -= spec->mac_size; michael@0: return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen, michael@0: input, inputLen, outbuf, outLen); michael@0: } michael@0: michael@0: static PRBool michael@0: ssl3_ClientAuthTokenPresent(sslSessionID *sid) { michael@0: PK11SlotInfo *slot = NULL; michael@0: PRBool isPresent = PR_TRUE; michael@0: michael@0: /* we only care if we are doing client auth */ michael@0: if (!sid || !sid->u.ssl3.clAuthValid) { michael@0: return PR_TRUE; michael@0: } michael@0: michael@0: /* get the slot */ michael@0: slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, michael@0: sid->u.ssl3.clAuthSlotID); michael@0: if (slot == NULL || michael@0: !PK11_IsPresent(slot) || michael@0: sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || michael@0: sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || michael@0: sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || michael@0: (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { michael@0: isPresent = PR_FALSE; michael@0: } michael@0: if (slot) { michael@0: PK11_FreeSlot(slot); michael@0: } michael@0: return isPresent; michael@0: } michael@0: michael@0: /* Caller must hold the spec read lock. */ michael@0: SECStatus michael@0: ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, michael@0: PRBool isServer, michael@0: PRBool isDTLS, michael@0: PRBool capRecordVersion, michael@0: SSL3ContentType type, michael@0: const SSL3Opaque * pIn, michael@0: PRUint32 contentLen, michael@0: sslBuffer * wrBuf) michael@0: { michael@0: const ssl3BulkCipherDef * cipher_def; michael@0: SECStatus rv; michael@0: PRUint32 macLen = 0; michael@0: PRUint32 fragLen; michael@0: PRUint32 p1Len, p2Len, oddLen = 0; michael@0: PRUint16 headerLen; michael@0: int ivLen = 0; michael@0: int cipherBytes = 0; michael@0: unsigned char pseudoHeader[13]; michael@0: unsigned int pseudoHeaderLen; michael@0: michael@0: cipher_def = cwSpec->cipher_def; michael@0: headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; michael@0: michael@0: if (cipher_def->type == type_block && michael@0: cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { michael@0: /* Prepend the per-record explicit IV using technique 2b from michael@0: * RFC 4346 section 6.2.3.2: The IV is a cryptographically michael@0: * strong random number XORed with the CBC residue from the previous michael@0: * record. michael@0: */ michael@0: ivLen = cipher_def->iv_size; michael@0: if (ivLen > wrBuf->space - headerLen) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); michael@0: return rv; michael@0: } michael@0: rv = cwSpec->encode( cwSpec->encodeContext, michael@0: wrBuf->buf + headerLen, michael@0: &cipherBytes, /* output and actual outLen */ michael@0: ivLen, /* max outlen */ michael@0: wrBuf->buf + headerLen, michael@0: ivLen); /* input and inputLen*/ michael@0: if (rv != SECSuccess || cipherBytes != ivLen) { michael@0: PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: if (cwSpec->compressor) { michael@0: int outlen; michael@0: rv = cwSpec->compressor( michael@0: cwSpec->compressContext, michael@0: wrBuf->buf + headerLen + ivLen, &outlen, michael@0: wrBuf->space - headerLen - ivLen, pIn, contentLen); michael@0: if (rv != SECSuccess) michael@0: return rv; michael@0: pIn = wrBuf->buf + headerLen + ivLen; michael@0: contentLen = outlen; michael@0: } michael@0: michael@0: pseudoHeaderLen = ssl3_BuildRecordPseudoHeader( michael@0: pseudoHeader, cwSpec->write_seq_num, type, michael@0: cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, michael@0: isDTLS, contentLen); michael@0: PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader)); michael@0: if (cipher_def->type == type_aead) { michael@0: const int nonceLen = cipher_def->explicit_nonce_size; michael@0: const int tagLen = cipher_def->tag_size; michael@0: michael@0: if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: cipherBytes = contentLen; michael@0: rv = cwSpec->aead( michael@0: isServer ? &cwSpec->server : &cwSpec->client, michael@0: PR_FALSE, /* do encrypt */ michael@0: wrBuf->buf + headerLen, /* output */ michael@0: &cipherBytes, /* out len */ michael@0: wrBuf->space - headerLen, /* max out */ michael@0: pIn, contentLen, /* input */ michael@0: pseudoHeader, pseudoHeaderLen); michael@0: if (rv != SECSuccess) { michael@0: PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: } else { michael@0: /* michael@0: * Add the MAC michael@0: */ michael@0: rv = ssl3_ComputeRecordMAC(cwSpec, isServer, michael@0: pseudoHeader, pseudoHeaderLen, pIn, contentLen, michael@0: wrBuf->buf + headerLen + ivLen + contentLen, &macLen); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: p1Len = contentLen; michael@0: p2Len = macLen; michael@0: fragLen = contentLen + macLen; /* needs to be encrypted */ michael@0: PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); michael@0: michael@0: /* michael@0: * Pad the text (if we're doing a block cipher) michael@0: * then Encrypt it michael@0: */ michael@0: if (cipher_def->type == type_block) { michael@0: unsigned char * pBuf; michael@0: int padding_length; michael@0: int i; michael@0: michael@0: oddLen = contentLen % cipher_def->block_size; michael@0: /* Assume blockSize is a power of two */ michael@0: padding_length = cipher_def->block_size - 1 - michael@0: ((fragLen) & (cipher_def->block_size - 1)); michael@0: fragLen += padding_length + 1; michael@0: PORT_Assert((fragLen % cipher_def->block_size) == 0); michael@0: michael@0: /* Pad according to TLS rules (also acceptable to SSL3). */ michael@0: pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; michael@0: for (i = padding_length + 1; i > 0; --i) { michael@0: *pBuf-- = padding_length; michael@0: } michael@0: /* now, if contentLen is not a multiple of block size, fix it */ michael@0: p2Len = fragLen - p1Len; michael@0: } michael@0: if (p1Len < 256) { michael@0: oddLen = p1Len; michael@0: p1Len = 0; michael@0: } else { michael@0: p1Len -= oddLen; michael@0: } michael@0: if (oddLen) { michael@0: p2Len += oddLen; michael@0: PORT_Assert( (cipher_def->block_size < 2) || \ michael@0: (p2Len % cipher_def->block_size) == 0); michael@0: memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, michael@0: oddLen); michael@0: } michael@0: if (p1Len > 0) { michael@0: int cipherBytesPart1 = -1; michael@0: rv = cwSpec->encode( cwSpec->encodeContext, michael@0: wrBuf->buf + headerLen + ivLen, /* output */ michael@0: &cipherBytesPart1, /* actual outlen */ michael@0: p1Len, /* max outlen */ michael@0: pIn, p1Len); /* input, and inputlen */ michael@0: PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); michael@0: if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { michael@0: PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: cipherBytes += cipherBytesPart1; michael@0: } michael@0: if (p2Len > 0) { michael@0: int cipherBytesPart2 = -1; michael@0: rv = cwSpec->encode( cwSpec->encodeContext, michael@0: wrBuf->buf + headerLen + ivLen + p1Len, michael@0: &cipherBytesPart2, /* output and actual outLen */ michael@0: p2Len, /* max outlen */ michael@0: wrBuf->buf + headerLen + ivLen + p1Len, michael@0: p2Len); /* input and inputLen*/ michael@0: PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); michael@0: if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { michael@0: PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: cipherBytes += cipherBytesPart2; michael@0: } michael@0: } michael@0: michael@0: PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); michael@0: michael@0: wrBuf->len = cipherBytes + headerLen; michael@0: wrBuf->buf[0] = type; michael@0: if (isDTLS) { michael@0: SSL3ProtocolVersion version; michael@0: michael@0: version = dtls_TLSVersionToDTLSVersion(cwSpec->version); michael@0: wrBuf->buf[1] = MSB(version); michael@0: wrBuf->buf[2] = LSB(version); michael@0: wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); michael@0: wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); michael@0: wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); michael@0: wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); michael@0: wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); michael@0: wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); michael@0: wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); michael@0: wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); michael@0: wrBuf->buf[11] = MSB(cipherBytes); michael@0: wrBuf->buf[12] = LSB(cipherBytes); michael@0: } else { michael@0: SSL3ProtocolVersion version = cwSpec->version; michael@0: michael@0: if (capRecordVersion) { michael@0: version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); michael@0: } michael@0: wrBuf->buf[1] = MSB(version); michael@0: wrBuf->buf[2] = LSB(version); michael@0: wrBuf->buf[3] = MSB(cipherBytes); michael@0: wrBuf->buf[4] = LSB(cipherBytes); michael@0: } michael@0: michael@0: ssl3_BumpSequenceNumber(&cwSpec->write_seq_num); michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* Process the plain text before sending it. michael@0: * Returns the number of bytes of plaintext that were successfully sent michael@0: * plus the number of bytes of plaintext that were copied into the michael@0: * output (write) buffer. michael@0: * Returns SECFailure on a hard IO error, memory error, or crypto error. michael@0: * Does NOT return SECWouldBlock. michael@0: * michael@0: * Notes on the use of the private ssl flags: michael@0: * (no private SSL flags) michael@0: * Attempt to make and send SSL records for all plaintext michael@0: * If non-blocking and a send gets WOULD_BLOCK, michael@0: * or if the pending (ciphertext) buffer is not empty, michael@0: * then buffer remaining bytes of ciphertext into pending buf, michael@0: * and continue to do that for all succssive records until all michael@0: * bytes are used. michael@0: * ssl_SEND_FLAG_FORCE_INTO_BUFFER michael@0: * As above, except this suppresses all write attempts, and forces michael@0: * all ciphertext into the pending ciphertext buffer. michael@0: * ssl_SEND_FLAG_USE_EPOCH (for DTLS) michael@0: * Forces the use of the provided epoch michael@0: * ssl_SEND_FLAG_CAP_RECORD_VERSION michael@0: * Caps the record layer version number of TLS ClientHello to { 3, 1 } michael@0: * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore michael@0: * ClientHello.client_version and use the record layer version number michael@0: * (TLSPlaintext.version) instead when negotiating protocol versions. In michael@0: * addition, if the record layer version number of ClientHello is { 3, 2 } michael@0: * (TLS 1.1) or higher, these servers reset the TCP connections. Lastly, michael@0: * some F5 BIG-IP servers hang if a record containing a ClientHello has a michael@0: * version greater than { 3, 1 } and a length greater than 255. Set this michael@0: * flag to work around such servers. michael@0: */ michael@0: PRInt32 michael@0: ssl3_SendRecord( sslSocket * ss, michael@0: DTLSEpoch epoch, /* DTLS only */ michael@0: SSL3ContentType type, michael@0: const SSL3Opaque * pIn, /* input buffer */ michael@0: PRInt32 nIn, /* bytes of input */ michael@0: PRInt32 flags) michael@0: { michael@0: sslBuffer * wrBuf = &ss->sec.writeBuf; michael@0: SECStatus rv; michael@0: PRInt32 totalSent = 0; michael@0: PRBool capRecordVersion; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", michael@0: SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), michael@0: nIn)); michael@0: PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); michael@0: michael@0: capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0); michael@0: michael@0: if (capRecordVersion) { michael@0: /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the michael@0: * TLS initial ClientHello. */ michael@0: PORT_Assert(!IS_DTLS(ss)); michael@0: PORT_Assert(!ss->firstHsDone); michael@0: PORT_Assert(type == content_handshake); michael@0: PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); michael@0: } michael@0: michael@0: if (ss->ssl3.initialized == PR_FALSE) { michael@0: /* This can happen on a server if the very first incoming record michael@0: ** looks like a defective ssl3 record (e.g. too long), and we're michael@0: ** trying to send an alert. michael@0: */ michael@0: PR_ASSERT(type == content_alert); michael@0: rv = ssl3_InitState(ss); michael@0: if (rv != SECSuccess) { michael@0: return SECFailure; /* ssl3_InitState has set the error code. */ michael@0: } michael@0: } michael@0: michael@0: /* check for Token Presence */ michael@0: if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { michael@0: PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); michael@0: return SECFailure; michael@0: } michael@0: michael@0: while (nIn > 0) { michael@0: PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); michael@0: unsigned int spaceNeeded; michael@0: unsigned int numRecords; michael@0: michael@0: ssl_GetSpecReadLock(ss); /********************************/ michael@0: michael@0: if (nIn > 1 && ss->opt.cbcRandomIV && michael@0: ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && michael@0: type == content_application_data && michael@0: ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { michael@0: /* We will split the first byte of the record into its own record, michael@0: * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h michael@0: */ michael@0: numRecords = 2; michael@0: } else { michael@0: numRecords = 1; michael@0: } michael@0: michael@0: spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); michael@0: if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && michael@0: ss->ssl3.cwSpec->cipher_def->type == type_block) { michael@0: spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; michael@0: } michael@0: if (spaceNeeded > wrBuf->space) { michael@0: rv = sslBuffer_Grow(wrBuf, spaceNeeded); michael@0: if (rv != SECSuccess) { michael@0: SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", michael@0: SSL_GETPID(), ss->fd, spaceNeeded)); michael@0: goto spec_locked_loser; /* sslBuffer_Grow set error code. */ michael@0: } michael@0: } michael@0: michael@0: if (numRecords == 2) { michael@0: sslBuffer secondRecord; michael@0: michael@0: rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, michael@0: ss->sec.isServer, IS_DTLS(ss), michael@0: capRecordVersion, type, pIn, michael@0: 1, wrBuf); michael@0: if (rv != SECSuccess) michael@0: goto spec_locked_loser; michael@0: michael@0: PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", michael@0: wrBuf->buf, wrBuf->len)); michael@0: michael@0: secondRecord.buf = wrBuf->buf + wrBuf->len; michael@0: secondRecord.len = 0; michael@0: secondRecord.space = wrBuf->space - wrBuf->len; michael@0: michael@0: rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, michael@0: ss->sec.isServer, IS_DTLS(ss), michael@0: capRecordVersion, type, michael@0: pIn + 1, contentLen - 1, michael@0: &secondRecord); michael@0: if (rv == SECSuccess) { michael@0: PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", michael@0: secondRecord.buf, secondRecord.len)); michael@0: wrBuf->len += secondRecord.len; michael@0: } michael@0: } else { michael@0: if (!IS_DTLS(ss)) { michael@0: rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, michael@0: ss->sec.isServer, michael@0: IS_DTLS(ss), michael@0: capRecordVersion, michael@0: type, pIn, michael@0: contentLen, wrBuf); michael@0: } else { michael@0: rv = dtls_CompressMACEncryptRecord(ss, epoch, michael@0: !!(flags & ssl_SEND_FLAG_USE_EPOCH), michael@0: type, pIn, michael@0: contentLen, wrBuf); michael@0: } michael@0: michael@0: if (rv == SECSuccess) { michael@0: PRINT_BUF(50, (ss, "send (encrypted) record data:", michael@0: wrBuf->buf, wrBuf->len)); michael@0: } michael@0: } michael@0: michael@0: spec_locked_loser: michael@0: ssl_ReleaseSpecReadLock(ss); /************************************/ michael@0: michael@0: if (rv != SECSuccess) michael@0: return SECFailure; michael@0: michael@0: pIn += contentLen; michael@0: nIn -= contentLen; michael@0: PORT_Assert( nIn >= 0 ); michael@0: michael@0: /* If there's still some previously saved ciphertext, michael@0: * or the caller doesn't want us to send the data yet, michael@0: * then add all our new ciphertext to the amount previously saved. michael@0: */ michael@0: if ((ss->pendingBuf.len > 0) || michael@0: (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { michael@0: michael@0: rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len); michael@0: if (rv != SECSuccess) { michael@0: /* presumably a memory error, SEC_ERROR_NO_MEMORY */ michael@0: return SECFailure; michael@0: } michael@0: wrBuf->len = 0; /* All cipher text is saved away. */ michael@0: michael@0: if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { michael@0: PRInt32 sent; michael@0: ss->handshakeBegun = 1; michael@0: sent = ssl_SendSavedWriteData(ss); michael@0: if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: if (ss->pendingBuf.len) { michael@0: flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; michael@0: } michael@0: } michael@0: } else if (wrBuf->len > 0) { michael@0: PRInt32 sent; michael@0: ss->handshakeBegun = 1; michael@0: sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, michael@0: flags & ~ssl_SEND_FLAG_MASK); michael@0: if (sent < 0) { michael@0: if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ michael@0: sent = 0; michael@0: } michael@0: wrBuf->len -= sent; michael@0: if (wrBuf->len) { michael@0: if (IS_DTLS(ss)) { michael@0: /* DTLS just says no in this case. No buffering */ michael@0: PR_SetError(PR_WOULD_BLOCK_ERROR, 0); michael@0: return SECFailure; michael@0: } michael@0: /* now take all the remaining unsent new ciphertext and michael@0: * append it to the buffer of previously unsent ciphertext. michael@0: */ michael@0: rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); michael@0: if (rv != SECSuccess) { michael@0: /* presumably a memory error, SEC_ERROR_NO_MEMORY */ michael@0: return SECFailure; michael@0: } michael@0: } michael@0: } michael@0: totalSent += contentLen; michael@0: } michael@0: return totalSent; michael@0: } michael@0: michael@0: #define SSL3_PENDING_HIGH_WATER 1024 michael@0: michael@0: /* Attempt to send the content of "in" in an SSL application_data record. michael@0: * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess. michael@0: */ michael@0: int michael@0: ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, michael@0: PRInt32 len, PRInt32 flags) michael@0: { michael@0: PRInt32 totalSent = 0; michael@0: PRInt32 discarded = 0; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); michael@0: /* These flags for internal use only */ michael@0: PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH | michael@0: ssl_SEND_FLAG_NO_RETRANSMIT))); michael@0: if (len < 0 || !in) { michael@0: PORT_SetError(PR_INVALID_ARGUMENT_ERROR); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && michael@0: !ssl_SocketIsBlocking(ss)) { michael@0: PORT_Assert(!ssl_SocketIsBlocking(ss)); michael@0: PORT_SetError(PR_WOULD_BLOCK_ERROR); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (ss->appDataBuffered && len) { michael@0: PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered)); michael@0: if (in[0] != (unsigned char)(ss->appDataBuffered)) { michael@0: PORT_SetError(PR_INVALID_ARGUMENT_ERROR); michael@0: return SECFailure; michael@0: } michael@0: in++; michael@0: len--; michael@0: discarded = 1; michael@0: } michael@0: while (len > totalSent) { michael@0: PRInt32 sent, toSend; michael@0: michael@0: if (totalSent > 0) { michael@0: /* michael@0: * The thread yield is intended to give the reader thread a michael@0: * chance to get some cycles while the writer thread is in michael@0: * the middle of a large application data write. (See michael@0: * Bugzilla bug 127740, comment #1.) michael@0: */ michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */ michael@0: ssl_GetXmitBufLock(ss); michael@0: } michael@0: toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); michael@0: /* michael@0: * Note that the 0 epoch is OK because flags will never require michael@0: * its use, as guaranteed by the PORT_Assert above. michael@0: */ michael@0: sent = ssl3_SendRecord(ss, 0, content_application_data, michael@0: in + totalSent, toSend, flags); michael@0: if (sent < 0) { michael@0: if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { michael@0: PORT_Assert(ss->lastWriteBlocked); michael@0: break; michael@0: } michael@0: return SECFailure; /* error code set by ssl3_SendRecord */ michael@0: } michael@0: totalSent += sent; michael@0: if (ss->pendingBuf.len) { michael@0: /* must be a non-blocking socket */ michael@0: PORT_Assert(!ssl_SocketIsBlocking(ss)); michael@0: PORT_Assert(ss->lastWriteBlocked); michael@0: break; michael@0: } michael@0: } michael@0: if (ss->pendingBuf.len) { michael@0: /* Must be non-blocking. */ michael@0: PORT_Assert(!ssl_SocketIsBlocking(ss)); michael@0: if (totalSent > 0) { michael@0: ss->appDataBuffered = 0x100 | in[totalSent - 1]; michael@0: } michael@0: michael@0: totalSent = totalSent + discarded - 1; michael@0: if (totalSent <= 0) { michael@0: PORT_SetError(PR_WOULD_BLOCK_ERROR); michael@0: totalSent = SECFailure; michael@0: } michael@0: return totalSent; michael@0: } michael@0: ss->appDataBuffered = 0; michael@0: return totalSent + discarded; michael@0: } michael@0: michael@0: /* Attempt to send buffered handshake messages. michael@0: * This function returns SECSuccess or SECFailure, never SECWouldBlock. michael@0: * Always set sendBuf.len to 0, even when returning SECFailure. michael@0: * michael@0: * Depending on whether we are doing DTLS or not, this either calls michael@0: * michael@0: * - ssl3_FlushHandshakeMessages if non-DTLS michael@0: * - dtls_FlushHandshakeMessages if DTLS michael@0: * michael@0: * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(), michael@0: * ssl3_AppendHandshake(), ssl3_SendClientHello(), michael@0: * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(), michael@0: * ssl3_SendFinished(), michael@0: */ michael@0: static SECStatus michael@0: ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) michael@0: { michael@0: if (IS_DTLS(ss)) { michael@0: return dtls_FlushHandshakeMessages(ss, flags); michael@0: } else { michael@0: return ssl3_FlushHandshakeMessages(ss, flags); michael@0: } michael@0: } michael@0: michael@0: /* Attempt to send the content of sendBuf buffer in an SSL handshake record. michael@0: * This function returns SECSuccess or SECFailure, never SECWouldBlock. michael@0: * Always set sendBuf.len to 0, even when returning SECFailure. michael@0: * michael@0: * Called from ssl3_FlushHandshake michael@0: */ michael@0: static SECStatus michael@0: ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) michael@0: { michael@0: static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER | michael@0: ssl_SEND_FLAG_CAP_RECORD_VERSION; michael@0: PRInt32 rv = SECSuccess; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); michael@0: michael@0: if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len) michael@0: return rv; michael@0: michael@0: /* only these flags are allowed */ michael@0: PORT_Assert(!(flags & ~allowedFlags)); michael@0: if ((flags & ~allowedFlags) != 0) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: rv = SECFailure; michael@0: } else { michael@0: rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf, michael@0: ss->sec.ci.sendBuf.len, flags); michael@0: } michael@0: if (rv < 0) { michael@0: int err = PORT_GetError(); michael@0: PORT_Assert(err != PR_WOULD_BLOCK_ERROR); michael@0: if (err == PR_WOULD_BLOCK_ERROR) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: } michael@0: } else if (rv < ss->sec.ci.sendBuf.len) { michael@0: /* short write should never happen */ michael@0: PORT_Assert(rv >= ss->sec.ci.sendBuf.len); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: rv = SECFailure; michael@0: } else { michael@0: rv = SECSuccess; michael@0: } michael@0: michael@0: /* Whether we succeeded or failed, toss the old handshake data. */ michael@0: ss->sec.ci.sendBuf.len = 0; michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when michael@0: * the remote client sends a negative response to our certificate request. michael@0: * Returns SECFailure if the application has required client auth. michael@0: * SECSuccess otherwise. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleNoCertificate(sslSocket *ss) michael@0: { michael@0: if (ss->sec.peerCert != NULL) { michael@0: if (ss->sec.peerKey != NULL) { michael@0: SECKEY_DestroyPublicKey(ss->sec.peerKey); michael@0: ss->sec.peerKey = NULL; michael@0: } michael@0: CERT_DestroyCertificate(ss->sec.peerCert); michael@0: ss->sec.peerCert = NULL; michael@0: } michael@0: ssl3_CleanupPeerCerts(ss); michael@0: michael@0: /* If the server has required client-auth blindly but doesn't michael@0: * actually look at the certificate it won't know that no michael@0: * certificate was presented so we shutdown the socket to ensure michael@0: * an error. We only do this if we haven't already completed the michael@0: * first handshake because if we're redoing the handshake we michael@0: * know the server is paying attention to the certificate. michael@0: */ michael@0: if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || michael@0: (!ss->firstHsDone && michael@0: (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { michael@0: PRFileDesc * lower; michael@0: michael@0: if (ss->sec.uncache) michael@0: ss->sec.uncache(ss->sec.ci.sid); michael@0: SSL3_SendAlert(ss, alert_fatal, bad_certificate); michael@0: michael@0: lower = ss->fd->lower; michael@0: #ifdef _WIN32 michael@0: lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); michael@0: #else michael@0: lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); michael@0: #endif michael@0: PORT_SetError(SSL_ERROR_NO_CERTIFICATE); michael@0: return SECFailure; michael@0: } michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /************************************************************************ michael@0: * Alerts michael@0: */ michael@0: michael@0: /* michael@0: ** Acquires both handshake and XmitBuf locks. michael@0: ** Called from: ssl3_IllegalParameter <- michael@0: ** ssl3_HandshakeFailure <- michael@0: ** ssl3_HandleAlert <- ssl3_HandleRecord. michael@0: ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord michael@0: ** ssl3_ConsumeHandshakeVariable <- michael@0: ** ssl3_HandleHelloRequest <- michael@0: ** ssl3_HandleServerHello <- michael@0: ** ssl3_HandleServerKeyExchange <- michael@0: ** ssl3_HandleCertificateRequest <- michael@0: ** ssl3_HandleServerHelloDone <- michael@0: ** ssl3_HandleClientHello <- michael@0: ** ssl3_HandleV2ClientHello <- michael@0: ** ssl3_HandleCertificateVerify <- michael@0: ** ssl3_HandleClientKeyExchange <- michael@0: ** ssl3_HandleCertificate <- michael@0: ** ssl3_HandleFinished <- michael@0: ** ssl3_HandleHandshakeMessage <- michael@0: ** ssl3_HandleRecord <- michael@0: ** michael@0: */ michael@0: SECStatus michael@0: SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) michael@0: { michael@0: PRUint8 bytes[2]; michael@0: SECStatus rv; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", michael@0: SSL_GETPID(), ss->fd, level, desc)); michael@0: michael@0: bytes[0] = level; michael@0: bytes[1] = desc; michael@0: michael@0: ssl_GetSSL3HandshakeLock(ss); michael@0: if (level == alert_fatal) { michael@0: if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { michael@0: ss->sec.uncache(ss->sec.ci.sid); michael@0: } michael@0: } michael@0: ssl_GetXmitBufLock(ss); michael@0: rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); michael@0: if (rv == SECSuccess) { michael@0: PRInt32 sent; michael@0: sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, michael@0: desc == no_certificate michael@0: ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); michael@0: rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; michael@0: } michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ michael@0: } michael@0: michael@0: /* michael@0: * Send illegal_parameter alert. Set generic error number. michael@0: */ michael@0: static SECStatus michael@0: ssl3_IllegalParameter(sslSocket *ss) michael@0: { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); michael@0: PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT michael@0: : SSL_ERROR_BAD_SERVER ); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* michael@0: * Send handshake_Failure alert. Set generic error number. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandshakeFailure(sslSocket *ss) michael@0: { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); michael@0: PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT michael@0: : SSL_ERROR_BAD_SERVER ); michael@0: return SECFailure; michael@0: } michael@0: michael@0: static void michael@0: ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode) michael@0: { michael@0: SSL3AlertDescription desc = bad_certificate; michael@0: PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS; michael@0: michael@0: switch (errCode) { michael@0: case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break; michael@0: case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break; michael@0: case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break; michael@0: case SEC_ERROR_INADEQUATE_KEY_USAGE: michael@0: case SEC_ERROR_INADEQUATE_CERT_TYPE: michael@0: desc = certificate_unknown; break; michael@0: case SEC_ERROR_UNTRUSTED_CERT: michael@0: desc = isTLS ? access_denied : certificate_unknown; break; michael@0: case SEC_ERROR_UNKNOWN_ISSUER: michael@0: case SEC_ERROR_UNTRUSTED_ISSUER: michael@0: desc = isTLS ? unknown_ca : certificate_unknown; break; michael@0: case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: michael@0: desc = isTLS ? unknown_ca : certificate_expired; break; michael@0: michael@0: case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: michael@0: case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: michael@0: case SEC_ERROR_CA_CERT_INVALID: michael@0: case SEC_ERROR_BAD_SIGNATURE: michael@0: default: desc = bad_certificate; break; michael@0: } michael@0: SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d", michael@0: SSL_GETPID(), ss->fd, errCode)); michael@0: michael@0: (void) SSL3_SendAlert(ss, alert_fatal, desc); michael@0: } michael@0: michael@0: michael@0: /* michael@0: * Send decode_error alert. Set generic error number. michael@0: */ michael@0: SECStatus michael@0: ssl3_DecodeError(sslSocket *ss) michael@0: { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, michael@0: ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error michael@0: : illegal_parameter); michael@0: PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT michael@0: : SSL_ERROR_BAD_SERVER ); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleRecord. michael@0: ** Caller must hold both RecvBuf and Handshake locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) michael@0: { michael@0: SSL3AlertLevel level; michael@0: SSL3AlertDescription desc; michael@0: int error; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd)); michael@0: michael@0: if (buf->len != 2) { michael@0: (void)ssl3_DecodeError(ss); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); michael@0: return SECFailure; michael@0: } michael@0: level = (SSL3AlertLevel)buf->buf[0]; michael@0: desc = (SSL3AlertDescription)buf->buf[1]; michael@0: buf->len = 0; michael@0: SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d", michael@0: SSL_GETPID(), ss->fd, level, desc)); michael@0: michael@0: switch (desc) { michael@0: case close_notify: ss->recvdCloseNotify = 1; michael@0: error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break; michael@0: case unexpected_message: error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; michael@0: break; michael@0: case bad_record_mac: error = SSL_ERROR_BAD_MAC_ALERT; break; michael@0: case decryption_failed_RESERVED: michael@0: error = SSL_ERROR_DECRYPTION_FAILED_ALERT; michael@0: break; michael@0: case record_overflow: error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break; michael@0: case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; michael@0: break; michael@0: case handshake_failure: error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; michael@0: break; michael@0: case no_certificate: error = SSL_ERROR_NO_CERTIFICATE; break; michael@0: case bad_certificate: error = SSL_ERROR_BAD_CERT_ALERT; break; michael@0: case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break; michael@0: case certificate_revoked: error = SSL_ERROR_REVOKED_CERT_ALERT; break; michael@0: case certificate_expired: error = SSL_ERROR_EXPIRED_CERT_ALERT; break; michael@0: case certificate_unknown: error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; michael@0: break; michael@0: case illegal_parameter: error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break; michael@0: case inappropriate_fallback: michael@0: error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; michael@0: break; michael@0: michael@0: /* All alerts below are TLS only. */ michael@0: case unknown_ca: error = SSL_ERROR_UNKNOWN_CA_ALERT; break; michael@0: case access_denied: error = SSL_ERROR_ACCESS_DENIED_ALERT; break; michael@0: case decode_error: error = SSL_ERROR_DECODE_ERROR_ALERT; break; michael@0: case decrypt_error: error = SSL_ERROR_DECRYPT_ERROR_ALERT; break; michael@0: case export_restriction: error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; michael@0: break; michael@0: case protocol_version: error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break; michael@0: case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; michael@0: break; michael@0: case internal_error: error = SSL_ERROR_INTERNAL_ERROR_ALERT; break; michael@0: case user_canceled: error = SSL_ERROR_USER_CANCELED_ALERT; break; michael@0: case no_renegotiation: error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break; michael@0: michael@0: /* Alerts for TLS client hello extensions */ michael@0: case unsupported_extension: michael@0: error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break; michael@0: case certificate_unobtainable: michael@0: error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break; michael@0: case unrecognized_name: michael@0: error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break; michael@0: case bad_certificate_status_response: michael@0: error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break; michael@0: case bad_certificate_hash_value: michael@0: error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break; michael@0: default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break; michael@0: } michael@0: if (level == alert_fatal) { michael@0: if (!ss->opt.noCache) { michael@0: if (ss->sec.uncache) michael@0: ss->sec.uncache(ss->sec.ci.sid); michael@0: } michael@0: if ((ss->ssl3.hs.ws == wait_server_hello) && michael@0: (desc == handshake_failure)) { michael@0: /* XXX This is a hack. We're assuming that any handshake failure michael@0: * XXX on the client hello is a failure to match ciphers. michael@0: */ michael@0: error = SSL_ERROR_NO_CYPHER_OVERLAP; michael@0: } michael@0: PORT_SetError(error); michael@0: return SECFailure; michael@0: } michael@0: if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) { michael@0: /* I'm a server. I've requested a client cert. He hasn't got one. */ michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert(ss->sec.isServer); michael@0: ss->ssl3.hs.ws = wait_client_key; michael@0: rv = ssl3_HandleNoCertificate(ss); michael@0: return rv; michael@0: } michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* michael@0: * Change Cipher Specs michael@0: * Called from ssl3_HandleServerHelloDone, michael@0: * ssl3_HandleClientHello, michael@0: * and ssl3_HandleFinished michael@0: * michael@0: * Acquires and releases spec write lock, to protect switching the current michael@0: * and pending write spec pointers. michael@0: */ michael@0: michael@0: static SECStatus michael@0: ssl3_SendChangeCipherSpecs(sslSocket *ss) michael@0: { michael@0: PRUint8 change = change_cipher_spec_choice; michael@0: ssl3CipherSpec * pwSpec; michael@0: SECStatus rv; michael@0: PRInt32 sent; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by ssl3_FlushHandshake */ michael@0: } michael@0: if (!IS_DTLS(ss)) { michael@0: sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, michael@0: ssl_SEND_FLAG_FORCE_INTO_BUFFER); michael@0: if (sent < 0) { michael@0: return (SECStatus)sent; /* error code set by ssl3_SendRecord */ michael@0: } michael@0: } else { michael@0: rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: } michael@0: michael@0: /* swap the pending and current write specs. */ michael@0: ssl_GetSpecWriteLock(ss); /**************************************/ michael@0: pwSpec = ss->ssl3.pwSpec; michael@0: michael@0: ss->ssl3.pwSpec = ss->ssl3.cwSpec; michael@0: ss->ssl3.cwSpec = pwSpec; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", michael@0: SSL_GETPID(), ss->fd )); michael@0: michael@0: /* We need to free up the contexts, keys and certs ! */ michael@0: /* If we are really through with the old cipher spec michael@0: * (Both the read and write sides have changed) destroy it. michael@0: */ michael@0: if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { michael@0: if (!IS_DTLS(ss)) { michael@0: ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/); michael@0: } else { michael@0: /* With DTLS, we need to set a holddown timer in case the final michael@0: * message got lost */ michael@0: ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; michael@0: dtls_StartTimer(ss, dtls_FinishedTimerCb); michael@0: } michael@0: } michael@0: ssl_ReleaseSpecWriteLock(ss); /**************************************/ michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleRecord. michael@0: ** Caller must hold both RecvBuf and Handshake locks. michael@0: * michael@0: * Acquires and releases spec write lock, to protect switching the current michael@0: * and pending write spec pointers. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) michael@0: { michael@0: ssl3CipherSpec * prSpec; michael@0: SSL3WaitState ws = ss->ssl3.hs.ws; michael@0: SSL3ChangeCipherSpecChoice change; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: if (ws != wait_change_cipher) { michael@0: if (IS_DTLS(ss)) { michael@0: /* Ignore this because it's out of order. */ michael@0: SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " michael@0: "DTLS change_cipher_spec", michael@0: SSL_GETPID(), ss->fd)); michael@0: buf->len = 0; michael@0: return SECSuccess; michael@0: } michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if(buf->len != 1) { michael@0: (void)ssl3_DecodeError(ss); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); michael@0: return SECFailure; michael@0: } michael@0: change = (SSL3ChangeCipherSpecChoice)buf->buf[0]; michael@0: if (change != change_cipher_spec_choice) { michael@0: /* illegal_parameter is correct here for both SSL3 and TLS. */ michael@0: (void)ssl3_IllegalParameter(ss); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); michael@0: return SECFailure; michael@0: } michael@0: buf->len = 0; michael@0: michael@0: /* Swap the pending and current read specs. */ michael@0: ssl_GetSpecWriteLock(ss); /*************************************/ michael@0: prSpec = ss->ssl3.prSpec; michael@0: michael@0: ss->ssl3.prSpec = ss->ssl3.crSpec; michael@0: ss->ssl3.crSpec = prSpec; michael@0: ss->ssl3.hs.ws = wait_finished; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", michael@0: SSL_GETPID(), ss->fd )); michael@0: michael@0: /* If we are really through with the old cipher prSpec michael@0: * (Both the read and write sides have changed) destroy it. michael@0: */ michael@0: if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { michael@0: ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/); michael@0: } michael@0: ssl_ReleaseSpecWriteLock(ss); /*************************************/ michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* This method uses PKCS11 to derive the MS from the PMS, where PMS michael@0: ** is a PKCS11 symkey. This is used in all cases except the michael@0: ** "triple bypass" with RSA key exchange. michael@0: ** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec. michael@0: */ michael@0: static SECStatus michael@0: ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) michael@0: { michael@0: ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; michael@0: const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def; michael@0: unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; michael@0: unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; michael@0: PRBool isTLS = (PRBool)(kea_def->tls_keygen || michael@0: (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); michael@0: PRBool isTLS12= michael@0: (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); michael@0: /* michael@0: * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH michael@0: * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size michael@0: * data into a 48-byte value. michael@0: */ michael@0: PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || michael@0: (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); michael@0: SECStatus rv = SECFailure; michael@0: CK_MECHANISM_TYPE master_derive; michael@0: CK_MECHANISM_TYPE key_derive; michael@0: SECItem params; michael@0: CK_FLAGS keyFlags; michael@0: CK_VERSION pms_version; michael@0: CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); michael@0: PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); michael@0: if (isTLS12) { michael@0: if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256; michael@0: else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256; michael@0: key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256; michael@0: keyFlags = CKF_SIGN | CKF_VERIFY; michael@0: } else if (isTLS) { michael@0: if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH; michael@0: else master_derive = CKM_TLS_MASTER_KEY_DERIVE; michael@0: key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; michael@0: keyFlags = CKF_SIGN | CKF_VERIFY; michael@0: } else { michael@0: if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH; michael@0: else master_derive = CKM_SSL3_MASTER_KEY_DERIVE; michael@0: key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; michael@0: keyFlags = 0; michael@0: } michael@0: michael@0: if (pms || !pwSpec->master_secret) { michael@0: if (isDH) { michael@0: master_params.pVersion = NULL; michael@0: } else { michael@0: master_params.pVersion = &pms_version; michael@0: } michael@0: master_params.RandomInfo.pClientRandom = cr; michael@0: master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; michael@0: master_params.RandomInfo.pServerRandom = sr; michael@0: master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; michael@0: michael@0: params.data = (unsigned char *) &master_params; michael@0: params.len = sizeof master_params; michael@0: } michael@0: michael@0: if (pms != NULL) { michael@0: #if defined(TRACE) michael@0: if (ssl_trace >= 100) { michael@0: SECStatus extractRV = PK11_ExtractKeyValue(pms); michael@0: if (extractRV == SECSuccess) { michael@0: SECItem * keyData = PK11_GetKeyData(pms); michael@0: if (keyData && keyData->data && keyData->len) { michael@0: ssl_PrintBuf(ss, "Pre-Master Secret", michael@0: keyData->data, keyData->len); michael@0: } michael@0: } michael@0: } michael@0: #endif michael@0: pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive, michael@0: ¶ms, key_derive, CKA_DERIVE, 0, keyFlags); michael@0: if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) { michael@0: SSL3ProtocolVersion client_version; michael@0: client_version = pms_version.major << 8 | pms_version.minor; michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: client_version = dtls_DTLSVersionToTLSVersion(client_version); michael@0: } michael@0: michael@0: if (client_version != ss->clientHelloVersion) { michael@0: /* Destroy it. Version roll-back detected. */ michael@0: PK11_FreeSymKey(pwSpec->master_secret); michael@0: pwSpec->master_secret = NULL; michael@0: } michael@0: } michael@0: if (pwSpec->master_secret == NULL) { michael@0: /* Generate a faux master secret in the same slot as the old one. */ michael@0: PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms); michael@0: PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot); michael@0: michael@0: PK11_FreeSlot(slot); michael@0: if (fpms != NULL) { michael@0: pwSpec->master_secret = PK11_DeriveWithFlags(fpms, michael@0: master_derive, ¶ms, key_derive, michael@0: CKA_DERIVE, 0, keyFlags); michael@0: PK11_FreeSymKey(fpms); michael@0: } michael@0: } michael@0: } michael@0: if (pwSpec->master_secret == NULL) { michael@0: /* Generate a faux master secret from the internal slot. */ michael@0: PK11SlotInfo * slot = PK11_GetInternalSlot(); michael@0: PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot); michael@0: michael@0: PK11_FreeSlot(slot); michael@0: if (fpms != NULL) { michael@0: pwSpec->master_secret = PK11_DeriveWithFlags(fpms, michael@0: master_derive, ¶ms, key_derive, michael@0: CKA_DERIVE, 0, keyFlags); michael@0: if (pwSpec->master_secret == NULL) { michael@0: pwSpec->master_secret = fpms; /* use the fpms as the master. */ michael@0: fpms = NULL; michael@0: } michael@0: } michael@0: if (fpms) { michael@0: PK11_FreeSymKey(fpms); michael@0: } michael@0: } michael@0: if (pwSpec->master_secret == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); michael@0: return rv; michael@0: } michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11) { michael@0: SECItem * keydata; michael@0: /* In hope of doing a "double bypass", michael@0: * need to extract the master secret's value from the key object michael@0: * and store it raw in the sslSocket struct. michael@0: */ michael@0: rv = PK11_ExtractKeyValue(pwSpec->master_secret); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: /* This returns the address of the secItem inside the key struct, michael@0: * not a copy or a reference. So, there's no need to free it. michael@0: */ michael@0: keydata = PK11_GetKeyData(pwSpec->master_secret); michael@0: if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { michael@0: memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); michael@0: pwSpec->msItem.data = pwSpec->raw_master_secret; michael@0: pwSpec->msItem.len = keydata->len; michael@0: } else { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: #endif michael@0: return SECSuccess; michael@0: } michael@0: michael@0: michael@0: /* michael@0: * Derive encryption and MAC Keys (and IVs) from master secret michael@0: * Sets a useful error code when returning SECFailure. michael@0: * michael@0: * Called only from ssl3_InitPendingCipherSpec(), michael@0: * which in turn is called from michael@0: * sendRSAClientKeyExchange (for Full handshake) michael@0: * sendDHClientKeyExchange (for Full handshake) michael@0: * ssl3_HandleClientKeyExchange (for Full handshake) michael@0: * ssl3_HandleServerHello (for session restart) michael@0: * ssl3_HandleClientHello (for session restart) michael@0: * Caller MUST hold the specWriteLock, and SSL3HandshakeLock. michael@0: * ssl3_InitPendingCipherSpec does that. michael@0: * michael@0: */ michael@0: static SECStatus michael@0: ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) michael@0: { michael@0: ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; michael@0: const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; michael@0: unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; michael@0: unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; michael@0: PRBool isTLS = (PRBool)(kea_def->tls_keygen || michael@0: (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); michael@0: PRBool isTLS12= michael@0: (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); michael@0: /* following variables used in PKCS11 path */ michael@0: const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; michael@0: PK11SlotInfo * slot = NULL; michael@0: PK11SymKey * symKey = NULL; michael@0: void * pwArg = ss->pkcs11PinArg; michael@0: int keySize; michael@0: CK_SSL3_KEY_MAT_PARAMS key_material_params; michael@0: CK_SSL3_KEY_MAT_OUT returnedKeys; michael@0: CK_MECHANISM_TYPE key_derive; michael@0: CK_MECHANISM_TYPE bulk_mechanism; michael@0: SSLCipherAlgorithm calg; michael@0: SECItem params; michael@0: PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); michael@0: PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); michael@0: michael@0: if (!pwSpec->master_secret) { michael@0: PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: /* michael@0: * generate the key material michael@0: */ michael@0: key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; michael@0: key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB; michael@0: key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; michael@0: if (cipher_def->type == type_block && michael@0: pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { michael@0: /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ michael@0: key_material_params.ulIVSizeInBits = 0; michael@0: memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); michael@0: memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); michael@0: } michael@0: michael@0: key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); michael@0: michael@0: key_material_params.RandomInfo.pClientRandom = cr; michael@0: key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; michael@0: key_material_params.RandomInfo.pServerRandom = sr; michael@0: key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; michael@0: key_material_params.pReturnedKeyMaterial = &returnedKeys; michael@0: michael@0: returnedKeys.pIVClient = pwSpec->client.write_iv; michael@0: returnedKeys.pIVServer = pwSpec->server.write_iv; michael@0: keySize = cipher_def->key_size; michael@0: michael@0: if (skipKeysAndIVs) { michael@0: keySize = 0; michael@0: key_material_params.ulKeySizeInBits = 0; michael@0: key_material_params.ulIVSizeInBits = 0; michael@0: returnedKeys.pIVClient = NULL; michael@0: returnedKeys.pIVServer = NULL; michael@0: } michael@0: michael@0: calg = cipher_def->calg; michael@0: PORT_Assert( alg2Mech[calg].calg == calg); michael@0: bulk_mechanism = alg2Mech[calg].cmech; michael@0: michael@0: params.data = (unsigned char *)&key_material_params; michael@0: params.len = sizeof(key_material_params); michael@0: michael@0: if (isTLS12) { michael@0: key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256; michael@0: } else if (isTLS) { michael@0: key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; michael@0: } else { michael@0: key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; michael@0: } michael@0: michael@0: /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and michael@0: * DERIVE by DEFAULT */ michael@0: symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms, michael@0: bulk_mechanism, CKA_ENCRYPT, keySize); michael@0: if (!symKey) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: /* we really should use the actual mac'ing mechanism here, but we michael@0: * don't because these types are used to map keytype anyway and both michael@0: * mac's map to the same keytype. michael@0: */ michael@0: slot = PK11_GetSlotFromKey(symKey); michael@0: michael@0: PK11_FreeSlot(slot); /* slot is held until the key is freed */ michael@0: pwSpec->client.write_mac_key = michael@0: PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, michael@0: CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); michael@0: if (pwSpec->client.write_mac_key == NULL ) { michael@0: goto loser; /* loser sets err */ michael@0: } michael@0: pwSpec->server.write_mac_key = michael@0: PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, michael@0: CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); michael@0: if (pwSpec->server.write_mac_key == NULL ) { michael@0: goto loser; /* loser sets err */ michael@0: } michael@0: if (!skipKeysAndIVs) { michael@0: pwSpec->client.write_key = michael@0: PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, michael@0: bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); michael@0: if (pwSpec->client.write_key == NULL ) { michael@0: goto loser; /* loser sets err */ michael@0: } michael@0: pwSpec->server.write_key = michael@0: PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, michael@0: bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); michael@0: if (pwSpec->server.write_key == NULL ) { michael@0: goto loser; /* loser sets err */ michael@0: } michael@0: } michael@0: PK11_FreeSymKey(symKey); michael@0: return SECSuccess; michael@0: michael@0: michael@0: loser: michael@0: if (symKey) PK11_FreeSymKey(symKey); michael@0: ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in michael@0: * buffered messages in ss->ssl3.hs.messages. */ michael@0: static SECStatus michael@0: ssl3_InitHandshakeHashes(sslSocket *ss) michael@0: { michael@0: SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11) { michael@0: PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); michael@0: if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { michael@0: /* If we ever support ciphersuites where the PRF hash isn't SHA-256 michael@0: * then this will need to be updated. */ michael@0: ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); michael@0: if (!ss->ssl3.hs.sha_obj) { michael@0: ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; michael@0: ss->ssl3.hs.hashType = handshake_hash_single; michael@0: ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); michael@0: } else { michael@0: ss->ssl3.hs.hashType = handshake_hash_combo; michael@0: MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); michael@0: SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); michael@0: } michael@0: } else michael@0: #endif michael@0: { michael@0: PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); michael@0: /* michael@0: * note: We should probably lookup an SSL3 slot for these michael@0: * handshake hashes in hopes that we wind up with the same slots michael@0: * that the master secret will wind up in ... michael@0: */ michael@0: if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { michael@0: /* If we ever support ciphersuites where the PRF hash isn't SHA-256 michael@0: * then this will need to be updated. */ michael@0: ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); michael@0: if (ss->ssl3.hs.sha == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: ss->ssl3.hs.hashType = handshake_hash_single; michael@0: michael@0: if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* Create a backup SHA-1 hash for a potential client auth michael@0: * signature. michael@0: * michael@0: * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the michael@0: * handshake hash function (SHA-256). If the server or the client michael@0: * does not support SHA-256 as a signature hash, we can either michael@0: * maintain a backup SHA-1 handshake hash or buffer all handshake michael@0: * messages. michael@0: */ michael@0: if (!ss->sec.isServer) { michael@0: ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); michael@0: if (ss->ssl3.hs.backupHash == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: } else { michael@0: /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or michael@0: * created successfully. */ michael@0: ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); michael@0: if (ss->ssl3.hs.md5 == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); michael@0: if (ss->ssl3.hs.sha == NULL) { michael@0: PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); michael@0: ss->ssl3.hs.md5 = NULL; michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: ss->ssl3.hs.hashType = handshake_hash_combo; michael@0: michael@0: if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (ss->ssl3.hs.messages.len > 0) { michael@0: if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, michael@0: ss->ssl3.hs.messages.len) != michael@0: SECSuccess) { michael@0: return SECFailure; michael@0: } michael@0: PORT_Free(ss->ssl3.hs.messages.buf); michael@0: ss->ssl3.hs.messages.buf = NULL; michael@0: ss->ssl3.hs.messages.len = 0; michael@0: ss->ssl3.hs.messages.space = 0; michael@0: } michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_RestartHandshakeHashes(sslSocket *ss) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: michael@0: SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes", michael@0: SSL_GETPID(), ss->fd )); michael@0: ss->ssl3.hs.hashType = handshake_hash_unknown; michael@0: ss->ssl3.hs.messages.len = 0; michael@0: #ifndef NO_PKCS11_BYPASS michael@0: ss->ssl3.hs.sha_obj = NULL; michael@0: ss->ssl3.hs.sha_clone = NULL; michael@0: #endif michael@0: if (ss->ssl3.hs.md5) { michael@0: PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); michael@0: ss->ssl3.hs.md5 = NULL; michael@0: } michael@0: if (ss->ssl3.hs.sha) { michael@0: PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); michael@0: ss->ssl3.hs.sha = NULL; michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * Handshake messages michael@0: */ michael@0: /* Called from ssl3_InitHandshakeHashes() michael@0: ** ssl3_AppendHandshake() michael@0: ** ssl3_StartHandshakeHash() michael@0: ** ssl3_HandleV2ClientHello() michael@0: ** ssl3_HandleHandshakeMessage() michael@0: ** Caller must hold the ssl3Handshake lock. michael@0: */ michael@0: static SECStatus michael@0: ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, michael@0: unsigned int l) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: /* We need to buffer the handshake messages until we have established michael@0: * which handshake hash function to use. */ michael@0: if (ss->ssl3.hs.hashType == handshake_hash_unknown) { michael@0: return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); michael@0: } michael@0: michael@0: PRINT_BUF(90, (NULL, "handshake hash input:", b, l)); michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11) { michael@0: if (ss->ssl3.hs.hashType == handshake_hash_single) { michael@0: ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); michael@0: } else { michael@0: MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); michael@0: SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); michael@0: } michael@0: return rv; michael@0: } michael@0: #endif michael@0: if (ss->ssl3.hs.hashType == handshake_hash_single) { michael@0: rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); michael@0: return rv; michael@0: } michael@0: if (ss->ssl3.hs.backupHash) { michael@0: rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: return rv; michael@0: } michael@0: } michael@0: } else { michael@0: rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: return rv; michael@0: } michael@0: rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: return rv; michael@0: } michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /************************************************************************** michael@0: * Append Handshake functions. michael@0: * All these functions set appropriate error codes. michael@0: * Most rely on ssl3_AppendHandshake to set the error code. michael@0: **************************************************************************/ michael@0: SECStatus michael@0: ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes) michael@0: { michael@0: unsigned char * src = (unsigned char *)void_src; michael@0: int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */ michael@0: michael@0: if (!bytes) michael@0: return SECSuccess; michael@0: if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) { michael@0: rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH, michael@0: PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes))); michael@0: if (rv != SECSuccess) michael@0: return rv; /* sslBuffer_Grow has set a memory error code. */ michael@0: room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; michael@0: } michael@0: michael@0: PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes)); michael@0: rv = ssl3_UpdateHandshakeHashes(ss, src, bytes); michael@0: if (rv != SECSuccess) michael@0: return rv; /* error code set by ssl3_UpdateHandshakeHashes */ michael@0: michael@0: while (bytes > room) { michael@0: if (room > 0) michael@0: PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, michael@0: room); michael@0: ss->sec.ci.sendBuf.len += room; michael@0: rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by ssl3_FlushHandshake */ michael@0: } michael@0: bytes -= room; michael@0: src += room; michael@0: room = ss->sec.ci.sendBuf.space; michael@0: PORT_Assert(ss->sec.ci.sendBuf.len == 0); michael@0: } michael@0: PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes); michael@0: ss->sec.ci.sendBuf.len += bytes; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: SECStatus michael@0: ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) michael@0: { michael@0: SECStatus rv; michael@0: PRUint8 b[4]; michael@0: PRUint8 * p = b; michael@0: michael@0: switch (lenSize) { michael@0: case 4: michael@0: *p++ = (num >> 24) & 0xff; michael@0: case 3: michael@0: *p++ = (num >> 16) & 0xff; michael@0: case 2: michael@0: *p++ = (num >> 8) & 0xff; michael@0: case 1: michael@0: *p = num & 0xff; michael@0: } michael@0: SSL_TRC(60, ("%d: number:", SSL_GETPID())); michael@0: rv = ssl3_AppendHandshake(ss, &b[0], lenSize); michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: michael@0: SECStatus michael@0: ssl3_AppendHandshakeVariable( michael@0: sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert((bytes < (1<<8) && lenSize == 1) || michael@0: (bytes < (1L<<16) && lenSize == 2) || michael@0: (bytes < (1L<<24) && lenSize == 3)); michael@0: michael@0: SSL_TRC(60,("%d: append variable:", SSL_GETPID())); michael@0: rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: SSL_TRC(60, ("data:")); michael@0: rv = ssl3_AppendHandshake(ss, src, bytes); michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: michael@0: SECStatus michael@0: ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: /* If we already have a message in place, we need to enqueue it. michael@0: * This empties the buffer. This is a convenient place to call michael@0: * dtls_StageHandshakeMessage to mark the message boundary. michael@0: */ michael@0: if (IS_DTLS(ss)) { michael@0: rv = dtls_StageHandshakeMessage(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: } michael@0: michael@0: SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s", michael@0: SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); michael@0: michael@0: rv = ssl3_AppendHandshakeNumber(ss, t, 1); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: rv = ssl3_AppendHandshakeNumber(ss, length, 3); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: /* Note that we make an unfragmented message here. We fragment in the michael@0: * transmission code, if necessary */ michael@0: rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: ss->ssl3.hs.sendMessageSeq++; michael@0: michael@0: /* 0 is the fragment offset, because it's not fragmented yet */ michael@0: rv = ssl3_AppendHandshakeNumber(ss, 0, 3); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: michael@0: /* Fragment length -- set to the packet length because not fragmented */ michael@0: rv = ssl3_AppendHandshakeNumber(ss, length, 3); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: } michael@0: michael@0: return rv; /* error code set by AppendHandshake, if applicable. */ michael@0: } michael@0: michael@0: /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of michael@0: * |sigAndHash| to the current handshake message. */ michael@0: SECStatus michael@0: ssl3_AppendSignatureAndHashAlgorithm( michael@0: sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash) michael@0: { michael@0: unsigned char serialized[2]; michael@0: michael@0: serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg); michael@0: if (serialized[0] == 0) { michael@0: PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); michael@0: return SECFailure; michael@0: } michael@0: michael@0: serialized[1] = sigAndHash->sigAlg; michael@0: michael@0: return ssl3_AppendHandshake(ss, serialized, sizeof(serialized)); michael@0: } michael@0: michael@0: /************************************************************************** michael@0: * Consume Handshake functions. michael@0: * michael@0: * All data used in these functions is protected by two locks, michael@0: * the RecvBufLock and the SSL3HandshakeLock michael@0: **************************************************************************/ michael@0: michael@0: /* Read up the next "bytes" number of bytes from the (decrypted) input michael@0: * stream "b" (which is *length bytes long). Copy them into buffer "v". michael@0: * Reduces *length by bytes. Advances *b by bytes. michael@0: * michael@0: * If this function returns SECFailure, it has already sent an alert, michael@0: * and has set a generic error code. The caller should probably michael@0: * override the generic error code by setting another. michael@0: */ michael@0: SECStatus michael@0: ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, michael@0: PRUint32 *length) michael@0: { michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if ((PRUint32)bytes > *length) { michael@0: return ssl3_DecodeError(ss); michael@0: } michael@0: PORT_Memcpy(v, *b, bytes); michael@0: PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); michael@0: *b += bytes; michael@0: *length -= bytes; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* Read up the next "bytes" number of bytes from the (decrypted) input michael@0: * stream "b" (which is *length bytes long), and interpret them as an michael@0: * integer in network byte order. Returns the received value. michael@0: * Reduces *length by bytes. Advances *b by bytes. michael@0: * michael@0: * Returns SECFailure (-1) on failure. michael@0: * This value is indistinguishable from the equivalent received value. michael@0: * Only positive numbers are to be received this way. michael@0: * Thus, the largest value that may be sent this way is 0x7fffffff. michael@0: * On error, an alert has been sent, and a generic error code has been set. michael@0: */ michael@0: PRInt32 michael@0: ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, michael@0: PRUint32 *length) michael@0: { michael@0: PRUint8 *buf = *b; michael@0: int i; michael@0: PRInt32 num = 0; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( bytes <= sizeof num); michael@0: michael@0: if ((PRUint32)bytes > *length) { michael@0: return ssl3_DecodeError(ss); michael@0: } michael@0: PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); michael@0: michael@0: for (i = 0; i < bytes; i++) michael@0: num = (num << 8) + buf[i]; michael@0: *b += bytes; michael@0: *length -= bytes; michael@0: return num; michael@0: } michael@0: michael@0: /* Read in two values from the incoming decrypted byte stream "b", which is michael@0: * *length bytes long. The first value is a number whose size is "bytes" michael@0: * bytes long. The second value is a byte-string whose size is the value michael@0: * of the first number received. The latter byte-string, and its length, michael@0: * is returned in the SECItem i. michael@0: * michael@0: * Returns SECFailure (-1) on failure. michael@0: * On error, an alert has been sent, and a generic error code has been set. michael@0: * michael@0: * RADICAL CHANGE for NSS 3.11. All callers of this function make copies michael@0: * of the data returned in the SECItem *i, so making a copy of it here michael@0: * is simply wasteful. So, This function now just sets SECItem *i to michael@0: * point to the values in the buffer **b. michael@0: */ michael@0: SECStatus michael@0: ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes, michael@0: SSL3Opaque **b, PRUint32 *length) michael@0: { michael@0: PRInt32 count; michael@0: michael@0: PORT_Assert(bytes <= 3); michael@0: i->len = 0; michael@0: i->data = NULL; michael@0: count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length); michael@0: if (count < 0) { /* Can't test for SECSuccess here. */ michael@0: return SECFailure; michael@0: } michael@0: if (count > 0) { michael@0: if ((PRUint32)count > *length) { michael@0: return ssl3_DecodeError(ss); michael@0: } michael@0: i->data = *b; michael@0: i->len = count; michael@0: *b += count; michael@0: *length -= count; michael@0: } michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the michael@0: * SECOidTag used internally by NSS. */ michael@0: static const struct { michael@0: int tlsHash; michael@0: SECOidTag oid; michael@0: } tlsHashOIDMap[] = { michael@0: { tls_hash_md5, SEC_OID_MD5 }, michael@0: { tls_hash_sha1, SEC_OID_SHA1 }, michael@0: { tls_hash_sha224, SEC_OID_SHA224 }, michael@0: { tls_hash_sha256, SEC_OID_SHA256 }, michael@0: { tls_hash_sha384, SEC_OID_SHA384 }, michael@0: { tls_hash_sha512, SEC_OID_SHA512 } michael@0: }; michael@0: michael@0: /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value. michael@0: * If the hash is not recognised, SEC_OID_UNKNOWN is returned. michael@0: * michael@0: * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ michael@0: SECOidTag michael@0: ssl3_TLSHashAlgorithmToOID(int hashFunc) michael@0: { michael@0: unsigned int i; michael@0: michael@0: for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { michael@0: if (hashFunc == tlsHashOIDMap[i].tlsHash) { michael@0: return tlsHashOIDMap[i].oid; michael@0: } michael@0: } michael@0: return SEC_OID_UNKNOWN; michael@0: } michael@0: michael@0: /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm michael@0: * identifier. If the hash is not recognised, zero is returned. michael@0: * michael@0: * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ michael@0: static int michael@0: ssl3_OIDToTLSHashAlgorithm(SECOidTag oid) michael@0: { michael@0: unsigned int i; michael@0: michael@0: for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { michael@0: if (oid == tlsHashOIDMap[i].oid) { michael@0: return tlsHashOIDMap[i].tlsHash; michael@0: } michael@0: } michael@0: return 0; michael@0: } michael@0: michael@0: /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm michael@0: * identifier for a given KeyType. */ michael@0: static SECStatus michael@0: ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, michael@0: TLSSignatureAlgorithm *out) michael@0: { michael@0: switch (keyType) { michael@0: case rsaKey: michael@0: *out = tls_sig_rsa; michael@0: return SECSuccess; michael@0: case dsaKey: michael@0: *out = tls_sig_dsa; michael@0: return SECSuccess; michael@0: case ecKey: michael@0: *out = tls_sig_ecdsa; michael@0: return SECSuccess; michael@0: default: michael@0: PORT_SetError(SEC_ERROR_INVALID_KEY); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature michael@0: * algorithm identifier for the given certificate. */ michael@0: static SECStatus michael@0: ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert, michael@0: TLSSignatureAlgorithm *out) michael@0: { michael@0: SECKEYPublicKey *key; michael@0: KeyType keyType; michael@0: michael@0: key = CERT_ExtractPublicKey(cert); michael@0: if (key == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: keyType = key->keyType; michael@0: SECKEY_DestroyPublicKey(key); michael@0: return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out); michael@0: } michael@0: michael@0: /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature michael@0: * algorithm identifier in |sigAndHash| is consistent with the public key in michael@0: * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called michael@0: * and SECFailure is returned. */ michael@0: SECStatus michael@0: ssl3_CheckSignatureAndHashAlgorithmConsistency( michael@0: const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert) michael@0: { michael@0: SECStatus rv; michael@0: TLSSignatureAlgorithm sigAlg; michael@0: michael@0: rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: if (sigAlg != sigAndHash->sigAlg) { michael@0: PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); michael@0: return SECFailure; michael@0: } michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm michael@0: * structure from |b| and puts the resulting value into |out|. |b| and |length| michael@0: * are updated accordingly. michael@0: * michael@0: * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ michael@0: SECStatus michael@0: ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, michael@0: SSL3Opaque **b, michael@0: PRUint32 *length, michael@0: SSL3SignatureAndHashAlgorithm *out) michael@0: { michael@0: unsigned char bytes[2]; michael@0: SECStatus rv; michael@0: michael@0: rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: michael@0: out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]); michael@0: if (out->hashAlg == SEC_OID_UNKNOWN) { michael@0: PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); michael@0: return SECFailure; michael@0: } michael@0: michael@0: out->sigAlg = bytes[1]; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /************************************************************************** michael@0: * end of Consume Handshake functions. michael@0: **************************************************************************/ michael@0: michael@0: /* Extract the hashes of handshake messages to this point. michael@0: * Called from ssl3_SendCertificateVerify michael@0: * ssl3_SendFinished michael@0: * ssl3_HandleHandshakeMessage michael@0: * michael@0: * Caller must hold the SSL3HandshakeLock. michael@0: * Caller must hold a read or write lock on the Spec R/W lock. michael@0: * (There is presently no way to assert on a Read lock.) michael@0: */ michael@0: static SECStatus michael@0: ssl3_ComputeHandshakeHashes(sslSocket * ss, michael@0: ssl3CipherSpec *spec, /* uses ->master_secret */ michael@0: SSL3Hashes * hashes, /* output goes here. */ michael@0: PRUint32 sender) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); michael@0: unsigned int outLength; michael@0: SSL3Opaque md5_inner[MAX_MAC_LENGTH]; michael@0: SSL3Opaque sha_inner[MAX_MAC_LENGTH]; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: hashes->hashAlg = SEC_OID_UNKNOWN; michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11 && michael@0: ss->ssl3.hs.hashType == handshake_hash_single) { michael@0: /* compute them without PKCS11 */ michael@0: PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; michael@0: michael@0: if (!spec->msItem.data) { michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); michael@0: ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, michael@0: sizeof(hashes->u.raw)); michael@0: michael@0: PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); michael@0: michael@0: /* If we ever support ciphersuites where the PRF hash isn't SHA-256 michael@0: * then this will need to be updated. */ michael@0: hashes->hashAlg = SEC_OID_SHA256; michael@0: rv = SECSuccess; michael@0: } else if (ss->opt.bypassPKCS11) { michael@0: /* compute them without PKCS11 */ michael@0: PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; michael@0: PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; michael@0: michael@0: #define md5cx ((MD5Context *)md5_cx) michael@0: #define shacx ((SHA1Context *)sha_cx) michael@0: michael@0: if (!spec->msItem.data) { michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); michael@0: SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); michael@0: michael@0: if (!isTLS) { michael@0: /* compute hashes for SSL3. */ michael@0: unsigned char s[4]; michael@0: michael@0: s[0] = (unsigned char)(sender >> 24); michael@0: s[1] = (unsigned char)(sender >> 16); michael@0: s[2] = (unsigned char)(sender >> 8); michael@0: s[3] = (unsigned char)sender; michael@0: michael@0: if (sender != 0) { michael@0: MD5_Update(md5cx, s, 4); michael@0: PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); michael@0: } michael@0: michael@0: PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, michael@0: mac_defs[mac_md5].pad_size)); michael@0: michael@0: MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); michael@0: MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); michael@0: MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); michael@0: michael@0: PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); michael@0: michael@0: if (sender != 0) { michael@0: SHA1_Update(shacx, s, 4); michael@0: PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); michael@0: } michael@0: michael@0: PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, michael@0: mac_defs[mac_sha].pad_size)); michael@0: michael@0: SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); michael@0: SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); michael@0: SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); michael@0: michael@0: PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); michael@0: PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, michael@0: mac_defs[mac_md5].pad_size)); michael@0: PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); michael@0: michael@0: MD5_Begin(md5cx); michael@0: MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); michael@0: MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); michael@0: MD5_Update(md5cx, md5_inner, MD5_LENGTH); michael@0: } michael@0: MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); michael@0: michael@0: PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); michael@0: michael@0: if (!isTLS) { michael@0: PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, michael@0: mac_defs[mac_sha].pad_size)); michael@0: PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); michael@0: michael@0: SHA1_Begin(shacx); michael@0: SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); michael@0: SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); michael@0: SHA1_Update(shacx, sha_inner, SHA1_LENGTH); michael@0: } michael@0: SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); michael@0: michael@0: PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); michael@0: michael@0: hashes->len = MD5_LENGTH + SHA1_LENGTH; michael@0: rv = SECSuccess; michael@0: #undef md5cx michael@0: #undef shacx michael@0: } else michael@0: #endif michael@0: if (ss->ssl3.hs.hashType == handshake_hash_single) { michael@0: /* compute hashes with PKCS11 */ michael@0: PK11Context *h; michael@0: unsigned int stateLen; michael@0: unsigned char stackBuf[1024]; michael@0: unsigned char *stateBuf = NULL; michael@0: michael@0: if (!spec->master_secret) { michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: h = ss->ssl3.hs.sha; michael@0: stateBuf = PK11_SaveContextAlloc(h, stackBuf, michael@0: sizeof(stackBuf), &stateLen); michael@0: if (stateBuf == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); michael@0: goto tls12_loser; michael@0: } michael@0: rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, michael@0: sizeof(hashes->u.raw)); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: goto tls12_loser; michael@0: } michael@0: /* If we ever support ciphersuites where the PRF hash isn't SHA-256 michael@0: * then this will need to be updated. */ michael@0: hashes->hashAlg = SEC_OID_SHA256; michael@0: rv = SECSuccess; michael@0: michael@0: tls12_loser: michael@0: if (stateBuf) { michael@0: if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: } michael@0: if (stateBuf != stackBuf) { michael@0: PORT_ZFree(stateBuf, stateLen); michael@0: } michael@0: } michael@0: } else { michael@0: /* compute hashes with PKCS11 */ michael@0: PK11Context * md5; michael@0: PK11Context * sha = NULL; michael@0: unsigned char *md5StateBuf = NULL; michael@0: unsigned char *shaStateBuf = NULL; michael@0: unsigned int md5StateLen, shaStateLen; michael@0: unsigned char md5StackBuf[256]; michael@0: unsigned char shaStackBuf[512]; michael@0: michael@0: if (!spec->master_secret) { michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, michael@0: sizeof md5StackBuf, &md5StateLen); michael@0: if (md5StateBuf == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: goto loser; michael@0: } michael@0: md5 = ss->ssl3.hs.md5; michael@0: michael@0: shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, michael@0: sizeof shaStackBuf, &shaStateLen); michael@0: if (shaStateBuf == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: goto loser; michael@0: } michael@0: sha = ss->ssl3.hs.sha; michael@0: michael@0: if (!isTLS) { michael@0: /* compute hashes for SSL3. */ michael@0: unsigned char s[4]; michael@0: michael@0: s[0] = (unsigned char)(sender >> 24); michael@0: s[1] = (unsigned char)(sender >> 16); michael@0: s[2] = (unsigned char)(sender >> 8); michael@0: s[3] = (unsigned char)sender; michael@0: michael@0: if (sender != 0) { michael@0: rv |= PK11_DigestOp(md5, s, 4); michael@0: PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); michael@0: } michael@0: michael@0: PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, michael@0: mac_defs[mac_md5].pad_size)); michael@0: michael@0: rv |= PK11_DigestKey(md5,spec->master_secret); michael@0: rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); michael@0: rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); michael@0: PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); michael@0: michael@0: if (sender != 0) { michael@0: rv |= PK11_DigestOp(sha, s, 4); michael@0: PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); michael@0: } michael@0: michael@0: PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, michael@0: mac_defs[mac_sha].pad_size)); michael@0: michael@0: rv |= PK11_DigestKey(sha, spec->master_secret); michael@0: rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); michael@0: rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); michael@0: PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); michael@0: michael@0: PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, michael@0: mac_defs[mac_md5].pad_size)); michael@0: PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); michael@0: michael@0: rv |= PK11_DigestBegin(md5); michael@0: rv |= PK11_DigestKey(md5, spec->master_secret); michael@0: rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); michael@0: rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); michael@0: } michael@0: rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); michael@0: PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); michael@0: michael@0: if (!isTLS) { michael@0: PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, michael@0: mac_defs[mac_sha].pad_size)); michael@0: PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); michael@0: michael@0: rv |= PK11_DigestBegin(sha); michael@0: rv |= PK11_DigestKey(sha,spec->master_secret); michael@0: rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); michael@0: rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); michael@0: } michael@0: rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); michael@0: PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); michael@0: michael@0: hashes->len = MD5_LENGTH + SHA1_LENGTH; michael@0: rv = SECSuccess; michael@0: michael@0: loser: michael@0: if (md5StateBuf) { michael@0: if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) michael@0: != SECSuccess) michael@0: { michael@0: ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: } michael@0: if (md5StateBuf != md5StackBuf) { michael@0: PORT_ZFree(md5StateBuf, md5StateLen); michael@0: } michael@0: } michael@0: if (shaStateBuf) { michael@0: if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) michael@0: != SECSuccess) michael@0: { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: } michael@0: if (shaStateBuf != shaStackBuf) { michael@0: PORT_ZFree(shaStateBuf, shaStateLen); michael@0: } michael@0: } michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, michael@0: SSL3Hashes * hashes) /* output goes here. */ michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( !ss->sec.isServer ); michael@0: PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); michael@0: michael@0: rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len, michael@0: sizeof(hashes->u.raw)); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: hashes->hashAlg = SEC_OID_SHA1; michael@0: michael@0: loser: michael@0: PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); michael@0: ss->ssl3.hs.backupHash = NULL; michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * SSL 2 based implementations pass in the initial outbound buffer michael@0: * so that the handshake hash can contain the included information. michael@0: * michael@0: * Called from ssl2_BeginClientHandshake() in sslcon.c michael@0: */ michael@0: SECStatus michael@0: ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: ssl_GetSSL3HandshakeLock(ss); /**************************************/ michael@0: michael@0: rv = ssl3_InitState(ss); michael@0: if (rv != SECSuccess) { michael@0: goto done; /* ssl3_InitState has set the error code. */ michael@0: } michael@0: rv = ssl3_RestartHandshakeHashes(ss); michael@0: if (rv != SECSuccess) { michael@0: goto done; michael@0: } michael@0: michael@0: PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); michael@0: PORT_Memcpy( michael@0: &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES], michael@0: &ss->sec.ci.clientChallenge, michael@0: SSL_CHALLENGE_BYTES); michael@0: michael@0: rv = ssl3_UpdateHandshakeHashes(ss, buf, length); michael@0: /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */ michael@0: michael@0: done: michael@0: ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ michael@0: return rv; michael@0: } michael@0: michael@0: /************************************************************************** michael@0: * end of Handshake Hash functions. michael@0: * Begin Send and Handle functions for handshakes. michael@0: **************************************************************************/ michael@0: michael@0: /* Called from ssl3_HandleHelloRequest(), michael@0: * ssl3_RedoHandshake() michael@0: * ssl2_BeginClientHandshake (when resuming ssl3 session) michael@0: * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) michael@0: */ michael@0: SECStatus michael@0: ssl3_SendClientHello(sslSocket *ss, PRBool resending) michael@0: { michael@0: sslSessionID * sid; michael@0: ssl3CipherSpec * cwSpec; michael@0: SECStatus rv; michael@0: int i; michael@0: int length; michael@0: int num_suites; michael@0: int actual_count = 0; michael@0: PRBool isTLS = PR_FALSE; michael@0: PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; michael@0: PRInt32 total_exten_len = 0; michael@0: unsigned paddingExtensionLen; michael@0: unsigned numCompressionMethods; michael@0: PRInt32 flags; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(), michael@0: ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); michael@0: michael@0: rv = ssl3_InitState(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* ssl3_InitState has set the error code. */ michael@0: } michael@0: ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */ michael@0: PORT_Assert(IS_DTLS(ss) || !resending); michael@0: michael@0: SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); michael@0: ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; michael@0: michael@0: /* We might be starting a session renegotiation in which case we should michael@0: * clear previous state. michael@0: */ michael@0: PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); michael@0: michael@0: rv = ssl3_RestartHandshakeHashes(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * During a renegotiation, ss->clientHelloVersion will be used again to michael@0: * work around a Windows SChannel bug. Ensure that it is still enabled. michael@0: */ michael@0: if (ss->firstHsDone) { michael@0: if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { michael@0: PORT_SetError(SSL_ERROR_SSL_DISABLED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (ss->clientHelloVersion < ss->vrange.min || michael@0: ss->clientHelloVersion > ss->vrange.max) { michael@0: PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup michael@0: * handles expired entries and other details. michael@0: * XXX If we've been called from ssl2_BeginClientHandshake, then michael@0: * this lookup is duplicative and wasteful. michael@0: */ michael@0: sid = (ss->opt.noCache) ? NULL michael@0: : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url); michael@0: michael@0: /* We can't resume based on a different token. If the sid exists, michael@0: * make sure the token that holds the master secret still exists ... michael@0: * If we previously did client-auth, make sure that the token that holds michael@0: * the private key still exists, is logged in, hasn't been removed, etc. michael@0: */ michael@0: if (sid) { michael@0: PRBool sidOK = PR_TRUE; michael@0: if (sid->u.ssl3.keys.msIsWrapped) { michael@0: /* Session key was wrapped, which means it was using PKCS11, */ michael@0: PK11SlotInfo *slot = NULL; michael@0: if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { michael@0: slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, michael@0: sid->u.ssl3.masterSlotID); michael@0: } michael@0: if (slot == NULL) { michael@0: sidOK = PR_FALSE; michael@0: } else { michael@0: PK11SymKey *wrapKey = NULL; michael@0: if (!PK11_IsPresent(slot) || michael@0: ((wrapKey = PK11_GetWrapKey(slot, michael@0: sid->u.ssl3.masterWrapIndex, michael@0: sid->u.ssl3.masterWrapMech, michael@0: sid->u.ssl3.masterWrapSeries, michael@0: ss->pkcs11PinArg)) == NULL) ) { michael@0: sidOK = PR_FALSE; michael@0: } michael@0: if (wrapKey) PK11_FreeSymKey(wrapKey); michael@0: PK11_FreeSlot(slot); michael@0: slot = NULL; michael@0: } michael@0: } michael@0: /* If we previously did client-auth, make sure that the token that michael@0: ** holds the private key still exists, is logged in, hasn't been michael@0: ** removed, etc. michael@0: */ michael@0: if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { michael@0: sidOK = PR_FALSE; michael@0: } michael@0: michael@0: /* TLS 1.0 (RFC 2246) Appendix E says: michael@0: * Whenever a client already knows the highest protocol known to michael@0: * a server (for example, when resuming a session), it should michael@0: * initiate the connection in that native protocol. michael@0: * So we pass sid->version to ssl3_NegotiateVersion() here, except michael@0: * when renegotiating. michael@0: * michael@0: * Windows SChannel compares the client_version inside the RSA michael@0: * EncryptedPreMasterSecret of a renegotiation with the michael@0: * client_version of the initial ClientHello rather than the michael@0: * ClientHello in the renegotiation. To work around this bug, we michael@0: * continue to use the client_version used in the initial michael@0: * ClientHello when renegotiating. michael@0: */ michael@0: if (sidOK) { michael@0: if (ss->firstHsDone) { michael@0: /* michael@0: * The client_version of the initial ClientHello is still michael@0: * available in ss->clientHelloVersion. Ensure that michael@0: * sid->version is bounded within michael@0: * [ss->vrange.min, ss->clientHelloVersion], otherwise we michael@0: * can't use sid. michael@0: */ michael@0: if (sid->version >= ss->vrange.min && michael@0: sid->version <= ss->clientHelloVersion) { michael@0: ss->version = ss->clientHelloVersion; michael@0: } else { michael@0: sidOK = PR_FALSE; michael@0: } michael@0: } else { michael@0: if (ssl3_NegotiateVersion(ss, sid->version, michael@0: PR_FALSE) != SECSuccess) { michael@0: sidOK = PR_FALSE; michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (!sidOK) { michael@0: SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok ); michael@0: if (ss->sec.uncache) michael@0: (*ss->sec.uncache)(sid); michael@0: ssl_FreeSID(sid); michael@0: sid = NULL; michael@0: } michael@0: } michael@0: michael@0: if (sid) { michael@0: requestingResume = PR_TRUE; michael@0: SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits ); michael@0: michael@0: PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, michael@0: sid->u.ssl3.sessionIDLength)); michael@0: michael@0: ss->ssl3.policy = sid->u.ssl3.policy; michael@0: } else { michael@0: SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses ); michael@0: michael@0: /* michael@0: * Windows SChannel compares the client_version inside the RSA michael@0: * EncryptedPreMasterSecret of a renegotiation with the michael@0: * client_version of the initial ClientHello rather than the michael@0: * ClientHello in the renegotiation. To work around this bug, we michael@0: * continue to use the client_version used in the initial michael@0: * ClientHello when renegotiating. michael@0: */ michael@0: if (ss->firstHsDone) { michael@0: ss->version = ss->clientHelloVersion; michael@0: } else { michael@0: rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, michael@0: PR_TRUE); michael@0: if (rv != SECSuccess) michael@0: return rv; /* error code was set */ michael@0: } michael@0: michael@0: sid = ssl3_NewSessionID(ss, PR_FALSE); michael@0: if (!sid) { michael@0: return SECFailure; /* memory error is set */ michael@0: } michael@0: } michael@0: michael@0: isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); michael@0: ssl_GetSpecWriteLock(ss); michael@0: cwSpec = ss->ssl3.cwSpec; michael@0: if (cwSpec->mac_def->mac == mac_null) { michael@0: /* SSL records are not being MACed. */ michael@0: cwSpec->version = ss->version; michael@0: } michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: michael@0: if (ss->sec.ci.sid != NULL) { michael@0: ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ michael@0: } michael@0: ss->sec.ci.sid = sid; michael@0: michael@0: ss->sec.send = ssl3_SendApplicationData; michael@0: michael@0: /* shouldn't get here if SSL3 is disabled, but ... */ michael@0: if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { michael@0: PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); michael@0: PORT_SetError(SSL_ERROR_SSL_DISABLED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* how many suites does our PKCS11 support (regardless of policy)? */ michael@0: num_suites = ssl3_config_match_init(ss); michael@0: if (!num_suites) michael@0: return SECFailure; /* ssl3_config_match_init has set error code. */ michael@0: michael@0: /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV, michael@0: * only if TLS is disabled. michael@0: */ michael@0: if (!ss->firstHsDone && !isTLS) { michael@0: /* Must set this before calling Hello Extension Senders, michael@0: * to suppress sending of empty RI extension. michael@0: */ michael@0: ss->ssl3.hs.sendingSCSV = PR_TRUE; michael@0: } michael@0: michael@0: /* When we attempt session resumption (only), we must lock the sid to michael@0: * prevent races with other resumption connections that receive a michael@0: * NewSessionTicket that will cause the ticket in the sid to be replaced. michael@0: * Once we've copied the session ticket into our ClientHello message, it michael@0: * is OK for the ticket to change, so we just need to make sure we hold michael@0: * the lock across the calls to ssl3_CallHelloExtensionSenders. michael@0: */ michael@0: if (sid->u.ssl3.lock) { michael@0: PR_RWLock_Rlock(sid->u.ssl3.lock); michael@0: } michael@0: michael@0: if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { michael@0: PRUint32 maxBytes = 65535; /* 2^16 - 1 */ michael@0: PRInt32 extLen; michael@0: michael@0: extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); michael@0: if (extLen < 0) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return SECFailure; michael@0: } michael@0: maxBytes -= extLen; michael@0: total_exten_len += extLen; michael@0: michael@0: if (total_exten_len > 0) michael@0: total_exten_len += 2; michael@0: } michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: if (!total_exten_len || !isTLS) { michael@0: /* not sending the elliptic_curves and ec_point_formats extensions */ michael@0: ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ michael@0: } michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: ssl3_DisableNonDTLSSuites(ss); michael@0: } michael@0: michael@0: /* how many suites are permitted by policy and user preference? */ michael@0: num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); michael@0: if (!num_suites) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return SECFailure; /* count_cipher_suites has set error code. */ michael@0: } michael@0: michael@0: fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume || michael@0: ss->version < sid->version); michael@0: /* make room for SCSV */ michael@0: if (ss->ssl3.hs.sendingSCSV) { michael@0: ++num_suites; michael@0: } michael@0: if (fallbackSCSV) { michael@0: ++num_suites; michael@0: } michael@0: michael@0: /* count compression methods */ michael@0: numCompressionMethods = 0; michael@0: for (i = 0; i < compressionMethodsCount; i++) { michael@0: if (compressionEnabled(ss, compressions[i])) michael@0: numCompressionMethods++; michael@0: } michael@0: michael@0: length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + michael@0: 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + michael@0: 2 + num_suites*sizeof(ssl3CipherSuite) + michael@0: 1 + numCompressionMethods + total_exten_len; michael@0: if (IS_DTLS(ss)) { michael@0: length += 1 + ss->ssl3.hs.cookieLen; michael@0: } michael@0: michael@0: /* A padding extension may be included to ensure that the record containing michael@0: * the ClientHello doesn't have a length between 256 and 511 bytes michael@0: * (inclusive). Initial, ClientHello records with such lengths trigger bugs michael@0: * in F5 devices. michael@0: * michael@0: * This is not done for DTLS nor for renegotiation. */ michael@0: if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) { michael@0: paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length); michael@0: total_exten_len += paddingExtensionLen; michael@0: length += paddingExtensionLen; michael@0: } else { michael@0: paddingExtensionLen = 0; michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, client_hello, length); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: michael@0: if (ss->firstHsDone) { michael@0: /* The client hello version must stay unchanged to work around michael@0: * the Windows SChannel bug described above. */ michael@0: PORT_Assert(ss->version == ss->clientHelloVersion); michael@0: } michael@0: ss->clientHelloVersion = ss->version; michael@0: if (IS_DTLS(ss)) { michael@0: PRUint16 version; michael@0: michael@0: version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); michael@0: rv = ssl3_AppendHandshakeNumber(ss, version, 2); michael@0: } else { michael@0: rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); michael@0: } michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: michael@0: if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */ michael@0: rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by GetNewRandom. */ michael@0: } michael@0: } michael@0: rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random, michael@0: SSL3_RANDOM_LENGTH); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: michael@0: if (sid) michael@0: rv = ssl3_AppendHandshakeVariable( michael@0: ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); michael@0: else michael@0: rv = ssl3_AppendHandshakeNumber(ss, 0, 1); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: rv = ssl3_AppendHandshakeVariable( michael@0: ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: michael@0: if (ss->ssl3.hs.sendingSCSV) { michael@0: /* Add the actual SCSV */ michael@0: rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, michael@0: sizeof(ssl3CipherSuite)); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: actual_count++; michael@0: } michael@0: if (fallbackSCSV) { michael@0: rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, michael@0: sizeof(ssl3CipherSuite)); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: actual_count++; michael@0: } michael@0: for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { michael@0: ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; michael@0: if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange)) { michael@0: actual_count++; michael@0: if (actual_count > num_suites) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: /* set error card removal/insertion error */ michael@0: PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, michael@0: sizeof(ssl3CipherSuite)); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* if cards were removed or inserted between count_cipher_suites and michael@0: * generating our list, detect the error here rather than send it off to michael@0: * the server.. */ michael@0: if (actual_count != num_suites) { michael@0: /* Card removal/insertion error */ michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); michael@0: return SECFailure; michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: for (i = 0; i < compressionMethodsCount; i++) { michael@0: if (!compressionEnabled(ss, compressions[i])) michael@0: continue; michael@0: rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: } michael@0: michael@0: if (total_exten_len) { michael@0: PRUint32 maxBytes = total_exten_len - 2; michael@0: PRInt32 extLen; michael@0: michael@0: rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); michael@0: if (rv != SECSuccess) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: michael@0: extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); michael@0: if (extLen < 0) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return SECFailure; michael@0: } michael@0: maxBytes -= extLen; michael@0: michael@0: extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); michael@0: if (extLen < 0) { michael@0: if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } michael@0: return SECFailure; michael@0: } michael@0: maxBytes -= extLen; michael@0: michael@0: PORT_Assert(!maxBytes); michael@0: } michael@0: michael@0: if (sid->u.ssl3.lock) { michael@0: PR_RWLock_Unlock(sid->u.ssl3.lock); michael@0: } michael@0: michael@0: if (ss->xtnData.sentSessionTicketInClientHello) { michael@0: SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes); michael@0: } michael@0: michael@0: if (ss->ssl3.hs.sendingSCSV) { michael@0: /* Since we sent the SCSV, pretend we sent empty RI extension. */ michael@0: TLSExtensionData *xtnData = &ss->xtnData; michael@0: xtnData->advertised[xtnData->numAdvertised++] = michael@0: ssl_renegotiation_info_xtn; michael@0: } michael@0: michael@0: flags = 0; michael@0: if (!ss->firstHsDone && !IS_DTLS(ss)) { michael@0: flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; michael@0: } michael@0: rv = ssl3_FlushHandshake(ss, flags); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by ssl3_FlushHandshake */ michael@0: } michael@0: michael@0: ss->ssl3.hs.ws = wait_server_hello; michael@0: return rv; michael@0: } michael@0: michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 Hello Request. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleHelloRequest(sslSocket *ss) michael@0: { michael@0: sslSessionID *sid = ss->sec.ci.sid; michael@0: SECStatus rv; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (ss->ssl3.hs.ws == wait_server_hello) michael@0: return SECSuccess; michael@0: if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); michael@0: return SECFailure; michael@0: } michael@0: if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { michael@0: ssl_GetXmitBufLock(ss); michael@0: rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation); michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (sid) { michael@0: if (ss->sec.uncache) michael@0: ss->sec.uncache(sid); michael@0: ssl_FreeSID(sid); michael@0: ss->sec.ci.sid = NULL; michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: dtls_RehandshakeCleanup(ss); michael@0: } michael@0: michael@0: ssl_GetXmitBufLock(ss); michael@0: rv = ssl3_SendClientHello(ss, PR_FALSE); michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: #define UNKNOWN_WRAP_MECHANISM 0x7fffffff michael@0: michael@0: static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = { michael@0: CKM_DES3_ECB, michael@0: CKM_CAST5_ECB, michael@0: CKM_DES_ECB, michael@0: CKM_KEY_WRAP_LYNKS, michael@0: CKM_IDEA_ECB, michael@0: CKM_CAST3_ECB, michael@0: CKM_CAST_ECB, michael@0: CKM_RC5_ECB, michael@0: CKM_RC2_ECB, michael@0: CKM_CDMF_ECB, michael@0: CKM_SKIPJACK_WRAP, michael@0: CKM_SKIPJACK_CBC64, michael@0: CKM_AES_ECB, michael@0: CKM_CAMELLIA_ECB, michael@0: CKM_SEED_ECB, michael@0: UNKNOWN_WRAP_MECHANISM michael@0: }; michael@0: michael@0: static int michael@0: ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) michael@0: { michael@0: const CK_MECHANISM_TYPE *pMech = wrapMechanismList; michael@0: michael@0: while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) { michael@0: ++pMech; michael@0: } michael@0: return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1 michael@0: : (pMech - wrapMechanismList); michael@0: } michael@0: michael@0: static PK11SymKey * michael@0: ssl_UnwrapSymWrappingKey( michael@0: SSLWrappedSymWrappingKey *pWswk, michael@0: SECKEYPrivateKey * svrPrivKey, michael@0: SSL3KEAType exchKeyType, michael@0: CK_MECHANISM_TYPE masterWrapMech, michael@0: void * pwArg) michael@0: { michael@0: PK11SymKey * unwrappedWrappingKey = NULL; michael@0: SECItem wrappedKey; michael@0: #ifndef NSS_DISABLE_ECC michael@0: PK11SymKey * Ks; michael@0: SECKEYPublicKey pubWrapKey; michael@0: ECCWrappedKeyInfo *ecWrapped; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: /* found the wrapping key on disk. */ michael@0: PORT_Assert(pWswk->symWrapMechanism == masterWrapMech); michael@0: PORT_Assert(pWswk->exchKeyType == exchKeyType); michael@0: if (pWswk->symWrapMechanism != masterWrapMech || michael@0: pWswk->exchKeyType != exchKeyType) { michael@0: goto loser; michael@0: } michael@0: wrappedKey.type = siBuffer; michael@0: wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; michael@0: wrappedKey.len = pWswk->wrappedSymKeyLen; michael@0: PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); michael@0: michael@0: switch (exchKeyType) { michael@0: michael@0: case kt_rsa: michael@0: unwrappedWrappingKey = michael@0: PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, michael@0: masterWrapMech, CKA_UNWRAP, 0); michael@0: break; michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: case kt_ecdh: michael@0: /* michael@0: * For kt_ecdh, we first create an EC public key based on michael@0: * data stored with the wrappedSymmetricWrappingkey. Next, michael@0: * we do an ECDH computation involving this public key and michael@0: * the SSL server's (long-term) EC private key. The resulting michael@0: * shared secret is treated the same way as Fortezza's Ks, i.e., michael@0: * it is used to recover the symmetric wrapping key. michael@0: * michael@0: * The data in wrappedSymmetricWrappingkey is laid out as defined michael@0: * in the ECCWrappedKeyInfo structure. michael@0: */ michael@0: ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey; michael@0: michael@0: PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + michael@0: ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN); michael@0: michael@0: if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + michael@0: ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: goto loser; michael@0: } michael@0: michael@0: pubWrapKey.keyType = ecKey; michael@0: pubWrapKey.u.ec.size = ecWrapped->size; michael@0: pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; michael@0: pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; michael@0: pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; michael@0: pubWrapKey.u.ec.publicValue.data = ecWrapped->var + michael@0: ecWrapped->encodedParamLen; michael@0: michael@0: wrappedKey.len = ecWrapped->wrappedKeyLen; michael@0: wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + michael@0: ecWrapped->pubValueLen; michael@0: michael@0: /* Derive Ks using ECDH */ michael@0: Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL, michael@0: NULL, CKM_ECDH1_DERIVE, masterWrapMech, michael@0: CKA_DERIVE, 0, CKD_NULL, NULL, NULL); michael@0: if (Ks == NULL) { michael@0: goto loser; michael@0: } michael@0: michael@0: /* Use Ks to unwrap the wrapping key */ michael@0: unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, michael@0: &wrappedKey, masterWrapMech, michael@0: CKA_UNWRAP, 0); michael@0: PK11_FreeSymKey(Ks); michael@0: michael@0: break; michael@0: #endif michael@0: michael@0: default: michael@0: /* Assert? */ michael@0: SET_ERROR_CODE michael@0: goto loser; michael@0: } michael@0: loser: michael@0: return unwrappedWrappingKey; michael@0: } michael@0: michael@0: /* Each process sharing the server session ID cache has its own array of michael@0: * SymKey pointers for the symmetric wrapping keys that are used to wrap michael@0: * the master secrets. There is one key for each KEA type. These Symkeys michael@0: * correspond to the wrapped SymKeys kept in the server session cache. michael@0: */ michael@0: michael@0: typedef struct { michael@0: PK11SymKey * symWrapKey[kt_kea_size]; michael@0: } ssl3SymWrapKey; michael@0: michael@0: static PZLock * symWrapKeysLock = NULL; michael@0: static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; michael@0: michael@0: SECStatus ssl_FreeSymWrapKeysLock(void) michael@0: { michael@0: if (symWrapKeysLock) { michael@0: PZ_DestroyLock(symWrapKeysLock); michael@0: symWrapKeysLock = NULL; michael@0: return SECSuccess; michael@0: } michael@0: PORT_SetError(SEC_ERROR_NOT_INITIALIZED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: SECStatus michael@0: SSL3_ShutdownServerCache(void) michael@0: { michael@0: int i, j; michael@0: michael@0: if (!symWrapKeysLock) michael@0: return SECSuccess; /* lock was never initialized */ michael@0: PZ_Lock(symWrapKeysLock); michael@0: /* get rid of all symWrapKeys */ michael@0: for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { michael@0: for (j = 0; j < kt_kea_size; ++j) { michael@0: PK11SymKey ** pSymWrapKey; michael@0: pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; michael@0: if (*pSymWrapKey) { michael@0: PK11_FreeSymKey(*pSymWrapKey); michael@0: *pSymWrapKey = NULL; michael@0: } michael@0: } michael@0: } michael@0: michael@0: PZ_Unlock(symWrapKeysLock); michael@0: ssl_FreeSessionCacheLocks(); michael@0: return SECSuccess; michael@0: } michael@0: michael@0: SECStatus ssl_InitSymWrapKeysLock(void) michael@0: { michael@0: symWrapKeysLock = PZ_NewLock(nssILockOther); michael@0: return symWrapKeysLock ? SECSuccess : SECFailure; michael@0: } michael@0: michael@0: /* Try to get wrapping key for mechanism from in-memory array. michael@0: * If that fails, look for one on disk. michael@0: * If that fails, generate a new one, put the new one on disk, michael@0: * Put the new key in the in-memory array. michael@0: */ michael@0: static PK11SymKey * michael@0: getWrappingKey( sslSocket * ss, michael@0: PK11SlotInfo * masterSecretSlot, michael@0: SSL3KEAType exchKeyType, michael@0: CK_MECHANISM_TYPE masterWrapMech, michael@0: void * pwArg) michael@0: { michael@0: SECKEYPrivateKey * svrPrivKey; michael@0: SECKEYPublicKey * svrPubKey = NULL; michael@0: PK11SymKey * unwrappedWrappingKey = NULL; michael@0: PK11SymKey ** pSymWrapKey; michael@0: CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; michael@0: int length; michael@0: int symWrapMechIndex; michael@0: SECStatus rv; michael@0: SECItem wrappedKey; michael@0: SSLWrappedSymWrappingKey wswk; michael@0: #ifndef NSS_DISABLE_ECC michael@0: PK11SymKey * Ks = NULL; michael@0: SECKEYPublicKey *pubWrapKey = NULL; michael@0: SECKEYPrivateKey *privWrapKey = NULL; michael@0: ECCWrappedKeyInfo *ecWrapped; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; michael@0: PORT_Assert(svrPrivKey != NULL); michael@0: if (!svrPrivKey) { michael@0: return NULL; /* why are we here?!? */ michael@0: } michael@0: michael@0: symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech); michael@0: PORT_Assert(symWrapMechIndex >= 0); michael@0: if (symWrapMechIndex < 0) michael@0: return NULL; /* invalid masterWrapMech. */ michael@0: michael@0: pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType]; michael@0: michael@0: ssl_InitSessionCacheLocks(PR_TRUE); michael@0: michael@0: PZ_Lock(symWrapKeysLock); michael@0: michael@0: unwrappedWrappingKey = *pSymWrapKey; michael@0: if (unwrappedWrappingKey != NULL) { michael@0: if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { michael@0: unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); michael@0: goto done; michael@0: } michael@0: /* slot series has changed, so this key is no good any more. */ michael@0: PK11_FreeSymKey(unwrappedWrappingKey); michael@0: *pSymWrapKey = unwrappedWrappingKey = NULL; michael@0: } michael@0: michael@0: /* Try to get wrapped SymWrapping key out of the (disk) cache. */ michael@0: /* Following call fills in wswk on success. */ michael@0: if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) { michael@0: /* found the wrapped sym wrapping key on disk. */ michael@0: unwrappedWrappingKey = michael@0: ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, michael@0: masterWrapMech, pwArg); michael@0: if (unwrappedWrappingKey) { michael@0: goto install; michael@0: } michael@0: } michael@0: michael@0: if (!masterSecretSlot) /* caller doesn't want to create a new one. */ michael@0: goto loser; michael@0: michael@0: length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech); michael@0: /* Zero length means fixed key length algorithm, or error. michael@0: * It's ambiguous. michael@0: */ michael@0: unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, michael@0: length, pwArg); michael@0: if (!unwrappedWrappingKey) { michael@0: goto loser; michael@0: } michael@0: michael@0: /* Prepare the buffer to receive the wrappedWrappingKey, michael@0: * the symmetric wrapping key wrapped using the server's pub key. michael@0: */ michael@0: PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ michael@0: michael@0: if (ss->serverCerts[exchKeyType].serverKeyPair) { michael@0: svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; michael@0: } michael@0: if (svrPubKey == NULL) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: goto loser; michael@0: } michael@0: wrappedKey.type = siBuffer; michael@0: wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); michael@0: wrappedKey.data = wswk.wrappedSymmetricWrappingkey; michael@0: michael@0: PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); michael@0: if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) michael@0: goto loser; michael@0: michael@0: /* wrap symmetric wrapping key in server's public key. */ michael@0: switch (exchKeyType) { michael@0: case kt_rsa: michael@0: asymWrapMechanism = CKM_RSA_PKCS; michael@0: rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, michael@0: unwrappedWrappingKey, &wrappedKey); michael@0: break; michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: case kt_ecdh: michael@0: /* michael@0: * We generate an ephemeral EC key pair. Perform an ECDH michael@0: * computation involving this ephemeral EC public key and michael@0: * the SSL server's (long-term) EC private key. The resulting michael@0: * shared secret is treated in the same way as Fortezza's Ks, michael@0: * i.e., it is used to wrap the wrapping key. To facilitate michael@0: * unwrapping in ssl_UnwrapWrappingKey, we also store all michael@0: * relevant info about the ephemeral EC public key in michael@0: * wswk.wrappedSymmetricWrappingkey and lay it out as michael@0: * described in the ECCWrappedKeyInfo structure. michael@0: */ michael@0: PORT_Assert(svrPubKey->keyType == ecKey); michael@0: if (svrPubKey->keyType != ecKey) { michael@0: /* something is wrong in sslsecur.c if this isn't an ecKey */ michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: rv = SECFailure; michael@0: goto ec_cleanup; michael@0: } michael@0: michael@0: privWrapKey = SECKEY_CreateECPrivateKey( michael@0: &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); michael@0: if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { michael@0: rv = SECFailure; michael@0: goto ec_cleanup; michael@0: } michael@0: michael@0: /* Set the key size in bits */ michael@0: if (pubWrapKey->u.ec.size == 0) { michael@0: pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey); michael@0: } michael@0: michael@0: PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + michael@0: pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN); michael@0: if (pubWrapKey->u.ec.DEREncodedParams.len + michael@0: pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) { michael@0: PORT_SetError(SEC_ERROR_INVALID_KEY); michael@0: rv = SECFailure; michael@0: goto ec_cleanup; michael@0: } michael@0: michael@0: /* Derive Ks using ECDH */ michael@0: Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, michael@0: NULL, CKM_ECDH1_DERIVE, masterWrapMech, michael@0: CKA_DERIVE, 0, CKD_NULL, NULL, NULL); michael@0: if (Ks == NULL) { michael@0: rv = SECFailure; michael@0: goto ec_cleanup; michael@0: } michael@0: michael@0: ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey); michael@0: ecWrapped->size = pubWrapKey->u.ec.size; michael@0: ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; michael@0: PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, michael@0: pubWrapKey->u.ec.DEREncodedParams.len); michael@0: michael@0: ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; michael@0: PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, michael@0: pubWrapKey->u.ec.publicValue.data, michael@0: pubWrapKey->u.ec.publicValue.len); michael@0: michael@0: wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - michael@0: (ecWrapped->encodedParamLen + ecWrapped->pubValueLen); michael@0: wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + michael@0: ecWrapped->pubValueLen; michael@0: michael@0: /* wrap symmetricWrapping key with the local Ks */ michael@0: rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, michael@0: unwrappedWrappingKey, &wrappedKey); michael@0: michael@0: if (rv != SECSuccess) { michael@0: goto ec_cleanup; michael@0: } michael@0: michael@0: /* Write down the length of wrapped key in the buffer michael@0: * wswk.wrappedSymmetricWrappingkey at the appropriate offset michael@0: */ michael@0: ecWrapped->wrappedKeyLen = wrappedKey.len; michael@0: michael@0: ec_cleanup: michael@0: if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey); michael@0: if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey); michael@0: if (Ks) PK11_FreeSymKey(Ks); michael@0: asymWrapMechanism = masterWrapMech; michael@0: break; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: default: michael@0: rv = SECFailure; michael@0: break; michael@0: } michael@0: michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: goto loser; michael@0: } michael@0: michael@0: PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); michael@0: michael@0: wswk.symWrapMechanism = masterWrapMech; michael@0: wswk.symWrapMechIndex = symWrapMechIndex; michael@0: wswk.asymWrapMechanism = asymWrapMechanism; michael@0: wswk.exchKeyType = exchKeyType; michael@0: wswk.wrappedSymKeyLen = wrappedKey.len; michael@0: michael@0: /* put it on disk. */ michael@0: /* If the wrapping key for this KEA type has already been set, michael@0: * then abandon the value we just computed and michael@0: * use the one we got from the disk. michael@0: */ michael@0: if (ssl_SetWrappingKey(&wswk)) { michael@0: /* somebody beat us to it. The original contents of our wswk michael@0: * has been replaced with the content on disk. Now, discard michael@0: * the key we just created and unwrap this new one. michael@0: */ michael@0: PK11_FreeSymKey(unwrappedWrappingKey); michael@0: michael@0: unwrappedWrappingKey = michael@0: ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, michael@0: masterWrapMech, pwArg); michael@0: } michael@0: michael@0: install: michael@0: if (unwrappedWrappingKey) { michael@0: *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); michael@0: } michael@0: michael@0: loser: michael@0: done: michael@0: PZ_Unlock(symWrapKeysLock); michael@0: return unwrappedWrappingKey; michael@0: } michael@0: michael@0: /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2| michael@0: * bytes to |out|. */ michael@0: static void michael@0: hexEncode(char *out, const unsigned char *in, unsigned int length) michael@0: { michael@0: static const char hextable[] = "0123456789abcdef"; michael@0: unsigned int i; michael@0: michael@0: for (i = 0; i < length; i++) { michael@0: *(out++) = hextable[in[i] >> 4]; michael@0: *(out++) = hextable[in[i] & 15]; michael@0: } michael@0: } michael@0: michael@0: /* Called from ssl3_SendClientKeyExchange(). */ michael@0: /* Presently, this always uses PKCS11. There is no bypass for this. */ michael@0: static SECStatus michael@0: sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) michael@0: { michael@0: PK11SymKey * pms = NULL; michael@0: SECStatus rv = SECFailure; michael@0: SECItem enc_pms = {siBuffer, NULL, 0}; michael@0: PRBool isTLS; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: michael@0: /* Generate the pre-master secret ... */ michael@0: ssl_GetSpecWriteLock(ss); michael@0: isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: michael@0: pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: if (pms == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: goto loser; michael@0: } michael@0: michael@0: /* Get the wrapped (encrypted) pre-master secret, enc_pms */ michael@0: enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); michael@0: enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len); michael@0: if (enc_pms.data == NULL) { michael@0: goto loser; /* err set by PORT_Alloc */ michael@0: } michael@0: michael@0: /* wrap pre-master secret in server's public key. */ michael@0: rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: goto loser; michael@0: } michael@0: michael@0: if (ssl_keylog_iob) { michael@0: SECStatus extractRV = PK11_ExtractKeyValue(pms); michael@0: if (extractRV == SECSuccess) { michael@0: SECItem * keyData = PK11_GetKeyData(pms); michael@0: if (keyData && keyData->data && keyData->len) { michael@0: #ifdef TRACE michael@0: if (ssl_trace >= 100) { michael@0: ssl_PrintBuf(ss, "Pre-Master Secret", michael@0: keyData->data, keyData->len); michael@0: } michael@0: #endif michael@0: if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { michael@0: /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ michael@0: michael@0: /* There could be multiple, concurrent writers to the michael@0: * keylog, so we have to do everything in a single call to michael@0: * fwrite. */ michael@0: char buf[4 + 8*2 + 1 + 48*2 + 1]; michael@0: michael@0: strcpy(buf, "RSA "); michael@0: hexEncode(buf + 4, enc_pms.data, 8); michael@0: buf[20] = ' '; michael@0: hexEncode(buf + 21, keyData->data, 48); michael@0: buf[sizeof(buf) - 1] = '\n'; michael@0: michael@0: fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); michael@0: fflush(ssl_keylog_iob); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_InitPendingCipherSpec(ss, pms); michael@0: PK11_FreeSymKey(pms); pms = NULL; michael@0: michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: goto loser; michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, michael@0: isTLS ? enc_pms.len + 2 : enc_pms.len); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: if (isTLS) { michael@0: rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); michael@0: } else { michael@0: rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); michael@0: } michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: michael@0: rv = SECSuccess; michael@0: michael@0: loser: michael@0: if (enc_pms.data != NULL) { michael@0: PORT_Free(enc_pms.data); michael@0: } michael@0: if (pms != NULL) { michael@0: PK11_FreeSymKey(pms); michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* Called from ssl3_SendClientKeyExchange(). */ michael@0: /* Presently, this always uses PKCS11. There is no bypass for this. */ michael@0: static SECStatus michael@0: sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) michael@0: { michael@0: PK11SymKey * pms = NULL; michael@0: SECStatus rv = SECFailure; michael@0: PRBool isTLS; michael@0: CK_MECHANISM_TYPE target; michael@0: michael@0: SECKEYDHParams dhParam; /* DH parameters */ michael@0: SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ michael@0: SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: michael@0: /* Copy DH parameters from server key */ michael@0: michael@0: if (svrPubKey->keyType != dhKey) { michael@0: PORT_SetError(SEC_ERROR_BAD_KEY); michael@0: goto loser; michael@0: } michael@0: dhParam.prime.data = svrPubKey->u.dh.prime.data; michael@0: dhParam.prime.len = svrPubKey->u.dh.prime.len; michael@0: dhParam.base.data = svrPubKey->u.dh.base.data; michael@0: dhParam.base.len = svrPubKey->u.dh.base.len; michael@0: michael@0: /* Generate ephemeral DH keypair */ michael@0: privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); michael@0: if (!privKey || !pubKey) { michael@0: ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: PRINT_BUF(50, (ss, "DH public value:", michael@0: pubKey->u.dh.publicValue.data, michael@0: pubKey->u.dh.publicValue.len)); michael@0: michael@0: if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH; michael@0: else target = CKM_SSL3_MASTER_KEY_DERIVE_DH; michael@0: michael@0: /* Determine the PMS */ michael@0: michael@0: pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL, michael@0: CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); michael@0: michael@0: if (pms == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: goto loser; michael@0: } michael@0: michael@0: SECKEY_DestroyPrivateKey(privKey); michael@0: privKey = NULL; michael@0: michael@0: rv = ssl3_InitPendingCipherSpec(ss, pms); michael@0: PK11_FreeSymKey(pms); pms = NULL; michael@0: michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: goto loser; michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, michael@0: pubKey->u.dh.publicValue.len + 2); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: rv = ssl3_AppendHandshakeVariable(ss, michael@0: pubKey->u.dh.publicValue.data, michael@0: pubKey->u.dh.publicValue.len, 2); michael@0: SECKEY_DestroyPublicKey(pubKey); michael@0: pubKey = NULL; michael@0: michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by ssl3_AppendHandshake* */ michael@0: } michael@0: michael@0: rv = SECSuccess; michael@0: michael@0: michael@0: loser: michael@0: michael@0: if(pms) PK11_FreeSymKey(pms); michael@0: if(privKey) SECKEY_DestroyPrivateKey(privKey); michael@0: if(pubKey) SECKEY_DestroyPublicKey(pubKey); michael@0: return rv; michael@0: } michael@0: michael@0: michael@0: michael@0: michael@0: michael@0: /* Called from ssl3_HandleServerHelloDone(). */ michael@0: static SECStatus michael@0: ssl3_SendClientKeyExchange(sslSocket *ss) michael@0: { michael@0: SECKEYPublicKey * serverKey = NULL; michael@0: SECStatus rv = SECFailure; michael@0: PRBool isTLS; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: if (ss->sec.peerKey == NULL) { michael@0: serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); michael@0: if (serverKey == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: } else { michael@0: serverKey = ss->sec.peerKey; michael@0: ss->sec.peerKey = NULL; /* we're done with it now */ michael@0: } michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: /* enforce limits on kea key sizes. */ michael@0: if (ss->ssl3.hs.kea_def->is_limited) { michael@0: int keyLen = SECKEY_PublicKeyStrength(serverKey); /* bytes */ michael@0: michael@0: if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) { michael@0: if (isTLS) michael@0: (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); michael@0: else michael@0: (void)ssl3_HandshakeFailure(ss); michael@0: PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); michael@0: goto loser; michael@0: } michael@0: } michael@0: michael@0: ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; michael@0: ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); michael@0: michael@0: switch (ss->ssl3.hs.kea_def->exchKeyType) { michael@0: case kt_rsa: michael@0: rv = sendRSAClientKeyExchange(ss, serverKey); michael@0: break; michael@0: michael@0: case kt_dh: michael@0: rv = sendDHClientKeyExchange(ss, serverKey); michael@0: break; michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: case kt_ecdh: michael@0: rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); michael@0: break; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: default: michael@0: /* got an unknown or unsupported Key Exchange Algorithm. */ michael@0: SEND_ALERT michael@0: PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); michael@0: break; michael@0: } michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: loser: michael@0: if (serverKey) michael@0: SECKEY_DestroyPublicKey(serverKey); michael@0: return rv; /* err code already set. */ michael@0: } michael@0: michael@0: /* Called from ssl3_HandleServerHelloDone(). */ michael@0: static SECStatus michael@0: ssl3_SendCertificateVerify(sslSocket *ss) michael@0: { michael@0: SECStatus rv = SECFailure; michael@0: PRBool isTLS; michael@0: PRBool isTLS12; michael@0: SECItem buf = {siBuffer, NULL, 0}; michael@0: SSL3Hashes hashes; michael@0: KeyType keyType; michael@0: unsigned int len; michael@0: SSL3SignatureAndHashAlgorithm sigAndHash; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: ssl_GetSpecReadLock(ss); michael@0: if (ss->ssl3.hs.hashType == handshake_hash_single && michael@0: ss->ssl3.hs.backupHash) { michael@0: rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); michael@0: PORT_Assert(!ss->ssl3.hs.backupHash); michael@0: } else { michael@0: rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); michael@0: } michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: if (rv != SECSuccess) { michael@0: goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ michael@0: } michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); michael@0: keyType = ss->ssl3.clientPrivateKey->keyType; michael@0: rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS); michael@0: if (rv == SECSuccess) { michael@0: PK11SlotInfo * slot; michael@0: sslSessionID * sid = ss->sec.ci.sid; michael@0: michael@0: /* Remember the info about the slot that did the signing. michael@0: ** Later, when doing an SSL restart handshake, verify this. michael@0: ** These calls are mere accessors, and can't fail. michael@0: */ michael@0: slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey); michael@0: sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); michael@0: sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); michael@0: sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); michael@0: sid->u.ssl3.clAuthValid = PR_TRUE; michael@0: PK11_FreeSlot(slot); michael@0: } michael@0: SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); michael@0: ss->ssl3.clientPrivateKey = NULL; michael@0: if (rv != SECSuccess) { michael@0: goto done; /* err code was set by ssl3_SignHashes */ michael@0: } michael@0: michael@0: len = buf.len + 2 + (isTLS12 ? 2 : 0); michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len); michael@0: if (rv != SECSuccess) { michael@0: goto done; /* error code set by AppendHandshake */ michael@0: } michael@0: if (isTLS12) { michael@0: rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, michael@0: &sigAndHash.sigAlg); michael@0: if (rv != SECSuccess) { michael@0: goto done; michael@0: } michael@0: sigAndHash.hashAlg = hashes.hashAlg; michael@0: michael@0: rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); michael@0: if (rv != SECSuccess) { michael@0: goto done; /* err set by AppendHandshake. */ michael@0: } michael@0: } michael@0: rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2); michael@0: if (rv != SECSuccess) { michael@0: goto done; /* error code set by AppendHandshake */ michael@0: } michael@0: michael@0: done: michael@0: if (buf.data) michael@0: PORT_Free(buf.data); michael@0: return rv; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 ServerHello message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: sslSessionID *sid = ss->sec.ci.sid; michael@0: PRInt32 temp; /* allow for consume number failure */ michael@0: PRBool suite_found = PR_FALSE; michael@0: int i; michael@0: int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; michael@0: SECStatus rv; michael@0: SECItem sidBytes = {siBuffer, NULL, 0}; michael@0: PRBool sid_match; michael@0: PRBool isTLS = PR_FALSE; michael@0: SSL3AlertDescription desc = illegal_parameter; michael@0: SSL3ProtocolVersion version; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->ssl3.initialized ); michael@0: michael@0: if (ss->ssl3.hs.ws != wait_server_hello) { michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; michael@0: desc = unexpected_message; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* clean up anything left from previous handshake. */ michael@0: if (ss->ssl3.clientCertChain != NULL) { michael@0: CERT_DestroyCertificateList(ss->ssl3.clientCertChain); michael@0: ss->ssl3.clientCertChain = NULL; michael@0: } michael@0: if (ss->ssl3.clientCertificate != NULL) { michael@0: CERT_DestroyCertificate(ss->ssl3.clientCertificate); michael@0: ss->ssl3.clientCertificate = NULL; michael@0: } michael@0: if (ss->ssl3.clientPrivateKey != NULL) { michael@0: SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); michael@0: ss->ssl3.clientPrivateKey = NULL; michael@0: } michael@0: michael@0: temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); michael@0: if (temp < 0) { michael@0: goto loser; /* alert has been sent */ michael@0: } michael@0: version = (SSL3ProtocolVersion)temp; michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: /* RFC 4347 required that you verify that the server versions michael@0: * match (Section 4.2.1) in the HelloVerifyRequest and the michael@0: * ServerHello. michael@0: * michael@0: * RFC 6347 suggests (SHOULD) that servers always use 1.0 michael@0: * in HelloVerifyRequest and allows the versions not to match, michael@0: * especially when 1.2 is being negotiated. michael@0: * michael@0: * Therefore we do not check for matching here. michael@0: */ michael@0: version = dtls_DTLSVersionToTLSVersion(version); michael@0: if (version == 0) { /* Insane version number */ michael@0: goto alert_loser; michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_NegotiateVersion(ss, version, PR_FALSE); michael@0: if (rv != SECSuccess) { michael@0: desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version michael@0: : handshake_failure; michael@0: errCode = SSL_ERROR_NO_CYPHER_OVERLAP; michael@0: goto alert_loser; michael@0: } michael@0: isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); michael@0: michael@0: rv = ssl3_InitHandshakeHashes(ss); michael@0: if (rv != SECSuccess) { michael@0: desc = internal_error; michael@0: errCode = PORT_GetError(); michael@0: goto alert_loser; michael@0: } michael@0: michael@0: rv = ssl3_ConsumeHandshake( michael@0: ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* alert has been sent */ michael@0: } michael@0: michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* alert has been sent */ michael@0: } michael@0: if (sidBytes.len > SSL3_SESSIONID_BYTES) { michael@0: if (isTLS) michael@0: desc = decode_error; michael@0: goto alert_loser; /* malformed. */ michael@0: } michael@0: michael@0: /* find selected cipher suite in our list. */ michael@0: temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); michael@0: if (temp < 0) { michael@0: goto loser; /* alert has been sent */ michael@0: } michael@0: ssl3_config_match_init(ss); michael@0: for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { michael@0: ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; michael@0: if (temp == suite->cipher_suite) { michael@0: SSLVersionRange vrange = {ss->version, ss->version}; michael@0: if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { michael@0: /* config_match already checks whether the cipher suite is michael@0: * acceptable for the version, but the check is repeated here michael@0: * in order to give a more precise error code. */ michael@0: if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) { michael@0: desc = handshake_failure; michael@0: errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: break; /* failure */ michael@0: } michael@0: michael@0: suite_found = PR_TRUE; michael@0: break; /* success */ michael@0: } michael@0: } michael@0: if (!suite_found) { michael@0: desc = handshake_failure; michael@0: errCode = SSL_ERROR_NO_CYPHER_OVERLAP; michael@0: goto alert_loser; michael@0: } michael@0: ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp; michael@0: ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); michael@0: PORT_Assert(ss->ssl3.hs.suite_def); michael@0: if (!ss->ssl3.hs.suite_def) { michael@0: PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE); michael@0: goto loser; /* we don't send alerts for our screw-ups. */ michael@0: } michael@0: michael@0: /* find selected compression method in our list. */ michael@0: temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); michael@0: if (temp < 0) { michael@0: goto loser; /* alert has been sent */ michael@0: } michael@0: suite_found = PR_FALSE; michael@0: for (i = 0; i < compressionMethodsCount; i++) { michael@0: if (temp == compressions[i]) { michael@0: if (!compressionEnabled(ss, compressions[i])) { michael@0: break; /* failure */ michael@0: } michael@0: suite_found = PR_TRUE; michael@0: break; /* success */ michael@0: } michael@0: } michael@0: if (!suite_found) { michael@0: desc = handshake_failure; michael@0: errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; michael@0: goto alert_loser; michael@0: } michael@0: ss->ssl3.hs.compression = (SSLCompressionMethod)temp; michael@0: michael@0: /* Note that if !isTLS and the extra stuff is not extensions, we michael@0: * do NOT goto alert_loser. michael@0: * There are some old SSL 3.0 implementations that do send stuff michael@0: * after the end of the server hello, and we deliberately ignore michael@0: * such stuff in the interest of maximal interoperability (being michael@0: * "generous in what you accept"). michael@0: * Update: Starting in NSS 3.12.6, we handle the renegotiation_info michael@0: * extension in SSL 3.0. michael@0: */ michael@0: if (length != 0) { michael@0: SECItem extensions; michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); michael@0: if (rv != SECSuccess || length != 0) { michael@0: if (isTLS) michael@0: goto alert_loser; michael@0: } else { michael@0: rv = ssl3_HandleHelloExtensions(ss, &extensions.data, michael@0: &extensions.len); michael@0: if (rv != SECSuccess) michael@0: goto alert_loser; michael@0: } michael@0: } michael@0: if ((ss->opt.requireSafeNegotiation || michael@0: (ss->firstHsDone && (ss->peerRequestedProtection || michael@0: ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) && michael@0: !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { michael@0: desc = handshake_failure; michael@0: errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED michael@0: : SSL_ERROR_UNSAFE_NEGOTIATION; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* Any errors after this point are not "malformed" errors. */ michael@0: desc = handshake_failure; michael@0: michael@0: /* we need to call ssl3_SetupPendingCipherSpec here so we can check the michael@0: * key exchange algorithm. */ michael@0: rv = ssl3_SetupPendingCipherSpec(ss); michael@0: if (rv != SECSuccess) { michael@0: goto alert_loser; /* error code is set. */ michael@0: } michael@0: michael@0: /* We may or may not have sent a session id, we may get one back or michael@0: * not and if so it may match the one we sent. michael@0: * Attempt to restore the master secret to see if this is so... michael@0: * Don't consider failure to find a matching SID an error. michael@0: */ michael@0: sid_match = (PRBool)(sidBytes.len > 0 && michael@0: sidBytes.len == sid->u.ssl3.sessionIDLength && michael@0: !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len)); michael@0: michael@0: if (sid_match && michael@0: sid->version == ss->version && michael@0: sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do { michael@0: ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; michael@0: michael@0: SECItem wrappedMS; /* wrapped master secret. */ michael@0: michael@0: ss->sec.authAlgorithm = sid->authAlgorithm; michael@0: ss->sec.authKeyBits = sid->authKeyBits; michael@0: ss->sec.keaType = sid->keaType; michael@0: ss->sec.keaKeyBits = sid->keaKeyBits; michael@0: michael@0: /* 3 cases here: michael@0: * a) key is wrapped (implies using PKCS11) michael@0: * b) key is unwrapped, but we're still using PKCS11 michael@0: * c) key is unwrapped, and we're bypassing PKCS11. michael@0: */ michael@0: if (sid->u.ssl3.keys.msIsWrapped) { michael@0: PK11SlotInfo *slot; michael@0: PK11SymKey * wrapKey; /* wrapping key */ michael@0: CK_FLAGS keyFlags = 0; michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11) { michael@0: /* we cannot restart a non-bypass session in a michael@0: ** bypass socket. michael@0: */ michael@0: break; michael@0: } michael@0: #endif michael@0: /* unwrap master secret with PKCS11 */ michael@0: slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, michael@0: sid->u.ssl3.masterSlotID); michael@0: if (slot == NULL) { michael@0: break; /* not considered an error. */ michael@0: } michael@0: if (!PK11_IsPresent(slot)) { michael@0: PK11_FreeSlot(slot); michael@0: break; /* not considered an error. */ michael@0: } michael@0: wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, michael@0: sid->u.ssl3.masterWrapMech, michael@0: sid->u.ssl3.masterWrapSeries, michael@0: ss->pkcs11PinArg); michael@0: PK11_FreeSlot(slot); michael@0: if (wrapKey == NULL) { michael@0: break; /* not considered an error. */ michael@0: } michael@0: michael@0: if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ michael@0: keyFlags = CKF_SIGN | CKF_VERIFY; michael@0: } michael@0: michael@0: wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; michael@0: wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; michael@0: pwSpec->master_secret = michael@0: PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, michael@0: NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, michael@0: CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); michael@0: errCode = PORT_GetError(); michael@0: PK11_FreeSymKey(wrapKey); michael@0: if (pwSpec->master_secret == NULL) { michael@0: break; /* errorCode set just after call to UnwrapSymKey. */ michael@0: } michael@0: #ifndef NO_PKCS11_BYPASS michael@0: } else if (ss->opt.bypassPKCS11) { michael@0: /* MS is not wrapped */ michael@0: wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; michael@0: wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; michael@0: memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); michael@0: pwSpec->msItem.data = pwSpec->raw_master_secret; michael@0: pwSpec->msItem.len = wrappedMS.len; michael@0: #endif michael@0: } else { michael@0: /* We CAN restart a bypass session in a non-bypass socket. */ michael@0: /* need to import the raw master secret to session object */ michael@0: PK11SlotInfo *slot = PK11_GetInternalSlot(); michael@0: wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; michael@0: wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; michael@0: pwSpec->master_secret = michael@0: PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, michael@0: PK11_OriginUnwrap, CKA_ENCRYPT, michael@0: &wrappedMS, NULL); michael@0: PK11_FreeSlot(slot); michael@0: if (pwSpec->master_secret == NULL) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: /* Got a Match */ michael@0: SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits ); michael@0: michael@0: /* If we sent a session ticket, then this is a stateless resume. */ michael@0: if (ss->xtnData.sentSessionTicketInClientHello) michael@0: SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes ); michael@0: michael@0: if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) michael@0: ss->ssl3.hs.ws = wait_new_session_ticket; michael@0: else michael@0: ss->ssl3.hs.ws = wait_change_cipher; michael@0: michael@0: ss->ssl3.hs.isResuming = PR_TRUE; michael@0: michael@0: /* copy the peer cert from the SID */ michael@0: if (sid->peerCert != NULL) { michael@0: ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); michael@0: } michael@0: michael@0: /* NULL value for PMS signifies re-use of the old MS */ michael@0: rv = ssl3_InitPendingCipherSpec(ss, NULL); michael@0: if (rv != SECSuccess) { michael@0: goto alert_loser; /* err code was set */ michael@0: } michael@0: return SECSuccess; michael@0: } while (0); michael@0: michael@0: if (sid_match) michael@0: SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok ); michael@0: else michael@0: SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses ); michael@0: michael@0: /* throw the old one away */ michael@0: sid->u.ssl3.keys.resumable = PR_FALSE; michael@0: if (ss->sec.uncache) michael@0: (*ss->sec.uncache)(sid); michael@0: ssl_FreeSID(sid); michael@0: michael@0: /* get a new sid */ michael@0: ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE); michael@0: if (sid == NULL) { michael@0: goto alert_loser; /* memory error is set. */ michael@0: } michael@0: michael@0: sid->version = ss->version; michael@0: sid->u.ssl3.sessionIDLength = sidBytes.len; michael@0: PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len); michael@0: michael@0: ss->ssl3.hs.isResuming = PR_FALSE; michael@0: ss->ssl3.hs.ws = wait_server_cert; michael@0: return SECSuccess; michael@0: michael@0: alert_loser: michael@0: (void)SSL3_SendAlert(ss, alert_fatal, desc); michael@0: michael@0: loser: michael@0: errCode = ssl_MapLowLevelError(errCode); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned, michael@0: * big-endian integer is > 1 */ michael@0: static PRBool michael@0: ssl3_BigIntGreaterThanOne(const SECItem* mpint) { michael@0: unsigned char firstNonZeroByte = 0; michael@0: unsigned int i; michael@0: michael@0: for (i = 0; i < mpint->len; i++) { michael@0: if (mpint->data[i]) { michael@0: firstNonZeroByte = mpint->data[i]; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (firstNonZeroByte == 0) michael@0: return PR_FALSE; michael@0: if (firstNonZeroByte > 1) michael@0: return PR_TRUE; michael@0: michael@0: /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte michael@0: * is followed by another byte. */ michael@0: return (i < mpint->len - 1); michael@0: } michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 ServerKeyExchange message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: PLArenaPool * arena = NULL; michael@0: SECKEYPublicKey *peerKey = NULL; michael@0: PRBool isTLS, isTLS12; michael@0: SECStatus rv; michael@0: int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; michael@0: SSL3AlertDescription desc = illegal_parameter; michael@0: SSL3Hashes hashes; michael@0: SECItem signature = {siBuffer, NULL, 0}; michael@0: SSL3SignatureAndHashAlgorithm sigAndHash; michael@0: michael@0: sigAndHash.hashAlg = SEC_OID_UNKNOWN; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (ss->ssl3.hs.ws != wait_server_key && michael@0: ss->ssl3.hs.ws != wait_server_cert) { michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; michael@0: desc = unexpected_message; michael@0: goto alert_loser; michael@0: } michael@0: if (ss->sec.peerCert == NULL) { michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; michael@0: desc = unexpected_message; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); michael@0: michael@0: switch (ss->ssl3.hs.kea_def->exchKeyType) { michael@0: michael@0: case kt_rsa: { michael@0: SECItem modulus = {siBuffer, NULL, 0}; michael@0: SECItem exponent = {siBuffer, NULL, 0}; michael@0: michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: if (isTLS12) { michael@0: rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, michael@0: &sigAndHash); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed or unsupported. */ michael@0: } michael@0: rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( michael@0: &sigAndHash, ss->sec.peerCert); michael@0: if (rv != SECSuccess) { michael@0: goto loser; michael@0: } michael@0: } michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: if (length != 0) { michael@0: if (isTLS) michael@0: desc = decode_error; michael@0: goto alert_loser; /* malformed. */ michael@0: } michael@0: michael@0: /* failures after this point are not malformed handshakes. */ michael@0: /* TLS: send decrypt_error if signature failed. */ michael@0: desc = isTLS ? decrypt_error : handshake_failure; michael@0: michael@0: /* michael@0: * check to make sure the hash is signed by right guy michael@0: */ michael@0: rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent, michael@0: &ss->ssl3.hs.client_random, michael@0: &ss->ssl3.hs.server_random, michael@0: &hashes, ss->opt.bypassPKCS11); michael@0: if (rv != SECSuccess) { michael@0: errCode = michael@0: ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: goto alert_loser; michael@0: } michael@0: rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, michael@0: isTLS, ss->pkcs11PinArg); michael@0: if (rv != SECSuccess) { michael@0: errCode = michael@0: ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* michael@0: * we really need to build a new key here because we can no longer michael@0: * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate michael@0: * pkcs11 slots and ID's. michael@0: */ michael@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); michael@0: if (arena == NULL) { michael@0: goto no_memory; michael@0: } michael@0: michael@0: peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); michael@0: if (peerKey == NULL) { michael@0: PORT_FreeArena(arena, PR_FALSE); michael@0: goto no_memory; michael@0: } michael@0: michael@0: peerKey->arena = arena; michael@0: peerKey->keyType = rsaKey; michael@0: peerKey->pkcs11Slot = NULL; michael@0: peerKey->pkcs11ID = CK_INVALID_HANDLE; michael@0: if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || michael@0: SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent)) michael@0: { michael@0: PORT_FreeArena(arena, PR_FALSE); michael@0: goto no_memory; michael@0: } michael@0: ss->sec.peerKey = peerKey; michael@0: ss->ssl3.hs.ws = wait_cert_request; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: case kt_dh: { michael@0: SECItem dh_p = {siBuffer, NULL, 0}; michael@0: SECItem dh_g = {siBuffer, NULL, 0}; michael@0: SECItem dh_Ys = {siBuffer, NULL, 0}; michael@0: michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: if (dh_p.len < 512/8) { michael@0: errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; michael@0: goto alert_loser; michael@0: } michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g)) michael@0: goto alert_loser; michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys)) michael@0: goto alert_loser; michael@0: if (isTLS12) { michael@0: rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, michael@0: &sigAndHash); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed or unsupported. */ michael@0: } michael@0: rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( michael@0: &sigAndHash, ss->sec.peerCert); michael@0: if (rv != SECSuccess) { michael@0: goto loser; michael@0: } michael@0: } michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: if (length != 0) { michael@0: if (isTLS) michael@0: desc = decode_error; michael@0: goto alert_loser; /* malformed. */ michael@0: } michael@0: michael@0: PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len)); michael@0: PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len)); michael@0: PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len)); michael@0: michael@0: /* failures after this point are not malformed handshakes. */ michael@0: /* TLS: send decrypt_error if signature failed. */ michael@0: desc = isTLS ? decrypt_error : handshake_failure; michael@0: michael@0: /* michael@0: * check to make sure the hash is signed by right guy michael@0: */ michael@0: rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys, michael@0: &ss->ssl3.hs.client_random, michael@0: &ss->ssl3.hs.server_random, michael@0: &hashes, ss->opt.bypassPKCS11); michael@0: if (rv != SECSuccess) { michael@0: errCode = michael@0: ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: goto alert_loser; michael@0: } michael@0: rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, michael@0: isTLS, ss->pkcs11PinArg); michael@0: if (rv != SECSuccess) { michael@0: errCode = michael@0: ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* michael@0: * we really need to build a new key here because we can no longer michael@0: * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate michael@0: * pkcs11 slots and ID's. michael@0: */ michael@0: arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); michael@0: if (arena == NULL) { michael@0: goto no_memory; michael@0: } michael@0: michael@0: ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); michael@0: if (peerKey == NULL) { michael@0: goto no_memory; michael@0: } michael@0: michael@0: peerKey->arena = arena; michael@0: peerKey->keyType = dhKey; michael@0: peerKey->pkcs11Slot = NULL; michael@0: peerKey->pkcs11ID = CK_INVALID_HANDLE; michael@0: michael@0: if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) || michael@0: SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) || michael@0: SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) michael@0: { michael@0: PORT_FreeArena(arena, PR_FALSE); michael@0: goto no_memory; michael@0: } michael@0: ss->sec.peerKey = peerKey; michael@0: ss->ssl3.hs.ws = wait_cert_request; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: case kt_ecdh: michael@0: rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); michael@0: return rv; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: default: michael@0: desc = handshake_failure; michael@0: errCode = SEC_ERROR_UNSUPPORTED_KEYALG; michael@0: break; /* goto alert_loser; */ michael@0: } michael@0: michael@0: alert_loser: michael@0: (void)SSL3_SendAlert(ss, alert_fatal, desc); michael@0: loser: michael@0: PORT_SetError( errCode ); michael@0: return SECFailure; michael@0: michael@0: no_memory: /* no-memory error has already been set. */ michael@0: ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: michael@0: /* michael@0: * Returns the TLS signature algorithm for the client authentication key and michael@0: * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes. michael@0: */ michael@0: static SECStatus michael@0: ssl3_ExtractClientKeyInfo(sslSocket *ss, michael@0: TLSSignatureAlgorithm *sigAlg, michael@0: PRBool *preferSha1) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: SECKEYPublicKey *pubk; michael@0: michael@0: pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); michael@0: if (pubk == NULL) { michael@0: rv = SECFailure; michael@0: goto done; michael@0: } michael@0: michael@0: rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg); michael@0: if (rv != SECSuccess) { michael@0: goto done; michael@0: } michael@0: michael@0: /* If the key is a 1024-bit RSA or DSA key, assume conservatively that michael@0: * it may be unable to sign SHA-256 hashes. This is the case for older michael@0: * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and michael@0: * older, DSA key size is at most 1024 bits and the hash function must michael@0: * be SHA-1. michael@0: */ michael@0: if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { michael@0: *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; michael@0: } else { michael@0: *preferSha1 = PR_FALSE; michael@0: } michael@0: michael@0: done: michael@0: if (pubk) michael@0: SECKEY_DestroyPublicKey(pubk); michael@0: return rv; michael@0: } michael@0: michael@0: /* Destroys the backup handshake hash context if we don't need it. Note that michael@0: * this function selects the hash algorithm for client authentication michael@0: * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash michael@0: * to determine whether to use SHA-1 or SHA-256. */ michael@0: static void michael@0: ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, michael@0: const SECItem *algorithms) michael@0: { michael@0: SECStatus rv; michael@0: TLSSignatureAlgorithm sigAlg; michael@0: PRBool preferSha1; michael@0: PRBool supportsSha1 = PR_FALSE; michael@0: PRBool supportsSha256 = PR_FALSE; michael@0: PRBool needBackupHash = PR_FALSE; michael@0: unsigned int i; michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: /* Backup handshake hash is not supported in PKCS #11 bypass mode. */ michael@0: if (ss->opt.bypassPKCS11) { michael@0: PORT_Assert(!ss->ssl3.hs.backupHash); michael@0: return; michael@0: } michael@0: #endif michael@0: PORT_Assert(ss->ssl3.hs.backupHash); michael@0: michael@0: /* Determine the key's signature algorithm and whether it prefers SHA-1. */ michael@0: rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1); michael@0: if (rv != SECSuccess) { michael@0: goto done; michael@0: } michael@0: michael@0: /* Determine the server's hash support for that signature algorithm. */ michael@0: for (i = 0; i < algorithms->len; i += 2) { michael@0: if (algorithms->data[i+1] == sigAlg) { michael@0: if (algorithms->data[i] == tls_hash_sha1) { michael@0: supportsSha1 = PR_TRUE; michael@0: } else if (algorithms->data[i] == tls_hash_sha256) { michael@0: supportsSha256 = PR_TRUE; michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* If either the server does not support SHA-256 or the client key prefers michael@0: * SHA-1, leave the backup hash. */ michael@0: if (supportsSha1 && (preferSha1 || !supportsSha256)) { michael@0: needBackupHash = PR_TRUE; michael@0: } michael@0: michael@0: done: michael@0: if (!needBackupHash) { michael@0: PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); michael@0: ss->ssl3.hs.backupHash = NULL; michael@0: } michael@0: } michael@0: michael@0: typedef struct dnameNode { michael@0: struct dnameNode *next; michael@0: SECItem name; michael@0: } dnameNode; michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 Certificate Request message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: PLArenaPool * arena = NULL; michael@0: dnameNode * node; michael@0: PRInt32 remaining; michael@0: PRBool isTLS = PR_FALSE; michael@0: PRBool isTLS12 = PR_FALSE; michael@0: int i; michael@0: int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; michael@0: int nnames = 0; michael@0: SECStatus rv; michael@0: SSL3AlertDescription desc = illegal_parameter; michael@0: SECItem cert_types = {siBuffer, NULL, 0}; michael@0: SECItem algorithms = {siBuffer, NULL, 0}; michael@0: CERTDistNames ca_list; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (ss->ssl3.hs.ws != wait_cert_request && michael@0: ss->ssl3.hs.ws != wait_server_key) { michael@0: desc = unexpected_message; michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: PORT_Assert(ss->ssl3.clientCertChain == NULL); michael@0: PORT_Assert(ss->ssl3.clientCertificate == NULL); michael@0: PORT_Assert(ss->ssl3.clientPrivateKey == NULL); michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length); michael@0: if (rv != SECSuccess) michael@0: goto loser; /* malformed, alert has been sent */ michael@0: michael@0: if (isTLS12) { michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); michael@0: if (rv != SECSuccess) michael@0: goto loser; /* malformed, alert has been sent */ michael@0: /* An empty or odd-length value is invalid. michael@0: * SignatureAndHashAlgorithm michael@0: * supported_signature_algorithms<2..2^16-2>; michael@0: */ michael@0: if (algorithms.len == 0 || (algorithms.len & 1) != 0) michael@0: goto alert_loser; michael@0: } michael@0: michael@0: arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); michael@0: if (arena == NULL) michael@0: goto no_mem; michael@0: michael@0: remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); michael@0: if (remaining < 0) michael@0: goto loser; /* malformed, alert has been sent */ michael@0: michael@0: if ((PRUint32)remaining > length) michael@0: goto alert_loser; michael@0: michael@0: ca_list.head = node = PORT_ArenaZNew(arena, dnameNode); michael@0: if (node == NULL) michael@0: goto no_mem; michael@0: michael@0: while (remaining > 0) { michael@0: PRInt32 len; michael@0: michael@0: if (remaining < 2) michael@0: goto alert_loser; /* malformed */ michael@0: michael@0: node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); michael@0: if (len <= 0) michael@0: goto loser; /* malformed, alert has been sent */ michael@0: michael@0: remaining -= 2; michael@0: if (remaining < len) michael@0: goto alert_loser; /* malformed */ michael@0: michael@0: node->name.data = b; michael@0: b += len; michael@0: length -= len; michael@0: remaining -= len; michael@0: nnames++; michael@0: if (remaining <= 0) michael@0: break; /* success */ michael@0: michael@0: node->next = PORT_ArenaZNew(arena, dnameNode); michael@0: node = node->next; michael@0: if (node == NULL) michael@0: goto no_mem; michael@0: } michael@0: michael@0: ca_list.nnames = nnames; michael@0: ca_list.names = PORT_ArenaNewArray(arena, SECItem, nnames); michael@0: if (nnames > 0 && ca_list.names == NULL) michael@0: goto no_mem; michael@0: michael@0: for(i = 0, node = (dnameNode*)ca_list.head; michael@0: i < nnames; michael@0: i++, node = node->next) { michael@0: ca_list.names[i] = node->name; michael@0: } michael@0: michael@0: if (length != 0) michael@0: goto alert_loser; /* malformed */ michael@0: michael@0: desc = no_certificate; michael@0: ss->ssl3.hs.ws = wait_hello_done; michael@0: michael@0: if (ss->getClientAuthData != NULL) { michael@0: /* XXX Should pass cert_types and algorithms in this call!! */ michael@0: rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg, michael@0: ss->fd, &ca_list, michael@0: &ss->ssl3.clientCertificate, michael@0: &ss->ssl3.clientPrivateKey); michael@0: } else { michael@0: rv = SECFailure; /* force it to send a no_certificate alert */ michael@0: } michael@0: switch (rv) { michael@0: case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ michael@0: ssl3_SetAlwaysBlock(ss); michael@0: break; /* not an error */ michael@0: michael@0: case SECSuccess: michael@0: /* check what the callback function returned */ michael@0: if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { michael@0: /* we are missing either the key or cert */ michael@0: if (ss->ssl3.clientCertificate) { michael@0: /* got a cert, but no key - free it */ michael@0: CERT_DestroyCertificate(ss->ssl3.clientCertificate); michael@0: ss->ssl3.clientCertificate = NULL; michael@0: } michael@0: if (ss->ssl3.clientPrivateKey) { michael@0: /* got a key, but no cert - free it */ michael@0: SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); michael@0: ss->ssl3.clientPrivateKey = NULL; michael@0: } michael@0: goto send_no_certificate; michael@0: } michael@0: /* Setting ssl3.clientCertChain non-NULL will cause michael@0: * ssl3_HandleServerHelloDone to call SendCertificate. michael@0: */ michael@0: ss->ssl3.clientCertChain = CERT_CertChainFromCert( michael@0: ss->ssl3.clientCertificate, michael@0: certUsageSSLClient, PR_FALSE); michael@0: if (ss->ssl3.clientCertChain == NULL) { michael@0: CERT_DestroyCertificate(ss->ssl3.clientCertificate); michael@0: ss->ssl3.clientCertificate = NULL; michael@0: SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); michael@0: ss->ssl3.clientPrivateKey = NULL; michael@0: goto send_no_certificate; michael@0: } michael@0: if (ss->ssl3.hs.hashType == handshake_hash_single) { michael@0: ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); michael@0: } michael@0: break; /* not an error */ michael@0: michael@0: case SECFailure: michael@0: default: michael@0: send_no_certificate: michael@0: if (isTLS) { michael@0: ss->ssl3.sendEmptyCert = PR_TRUE; michael@0: } else { michael@0: (void)SSL3_SendAlert(ss, alert_warning, no_certificate); michael@0: } michael@0: rv = SECSuccess; michael@0: break; michael@0: } michael@0: goto done; michael@0: michael@0: no_mem: michael@0: rv = SECFailure; michael@0: PORT_SetError(SEC_ERROR_NO_MEMORY); michael@0: goto done; michael@0: michael@0: alert_loser: michael@0: if (isTLS && desc == illegal_parameter) michael@0: desc = decode_error; michael@0: (void)SSL3_SendAlert(ss, alert_fatal, desc); michael@0: loser: michael@0: PORT_SetError(errCode); michael@0: rv = SECFailure; michael@0: done: michael@0: if (arena != NULL) michael@0: PORT_FreeArena(arena, PR_FALSE); michael@0: return rv; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_CheckFalseStart(sslSocket *ss) michael@0: { michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( !ss->ssl3.hs.authCertificatePending ); michael@0: PORT_Assert( !ss->ssl3.hs.canFalseStart ); michael@0: michael@0: if (!ss->canFalseStartCallback) { michael@0: SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", michael@0: SSL_GETPID(), ss->fd)); michael@0: } else { michael@0: PRBool maybeFalseStart; michael@0: SECStatus rv; michael@0: michael@0: /* An attacker can control the selected ciphersuite so we only wish to michael@0: * do False Start in the case that the selected ciphersuite is michael@0: * sufficiently strong that the attack can gain no advantage. michael@0: * Therefore we always require an 80-bit cipher. */ michael@0: ssl_GetSpecReadLock(ss); michael@0: maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10; michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: michael@0: if (!maybeFalseStart) { michael@0: SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", michael@0: SSL_GETPID(), ss->fd)); michael@0: } else { michael@0: rv = (ss->canFalseStartCallback)(ss->fd, michael@0: ss->canFalseStartCallbackData, michael@0: &ss->ssl3.hs.canFalseStart); michael@0: if (rv == SECSuccess) { michael@0: SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", michael@0: SSL_GETPID(), ss->fd, michael@0: ss->ssl3.hs.canFalseStart ? "TRUE" : "FALSE")); michael@0: } else { michael@0: SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", michael@0: SSL_GETPID(), ss->fd, michael@0: PR_ErrorToName(PR_GetError()))); michael@0: } michael@0: return rv; michael@0: } michael@0: } michael@0: michael@0: ss->ssl3.hs.canFalseStart = PR_FALSE; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: PRBool michael@0: ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss) michael@0: { michael@0: PRBool result; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: switch (ss->ssl3.hs.ws) { michael@0: case wait_new_session_ticket: michael@0: result = PR_TRUE; michael@0: break; michael@0: case wait_change_cipher: michael@0: result = !ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn); michael@0: break; michael@0: default: michael@0: result = PR_FALSE; michael@0: break; michael@0: } michael@0: michael@0: return result; michael@0: } michael@0: michael@0: static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 Server Hello Done message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleServerHelloDone(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: SSL3WaitState ws = ss->ssl3.hs.ws; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (ws != wait_hello_done && michael@0: ws != wait_server_cert && michael@0: ws != wait_server_key && michael@0: ws != wait_cert_request) { michael@0: SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: rv = ssl3_SendClientSecondRound(ss); michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete. michael@0: * michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_SendClientSecondRound(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: PRBool sendClientCert; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: sendClientCert = !ss->ssl3.sendEmptyCert && michael@0: ss->ssl3.clientCertChain != NULL && michael@0: ss->ssl3.clientPrivateKey != NULL; michael@0: michael@0: if (!sendClientCert && michael@0: ss->ssl3.hs.hashType == handshake_hash_single && michael@0: ss->ssl3.hs.backupHash) { michael@0: /* Don't need the backup handshake hash. */ michael@0: PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); michael@0: ss->ssl3.hs.backupHash = NULL; michael@0: } michael@0: michael@0: /* We must wait for the server's certificate to be authenticated before michael@0: * sending the client certificate in order to disclosing the client michael@0: * certificate to an attacker that does not have a valid cert for the michael@0: * domain we are connecting to. michael@0: * michael@0: * XXX: We should do the same for the NPN extension, but for that we michael@0: * need an option to give the application the ability to leak the NPN michael@0: * information to get better performance. michael@0: * michael@0: * During the initial handshake on a connection, we never send/receive michael@0: * application data until we have authenticated the server's certificate; michael@0: * i.e. we have fully authenticated the handshake before using the cipher michael@0: * specs agreed upon for that handshake. During a renegotiation, we may michael@0: * continue sending and receiving application data during the handshake michael@0: * interleaved with the handshake records. If we were to send the client's michael@0: * second round for a renegotiation before the server's certificate was michael@0: * authenticated, then the application data sent/received after this point michael@0: * would be using cipher spec that hadn't been authenticated. By waiting michael@0: * until the server's certificate has been authenticated during michael@0: * renegotiations, we ensure that renegotiations have the same property michael@0: * as initial handshakes; i.e. we have fully authenticated the handshake michael@0: * before using the cipher specs agreed upon for that handshake for michael@0: * application data. michael@0: */ michael@0: if (ss->ssl3.hs.restartTarget) { michael@0: PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: if (ss->ssl3.hs.authCertificatePending && michael@0: (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) { michael@0: SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" michael@0: " certificate authentication is still pending.", michael@0: SSL_GETPID(), ss->fd)); michael@0: ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; michael@0: return SECWouldBlock; michael@0: } michael@0: michael@0: ssl_GetXmitBufLock(ss); /*******************************/ michael@0: michael@0: if (ss->ssl3.sendEmptyCert) { michael@0: ss->ssl3.sendEmptyCert = PR_FALSE; michael@0: rv = ssl3_SendEmptyCertificate(ss); michael@0: /* Don't send verify */ michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* error code is set. */ michael@0: } michael@0: } else if (sendClientCert) { michael@0: rv = ssl3_SendCertificate(ss); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* error code is set. */ michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_SendClientKeyExchange(ss); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err is set. */ michael@0: } michael@0: michael@0: if (sendClientCert) { michael@0: rv = ssl3_SendCertificateVerify(ss); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err is set. */ michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_SendChangeCipherSpecs(ss); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err code was set. */ michael@0: } michael@0: michael@0: /* This must be done after we've set ss->ssl3.cwSpec in michael@0: * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information michael@0: * from cwSpec. This must be done before we call ssl3_CheckFalseStart michael@0: * because the false start callback (if any) may need the information from michael@0: * the functions that depend on this being set. michael@0: */ michael@0: ss->enoughFirstHsDone = PR_TRUE; michael@0: michael@0: if (!ss->firstHsDone) { michael@0: /* XXX: If the server's certificate hasn't been authenticated by this michael@0: * point, then we may be leaking this NPN message to an attacker. michael@0: */ michael@0: rv = ssl3_SendNextProto(ss); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err code was set. */ michael@0: } michael@0: michael@0: if (ss->opt.enableFalseStart) { michael@0: if (!ss->ssl3.hs.authCertificatePending) { michael@0: /* When we fix bug 589047, we will need to know whether we are michael@0: * false starting before we try to flush the client second michael@0: * round to the network. With that in mind, we purposefully michael@0: * call ssl3_CheckFalseStart before calling ssl3_SendFinished, michael@0: * which includes a call to ssl3_FlushHandshake, so that michael@0: * no application develops a reliance on such flushing being michael@0: * done before its false start callback is called. michael@0: */ michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: rv = ssl3_CheckFalseStart(ss); michael@0: ssl_GetXmitBufLock(ss); michael@0: if (rv != SECSuccess) { michael@0: goto loser; michael@0: } michael@0: } else { michael@0: /* The certificate authentication and the server's Finished michael@0: * message are racing each other. If the certificate michael@0: * authentication wins, then we will try to false start in michael@0: * ssl3_AuthCertificateComplete. michael@0: */ michael@0: SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" michael@0: " certificate authentication is still pending.", michael@0: SSL_GETPID(), ss->fd)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_SendFinished(ss, 0); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err code was set. */ michael@0: } michael@0: michael@0: ssl_ReleaseXmitBufLock(ss); /*******************************/ michael@0: michael@0: if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) michael@0: ss->ssl3.hs.ws = wait_new_session_ticket; michael@0: else michael@0: ss->ssl3.hs.ws = wait_change_cipher; michael@0: michael@0: PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss)); michael@0: michael@0: return SECSuccess; michael@0: michael@0: loser: michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * Routines used by servers michael@0: */ michael@0: static SECStatus michael@0: ssl3_SendHelloRequest(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), michael@0: ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake */ michael@0: } michael@0: rv = ssl3_FlushHandshake(ss, 0); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by ssl3_FlushHandshake */ michael@0: } michael@0: ss->ssl3.hs.ws = wait_client_hello; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* michael@0: * Called from: michael@0: * ssl3_HandleClientHello() michael@0: */ michael@0: static SECComparison michael@0: ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) michael@0: { michael@0: if (!name1 != !name2) { michael@0: return SECLessThan; michael@0: } michael@0: if (!name1) { michael@0: return SECEqual; michael@0: } michael@0: if (name1->type != name2->type) { michael@0: return SECLessThan; michael@0: } michael@0: return SECITEM_CompareItem(name1, name2); michael@0: } michael@0: michael@0: /* Sets memory error when returning NULL. michael@0: * Called from: michael@0: * ssl3_SendClientHello() michael@0: * ssl3_HandleServerHello() michael@0: * ssl3_HandleClientHello() michael@0: * ssl3_HandleV2ClientHello() michael@0: */ michael@0: sslSessionID * michael@0: ssl3_NewSessionID(sslSocket *ss, PRBool is_server) michael@0: { michael@0: sslSessionID *sid; michael@0: michael@0: sid = PORT_ZNew(sslSessionID); michael@0: if (sid == NULL) michael@0: return sid; michael@0: michael@0: if (is_server) { michael@0: const SECItem * srvName; michael@0: SECStatus rv = SECSuccess; michael@0: michael@0: ssl_GetSpecReadLock(ss); /********************************/ michael@0: srvName = &ss->ssl3.prSpec->srvVirtName; michael@0: if (srvName->len && srvName->data) { michael@0: rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); michael@0: } michael@0: ssl_ReleaseSpecReadLock(ss); /************************************/ michael@0: if (rv != SECSuccess) { michael@0: PORT_Free(sid); michael@0: return NULL; michael@0: } michael@0: } michael@0: sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); michael@0: sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); michael@0: sid->addr = ss->sec.ci.peer; michael@0: sid->port = ss->sec.ci.port; michael@0: sid->references = 1; michael@0: sid->cached = never_cached; michael@0: sid->version = ss->version; michael@0: michael@0: sid->u.ssl3.keys.resumable = PR_TRUE; michael@0: sid->u.ssl3.policy = SSL_ALLOWED; michael@0: sid->u.ssl3.clientWriteKey = NULL; michael@0: sid->u.ssl3.serverWriteKey = NULL; michael@0: michael@0: if (is_server) { michael@0: SECStatus rv; michael@0: int pid = SSL_GETPID(); michael@0: michael@0: sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; michael@0: sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; michael@0: sid->u.ssl3.sessionID[1] = pid & 0xff; michael@0: rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, michael@0: SSL3_SESSIONID_BYTES -2); michael@0: if (rv != SECSuccess) { michael@0: ssl_FreeSID(sid); michael@0: ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); michael@0: return NULL; michael@0: } michael@0: } michael@0: return sid; michael@0: } michael@0: michael@0: /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */ michael@0: static SECStatus michael@0: ssl3_SendServerHelloSequence(sslSocket *ss) michael@0: { michael@0: const ssl3KEADef *kea_def; michael@0: SECStatus rv; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); michael@0: michael@0: rv = ssl3_SendServerHello(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err code is set. */ michael@0: } michael@0: rv = ssl3_SendCertificate(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code is set. */ michael@0: } michael@0: rv = ssl3_SendCertificateStatus(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code is set. */ michael@0: } michael@0: /* We have to do this after the call to ssl3_SendServerHello, michael@0: * because kea_def is set up by ssl3_SendServerHello(). michael@0: */ michael@0: kea_def = ss->ssl3.hs.kea_def; michael@0: ss->ssl3.hs.usedStepDownKey = PR_FALSE; michael@0: michael@0: if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) { michael@0: /* see if we can legally use the key in the cert. */ michael@0: int keyLen; /* bytes */ michael@0: michael@0: keyLen = PK11_GetPrivateModulusLen( michael@0: ss->serverCerts[kea_def->exchKeyType].SERVERKEY); michael@0: michael@0: if (keyLen > 0 && michael@0: keyLen * BPB <= kea_def->key_size_limit ) { michael@0: /* XXX AND cert is not signing only!! */ michael@0: /* just fall through and use it. */ michael@0: } else if (ss->stepDownKeyPair != NULL) { michael@0: ss->ssl3.hs.usedStepDownKey = PR_TRUE; michael@0: rv = ssl3_SendServerKeyExchange(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err code was set. */ michael@0: } michael@0: } else { michael@0: #ifndef HACKED_EXPORT_SERVER michael@0: PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); michael@0: return rv; michael@0: #endif michael@0: } michael@0: #ifndef NSS_DISABLE_ECC michael@0: } else if ((kea_def->kea == kea_ecdhe_rsa) || michael@0: (kea_def->kea == kea_ecdhe_ecdsa)) { michael@0: rv = ssl3_SendServerKeyExchange(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err code was set. */ michael@0: } michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: } michael@0: michael@0: if (ss->opt.requestCertificate) { michael@0: rv = ssl3_SendCertificateRequest(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err code is set. */ michael@0: } michael@0: } michael@0: rv = ssl3_SendServerHelloDone(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err code is set. */ michael@0: } michael@0: michael@0: ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert michael@0: : wait_client_key; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* An empty TLS Renegotiation Info (RI) extension */ michael@0: static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00}; michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 Client Hello message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: sslSessionID * sid = NULL; michael@0: PRInt32 tmp; michael@0: unsigned int i; michael@0: int j; michael@0: SECStatus rv; michael@0: int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; michael@0: SSL3AlertDescription desc = illegal_parameter; michael@0: SSL3AlertLevel level = alert_fatal; michael@0: SSL3ProtocolVersion version; michael@0: SECItem sidBytes = {siBuffer, NULL, 0}; michael@0: SECItem cookieBytes = {siBuffer, NULL, 0}; michael@0: SECItem suites = {siBuffer, NULL, 0}; michael@0: SECItem comps = {siBuffer, NULL, 0}; michael@0: PRBool haveSpecWriteLock = PR_FALSE; michael@0: PRBool haveXmitBufLock = PR_FALSE; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: PORT_Assert( ss->ssl3.initialized ); michael@0: michael@0: /* Get peer name of client */ michael@0: rv = ssl_GetPeerInfo(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code is set. */ michael@0: } michael@0: michael@0: /* Clearing the handshake pointers so that ssl_Do1stHandshake won't michael@0: * call ssl2_HandleMessage. michael@0: * michael@0: * The issue here is that TLS ordinarily starts out in michael@0: * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility michael@0: * code paths. That function zeroes these next pointers. But with DTLS, michael@0: * we don't even try to do the v2 ClientHello so we skip that function michael@0: * and need to reset these values here. michael@0: */ michael@0: if (IS_DTLS(ss)) { michael@0: ss->nextHandshake = 0; michael@0: ss->securityHandshake = 0; michael@0: } michael@0: michael@0: /* We might be starting session renegotiation in which case we should michael@0: * clear previous state. michael@0: */ michael@0: PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); michael@0: ss->statelessResume = PR_FALSE; michael@0: michael@0: if ((ss->ssl3.hs.ws != wait_client_hello) && michael@0: (ss->ssl3.hs.ws != idle_handshake)) { michael@0: desc = unexpected_message; michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; michael@0: goto alert_loser; michael@0: } michael@0: if (ss->ssl3.hs.ws == idle_handshake && michael@0: ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { michael@0: desc = no_renegotiation; michael@0: level = alert_warning; michael@0: errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: dtls_RehandshakeCleanup(ss); michael@0: } michael@0: michael@0: tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); michael@0: if (tmp < 0) michael@0: goto loser; /* malformed, alert already sent */ michael@0: michael@0: /* Translate the version */ michael@0: if (IS_DTLS(ss)) { michael@0: ss->clientHelloVersion = version = michael@0: dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); michael@0: } else { michael@0: ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; michael@0: } michael@0: michael@0: rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); michael@0: if (rv != SECSuccess) { michael@0: desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version michael@0: : handshake_failure; michael@0: errCode = SSL_ERROR_NO_CYPHER_OVERLAP; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: rv = ssl3_InitHandshakeHashes(ss); michael@0: if (rv != SECSuccess) { michael@0: desc = internal_error; michael@0: errCode = PORT_GetError(); michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* grab the client random data. */ michael@0: rv = ssl3_ConsumeHandshake( michael@0: ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed */ michael@0: } michael@0: michael@0: /* grab the client's SID, if present. */ michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed */ michael@0: } michael@0: michael@0: /* grab the client's cookie, if present. */ michael@0: if (IS_DTLS(ss)) { michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed */ michael@0: } michael@0: } michael@0: michael@0: /* grab the list of cipher suites. */ michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed */ michael@0: } michael@0: michael@0: /* If the ClientHello version is less than our maximum version, check for a michael@0: * TLS_FALLBACK_SCSV and reject the connection if found. */ michael@0: if (ss->vrange.max > ss->clientHelloVersion) { michael@0: for (i = 0; i + 1 < suites.len; i += 2) { michael@0: PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; michael@0: if (suite_i != TLS_FALLBACK_SCSV) michael@0: continue; michael@0: desc = inappropriate_fallback; michael@0: errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; michael@0: goto alert_loser; michael@0: } michael@0: } michael@0: michael@0: /* grab the list of compression methods. */ michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed */ michael@0: } michael@0: michael@0: desc = handshake_failure; michael@0: michael@0: /* Handle TLS hello extensions for SSL3 & TLS. We do not know if michael@0: * we are restarting a previous session until extensions have been michael@0: * parsed, since we might have received a SessionTicket extension. michael@0: * Note: we allow extensions even when negotiating SSL3 for the sake michael@0: * of interoperability (and backwards compatibility). michael@0: */ michael@0: michael@0: if (length) { michael@0: /* Get length of hello extensions */ michael@0: PRInt32 extension_length; michael@0: extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); michael@0: if (extension_length < 0) { michael@0: goto loser; /* alert already sent */ michael@0: } michael@0: if (extension_length != length) { michael@0: ssl3_DecodeError(ss); /* send alert */ michael@0: goto loser; michael@0: } michael@0: rv = ssl3_HandleHelloExtensions(ss, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed */ michael@0: } michael@0: } michael@0: if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { michael@0: /* If we didn't receive an RI extension, look for the SCSV, michael@0: * and if found, treat it just like an empty RI extension michael@0: * by processing a local copy of an empty RI extension. michael@0: */ michael@0: for (i = 0; i + 1 < suites.len; i += 2) { michael@0: PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; michael@0: if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { michael@0: SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; michael@0: PRUint32 L2 = sizeof emptyRIext; michael@0: (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: if (ss->firstHsDone && michael@0: (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN || michael@0: ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && michael@0: !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { michael@0: desc = no_renegotiation; michael@0: level = alert_warning; michael@0: errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; michael@0: goto alert_loser; michael@0: } michael@0: if ((ss->opt.requireSafeNegotiation || michael@0: (ss->firstHsDone && ss->peerRequestedProtection)) && michael@0: !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { michael@0: desc = handshake_failure; michael@0: errCode = SSL_ERROR_UNSAFE_NEGOTIATION; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* We do stateful resumes only if either of the following michael@0: * conditions are satisfied: (1) the client does not support the michael@0: * session ticket extension, or (2) the client support the session michael@0: * ticket extension, but sent an empty ticket. michael@0: */ michael@0: if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) || michael@0: ss->xtnData.emptySessionTicket) { michael@0: if (sidBytes.len > 0 && !ss->opt.noCache) { michael@0: SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x", michael@0: SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], michael@0: ss->sec.ci.peer.pr_s6_addr32[1], michael@0: ss->sec.ci.peer.pr_s6_addr32[2], michael@0: ss->sec.ci.peer.pr_s6_addr32[3])); michael@0: if (ssl_sid_lookup) { michael@0: sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, michael@0: sidBytes.len, ss->dbHandle); michael@0: } else { michael@0: errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; michael@0: goto loser; michael@0: } michael@0: } michael@0: } else if (ss->statelessResume) { michael@0: /* Fill in the client's session ID if doing a stateless resume. michael@0: * (When doing stateless resumes, server echos client's SessionID.) michael@0: */ michael@0: sid = ss->sec.ci.sid; michael@0: PORT_Assert(sid != NULL); /* Should have already been filled in.*/ michael@0: michael@0: if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { michael@0: sid->u.ssl3.sessionIDLength = sidBytes.len; michael@0: PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, michael@0: sidBytes.len); michael@0: sid->u.ssl3.sessionIDLength = sidBytes.len; michael@0: } else { michael@0: sid->u.ssl3.sessionIDLength = 0; michael@0: } michael@0: ss->sec.ci.sid = NULL; michael@0: } michael@0: michael@0: /* We only send a session ticket extension if the client supports michael@0: * the extension and we are unable to do either a stateful or michael@0: * stateless resume. michael@0: * michael@0: * TODO: send a session ticket if performing a stateful michael@0: * resumption. (As per RFC4507, a server may issue a session michael@0: * ticket while doing a (stateless or stateful) session resume, michael@0: * but OpenSSL-0.9.8g does not accept session tickets while michael@0: * resuming.) michael@0: */ michael@0: if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) { michael@0: ssl3_RegisterServerHelloExtensionSender(ss, michael@0: ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn); michael@0: } michael@0: michael@0: if (sid != NULL) { michael@0: /* We've found a session cache entry for this client. michael@0: * Now, if we're going to require a client-auth cert, michael@0: * and we don't already have this client's cert in the session cache, michael@0: * and this is the first handshake on this connection (not a redo), michael@0: * then drop this old cache entry and start a new session. michael@0: */ michael@0: if ((sid->peerCert == NULL) && ss->opt.requestCertificate && michael@0: ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || michael@0: (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || michael@0: ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) michael@0: && !ss->firstHsDone))) { michael@0: michael@0: SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); michael@0: if (ss->sec.uncache) michael@0: ss->sec.uncache(sid); michael@0: ssl_FreeSID(sid); michael@0: sid = NULL; michael@0: } michael@0: } michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: /* Disable any ECC cipher suites for which we have no cert. */ michael@0: ssl3_FilterECCipherSuitesByServerCerts(ss); michael@0: #endif michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: ssl3_DisableNonDTLSSuites(ss); michael@0: } michael@0: michael@0: #ifdef PARANOID michael@0: /* Look for a matching cipher suite. */ michael@0: j = ssl3_config_match_init(ss); michael@0: if (j <= 0) { /* no ciphers are working/supported by PK11 */ michael@0: errCode = PORT_GetError(); /* error code is already set. */ michael@0: goto alert_loser; michael@0: } michael@0: #endif michael@0: michael@0: /* If we already have a session for this client, be sure to pick the michael@0: ** same cipher suite and compression method we picked before. michael@0: ** This is not a loop, despite appearances. michael@0: */ michael@0: if (sid) do { michael@0: ssl3CipherSuiteCfg *suite; michael@0: #ifdef PARANOID michael@0: SSLVersionRange vrange = {ss->version, ss->version}; michael@0: #endif michael@0: michael@0: /* Check that the cached compression method is still enabled. */ michael@0: if (!compressionEnabled(ss, sid->u.ssl3.compression)) michael@0: break; michael@0: michael@0: /* Check that the cached compression method is in the client's list */ michael@0: for (i = 0; i < comps.len; i++) { michael@0: if (comps.data[i] == sid->u.ssl3.compression) michael@0: break; michael@0: } michael@0: if (i == comps.len) michael@0: break; michael@0: michael@0: suite = ss->cipherSuites; michael@0: /* Find the entry for the cipher suite used in the cached session. */ michael@0: for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { michael@0: if (suite->cipher_suite == sid->u.ssl3.cipherSuite) michael@0: break; michael@0: } michael@0: PORT_Assert(j > 0); michael@0: if (j <= 0) michael@0: break; michael@0: #ifdef PARANOID michael@0: /* Double check that the cached cipher suite is still enabled, michael@0: * implemented, and allowed by policy. Might have been disabled. michael@0: * The product policy won't change during the process lifetime. michael@0: * Implemented ("isPresent") shouldn't change for servers. michael@0: */ michael@0: if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) michael@0: break; michael@0: #else michael@0: if (!suite->enabled) michael@0: break; michael@0: #endif michael@0: /* Double check that the cached cipher suite is in the client's list */ michael@0: for (i = 0; i + 1 < suites.len; i += 2) { michael@0: PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; michael@0: if (suite_i == suite->cipher_suite) { michael@0: ss->ssl3.hs.cipher_suite = suite->cipher_suite; michael@0: ss->ssl3.hs.suite_def = michael@0: ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); michael@0: michael@0: /* Use the cached compression method. */ michael@0: ss->ssl3.hs.compression = sid->u.ssl3.compression; michael@0: goto compression_found; michael@0: } michael@0: } michael@0: } while (0); michael@0: michael@0: /* START A NEW SESSION */ michael@0: michael@0: #ifndef PARANOID michael@0: /* Look for a matching cipher suite. */ michael@0: j = ssl3_config_match_init(ss); michael@0: if (j <= 0) { /* no ciphers are working/supported by PK11 */ michael@0: errCode = PORT_GetError(); /* error code is already set. */ michael@0: goto alert_loser; michael@0: } michael@0: #endif michael@0: michael@0: /* Select a cipher suite. michael@0: ** michael@0: ** NOTE: This suite selection algorithm should be the same as the one in michael@0: ** ssl3_HandleV2ClientHello(). michael@0: ** michael@0: ** If TLS 1.0 is enabled, we could handle the case where the client michael@0: ** offered TLS 1.1 but offered only export cipher suites by choosing TLS michael@0: ** 1.0 and selecting one of those export cipher suites. However, a secure michael@0: ** TLS 1.1 client should not have export cipher suites enabled at all, michael@0: ** and a TLS 1.1 client should definitely not be offering *only* export michael@0: ** cipher suites. Therefore, we refuse to negotiate export cipher suites michael@0: ** with any client that indicates support for TLS 1.1 or higher when we michael@0: ** (the server) have TLS 1.1 support enabled. michael@0: */ michael@0: for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { michael@0: ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; michael@0: SSLVersionRange vrange = {ss->version, ss->version}; michael@0: if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { michael@0: continue; michael@0: } michael@0: for (i = 0; i + 1 < suites.len; i += 2) { michael@0: PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; michael@0: if (suite_i == suite->cipher_suite) { michael@0: ss->ssl3.hs.cipher_suite = suite->cipher_suite; michael@0: ss->ssl3.hs.suite_def = michael@0: ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); michael@0: goto suite_found; michael@0: } michael@0: } michael@0: } michael@0: errCode = SSL_ERROR_NO_CYPHER_OVERLAP; michael@0: goto alert_loser; michael@0: michael@0: suite_found: michael@0: /* Select a compression algorithm. */ michael@0: for (i = 0; i < comps.len; i++) { michael@0: if (!compressionEnabled(ss, comps.data[i])) michael@0: continue; michael@0: for (j = 0; j < compressionMethodsCount; j++) { michael@0: if (comps.data[i] == compressions[j]) { michael@0: ss->ssl3.hs.compression = michael@0: (SSLCompressionMethod)compressions[j]; michael@0: goto compression_found; michael@0: } michael@0: } michael@0: } michael@0: errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; michael@0: /* null compression must be supported */ michael@0: goto alert_loser; michael@0: michael@0: compression_found: michael@0: suites.data = NULL; michael@0: comps.data = NULL; michael@0: michael@0: ss->sec.send = ssl3_SendApplicationData; michael@0: michael@0: /* If there are any failures while processing the old sid, michael@0: * we don't consider them to be errors. Instead, We just behave michael@0: * as if the client had sent us no sid to begin with, and make a new one. michael@0: */ michael@0: if (sid != NULL) do { michael@0: ssl3CipherSpec *pwSpec; michael@0: SECItem wrappedMS; /* wrapped key */ michael@0: michael@0: if (sid->version != ss->version || michael@0: sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || michael@0: sid->u.ssl3.compression != ss->ssl3.hs.compression) { michael@0: break; /* not an error */ michael@0: } michael@0: michael@0: if (ss->sec.ci.sid) { michael@0: if (ss->sec.uncache) michael@0: ss->sec.uncache(ss->sec.ci.sid); michael@0: PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */ michael@0: if (ss->sec.ci.sid != sid) { michael@0: ssl_FreeSID(ss->sec.ci.sid); michael@0: } michael@0: ss->sec.ci.sid = NULL; michael@0: } michael@0: /* we need to resurrect the master secret.... */ michael@0: michael@0: ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE; michael@0: pwSpec = ss->ssl3.pwSpec; michael@0: if (sid->u.ssl3.keys.msIsWrapped) { michael@0: PK11SymKey * wrapKey; /* wrapping key */ michael@0: CK_FLAGS keyFlags = 0; michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11) { michael@0: /* we cannot restart a non-bypass session in a michael@0: ** bypass socket. michael@0: */ michael@0: break; michael@0: } michael@0: #endif michael@0: michael@0: wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, michael@0: sid->u.ssl3.masterWrapMech, michael@0: ss->pkcs11PinArg); michael@0: if (!wrapKey) { michael@0: /* we have a SID cache entry, but no wrapping key for it??? */ michael@0: break; michael@0: } michael@0: michael@0: if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ michael@0: keyFlags = CKF_SIGN | CKF_VERIFY; michael@0: } michael@0: michael@0: wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; michael@0: wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; michael@0: michael@0: /* unwrap the master secret. */ michael@0: pwSpec->master_secret = michael@0: PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, michael@0: NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, michael@0: CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); michael@0: PK11_FreeSymKey(wrapKey); michael@0: if (pwSpec->master_secret == NULL) { michael@0: break; /* not an error */ michael@0: } michael@0: #ifndef NO_PKCS11_BYPASS michael@0: } else if (ss->opt.bypassPKCS11) { michael@0: wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; michael@0: wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; michael@0: memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); michael@0: pwSpec->msItem.data = pwSpec->raw_master_secret; michael@0: pwSpec->msItem.len = wrappedMS.len; michael@0: #endif michael@0: } else { michael@0: /* We CAN restart a bypass session in a non-bypass socket. */ michael@0: /* need to import the raw master secret to session object */ michael@0: PK11SlotInfo * slot; michael@0: wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; michael@0: wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; michael@0: slot = PK11_GetInternalSlot(); michael@0: pwSpec->master_secret = michael@0: PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, michael@0: PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, michael@0: NULL); michael@0: PK11_FreeSlot(slot); michael@0: if (pwSpec->master_secret == NULL) { michael@0: break; /* not an error */ michael@0: } michael@0: } michael@0: ss->sec.ci.sid = sid; michael@0: if (sid->peerCert != NULL) { michael@0: ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); michael@0: } michael@0: michael@0: /* michael@0: * Old SID passed all tests, so resume this old session. michael@0: * michael@0: * XXX make sure compression still matches michael@0: */ michael@0: SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits ); michael@0: if (ss->statelessResume) michael@0: SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes ); michael@0: ss->ssl3.hs.isResuming = PR_TRUE; michael@0: michael@0: ss->sec.authAlgorithm = sid->authAlgorithm; michael@0: ss->sec.authKeyBits = sid->authKeyBits; michael@0: ss->sec.keaType = sid->keaType; michael@0: ss->sec.keaKeyBits = sid->keaKeyBits; michael@0: michael@0: /* server sids don't remember the server cert we previously sent, michael@0: ** but they do remember the kea type we originally used, so we michael@0: ** can locate it again, provided that the current ssl socket michael@0: ** has had its server certs configured the same as the previous one. michael@0: */ michael@0: ss->sec.localCert = michael@0: CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert); michael@0: michael@0: /* Copy cached name in to pending spec */ michael@0: if (sid != NULL && michael@0: sid->version > SSL_LIBRARY_VERSION_3_0 && michael@0: sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { michael@0: /* Set server name from sid */ michael@0: SECItem *sidName = &sid->u.ssl3.srvName; michael@0: SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName; michael@0: if (pwsName->data) { michael@0: SECITEM_FreeItem(pwsName, PR_FALSE); michael@0: } michael@0: rv = SECITEM_CopyItem(NULL, pwsName, sidName); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: desc = internal_error; michael@0: goto alert_loser; michael@0: } michael@0: } michael@0: michael@0: /* Clean up sni name array */ michael@0: if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && michael@0: ss->xtnData.sniNameArr) { michael@0: PORT_Free(ss->xtnData.sniNameArr); michael@0: ss->xtnData.sniNameArr = NULL; michael@0: ss->xtnData.sniNameArrSize = 0; michael@0: } michael@0: michael@0: ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE; michael@0: michael@0: rv = ssl3_SendServerHello(ss); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: michael@0: if (haveSpecWriteLock) { michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: haveSpecWriteLock = PR_FALSE; michael@0: } michael@0: michael@0: /* NULL value for PMS signifies re-use of the old MS */ michael@0: rv = ssl3_InitPendingCipherSpec(ss, NULL); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: michael@0: rv = ssl3_SendChangeCipherSpecs(ss); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: rv = ssl3_SendFinished(ss, 0); michael@0: ss->ssl3.hs.ws = wait_change_cipher; michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: michael@0: if (haveXmitBufLock) { michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: haveXmitBufLock = PR_FALSE; michael@0: } michael@0: michael@0: return SECSuccess; michael@0: } while (0); michael@0: michael@0: if (haveSpecWriteLock) { michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: haveSpecWriteLock = PR_FALSE; michael@0: } michael@0: michael@0: if (sid) { /* we had a sid, but it's no longer valid, free it */ michael@0: SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); michael@0: if (ss->sec.uncache) michael@0: ss->sec.uncache(sid); michael@0: ssl_FreeSID(sid); michael@0: sid = NULL; michael@0: } michael@0: SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); michael@0: michael@0: if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { michael@0: int ret = 0; michael@0: if (ss->sniSocketConfig) do { /* not a loop */ michael@0: ret = SSL_SNI_SEND_ALERT; michael@0: /* If extension is negotiated, the len of names should > 0. */ michael@0: if (ss->xtnData.sniNameArrSize) { michael@0: /* Calling client callback to reconfigure the socket. */ michael@0: ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd, michael@0: ss->xtnData.sniNameArr, michael@0: ss->xtnData.sniNameArrSize, michael@0: ss->sniSocketConfigArg); michael@0: } michael@0: if (ret <= SSL_SNI_SEND_ALERT) { michael@0: /* Application does not know the name or was not able to michael@0: * properly reconfigure the socket. */ michael@0: errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; michael@0: desc = unrecognized_name; michael@0: break; michael@0: } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { michael@0: SECStatus rv = SECSuccess; michael@0: SECItem * cwsName, *pwsName; michael@0: michael@0: ssl_GetSpecWriteLock(ss); /*******************************/ michael@0: pwsName = &ss->ssl3.pwSpec->srvVirtName; michael@0: cwsName = &ss->ssl3.cwSpec->srvVirtName; michael@0: #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS michael@0: /* not allow name change on the 2d HS */ michael@0: if (ss->firstHsDone) { michael@0: if (ssl3_ServerNameCompare(pwsName, cwsName)) { michael@0: ssl_ReleaseSpecWriteLock(ss); /******************/ michael@0: errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; michael@0: desc = handshake_failure; michael@0: ret = SSL_SNI_SEND_ALERT; michael@0: break; michael@0: } michael@0: } michael@0: #endif michael@0: if (pwsName->data) { michael@0: SECITEM_FreeItem(pwsName, PR_FALSE); michael@0: } michael@0: if (cwsName->data) { michael@0: rv = SECITEM_CopyItem(NULL, pwsName, cwsName); michael@0: } michael@0: ssl_ReleaseSpecWriteLock(ss); /**************************/ michael@0: if (rv != SECSuccess) { michael@0: errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; michael@0: desc = internal_error; michael@0: ret = SSL_SNI_SEND_ALERT; michael@0: break; michael@0: } michael@0: } else if (ret < ss->xtnData.sniNameArrSize) { michael@0: /* Application has configured new socket info. Lets check it michael@0: * and save the name. */ michael@0: SECStatus rv; michael@0: SECItem * name = &ss->xtnData.sniNameArr[ret]; michael@0: int configedCiphers; michael@0: SECItem * pwsName; michael@0: michael@0: /* get rid of the old name and save the newly picked. */ michael@0: /* This code is protected by ssl3HandshakeLock. */ michael@0: ssl_GetSpecWriteLock(ss); /*******************************/ michael@0: #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS michael@0: /* not allow name change on the 2d HS */ michael@0: if (ss->firstHsDone) { michael@0: SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName; michael@0: if (ssl3_ServerNameCompare(name, cwsName)) { michael@0: ssl_ReleaseSpecWriteLock(ss); /******************/ michael@0: errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; michael@0: desc = handshake_failure; michael@0: ret = SSL_SNI_SEND_ALERT; michael@0: break; michael@0: } michael@0: } michael@0: #endif michael@0: pwsName = &ss->ssl3.pwSpec->srvVirtName; michael@0: if (pwsName->data) { michael@0: SECITEM_FreeItem(pwsName, PR_FALSE); michael@0: } michael@0: rv = SECITEM_CopyItem(NULL, pwsName, name); michael@0: ssl_ReleaseSpecWriteLock(ss); /***************************/ michael@0: if (rv != SECSuccess) { michael@0: errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; michael@0: desc = internal_error; michael@0: ret = SSL_SNI_SEND_ALERT; michael@0: break; michael@0: } michael@0: configedCiphers = ssl3_config_match_init(ss); michael@0: if (configedCiphers <= 0) { michael@0: /* no ciphers are working/supported */ michael@0: errCode = PORT_GetError(); michael@0: desc = handshake_failure; michael@0: ret = SSL_SNI_SEND_ALERT; michael@0: break; michael@0: } michael@0: /* Need to tell the client that application has picked michael@0: * the name from the offered list and reconfigured the socket. michael@0: */ michael@0: ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn, michael@0: ssl3_SendServerNameXtn); michael@0: } else { michael@0: /* Callback returned index outside of the boundary. */ michael@0: PORT_Assert(ret < ss->xtnData.sniNameArrSize); michael@0: errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; michael@0: desc = internal_error; michael@0: ret = SSL_SNI_SEND_ALERT; michael@0: break; michael@0: } michael@0: } while (0); michael@0: /* Free sniNameArr. The data that each SECItem in the array michael@0: * points into is the data from the input buffer "b". It will michael@0: * not be available outside the scope of this or it's child michael@0: * functions.*/ michael@0: if (ss->xtnData.sniNameArr) { michael@0: PORT_Free(ss->xtnData.sniNameArr); michael@0: ss->xtnData.sniNameArr = NULL; michael@0: ss->xtnData.sniNameArrSize = 0; michael@0: } michael@0: if (ret <= SSL_SNI_SEND_ALERT) { michael@0: /* desc and errCode should be set. */ michael@0: goto alert_loser; michael@0: } michael@0: } michael@0: #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS michael@0: else if (ss->firstHsDone) { michael@0: /* Check that we don't have the name is current spec michael@0: * if this extension was not negotiated on the 2d hs. */ michael@0: PRBool passed = PR_TRUE; michael@0: ssl_GetSpecReadLock(ss); /*******************************/ michael@0: if (ss->ssl3.cwSpec->srvVirtName.data) { michael@0: passed = PR_FALSE; michael@0: } michael@0: ssl_ReleaseSpecReadLock(ss); /***************************/ michael@0: if (!passed) { michael@0: errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; michael@0: desc = handshake_failure; michael@0: goto alert_loser; michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: sid = ssl3_NewSessionID(ss, PR_TRUE); michael@0: if (sid == NULL) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; /* memory error is set. */ michael@0: } michael@0: ss->sec.ci.sid = sid; michael@0: michael@0: ss->ssl3.hs.isResuming = PR_FALSE; michael@0: ssl_GetXmitBufLock(ss); michael@0: rv = ssl3_SendServerHelloSequence(ss); michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: michael@0: if (haveXmitBufLock) { michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: haveXmitBufLock = PR_FALSE; michael@0: } michael@0: michael@0: return SECSuccess; michael@0: michael@0: alert_loser: michael@0: if (haveSpecWriteLock) { michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: haveSpecWriteLock = PR_FALSE; michael@0: } michael@0: (void)SSL3_SendAlert(ss, level, desc); michael@0: /* FALLTHRU */ michael@0: loser: michael@0: if (haveSpecWriteLock) { michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: haveSpecWriteLock = PR_FALSE; michael@0: } michael@0: michael@0: if (haveXmitBufLock) { michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: haveXmitBufLock = PR_FALSE; michael@0: } michael@0: michael@0: PORT_SetError(errCode); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* michael@0: * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes michael@0: * in asking to use the V3 handshake. michael@0: * Called from ssl2_HandleClientHelloMessage() in sslcon.c michael@0: */ michael@0: SECStatus michael@0: ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) michael@0: { michael@0: sslSessionID * sid = NULL; michael@0: unsigned char * suites; michael@0: unsigned char * random; michael@0: SSL3ProtocolVersion version; michael@0: SECStatus rv; michael@0: int i; michael@0: int j; michael@0: int sid_length; michael@0: int suite_length; michael@0: int rand_length; michael@0: int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; michael@0: SSL3AlertDescription desc = handshake_failure; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: michael@0: ssl_GetSSL3HandshakeLock(ss); michael@0: michael@0: PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); michael@0: michael@0: rv = ssl3_InitState(ss); michael@0: if (rv != SECSuccess) { michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: return rv; /* ssl3_InitState has set the error code. */ michael@0: } michael@0: rv = ssl3_RestartHandshakeHashes(ss); michael@0: if (rv != SECSuccess) { michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: return rv; michael@0: } michael@0: michael@0: if (ss->ssl3.hs.ws != wait_client_hello) { michael@0: desc = unexpected_message; michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; michael@0: goto loser; /* alert_loser */ michael@0: } michael@0: michael@0: version = (buffer[1] << 8) | buffer[2]; michael@0: suite_length = (buffer[3] << 8) | buffer[4]; michael@0: sid_length = (buffer[5] << 8) | buffer[6]; michael@0: rand_length = (buffer[7] << 8) | buffer[8]; michael@0: ss->clientHelloVersion = version; michael@0: michael@0: rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); michael@0: if (rv != SECSuccess) { michael@0: /* send back which ever alert client will understand. */ michael@0: desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure; michael@0: errCode = SSL_ERROR_NO_CYPHER_OVERLAP; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: rv = ssl3_InitHandshakeHashes(ss); michael@0: if (rv != SECSuccess) { michael@0: desc = internal_error; michael@0: errCode = PORT_GetError(); michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* if we get a non-zero SID, just ignore it. */ michael@0: if (length != michael@0: SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) { michael@0: SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", michael@0: SSL_GETPID(), ss->fd, length, michael@0: SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + michael@0: rand_length)); michael@0: goto loser; /* malformed */ /* alert_loser */ michael@0: } michael@0: michael@0: suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES; michael@0: random = suites + suite_length + sid_length; michael@0: michael@0: if (rand_length < SSL_MIN_CHALLENGE_BYTES || michael@0: rand_length > SSL_MAX_CHALLENGE_BYTES) { michael@0: goto loser; /* malformed */ /* alert_loser */ michael@0: } michael@0: michael@0: PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH); michael@0: michael@0: PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); michael@0: PORT_Memcpy( michael@0: &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], michael@0: random, rand_length); michael@0: michael@0: PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0], michael@0: SSL3_RANDOM_LENGTH)); michael@0: #ifndef NSS_DISABLE_ECC michael@0: /* Disable any ECC cipher suites for which we have no cert. */ michael@0: ssl3_FilterECCipherSuitesByServerCerts(ss); michael@0: #endif michael@0: i = ssl3_config_match_init(ss); michael@0: if (i <= 0) { michael@0: errCode = PORT_GetError(); /* error code is already set. */ michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* Select a cipher suite. michael@0: ** michael@0: ** NOTE: This suite selection algorithm should be the same as the one in michael@0: ** ssl3_HandleClientHello(). michael@0: ** michael@0: ** See the comments about export cipher suites in ssl3_HandleClientHello(). michael@0: */ michael@0: for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { michael@0: ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; michael@0: SSLVersionRange vrange = {ss->version, ss->version}; michael@0: if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { michael@0: continue; michael@0: } michael@0: for (i = 0; i+2 < suite_length; i += 3) { michael@0: PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2]; michael@0: if (suite_i == suite->cipher_suite) { michael@0: ss->ssl3.hs.cipher_suite = suite->cipher_suite; michael@0: ss->ssl3.hs.suite_def = michael@0: ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); michael@0: goto suite_found; michael@0: } michael@0: } michael@0: } michael@0: errCode = SSL_ERROR_NO_CYPHER_OVERLAP; michael@0: goto alert_loser; michael@0: michael@0: suite_found: michael@0: michael@0: /* Look for the SCSV, and if found, treat it just like an empty RI michael@0: * extension by processing a local copy of an empty RI extension. michael@0: */ michael@0: for (i = 0; i+2 < suite_length; i += 3) { michael@0: PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2]; michael@0: if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { michael@0: SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; michael@0: PRUint32 L2 = sizeof emptyRIext; michael@0: (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (ss->opt.requireSafeNegotiation && michael@0: !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { michael@0: desc = handshake_failure; michael@0: errCode = SSL_ERROR_UNSAFE_NEGOTIATION; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: ss->ssl3.hs.compression = ssl_compression_null; michael@0: ss->sec.send = ssl3_SendApplicationData; michael@0: michael@0: /* we don't even search for a cache hit here. It's just a miss. */ michael@0: SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); michael@0: sid = ssl3_NewSessionID(ss, PR_TRUE); michael@0: if (sid == NULL) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; /* memory error is set. */ michael@0: } michael@0: ss->sec.ci.sid = sid; michael@0: /* do not worry about memory leak of sid since it now belongs to ci */ michael@0: michael@0: /* We have to update the handshake hashes before we can send stuff */ michael@0: rv = ssl3_UpdateHandshakeHashes(ss, buffer, length); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: michael@0: ssl_GetXmitBufLock(ss); michael@0: rv = ssl3_SendServerHelloSequence(ss); michael@0: ssl_ReleaseXmitBufLock(ss); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: michael@0: /* XXX_1 The call stack to here is: michael@0: * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here. michael@0: * ssl2_HandleClientHelloMessage returns whatever we return here. michael@0: * ssl_Do1stHandshake will continue looping if it gets back either michael@0: * SECSuccess or SECWouldBlock. michael@0: * SECSuccess is preferable here. See XXX_1 in sslgathr.c. michael@0: */ michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: return SECSuccess; michael@0: michael@0: alert_loser: michael@0: SSL3_SendAlert(ss, alert_fatal, desc); michael@0: loser: michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: PORT_SetError(errCode); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* The negotiated version number has been already placed in ss->version. michael@0: ** michael@0: ** Called from: ssl3_HandleClientHello (resuming session), michael@0: ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), michael@0: ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) michael@0: */ michael@0: static SECStatus michael@0: ssl3_SendServerHello(sslSocket *ss) michael@0: { michael@0: sslSessionID *sid; michael@0: SECStatus rv; michael@0: PRUint32 maxBytes = 65535; michael@0: PRUint32 length; michael@0: PRInt32 extensions_len = 0; michael@0: SSL3ProtocolVersion version; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), michael@0: ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: if (!IS_DTLS(ss)) { michael@0: PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); michael@0: michael@0: if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { michael@0: PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); michael@0: return SECFailure; michael@0: } michael@0: } else { michael@0: PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); michael@0: michael@0: if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { michael@0: PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: sid = ss->sec.ci.sid; michael@0: michael@0: extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, michael@0: &ss->xtnData.serverSenders[0]); michael@0: if (extensions_len > 0) michael@0: extensions_len += 2; /* Add sizeof total extension length */ michael@0: michael@0: length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 + michael@0: ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) + michael@0: sizeof(ssl3CipherSuite) + 1 + extensions_len; michael@0: rv = ssl3_AppendHandshakeHeader(ss, server_hello, length); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: version = dtls_TLSVersionToDTLSVersion(ss->version); michael@0: } else { michael@0: version = ss->version; michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeNumber(ss, version, 2); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); michael@0: return rv; michael@0: } michael@0: rv = ssl3_AppendHandshake( michael@0: ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: michael@0: if (sid) michael@0: rv = ssl3_AppendHandshakeVariable( michael@0: ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); michael@0: else michael@0: rv = ssl3_AppendHandshakeNumber(ss, 0, 1); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: if (extensions_len) { michael@0: PRInt32 sent_len; michael@0: michael@0: extensions_len -= 2; michael@0: rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); michael@0: if (rv != SECSuccess) michael@0: return rv; /* err set by ssl3_SetupPendingCipherSpec */ michael@0: sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, michael@0: &ss->xtnData.serverSenders[0]); michael@0: PORT_Assert(sent_len == extensions_len); michael@0: if (sent_len != extensions_len) { michael@0: if (sent_len >= 0) michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: rv = ssl3_SetupPendingCipherSpec(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by ssl3_SetupPendingCipherSpec */ michael@0: } michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing michael@0: * elements of the handshake. (The negotiated cipher suite determines the michael@0: * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always michael@0: * used. With TLS 1.2, a client may advertise its support for signature and michael@0: * hash combinations. */ michael@0: static SECStatus michael@0: ssl3_PickSignatureHashAlgorithm(sslSocket *ss, michael@0: SSL3SignatureAndHashAlgorithm* out) michael@0: { michael@0: TLSSignatureAlgorithm sigAlg; michael@0: unsigned int i, j; michael@0: /* hashPreference expresses our preferences for hash algorithms, most michael@0: * preferable first. */ michael@0: static const PRUint8 hashPreference[] = { michael@0: tls_hash_sha256, michael@0: tls_hash_sha384, michael@0: tls_hash_sha512, michael@0: tls_hash_sha1, michael@0: }; michael@0: michael@0: switch (ss->ssl3.hs.kea_def->kea) { michael@0: case kea_rsa: michael@0: case kea_rsa_export: michael@0: case kea_rsa_export_1024: michael@0: case kea_dh_rsa: michael@0: case kea_dh_rsa_export: michael@0: case kea_dhe_rsa: michael@0: case kea_dhe_rsa_export: michael@0: case kea_rsa_fips: michael@0: case kea_ecdh_rsa: michael@0: case kea_ecdhe_rsa: michael@0: sigAlg = tls_sig_rsa; michael@0: break; michael@0: case kea_dh_dss: michael@0: case kea_dh_dss_export: michael@0: case kea_dhe_dss: michael@0: case kea_dhe_dss_export: michael@0: sigAlg = tls_sig_dsa; michael@0: break; michael@0: case kea_ecdh_ecdsa: michael@0: case kea_ecdhe_ecdsa: michael@0: sigAlg = tls_sig_ecdsa; michael@0: break; michael@0: default: michael@0: PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); michael@0: return SECFailure; michael@0: } michael@0: out->sigAlg = sigAlg; michael@0: michael@0: if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) { michael@0: /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and michael@0: * prior. */ michael@0: out->hashAlg = SEC_OID_UNKNOWN; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: if (ss->ssl3.hs.numClientSigAndHash == 0) { michael@0: /* If the client didn't provide any signature_algorithms extension then michael@0: * we can assume that they support SHA-1: michael@0: * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ michael@0: out->hashAlg = SEC_OID_SHA1; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) { michael@0: for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) { michael@0: const SSL3SignatureAndHashAlgorithm* sh = michael@0: &ss->ssl3.hs.clientSigAndHash[j]; michael@0: if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) { michael@0: out->hashAlg = sh->hashAlg; michael@0: return SECSuccess; michael@0: } michael@0: } michael@0: } michael@0: michael@0: PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); michael@0: return SECFailure; michael@0: } michael@0: michael@0: michael@0: static SECStatus michael@0: ssl3_SendServerKeyExchange(sslSocket *ss) michael@0: { michael@0: const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; michael@0: SECStatus rv = SECFailure; michael@0: int length; michael@0: PRBool isTLS; michael@0: SECItem signed_hash = {siBuffer, NULL, 0}; michael@0: SSL3Hashes hashes; michael@0: SECKEYPublicKey * sdPub; /* public key for step-down */ michael@0: SSL3SignatureAndHashAlgorithm sigAndHash; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { michael@0: return SECFailure; michael@0: } michael@0: michael@0: switch (kea_def->exchKeyType) { michael@0: case kt_rsa: michael@0: /* Perform SSL Step-Down here. */ michael@0: sdPub = ss->stepDownKeyPair->pubKey; michael@0: PORT_Assert(sdPub != NULL); michael@0: if (!sdPub) { michael@0: PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, michael@0: sdPub->u.rsa.modulus, michael@0: sdPub->u.rsa.publicExponent, michael@0: &ss->ssl3.hs.client_random, michael@0: &ss->ssl3.hs.server_random, michael@0: &hashes, ss->opt.bypassPKCS11); michael@0: if (rv != SECSuccess) { michael@0: ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: return rv; michael@0: } michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, michael@0: &signed_hash, isTLS); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* ssl3_SignHashes has set err. */ michael@0: } michael@0: if (signed_hash.data == NULL) { michael@0: /* how can this happen and rv == SECSuccess ?? */ michael@0: PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); michael@0: goto loser; michael@0: } michael@0: length = 2 + sdPub->u.rsa.modulus.len + michael@0: 2 + sdPub->u.rsa.publicExponent.len + michael@0: 2 + signed_hash.len; michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by AppendHandshake. */ michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, michael@0: sdPub->u.rsa.modulus.len, 2); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by AppendHandshake. */ michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeVariable( michael@0: ss, sdPub->u.rsa.publicExponent.data, michael@0: sdPub->u.rsa.publicExponent.len, 2); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by AppendHandshake. */ michael@0: } michael@0: michael@0: if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { michael@0: rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by AppendHandshake. */ michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, michael@0: signed_hash.len, 2); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* err set by AppendHandshake. */ michael@0: } michael@0: PORT_Free(signed_hash.data); michael@0: return SECSuccess; michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: case kt_ecdh: { michael@0: rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); michael@0: return rv; michael@0: } michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: case kt_dh: michael@0: case kt_null: michael@0: default: michael@0: PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); michael@0: break; michael@0: } michael@0: loser: michael@0: if (signed_hash.data != NULL) michael@0: PORT_Free(signed_hash.data); michael@0: return SECFailure; michael@0: } michael@0: michael@0: michael@0: static SECStatus michael@0: ssl3_SendCertificateRequest(sslSocket *ss) michael@0: { michael@0: PRBool isTLS12; michael@0: SECItem * name; michael@0: CERTDistNames *ca_list; michael@0: const PRUint8 *certTypes; michael@0: const PRUint8 *sigAlgs; michael@0: SECItem * names = NULL; michael@0: SECStatus rv; michael@0: int length; michael@0: int i; michael@0: int calen = 0; michael@0: int nnames = 0; michael@0: int certTypesLength; michael@0: int sigAlgsLength; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); michael@0: michael@0: /* ssl3.ca_list is initialized to NULL, and never changed. */ michael@0: ca_list = ss->ssl3.ca_list; michael@0: if (!ca_list) { michael@0: ca_list = ssl3_server_ca_list; michael@0: } michael@0: michael@0: if (ca_list != NULL) { michael@0: names = ca_list->names; michael@0: nnames = ca_list->nnames; michael@0: } michael@0: michael@0: for (i = 0, name = names; i < nnames; i++, name++) { michael@0: calen += 2 + name->len; michael@0: } michael@0: michael@0: certTypes = certificate_types; michael@0: certTypesLength = sizeof certificate_types; michael@0: sigAlgs = supported_signature_algorithms; michael@0: sigAlgsLength = sizeof supported_signature_algorithms; michael@0: michael@0: length = 1 + certTypesLength + 2 + calen; michael@0: if (isTLS12) { michael@0: length += 2 + sigAlgsLength; michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: if (isTLS12) { michael@0: rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: } michael@0: rv = ssl3_AppendHandshakeNumber(ss, calen, 2); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: for (i = 0, name = names; i < nnames; i++, name++) { michael@0: rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: } michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_SendServerHelloDone(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: rv = ssl3_FlushHandshake(ss, 0); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by ssl3_FlushHandshake */ michael@0: } michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 Certificate Verify message michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length, michael@0: SSL3Hashes *hashes) michael@0: { michael@0: SECItem signed_hash = {siBuffer, NULL, 0}; michael@0: SECStatus rv; michael@0: int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; michael@0: SSL3AlertDescription desc = handshake_failure; michael@0: PRBool isTLS, isTLS12; michael@0: SSL3SignatureAndHashAlgorithm sigAndHash; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); michael@0: michael@0: if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) { michael@0: desc = unexpected_message; michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: if (isTLS12) { michael@0: rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, michael@0: &sigAndHash); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed or unsupported. */ michael@0: } michael@0: rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( michael@0: &sigAndHash, ss->sec.peerCert); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: desc = decrypt_error; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: /* We only support CertificateVerify messages that use the handshake michael@0: * hash. */ michael@0: if (sigAndHash.hashAlg != hashes->hashAlg) { michael@0: errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; michael@0: desc = decrypt_error; michael@0: goto alert_loser; michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); michael@0: if (rv != SECSuccess) { michael@0: goto loser; /* malformed. */ michael@0: } michael@0: michael@0: /* XXX verify that the key & kea match */ michael@0: rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash, michael@0: isTLS, ss->pkcs11PinArg); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: desc = isTLS ? decrypt_error : handshake_failure; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: signed_hash.data = NULL; michael@0: michael@0: if (length != 0) { michael@0: desc = isTLS ? decode_error : illegal_parameter; michael@0: goto alert_loser; /* malformed */ michael@0: } michael@0: ss->ssl3.hs.ws = wait_change_cipher; michael@0: return SECSuccess; michael@0: michael@0: alert_loser: michael@0: SSL3_SendAlert(ss, alert_fatal, desc); michael@0: loser: michael@0: PORT_SetError(errCode); michael@0: return SECFailure; michael@0: } michael@0: michael@0: michael@0: /* find a slot that is able to generate a PMS and wrap it with RSA. michael@0: * Then generate and return the PMS. michael@0: * If the serverKeySlot parameter is non-null, this function will use michael@0: * that slot to do the job, otherwise it will find a slot. michael@0: * michael@0: * Called from ssl3_DeriveConnectionKeysPKCS11() (above) michael@0: * sendRSAClientKeyExchange() (above) michael@0: * ssl3_HandleRSAClientKeyExchange() (below) michael@0: * Caller must hold the SpecWriteLock, the SSL3HandshakeLock michael@0: */ michael@0: static PK11SymKey * michael@0: ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, michael@0: PK11SlotInfo * serverKeySlot) michael@0: { michael@0: PK11SymKey * pms = NULL; michael@0: PK11SlotInfo * slot = serverKeySlot; michael@0: void * pwArg = ss->pkcs11PinArg; michael@0: SECItem param; michael@0: CK_VERSION version; michael@0: CK_MECHANISM_TYPE mechanism_array[3]; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (slot == NULL) { michael@0: SSLCipherAlgorithm calg; michael@0: /* The specReadLock would suffice here, but we cannot assert on michael@0: ** read locks. Also, all the callers who call with a non-null michael@0: ** slot already hold the SpecWriteLock. michael@0: */ michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); michael@0: PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); michael@0: michael@0: calg = spec->cipher_def->calg; michael@0: PORT_Assert(alg2Mech[calg].calg == calg); michael@0: michael@0: /* First get an appropriate slot. */ michael@0: mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; michael@0: mechanism_array[1] = CKM_RSA_PKCS; michael@0: mechanism_array[2] = alg2Mech[calg].cmech; michael@0: michael@0: slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); michael@0: if (slot == NULL) { michael@0: /* can't find a slot with all three, find a slot with the minimum */ michael@0: slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); michael@0: if (slot == NULL) { michael@0: PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); michael@0: return pms; /* which is NULL */ michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* Generate the pre-master secret ... */ michael@0: if (IS_DTLS(ss)) { michael@0: SSL3ProtocolVersion temp; michael@0: michael@0: temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); michael@0: version.major = MSB(temp); michael@0: version.minor = LSB(temp); michael@0: } else { michael@0: version.major = MSB(ss->clientHelloVersion); michael@0: version.minor = LSB(ss->clientHelloVersion); michael@0: } michael@0: michael@0: param.data = (unsigned char *)&version; michael@0: param.len = sizeof version; michael@0: michael@0: pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); michael@0: if (!serverKeySlot) michael@0: PK11_FreeSlot(slot); michael@0: if (pms == NULL) { michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: } michael@0: return pms; michael@0: } michael@0: michael@0: /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER michael@0: * return any indication of failure of the Client Key Exchange message, michael@0: * where that failure is caused by the content of the client's message. michael@0: * This function must not return SECFailure for any reason that is directly michael@0: * or indirectly caused by the content of the client's encrypted PMS. michael@0: * We must not send an alert and also not drop the connection. michael@0: * Instead, we generate a random PMS. This will cause a failure michael@0: * in the processing the finished message, which is exactly where michael@0: * the failure must occur. michael@0: * michael@0: * Called from ssl3_HandleClientKeyExchange michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleRSAClientKeyExchange(sslSocket *ss, michael@0: SSL3Opaque *b, michael@0: PRUint32 length, michael@0: SECKEYPrivateKey *serverKey) michael@0: { michael@0: PK11SymKey * pms; michael@0: #ifndef NO_PKCS11_BYPASS michael@0: unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; michael@0: unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; michael@0: ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; michael@0: unsigned int outLen = 0; michael@0: #endif michael@0: PRBool isTLS = PR_FALSE; michael@0: SECStatus rv; michael@0: SECItem enc_pms; michael@0: unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; michael@0: SECItem pmsItem = {siBuffer, NULL, 0}; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec ); michael@0: michael@0: enc_pms.data = b; michael@0: enc_pms.len = length; michael@0: pmsItem.data = rsaPmsBuf; michael@0: pmsItem.len = sizeof rsaPmsBuf; michael@0: michael@0: if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ michael@0: PRInt32 kLen; michael@0: kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); michael@0: if (kLen < 0) { michael@0: PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: if ((unsigned)kLen < enc_pms.len) { michael@0: enc_pms.len = kLen; michael@0: } michael@0: isTLS = PR_TRUE; michael@0: } else { michael@0: isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); michael@0: } michael@0: michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11) { michael@0: /* TRIPLE BYPASS, get PMS directly from RSA decryption. michael@0: * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, michael@0: * then, check for version rollback attack, then michael@0: * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in michael@0: * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with michael@0: * ss and NULL, so that it will use the MS we've already derived here. michael@0: */ michael@0: michael@0: rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, michael@0: sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); michael@0: if (rv != SECSuccess) { michael@0: /* triple bypass failed. Let's try for a double bypass. */ michael@0: goto double_bypass; michael@0: } else if (ss->opt.detectRollBack) { michael@0: SSL3ProtocolVersion client_version = michael@0: (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: client_version = dtls_DTLSVersionToTLSVersion(client_version); michael@0: } michael@0: michael@0: if (client_version != ss->clientHelloVersion) { michael@0: /* Version roll-back detected. ensure failure. */ michael@0: rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); michael@0: } michael@0: } michael@0: /* have PMS, build MS without PKCS11 */ michael@0: rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, michael@0: PR_TRUE); michael@0: if (rv != SECSuccess) { michael@0: pwSpec->msItem.data = pwSpec->raw_master_secret; michael@0: pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; michael@0: PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); michael@0: } michael@0: rv = ssl3_InitPendingCipherSpec(ss, NULL); michael@0: } else michael@0: #endif michael@0: { michael@0: #ifndef NO_PKCS11_BYPASS michael@0: double_bypass: michael@0: #endif michael@0: /* michael@0: * unwrap pms out of the incoming buffer michael@0: * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do michael@0: * the unwrap. Rather, it is the mechanism with which the michael@0: * unwrapped pms will be used. michael@0: */ michael@0: pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, michael@0: CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); michael@0: if (pms != NULL) { michael@0: PRINT_BUF(60, (ss, "decrypted premaster secret:", michael@0: PK11_GetKeyData(pms)->data, michael@0: PK11_GetKeyData(pms)->len)); michael@0: } else { michael@0: /* unwrap failed. Generate a bogus PMS and carry on. */ michael@0: PK11SlotInfo * slot = PK11_GetSlotFromPrivateKey(serverKey); michael@0: michael@0: ssl_GetSpecWriteLock(ss); michael@0: pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot); michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: PK11_FreeSlot(slot); michael@0: } michael@0: michael@0: if (pms == NULL) { michael@0: /* last gasp. */ michael@0: ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* This step will derive the MS from the PMS, among other things. */ michael@0: rv = ssl3_InitPendingCipherSpec(ss, pms); michael@0: PK11_FreeSymKey(pms); michael@0: } michael@0: michael@0: if (rv != SECSuccess) { michael@0: SEND_ALERT michael@0: return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ michael@0: } michael@0: return SECSuccess; michael@0: } michael@0: michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 ClientKeyExchange message from the remote client michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: SECKEYPrivateKey *serverKey = NULL; michael@0: SECStatus rv; michael@0: const ssl3KEADef *kea_def; michael@0: ssl3KeyPair *serverKeyPair = NULL; michael@0: #ifndef NSS_DISABLE_ECC michael@0: SECKEYPublicKey *serverPubKey = NULL; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (ss->ssl3.hs.ws != wait_client_key) { michael@0: SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); michael@0: return SECFailure; michael@0: } michael@0: michael@0: kea_def = ss->ssl3.hs.kea_def; michael@0: michael@0: if (ss->ssl3.hs.usedStepDownKey) { michael@0: PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ michael@0: && kea_def->exchKeyType == kt_rsa michael@0: && ss->stepDownKeyPair != NULL); michael@0: if (!kea_def->is_limited || michael@0: kea_def->exchKeyType != kt_rsa || michael@0: ss->stepDownKeyPair == NULL) { michael@0: /* shouldn't happen, don't use step down if it does */ michael@0: goto skip; michael@0: } michael@0: serverKeyPair = ss->stepDownKeyPair; michael@0: ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; michael@0: } else michael@0: skip: michael@0: #ifndef NSS_DISABLE_ECC michael@0: /* XXX Using SSLKEAType to index server certifiates michael@0: * does not work for (EC)DHE ciphers. Until we have michael@0: * an indexing mechanism general enough for all key michael@0: * exchange algorithms, we'll need to deal with each michael@0: * one seprately. michael@0: */ michael@0: if ((kea_def->kea == kea_ecdhe_rsa) || michael@0: (kea_def->kea == kea_ecdhe_ecdsa)) { michael@0: if (ss->ephemeralECDHKeyPair != NULL) { michael@0: serverKeyPair = ss->ephemeralECDHKeyPair; michael@0: if (serverKeyPair->pubKey) { michael@0: ss->sec.keaKeyBits = michael@0: SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); michael@0: } michael@0: } michael@0: } else michael@0: #endif michael@0: { michael@0: sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType; michael@0: serverKeyPair = sc->serverKeyPair; michael@0: ss->sec.keaKeyBits = sc->serverKeyBits; michael@0: } michael@0: michael@0: if (serverKeyPair) { michael@0: serverKey = serverKeyPair->privKey; michael@0: } michael@0: michael@0: if (serverKey == NULL) { michael@0: SEND_ALERT michael@0: PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); michael@0: return SECFailure; michael@0: } michael@0: michael@0: ss->sec.keaType = kea_def->exchKeyType; michael@0: michael@0: switch (kea_def->exchKeyType) { michael@0: case kt_rsa: michael@0: rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); michael@0: if (rv != SECSuccess) { michael@0: SEND_ALERT michael@0: return SECFailure; /* error code set */ michael@0: } michael@0: break; michael@0: michael@0: michael@0: #ifndef NSS_DISABLE_ECC michael@0: case kt_ecdh: michael@0: /* XXX We really ought to be able to store multiple michael@0: * EC certs (a requirement if we wish to support both michael@0: * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). michael@0: * When we make that change, we'll need an index other michael@0: * than kt_ecdh to pick the right EC certificate. michael@0: */ michael@0: if (serverKeyPair) { michael@0: serverPubKey = serverKeyPair->pubKey; michael@0: } michael@0: if (serverPubKey == NULL) { michael@0: /* XXX Is this the right error code? */ michael@0: PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, michael@0: serverPubKey, serverKey); michael@0: if (rv != SECSuccess) { michael@0: return SECFailure; /* error code set */ michael@0: } michael@0: break; michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: michael@0: default: michael@0: (void) ssl3_HandshakeFailure(ss); michael@0: PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); michael@0: return SECFailure; michael@0: } michael@0: ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; michael@0: return SECSuccess; michael@0: michael@0: } michael@0: michael@0: /* This is TLS's equivalent of sending a no_certificate alert. */ michael@0: static SECStatus michael@0: ssl3_SendEmptyCertificate(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, certificate, 3); michael@0: if (rv == SECSuccess) { michael@0: rv = ssl3_AppendHandshakeNumber(ss, 0, 3); michael@0: } michael@0: return rv; /* error, if any, set by functions called above. */ michael@0: } michael@0: michael@0: SECStatus michael@0: ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: SECStatus rv; michael@0: SECItem ticketData; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); michael@0: PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket); michael@0: michael@0: if (ss->ssl3.hs.ws != wait_new_session_ticket) { michael@0: SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid michael@0: * until it has verified the server's Finished message." See the comment in michael@0: * ssl3_FinishHandshake for more details. michael@0: */ michael@0: ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(); michael@0: if (length < 4) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, decode_error); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); michael@0: return SECFailure; michael@0: } michael@0: ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = michael@0: (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); michael@0: michael@0: rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length); michael@0: if (rv != SECSuccess || length != 0) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, decode_error); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); michael@0: return SECFailure; /* malformed */ michael@0: } michael@0: /* If the server sent a zero-length ticket, ignore it and keep the michael@0: * existing ticket. */ michael@0: if (ticketData.len != 0) { michael@0: rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, michael@0: &ticketData); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; michael@0: } michael@0: michael@0: ss->ssl3.hs.ws = wait_change_cipher; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: #ifdef NISCC_TEST michael@0: static PRInt32 connNum = 0; michael@0: michael@0: static SECStatus michael@0: get_fake_cert(SECItem *pCertItem, int *pIndex) michael@0: { michael@0: PRFileDesc *cf; michael@0: char * testdir; michael@0: char * startat; michael@0: char * stopat; michael@0: const char *extension; michael@0: int fileNum; michael@0: PRInt32 numBytes = 0; michael@0: PRStatus prStatus; michael@0: PRFileInfo info; michael@0: char cfn[100]; michael@0: michael@0: pCertItem->data = 0; michael@0: if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) { michael@0: return SECSuccess; michael@0: } michael@0: *pIndex = (NULL != strstr(testdir, "root")); michael@0: extension = (strstr(testdir, "simple") ? "" : ".der"); michael@0: fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; michael@0: if ((startat = PR_GetEnv("START_AT")) != NULL) { michael@0: fileNum += atoi(startat); michael@0: } michael@0: if ((stopat = PR_GetEnv("STOP_AT")) != NULL && michael@0: fileNum >= atoi(stopat)) { michael@0: *pIndex = -1; michael@0: return SECSuccess; michael@0: } michael@0: sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension); michael@0: cf = PR_Open(cfn, PR_RDONLY, 0); michael@0: if (!cf) { michael@0: goto loser; michael@0: } michael@0: prStatus = PR_GetOpenFileInfo(cf, &info); michael@0: if (prStatus != PR_SUCCESS) { michael@0: PR_Close(cf); michael@0: goto loser; michael@0: } michael@0: pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); michael@0: if (pCertItem) { michael@0: numBytes = PR_Read(cf, pCertItem->data, info.size); michael@0: } michael@0: PR_Close(cf); michael@0: if (numBytes != info.size) { michael@0: SECITEM_FreeItem(pCertItem, PR_FALSE); michael@0: PORT_SetError(SEC_ERROR_IO); michael@0: goto loser; michael@0: } michael@0: fprintf(stderr, "using %s\n", cfn); michael@0: return SECSuccess; michael@0: michael@0: loser: michael@0: fprintf(stderr, "failed to use %s\n", cfn); michael@0: *pIndex = -1; michael@0: return SECFailure; michael@0: } michael@0: #endif michael@0: michael@0: /* michael@0: * Used by both client and server. michael@0: * Called from HandleServerHelloDone and from SendServerHelloSequence. michael@0: */ michael@0: static SECStatus michael@0: ssl3_SendCertificate(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: CERTCertificateList *certChain; michael@0: int len = 0; michael@0: int i; michael@0: SSL3KEAType certIndex; michael@0: #ifdef NISCC_TEST michael@0: SECItem fakeCert; michael@0: int ndex = -1; michael@0: #endif michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: if (ss->sec.localCert) michael@0: CERT_DestroyCertificate(ss->sec.localCert); michael@0: if (ss->sec.isServer) { michael@0: sslServerCerts * sc = NULL; michael@0: michael@0: /* XXX SSLKEAType isn't really a good choice for michael@0: * indexing certificates (it breaks when we deal michael@0: * with (EC)DHE-* cipher suites. This hack ensures michael@0: * the RSA cert is picked for (EC)DHE-RSA. michael@0: * Revisit this when we add server side support michael@0: * for ECDHE-ECDSA or client-side authentication michael@0: * using EC certificates. michael@0: */ michael@0: if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || michael@0: (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { michael@0: certIndex = kt_rsa; michael@0: } else { michael@0: certIndex = ss->ssl3.hs.kea_def->exchKeyType; michael@0: } michael@0: sc = ss->serverCerts + certIndex; michael@0: certChain = sc->serverCertChain; michael@0: ss->sec.authKeyBits = sc->serverKeyBits; michael@0: ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; michael@0: ss->sec.localCert = CERT_DupCertificate(sc->serverCert); michael@0: } else { michael@0: certChain = ss->ssl3.clientCertChain; michael@0: ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); michael@0: } michael@0: michael@0: #ifdef NISCC_TEST michael@0: rv = get_fake_cert(&fakeCert, &ndex); michael@0: #endif michael@0: michael@0: if (certChain) { michael@0: for (i = 0; i < certChain->len; i++) { michael@0: #ifdef NISCC_TEST michael@0: if (fakeCert.len > 0 && i == ndex) { michael@0: len += fakeCert.len + 3; michael@0: } else { michael@0: len += certChain->certs[i].len + 3; michael@0: } michael@0: #else michael@0: len += certChain->certs[i].len + 3; michael@0: #endif michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: rv = ssl3_AppendHandshakeNumber(ss, len, 3); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: if (certChain) { michael@0: for (i = 0; i < certChain->len; i++) { michael@0: #ifdef NISCC_TEST michael@0: if (fakeCert.len > 0 && i == ndex) { michael@0: rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data, michael@0: fakeCert.len, 3); michael@0: SECITEM_FreeItem(&fakeCert, PR_FALSE); michael@0: } else { michael@0: rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, michael@0: certChain->certs[i].len, 3); michael@0: } michael@0: #else michael@0: rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, michael@0: certChain->certs[i].len, 3); michael@0: #endif michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: } michael@0: } michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* michael@0: * Used by server only. michael@0: * single-stapling, send only a single cert status michael@0: */ michael@0: static SECStatus michael@0: ssl3_SendCertificateStatus(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: int len = 0; michael@0: SECItemArray *statusToSend = NULL; michael@0: SSL3KEAType certIndex; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: PORT_Assert( ss->sec.isServer); michael@0: michael@0: if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) michael@0: return SECSuccess; michael@0: michael@0: /* Use certStatus based on the cert being used. */ michael@0: if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || michael@0: (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { michael@0: certIndex = kt_rsa; michael@0: } else { michael@0: certIndex = ss->ssl3.hs.kea_def->exchKeyType; michael@0: } michael@0: if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) { michael@0: statusToSend = ss->certStatusArray[certIndex]; michael@0: } michael@0: if (!statusToSend) michael@0: return SECSuccess; michael@0: michael@0: /* Use the array's first item only (single stapling) */ michael@0: len = 1 + statusToSend->items[0].len + 3; michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* err set by AppendHandshake. */ michael@0: } michael@0: rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); michael@0: if (rv != SECSuccess) michael@0: return rv; /* err set by AppendHandshake. */ michael@0: michael@0: rv = ssl3_AppendHandshakeVariable(ss, michael@0: statusToSend->items[0].data, michael@0: statusToSend->items[0].len, michael@0: 3); michael@0: if (rv != SECSuccess) michael@0: return rv; /* err set by AppendHandshake. */ michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* This is used to delete the CA certificates in the peer certificate chain michael@0: * from the cert database after they've been validated. michael@0: */ michael@0: static void michael@0: ssl3_CleanupPeerCerts(sslSocket *ss) michael@0: { michael@0: PLArenaPool * arena = ss->ssl3.peerCertArena; michael@0: ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain; michael@0: michael@0: for (; certs; certs = certs->next) { michael@0: CERT_DestroyCertificate(certs->cert); michael@0: } michael@0: if (arena) PORT_FreeArena(arena, PR_FALSE); michael@0: ss->ssl3.peerCertArena = NULL; michael@0: ss->ssl3.peerCertChain = NULL; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 CertificateStatus message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: * This is always called before ssl3_HandleCertificate, even if the Certificate michael@0: * message is sent first. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: PRInt32 status, len; michael@0: michael@0: if (ss->ssl3.hs.ws != wait_certificate_status) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS); michael@0: return SECFailure; michael@0: } michael@0: michael@0: PORT_Assert(!ss->sec.isServer); michael@0: michael@0: /* Consume the CertificateStatusType enum */ michael@0: status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); michael@0: if (status != 1 /* ocsp */) { michael@0: goto format_loser; michael@0: } michael@0: michael@0: len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); michael@0: if (len != length) { michael@0: goto format_loser; michael@0: } michael@0: michael@0: #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ michael@0: if (length > MAX_CERTSTATUS_LEN) michael@0: goto format_loser; michael@0: #undef MAX_CERTSTATUS_LEN michael@0: michael@0: /* Array size 1, because we currently implement single-stapling only */ michael@0: SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1); michael@0: if (!ss->sec.ci.sid->peerCertStatus.items) michael@0: return SECFailure; michael@0: michael@0: ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length); michael@0: michael@0: if (!ss->sec.ci.sid->peerCertStatus.items[0].data) { michael@0: SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length); michael@0: ss->sec.ci.sid->peerCertStatus.items[0].len = length; michael@0: ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer; michael@0: michael@0: return ssl3_AuthCertificate(ss); michael@0: michael@0: format_loser: michael@0: return ssl3_DecodeError(ss); michael@0: } michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 Certificate message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: ssl3CertNode * c; michael@0: ssl3CertNode * lastCert = NULL; michael@0: PRInt32 remaining = 0; michael@0: PRInt32 size; michael@0: SECStatus rv; michael@0: PRBool isServer = (PRBool)(!!ss->sec.isServer); michael@0: PRBool isTLS; michael@0: SSL3AlertDescription desc; michael@0: int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; michael@0: SECItem certItem; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if ((ss->ssl3.hs.ws != wait_server_cert) && michael@0: (ss->ssl3.hs.ws != wait_client_cert)) { michael@0: desc = unexpected_message; michael@0: errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE; michael@0: goto alert_loser; michael@0: } michael@0: michael@0: if (ss->sec.peerCert != NULL) { michael@0: if (ss->sec.peerKey) { michael@0: SECKEY_DestroyPublicKey(ss->sec.peerKey); michael@0: ss->sec.peerKey = NULL; michael@0: } michael@0: CERT_DestroyCertificate(ss->sec.peerCert); michael@0: ss->sec.peerCert = NULL; michael@0: } michael@0: michael@0: ssl3_CleanupPeerCerts(ss); michael@0: isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: michael@0: /* It is reported that some TLS client sends a Certificate message michael@0: ** with a zero-length message body. We'll treat that case like a michael@0: ** normal no_certificates message to maximize interoperability. michael@0: */ michael@0: if (length) { michael@0: remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); michael@0: if (remaining < 0) michael@0: goto loser; /* fatal alert already sent by ConsumeHandshake. */ michael@0: if ((PRUint32)remaining > length) michael@0: goto decode_loser; michael@0: } michael@0: michael@0: if (!remaining) { michael@0: if (!(isTLS && isServer)) { michael@0: desc = bad_certificate; michael@0: goto alert_loser; michael@0: } michael@0: /* This is TLS's version of a no_certificate alert. */ michael@0: /* I'm a server. I've requested a client cert. He hasn't got one. */ michael@0: rv = ssl3_HandleNoCertificate(ss); michael@0: if (rv != SECSuccess) { michael@0: errCode = PORT_GetError(); michael@0: goto loser; michael@0: } michael@0: ss->ssl3.hs.ws = wait_client_key; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); michael@0: if (ss->ssl3.peerCertArena == NULL) { michael@0: goto loser; /* don't send alerts on memory errors */ michael@0: } michael@0: michael@0: /* First get the peer cert. */ michael@0: remaining -= 3; michael@0: if (remaining < 0) michael@0: goto decode_loser; michael@0: michael@0: size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); michael@0: if (size <= 0) michael@0: goto loser; /* fatal alert already sent by ConsumeHandshake. */ michael@0: michael@0: if (remaining < size) michael@0: goto decode_loser; michael@0: michael@0: certItem.data = b; michael@0: certItem.len = size; michael@0: b += size; michael@0: length -= size; michael@0: remaining -= size; michael@0: michael@0: ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, michael@0: PR_FALSE, PR_TRUE); michael@0: if (ss->sec.peerCert == NULL) { michael@0: /* We should report an alert if the cert was bad, but not if the michael@0: * problem was just some local problem, like memory error. michael@0: */ michael@0: goto ambiguous_err; michael@0: } michael@0: michael@0: /* Now get all of the CA certs. */ michael@0: while (remaining > 0) { michael@0: remaining -= 3; michael@0: if (remaining < 0) michael@0: goto decode_loser; michael@0: michael@0: size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); michael@0: if (size <= 0) michael@0: goto loser; /* fatal alert already sent by ConsumeHandshake. */ michael@0: michael@0: if (remaining < size) michael@0: goto decode_loser; michael@0: michael@0: certItem.data = b; michael@0: certItem.len = size; michael@0: b += size; michael@0: length -= size; michael@0: remaining -= size; michael@0: michael@0: c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); michael@0: if (c == NULL) { michael@0: goto loser; /* don't send alerts on memory errors */ michael@0: } michael@0: michael@0: c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, michael@0: PR_FALSE, PR_TRUE); michael@0: if (c->cert == NULL) { michael@0: goto ambiguous_err; michael@0: } michael@0: michael@0: c->next = NULL; michael@0: if (lastCert) { michael@0: lastCert->next = c; michael@0: } else { michael@0: ss->ssl3.peerCertChain = c; michael@0: } michael@0: lastCert = c; michael@0: } michael@0: michael@0: if (remaining != 0) michael@0: goto decode_loser; michael@0: michael@0: SECKEY_UpdateCertPQG(ss->sec.peerCert); michael@0: michael@0: if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { michael@0: ss->ssl3.hs.ws = wait_certificate_status; michael@0: rv = SECSuccess; michael@0: } else { michael@0: rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ michael@0: } michael@0: michael@0: return rv; michael@0: michael@0: ambiguous_err: michael@0: errCode = PORT_GetError(); michael@0: switch (errCode) { michael@0: case PR_OUT_OF_MEMORY_ERROR: michael@0: case SEC_ERROR_BAD_DATABASE: michael@0: case SEC_ERROR_NO_MEMORY: michael@0: if (isTLS) { michael@0: desc = internal_error; michael@0: goto alert_loser; michael@0: } michael@0: goto loser; michael@0: } michael@0: ssl3_SendAlertForCertError(ss, errCode); michael@0: goto loser; michael@0: michael@0: decode_loser: michael@0: desc = isTLS ? decode_error : bad_certificate; michael@0: michael@0: alert_loser: michael@0: (void)SSL3_SendAlert(ss, alert_fatal, desc); michael@0: michael@0: loser: michael@0: (void)ssl_MapLowLevelError(errCode); michael@0: return SECFailure; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_AuthCertificate(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: PRBool isServer = (PRBool)(!!ss->sec.isServer); michael@0: int errCode; michael@0: michael@0: ss->ssl3.hs.authCertificatePending = PR_FALSE; michael@0: michael@0: /* michael@0: * Ask caller-supplied callback function to validate cert chain. michael@0: */ michael@0: rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, michael@0: PR_TRUE, isServer); michael@0: if (rv) { michael@0: errCode = PORT_GetError(); michael@0: if (rv != SECWouldBlock) { michael@0: if (ss->handleBadCert) { michael@0: rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); michael@0: } michael@0: } michael@0: michael@0: if (rv == SECWouldBlock) { michael@0: if (ss->sec.isServer) { michael@0: errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: ss->ssl3.hs.authCertificatePending = PR_TRUE; michael@0: rv = SECSuccess; michael@0: } michael@0: michael@0: if (rv != SECSuccess) { michael@0: ssl3_SendAlertForCertError(ss, errCode); michael@0: goto loser; michael@0: } michael@0: } michael@0: michael@0: ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); michael@0: michael@0: if (!ss->sec.isServer) { michael@0: CERTCertificate *cert = ss->sec.peerCert; michael@0: michael@0: /* set the server authentication and key exchange types and sizes michael@0: ** from the value in the cert. If the key exchange key is different, michael@0: ** it will get fixed when we handle the server key exchange message. michael@0: */ michael@0: SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert); michael@0: ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; michael@0: ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; michael@0: if (pubKey) { michael@0: ss->sec.keaKeyBits = ss->sec.authKeyBits = michael@0: SECKEY_PublicKeyStrengthInBits(pubKey); michael@0: #ifndef NSS_DISABLE_ECC michael@0: if (ss->sec.keaType == kt_ecdh) { michael@0: /* Get authKeyBits from signing key. michael@0: * XXX The code below uses a quick approximation of michael@0: * key size based on cert->signatureWrap.signature.data michael@0: * (which contains the DER encoded signature). The field michael@0: * cert->signatureWrap.signature.len contains the michael@0: * length of the encoded signature in bits. michael@0: */ michael@0: if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) { michael@0: ss->sec.authKeyBits = michael@0: cert->signatureWrap.signature.data[3]*8; michael@0: if (cert->signatureWrap.signature.data[4] == 0x00) michael@0: ss->sec.authKeyBits -= 8; michael@0: /* michael@0: * XXX: if cert is not signed by ecdsa we should michael@0: * destroy pubKey and goto bad_cert michael@0: */ michael@0: } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) { michael@0: ss->sec.authKeyBits = cert->signatureWrap.signature.len; michael@0: /* michael@0: * XXX: if cert is not signed by rsa we should michael@0: * destroy pubKey and goto bad_cert michael@0: */ michael@0: } michael@0: } michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: SECKEY_DestroyPublicKey(pubKey); michael@0: pubKey = NULL; michael@0: } michael@0: michael@0: ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */ michael@0: if (ss->ssl3.hs.kea_def->is_limited || michael@0: /* XXX OR server cert is signing only. */ michael@0: #ifndef NSS_DISABLE_ECC michael@0: ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa || michael@0: ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || michael@0: #endif /* NSS_DISABLE_ECC */ michael@0: ss->ssl3.hs.kea_def->exchKeyType == kt_dh) { michael@0: ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */ michael@0: } michael@0: } else { michael@0: ss->ssl3.hs.ws = wait_client_key; michael@0: } michael@0: michael@0: PORT_Assert(rv == SECSuccess); michael@0: if (rv != SECSuccess) { michael@0: errCode = SEC_ERROR_LIBRARY_FAILURE; michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: return rv; michael@0: michael@0: loser: michael@0: (void)ssl_MapLowLevelError(errCode); michael@0: return SECFailure; michael@0: } michael@0: michael@0: static SECStatus ssl3_FinishHandshake(sslSocket *ss); michael@0: michael@0: static SECStatus michael@0: ssl3_AlwaysFail(sslSocket * ss) michael@0: { michael@0: PORT_SetError(PR_INVALID_STATE_ERROR); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* Caller must hold 1stHandshakeLock. michael@0: */ michael@0: SECStatus michael@0: ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) michael@0: { michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); michael@0: michael@0: if (ss->sec.isServer) { michael@0: PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); michael@0: return SECFailure; michael@0: } michael@0: michael@0: ssl_GetRecvBufLock(ss); michael@0: ssl_GetSSL3HandshakeLock(ss); michael@0: michael@0: if (!ss->ssl3.hs.authCertificatePending) { michael@0: PORT_SetError(PR_INVALID_STATE_ERROR); michael@0: rv = SECFailure; michael@0: goto done; michael@0: } michael@0: michael@0: ss->ssl3.hs.authCertificatePending = PR_FALSE; michael@0: michael@0: if (error != 0) { michael@0: ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; michael@0: ssl3_SendAlertForCertError(ss, error); michael@0: rv = SECSuccess; michael@0: } else if (ss->ssl3.hs.restartTarget != NULL) { michael@0: sslRestartTarget target = ss->ssl3.hs.restartTarget; michael@0: ss->ssl3.hs.restartTarget = NULL; michael@0: michael@0: if (target == ssl3_FinishHandshake) { michael@0: SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race" michael@0: " with peer's finished message", SSL_GETPID(), ss->fd)); michael@0: } michael@0: michael@0: rv = target(ss); michael@0: /* Even if we blocked here, we have accomplished enough to claim michael@0: * success. Any remaining work will be taken care of by subsequent michael@0: * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. michael@0: */ michael@0: if (rv == SECWouldBlock) { michael@0: rv = SECSuccess; michael@0: } michael@0: } else { michael@0: SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" michael@0: " peer's finished message", SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert(!ss->ssl3.hs.isResuming); michael@0: PORT_Assert(ss->ssl3.hs.ws != idle_handshake); michael@0: michael@0: if (ss->opt.enableFalseStart && michael@0: !ss->firstHsDone && michael@0: !ss->ssl3.hs.isResuming && michael@0: ssl3_WaitingForStartOfServerSecondRound(ss)) { michael@0: /* ssl3_SendClientSecondRound deferred the false start check because michael@0: * certificate authentication was pending, so we do it now if we still michael@0: * haven't received any of the server's second round yet. michael@0: */ michael@0: rv = ssl3_CheckFalseStart(ss); michael@0: } else { michael@0: rv = SECSuccess; michael@0: } michael@0: } michael@0: michael@0: done: michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: ssl_ReleaseRecvBufLock(ss); michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, michael@0: PRBool isServer, michael@0: const SSL3Hashes * hashes, michael@0: TLSFinished * tlsFinished) michael@0: { michael@0: const char * label; michael@0: unsigned int len; michael@0: SECStatus rv; michael@0: michael@0: label = isServer ? "server finished" : "client finished"; michael@0: len = 15; michael@0: michael@0: rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, michael@0: hashes->len, tlsFinished->verify_data, michael@0: sizeof tlsFinished->verify_data); michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: /* The calling function must acquire and release the appropriate michael@0: * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for michael@0: * ss->ssl3.crSpec). michael@0: */ michael@0: SECStatus michael@0: ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, michael@0: unsigned int labelLen, const unsigned char *val, unsigned int valLen, michael@0: unsigned char *out, unsigned int outLen) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: michael@0: if (spec->master_secret && !spec->bypassCiphers) { michael@0: SECItem param = {siBuffer, NULL, 0}; michael@0: CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; michael@0: PK11Context *prf_context; michael@0: unsigned int retLen; michael@0: michael@0: if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { michael@0: mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; michael@0: } michael@0: prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, michael@0: spec->master_secret, ¶m); michael@0: if (!prf_context) michael@0: return SECFailure; michael@0: michael@0: rv = PK11_DigestBegin(prf_context); michael@0: rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen); michael@0: rv |= PK11_DigestOp(prf_context, val, valLen); michael@0: rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); michael@0: PORT_Assert(rv != SECSuccess || retLen == outLen); michael@0: michael@0: PK11_DestroyContext(prf_context, PR_TRUE); michael@0: } else { michael@0: /* bypass PKCS11 */ michael@0: #ifdef NO_PKCS11_BYPASS michael@0: PORT_Assert(spec->master_secret); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: rv = SECFailure; michael@0: #else michael@0: SECItem inData = { siBuffer, }; michael@0: SECItem outData = { siBuffer, }; michael@0: PRBool isFIPS = PR_FALSE; michael@0: michael@0: inData.data = (unsigned char *) val; michael@0: inData.len = valLen; michael@0: outData.data = out; michael@0: outData.len = outLen; michael@0: if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { michael@0: rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, michael@0: &outData, isFIPS); michael@0: } else { michael@0: rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); michael@0: } michael@0: PORT_Assert(rv != SECSuccess || outData.len == outLen); michael@0: #endif michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* called from ssl3_SendClientSecondRound michael@0: * ssl3_HandleFinished michael@0: */ michael@0: static SECStatus michael@0: ssl3_SendNextProto(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: int padding_len; michael@0: static const unsigned char padding[32] = {0}; michael@0: michael@0: if (ss->ssl3.nextProto.len == 0 || michael@0: ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { michael@0: return SECSuccess; michael@0: } michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32); michael@0: michael@0: rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len + michael@0: 2 + padding_len); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshakeHeader */ michael@0: } michael@0: rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, michael@0: ss->ssl3.nextProto.len, 1); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake */ michael@0: } michael@0: rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code set by AppendHandshake */ michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* called from ssl3_SendFinished michael@0: * michael@0: * This function is simply a debugging aid and therefore does not return a michael@0: * SECStatus. */ michael@0: static void michael@0: ssl3_RecordKeyLog(sslSocket *ss) michael@0: { michael@0: SECStatus rv; michael@0: SECItem *keyData; michael@0: char buf[14 /* "CLIENT_RANDOM " */ + michael@0: SSL3_RANDOM_LENGTH*2 /* client_random */ + michael@0: 1 /* " " */ + michael@0: 48*2 /* master secret */ + michael@0: 1 /* new line */]; michael@0: unsigned int j; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: if (!ssl_keylog_iob) michael@0: return; michael@0: michael@0: rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret); michael@0: if (rv != SECSuccess) michael@0: return; michael@0: michael@0: ssl_GetSpecReadLock(ss); michael@0: michael@0: /* keyData does not need to be freed. */ michael@0: keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret); michael@0: if (!keyData || !keyData->data || keyData->len != 48) { michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: return; michael@0: } michael@0: michael@0: /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ michael@0: michael@0: /* There could be multiple, concurrent writers to the michael@0: * keylog, so we have to do everything in a single call to michael@0: * fwrite. */ michael@0: michael@0: memcpy(buf, "CLIENT_RANDOM ", 14); michael@0: j = 14; michael@0: hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); michael@0: j += SSL3_RANDOM_LENGTH*2; michael@0: buf[j++] = ' '; michael@0: hexEncode(buf + j, keyData->data, 48); michael@0: j += 48*2; michael@0: buf[j++] = '\n'; michael@0: michael@0: PORT_Assert(j == sizeof(buf)); michael@0: michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: michael@0: if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1) michael@0: return; michael@0: fflush(ssl_keylog_iob); michael@0: return; michael@0: } michael@0: michael@0: /* called from ssl3_SendClientSecondRound michael@0: * ssl3_HandleClientHello michael@0: * ssl3_HandleFinished michael@0: */ michael@0: static SECStatus michael@0: ssl3_SendFinished(sslSocket *ss, PRInt32 flags) michael@0: { michael@0: ssl3CipherSpec *cwSpec; michael@0: PRBool isTLS; michael@0: PRBool isServer = ss->sec.isServer; michael@0: SECStatus rv; michael@0: SSL3Sender sender = isServer ? sender_server : sender_client; michael@0: SSL3Hashes hashes; michael@0: TLSFinished tlsFinished; michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd)); michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: ssl_GetSpecReadLock(ss); michael@0: cwSpec = ss->ssl3.cwSpec; michael@0: isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender); michael@0: if (isTLS && rv == SECSuccess) { michael@0: rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished); michael@0: } michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: if (rv != SECSuccess) { michael@0: goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ michael@0: } michael@0: michael@0: if (isTLS) { michael@0: if (isServer) michael@0: ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; michael@0: else michael@0: ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; michael@0: ss->ssl3.hs.finishedBytes = sizeof tlsFinished; michael@0: rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished); michael@0: if (rv != SECSuccess) michael@0: goto fail; /* err set by AppendHandshake. */ michael@0: rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); michael@0: if (rv != SECSuccess) michael@0: goto fail; /* err set by AppendHandshake. */ michael@0: } else { michael@0: if (isServer) michael@0: ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; michael@0: else michael@0: ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; michael@0: PORT_Assert(hashes.len == sizeof hashes.u.s); michael@0: ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; michael@0: rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s); michael@0: if (rv != SECSuccess) michael@0: goto fail; /* err set by AppendHandshake. */ michael@0: rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); michael@0: if (rv != SECSuccess) michael@0: goto fail; /* err set by AppendHandshake. */ michael@0: } michael@0: rv = ssl3_FlushHandshake(ss, flags); michael@0: if (rv != SECSuccess) { michael@0: goto fail; /* error code set by ssl3_FlushHandshake */ michael@0: } michael@0: michael@0: ssl3_RecordKeyLog(ss); michael@0: michael@0: return SECSuccess; michael@0: michael@0: fail: michael@0: return rv; michael@0: } michael@0: michael@0: /* wrap the master secret, and put it into the SID. michael@0: * Caller holds the Spec read lock. michael@0: */ michael@0: SECStatus michael@0: ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, michael@0: ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType) michael@0: { michael@0: PK11SymKey * wrappingKey = NULL; michael@0: PK11SlotInfo * symKeySlot; michael@0: void * pwArg = ss->pkcs11PinArg; michael@0: SECStatus rv = SECFailure; michael@0: PRBool isServer = ss->sec.isServer; michael@0: CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; michael@0: symKeySlot = PK11_GetSlotFromKey(spec->master_secret); michael@0: if (!isServer) { michael@0: int wrapKeyIndex; michael@0: int incarnation; michael@0: michael@0: /* these next few functions are mere accessors and don't fail. */ michael@0: sid->u.ssl3.masterWrapIndex = wrapKeyIndex = michael@0: PK11_GetCurrentWrapIndex(symKeySlot); michael@0: PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */ michael@0: michael@0: sid->u.ssl3.masterWrapSeries = incarnation = michael@0: PK11_GetSlotSeries(symKeySlot); michael@0: sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); michael@0: sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); michael@0: sid->u.ssl3.masterValid = PR_TRUE; michael@0: /* Get the default wrapping key, for wrapping the master secret before michael@0: * placing it in the SID cache entry. */ michael@0: wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, michael@0: CKM_INVALID_MECHANISM, incarnation, michael@0: pwArg); michael@0: if (wrappingKey) { michael@0: mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ michael@0: } else { michael@0: int keyLength; michael@0: /* if the wrappingKey doesn't exist, attempt to create it. michael@0: * Note: we intentionally ignore errors here. If we cannot michael@0: * generate a wrapping key, it is not fatal to this SSL connection, michael@0: * but we will not be able to restart this session. michael@0: */ michael@0: mechanism = PK11_GetBestWrapMechanism(symKeySlot); michael@0: keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); michael@0: /* Zero length means fixed key length algorithm, or error. michael@0: * It's ambiguous. michael@0: */ michael@0: wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, michael@0: keyLength, pwArg); michael@0: if (wrappingKey) { michael@0: PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); michael@0: } michael@0: } michael@0: } else { michael@0: /* server socket using session cache. */ michael@0: mechanism = PK11_GetBestWrapMechanism(symKeySlot); michael@0: if (mechanism != CKM_INVALID_MECHANISM) { michael@0: wrappingKey = michael@0: getWrappingKey(ss, symKeySlot, effectiveExchKeyType, michael@0: mechanism, pwArg); michael@0: if (wrappingKey) { michael@0: mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ michael@0: } michael@0: } michael@0: } michael@0: michael@0: sid->u.ssl3.masterWrapMech = mechanism; michael@0: PK11_FreeSlot(symKeySlot); michael@0: michael@0: if (wrappingKey) { michael@0: SECItem wmsItem; michael@0: michael@0: wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; michael@0: wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; michael@0: rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, michael@0: spec->master_secret, &wmsItem); michael@0: /* rv is examined below. */ michael@0: sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; michael@0: PK11_FreeSymKey(wrappingKey); michael@0: } michael@0: return rv; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete michael@0: * ssl3 Finished message from the peer. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, michael@0: const SSL3Hashes *hashes) michael@0: { michael@0: sslSessionID * sid = ss->sec.ci.sid; michael@0: SECStatus rv = SECSuccess; michael@0: PRBool isServer = ss->sec.isServer; michael@0: PRBool isTLS; michael@0: SSL3KEAType effectiveExchKeyType; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: michael@0: if (ss->ssl3.hs.ws != wait_finished) { michael@0: SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: if (isTLS) { michael@0: TLSFinished tlsFinished; michael@0: michael@0: if (length != sizeof tlsFinished) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, decode_error); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, michael@0: hashes, &tlsFinished); michael@0: if (!isServer) michael@0: ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; michael@0: else michael@0: ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; michael@0: ss->ssl3.hs.finishedBytes = sizeof tlsFinished; michael@0: if (rv != SECSuccess || michael@0: 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); michael@0: PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); michael@0: return SECFailure; michael@0: } michael@0: } else { michael@0: if (length != sizeof(SSL3Finished)) { michael@0: (void)ssl3_IllegalParameter(ss); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (!isServer) michael@0: ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s; michael@0: else michael@0: ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s; michael@0: PORT_Assert(hashes->len == sizeof hashes->u.s); michael@0: ss->ssl3.hs.finishedBytes = sizeof hashes->u.s; michael@0: if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) { michael@0: (void)ssl3_HandshakeFailure(ss); michael@0: PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: ssl_GetXmitBufLock(ss); /*************************************/ michael@0: michael@0: if ((isServer && !ss->ssl3.hs.isResuming) || michael@0: (!isServer && ss->ssl3.hs.isResuming)) { michael@0: PRInt32 flags = 0; michael@0: michael@0: /* Send a NewSessionTicket message if the client sent us michael@0: * either an empty session ticket, or one that did not verify. michael@0: * (Note that if either of these conditions was met, then the michael@0: * server has sent a SessionTicket extension in the michael@0: * ServerHello message.) michael@0: */ michael@0: if (isServer && !ss->ssl3.hs.isResuming && michael@0: ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) { michael@0: /* RFC 5077 Section 3.3: "In the case of a full handshake, the michael@0: * server MUST verify the client's Finished message before sending michael@0: * the ticket." Presumably, this also means that the client's michael@0: * certificate, if any, must be verified beforehand too. michael@0: */ michael@0: rv = ssl3_SendNewSessionTicket(ss); michael@0: if (rv != SECSuccess) { michael@0: goto xmit_loser; michael@0: } michael@0: } michael@0: michael@0: rv = ssl3_SendChangeCipherSpecs(ss); michael@0: if (rv != SECSuccess) { michael@0: goto xmit_loser; /* err is set. */ michael@0: } michael@0: /* If this thread is in SSL_SecureSend (trying to write some data) michael@0: ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the michael@0: ** last two handshake messages (change cipher spec and finished) michael@0: ** will be sent in the same send/write call as the application data. michael@0: */ michael@0: if (ss->writerThread == PR_GetCurrentThread()) { michael@0: flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; michael@0: } michael@0: michael@0: if (!isServer && !ss->firstHsDone) { michael@0: rv = ssl3_SendNextProto(ss); michael@0: if (rv != SECSuccess) { michael@0: goto xmit_loser; /* err code was set. */ michael@0: } michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: flags |= ssl_SEND_FLAG_NO_RETRANSMIT; michael@0: } michael@0: michael@0: rv = ssl3_SendFinished(ss, flags); michael@0: if (rv != SECSuccess) { michael@0: goto xmit_loser; /* err is set. */ michael@0: } michael@0: } michael@0: michael@0: xmit_loser: michael@0: ssl_ReleaseXmitBufLock(ss); /*************************************/ michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: michael@0: if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) { michael@0: effectiveExchKeyType = kt_rsa; michael@0: } else { michael@0: effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; michael@0: } michael@0: michael@0: if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) { michael@0: /* fill in the sid */ michael@0: sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; michael@0: sid->u.ssl3.compression = ss->ssl3.hs.compression; michael@0: sid->u.ssl3.policy = ss->ssl3.policy; michael@0: #ifndef NSS_DISABLE_ECC michael@0: sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; michael@0: #endif michael@0: sid->u.ssl3.exchKeyType = effectiveExchKeyType; michael@0: sid->version = ss->version; michael@0: sid->authAlgorithm = ss->sec.authAlgorithm; michael@0: sid->authKeyBits = ss->sec.authKeyBits; michael@0: sid->keaType = ss->sec.keaType; michael@0: sid->keaKeyBits = ss->sec.keaKeyBits; michael@0: sid->lastAccessTime = sid->creationTime = ssl_Time(); michael@0: sid->expirationTime = sid->creationTime + ssl3_sid_timeout; michael@0: sid->localCert = CERT_DupCertificate(ss->sec.localCert); michael@0: michael@0: ssl_GetSpecReadLock(ss); /*************************************/ michael@0: michael@0: /* Copy the master secret (wrapped or unwrapped) into the sid */ michael@0: if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { michael@0: sid->u.ssl3.keys.wrapped_master_secret_len = michael@0: ss->ssl3.crSpec->msItem.len; michael@0: memcpy(sid->u.ssl3.keys.wrapped_master_secret, michael@0: ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); michael@0: sid->u.ssl3.masterValid = PR_TRUE; michael@0: sid->u.ssl3.keys.msIsWrapped = PR_FALSE; michael@0: rv = SECSuccess; michael@0: } else { michael@0: rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, michael@0: ss->ssl3.crSpec, michael@0: effectiveExchKeyType); michael@0: sid->u.ssl3.keys.msIsWrapped = PR_TRUE; michael@0: } michael@0: ssl_ReleaseSpecReadLock(ss); /*************************************/ michael@0: michael@0: /* If the wrap failed, we don't cache the sid. michael@0: * The connection continues normally however. michael@0: */ michael@0: ss->ssl3.hs.cacheSID = rv == SECSuccess; michael@0: } michael@0: michael@0: if (ss->ssl3.hs.authCertificatePending) { michael@0: if (ss->ssl3.hs.restartTarget) { michael@0: PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; michael@0: return SECWouldBlock; michael@0: } michael@0: michael@0: rv = ssl3_FinishHandshake(ss); michael@0: return rv; michael@0: } michael@0: michael@0: /* The return type is SECStatus instead of void because this function needs michael@0: * to have type sslRestartTarget. michael@0: */ michael@0: SECStatus michael@0: ssl3_FinishHandshake(sslSocket * ss) michael@0: { michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: PORT_Assert( ss->ssl3.hs.restartTarget == NULL ); michael@0: michael@0: /* The first handshake is now completed. */ michael@0: ss->handshake = NULL; michael@0: michael@0: /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid michael@0: * until it has verified the server's Finished message." When the server michael@0: * sends a NewSessionTicket in a resumption handshake, we must wait until michael@0: * the handshake is finished (we have verified the server's Finished michael@0: * AND the server's certificate) before we update the ticket in the sid. michael@0: * michael@0: * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid) michael@0: * because CacheSID requires the session ticket to already be set, and also michael@0: * because of the lazy lock creation scheme used by CacheSID and michael@0: * ssl3_SetSIDSessionTicket. michael@0: */ michael@0: if (ss->ssl3.hs.receivedNewSessionTicket) { michael@0: PORT_Assert(!ss->sec.isServer); michael@0: ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); michael@0: /* The sid took over the ticket data */ michael@0: PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); michael@0: ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; michael@0: } michael@0: michael@0: if (ss->ssl3.hs.cacheSID) { michael@0: PORT_Assert(ss->sec.ci.sid->cached == never_cached); michael@0: (*ss->sec.cache)(ss->sec.ci.sid); michael@0: ss->ssl3.hs.cacheSID = PR_FALSE; michael@0: } michael@0: michael@0: ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ michael@0: ss->ssl3.hs.ws = idle_handshake; michael@0: michael@0: ssl_FinishHandshake(ss); michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3 michael@0: * hanshake message. michael@0: * Caller must hold Handshake and RecvBuf locks. michael@0: */ michael@0: SECStatus michael@0: ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: SSL3HandshakeType type = ss->ssl3.hs.msg_type; michael@0: SSL3Hashes hashes; /* computed hashes are put here. */ michael@0: PRUint8 hdr[4]; michael@0: PRUint8 dtlsData[8]; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: /* michael@0: * We have to compute the hashes before we update them with the michael@0: * current message. michael@0: */ michael@0: ssl_GetSpecReadLock(ss); /************************************/ michael@0: if((type == finished) || (type == certificate_verify)) { michael@0: SSL3Sender sender = (SSL3Sender)0; michael@0: ssl3CipherSpec *rSpec = ss->ssl3.prSpec; michael@0: michael@0: if (type == finished) { michael@0: sender = ss->sec.isServer ? sender_client : sender_server; michael@0: rSpec = ss->ssl3.crSpec; michael@0: } michael@0: rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); michael@0: } michael@0: ssl_ReleaseSpecReadLock(ss); /************************************/ michael@0: if (rv != SECSuccess) { michael@0: return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ michael@0: } michael@0: SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), michael@0: ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); michael@0: michael@0: hdr[0] = (PRUint8)ss->ssl3.hs.msg_type; michael@0: hdr[1] = (PRUint8)(length >> 16); michael@0: hdr[2] = (PRUint8)(length >> 8); michael@0: hdr[3] = (PRUint8)(length ); michael@0: michael@0: /* Start new handshake hashes when we start a new handshake */ michael@0: if (ss->ssl3.hs.msg_type == client_hello) { michael@0: rv = ssl3_RestartHandshakeHashes(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: } michael@0: /* We should not include hello_request and hello_verify_request messages michael@0: * in the handshake hashes */ michael@0: if ((ss->ssl3.hs.msg_type != hello_request) && michael@0: (ss->ssl3.hs.msg_type != hello_verify_request)) { michael@0: rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4); michael@0: if (rv != SECSuccess) return rv; /* err code already set. */ michael@0: michael@0: /* Extra data to simulate a complete DTLS handshake fragment */ michael@0: if (IS_DTLS(ss)) { michael@0: /* Sequence number */ michael@0: dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq); michael@0: dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); michael@0: michael@0: /* Fragment offset */ michael@0: dtlsData[2] = 0; michael@0: dtlsData[3] = 0; michael@0: dtlsData[4] = 0; michael@0: michael@0: /* Fragment length */ michael@0: dtlsData[5] = (PRUint8)(length >> 16); michael@0: dtlsData[6] = (PRUint8)(length >> 8); michael@0: dtlsData[7] = (PRUint8)(length ); michael@0: michael@0: rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData, michael@0: sizeof(dtlsData)); michael@0: if (rv != SECSuccess) return rv; /* err code already set. */ michael@0: } michael@0: michael@0: /* The message body */ michael@0: rv = ssl3_UpdateHandshakeHashes(ss, b, length); michael@0: if (rv != SECSuccess) return rv; /* err code already set. */ michael@0: } michael@0: michael@0: PORT_SetError(0); /* each message starts with no error. */ michael@0: michael@0: if (ss->ssl3.hs.ws == wait_certificate_status && michael@0: ss->ssl3.hs.msg_type != certificate_status) { michael@0: /* If we negotiated the certificate_status extension then we deferred michael@0: * certificate validation until we get the CertificateStatus messsage. michael@0: * But the CertificateStatus message is optional. If the server did michael@0: * not send it then we need to validate the certificate now. If the michael@0: * server does send the CertificateStatus message then we will michael@0: * authenticate the certificate in ssl3_HandleCertificateStatus. michael@0: */ michael@0: rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ michael@0: PORT_Assert(rv != SECWouldBlock); michael@0: if (rv != SECSuccess) { michael@0: return rv; michael@0: } michael@0: } michael@0: michael@0: switch (ss->ssl3.hs.msg_type) { michael@0: case hello_request: michael@0: if (length != 0) { michael@0: (void)ssl3_DecodeError(ss); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); michael@0: return SECFailure; michael@0: } michael@0: if (ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleHelloRequest(ss); michael@0: break; michael@0: case client_hello: michael@0: if (!ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleClientHello(ss, b, length); michael@0: break; michael@0: case server_hello: michael@0: if (ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleServerHello(ss, b, length); michael@0: break; michael@0: case hello_verify_request: michael@0: if (!IS_DTLS(ss) || ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST); michael@0: return SECFailure; michael@0: } michael@0: rv = dtls_HandleHelloVerifyRequest(ss, b, length); michael@0: break; michael@0: case certificate: michael@0: rv = ssl3_HandleCertificate(ss, b, length); michael@0: break; michael@0: case certificate_status: michael@0: rv = ssl3_HandleCertificateStatus(ss, b, length); michael@0: break; michael@0: case server_key_exchange: michael@0: if (ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleServerKeyExchange(ss, b, length); michael@0: break; michael@0: case certificate_request: michael@0: if (ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleCertificateRequest(ss, b, length); michael@0: break; michael@0: case server_hello_done: michael@0: if (length != 0) { michael@0: (void)ssl3_DecodeError(ss); michael@0: PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE); michael@0: return SECFailure; michael@0: } michael@0: if (ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleServerHelloDone(ss); michael@0: break; michael@0: case certificate_verify: michael@0: if (!ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes); michael@0: break; michael@0: case client_key_exchange: michael@0: if (!ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleClientKeyExchange(ss, b, length); michael@0: break; michael@0: case new_session_ticket: michael@0: if (ss->sec.isServer) { michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); michael@0: return SECFailure; michael@0: } michael@0: rv = ssl3_HandleNewSessionTicket(ss, b, length); michael@0: break; michael@0: case finished: michael@0: rv = ssl3_HandleFinished(ss, b, length, &hashes); michael@0: break; michael@0: default: michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); michael@0: rv = SECFailure; michael@0: } michael@0: michael@0: if (IS_DTLS(ss) && (rv != SECFailure)) { michael@0: /* Increment the expected sequence number */ michael@0: ss->ssl3.hs.recvMessageSeq++; michael@0: } michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record. michael@0: * origBuf is the decrypted ssl record content. michael@0: * Caller must hold the handshake and RecvBuf locks. michael@0: */ michael@0: static SECStatus michael@0: ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) michael@0: { michael@0: /* michael@0: * There may be a partial handshake message already in the handshake michael@0: * state. The incoming buffer may contain another portion, or a michael@0: * complete message or several messages followed by another portion. michael@0: * michael@0: * Each message is made contiguous before being passed to the actual michael@0: * message parser. michael@0: */ michael@0: sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */ michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (buf->buf == NULL) { michael@0: *buf = *origBuf; michael@0: } michael@0: while (buf->len > 0) { michael@0: if (ss->ssl3.hs.header_bytes < 4) { michael@0: PRUint8 t; michael@0: t = *(buf->buf++); michael@0: buf->len--; michael@0: if (ss->ssl3.hs.header_bytes++ == 0) michael@0: ss->ssl3.hs.msg_type = (SSL3HandshakeType)t; michael@0: else michael@0: ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; michael@0: if (ss->ssl3.hs.header_bytes < 4) michael@0: continue; michael@0: michael@0: #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */ michael@0: if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { michael@0: (void)ssl3_DecodeError(ss); michael@0: PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); michael@0: return SECFailure; michael@0: } michael@0: #undef MAX_HANDSHAKE_MSG_LEN michael@0: michael@0: /* If msg_len is zero, be sure we fall through, michael@0: ** even if buf->len is zero. michael@0: */ michael@0: if (ss->ssl3.hs.msg_len > 0) michael@0: continue; michael@0: } michael@0: michael@0: /* michael@0: * Header has been gathered and there is at least one byte of new michael@0: * data available for this message. If it can be done right out michael@0: * of the original buffer, then use it from there. michael@0: */ michael@0: if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) { michael@0: /* handle it from input buffer */ michael@0: rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len); michael@0: if (rv == SECFailure) { michael@0: /* This test wants to fall through on either michael@0: * SECSuccess or SECWouldBlock. michael@0: * ssl3_HandleHandshakeMessage MUST set the error code. michael@0: */ michael@0: return rv; michael@0: } michael@0: buf->buf += ss->ssl3.hs.msg_len; michael@0: buf->len -= ss->ssl3.hs.msg_len; michael@0: ss->ssl3.hs.msg_len = 0; michael@0: ss->ssl3.hs.header_bytes = 0; michael@0: if (rv != SECSuccess) { /* return if SECWouldBlock. */ michael@0: return rv; michael@0: } michael@0: } else { michael@0: /* must be copied to msg_body and dealt with from there */ michael@0: unsigned int bytes; michael@0: michael@0: PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); michael@0: bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len); michael@0: michael@0: /* Grow the buffer if needed */ michael@0: rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); michael@0: if (rv != SECSuccess) { michael@0: /* sslBuffer_Grow has set a memory error code. */ michael@0: return SECFailure; michael@0: } michael@0: michael@0: PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, michael@0: buf->buf, bytes); michael@0: ss->ssl3.hs.msg_body.len += bytes; michael@0: buf->buf += bytes; michael@0: buf->len -= bytes; michael@0: michael@0: PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); michael@0: michael@0: /* if we have a whole message, do it */ michael@0: if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { michael@0: rv = ssl3_HandleHandshakeMessage( michael@0: ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len); michael@0: if (rv == SECFailure) { michael@0: /* This test wants to fall through on either michael@0: * SECSuccess or SECWouldBlock. michael@0: * ssl3_HandleHandshakeMessage MUST set error code. michael@0: */ michael@0: return rv; michael@0: } michael@0: ss->ssl3.hs.msg_body.len = 0; michael@0: ss->ssl3.hs.msg_len = 0; michael@0: ss->ssl3.hs.header_bytes = 0; michael@0: if (rv != SECSuccess) { /* return if SECWouldBlock. */ michael@0: return rv; michael@0: } michael@0: } else { michael@0: PORT_Assert(buf->len == 0); michael@0: break; michael@0: } michael@0: } michael@0: } /* end loop */ michael@0: michael@0: origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ michael@0: buf->buf = NULL; /* not a leak. */ michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* These macros return the given value with the MSB copied to all the other michael@0: * bits. They use the fact that arithmetic shift shifts-in the sign bit. michael@0: * However, this is not ensured by the C standard so you may need to replace michael@0: * them with something else for odd compilers. */ michael@0: #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) ) michael@0: #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x))) michael@0: michael@0: /* SECStatusToMask returns, in constant time, a mask value of all ones if michael@0: * rv == SECSuccess. Otherwise it returns zero. */ michael@0: static unsigned int michael@0: SECStatusToMask(SECStatus rv) michael@0: { michael@0: unsigned int good; michael@0: /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results michael@0: * in the MSB being set to one iff it was zero before. */ michael@0: good = rv ^ SECSuccess; michael@0: good--; michael@0: return DUPLICATE_MSB_TO_ALL(good); michael@0: } michael@0: michael@0: /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */ michael@0: static unsigned char michael@0: ssl_ConstantTimeGE(unsigned int a, unsigned int b) michael@0: { michael@0: a -= b; michael@0: return DUPLICATE_MSB_TO_ALL(~a); michael@0: } michael@0: michael@0: /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */ michael@0: static unsigned char michael@0: ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) michael@0: { michael@0: unsigned int c = a ^ b; michael@0: c--; michael@0: return DUPLICATE_MSB_TO_ALL_8(c); michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, michael@0: unsigned int blockSize, michael@0: unsigned int macSize) michael@0: { michael@0: unsigned int paddingLength, good, t; michael@0: const unsigned int overhead = 1 /* padding length byte */ + macSize; michael@0: michael@0: /* These lengths are all public so we can test them in non-constant michael@0: * time. */ michael@0: if (overhead > plaintext->len) { michael@0: return SECFailure; michael@0: } michael@0: michael@0: paddingLength = plaintext->buf[plaintext->len-1]; michael@0: /* SSLv3 padding bytes are random and cannot be checked. */ michael@0: t = plaintext->len; michael@0: t -= paddingLength+overhead; michael@0: /* If len >= paddingLength+overhead then the MSB of t is zero. */ michael@0: good = DUPLICATE_MSB_TO_ALL(~t); michael@0: /* SSLv3 requires that the padding is minimal. */ michael@0: t = blockSize - (paddingLength+1); michael@0: good &= DUPLICATE_MSB_TO_ALL(~t); michael@0: plaintext->len -= good & (paddingLength+1); michael@0: return (good & SECSuccess) | (~good & SECFailure); michael@0: } michael@0: michael@0: static SECStatus michael@0: ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) michael@0: { michael@0: unsigned int paddingLength, good, t, toCheck, i; michael@0: const unsigned int overhead = 1 /* padding length byte */ + macSize; michael@0: michael@0: /* These lengths are all public so we can test them in non-constant michael@0: * time. */ michael@0: if (overhead > plaintext->len) { michael@0: return SECFailure; michael@0: } michael@0: michael@0: paddingLength = plaintext->buf[plaintext->len-1]; michael@0: t = plaintext->len; michael@0: t -= paddingLength+overhead; michael@0: /* If len >= paddingLength+overhead then the MSB of t is zero. */ michael@0: good = DUPLICATE_MSB_TO_ALL(~t); michael@0: michael@0: /* The padding consists of a length byte at the end of the record and then michael@0: * that many bytes of padding, all with the same value as the length byte. michael@0: * Thus, with the length byte included, there are paddingLength+1 bytes of michael@0: * padding. michael@0: * michael@0: * We can't check just |paddingLength+1| bytes because that leaks michael@0: * decrypted information. Therefore we always have to check the maximum michael@0: * amount of padding possible. (Again, the length of the record is michael@0: * public information so we can use it.) */ michael@0: toCheck = 255; /* maximum amount of padding. */ michael@0: if (toCheck > plaintext->len-1) { michael@0: toCheck = plaintext->len-1; michael@0: } michael@0: michael@0: for (i = 0; i < toCheck; i++) { michael@0: unsigned int t = paddingLength - i; michael@0: /* If i <= paddingLength then the MSB of t is zero and mask is michael@0: * 0xff. Otherwise, mask is 0. */ michael@0: unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); michael@0: unsigned char b = plaintext->buf[plaintext->len-1-i]; michael@0: /* The final |paddingLength+1| bytes should all have the value michael@0: * |paddingLength|. Therefore the XOR should be zero. */ michael@0: good &= ~(mask&(paddingLength ^ b)); michael@0: } michael@0: michael@0: /* If any of the final |paddingLength+1| bytes had the wrong value, michael@0: * one or more of the lower eight bits of |good| will be cleared. We michael@0: * AND the bottom 8 bits together and duplicate the result to all the michael@0: * bits. */ michael@0: good &= good >> 4; michael@0: good &= good >> 2; michael@0: good &= good >> 1; michael@0: good <<= sizeof(good)*8-1; michael@0: good = DUPLICATE_MSB_TO_ALL(good); michael@0: michael@0: plaintext->len -= good & (paddingLength+1); michael@0: return (good & SECSuccess) | (~good & SECFailure); michael@0: } michael@0: michael@0: /* On entry: michael@0: * originalLength >= macSize michael@0: * macSize <= MAX_MAC_LENGTH michael@0: * plaintext->len >= macSize michael@0: */ michael@0: static void michael@0: ssl_CBCExtractMAC(sslBuffer *plaintext, michael@0: unsigned int originalLength, michael@0: SSL3Opaque* out, michael@0: unsigned int macSize) michael@0: { michael@0: unsigned char rotatedMac[MAX_MAC_LENGTH]; michael@0: /* macEnd is the index of |plaintext->buf| just after the end of the michael@0: * MAC. */ michael@0: unsigned macEnd = plaintext->len; michael@0: unsigned macStart = macEnd - macSize; michael@0: /* scanStart contains the number of bytes that we can ignore because michael@0: * the MAC's position can only vary by 255 bytes. */ michael@0: unsigned scanStart = 0; michael@0: unsigned i, j, divSpoiler; michael@0: unsigned char rotateOffset; michael@0: michael@0: if (originalLength > macSize + 255 + 1) michael@0: scanStart = originalLength - (macSize + 255 + 1); michael@0: michael@0: /* divSpoiler contains a multiple of macSize that is used to cause the michael@0: * modulo operation to be constant time. Without this, the time varies michael@0: * based on the amount of padding when running on Intel chips at least. michael@0: * michael@0: * The aim of right-shifting macSize is so that the compiler doesn't michael@0: * figure out that it can remove divSpoiler as that would require it michael@0: * to prove that macSize is always even, which I hope is beyond it. */ michael@0: divSpoiler = macSize >> 1; michael@0: divSpoiler <<= (sizeof(divSpoiler)-1)*8; michael@0: rotateOffset = (divSpoiler + macStart - scanStart) % macSize; michael@0: michael@0: memset(rotatedMac, 0, macSize); michael@0: for (i = scanStart; i < originalLength;) { michael@0: for (j = 0; j < macSize && i < originalLength; i++, j++) { michael@0: unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); michael@0: unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); michael@0: unsigned char b = 0; michael@0: b = plaintext->buf[i]; michael@0: rotatedMac[j] |= b & macStarted & ~macEnded; michael@0: } michael@0: } michael@0: michael@0: /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line michael@0: * we could line-align |rotatedMac| and rotate in place. */ michael@0: memset(out, 0, macSize); michael@0: for (i = 0; i < macSize; i++) { michael@0: unsigned char offset = michael@0: (divSpoiler + macSize - rotateOffset + i) % macSize; michael@0: for (j = 0; j < macSize; j++) { michael@0: out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* if cText is non-null, then decipher, check MAC, and decompress the michael@0: * SSL record from cText->buf (typically gs->inbuf) michael@0: * into databuf (typically gs->buf), and any previous contents of databuf michael@0: * is lost. Then handle databuf according to its SSL record type, michael@0: * unless it's an application record. michael@0: * michael@0: * If cText is NULL, then the ciphertext has previously been deciphered and michael@0: * checked, and is already sitting in databuf. It is processed as an SSL michael@0: * Handshake message. michael@0: * michael@0: * DOES NOT process the decrypted/decompressed application data. michael@0: * On return, databuf contains the decrypted/decompressed record. michael@0: * michael@0: * Called from ssl3_GatherCompleteHandshake michael@0: * ssl3_RestartHandshakeAfterCertReq michael@0: * michael@0: * Caller must hold the RecvBufLock. michael@0: * michael@0: * This function aquires and releases the SSL3Handshake Lock, holding the michael@0: * lock around any calls to functions that handle records other than michael@0: * Application Data records. michael@0: */ michael@0: SECStatus michael@0: ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) michael@0: { michael@0: const ssl3BulkCipherDef *cipher_def; michael@0: ssl3CipherSpec * crSpec; michael@0: SECStatus rv; michael@0: unsigned int hashBytes = MAX_MAC_LENGTH + 1; michael@0: PRBool isTLS; michael@0: SSL3ContentType rType; michael@0: SSL3Opaque hash[MAX_MAC_LENGTH]; michael@0: SSL3Opaque givenHashBuf[MAX_MAC_LENGTH]; michael@0: SSL3Opaque *givenHash; michael@0: sslBuffer *plaintext; michael@0: sslBuffer temp_buf; michael@0: PRUint64 dtls_seq_num; michael@0: unsigned int ivLen = 0; michael@0: unsigned int originalLen = 0; michael@0: unsigned int good; michael@0: unsigned int minLength; michael@0: unsigned char header[13]; michael@0: unsigned int headerLen; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); michael@0: michael@0: if (!ss->ssl3.initialized) { michael@0: ssl_GetSSL3HandshakeLock(ss); michael@0: rv = ssl3_InitState(ss); michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: if (rv != SECSuccess) { michael@0: return rv; /* ssl3_InitState has set the error code. */ michael@0: } michael@0: } michael@0: michael@0: /* check for Token Presence */ michael@0: if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { michael@0: PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX(). michael@0: * This implies that databuf holds a previously deciphered SSL Handshake michael@0: * message. michael@0: */ michael@0: if (cText == NULL) { michael@0: SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", michael@0: SSL_GETPID(), ss->fd)); michael@0: rType = content_handshake; michael@0: goto process_it; michael@0: } michael@0: michael@0: ssl_GetSpecReadLock(ss); /******************************************/ michael@0: michael@0: crSpec = ss->ssl3.crSpec; michael@0: cipher_def = crSpec->cipher_def; michael@0: michael@0: /* michael@0: * DTLS relevance checks: michael@0: * Note that this code currently ignores all out-of-epoch packets, michael@0: * which means we lose some in the case of rehandshake + michael@0: * loss/reordering. Since DTLS is explicitly unreliable, this michael@0: * seems like a good tradeoff for implementation effort and is michael@0: * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1 michael@0: */ michael@0: if (IS_DTLS(ss)) { michael@0: DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff; michael@0: michael@0: if (crSpec->epoch != epoch) { michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet " michael@0: "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch)); michael@0: /* Silently drop the packet */ michael@0: databuf->len = 0; /* Needed to ensure data not left around */ michael@0: return SECSuccess; michael@0: } michael@0: michael@0: dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) | michael@0: ((PRUint64)cText->seq_num.low); michael@0: michael@0: if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) { michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting " michael@0: "potentially replayed packet", SSL_GETPID(), ss->fd)); michael@0: /* Silently drop the packet */ michael@0: databuf->len = 0; /* Needed to ensure data not left around */ michael@0: return SECSuccess; michael@0: } michael@0: } michael@0: michael@0: good = ~0U; michael@0: minLength = crSpec->mac_size; michael@0: if (cipher_def->type == type_block) { michael@0: /* CBC records have a padding length byte at the end. */ michael@0: minLength++; michael@0: if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { michael@0: /* With >= TLS 1.1, CBC records have an explicit IV. */ michael@0: minLength += cipher_def->iv_size; michael@0: } michael@0: } else if (cipher_def->type == type_aead) { michael@0: minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; michael@0: } michael@0: michael@0: /* We can perform this test in variable time because the record's total michael@0: * length and the ciphersuite are both public knowledge. */ michael@0: if (cText->buf->len < minLength) { michael@0: goto decrypt_loser; michael@0: } michael@0: michael@0: if (cipher_def->type == type_block && michael@0: crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { michael@0: /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states michael@0: * "The receiver decrypts the entire GenericBlockCipher structure and michael@0: * then discards the first cipher block corresponding to the IV michael@0: * component." Instead, we decrypt the first cipher block and then michael@0: * discard it before decrypting the rest. michael@0: */ michael@0: SSL3Opaque iv[MAX_IV_LENGTH]; michael@0: int decoded; michael@0: michael@0: ivLen = cipher_def->iv_size; michael@0: if (ivLen < 8 || ivLen > sizeof(iv)) { michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return SECFailure; michael@0: } michael@0: michael@0: PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen)); michael@0: michael@0: /* The decryption result is garbage, but since we just throw away michael@0: * the block it doesn't matter. The decryption of the next block michael@0: * depends only on the ciphertext of the IV block. michael@0: */ michael@0: rv = crSpec->decode(crSpec->decodeContext, iv, &decoded, michael@0: sizeof(iv), cText->buf->buf, ivLen); michael@0: michael@0: good &= SECStatusToMask(rv); michael@0: } michael@0: michael@0: /* If we will be decompressing the buffer we need to decrypt somewhere michael@0: * other than into databuf */ michael@0: if (crSpec->decompressor) { michael@0: temp_buf.buf = NULL; michael@0: temp_buf.space = 0; michael@0: plaintext = &temp_buf; michael@0: } else { michael@0: plaintext = databuf; michael@0: } michael@0: michael@0: plaintext->len = 0; /* filled in by decode call below. */ michael@0: if (plaintext->space < MAX_FRAGMENT_LENGTH) { michael@0: rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); michael@0: if (rv != SECSuccess) { michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", michael@0: SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); michael@0: /* sslBuffer_Grow has set a memory error code. */ michael@0: /* Perhaps we should send an alert. (but we have no memory!) */ michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, michael@0: cText->buf->len - ivLen)); michael@0: michael@0: isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); michael@0: michael@0: if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: SSL3_SendAlert(ss, alert_fatal, record_overflow); michael@0: PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); michael@0: return SECFailure; michael@0: } michael@0: michael@0: rType = cText->type; michael@0: if (cipher_def->type == type_aead) { michael@0: /* XXX For many AEAD ciphers, the plaintext is shorter than the michael@0: * ciphertext by a fixed byte count, but it is not true in general. michael@0: * Each AEAD cipher should provide a function that returns the michael@0: * plaintext length for a given ciphertext. */ michael@0: unsigned int decryptedLen = michael@0: cText->buf->len - cipher_def->explicit_nonce_size - michael@0: cipher_def->tag_size; michael@0: headerLen = ssl3_BuildRecordPseudoHeader( michael@0: header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, michael@0: rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); michael@0: PORT_Assert(headerLen <= sizeof(header)); michael@0: rv = crSpec->aead( michael@0: ss->sec.isServer ? &crSpec->client : &crSpec->server, michael@0: PR_TRUE, /* do decrypt */ michael@0: plaintext->buf, /* out */ michael@0: (int*) &plaintext->len, /* outlen */ michael@0: plaintext->space, /* maxout */ michael@0: cText->buf->buf, /* in */ michael@0: cText->buf->len, /* inlen */ michael@0: header, headerLen); michael@0: if (rv != SECSuccess) { michael@0: good = 0; michael@0: } michael@0: } else { michael@0: if (cipher_def->type == type_block && michael@0: ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { michael@0: goto decrypt_loser; michael@0: } michael@0: michael@0: /* decrypt from cText buf to plaintext. */ michael@0: rv = crSpec->decode( michael@0: crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, michael@0: plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); michael@0: if (rv != SECSuccess) { michael@0: goto decrypt_loser; michael@0: } michael@0: michael@0: PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); michael@0: michael@0: originalLen = plaintext->len; michael@0: michael@0: /* If it's a block cipher, check and strip the padding. */ michael@0: if (cipher_def->type == type_block) { michael@0: const unsigned int blockSize = cipher_def->block_size; michael@0: const unsigned int macSize = crSpec->mac_size; michael@0: michael@0: if (!isTLS) { michael@0: good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( michael@0: plaintext, blockSize, macSize)); michael@0: } else { michael@0: good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( michael@0: plaintext, macSize)); michael@0: } michael@0: } michael@0: michael@0: /* compute the MAC */ michael@0: headerLen = ssl3_BuildRecordPseudoHeader( michael@0: header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, michael@0: rType, isTLS, cText->version, IS_DTLS(ss), michael@0: plaintext->len - crSpec->mac_size); michael@0: PORT_Assert(headerLen <= sizeof(header)); michael@0: if (cipher_def->type == type_block) { michael@0: rv = ssl3_ComputeRecordMACConstantTime( michael@0: crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, michael@0: plaintext->buf, plaintext->len, originalLen, michael@0: hash, &hashBytes); michael@0: michael@0: ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, michael@0: crSpec->mac_size); michael@0: givenHash = givenHashBuf; michael@0: michael@0: /* plaintext->len will always have enough space to remove the MAC michael@0: * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust michael@0: * plaintext->len if the result has enough space for the MAC and we michael@0: * tested the unadjusted size against minLength, above. */ michael@0: plaintext->len -= crSpec->mac_size; michael@0: } else { michael@0: /* This is safe because we checked the minLength above. */ michael@0: plaintext->len -= crSpec->mac_size; michael@0: michael@0: rv = ssl3_ComputeRecordMAC( michael@0: crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, michael@0: plaintext->buf, plaintext->len, hash, &hashBytes); michael@0: michael@0: /* We can read the MAC directly from the record because its location michael@0: * is public when a stream cipher is used. */ michael@0: givenHash = plaintext->buf + plaintext->len; michael@0: } michael@0: michael@0: good &= SECStatusToMask(rv); michael@0: michael@0: if (hashBytes != (unsigned)crSpec->mac_size || michael@0: NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { michael@0: /* We're allowed to leak whether or not the MAC check was correct */ michael@0: good = 0; michael@0: } michael@0: } michael@0: michael@0: if (good == 0) { michael@0: decrypt_loser: michael@0: /* must not hold spec lock when calling SSL3_SendAlert. */ michael@0: ssl_ReleaseSpecReadLock(ss); michael@0: michael@0: SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); michael@0: michael@0: if (!IS_DTLS(ss)) { michael@0: SSL3_SendAlert(ss, alert_fatal, bad_record_mac); michael@0: /* always log mac error, in case attacker can read server logs. */ michael@0: PORT_SetError(SSL_ERROR_BAD_MAC_READ); michael@0: return SECFailure; michael@0: } else { michael@0: /* Silently drop the packet */ michael@0: databuf->len = 0; /* Needed to ensure data not left around */ michael@0: return SECSuccess; michael@0: } michael@0: } michael@0: michael@0: if (!IS_DTLS(ss)) { michael@0: ssl3_BumpSequenceNumber(&crSpec->read_seq_num); michael@0: } else { michael@0: dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); michael@0: } michael@0: michael@0: ssl_ReleaseSpecReadLock(ss); /*****************************************/ michael@0: michael@0: /* michael@0: * The decrypted data is now in plaintext. michael@0: */ michael@0: michael@0: /* possibly decompress the record. If we aren't using compression then michael@0: * plaintext == databuf and so the uncompressed data is already in michael@0: * databuf. */ michael@0: if (crSpec->decompressor) { michael@0: if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { michael@0: rv = sslBuffer_Grow( michael@0: databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); michael@0: if (rv != SECSuccess) { michael@0: SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", michael@0: SSL_GETPID(), ss->fd, michael@0: plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION)); michael@0: /* sslBuffer_Grow has set a memory error code. */ michael@0: /* Perhaps we should send an alert. (but we have no memory!) */ michael@0: PORT_Free(plaintext->buf); michael@0: return SECFailure; michael@0: } michael@0: } michael@0: michael@0: rv = crSpec->decompressor(crSpec->decompressContext, michael@0: databuf->buf, michael@0: (int*) &databuf->len, michael@0: databuf->space, michael@0: plaintext->buf, michael@0: plaintext->len); michael@0: michael@0: if (rv != SECSuccess) { michael@0: int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); michael@0: SSL3_SendAlert(ss, alert_fatal, michael@0: isTLS ? decompression_failure : bad_record_mac); michael@0: michael@0: /* There appears to be a bug with (at least) Apache + OpenSSL where michael@0: * resumed SSLv3 connections don't actually use compression. See michael@0: * comments 93-95 of michael@0: * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 michael@0: * michael@0: * So, if we get a decompression error, and the record appears to michael@0: * be already uncompressed, then we return a more specific error michael@0: * code to hopefully save somebody some debugging time in the michael@0: * future. michael@0: */ michael@0: if (plaintext->len >= 4) { michael@0: unsigned int len = ((unsigned int) plaintext->buf[1] << 16) | michael@0: ((unsigned int) plaintext->buf[2] << 8) | michael@0: (unsigned int) plaintext->buf[3]; michael@0: if (len == plaintext->len - 4) { michael@0: /* This appears to be uncompressed already */ michael@0: err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; michael@0: } michael@0: } michael@0: michael@0: PORT_Free(plaintext->buf); michael@0: PORT_SetError(err); michael@0: return SECFailure; michael@0: } michael@0: michael@0: PORT_Free(plaintext->buf); michael@0: } michael@0: michael@0: /* michael@0: ** Having completed the decompression, check the length again. michael@0: */ michael@0: if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) { michael@0: SSL3_SendAlert(ss, alert_fatal, record_overflow); michael@0: PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* Application data records are processed by the caller of this michael@0: ** function, not by this function. michael@0: */ michael@0: if (rType == content_application_data) { michael@0: if (ss->firstHsDone) michael@0: return SECSuccess; michael@0: (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); michael@0: PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); michael@0: return SECFailure; michael@0: } michael@0: michael@0: /* It's a record that must be handled by ssl itself, not the application. michael@0: */ michael@0: process_it: michael@0: /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting michael@0: * data ang getting the xmit lock here prevents deadlocks. michael@0: */ michael@0: ssl_GetSSL3HandshakeLock(ss); michael@0: michael@0: /* All the functions called in this switch MUST set error code if michael@0: ** they return SECFailure or SECWouldBlock. michael@0: */ michael@0: switch (rType) { michael@0: case content_change_cipher_spec: michael@0: rv = ssl3_HandleChangeCipherSpecs(ss, databuf); michael@0: break; michael@0: case content_alert: michael@0: rv = ssl3_HandleAlert(ss, databuf); michael@0: break; michael@0: case content_handshake: michael@0: if (!IS_DTLS(ss)) { michael@0: rv = ssl3_HandleHandshake(ss, databuf); michael@0: } else { michael@0: rv = dtls_HandleHandshake(ss, databuf); michael@0: } michael@0: break; michael@0: /* michael@0: case content_application_data is handled before this switch michael@0: */ michael@0: default: michael@0: SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", michael@0: SSL_GETPID(), ss->fd, cText->type)); michael@0: /* XXX Send an alert ??? */ michael@0: PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); michael@0: rv = SECFailure; michael@0: break; michael@0: } michael@0: michael@0: ssl_ReleaseSSL3HandshakeLock(ss); michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * Initialization functions michael@0: */ michael@0: michael@0: /* Called from ssl3_InitState, immediately below. */ michael@0: /* Caller must hold the SpecWriteLock. */ michael@0: static void michael@0: ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) michael@0: { michael@0: spec->cipher_def = &bulk_cipher_defs[cipher_null]; michael@0: PORT_Assert(spec->cipher_def->cipher == cipher_null); michael@0: spec->mac_def = &mac_defs[mac_null]; michael@0: PORT_Assert(spec->mac_def->mac == mac_null); michael@0: spec->encode = Null_Cipher; michael@0: spec->decode = Null_Cipher; michael@0: spec->destroy = NULL; michael@0: spec->compressor = NULL; michael@0: spec->decompressor = NULL; michael@0: spec->destroyCompressContext = NULL; michael@0: spec->destroyDecompressContext = NULL; michael@0: spec->mac_size = 0; michael@0: spec->master_secret = NULL; michael@0: spec->bypassCiphers = PR_FALSE; michael@0: michael@0: spec->msItem.data = NULL; michael@0: spec->msItem.len = 0; michael@0: michael@0: spec->client.write_key = NULL; michael@0: spec->client.write_mac_key = NULL; michael@0: spec->client.write_mac_context = NULL; michael@0: michael@0: spec->server.write_key = NULL; michael@0: spec->server.write_mac_key = NULL; michael@0: spec->server.write_mac_context = NULL; michael@0: michael@0: spec->write_seq_num.high = 0; michael@0: spec->write_seq_num.low = 0; michael@0: michael@0: spec->read_seq_num.high = 0; michael@0: spec->read_seq_num.low = 0; michael@0: michael@0: spec->epoch = 0; michael@0: dtls_InitRecvdRecords(&spec->recvdRecords); michael@0: michael@0: spec->version = ss->vrange.max; michael@0: } michael@0: michael@0: /* Called from: ssl3_SendRecord michael@0: ** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() michael@0: ** ssl3_SendClientHello() michael@0: ** ssl3_HandleV2ClientHello() michael@0: ** ssl3_HandleRecord() michael@0: ** michael@0: ** This function should perhaps acquire and release the SpecWriteLock. michael@0: ** michael@0: ** michael@0: */ michael@0: static SECStatus michael@0: ssl3_InitState(sslSocket *ss) michael@0: { michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); michael@0: michael@0: if (ss->ssl3.initialized) michael@0: return SECSuccess; /* Function should be idempotent */ michael@0: michael@0: ss->ssl3.policy = SSL_ALLOWED; michael@0: michael@0: ssl_GetSpecWriteLock(ss); michael@0: ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0]; michael@0: ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1]; michael@0: ss->ssl3.hs.sendingSCSV = PR_FALSE; michael@0: ssl3_InitCipherSpec(ss, ss->ssl3.crSpec); michael@0: ssl3_InitCipherSpec(ss, ss->ssl3.prSpec); michael@0: michael@0: ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello; michael@0: #ifndef NSS_DISABLE_ECC michael@0: ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss); michael@0: #endif michael@0: ssl_ReleaseSpecWriteLock(ss); michael@0: michael@0: PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: ss->ssl3.hs.sendMessageSeq = 0; michael@0: ss->ssl3.hs.recvMessageSeq = 0; michael@0: ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; michael@0: ss->ssl3.hs.rtRetries = 0; michael@0: ss->ssl3.hs.recvdHighWater = -1; michael@0: PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); michael@0: dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ michael@0: } michael@0: michael@0: PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space); michael@0: ss->ssl3.hs.messages.buf = NULL; michael@0: ss->ssl3.hs.messages.space = 0; michael@0: michael@0: ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; michael@0: PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, michael@0: sizeof(ss->ssl3.hs.newSessionTicket)); michael@0: michael@0: ss->ssl3.initialized = PR_TRUE; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* Returns a reference counted object that contains a key pair. michael@0: * Or NULL on failure. Initial ref count is 1. michael@0: * Uses the keys in the pair as input. michael@0: */ michael@0: ssl3KeyPair * michael@0: ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey) michael@0: { michael@0: ssl3KeyPair * pair; michael@0: michael@0: if (!privKey || !pubKey) { michael@0: PORT_SetError(PR_INVALID_ARGUMENT_ERROR); michael@0: return NULL; michael@0: } michael@0: pair = PORT_ZNew(ssl3KeyPair); michael@0: if (!pair) michael@0: return NULL; /* error code is set. */ michael@0: pair->refCount = 1; michael@0: pair->privKey = privKey; michael@0: pair->pubKey = pubKey; michael@0: return pair; /* success */ michael@0: } michael@0: michael@0: ssl3KeyPair * michael@0: ssl3_GetKeyPairRef(ssl3KeyPair * keyPair) michael@0: { michael@0: PR_ATOMIC_INCREMENT(&keyPair->refCount); michael@0: return keyPair; michael@0: } michael@0: michael@0: void michael@0: ssl3_FreeKeyPair(ssl3KeyPair * keyPair) michael@0: { michael@0: PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); michael@0: if (!newCount) { michael@0: if (keyPair->privKey) michael@0: SECKEY_DestroyPrivateKey(keyPair->privKey); michael@0: if (keyPair->pubKey) michael@0: SECKEY_DestroyPublicKey( keyPair->pubKey); michael@0: PORT_Free(keyPair); michael@0: } michael@0: } michael@0: michael@0: michael@0: michael@0: /* michael@0: * Creates the public and private RSA keys for SSL Step down. michael@0: * Called from SSL_ConfigSecureServer in sslsecur.c michael@0: */ michael@0: SECStatus michael@0: ssl3_CreateRSAStepDownKeys(sslSocket *ss) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: SECKEYPrivateKey * privKey; /* RSA step down key */ michael@0: SECKEYPublicKey * pubKey; /* RSA step down key */ michael@0: michael@0: if (ss->stepDownKeyPair) michael@0: ssl3_FreeKeyPair(ss->stepDownKeyPair); michael@0: ss->stepDownKeyPair = NULL; michael@0: #ifndef HACKED_EXPORT_SERVER michael@0: /* Sigh, should have a get key strength call for private keys */ michael@0: if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) > michael@0: EXPORT_RSA_KEY_LENGTH) { michael@0: /* need to ask for the key size in bits */ michael@0: privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, michael@0: &pubKey, NULL); michael@0: if (!privKey || !pubKey || michael@0: !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { michael@0: ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); michael@0: rv = SECFailure; michael@0: } michael@0: } michael@0: #endif michael@0: return rv; michael@0: } michael@0: michael@0: michael@0: /* record the export policy for this cipher suite */ michael@0: SECStatus michael@0: ssl3_SetPolicy(ssl3CipherSuite which, int policy) michael@0: { michael@0: ssl3CipherSuiteCfg *suite; michael@0: michael@0: suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); michael@0: if (suite == NULL) { michael@0: return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ michael@0: } michael@0: suite->policy = policy; michael@0: michael@0: return SECSuccess; michael@0: } michael@0: michael@0: SECStatus michael@0: ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) michael@0: { michael@0: ssl3CipherSuiteCfg *suite; michael@0: PRInt32 policy; michael@0: SECStatus rv; michael@0: michael@0: suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); michael@0: if (suite) { michael@0: policy = suite->policy; michael@0: rv = SECSuccess; michael@0: } else { michael@0: policy = SSL_NOT_ALLOWED; michael@0: rv = SECFailure; /* err code was set by Lookup. */ michael@0: } michael@0: *oPolicy = policy; michael@0: return rv; michael@0: } michael@0: michael@0: /* record the user preference for this suite */ michael@0: SECStatus michael@0: ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) michael@0: { michael@0: ssl3CipherSuiteCfg *suite; michael@0: michael@0: suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); michael@0: if (suite == NULL) { michael@0: return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ michael@0: } michael@0: suite->enabled = enabled; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* return the user preference for this suite */ michael@0: SECStatus michael@0: ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) michael@0: { michael@0: ssl3CipherSuiteCfg *suite; michael@0: PRBool pref; michael@0: SECStatus rv; michael@0: michael@0: suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); michael@0: if (suite) { michael@0: pref = suite->enabled; michael@0: rv = SECSuccess; michael@0: } else { michael@0: pref = SSL_NOT_ALLOWED; michael@0: rv = SECFailure; /* err code was set by Lookup. */ michael@0: } michael@0: *enabled = pref; michael@0: return rv; michael@0: } michael@0: michael@0: SECStatus michael@0: ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) michael@0: { michael@0: ssl3CipherSuiteCfg *suite; michael@0: michael@0: suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); michael@0: if (suite == NULL) { michael@0: return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ michael@0: } michael@0: suite->enabled = enabled; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: SECStatus michael@0: ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) michael@0: { michael@0: ssl3CipherSuiteCfg *suite; michael@0: PRBool pref; michael@0: SECStatus rv; michael@0: michael@0: suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); michael@0: if (suite) { michael@0: pref = suite->enabled; michael@0: rv = SECSuccess; michael@0: } else { michael@0: pref = SSL_NOT_ALLOWED; michael@0: rv = SECFailure; /* err code was set by Lookup. */ michael@0: } michael@0: *enabled = pref; michael@0: return rv; michael@0: } michael@0: michael@0: /* copy global default policy into socket. */ michael@0: void michael@0: ssl3_InitSocketPolicy(sslSocket *ss) michael@0: { michael@0: PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites); michael@0: } michael@0: michael@0: /* ssl3_config_match_init must have already been called by michael@0: * the caller of this function. michael@0: */ michael@0: SECStatus michael@0: ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) michael@0: { michael@0: int i, count = 0; michael@0: michael@0: PORT_Assert(ss != 0); michael@0: if (!ss) { michael@0: PORT_SetError(PR_INVALID_ARGUMENT_ERROR); michael@0: return SECFailure; michael@0: } michael@0: if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { michael@0: *size = 0; michael@0: return SECSuccess; michael@0: } michael@0: if (cs == NULL) { michael@0: *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* ssl3_config_match_init was called by the caller of this function. */ michael@0: for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { michael@0: ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; michael@0: if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange)) { michael@0: if (cs != NULL) { michael@0: *cs++ = 0x00; michael@0: *cs++ = (suite->cipher_suite >> 8) & 0xFF; michael@0: *cs++ = suite->cipher_suite & 0xFF; michael@0: } michael@0: count++; michael@0: } michael@0: } michael@0: *size = count; michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* michael@0: ** If ssl3 socket has completed the first handshake, and is in idle state, michael@0: ** then start a new handshake. michael@0: ** If flushCache is true, the SID cache will be flushed first, forcing a michael@0: ** "Full" handshake (not a session restart handshake), to be done. michael@0: ** michael@0: ** called from SSL_RedoHandshake(), which already holds the handshake locks. michael@0: */ michael@0: SECStatus michael@0: ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) michael@0: { michael@0: sslSessionID * sid = ss->sec.ci.sid; michael@0: SECStatus rv; michael@0: michael@0: PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); michael@0: michael@0: if (!ss->firstHsDone || michael@0: ((ss->version >= SSL_LIBRARY_VERSION_3_0) && michael@0: ss->ssl3.initialized && michael@0: (ss->ssl3.hs.ws != idle_handshake))) { michael@0: PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (IS_DTLS(ss)) { michael@0: dtls_RehandshakeCleanup(ss); michael@0: } michael@0: michael@0: if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { michael@0: PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); michael@0: return SECFailure; michael@0: } michael@0: if (sid && flushCache) { michael@0: if (ss->sec.uncache) michael@0: ss->sec.uncache(sid); /* remove it from whichever cache it's in. */ michael@0: ssl_FreeSID(sid); /* dec ref count and free if zero. */ michael@0: ss->sec.ci.sid = NULL; michael@0: } michael@0: michael@0: ssl_GetXmitBufLock(ss); /**************************************/ michael@0: michael@0: /* start off a new handshake. */ michael@0: rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss) michael@0: : ssl3_SendClientHello(ss, PR_FALSE); michael@0: michael@0: ssl_ReleaseXmitBufLock(ss); /**************************************/ michael@0: return rv; michael@0: } michael@0: michael@0: /* Called from ssl_DestroySocketContents() in sslsock.c */ michael@0: void michael@0: ssl3_DestroySSL3Info(sslSocket *ss) michael@0: { michael@0: michael@0: if (ss->ssl3.clientCertificate != NULL) michael@0: CERT_DestroyCertificate(ss->ssl3.clientCertificate); michael@0: michael@0: if (ss->ssl3.clientPrivateKey != NULL) michael@0: SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); michael@0: michael@0: if (ss->ssl3.peerCertArena != NULL) michael@0: ssl3_CleanupPeerCerts(ss); michael@0: michael@0: if (ss->ssl3.clientCertChain != NULL) { michael@0: CERT_DestroyCertificateList(ss->ssl3.clientCertChain); michael@0: ss->ssl3.clientCertChain = NULL; michael@0: } michael@0: michael@0: /* clean up handshake */ michael@0: #ifndef NO_PKCS11_BYPASS michael@0: if (ss->opt.bypassPKCS11) { michael@0: if (ss->ssl3.hs.hashType == handshake_hash_combo) { michael@0: SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); michael@0: MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); michael@0: } else if (ss->ssl3.hs.hashType == handshake_hash_single) { michael@0: ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); michael@0: } michael@0: } michael@0: #endif michael@0: if (ss->ssl3.hs.md5) { michael@0: PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); michael@0: } michael@0: if (ss->ssl3.hs.sha) { michael@0: PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); michael@0: } michael@0: if (ss->ssl3.hs.clientSigAndHash) { michael@0: PORT_Free(ss->ssl3.hs.clientSigAndHash); michael@0: } michael@0: if (ss->ssl3.hs.messages.buf) { michael@0: PORT_Free(ss->ssl3.hs.messages.buf); michael@0: ss->ssl3.hs.messages.buf = NULL; michael@0: ss->ssl3.hs.messages.len = 0; michael@0: ss->ssl3.hs.messages.space = 0; michael@0: } michael@0: michael@0: /* free the SSL3Buffer (msg_body) */ michael@0: PORT_Free(ss->ssl3.hs.msg_body.buf); michael@0: michael@0: SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); michael@0: michael@0: /* free up the CipherSpecs */ michael@0: ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/); michael@0: ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/); michael@0: michael@0: /* Destroy the DTLS data */ michael@0: if (IS_DTLS(ss)) { michael@0: dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); michael@0: if (ss->ssl3.hs.recvdFragments.buf) { michael@0: PORT_Free(ss->ssl3.hs.recvdFragments.buf); michael@0: } michael@0: } michael@0: michael@0: ss->ssl3.initialized = PR_FALSE; michael@0: michael@0: SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); michael@0: } michael@0: michael@0: /* End of ssl3con.c */