ssl3con.c (517196B)
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ 2 /* 3 * SSL3 Protocol 4 * 5 * This Source Code Form is subject to the terms of the Mozilla Public 6 * License, v. 2.0. If a copy of the MPL was not distributed with this 7 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 8 9 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */ 10 11 #include "cert.h" 12 #include "ssl.h" 13 #include "cryptohi.h" /* for DSAU_ stuff */ 14 #include "keyhi.h" 15 #include "secder.h" 16 #include "secitem.h" 17 #include "sechash.h" 18 19 #include "sslimpl.h" 20 #include "sslproto.h" 21 #include "sslerr.h" 22 #include "ssl3ext.h" 23 #include "ssl3exthandle.h" 24 #include "tls13ech.h" 25 #include "tls13exthandle.h" 26 #include "tls13psk.h" 27 #include "tls13subcerts.h" 28 #include "prtime.h" 29 #include "prinrval.h" 30 #include "prerror.h" 31 #include "pratom.h" 32 #include "prthread.h" 33 #include "nss.h" 34 #include "nssoptions.h" 35 36 #include "pk11func.h" 37 #include "secmod.h" 38 #include "blapi.h" 39 40 #include <limits.h> 41 #include <stdio.h> 42 43 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, 44 PK11SlotInfo *serverKeySlot); 45 static SECStatus ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms, 46 PK11SymKey **msp); 47 static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss, 48 PK11SymKey *masterSecret); 49 static SECStatus ssl3_HandshakeFailure(sslSocket *ss); 50 static SECStatus ssl3_SendCertificate(sslSocket *ss); 51 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss); 52 static SECStatus ssl3_SendNextProto(sslSocket *ss); 53 static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags); 54 static SECStatus ssl3_SendServerHelloDone(sslSocket *ss); 55 static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss); 56 static SECStatus ssl3_HandleClientHelloPart2(sslSocket *ss, 57 SECItem *suites, 58 sslSessionID *sid, 59 const PRUint8 *msg, 60 unsigned int len); 61 static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss, 62 const SECItem *sidBytes, 63 int *retErrCode); 64 static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, 65 PRUint8 *b, 66 PRUint32 length); 67 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); 68 static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType); 69 static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash); 70 PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme); 71 PRBool ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme); 72 PRBool ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme); 73 PRBool ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme); 74 static SECStatus ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, 75 const unsigned char *b, 76 unsigned int l); 77 const PRUint32 kSSLSigSchemePolicy = 78 NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_ANY_SIGNATURE; 79 80 const PRUint8 ssl_hello_retry_random[] = { 81 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 82 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, 83 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 84 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C 85 }; 86 PR_STATIC_ASSERT(PR_ARRAY_SIZE(ssl_hello_retry_random) == SSL3_RANDOM_LENGTH); 87 88 /* This list of SSL3 cipher suites is sorted in descending order of 89 * precedence (desirability). It only includes cipher suites we implement. 90 * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites 91 * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c) 92 * 93 * Important: See bug 946147 before enabling, reordering, or adding any cipher 94 * suites to this list. 95 */ 96 /* clang-format off */ 97 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { 98 /* cipher_suite policy enabled isPresent */ 99 /* Special TLS 1.3 suites. */ 100 { TLS_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE }, 101 { TLS_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE }, 102 { TLS_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE }, 103 104 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 105 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 106 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 107 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 108 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 109 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 110 /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around 111 * bug 946147. 112 */ 113 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 114 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 115 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 116 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 117 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 118 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 119 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 120 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 121 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 122 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 123 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 124 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 125 126 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 127 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE, PR_FALSE}, 128 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 129 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 130 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 131 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 132 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 133 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 134 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 135 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 136 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 137 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 138 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 139 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 140 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 141 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 142 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 143 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 144 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 145 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 146 147 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 148 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 149 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 150 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 151 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 152 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 153 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 154 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 155 156 /* RSA */ 157 { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 158 { TLS_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 159 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 160 { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 161 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 162 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 163 { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 164 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 165 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 166 { TLS_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 167 { TLS_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 168 { TLS_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 169 170 /* 56-bit DES "domestic" cipher suites */ 171 { TLS_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 172 { TLS_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 173 { TLS_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 174 175 /* ciphersuites with no encryption */ 176 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 177 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 178 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 179 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 180 { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 181 { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 182 { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 183 }; 184 /* clang-format on */ 185 186 /* This is the default supported set of signature schemes. The order of the 187 * hashes here is all that is important, since that will (sometimes) determine 188 * which hash we use. The key pair (i.e., cert) is the primary thing that 189 * determines what we use and this doesn't affect how we select key pairs. The 190 * order of signature types is based on the same rules for ordering we use for 191 * cipher suites just for consistency. 192 */ 193 static const SSLSignatureScheme defaultSignatureSchemes[] = { 194 ssl_sig_ecdsa_secp256r1_sha256, 195 ssl_sig_ecdsa_secp384r1_sha384, 196 ssl_sig_ecdsa_secp521r1_sha512, 197 ssl_sig_ecdsa_sha1, 198 ssl_sig_rsa_pss_rsae_sha256, 199 ssl_sig_rsa_pss_rsae_sha384, 200 ssl_sig_rsa_pss_rsae_sha512, 201 ssl_sig_rsa_pkcs1_sha256, 202 ssl_sig_rsa_pkcs1_sha384, 203 ssl_sig_rsa_pkcs1_sha512, 204 ssl_sig_rsa_pkcs1_sha1, 205 ssl_sig_dsa_sha256, 206 ssl_sig_dsa_sha384, 207 ssl_sig_dsa_sha512, 208 ssl_sig_dsa_sha1 209 }; 210 PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureSchemes) <= 211 MAX_SIGNATURE_SCHEMES); 212 213 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order. 214 */ 215 #ifdef DEBUG 216 void 217 ssl3_CheckCipherSuiteOrderConsistency() 218 { 219 unsigned int i; 220 221 PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites)); 222 223 for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) { 224 PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite); 225 } 226 } 227 #endif 228 229 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = { 230 ct_RSA_sign, 231 ct_ECDSA_sign, 232 ct_DSS_sign, 233 }; 234 235 static SSL3Statistics ssl3stats; 236 237 static const ssl3KEADef kea_defs[] = { 238 /* indexed by SSL3KeyExchangeAlgorithm */ 239 /* kea exchKeyType signKeyType authKeyType ephemeral oid */ 240 { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE, 0 }, 241 { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE, SEC_OID_TLS_RSA }, 242 { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE, SEC_OID_TLS_DH_DSS }, 243 { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE, SEC_OID_TLS_DH_RSA }, 244 { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE, SEC_OID_TLS_DHE_DSS }, 245 { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_DHE_RSA }, 246 { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_DH_ANON }, 247 { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA }, 248 { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA }, 249 { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE, SEC_OID_TLS_ECDH_RSA }, 250 { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_ECDHE_RSA }, 251 { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_ECDH_ANON }, 252 { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_ECDHE_PSK }, 253 { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_DHE_PSK }, 254 { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE, SEC_OID_TLS13_KEA_ANY }, 255 }; 256 257 /* must use ssl_LookupCipherSuiteDef to access */ 258 static const ssl3CipherSuiteDef cipher_suite_defs[] = { 259 /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg prf_hash */ 260 /* Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h. */ 261 262 { TLS_NULL_WITH_NULL_NULL, cipher_null, ssl_mac_null, kea_null, ssl_hash_none }, 263 { TLS_RSA_WITH_NULL_MD5, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none }, 264 { TLS_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none }, 265 { TLS_RSA_WITH_NULL_SHA256, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 }, 266 { TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none }, 267 { TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none }, 268 { TLS_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none }, 269 { TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none }, 270 { TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none }, 271 { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, 272 cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none }, 273 { TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none }, 274 { TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none }, 275 { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, 276 cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none }, 277 278 /* New TLS cipher suites */ 279 { TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none }, 280 { TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 }, 281 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none }, 282 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none }, 283 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 }, 284 { TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none }, 285 { TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 }, 286 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none }, 287 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none }, 288 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 }, 289 { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 }, 290 291 { TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none }, 292 293 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none }, 294 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, 295 cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none }, 296 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, 297 cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none }, 298 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none }, 299 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, 300 cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none }, 301 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, 302 cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none }, 303 304 { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 }, 305 { TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 }, 306 307 { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 }, 308 { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 }, 309 { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 }, 310 { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 }, 311 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 }, 312 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 }, 313 { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 }, 314 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 }, 315 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 }, 316 { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 }, 317 { TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 }, 318 319 { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 }, 320 321 { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 }, 322 { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 }, 323 324 { TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none }, 325 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none }, 326 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none }, 327 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none }, 328 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none }, 329 330 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none }, 331 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none }, 332 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none }, 333 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none }, 334 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 }, 335 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none }, 336 337 { TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none }, 338 { TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none }, 339 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none }, 340 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none }, 341 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none }, 342 343 { TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none }, 344 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none }, 345 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none }, 346 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none }, 347 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 }, 348 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none }, 349 350 { TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 }, 351 { TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 }, 352 { TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 }, 353 }; 354 355 static const CK_MECHANISM_TYPE auth_alg_defs[] = { 356 CKM_INVALID_MECHANISM, /* ssl_auth_null */ 357 CKM_RSA_PKCS, /* ssl_auth_rsa_decrypt */ 358 CKM_DSA, /* ? _SHA1 */ /* ssl_auth_dsa */ 359 CKM_INVALID_MECHANISM, /* ssl_auth_kea (unused) */ 360 CKM_ECDSA, /* ssl_auth_ecdsa */ 361 CKM_ECDH1_DERIVE, /* ssl_auth_ecdh_rsa */ 362 CKM_ECDH1_DERIVE, /* ssl_auth_ecdh_ecdsa */ 363 CKM_RSA_PKCS, /* ssl_auth_rsa_sign */ 364 CKM_RSA_PKCS_PSS, /* ssl_auth_rsa_pss */ 365 CKM_HKDF_DATA, /* ssl_auth_psk (just check for HKDF) */ 366 CKM_INVALID_MECHANISM /* ssl_auth_tls13_any */ 367 }; 368 PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size); 369 370 static const CK_MECHANISM_TYPE kea_alg_defs[] = { 371 CKM_INVALID_MECHANISM, /* ssl_kea_null */ 372 CKM_RSA_PKCS, /* ssl_kea_rsa */ 373 CKM_DH_PKCS_DERIVE, /* ssl_kea_dh */ 374 CKM_INVALID_MECHANISM, /* ssl_kea_fortezza (unused) */ 375 CKM_ECDH1_DERIVE, /* ssl_kea_ecdh */ 376 CKM_ECDH1_DERIVE, /* ssl_kea_ecdh_psk */ 377 CKM_DH_PKCS_DERIVE, /* ssl_kea_dh_psk */ 378 CKM_INVALID_MECHANISM, /* ssl_kea_tls13_any */ 379 CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid */ 380 CKM_INVALID_MECHANISM, /* ssl_kea_ecdh_hybrid_psk */ 381 }; 382 PR_STATIC_ASSERT(PR_ARRAY_SIZE(kea_alg_defs) == ssl_kea_size); 383 384 typedef struct SSLCipher2MechStr { 385 SSLCipherAlgorithm calg; 386 CK_MECHANISM_TYPE cmech; 387 } SSLCipher2Mech; 388 389 /* indexed by type SSLCipherAlgorithm */ 390 static const SSLCipher2Mech alg2Mech[] = { 391 /* calg, cmech */ 392 { ssl_calg_null, CKM_INVALID_MECHANISM }, 393 { ssl_calg_rc4, CKM_RC4 }, 394 { ssl_calg_rc2, CKM_RC2_CBC }, 395 { ssl_calg_des, CKM_DES_CBC }, 396 { ssl_calg_3des, CKM_DES3_CBC }, 397 { ssl_calg_idea, CKM_IDEA_CBC }, 398 { ssl_calg_fortezza, CKM_SKIPJACK_CBC64 }, 399 { ssl_calg_aes, CKM_AES_CBC }, 400 { ssl_calg_camellia, CKM_CAMELLIA_CBC }, 401 { ssl_calg_seed, CKM_SEED_CBC }, 402 { ssl_calg_aes_gcm, CKM_AES_GCM }, 403 { ssl_calg_chacha20, CKM_CHACHA20_POLY1305 }, 404 }; 405 406 const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, 407 0x47, 0x52, 0x44, 0x01 }; 408 const PRUint8 tls1_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, 409 0x47, 0x52, 0x44, 0x00 }; 410 PR_STATIC_ASSERT(sizeof(tls12_downgrade_random) == 411 sizeof(tls1_downgrade_random)); 412 413 /* The ECCWrappedKeyInfo structure defines how various pieces of 414 * information are laid out within wrappedSymmetricWrappingkey 415 * for ECDH key exchange. Since wrappedSymmetricWrappingkey is 416 * a 512-byte buffer (see sslimpl.h), the variable length field 417 * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes. 418 * 419 * XXX For now, NSS only supports named elliptic curves of size 571 bits 420 * or smaller. The public value will fit within 145 bytes and EC params 421 * will fit within 12 bytes. We'll need to revisit this when NSS 422 * supports arbitrary curves. 423 */ 424 #define MAX_EC_WRAPPED_KEY_BUFLEN 504 425 426 typedef struct ECCWrappedKeyInfoStr { 427 PRUint16 size; /* EC public key size in bits */ 428 PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */ 429 PRUint16 pubValueLen; /* length (in bytes) of EC public value */ 430 PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */ 431 PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */ 432 /* EC public-key params, the EC public value and the wrapped key */ 433 } ECCWrappedKeyInfo; 434 435 CK_MECHANISM_TYPE 436 ssl3_Alg2Mech(SSLCipherAlgorithm calg) 437 { 438 PORT_Assert(alg2Mech[calg].calg == calg); 439 return alg2Mech[calg].cmech; 440 } 441 442 #if defined(TRACE) 443 444 static char * 445 ssl3_DecodeHandshakeType(int msgType) 446 { 447 char *rv; 448 static char line[40]; 449 450 switch (msgType) { 451 case ssl_hs_hello_request: 452 rv = "hello_request (0)"; 453 break; 454 case ssl_hs_client_hello: 455 rv = "client_hello (1)"; 456 break; 457 case ssl_hs_server_hello: 458 rv = "server_hello (2)"; 459 break; 460 case ssl_hs_hello_verify_request: 461 rv = "hello_verify_request (3)"; 462 break; 463 case ssl_hs_new_session_ticket: 464 rv = "new_session_ticket (4)"; 465 break; 466 case ssl_hs_end_of_early_data: 467 rv = "end_of_early_data (5)"; 468 break; 469 case ssl_hs_hello_retry_request: 470 rv = "hello_retry_request (6)"; 471 break; 472 case ssl_hs_encrypted_extensions: 473 rv = "encrypted_extensions (8)"; 474 break; 475 case ssl_hs_certificate: 476 rv = "certificate (11)"; 477 break; 478 case ssl_hs_server_key_exchange: 479 rv = "server_key_exchange (12)"; 480 break; 481 case ssl_hs_certificate_request: 482 rv = "certificate_request (13)"; 483 break; 484 case ssl_hs_server_hello_done: 485 rv = "server_hello_done (14)"; 486 break; 487 case ssl_hs_certificate_verify: 488 rv = "certificate_verify (15)"; 489 break; 490 case ssl_hs_client_key_exchange: 491 rv = "client_key_exchange (16)"; 492 break; 493 case ssl_hs_finished: 494 rv = "finished (20)"; 495 break; 496 case ssl_hs_certificate_status: 497 rv = "certificate_status (22)"; 498 break; 499 case ssl_hs_key_update: 500 rv = "key_update (24)"; 501 break; 502 case ssl_hs_compressed_certificate: 503 rv = "compressed certificate (25)"; 504 break; 505 default: 506 snprintf(line, sizeof(line), "*UNKNOWN* handshake type! (%d)", msgType); 507 rv = line; 508 } 509 return rv; 510 } 511 512 static char * 513 ssl3_DecodeContentType(int msgType) 514 { 515 char *rv; 516 static char line[40]; 517 518 switch (msgType) { 519 case ssl_ct_change_cipher_spec: 520 rv = "change_cipher_spec (20)"; 521 break; 522 case ssl_ct_alert: 523 rv = "alert (21)"; 524 break; 525 case ssl_ct_handshake: 526 rv = "handshake (22)"; 527 break; 528 case ssl_ct_application_data: 529 rv = "application_data (23)"; 530 break; 531 case ssl_ct_ack: 532 rv = "ack (26)"; 533 break; 534 default: 535 snprintf(line, sizeof(line), "*UNKNOWN* record type! (%d)", msgType); 536 rv = line; 537 } 538 return rv; 539 } 540 541 #endif 542 543 PRBool 544 ssl_HaveRecvBufLock(sslSocket *ss) 545 { 546 if (!ss->opt.noLocks) { 547 return PZ_InMonitor(ss->recvBufLock); 548 } else { 549 return PR_TRUE; 550 } 551 } 552 553 PRBool 554 ssl_HaveXmitBufLock(sslSocket *ss) 555 { 556 if (!ss->opt.noLocks) { 557 return PZ_InMonitor(ss->xmitBufLock); 558 } else { 559 return PR_TRUE; 560 } 561 } 562 563 PRBool 564 ssl_Have1stHandshakeLock(sslSocket *ss) 565 { 566 if (!ss->opt.noLocks) { 567 return PZ_InMonitor(ss->firstHandshakeLock); 568 } else { 569 return PR_TRUE; 570 } 571 } 572 573 PRBool 574 ssl_HaveSSL3HandshakeLock(sslSocket *ss) 575 { 576 if (!ss->opt.noLocks) { 577 return PZ_InMonitor(ss->ssl3HandshakeLock); 578 } else { 579 return PR_TRUE; 580 } 581 } 582 583 PRBool 584 ssl_HaveSpecWriteLock(sslSocket *ss) 585 { 586 if (!ss->opt.noLocks) { 587 return NSSRWLock_HaveWriteLock(ss->specLock); 588 } else { 589 return PR_TRUE; 590 } 591 } 592 593 /* firstHandshakeLock -> recvBufLock */ 594 void 595 ssl_Get1stHandshakeLock(sslSocket *ss) 596 { 597 if (!ss->opt.noLocks) { 598 PORT_Assert(PZ_InMonitor(ss->firstHandshakeLock) || 599 !ssl_HaveRecvBufLock(ss)); 600 PZ_EnterMonitor(ss->firstHandshakeLock); 601 } 602 } 603 604 void 605 ssl_Release1stHandshakeLock(sslSocket *ss) 606 { 607 if (!ss->opt.noLocks) { 608 PZ_ExitMonitor(ss->firstHandshakeLock); 609 } 610 } 611 612 void 613 ssl_GetSSL3HandshakeLock(sslSocket *ss) 614 { 615 if (!ss->opt.noLocks) { 616 PORT_Assert(!ssl_HaveXmitBufLock(ss)); 617 PZ_EnterMonitor(ss->ssl3HandshakeLock); 618 } 619 } 620 621 void 622 ssl_ReleaseSSL3HandshakeLock(sslSocket *ss) 623 { 624 if (!ss->opt.noLocks) { 625 PZ_ExitMonitor(ss->ssl3HandshakeLock); 626 } 627 } 628 629 void 630 ssl_GetSpecReadLock(sslSocket *ss) 631 { 632 if (!ss->opt.noLocks) { 633 NSSRWLock_LockRead(ss->specLock); 634 } 635 } 636 637 void 638 ssl_ReleaseSpecReadLock(sslSocket *ss) 639 { 640 if (!ss->opt.noLocks) { 641 NSSRWLock_UnlockRead(ss->specLock); 642 } 643 } 644 645 /* NSSRWLock_HaveReadLock is not exported so there's no 646 * ssl_HaveSpecReadLock. */ 647 void 648 ssl_GetSpecWriteLock(sslSocket *ss) 649 { 650 if (!ss->opt.noLocks) { 651 NSSRWLock_LockWrite(ss->specLock); 652 } 653 } 654 655 void 656 ssl_ReleaseSpecWriteLock(sslSocket *ss) 657 { 658 if (!ss->opt.noLocks) { 659 NSSRWLock_UnlockWrite(ss->specLock); 660 } 661 } 662 663 /* recvBufLock -> ssl3HandshakeLock -> xmitBufLock */ 664 void 665 ssl_GetRecvBufLock(sslSocket *ss) 666 { 667 if (!ss->opt.noLocks) { 668 PORT_Assert(!ssl_HaveSSL3HandshakeLock(ss)); 669 PORT_Assert(!ssl_HaveXmitBufLock(ss)); 670 PZ_EnterMonitor(ss->recvBufLock); 671 } 672 } 673 674 void 675 ssl_ReleaseRecvBufLock(sslSocket *ss) 676 { 677 if (!ss->opt.noLocks) { 678 PZ_ExitMonitor(ss->recvBufLock); 679 } 680 } 681 682 /* xmitBufLock -> specLock */ 683 void 684 ssl_GetXmitBufLock(sslSocket *ss) 685 { 686 if (!ss->opt.noLocks) { 687 PZ_EnterMonitor(ss->xmitBufLock); 688 } 689 } 690 691 void 692 ssl_ReleaseXmitBufLock(sslSocket *ss) 693 { 694 if (!ss->opt.noLocks) { 695 PZ_ExitMonitor(ss->xmitBufLock); 696 } 697 } 698 699 SSL3Statistics * 700 SSL_GetStatistics(void) 701 { 702 return &ssl3stats; 703 } 704 705 typedef struct tooLongStr { 706 #if defined(IS_LITTLE_ENDIAN) 707 PRInt32 low; 708 PRInt32 high; 709 #else 710 PRInt32 high; 711 PRInt32 low; 712 #endif 713 } tooLong; 714 715 void 716 SSL_AtomicIncrementLong(long *x) 717 { 718 if ((sizeof *x) == sizeof(PRInt32)) { 719 PR_ATOMIC_INCREMENT((PRInt32 *)x); 720 } else { 721 tooLong *tl = (tooLong *)x; 722 if (PR_ATOMIC_INCREMENT(&tl->low) == 0) 723 PR_ATOMIC_INCREMENT(&tl->high); 724 } 725 } 726 727 PRBool 728 ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite, 729 const SSLVersionRange *vrange) 730 { 731 switch (cipherSuite) { 732 case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: 733 case TLS_RSA_WITH_AES_256_CBC_SHA256: 734 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: 735 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: 736 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: 737 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: 738 case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: 739 case TLS_RSA_WITH_AES_128_CBC_SHA256: 740 case TLS_RSA_WITH_AES_128_GCM_SHA256: 741 case TLS_RSA_WITH_AES_256_GCM_SHA384: 742 case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: 743 case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: 744 case TLS_RSA_WITH_NULL_SHA256: 745 case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: 746 case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: 747 case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 748 case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: 749 case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 750 case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: 751 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: 752 case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: 753 case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: 754 case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: 755 case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: 756 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2 && 757 vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; 758 759 /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and 760 * point formats.*/ 761 case TLS_ECDH_ECDSA_WITH_NULL_SHA: 762 case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: 763 case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: 764 case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: 765 case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: 766 case TLS_ECDHE_ECDSA_WITH_NULL_SHA: 767 case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: 768 case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: 769 case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: 770 case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: 771 case TLS_ECDH_RSA_WITH_NULL_SHA: 772 case TLS_ECDH_RSA_WITH_RC4_128_SHA: 773 case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: 774 case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: 775 case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: 776 case TLS_ECDHE_RSA_WITH_NULL_SHA: 777 case TLS_ECDHE_RSA_WITH_RC4_128_SHA: 778 case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: 779 case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 780 case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: 781 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 && 782 vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; 783 784 case TLS_AES_128_GCM_SHA256: 785 case TLS_AES_256_GCM_SHA384: 786 case TLS_CHACHA20_POLY1305_SHA256: 787 return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3; 788 789 default: 790 return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; 791 } 792 } 793 794 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */ 795 /* XXX This does a linear search. A binary search would be better. */ 796 const ssl3CipherSuiteDef * 797 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) 798 { 799 int cipher_suite_def_len = 800 sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); 801 int i; 802 803 for (i = 0; i < cipher_suite_def_len; i++) { 804 if (cipher_suite_defs[i].cipher_suite == suite) 805 return &cipher_suite_defs[i]; 806 } 807 PORT_Assert(PR_FALSE); /* We should never get here. */ 808 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); 809 return NULL; 810 } 811 812 /* Find the cipher configuration struct associate with suite */ 813 /* XXX This does a linear search. A binary search would be better. */ 814 static ssl3CipherSuiteCfg * 815 ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite, 816 ssl3CipherSuiteCfg *suites) 817 { 818 int i; 819 820 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 821 if (suites[i].cipher_suite == suite) 822 return &suites[i]; 823 } 824 /* return NULL and let the caller handle it. */ 825 PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); 826 return NULL; 827 } 828 829 const ssl3CipherSuiteCfg * 830 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites) 831 { 832 return ssl_LookupCipherSuiteCfgMutable(suite, 833 CONST_CAST(ssl3CipherSuiteCfg, suites)); 834 } 835 836 static PRBool 837 ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType) 838 { 839 unsigned int i; 840 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) { 841 if (ss->namedGroupPreferences[i] && 842 ss->namedGroupPreferences[i]->keaType == keaType) { 843 return PR_TRUE; 844 } 845 } 846 return PR_FALSE; 847 } 848 849 static PRBool 850 ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType) 851 { 852 switch (keaType) { 853 case ssl_kea_rsa: 854 return PR_TRUE; 855 856 case ssl_kea_dh: 857 case ssl_kea_dh_psk: { 858 if (ss->sec.isServer && !ss->opt.enableServerDhe) { 859 return PR_FALSE; 860 } 861 862 if (ss->sec.isServer) { 863 /* If the server requires named FFDHE groups, then the client 864 * must have included an FFDHE group. peerSupportsFfdheGroups 865 * is set to true in ssl_HandleSupportedGroupsXtn(). */ 866 if (ss->opt.requireDHENamedGroups && 867 !ss->xtnData.peerSupportsFfdheGroups) { 868 return PR_FALSE; 869 } 870 871 /* We can use the weak DH group if all of these are true: 872 * 1. We don't require named groups. 873 * 2. The peer doesn't support named groups. 874 * 3. This isn't TLS 1.3. 875 * 4. The weak group is enabled. */ 876 if (!ss->opt.requireDHENamedGroups && 877 !ss->xtnData.peerSupportsFfdheGroups && 878 ss->version < SSL_LIBRARY_VERSION_TLS_1_3 && 879 ss->ssl3.dheWeakGroupEnabled) { 880 return PR_TRUE; 881 } 882 } else { 883 if (ss->vrange.min < SSL_LIBRARY_VERSION_TLS_1_3 && 884 !ss->opt.requireDHENamedGroups) { 885 /* The client enables DHE cipher suites even if no DHE groups 886 * are enabled. Only if this isn't TLS 1.3 and named groups 887 * are not required. */ 888 return PR_TRUE; 889 } 890 } 891 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh); 892 } 893 894 case ssl_kea_ecdh: 895 case ssl_kea_ecdh_psk: 896 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh); 897 898 case ssl_kea_ecdh_hybrid: 899 case ssl_kea_ecdh_hybrid_psk: 900 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 901 return PR_FALSE; 902 } 903 return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh_hybrid); 904 905 case ssl_kea_tls13_any: 906 return PR_TRUE; 907 908 case ssl_kea_fortezza: 909 default: 910 PORT_Assert(0); 911 } 912 return PR_FALSE; 913 } 914 915 static PRBool 916 ssl_HasCert(const sslSocket *ss, PRUint16 maxVersion, SSLAuthType authType) 917 { 918 PRCList *cursor; 919 if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) { 920 return PR_TRUE; 921 } 922 for (cursor = PR_NEXT_LINK(&ss->serverCerts); 923 cursor != &ss->serverCerts; 924 cursor = PR_NEXT_LINK(cursor)) { 925 sslServerCert *cert = (sslServerCert *)cursor; 926 if (!cert->serverKeyPair || 927 !cert->serverKeyPair->privKey || 928 !cert->serverCertChain || 929 !SSL_CERT_IS(cert, authType)) { 930 continue; 931 } 932 /* When called from ssl3_config_match_init(), all the EC curves will be 933 * enabled, so this will essentially do nothing (unless we implement 934 * curve configuration). However, once we have seen the 935 * supported_groups extension and this is called from config_match(), 936 * this will filter out certificates with an unsupported curve. 937 * 938 * If we might negotiate TLS 1.3, skip this test as group configuration 939 * doesn't affect choices in TLS 1.3. 940 */ 941 if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3 && 942 (authType == ssl_auth_ecdsa || 943 authType == ssl_auth_ecdh_ecdsa || 944 authType == ssl_auth_ecdh_rsa) && 945 !ssl_NamedGroupEnabled(ss, cert->namedCurve)) { 946 continue; 947 } 948 return PR_TRUE; 949 } 950 if (authType == ssl_auth_rsa_sign) { 951 return ssl_HasCert(ss, maxVersion, ssl_auth_rsa_pss); 952 } 953 return PR_FALSE; 954 } 955 956 /* return true if the scheme is allowed by policy, This prevents 957 * failures later when our actual signatures are rejected by 958 * policy by either ssl code, or lower level NSS code */ 959 static PRBool 960 ssl_SchemePolicyOK(SSLSignatureScheme scheme, PRUint32 require) 961 { 962 /* Hash policy. */ 963 PRUint32 policy; 964 SECOidTag hashOID = ssl3_HashTypeToOID(ssl_SignatureSchemeToHashType(scheme)); 965 SECOidTag sigOID; 966 967 /* policy bits needed to enable a SignatureScheme */ 968 SECStatus rv = NSS_GetAlgorithmPolicy(hashOID, &policy); 969 if (rv == SECSuccess && 970 (policy & require) != require) { 971 return PR_FALSE; 972 } 973 974 /* ssl_SignatureSchemeToAuthType reports rsa for rsa_pss_rsae, but we 975 * actually implement pss signatures when we sign, so just use RSA_PSS 976 * for all RSA PSS Siganture schemes */ 977 if (ssl_IsRsaPssSignatureScheme(scheme)) { 978 sigOID = SEC_OID_PKCS1_RSA_PSS_SIGNATURE; 979 } else { 980 sigOID = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme)); 981 } 982 /* Signature Policy. */ 983 rv = NSS_GetAlgorithmPolicy(sigOID, &policy); 984 if (rv == SECSuccess && 985 (policy & require) != require) { 986 return PR_FALSE; 987 } 988 return PR_TRUE; 989 } 990 991 /* Check that a signature scheme is accepted. 992 * Both by policy and by having a token that supports it. */ 993 static PRBool 994 ssl_SignatureSchemeAccepted(PRUint16 minVersion, 995 SSLSignatureScheme scheme, 996 PRBool forCert) 997 { 998 /* Disable RSA-PSS schemes if there are no tokens to verify them. */ 999 if (ssl_IsRsaPssSignatureScheme(scheme)) { 1000 if (!PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) { 1001 return PR_FALSE; 1002 } 1003 } else if (!forCert && ssl_IsRsaPkcs1SignatureScheme(scheme)) { 1004 /* Disable PKCS#1 signatures if we are limited to TLS 1.3. 1005 * We still need to advertise PKCS#1 signatures in CH and CR 1006 * for certificate signatures. 1007 */ 1008 if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) { 1009 return PR_FALSE; 1010 } 1011 } else if (ssl_IsDsaSignatureScheme(scheme)) { 1012 /* DSA: not in TLS 1.3, and check policy. */ 1013 if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) { 1014 return PR_FALSE; 1015 } 1016 } 1017 1018 return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy); 1019 } 1020 1021 static SECStatus 1022 ssl_CheckSignatureSchemes(sslSocket *ss) 1023 { 1024 if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) { 1025 return SECSuccess; 1026 } 1027 1028 /* If this is a server using TLS 1.3, we just need to have one signature 1029 * scheme for which we have a usable certificate. 1030 * 1031 * Note: Certificates for earlier TLS versions are checked along with the 1032 * cipher suite in ssl3_config_match_init. */ 1033 if (ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) { 1034 PRBool foundCert = PR_FALSE; 1035 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 1036 SSLAuthType authType = 1037 ssl_SignatureSchemeToAuthType(ss->ssl3.signatureSchemes[i]); 1038 if (ssl_HasCert(ss, ss->vrange.max, authType)) { 1039 foundCert = PR_TRUE; 1040 break; 1041 } 1042 } 1043 if (!foundCert) { 1044 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1045 return SECFailure; 1046 } 1047 } 1048 1049 /* Ensure that there is a signature scheme that can be accepted.*/ 1050 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 1051 if (ssl_SignatureSchemeAccepted(ss->vrange.min, 1052 ss->ssl3.signatureSchemes[i], 1053 PR_FALSE /* forCert */)) { 1054 return SECSuccess; 1055 } 1056 } 1057 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 1058 return SECFailure; 1059 } 1060 1061 /* For a server, check that a signature scheme that can be used with the 1062 * provided authType is both enabled and usable. */ 1063 static PRBool 1064 ssl_HasSignatureScheme(const sslSocket *ss, SSLAuthType authType) 1065 { 1066 PORT_Assert(ss->sec.isServer); 1067 PORT_Assert(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version); 1068 PORT_Assert(authType != ssl_auth_null); 1069 PORT_Assert(authType != ssl_auth_tls13_any); 1070 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2 || 1071 authType == ssl_auth_rsa_decrypt || 1072 authType == ssl_auth_ecdh_rsa || 1073 authType == ssl_auth_ecdh_ecdsa) { 1074 return PR_TRUE; 1075 } 1076 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 1077 SSLSignatureScheme scheme = ss->ssl3.signatureSchemes[i]; 1078 SSLAuthType schemeAuthType = ssl_SignatureSchemeToAuthType(scheme); 1079 PRBool acceptable = authType == schemeAuthType || 1080 (schemeAuthType == ssl_auth_rsa_pss && 1081 authType == ssl_auth_rsa_sign); 1082 if (acceptable && ssl_SignatureSchemeAccepted(ss->version, scheme, PR_FALSE /* forCert */)) { 1083 return PR_TRUE; 1084 } 1085 } 1086 return PR_FALSE; 1087 } 1088 1089 /* Initialize the suite->isPresent value for config_match 1090 * Returns count of enabled ciphers supported by extant tokens, 1091 * regardless of policy or user preference. 1092 * If this returns zero, the user cannot do SSL v3. 1093 */ 1094 unsigned int 1095 ssl3_config_match_init(sslSocket *ss) 1096 { 1097 ssl3CipherSuiteCfg *suite; 1098 const ssl3CipherSuiteDef *cipher_def; 1099 SSLCipherAlgorithm cipher_alg; 1100 CK_MECHANISM_TYPE cipher_mech; 1101 SSLAuthType authType; 1102 SSLKEAType keaType; 1103 unsigned int i; 1104 unsigned int numPresent = 0; 1105 unsigned int numEnabled = 0; 1106 1107 PORT_Assert(ss); 1108 if (!ss) { 1109 PORT_SetError(SEC_ERROR_INVALID_ARGS); 1110 return 0; 1111 } 1112 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1113 return 0; 1114 } 1115 if (ss->sec.isServer && ss->psk && 1116 PR_CLIST_IS_EMPTY(&ss->serverCerts) && 1117 (ss->opt.requestCertificate || ss->opt.requireCertificate)) { 1118 /* PSK and certificate auth cannot be combined. */ 1119 PORT_SetError(SSL_ERROR_NO_CERTIFICATE); 1120 return 0; 1121 } 1122 if (ssl_CheckSignatureSchemes(ss) != SECSuccess) { 1123 return 0; /* Code already set. */ 1124 } 1125 1126 ssl_FilterSupportedGroups(ss); 1127 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 1128 suite = &ss->cipherSuites[i]; 1129 if (suite->enabled) { 1130 ++numEnabled; 1131 /* We need the cipher defs to see if we have a token that can handle 1132 * this cipher. It isn't part of the static definition. 1133 */ 1134 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); 1135 if (!cipher_def) { 1136 suite->isPresent = PR_FALSE; 1137 continue; 1138 } 1139 cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg; 1140 cipher_mech = ssl3_Alg2Mech(cipher_alg); 1141 1142 /* Mark the suites that are backed by real tokens, certs and keys */ 1143 suite->isPresent = PR_TRUE; 1144 1145 authType = kea_defs[cipher_def->key_exchange_alg].authKeyType; 1146 if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) { 1147 if (ss->sec.isServer && 1148 !(ssl_HasCert(ss, ss->vrange.max, authType) && 1149 ssl_HasSignatureScheme(ss, authType))) { 1150 suite->isPresent = PR_FALSE; 1151 } else if (!PK11_TokenExists(auth_alg_defs[authType])) { 1152 suite->isPresent = PR_FALSE; 1153 } 1154 } 1155 1156 keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType; 1157 if (keaType != ssl_kea_null && 1158 keaType != ssl_kea_tls13_any && 1159 !PK11_TokenExists(kea_alg_defs[keaType])) { 1160 suite->isPresent = PR_FALSE; 1161 } 1162 1163 if (cipher_alg != ssl_calg_null && 1164 !PK11_TokenExists(cipher_mech)) { 1165 suite->isPresent = PR_FALSE; 1166 } 1167 1168 if (suite->isPresent) { 1169 ++numPresent; 1170 } 1171 } 1172 } 1173 PORT_AssertArg(numPresent > 0 || numEnabled == 0); 1174 if (numPresent == 0) { 1175 PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); 1176 } 1177 return numPresent; 1178 } 1179 1180 /* Return PR_TRUE if suite is usable. This if the suite is permitted by policy, 1181 * enabled, has a certificate (as needed), has a viable key agreement method, is 1182 * usable with the negotiated TLS version, and is otherwise usable. */ 1183 PRBool 1184 ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy, 1185 const SSLVersionRange *vrange, const sslSocket *ss) 1186 { 1187 const ssl3CipherSuiteDef *cipher_def; 1188 const ssl3KEADef *kea_def; 1189 1190 if (!suite) { 1191 PORT_Assert(suite); 1192 return PR_FALSE; 1193 } 1194 1195 PORT_Assert(policy != SSL_NOT_ALLOWED); 1196 if (policy == SSL_NOT_ALLOWED) 1197 return PR_FALSE; 1198 1199 if (!suite->enabled || !suite->isPresent) 1200 return PR_FALSE; 1201 1202 if ((suite->policy == SSL_NOT_ALLOWED) || 1203 (suite->policy > policy)) 1204 return PR_FALSE; 1205 1206 PORT_Assert(ss != NULL); 1207 cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); 1208 PORT_Assert(cipher_def != NULL); 1209 kea_def = &kea_defs[cipher_def->key_exchange_alg]; 1210 PORT_Assert(kea_def != NULL); 1211 if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) { 1212 return PR_FALSE; 1213 } 1214 1215 if (ss->sec.isServer && !ssl_HasCert(ss, vrange->max, kea_def->authKeyType)) { 1216 return PR_FALSE; 1217 } 1218 1219 /* If a PSK is selected, disable suites that use a different hash than 1220 * the PSK. We advertise non-PSK-compatible suites in the CH, as we could 1221 * fallback to certificate auth. The client handler will check hash 1222 * compatibility before committing to use the PSK. */ 1223 if (ss->xtnData.selectedPsk) { 1224 if (ss->xtnData.selectedPsk->hash != cipher_def->prf_hash) { 1225 return PR_FALSE; 1226 } 1227 } 1228 1229 return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange); 1230 } 1231 1232 /* For TLS 1.3, when resuming, check for a ciphersuite that is both compatible 1233 * with the identified ciphersuite and enabled. */ 1234 static PRBool 1235 tls13_ResumptionCompatible(sslSocket *ss, ssl3CipherSuite suite) 1236 { 1237 SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_3, 1238 SSL_LIBRARY_VERSION_TLS_1_3 }; 1239 SSLHashType hash = tls13_GetHashForCipherSuite(suite); 1240 for (unsigned int i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) { 1241 if (cipher_suite_defs[i].prf_hash == hash) { 1242 const ssl3CipherSuiteCfg *suiteCfg = 1243 ssl_LookupCipherSuiteCfg(cipher_suite_defs[i].cipher_suite, 1244 ss->cipherSuites); 1245 if (suite && ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) { 1246 return PR_TRUE; 1247 } 1248 } 1249 } 1250 return PR_FALSE; 1251 } 1252 1253 /* 1254 * Null compression, mac and encryption functions 1255 */ 1256 SECStatus 1257 Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen, 1258 const unsigned char *input, unsigned int inputLen) 1259 { 1260 if (inputLen > maxOutputLen) { 1261 *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ 1262 PORT_SetError(SEC_ERROR_OUTPUT_LEN); 1263 return SECFailure; 1264 } 1265 *outputLen = inputLen; 1266 if (inputLen > 0 && input != output) { 1267 PORT_Memcpy(output, input, inputLen); 1268 } 1269 return SECSuccess; 1270 } 1271 1272 /* Wrapper around PK11_CipherOp to avoid undefined behavior due to incompatible 1273 * function pointer type cast 1274 */ 1275 static SECStatus 1276 SSLCipher_PK11_CipherOp(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen, 1277 const unsigned char *input, unsigned int inputLen) 1278 { 1279 PK11Context *pctx = ctx; 1280 PORT_Assert(maxOutputLen <= INT_MAX); 1281 int signedOutputLen = maxOutputLen; 1282 SECStatus rv = PK11_CipherOp(pctx, output, &signedOutputLen, maxOutputLen, input, inputLen); 1283 PORT_Assert(signedOutputLen >= 0); 1284 *outputLen = signedOutputLen; 1285 return rv; 1286 } 1287 1288 /* 1289 * SSL3 Utility functions 1290 */ 1291 1292 static void 1293 ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec) 1294 { 1295 spec->version = ss->version; 1296 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 1297 tls13_SetSpecRecordVersion(ss, spec); 1298 } else if (IS_DTLS(ss)) { 1299 spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version); 1300 } else { 1301 spec->recordVersion = ss->version; 1302 } 1303 } 1304 1305 /* allowLargerPeerVersion controls whether the function will select the 1306 * highest enabled SSL version or fail when peerVersion is greater than the 1307 * highest enabled version. 1308 * 1309 * If allowLargerPeerVersion is true, peerVersion is the peer's highest 1310 * enabled version rather than the peer's selected version. 1311 */ 1312 SECStatus 1313 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, 1314 PRBool allowLargerPeerVersion) 1315 { 1316 SSL3ProtocolVersion negotiated; 1317 1318 /* Prevent negotiating to a lower version in response to a TLS 1.3 HRR. */ 1319 if (ss->ssl3.hs.helloRetry) { 1320 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); 1321 return SECFailure; 1322 } 1323 1324 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1325 PORT_SetError(SSL_ERROR_SSL_DISABLED); 1326 return SECFailure; 1327 } 1328 1329 if (peerVersion < ss->vrange.min || 1330 (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { 1331 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); 1332 return SECFailure; 1333 } 1334 1335 negotiated = PR_MIN(peerVersion, ss->vrange.max); 1336 PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated)); 1337 if (ss->firstHsDone && ss->version != negotiated) { 1338 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); 1339 return SECFailure; 1340 } 1341 1342 ss->version = negotiated; 1343 return SECSuccess; 1344 } 1345 1346 /* Used by the client when the server produces a version number. 1347 * This reads, validates, and normalizes the value. */ 1348 SECStatus 1349 ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len, 1350 SSL3ProtocolVersion *version) 1351 { 1352 SSL3ProtocolVersion v; 1353 PRUint32 temp; 1354 SECStatus rv; 1355 1356 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len); 1357 if (rv != SECSuccess) { 1358 return SECFailure; /* alert has been sent */ 1359 } 1360 v = (SSL3ProtocolVersion)temp; 1361 1362 if (IS_DTLS(ss)) { 1363 v = dtls_DTLSVersionToTLSVersion(v); 1364 /* Check for failure. */ 1365 if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) { 1366 SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 1367 return SECFailure; 1368 } 1369 } 1370 1371 /* You can't negotiate TLS 1.3 this way. */ 1372 if (v >= SSL_LIBRARY_VERSION_TLS_1_3) { 1373 SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 1374 return SECFailure; 1375 } 1376 *version = v; 1377 return SECSuccess; 1378 } 1379 1380 SECStatus 1381 ssl3_GetNewRandom(SSL3Random random) 1382 { 1383 SECStatus rv; 1384 1385 rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH); 1386 if (rv != SECSuccess) { 1387 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 1388 } 1389 return rv; 1390 } 1391 1392 /* this only implements TLS 1.2 and earlier signatures */ 1393 static SECStatus 1394 ssl3_SignHashesWithPrivKey(SSL3Hashes *hash, SECKEYPrivateKey *key, 1395 SSLSignatureScheme scheme, PRBool isTls, SECItem *buf) 1396 { 1397 SECStatus rv = SECFailure; 1398 PRBool doDerEncode = PR_FALSE; 1399 PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(scheme); 1400 SECItem hashItem; 1401 1402 buf->data = NULL; 1403 1404 switch (SECKEY_GetPrivateKeyType(key)) { 1405 case rsaKey: 1406 hashItem.data = hash->u.raw; 1407 hashItem.len = hash->len; 1408 break; 1409 case dsaKey: 1410 doDerEncode = isTls; 1411 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1412 * In that case, we use just the SHA1 part. */ 1413 if (hash->hashAlg == ssl_hash_none) { 1414 hashItem.data = hash->u.s.sha; 1415 hashItem.len = sizeof(hash->u.s.sha); 1416 } else { 1417 hashItem.data = hash->u.raw; 1418 hashItem.len = hash->len; 1419 } 1420 break; 1421 case ecKey: 1422 doDerEncode = PR_TRUE; 1423 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1424 * In that case, we use just the SHA1 part. */ 1425 if (hash->hashAlg == ssl_hash_none) { 1426 hashItem.data = hash->u.s.sha; 1427 hashItem.len = sizeof(hash->u.s.sha); 1428 } else { 1429 hashItem.data = hash->u.raw; 1430 hashItem.len = hash->len; 1431 } 1432 break; 1433 default: 1434 PORT_SetError(SEC_ERROR_INVALID_KEY); 1435 goto done; 1436 } 1437 PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len)); 1438 1439 if (useRsaPss || hash->hashAlg == ssl_hash_none) { 1440 CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType); 1441 int signatureLen = PK11_SignatureLen(key); 1442 PRInt32 optval; 1443 1444 SECItem *params = NULL; 1445 CK_RSA_PKCS_PSS_PARAMS pssParams; 1446 SECItem pssParamsItem = { siBuffer, 1447 (unsigned char *)&pssParams, 1448 sizeof(pssParams) }; 1449 1450 if (signatureLen <= 0) { 1451 PORT_SetError(SEC_ERROR_INVALID_KEY); 1452 goto done; 1453 } 1454 /* since we are calling PK11_SignWithMechanism directly, we need to 1455 * check the key policy ourselves (which is already checked in 1456 * SGN_Digest) */ 1457 rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval); 1458 if ((rv == SECSuccess) && 1459 ((optval & NSS_KEY_SIZE_POLICY_SIGN_FLAG) == NSS_KEY_SIZE_POLICY_SIGN_FLAG)) { 1460 rv = SECKEY_EnforceKeySize(key->keyType, SECKEY_PrivateKeyStrengthInBits(key), 1461 SEC_ERROR_SIGNATURE_ALGORITHM_DISABLED); 1462 if (rv != SECSuccess) { 1463 goto done; /* error code already set */ 1464 } 1465 } 1466 1467 buf->len = (unsigned)signatureLen; 1468 buf->data = (unsigned char *)PORT_Alloc(signatureLen); 1469 if (!buf->data) 1470 goto done; /* error code was set. */ 1471 1472 if (useRsaPss) { 1473 pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg); 1474 pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg); 1475 pssParams.sLen = hashItem.len; 1476 params = &pssParamsItem; 1477 mech = CKM_RSA_PKCS_PSS; 1478 } 1479 1480 rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem); 1481 } else { 1482 SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg); 1483 rv = SGN_Digest(key, hashOID, buf, &hashItem); 1484 } 1485 if (rv != SECSuccess) { 1486 ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); 1487 } else if (doDerEncode) { 1488 SECItem derSig = { siBuffer, NULL, 0 }; 1489 1490 /* This also works for an ECDSA signature */ 1491 rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); 1492 if (rv == SECSuccess) { 1493 PORT_Free(buf->data); /* discard unencoded signature. */ 1494 *buf = derSig; /* give caller encoded signature. */ 1495 } else if (derSig.data) { 1496 PORT_Free(derSig.data); 1497 } 1498 } 1499 1500 PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len)); 1501 done: 1502 if (rv != SECSuccess && buf->data) { 1503 PORT_Free(buf->data); 1504 buf->data = NULL; 1505 } 1506 return rv; 1507 } 1508 1509 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ 1510 SECStatus 1511 ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key, 1512 SECItem *buf) 1513 { 1514 SECStatus rv = SECFailure; 1515 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0); 1516 SSLSignatureScheme scheme = ss->ssl3.hs.signatureScheme; 1517 1518 rv = ssl3_SignHashesWithPrivKey(hash, key, scheme, isTLS, buf); 1519 if (rv != SECSuccess) { 1520 return SECFailure; 1521 } 1522 1523 if (ss->sec.isServer) { 1524 ss->sec.signatureScheme = scheme; 1525 ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme); 1526 } 1527 1528 return SECSuccess; 1529 } 1530 1531 /* Called from ssl3_VerifySignedHashes */ 1532 /* this only implements TLS 1.2 and earlier signatures */ 1533 static SECStatus 1534 ssl_VerifySignedHashesWithPubKey(sslSocket *ss, SECKEYPublicKey *key, 1535 SSLSignatureScheme scheme, 1536 SSL3Hashes *hash, SECItem *buf) 1537 { 1538 SECItem *signature = NULL; 1539 SECStatus rv = SECFailure; 1540 SECItem hashItem; 1541 SECOidTag encAlg; 1542 SECOidTag hashAlg; 1543 void *pwArg = ss->pkcs11PinArg; 1544 PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme); 1545 1546 PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len)); 1547 1548 hashAlg = ssl3_HashTypeToOID(hash->hashAlg); 1549 switch (SECKEY_GetPublicKeyType(key)) { 1550 case rsaKey: 1551 encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; 1552 hashItem.data = hash->u.raw; 1553 hashItem.len = hash->len; 1554 if (scheme == ssl_sig_none) { 1555 scheme = ssl_sig_rsa_pkcs1_sha1md5; 1556 } 1557 break; 1558 case dsaKey: 1559 encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; 1560 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1561 * In that case, we use just the SHA1 part. */ 1562 if (hash->hashAlg == ssl_hash_none) { 1563 hashItem.data = hash->u.s.sha; 1564 hashItem.len = sizeof(hash->u.s.sha); 1565 } else { 1566 hashItem.data = hash->u.raw; 1567 hashItem.len = hash->len; 1568 } 1569 /* Allow DER encoded DSA signatures in SSL 3.0 */ 1570 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 || 1571 buf->len != SECKEY_SignatureLen(key)) { 1572 signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); 1573 if (!signature) { 1574 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1575 goto loser; 1576 } 1577 buf = signature; 1578 } 1579 if (scheme == ssl_sig_none) { 1580 scheme = ssl_sig_dsa_sha1; 1581 } 1582 break; 1583 1584 case ecKey: 1585 encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; 1586 /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash. 1587 * In that case, we use just the SHA1 part. 1588 * ECDSA signatures always encode the integers r and s using ASN.1 1589 * (unlike DSA where ASN.1 encoding is used with TLS but not with 1590 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. 1591 */ 1592 if (hash->hashAlg == ssl_hash_none) { 1593 hashAlg = SEC_OID_SHA1; 1594 hashItem.data = hash->u.s.sha; 1595 hashItem.len = sizeof(hash->u.s.sha); 1596 } else { 1597 hashItem.data = hash->u.raw; 1598 hashItem.len = hash->len; 1599 } 1600 if (scheme == ssl_sig_none) { 1601 scheme = ssl_sig_ecdsa_sha1; 1602 } 1603 break; 1604 1605 default: 1606 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 1607 goto loser; 1608 } 1609 1610 PRINT_BUF(60, (NULL, "hash(es) to be verified", 1611 hashItem.data, hashItem.len)); 1612 1613 if (isRsaPssScheme || 1614 hashAlg == SEC_OID_UNKNOWN || 1615 SECKEY_GetPublicKeyType(key) == dsaKey) { 1616 /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. 1617 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code 1618 * above always removes the DER encoding of DSA signatures when 1619 * present. Thus DSA signatures are always verified with PK11_Verify. 1620 */ 1621 CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType); 1622 1623 SECItem *params = NULL; 1624 CK_RSA_PKCS_PSS_PARAMS pssParams; 1625 SECItem pssParamsItem = { siBuffer, 1626 (unsigned char *)&pssParams, 1627 sizeof(pssParams) }; 1628 1629 if (isRsaPssScheme) { 1630 pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg); 1631 pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg); 1632 pssParams.sLen = hashItem.len; 1633 params = &pssParamsItem; 1634 mech = CKM_RSA_PKCS_PSS; 1635 } 1636 1637 rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg); 1638 } else { 1639 rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg, 1640 pwArg); 1641 } 1642 if (signature) { 1643 SECITEM_FreeItem(signature, PR_TRUE); 1644 } 1645 if (rv != SECSuccess) { 1646 ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1647 } 1648 if (!ss->sec.isServer) { 1649 ss->sec.signatureScheme = scheme; 1650 ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme); 1651 } 1652 1653 loser: 1654 #ifdef UNSAFE_FUZZER_MODE 1655 rv = SECSuccess; 1656 PORT_SetError(0); 1657 #endif 1658 return rv; 1659 } 1660 1661 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ 1662 SECStatus 1663 ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash, 1664 SECItem *buf) 1665 { 1666 SECKEYPublicKey *pubKey = 1667 SECKEY_ExtractPublicKey(&ss->sec.peerCert->subjectPublicKeyInfo); 1668 if (pubKey == NULL) { 1669 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 1670 return SECFailure; 1671 } 1672 SECStatus rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, scheme, 1673 hash, buf); 1674 SECKEY_DestroyPublicKey(pubKey); 1675 return rv; 1676 } 1677 1678 /* Caller must set hiLevel error code. */ 1679 /* Called from ssl3_ComputeDHKeyHash 1680 * which are called from ssl3_HandleServerKeyExchange. 1681 * 1682 * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash. 1683 */ 1684 SECStatus 1685 ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, 1686 PRUint8 *hashBuf, unsigned int bufLen, 1687 SSL3Hashes *hashes) 1688 { 1689 SECStatus rv; 1690 SECOidTag hashOID; 1691 PRUint32 policy; 1692 1693 if (hashAlg == ssl_hash_none) { 1694 if ((NSS_GetAlgorithmPolicy(SEC_OID_SHA1, &policy) == SECSuccess) && 1695 !(policy & NSS_USE_ALG_IN_SSL_KX)) { 1696 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1697 return SECFailure; 1698 } 1699 rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen); 1700 if (rv != SECSuccess) { 1701 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1702 return rv; 1703 } 1704 rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen); 1705 if (rv != SECSuccess) { 1706 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1707 return rv; 1708 } 1709 hashes->len = MD5_LENGTH + SHA1_LENGTH; 1710 } else { 1711 hashOID = ssl3_HashTypeToOID(hashAlg); 1712 if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) && 1713 !(policy & NSS_USE_ALG_IN_SSL_KX)) { 1714 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1715 return SECFailure; 1716 } 1717 hashes->len = HASH_ResultLenByOidTag(hashOID); 1718 if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) { 1719 ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1720 return SECFailure; 1721 } 1722 rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen); 1723 if (rv != SECSuccess) { 1724 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1725 return rv; 1726 } 1727 } 1728 hashes->hashAlg = hashAlg; 1729 return SECSuccess; 1730 } 1731 1732 /* Caller must set hiLevel error code. */ 1733 /* Called from ssl3_HandleServerKeyExchange. */ 1734 static SECStatus 1735 ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes, 1736 SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY) 1737 { 1738 sslBuffer buf = SSL_BUFFER_EMPTY; 1739 SECStatus rv; 1740 unsigned int yLen; 1741 unsigned int i; 1742 1743 PORT_Assert(dh_p.data); 1744 PORT_Assert(dh_g.data); 1745 PORT_Assert(dh_Ys.data); 1746 1747 rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH); 1748 if (rv != SECSuccess) { 1749 goto loser; 1750 } 1751 rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); 1752 if (rv != SECSuccess) { 1753 goto loser; 1754 } 1755 /* p */ 1756 rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2); 1757 if (rv != SECSuccess) { 1758 goto loser; 1759 } 1760 /* g */ 1761 rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2); 1762 if (rv != SECSuccess) { 1763 goto loser; 1764 } 1765 /* y - complicated by padding */ 1766 yLen = padY ? dh_p.len : dh_Ys.len; 1767 rv = sslBuffer_AppendNumber(&buf, yLen, 2); 1768 if (rv != SECSuccess) { 1769 goto loser; 1770 } 1771 /* If we're padding Y, dh_Ys can't be longer than dh_p. */ 1772 PORT_Assert(!padY || dh_p.len >= dh_Ys.len); 1773 for (i = dh_Ys.len; i < yLen; ++i) { 1774 rv = sslBuffer_AppendNumber(&buf, 0, 1); 1775 if (rv != SECSuccess) { 1776 goto loser; 1777 } 1778 } 1779 rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len); 1780 if (rv != SECSuccess) { 1781 goto loser; 1782 } 1783 1784 rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf), 1785 SSL_BUFFER_LEN(&buf), hashes); 1786 if (rv != SECSuccess) { 1787 goto loser; 1788 } 1789 1790 PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf), 1791 SSL_BUFFER_LEN(&buf))); 1792 if (hashAlg == ssl_hash_none) { 1793 PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", 1794 hashes->u.s.md5, MD5_LENGTH)); 1795 PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", 1796 hashes->u.s.sha, SHA1_LENGTH)); 1797 } else { 1798 PRINT_BUF(95, (NULL, "DHkey hash: result", 1799 hashes->u.raw, hashes->len)); 1800 } 1801 1802 sslBuffer_Clear(&buf); 1803 return SECSuccess; 1804 1805 loser: 1806 sslBuffer_Clear(&buf); 1807 return SECFailure; 1808 } 1809 1810 static SECStatus 1811 ssl3_SetupPendingCipherSpec(sslSocket *ss, SSLSecretDirection direction, 1812 const ssl3CipherSuiteDef *suiteDef, 1813 ssl3CipherSpec **specp) 1814 { 1815 ssl3CipherSpec *spec; 1816 const ssl3CipherSpec *prev; 1817 1818 prev = (direction == ssl_secret_write) ? ss->ssl3.cwSpec : ss->ssl3.crSpec; 1819 if (prev->epoch == PR_UINT16_MAX) { 1820 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 1821 return SECFailure; 1822 } 1823 1824 spec = ssl_CreateCipherSpec(ss, direction); 1825 if (!spec) { 1826 return SECFailure; 1827 } 1828 1829 spec->cipherDef = ssl_GetBulkCipherDef(suiteDef); 1830 spec->macDef = ssl_GetMacDef(ss, suiteDef); 1831 1832 spec->epoch = prev->epoch + 1; 1833 spec->nextSeqNum = 0; 1834 if (IS_DTLS(ss) && direction == ssl_secret_read) { 1835 dtls_InitRecvdRecords(&spec->recvdRecords); 1836 } 1837 ssl_SetSpecVersions(ss, spec); 1838 1839 ssl_SaveCipherSpec(ss, spec); 1840 *specp = spec; 1841 return SECSuccess; 1842 } 1843 1844 /* Fill in the pending cipher spec with info from the selected ciphersuite. 1845 ** This is as much initialization as we can do without having key material. 1846 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello() 1847 ** Caller must hold the ssl3 handshake lock. 1848 ** Acquires & releases SpecWriteLock. 1849 */ 1850 SECStatus 1851 ssl3_SetupBothPendingCipherSpecs(sslSocket *ss) 1852 { 1853 ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; 1854 SSL3KeyExchangeAlgorithm kea; 1855 const ssl3CipherSuiteDef *suiteDef; 1856 SECStatus rv; 1857 1858 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1859 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); 1860 1861 ssl_GetSpecWriteLock(ss); /*******************************/ 1862 1863 /* This hack provides maximal interoperability with SSL 3 servers. */ 1864 if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) { 1865 /* SSL records are not being MACed. */ 1866 ss->ssl3.cwSpec->version = ss->version; 1867 } 1868 1869 SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", 1870 SSL_GETPID(), ss->fd, suite)); 1871 1872 suiteDef = ssl_LookupCipherSuiteDef(suite); 1873 if (suiteDef == NULL) { 1874 goto loser; 1875 } 1876 1877 if (IS_DTLS(ss)) { 1878 /* Double-check that we did not pick an RC4 suite */ 1879 PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4); 1880 } 1881 1882 ss->ssl3.hs.suite_def = suiteDef; 1883 1884 kea = suiteDef->key_exchange_alg; 1885 ss->ssl3.hs.kea_def = &kea_defs[kea]; 1886 PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); 1887 1888 rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_read, suiteDef, 1889 &ss->ssl3.prSpec); 1890 if (rv != SECSuccess) { 1891 goto loser; 1892 } 1893 rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_write, suiteDef, 1894 &ss->ssl3.pwSpec); 1895 if (rv != SECSuccess) { 1896 goto loser; 1897 } 1898 1899 if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) { 1900 ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH, 1901 ss->opt.recordSizeLimit); 1902 ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH, 1903 ss->xtnData.recordSizeLimit); 1904 } 1905 1906 ssl_ReleaseSpecWriteLock(ss); /*******************************/ 1907 return SECSuccess; 1908 1909 loser: 1910 ssl_ReleaseSpecWriteLock(ss); 1911 return SECFailure; 1912 } 1913 1914 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which 1915 * is included in the MAC or AEAD additional data) to |buf|. See 1916 * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the 1917 * AEAD additional data. 1918 * 1919 * TLS pseudo-header includes the record's version field, SSL's doesn't. Which 1920 * pseudo-header definition to use should be decided based on the version of 1921 * the protocol that was negotiated when the cipher spec became current, NOT 1922 * based on the version value in the record itself, and the decision is passed 1923 * to this function as the |includesVersion| argument. But, the |version| 1924 * argument should be the record's version value. 1925 */ 1926 static SECStatus 1927 ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch, 1928 sslSequenceNumber seqNum, 1929 SSLContentType ct, 1930 PRBool includesVersion, 1931 SSL3ProtocolVersion version, 1932 PRBool isDTLS, 1933 int length, 1934 sslBuffer *buf, SSL3ProtocolVersion v) 1935 { 1936 SECStatus rv; 1937 if (isDTLS && v < SSL_LIBRARY_VERSION_TLS_1_3) { 1938 rv = sslBuffer_AppendNumber(buf, epoch, 2); 1939 if (rv != SECSuccess) { 1940 return SECFailure; 1941 } 1942 rv = sslBuffer_AppendNumber(buf, seqNum, 6); 1943 } else { 1944 rv = sslBuffer_AppendNumber(buf, seqNum, 8); 1945 } 1946 if (rv != SECSuccess) { 1947 return SECFailure; 1948 } 1949 rv = sslBuffer_AppendNumber(buf, ct, 1); 1950 if (rv != SECSuccess) { 1951 return SECFailure; 1952 } 1953 1954 /* SSL3 MAC doesn't include the record's version field. */ 1955 if (includesVersion) { 1956 /* TLS MAC and AEAD additional data include version. */ 1957 rv = sslBuffer_AppendNumber(buf, version, 2); 1958 if (rv != SECSuccess) { 1959 return SECFailure; 1960 } 1961 } 1962 rv = sslBuffer_AppendNumber(buf, length, 2); 1963 if (rv != SECSuccess) { 1964 return SECFailure; 1965 } 1966 1967 return SECSuccess; 1968 } 1969 1970 /* Initialize encryption and MAC contexts for pending spec. 1971 * Master Secret already is derived. 1972 * Caller holds Spec write lock. 1973 */ 1974 static SECStatus 1975 ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec) 1976 { 1977 CK_MECHANISM_TYPE encMechanism; 1978 CK_ATTRIBUTE_TYPE encMode; 1979 SECItem macParam; 1980 CK_ULONG macLength; 1981 SECItem iv; 1982 SSLCipherAlgorithm calg; 1983 1984 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1985 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 1986 1987 calg = spec->cipherDef->calg; 1988 PORT_Assert(alg2Mech[calg].calg == calg); 1989 1990 if (spec->cipherDef->type != type_aead) { 1991 macLength = spec->macDef->mac_size; 1992 1993 /* 1994 ** Now setup the MAC contexts, 1995 ** crypto contexts are setup below. 1996 */ 1997 macParam.data = (unsigned char *)&macLength; 1998 macParam.len = sizeof(macLength); 1999 macParam.type = siBuffer; 2000 2001 spec->keyMaterial.macContext = PK11_CreateContextBySymKey( 2002 spec->macDef->mmech, CKA_SIGN, spec->keyMaterial.macKey, &macParam); 2003 if (!spec->keyMaterial.macContext) { 2004 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 2005 return SECFailure; 2006 } 2007 } 2008 2009 /* 2010 ** Now setup the crypto contexts. 2011 */ 2012 if (calg == ssl_calg_null) { 2013 spec->cipher = Null_Cipher; 2014 return SECSuccess; 2015 } 2016 2017 encMechanism = ssl3_Alg2Mech(calg); 2018 encMode = (spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT; 2019 if (spec->cipherDef->type == type_aead) { 2020 encMode |= CKA_NSS_MESSAGE; 2021 iv.data = NULL; 2022 iv.len = 0; 2023 } else { 2024 spec->cipher = SSLCipher_PK11_CipherOp; 2025 iv.data = spec->keyMaterial.iv; 2026 iv.len = spec->cipherDef->iv_size; 2027 } 2028 2029 /* 2030 * build the context 2031 */ 2032 spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode, 2033 spec->keyMaterial.key, 2034 &iv); 2035 if (!spec->cipherContext) { 2036 ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 2037 return SECFailure; 2038 } 2039 2040 return SECSuccess; 2041 } 2042 2043 /* Complete the initialization of all keys, ciphers, MACs and their contexts 2044 * for the pending Cipher Spec. 2045 * Called from: ssl3_SendClientKeyExchange (for Full handshake) 2046 * ssl3_HandleRSAClientKeyExchange (for Full handshake) 2047 * ssl3_HandleServerHello (for session restart) 2048 * ssl3_HandleClientHello (for session restart) 2049 * Sets error code, but caller probably should override to disambiguate. 2050 * 2051 * If |secret| is a master secret from a previous connection is reused, |derive| 2052 * is PR_FALSE. If the secret is a pre-master secret, then |derive| is PR_TRUE 2053 * and the master secret is derived from |secret|. 2054 */ 2055 SECStatus 2056 ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive) 2057 { 2058 PK11SymKey *masterSecret; 2059 ssl3CipherSpec *pwSpec; 2060 ssl3CipherSpec *prSpec; 2061 SECStatus rv; 2062 2063 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 2064 PORT_Assert(secret); 2065 2066 ssl_GetSpecWriteLock(ss); /**************************************/ 2067 2068 PORT_Assert(ss->ssl3.pwSpec); 2069 PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch); 2070 prSpec = ss->ssl3.prSpec; 2071 pwSpec = ss->ssl3.pwSpec; 2072 2073 if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX) { 2074 /* The problem here is that we have rehandshaked too many 2075 * times (you are not allowed to wrap the epoch). The 2076 * spec says you should be discarding the connection 2077 * and start over, so not much we can do here. */ 2078 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2079 goto loser; 2080 } 2081 2082 if (derive) { 2083 rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret); 2084 if (rv != SECSuccess) { 2085 goto loser; 2086 } 2087 } else { 2088 masterSecret = secret; 2089 } 2090 2091 PORT_Assert(masterSecret); 2092 rv = ssl3_DeriveConnectionKeys(ss, masterSecret); 2093 if (rv != SECSuccess) { 2094 if (derive) { 2095 /* masterSecret was created here. */ 2096 PK11_FreeSymKey(masterSecret); 2097 } 2098 goto loser; 2099 } 2100 2101 /* Both cipher specs maintain a reference to the master secret, since each 2102 * is managed and freed independently. */ 2103 prSpec->masterSecret = masterSecret; 2104 pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret); 2105 rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec); 2106 if (rv != SECSuccess) { 2107 goto loser; 2108 } 2109 2110 rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec); 2111 if (rv != SECSuccess) { 2112 goto loser; 2113 } 2114 2115 ssl_ReleaseSpecWriteLock(ss); /******************************/ 2116 return SECSuccess; 2117 2118 loser: 2119 ssl_ReleaseSpecWriteLock(ss); /******************************/ 2120 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 2121 return SECFailure; 2122 } 2123 2124 /* 2125 * 60 bytes is 3 times the maximum length MAC size that is supported. 2126 */ 2127 static const unsigned char mac_pad_1[60] = { 2128 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2129 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2130 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2131 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2132 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2133 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2134 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 2135 0x36, 0x36, 0x36, 0x36 2136 }; 2137 static const unsigned char mac_pad_2[60] = { 2138 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2139 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2140 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2141 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2142 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2143 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2144 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 2145 0x5c, 0x5c, 0x5c, 0x5c 2146 }; 2147 2148 /* Called from: ssl3_SendRecord() 2149 ** Caller must already hold the SpecReadLock. (wish we could assert that!) 2150 */ 2151 static SECStatus 2152 ssl3_ComputeRecordMAC( 2153 ssl3CipherSpec *spec, 2154 const unsigned char *header, 2155 unsigned int headerLen, 2156 const PRUint8 *input, 2157 int inputLen, 2158 unsigned char *outbuf, 2159 unsigned int *outLen) 2160 { 2161 PK11Context *context; 2162 int macSize = spec->macDef->mac_size; 2163 SECStatus rv; 2164 2165 PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); 2166 PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen)); 2167 2168 if (spec->macDef->mac == ssl_mac_null) { 2169 *outLen = 0; 2170 return SECSuccess; 2171 } 2172 2173 context = spec->keyMaterial.macContext; 2174 rv = PK11_DigestBegin(context); 2175 rv |= PK11_DigestOp(context, header, headerLen); 2176 rv |= PK11_DigestOp(context, input, inputLen); 2177 rv |= PK11_DigestFinal(context, outbuf, outLen, macSize); 2178 PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize); 2179 2180 PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen)); 2181 2182 if (rv != SECSuccess) { 2183 rv = SECFailure; 2184 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 2185 } 2186 return rv; 2187 } 2188 2189 /* Called from: ssl3_HandleRecord() 2190 * Caller must already hold the SpecReadLock. (wish we could assert that!) 2191 * 2192 * On entry: 2193 * originalLen >= inputLen >= MAC size 2194 */ 2195 static SECStatus 2196 ssl3_ComputeRecordMACConstantTime( 2197 ssl3CipherSpec *spec, 2198 const unsigned char *header, 2199 unsigned int headerLen, 2200 const PRUint8 *input, 2201 int inputLen, 2202 int originalLen, 2203 unsigned char *outbuf, 2204 unsigned int *outLen) 2205 { 2206 CK_MECHANISM_TYPE macType; 2207 CK_NSS_MAC_CONSTANT_TIME_PARAMS params; 2208 SECItem param, inputItem, outputItem; 2209 int macSize = spec->macDef->mac_size; 2210 SECStatus rv; 2211 2212 PORT_Assert(inputLen >= spec->macDef->mac_size); 2213 PORT_Assert(originalLen >= inputLen); 2214 2215 if (spec->macDef->mac == ssl_mac_null) { 2216 *outLen = 0; 2217 return SECSuccess; 2218 } 2219 2220 macType = CKM_NSS_HMAC_CONSTANT_TIME; 2221 if (spec->version == SSL_LIBRARY_VERSION_3_0) { 2222 macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; 2223 } 2224 2225 params.macAlg = spec->macDef->mmech; 2226 params.ulBodyTotalLen = originalLen; 2227 params.pHeader = (unsigned char *)header; /* const cast */ 2228 params.ulHeaderLen = headerLen; 2229 2230 param.data = (unsigned char *)¶ms; 2231 param.len = sizeof(params); 2232 param.type = 0; 2233 2234 inputItem.data = (unsigned char *)input; 2235 inputItem.len = inputLen; 2236 inputItem.type = 0; 2237 2238 outputItem.data = outbuf; 2239 outputItem.len = *outLen; 2240 outputItem.type = 0; 2241 2242 rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, ¶m, 2243 &outputItem, &inputItem); 2244 if (rv != SECSuccess) { 2245 if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { 2246 /* ssl3_ComputeRecordMAC() expects the MAC to have been removed 2247 * from the input length already. */ 2248 return ssl3_ComputeRecordMAC(spec, header, headerLen, 2249 input, inputLen - macSize, 2250 outbuf, outLen); 2251 } 2252 2253 *outLen = 0; 2254 rv = SECFailure; 2255 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 2256 return rv; 2257 } 2258 2259 PORT_Assert(outputItem.len == (unsigned)macSize); 2260 *outLen = outputItem.len; 2261 2262 return rv; 2263 } 2264 2265 static PRBool 2266 ssl3_ClientAuthTokenPresent(sslSessionID *sid) 2267 { 2268 PK11SlotInfo *slot = NULL; 2269 PRBool isPresent = PR_TRUE; 2270 2271 /* we only care if we are doing client auth */ 2272 if (!sid || !sid->u.ssl3.clAuthValid) { 2273 return PR_TRUE; 2274 } 2275 2276 /* get the slot */ 2277 slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, 2278 sid->u.ssl3.clAuthSlotID); 2279 if (slot == NULL || 2280 !PK11_IsPresent(slot) || 2281 sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || 2282 sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || 2283 sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || 2284 (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { 2285 isPresent = PR_FALSE; 2286 } 2287 if (slot) { 2288 PK11_FreeSlot(slot); 2289 } 2290 return isPresent; 2291 } 2292 2293 /* Caller must hold the spec read lock. */ 2294 SECStatus 2295 ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec, 2296 PRBool isServer, 2297 PRBool isDTLS, 2298 SSLContentType ct, 2299 const PRUint8 *pIn, 2300 PRUint32 contentLen, 2301 sslBuffer *wrBuf) 2302 { 2303 SECStatus rv; 2304 PRUint32 macLen = 0; 2305 PRUint32 fragLen; 2306 PRUint32 p1Len, p2Len, oddLen = 0; 2307 unsigned int ivLen = 0; 2308 unsigned char pseudoHeaderBuf[13]; 2309 sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf); 2310 unsigned int len; 2311 2312 if (cwSpec->cipherDef->type == type_block && 2313 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 2314 /* Prepend the per-record explicit IV using technique 2b from 2315 * RFC 4346 section 6.2.3.2: The IV is a cryptographically 2316 * strong random number XORed with the CBC residue from the previous 2317 * record. 2318 */ 2319 ivLen = cwSpec->cipherDef->iv_size; 2320 if (ivLen > SSL_BUFFER_SPACE(wrBuf)) { 2321 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2322 return SECFailure; 2323 } 2324 rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen); 2325 if (rv != SECSuccess) { 2326 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 2327 return rv; 2328 } 2329 rv = cwSpec->cipher(cwSpec->cipherContext, 2330 SSL_BUFFER_NEXT(wrBuf), /* output */ 2331 &len, /* outlen */ 2332 ivLen, /* max outlen */ 2333 SSL_BUFFER_NEXT(wrBuf), /* input */ 2334 ivLen); /* input len */ 2335 if (rv != SECSuccess || len != ivLen) { 2336 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2337 return SECFailure; 2338 } 2339 2340 rv = sslBuffer_Skip(wrBuf, len, NULL); 2341 PORT_Assert(rv == SECSuccess); /* Can't fail. */ 2342 } 2343 rv = ssl3_BuildRecordPseudoHeader( 2344 cwSpec->epoch, cwSpec->nextSeqNum, ct, 2345 cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion, 2346 isDTLS, contentLen, &pseudoHeader, cwSpec->version); 2347 PORT_Assert(rv == SECSuccess); 2348 if (cwSpec->cipherDef->type == type_aead) { 2349 const unsigned int nonceLen = cwSpec->cipherDef->explicit_nonce_size; 2350 const unsigned int tagLen = cwSpec->cipherDef->tag_size; 2351 unsigned int ivOffset = 0; 2352 CK_GENERATOR_FUNCTION gen; 2353 /* ivOut includes the iv and the nonce and is the internal iv/nonce 2354 * for the AEAD function. On Encrypt, this is an in/out parameter */ 2355 unsigned char ivOut[MAX_IV_LENGTH]; 2356 ivLen = cwSpec->cipherDef->iv_size; 2357 2358 PORT_Assert((ivLen + nonceLen) <= MAX_IV_LENGTH); 2359 PORT_Assert((ivLen + nonceLen) >= sizeof(sslSequenceNumber)); 2360 2361 if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) { 2362 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2363 return SECFailure; 2364 } 2365 2366 if (nonceLen == 0) { 2367 ivOffset = ivLen - sizeof(sslSequenceNumber); 2368 gen = CKG_GENERATE_COUNTER_XOR; 2369 } else { 2370 ivOffset = ivLen; 2371 gen = CKG_GENERATE_COUNTER; 2372 } 2373 ivOffset = tls13_SetupAeadIv(isDTLS, cwSpec->version, ivOut, cwSpec->keyMaterial.iv, 2374 ivOffset, ivLen, cwSpec->epoch); 2375 rv = tls13_AEAD(cwSpec->cipherContext, 2376 PR_FALSE, 2377 gen, ivOffset * BPB, /* iv generator params */ 2378 ivOut, /* iv in */ 2379 ivOut, /* iv out */ 2380 ivLen + nonceLen, /* full iv length */ 2381 NULL, 0, /* nonce is generated*/ 2382 SSL_BUFFER_BASE(&pseudoHeader), /* aad */ 2383 SSL_BUFFER_LEN(&pseudoHeader), /* aadlen */ 2384 SSL_BUFFER_NEXT(wrBuf) + nonceLen, /* output */ 2385 &len, /* out len */ 2386 SSL_BUFFER_SPACE(wrBuf) - nonceLen, /* max out */ 2387 tagLen, 2388 pIn, contentLen); /* input */ 2389 if (rv != SECSuccess) { 2390 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2391 return SECFailure; 2392 } 2393 len += nonceLen; /* include the nonce at the beginning */ 2394 /* copy out the generated iv if we are using explict nonces */ 2395 if (nonceLen) { 2396 PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), ivOut + ivLen, nonceLen); 2397 } 2398 2399 rv = sslBuffer_Skip(wrBuf, len, NULL); 2400 PORT_Assert(rv == SECSuccess); /* Can't fail. */ 2401 } else { 2402 int blockSize = cwSpec->cipherDef->block_size; 2403 2404 /* 2405 * Add the MAC 2406 */ 2407 rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader), 2408 SSL_BUFFER_LEN(&pseudoHeader), 2409 pIn, contentLen, 2410 SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen); 2411 if (rv != SECSuccess) { 2412 ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 2413 return SECFailure; 2414 } 2415 p1Len = contentLen; 2416 p2Len = macLen; 2417 fragLen = contentLen + macLen; /* needs to be encrypted */ 2418 PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); 2419 2420 /* 2421 * Pad the text (if we're doing a block cipher) 2422 * then Encrypt it 2423 */ 2424 if (cwSpec->cipherDef->type == type_block) { 2425 unsigned char *pBuf; 2426 int padding_length; 2427 int i; 2428 2429 oddLen = contentLen % blockSize; 2430 /* Assume blockSize is a power of two */ 2431 padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1)); 2432 fragLen += padding_length + 1; 2433 PORT_Assert((fragLen % blockSize) == 0); 2434 2435 /* Pad according to TLS rules (also acceptable to SSL3). */ 2436 pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1; 2437 for (i = padding_length + 1; i > 0; --i) { 2438 *pBuf-- = padding_length; 2439 } 2440 /* now, if contentLen is not a multiple of block size, fix it */ 2441 p2Len = fragLen - p1Len; 2442 } 2443 if (p1Len < 256) { 2444 oddLen = p1Len; 2445 p1Len = 0; 2446 } else { 2447 p1Len -= oddLen; 2448 } 2449 if (oddLen) { 2450 p2Len += oddLen; 2451 PORT_Assert((blockSize < 2) || 2452 (p2Len % blockSize) == 0); 2453 memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen); 2454 } 2455 if (p1Len > 0) { 2456 unsigned int cipherBytesPart1 = 0; 2457 rv = cwSpec->cipher(cwSpec->cipherContext, 2458 SSL_BUFFER_NEXT(wrBuf), /* output */ 2459 &cipherBytesPart1, /* actual outlen */ 2460 p1Len, /* max outlen */ 2461 pIn, 2462 p1Len); /* input, and inputlen */ 2463 PORT_Assert(rv == SECSuccess && cipherBytesPart1 == p1Len); 2464 if (rv != SECSuccess || cipherBytesPart1 != p1Len) { 2465 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2466 return SECFailure; 2467 } 2468 rv = sslBuffer_Skip(wrBuf, p1Len, NULL); 2469 PORT_Assert(rv == SECSuccess); 2470 } 2471 if (p2Len > 0) { 2472 unsigned int cipherBytesPart2 = 0; 2473 rv = cwSpec->cipher(cwSpec->cipherContext, 2474 SSL_BUFFER_NEXT(wrBuf), 2475 &cipherBytesPart2, /* output and actual outLen */ 2476 p2Len, /* max outlen */ 2477 SSL_BUFFER_NEXT(wrBuf), 2478 p2Len); /* input and inputLen*/ 2479 PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len); 2480 if (rv != SECSuccess || cipherBytesPart2 != p2Len) { 2481 PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 2482 return SECFailure; 2483 } 2484 rv = sslBuffer_Skip(wrBuf, p2Len, NULL); 2485 PORT_Assert(rv == SECSuccess); 2486 } 2487 } 2488 2489 return SECSuccess; 2490 } 2491 2492 /* Note: though this can report failure, it shouldn't. */ 2493 SECStatus 2494 ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec, 2495 SSLContentType contentType, sslBuffer *wrBuf, 2496 PRBool *needsLength) 2497 { 2498 SECStatus rv; 2499 2500 #ifndef UNSAFE_FUZZER_MODE 2501 if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 2502 cwSpec->epoch > TrafficKeyClearText) { 2503 if (IS_DTLS(ss)) { 2504 return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf, 2505 needsLength); 2506 } 2507 contentType = ssl_ct_application_data; 2508 } 2509 #endif 2510 rv = sslBuffer_AppendNumber(wrBuf, contentType, 1); 2511 if (rv != SECSuccess) { 2512 return SECFailure; 2513 } 2514 2515 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2); 2516 if (rv != SECSuccess) { 2517 return SECFailure; 2518 } 2519 if (IS_DTLS(ss)) { 2520 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2); 2521 if (rv != SECSuccess) { 2522 return SECFailure; 2523 } 2524 rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6); 2525 if (rv != SECSuccess) { 2526 return SECFailure; 2527 } 2528 } 2529 *needsLength = PR_TRUE; 2530 return SECSuccess; 2531 } 2532 2533 SECStatus 2534 ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct, 2535 const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf) 2536 { 2537 PRBool needsLength; 2538 unsigned int lenOffset; 2539 SECStatus rv; 2540 2541 PORT_Assert(cwSpec->direction == ssl_secret_write); 2542 PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0); 2543 PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX); 2544 2545 if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) { 2546 SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx", 2547 SSL_GETPID(), cwSpec->nextSeqNum)); 2548 PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS); 2549 return SECFailure; 2550 } 2551 2552 rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength); 2553 if (rv != SECSuccess) { 2554 return SECFailure; 2555 } 2556 if (needsLength) { 2557 rv = sslBuffer_Skip(wrBuf, 2, &lenOffset); 2558 if (rv != SECSuccess) { 2559 return SECFailure; 2560 } 2561 } 2562 2563 #ifdef UNSAFE_FUZZER_MODE 2564 { 2565 unsigned int len; 2566 rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len, 2567 SSL_BUFFER_SPACE(wrBuf), pIn, contentLen); 2568 if (rv != SECSuccess) { 2569 return SECFailure; /* error was set */ 2570 } 2571 rv = sslBuffer_Skip(wrBuf, len, NULL); 2572 PORT_Assert(rv == SECSuccess); /* Can't fail. */ 2573 } 2574 #else 2575 if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 2576 PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf); 2577 unsigned int bufLen = SSL_BUFFER_LEN(wrBuf); 2578 rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf); 2579 if (rv != SECSuccess) { 2580 return SECFailure; 2581 } 2582 if (IS_DTLS(ss)) { 2583 bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen; 2584 rv = dtls13_MaskSequenceNumber(ss, cwSpec, 2585 SSL_BUFFER_BASE(wrBuf), 2586 cipherText, bufLen); 2587 } 2588 } else { 2589 rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct, 2590 pIn, contentLen, wrBuf); 2591 } 2592 #endif 2593 if (rv != SECSuccess) { 2594 return SECFailure; /* error was set */ 2595 } 2596 2597 if (needsLength) { 2598 /* Insert the length. */ 2599 rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2); 2600 if (rv != SECSuccess) { 2601 PORT_Assert(0); /* Can't fail. */ 2602 return SECFailure; 2603 } 2604 } 2605 2606 ++cwSpec->nextSeqNum; 2607 return SECSuccess; 2608 } 2609 2610 SECStatus 2611 ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct, 2612 const PRUint8 *pIn, unsigned int nIn, 2613 unsigned int *written) 2614 { 2615 sslBuffer *wrBuf = &ss->sec.writeBuf; 2616 unsigned int contentLen; 2617 unsigned int spaceNeeded; 2618 SECStatus rv; 2619 2620 contentLen = PR_MIN(nIn, spec->recordSizeLimit); 2621 spaceNeeded = contentLen + SSL3_BUFFER_FUDGE; 2622 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && 2623 spec->cipherDef->type == type_block) { 2624 spaceNeeded += spec->cipherDef->iv_size; 2625 } 2626 if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)) { 2627 rv = sslBuffer_Grow(wrBuf, spaceNeeded); 2628 if (rv != SECSuccess) { 2629 SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d", 2630 SSL_GETPID(), ss->fd, spaceNeeded)); 2631 return SECFailure; 2632 } 2633 } 2634 2635 rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf); 2636 if (rv != SECSuccess) { 2637 return SECFailure; 2638 } 2639 PRINT_BUF(50, (ss, "send (encrypted) record data:", 2640 SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf))); 2641 *written = contentLen; 2642 return SECSuccess; 2643 } 2644 2645 /* Process the plain text before sending it. 2646 * Returns the number of bytes of plaintext that were successfully sent 2647 * plus the number of bytes of plaintext that were copied into the 2648 * output (write) buffer. 2649 * Returns -1 on an error. PR_WOULD_BLOCK_ERROR is set if the error is blocking 2650 * and not terminal. 2651 * 2652 * Notes on the use of the private ssl flags: 2653 * (no private SSL flags) 2654 * Attempt to make and send SSL records for all plaintext 2655 * If non-blocking and a send gets WOULD_BLOCK, 2656 * or if the pending (ciphertext) buffer is not empty, 2657 * then buffer remaining bytes of ciphertext into pending buf, 2658 * and continue to do that for all succssive records until all 2659 * bytes are used. 2660 * ssl_SEND_FLAG_FORCE_INTO_BUFFER 2661 * As above, except this suppresses all write attempts, and forces 2662 * all ciphertext into the pending ciphertext buffer. 2663 * ssl_SEND_FLAG_USE_EPOCH (for DTLS) 2664 * Forces the use of the provided epoch 2665 */ 2666 PRInt32 2667 ssl3_SendRecord(sslSocket *ss, 2668 ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */ 2669 SSLContentType ct, 2670 const PRUint8 *pIn, /* input buffer */ 2671 PRInt32 nIn, /* bytes of input */ 2672 PRInt32 flags) 2673 { 2674 sslBuffer *wrBuf = &ss->sec.writeBuf; 2675 ssl3CipherSpec *spec; 2676 SECStatus rv; 2677 PRInt32 totalSent = 0; 2678 2679 SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", 2680 SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct), 2681 nIn)); 2682 PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); 2683 2684 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 2685 PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0); 2686 2687 if (ss->ssl3.fatalAlertSent) { 2688 SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent", 2689 SSL_GETPID(), ss->fd)); 2690 if (ct != ssl_ct_alert) { 2691 /* If we are sending an alert, then we already have an 2692 * error, so don't overwrite. */ 2693 PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED); 2694 } 2695 return -1; 2696 } 2697 2698 /* check for Token Presence */ 2699 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { 2700 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 2701 return -1; 2702 } 2703 2704 if (ss->recordWriteCallback) { 2705 PRUint16 epoch; 2706 ssl_GetSpecReadLock(ss); 2707 epoch = ss->ssl3.cwSpec->epoch; 2708 ssl_ReleaseSpecReadLock(ss); 2709 rv = ss->recordWriteCallback(ss->fd, epoch, ct, pIn, nIn, 2710 ss->recordWriteCallbackArg); 2711 if (rv != SECSuccess) { 2712 return -1; 2713 } 2714 return nIn; 2715 } 2716 2717 if (cwSpec) { 2718 /* cwSpec can only be set for retransmissions of the DTLS handshake. */ 2719 PORT_Assert(IS_DTLS(ss) && 2720 (ct == ssl_ct_handshake || 2721 ct == ssl_ct_change_cipher_spec)); 2722 spec = cwSpec; 2723 } else { 2724 spec = ss->ssl3.cwSpec; 2725 } 2726 2727 while (nIn > 0) { 2728 unsigned int written = 0; 2729 PRInt32 sent; 2730 2731 ssl_GetSpecReadLock(ss); 2732 rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written); 2733 ssl_ReleaseSpecReadLock(ss); 2734 if (rv != SECSuccess) { 2735 goto loser; 2736 } 2737 2738 PORT_Assert(written > 0); 2739 /* DTLS should not fragment non-application data here. */ 2740 if (IS_DTLS(ss) && ct != ssl_ct_application_data) { 2741 PORT_Assert(written == nIn); 2742 } 2743 2744 pIn += written; 2745 nIn -= written; 2746 PORT_Assert(nIn >= 0); 2747 2748 /* If there's still some previously saved ciphertext, 2749 * or the caller doesn't want us to send the data yet, 2750 * then add all our new ciphertext to the amount previously saved. 2751 */ 2752 if ((ss->pendingBuf.len > 0) || 2753 (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { 2754 2755 rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf), 2756 SSL_BUFFER_LEN(wrBuf)); 2757 if (rv != SECSuccess) { 2758 /* presumably a memory error, SEC_ERROR_NO_MEMORY */ 2759 goto loser; 2760 } 2761 2762 if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { 2763 ss->handshakeBegun = 1; 2764 sent = ssl_SendSavedWriteData(ss); 2765 if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { 2766 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); 2767 goto loser; 2768 } 2769 if (ss->pendingBuf.len) { 2770 flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; 2771 } 2772 } 2773 } else { 2774 PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0); 2775 ss->handshakeBegun = 1; 2776 sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf), 2777 SSL_BUFFER_LEN(wrBuf), 2778 flags & ~ssl_SEND_FLAG_MASK); 2779 if (sent < 0) { 2780 if (PORT_GetError() != PR_WOULD_BLOCK_ERROR) { 2781 ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); 2782 goto loser; 2783 } 2784 /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ 2785 sent = 0; 2786 } 2787 if (SSL_BUFFER_LEN(wrBuf) > (unsigned int)sent) { 2788 if (IS_DTLS(ss)) { 2789 /* DTLS just says no in this case. No buffering */ 2790 PORT_SetError(PR_WOULD_BLOCK_ERROR); 2791 goto loser; 2792 } 2793 /* now take all the remaining unsent new ciphertext and 2794 * append it to the buffer of previously unsent ciphertext. 2795 */ 2796 rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf) + sent, 2797 SSL_BUFFER_LEN(wrBuf) - sent); 2798 if (rv != SECSuccess) { 2799 /* presumably a memory error, SEC_ERROR_NO_MEMORY */ 2800 goto loser; 2801 } 2802 } 2803 } 2804 wrBuf->len = 0; 2805 totalSent += written; 2806 } 2807 return totalSent; 2808 2809 loser: 2810 /* Don't leave bits of buffer lying around. */ 2811 wrBuf->len = 0; 2812 return -1; 2813 } 2814 2815 #define SSL3_PENDING_HIGH_WATER 1024 2816 2817 /* Attempt to send the content of "in" in an SSL application_data record. 2818 * Returns "len" or -1 on failure. 2819 */ 2820 int 2821 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, 2822 PRInt32 len, PRInt32 flags) 2823 { 2824 PRInt32 totalSent = 0; 2825 PRInt32 discarded = 0; 2826 PRBool splitNeeded = PR_FALSE; 2827 2828 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 2829 /* These flags for internal use only */ 2830 PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT)); 2831 if (len < 0 || !in) { 2832 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 2833 return -1; 2834 } 2835 2836 if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && 2837 !ssl_SocketIsBlocking(ss)) { 2838 PORT_Assert(!ssl_SocketIsBlocking(ss)); 2839 PORT_SetError(PR_WOULD_BLOCK_ERROR); 2840 return -1; 2841 } 2842 2843 if (ss->appDataBuffered && len) { 2844 PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered)); 2845 if (in[0] != (unsigned char)(ss->appDataBuffered)) { 2846 PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 2847 return -1; 2848 } 2849 in++; 2850 len--; 2851 discarded = 1; 2852 } 2853 2854 /* We will split the first byte of the record into its own record, as 2855 * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h. 2856 */ 2857 if (len > 1 && ss->opt.cbcRandomIV && 2858 ss->version < SSL_LIBRARY_VERSION_TLS_1_1 && 2859 ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) { 2860 splitNeeded = PR_TRUE; 2861 } 2862 2863 while (len > totalSent) { 2864 PRInt32 sent, toSend; 2865 2866 if (totalSent > 0) { 2867 /* 2868 * The thread yield is intended to give the reader thread a 2869 * chance to get some cycles while the writer thread is in 2870 * the middle of a large application data write. (See 2871 * Bugzilla bug 127740, comment #1.) 2872 */ 2873 ssl_ReleaseXmitBufLock(ss); 2874 PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */ 2875 ssl_GetXmitBufLock(ss); 2876 } 2877 2878 if (splitNeeded) { 2879 toSend = 1; 2880 splitNeeded = PR_FALSE; 2881 } else { 2882 toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); 2883 } 2884 2885 /* 2886 * Note that the 0 epoch is OK because flags will never require 2887 * its use, as guaranteed by the PORT_Assert above. 2888 */ 2889 sent = ssl3_SendRecord(ss, NULL, ssl_ct_application_data, 2890 in + totalSent, toSend, flags); 2891 if (sent < 0) { 2892 if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { 2893 PORT_Assert(ss->lastWriteBlocked); 2894 break; 2895 } 2896 return -1; /* error code set by ssl3_SendRecord */ 2897 } 2898 totalSent += sent; 2899 if (ss->pendingBuf.len) { 2900 /* must be a non-blocking socket */ 2901 PORT_Assert(!ssl_SocketIsBlocking(ss)); 2902 PORT_Assert(ss->lastWriteBlocked); 2903 break; 2904 } 2905 } 2906 if (ss->pendingBuf.len) { 2907 /* Must be non-blocking. */ 2908 PORT_Assert(!ssl_SocketIsBlocking(ss)); 2909 if (totalSent > 0) { 2910 ss->appDataBuffered = 0x100 | in[totalSent - 1]; 2911 } 2912 2913 totalSent = totalSent + discarded - 1; 2914 if (totalSent <= 0) { 2915 PORT_SetError(PR_WOULD_BLOCK_ERROR); 2916 totalSent = SECFailure; 2917 } 2918 return totalSent; 2919 } 2920 ss->appDataBuffered = 0; 2921 return totalSent + discarded; 2922 } 2923 2924 /* Attempt to send buffered handshake messages. 2925 * Always set sendBuf.len to 0, even when returning SECFailure. 2926 * 2927 * Depending on whether we are doing DTLS or not, this either calls 2928 * 2929 * - ssl3_FlushHandshakeMessages if non-DTLS 2930 * - dtls_FlushHandshakeMessages if DTLS 2931 * 2932 * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(), 2933 * ssl3_AppendHandshake(), ssl3_SendClientHello(), 2934 * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(), 2935 * ssl3_SendFinished(), 2936 */ 2937 SECStatus 2938 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) 2939 { 2940 if (IS_DTLS(ss)) { 2941 return dtls_FlushHandshakeMessages(ss, flags); 2942 } 2943 return ssl3_FlushHandshakeMessages(ss, flags); 2944 } 2945 2946 /* Attempt to send the content of sendBuf buffer in an SSL handshake record. 2947 * Always set sendBuf.len to 0, even when returning SECFailure. 2948 * 2949 * Called from ssl3_FlushHandshake 2950 */ 2951 static SECStatus 2952 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) 2953 { 2954 static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; 2955 PRInt32 count = -1; 2956 SECStatus rv; 2957 2958 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 2959 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 2960 2961 if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len) 2962 return SECSuccess; 2963 2964 /* only these flags are allowed */ 2965 PORT_Assert(!(flags & ~allowedFlags)); 2966 if ((flags & ~allowedFlags) != 0) { 2967 PORT_SetError(SEC_ERROR_INVALID_ARGS); 2968 return SECFailure; 2969 } 2970 count = ssl3_SendRecord(ss, NULL, ssl_ct_handshake, 2971 ss->sec.ci.sendBuf.buf, 2972 ss->sec.ci.sendBuf.len, flags); 2973 if (count < 0) { 2974 int err = PORT_GetError(); 2975 PORT_Assert(err != PR_WOULD_BLOCK_ERROR); 2976 if (err == PR_WOULD_BLOCK_ERROR) { 2977 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2978 } 2979 rv = SECFailure; 2980 } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) { 2981 /* short write should never happen */ 2982 PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len); 2983 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 2984 rv = SECFailure; 2985 } else { 2986 rv = SECSuccess; 2987 } 2988 2989 /* Whether we succeeded or failed, toss the old handshake data. */ 2990 ss->sec.ci.sendBuf.len = 0; 2991 return rv; 2992 } 2993 2994 /* 2995 * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when 2996 * the remote client sends a negative response to our certificate request. 2997 * Returns SECFailure if the application has required client auth. 2998 * SECSuccess otherwise. 2999 */ 3000 SECStatus 3001 ssl3_HandleNoCertificate(sslSocket *ss) 3002 { 3003 ssl3_CleanupPeerCerts(ss); 3004 3005 /* If the server has required client-auth blindly but doesn't 3006 * actually look at the certificate it won't know that no 3007 * certificate was presented so we shutdown the socket to ensure 3008 * an error. We only do this if we haven't already completed the 3009 * first handshake because if we're redoing the handshake we 3010 * know the server is paying attention to the certificate. 3011 */ 3012 if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || 3013 (!ss->firstHsDone && 3014 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { 3015 PRFileDesc *lower; 3016 3017 ssl_UncacheSessionID(ss); 3018 3019 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 3020 SSL3_SendAlert(ss, alert_fatal, certificate_required); 3021 } else { 3022 SSL3_SendAlert(ss, alert_fatal, bad_certificate); 3023 } 3024 3025 lower = ss->fd->lower; 3026 #ifdef _WIN32 3027 lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); 3028 #else 3029 lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); 3030 #endif 3031 PORT_SetError(SSL_ERROR_NO_CERTIFICATE); 3032 return SECFailure; 3033 } 3034 return SECSuccess; 3035 } 3036 3037 /************************************************************************ 3038 * Alerts 3039 */ 3040 3041 /* 3042 ** Acquires both handshake and XmitBuf locks. 3043 ** Called from: ssl3_IllegalParameter <- 3044 ** ssl3_HandshakeFailure <- 3045 ** ssl3_HandleAlert <- ssl3_HandleRecord. 3046 ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord 3047 ** ssl3_ConsumeHandshakeVariable <- 3048 ** ssl3_HandleHelloRequest <- 3049 ** ssl3_HandleServerHello <- 3050 ** ssl3_HandleServerKeyExchange <- 3051 ** ssl3_HandleCertificateRequest <- 3052 ** ssl3_HandleServerHelloDone <- 3053 ** ssl3_HandleClientHello <- 3054 ** ssl3_HandleV2ClientHello <- 3055 ** ssl3_HandleCertificateVerify <- 3056 ** ssl3_HandleClientKeyExchange <- 3057 ** ssl3_HandleCertificate <- 3058 ** ssl3_HandleFinished <- 3059 ** ssl3_HandleHandshakeMessage <- 3060 ** ssl3_HandlePostHelloHandshakeMessage <- 3061 ** ssl3_HandleRecord <- 3062 ** 3063 */ 3064 SECStatus 3065 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) 3066 { 3067 PRUint8 bytes[2]; 3068 SECStatus rv; 3069 PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss); 3070 3071 /* Check that if I need the HS lock I also need the Xmit lock */ 3072 PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss)); 3073 3074 SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", 3075 SSL_GETPID(), ss->fd, level, desc)); 3076 3077 bytes[0] = level; 3078 bytes[1] = desc; 3079 3080 if (needHsLock) { 3081 ssl_GetSSL3HandshakeLock(ss); 3082 } 3083 if (level == alert_fatal) { 3084 if (ss->sec.ci.sid) { 3085 ssl_UncacheSessionID(ss); 3086 } 3087 } 3088 3089 rv = tls13_SetAlertCipherSpec(ss); 3090 if (rv != SECSuccess) { 3091 if (needHsLock) { 3092 ssl_ReleaseSSL3HandshakeLock(ss); 3093 } 3094 return rv; 3095 } 3096 3097 ssl_GetXmitBufLock(ss); 3098 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 3099 if (rv == SECSuccess) { 3100 PRInt32 sent; 3101 sent = ssl3_SendRecord(ss, NULL, ssl_ct_alert, bytes, 2, 3102 (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); 3103 rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; 3104 } 3105 if (level == alert_fatal) { 3106 ss->ssl3.fatalAlertSent = PR_TRUE; 3107 } 3108 ssl_ReleaseXmitBufLock(ss); 3109 if (needHsLock) { 3110 ssl_ReleaseSSL3HandshakeLock(ss); 3111 } 3112 if (rv == SECSuccess && ss->alertSentCallback) { 3113 SSLAlert alert = { level, desc }; 3114 ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert); 3115 } 3116 return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ 3117 } 3118 3119 /* 3120 * Send illegal_parameter alert. Set generic error number. 3121 */ 3122 static SECStatus 3123 ssl3_IllegalParameter(sslSocket *ss) 3124 { 3125 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 3126 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 3127 : SSL_ERROR_BAD_SERVER); 3128 return SECFailure; 3129 } 3130 3131 /* 3132 * Send handshake_Failure alert. Set generic error number. 3133 */ 3134 static SECStatus 3135 ssl3_HandshakeFailure(sslSocket *ss) 3136 { 3137 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); 3138 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 3139 : SSL_ERROR_BAD_SERVER); 3140 return SECFailure; 3141 } 3142 3143 void 3144 ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode) 3145 { 3146 SSL3AlertDescription desc = bad_certificate; 3147 PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS; 3148 3149 switch (errCode) { 3150 case SEC_ERROR_LIBRARY_FAILURE: 3151 desc = unsupported_certificate; 3152 break; 3153 case SEC_ERROR_EXPIRED_CERTIFICATE: 3154 desc = certificate_expired; 3155 break; 3156 case SEC_ERROR_REVOKED_CERTIFICATE: 3157 desc = certificate_revoked; 3158 break; 3159 case SEC_ERROR_INADEQUATE_KEY_USAGE: 3160 case SEC_ERROR_INADEQUATE_CERT_TYPE: 3161 desc = certificate_unknown; 3162 break; 3163 case SEC_ERROR_UNTRUSTED_CERT: 3164 desc = isTLS ? access_denied : certificate_unknown; 3165 break; 3166 case SEC_ERROR_UNKNOWN_ISSUER: 3167 case SEC_ERROR_UNTRUSTED_ISSUER: 3168 desc = isTLS ? unknown_ca : certificate_unknown; 3169 break; 3170 case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: 3171 desc = isTLS ? unknown_ca : certificate_expired; 3172 break; 3173 3174 case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: 3175 case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: 3176 case SEC_ERROR_CA_CERT_INVALID: 3177 case SEC_ERROR_BAD_SIGNATURE: 3178 default: 3179 desc = bad_certificate; 3180 break; 3181 } 3182 SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d", 3183 SSL_GETPID(), ss->fd, errCode)); 3184 3185 (void)SSL3_SendAlert(ss, alert_fatal, desc); 3186 } 3187 3188 /* 3189 * Send decode_error alert. Set generic error number. 3190 */ 3191 SECStatus 3192 ssl3_DecodeError(sslSocket *ss) 3193 { 3194 (void)SSL3_SendAlert(ss, alert_fatal, 3195 ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error 3196 : illegal_parameter); 3197 PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 3198 : SSL_ERROR_BAD_SERVER); 3199 return SECFailure; 3200 } 3201 3202 /* Called from ssl3_HandleRecord. 3203 ** Caller must hold both RecvBuf and Handshake locks. 3204 */ 3205 static SECStatus 3206 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) 3207 { 3208 SSL3AlertLevel level; 3209 SSL3AlertDescription desc; 3210 int error; 3211 3212 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 3213 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 3214 3215 SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd)); 3216 3217 if (buf->len != 2) { 3218 (void)ssl3_DecodeError(ss); 3219 PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); 3220 return SECFailure; 3221 } 3222 level = (SSL3AlertLevel)buf->buf[0]; 3223 desc = (SSL3AlertDescription)buf->buf[1]; 3224 buf->len = 0; 3225 SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d", 3226 SSL_GETPID(), ss->fd, level, desc)); 3227 3228 if (ss->alertReceivedCallback) { 3229 SSLAlert alert = { level, desc }; 3230 ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert); 3231 } 3232 3233 switch (desc) { 3234 case close_notify: 3235 ss->recvdCloseNotify = 1; 3236 error = SSL_ERROR_CLOSE_NOTIFY_ALERT; 3237 break; 3238 case unexpected_message: 3239 error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; 3240 break; 3241 case bad_record_mac: 3242 error = SSL_ERROR_BAD_MAC_ALERT; 3243 break; 3244 case decryption_failed_RESERVED: 3245 error = SSL_ERROR_DECRYPTION_FAILED_ALERT; 3246 break; 3247 case record_overflow: 3248 error = SSL_ERROR_RECORD_OVERFLOW_ALERT; 3249 break; 3250 case decompression_failure: 3251 error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; 3252 break; 3253 case handshake_failure: 3254 error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; 3255 break; 3256 case no_certificate: 3257 error = SSL_ERROR_NO_CERTIFICATE; 3258 break; 3259 case certificate_required: 3260 error = SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT; 3261 break; 3262 case bad_certificate: 3263 error = SSL_ERROR_BAD_CERT_ALERT; 3264 break; 3265 case unsupported_certificate: 3266 error = SSL_ERROR_UNSUPPORTED_CERT_ALERT; 3267 break; 3268 case certificate_revoked: 3269 error = SSL_ERROR_REVOKED_CERT_ALERT; 3270 break; 3271 case certificate_expired: 3272 error = SSL_ERROR_EXPIRED_CERT_ALERT; 3273 break; 3274 case certificate_unknown: 3275 error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; 3276 break; 3277 case illegal_parameter: 3278 error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT; 3279 break; 3280 case inappropriate_fallback: 3281 error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; 3282 break; 3283 3284 /* All alerts below are TLS only. */ 3285 case unknown_ca: 3286 error = SSL_ERROR_UNKNOWN_CA_ALERT; 3287 break; 3288 case access_denied: 3289 error = SSL_ERROR_ACCESS_DENIED_ALERT; 3290 break; 3291 case decode_error: 3292 error = SSL_ERROR_DECODE_ERROR_ALERT; 3293 break; 3294 case decrypt_error: 3295 error = SSL_ERROR_DECRYPT_ERROR_ALERT; 3296 break; 3297 case export_restriction: 3298 error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; 3299 break; 3300 case protocol_version: 3301 error = SSL_ERROR_PROTOCOL_VERSION_ALERT; 3302 break; 3303 case insufficient_security: 3304 error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; 3305 break; 3306 case internal_error: 3307 error = SSL_ERROR_INTERNAL_ERROR_ALERT; 3308 break; 3309 case user_canceled: 3310 error = SSL_ERROR_USER_CANCELED_ALERT; 3311 break; 3312 case no_renegotiation: 3313 error = SSL_ERROR_NO_RENEGOTIATION_ALERT; 3314 break; 3315 3316 /* Alerts for TLS client hello extensions */ 3317 case missing_extension: 3318 error = SSL_ERROR_MISSING_EXTENSION_ALERT; 3319 break; 3320 case unsupported_extension: 3321 error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; 3322 break; 3323 case certificate_unobtainable: 3324 error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; 3325 break; 3326 case unrecognized_name: 3327 error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 3328 break; 3329 case bad_certificate_status_response: 3330 error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; 3331 break; 3332 case bad_certificate_hash_value: 3333 error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; 3334 break; 3335 case no_application_protocol: 3336 error = SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL; 3337 break; 3338 case ech_required: 3339 error = SSL_ERROR_ECH_REQUIRED_ALERT; 3340 break; 3341 default: 3342 error = SSL_ERROR_RX_UNKNOWN_ALERT; 3343 break; 3344 } 3345 if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) && 3346 (ss->ssl3.hs.ws != wait_server_hello)) { 3347 /* TLS 1.3 requires all but "end of data" alerts to be 3348 * treated as fatal. */ 3349 switch (desc) { 3350 case close_notify: 3351 case user_canceled: 3352 break; 3353 default: 3354 level = alert_fatal; 3355 } 3356 } 3357 if (level == alert_fatal) { 3358 ssl_UncacheSessionID(ss); 3359 if ((ss->ssl3.hs.ws == wait_server_hello) && 3360 (desc == handshake_failure)) { 3361 /* XXX This is a hack. We're assuming that any handshake failure 3362 * XXX on the client hello is a failure to match ciphers. 3363 */ 3364 error = SSL_ERROR_NO_CYPHER_OVERLAP; 3365 } 3366 PORT_SetError(error); 3367 return SECFailure; 3368 } 3369 if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) { 3370 /* I'm a server. I've requested a client cert. He hasn't got one. */ 3371 SECStatus rv; 3372 3373 PORT_Assert(ss->sec.isServer); 3374 ss->ssl3.hs.ws = wait_client_key; 3375 rv = ssl3_HandleNoCertificate(ss); 3376 return rv; 3377 } 3378 return SECSuccess; 3379 } 3380 3381 /* 3382 * Change Cipher Specs 3383 * Called from ssl3_HandleServerHelloDone, 3384 * ssl3_HandleClientHello, 3385 * and ssl3_HandleFinished 3386 * 3387 * Acquires and releases spec write lock, to protect switching the current 3388 * and pending write spec pointers. 3389 */ 3390 3391 SECStatus 3392 ssl3_SendChangeCipherSpecsInt(sslSocket *ss) 3393 { 3394 PRUint8 change = change_cipher_spec_choice; 3395 SECStatus rv; 3396 3397 SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", 3398 SSL_GETPID(), ss->fd)); 3399 3400 rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 3401 if (rv != SECSuccess) { 3402 return SECFailure; /* error code set by ssl3_FlushHandshake */ 3403 } 3404 3405 if (!IS_DTLS(ss)) { 3406 PRInt32 sent; 3407 sent = ssl3_SendRecord(ss, NULL, ssl_ct_change_cipher_spec, 3408 &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 3409 if (sent < 0) { 3410 return SECFailure; /* error code set by ssl3_SendRecord */ 3411 } 3412 } else { 3413 rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1); 3414 if (rv != SECSuccess) { 3415 return SECFailure; 3416 } 3417 } 3418 return SECSuccess; 3419 } 3420 3421 static SECStatus 3422 ssl3_SendChangeCipherSpecs(sslSocket *ss) 3423 { 3424 SECStatus rv; 3425 3426 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 3427 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 3428 3429 rv = ssl3_SendChangeCipherSpecsInt(ss); 3430 if (rv != SECSuccess) { 3431 return rv; /* Error code set. */ 3432 } 3433 3434 /* swap the pending and current write specs. */ 3435 ssl_GetSpecWriteLock(ss); /**************************************/ 3436 3437 ssl_CipherSpecRelease(ss->ssl3.cwSpec); 3438 ss->ssl3.cwSpec = ss->ssl3.pwSpec; 3439 ss->ssl3.pwSpec = NULL; 3440 3441 SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", 3442 SSL_GETPID(), ss->fd)); 3443 3444 /* With DTLS, we need to set a holddown timer in case the final 3445 * message got lost */ 3446 if (IS_DTLS(ss) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) { 3447 rv = dtls_StartHolddownTimer(ss); 3448 } 3449 ssl_ReleaseSpecWriteLock(ss); /**************************************/ 3450 3451 return rv; 3452 } 3453 3454 /* Called from ssl3_HandleRecord. 3455 ** Caller must hold both RecvBuf and Handshake locks. 3456 * 3457 * Acquires and releases spec write lock, to protect switching the current 3458 * and pending write spec pointers. 3459 */ 3460 static SECStatus 3461 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) 3462 { 3463 SSL3WaitState ws = ss->ssl3.hs.ws; 3464 SSL3ChangeCipherSpecChoice change; 3465 3466 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 3467 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 3468 3469 SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record", 3470 SSL_GETPID(), ss->fd)); 3471 3472 /* For DTLS: Ignore this if we aren't expecting it. Don't kill a connection 3473 * as a result of receiving trash. 3474 * For TLS: Maybe ignore, but only after checking format. */ 3475 if (ws != wait_change_cipher && IS_DTLS(ss)) { 3476 /* Ignore this because it's out of order. */ 3477 SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " 3478 "DTLS change_cipher_spec", 3479 SSL_GETPID(), ss->fd)); 3480 buf->len = 0; 3481 return SECSuccess; 3482 } 3483 3484 /* Handshake messages should not span ChangeCipherSpec. */ 3485 if (ss->ssl3.hs.header_bytes) { 3486 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 3487 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); 3488 return SECFailure; 3489 } 3490 if (buf->len != 1) { 3491 (void)ssl3_DecodeError(ss); 3492 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); 3493 return SECFailure; 3494 } 3495 change = (SSL3ChangeCipherSpecChoice)buf->buf[0]; 3496 if (change != change_cipher_spec_choice) { 3497 /* illegal_parameter is correct here for both SSL3 and TLS. */ 3498 (void)ssl3_IllegalParameter(ss); 3499 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); 3500 return SECFailure; 3501 } 3502 3503 buf->len = 0; 3504 if (ws != wait_change_cipher) { 3505 /* Ignore a CCS for TLS 1.3. This only happens if the server sends a 3506 * HelloRetryRequest. In other cases, the CCS will fail decryption and 3507 * will be discarded by ssl3_HandleRecord(). */ 3508 if (ws == wait_server_hello && 3509 ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 3510 ss->ssl3.hs.helloRetry) { 3511 PORT_Assert(!ss->sec.isServer); 3512 return SECSuccess; 3513 } 3514 /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or 3515 * ss->version because the server might be stateless (and so it won't 3516 * have set either value yet). Set a flag so that at least we will 3517 * guarantee that the server will treat any ClientHello properly. */ 3518 if (ws == wait_client_hello && 3519 ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 && 3520 !ss->ssl3.hs.receivedCcs) { 3521 PORT_Assert(ss->sec.isServer); 3522 ss->ssl3.hs.receivedCcs = PR_TRUE; 3523 return SECSuccess; 3524 } 3525 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 3526 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); 3527 return SECFailure; 3528 } 3529 3530 SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", 3531 SSL_GETPID(), ss->fd)); 3532 ssl_GetSpecWriteLock(ss); /*************************************/ 3533 PORT_Assert(ss->ssl3.prSpec); 3534 ssl_CipherSpecRelease(ss->ssl3.crSpec); 3535 ss->ssl3.crSpec = ss->ssl3.prSpec; 3536 ss->ssl3.prSpec = NULL; 3537 ssl_ReleaseSpecWriteLock(ss); /*************************************/ 3538 3539 ss->ssl3.hs.ws = wait_finished; 3540 return SECSuccess; 3541 } 3542 3543 static CK_MECHANISM_TYPE 3544 ssl3_GetMgfMechanismByHashType(SSLHashType hash) 3545 { 3546 switch (hash) { 3547 case ssl_hash_sha256: 3548 return CKG_MGF1_SHA256; 3549 case ssl_hash_sha384: 3550 return CKG_MGF1_SHA384; 3551 case ssl_hash_sha512: 3552 return CKG_MGF1_SHA512; 3553 default: 3554 PORT_Assert(0); 3555 } 3556 return CKG_MGF1_SHA256; 3557 } 3558 3559 /* Function valid for >= TLS 1.2, only. */ 3560 static CK_MECHANISM_TYPE 3561 ssl3_GetHashMechanismByHashType(SSLHashType hashType) 3562 { 3563 switch (hashType) { 3564 case ssl_hash_sha512: 3565 return CKM_SHA512; 3566 case ssl_hash_sha384: 3567 return CKM_SHA384; 3568 case ssl_hash_sha256: 3569 case ssl_hash_none: 3570 /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */ 3571 return CKM_SHA256; 3572 case ssl_hash_sha1: 3573 return CKM_SHA_1; 3574 default: 3575 PORT_Assert(0); 3576 } 3577 return CKM_SHA256; 3578 } 3579 3580 /* Function valid for >= TLS 1.2, only. */ 3581 static CK_MECHANISM_TYPE 3582 ssl3_GetPrfHashMechanism(sslSocket *ss) 3583 { 3584 return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash); 3585 } 3586 3587 static SSLHashType 3588 ssl3_GetSuitePrfHash(sslSocket *ss) 3589 { 3590 /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */ 3591 if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) { 3592 return ssl_hash_sha256; 3593 } 3594 return ss->ssl3.hs.suite_def->prf_hash; 3595 } 3596 3597 /* This method completes the derivation of the MS from the PMS. 3598 ** 3599 ** 1. Derive the MS, if possible, else return an error. 3600 ** 3601 ** 2. Check the version if |pms_version| is non-zero and if wrong, 3602 ** return an error. 3603 ** 3604 ** 3. If |msp| is nonzero, return MS in |*msp|. 3605 3606 ** Called from: 3607 ** ssl3_ComputeMasterSecretInt 3608 ** tls_ComputeExtendedMasterSecretInt 3609 */ 3610 static SECStatus 3611 ssl3_ComputeMasterSecretFinish(sslSocket *ss, 3612 CK_MECHANISM_TYPE master_derive, 3613 CK_MECHANISM_TYPE key_derive, 3614 CK_VERSION *pms_version, 3615 SECItem *params, CK_FLAGS keyFlags, 3616 PK11SymKey *pms, PK11SymKey **msp) 3617 { 3618 PK11SymKey *ms = NULL; 3619 3620 ms = PK11_DeriveWithFlags(pms, master_derive, 3621 params, key_derive, 3622 CKA_DERIVE, 0, keyFlags); 3623 if (!ms) { 3624 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 3625 return SECFailure; 3626 } 3627 3628 if (pms_version && ss->opt.detectRollBack) { 3629 SSL3ProtocolVersion client_version; 3630 client_version = pms_version->major << 8 | pms_version->minor; 3631 3632 if (IS_DTLS(ss)) { 3633 client_version = dtls_DTLSVersionToTLSVersion(client_version); 3634 } 3635 3636 if (client_version != ss->clientHelloVersion) { 3637 /* Destroy MS. Version roll-back detected. */ 3638 PK11_FreeSymKey(ms); 3639 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 3640 return SECFailure; 3641 } 3642 } 3643 3644 if (msp) { 3645 *msp = ms; 3646 } else { 3647 PK11_FreeSymKey(ms); 3648 } 3649 3650 return SECSuccess; 3651 } 3652 3653 /* Compute the ordinary (pre draft-ietf-tls-session-hash) master 3654 ** secret and return it in |*msp|. 3655 ** 3656 ** Called from: ssl3_ComputeMasterSecret 3657 */ 3658 static SECStatus 3659 ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms, 3660 PK11SymKey **msp) 3661 { 3662 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0); 3663 PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2); 3664 /* 3665 * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH 3666 * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size 3667 * data into a 48-byte value, and does not expect to return the version. 3668 */ 3669 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) || 3670 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) || 3671 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid)); 3672 CK_MECHANISM_TYPE master_derive; 3673 CK_MECHANISM_TYPE key_derive; 3674 SECItem params; 3675 CK_FLAGS keyFlags; 3676 CK_VERSION pms_version; 3677 CK_VERSION *pms_version_ptr = NULL; 3678 /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */ 3679 CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params; 3680 unsigned int master_params_len; 3681 3682 /* if we are using TLS and we aren't using the extended master secret, 3683 * and SEC_OID_TLS_REQUIRE_EMS policy is true, fail. The caller will 3684 * send an alert (eventually). In the RSA Server case, the alert 3685 * won't happen until Finish time because the upper level code 3686 * can't tell a difference between this failure and an RSA decrypt 3687 * failure, so it will proceed with a faux key */ 3688 if (isTLS) { 3689 PRUint32 policy; 3690 SECStatus rv; 3691 3692 /* first fetch the policy for this algorithm */ 3693 rv = NSS_GetAlgorithmPolicy(SEC_OID_TLS_REQUIRE_EMS, &policy); 3694 /* we only look at the policy if we can fetch it. */ 3695 if ((rv == SECSuccess) && (policy & NSS_USE_ALG_IN_SSL_KX)) { 3696 /* just set the error, we don't want to map any errors 3697 * set by NSS_GetAlgorithmPolicy here */ 3698 PORT_SetError(SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET); 3699 return SECFailure; 3700 } 3701 } 3702 3703 if (isTLS12) { 3704 if (isDH) 3705 master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH; 3706 else 3707 master_derive = CKM_TLS12_MASTER_KEY_DERIVE; 3708 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; 3709 keyFlags = CKF_SIGN | CKF_VERIFY; 3710 } else if (isTLS) { 3711 if (isDH) 3712 master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH; 3713 else 3714 master_derive = CKM_TLS_MASTER_KEY_DERIVE; 3715 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 3716 keyFlags = CKF_SIGN | CKF_VERIFY; 3717 } else { 3718 if (isDH) 3719 master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH; 3720 else 3721 master_derive = CKM_SSL3_MASTER_KEY_DERIVE; 3722 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; 3723 keyFlags = 0; 3724 } 3725 3726 if (!isDH) { 3727 pms_version_ptr = &pms_version; 3728 } 3729 3730 master_params.pVersion = pms_version_ptr; 3731 master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random; 3732 master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; 3733 master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random; 3734 master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; 3735 if (isTLS12) { 3736 master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss); 3737 master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS); 3738 } else { 3739 /* prfHashMechanism is not relevant with this PRF */ 3740 master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS); 3741 } 3742 3743 params.data = (unsigned char *)&master_params; 3744 params.len = master_params_len; 3745 3746 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, 3747 pms_version_ptr, ¶ms, 3748 keyFlags, pms, msp); 3749 } 3750 3751 /* Compute the draft-ietf-tls-session-hash master 3752 ** secret and return it in |*msp|. 3753 ** 3754 ** Called from: ssl3_ComputeMasterSecret 3755 */ 3756 static SECStatus 3757 tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, 3758 PK11SymKey **msp) 3759 { 3760 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; 3761 CK_TLS12_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params; 3762 SSL3Hashes hashes; 3763 3764 /* 3765 * Determine whether to use the DH/ECDH or RSA derivation modes. 3766 */ 3767 /* 3768 * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion 3769 * mode. Bug 1198298 */ 3770 PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) || 3771 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh) || 3772 (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh_hybrid)); 3773 CK_MECHANISM_TYPE master_derive; 3774 CK_MECHANISM_TYPE key_derive; 3775 SECItem params; 3776 const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY; 3777 CK_VERSION pms_version; 3778 CK_VERSION *pms_version_ptr = NULL; 3779 SECStatus rv; 3780 3781 rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0); 3782 if (rv != SECSuccess) { 3783 PORT_Assert(0); /* Should never fail */ 3784 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 3785 return SECFailure; 3786 } 3787 3788 if (isDH) { 3789 master_derive = CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE_DH; 3790 } else { 3791 master_derive = CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE; 3792 pms_version_ptr = &pms_version; 3793 } 3794 3795 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 3796 /* TLS 1.2+ */ 3797 extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss); 3798 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; 3799 } else { 3800 /* TLS < 1.2 */ 3801 extended_master_params.prfHashMechanism = CKM_TLS_PRF; 3802 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 3803 } 3804 3805 extended_master_params.pVersion = pms_version_ptr; 3806 extended_master_params.pSessionHash = hashes.u.raw; 3807 extended_master_params.ulSessionHashLen = hashes.len; 3808 3809 params.data = (unsigned char *)&extended_master_params; 3810 params.len = sizeof extended_master_params; 3811 3812 return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, 3813 pms_version_ptr, ¶ms, 3814 keyFlags, pms, msp); 3815 } 3816 3817 /* Wrapper method to compute the master secret and return it in |*msp|. 3818 ** 3819 ** Called from ssl3_ComputeMasterSecret 3820 */ 3821 static SECStatus 3822 ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms, 3823 PK11SymKey **msp) 3824 { 3825 PORT_Assert(pms != NULL); 3826 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 3827 3828 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { 3829 return tls_ComputeExtendedMasterSecretInt(ss, pms, msp); 3830 } else { 3831 return ssl3_ComputeMasterSecretInt(ss, pms, msp); 3832 } 3833 } 3834 3835 /* 3836 * Derive encryption and MAC Keys (and IVs) from master secret 3837 * Sets a useful error code when returning SECFailure. 3838 * 3839 * Called only from ssl3_InitPendingCipherSpec(), 3840 * which in turn is called from 3841 * ssl3_SendRSAClientKeyExchange (for Full handshake) 3842 * ssl3_SendDHClientKeyExchange (for Full handshake) 3843 * ssl3_HandleClientKeyExchange (for Full handshake) 3844 * ssl3_HandleServerHello (for session restart) 3845 * ssl3_HandleClientHello (for session restart) 3846 * Caller MUST hold the specWriteLock, and SSL3HandshakeLock. 3847 * ssl3_InitPendingCipherSpec does that. 3848 * 3849 */ 3850 static SECStatus 3851 ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret) 3852 { 3853 ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; 3854 ssl3CipherSpec *prSpec = ss->ssl3.prSpec; 3855 ssl3CipherSpec *clientSpec; 3856 ssl3CipherSpec *serverSpec; 3857 PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0); 3858 PRBool isTLS12 = 3859 (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_2); 3860 const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef; 3861 PK11SlotInfo *slot = NULL; 3862 PK11SymKey *derivedKeyHandle = NULL; 3863 void *pwArg = ss->pkcs11PinArg; 3864 int keySize; 3865 CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a 3866 * CK_SSL3_KEY_MAT_PARAMS */ 3867 unsigned int key_material_params_len; 3868 CK_SSL3_KEY_MAT_OUT returnedKeys; 3869 CK_MECHANISM_TYPE key_derive; 3870 CK_MECHANISM_TYPE bulk_mechanism; 3871 SSLCipherAlgorithm calg; 3872 SECItem params; 3873 PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null); 3874 3875 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 3876 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 3877 PORT_Assert(masterSecret); 3878 3879 /* These functions operate in terms of who is writing specs. */ 3880 if (ss->sec.isServer) { 3881 clientSpec = prSpec; 3882 serverSpec = pwSpec; 3883 } else { 3884 clientSpec = pwSpec; 3885 serverSpec = prSpec; 3886 } 3887 3888 /* 3889 * generate the key material 3890 */ 3891 if (cipher_def->type == type_block && 3892 ss->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 3893 /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ 3894 key_material_params.ulIVSizeInBits = 0; 3895 PORT_Memset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size); 3896 PORT_Memset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size); 3897 } 3898 3899 key_material_params.bIsExport = PR_FALSE; 3900 key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random; 3901 key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; 3902 key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random; 3903 key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; 3904 key_material_params.pReturnedKeyMaterial = &returnedKeys; 3905 3906 if (skipKeysAndIVs) { 3907 keySize = 0; 3908 returnedKeys.pIVClient = NULL; 3909 returnedKeys.pIVServer = NULL; 3910 key_material_params.ulKeySizeInBits = 0; 3911 key_material_params.ulIVSizeInBits = 0; 3912 } else { 3913 keySize = cipher_def->key_size; 3914 returnedKeys.pIVClient = clientSpec->keyMaterial.iv; 3915 returnedKeys.pIVServer = serverSpec->keyMaterial.iv; 3916 key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB; 3917 key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; 3918 } 3919 key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB; 3920 3921 calg = cipher_def->calg; 3922 bulk_mechanism = ssl3_Alg2Mech(calg); 3923 3924 if (isTLS12) { 3925 key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; 3926 key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss); 3927 key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS); 3928 } else if (isTLS) { 3929 key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 3930 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); 3931 } else { 3932 key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; 3933 key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS); 3934 } 3935 3936 params.data = (unsigned char *)&key_material_params; 3937 params.len = key_material_params_len; 3938 3939 /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and 3940 * DERIVE by DEFAULT */ 3941 derivedKeyHandle = PK11_Derive(masterSecret, key_derive, ¶ms, 3942 bulk_mechanism, CKA_ENCRYPT, keySize); 3943 if (!derivedKeyHandle) { 3944 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 3945 return SECFailure; 3946 } 3947 /* we really should use the actual mac'ing mechanism here, but we 3948 * don't because these types are used to map keytype anyway and both 3949 * mac's map to the same keytype. 3950 */ 3951 slot = PK11_GetSlotFromKey(derivedKeyHandle); 3952 3953 PK11_FreeSlot(slot); /* slot is held until the key is freed */ 3954 clientSpec->keyMaterial.macKey = 3955 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive, 3956 CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, 3957 PR_TRUE, pwArg); 3958 if (clientSpec->keyMaterial.macKey == NULL) { 3959 goto loser; /* loser sets err */ 3960 } 3961 serverSpec->keyMaterial.macKey = 3962 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive, 3963 CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, 3964 PR_TRUE, pwArg); 3965 if (serverSpec->keyMaterial.macKey == NULL) { 3966 goto loser; /* loser sets err */ 3967 } 3968 if (!skipKeysAndIVs) { 3969 clientSpec->keyMaterial.key = 3970 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive, 3971 bulk_mechanism, returnedKeys.hClientKey, 3972 PR_TRUE, pwArg); 3973 if (clientSpec->keyMaterial.key == NULL) { 3974 goto loser; /* loser sets err */ 3975 } 3976 serverSpec->keyMaterial.key = 3977 PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive, 3978 bulk_mechanism, returnedKeys.hServerKey, 3979 PR_TRUE, pwArg); 3980 if (serverSpec->keyMaterial.key == NULL) { 3981 goto loser; /* loser sets err */ 3982 } 3983 } 3984 PK11_FreeSymKey(derivedKeyHandle); 3985 return SECSuccess; 3986 3987 loser: 3988 PK11_FreeSymKey(derivedKeyHandle); 3989 ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 3990 return SECFailure; 3991 } 3992 3993 void 3994 ssl3_CoalesceEchHandshakeHashes(sslSocket *ss) 3995 { 3996 /* |sha| contains the CHOuter transcript, which is the singular 3997 * transcript if not doing ECH. If the server responded with 1.2, 3998 * contexts are not yet initialized. */ 3999 if (ss->ssl3.hs.echAccepted) { 4000 if (ss->ssl3.hs.sha) { 4001 PORT_Assert(ss->ssl3.hs.shaEchInner); 4002 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); 4003 ss->ssl3.hs.sha = ss->ssl3.hs.shaEchInner; 4004 ss->ssl3.hs.shaEchInner = NULL; 4005 } 4006 } else { 4007 if (ss->ssl3.hs.shaEchInner) { 4008 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE); 4009 ss->ssl3.hs.shaEchInner = NULL; 4010 } 4011 } 4012 } 4013 4014 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in 4015 * buffered messages in ss->ssl3.hs.messages. Called from 4016 * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(), 4017 * and ssl3_HandleServerHello. */ 4018 SECStatus 4019 ssl3_InitHandshakeHashes(sslSocket *ss) 4020 { 4021 SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); 4022 4023 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); 4024 if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) { 4025 ss->ssl3.hs.hashType = handshake_hash_record; 4026 } else { 4027 PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); 4028 /* 4029 * note: We should probably lookup an SSL3 slot for these 4030 * handshake hashes in hopes that we wind up with the same slots 4031 * that the master secret will wind up in ... 4032 */ 4033 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 4034 /* determine the hash from the prf */ 4035 const SECOidData *hash_oid = 4036 SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss)); 4037 4038 /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash) 4039 * Convert that to the OidTag. We can then use that OidTag to create our 4040 * PK11Context */ 4041 PORT_Assert(hash_oid != NULL); 4042 if (hash_oid == NULL) { 4043 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4044 return SECFailure; 4045 } 4046 4047 ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset); 4048 if (ss->ssl3.hs.sha == NULL) { 4049 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4050 return SECFailure; 4051 } 4052 ss->ssl3.hs.hashType = handshake_hash_single; 4053 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { 4054 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4055 return SECFailure; 4056 } 4057 4058 /* Transcript hash used on ECH client. */ 4059 if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx) { 4060 ss->ssl3.hs.shaEchInner = PK11_CreateDigestContext(hash_oid->offset); 4061 if (ss->ssl3.hs.shaEchInner == NULL) { 4062 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4063 return SECFailure; 4064 } 4065 if (PK11_DigestBegin(ss->ssl3.hs.shaEchInner) != SECSuccess) { 4066 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4067 return SECFailure; 4068 } 4069 } 4070 } else { 4071 /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or 4072 * created successfully. */ 4073 ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); 4074 if (ss->ssl3.hs.md5 == NULL) { 4075 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 4076 return SECFailure; 4077 } 4078 ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); 4079 if (ss->ssl3.hs.sha == NULL) { 4080 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); 4081 ss->ssl3.hs.md5 = NULL; 4082 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4083 return SECFailure; 4084 } 4085 ss->ssl3.hs.hashType = handshake_hash_combo; 4086 4087 if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { 4088 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 4089 return SECFailure; 4090 } 4091 if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { 4092 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4093 return SECFailure; 4094 } 4095 } 4096 } 4097 4098 if (ss->ssl3.hs.hashType != handshake_hash_record && 4099 ss->ssl3.hs.messages.len > 0) { 4100 /* When doing ECH, ssl3_UpdateHandshakeHashes will store outer messages 4101 * into the both the outer and inner transcripts. 4102 * ssl3_UpdateDefaultHandshakeHashes uses the default context which is 4103 * the outer when doing client ECH. For ECH shared-mode or backend 4104 * servers only the hs.messages buffer is used. */ 4105 if (ssl3_UpdateDefaultHandshakeHashes(ss, ss->ssl3.hs.messages.buf, 4106 ss->ssl3.hs.messages.len) != SECSuccess) { 4107 return SECFailure; 4108 } 4109 /* When doing ECH, deriving the accept_confirmation value requires all 4110 * messages up to and including the ServerHello 4111 * (see draft-ietf-tls-esni-14, Section 7.2). 4112 * 4113 * Don't free the transcript buffer until confirmation calculation. */ 4114 if (!ss->ssl3.hs.echHpkeCtx && !ss->opt.enableTls13BackendEch) { 4115 sslBuffer_Clear(&ss->ssl3.hs.messages); 4116 } 4117 } 4118 if (ss->ssl3.hs.shaEchInner && 4119 ss->ssl3.hs.echInnerMessages.len > 0) { 4120 if (PK11_DigestOp(ss->ssl3.hs.shaEchInner, ss->ssl3.hs.echInnerMessages.buf, 4121 ss->ssl3.hs.echInnerMessages.len) != SECSuccess) { 4122 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4123 return SECFailure; 4124 } 4125 if (!ss->ssl3.hs.echHpkeCtx) { 4126 sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages); 4127 } 4128 } 4129 4130 return SECSuccess; 4131 } 4132 4133 void 4134 ssl3_RestartHandshakeHashes(sslSocket *ss) 4135 { 4136 SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes", 4137 SSL_GETPID(), ss->fd)); 4138 ss->ssl3.hs.hashType = handshake_hash_unknown; 4139 ss->ssl3.hs.messages.len = 0; 4140 ss->ssl3.hs.echInnerMessages.len = 0; 4141 if (ss->ssl3.hs.md5) { 4142 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); 4143 ss->ssl3.hs.md5 = NULL; 4144 } 4145 if (ss->ssl3.hs.sha) { 4146 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); 4147 ss->ssl3.hs.sha = NULL; 4148 } 4149 if (ss->ssl3.hs.shaEchInner) { 4150 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE); 4151 ss->ssl3.hs.shaEchInner = NULL; 4152 } 4153 if (ss->ssl3.hs.shaPostHandshake) { 4154 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE); 4155 ss->ssl3.hs.shaPostHandshake = NULL; 4156 } 4157 } 4158 4159 /* Add the provided bytes to the handshake hash context. When doing 4160 * TLS 1.3 ECH, |target| may be provided to specify only the inner/outer 4161 * transcript, else the input is added to both contexts. This happens 4162 * only on the client. On the server, only the default context is used. */ 4163 SECStatus 4164 ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b, 4165 unsigned int l, sslBuffer *target) 4166 { 4167 4168 SECStatus rv = SECSuccess; 4169 PRBool explicit = (target != NULL); 4170 PRBool appendToEchInner = !ss->sec.isServer && 4171 ss->ssl3.hs.echHpkeCtx && 4172 !explicit; 4173 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 4174 PORT_Assert(target != &ss->ssl3.hs.echInnerMessages || 4175 !ss->sec.isServer); 4176 4177 if (target == NULL) { 4178 /* Default context. */ 4179 target = &ss->ssl3.hs.messages; 4180 } 4181 /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es) 4182 * always up to date. However, we must initially buffer the handshake 4183 * messages, until we know what to do. 4184 * If ss->ssl3.hs.hashType != handshake_hash_unknown, 4185 * it means we know what to do. We calculate (hash our input), 4186 * and we stop appending to the buffer. 4187 * 4188 * With TLS 1.2, we always append all handshake messages, 4189 * and never update the hash, because the hash function we must use for 4190 * certificate_verify might be different from the hash function we use 4191 * when signing other handshake hashes. */ 4192 if (ss->ssl3.hs.hashType == handshake_hash_unknown || 4193 ss->ssl3.hs.hashType == handshake_hash_record) { 4194 rv = sslBuffer_Append(target, b, l); 4195 if (rv != SECSuccess) { 4196 return SECFailure; 4197 } 4198 if (appendToEchInner) { 4199 return sslBuffer_Append(&ss->ssl3.hs.echInnerMessages, b, l); 4200 } 4201 return SECSuccess; 4202 } 4203 4204 PRINT_BUF(90, (ss, "handshake hash input:", b, l)); 4205 4206 if (ss->ssl3.hs.hashType == handshake_hash_single) { 4207 PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); 4208 if (target == &ss->ssl3.hs.messages) { 4209 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); 4210 if (rv != SECSuccess) { 4211 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4212 return rv; 4213 } 4214 } 4215 if (ss->ssl3.hs.shaEchInner && 4216 (target == &ss->ssl3.hs.echInnerMessages || !explicit)) { 4217 rv = PK11_DigestOp(ss->ssl3.hs.shaEchInner, b, l); 4218 if (rv != SECSuccess) { 4219 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 4220 return rv; 4221 } 4222 } 4223 } else if (ss->ssl3.hs.hashType == handshake_hash_combo) { 4224 rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); 4225 if (rv != SECSuccess) { 4226 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 4227 return rv; 4228 } 4229 rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); 4230 if (rv != SECSuccess) { 4231 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 4232 return rv; 4233 } 4234 } 4235 return rv; 4236 } 4237 4238 static SECStatus 4239 ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, const unsigned char *b, 4240 unsigned int l) 4241 { 4242 return ssl3_UpdateHandshakeHashesInt(ss, b, l, 4243 &ss->ssl3.hs.messages); 4244 } 4245 4246 static SECStatus 4247 ssl3_UpdateInnerHandshakeHashes(sslSocket *ss, const unsigned char *b, 4248 unsigned int l) 4249 { 4250 return ssl3_UpdateHandshakeHashesInt(ss, b, l, 4251 &ss->ssl3.hs.echInnerMessages); 4252 } 4253 4254 /* 4255 * Handshake messages 4256 */ 4257 /* Called from ssl3_InitHandshakeHashes() 4258 ** ssl3_AppendHandshake() 4259 ** ssl3_HandleV2ClientHello() 4260 ** ssl3_HandleHandshakeMessage() 4261 ** Caller must hold the ssl3Handshake lock. 4262 */ 4263 SECStatus 4264 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l) 4265 { 4266 return ssl3_UpdateHandshakeHashesInt(ss, b, l, NULL); 4267 } 4268 4269 SECStatus 4270 ssl3_UpdatePostHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l) 4271 { 4272 SECStatus rv = SECSuccess; 4273 4274 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 4275 4276 PRINT_BUF(90, (ss, "post handshake hash input:", b, l)); 4277 4278 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single); 4279 PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); 4280 rv = PK11_DigestOp(ss->ssl3.hs.shaPostHandshake, b, l); 4281 if (rv != SECSuccess) { 4282 PORT_SetError(SSL_ERROR_DIGEST_FAILURE); 4283 } 4284 return rv; 4285 } 4286 4287 /* The next two functions serve to append the handshake header. 4288 The first one additionally writes to seqNumberBuffer 4289 the sequence number of the message we are generating. 4290 This function is used when generating the keyUpdate message in dtls13_enqueueKeyUpdateMessage. 4291 */ 4292 SECStatus 4293 ssl3_AppendHandshakeHeaderAndStashSeqNum(sslSocket *ss, SSLHandshakeType t, PRUint32 length, PRUint64 *sendMessageSeqOut) 4294 { 4295 PORT_Assert(t != ssl_hs_client_hello); 4296 SECStatus rv; 4297 4298 /* If we already have a message in place, we need to enqueue it. 4299 * This empties the buffer. This is a convenient place to call 4300 * dtls_StageHandshakeMessage to mark the message boundary. 4301 */ 4302 if (IS_DTLS(ss)) { 4303 rv = dtls_StageHandshakeMessage(ss); 4304 if (rv != SECSuccess) { 4305 return rv; 4306 } 4307 } 4308 4309 SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s", 4310 SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); 4311 4312 rv = ssl3_AppendHandshakeNumber(ss, t, 1); 4313 if (rv != SECSuccess) { 4314 return rv; /* error code set by AppendHandshake, if applicable. */ 4315 } 4316 rv = ssl3_AppendHandshakeNumber(ss, length, 3); 4317 if (rv != SECSuccess) { 4318 return rv; /* error code set by AppendHandshake, if applicable. */ 4319 } 4320 4321 if (IS_DTLS(ss)) { 4322 /* RFC 9147. 5.2. DTLS Handshake Message Format. 4323 * In DTLS 1.3, the message transcript is computed over the original TLS 4324 * 1.3-style Handshake messages without the message_seq, 4325 * fragment_offset, and fragment_length values. Note that this is a 4326 * change from DTLS 1.2 where those values were included in the transcript. */ 4327 PRBool suppressHash = ss->version == SSL_LIBRARY_VERSION_TLS_1_3 ? PR_TRUE : PR_FALSE; 4328 4329 /* Note that we make an unfragmented message here. We fragment in the 4330 * transmission code, if necessary */ 4331 rv = ssl3_AppendHandshakeNumberSuppressHash(ss, ss->ssl3.hs.sendMessageSeq, 2, suppressHash); 4332 if (rv != SECSuccess) { 4333 return rv; /* error code set by AppendHandshake, if applicable. */ 4334 } 4335 /* In case if we provide a buffer for the sequence message, 4336 we write down sendMessageSeq to the buffer. */ 4337 if (sendMessageSeqOut != NULL) { 4338 *sendMessageSeqOut = ss->ssl3.hs.sendMessageSeq; 4339 } 4340 ss->ssl3.hs.sendMessageSeq++; 4341 4342 /* 0 is the fragment offset, because it's not fragmented yet */ 4343 rv = ssl3_AppendHandshakeNumberSuppressHash(ss, 0, 3, suppressHash); 4344 if (rv != SECSuccess) { 4345 return rv; /* error code set by AppendHandshake, if applicable. */ 4346 } 4347 4348 /* Fragment length -- set to the packet length because not fragmented */ 4349 rv = ssl3_AppendHandshakeNumberSuppressHash(ss, length, 3, suppressHash); 4350 if (rv != SECSuccess) { 4351 return rv; /* error code set by AppendHandshake, if applicable. */ 4352 } 4353 } 4354 4355 return rv; /* error code set by AppendHandshake, if applicable. */ 4356 } 4357 4358 /* The function calls the ssl3_AppendHandshakeHeaderAndStashSeqNum implemented above. 4359 As in the majority of the cases we do not need the last parameter, 4360 we separate out this function. */ 4361 SECStatus 4362 ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length) 4363 { 4364 return ssl3_AppendHandshakeHeaderAndStashSeqNum(ss, t, length, NULL); 4365 } 4366 4367 /************************************************************************** 4368 * Consume Handshake functions. 4369 * 4370 * All data used in these functions is protected by two locks, 4371 * the RecvBufLock and the SSL3HandshakeLock 4372 **************************************************************************/ 4373 4374 /* Read up the next "bytes" number of bytes from the (decrypted) input 4375 * stream "b" (which is *length bytes long). Copy them into buffer "v". 4376 * Reduces *length by bytes. Advances *b by bytes. 4377 * 4378 * If this function returns SECFailure, it has already sent an alert, 4379 * and has set a generic error code. The caller should probably 4380 * override the generic error code by setting another. 4381 */ 4382 SECStatus 4383 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b, 4384 PRUint32 *length) 4385 { 4386 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 4387 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 4388 4389 if ((PRUint32)bytes > *length) { 4390 return ssl3_DecodeError(ss); 4391 } 4392 PORT_Memcpy(v, *b, bytes); 4393 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); 4394 *b += bytes; 4395 *length -= bytes; 4396 return SECSuccess; 4397 } 4398 4399 /* Read up the next "bytes" number of bytes from the (decrypted) input 4400 * stream "b" (which is *length bytes long), and interpret them as an 4401 * integer in network byte order. Sets *num to the received value. 4402 * Reduces *length by bytes. Advances *b by bytes. 4403 * 4404 * On error, an alert has been sent, and a generic error code has been set. 4405 */ 4406 SECStatus 4407 ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes, 4408 PRUint8 **b, PRUint32 *length) 4409 { 4410 PRUint8 *buf = *b; 4411 PRUint32 i; 4412 4413 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 4414 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 4415 4416 *num = 0; 4417 if (bytes > sizeof(*num)) { 4418 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 4419 return SECFailure; 4420 } 4421 4422 if (bytes > *length) { 4423 return ssl3_DecodeError(ss); 4424 } 4425 PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); 4426 4427 for (i = 0; i < bytes; i++) { 4428 *num = (*num << 8) + buf[i]; 4429 } 4430 *b += bytes; 4431 *length -= bytes; 4432 return SECSuccess; 4433 } 4434 4435 SECStatus 4436 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes, 4437 PRUint8 **b, PRUint32 *length) 4438 { 4439 PRUint64 num64; 4440 SECStatus rv; 4441 4442 PORT_Assert(bytes <= sizeof(*num)); 4443 if (bytes > sizeof(*num)) { 4444 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 4445 return SECFailure; 4446 } 4447 rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length); 4448 if (rv != SECSuccess) { 4449 return SECFailure; 4450 } 4451 *num = num64 & 0xffffffff; 4452 return SECSuccess; 4453 } 4454 4455 /* Read in two values from the incoming decrypted byte stream "b", which is 4456 * *length bytes long. The first value is a number whose size is "bytes" 4457 * bytes long. The second value is a byte-string whose size is the value 4458 * of the first number received. The latter byte-string, and its length, 4459 * is returned in the SECItem i. 4460 * 4461 * Returns SECFailure (-1) on failure. 4462 * On error, an alert has been sent, and a generic error code has been set. 4463 * 4464 * RADICAL CHANGE for NSS 3.11. All callers of this function make copies 4465 * of the data returned in the SECItem *i, so making a copy of it here 4466 * is simply wasteful. So, This function now just sets SECItem *i to 4467 * point to the values in the buffer **b. 4468 */ 4469 SECStatus 4470 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes, 4471 PRUint8 **b, PRUint32 *length) 4472 { 4473 PRUint32 count; 4474 SECStatus rv; 4475 4476 PORT_Assert(bytes <= 3); 4477 i->len = 0; 4478 i->data = NULL; 4479 i->type = siBuffer; 4480 rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length); 4481 if (rv != SECSuccess) { 4482 return SECFailure; 4483 } 4484 if (count > 0) { 4485 if (count > *length) { 4486 return ssl3_DecodeError(ss); 4487 } 4488 i->data = *b; 4489 i->len = count; 4490 *b += count; 4491 *length -= count; 4492 } 4493 return SECSuccess; 4494 } 4495 4496 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value. 4497 * If the hash is not recognised, SEC_OID_UNKNOWN is returned. 4498 * 4499 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 4500 SECOidTag 4501 ssl3_HashTypeToOID(SSLHashType hashType) 4502 { 4503 switch (hashType) { 4504 case ssl_hash_sha1: 4505 return SEC_OID_SHA1; 4506 case ssl_hash_sha256: 4507 return SEC_OID_SHA256; 4508 case ssl_hash_sha384: 4509 return SEC_OID_SHA384; 4510 case ssl_hash_sha512: 4511 return SEC_OID_SHA512; 4512 default: 4513 break; 4514 } 4515 return SEC_OID_UNKNOWN; 4516 } 4517 4518 SECOidTag 4519 ssl3_AuthTypeToOID(SSLAuthType authType) 4520 { 4521 switch (authType) { 4522 case ssl_auth_rsa_sign: 4523 return SEC_OID_PKCS1_RSA_ENCRYPTION; 4524 case ssl_auth_rsa_pss: 4525 return SEC_OID_PKCS1_RSA_PSS_SIGNATURE; 4526 case ssl_auth_ecdsa: 4527 return SEC_OID_ANSIX962_EC_PUBLIC_KEY; 4528 case ssl_auth_dsa: 4529 return SEC_OID_ANSIX9_DSA_SIGNATURE; 4530 default: 4531 break; 4532 } 4533 /* shouldn't ever get there */ 4534 PORT_Assert(0); 4535 return SEC_OID_UNKNOWN; 4536 } 4537 4538 SSLHashType 4539 ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme) 4540 { 4541 switch (scheme) { 4542 case ssl_sig_rsa_pkcs1_sha1: 4543 case ssl_sig_dsa_sha1: 4544 case ssl_sig_ecdsa_sha1: 4545 return ssl_hash_sha1; 4546 case ssl_sig_rsa_pkcs1_sha256: 4547 case ssl_sig_ecdsa_secp256r1_sha256: 4548 case ssl_sig_rsa_pss_rsae_sha256: 4549 case ssl_sig_rsa_pss_pss_sha256: 4550 case ssl_sig_dsa_sha256: 4551 return ssl_hash_sha256; 4552 case ssl_sig_rsa_pkcs1_sha384: 4553 case ssl_sig_ecdsa_secp384r1_sha384: 4554 case ssl_sig_rsa_pss_rsae_sha384: 4555 case ssl_sig_rsa_pss_pss_sha384: 4556 case ssl_sig_dsa_sha384: 4557 return ssl_hash_sha384; 4558 case ssl_sig_rsa_pkcs1_sha512: 4559 case ssl_sig_ecdsa_secp521r1_sha512: 4560 case ssl_sig_rsa_pss_rsae_sha512: 4561 case ssl_sig_rsa_pss_pss_sha512: 4562 case ssl_sig_dsa_sha512: 4563 return ssl_hash_sha512; 4564 case ssl_sig_rsa_pkcs1_sha1md5: 4565 return ssl_hash_none; /* Special for TLS 1.0/1.1. */ 4566 case ssl_sig_none: 4567 case ssl_sig_ed25519: 4568 case ssl_sig_ed448: 4569 break; 4570 } 4571 PORT_Assert(0); 4572 return ssl_hash_none; 4573 } 4574 4575 static PRBool 4576 ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid) 4577 { 4578 SECOidTag authOid = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme)); 4579 4580 if (spkiOid == authOid) { 4581 return PR_TRUE; 4582 } 4583 if ((authOid == SEC_OID_PKCS1_RSA_ENCRYPTION) && 4584 (spkiOid == SEC_OID_X500_RSA_ENCRYPTION)) { 4585 return PR_TRUE; 4586 } 4587 return PR_FALSE; 4588 } 4589 4590 /* Validate that the signature scheme works for the given key type. */ 4591 PRBool 4592 ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid, 4593 PRBool isTls13) 4594 { 4595 if (!ssl_IsSupportedSignatureScheme(scheme)) { 4596 return PR_FALSE; 4597 } 4598 /* if we are purposefully passed SEC_OID_UNKNOWN, it means 4599 * we not checking the scheme against a potential key, so skip 4600 * the call */ 4601 if ((spkiOid != SEC_OID_UNKNOWN) && 4602 !ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) { 4603 return PR_FALSE; 4604 } 4605 if (isTls13) { 4606 if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) { 4607 return PR_FALSE; 4608 } 4609 if (ssl_IsRsaPkcs1SignatureScheme(scheme)) { 4610 return PR_FALSE; 4611 } 4612 if (ssl_IsDsaSignatureScheme(scheme)) { 4613 return PR_FALSE; 4614 } 4615 /* With TLS 1.3, EC keys should have been selected based on calling 4616 * ssl_SignatureSchemeFromSpki(), reject them otherwise. */ 4617 return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY; 4618 } 4619 return PR_TRUE; 4620 } 4621 4622 static SECStatus 4623 ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo *spki, 4624 SSLSignatureScheme *scheme) 4625 { 4626 SECKEYRSAPSSParams pssParam = { 0 }; 4627 PORTCheapArenaPool arena; 4628 SECStatus rv; 4629 4630 /* The key doesn't have parameters, boo. */ 4631 if (!spki->algorithm.parameters.len) { 4632 *scheme = ssl_sig_none; 4633 return SECSuccess; 4634 } 4635 4636 PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE); 4637 rv = SEC_QuickDERDecodeItem(&arena.arena, &pssParam, 4638 SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate), 4639 &spki->algorithm.parameters); 4640 if (rv != SECSuccess) { 4641 goto loser; 4642 } 4643 /* Not having hashAlg means SHA-1 and we don't accept that. */ 4644 if (!pssParam.hashAlg) { 4645 goto loser; 4646 } 4647 switch (SECOID_GetAlgorithmTag(pssParam.hashAlg)) { 4648 case SEC_OID_SHA256: 4649 *scheme = ssl_sig_rsa_pss_pss_sha256; 4650 break; 4651 case SEC_OID_SHA384: 4652 *scheme = ssl_sig_rsa_pss_pss_sha384; 4653 break; 4654 case SEC_OID_SHA512: 4655 *scheme = ssl_sig_rsa_pss_pss_sha512; 4656 break; 4657 default: 4658 goto loser; 4659 } 4660 4661 PORT_DestroyCheapArena(&arena); 4662 return SECSuccess; 4663 4664 loser: 4665 PORT_DestroyCheapArena(&arena); 4666 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); 4667 return SECFailure; 4668 } 4669 4670 static SECStatus 4671 ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo *spki, 4672 SSLSignatureScheme *scheme) 4673 { 4674 const sslNamedGroupDef *group; 4675 SECKEYPublicKey *key; 4676 4677 key = SECKEY_ExtractPublicKey(spki); 4678 if (!key) { 4679 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); 4680 return SECFailure; 4681 } 4682 group = ssl_ECPubKey2NamedGroup(key); 4683 SECKEY_DestroyPublicKey(key); 4684 if (!group) { 4685 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); 4686 return SECFailure; 4687 } 4688 switch (group->name) { 4689 case ssl_grp_ec_secp256r1: 4690 *scheme = ssl_sig_ecdsa_secp256r1_sha256; 4691 return SECSuccess; 4692 case ssl_grp_ec_secp384r1: 4693 *scheme = ssl_sig_ecdsa_secp384r1_sha384; 4694 return SECSuccess; 4695 case ssl_grp_ec_secp521r1: 4696 *scheme = ssl_sig_ecdsa_secp521r1_sha512; 4697 return SECSuccess; 4698 default: 4699 break; 4700 } 4701 PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); 4702 return SECFailure; 4703 } 4704 4705 /* Newer signature schemes are designed so that a single SPKI can be used with 4706 * that scheme. This determines that scheme from the SPKI. If the SPKI doesn't 4707 * have a single scheme, |*scheme| is set to ssl_sig_none. */ 4708 SECStatus 4709 ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki, 4710 PRBool isTls13, SSLSignatureScheme *scheme) 4711 { 4712 SECOidTag spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm); 4713 4714 if (spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) { 4715 return ssl_SignatureSchemeFromPssSpki(spki, scheme); 4716 } 4717 4718 /* Only do this lookup for TLS 1.3, where the scheme can be determined from 4719 * the SPKI alone because the ECDSA key size determines the hash. Earlier 4720 * TLS versions allow the same EC key to be used with different hashes. */ 4721 if (isTls13 && spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) { 4722 return ssl_SignatureSchemeFromEcSpki(spki, scheme); 4723 } 4724 4725 *scheme = ssl_sig_none; 4726 return SECSuccess; 4727 } 4728 4729 /* Check that a signature scheme is enabled by configuration. */ 4730 PRBool 4731 ssl_SignatureSchemeEnabled(const sslSocket *ss, SSLSignatureScheme scheme) 4732 { 4733 unsigned int i; 4734 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 4735 if (scheme == ss->ssl3.signatureSchemes[i]) { 4736 return PR_TRUE; 4737 } 4738 } 4739 return PR_FALSE; 4740 } 4741 4742 static PRBool 4743 ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid) 4744 { 4745 switch (spkiOid) { 4746 case SEC_OID_X500_RSA_ENCRYPTION: 4747 case SEC_OID_PKCS1_RSA_ENCRYPTION: 4748 case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: 4749 return keaDef->signKeyType == rsaKey; 4750 case SEC_OID_ANSIX9_DSA_SIGNATURE: 4751 return keaDef->signKeyType == dsaKey; 4752 case SEC_OID_ANSIX962_EC_PUBLIC_KEY: 4753 return keaDef->signKeyType == ecKey; 4754 default: 4755 break; 4756 } 4757 return PR_FALSE; 4758 } 4759 4760 /* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm 4761 * identifier in |scheme| is consistent with the public key in |spki|. It also 4762 * checks the hash algorithm against the configured signature algorithms. If 4763 * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is 4764 * called and SECFailure is returned. */ 4765 SECStatus 4766 ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme, 4767 CERTSubjectPublicKeyInfo *spki) 4768 { 4769 SSLSignatureScheme spkiScheme; 4770 PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3; 4771 SECOidTag spkiOid; 4772 SECStatus rv; 4773 4774 rv = ssl_SignatureSchemeFromSpki(spki, isTLS13, &spkiScheme); 4775 if (rv != SECSuccess) { 4776 return SECFailure; 4777 } 4778 if (spkiScheme != ssl_sig_none) { 4779 /* The SPKI in the certificate can only be used for a single scheme. */ 4780 if (spkiScheme != scheme || 4781 !ssl_SignatureSchemeEnabled(ss, scheme)) { 4782 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); 4783 return SECFailure; 4784 } 4785 return SECSuccess; 4786 } 4787 4788 spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm); 4789 4790 /* If we're a client, check that the signature algorithm matches the signing 4791 * key type of the cipher suite. */ 4792 if (!isTLS13 && !ss->sec.isServer) { 4793 if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) { 4794 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); 4795 return SECFailure; 4796 } 4797 } 4798 4799 /* Verify that the signature scheme matches the signing key. */ 4800 if ((spkiOid == SEC_OID_UNKNOWN) || 4801 !ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) { 4802 PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); 4803 return SECFailure; 4804 } 4805 4806 if (!ssl_SignatureSchemeEnabled(ss, scheme)) { 4807 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 4808 return SECFailure; 4809 } 4810 4811 return SECSuccess; 4812 } 4813 4814 PRBool 4815 ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme) 4816 { 4817 switch (scheme) { 4818 case ssl_sig_rsa_pkcs1_sha1: 4819 case ssl_sig_rsa_pkcs1_sha256: 4820 case ssl_sig_rsa_pkcs1_sha384: 4821 case ssl_sig_rsa_pkcs1_sha512: 4822 case ssl_sig_rsa_pss_rsae_sha256: 4823 case ssl_sig_rsa_pss_rsae_sha384: 4824 case ssl_sig_rsa_pss_rsae_sha512: 4825 case ssl_sig_rsa_pss_pss_sha256: 4826 case ssl_sig_rsa_pss_pss_sha384: 4827 case ssl_sig_rsa_pss_pss_sha512: 4828 case ssl_sig_ecdsa_secp256r1_sha256: 4829 case ssl_sig_ecdsa_secp384r1_sha384: 4830 case ssl_sig_ecdsa_secp521r1_sha512: 4831 case ssl_sig_dsa_sha1: 4832 case ssl_sig_dsa_sha256: 4833 case ssl_sig_dsa_sha384: 4834 case ssl_sig_dsa_sha512: 4835 case ssl_sig_ecdsa_sha1: 4836 return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy); 4837 break; 4838 4839 case ssl_sig_rsa_pkcs1_sha1md5: 4840 case ssl_sig_none: 4841 case ssl_sig_ed25519: 4842 case ssl_sig_ed448: 4843 return PR_FALSE; 4844 } 4845 return PR_FALSE; 4846 } 4847 4848 PRBool 4849 ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme) 4850 { 4851 switch (scheme) { 4852 case ssl_sig_rsa_pss_rsae_sha256: 4853 case ssl_sig_rsa_pss_rsae_sha384: 4854 case ssl_sig_rsa_pss_rsae_sha512: 4855 case ssl_sig_rsa_pss_pss_sha256: 4856 case ssl_sig_rsa_pss_pss_sha384: 4857 case ssl_sig_rsa_pss_pss_sha512: 4858 return PR_TRUE; 4859 4860 default: 4861 return PR_FALSE; 4862 } 4863 return PR_FALSE; 4864 } 4865 4866 PRBool 4867 ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme) 4868 { 4869 switch (scheme) { 4870 case ssl_sig_rsa_pss_rsae_sha256: 4871 case ssl_sig_rsa_pss_rsae_sha384: 4872 case ssl_sig_rsa_pss_rsae_sha512: 4873 return PR_TRUE; 4874 4875 default: 4876 return PR_FALSE; 4877 } 4878 return PR_FALSE; 4879 } 4880 4881 PRBool 4882 ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme) 4883 { 4884 switch (scheme) { 4885 case ssl_sig_rsa_pkcs1_sha256: 4886 case ssl_sig_rsa_pkcs1_sha384: 4887 case ssl_sig_rsa_pkcs1_sha512: 4888 case ssl_sig_rsa_pkcs1_sha1: 4889 return PR_TRUE; 4890 4891 default: 4892 return PR_FALSE; 4893 } 4894 return PR_FALSE; 4895 } 4896 4897 PRBool 4898 ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme) 4899 { 4900 switch (scheme) { 4901 case ssl_sig_dsa_sha256: 4902 case ssl_sig_dsa_sha384: 4903 case ssl_sig_dsa_sha512: 4904 case ssl_sig_dsa_sha1: 4905 return PR_TRUE; 4906 4907 default: 4908 return PR_FALSE; 4909 } 4910 return PR_FALSE; 4911 } 4912 4913 SSLAuthType 4914 ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme) 4915 { 4916 switch (scheme) { 4917 case ssl_sig_rsa_pkcs1_sha1: 4918 case ssl_sig_rsa_pkcs1_sha1md5: 4919 case ssl_sig_rsa_pkcs1_sha256: 4920 case ssl_sig_rsa_pkcs1_sha384: 4921 case ssl_sig_rsa_pkcs1_sha512: 4922 /* We report based on the key type for PSS signatures. */ 4923 case ssl_sig_rsa_pss_rsae_sha256: 4924 case ssl_sig_rsa_pss_rsae_sha384: 4925 case ssl_sig_rsa_pss_rsae_sha512: 4926 return ssl_auth_rsa_sign; 4927 case ssl_sig_rsa_pss_pss_sha256: 4928 case ssl_sig_rsa_pss_pss_sha384: 4929 case ssl_sig_rsa_pss_pss_sha512: 4930 return ssl_auth_rsa_pss; 4931 case ssl_sig_ecdsa_secp256r1_sha256: 4932 case ssl_sig_ecdsa_secp384r1_sha384: 4933 case ssl_sig_ecdsa_secp521r1_sha512: 4934 case ssl_sig_ecdsa_sha1: 4935 return ssl_auth_ecdsa; 4936 case ssl_sig_dsa_sha1: 4937 case ssl_sig_dsa_sha256: 4938 case ssl_sig_dsa_sha384: 4939 case ssl_sig_dsa_sha512: 4940 return ssl_auth_dsa; 4941 4942 default: 4943 PORT_Assert(0); 4944 } 4945 return ssl_auth_null; 4946 } 4947 4948 /* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly 4949 * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value 4950 * into |out|. |b| and |length| are updated accordingly. 4951 * 4952 * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 4953 SECStatus 4954 ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b, 4955 PRUint32 *length, SSLSignatureScheme *out) 4956 { 4957 PRUint32 tmp; 4958 SECStatus rv; 4959 4960 rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length); 4961 if (rv != SECSuccess) { 4962 return SECFailure; /* Alert sent, Error code set already. */ 4963 } 4964 if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) { 4965 SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 4966 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 4967 return SECFailure; 4968 } 4969 *out = (SSLSignatureScheme)tmp; 4970 return SECSuccess; 4971 } 4972 4973 /************************************************************************** 4974 * end of Consume Handshake functions. 4975 **************************************************************************/ 4976 4977 static SECStatus 4978 ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len, 4979 SSLHashType hashAlg, SSL3Hashes *hashes) 4980 { 4981 SECStatus rv = SECFailure; 4982 PK11Context *hashContext = PK11_CreateDigestContext( 4983 ssl3_HashTypeToOID(hashAlg)); 4984 4985 if (!hashContext) { 4986 return rv; 4987 } 4988 rv = PK11_DigestBegin(hashContext); 4989 if (rv == SECSuccess) { 4990 rv = PK11_DigestOp(hashContext, buf, len); 4991 } 4992 if (rv == SECSuccess) { 4993 rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len, 4994 sizeof(hashes->u.raw)); 4995 } 4996 if (rv == SECSuccess) { 4997 hashes->hashAlg = hashAlg; 4998 } 4999 PK11_DestroyContext(hashContext, PR_TRUE); 5000 return rv; 5001 } 5002 5003 /* Extract the hashes of handshake messages to this point. 5004 * Called from ssl3_SendCertificateVerify 5005 * ssl3_SendFinished 5006 * ssl3_HandleHandshakeMessage 5007 * 5008 * Caller must hold the SSL3HandshakeLock. 5009 * Caller must hold a read or write lock on the Spec R/W lock. 5010 * (There is presently no way to assert on a Read lock.) 5011 */ 5012 SECStatus 5013 ssl3_ComputeHandshakeHashes(sslSocket *ss, 5014 ssl3CipherSpec *spec, /* uses ->master_secret */ 5015 SSL3Hashes *hashes, /* output goes here. */ 5016 PRUint32 sender) 5017 { 5018 SECStatus rv = SECSuccess; 5019 PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); 5020 unsigned int outLength; 5021 PRUint8 md5_inner[MAX_MAC_LENGTH]; 5022 PRUint8 sha_inner[MAX_MAC_LENGTH]; 5023 5024 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 5025 if (ss->ssl3.hs.hashType == handshake_hash_unknown) { 5026 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 5027 return SECFailure; 5028 } 5029 5030 hashes->hashAlg = ssl_hash_none; 5031 5032 if (ss->ssl3.hs.hashType == handshake_hash_single) { 5033 PK11Context *h; 5034 unsigned int stateLen; 5035 unsigned char stackBuf[1024]; 5036 unsigned char *stateBuf = NULL; 5037 5038 h = ss->ssl3.hs.sha; 5039 stateBuf = PK11_SaveContextAlloc(h, stackBuf, 5040 sizeof(stackBuf), &stateLen); 5041 if (stateBuf == NULL) { 5042 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 5043 rv = SECFailure; 5044 goto tls12_loser; 5045 } 5046 rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, 5047 sizeof(hashes->u.raw)); 5048 if (rv != SECSuccess) { 5049 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 5050 rv = SECFailure; 5051 goto tls12_loser; 5052 } 5053 5054 hashes->hashAlg = ssl3_GetSuitePrfHash(ss); 5055 5056 tls12_loser: 5057 if (stateBuf) { 5058 if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { 5059 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 5060 rv = SECFailure; 5061 } 5062 if (stateBuf != stackBuf) { 5063 PORT_ZFree(stateBuf, stateLen); 5064 } 5065 } 5066 } else if (ss->ssl3.hs.hashType == handshake_hash_record) { 5067 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf, 5068 ss->ssl3.hs.messages.len, 5069 ssl3_GetSuitePrfHash(ss), 5070 hashes); 5071 } else { 5072 PK11Context *md5; 5073 PK11Context *sha = NULL; 5074 unsigned char *md5StateBuf = NULL; 5075 unsigned char *shaStateBuf = NULL; 5076 unsigned int md5StateLen, shaStateLen; 5077 unsigned char md5StackBuf[256]; 5078 unsigned char shaStackBuf[512]; 5079 const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size; 5080 const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size; 5081 5082 md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, 5083 sizeof md5StackBuf, &md5StateLen); 5084 if (md5StateBuf == NULL) { 5085 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5086 rv = SECFailure; 5087 goto loser; 5088 } 5089 md5 = ss->ssl3.hs.md5; 5090 5091 shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, 5092 sizeof shaStackBuf, &shaStateLen); 5093 if (shaStateBuf == NULL) { 5094 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5095 rv = SECFailure; 5096 goto loser; 5097 } 5098 sha = ss->ssl3.hs.sha; 5099 5100 if (!isTLS) { 5101 /* compute hashes for SSL3. */ 5102 unsigned char s[4]; 5103 5104 if (!spec->masterSecret) { 5105 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 5106 rv = SECFailure; 5107 goto loser; 5108 } 5109 5110 s[0] = (unsigned char)(sender >> 24); 5111 s[1] = (unsigned char)(sender >> 16); 5112 s[2] = (unsigned char)(sender >> 8); 5113 s[3] = (unsigned char)sender; 5114 5115 if (sender != 0) { 5116 rv |= PK11_DigestOp(md5, s, 4); 5117 PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); 5118 } 5119 5120 PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad)); 5121 5122 rv |= PK11_DigestKey(md5, spec->masterSecret); 5123 rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad); 5124 rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); 5125 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); 5126 if (rv != SECSuccess) { 5127 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5128 rv = SECFailure; 5129 goto loser; 5130 } 5131 5132 PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); 5133 5134 if (sender != 0) { 5135 rv |= PK11_DigestOp(sha, s, 4); 5136 PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); 5137 } 5138 5139 PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad)); 5140 5141 rv |= PK11_DigestKey(sha, spec->masterSecret); 5142 rv |= PK11_DigestOp(sha, mac_pad_1, shaPad); 5143 rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); 5144 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); 5145 if (rv != SECSuccess) { 5146 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5147 rv = SECFailure; 5148 goto loser; 5149 } 5150 5151 PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); 5152 5153 PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad)); 5154 PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); 5155 5156 rv |= PK11_DigestBegin(md5); 5157 rv |= PK11_DigestKey(md5, spec->masterSecret); 5158 rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad); 5159 rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); 5160 } 5161 rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); 5162 PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); 5163 if (rv != SECSuccess) { 5164 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5165 rv = SECFailure; 5166 goto loser; 5167 } 5168 5169 PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); 5170 5171 if (!isTLS) { 5172 PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad)); 5173 PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); 5174 5175 rv |= PK11_DigestBegin(sha); 5176 rv |= PK11_DigestKey(sha, spec->masterSecret); 5177 rv |= PK11_DigestOp(sha, mac_pad_2, shaPad); 5178 rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); 5179 } 5180 rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); 5181 PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); 5182 if (rv != SECSuccess) { 5183 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5184 rv = SECFailure; 5185 goto loser; 5186 } 5187 5188 PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); 5189 5190 hashes->len = MD5_LENGTH + SHA1_LENGTH; 5191 5192 loser: 5193 if (md5StateBuf) { 5194 if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) != 5195 SECSuccess) { 5196 ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 5197 rv = SECFailure; 5198 } 5199 if (md5StateBuf != md5StackBuf) { 5200 PORT_ZFree(md5StateBuf, md5StateLen); 5201 } 5202 } 5203 if (shaStateBuf) { 5204 if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) != 5205 SECSuccess) { 5206 ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 5207 rv = SECFailure; 5208 } 5209 if (shaStateBuf != shaStackBuf) { 5210 PORT_ZFree(shaStateBuf, shaStateLen); 5211 } 5212 } 5213 } 5214 return rv; 5215 } 5216 5217 /************************************************************************** 5218 * end of Handshake Hash functions. 5219 * Begin Send and Handle functions for handshakes. 5220 **************************************************************************/ 5221 5222 #ifdef TRACE 5223 #define CHTYPE(t) \ 5224 case client_hello_##t: \ 5225 return #t; 5226 5227 static const char * 5228 ssl_ClientHelloTypeName(sslClientHelloType type) 5229 { 5230 switch (type) { 5231 CHTYPE(initial); 5232 CHTYPE(retry); 5233 CHTYPE(retransmit); /* DTLS only */ 5234 CHTYPE(renegotiation); /* TLS <= 1.2 only */ 5235 } 5236 PORT_Assert(0); 5237 return NULL; 5238 } 5239 #undef CHTYPE 5240 #endif 5241 5242 PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH); 5243 static void 5244 ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf) 5245 { 5246 PRUint8 x = 0x5a; 5247 int i; 5248 for (i = 0; i < SSL3_SESSIONID_BYTES; ++i) { 5249 x += ss->ssl3.hs.client_random[i]; 5250 buf[i] = x; 5251 } 5252 } 5253 5254 /* Set the version fields of the cipher spec for a ClientHello. */ 5255 static void 5256 ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec) 5257 { 5258 ssl_GetSpecWriteLock(ss); 5259 PORT_Assert(spec->cipherDef->cipher == cipher_null); 5260 /* This is - a best guess - but it doesn't matter here. */ 5261 spec->version = ss->vrange.max; 5262 if (IS_DTLS(ss)) { 5263 spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE; 5264 } else { 5265 /* For new connections, cap the record layer version number of TLS 5266 * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem 5267 * to use F5 BIG-IP) ignore ClientHello.client_version and use the 5268 * record layer version number (TLSPlaintext.version) instead when 5269 * negotiating protocol versions. In addition, if the record layer 5270 * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these 5271 * servers reset the TCP connections. Lastly, some F5 BIG-IP servers 5272 * hang if a record containing a ClientHello has a version greater than 5273 * { 3, 1 } and a length greater than 255. Set this flag to work around 5274 * such servers. 5275 * 5276 * The final version is set when a version is negotiated. 5277 */ 5278 spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, 5279 ss->vrange.max); 5280 } 5281 ssl_ReleaseSpecWriteLock(ss); 5282 } 5283 5284 SECStatus 5285 ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions) 5286 { 5287 SECStatus rv; 5288 unsigned int msgLen = preamble->len; 5289 msgLen += extensions->len ? (2 + extensions->len) : 0; 5290 unsigned int headerLen = IS_DTLS(ss) ? 12 : 4; 5291 5292 /* Record the message length. */ 5293 rv = sslBuffer_InsertNumber(preamble, 1, msgLen - headerLen, 3); 5294 if (rv != SECSuccess) { 5295 return SECFailure; /* code set */ 5296 } 5297 if (IS_DTLS(ss)) { 5298 /* Record the (unfragmented) fragment length. */ 5299 unsigned int offset = 1 /* ch */ + 3 /* len */ + 5300 2 /* seq */ + 3 /* fragment offset */; 5301 rv = sslBuffer_InsertNumber(preamble, offset, msgLen - headerLen, 3); 5302 if (rv != SECSuccess) { 5303 return SECFailure; /* code set */ 5304 } 5305 } 5306 5307 return SECSuccess; 5308 } 5309 5310 static SECStatus 5311 ssl3_AppendCipherSuites(sslSocket *ss, PRBool fallbackSCSV, sslBuffer *buf) 5312 { 5313 SECStatus rv; 5314 unsigned int offset; 5315 unsigned int i; 5316 unsigned int saveLen; 5317 5318 rv = sslBuffer_Skip(buf, 2, &offset); 5319 if (rv != SECSuccess) { 5320 return SECFailure; 5321 } 5322 5323 if (ss->ssl3.hs.sendingSCSV) { 5324 /* Add the actual SCSV */ 5325 rv = sslBuffer_AppendNumber(buf, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, 5326 sizeof(ssl3CipherSuite)); 5327 if (rv != SECSuccess) { 5328 return SECFailure; 5329 } 5330 } 5331 if (fallbackSCSV) { 5332 rv = sslBuffer_AppendNumber(buf, TLS_FALLBACK_SCSV, 5333 sizeof(ssl3CipherSuite)); 5334 if (rv != SECSuccess) { 5335 return SECFailure; 5336 } 5337 } 5338 5339 saveLen = SSL_BUFFER_LEN(buf); 5340 /* CipherSuites are appended to Hello message here */ 5341 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 5342 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 5343 if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) { 5344 rv = sslBuffer_AppendNumber(buf, suite->cipher_suite, 5345 sizeof(ssl3CipherSuite)); 5346 if (rv != SECSuccess) { 5347 return SECFailure; 5348 } 5349 } 5350 } 5351 5352 /* GREASE CipherSuites: 5353 * A client MAY select one or more GREASE cipher suite values and advertise 5354 * them in the "cipher_suites" field [RFC8701, Section 3.1]. */ 5355 if (ss->opt.enableGrease && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) { 5356 rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_cipher], 5357 sizeof(ssl3CipherSuite)); 5358 if (rv != SECSuccess) { 5359 return SECFailure; 5360 } 5361 } 5362 5363 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange) || 5364 (SSL_BUFFER_LEN(buf) - saveLen) == 0) { 5365 PORT_SetError(SSL_ERROR_SSL_DISABLED); 5366 return SECFailure; 5367 } 5368 5369 return sslBuffer_InsertLength(buf, offset, 2); 5370 } 5371 5372 SECStatus 5373 ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid, 5374 PRBool realSid, PRUint16 version, PRBool isEchInner, 5375 const sslBuffer *extensions, sslBuffer *preamble) 5376 { 5377 SECStatus rv; 5378 sslBuffer constructed = SSL_BUFFER_EMPTY; 5379 const PRUint8 *client_random = isEchInner ? ss->ssl3.hs.client_inner_random : ss->ssl3.hs.client_random; 5380 PORT_Assert(sid); 5381 PRBool fallbackSCSV = ss->opt.enableFallbackSCSV && !isEchInner && 5382 (!realSid || version < sid->version); 5383 5384 rv = sslBuffer_AppendNumber(&constructed, ssl_hs_client_hello, 1); 5385 if (rv != SECSuccess) { 5386 goto loser; 5387 } 5388 5389 rv = sslBuffer_Skip(&constructed, 3, NULL); 5390 if (rv != SECSuccess) { 5391 goto loser; 5392 } 5393 5394 if (IS_DTLS(ss)) { 5395 /* Note that we make an unfragmented message here. We fragment in the 5396 * transmission code, if necessary */ 5397 rv = sslBuffer_AppendNumber(&constructed, ss->ssl3.hs.sendMessageSeq, 2); 5398 if (rv != SECSuccess) { 5399 goto loser; 5400 } 5401 ss->ssl3.hs.sendMessageSeq++; 5402 5403 /* 0 is the fragment offset, because it's not fragmented yet */ 5404 rv = sslBuffer_AppendNumber(&constructed, 0, 3); 5405 if (rv != SECSuccess) { 5406 goto loser; 5407 } 5408 5409 /* Fragment length -- set to the packet length because not fragmented */ 5410 rv = sslBuffer_Skip(&constructed, 3, NULL); 5411 if (rv != SECSuccess) { 5412 goto loser; 5413 } 5414 } 5415 5416 if (ss->firstHsDone) { 5417 /* The client hello version must stay unchanged to work around 5418 * the Windows SChannel bug described in ssl3_SendClientHello. */ 5419 PORT_Assert(version == ss->clientHelloVersion); 5420 } 5421 5422 ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2); 5423 if (IS_DTLS(ss)) { 5424 PRUint16 dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); 5425 rv = sslBuffer_AppendNumber(&constructed, dtlsVersion, 2); 5426 } else { 5427 rv = sslBuffer_AppendNumber(&constructed, ss->clientHelloVersion, 2); 5428 } 5429 if (rv != SECSuccess) { 5430 goto loser; 5431 } 5432 5433 rv = sslBuffer_Append(&constructed, client_random, SSL3_RANDOM_LENGTH); 5434 if (rv != SECSuccess) { 5435 goto loser; 5436 } 5437 5438 if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3 && !isEchInner) { 5439 rv = sslBuffer_AppendVariable(&constructed, sid->u.ssl3.sessionID, 5440 sid->u.ssl3.sessionIDLength, 1); 5441 } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) { 5442 /* We're faking session resumption, so rather than create new 5443 * randomness, just mix up the client random a little. */ 5444 PRUint8 buf[SSL3_SESSIONID_BYTES]; 5445 ssl_MakeFakeSid(ss, buf); 5446 rv = sslBuffer_AppendVariable(&constructed, buf, SSL3_SESSIONID_BYTES, 1); 5447 } else { 5448 rv = sslBuffer_AppendNumber(&constructed, 0, 1); 5449 } 5450 if (rv != SECSuccess) { 5451 goto loser; 5452 } 5453 5454 if (IS_DTLS(ss)) { 5455 /* This cookieLen applies to the cookie that appears in the DTLS 5456 * ClientHello, which isn't used in DTLS 1.3. */ 5457 rv = sslBuffer_AppendVariable(&constructed, ss->ssl3.hs.cookie.data, 5458 ss->ssl3.hs.helloRetry ? 0 : ss->ssl3.hs.cookie.len, 5459 1); 5460 if (rv != SECSuccess) { 5461 goto loser; 5462 } 5463 } 5464 5465 rv = ssl3_AppendCipherSuites(ss, fallbackSCSV, &constructed); 5466 if (rv != SECSuccess) { 5467 goto loser; 5468 } 5469 5470 /* Compression methods: count is always 1, null compression. */ 5471 rv = sslBuffer_AppendNumber(&constructed, 1, 1); 5472 if (rv != SECSuccess) { 5473 goto loser; 5474 } 5475 rv = sslBuffer_AppendNumber(&constructed, ssl_compression_null, 1); 5476 if (rv != SECSuccess) { 5477 goto loser; 5478 } 5479 5480 rv = ssl3_InsertChHeaderSize(ss, &constructed, extensions); 5481 if (rv != SECSuccess) { 5482 goto loser; 5483 } 5484 5485 *preamble = constructed; 5486 return SECSuccess; 5487 loser: 5488 sslBuffer_Clear(&constructed); 5489 return SECFailure; 5490 } 5491 5492 /* Called from ssl3_HandleHelloRequest(), 5493 * ssl3_RedoHandshake() 5494 * ssl_BeginClientHandshake (when resuming ssl3 session) 5495 * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) 5496 * 5497 * The |type| argument indicates what is going on here: 5498 * - client_hello_initial is set for the very first ClientHello 5499 * - client_hello_retry indicates that this is a second attempt after receiving 5500 * a HelloRetryRequest (in TLS 1.3) 5501 * - client_hello_retransmit is used in DTLS when resending 5502 * - client_hello_renegotiation is used to renegotiate (in TLS <1.3) 5503 */ 5504 SECStatus 5505 ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type) 5506 { 5507 sslSessionID *sid; 5508 SECStatus rv; 5509 PRBool isTLS = PR_FALSE; 5510 PRBool requestingResume = PR_FALSE; 5511 PRBool unlockNeeded = PR_FALSE; 5512 sslBuffer extensionBuf = SSL_BUFFER_EMPTY; 5513 PRUint16 version = ss->vrange.max; 5514 PRInt32 flags; 5515 sslBuffer chBuf = SSL_BUFFER_EMPTY; 5516 5517 SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(), 5518 ss->fd, ssl_ClientHelloTypeName(type))); 5519 5520 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 5521 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 5522 5523 /* shouldn't get here if SSL3 is disabled, but ... */ 5524 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) { 5525 PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); 5526 PORT_SetError(SSL_ERROR_SSL_DISABLED); 5527 return SECFailure; 5528 } 5529 5530 /* If we are responding to a HelloRetryRequest, don't reinitialize. We need 5531 * to maintain the handshake hashes. */ 5532 if (!ss->ssl3.hs.helloRetry) { 5533 ssl3_RestartHandshakeHashes(ss); 5534 } 5535 PORT_Assert(!ss->ssl3.hs.helloRetry || type == client_hello_retry); 5536 5537 if (type == client_hello_initial) { 5538 ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec); 5539 } 5540 /* These must be reset every handshake. */ 5541 ssl3_ResetExtensionData(&ss->xtnData, ss); 5542 ss->ssl3.hs.sendingSCSV = PR_FALSE; 5543 ss->ssl3.hs.preliminaryInfo = 0; 5544 PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit); 5545 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); 5546 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 5547 5548 /* How many suites does our PKCS11 support (regardless of policy)? */ 5549 if (ssl3_config_match_init(ss) == 0) { 5550 return SECFailure; /* ssl3_config_match_init has set error code. */ 5551 } 5552 5553 /* 5554 * During a renegotiation, ss->clientHelloVersion will be used again to 5555 * work around a Windows SChannel bug. Ensure that it is still enabled. 5556 */ 5557 if (ss->firstHsDone) { 5558 PORT_Assert(type != client_hello_initial); 5559 if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) { 5560 PORT_SetError(SSL_ERROR_SSL_DISABLED); 5561 return SECFailure; 5562 } 5563 5564 if (ss->clientHelloVersion < ss->vrange.min || 5565 ss->clientHelloVersion > ss->vrange.max) { 5566 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 5567 return SECFailure; 5568 } 5569 } 5570 5571 /* Check if we have a ss->sec.ci.sid. 5572 * Check that it's not expired. 5573 * If we have an sid and it comes from an external cache, we use it. */ 5574 if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) { 5575 PORT_Assert(!ss->sec.isServer); 5576 sid = ssl_ReferenceSID(ss->sec.ci.sid); 5577 SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello", 5578 SSL_GETPID(), ss->fd)); 5579 } else if (ss->sec.ci.sid && ss->statelessResume && type == client_hello_retry) { 5580 /* If we are sending a second ClientHello, reuse the same SID 5581 * as the original one. */ 5582 sid = ssl_ReferenceSID(ss->sec.ci.sid); 5583 } else if (!ss->opt.noCache) { 5584 /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup 5585 * handles expired entries and other details. 5586 * XXX If we've been called from ssl_BeginClientHandshake, then 5587 * this lookup is duplicative and wasteful. 5588 */ 5589 sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer, 5590 ss->sec.ci.port, ss->peerID, ss->url); 5591 } else { 5592 sid = NULL; 5593 } 5594 5595 /* We can't resume based on a different token. If the sid exists, 5596 * make sure the token that holds the master secret still exists ... 5597 * If we previously did client-auth, make sure that the token that holds 5598 * the private key still exists, is logged in, hasn't been removed, etc. 5599 */ 5600 if (sid) { 5601 PRBool sidOK = PR_TRUE; 5602 5603 if (sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 5604 if (!tls13_ResumptionCompatible(ss, sid->u.ssl3.cipherSuite)) { 5605 sidOK = PR_FALSE; 5606 } 5607 } else { 5608 /* Check that the cipher suite we need is enabled. */ 5609 const ssl3CipherSuiteCfg *suite = 5610 ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite, 5611 ss->cipherSuites); 5612 SSLVersionRange vrange = { sid->version, sid->version }; 5613 if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) { 5614 sidOK = PR_FALSE; 5615 } 5616 5617 /* Check that no (valid) ECHConfigs are setup in combination with a 5618 * (resumable) TLS < 1.3 session id. */ 5619 if (!PR_CLIST_IS_EMPTY(&ss->echConfigs)) { 5620 /* If there are ECH configs, the client must not resume but 5621 * offer ECH. */ 5622 sidOK = PR_FALSE; 5623 } 5624 } 5625 5626 /* Check that we can recover the master secret. */ 5627 if (sidOK) { 5628 PK11SlotInfo *slot = NULL; 5629 if (sid->u.ssl3.masterValid) { 5630 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, 5631 sid->u.ssl3.masterSlotID); 5632 } 5633 if (slot == NULL) { 5634 sidOK = PR_FALSE; 5635 } else { 5636 PK11SymKey *wrapKey = NULL; 5637 if (!PK11_IsPresent(slot) || 5638 ((wrapKey = PK11_GetWrapKey(slot, 5639 sid->u.ssl3.masterWrapIndex, 5640 sid->u.ssl3.masterWrapMech, 5641 sid->u.ssl3.masterWrapSeries, 5642 ss->pkcs11PinArg)) == NULL)) { 5643 sidOK = PR_FALSE; 5644 } 5645 if (wrapKey) 5646 PK11_FreeSymKey(wrapKey); 5647 PK11_FreeSlot(slot); 5648 slot = NULL; 5649 } 5650 } 5651 /* If we previously did client-auth, make sure that the token that 5652 ** holds the private key still exists, is logged in, hasn't been 5653 ** removed, etc. 5654 */ 5655 if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { 5656 sidOK = PR_FALSE; 5657 } 5658 5659 if (sidOK) { 5660 /* Set version based on the sid. */ 5661 if (ss->firstHsDone) { 5662 /* 5663 * Windows SChannel compares the client_version inside the RSA 5664 * EncryptedPreMasterSecret of a renegotiation with the 5665 * client_version of the initial ClientHello rather than the 5666 * ClientHello in the renegotiation. To work around this bug, we 5667 * continue to use the client_version used in the initial 5668 * ClientHello when renegotiating. 5669 * 5670 * The client_version of the initial ClientHello is still 5671 * available in ss->clientHelloVersion. Ensure that 5672 * sid->version is bounded within 5673 * [ss->vrange.min, ss->clientHelloVersion], otherwise we 5674 * can't use sid. 5675 */ 5676 if (sid->version >= ss->vrange.min && 5677 sid->version <= ss->clientHelloVersion) { 5678 version = ss->clientHelloVersion; 5679 } else { 5680 sidOK = PR_FALSE; 5681 } 5682 } else { 5683 /* 5684 * Check sid->version is OK first. 5685 * Previously, we would cap the version based on sid->version, 5686 * but that prevents negotiation of a higher version if the 5687 * previous session was reduced (e.g., with version fallback) 5688 */ 5689 if (sid->version < ss->vrange.min || 5690 sid->version > ss->vrange.max) { 5691 sidOK = PR_FALSE; 5692 } 5693 } 5694 } 5695 5696 if (!sidOK) { 5697 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok); 5698 ssl_UncacheSessionID(ss); 5699 ssl_FreeSID(sid); 5700 sid = NULL; 5701 } 5702 } 5703 5704 if (sid) { 5705 requestingResume = PR_TRUE; 5706 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits); 5707 5708 PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, 5709 sid->u.ssl3.sessionIDLength)); 5710 5711 ss->ssl3.policy = sid->u.ssl3.policy; 5712 } else { 5713 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses); 5714 5715 /* 5716 * Windows SChannel compares the client_version inside the RSA 5717 * EncryptedPreMasterSecret of a renegotiation with the 5718 * client_version of the initial ClientHello rather than the 5719 * ClientHello in the renegotiation. To work around this bug, we 5720 * continue to use the client_version used in the initial 5721 * ClientHello when renegotiating. 5722 */ 5723 if (ss->firstHsDone) { 5724 version = ss->clientHelloVersion; 5725 } 5726 5727 sid = ssl3_NewSessionID(ss, PR_FALSE); 5728 if (!sid) { 5729 return SECFailure; /* memory error is set */ 5730 } 5731 /* ss->version isn't set yet, but the sid needs a sane value. */ 5732 sid->version = version; 5733 } 5734 5735 isTLS = (version > SSL_LIBRARY_VERSION_3_0); 5736 ssl_GetSpecWriteLock(ss); 5737 if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) { 5738 /* SSL records are not being MACed. */ 5739 ss->ssl3.cwSpec->version = version; 5740 } 5741 ssl_ReleaseSpecWriteLock(ss); 5742 5743 ssl_FreeSID(ss->sec.ci.sid); /* release the old sid */ 5744 ss->sec.ci.sid = sid; 5745 5746 /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV, 5747 * only if TLS is disabled. 5748 */ 5749 if (!ss->firstHsDone && !isTLS) { 5750 /* Must set this before calling Hello Extension Senders, 5751 * to suppress sending of empty RI extension. 5752 */ 5753 ss->ssl3.hs.sendingSCSV = PR_TRUE; 5754 } 5755 5756 /* When we attempt session resumption (only), we must lock the sid to 5757 * prevent races with other resumption connections that receive a 5758 * NewSessionTicket that will cause the ticket in the sid to be replaced. 5759 * Once we've copied the session ticket into our ClientHello message, it 5760 * is OK for the ticket to change, so we just need to make sure we hold 5761 * the lock across the calls to ssl_ConstructExtensions. 5762 */ 5763 if (sid->u.ssl3.lock) { 5764 unlockNeeded = PR_TRUE; 5765 PR_RWLock_Rlock(sid->u.ssl3.lock); 5766 } 5767 5768 /* Generate a new random if this is the first attempt or renegotiation. */ 5769 if (type == client_hello_initial || 5770 type == client_hello_renegotiation) { 5771 rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random); 5772 if (rv != SECSuccess) { 5773 goto loser; /* err set by GetNewRandom. */ 5774 } 5775 } 5776 5777 if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) { 5778 rv = tls13_SetupClientHello(ss, type); 5779 if (rv != SECSuccess) { 5780 goto loser; 5781 } 5782 } 5783 5784 /* Setup TLS ClientHello Extension Permutation? */ 5785 if (type == client_hello_initial && 5786 ss->vrange.max > SSL_LIBRARY_VERSION_3_0 && 5787 ss->opt.enableChXtnPermutation) { 5788 rv = tls_ClientHelloExtensionPermutationSetup(ss); 5789 if (rv != SECSuccess) { 5790 goto loser; 5791 } 5792 } 5793 5794 if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { 5795 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello); 5796 if (rv != SECSuccess) { 5797 goto loser; 5798 } 5799 } 5800 5801 if (IS_DTLS(ss)) { 5802 ssl3_DisableNonDTLSSuites(ss); 5803 } 5804 5805 rv = ssl3_CreateClientHelloPreamble(ss, sid, requestingResume, version, 5806 PR_FALSE, &extensionBuf, &chBuf); 5807 if (rv != SECSuccess) { 5808 goto loser; /* err set by ssl3_CreateClientHelloPreamble. */ 5809 } 5810 5811 if (!ss->ssl3.hs.echHpkeCtx) { 5812 if (extensionBuf.len) { 5813 rv = tls13_MaybeGreaseEch(ss, &chBuf, &extensionBuf); 5814 if (rv != SECSuccess) { 5815 goto loser; /* err set by tls13_MaybeGreaseEch. */ 5816 } 5817 rv = ssl_InsertPaddingExtension(ss, chBuf.len, &extensionBuf); 5818 if (rv != SECSuccess) { 5819 goto loser; /* err set by ssl_InsertPaddingExtension. */ 5820 } 5821 5822 rv = ssl3_InsertChHeaderSize(ss, &chBuf, &extensionBuf); 5823 if (rv != SECSuccess) { 5824 goto loser; /* err set by ssl3_InsertChHeaderSize. */ 5825 } 5826 5827 /* If we are sending a PSK binder, replace the dummy value. */ 5828 if (ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) { 5829 rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf, &chBuf); 5830 } else { 5831 rv = sslBuffer_AppendNumber(&chBuf, extensionBuf.len, 2); 5832 if (rv != SECSuccess) { 5833 goto loser; 5834 } 5835 rv = sslBuffer_AppendBuffer(&chBuf, &extensionBuf); 5836 } 5837 if (rv != SECSuccess) { 5838 goto loser; /* err set by sslBuffer_Append*. */ 5839 } 5840 } 5841 5842 /* If we already have a message in place, we need to enqueue it. 5843 * This empties the buffer. This is a convenient place to call 5844 * dtls_StageHandshakeMessage to mark the message boundary. */ 5845 if (IS_DTLS(ss)) { 5846 rv = dtls_StageHandshakeMessage(ss); 5847 if (rv != SECSuccess) { 5848 goto loser; 5849 } 5850 } 5851 5852 /* As here the function takes the full message and hashes it in one go, 5853 * For DTLS1.3, we skip hashing the unnecessary header fields. 5854 * See ssl3_AppendHandshakeHeader. */ 5855 if (IS_DTLS(ss) && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) { 5856 rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len); 5857 if (rv != SECSuccess) { 5858 goto loser; /* code set */ 5859 } 5860 if (!ss->firstHsDone) { 5861 PORT_Assert(type == client_hello_retransmit || 5862 ss->ssl3.hs.dtls13ClientMessageBuffer.len == 0); 5863 sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer); 5864 /* Here instead of computing the hash, we copy the data to a buffer.*/ 5865 rv = sslBuffer_Append(&ss->ssl3.hs.dtls13ClientMessageBuffer, chBuf.buf, chBuf.len); 5866 } 5867 } else { 5868 rv = ssl3_AppendHandshake(ss, chBuf.buf, chBuf.len); 5869 } 5870 5871 } else { 5872 PORT_Assert(!IS_DTLS(ss)); 5873 rv = tls13_ConstructClientHelloWithEch(ss, sid, !requestingResume, &chBuf, &extensionBuf); 5874 if (rv != SECSuccess) { 5875 goto loser; /* code set */ 5876 } 5877 rv = ssl3_UpdateDefaultHandshakeHashes(ss, chBuf.buf, chBuf.len); 5878 if (rv != SECSuccess) { 5879 goto loser; /* code set */ 5880 } 5881 5882 if (IS_DTLS(ss)) { 5883 rv = dtls_StageHandshakeMessage(ss); 5884 if (rv != SECSuccess) { 5885 goto loser; 5886 } 5887 } 5888 /* By default, all messagess are added to both the inner and 5889 * outer transcripts. For CH (or CH2 if HRR), that's problematic. */ 5890 rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len); 5891 } 5892 if (rv != SECSuccess) { 5893 goto loser; 5894 } 5895 5896 if (unlockNeeded) { 5897 /* Note: goto loser can't be used past this point. */ 5898 PR_RWLock_Unlock(sid->u.ssl3.lock); 5899 } 5900 5901 if (ss->xtnData.sentSessionTicketInClientHello) { 5902 SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes); 5903 } 5904 5905 if (ss->ssl3.hs.sendingSCSV) { 5906 /* Since we sent the SCSV, pretend we sent empty RI extension. */ 5907 TLSExtensionData *xtnData = &ss->xtnData; 5908 xtnData->advertised[xtnData->numAdvertised++] = 5909 ssl_renegotiation_info_xtn; 5910 } 5911 5912 flags = 0; 5913 rv = ssl3_FlushHandshake(ss, flags); 5914 if (rv != SECSuccess) { 5915 return rv; /* error code set by ssl3_FlushHandshake */ 5916 } 5917 5918 if (version >= SSL_LIBRARY_VERSION_TLS_1_3) { 5919 rv = tls13_MaybeDo0RTTHandshake(ss); 5920 if (rv != SECSuccess) { 5921 return SECFailure; /* error code set already. */ 5922 } 5923 } 5924 5925 ss->ssl3.hs.ws = wait_server_hello; 5926 sslBuffer_Clear(&chBuf); 5927 sslBuffer_Clear(&extensionBuf); 5928 return SECSuccess; 5929 5930 loser: 5931 if (unlockNeeded) { 5932 PR_RWLock_Unlock(sid->u.ssl3.lock); 5933 } 5934 sslBuffer_Clear(&chBuf); 5935 sslBuffer_Clear(&extensionBuf); 5936 return SECFailure; 5937 } 5938 5939 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a 5940 * complete ssl3 Hello Request. 5941 * Caller must hold Handshake and RecvBuf locks. 5942 */ 5943 static SECStatus 5944 ssl3_HandleHelloRequest(sslSocket *ss) 5945 { 5946 sslSessionID *sid = ss->sec.ci.sid; 5947 SECStatus rv; 5948 5949 SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake", 5950 SSL_GETPID(), ss->fd)); 5951 5952 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 5953 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 5954 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); 5955 5956 if (ss->ssl3.hs.ws == wait_server_hello) 5957 return SECSuccess; 5958 if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) { 5959 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 5960 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); 5961 return SECFailure; 5962 } 5963 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 5964 (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation); 5965 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 5966 return SECFailure; 5967 } 5968 5969 if (sid) { 5970 ssl_UncacheSessionID(ss); 5971 ssl_FreeSID(sid); 5972 ss->sec.ci.sid = NULL; 5973 } 5974 5975 if (IS_DTLS(ss)) { 5976 dtls_RehandshakeCleanup(ss); 5977 } 5978 5979 ssl_GetXmitBufLock(ss); 5980 rv = ssl3_SendClientHello(ss, client_hello_renegotiation); 5981 ssl_ReleaseXmitBufLock(ss); 5982 5983 return rv; 5984 } 5985 5986 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = { 5987 CKM_DES3_ECB, 5988 CKM_CAST5_ECB, 5989 CKM_DES_ECB, 5990 CKM_KEY_WRAP_LYNKS, 5991 CKM_IDEA_ECB, 5992 CKM_CAST3_ECB, 5993 CKM_CAST_ECB, 5994 CKM_RC5_ECB, 5995 CKM_RC2_ECB, 5996 CKM_CDMF_ECB, 5997 CKM_SKIPJACK_WRAP, 5998 CKM_SKIPJACK_CBC64, 5999 CKM_AES_ECB, 6000 CKM_CAMELLIA_ECB, 6001 CKM_SEED_ECB 6002 }; 6003 6004 static SECStatus 6005 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex) 6006 { 6007 unsigned int i; 6008 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { 6009 if (wrapMechanismList[i] == mech) { 6010 *wrapMechIndex = i; 6011 return SECSuccess; 6012 } 6013 } 6014 PORT_Assert(0); 6015 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6016 return SECFailure; 6017 } 6018 6019 /* Each process sharing the server session ID cache has its own array of SymKey 6020 * pointers for the symmetric wrapping keys that are used to wrap the master 6021 * secrets. There is one key for each authentication type. These Symkeys 6022 * correspond to the wrapped SymKeys kept in the server session cache. 6023 */ 6024 const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = { 6025 ssl_auth_rsa_decrypt, 6026 ssl_auth_rsa_sign, 6027 ssl_auth_rsa_pss, 6028 ssl_auth_ecdsa, 6029 ssl_auth_ecdh_rsa, 6030 ssl_auth_ecdh_ecdsa 6031 }; 6032 6033 static SECStatus 6034 ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex) 6035 { 6036 unsigned int i; 6037 for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) { 6038 if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) { 6039 *wrapKeyIndex = i; 6040 return SECSuccess; 6041 } 6042 } 6043 /* Can't assert here because we still get people using DSA certificates. */ 6044 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6045 return SECFailure; 6046 } 6047 6048 static PK11SymKey * 6049 ssl_UnwrapSymWrappingKey( 6050 SSLWrappedSymWrappingKey *pWswk, 6051 SECKEYPrivateKey *svrPrivKey, 6052 unsigned int wrapKeyIndex, 6053 CK_MECHANISM_TYPE masterWrapMech, 6054 void *pwArg) 6055 { 6056 PK11SymKey *unwrappedWrappingKey = NULL; 6057 SECItem wrappedKey; 6058 PK11SymKey *Ks; 6059 SECKEYPublicKey pubWrapKey; 6060 ECCWrappedKeyInfo *ecWrapped; 6061 6062 /* found the wrapping key on disk. */ 6063 PORT_Assert(pWswk->symWrapMechanism == masterWrapMech); 6064 PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex); 6065 if (pWswk->symWrapMechanism != masterWrapMech || 6066 pWswk->wrapKeyIndex != wrapKeyIndex) { 6067 goto loser; 6068 } 6069 wrappedKey.type = siBuffer; 6070 wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; 6071 wrappedKey.len = pWswk->wrappedSymKeyLen; 6072 PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); 6073 6074 switch (ssl_wrap_key_auth_type[wrapKeyIndex]) { 6075 6076 case ssl_auth_rsa_decrypt: 6077 case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */ 6078 unwrappedWrappingKey = 6079 PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, 6080 masterWrapMech, CKA_UNWRAP, 0); 6081 break; 6082 6083 case ssl_auth_ecdsa: 6084 case ssl_auth_ecdh_rsa: 6085 case ssl_auth_ecdh_ecdsa: 6086 /* 6087 * For ssl_auth_ecd*, we first create an EC public key based on 6088 * data stored with the wrappedSymmetricWrappingkey. Next, 6089 * we do an ECDH computation involving this public key and 6090 * the SSL server's (long-term) EC private key. The resulting 6091 * shared secret is treated the same way as Fortezza's Ks, i.e., 6092 * it is used to recover the symmetric wrapping key. 6093 * 6094 * The data in wrappedSymmetricWrappingkey is laid out as defined 6095 * in the ECCWrappedKeyInfo structure. 6096 */ 6097 ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey; 6098 6099 PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 6100 ecWrapped->wrappedKeyLen <= 6101 MAX_EC_WRAPPED_KEY_BUFLEN); 6102 6103 if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 6104 ecWrapped->wrappedKeyLen > 6105 MAX_EC_WRAPPED_KEY_BUFLEN) { 6106 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6107 goto loser; 6108 } 6109 6110 pubWrapKey.keyType = ecKey; 6111 pubWrapKey.u.ec.size = ecWrapped->size; 6112 pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; 6113 pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; 6114 pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; 6115 pubWrapKey.u.ec.publicValue.data = ecWrapped->var + 6116 ecWrapped->encodedParamLen; 6117 6118 wrappedKey.len = ecWrapped->wrappedKeyLen; 6119 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 6120 ecWrapped->pubValueLen; 6121 6122 /* Derive Ks using ECDH */ 6123 Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL, 6124 NULL, CKM_ECDH1_DERIVE, masterWrapMech, 6125 CKA_DERIVE, 0, CKD_NULL, NULL, NULL); 6126 if (Ks == NULL) { 6127 goto loser; 6128 } 6129 6130 /* Use Ks to unwrap the wrapping key */ 6131 unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, 6132 &wrappedKey, masterWrapMech, 6133 CKA_UNWRAP, 0); 6134 PK11_FreeSymKey(Ks); 6135 6136 break; 6137 6138 default: 6139 PORT_Assert(0); 6140 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6141 goto loser; 6142 } 6143 loser: 6144 return unwrappedWrappingKey; 6145 } 6146 6147 typedef struct { 6148 PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS]; 6149 } ssl3SymWrapKey; 6150 6151 static PZLock *symWrapKeysLock = NULL; 6152 static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; 6153 6154 SECStatus 6155 ssl_FreeSymWrapKeysLock(void) 6156 { 6157 if (symWrapKeysLock) { 6158 PZ_DestroyLock(symWrapKeysLock); 6159 symWrapKeysLock = NULL; 6160 return SECSuccess; 6161 } 6162 PORT_SetError(SEC_ERROR_NOT_INITIALIZED); 6163 return SECFailure; 6164 } 6165 6166 SECStatus 6167 SSL3_ShutdownServerCache(void) 6168 { 6169 int i, j; 6170 6171 if (!symWrapKeysLock) 6172 return SECSuccess; /* lock was never initialized */ 6173 PZ_Lock(symWrapKeysLock); 6174 /* get rid of all symWrapKeys */ 6175 for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { 6176 for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) { 6177 PK11SymKey **pSymWrapKey; 6178 pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; 6179 if (*pSymWrapKey) { 6180 PK11_FreeSymKey(*pSymWrapKey); 6181 *pSymWrapKey = NULL; 6182 } 6183 } 6184 } 6185 6186 PZ_Unlock(symWrapKeysLock); 6187 ssl_FreeSessionCacheLocks(); 6188 return SECSuccess; 6189 } 6190 6191 SECStatus 6192 ssl_InitSymWrapKeysLock(void) 6193 { 6194 symWrapKeysLock = PZ_NewLock(nssILockOther); 6195 return symWrapKeysLock ? SECSuccess : SECFailure; 6196 } 6197 6198 /* Try to get wrapping key for mechanism from in-memory array. 6199 * If that fails, look for one on disk. 6200 * If that fails, generate a new one, put the new one on disk, 6201 * Put the new key in the in-memory array. 6202 * 6203 * Note that this function performs some fairly inadvisable functions with 6204 * certificate private keys. ECDSA keys are used with ECDH; similarly, RSA 6205 * signing keys are used to encrypt. Bug 1248320. 6206 */ 6207 PK11SymKey * 6208 ssl3_GetWrappingKey(sslSocket *ss, 6209 PK11SlotInfo *masterSecretSlot, 6210 CK_MECHANISM_TYPE masterWrapMech, 6211 void *pwArg) 6212 { 6213 SSLAuthType authType; 6214 SECKEYPrivateKey *svrPrivKey; 6215 SECKEYPublicKey *svrPubKey = NULL; 6216 PK11SymKey *unwrappedWrappingKey = NULL; 6217 PK11SymKey **pSymWrapKey; 6218 CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; 6219 int length; 6220 unsigned int wrapMechIndex; 6221 unsigned int wrapKeyIndex; 6222 SECStatus rv; 6223 SECItem wrappedKey; 6224 SSLWrappedSymWrappingKey wswk; 6225 PK11SymKey *Ks = NULL; 6226 SECKEYPublicKey *pubWrapKey = NULL; 6227 SECKEYPrivateKey *privWrapKey = NULL; 6228 ECCWrappedKeyInfo *ecWrapped; 6229 const sslServerCert *serverCert = ss->sec.serverCert; 6230 6231 PORT_Assert(serverCert); 6232 PORT_Assert(serverCert->serverKeyPair); 6233 PORT_Assert(serverCert->serverKeyPair->privKey); 6234 PORT_Assert(serverCert->serverKeyPair->pubKey); 6235 if (!serverCert || !serverCert->serverKeyPair || 6236 !serverCert->serverKeyPair->privKey || 6237 !serverCert->serverKeyPair->pubKey) { 6238 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6239 return NULL; /* hmm */ 6240 } 6241 6242 rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex); 6243 if (rv != SECSuccess) 6244 return NULL; /* unusable wrapping key. */ 6245 6246 rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex); 6247 if (rv != SECSuccess) 6248 return NULL; /* invalid masterWrapMech. */ 6249 6250 authType = ssl_wrap_key_auth_type[wrapKeyIndex]; 6251 svrPrivKey = serverCert->serverKeyPair->privKey; 6252 pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex]; 6253 6254 ssl_InitSessionCacheLocks(PR_TRUE); 6255 6256 PZ_Lock(symWrapKeysLock); 6257 6258 unwrappedWrappingKey = *pSymWrapKey; 6259 if (unwrappedWrappingKey != NULL) { 6260 if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { 6261 unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); 6262 goto done; 6263 } 6264 /* slot series has changed, so this key is no good any more. */ 6265 PK11_FreeSymKey(unwrappedWrappingKey); 6266 *pSymWrapKey = unwrappedWrappingKey = NULL; 6267 } 6268 6269 /* Try to get wrapped SymWrapping key out of the (disk) cache. */ 6270 /* Following call fills in wswk on success. */ 6271 rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk); 6272 if (rv == SECSuccess) { 6273 /* found the wrapped sym wrapping key on disk. */ 6274 unwrappedWrappingKey = 6275 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex, 6276 masterWrapMech, pwArg); 6277 if (unwrappedWrappingKey) { 6278 goto install; 6279 } 6280 } 6281 6282 if (!masterSecretSlot) /* caller doesn't want to create a new one. */ 6283 goto loser; 6284 6285 length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech); 6286 /* Zero length means fixed key length algorithm, or error. 6287 * It's ambiguous. 6288 */ 6289 unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, 6290 length, pwArg); 6291 if (!unwrappedWrappingKey) { 6292 goto loser; 6293 } 6294 6295 /* Prepare the buffer to receive the wrappedWrappingKey, 6296 * the symmetric wrapping key wrapped using the server's pub key. 6297 */ 6298 PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ 6299 6300 svrPubKey = serverCert->serverKeyPair->pubKey; 6301 wrappedKey.type = siBuffer; 6302 wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); 6303 wrappedKey.data = wswk.wrappedSymmetricWrappingkey; 6304 6305 PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); 6306 if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) 6307 goto loser; 6308 6309 /* wrap symmetric wrapping key in server's public key. */ 6310 switch (authType) { 6311 case ssl_auth_rsa_decrypt: 6312 case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */ 6313 case ssl_auth_rsa_pss: 6314 asymWrapMechanism = CKM_RSA_PKCS; 6315 rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, 6316 unwrappedWrappingKey, &wrappedKey); 6317 break; 6318 6319 case ssl_auth_ecdsa: 6320 case ssl_auth_ecdh_rsa: 6321 case ssl_auth_ecdh_ecdsa: 6322 /* 6323 * We generate an ephemeral EC key pair. Perform an ECDH 6324 * computation involving this ephemeral EC public key and 6325 * the SSL server's (long-term) EC private key. The resulting 6326 * shared secret is treated in the same way as Fortezza's Ks, 6327 * i.e., it is used to wrap the wrapping key. To facilitate 6328 * unwrapping in ssl_UnwrapWrappingKey, we also store all 6329 * relevant info about the ephemeral EC public key in 6330 * wswk.wrappedSymmetricWrappingkey and lay it out as 6331 * described in the ECCWrappedKeyInfo structure. 6332 */ 6333 PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey); 6334 if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) { 6335 /* something is wrong in sslsecur.c if this isn't an ecKey */ 6336 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6337 rv = SECFailure; 6338 goto ec_cleanup; 6339 } 6340 6341 privWrapKey = SECKEY_CreateECPrivateKey( 6342 &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); 6343 if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { 6344 rv = SECFailure; 6345 goto ec_cleanup; 6346 } 6347 6348 /* Set the key size in bits */ 6349 if (pubWrapKey->u.ec.size == 0) { 6350 pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey); 6351 } 6352 6353 PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + 6354 pubWrapKey->u.ec.publicValue.len < 6355 MAX_EC_WRAPPED_KEY_BUFLEN); 6356 if (pubWrapKey->u.ec.DEREncodedParams.len + 6357 pubWrapKey->u.ec.publicValue.len >= 6358 MAX_EC_WRAPPED_KEY_BUFLEN) { 6359 PORT_SetError(SEC_ERROR_INVALID_KEY); 6360 rv = SECFailure; 6361 goto ec_cleanup; 6362 } 6363 6364 /* Derive Ks using ECDH */ 6365 Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, 6366 NULL, CKM_ECDH1_DERIVE, masterWrapMech, 6367 CKA_DERIVE, 0, CKD_NULL, NULL, NULL); 6368 if (Ks == NULL) { 6369 rv = SECFailure; 6370 goto ec_cleanup; 6371 } 6372 6373 ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey); 6374 ecWrapped->size = pubWrapKey->u.ec.size; 6375 ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; 6376 PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, 6377 pubWrapKey->u.ec.DEREncodedParams.len); 6378 6379 ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; 6380 PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, 6381 pubWrapKey->u.ec.publicValue.data, 6382 pubWrapKey->u.ec.publicValue.len); 6383 6384 wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - 6385 (ecWrapped->encodedParamLen + ecWrapped->pubValueLen); 6386 wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 6387 ecWrapped->pubValueLen; 6388 6389 /* wrap symmetricWrapping key with the local Ks */ 6390 rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, 6391 unwrappedWrappingKey, &wrappedKey); 6392 6393 if (rv != SECSuccess) { 6394 goto ec_cleanup; 6395 } 6396 6397 /* Write down the length of wrapped key in the buffer 6398 * wswk.wrappedSymmetricWrappingkey at the appropriate offset 6399 */ 6400 ecWrapped->wrappedKeyLen = wrappedKey.len; 6401 6402 ec_cleanup: 6403 if (privWrapKey) 6404 SECKEY_DestroyPrivateKey(privWrapKey); 6405 if (pubWrapKey) 6406 SECKEY_DestroyPublicKey(pubWrapKey); 6407 if (Ks) 6408 PK11_FreeSymKey(Ks); 6409 asymWrapMechanism = masterWrapMech; 6410 break; 6411 6412 default: 6413 rv = SECFailure; 6414 break; 6415 } 6416 6417 if (rv != SECSuccess) { 6418 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6419 goto loser; 6420 } 6421 6422 PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); 6423 6424 wswk.symWrapMechanism = masterWrapMech; 6425 wswk.asymWrapMechanism = asymWrapMechanism; 6426 wswk.wrapMechIndex = wrapMechIndex; 6427 wswk.wrapKeyIndex = wrapKeyIndex; 6428 wswk.wrappedSymKeyLen = wrappedKey.len; 6429 6430 /* put it on disk. */ 6431 /* If the wrapping key for this KEA type has already been set, 6432 * then abandon the value we just computed and 6433 * use the one we got from the disk. 6434 */ 6435 rv = ssl_SetWrappingKey(&wswk); 6436 if (rv == SECSuccess) { 6437 /* somebody beat us to it. The original contents of our wswk 6438 * has been replaced with the content on disk. Now, discard 6439 * the key we just created and unwrap this new one. 6440 */ 6441 PK11_FreeSymKey(unwrappedWrappingKey); 6442 6443 unwrappedWrappingKey = 6444 ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex, 6445 masterWrapMech, pwArg); 6446 } 6447 6448 install: 6449 if (unwrappedWrappingKey) { 6450 *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); 6451 } 6452 6453 loser: 6454 done: 6455 PZ_Unlock(symWrapKeysLock); 6456 return unwrappedWrappingKey; 6457 } 6458 6459 #ifdef NSS_ALLOW_SSLKEYLOGFILE 6460 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2| 6461 * bytes to |out|. */ 6462 static void 6463 hexEncode(char *out, const unsigned char *in, unsigned int length) 6464 { 6465 static const char hextable[] = "0123456789abcdef"; 6466 unsigned int i; 6467 6468 for (i = 0; i < length; i++) { 6469 *(out++) = hextable[in[i] >> 4]; 6470 *(out++) = hextable[in[i] & 15]; 6471 } 6472 } 6473 #endif 6474 6475 /* Called from ssl3_SendClientKeyExchange(). */ 6476 static SECStatus 6477 ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) 6478 { 6479 PK11SymKey *pms = NULL; 6480 SECStatus rv = SECFailure; 6481 SECItem enc_pms = { siBuffer, NULL, 0 }; 6482 PRBool isTLS; 6483 6484 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 6485 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 6486 6487 /* Generate the pre-master secret ... */ 6488 ssl_GetSpecWriteLock(ss); 6489 isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0); 6490 6491 pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); 6492 ssl_ReleaseSpecWriteLock(ss); 6493 if (pms == NULL) { 6494 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6495 goto loser; 6496 } 6497 6498 /* Get the wrapped (encrypted) pre-master secret, enc_pms */ 6499 unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey); 6500 enc_pms.len = (svrPubKeyBits + 7) / 8; 6501 /* Check that the RSA key isn't larger than 8k bit. */ 6502 if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS) { 6503 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 6504 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6505 goto loser; 6506 } 6507 enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len); 6508 if (enc_pms.data == NULL) { 6509 goto loser; /* err set by PORT_Alloc */ 6510 } 6511 6512 /* Wrap pre-master secret in server's public key. */ 6513 rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms); 6514 if (rv != SECSuccess) { 6515 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6516 goto loser; 6517 } 6518 6519 #ifdef TRACE 6520 if (ssl_trace >= 100) { 6521 SECStatus extractRV = PK11_ExtractKeyValue(pms); 6522 if (extractRV == SECSuccess) { 6523 SECItem *keyData = PK11_GetKeyData(pms); 6524 if (keyData && keyData->data && keyData->len) { 6525 ssl_PrintBuf(ss, "Pre-Master Secret", 6526 keyData->data, keyData->len); 6527 } 6528 } 6529 } 6530 #endif 6531 6532 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange, 6533 isTLS ? enc_pms.len + 2 6534 : enc_pms.len); 6535 if (rv != SECSuccess) { 6536 goto loser; /* err set by ssl3_AppendHandshake* */ 6537 } 6538 if (isTLS) { 6539 rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); 6540 } else { 6541 rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); 6542 } 6543 if (rv != SECSuccess) { 6544 goto loser; /* err set by ssl3_AppendHandshake* */ 6545 } 6546 6547 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE); 6548 PK11_FreeSymKey(pms); 6549 pms = NULL; 6550 6551 if (rv != SECSuccess) { 6552 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6553 goto loser; 6554 } 6555 6556 rv = SECSuccess; 6557 6558 loser: 6559 if (enc_pms.data != NULL) { 6560 PORT_Free(enc_pms.data); 6561 } 6562 if (pms != NULL) { 6563 PK11_FreeSymKey(pms); 6564 } 6565 return rv; 6566 } 6567 6568 /* DH shares need to be padded to the size of their prime. Some implementations 6569 * require this. TLS 1.3 also requires this. */ 6570 SECStatus 6571 ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey, 6572 PRBool appendLength) 6573 { 6574 SECStatus rv; 6575 unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len; 6576 6577 if (appendLength) { 6578 rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2); 6579 if (rv != SECSuccess) { 6580 return rv; 6581 } 6582 } 6583 while (pad) { 6584 rv = sslBuffer_AppendNumber(buf, 0, 1); 6585 if (rv != SECSuccess) { 6586 return rv; 6587 } 6588 --pad; 6589 } 6590 rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data, 6591 pubKey->u.dh.publicValue.len); 6592 if (rv != SECSuccess) { 6593 return rv; 6594 } 6595 return SECSuccess; 6596 } 6597 6598 /* Called from ssl3_SendClientKeyExchange(). */ 6599 static SECStatus 6600 ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) 6601 { 6602 PK11SymKey *pms = NULL; 6603 SECStatus rv; 6604 PRBool isTLS; 6605 CK_MECHANISM_TYPE target; 6606 6607 const ssl3DHParams *params; 6608 ssl3DHParams customParams; 6609 const sslNamedGroupDef *groupDef; 6610 static const sslNamedGroupDef customGroupDef = { 6611 ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE 6612 }; 6613 sslEphemeralKeyPair *keyPair = NULL; 6614 SECKEYPublicKey *pubKey; 6615 PRUint8 dhData[SSL_MAX_DH_KEY_BITS / 8 + 2]; 6616 sslBuffer dhBuf = SSL_BUFFER(dhData); 6617 6618 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 6619 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 6620 6621 isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0); 6622 6623 /* Copy DH parameters from server key */ 6624 6625 if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) { 6626 PORT_SetError(SEC_ERROR_BAD_KEY); 6627 return SECFailure; 6628 } 6629 6630 /* Work out the parameters. */ 6631 rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime, 6632 &svrPubKey->u.dh.base, 6633 &groupDef, ¶ms); 6634 if (rv != SECSuccess) { 6635 /* If we require named groups, we will have already validated the group 6636 * in ssl_HandleDHServerKeyExchange() */ 6637 PORT_Assert(!ss->opt.requireDHENamedGroups && 6638 !ss->xtnData.peerSupportsFfdheGroups); 6639 6640 customParams.name = ssl_grp_ffdhe_custom; 6641 customParams.prime.data = svrPubKey->u.dh.prime.data; 6642 customParams.prime.len = svrPubKey->u.dh.prime.len; 6643 customParams.base.data = svrPubKey->u.dh.base.data; 6644 customParams.base.len = svrPubKey->u.dh.base.len; 6645 params = &customParams; 6646 groupDef = &customGroupDef; 6647 } 6648 ss->sec.keaGroup = groupDef; 6649 6650 rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair); 6651 if (rv != SECSuccess) { 6652 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); 6653 goto loser; 6654 } 6655 pubKey = keyPair->keys->pubKey; 6656 PRINT_BUF(50, (ss, "DH public value:", 6657 pubKey->u.dh.publicValue.data, 6658 pubKey->u.dh.publicValue.len)); 6659 6660 if (isTLS) 6661 target = CKM_TLS_MASTER_KEY_DERIVE_DH; 6662 else 6663 target = CKM_SSL3_MASTER_KEY_DERIVE_DH; 6664 6665 /* Determine the PMS */ 6666 pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey, 6667 PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE, 6668 target, CKA_DERIVE, 0, NULL); 6669 6670 if (pms == NULL) { 6671 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6672 goto loser; 6673 } 6674 6675 /* Note: send the DH share padded to avoid triggering bugs. */ 6676 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange, 6677 params->prime.len + 2); 6678 if (rv != SECSuccess) { 6679 goto loser; /* err set by ssl3_AppendHandshake* */ 6680 } 6681 rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE); 6682 if (rv != SECSuccess) { 6683 goto loser; /* err set by ssl_AppendPaddedDHKeyShare */ 6684 } 6685 rv = ssl3_AppendBufferToHandshake(ss, &dhBuf); 6686 if (rv != SECSuccess) { 6687 goto loser; /* err set by ssl3_AppendBufferToHandshake */ 6688 } 6689 6690 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE); 6691 if (rv != SECSuccess) { 6692 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 6693 goto loser; 6694 } 6695 6696 sslBuffer_Clear(&dhBuf); 6697 PK11_FreeSymKey(pms); 6698 ssl_FreeEphemeralKeyPair(keyPair); 6699 return SECSuccess; 6700 6701 loser: 6702 if (pms) 6703 PK11_FreeSymKey(pms); 6704 if (keyPair) 6705 ssl_FreeEphemeralKeyPair(keyPair); 6706 sslBuffer_Clear(&dhBuf); 6707 return SECFailure; 6708 } 6709 6710 /* Called from ssl3_HandleServerHelloDone(). */ 6711 static SECStatus 6712 ssl3_SendClientKeyExchange(sslSocket *ss) 6713 { 6714 SECKEYPublicKey *serverKey = NULL; 6715 SECStatus rv = SECFailure; 6716 6717 SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", 6718 SSL_GETPID(), ss->fd)); 6719 6720 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 6721 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 6722 6723 if (ss->sec.peerKey == NULL) { 6724 serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); 6725 if (serverKey == NULL) { 6726 ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 6727 return SECFailure; 6728 } 6729 } else { 6730 serverKey = ss->sec.peerKey; 6731 ss->sec.peerKey = NULL; /* we're done with it now */ 6732 } 6733 6734 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; 6735 ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); 6736 6737 switch (ss->ssl3.hs.kea_def->exchKeyType) { 6738 case ssl_kea_rsa: 6739 rv = ssl3_SendRSAClientKeyExchange(ss, serverKey); 6740 break; 6741 6742 case ssl_kea_dh: 6743 rv = ssl3_SendDHClientKeyExchange(ss, serverKey); 6744 break; 6745 6746 case ssl_kea_ecdh: 6747 rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); 6748 break; 6749 6750 default: 6751 PORT_Assert(0); 6752 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6753 break; 6754 } 6755 6756 SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange", 6757 SSL_GETPID(), ss->fd)); 6758 6759 SECKEY_DestroyPublicKey(serverKey); 6760 return rv; /* err code already set. */ 6761 } 6762 6763 /* Used by ssl_PickSignatureScheme(). */ 6764 PRBool 6765 ssl_CanUseSignatureScheme(SSLSignatureScheme scheme, 6766 const SSLSignatureScheme *peerSchemes, 6767 unsigned int peerSchemeCount, 6768 PRBool requireSha1, 6769 PRBool slotDoesPss) 6770 { 6771 SSLHashType hashType; 6772 unsigned int i; 6773 6774 /* Skip RSA-PSS schemes when the certificate's private key slot does 6775 * not support this signature mechanism. */ 6776 if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) { 6777 return PR_FALSE; 6778 } 6779 6780 hashType = ssl_SignatureSchemeToHashType(scheme); 6781 if (requireSha1 && (hashType != ssl_hash_sha1)) { 6782 return PR_FALSE; 6783 } 6784 6785 if (!ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy)) { 6786 return PR_FALSE; 6787 } 6788 6789 for (i = 0; i < peerSchemeCount; i++) { 6790 if (peerSchemes[i] == scheme) { 6791 return PR_TRUE; 6792 } 6793 } 6794 return PR_FALSE; 6795 } 6796 6797 SECStatus 6798 ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey, CERTCertificate *cert, 6799 void *pwarg, PRBool *supportsRsaPss) 6800 { 6801 PK11SlotInfo *slot = NULL; 6802 if (privKey) { 6803 slot = PK11_GetSlotFromPrivateKey(privKey); 6804 } else { 6805 CK_OBJECT_HANDLE certID = PK11_FindObjectForCert(cert, pwarg, &slot); 6806 if (certID == CK_INVALID_HANDLE) { 6807 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6808 return SECFailure; 6809 } 6810 } 6811 if (!slot) { 6812 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6813 return SECFailure; 6814 } 6815 *supportsRsaPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]); 6816 PK11_FreeSlot(slot); 6817 return SECSuccess; 6818 } 6819 6820 SECStatus 6821 ssl_PickSignatureScheme(sslSocket *ss, 6822 CERTCertificate *cert, 6823 SECKEYPublicKey *pubKey, 6824 SECKEYPrivateKey *privKey, 6825 const SSLSignatureScheme *peerSchemes, 6826 unsigned int peerSchemeCount, 6827 PRBool requireSha1, 6828 SSLSignatureScheme *schemePtr) 6829 { 6830 unsigned int i; 6831 PRBool doesRsaPss; 6832 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; 6833 SECStatus rv; 6834 SSLSignatureScheme scheme; 6835 SECOidTag spkiOid; 6836 6837 /* We can't require SHA-1 in TLS 1.3. */ 6838 PORT_Assert(!(requireSha1 && isTLS13)); 6839 if (!pubKey || !cert) { 6840 PORT_Assert(0); 6841 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 6842 return SECFailure; 6843 } 6844 rv = ssl_PrivateKeySupportsRsaPss(privKey, cert, ss->pkcs11PinArg, 6845 &doesRsaPss); 6846 if (rv != SECSuccess) { 6847 return SECFailure; 6848 } 6849 6850 /* If the certificate SPKI indicates a single scheme, don't search. */ 6851 rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo, 6852 isTLS13, &scheme); 6853 if (rv != SECSuccess) { 6854 return SECFailure; 6855 } 6856 if (scheme != ssl_sig_none) { 6857 if (!ssl_SignatureSchemeEnabled(ss, scheme) || 6858 !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount, 6859 requireSha1, doesRsaPss)) { 6860 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 6861 return SECFailure; 6862 } 6863 *schemePtr = scheme; 6864 return SECSuccess; 6865 } 6866 6867 spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm); 6868 if (spkiOid == SEC_OID_UNKNOWN) { 6869 return SECFailure; 6870 } 6871 6872 /* Now we have to search based on the key type. Go through our preferred 6873 * schemes in order and find the first that can be used. */ 6874 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 6875 scheme = ss->ssl3.signatureSchemes[i]; 6876 6877 if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) && 6878 ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount, 6879 requireSha1, doesRsaPss)) { 6880 *schemePtr = scheme; 6881 return SECSuccess; 6882 } 6883 } 6884 6885 PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); 6886 return SECFailure; 6887 } 6888 6889 static SECStatus 6890 ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey) 6891 { 6892 PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2; 6893 6894 switch (SECKEY_GetPublicKeyType(pubKey)) { 6895 case rsaKey: 6896 if (isTLS12) { 6897 ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1; 6898 } else { 6899 ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5; 6900 } 6901 break; 6902 case ecKey: 6903 ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1; 6904 break; 6905 case dsaKey: 6906 ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1; 6907 break; 6908 default: 6909 PORT_Assert(0); 6910 PORT_SetError(SEC_ERROR_INVALID_KEY); 6911 return SECFailure; 6912 } 6913 return SECSuccess; 6914 } 6915 6916 /* ssl3_PickServerSignatureScheme selects a signature scheme for signing the 6917 * handshake. Most of this is determined by the key pair we are using. 6918 * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a 6919 * client may advertise its support for signature and hash combinations. */ 6920 static SECStatus 6921 ssl3_PickServerSignatureScheme(sslSocket *ss) 6922 { 6923 const sslServerCert *cert = ss->sec.serverCert; 6924 PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2; 6925 6926 if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) { 6927 /* If the client didn't provide any signature_algorithms extension then 6928 * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */ 6929 return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey); 6930 } 6931 6932 /* Sets error code, if needed. */ 6933 return ssl_PickSignatureScheme(ss, cert->serverCert, 6934 cert->serverKeyPair->pubKey, 6935 cert->serverKeyPair->privKey, 6936 ss->xtnData.sigSchemes, 6937 ss->xtnData.numSigSchemes, 6938 PR_FALSE /* requireSha1 */, 6939 &ss->ssl3.hs.signatureScheme); 6940 } 6941 6942 SECStatus 6943 ssl_PickClientSignatureScheme(sslSocket *ss, CERTCertificate *clientCertificate, 6944 SECKEYPrivateKey *privKey, 6945 const SSLSignatureScheme *schemes, 6946 unsigned int numSchemes, 6947 SSLSignatureScheme *schemePtr) 6948 { 6949 SECStatus rv; 6950 PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; 6951 SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(clientCertificate); 6952 6953 PORT_Assert(pubKey); 6954 6955 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 6956 /* We should have already checked that a signature scheme was 6957 * listed in the request. */ 6958 PORT_Assert(schemes && numSchemes > 0); 6959 } 6960 6961 if (!isTLS13 && 6962 (SECKEY_GetPublicKeyType(pubKey) == rsaKey || 6963 SECKEY_GetPublicKeyType(pubKey) == dsaKey) && 6964 SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) { 6965 /* If the key is a 1024-bit RSA or DSA key, assume conservatively that 6966 * it may be unable to sign SHA-256 hashes. This is the case for older 6967 * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and 6968 * older, DSA key size is at most 1024 bits and the hash function must 6969 * be SHA-1. 6970 */ 6971 rv = ssl_PickSignatureScheme(ss, clientCertificate, 6972 pubKey, privKey, schemes, numSchemes, 6973 PR_TRUE /* requireSha1 */, schemePtr); 6974 if (rv == SECSuccess) { 6975 SECKEY_DestroyPublicKey(pubKey); 6976 return SECSuccess; 6977 } 6978 /* If this fails, that's because the peer doesn't advertise SHA-1, 6979 * so fall back to the full negotiation. */ 6980 } 6981 rv = ssl_PickSignatureScheme(ss, clientCertificate, 6982 pubKey, privKey, schemes, numSchemes, 6983 PR_FALSE /* requireSha1 */, schemePtr); 6984 SECKEY_DestroyPublicKey(pubKey); 6985 return rv; 6986 } 6987 6988 /* Called from ssl3_HandleServerHelloDone(). */ 6989 static SECStatus 6990 ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey) 6991 { 6992 SECStatus rv = SECFailure; 6993 PRBool isTLS12; 6994 SECItem buf = { siBuffer, NULL, 0 }; 6995 SSL3Hashes hashes; 6996 unsigned int len; 6997 SSLHashType hashAlg; 6998 6999 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 7000 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 7001 7002 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake", 7003 SSL_GETPID(), ss->fd)); 7004 7005 ssl_GetSpecReadLock(ss); 7006 7007 if (ss->ssl3.hs.hashType == handshake_hash_record) { 7008 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme); 7009 } else { 7010 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */ 7011 hashAlg = ssl_hash_none; 7012 } 7013 if (ss->ssl3.hs.hashType == handshake_hash_record && 7014 hashAlg != ssl3_GetSuitePrfHash(ss)) { 7015 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf, 7016 ss->ssl3.hs.messages.len, 7017 hashAlg, &hashes); 7018 if (rv != SECSuccess) { 7019 ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 7020 } 7021 } else { 7022 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); 7023 } 7024 ssl_ReleaseSpecReadLock(ss); 7025 if (rv != SECSuccess) { 7026 goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */ 7027 } 7028 7029 isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_2); 7030 PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2); 7031 7032 rv = ssl3_SignHashes(ss, &hashes, privKey, &buf); 7033 if (rv == SECSuccess && !ss->sec.isServer) { 7034 /* Remember the info about the slot that did the signing. 7035 ** Later, when doing an SSL restart handshake, verify this. 7036 ** These calls are mere accessors, and can't fail. 7037 */ 7038 PK11SlotInfo *slot; 7039 sslSessionID *sid = ss->sec.ci.sid; 7040 7041 slot = PK11_GetSlotFromPrivateKey(privKey); 7042 sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); 7043 sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); 7044 sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); 7045 sid->u.ssl3.clAuthValid = PR_TRUE; 7046 PK11_FreeSlot(slot); 7047 } 7048 if (rv != SECSuccess) { 7049 goto done; /* err code was set by ssl3_SignHashes */ 7050 } 7051 7052 len = buf.len + 2 + (isTLS12 ? 2 : 0); 7053 7054 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len); 7055 if (rv != SECSuccess) { 7056 goto done; /* error code set by AppendHandshake */ 7057 } 7058 if (isTLS12) { 7059 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2); 7060 if (rv != SECSuccess) { 7061 goto done; /* err set by AppendHandshake. */ 7062 } 7063 } 7064 rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2); 7065 if (rv != SECSuccess) { 7066 goto done; /* error code set by AppendHandshake */ 7067 } 7068 7069 done: 7070 if (buf.data) 7071 PORT_Free(buf.data); 7072 return rv; 7073 } 7074 7075 /* Once a cipher suite has been selected, make sure that the necessary secondary 7076 * information is properly set. */ 7077 SECStatus 7078 ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes) 7079 { 7080 ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); 7081 if (!ss->ssl3.hs.suite_def) { 7082 PORT_Assert(0); 7083 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 7084 return SECFailure; 7085 } 7086 7087 ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg]; 7088 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; 7089 7090 if (!initHashes) { 7091 return SECSuccess; 7092 } 7093 /* Now we have a cipher suite, initialize the handshake hashes. */ 7094 return ssl3_InitHandshakeHashes(ss); 7095 } 7096 7097 SECStatus 7098 ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version, 7099 ssl3CipherSuite suite, PRBool initHashes) 7100 { 7101 unsigned int i; 7102 if (ssl3_config_match_init(ss) == 0) { 7103 PORT_Assert(PR_FALSE); 7104 return SECFailure; 7105 } 7106 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 7107 ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i]; 7108 if (suite == suiteCfg->cipher_suite) { 7109 SSLVersionRange vrange = { version, version }; 7110 if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) { 7111 /* config_match already checks whether the cipher suite is 7112 * acceptable for the version, but the check is repeated here 7113 * in order to give a more precise error code. */ 7114 if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) { 7115 PORT_SetError(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION); 7116 } else { 7117 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 7118 } 7119 return SECFailure; 7120 } 7121 break; 7122 } 7123 } 7124 if (i >= ssl_V3_SUITES_IMPLEMENTED) { 7125 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 7126 return SECFailure; 7127 } 7128 7129 /* Don't let the server change its mind. */ 7130 if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) { 7131 (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 7132 PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO); 7133 return SECFailure; 7134 } 7135 7136 ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite; 7137 return ssl3_SetupCipherSuite(ss, initHashes); 7138 } 7139 7140 /* Check that session ID we received from the server, if any, matches our 7141 * expectations, depending on whether we're in compat mode and whether we 7142 * negotiated TLS 1.3+ or TLS 1.2-. 7143 */ 7144 static PRBool 7145 ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes) 7146 { 7147 sslSessionID *sid = ss->sec.ci.sid; 7148 PRBool sidMatch = PR_FALSE; 7149 PRBool sentFakeSid = PR_FALSE; 7150 PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3; 7151 7152 /* If attempting to resume a TLS 1.2 connection, the session ID won't be a 7153 * fake. Check for the real value. */ 7154 if (sentRealSid) { 7155 sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) && 7156 (!sidBytes->len || PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0); 7157 } else { 7158 /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is 7159 * enabled. If so, check for the fake value. */ 7160 sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss); 7161 if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) { 7162 PRUint8 buf[SSL3_SESSIONID_BYTES]; 7163 ssl_MakeFakeSid(ss, buf); 7164 sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0; 7165 } 7166 } 7167 7168 /* TLS 1.2: Session ID shouldn't match if we sent a fake. */ 7169 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 7170 if (sentFakeSid) { 7171 return !sidMatch; 7172 } 7173 return PR_TRUE; 7174 } 7175 7176 /* TLS 1.3: We sent a session ID. The server's should match. */ 7177 if (!IS_DTLS(ss) && (sentRealSid || sentFakeSid)) { 7178 return sidMatch; 7179 } 7180 7181 /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */ 7182 return sidBytes->len == 0; 7183 } 7184 7185 static SECStatus 7186 ssl_CheckServerRandom(sslSocket *ss) 7187 { 7188 /* Check the ServerHello.random per [RFC 8446 Section 4.1.3]. 7189 * 7190 * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below 7191 * MUST check that the last 8 bytes are not equal to either of these 7192 * values. TLS 1.2 clients SHOULD also check that the last 8 bytes are 7193 * not equal to the second value if the ServerHello indicates TLS 1.1 or 7194 * below. If a match is found, the client MUST abort the handshake with 7195 * an "illegal_parameter" alert. 7196 */ 7197 SSL3ProtocolVersion checkVersion = 7198 ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion 7199 : ss->vrange.max; 7200 7201 if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_2 && 7202 checkVersion > ss->version) { 7203 /* Both sections use the same sentinel region. */ 7204 PRUint8 *downgrade_sentinel = 7205 ss->ssl3.hs.server_random + 7206 SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random); 7207 7208 if (!PORT_Memcmp(downgrade_sentinel, 7209 tls12_downgrade_random, 7210 sizeof(tls12_downgrade_random)) || 7211 !PORT_Memcmp(downgrade_sentinel, 7212 tls1_downgrade_random, 7213 sizeof(tls1_downgrade_random))) { 7214 return SECFailure; 7215 } 7216 } 7217 7218 return SECSuccess; 7219 } 7220 7221 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 7222 * ssl3 ServerHello message. 7223 * Caller must hold Handshake and RecvBuf locks. 7224 */ 7225 static SECStatus 7226 ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length) 7227 { 7228 PRUint32 cipher; 7229 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 7230 PRUint32 compression; 7231 SECStatus rv; 7232 SECItem sidBytes = { siBuffer, NULL, 0 }; 7233 PRBool isHelloRetry; 7234 SSL3AlertDescription desc = illegal_parameter; 7235 const PRUint8 *savedMsg = b; 7236 const PRUint32 savedLength = length; 7237 7238 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake", 7239 SSL_GETPID(), ss->fd)); 7240 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 7241 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 7242 7243 if (ss->ssl3.hs.ws != wait_server_hello) { 7244 errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; 7245 desc = unexpected_message; 7246 goto alert_loser; 7247 } 7248 7249 /* clean up anything left from previous handshake. */ 7250 if (ss->ssl3.clientCertChain != NULL) { 7251 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 7252 ss->ssl3.clientCertChain = NULL; 7253 } 7254 if (ss->ssl3.clientCertificate != NULL) { 7255 CERT_DestroyCertificate(ss->ssl3.clientCertificate); 7256 ss->ssl3.clientCertificate = NULL; 7257 } 7258 if (ss->ssl3.clientPrivateKey != NULL) { 7259 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 7260 ss->ssl3.clientPrivateKey = NULL; 7261 } 7262 // TODO(djackson) - Bob removed this. Why? 7263 if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) { 7264 PR_Free(ss->ssl3.hs.clientAuthSignatureSchemes); 7265 ss->ssl3.hs.clientAuthSignatureSchemes = NULL; 7266 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0; 7267 } 7268 7269 /* Note that if the server selects TLS 1.3, this will set the version to TLS 7270 * 1.2. We will amend that once all other fields have been read. */ 7271 rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version); 7272 if (rv != SECSuccess) { 7273 goto loser; /* alert has been sent */ 7274 } 7275 7276 rv = ssl3_ConsumeHandshake( 7277 ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); 7278 if (rv != SECSuccess) { 7279 goto loser; /* alert has been sent */ 7280 } 7281 isHelloRetry = !PORT_Memcmp(ss->ssl3.hs.server_random, 7282 ssl_hello_retry_random, SSL3_RANDOM_LENGTH); 7283 7284 rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); 7285 if (rv != SECSuccess) { 7286 goto loser; /* alert has been sent */ 7287 } 7288 if (sidBytes.len > SSL3_SESSIONID_BYTES) { 7289 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_0) 7290 desc = decode_error; 7291 goto alert_loser; /* malformed. */ 7292 } 7293 7294 /* Read the cipher suite. */ 7295 rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length); 7296 if (rv != SECSuccess) { 7297 goto loser; /* alert has been sent */ 7298 } 7299 7300 /* Compression method. */ 7301 rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length); 7302 if (rv != SECSuccess) { 7303 goto loser; /* alert has been sent */ 7304 } 7305 if (compression != ssl_compression_null) { 7306 desc = illegal_parameter; 7307 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 7308 goto alert_loser; 7309 } 7310 7311 /* Parse extensions. */ 7312 if (length != 0) { 7313 PRUint32 extensionLength; 7314 rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length); 7315 if (rv != SECSuccess) { 7316 goto loser; /* alert already sent */ 7317 } 7318 if (extensionLength != length) { 7319 desc = decode_error; 7320 goto alert_loser; 7321 } 7322 rv = ssl3_ParseExtensions(ss, &b, &length); 7323 if (rv != SECSuccess) { 7324 goto alert_loser; /* malformed */ 7325 } 7326 } 7327 7328 /* Read supported_versions if present. */ 7329 rv = tls13_ClientReadSupportedVersion(ss); 7330 if (rv != SECSuccess) { 7331 goto loser; 7332 } 7333 7334 /* RFC 9147. 5.2. 7335 * DTLS Handshake Message Format states the difference between the computation 7336 * of the transcript if the version is DTLS1.2 or DTLS1.3. 7337 * 7338 * At this moment we are sure which version 7339 * we are planning to use during the connection, so we can compute the hash. */ 7340 rv = ssl3_MaybeUpdateHashWithSavedRecord(ss); 7341 if (rv != SECSuccess) { 7342 goto loser; 7343 } 7344 7345 PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange)); 7346 /* Check that the version is within the configured range. */ 7347 if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) { 7348 desc = (ss->version > SSL_LIBRARY_VERSION_3_0) 7349 ? protocol_version 7350 : handshake_failure; 7351 errCode = SSL_ERROR_UNSUPPORTED_VERSION; 7352 goto alert_loser; 7353 } 7354 7355 if (isHelloRetry && ss->ssl3.hs.helloRetry) { 7356 SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request", 7357 SSL_GETPID(), ss->fd)); 7358 desc = unexpected_message; 7359 errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST; 7360 goto alert_loser; 7361 } 7362 7363 /* There are three situations in which the server must pick 7364 * TLS 1.3. 7365 * 7366 * 1. We received HRR 7367 * 2. We sent early app data 7368 * 3. ECH was accepted (checked in MaybeHandleEchSignal) 7369 * 7370 * If we offered ECH and the server negotiated a lower version, 7371 * authenticate to the public name for secure disablement. 7372 * 7373 */ 7374 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 7375 if (isHelloRetry || ss->ssl3.hs.helloRetry) { 7376 /* SSL3_SendAlert() will uncache the SID. */ 7377 desc = illegal_parameter; 7378 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 7379 goto alert_loser; 7380 } 7381 if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) { 7382 /* SSL3_SendAlert() will uncache the SID. */ 7383 desc = illegal_parameter; 7384 errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA; 7385 goto alert_loser; 7386 } 7387 } 7388 7389 /* Check that the server negotiated the same version as it did 7390 * in the first handshake. This isn't really the best place for 7391 * us to be getting this version number, but it's what we have. 7392 * (1294697). */ 7393 if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) { 7394 desc = protocol_version; 7395 errCode = SSL_ERROR_UNSUPPORTED_VERSION; 7396 goto alert_loser; 7397 } 7398 7399 if (ss->opt.enableHelloDowngradeCheck) { 7400 rv = ssl_CheckServerRandom(ss); 7401 if (rv != SECSuccess) { 7402 desc = illegal_parameter; 7403 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 7404 goto alert_loser; 7405 } 7406 } 7407 7408 /* Finally, now all the version-related checks have passed. */ 7409 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; 7410 /* Update the write cipher spec to match the version. But not after 7411 * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec, 7412 * in which case this is a no-op. */ 7413 if (!ss->firstHsDone && !isHelloRetry) { 7414 ssl_GetSpecWriteLock(ss); 7415 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec); 7416 ssl_ReleaseSpecWriteLock(ss); 7417 } 7418 7419 /* Check that the session ID is as expected. */ 7420 if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) { 7421 desc = illegal_parameter; 7422 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 7423 goto alert_loser; 7424 } 7425 7426 /* Only initialize hashes if this isn't a Hello Retry. */ 7427 rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher, 7428 !isHelloRetry); 7429 if (rv != SECSuccess) { 7430 desc = illegal_parameter; 7431 errCode = PORT_GetError(); 7432 goto alert_loser; 7433 } 7434 7435 dtls_ReceivedFirstMessageInFlight(ss); 7436 7437 if (isHelloRetry) { 7438 rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength); 7439 if (rv != SECSuccess) { 7440 goto loser; 7441 } 7442 return SECSuccess; 7443 } 7444 7445 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello); 7446 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions); 7447 if (rv != SECSuccess) { 7448 goto alert_loser; 7449 } 7450 7451 rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello, 7452 savedMsg, savedLength); 7453 if (rv != SECSuccess) { 7454 goto loser; 7455 } 7456 7457 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 7458 rv = tls13_HandleServerHelloPart2(ss, savedMsg, savedLength); 7459 if (rv != SECSuccess) { 7460 errCode = PORT_GetError(); 7461 goto loser; 7462 } 7463 } else { 7464 rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode); 7465 if (rv != SECSuccess) 7466 goto loser; 7467 } 7468 7469 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech; 7470 return SECSuccess; 7471 7472 alert_loser: 7473 (void)SSL3_SendAlert(ss, alert_fatal, desc); 7474 7475 loser: 7476 /* Clean up the temporary pointer to the handshake buffer. */ 7477 ss->xtnData.signedCertTimestamps.len = 0; 7478 ssl_MapLowLevelError(errCode); 7479 return SECFailure; 7480 } 7481 7482 static SECStatus 7483 ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms) 7484 { 7485 PK11SlotInfo *slot; 7486 PK11SymKey *wrapKey; 7487 CK_FLAGS keyFlags = 0; 7488 SECItem wrappedMS = { 7489 siBuffer, 7490 sid->u.ssl3.keys.wrapped_master_secret, 7491 sid->u.ssl3.keys.wrapped_master_secret_len 7492 }; 7493 7494 /* unwrap master secret */ 7495 slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, 7496 sid->u.ssl3.masterSlotID); 7497 if (slot == NULL) { 7498 return SECFailure; 7499 } 7500 if (!PK11_IsPresent(slot)) { 7501 PK11_FreeSlot(slot); 7502 return SECFailure; 7503 } 7504 wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, 7505 sid->u.ssl3.masterWrapMech, 7506 sid->u.ssl3.masterWrapSeries, 7507 ss->pkcs11PinArg); 7508 PK11_FreeSlot(slot); 7509 if (wrapKey == NULL) { 7510 return SECFailure; 7511 } 7512 7513 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ 7514 keyFlags = CKF_SIGN | CKF_VERIFY; 7515 } 7516 7517 *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 7518 NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, 7519 CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags); 7520 PK11_FreeSymKey(wrapKey); 7521 if (!*ms) { 7522 return SECFailure; 7523 } 7524 return SECSuccess; 7525 } 7526 7527 static SECStatus 7528 ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes, 7529 int *retErrCode) 7530 { 7531 SSL3AlertDescription desc = handshake_failure; 7532 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 7533 SECStatus rv; 7534 PRBool sid_match; 7535 sslSessionID *sid = ss->sec.ci.sid; 7536 7537 if ((ss->opt.requireSafeNegotiation || 7538 (ss->firstHsDone && (ss->peerRequestedProtection || 7539 ss->opt.enableRenegotiation == 7540 SSL_RENEGOTIATE_REQUIRES_XTN))) && 7541 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 7542 desc = handshake_failure; 7543 errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED 7544 : SSL_ERROR_UNSAFE_NEGOTIATION; 7545 goto alert_loser; 7546 } 7547 7548 /* Any errors after this point are not "malformed" errors. */ 7549 desc = handshake_failure; 7550 7551 /* we need to call ssl3_SetupPendingCipherSpec here so we can check the 7552 * key exchange algorithm. */ 7553 rv = ssl3_SetupBothPendingCipherSpecs(ss); 7554 if (rv != SECSuccess) { 7555 goto alert_loser; /* error code is set. */ 7556 } 7557 7558 /* We may or may not have sent a session id, we may get one back or 7559 * not and if so it may match the one we sent. 7560 * Attempt to restore the master secret to see if this is so... 7561 * Don't consider failure to find a matching SID an error. 7562 */ 7563 sid_match = (PRBool)(sidBytes->len > 0 && 7564 sidBytes->len == 7565 sid->u.ssl3.sessionIDLength && 7566 !PORT_Memcmp(sid->u.ssl3.sessionID, 7567 sidBytes->data, sidBytes->len)); 7568 7569 if (sid_match) { 7570 if (sid->version != ss->version || 7571 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) { 7572 errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 7573 goto alert_loser; 7574 } 7575 do { 7576 PK11SymKey *masterSecret; 7577 7578 /* [draft-ietf-tls-session-hash-06; Section 5.3] 7579 * 7580 * o If the original session did not use the "extended_master_secret" 7581 * extension but the new ServerHello contains the extension, the 7582 * client MUST abort the handshake. 7583 */ 7584 if (!sid->u.ssl3.keys.extendedMasterSecretUsed && 7585 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { 7586 errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET; 7587 goto alert_loser; 7588 } 7589 7590 /* 7591 * o If the original session used an extended master secret but the new 7592 * ServerHello does not contain the "extended_master_secret" 7593 * extension, the client SHOULD abort the handshake. 7594 * 7595 * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not 7596 * used at all (bug 1176526). 7597 */ 7598 if (sid->u.ssl3.keys.extendedMasterSecretUsed && 7599 !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { 7600 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; 7601 goto alert_loser; 7602 } 7603 7604 ss->sec.authType = sid->authType; 7605 ss->sec.authKeyBits = sid->authKeyBits; 7606 ss->sec.keaType = sid->keaType; 7607 ss->sec.keaKeyBits = sid->keaKeyBits; 7608 ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup); 7609 ss->sec.signatureScheme = sid->sigScheme; 7610 7611 rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret); 7612 if (rv != SECSuccess) { 7613 break; /* not considered an error */ 7614 } 7615 7616 /* Got a Match */ 7617 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits); 7618 7619 /* If we sent a session ticket, then this is a stateless resume. */ 7620 if (ss->xtnData.sentSessionTicketInClientHello) 7621 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes); 7622 7623 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) 7624 ss->ssl3.hs.ws = wait_new_session_ticket; 7625 else 7626 ss->ssl3.hs.ws = wait_change_cipher; 7627 7628 ss->ssl3.hs.isResuming = PR_TRUE; 7629 7630 /* copy the peer cert from the SID */ 7631 if (sid->peerCert != NULL) { 7632 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); 7633 } 7634 7635 /* We are re-using the old MS, so no need to derive again. */ 7636 rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE); 7637 if (rv != SECSuccess) { 7638 goto alert_loser; /* err code was set */ 7639 } 7640 return SECSuccess; 7641 } while (0); 7642 } 7643 7644 if (sid_match) 7645 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok); 7646 else 7647 SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses); 7648 7649 /* We tried to resume a 1.3 session but the server negotiated 1.2. */ 7650 if (ss->statelessResume) { 7651 PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3); 7652 PORT_Assert(ss->ssl3.hs.currentSecret); 7653 7654 /* Reset resumption state, only used by 1.3 code. */ 7655 ss->statelessResume = PR_FALSE; 7656 7657 /* Clear TLS 1.3 early data traffic key. */ 7658 PK11_FreeSymKey(ss->ssl3.hs.currentSecret); 7659 ss->ssl3.hs.currentSecret = NULL; 7660 } 7661 7662 /* throw the old one away */ 7663 sid->u.ssl3.keys.resumable = PR_FALSE; 7664 ssl_UncacheSessionID(ss); 7665 ssl_FreeSID(sid); 7666 7667 /* get a new sid */ 7668 ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE); 7669 if (sid == NULL) { 7670 goto alert_loser; /* memory error is set. */ 7671 } 7672 7673 sid->version = ss->version; 7674 sid->u.ssl3.sessionIDLength = sidBytes->len; 7675 if (sidBytes->len > 0) { 7676 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len); 7677 } 7678 7679 sid->u.ssl3.keys.extendedMasterSecretUsed = 7680 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); 7681 7682 /* Copy Signed Certificate Timestamps, if any. */ 7683 if (ss->xtnData.signedCertTimestamps.len) { 7684 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps, 7685 &ss->xtnData.signedCertTimestamps); 7686 ss->xtnData.signedCertTimestamps.len = 0; 7687 if (rv != SECSuccess) 7688 goto loser; 7689 } 7690 7691 ss->ssl3.hs.isResuming = PR_FALSE; 7692 if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) { 7693 /* All current cipher suites other than those with ssl_auth_null (i.e., 7694 * (EC)DH_anon_* suites) require a certificate, so use that signal. */ 7695 ss->ssl3.hs.ws = wait_server_cert; 7696 } else { 7697 /* All the remaining cipher suites must be (EC)DH_anon_* and so 7698 * must be ephemeral. Note, if we ever add PSK this might 7699 * change. */ 7700 PORT_Assert(ss->ssl3.hs.kea_def->ephemeral); 7701 ss->ssl3.hs.ws = wait_server_key; 7702 } 7703 return SECSuccess; 7704 7705 alert_loser: 7706 (void)SSL3_SendAlert(ss, alert_fatal, desc); 7707 7708 loser: 7709 *retErrCode = errCode; 7710 return SECFailure; 7711 } 7712 7713 static SECStatus 7714 ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length) 7715 { 7716 SECStatus rv; 7717 int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; 7718 SSL3AlertDescription desc = illegal_parameter; 7719 SSLHashType hashAlg; 7720 PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0; 7721 SSLSignatureScheme sigScheme; 7722 7723 SECItem dh_p = { siBuffer, NULL, 0 }; 7724 SECItem dh_g = { siBuffer, NULL, 0 }; 7725 SECItem dh_Ys = { siBuffer, NULL, 0 }; 7726 unsigned dh_p_bits; 7727 unsigned dh_g_bits; 7728 PRInt32 minDH = 0; 7729 PRInt32 optval; 7730 7731 SSL3Hashes hashes; 7732 SECItem signature = { siBuffer, NULL, 0 }; 7733 PLArenaPool *arena = NULL; 7734 SECKEYPublicKey *peerKey = NULL; 7735 7736 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); 7737 if (rv != SECSuccess) { 7738 goto loser; /* malformed. */ 7739 } 7740 rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval); 7741 if ((rv == SECSuccess) && (optval & NSS_KEY_SIZE_POLICY_SSL_FLAG)) { 7742 (void)NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH); 7743 } 7744 7745 if (minDH <= 0) { 7746 minDH = SSL_DH_MIN_P_BITS; 7747 } 7748 dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p); 7749 if (dh_p_bits < (unsigned)minDH) { 7750 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; 7751 goto alert_loser; 7752 } 7753 if (dh_p_bits > SSL_MAX_DH_KEY_BITS) { 7754 errCode = SSL_ERROR_DH_KEY_TOO_LONG; 7755 goto alert_loser; 7756 } 7757 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length); 7758 if (rv != SECSuccess) { 7759 goto loser; /* malformed. */ 7760 } 7761 /* Abort if dh_g is 0, 1, or obviously too big. */ 7762 dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g); 7763 if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) { 7764 goto alert_loser; 7765 } 7766 if (ss->opt.requireDHENamedGroups) { 7767 /* If we're doing named groups, make sure it's good. */ 7768 rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL, NULL); 7769 if (rv != SECSuccess) { 7770 errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; 7771 goto alert_loser; 7772 } 7773 } 7774 7775 rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); 7776 if (rv != SECSuccess) { 7777 goto loser; /* malformed. */ 7778 } 7779 if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) { 7780 errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE; 7781 goto alert_loser; 7782 } 7783 7784 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 7785 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme); 7786 if (rv != SECSuccess) { 7787 goto loser; /* alert already sent */ 7788 } 7789 rv = ssl_CheckSignatureSchemeConsistency( 7790 ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo); 7791 if (rv != SECSuccess) { 7792 goto alert_loser; 7793 } 7794 hashAlg = ssl_SignatureSchemeToHashType(sigScheme); 7795 } else { 7796 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */ 7797 hashAlg = ssl_hash_none; 7798 sigScheme = ssl_sig_none; 7799 } 7800 rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); 7801 if (rv != SECSuccess) { 7802 goto loser; /* malformed. */ 7803 } 7804 if (length != 0) { 7805 if (isTLS) { 7806 desc = decode_error; 7807 } 7808 goto alert_loser; /* malformed. */ 7809 } 7810 7811 PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len)); 7812 PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len)); 7813 PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len)); 7814 7815 /* failures after this point are not malformed handshakes. */ 7816 /* TLS: send decrypt_error if signature failed. */ 7817 desc = isTLS ? decrypt_error : handshake_failure; 7818 7819 /* 7820 * Check to make sure the hash is signed by right guy. 7821 */ 7822 rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes, 7823 dh_p, dh_g, dh_Ys, PR_FALSE /* padY */); 7824 if (rv != SECSuccess) { 7825 errCode = 7826 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 7827 goto alert_loser; 7828 } 7829 rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature); 7830 if (rv != SECSuccess) { 7831 errCode = 7832 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 7833 goto alert_loser; 7834 } 7835 7836 /* 7837 * we really need to build a new key here because we can no longer 7838 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate 7839 * pkcs11 slots and ID's. 7840 */ 7841 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 7842 if (arena == NULL) { 7843 errCode = SEC_ERROR_NO_MEMORY; 7844 goto loser; 7845 } 7846 7847 peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); 7848 if (peerKey == NULL) { 7849 errCode = SEC_ERROR_NO_MEMORY; 7850 goto loser; 7851 } 7852 7853 peerKey->arena = arena; 7854 peerKey->keyType = dhKey; 7855 peerKey->pkcs11Slot = NULL; 7856 peerKey->pkcs11ID = CK_INVALID_HANDLE; 7857 7858 if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) || 7859 SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) || 7860 SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) { 7861 errCode = SEC_ERROR_NO_MEMORY; 7862 goto loser; 7863 } 7864 ss->sec.peerKey = peerKey; 7865 return SECSuccess; 7866 7867 alert_loser: 7868 (void)SSL3_SendAlert(ss, alert_fatal, desc); 7869 loser: 7870 if (arena) { 7871 PORT_FreeArena(arena, PR_FALSE); 7872 } 7873 PORT_SetError(ssl_MapLowLevelError(errCode)); 7874 return SECFailure; 7875 } 7876 7877 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a 7878 * complete ssl3 ServerKeyExchange message. 7879 * Caller must hold Handshake and RecvBuf locks. 7880 */ 7881 static SECStatus 7882 ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length) 7883 { 7884 SECStatus rv; 7885 7886 SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake", 7887 SSL_GETPID(), ss->fd)); 7888 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 7889 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 7890 7891 if (ss->ssl3.hs.ws != wait_server_key) { 7892 SSL3_SendAlert(ss, alert_fatal, unexpected_message); 7893 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); 7894 return SECFailure; 7895 } 7896 7897 switch (ss->ssl3.hs.kea_def->exchKeyType) { 7898 case ssl_kea_dh: 7899 rv = ssl_HandleDHServerKeyExchange(ss, b, length); 7900 break; 7901 7902 case ssl_kea_ecdh: 7903 rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); 7904 break; 7905 7906 default: 7907 SSL3_SendAlert(ss, alert_fatal, handshake_failure); 7908 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 7909 rv = SECFailure; 7910 break; 7911 } 7912 7913 if (rv == SECSuccess) { 7914 ss->ssl3.hs.ws = wait_cert_request; 7915 } 7916 /* All Handle*ServerKeyExchange functions set the error code. */ 7917 return rv; 7918 } 7919 7920 typedef struct dnameNode { 7921 struct dnameNode *next; 7922 SECItem name; 7923 } dnameNode; 7924 7925 /* 7926 * Parse the ca_list structure in a CertificateRequest. 7927 * 7928 * Called from: 7929 * ssl3_HandleCertificateRequest 7930 * tls13_HandleCertificateRequest 7931 */ 7932 SECStatus 7933 ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length, 7934 CERTDistNames *ca_list) 7935 { 7936 PRUint32 remaining; 7937 int nnames = 0; 7938 dnameNode *node; 7939 SECStatus rv; 7940 int i; 7941 7942 rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length); 7943 if (rv != SECSuccess) 7944 return SECFailure; /* malformed, alert has been sent */ 7945 7946 if (remaining > *length) 7947 goto alert_loser; 7948 7949 ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode); 7950 if (node == NULL) 7951 goto no_mem; 7952 7953 while (remaining > 0) { 7954 PRUint32 len; 7955 7956 if (remaining < 2) 7957 goto alert_loser; /* malformed */ 7958 7959 rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length); 7960 if (rv != SECSuccess) 7961 return SECFailure; /* malformed, alert has been sent */ 7962 if (len == 0 || remaining < len + 2) 7963 goto alert_loser; /* malformed */ 7964 7965 remaining -= 2; 7966 if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) { 7967 goto no_mem; 7968 } 7969 node->name.len = len; 7970 *b += len; 7971 *length -= len; 7972 remaining -= len; 7973 nnames++; 7974 if (remaining <= 0) 7975 break; /* success */ 7976 7977 node->next = PORT_ArenaZNew(ca_list->arena, dnameNode); 7978 node = node->next; 7979 if (node == NULL) 7980 goto no_mem; 7981 } 7982 7983 ca_list->nnames = nnames; 7984 ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames); 7985 if (nnames > 0 && ca_list->names == NULL) 7986 goto no_mem; 7987 7988 for (i = 0, node = (dnameNode *)ca_list->head; 7989 i < nnames; 7990 i++, node = node->next) { 7991 ca_list->names[i] = node->name; 7992 } 7993 7994 return SECSuccess; 7995 7996 no_mem: 7997 return SECFailure; 7998 7999 alert_loser: 8000 (void)SSL3_SendAlert(ss, alert_fatal, 8001 ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter 8002 : decode_error); 8003 PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST); 8004 return SECFailure; 8005 } 8006 8007 SECStatus 8008 ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena, 8009 SSLSignatureScheme **schemesOut, 8010 unsigned int *numSchemesOut, 8011 unsigned char **b, unsigned int *len) 8012 { 8013 SECStatus rv; 8014 SECItem buf; 8015 SSLSignatureScheme *schemes = NULL; 8016 unsigned int numSupported = 0; 8017 unsigned int numRemaining = 0; 8018 unsigned int max; 8019 8020 rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len); 8021 if (rv != SECSuccess) { 8022 return SECFailure; 8023 } 8024 /* An odd-length value is invalid. */ 8025 if ((buf.len & 1) != 0) { 8026 ssl3_ExtSendAlert(ss, alert_fatal, decode_error); 8027 return SECFailure; 8028 } 8029 8030 /* Let the caller decide whether to alert here. */ 8031 if (buf.len == 0) { 8032 goto done; 8033 } 8034 8035 /* Limit the number of schemes we read. */ 8036 numRemaining = buf.len / 2; 8037 max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES); 8038 8039 if (arena) { 8040 schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max); 8041 } else { 8042 schemes = PORT_ZNewArray(SSLSignatureScheme, max); 8043 } 8044 if (!schemes) { 8045 ssl3_ExtSendAlert(ss, alert_fatal, internal_error); 8046 return SECFailure; 8047 } 8048 8049 for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES; --numRemaining) { 8050 PRUint32 tmp; 8051 rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len); 8052 if (rv != SECSuccess) { 8053 PORT_Assert(0); 8054 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 8055 return SECFailure; 8056 } 8057 if (ssl_SignatureSchemeValid((SSLSignatureScheme)tmp, SEC_OID_UNKNOWN, 8058 (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) { 8059 ; 8060 schemes[numSupported++] = (SSLSignatureScheme)tmp; 8061 } 8062 } 8063 8064 if (!numSupported) { 8065 if (!arena) { 8066 PORT_Free(schemes); 8067 } 8068 schemes = NULL; 8069 } 8070 8071 done: 8072 *schemesOut = schemes; 8073 *numSchemesOut = numSupported; 8074 return SECSuccess; 8075 } 8076 8077 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered 8078 * a complete ssl3 Certificate Request message. 8079 * Caller must hold Handshake and RecvBuf locks. 8080 */ 8081 static SECStatus 8082 ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length) 8083 { 8084 PLArenaPool *arena = NULL; 8085 PRBool isTLS = PR_FALSE; 8086 PRBool isTLS12 = PR_FALSE; 8087 int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; 8088 SECStatus rv; 8089 SSL3AlertDescription desc = illegal_parameter; 8090 SECItem cert_types = { siBuffer, NULL, 0 }; 8091 SSLSignatureScheme *signatureSchemes = NULL; 8092 unsigned int signatureSchemeCount = 0; 8093 CERTDistNames ca_list; 8094 8095 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake", 8096 SSL_GETPID(), ss->fd)); 8097 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 8098 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8099 8100 if (ss->ssl3.hs.ws != wait_cert_request) { 8101 desc = unexpected_message; 8102 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST; 8103 goto alert_loser; 8104 } 8105 8106 PORT_Assert(ss->ssl3.clientCertChain == NULL); 8107 PORT_Assert(ss->ssl3.clientCertificate == NULL); 8108 PORT_Assert(ss->ssl3.clientPrivateKey == NULL); 8109 8110 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 8111 isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 8112 rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length); 8113 if (rv != SECSuccess) 8114 goto loser; /* malformed, alert has been sent */ 8115 8116 arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 8117 if (arena == NULL) 8118 goto no_mem; 8119 8120 if (isTLS12) { 8121 rv = ssl_ParseSignatureSchemes(ss, arena, 8122 &signatureSchemes, 8123 &signatureSchemeCount, 8124 &b, &length); 8125 if (rv != SECSuccess) { 8126 PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST); 8127 goto loser; /* malformed, alert has been sent */ 8128 } 8129 if (signatureSchemeCount == 0) { 8130 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM; 8131 desc = handshake_failure; 8132 goto alert_loser; 8133 } 8134 } 8135 8136 rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list); 8137 if (rv != SECSuccess) 8138 goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */ 8139 8140 if (length != 0) 8141 goto alert_loser; /* malformed */ 8142 8143 ss->ssl3.hs.ws = wait_hello_done; 8144 8145 rv = ssl3_BeginHandleCertificateRequest(ss, signatureSchemes, 8146 signatureSchemeCount, &ca_list); 8147 if (rv != SECSuccess) { 8148 PORT_Assert(0); 8149 errCode = SEC_ERROR_LIBRARY_FAILURE; 8150 desc = internal_error; 8151 goto alert_loser; 8152 } 8153 goto done; 8154 8155 no_mem: 8156 rv = SECFailure; 8157 PORT_SetError(SEC_ERROR_NO_MEMORY); 8158 goto done; 8159 8160 alert_loser: 8161 if (isTLS && desc == illegal_parameter) 8162 desc = decode_error; 8163 (void)SSL3_SendAlert(ss, alert_fatal, desc); 8164 loser: 8165 PORT_SetError(errCode); 8166 rv = SECFailure; 8167 done: 8168 if (arena != NULL) 8169 PORT_FreeArena(arena, PR_FALSE); 8170 return rv; 8171 } 8172 8173 static void 8174 ssl3_ClientAuthCallbackOutcome(sslSocket *ss, SECStatus outcome) 8175 { 8176 SECStatus rv; 8177 switch (outcome) { 8178 case SECSuccess: 8179 /* check what the callback function returned */ 8180 if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { 8181 /* we are missing either the key or cert */ 8182 goto send_no_certificate; 8183 } 8184 /* Setting ssl3.clientCertChain non-NULL will cause 8185 * ssl3_HandleServerHelloDone to call SendCertificate. 8186 */ 8187 ss->ssl3.clientCertChain = CERT_CertChainFromCert( 8188 ss->ssl3.clientCertificate, 8189 certUsageSSLClient, PR_FALSE); 8190 if (ss->ssl3.clientCertChain == NULL) { 8191 goto send_no_certificate; 8192 } 8193 if (ss->ssl3.hs.hashType == handshake_hash_record || 8194 ss->ssl3.hs.hashType == handshake_hash_single) { 8195 rv = ssl_PickClientSignatureScheme(ss, 8196 ss->ssl3.clientCertificate, 8197 ss->ssl3.clientPrivateKey, 8198 ss->ssl3.hs.clientAuthSignatureSchemes, 8199 ss->ssl3.hs.clientAuthSignatureSchemesLen, 8200 &ss->ssl3.hs.signatureScheme); 8201 if (rv != SECSuccess) { 8202 /* This should only happen if our schemes changed or 8203 * if an RSA-PSS cert was selected, but the token 8204 * does not support PSS schemes. 8205 */ 8206 goto send_no_certificate; 8207 } 8208 } 8209 break; 8210 8211 case SECFailure: 8212 default: 8213 send_no_certificate: 8214 CERT_DestroyCertificate(ss->ssl3.clientCertificate); 8215 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 8216 ss->ssl3.clientCertificate = NULL; 8217 ss->ssl3.clientPrivateKey = NULL; 8218 if (ss->ssl3.clientCertChain) { 8219 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 8220 ss->ssl3.clientCertChain = NULL; 8221 } 8222 8223 if (ss->version > SSL_LIBRARY_VERSION_3_0) { 8224 ss->ssl3.sendEmptyCert = PR_TRUE; 8225 } else { 8226 (void)SSL3_SendAlert(ss, alert_warning, no_certificate); 8227 } 8228 break; 8229 } 8230 8231 /* Release the cached parameters */ 8232 PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes); 8233 ss->ssl3.hs.clientAuthSignatureSchemes = NULL; 8234 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0; 8235 } 8236 8237 SECStatus 8238 ssl3_BeginHandleCertificateRequest(sslSocket *ss, 8239 const SSLSignatureScheme *signatureSchemes, 8240 unsigned int signatureSchemeCount, 8241 CERTDistNames *ca_list) 8242 { 8243 SECStatus rv; 8244 8245 PR_ASSERT(!ss->ssl3.hs.clientCertificatePending); 8246 8247 /* Should not send a client cert when (non-GREASE) ECH is rejected. */ 8248 if (ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) { 8249 PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)); 8250 rv = SECFailure; 8251 } else if (ss->getClientAuthData != NULL) { 8252 PORT_Assert(signatureSchemes || !signatureSchemeCount); 8253 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == 8254 ssl_preinfo_all); 8255 PORT_Assert(ss->ssl3.clientPrivateKey == NULL); 8256 PORT_Assert(ss->ssl3.clientCertificate == NULL); 8257 PORT_Assert(ss->ssl3.clientCertChain == NULL); 8258 8259 /* Previously cached parameters should be empty */ 8260 PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL); 8261 PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0); 8262 /* 8263 * Peer signatures are only available while in the context of 8264 * of a getClientAuthData callback. It is required for proper 8265 * functioning of SSL_CertIsUsable and SSL_FilterClientCertListBySocket 8266 * Calling these functions outside the context of a getClientAuthData 8267 * callback will result in no filtering.*/ 8268 8269 ss->ssl3.hs.clientAuthSignatureSchemes = PORT_ZNewArray(SSLSignatureScheme, signatureSchemeCount); 8270 if (signatureSchemes) { 8271 PORT_Memcpy(ss->ssl3.hs.clientAuthSignatureSchemes, signatureSchemes, signatureSchemeCount * sizeof(SSLSignatureScheme)); 8272 } 8273 ss->ssl3.hs.clientAuthSignatureSchemesLen = signatureSchemeCount; 8274 8275 rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg, 8276 ss->fd, ca_list, 8277 &ss->ssl3.clientCertificate, 8278 &ss->ssl3.clientPrivateKey); 8279 } else { 8280 rv = SECFailure; /* force it to send a no_certificate alert */ 8281 } 8282 8283 if (rv == SECWouldBlock) { 8284 /* getClientAuthData needs more time (e.g. for user interaction) */ 8285 8286 /* The out parameters should not have changed. */ 8287 PORT_Assert(ss->ssl3.clientCertificate == NULL); 8288 PORT_Assert(ss->ssl3.clientPrivateKey == NULL); 8289 8290 /* Mark the handshake as blocked */ 8291 ss->ssl3.hs.clientCertificatePending = PR_TRUE; 8292 8293 rv = SECSuccess; 8294 } else { 8295 /* getClientAuthData returned SECSuccess or SECFailure immediately, handle accordingly */ 8296 ssl3_ClientAuthCallbackOutcome(ss, rv); 8297 rv = SECSuccess; 8298 } 8299 return rv; 8300 } 8301 8302 /* Invoked by the application when client certificate selection is complete */ 8303 SECStatus 8304 ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate) 8305 { 8306 PORT_Assert(ss->ssl3.hs.clientCertificatePending); 8307 ss->ssl3.hs.clientCertificatePending = PR_FALSE; 8308 8309 ss->ssl3.clientCertificate = clientCertificate; 8310 ss->ssl3.clientPrivateKey = clientPrivateKey; 8311 8312 ssl3_ClientAuthCallbackOutcome(ss, outcome); 8313 8314 /* Continue the handshake */ 8315 PORT_Assert(ss->ssl3.hs.restartTarget); 8316 if (!ss->ssl3.hs.restartTarget) { 8317 FATAL_ERROR(ss, PR_INVALID_STATE_ERROR, internal_error); 8318 return SECFailure; 8319 } 8320 sslRestartTarget target = ss->ssl3.hs.restartTarget; 8321 ss->ssl3.hs.restartTarget = NULL; 8322 return target(ss); 8323 } 8324 8325 static SECStatus 8326 ssl3_CheckFalseStart(sslSocket *ss) 8327 { 8328 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8329 PORT_Assert(!ss->ssl3.hs.authCertificatePending); 8330 PORT_Assert(!ss->ssl3.hs.canFalseStart); 8331 8332 if (!ss->canFalseStartCallback) { 8333 SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", 8334 SSL_GETPID(), ss->fd)); 8335 } else { 8336 SECStatus rv; 8337 8338 rv = ssl_CheckServerRandom(ss); 8339 if (rv != SECSuccess) { 8340 SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade", 8341 SSL_GETPID(), ss->fd)); 8342 goto no_false_start; 8343 } 8344 8345 /* An attacker can control the selected ciphersuite so we only wish to 8346 * do False Start in the case that the selected ciphersuite is 8347 * sufficiently strong that the attack can gain no advantage. 8348 * Therefore we always require an 80-bit cipher. */ 8349 ssl_GetSpecReadLock(ss); 8350 PRBool weakCipher = ss->ssl3.cwSpec->cipherDef->secret_key_size < 10; 8351 ssl_ReleaseSpecReadLock(ss); 8352 if (weakCipher) { 8353 SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", 8354 SSL_GETPID(), ss->fd)); 8355 goto no_false_start; 8356 } 8357 8358 if (ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) { 8359 SSL_TRC(3, ("%d: SSL[%d]: no false start due to lower version after ECH", 8360 SSL_GETPID(), ss->fd)); 8361 goto no_false_start; 8362 } 8363 8364 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == 8365 ssl_preinfo_all); 8366 rv = (ss->canFalseStartCallback)(ss->fd, 8367 ss->canFalseStartCallbackData, 8368 &ss->ssl3.hs.canFalseStart); 8369 if (rv == SECSuccess) { 8370 SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", 8371 SSL_GETPID(), ss->fd, 8372 ss->ssl3.hs.canFalseStart ? "TRUE" 8373 : "FALSE")); 8374 } else { 8375 SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", 8376 SSL_GETPID(), ss->fd, 8377 PR_ErrorToName(PR_GetError()))); 8378 } 8379 return rv; 8380 } 8381 8382 no_false_start: 8383 ss->ssl3.hs.canFalseStart = PR_FALSE; 8384 return SECSuccess; 8385 } 8386 8387 PRBool 8388 ssl3_WaitingForServerSecondRound(sslSocket *ss) 8389 { 8390 PRBool result; 8391 8392 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8393 8394 switch (ss->ssl3.hs.ws) { 8395 case wait_new_session_ticket: 8396 case wait_change_cipher: 8397 case wait_finished: 8398 result = PR_TRUE; 8399 break; 8400 default: 8401 result = PR_FALSE; 8402 break; 8403 } 8404 8405 return result; 8406 } 8407 8408 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); 8409 8410 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered 8411 * a complete ssl3 Server Hello Done message. 8412 * Caller must hold Handshake and RecvBuf locks. 8413 */ 8414 static SECStatus 8415 ssl3_HandleServerHelloDone(sslSocket *ss) 8416 { 8417 SECStatus rv; 8418 SSL3WaitState ws = ss->ssl3.hs.ws; 8419 8420 SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake", 8421 SSL_GETPID(), ss->fd)); 8422 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 8423 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8424 8425 /* Skipping CertificateRequest is always permitted. */ 8426 if (ws != wait_hello_done && 8427 ws != wait_cert_request) { 8428 SSL3_SendAlert(ss, alert_fatal, unexpected_message); 8429 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); 8430 return SECFailure; 8431 } 8432 8433 rv = ssl3_SendClientSecondRound(ss); 8434 8435 return rv; 8436 } 8437 8438 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete. 8439 * 8440 * Caller must hold Handshake and RecvBuf locks. 8441 */ 8442 static SECStatus 8443 ssl3_SendClientSecondRound(sslSocket *ss) 8444 { 8445 SECStatus rv; 8446 PRBool sendClientCert; 8447 8448 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 8449 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8450 8451 sendClientCert = !ss->ssl3.sendEmptyCert && 8452 ss->ssl3.clientCertChain != NULL && 8453 ss->ssl3.clientPrivateKey != NULL; 8454 8455 /* We must wait for the server's certificate to be authenticated before 8456 * sending the client certificate in order to disclosing the client 8457 * certificate to an attacker that does not have a valid cert for the 8458 * domain we are connecting to. 8459 * 8460 * During the initial handshake on a connection, we never send/receive 8461 * application data until we have authenticated the server's certificate; 8462 * i.e. we have fully authenticated the handshake before using the cipher 8463 * specs agreed upon for that handshake. During a renegotiation, we may 8464 * continue sending and receiving application data during the handshake 8465 * interleaved with the handshake records. If we were to send the client's 8466 * second round for a renegotiation before the server's certificate was 8467 * authenticated, then the application data sent/received after this point 8468 * would be using cipher spec that hadn't been authenticated. By waiting 8469 * until the server's certificate has been authenticated during 8470 * renegotiations, we ensure that renegotiations have the same property 8471 * as initial handshakes; i.e. we have fully authenticated the handshake 8472 * before using the cipher specs agreed upon for that handshake for 8473 * application data. 8474 */ 8475 if (ss->ssl3.hs.restartTarget) { 8476 PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); 8477 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 8478 return SECFailure; 8479 } 8480 /* Check whether waiting for client certificate selection OR 8481 waiting on server certificate verification AND 8482 going to send client cert */ 8483 if ((ss->ssl3.hs.clientCertificatePending) || 8484 (ss->ssl3.hs.authCertificatePending && (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone))) { 8485 SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" 8486 " certificate authentication is still pending.", 8487 SSL_GETPID(), ss->fd)); 8488 ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; 8489 PORT_SetError(PR_WOULD_BLOCK_ERROR); 8490 return SECFailure; 8491 } 8492 8493 ssl_GetXmitBufLock(ss); /*******************************/ 8494 8495 if (ss->ssl3.sendEmptyCert) { 8496 ss->ssl3.sendEmptyCert = PR_FALSE; 8497 rv = ssl3_SendEmptyCertificate(ss); 8498 /* Don't send verify */ 8499 if (rv != SECSuccess) { 8500 goto loser; /* error code is set. */ 8501 } 8502 } else if (sendClientCert) { 8503 rv = ssl3_SendCertificate(ss); 8504 if (rv != SECSuccess) { 8505 goto loser; /* error code is set. */ 8506 } 8507 } 8508 8509 rv = ssl3_SendClientKeyExchange(ss); 8510 if (rv != SECSuccess) { 8511 goto loser; /* err is set. */ 8512 } 8513 8514 if (sendClientCert) { 8515 rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey); 8516 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 8517 ss->ssl3.clientPrivateKey = NULL; 8518 if (rv != SECSuccess) { 8519 goto loser; /* err is set. */ 8520 } 8521 } 8522 8523 rv = ssl3_SendChangeCipherSpecs(ss); 8524 if (rv != SECSuccess) { 8525 goto loser; /* err code was set. */ 8526 } 8527 8528 /* This must be done after we've set ss->ssl3.cwSpec in 8529 * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information 8530 * from cwSpec. This must be done before we call ssl3_CheckFalseStart 8531 * because the false start callback (if any) may need the information from 8532 * the functions that depend on this being set. 8533 */ 8534 ss->enoughFirstHsDone = PR_TRUE; 8535 8536 if (!ss->firstHsDone) { 8537 if (ss->opt.enableFalseStart) { 8538 if (!ss->ssl3.hs.authCertificatePending) { 8539 /* When we fix bug 589047, we will need to know whether we are 8540 * false starting before we try to flush the client second 8541 * round to the network. With that in mind, we purposefully 8542 * call ssl3_CheckFalseStart before calling ssl3_SendFinished, 8543 * which includes a call to ssl3_FlushHandshake, so that 8544 * no application develops a reliance on such flushing being 8545 * done before its false start callback is called. 8546 */ 8547 ssl_ReleaseXmitBufLock(ss); 8548 rv = ssl3_CheckFalseStart(ss); 8549 ssl_GetXmitBufLock(ss); 8550 if (rv != SECSuccess) { 8551 goto loser; 8552 } 8553 } else { 8554 /* The certificate authentication and the server's Finished 8555 * message are racing each other. If the certificate 8556 * authentication wins, then we will try to false start in 8557 * ssl3_AuthCertificateComplete. 8558 */ 8559 SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" 8560 " certificate authentication is still pending.", 8561 SSL_GETPID(), ss->fd)); 8562 } 8563 } 8564 } 8565 8566 rv = ssl3_SendFinished(ss, 0); 8567 if (rv != SECSuccess) { 8568 goto loser; /* err code was set. */ 8569 } 8570 8571 ssl_ReleaseXmitBufLock(ss); /*******************************/ 8572 8573 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) 8574 ss->ssl3.hs.ws = wait_new_session_ticket; 8575 else 8576 ss->ssl3.hs.ws = wait_change_cipher; 8577 8578 PORT_Assert(ssl3_WaitingForServerSecondRound(ss)); 8579 8580 return SECSuccess; 8581 8582 loser: 8583 ssl_ReleaseXmitBufLock(ss); 8584 return rv; 8585 } 8586 8587 /* 8588 * Routines used by servers 8589 */ 8590 static SECStatus 8591 ssl3_SendHelloRequest(sslSocket *ss) 8592 { 8593 SECStatus rv; 8594 8595 SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), 8596 ss->fd)); 8597 8598 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8599 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 8600 8601 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0); 8602 if (rv != SECSuccess) { 8603 return rv; /* err set by AppendHandshake */ 8604 } 8605 rv = ssl3_FlushHandshake(ss, 0); 8606 if (rv != SECSuccess) { 8607 return rv; /* error code set by ssl3_FlushHandshake */ 8608 } 8609 ss->ssl3.hs.ws = wait_client_hello; 8610 return SECSuccess; 8611 } 8612 8613 /* 8614 * Called from: 8615 * ssl3_HandleClientHello() 8616 */ 8617 static SECComparison 8618 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) 8619 { 8620 if (!name1 != !name2) { 8621 return SECLessThan; 8622 } 8623 if (!name1) { 8624 return SECEqual; 8625 } 8626 if (name1->type != name2->type) { 8627 return SECLessThan; 8628 } 8629 return SECITEM_CompareItem(name1, name2); 8630 } 8631 8632 /* Sets memory error when returning NULL. 8633 * Called from: 8634 * ssl3_SendClientHello() 8635 * ssl3_HandleServerHello() 8636 * ssl3_HandleClientHello() 8637 * ssl3_HandleV2ClientHello() 8638 */ 8639 sslSessionID * 8640 ssl3_NewSessionID(sslSocket *ss, PRBool is_server) 8641 { 8642 sslSessionID *sid; 8643 8644 sid = PORT_ZNew(sslSessionID); 8645 if (sid == NULL) 8646 return sid; 8647 8648 if (is_server) { 8649 const SECItem *srvName; 8650 SECStatus rv = SECSuccess; 8651 8652 ssl_GetSpecReadLock(ss); /********************************/ 8653 srvName = &ss->ssl3.hs.srvVirtName; 8654 if (srvName->len && srvName->data) { 8655 rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); 8656 } 8657 ssl_ReleaseSpecReadLock(ss); /************************************/ 8658 if (rv != SECSuccess) { 8659 PORT_Free(sid); 8660 return NULL; 8661 } 8662 } 8663 sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); 8664 sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); 8665 sid->addr = ss->sec.ci.peer; 8666 sid->port = ss->sec.ci.port; 8667 sid->references = 1; 8668 sid->cached = never_cached; 8669 sid->version = ss->version; 8670 sid->sigScheme = ssl_sig_none; 8671 8672 sid->u.ssl3.keys.resumable = PR_TRUE; 8673 sid->u.ssl3.policy = SSL_ALLOWED; 8674 sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE; 8675 8676 if (is_server) { 8677 SECStatus rv; 8678 int pid = SSL_GETPID(); 8679 8680 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; 8681 sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; 8682 sid->u.ssl3.sessionID[1] = pid & 0xff; 8683 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, 8684 SSL3_SESSIONID_BYTES - 2); 8685 if (rv != SECSuccess) { 8686 ssl_FreeSID(sid); 8687 ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 8688 return NULL; 8689 } 8690 } 8691 return sid; 8692 } 8693 8694 /* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */ 8695 static SECStatus 8696 ssl3_SendServerHelloSequence(sslSocket *ss) 8697 { 8698 const ssl3KEADef *kea_def; 8699 SECStatus rv; 8700 8701 SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", 8702 SSL_GETPID(), ss->fd)); 8703 8704 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 8705 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 8706 8707 rv = ssl3_SendServerHello(ss); 8708 if (rv != SECSuccess) { 8709 return rv; /* err code is set. */ 8710 } 8711 rv = ssl3_SendCertificate(ss); 8712 if (rv != SECSuccess) { 8713 return rv; /* error code is set. */ 8714 } 8715 rv = ssl3_SendCertificateStatus(ss); 8716 if (rv != SECSuccess) { 8717 return rv; /* error code is set. */ 8718 } 8719 /* We have to do this after the call to ssl3_SendServerHello, 8720 * because kea_def is set up by ssl3_SendServerHello(). 8721 */ 8722 kea_def = ss->ssl3.hs.kea_def; 8723 8724 if (kea_def->ephemeral) { 8725 rv = ssl3_SendServerKeyExchange(ss); 8726 if (rv != SECSuccess) { 8727 return rv; /* err code was set. */ 8728 } 8729 } 8730 8731 if (ss->opt.requestCertificate) { 8732 rv = ssl3_SendCertificateRequest(ss); 8733 if (rv != SECSuccess) { 8734 return rv; /* err code is set. */ 8735 } 8736 } 8737 rv = ssl3_SendServerHelloDone(ss); 8738 if (rv != SECSuccess) { 8739 return rv; /* err code is set. */ 8740 } 8741 8742 ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert 8743 : wait_client_key; 8744 return SECSuccess; 8745 } 8746 8747 /* An empty TLS Renegotiation Info (RI) extension */ 8748 static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 }; 8749 8750 static PRBool 8751 ssl3_KEASupportsTickets(const ssl3KEADef *kea_def) 8752 { 8753 if (kea_def->signKeyType == dsaKey) { 8754 /* TODO: Fix session tickets for DSS. The server code rejects the 8755 * session ticket received from the client. Bug 1174677 */ 8756 return PR_FALSE; 8757 } 8758 return PR_TRUE; 8759 } 8760 8761 static PRBool 8762 ssl3_PeerSupportsCipherSuite(const SECItem *peerSuites, uint16_t suite) 8763 { 8764 for (unsigned int i = 0; i + 1 < peerSuites->len; i += 2) { 8765 PRUint16 suite_i = (peerSuites->data[i] << 8) | peerSuites->data[i + 1]; 8766 if (suite_i == suite) { 8767 return PR_TRUE; 8768 } 8769 } 8770 return PR_FALSE; 8771 } 8772 8773 SECStatus 8774 ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites, 8775 PRUint16 version, PRUint16 *suitep) 8776 { 8777 unsigned int i; 8778 SSLVersionRange vrange = { version, version }; 8779 8780 /* If we negotiated an External PSK and that PSK has a ciphersuite 8781 * configured, we need to constrain our choice. If the client does 8782 * not support it, negotiate a certificate auth suite and fall back. 8783 */ 8784 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 8785 ss->xtnData.selectedPsk && 8786 ss->xtnData.selectedPsk->type == ssl_psk_external && 8787 ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) { 8788 PRUint16 pskSuite = ss->xtnData.selectedPsk->zeroRttSuite; 8789 ssl3CipherSuiteCfg *pskSuiteCfg = ssl_LookupCipherSuiteCfgMutable(pskSuite, 8790 ss->cipherSuites); 8791 if (ssl3_config_match(pskSuiteCfg, ss->ssl3.policy, &vrange, ss) && 8792 ssl3_PeerSupportsCipherSuite(suites, pskSuite)) { 8793 *suitep = pskSuite; 8794 return SECSuccess; 8795 } 8796 } 8797 8798 for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 8799 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 8800 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) { 8801 continue; 8802 } 8803 if (!ssl3_PeerSupportsCipherSuite(suites, suite->cipher_suite)) { 8804 continue; 8805 } 8806 *suitep = suite->cipher_suite; 8807 return SECSuccess; 8808 } 8809 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 8810 return SECFailure; 8811 } 8812 8813 /* Select a cipher suite. 8814 ** 8815 ** NOTE: This suite selection algorithm should be the same as the one in 8816 ** ssl3_HandleV2ClientHello(). 8817 ** 8818 ** If TLS 1.0 is enabled, we could handle the case where the client 8819 ** offered TLS 1.1 but offered only export cipher suites by choosing TLS 8820 ** 1.0 and selecting one of those export cipher suites. However, a secure 8821 ** TLS 1.1 client should not have export cipher suites enabled at all, 8822 ** and a TLS 1.1 client should definitely not be offering *only* export 8823 ** cipher suites. Therefore, we refuse to negotiate export cipher suites 8824 ** with any client that indicates support for TLS 1.1 or higher when we 8825 ** (the server) have TLS 1.1 support enabled. 8826 */ 8827 SECStatus 8828 ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites, 8829 PRBool initHashes) 8830 { 8831 PRUint16 selected; 8832 SECStatus rv; 8833 8834 /* Ensure that only valid cipher suites are enabled. */ 8835 if (ssl3_config_match_init(ss) == 0) { 8836 /* No configured cipher is both supported by PK11 and allowed. 8837 * This is a configuration error, so report handshake failure.*/ 8838 FATAL_ERROR(ss, PORT_GetError(), handshake_failure); 8839 return SECFailure; 8840 } 8841 8842 rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected); 8843 if (rv != SECSuccess) { 8844 return SECFailure; 8845 } 8846 8847 ss->ssl3.hs.cipher_suite = selected; 8848 return ssl3_SetupCipherSuite(ss, initHashes); 8849 } 8850 8851 /* 8852 * Call the SNI config hook. 8853 * 8854 * Called from: 8855 * ssl3_HandleClientHello 8856 * tls13_HandleClientHelloPart2 8857 */ 8858 SECStatus 8859 ssl3_ServerCallSNICallback(sslSocket *ss) 8860 { 8861 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 8862 SSL3AlertDescription desc = illegal_parameter; 8863 int ret = 0; 8864 8865 #ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS 8866 #error("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS") 8867 #endif 8868 if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { 8869 if (ss->firstHsDone) { 8870 /* Check that we don't have the name is current spec 8871 * if this extension was not negotiated on the 2d hs. */ 8872 PRBool passed = PR_TRUE; 8873 ssl_GetSpecReadLock(ss); /*******************************/ 8874 if (ss->ssl3.hs.srvVirtName.data) { 8875 passed = PR_FALSE; 8876 } 8877 ssl_ReleaseSpecReadLock(ss); /***************************/ 8878 if (!passed) { 8879 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 8880 desc = handshake_failure; 8881 goto alert_loser; 8882 } 8883 } 8884 return SECSuccess; 8885 } 8886 8887 if (ss->sniSocketConfig) 8888 do { /* not a loop */ 8889 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == 8890 ssl_preinfo_all); 8891 8892 ret = SSL_SNI_SEND_ALERT; 8893 /* If extension is negotiated, the len of names should > 0. */ 8894 if (ss->xtnData.sniNameArrSize) { 8895 /* Calling client callback to reconfigure the socket. */ 8896 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd, 8897 ss->xtnData.sniNameArr, 8898 ss->xtnData.sniNameArrSize, 8899 ss->sniSocketConfigArg); 8900 } 8901 if (ret <= SSL_SNI_SEND_ALERT) { 8902 /* Application does not know the name or was not able to 8903 * properly reconfigure the socket. */ 8904 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 8905 desc = unrecognized_name; 8906 break; 8907 } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { 8908 SECStatus rv = SECSuccess; 8909 SECItem pwsNameBuf = { 0, NULL, 0 }; 8910 SECItem *pwsName = &pwsNameBuf; 8911 SECItem *cwsName; 8912 8913 ssl_GetSpecWriteLock(ss); /*******************************/ 8914 cwsName = &ss->ssl3.hs.srvVirtName; 8915 /* not allow name change on the 2d HS */ 8916 if (ss->firstHsDone) { 8917 if (ssl3_ServerNameCompare(pwsName, cwsName)) { 8918 ssl_ReleaseSpecWriteLock(ss); /******************/ 8919 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 8920 desc = handshake_failure; 8921 ret = SSL_SNI_SEND_ALERT; 8922 break; 8923 } 8924 } 8925 if (pwsName->data) { 8926 SECITEM_FreeItem(pwsName, PR_FALSE); 8927 } 8928 if (cwsName->data) { 8929 rv = SECITEM_CopyItem(NULL, pwsName, cwsName); 8930 } 8931 ssl_ReleaseSpecWriteLock(ss); /**************************/ 8932 if (rv != SECSuccess) { 8933 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; 8934 desc = internal_error; 8935 ret = SSL_SNI_SEND_ALERT; 8936 break; 8937 } 8938 } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) { 8939 /* Application has configured new socket info. Lets check it 8940 * and save the name. */ 8941 SECStatus rv; 8942 SECItem *name = &ss->xtnData.sniNameArr[ret]; 8943 SECItem *pwsName; 8944 8945 /* get rid of the old name and save the newly picked. */ 8946 /* This code is protected by ssl3HandshakeLock. */ 8947 ssl_GetSpecWriteLock(ss); /*******************************/ 8948 /* not allow name change on the 2d HS */ 8949 if (ss->firstHsDone) { 8950 SECItem *cwsName = &ss->ssl3.hs.srvVirtName; 8951 if (ssl3_ServerNameCompare(name, cwsName)) { 8952 ssl_ReleaseSpecWriteLock(ss); /******************/ 8953 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 8954 desc = handshake_failure; 8955 ret = SSL_SNI_SEND_ALERT; 8956 break; 8957 } 8958 } 8959 pwsName = &ss->ssl3.hs.srvVirtName; 8960 if (pwsName->data) { 8961 SECITEM_FreeItem(pwsName, PR_FALSE); 8962 } 8963 rv = SECITEM_CopyItem(NULL, pwsName, name); 8964 ssl_ReleaseSpecWriteLock(ss); /***************************/ 8965 if (rv != SECSuccess) { 8966 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; 8967 desc = internal_error; 8968 ret = SSL_SNI_SEND_ALERT; 8969 break; 8970 } 8971 /* Need to tell the client that application has picked 8972 * the name from the offered list and reconfigured the socket. 8973 */ 8974 ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn, 8975 ssl_SendEmptyExtension); 8976 } else { 8977 /* Callback returned index outside of the boundary. */ 8978 PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize); 8979 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; 8980 desc = internal_error; 8981 ret = SSL_SNI_SEND_ALERT; 8982 break; 8983 } 8984 } while (0); 8985 ssl3_FreeSniNameArray(&ss->xtnData); 8986 if (ret <= SSL_SNI_SEND_ALERT) { 8987 /* desc and errCode should be set. */ 8988 goto alert_loser; 8989 } 8990 8991 return SECSuccess; 8992 8993 alert_loser: 8994 (void)SSL3_SendAlert(ss, alert_fatal, desc); 8995 PORT_SetError(errCode); 8996 return SECFailure; 8997 } 8998 8999 SECStatus 9000 ssl3_SelectServerCert(sslSocket *ss) 9001 { 9002 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; 9003 PRCList *cursor; 9004 SECStatus rv; 9005 9006 /* If the client didn't include the supported groups extension, assume just 9007 * P-256 support and disable all the other ECDHE groups. This also affects 9008 * ECDHE group selection, but this function is called first. */ 9009 if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) { 9010 unsigned int i; 9011 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) { 9012 if (ss->namedGroupPreferences[i] && 9013 ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh && 9014 ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) { 9015 ss->namedGroupPreferences[i] = NULL; 9016 } 9017 } 9018 } 9019 9020 /* This picks the first certificate that has: 9021 * a) the right authentication method, and 9022 * b) the right named curve (EC only) 9023 * 9024 * We might want to do some sort of ranking here later. For now, it's all 9025 * based on what order they are configured in. */ 9026 for (cursor = PR_NEXT_LINK(&ss->serverCerts); 9027 cursor != &ss->serverCerts; 9028 cursor = PR_NEXT_LINK(cursor)) { 9029 sslServerCert *cert = (sslServerCert *)cursor; 9030 if (kea_def->authKeyType == ssl_auth_rsa_sign) { 9031 /* We consider PSS certificates here as well for TLS 1.2. */ 9032 if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign) && 9033 (!SSL_CERT_IS(cert, ssl_auth_rsa_pss) || 9034 ss->version < SSL_LIBRARY_VERSION_TLS_1_2)) { 9035 continue; 9036 } 9037 } else { 9038 if (!SSL_CERT_IS(cert, kea_def->authKeyType)) { 9039 continue; 9040 } 9041 if (SSL_CERT_IS_EC(cert) && 9042 !ssl_NamedGroupEnabled(ss, cert->namedCurve)) { 9043 continue; 9044 } 9045 } 9046 9047 /* Found one. */ 9048 ss->sec.serverCert = cert; 9049 ss->sec.authKeyBits = cert->serverKeyBits; 9050 9051 /* Don't pick a signature scheme if we aren't going to use it. */ 9052 if (kea_def->signKeyType == nullKey) { 9053 ss->sec.authType = kea_def->authKeyType; 9054 return SECSuccess; 9055 } 9056 9057 rv = ssl3_PickServerSignatureScheme(ss); 9058 if (rv != SECSuccess) { 9059 return SECFailure; 9060 } 9061 ss->sec.authType = 9062 ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme); 9063 return SECSuccess; 9064 } 9065 9066 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 9067 return SECFailure; 9068 } 9069 9070 static SECStatus 9071 ssl_GenerateServerRandom(sslSocket *ss) 9072 { 9073 SECStatus rv; 9074 PRUint8 *downgradeSentinel; 9075 9076 rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random); 9077 if (rv != SECSuccess) { 9078 return SECFailure; 9079 } 9080 9081 if (ss->version == ss->vrange.max) { 9082 return SECSuccess; 9083 } 9084 9085 /* 9086 * [RFC 8446 Section 4.1.3]. 9087 * 9088 * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a 9089 * ClientHello MUST set the last 8 bytes of their Random value specially in 9090 * their ServerHello. 9091 * 9092 * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of 9093 * their Random value to the bytes: 9094 * 9095 * 44 4F 57 4E 47 52 44 01 9096 * 9097 * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2 9098 * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to 9099 * the bytes: 9100 * 9101 * 44 4F 57 4E 47 52 44 00 9102 */ 9103 downgradeSentinel = 9104 ss->ssl3.hs.server_random + 9105 SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random); 9106 if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2) { 9107 switch (ss->version) { 9108 case SSL_LIBRARY_VERSION_TLS_1_2: 9109 /* vrange.max > 1.2, since we didn't early exit above. */ 9110 PORT_Memcpy(downgradeSentinel, 9111 tls12_downgrade_random, sizeof(tls12_downgrade_random)); 9112 break; 9113 case SSL_LIBRARY_VERSION_TLS_1_1: 9114 case SSL_LIBRARY_VERSION_TLS_1_0: 9115 PORT_Memcpy(downgradeSentinel, 9116 tls1_downgrade_random, sizeof(tls1_downgrade_random)); 9117 break; 9118 default: 9119 /* Do not change random. */ 9120 break; 9121 } 9122 } 9123 9124 return SECSuccess; 9125 } 9126 9127 SECStatus 9128 ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes, 9129 SECItem *cookieBytes, SECItem *suites, SECItem *comps) 9130 { 9131 SECStatus rv; 9132 PRUint32 tmp; 9133 rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length); 9134 if (rv != SECSuccess) { 9135 return SECFailure; /* malformed, alert already sent */ 9136 } 9137 9138 /* Translate the version. */ 9139 if (IS_DTLS(ss)) { 9140 ss->clientHelloVersion = dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); 9141 } else { 9142 ss->clientHelloVersion = (SSL3ProtocolVersion)tmp; 9143 } 9144 9145 /* Grab the client random data. */ 9146 rv = ssl3_ConsumeHandshake( 9147 ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, b, length); 9148 if (rv != SECSuccess) { 9149 return SECFailure; /* malformed */ 9150 } 9151 9152 /* Grab the client's SID, if present. */ 9153 rv = ssl3_ConsumeHandshakeVariable(ss, sidBytes, 1, b, length); 9154 /* Check that the SID has the format: opaque legacy_session_id<0..32>, as 9155 * specified in RFC8446, Section 4.1.2. */ 9156 if (rv != SECSuccess || sidBytes->len > SSL3_SESSIONID_BYTES) { 9157 return SECFailure; /* malformed */ 9158 } 9159 9160 /* Grab the client's cookie, if present. It is checked after version negotiation. */ 9161 if (IS_DTLS(ss)) { 9162 rv = ssl3_ConsumeHandshakeVariable(ss, cookieBytes, 1, b, length); 9163 if (rv != SECSuccess) { 9164 return SECFailure; /* malformed */ 9165 } 9166 } 9167 9168 /* Grab the list of cipher suites. */ 9169 rv = ssl3_ConsumeHandshakeVariable(ss, suites, 2, b, length); 9170 if (rv != SECSuccess) { 9171 return SECFailure; /* malformed */ 9172 } 9173 9174 /* Grab the list of compression methods. */ 9175 rv = ssl3_ConsumeHandshakeVariable(ss, comps, 1, b, length); 9176 if (rv != SECSuccess) { 9177 return SECFailure; /* malformed */ 9178 } 9179 return SECSuccess; 9180 } 9181 9182 static SECStatus 9183 ssl3_ValidatePreambleWithVersion(sslSocket *ss, const SECItem *sidBytes, const SECItem *comps, 9184 const SECItem *cookieBytes) 9185 { 9186 SECStatus rv; 9187 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 9188 if (sidBytes->len > 0 && !IS_DTLS(ss)) { 9189 SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE); 9190 rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, sidBytes); 9191 if (rv != SECSuccess) { 9192 FATAL_ERROR(ss, PORT_GetError(), internal_error); 9193 return SECFailure; 9194 } 9195 } 9196 9197 /* TLS 1.3 requires that compression include only null. */ 9198 if (comps->len != 1 || comps->data[0] != ssl_compression_null) { 9199 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter); 9200 return SECFailure; 9201 } 9202 9203 /* receivedCcs is only valid if we sent an HRR. */ 9204 if (ss->ssl3.hs.receivedCcs && !ss->ssl3.hs.helloRetry) { 9205 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message); 9206 return SECFailure; 9207 } 9208 9209 /* A DTLS 1.3-only client MUST set the legacy_cookie field to zero length. 9210 * If a DTLS 1.3 ClientHello is received with any other value in this field, 9211 * the server MUST abort the handshake with an "illegal_parameter" alert. */ 9212 if (IS_DTLS(ss) && cookieBytes->len != 0) { 9213 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter); 9214 return SECFailure; 9215 } 9216 } else { 9217 /* ECH not possible here. */ 9218 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech; 9219 9220 /* HRR and ECH are TLS1.3-only. We ignore the Cookie extension here. */ 9221 if (ss->ssl3.hs.helloRetry) { 9222 FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version); 9223 return SECFailure; 9224 } 9225 9226 /* receivedCcs is only valid if we sent an HRR. */ 9227 if (ss->ssl3.hs.receivedCcs) { 9228 FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message); 9229 return SECFailure; 9230 } 9231 9232 /* TLS versions prior to 1.3 must include null somewhere. */ 9233 if (comps->len < 1 || 9234 !memchr(comps->data, ssl_compression_null, comps->len)) { 9235 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter); 9236 return SECFailure; 9237 } 9238 9239 /* We never send cookies in DTLS 1.2. */ 9240 if (IS_DTLS(ss) && cookieBytes->len != 0) { 9241 FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter); 9242 return SECFailure; 9243 } 9244 } 9245 9246 return SECSuccess; 9247 } 9248 9249 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 9250 * ssl3 Client Hello message. 9251 * Caller must hold Handshake and RecvBuf locks. 9252 */ 9253 static SECStatus 9254 ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length) 9255 { 9256 sslSessionID *sid = NULL; 9257 unsigned int i; 9258 SECStatus rv; 9259 PRUint32 extensionLength; 9260 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 9261 SSL3AlertDescription desc = illegal_parameter; 9262 SSL3AlertLevel level = alert_fatal; 9263 TLSExtension *versionExtension; 9264 SECItem sidBytes = { siBuffer, NULL, 0 }; 9265 SECItem cookieBytes = { siBuffer, NULL, 0 }; 9266 SECItem suites = { siBuffer, NULL, 0 }; 9267 SECItem comps = { siBuffer, NULL, 0 }; 9268 SECItem *echInner = NULL; 9269 PRBool isTLS13; 9270 const PRUint8 *savedMsg = b; 9271 const PRUint32 savedLen = length; 9272 9273 SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake", 9274 SSL_GETPID(), ss->fd)); 9275 9276 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 9277 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 9278 ss->ssl3.hs.preliminaryInfo = 0; 9279 9280 if (!ss->sec.isServer || 9281 (ss->ssl3.hs.ws != wait_client_hello && 9282 ss->ssl3.hs.ws != idle_handshake)) { 9283 desc = unexpected_message; 9284 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; 9285 goto alert_loser; 9286 } 9287 if (ss->ssl3.hs.ws == idle_handshake) { 9288 /* Refuse re-handshake when we have already negotiated TLS 1.3. */ 9289 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 9290 desc = unexpected_message; 9291 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 9292 goto alert_loser; 9293 } 9294 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 9295 desc = no_renegotiation; 9296 level = alert_warning; 9297 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 9298 goto alert_loser; 9299 } 9300 } 9301 9302 /* We should always be in a fresh state. */ 9303 SSL_ASSERT_HASHES_EMPTY(ss); 9304 9305 /* Get peer name of client */ 9306 rv = ssl_GetPeerInfo(ss); 9307 if (rv != SECSuccess) { 9308 return rv; /* error code is set. */ 9309 } 9310 9311 /* We might be starting session renegotiation in which case we should 9312 * clear previous state. 9313 */ 9314 ssl3_ResetExtensionData(&ss->xtnData, ss); 9315 ss->statelessResume = PR_FALSE; 9316 9317 if (IS_DTLS(ss)) { 9318 dtls_RehandshakeCleanup(ss); 9319 } 9320 9321 rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &sidBytes, 9322 &cookieBytes, &suites, &comps); 9323 if (rv != SECSuccess) { 9324 goto loser; /* malformed */ 9325 } 9326 9327 /* Handle TLS hello extensions for SSL3 & TLS. We do not know if 9328 * we are restarting a previous session until extensions have been 9329 * parsed, since we might have received a SessionTicket extension. 9330 * Note: we allow extensions even when negotiating SSL3 for the sake 9331 * of interoperability (and backwards compatibility). 9332 */ 9333 if (length) { 9334 /* Get length of hello extensions */ 9335 rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length); 9336 if (rv != SECSuccess) { 9337 goto loser; /* alert already sent */ 9338 } 9339 if (extensionLength != length) { 9340 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 9341 desc = decode_error; 9342 goto alert_loser; 9343 } 9344 9345 rv = ssl3_ParseExtensions(ss, &b, &length); 9346 if (rv != SECSuccess) { 9347 goto loser; /* malformed */ 9348 } 9349 } 9350 9351 versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn); 9352 if (versionExtension) { 9353 rv = tls13_NegotiateVersion(ss, versionExtension); 9354 if (rv != SECSuccess) { 9355 errCode = PORT_GetError(); 9356 desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter; 9357 goto alert_loser; 9358 } 9359 } else { 9360 /* The PR_MIN here ensures that we never negotiate 1.3 if the 9361 * peer didn't offer "supported_versions". */ 9362 rv = ssl3_NegotiateVersion(ss, 9363 PR_MIN(ss->clientHelloVersion, 9364 SSL_LIBRARY_VERSION_TLS_1_2), 9365 PR_TRUE); 9366 /* Send protocol version alert if the ClientHello.legacy_version is not 9367 * supported by the server. 9368 * 9369 * If the "supported_versions" extension is absent and the server only 9370 * supports versions greater than ClientHello.legacy_version, the 9371 * server MUST abort the handshake with a "protocol_version" alert 9372 * [RFC8446, Appendix D.2]. */ 9373 if (rv != SECSuccess) { 9374 desc = protocol_version; 9375 errCode = SSL_ERROR_UNSUPPORTED_VERSION; 9376 goto alert_loser; 9377 } 9378 } 9379 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; 9380 9381 /* Update the write spec to match the selected version. */ 9382 if (!ss->firstHsDone) { 9383 ssl_GetSpecWriteLock(ss); 9384 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec); 9385 ssl_ReleaseSpecWriteLock(ss); 9386 } 9387 9388 isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; 9389 if (isTLS13) { 9390 if (ss->firstHsDone) { 9391 desc = unexpected_message; 9392 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 9393 goto alert_loser; 9394 } 9395 9396 /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */ 9397 if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) { 9398 ss->ssl3.hs.helloRetry = PR_TRUE; 9399 } 9400 9401 rv = tls13_MaybeHandleEch(ss, savedMsg, savedLen, &sidBytes, 9402 &comps, &cookieBytes, &suites, &echInner); 9403 if (rv != SECSuccess) { 9404 errCode = PORT_GetError(); 9405 goto loser; /* code set, alert sent. */ 9406 } 9407 } 9408 9409 rv = ssl3_ValidatePreambleWithVersion(ss, &sidBytes, &comps, &cookieBytes); 9410 if (rv != SECSuccess) { 9411 errCode = PORT_GetError(); 9412 goto loser; /* code set, alert sent. */ 9413 } 9414 9415 /* Now parse the rest of the extensions. */ 9416 rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello); 9417 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions); 9418 if (rv != SECSuccess) { 9419 if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) { 9420 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM; 9421 } 9422 goto loser; /* malformed */ 9423 } 9424 9425 /* If the ClientHello version is less than our maximum version, check for a 9426 * TLS_FALLBACK_SCSV and reject the connection if found. */ 9427 if (ss->vrange.max > ss->version) { 9428 for (i = 0; i + 1 < suites.len; i += 2) { 9429 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 9430 if (suite_i != TLS_FALLBACK_SCSV) 9431 continue; 9432 desc = inappropriate_fallback; 9433 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; 9434 goto alert_loser; 9435 } 9436 } 9437 9438 if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 9439 /* If we didn't receive an RI extension, look for the SCSV, 9440 * and if found, treat it just like an empty RI extension 9441 * by processing a local copy of an empty RI extension. 9442 */ 9443 for (i = 0; i + 1 < suites.len; i += 2) { 9444 PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 9445 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { 9446 PRUint8 *b2 = (PRUint8 *)emptyRIext; 9447 PRUint32 L2 = sizeof emptyRIext; 9448 (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello); 9449 break; 9450 } 9451 } 9452 } 9453 9454 /* The check for renegotiation in TLS 1.3 is earlier. */ 9455 if (!isTLS13) { 9456 if (ss->firstHsDone && 9457 (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN || 9458 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && 9459 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 9460 desc = no_renegotiation; 9461 level = alert_warning; 9462 errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 9463 goto alert_loser; 9464 } 9465 if ((ss->opt.requireSafeNegotiation || 9466 (ss->firstHsDone && ss->peerRequestedProtection)) && 9467 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 9468 desc = handshake_failure; 9469 errCode = SSL_ERROR_UNSAFE_NEGOTIATION; 9470 goto alert_loser; 9471 } 9472 } 9473 9474 /* We do stateful resumes only if we are in TLS < 1.3 and 9475 * either of the following conditions are satisfied: 9476 * (1) the client does not support the session ticket extension, or 9477 * (2) the client support the session ticket extension, but sent an 9478 * empty ticket. 9479 */ 9480 if (!isTLS13 && 9481 (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) || 9482 ss->xtnData.emptySessionTicket)) { 9483 if (sidBytes.len > 0 && !ss->opt.noCache) { 9484 SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x", 9485 SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], 9486 ss->sec.ci.peer.pr_s6_addr32[1], 9487 ss->sec.ci.peer.pr_s6_addr32[2], 9488 ss->sec.ci.peer.pr_s6_addr32[3])); 9489 if (ssl_sid_lookup) { 9490 sid = (*ssl_sid_lookup)(ssl_Time(ss), &ss->sec.ci.peer, 9491 sidBytes.data, sidBytes.len, ss->dbHandle); 9492 } else { 9493 errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; 9494 goto loser; 9495 } 9496 } 9497 } else if (ss->statelessResume) { 9498 /* Fill in the client's session ID if doing a stateless resume. 9499 * (When doing stateless resumes, server echos client's SessionID.) 9500 * This branch also handles TLS 1.3 resumption-PSK. 9501 */ 9502 sid = ss->sec.ci.sid; 9503 PORT_Assert(sid != NULL); /* Should have already been filled in.*/ 9504 9505 if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { 9506 sid->u.ssl3.sessionIDLength = sidBytes.len; 9507 PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, 9508 sidBytes.len); 9509 sid->u.ssl3.sessionIDLength = sidBytes.len; 9510 } else { 9511 sid->u.ssl3.sessionIDLength = 0; 9512 } 9513 ss->sec.ci.sid = NULL; 9514 } 9515 9516 /* Free a potentially leftover session ID from a previous handshake. */ 9517 if (ss->sec.ci.sid) { 9518 ssl_FreeSID(ss->sec.ci.sid); 9519 ss->sec.ci.sid = NULL; 9520 } 9521 9522 if (sid != NULL) { 9523 /* We've found a session cache entry for this client. 9524 * Now, if we're going to require a client-auth cert, 9525 * and we don't already have this client's cert in the session cache, 9526 * and this is the first handshake on this connection (not a redo), 9527 * then drop this old cache entry and start a new session. 9528 */ 9529 if ((sid->peerCert == NULL) && ss->opt.requestCertificate && 9530 ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || 9531 (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || 9532 ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) && 9533 !ss->firstHsDone))) { 9534 9535 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok); 9536 ssl_FreeSID(sid); 9537 sid = NULL; 9538 ss->statelessResume = PR_FALSE; 9539 } 9540 } 9541 9542 if (IS_DTLS(ss)) { 9543 ssl3_DisableNonDTLSSuites(ss); 9544 dtls_ReceivedFirstMessageInFlight(ss); 9545 } 9546 9547 if (isTLS13) { 9548 rv = tls13_HandleClientHelloPart2(ss, &suites, sid, 9549 ss->ssl3.hs.echAccepted ? echInner->data : savedMsg, 9550 ss->ssl3.hs.echAccepted ? echInner->len : savedLen); 9551 SECITEM_FreeItem(echInner, PR_TRUE); 9552 echInner = NULL; 9553 } else { 9554 rv = ssl3_HandleClientHelloPart2(ss, &suites, sid, 9555 savedMsg, savedLen); 9556 } 9557 if (rv != SECSuccess) { 9558 errCode = PORT_GetError(); 9559 goto loser; 9560 } 9561 return SECSuccess; 9562 9563 alert_loser: 9564 (void)SSL3_SendAlert(ss, level, desc); 9565 /* FALLTHRU */ 9566 loser: 9567 SECITEM_FreeItem(echInner, PR_TRUE); 9568 PORT_SetError(errCode); 9569 return SECFailure; 9570 } 9571 9572 /* unwrap helper function to handle the case where the wrapKey doesn't wind 9573 * up in the correct token for the master secret */ 9574 PK11SymKey * 9575 ssl_unwrapSymKey(PK11SymKey *wrapKey, 9576 CK_MECHANISM_TYPE wrapType, SECItem *param, 9577 SECItem *wrappedKey, 9578 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, 9579 int keySize, CK_FLAGS keyFlags, void *pinArg) 9580 { 9581 PK11SymKey *unwrappedKey; 9582 9583 /* unwrap the master secret. */ 9584 unwrappedKey = PK11_UnwrapSymKeyWithFlags(wrapKey, wrapType, param, 9585 wrappedKey, target, operation, keySize, 9586 keyFlags); 9587 if (!unwrappedKey) { 9588 PK11SlotInfo *targetSlot = PK11_GetBestSlot(target, pinArg); 9589 PK11SymKey *newWrapKey; 9590 9591 /* it's possible that we failed to unwrap because the wrapKey is in 9592 * a slot that can't handle target. Move the wrapKey to a slot that 9593 * can handle this mechanism and retry the operation */ 9594 if (targetSlot == NULL) { 9595 return NULL; 9596 } 9597 newWrapKey = PK11_MoveSymKey(targetSlot, CKA_UNWRAP, 0, 9598 PR_FALSE, wrapKey); 9599 PK11_FreeSlot(targetSlot); 9600 if (newWrapKey == NULL) { 9601 return NULL; 9602 } 9603 unwrappedKey = PK11_UnwrapSymKeyWithFlags(newWrapKey, wrapType, param, 9604 wrappedKey, target, operation, keySize, 9605 keyFlags); 9606 PK11_FreeSymKey(newWrapKey); 9607 } 9608 return unwrappedKey; 9609 } 9610 9611 static SECStatus 9612 ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms) 9613 { 9614 PK11SymKey *wrapKey; 9615 CK_FLAGS keyFlags = 0; 9616 SECItem wrappedMS = { 9617 siBuffer, 9618 sid->u.ssl3.keys.wrapped_master_secret, 9619 sid->u.ssl3.keys.wrapped_master_secret_len 9620 }; 9621 9622 wrapKey = ssl3_GetWrappingKey(ss, NULL, sid->u.ssl3.masterWrapMech, 9623 ss->pkcs11PinArg); 9624 if (!wrapKey) { 9625 return SECFailure; 9626 } 9627 9628 if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ 9629 keyFlags = CKF_SIGN | CKF_VERIFY; 9630 } 9631 9632 *ms = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech, NULL, 9633 &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, 9634 CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, 9635 keyFlags, ss->pkcs11PinArg); 9636 PK11_FreeSymKey(wrapKey); 9637 if (!*ms) { 9638 SSL_TRC(10, ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx", 9639 SSL_GETPID(), ss->fd, sid->u.ssl3.masterWrapMech)); 9640 return SECFailure; 9641 } 9642 return SECSuccess; 9643 } 9644 9645 static SECStatus 9646 ssl3_HandleClientHelloPart2(sslSocket *ss, 9647 SECItem *suites, 9648 sslSessionID *sid, 9649 const PRUint8 *msg, 9650 unsigned int len) 9651 { 9652 PRBool haveXmitBufLock = PR_FALSE; 9653 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 9654 SSL3AlertDescription desc = illegal_parameter; 9655 SECStatus rv; 9656 unsigned int i; 9657 unsigned int j; 9658 9659 rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len); 9660 if (rv != SECSuccess) { 9661 errCode = SEC_ERROR_LIBRARY_FAILURE; 9662 desc = internal_error; 9663 goto alert_loser; 9664 } 9665 9666 /* If we already have a session for this client, be sure to pick the same 9667 ** cipher suite we picked before. This is not a loop, despite appearances. 9668 */ 9669 if (sid) 9670 do { 9671 ssl3CipherSuiteCfg *suite; 9672 SSLVersionRange vrange = { ss->version, ss->version }; 9673 9674 suite = ss->cipherSuites; 9675 /* Find the entry for the cipher suite used in the cached session. */ 9676 for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { 9677 if (suite->cipher_suite == sid->u.ssl3.cipherSuite) 9678 break; 9679 } 9680 9681 if (j == 0) 9682 break; 9683 9684 /* Double check that the cached cipher suite is still enabled, 9685 * implemented, and allowed by policy. Might have been disabled. 9686 */ 9687 if (ssl3_config_match_init(ss) == 0) { 9688 desc = handshake_failure; 9689 errCode = PORT_GetError(); 9690 goto alert_loser; 9691 } 9692 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) 9693 break; 9694 9695 /* Double check that the cached cipher suite is in the client's 9696 * list. If it isn't, fall through and start a new session. */ 9697 for (i = 0; i + 1 < suites->len; i += 2) { 9698 PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1]; 9699 if (suite_i == suite->cipher_suite) { 9700 ss->ssl3.hs.cipher_suite = suite_i; 9701 rv = ssl3_SetupCipherSuite(ss, PR_TRUE); 9702 if (rv != SECSuccess) { 9703 desc = internal_error; 9704 errCode = PORT_GetError(); 9705 goto alert_loser; 9706 } 9707 9708 goto cipher_found; 9709 } 9710 } 9711 } while (0); 9712 /* START A NEW SESSION */ 9713 9714 rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE); 9715 if (rv != SECSuccess) { 9716 desc = handshake_failure; 9717 errCode = PORT_GetError(); 9718 goto alert_loser; 9719 } 9720 9721 cipher_found: 9722 suites->data = NULL; 9723 9724 /* If there are any failures while processing the old sid, 9725 * we don't consider them to be errors. Instead, We just behave 9726 * as if the client had sent us no sid to begin with, and make a new one. 9727 * The exception here is attempts to resume extended_master_secret 9728 * sessions without the extension, which causes an alert. 9729 */ 9730 if (sid != NULL) 9731 do { 9732 PK11SymKey *masterSecret; 9733 9734 if (sid->version != ss->version || 9735 sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) { 9736 break; /* not an error */ 9737 } 9738 9739 /* server sids don't remember the server cert we previously sent, 9740 ** but they do remember the slot we originally used, so we 9741 ** can locate it again, provided that the current ssl socket 9742 ** has had its server certs configured the same as the previous one. 9743 */ 9744 ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve); 9745 if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) { 9746 /* A compatible certificate must not have been configured. It 9747 * might not be the same certificate, but we only find that out 9748 * when the ticket fails to decrypt. */ 9749 break; 9750 } 9751 9752 /* [draft-ietf-tls-session-hash-06; Section 5.3] 9753 * o If the original session did not use the "extended_master_secret" 9754 * extension but the new ClientHello contains the extension, then the 9755 * server MUST NOT perform the abbreviated handshake. Instead, it 9756 * SHOULD continue with a full handshake (as described in 9757 * Section 5.2) to negotiate a new session. 9758 * 9759 * o If the original session used the "extended_master_secret" 9760 * extension but the new ClientHello does not contain the extension, 9761 * the server MUST abort the abbreviated handshake. 9762 */ 9763 if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) { 9764 if (!sid->u.ssl3.keys.extendedMasterSecretUsed) { 9765 break; /* not an error */ 9766 } 9767 } else { 9768 if (sid->u.ssl3.keys.extendedMasterSecretUsed) { 9769 /* Note: we do not destroy the session */ 9770 desc = handshake_failure; 9771 errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET; 9772 goto alert_loser; 9773 } 9774 } 9775 9776 if (ss->sec.ci.sid) { 9777 ssl_UncacheSessionID(ss); 9778 PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */ 9779 if (ss->sec.ci.sid != sid) { 9780 ssl_FreeSID(ss->sec.ci.sid); 9781 } 9782 ss->sec.ci.sid = NULL; 9783 } 9784 9785 /* we need to resurrect the master secret.... */ 9786 rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret); 9787 if (rv != SECSuccess) { 9788 break; /* not an error */ 9789 } 9790 9791 ss->sec.ci.sid = sid; 9792 if (sid->peerCert != NULL) { 9793 ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); 9794 } 9795 9796 /* 9797 * Old SID passed all tests, so resume this old session. 9798 */ 9799 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits); 9800 if (ss->statelessResume) 9801 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes); 9802 ss->ssl3.hs.isResuming = PR_TRUE; 9803 9804 ss->sec.authType = sid->authType; 9805 ss->sec.authKeyBits = sid->authKeyBits; 9806 ss->sec.keaType = sid->keaType; 9807 ss->sec.keaKeyBits = sid->keaKeyBits; 9808 ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup); 9809 ss->sec.signatureScheme = sid->sigScheme; 9810 9811 ss->sec.localCert = 9812 CERT_DupCertificate(ss->sec.serverCert->serverCert); 9813 9814 /* Copy cached name in to pending spec */ 9815 if (sid != NULL && 9816 sid->version > SSL_LIBRARY_VERSION_3_0 && 9817 sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { 9818 /* Set server name from sid */ 9819 SECItem *sidName = &sid->u.ssl3.srvName; 9820 SECItem *pwsName = &ss->ssl3.hs.srvVirtName; 9821 if (pwsName->data) { 9822 SECITEM_FreeItem(pwsName, PR_FALSE); 9823 } 9824 rv = SECITEM_CopyItem(NULL, pwsName, sidName); 9825 if (rv != SECSuccess) { 9826 errCode = PORT_GetError(); 9827 desc = internal_error; 9828 goto alert_loser; 9829 } 9830 } 9831 9832 /* Clean up sni name array */ 9833 ssl3_FreeSniNameArray(&ss->xtnData); 9834 9835 ssl_GetXmitBufLock(ss); 9836 haveXmitBufLock = PR_TRUE; 9837 9838 rv = ssl3_SendServerHello(ss); 9839 if (rv != SECSuccess) { 9840 errCode = PORT_GetError(); 9841 goto loser; 9842 } 9843 9844 /* We are re-using the old MS, so no need to derive again. */ 9845 rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE); 9846 if (rv != SECSuccess) { 9847 errCode = PORT_GetError(); 9848 goto loser; 9849 } 9850 9851 rv = ssl3_SendChangeCipherSpecs(ss); 9852 if (rv != SECSuccess) { 9853 errCode = PORT_GetError(); 9854 goto loser; 9855 } 9856 rv = ssl3_SendFinished(ss, 0); 9857 ss->ssl3.hs.ws = wait_change_cipher; 9858 if (rv != SECSuccess) { 9859 errCode = PORT_GetError(); 9860 goto loser; 9861 } 9862 9863 ssl_ReleaseXmitBufLock(ss); 9864 9865 return SECSuccess; 9866 } while (0); 9867 9868 if (sid) { /* we had a sid, but it's no longer valid, free it */ 9869 ss->statelessResume = PR_FALSE; 9870 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok); 9871 ssl_UncacheSessionID(ss); 9872 ssl_FreeSID(sid); 9873 sid = NULL; 9874 } 9875 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses); 9876 9877 /* We only send a session ticket extension if the client supports 9878 * the extension and we are unable to resume. 9879 * 9880 * TODO: send a session ticket if performing a stateful 9881 * resumption. (As per RFC4507, a server may issue a session 9882 * ticket while doing a (stateless or stateful) session resume, 9883 * but OpenSSL-0.9.8g does not accept session tickets while 9884 * resuming.) 9885 */ 9886 if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && 9887 ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) { 9888 ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn, 9889 ssl_SendEmptyExtension); 9890 } 9891 9892 rv = ssl3_ServerCallSNICallback(ss); 9893 if (rv != SECSuccess) { 9894 /* The alert has already been sent. */ 9895 errCode = PORT_GetError(); 9896 goto loser; 9897 } 9898 9899 rv = ssl3_SelectServerCert(ss); 9900 if (rv != SECSuccess) { 9901 errCode = PORT_GetError(); 9902 desc = handshake_failure; 9903 goto alert_loser; 9904 } 9905 9906 sid = ssl3_NewSessionID(ss, PR_TRUE); 9907 if (sid == NULL) { 9908 errCode = PORT_GetError(); 9909 goto loser; /* memory error is set. */ 9910 } 9911 ss->sec.ci.sid = sid; 9912 9913 sid->u.ssl3.keys.extendedMasterSecretUsed = 9914 ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); 9915 ss->ssl3.hs.isResuming = PR_FALSE; 9916 9917 ssl_GetXmitBufLock(ss); 9918 rv = ssl3_SendServerHelloSequence(ss); 9919 ssl_ReleaseXmitBufLock(ss); 9920 if (rv != SECSuccess) { 9921 errCode = PORT_GetError(); 9922 desc = handshake_failure; 9923 goto alert_loser; 9924 } 9925 9926 return SECSuccess; 9927 9928 alert_loser: 9929 (void)SSL3_SendAlert(ss, alert_fatal, desc); 9930 /* FALLTHRU */ 9931 loser: 9932 if (sid && sid != ss->sec.ci.sid) { 9933 ssl_UncacheSessionID(ss); 9934 ssl_FreeSID(sid); 9935 } 9936 9937 if (haveXmitBufLock) { 9938 ssl_ReleaseXmitBufLock(ss); 9939 } 9940 9941 PORT_SetError(errCode); 9942 return SECFailure; 9943 } 9944 9945 /* 9946 * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes 9947 * in asking to use the V3 handshake. 9948 */ 9949 SECStatus 9950 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length, 9951 PRUint8 padding) 9952 { 9953 sslSessionID *sid = NULL; 9954 unsigned char *suites; 9955 unsigned char *random; 9956 SSL3ProtocolVersion version; 9957 SECStatus rv; 9958 unsigned int i; 9959 unsigned int j; 9960 unsigned int sid_length; 9961 unsigned int suite_length; 9962 unsigned int rand_length; 9963 int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 9964 SSL3AlertDescription desc = handshake_failure; 9965 unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES; 9966 9967 SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd)); 9968 9969 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 9970 9971 ssl_GetSSL3HandshakeLock(ss); 9972 9973 version = (buffer[1] << 8) | buffer[2]; 9974 if (version < SSL_LIBRARY_VERSION_3_0) { 9975 goto loser; 9976 } 9977 9978 ssl3_RestartHandshakeHashes(ss); 9979 9980 if (ss->ssl3.hs.ws != wait_client_hello) { 9981 desc = unexpected_message; 9982 errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; 9983 goto alert_loser; 9984 } 9985 9986 total += suite_length = (buffer[3] << 8) | buffer[4]; 9987 total += sid_length = (buffer[5] << 8) | buffer[6]; 9988 total += rand_length = (buffer[7] << 8) | buffer[8]; 9989 total += padding; 9990 ss->clientHelloVersion = version; 9991 9992 if (version >= SSL_LIBRARY_VERSION_TLS_1_3) { 9993 /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3 9994 * ClientHello using the backwards-compatible format. */ 9995 desc = illegal_parameter; 9996 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 9997 goto alert_loser; 9998 } 9999 10000 rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); 10001 if (rv != SECSuccess) { 10002 /* send back which ever alert client will understand. */ 10003 desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 10004 : handshake_failure; 10005 errCode = SSL_ERROR_UNSUPPORTED_VERSION; 10006 goto alert_loser; 10007 } 10008 /* ECH not possible here. */ 10009 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech; 10010 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; 10011 if (!ss->firstHsDone) { 10012 ssl_GetSpecWriteLock(ss); 10013 ssl_SetSpecVersions(ss, ss->ssl3.cwSpec); 10014 ssl_ReleaseSpecWriteLock(ss); 10015 } 10016 10017 /* if we get a non-zero SID, just ignore it. */ 10018 if (length != total) { 10019 SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", 10020 SSL_GETPID(), ss->fd, length, total)); 10021 desc = illegal_parameter; 10022 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 10023 goto alert_loser; 10024 } 10025 10026 suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES; 10027 random = suites + suite_length + sid_length; 10028 10029 if (rand_length < SSL_MIN_CHALLENGE_BYTES || 10030 rand_length > SSL_MAX_CHALLENGE_BYTES) { 10031 desc = illegal_parameter; 10032 errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 10033 goto alert_loser; 10034 } 10035 10036 PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH); 10037 10038 PORT_Memset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); 10039 PORT_Memcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH - rand_length], 10040 random, rand_length); 10041 10042 PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random, 10043 SSL3_RANDOM_LENGTH)); 10044 10045 if (ssl3_config_match_init(ss) == 0) { 10046 errCode = PORT_GetError(); /* error code is already set. */ 10047 goto alert_loser; 10048 } 10049 10050 /* Select a cipher suite. 10051 ** 10052 ** NOTE: This suite selection algorithm should be the same as the one in 10053 ** ssl3_HandleClientHello(). 10054 */ 10055 for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { 10056 ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; 10057 SSLVersionRange vrange = { ss->version, ss->version }; 10058 if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) { 10059 continue; 10060 } 10061 for (i = 0; i + 2 < suite_length; i += 3) { 10062 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2]; 10063 if (suite_i == suite->cipher_suite) { 10064 ss->ssl3.hs.cipher_suite = suite_i; 10065 rv = ssl3_SetupCipherSuite(ss, PR_TRUE); 10066 if (rv != SECSuccess) { 10067 desc = internal_error; 10068 errCode = PORT_GetError(); 10069 goto alert_loser; 10070 } 10071 goto suite_found; 10072 } 10073 } 10074 } 10075 errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 10076 goto alert_loser; 10077 10078 suite_found: 10079 10080 /* If the ClientHello version is less than our maximum version, check for a 10081 * TLS_FALLBACK_SCSV and reject the connection if found. */ 10082 if (ss->vrange.max > ss->clientHelloVersion) { 10083 for (i = 0; i + 2 < suite_length; i += 3) { 10084 PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2]; 10085 if (suite_i == TLS_FALLBACK_SCSV) { 10086 desc = inappropriate_fallback; 10087 errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; 10088 goto alert_loser; 10089 } 10090 } 10091 } 10092 10093 /* Look for the SCSV, and if found, treat it just like an empty RI 10094 * extension by processing a local copy of an empty RI extension. 10095 */ 10096 for (i = 0; i + 2 < suite_length; i += 3) { 10097 PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2]; 10098 if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { 10099 PRUint8 *b2 = (PRUint8 *)emptyRIext; 10100 PRUint32 L2 = sizeof emptyRIext; 10101 (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello); 10102 break; 10103 } 10104 } 10105 10106 if (ss->opt.requireSafeNegotiation && 10107 !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 10108 desc = handshake_failure; 10109 errCode = SSL_ERROR_UNSAFE_NEGOTIATION; 10110 goto alert_loser; 10111 } 10112 10113 rv = ssl3_SelectServerCert(ss); 10114 if (rv != SECSuccess) { 10115 errCode = PORT_GetError(); 10116 desc = handshake_failure; 10117 goto alert_loser; 10118 } 10119 10120 /* we don't even search for a cache hit here. It's just a miss. */ 10121 SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses); 10122 sid = ssl3_NewSessionID(ss, PR_TRUE); 10123 if (sid == NULL) { 10124 errCode = PORT_GetError(); 10125 goto loser; /* memory error is set. */ 10126 } 10127 ss->sec.ci.sid = sid; 10128 /* do not worry about memory leak of sid since it now belongs to ci */ 10129 10130 /* We have to update the handshake hashes before we can send stuff */ 10131 rv = ssl3_UpdateHandshakeHashes(ss, buffer, length); 10132 if (rv != SECSuccess) { 10133 errCode = PORT_GetError(); 10134 goto loser; 10135 } 10136 10137 ssl_GetXmitBufLock(ss); 10138 rv = ssl3_SendServerHelloSequence(ss); 10139 ssl_ReleaseXmitBufLock(ss); 10140 if (rv != SECSuccess) { 10141 errCode = PORT_GetError(); 10142 goto loser; 10143 } 10144 10145 ssl_ReleaseSSL3HandshakeLock(ss); 10146 return SECSuccess; 10147 10148 alert_loser: 10149 SSL3_SendAlert(ss, alert_fatal, desc); 10150 loser: 10151 ssl_ReleaseSSL3HandshakeLock(ss); 10152 PORT_SetError(errCode); 10153 return SECFailure; 10154 } 10155 10156 SECStatus 10157 ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry, 10158 const sslBuffer *extensionBuf, sslBuffer *messageBuf) 10159 { 10160 SECStatus rv; 10161 SSL3ProtocolVersion version; 10162 sslSessionID *sid = ss->sec.ci.sid; 10163 const PRUint8 *random; 10164 10165 version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2); 10166 if (IS_DTLS(ss)) { 10167 version = dtls_TLSVersionToDTLSVersion(version); 10168 } 10169 rv = sslBuffer_AppendNumber(messageBuf, version, 2); 10170 if (rv != SECSuccess) { 10171 return SECFailure; 10172 } 10173 10174 if (helloRetry) { 10175 random = ssl_hello_retry_random; 10176 } else { 10177 rv = ssl_GenerateServerRandom(ss); 10178 if (rv != SECSuccess) { 10179 return SECFailure; 10180 } 10181 random = ss->ssl3.hs.server_random; 10182 } 10183 rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH); 10184 if (rv != SECSuccess) { 10185 return SECFailure; 10186 } 10187 10188 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 10189 if (sid) { 10190 rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID, 10191 sid->u.ssl3.sessionIDLength, 1); 10192 } else { 10193 rv = sslBuffer_AppendNumber(messageBuf, 0, 1); 10194 } 10195 } else { 10196 rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data, 10197 ss->ssl3.hs.fakeSid.len, 1); 10198 } 10199 if (rv != SECSuccess) { 10200 return SECFailure; 10201 } 10202 10203 rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2); 10204 if (rv != SECSuccess) { 10205 return SECFailure; 10206 } 10207 rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1); 10208 if (rv != SECSuccess) { 10209 return SECFailure; 10210 } 10211 if (SSL_BUFFER_LEN(extensionBuf)) { 10212 /* Directly copy the extensions */ 10213 rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2); 10214 if (rv != SECSuccess) { 10215 return SECFailure; 10216 } 10217 } 10218 10219 if (ss->xtnData.ech && ss->xtnData.ech->receivedInnerXtn) { 10220 /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e. 10221 * in shared mode), or if we received a CHInner in split/backend mode. */ 10222 if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) { 10223 if (helloRetry) { 10224 return tls13_WriteServerEchHrrSignal(ss, SSL_BUFFER_BASE(messageBuf), 10225 SSL_BUFFER_LEN(messageBuf)); 10226 } else { 10227 return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf), 10228 SSL_BUFFER_LEN(messageBuf)); 10229 } 10230 } 10231 } 10232 return SECSuccess; 10233 } 10234 10235 /* The negotiated version number has been already placed in ss->version. 10236 ** 10237 ** Called from: ssl3_HandleClientHello (resuming session), 10238 ** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), 10239 ** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) 10240 */ 10241 SECStatus 10242 ssl3_SendServerHello(sslSocket *ss) 10243 { 10244 SECStatus rv; 10245 sslBuffer extensionBuf = SSL_BUFFER_EMPTY; 10246 sslBuffer messageBuf = SSL_BUFFER_EMPTY; 10247 10248 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), 10249 ss->fd)); 10250 10251 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 10252 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10253 10254 PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); 10255 if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { 10256 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 10257 return SECFailure; 10258 } 10259 10260 rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello); 10261 if (rv != SECSuccess) { 10262 goto loser; 10263 } 10264 10265 rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf); 10266 if (rv != SECSuccess) { 10267 goto loser; 10268 } 10269 10270 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello, 10271 SSL_BUFFER_LEN(&messageBuf)); 10272 if (rv != SECSuccess) { 10273 goto loser; /* err set by AppendHandshake. */ 10274 } 10275 10276 rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf), 10277 SSL_BUFFER_LEN(&messageBuf)); 10278 if (rv != SECSuccess) { 10279 goto loser; /* err set by AppendHandshake. */ 10280 } 10281 10282 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 10283 rv = ssl3_SetupBothPendingCipherSpecs(ss); 10284 if (rv != SECSuccess) { 10285 goto loser; /* err set */ 10286 } 10287 } 10288 10289 sslBuffer_Clear(&extensionBuf); 10290 sslBuffer_Clear(&messageBuf); 10291 return SECSuccess; 10292 10293 loser: 10294 sslBuffer_Clear(&extensionBuf); 10295 sslBuffer_Clear(&messageBuf); 10296 return SECFailure; 10297 } 10298 10299 SECStatus 10300 ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef, 10301 const ssl3DHParams *params, 10302 sslEphemeralKeyPair **keyPair) 10303 { 10304 SECKEYDHParams dhParam; 10305 SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ 10306 SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ 10307 sslEphemeralKeyPair *pair; 10308 10309 dhParam.prime.data = params->prime.data; 10310 dhParam.prime.len = params->prime.len; 10311 dhParam.base.data = params->base.data; 10312 dhParam.base.len = params->base.len; 10313 10314 PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data, 10315 dhParam.prime.len)); 10316 PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data, 10317 dhParam.base.len)); 10318 10319 /* Generate ephemeral DH keypair */ 10320 privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); 10321 if (!privKey || !pubKey) { 10322 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); 10323 return SECFailure; 10324 } 10325 10326 pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey); 10327 if (!pair) { 10328 SECKEY_DestroyPrivateKey(privKey); 10329 SECKEY_DestroyPublicKey(pubKey); 10330 10331 return SECFailure; 10332 } 10333 10334 *keyPair = pair; 10335 return SECSuccess; 10336 } 10337 10338 static SECStatus 10339 ssl3_SendDHServerKeyExchange(sslSocket *ss) 10340 { 10341 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; 10342 SECStatus rv = SECFailure; 10343 int length; 10344 SECItem signed_hash = { siBuffer, NULL, 0 }; 10345 SSL3Hashes hashes; 10346 SSLHashType hashAlg; 10347 10348 const ssl3DHParams *params; 10349 sslEphemeralKeyPair *keyPair; 10350 SECKEYPublicKey *pubKey; 10351 SECKEYPrivateKey *certPrivateKey; 10352 const sslNamedGroupDef *groupDef; 10353 /* Do this on the heap, this could be over 2k long. */ 10354 sslBuffer dhBuf = SSL_BUFFER_EMPTY; 10355 10356 if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) { 10357 /* TODO: Support DH_anon. It might be sufficient to drop the signature. 10358 See bug 1170510. */ 10359 PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 10360 return SECFailure; 10361 } 10362 10363 rv = ssl_SelectDHEGroup(ss, &groupDef); 10364 if (rv == SECFailure) { 10365 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 10366 return SECFailure; 10367 } 10368 ss->sec.keaGroup = groupDef; 10369 10370 params = ssl_GetDHEParams(groupDef); 10371 rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair); 10372 if (rv == SECFailure) { 10373 ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); 10374 return SECFailure; 10375 } 10376 PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs); 10377 10378 if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) { 10379 hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme); 10380 } else { 10381 /* Use ssl_hash_none to represent the MD5+SHA1 combo. */ 10382 hashAlg = ssl_hash_none; 10383 } 10384 10385 pubKey = keyPair->keys->pubKey; 10386 PRINT_BUF(50, (ss, "DH public value:", 10387 pubKey->u.dh.publicValue.data, 10388 pubKey->u.dh.publicValue.len)); 10389 rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes, 10390 pubKey->u.dh.prime, 10391 pubKey->u.dh.base, 10392 pubKey->u.dh.publicValue, 10393 PR_TRUE /* padY */); 10394 if (rv != SECSuccess) { 10395 ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 10396 goto loser; 10397 } 10398 10399 certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey; 10400 rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash); 10401 if (rv != SECSuccess) { 10402 goto loser; /* ssl3_SignHashes has set err. */ 10403 } 10404 10405 length = 2 + pubKey->u.dh.prime.len + 10406 2 + pubKey->u.dh.base.len + 10407 2 + pubKey->u.dh.prime.len + 10408 2 + signed_hash.len; 10409 10410 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 10411 length += 2; 10412 } 10413 10414 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length); 10415 if (rv != SECSuccess) { 10416 goto loser; /* err set by AppendHandshake. */ 10417 } 10418 10419 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data, 10420 pubKey->u.dh.prime.len, 2); 10421 if (rv != SECSuccess) { 10422 goto loser; /* err set by AppendHandshake. */ 10423 } 10424 10425 rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data, 10426 pubKey->u.dh.base.len, 2); 10427 if (rv != SECSuccess) { 10428 goto loser; /* err set by AppendHandshake. */ 10429 } 10430 10431 rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE); 10432 if (rv != SECSuccess) { 10433 goto loser; /* err set by AppendPaddedDHKeyShare. */ 10434 } 10435 rv = ssl3_AppendBufferToHandshake(ss, &dhBuf); 10436 if (rv != SECSuccess) { 10437 goto loser; /* err set by AppendHandshake. */ 10438 } 10439 10440 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 10441 rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2); 10442 if (rv != SECSuccess) { 10443 goto loser; /* err set by AppendHandshake. */ 10444 } 10445 } 10446 10447 rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, 10448 signed_hash.len, 2); 10449 if (rv != SECSuccess) { 10450 goto loser; /* err set by AppendHandshake. */ 10451 } 10452 10453 sslBuffer_Clear(&dhBuf); 10454 PORT_Free(signed_hash.data); 10455 return SECSuccess; 10456 10457 loser: 10458 if (signed_hash.data) 10459 PORT_Free(signed_hash.data); 10460 sslBuffer_Clear(&dhBuf); 10461 return SECFailure; 10462 } 10463 10464 static SECStatus 10465 ssl3_SendServerKeyExchange(sslSocket *ss) 10466 { 10467 const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; 10468 10469 SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", 10470 SSL_GETPID(), ss->fd)); 10471 10472 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 10473 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10474 10475 switch (kea_def->exchKeyType) { 10476 case ssl_kea_dh: { 10477 return ssl3_SendDHServerKeyExchange(ss); 10478 } 10479 10480 case ssl_kea_ecdh: { 10481 return ssl3_SendECDHServerKeyExchange(ss); 10482 } 10483 10484 case ssl_kea_rsa: 10485 case ssl_kea_null: 10486 default: 10487 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 10488 break; 10489 } 10490 10491 return SECFailure; 10492 } 10493 10494 SECStatus 10495 ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert, 10496 PRBool grease, sslBuffer *buf) 10497 { 10498 SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 }; 10499 unsigned int filteredCount = 0; 10500 10501 SECStatus rv = ssl3_FilterSigAlgs(ss, minVersion, PR_FALSE, forCert, 10502 PR_ARRAY_SIZE(filtered), 10503 filtered, &filteredCount); 10504 if (rv != SECSuccess) { 10505 return SECFailure; 10506 } 10507 return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, grease, buf); 10508 } 10509 10510 SECStatus 10511 ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes, 10512 PRUint32 numSchemes, PRBool grease, sslBuffer *buf) 10513 { 10514 if (!numSchemes) { 10515 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 10516 return SECFailure; 10517 } 10518 10519 unsigned int lengthOffset; 10520 SECStatus rv; 10521 10522 rv = sslBuffer_Skip(buf, 2, &lengthOffset); 10523 if (rv != SECSuccess) { 10524 return SECFailure; 10525 } 10526 10527 for (unsigned int i = 0; i < numSchemes; ++i) { 10528 rv = sslBuffer_AppendNumber(buf, schemes[i], 2); 10529 if (rv != SECSuccess) { 10530 return SECFailure; 10531 } 10532 } 10533 10534 /* GREASE SignatureAlgorithms: 10535 * A client MAY select one or more GREASE signature algorithm values and 10536 * advertise them in the "signature_algorithms" or 10537 * "signature_algorithms_cert" extensions, if sent [RFC8701, Section 3.1]. 10538 * 10539 * When sending a CertificateRequest in TLS 1.3, a server MAY behave as 10540 * follows: [...] A server MAY select one or more GREASE signature 10541 * algorithm values and advertise them in the "signature_algorithms" or 10542 * "signature_algorithms_cert" extensions, if present 10543 * [RFC8701, Section 4.1]. */ 10544 if (grease && 10545 ((!ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) || 10546 (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3))) { 10547 PRUint16 value; 10548 if (ss->sec.isServer) { 10549 rv = tls13_RandomGreaseValue(&value); 10550 if (rv != SECSuccess) { 10551 return SECFailure; 10552 } 10553 } else { 10554 value = ss->ssl3.hs.grease->idx[grease_sigalg]; 10555 } 10556 rv = sslBuffer_AppendNumber(buf, value, 2); 10557 if (rv != SECSuccess) { 10558 return SECFailure; 10559 } 10560 } 10561 10562 return sslBuffer_InsertLength(buf, lengthOffset, 2); 10563 } 10564 10565 /* 10566 * In TLS 1.3 we are permitted to advertise support for PKCS#1 10567 * schemes. This doesn't affect the signatures in TLS itself, just 10568 * those on certificates. Not advertising PKCS#1 signatures creates a 10569 * serious compatibility risk as it excludes many certificate chains 10570 * that include PKCS#1. Hence, forCert is used to enable advertising 10571 * PKCS#1 support. Note that we include these in signature_algorithms 10572 * because we don't yet support signature_algorithms_cert. TLS 1.3 10573 * requires that PKCS#1 schemes are placed last in the list if they 10574 * are present. This sorting can be removed once we support 10575 * signature_algorithms_cert. 10576 */ 10577 SECStatus 10578 ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae, 10579 PRBool forCert, 10580 unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes, 10581 unsigned int *numFilteredSchemes) 10582 { 10583 PORT_Assert(filteredSchemes); 10584 PORT_Assert(numFilteredSchemes); 10585 PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount); 10586 if (maxSchemes < ss->ssl3.signatureSchemeCount) { 10587 return SECFailure; 10588 } 10589 10590 *numFilteredSchemes = 0; 10591 PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_3; 10592 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 10593 if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) { 10594 continue; 10595 } 10596 if (ssl_SignatureSchemeAccepted(minVersion, 10597 ss->ssl3.signatureSchemes[i], 10598 allowUnsortedPkcs1)) { 10599 filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i]; 10600 } 10601 } 10602 if (forCert && !allowUnsortedPkcs1) { 10603 for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 10604 if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) { 10605 continue; 10606 } 10607 if (!ssl_SignatureSchemeAccepted(minVersion, 10608 ss->ssl3.signatureSchemes[i], 10609 PR_FALSE) && 10610 ssl_SignatureSchemeAccepted(minVersion, 10611 ss->ssl3.signatureSchemes[i], 10612 PR_TRUE)) { 10613 filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i]; 10614 } 10615 } 10616 } 10617 return SECSuccess; 10618 } 10619 10620 static SECStatus 10621 ssl3_SendCertificateRequest(sslSocket *ss) 10622 { 10623 PRBool isTLS12; 10624 const PRUint8 *certTypes; 10625 SECStatus rv; 10626 PRUint32 length; 10627 const SECItem *names; 10628 unsigned int calen; 10629 unsigned int nnames; 10630 const SECItem *name; 10631 unsigned int i; 10632 int certTypesLength; 10633 PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2]; 10634 sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs); 10635 10636 SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", 10637 SSL_GETPID(), ss->fd)); 10638 10639 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 10640 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10641 10642 isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2); 10643 10644 rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames); 10645 if (rv != SECSuccess) { 10646 return rv; 10647 } 10648 certTypes = certificate_types; 10649 certTypesLength = sizeof certificate_types; 10650 10651 length = 1 + certTypesLength + 2 + calen; 10652 if (isTLS12) { 10653 rv = ssl3_EncodeSigAlgs(ss, ss->version, PR_TRUE /* forCert */, 10654 PR_FALSE /* GREASE */, &sigAlgsBuf); 10655 if (rv != SECSuccess) { 10656 return rv; 10657 } 10658 length += SSL_BUFFER_LEN(&sigAlgsBuf); 10659 } 10660 10661 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length); 10662 if (rv != SECSuccess) { 10663 return rv; /* err set by AppendHandshake. */ 10664 } 10665 rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); 10666 if (rv != SECSuccess) { 10667 return rv; /* err set by AppendHandshake. */ 10668 } 10669 if (isTLS12) { 10670 rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf), 10671 SSL_BUFFER_LEN(&sigAlgsBuf)); 10672 if (rv != SECSuccess) { 10673 return rv; /* err set by AppendHandshake. */ 10674 } 10675 } 10676 rv = ssl3_AppendHandshakeNumber(ss, calen, 2); 10677 if (rv != SECSuccess) { 10678 return rv; /* err set by AppendHandshake. */ 10679 } 10680 for (i = 0, name = names; i < nnames; i++, name++) { 10681 rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); 10682 if (rv != SECSuccess) { 10683 return rv; /* err set by AppendHandshake. */ 10684 } 10685 } 10686 10687 return SECSuccess; 10688 } 10689 10690 static SECStatus 10691 ssl3_SendServerHelloDone(sslSocket *ss) 10692 { 10693 SECStatus rv; 10694 10695 SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", 10696 SSL_GETPID(), ss->fd)); 10697 10698 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 10699 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10700 10701 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0); 10702 if (rv != SECSuccess) { 10703 return rv; /* err set by AppendHandshake. */ 10704 } 10705 rv = ssl3_FlushHandshake(ss, 0); 10706 if (rv != SECSuccess) { 10707 return rv; /* error code set by ssl3_FlushHandshake */ 10708 } 10709 return SECSuccess; 10710 } 10711 10712 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered 10713 * a complete ssl3 Certificate Verify message 10714 * Caller must hold Handshake and RecvBuf locks. 10715 */ 10716 static SECStatus 10717 ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length) 10718 { 10719 SECItem signed_hash = { siBuffer, NULL, 0 }; 10720 SECStatus rv; 10721 int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; 10722 SSL3AlertDescription desc = handshake_failure; 10723 PRBool isTLS; 10724 SSLSignatureScheme sigScheme; 10725 SSL3Hashes hashes; 10726 const PRUint8 *savedMsg = b; 10727 const PRUint32 savedLen = length; 10728 10729 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake", 10730 SSL_GETPID(), ss->fd)); 10731 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 10732 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10733 10734 if (ss->ssl3.hs.ws != wait_cert_verify) { 10735 desc = unexpected_message; 10736 errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; 10737 goto alert_loser; 10738 } 10739 10740 /* TLS 1.3 is handled by tls13_HandleCertificateVerify */ 10741 PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2); 10742 10743 if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) { 10744 PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record); 10745 rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme); 10746 if (rv != SECSuccess) { 10747 if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) { 10748 errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM; 10749 } 10750 goto loser; /* alert already sent */ 10751 } 10752 rv = ssl_CheckSignatureSchemeConsistency( 10753 ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo); 10754 if (rv != SECSuccess) { 10755 errCode = PORT_GetError(); 10756 desc = illegal_parameter; 10757 goto alert_loser; 10758 } 10759 10760 rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf, 10761 ss->ssl3.hs.messages.len, 10762 ssl_SignatureSchemeToHashType(sigScheme), 10763 &hashes); 10764 } else { 10765 PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record); 10766 sigScheme = ssl_sig_none; 10767 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0); 10768 } 10769 10770 if (rv != SECSuccess) { 10771 errCode = SSL_ERROR_DIGEST_FAILURE; 10772 desc = decrypt_error; 10773 goto alert_loser; 10774 } 10775 10776 rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); 10777 if (rv != SECSuccess) { 10778 goto loser; /* malformed. */ 10779 } 10780 10781 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 10782 10783 /* XXX verify that the key & kea match */ 10784 rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash); 10785 if (rv != SECSuccess) { 10786 errCode = PORT_GetError(); 10787 desc = isTLS ? decrypt_error : handshake_failure; 10788 goto alert_loser; 10789 } 10790 10791 signed_hash.data = NULL; 10792 10793 if (length != 0) { 10794 desc = isTLS ? decode_error : illegal_parameter; 10795 goto alert_loser; /* malformed */ 10796 } 10797 10798 rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, 10799 savedMsg, savedLen); 10800 if (rv != SECSuccess) { 10801 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 10802 return rv; 10803 } 10804 10805 ss->ssl3.hs.ws = wait_change_cipher; 10806 return SECSuccess; 10807 10808 alert_loser: 10809 SSL3_SendAlert(ss, alert_fatal, desc); 10810 loser: 10811 PORT_SetError(errCode); 10812 return SECFailure; 10813 } 10814 10815 /* find a slot that is able to generate a PMS and wrap it with RSA. 10816 * Then generate and return the PMS. 10817 * If the serverKeySlot parameter is non-null, this function will use 10818 * that slot to do the job, otherwise it will find a slot. 10819 * 10820 * Called from ssl3_DeriveConnectionKeys() (above) 10821 * ssl3_SendRSAClientKeyExchange() (above) 10822 * ssl3_HandleRSAClientKeyExchange() (below) 10823 * Caller must hold the SpecWriteLock, the SSL3HandshakeLock 10824 */ 10825 static PK11SymKey * 10826 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, 10827 PK11SlotInfo *serverKeySlot) 10828 { 10829 PK11SymKey *pms = NULL; 10830 PK11SlotInfo *slot = serverKeySlot; 10831 void *pwArg = ss->pkcs11PinArg; 10832 SECItem param; 10833 CK_VERSION version; 10834 CK_MECHANISM_TYPE mechanism_array[3]; 10835 10836 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10837 10838 if (slot == NULL) { 10839 SSLCipherAlgorithm calg; 10840 /* The specReadLock would suffice here, but we cannot assert on 10841 ** read locks. Also, all the callers who call with a non-null 10842 ** slot already hold the SpecWriteLock. 10843 */ 10844 PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 10845 PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch); 10846 10847 calg = spec->cipherDef->calg; 10848 10849 /* First get an appropriate slot. */ 10850 mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; 10851 mechanism_array[1] = CKM_RSA_PKCS; 10852 mechanism_array[2] = ssl3_Alg2Mech(calg); 10853 10854 slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); 10855 if (slot == NULL) { 10856 /* can't find a slot with all three, find a slot with the minimum */ 10857 slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); 10858 if (slot == NULL) { 10859 PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); 10860 return pms; /* which is NULL */ 10861 } 10862 } 10863 } 10864 10865 /* Generate the pre-master secret ... */ 10866 if (IS_DTLS(ss)) { 10867 SSL3ProtocolVersion temp; 10868 10869 temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); 10870 version.major = MSB(temp); 10871 version.minor = LSB(temp); 10872 } else { 10873 version.major = MSB(ss->clientHelloVersion); 10874 version.minor = LSB(ss->clientHelloVersion); 10875 } 10876 10877 param.data = (unsigned char *)&version; 10878 param.len = sizeof version; 10879 10880 pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); 10881 if (!serverKeySlot) 10882 PK11_FreeSlot(slot); 10883 if (pms == NULL) { 10884 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 10885 } 10886 return pms; 10887 } 10888 10889 static void 10890 ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c) 10891 { 10892 uintptr_t mask = (uintptr_t)c; 10893 unsigned int i; 10894 for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) { 10895 mask |= mask << i; 10896 } 10897 uintptr_t x_ptr = (uintptr_t)*x; 10898 uintptr_t y_ptr = (uintptr_t)*y; 10899 uintptr_t tmp = (x_ptr ^ y_ptr) & mask; 10900 x_ptr = x_ptr ^ tmp; 10901 y_ptr = y_ptr ^ tmp; 10902 *x = (PK11SymKey *)x_ptr; 10903 *y = (PK11SymKey *)y_ptr; 10904 } 10905 10906 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER 10907 * return any indication of failure of the Client Key Exchange message, 10908 * where that failure is caused by the content of the client's message. 10909 * This function must not return SECFailure for any reason that is directly 10910 * or indirectly caused by the content of the client's encrypted PMS. 10911 * We must not send an alert and also not drop the connection. 10912 * Instead, we generate a random PMS. This will cause a failure 10913 * in the processing the finished message, which is exactly where 10914 * the failure must occur. 10915 * 10916 * Called from ssl3_HandleClientKeyExchange 10917 */ 10918 static SECStatus 10919 ssl3_HandleRSAClientKeyExchange(sslSocket *ss, 10920 PRUint8 *b, 10921 PRUint32 length, 10922 sslKeyPair *serverKeyPair) 10923 { 10924 SECStatus rv; 10925 SECItem enc_pms; 10926 PK11SymKey *pms = NULL; 10927 PK11SymKey *fauxPms = NULL; 10928 PK11SlotInfo *slot = NULL; 10929 10930 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 10931 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 10932 PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch); 10933 10934 enc_pms.data = b; 10935 enc_pms.len = length; 10936 10937 if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ 10938 PRUint32 kLen; 10939 rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len); 10940 if (rv != SECSuccess) { 10941 PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 10942 return SECFailure; 10943 } 10944 if ((unsigned)kLen < enc_pms.len) { 10945 enc_pms.len = kLen; 10946 } 10947 } 10948 10949 /* 10950 * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1 10951 * as we can within the constraints of the PKCS#11 interface. 10952 * 10953 * 1. Unconditionally generate a bogus PMS (what RFC 5246 10954 * calls R). 10955 * 2. Attempt the RSA decryption to recover the PMS (what 10956 * RFC 5246 calls M). 10957 * 3. Set PMS = (M == NULL) ? R : M 10958 * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive 10959 * the MS from PMS. This includes performing the version 10960 * check and length check. 10961 * 5. If either the initial RSA decryption failed or 10962 * ssl3_ComputeMasterSecret(PMS) failed, then discard 10963 * M and set PMS = R. Else, discard R and set PMS = M. 10964 * 10965 * We do two derivations here because we can't rely on having 10966 * a function that only performs the PMS version and length 10967 * check. The only redundant cost is that this runs the PRF, 10968 * which isn't necessary here. 10969 */ 10970 10971 /* Generate the bogus PMS (R) */ 10972 slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey); 10973 if (!slot) { 10974 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 10975 return SECFailure; 10976 } 10977 10978 if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) { 10979 PK11_FreeSlot(slot); 10980 slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL); 10981 if (!slot) { 10982 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 10983 return SECFailure; 10984 } 10985 } 10986 10987 ssl_GetSpecWriteLock(ss); 10988 fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot); 10989 ssl_ReleaseSpecWriteLock(ss); 10990 PK11_FreeSlot(slot); 10991 10992 if (fauxPms == NULL) { 10993 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 10994 return SECFailure; 10995 } 10996 10997 /* 10998 * unwrap pms out of the incoming buffer 10999 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do 11000 * the unwrap. Rather, it is the mechanism with which the 11001 * unwrapped pms will be used. 11002 */ 11003 pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms, 11004 CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); 11005 /* Temporarily use the PMS if unwrapping the real PMS fails. */ 11006 ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL); 11007 11008 /* Attempt to derive the MS from the PMS. This is the only way to 11009 * check the version field in the RSA PMS. If this fails, we 11010 * then use the faux PMS in place of the PMS. Note that this 11011 * operation should never fail if we are using the faux PMS 11012 * since it is correctly formatted. */ 11013 rv = ssl3_ComputeMasterSecret(ss, pms, NULL); 11014 11015 /* If we succeeded, then select the true PMS, else select the FPMS. */ 11016 ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL)); 11017 11018 /* This step will derive the MS from the PMS, among other things. */ 11019 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE); 11020 11021 /* Clear both PMS. */ 11022 PK11_FreeSymKey(pms); 11023 PK11_FreeSymKey(fauxPms); 11024 11025 if (rv != SECSuccess) { 11026 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); 11027 return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ 11028 } 11029 11030 return SECSuccess; 11031 } 11032 11033 static SECStatus 11034 ssl3_HandleDHClientKeyExchange(sslSocket *ss, 11035 PRUint8 *b, 11036 PRUint32 length, 11037 sslKeyPair *serverKeyPair) 11038 { 11039 PK11SymKey *pms; 11040 SECStatus rv; 11041 SECKEYPublicKey clntPubKey; 11042 CK_MECHANISM_TYPE target; 11043 PRBool isTLS; 11044 11045 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 11046 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11047 11048 clntPubKey.keyType = dhKey; 11049 clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len; 11050 clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data; 11051 clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len; 11052 clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data; 11053 11054 rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue, 11055 2, &b, &length); 11056 if (rv != SECSuccess) { 11057 return SECFailure; 11058 } 11059 11060 if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime, 11061 &clntPubKey.u.dh.publicValue)) { 11062 PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE); 11063 return SECFailure; 11064 } 11065 11066 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 11067 11068 if (isTLS) 11069 target = CKM_TLS_MASTER_KEY_DERIVE_DH; 11070 else 11071 target = CKM_SSL3_MASTER_KEY_DERIVE_DH; 11072 11073 /* Determine the PMS */ 11074 pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL, 11075 CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); 11076 if (pms == NULL) { 11077 ssl_FreeEphemeralKeyPairs(ss); 11078 ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 11079 return SECFailure; 11080 } 11081 11082 rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE); 11083 PK11_FreeSymKey(pms); 11084 ssl_FreeEphemeralKeyPairs(ss); 11085 return rv; 11086 } 11087 11088 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered 11089 * a complete ssl3 ClientKeyExchange message from the remote client 11090 * Caller must hold Handshake and RecvBuf locks. 11091 */ 11092 static SECStatus 11093 ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length) 11094 { 11095 sslKeyPair *serverKeyPair = NULL; 11096 SECStatus rv; 11097 const ssl3KEADef *kea_def; 11098 11099 SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake", 11100 SSL_GETPID(), ss->fd)); 11101 11102 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 11103 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11104 11105 if (ss->ssl3.hs.ws != wait_client_key) { 11106 SSL3_SendAlert(ss, alert_fatal, unexpected_message); 11107 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); 11108 return SECFailure; 11109 } 11110 11111 kea_def = ss->ssl3.hs.kea_def; 11112 11113 if (kea_def->ephemeral) { 11114 sslEphemeralKeyPair *keyPair; 11115 /* There should be exactly one pair. */ 11116 PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)); 11117 PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) == 11118 PR_NEXT_LINK(&ss->ephemeralKeyPairs)); 11119 keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs); 11120 serverKeyPair = keyPair->keys; 11121 ss->sec.keaKeyBits = 11122 SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); 11123 } else { 11124 serverKeyPair = ss->sec.serverCert->serverKeyPair; 11125 ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits; 11126 } 11127 11128 if (!serverKeyPair) { 11129 SSL3_SendAlert(ss, alert_fatal, handshake_failure); 11130 PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); 11131 return SECFailure; 11132 } 11133 PORT_Assert(serverKeyPair->pubKey); 11134 PORT_Assert(serverKeyPair->privKey); 11135 11136 ss->sec.keaType = kea_def->exchKeyType; 11137 11138 switch (kea_def->exchKeyType) { 11139 case ssl_kea_rsa: 11140 rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair); 11141 break; 11142 11143 case ssl_kea_dh: 11144 rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair); 11145 break; 11146 11147 case ssl_kea_ecdh: 11148 rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair); 11149 break; 11150 11151 default: 11152 (void)ssl3_HandshakeFailure(ss); 11153 PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 11154 return SECFailure; 11155 } 11156 ssl_FreeEphemeralKeyPairs(ss); 11157 if (rv == SECSuccess) { 11158 ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; 11159 } else { 11160 /* PORT_SetError has been called by all the Handle*ClientKeyExchange 11161 * functions above. However, not all error paths result in an alert, so 11162 * this ensures that the server knows about the error. Note that if an 11163 * alert was already sent, SSL3_SendAlert() is a noop. */ 11164 PRErrorCode errCode = PORT_GetError(); 11165 (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); 11166 PORT_SetError(errCode); 11167 } 11168 return rv; 11169 } 11170 11171 /* This is TLS's equivalent of sending a no_certificate alert. */ 11172 SECStatus 11173 ssl3_SendEmptyCertificate(sslSocket *ss) 11174 { 11175 SECStatus rv; 11176 unsigned int len = 0; 11177 PRBool isTLS13 = PR_FALSE; 11178 const SECItem *context; 11179 11180 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 11181 PORT_Assert(ss->ssl3.hs.clientCertRequested); 11182 context = &ss->xtnData.certReqContext; 11183 len = context->len + 1; 11184 isTLS13 = PR_TRUE; 11185 } 11186 11187 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3); 11188 if (rv != SECSuccess) { 11189 return rv; 11190 } 11191 11192 if (isTLS13) { 11193 rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1); 11194 if (rv != SECSuccess) { 11195 return rv; 11196 } 11197 } 11198 11199 return ssl3_AppendHandshakeNumber(ss, 0, 3); 11200 } 11201 11202 /* 11203 * NewSessionTicket 11204 * Called from ssl3_HandleFinished 11205 */ 11206 static SECStatus 11207 ssl3_SendNewSessionTicket(sslSocket *ss) 11208 { 11209 SECItem ticket = { 0, NULL, 0 }; 11210 SECStatus rv; 11211 NewSessionTicket nticket = { 0 }; 11212 11213 rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0, 11214 ss->ssl3.pwSpec->masterSecret, &ticket); 11215 if (rv != SECSuccess) 11216 goto loser; 11217 11218 /* Serialize the handshake message. Length = 11219 * lifetime (4) + ticket length (2) + ticket. */ 11220 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket, 11221 4 + 2 + ticket.len); 11222 if (rv != SECSuccess) 11223 goto loser; 11224 11225 /* This is a fixed value. */ 11226 rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4); 11227 if (rv != SECSuccess) 11228 goto loser; 11229 11230 /* Encode the ticket. */ 11231 rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2); 11232 if (rv != SECSuccess) 11233 goto loser; 11234 11235 rv = SECSuccess; 11236 11237 loser: 11238 if (ticket.data) { 11239 SECITEM_FreeItem(&ticket, PR_FALSE); 11240 } 11241 return rv; 11242 } 11243 11244 static SECStatus 11245 ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length) 11246 { 11247 SECStatus rv; 11248 SECItem ticketData; 11249 PRUint32 temp; 11250 11251 SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake", 11252 SSL_GETPID(), ss->fd)); 11253 11254 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 11255 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11256 11257 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); 11258 PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket); 11259 11260 if (ss->ssl3.hs.ws != wait_new_session_ticket) { 11261 SSL3_SendAlert(ss, alert_fatal, unexpected_message); 11262 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); 11263 return SECFailure; 11264 } 11265 11266 /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid 11267 * until it has verified the server's Finished message." See the comment in 11268 * ssl3_FinishHandshake for more details. 11269 */ 11270 ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss); 11271 if (length < 4) { 11272 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 11273 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); 11274 return SECFailure; 11275 } 11276 11277 rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length); 11278 if (rv != SECSuccess) { 11279 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); 11280 return SECFailure; 11281 } 11282 ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp; 11283 11284 rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length); 11285 if (rv != SECSuccess || length != 0) { 11286 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 11287 PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); 11288 return SECFailure; /* malformed */ 11289 } 11290 /* If the server sent a zero-length ticket, ignore it and keep the 11291 * existing ticket. */ 11292 if (ticketData.len != 0) { 11293 rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, 11294 &ticketData); 11295 if (rv != SECSuccess) { 11296 return rv; 11297 } 11298 ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; 11299 } 11300 11301 ss->ssl3.hs.ws = wait_change_cipher; 11302 return SECSuccess; 11303 } 11304 11305 #ifdef NISCC_TEST 11306 static PRInt32 connNum = 0; 11307 11308 static SECStatus 11309 get_fake_cert(SECItem *pCertItem, int *pIndex) 11310 { 11311 PRFileDesc *cf; 11312 char *testdir; 11313 char *startat; 11314 char *stopat; 11315 const char *extension; 11316 int fileNum; 11317 PRInt32 numBytes = 0; 11318 PRStatus prStatus; 11319 PRFileInfo info; 11320 char cfn[100]; 11321 11322 pCertItem->data = 0; 11323 if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) { 11324 return SECSuccess; 11325 } 11326 *pIndex = (NULL != strstr(testdir, "root")); 11327 extension = (strstr(testdir, "simple") ? "" : ".der"); 11328 fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; 11329 if ((startat = PR_GetEnvSecure("START_AT")) != NULL) { 11330 fileNum += atoi(startat); 11331 } 11332 if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL && 11333 fileNum >= atoi(stopat)) { 11334 *pIndex = -1; 11335 return SECSuccess; 11336 } 11337 snprintf(cfn, sizeof(cfn), "%s/%08d%s", testdir, fileNum, extension); 11338 cf = PR_Open(cfn, PR_RDONLY, 0); 11339 if (!cf) { 11340 goto loser; 11341 } 11342 prStatus = PR_GetOpenFileInfo(cf, &info); 11343 if (prStatus != PR_SUCCESS) { 11344 PR_Close(cf); 11345 goto loser; 11346 } 11347 pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); 11348 if (pCertItem) { 11349 numBytes = PR_Read(cf, pCertItem->data, info.size); 11350 } 11351 PR_Close(cf); 11352 if (numBytes != info.size) { 11353 SECITEM_FreeItem(pCertItem, PR_FALSE); 11354 PORT_SetError(SEC_ERROR_IO); 11355 goto loser; 11356 } 11357 fprintf(stderr, "using %s\n", cfn); 11358 return SECSuccess; 11359 11360 loser: 11361 fprintf(stderr, "failed to use %s\n", cfn); 11362 *pIndex = -1; 11363 return SECFailure; 11364 } 11365 #endif 11366 11367 /* 11368 * Used by both client and server. 11369 * Called from HandleServerHelloDone and from SendServerHelloSequence. 11370 */ 11371 static SECStatus 11372 ssl3_SendCertificate(sslSocket *ss) 11373 { 11374 SECStatus rv; 11375 CERTCertificateList *certChain; 11376 int certChainLen = 0; 11377 int i; 11378 #ifdef NISCC_TEST 11379 SECItem fakeCert; 11380 int ndex = -1; 11381 #endif 11382 PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; 11383 SECItem context = { siBuffer, NULL, 0 }; 11384 unsigned int contextLen = 0; 11385 11386 SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake", 11387 SSL_GETPID(), ss->fd)); 11388 11389 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 11390 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11391 PR_ASSERT(!ss->ssl3.hs.clientCertificatePending); 11392 11393 if (ss->sec.localCert) 11394 CERT_DestroyCertificate(ss->sec.localCert); 11395 if (ss->sec.isServer) { 11396 /* A server certificate is selected in ssl3_HandleClientHello. */ 11397 PORT_Assert(ss->sec.serverCert); 11398 11399 certChain = ss->sec.serverCert->serverCertChain; 11400 ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert); 11401 } else { 11402 certChain = ss->ssl3.clientCertChain; 11403 ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); 11404 } 11405 11406 #ifdef NISCC_TEST 11407 rv = get_fake_cert(&fakeCert, &ndex); 11408 #endif 11409 11410 if (isTLS13) { 11411 contextLen = 1; /* Size of the context length */ 11412 if (!ss->sec.isServer) { 11413 PORT_Assert(ss->ssl3.hs.clientCertRequested); 11414 context = ss->xtnData.certReqContext; 11415 contextLen += context.len; 11416 } 11417 } 11418 if (certChain) { 11419 for (i = 0; i < certChain->len; i++) { 11420 #ifdef NISCC_TEST 11421 if (fakeCert.len > 0 && i == ndex) { 11422 certChainLen += fakeCert.len + 3; 11423 } else { 11424 certChainLen += certChain->certs[i].len + 3; 11425 } 11426 #else 11427 certChainLen += certChain->certs[i].len + 3; 11428 #endif 11429 } 11430 } 11431 11432 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, 11433 contextLen + certChainLen + 3); 11434 if (rv != SECSuccess) { 11435 return rv; /* err set by AppendHandshake. */ 11436 } 11437 11438 if (isTLS13) { 11439 rv = ssl3_AppendHandshakeVariable(ss, context.data, 11440 context.len, 1); 11441 if (rv != SECSuccess) { 11442 return rv; /* err set by AppendHandshake. */ 11443 } 11444 } 11445 11446 rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3); 11447 if (rv != SECSuccess) { 11448 return rv; /* err set by AppendHandshake. */ 11449 } 11450 if (certChain) { 11451 for (i = 0; i < certChain->len; i++) { 11452 #ifdef NISCC_TEST 11453 if (fakeCert.len > 0 && i == ndex) { 11454 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data, 11455 fakeCert.len, 3); 11456 SECITEM_FreeItem(&fakeCert, PR_FALSE); 11457 } else { 11458 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, 11459 certChain->certs[i].len, 3); 11460 } 11461 #else 11462 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, 11463 certChain->certs[i].len, 3); 11464 #endif 11465 if (rv != SECSuccess) { 11466 return rv; /* err set by AppendHandshake. */ 11467 } 11468 } 11469 } 11470 11471 return SECSuccess; 11472 } 11473 11474 /* 11475 * Used by server only. 11476 * single-stapling, send only a single cert status 11477 */ 11478 SECStatus 11479 ssl3_SendCertificateStatus(sslSocket *ss) 11480 { 11481 SECStatus rv; 11482 int len = 0; 11483 SECItemArray *statusToSend = NULL; 11484 const sslServerCert *serverCert; 11485 11486 SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", 11487 SSL_GETPID(), ss->fd)); 11488 11489 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 11490 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11491 PORT_Assert(ss->sec.isServer); 11492 11493 if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) 11494 return SECSuccess; 11495 11496 /* Use certStatus based on the cert being used. */ 11497 serverCert = ss->sec.serverCert; 11498 if (serverCert->certStatusArray && serverCert->certStatusArray->len) { 11499 statusToSend = serverCert->certStatusArray; 11500 } 11501 if (!statusToSend) 11502 return SECSuccess; 11503 11504 /* Use the array's first item only (single stapling) */ 11505 len = 1 + statusToSend->items[0].len + 3; 11506 11507 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len); 11508 if (rv != SECSuccess) { 11509 return rv; /* err set by AppendHandshake. */ 11510 } 11511 rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); 11512 if (rv != SECSuccess) 11513 return rv; /* err set by AppendHandshake. */ 11514 11515 rv = ssl3_AppendHandshakeVariable(ss, 11516 statusToSend->items[0].data, 11517 statusToSend->items[0].len, 11518 3); 11519 if (rv != SECSuccess) 11520 return rv; /* err set by AppendHandshake. */ 11521 11522 return SECSuccess; 11523 } 11524 11525 /* This is used to delete the CA certificates in the peer certificate chain 11526 * from the cert database after they've been validated. 11527 */ 11528 void 11529 ssl3_CleanupPeerCerts(sslSocket *ss) 11530 { 11531 PLArenaPool *arena = ss->ssl3.peerCertArena; 11532 11533 if (arena) 11534 PORT_FreeArena(arena, PR_FALSE); 11535 ss->ssl3.peerCertArena = NULL; 11536 ss->ssl3.peerCertChain = NULL; 11537 11538 if (ss->sec.peerCert != NULL) { 11539 if (ss->sec.peerKey) { 11540 SECKEY_DestroyPublicKey(ss->sec.peerKey); 11541 ss->sec.peerKey = NULL; 11542 } 11543 CERT_DestroyCertificate(ss->sec.peerCert); 11544 ss->sec.peerCert = NULL; 11545 } 11546 } 11547 11548 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered 11549 * a complete ssl3 CertificateStatus message. 11550 * Caller must hold Handshake and RecvBuf locks. 11551 */ 11552 static SECStatus 11553 ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length) 11554 { 11555 SECStatus rv; 11556 11557 if (ss->ssl3.hs.ws != wait_certificate_status) { 11558 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 11559 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS); 11560 return SECFailure; 11561 } 11562 11563 rv = ssl_ReadCertificateStatus(ss, b, length); 11564 if (rv != SECSuccess) { 11565 return SECFailure; /* code already set */ 11566 } 11567 11568 return ssl3_AuthCertificate(ss); 11569 } 11570 11571 SECStatus 11572 ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length) 11573 { 11574 PRUint32 status, len; 11575 SECStatus rv; 11576 11577 PORT_Assert(!ss->sec.isServer); 11578 11579 /* Consume the CertificateStatusType enum */ 11580 rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length); 11581 if (rv != SECSuccess || status != 1 /* ocsp */) { 11582 return ssl3_DecodeError(ss); 11583 } 11584 11585 rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length); 11586 if (rv != SECSuccess || len != length) { 11587 return ssl3_DecodeError(ss); 11588 } 11589 11590 #define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ 11591 if (length > MAX_CERTSTATUS_LEN) { 11592 ssl3_DecodeError(ss); /* sets error code */ 11593 return SECFailure; 11594 } 11595 #undef MAX_CERTSTATUS_LEN 11596 11597 /* Array size 1, because we currently implement single-stapling only */ 11598 SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1); 11599 if (!ss->sec.ci.sid->peerCertStatus.items) 11600 return SECFailure; /* code already set */ 11601 11602 ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length); 11603 11604 if (!ss->sec.ci.sid->peerCertStatus.items[0].data) { 11605 SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE); 11606 return SECFailure; /* code already set */ 11607 } 11608 11609 PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length); 11610 ss->sec.ci.sid->peerCertStatus.items[0].len = length; 11611 ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer; 11612 return SECSuccess; 11613 } 11614 11615 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered 11616 * a complete ssl3 Certificate message. 11617 * Caller must hold Handshake and RecvBuf locks. 11618 */ 11619 static SECStatus 11620 ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length) 11621 { 11622 SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake", 11623 SSL_GETPID(), ss->fd)); 11624 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 11625 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 11626 11627 if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) || 11628 (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) { 11629 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 11630 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE); 11631 return SECFailure; 11632 } 11633 11634 if (ss->sec.isServer) { 11635 dtls_ReceivedFirstMessageInFlight(ss); 11636 } 11637 11638 return ssl3_CompleteHandleCertificate(ss, b, length); 11639 } 11640 11641 /* Called from ssl3_HandleCertificate 11642 */ 11643 SECStatus 11644 ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length) 11645 { 11646 ssl3CertNode *c; 11647 ssl3CertNode *lastCert = NULL; 11648 PRUint32 remaining = 0; 11649 PRUint32 size; 11650 SECStatus rv; 11651 PRBool isServer = ss->sec.isServer; 11652 PRBool isTLS; 11653 SSL3AlertDescription desc; 11654 int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; 11655 SECItem certItem; 11656 11657 ssl3_CleanupPeerCerts(ss); 11658 isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 11659 11660 /* It is reported that some TLS client sends a Certificate message 11661 ** with a zero-length message body. We'll treat that case like a 11662 ** normal no_certificates message to maximize interoperability. 11663 */ 11664 if (length) { 11665 rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length); 11666 if (rv != SECSuccess) 11667 goto loser; /* fatal alert already sent by ConsumeHandshake. */ 11668 if (remaining > length) 11669 goto decode_loser; 11670 } 11671 11672 if (!remaining) { 11673 if (!(isTLS && isServer)) { 11674 desc = bad_certificate; 11675 goto alert_loser; 11676 } 11677 /* This is TLS's version of a no_certificate alert. */ 11678 /* I'm a server. I've requested a client cert. He hasn't got one. */ 11679 rv = ssl3_HandleNoCertificate(ss); 11680 if (rv != SECSuccess) { 11681 errCode = PORT_GetError(); 11682 goto loser; 11683 } 11684 11685 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 11686 ss->ssl3.hs.ws = wait_client_key; 11687 } else { 11688 TLS13_SET_HS_STATE(ss, wait_finished); 11689 } 11690 return SECSuccess; 11691 } 11692 11693 ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 11694 if (ss->ssl3.peerCertArena == NULL) { 11695 goto loser; /* don't send alerts on memory errors */ 11696 } 11697 11698 /* First get the peer cert. */ 11699 if (remaining < 3) 11700 goto decode_loser; 11701 11702 remaining -= 3; 11703 rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length); 11704 if (rv != SECSuccess) 11705 goto loser; /* fatal alert already sent by ConsumeHandshake. */ 11706 if (size == 0 || remaining < size) 11707 goto decode_loser; 11708 11709 certItem.data = b; 11710 certItem.len = size; 11711 b += size; 11712 length -= size; 11713 remaining -= size; 11714 11715 ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, 11716 PR_FALSE, PR_TRUE); 11717 if (ss->sec.peerCert == NULL) { 11718 /* We should report an alert if the cert was bad, but not if the 11719 * problem was just some local problem, like memory error. 11720 */ 11721 goto ambiguous_err; 11722 } 11723 11724 /* Now get all of the CA certs. */ 11725 while (remaining > 0) { 11726 if (remaining < 3) 11727 goto decode_loser; 11728 11729 remaining -= 3; 11730 rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length); 11731 if (rv != SECSuccess) 11732 goto loser; /* fatal alert already sent by ConsumeHandshake. */ 11733 if (size == 0 || remaining < size) 11734 goto decode_loser; 11735 11736 certItem.data = b; 11737 certItem.len = size; 11738 b += size; 11739 length -= size; 11740 remaining -= size; 11741 11742 c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); 11743 if (c == NULL) { 11744 goto loser; /* don't send alerts on memory errors */ 11745 } 11746 11747 c->derCert = SECITEM_ArenaDupItem(ss->ssl3.peerCertArena, 11748 &certItem); 11749 if (c->derCert == NULL) { 11750 goto loser; 11751 } 11752 11753 c->next = NULL; 11754 if (lastCert) { 11755 lastCert->next = c; 11756 } else { 11757 ss->ssl3.peerCertChain = c; 11758 } 11759 lastCert = c; 11760 } 11761 11762 SECKEY_UpdateCertPQG(ss->sec.peerCert); 11763 11764 if (!isServer && 11765 ss->version < SSL_LIBRARY_VERSION_TLS_1_3 && 11766 ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { 11767 ss->ssl3.hs.ws = wait_certificate_status; 11768 rv = SECSuccess; 11769 } else { 11770 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ 11771 } 11772 11773 return rv; 11774 11775 ambiguous_err: 11776 errCode = PORT_GetError(); 11777 switch (errCode) { 11778 case PR_OUT_OF_MEMORY_ERROR: 11779 case SEC_ERROR_BAD_DATABASE: 11780 case SEC_ERROR_NO_MEMORY: 11781 if (isTLS) { 11782 desc = internal_error; 11783 goto alert_loser; 11784 } 11785 goto loser; 11786 } 11787 ssl3_SendAlertForCertError(ss, errCode); 11788 goto loser; 11789 11790 decode_loser: 11791 desc = isTLS ? decode_error : bad_certificate; 11792 11793 alert_loser: 11794 (void)SSL3_SendAlert(ss, alert_fatal, desc); 11795 11796 loser: 11797 (void)ssl_MapLowLevelError(errCode); 11798 return SECFailure; 11799 } 11800 11801 SECStatus 11802 ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey) 11803 { 11804 SECStatus rv; 11805 PRUint32 minKey = 0; 11806 PRInt32 optval; 11807 PRBool usePolicyLength = PR_TRUE; 11808 11809 rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval); 11810 if (rv == SECSuccess) { 11811 usePolicyLength = (PRBool)((optval & NSS_KEY_SIZE_POLICY_SSL_FLAG) == NSS_KEY_SIZE_POLICY_SSL_FLAG); 11812 } 11813 11814 ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey); 11815 switch (SECKEY_GetPublicKeyType(pubKey)) { 11816 case rsaKey: 11817 case rsaPssKey: 11818 case rsaOaepKey: 11819 rv = usePolicyLength ? NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval) 11820 : SECFailure; 11821 if (rv == SECSuccess && optval > 0) { 11822 minKey = (PRUint32)optval; 11823 } else { 11824 minKey = SSL_RSA_MIN_MODULUS_BITS; 11825 } 11826 break; 11827 11828 case dsaKey: 11829 rv = usePolicyLength ? NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval) 11830 : SECFailure; 11831 if (rv == SECSuccess && optval > 0) { 11832 minKey = (PRUint32)optval; 11833 } else { 11834 minKey = SSL_DSA_MIN_P_BITS; 11835 } 11836 break; 11837 11838 case dhKey: 11839 rv = usePolicyLength ? NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval) 11840 : SECFailure; 11841 if (rv == SECSuccess && optval > 0) { 11842 minKey = (PRUint32)optval; 11843 } else { 11844 minKey = SSL_DH_MIN_P_BITS; 11845 } 11846 break; 11847 11848 case ecKey: 11849 rv = usePolicyLength ? NSS_OptionGet(NSS_ECC_MIN_KEY_SIZE, &optval) 11850 : SECFailure; 11851 if (rv == SECSuccess && optval > 0) { 11852 minKey = (PRUint32)optval; 11853 } else { 11854 /* Don't check EC strength here on the understanding that we 11855 * only support curves we like. */ 11856 minKey = ss->sec.authKeyBits; 11857 } 11858 break; 11859 11860 default: 11861 FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); 11862 return SECFailure; 11863 } 11864 11865 /* Too small: not good enough. Send a fatal alert. */ 11866 if (ss->sec.authKeyBits < minKey) { 11867 FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY, 11868 ss->version >= SSL_LIBRARY_VERSION_TLS_1_0 11869 ? insufficient_security 11870 : illegal_parameter); 11871 return SECFailure; 11872 } 11873 11874 /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */ 11875 ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth; 11876 11877 return SECSuccess; 11878 } 11879 11880 SECStatus 11881 ssl3_HandleServerSpki(sslSocket *ss) 11882 { 11883 PORT_Assert(!ss->sec.isServer); 11884 SECKEYPublicKey *pubKey; 11885 11886 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 11887 tls13_IsVerifyingWithDelegatedCredential(ss)) { 11888 sslDelegatedCredential *dc = ss->xtnData.peerDelegCred; 11889 pubKey = SECKEY_ExtractPublicKey(dc->spki); 11890 if (!pubKey) { 11891 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 11892 return SECFailure; 11893 } 11894 11895 /* Because we have only a single authType (ssl_auth_tls13_any) 11896 * for TLS 1.3 at this point, set the scheme so that the 11897 * callback can interpret |authKeyBits| correctly. 11898 */ 11899 ss->sec.signatureScheme = dc->expectedCertVerifyAlg; 11900 } else { 11901 pubKey = CERT_ExtractPublicKey(ss->sec.peerCert); 11902 if (!pubKey) { 11903 PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 11904 return SECFailure; 11905 } 11906 } 11907 11908 SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey); 11909 SECKEY_DestroyPublicKey(pubKey); 11910 if (rv != SECSuccess) { 11911 return rv; /* Alert sent and code set. */ 11912 } 11913 11914 return SECSuccess; 11915 } 11916 11917 SECStatus 11918 ssl3_AuthCertificate(sslSocket *ss) 11919 { 11920 SECStatus rv; 11921 PRBool isServer = ss->sec.isServer; 11922 int errCode; 11923 CERTCertList *peerChain = NULL; 11924 11925 ss->ssl3.hs.authCertificatePending = PR_FALSE; 11926 11927 PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == 11928 ssl_preinfo_all); 11929 11930 if (!ss->sec.isServer) { 11931 /* Set the |spki| used to verify the handshake. When verifying with a 11932 * delegated credential (DC), this corresponds to the DC public key; 11933 * otherwise it correspond to the public key of the peer's end-entity 11934 * certificate. */ 11935 rv = ssl3_HandleServerSpki(ss); 11936 if (rv != SECSuccess) { 11937 /* Alert sent and code set (if not SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE). 11938 * In either case, we're done here. */ 11939 errCode = PORT_GetError(); 11940 goto loser; 11941 } 11942 11943 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 11944 ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType; 11945 ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; 11946 } 11947 } 11948 11949 /* 11950 * Ask caller-supplied callback function to validate cert chain. 11951 */ 11952 if (ss->opt.dbLoadCertChain) { 11953 /* Imports the certificate chain into the db. Indirectly used by the 11954 * authCertificate callback below. */ 11955 peerChain = SSL_PeerCertificateChain(ss->fd); 11956 if (!peerChain) { 11957 errCode = PORT_GetError(); 11958 goto loser; 11959 } 11960 } 11961 11962 rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, 11963 PR_TRUE, isServer); 11964 11965 if (ss->opt.dbLoadCertChain && peerChain) { 11966 CERT_DestroyCertList(peerChain); 11967 peerChain = NULL; 11968 } 11969 11970 if (rv != SECSuccess) { 11971 errCode = PORT_GetError(); 11972 if (errCode == 0) { 11973 errCode = SSL_ERROR_BAD_CERTIFICATE; 11974 } 11975 if (rv != SECWouldBlock) { 11976 if (ss->handleBadCert) { 11977 rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); 11978 } 11979 } 11980 11981 if (rv == SECWouldBlock) { 11982 if (ss->sec.isServer) { 11983 errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; 11984 goto loser; 11985 } 11986 11987 ss->ssl3.hs.authCertificatePending = PR_TRUE; 11988 rv = SECSuccess; 11989 } 11990 11991 if (rv != SECSuccess) { 11992 ssl3_SendAlertForCertError(ss, errCode); 11993 goto loser; 11994 } 11995 } 11996 11997 if (ss->sec.ci.sid->peerCert) { 11998 CERT_DestroyCertificate(ss->sec.ci.sid->peerCert); 11999 } 12000 ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); 12001 12002 if (!ss->sec.isServer) { 12003 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 12004 TLS13_SET_HS_STATE(ss, wait_cert_verify); 12005 } else { 12006 /* Ephemeral suites require ServerKeyExchange. */ 12007 if (ss->ssl3.hs.kea_def->ephemeral) { 12008 /* require server_key_exchange */ 12009 ss->ssl3.hs.ws = wait_server_key; 12010 } else { 12011 /* disallow server_key_exchange */ 12012 ss->ssl3.hs.ws = wait_cert_request; 12013 /* This is static RSA key exchange so set the key exchange 12014 * details to compensate for that. */ 12015 ss->sec.keaKeyBits = ss->sec.authKeyBits; 12016 ss->sec.signatureScheme = ssl_sig_none; 12017 ss->sec.keaGroup = NULL; 12018 } 12019 } 12020 } else { 12021 /* Server */ 12022 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 12023 ss->ssl3.hs.ws = wait_client_key; 12024 } else { 12025 TLS13_SET_HS_STATE(ss, wait_cert_verify); 12026 } 12027 } 12028 12029 PORT_Assert(rv == SECSuccess); 12030 if (rv != SECSuccess) { 12031 errCode = SEC_ERROR_LIBRARY_FAILURE; 12032 goto loser; 12033 } 12034 12035 return SECSuccess; 12036 12037 loser: 12038 (void)ssl_MapLowLevelError(errCode); 12039 return SECFailure; 12040 } 12041 12042 static SECStatus ssl3_FinishHandshake(sslSocket *ss); 12043 12044 static SECStatus 12045 ssl3_AlwaysFail(sslSocket *ss) 12046 { 12047 /* The caller should have cleared the callback. */ 12048 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; 12049 PORT_SetError(PR_INVALID_STATE_ERROR); 12050 return SECFailure; 12051 } 12052 12053 /* Caller must hold 1stHandshakeLock. 12054 */ 12055 SECStatus 12056 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) 12057 { 12058 SECStatus rv; 12059 12060 PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); 12061 12062 if (ss->sec.isServer) { 12063 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); 12064 return SECFailure; 12065 } 12066 12067 ssl_GetRecvBufLock(ss); 12068 ssl_GetSSL3HandshakeLock(ss); 12069 12070 if (!ss->ssl3.hs.authCertificatePending) { 12071 PORT_SetError(PR_INVALID_STATE_ERROR); 12072 rv = SECFailure; 12073 goto done; 12074 } 12075 12076 ss->ssl3.hs.authCertificatePending = PR_FALSE; 12077 12078 if (error != 0) { 12079 ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; 12080 ssl3_SendAlertForCertError(ss, error); 12081 rv = SECSuccess; 12082 } else if (ss->ssl3.hs.restartTarget != NULL) { 12083 sslRestartTarget target = ss->ssl3.hs.restartTarget; 12084 ss->ssl3.hs.restartTarget = NULL; 12085 12086 if (target == ssl3_FinishHandshake) { 12087 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race" 12088 " with peer's finished message", 12089 SSL_GETPID(), ss->fd)); 12090 } 12091 12092 rv = target(ss); 12093 } else { 12094 SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" 12095 " peer's finished message", 12096 SSL_GETPID(), ss->fd)); 12097 12098 PORT_Assert(!ss->ssl3.hs.isResuming); 12099 PORT_Assert(ss->ssl3.hs.ws != idle_handshake); 12100 12101 if (ss->opt.enableFalseStart && 12102 !ss->firstHsDone && 12103 !ss->ssl3.hs.isResuming && 12104 ssl3_WaitingForServerSecondRound(ss)) { 12105 /* ssl3_SendClientSecondRound deferred the false start check because 12106 * certificate authentication was pending, so we do it now if we still 12107 * haven't received all of the server's second round yet. 12108 */ 12109 rv = ssl3_CheckFalseStart(ss); 12110 } else { 12111 rv = SECSuccess; 12112 } 12113 } 12114 12115 done: 12116 ssl_ReleaseSSL3HandshakeLock(ss); 12117 ssl_ReleaseRecvBufLock(ss); 12118 12119 return rv; 12120 } 12121 12122 static SECStatus 12123 ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec, 12124 PRBool isServer, 12125 const SSL3Hashes *hashes, 12126 TLSFinished *tlsFinished) 12127 { 12128 SECStatus rv; 12129 CK_TLS_MAC_PARAMS tls_mac_params; 12130 SECItem param = { siBuffer, NULL, 0 }; 12131 PK11Context *prf_context; 12132 unsigned int retLen; 12133 12134 PORT_Assert(spec->masterSecret); 12135 if (!spec->masterSecret) { 12136 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12137 return SECFailure; 12138 } 12139 12140 if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) { 12141 tls_mac_params.prfHashMechanism = CKM_TLS_PRF; 12142 } else { 12143 tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss); 12144 } 12145 tls_mac_params.ulMacLength = 12; 12146 tls_mac_params.ulServerOrClient = isServer ? 1 : 2; 12147 param.data = (unsigned char *)&tls_mac_params; 12148 param.len = sizeof(tls_mac_params); 12149 prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN, 12150 spec->masterSecret, ¶m); 12151 if (!prf_context) 12152 return SECFailure; 12153 12154 rv = PK11_DigestBegin(prf_context); 12155 rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len); 12156 rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen, 12157 sizeof tlsFinished->verify_data); 12158 PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data); 12159 12160 PK11_DestroyContext(prf_context, PR_TRUE); 12161 12162 return rv; 12163 } 12164 12165 /* The calling function must acquire and release the appropriate 12166 * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for 12167 * ss->ssl3.crSpec). 12168 */ 12169 SECStatus 12170 ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec, 12171 const char *label, unsigned int labelLen, 12172 const unsigned char *val, unsigned int valLen, 12173 unsigned char *out, unsigned int outLen) 12174 { 12175 SECItem param = { siBuffer, NULL, 0 }; 12176 CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; 12177 PK11Context *prf_context; 12178 unsigned int retLen; 12179 SECStatus rv; 12180 12181 if (!spec->masterSecret) { 12182 PORT_Assert(spec->masterSecret); 12183 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12184 return SECFailure; 12185 } 12186 12187 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 12188 /* Bug 1312976 non-SHA256 exporters are broken. */ 12189 if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) { 12190 PORT_Assert(0); 12191 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12192 return SECFailure; 12193 } 12194 mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; 12195 } 12196 prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, 12197 spec->masterSecret, ¶m); 12198 if (!prf_context) 12199 return SECFailure; 12200 12201 rv = PK11_DigestBegin(prf_context); 12202 rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen); 12203 rv |= PK11_DigestOp(prf_context, val, valLen); 12204 rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); 12205 PORT_Assert(rv != SECSuccess || retLen == outLen); 12206 12207 PK11_DestroyContext(prf_context, PR_TRUE); 12208 return rv; 12209 } 12210 12211 /* called from ssl3_SendClientSecondRound 12212 * ssl3_HandleFinished 12213 */ 12214 static SECStatus 12215 ssl3_SendNextProto(sslSocket *ss) 12216 { 12217 SECStatus rv; 12218 int padding_len; 12219 static const unsigned char padding[32] = { 0 }; 12220 12221 if (ss->xtnData.nextProto.len == 0 || 12222 ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) { 12223 return SECSuccess; 12224 } 12225 12226 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 12227 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 12228 12229 padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32); 12230 12231 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len); 12232 if (rv != SECSuccess) { 12233 return rv; /* error code set by AppendHandshakeHeader */ 12234 } 12235 rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data, 12236 ss->xtnData.nextProto.len, 1); 12237 if (rv != SECSuccess) { 12238 return rv; /* error code set by AppendHandshake */ 12239 } 12240 rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1); 12241 if (rv != SECSuccess) { 12242 return rv; /* error code set by AppendHandshake */ 12243 } 12244 return rv; 12245 } 12246 12247 /* called from ssl3_SendFinished, tls13_DeriveSecret and tls13_LogECHSecret. 12248 * 12249 * This function is simply a debugging aid and therefore does not return a 12250 * SECStatus. */ 12251 void 12252 ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret) 12253 { 12254 #ifdef NSS_ALLOW_SSLKEYLOGFILE 12255 SECStatus rv; 12256 SECItem *keyData; 12257 12258 rv = PK11_ExtractKeyValue(secret); 12259 if (rv != SECSuccess) 12260 return; 12261 12262 /* keyData does not need to be freed. */ 12263 keyData = PK11_GetKeyData(secret); 12264 12265 ssl3_WriteKeyLog(ss, label, keyData); 12266 #endif 12267 } 12268 12269 /* called from ssl3_RecordKeyLog and tls13_EchKeyLog. 12270 * 12271 * This function is simply a debugging aid and therefore does not return a 12272 * SECStatus. */ 12273 void 12274 ssl3_WriteKeyLog(sslSocket *ss, const char *label, const SECItem *item) 12275 { 12276 #ifdef NSS_ALLOW_SSLKEYLOGFILE 12277 char *buf; 12278 unsigned int offset, len; 12279 12280 if (item == NULL || item->data == NULL) 12281 return; 12282 12283 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 12284 12285 if (!ssl_keylog_iob) 12286 return; 12287 12288 len = strlen(label) + 1 + /* label + space */ 12289 SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */ 12290 item->len * 2 + 1; /* secret (hex) + newline */ 12291 buf = (char *)PORT_Alloc(len); 12292 if (!buf) 12293 return; 12294 12295 /* There could be multiple, concurrent writers to the 12296 * keylog, so we have to do everything in a single call to 12297 * fwrite. */ 12298 12299 strcpy(buf, label); 12300 offset = strlen(label); 12301 buf[offset++] += ' '; 12302 hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH); 12303 offset += SSL3_RANDOM_LENGTH * 2; 12304 buf[offset++] = ' '; 12305 hexEncode(buf + offset, item->data, item->len); 12306 offset += item->len * 2; 12307 buf[offset++] = '\n'; 12308 12309 PORT_Assert(offset == len); 12310 12311 PZ_Lock(ssl_keylog_lock); 12312 if (fwrite(buf, len, 1, ssl_keylog_iob) == 1) 12313 fflush(ssl_keylog_iob); 12314 PZ_Unlock(ssl_keylog_lock); 12315 PORT_Free(buf); 12316 #endif 12317 } 12318 12319 /* called from ssl3_SendClientSecondRound 12320 * ssl3_HandleClientHello 12321 * ssl3_HandleFinished 12322 */ 12323 static SECStatus 12324 ssl3_SendFinished(sslSocket *ss, PRInt32 flags) 12325 { 12326 ssl3CipherSpec *cwSpec; 12327 PRBool isTLS; 12328 PRBool isServer = ss->sec.isServer; 12329 SECStatus rv; 12330 SSL3Sender sender = isServer ? sender_server : sender_client; 12331 SSL3Hashes hashes; 12332 TLSFinished tlsFinished; 12333 12334 SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd)); 12335 12336 PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 12337 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 12338 PR_ASSERT(!ss->ssl3.hs.clientCertificatePending); 12339 12340 ssl_GetSpecReadLock(ss); 12341 cwSpec = ss->ssl3.cwSpec; 12342 isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0); 12343 rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender); 12344 if (isTLS && rv == SECSuccess) { 12345 rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished); 12346 } 12347 ssl_ReleaseSpecReadLock(ss); 12348 if (rv != SECSuccess) { 12349 goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ 12350 } 12351 12352 if (isTLS) { 12353 if (isServer) 12354 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; 12355 else 12356 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; 12357 ss->ssl3.hs.finishedBytes = sizeof tlsFinished; 12358 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished); 12359 if (rv != SECSuccess) 12360 goto fail; /* err set by AppendHandshake. */ 12361 rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); 12362 if (rv != SECSuccess) 12363 goto fail; /* err set by AppendHandshake. */ 12364 } else { 12365 if (isServer) 12366 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; 12367 else 12368 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; 12369 PORT_Assert(hashes.len == sizeof hashes.u.s); 12370 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; 12371 rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s); 12372 if (rv != SECSuccess) 12373 goto fail; /* err set by AppendHandshake. */ 12374 rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); 12375 if (rv != SECSuccess) 12376 goto fail; /* err set by AppendHandshake. */ 12377 } 12378 rv = ssl3_FlushHandshake(ss, flags); 12379 if (rv != SECSuccess) { 12380 goto fail; /* error code set by ssl3_FlushHandshake */ 12381 } 12382 12383 ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret); 12384 12385 return SECSuccess; 12386 12387 fail: 12388 return rv; 12389 } 12390 12391 /* wrap the master secret, and put it into the SID. 12392 * Caller holds the Spec read lock. 12393 */ 12394 SECStatus 12395 ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid, 12396 PK11SymKey *secret) 12397 { 12398 PK11SymKey *wrappingKey = NULL; 12399 PK11SlotInfo *symKeySlot; 12400 void *pwArg = ss->pkcs11PinArg; 12401 SECStatus rv = SECFailure; 12402 PRBool isServer = ss->sec.isServer; 12403 CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; 12404 12405 symKeySlot = PK11_GetSlotFromKey(secret); 12406 if (!isServer) { 12407 int wrapKeyIndex; 12408 int incarnation; 12409 12410 /* these next few functions are mere accessors and don't fail. */ 12411 sid->u.ssl3.masterWrapIndex = wrapKeyIndex = 12412 PK11_GetCurrentWrapIndex(symKeySlot); 12413 PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */ 12414 12415 sid->u.ssl3.masterWrapSeries = incarnation = 12416 PK11_GetSlotSeries(symKeySlot); 12417 sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); 12418 sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); 12419 sid->u.ssl3.masterValid = PR_TRUE; 12420 /* Get the default wrapping key, for wrapping the master secret before 12421 * placing it in the SID cache entry. */ 12422 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, 12423 CKM_INVALID_MECHANISM, incarnation, 12424 pwArg); 12425 if (wrappingKey) { 12426 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ 12427 } else { 12428 int keyLength; 12429 /* if the wrappingKey doesn't exist, attempt to create it. 12430 * Note: we intentionally ignore errors here. If we cannot 12431 * generate a wrapping key, it is not fatal to this SSL connection, 12432 * but we will not be able to restart this session. 12433 */ 12434 mechanism = PK11_GetBestWrapMechanism(symKeySlot); 12435 keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); 12436 /* Zero length means fixed key length algorithm, or error. 12437 * It's ambiguous. 12438 */ 12439 wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, 12440 keyLength, pwArg); 12441 if (wrappingKey) { 12442 /* The thread safety characteristics of PK11_[SG]etWrapKey is 12443 * abominable. This protects against races in calling 12444 * PK11_SetWrapKey by dropping and re-acquiring the canonical 12445 * value once it is set. The mutex in PK11_[SG]etWrapKey will 12446 * ensure that races produce the same value in the end. */ 12447 PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); 12448 PK11_FreeSymKey(wrappingKey); 12449 wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, 12450 CKM_INVALID_MECHANISM, incarnation, pwArg); 12451 if (!wrappingKey) { 12452 PK11_FreeSlot(symKeySlot); 12453 return SECFailure; 12454 } 12455 } 12456 } 12457 } else { 12458 /* server socket using session cache. */ 12459 mechanism = PK11_GetBestWrapMechanism(symKeySlot); 12460 if (mechanism != CKM_INVALID_MECHANISM) { 12461 wrappingKey = 12462 ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg); 12463 if (wrappingKey) { 12464 mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ 12465 } 12466 } 12467 } 12468 12469 sid->u.ssl3.masterWrapMech = mechanism; 12470 PK11_FreeSlot(symKeySlot); 12471 12472 if (wrappingKey) { 12473 SECItem wmsItem; 12474 12475 wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; 12476 wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; 12477 rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, 12478 secret, &wmsItem); 12479 /* rv is examined below. */ 12480 sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; 12481 PK11_FreeSymKey(wrappingKey); 12482 } 12483 return rv; 12484 } 12485 12486 /* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered 12487 * a complete ssl3 Finished message from the peer. 12488 * Caller must hold Handshake and RecvBuf locks. 12489 */ 12490 static SECStatus 12491 ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length) 12492 { 12493 SECStatus rv = SECSuccess; 12494 PRBool isServer = ss->sec.isServer; 12495 PRBool isTLS; 12496 SSL3Hashes hashes; 12497 12498 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 12499 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 12500 12501 SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake", 12502 SSL_GETPID(), ss->fd)); 12503 12504 if (ss->ssl3.hs.ws != wait_finished) { 12505 SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12506 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); 12507 return SECFailure; 12508 } 12509 12510 if (!ss->sec.isServer || !ss->opt.requestCertificate) { 12511 dtls_ReceivedFirstMessageInFlight(ss); 12512 } 12513 12514 rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes, 12515 isServer ? sender_client : sender_server); 12516 if (rv != SECSuccess) { 12517 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12518 return SECFailure; 12519 } 12520 12521 rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length); 12522 if (rv != SECSuccess) { 12523 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12524 return rv; 12525 } 12526 12527 isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); 12528 if (isTLS) { 12529 TLSFinished tlsFinished; 12530 12531 if (length != sizeof(tlsFinished)) { 12532 #ifndef UNSAFE_FUZZER_MODE 12533 (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 12534 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); 12535 return SECFailure; 12536 #endif 12537 } 12538 rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer, 12539 &hashes, &tlsFinished); 12540 if (!isServer) 12541 ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; 12542 else 12543 ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; 12544 ss->ssl3.hs.finishedBytes = sizeof(tlsFinished); 12545 if (rv != SECSuccess || 12546 0 != NSS_SecureMemcmp(&tlsFinished, b, 12547 PR_MIN(length, ss->ssl3.hs.finishedBytes))) { 12548 #ifndef UNSAFE_FUZZER_MODE 12549 (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); 12550 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 12551 return SECFailure; 12552 #endif 12553 } 12554 } else { 12555 if (length != sizeof(SSL3Finished)) { 12556 (void)ssl3_IllegalParameter(ss); 12557 PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); 12558 return SECFailure; 12559 } 12560 12561 if (!isServer) 12562 ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; 12563 else 12564 ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; 12565 PORT_Assert(hashes.len == sizeof hashes.u.s); 12566 ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; 12567 if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) { 12568 (void)ssl3_HandshakeFailure(ss); 12569 PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 12570 return SECFailure; 12571 } 12572 } 12573 12574 ssl_GetXmitBufLock(ss); /*************************************/ 12575 12576 if ((isServer && !ss->ssl3.hs.isResuming) || 12577 (!isServer && ss->ssl3.hs.isResuming)) { 12578 PRInt32 flags = 0; 12579 12580 /* Send a NewSessionTicket message if the client sent us 12581 * either an empty session ticket, or one that did not verify. 12582 * (Note that if either of these conditions was met, then the 12583 * server has sent a SessionTicket extension in the 12584 * ServerHello message.) 12585 */ 12586 if (isServer && !ss->ssl3.hs.isResuming && 12587 ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && 12588 ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) { 12589 /* RFC 5077 Section 3.3: "In the case of a full handshake, the 12590 * server MUST verify the client's Finished message before sending 12591 * the ticket." Presumably, this also means that the client's 12592 * certificate, if any, must be verified beforehand too. 12593 */ 12594 rv = ssl3_SendNewSessionTicket(ss); 12595 if (rv != SECSuccess) { 12596 goto xmit_loser; 12597 } 12598 } 12599 12600 rv = ssl3_SendChangeCipherSpecs(ss); 12601 if (rv != SECSuccess) { 12602 goto xmit_loser; /* err is set. */ 12603 } 12604 /* If this thread is in SSL_SecureSend (trying to write some data) 12605 ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the 12606 ** last two handshake messages (change cipher spec and finished) 12607 ** will be sent in the same send/write call as the application data. 12608 */ 12609 if (ss->writerThread == PR_GetCurrentThread()) { 12610 flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; 12611 } 12612 12613 if (!isServer && !ss->firstHsDone) { 12614 rv = ssl3_SendNextProto(ss); 12615 if (rv != SECSuccess) { 12616 goto xmit_loser; /* err code was set. */ 12617 } 12618 } 12619 12620 if (IS_DTLS(ss)) { 12621 flags |= ssl_SEND_FLAG_NO_RETRANSMIT; 12622 } 12623 12624 rv = ssl3_SendFinished(ss, flags); 12625 if (rv != SECSuccess) { 12626 goto xmit_loser; /* err is set. */ 12627 } 12628 } 12629 12630 xmit_loser: 12631 ssl_ReleaseXmitBufLock(ss); /*************************************/ 12632 if (rv != SECSuccess) { 12633 return rv; 12634 } 12635 12636 if (ss->ssl3.hs.authCertificatePending) { 12637 if (ss->ssl3.hs.restartTarget) { 12638 PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); 12639 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 12640 return SECFailure; 12641 } 12642 12643 ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; 12644 PORT_SetError(PR_WOULD_BLOCK_ERROR); 12645 return SECFailure; 12646 } 12647 12648 rv = ssl3_FinishHandshake(ss); 12649 return rv; 12650 } 12651 12652 SECStatus 12653 ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret) 12654 { 12655 PORT_Assert(secret); 12656 12657 /* fill in the sid */ 12658 sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; 12659 sid->u.ssl3.policy = ss->ssl3.policy; 12660 sid->version = ss->version; 12661 sid->authType = ss->sec.authType; 12662 sid->authKeyBits = ss->sec.authKeyBits; 12663 sid->keaType = ss->sec.keaType; 12664 sid->keaKeyBits = ss->sec.keaKeyBits; 12665 if (ss->sec.keaGroup) { 12666 sid->keaGroup = ss->sec.keaGroup->name; 12667 } else { 12668 sid->keaGroup = ssl_grp_none; 12669 } 12670 sid->sigScheme = ss->sec.signatureScheme; 12671 sid->lastAccessTime = sid->creationTime = ssl_Time(ss); 12672 sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC); 12673 if (sid->localCert) { 12674 CERT_DestroyCertificate(sid->localCert); 12675 } 12676 sid->localCert = CERT_DupCertificate(ss->sec.localCert); 12677 if (ss->sec.isServer) { 12678 sid->namedCurve = ss->sec.serverCert->namedCurve; 12679 } 12680 12681 if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT && 12682 ss->xtnData.nextProto.data) { 12683 SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE); 12684 if (SECITEM_CopyItem( 12685 NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) { 12686 return SECFailure; /* error already set. */ 12687 } 12688 } 12689 12690 /* Copy the master secret (wrapped or unwrapped) into the sid */ 12691 return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret); 12692 } 12693 12694 /* The return type is SECStatus instead of void because this function needs 12695 * to have type sslRestartTarget. 12696 */ 12697 SECStatus 12698 ssl3_FinishHandshake(sslSocket *ss) 12699 { 12700 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 12701 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 12702 PORT_Assert(ss->ssl3.hs.restartTarget == NULL); 12703 sslSessionID *sid = ss->sec.ci.sid; 12704 SECStatus sidRv = SECFailure; 12705 12706 /* The first handshake is now completed. */ 12707 ss->handshake = NULL; 12708 12709 if (sid->cached == never_cached && !ss->opt.noCache) { 12710 /* If the wrap fails, don't cache the sid. The connection proceeds 12711 * normally, so the rv is only used to determine whether we cache. */ 12712 sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret); 12713 } 12714 12715 /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid 12716 * until it has verified the server's Finished message." When the server 12717 * sends a NewSessionTicket in a resumption handshake, we must wait until 12718 * the handshake is finished (we have verified the server's Finished 12719 * AND the server's certificate) before we update the ticket in the sid. 12720 * 12721 * This must be done before we call ssl_CacheSessionID(ss) 12722 * because CacheSID requires the session ticket to already be set, and also 12723 * because of the lazy lock creation scheme used by CacheSID and 12724 * ssl3_SetSIDSessionTicket. */ 12725 if (ss->ssl3.hs.receivedNewSessionTicket) { 12726 PORT_Assert(!ss->sec.isServer); 12727 if (sidRv == SECSuccess) { 12728 /* The sid takes over the ticket data */ 12729 ssl3_SetSIDSessionTicket(ss->sec.ci.sid, 12730 &ss->ssl3.hs.newSessionTicket); 12731 } else { 12732 PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data); 12733 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, 12734 PR_FALSE); 12735 } 12736 PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); 12737 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 12738 } 12739 if (sidRv == SECSuccess) { 12740 PORT_Assert(ss->sec.ci.sid->cached == never_cached); 12741 ssl_CacheSessionID(ss); 12742 } 12743 12744 ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ 12745 ss->ssl3.hs.ws = idle_handshake; 12746 12747 return ssl_FinishHandshake(ss); 12748 } 12749 12750 SECStatus 12751 ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct, 12752 PRUint32 dtlsSeq, 12753 const PRUint8 *b, PRUint32 length, 12754 sslUpdateHandshakeHashes updateHashes) 12755 { 12756 PRUint8 hdr[4]; 12757 PRUint8 dtlsData[8]; 12758 SECStatus rv; 12759 12760 PRINT_BUF(50, (ss, "Hash handshake message:", b, length)); 12761 12762 hdr[0] = (PRUint8)ct; 12763 hdr[1] = (PRUint8)(length >> 16); 12764 hdr[2] = (PRUint8)(length >> 8); 12765 hdr[3] = (PRUint8)(length); 12766 12767 rv = updateHashes(ss, (unsigned char *)hdr, 4); 12768 if (rv != SECSuccess) 12769 return rv; /* err code already set. */ 12770 12771 /* Extra data to simulate a complete DTLS handshake fragment */ 12772 if (IS_DTLS_1_OR_12(ss)) { 12773 /* Sequence number */ 12774 dtlsData[0] = MSB(dtlsSeq); 12775 dtlsData[1] = LSB(dtlsSeq); 12776 12777 /* Fragment offset */ 12778 dtlsData[2] = 0; 12779 dtlsData[3] = 0; 12780 dtlsData[4] = 0; 12781 12782 /* Fragment length */ 12783 dtlsData[5] = (PRUint8)(length >> 16); 12784 dtlsData[6] = (PRUint8)(length >> 8); 12785 dtlsData[7] = (PRUint8)(length); 12786 12787 rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData)); 12788 if (rv != SECSuccess) 12789 return rv; /* err code already set. */ 12790 } 12791 12792 /* The message body */ 12793 rv = updateHashes(ss, b, length); 12794 if (rv != SECSuccess) 12795 return rv; /* err code already set. */ 12796 12797 return SECSuccess; 12798 } 12799 12800 SECStatus 12801 ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct, 12802 const PRUint8 *b, PRUint32 length) 12803 { 12804 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq, 12805 b, length, ssl3_UpdateHandshakeHashes); 12806 } 12807 12808 SECStatus 12809 ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct, 12810 const PRUint8 *b, PRUint32 length) 12811 { 12812 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq, 12813 b, length, ssl3_UpdateDefaultHandshakeHashes); 12814 } 12815 SECStatus 12816 ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct, 12817 const PRUint8 *b, PRUint32 length) 12818 { 12819 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq, 12820 b, length, ssl3_UpdateInnerHandshakeHashes); 12821 } 12822 12823 SECStatus 12824 ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct, 12825 const PRUint8 *b, PRUint32 length) 12826 { 12827 return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq, 12828 b, length, ssl3_UpdatePostHandshakeHashes); 12829 } 12830 12831 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3 12832 * handshake message. 12833 * Caller must hold Handshake and RecvBuf locks. 12834 */ 12835 SECStatus 12836 ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length, 12837 PRBool endOfRecord) 12838 { 12839 SECStatus rv = SECSuccess; 12840 PRUint16 epoch; 12841 12842 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 12843 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 12844 12845 SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), 12846 ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); 12847 12848 /* Start new handshake hashes when we start a new handshake. */ 12849 if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) { 12850 ssl3_RestartHandshakeHashes(ss); 12851 } 12852 switch (ss->ssl3.hs.msg_type) { 12853 case ssl_hs_hello_request: 12854 case ssl_hs_hello_verify_request: 12855 /* We don't include hello_request and hello_verify_request messages 12856 * in the handshake hashes */ 12857 break; 12858 12859 /* Defer hashing of these messages until the message handlers. */ 12860 case ssl_hs_client_hello: 12861 case ssl_hs_server_hello: 12862 case ssl_hs_certificate_verify: 12863 case ssl_hs_finished: 12864 break; 12865 12866 default: 12867 if (!tls13_IsPostHandshake(ss)) { 12868 rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length); 12869 if (rv != SECSuccess) { 12870 return SECFailure; 12871 } 12872 } 12873 } 12874 12875 PORT_SetError(0); /* each message starts with no error. */ 12876 12877 if (ss->ssl3.hs.ws == wait_certificate_status && 12878 ss->ssl3.hs.msg_type != ssl_hs_certificate_status) { 12879 /* If we negotiated the certificate_status extension then we deferred 12880 * certificate validation until we get the CertificateStatus messsage. 12881 * But the CertificateStatus message is optional. If the server did 12882 * not send it then we need to validate the certificate now. If the 12883 * server does send the CertificateStatus message then we will 12884 * authenticate the certificate in ssl3_HandleCertificateStatus. 12885 */ 12886 rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ 12887 if (rv != SECSuccess) { 12888 /* This can't block. */ 12889 PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR); 12890 return SECFailure; 12891 } 12892 } 12893 12894 epoch = ss->ssl3.crSpec->epoch; 12895 switch (ss->ssl3.hs.msg_type) { 12896 case ssl_hs_client_hello: 12897 if (!ss->sec.isServer) { 12898 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12899 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); 12900 return SECFailure; 12901 } 12902 rv = ssl3_HandleClientHello(ss, b, length); 12903 break; 12904 case ssl_hs_server_hello: 12905 if (ss->sec.isServer) { 12906 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12907 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO); 12908 return SECFailure; 12909 } 12910 rv = ssl3_HandleServerHello(ss, b, length); 12911 break; 12912 default: 12913 if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { 12914 rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length); 12915 } else { 12916 rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length); 12917 } 12918 break; 12919 } 12920 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 12921 (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) { 12922 /* If we changed read cipher states, there must not be any 12923 * data in the input queue. */ 12924 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12925 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 12926 return SECFailure; 12927 } 12928 /* We consider the record to have been handled if SECSuccess or else WOULD_BLOCK is set 12929 * Whoever set WOULD_BLOCK must handle any remaining actions required to finsih processing the record. 12930 * e.g. by setting restartTarget. 12931 */ 12932 if (IS_DTLS(ss) && (rv == SECSuccess || (rv == SECFailure && PR_GetError() == PR_WOULD_BLOCK_ERROR))) { 12933 /* Increment the expected sequence number */ 12934 ss->ssl3.hs.recvMessageSeq++; 12935 } 12936 12937 /* Taint the message so that it's easier to detect UAFs. */ 12938 PORT_Memset(b, 'N', length); 12939 12940 return rv; 12941 } 12942 12943 static SECStatus 12944 ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b, 12945 PRUint32 length) 12946 { 12947 SECStatus rv; 12948 PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); 12949 12950 switch (ss->ssl3.hs.msg_type) { 12951 case ssl_hs_hello_request: 12952 if (length != 0) { 12953 (void)ssl3_DecodeError(ss); 12954 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); 12955 return SECFailure; 12956 } 12957 if (ss->sec.isServer) { 12958 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12959 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); 12960 return SECFailure; 12961 } 12962 rv = ssl3_HandleHelloRequest(ss); 12963 break; 12964 12965 case ssl_hs_hello_verify_request: 12966 if (!IS_DTLS(ss) || ss->sec.isServer) { 12967 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12968 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST); 12969 return SECFailure; 12970 } 12971 rv = dtls_HandleHelloVerifyRequest(ss, b, length); 12972 break; 12973 case ssl_hs_certificate: 12974 rv = ssl3_HandleCertificate(ss, b, length); 12975 break; 12976 case ssl_hs_certificate_status: 12977 rv = ssl3_HandleCertificateStatus(ss, b, length); 12978 break; 12979 case ssl_hs_server_key_exchange: 12980 if (ss->sec.isServer) { 12981 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12982 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); 12983 return SECFailure; 12984 } 12985 rv = ssl3_HandleServerKeyExchange(ss, b, length); 12986 break; 12987 case ssl_hs_certificate_request: 12988 if (ss->sec.isServer) { 12989 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 12990 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST); 12991 return SECFailure; 12992 } 12993 rv = ssl3_HandleCertificateRequest(ss, b, length); 12994 break; 12995 case ssl_hs_server_hello_done: 12996 if (length != 0) { 12997 (void)ssl3_DecodeError(ss); 12998 PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE); 12999 return SECFailure; 13000 } 13001 if (ss->sec.isServer) { 13002 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13003 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); 13004 return SECFailure; 13005 } 13006 rv = ssl3_HandleServerHelloDone(ss); 13007 break; 13008 case ssl_hs_certificate_verify: 13009 if (!ss->sec.isServer) { 13010 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13011 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY); 13012 return SECFailure; 13013 } 13014 rv = ssl3_HandleCertificateVerify(ss, b, length); 13015 break; 13016 case ssl_hs_client_key_exchange: 13017 if (!ss->sec.isServer) { 13018 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13019 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); 13020 return SECFailure; 13021 } 13022 rv = ssl3_HandleClientKeyExchange(ss, b, length); 13023 break; 13024 case ssl_hs_new_session_ticket: 13025 if (ss->sec.isServer) { 13026 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13027 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); 13028 return SECFailure; 13029 } 13030 rv = ssl3_HandleNewSessionTicket(ss, b, length); 13031 break; 13032 case ssl_hs_finished: 13033 rv = ssl3_HandleFinished(ss, b, length); 13034 break; 13035 default: 13036 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13037 PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); 13038 rv = SECFailure; 13039 } 13040 13041 return rv; 13042 } 13043 13044 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record. 13045 * origBuf is the decrypted ssl record content. 13046 * Caller must hold the handshake and RecvBuf locks. 13047 */ 13048 static SECStatus 13049 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) 13050 { 13051 sslBuffer buf = *origBuf; /* Work from a copy. */ 13052 SECStatus rv; 13053 13054 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 13055 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 13056 13057 while (buf.len > 0) { 13058 if (ss->ssl3.hs.header_bytes < 4) { 13059 PRUint8 t; 13060 t = *(buf.buf++); 13061 buf.len--; 13062 if (ss->ssl3.hs.header_bytes++ == 0) 13063 ss->ssl3.hs.msg_type = (SSLHandshakeType)t; 13064 else 13065 ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; 13066 if (ss->ssl3.hs.header_bytes < 4) 13067 continue; 13068 13069 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */ 13070 if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { 13071 (void)ssl3_DecodeError(ss); 13072 PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE); 13073 goto loser; 13074 } 13075 #undef MAX_HANDSHAKE_MSG_LEN 13076 13077 /* If msg_len is zero, be sure we fall through, 13078 ** even if buf.len is zero. 13079 */ 13080 if (ss->ssl3.hs.msg_len > 0) 13081 continue; 13082 } 13083 13084 /* 13085 * Header has been gathered and there is at least one byte of new 13086 * data available for this message. If it can be done right out 13087 * of the original buffer, then use it from there. 13088 */ 13089 if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) { 13090 /* handle it from input buffer */ 13091 rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len, 13092 buf.len == ss->ssl3.hs.msg_len); 13093 buf.buf += ss->ssl3.hs.msg_len; 13094 buf.len -= ss->ssl3.hs.msg_len; 13095 ss->ssl3.hs.msg_len = 0; 13096 ss->ssl3.hs.header_bytes = 0; 13097 if (rv != SECSuccess) { 13098 goto loser; 13099 } 13100 } else { 13101 /* must be copied to msg_body and dealt with from there */ 13102 unsigned int bytes; 13103 13104 PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); 13105 bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len); 13106 13107 /* Grow the buffer if needed */ 13108 rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); 13109 if (rv != SECSuccess) { 13110 /* sslBuffer_Grow has set a memory error code. */ 13111 goto loser; 13112 } 13113 13114 PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, 13115 buf.buf, bytes); 13116 ss->ssl3.hs.msg_body.len += bytes; 13117 buf.buf += bytes; 13118 buf.len -= bytes; 13119 13120 PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); 13121 13122 /* if we have a whole message, do it */ 13123 if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { 13124 rv = ssl3_HandleHandshakeMessage( 13125 ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len, 13126 buf.len == 0); 13127 ss->ssl3.hs.msg_body.len = 0; 13128 ss->ssl3.hs.msg_len = 0; 13129 ss->ssl3.hs.header_bytes = 0; 13130 if (rv != SECSuccess) { 13131 goto loser; 13132 } 13133 } else { 13134 PORT_Assert(buf.len == 0); 13135 break; 13136 } 13137 } 13138 } /* end loop */ 13139 13140 origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ 13141 return SECSuccess; 13142 13143 loser : { 13144 /* Make sure to remove any data that was consumed. */ 13145 unsigned int consumed = origBuf->len - buf.len; 13146 PORT_Assert(consumed == buf.buf - origBuf->buf); 13147 if (consumed > 0) { 13148 memmove(origBuf->buf, origBuf->buf + consumed, buf.len); 13149 origBuf->len = buf.len; 13150 } 13151 } 13152 return SECFailure; 13153 } 13154 13155 /* SECStatusToMask returns, in constant time, a mask value of all ones if 13156 * rv == SECSuccess. Otherwise it returns zero. */ 13157 static unsigned int 13158 SECStatusToMask(SECStatus rv) 13159 { 13160 return PORT_CT_EQ(rv, SECSuccess); 13161 } 13162 13163 /* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */ 13164 static unsigned char 13165 ssl_ConstantTimeGE(unsigned int a, unsigned int b) 13166 { 13167 return PORT_CT_GE(a, b); 13168 } 13169 13170 /* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */ 13171 static unsigned char 13172 ssl_ConstantTimeEQ(unsigned char a, unsigned char b) 13173 { 13174 return PORT_CT_EQ(a, b); 13175 } 13176 13177 /* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */ 13178 static unsigned char 13179 ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b) 13180 { 13181 return (mask & a) | (~mask & b); 13182 } 13183 13184 static SECStatus 13185 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, 13186 unsigned int blockSize, 13187 unsigned int macSize) 13188 { 13189 unsigned int paddingLength, good; 13190 const unsigned int overhead = 1 /* padding length byte */ + macSize; 13191 13192 /* These lengths are all public so we can test them in non-constant 13193 * time. */ 13194 if (overhead > plaintext->len) { 13195 return SECFailure; 13196 } 13197 13198 paddingLength = plaintext->buf[plaintext->len - 1]; 13199 /* SSLv3 padding bytes are random and cannot be checked. */ 13200 good = PORT_CT_GE(plaintext->len, paddingLength + overhead); 13201 /* SSLv3 requires that the padding is minimal. */ 13202 good &= PORT_CT_GE(blockSize, paddingLength + 1); 13203 plaintext->len -= good & (paddingLength + 1); 13204 return (good & SECSuccess) | (~good & SECFailure); 13205 } 13206 13207 SECStatus 13208 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) 13209 { 13210 unsigned int paddingLength, good, toCheck, i; 13211 const unsigned int overhead = 1 /* padding length byte */ + macSize; 13212 13213 /* These lengths are all public so we can test them in non-constant 13214 * time. */ 13215 if (overhead > plaintext->len) { 13216 return SECFailure; 13217 } 13218 13219 paddingLength = plaintext->buf[plaintext->len - 1]; 13220 good = PORT_CT_GE(plaintext->len, paddingLength + overhead); 13221 13222 /* The padding consists of a length byte at the end of the record and then 13223 * that many bytes of padding, all with the same value as the length byte. 13224 * Thus, with the length byte included, there are paddingLength+1 bytes of 13225 * padding. 13226 * 13227 * We can't check just |paddingLength+1| bytes because that leaks 13228 * decrypted information. Therefore we always have to check the maximum 13229 * amount of padding possible. (Again, the length of the record is 13230 * public information so we can use it.) */ 13231 toCheck = 256; /* maximum amount of padding + 1. */ 13232 if (toCheck > plaintext->len) { 13233 toCheck = plaintext->len; 13234 } 13235 13236 for (i = 0; i < toCheck; i++) { 13237 /* If i <= paddingLength then the MSB of t is zero and mask is 13238 * 0xff. Otherwise, mask is 0. */ 13239 unsigned char mask = PORT_CT_LE(i, paddingLength); 13240 unsigned char b = plaintext->buf[plaintext->len - 1 - i]; 13241 /* The final |paddingLength+1| bytes should all have the value 13242 * |paddingLength|. Therefore the XOR should be zero. */ 13243 good &= ~(mask & (paddingLength ^ b)); 13244 } 13245 13246 /* If any of the final |paddingLength+1| bytes had the wrong value, 13247 * one or more of the lower eight bits of |good| will be cleared. We 13248 * AND the bottom 8 bits together and duplicate the result to all the 13249 * bits. */ 13250 good &= good >> 4; 13251 good &= good >> 2; 13252 good &= good >> 1; 13253 good <<= sizeof(good) * 8 - 1; 13254 good = PORT_CT_DUPLICATE_MSB_TO_ALL(good); 13255 13256 plaintext->len -= good & (paddingLength + 1); 13257 return (good & SECSuccess) | (~good & SECFailure); 13258 } 13259 13260 /* On entry: 13261 * originalLength >= macSize 13262 * macSize <= MAX_MAC_LENGTH 13263 * plaintext->len >= macSize 13264 */ 13265 static void 13266 ssl_CBCExtractMAC(sslBuffer *plaintext, 13267 unsigned int originalLength, 13268 PRUint8 *out, 13269 unsigned int macSize) 13270 { 13271 unsigned char rotatedMac[MAX_MAC_LENGTH]; 13272 /* macEnd is the index of |plaintext->buf| just after the end of the 13273 * MAC. */ 13274 unsigned macEnd = plaintext->len; 13275 unsigned macStart = macEnd - macSize; 13276 /* scanStart contains the number of bytes that we can ignore because 13277 * the MAC's position can only vary by 255 bytes. */ 13278 unsigned scanStart = 0; 13279 unsigned i, j; 13280 unsigned char rotateOffset; 13281 13282 if (originalLength > macSize + 255 + 1) { 13283 scanStart = originalLength - (macSize + 255 + 1); 13284 } 13285 13286 /* We want to compute 13287 * rotateOffset = (macStart - scanStart) % macSize 13288 * But the time to compute this varies based on the amount of padding. Thus 13289 * we explicitely handle all mac sizes with (hopefully) constant time modulo 13290 * using Barrett reduction: 13291 * q := (rotateOffset * m) >> k 13292 * rotateOffset -= q * n 13293 * if (n <= rotateOffset) rotateOffset -= n 13294 */ 13295 rotateOffset = macStart - scanStart; 13296 /* rotateOffset < 255 + 1 + 48 = 304 */ 13297 if (macSize == 16) { 13298 rotateOffset &= 15; 13299 } else if (macSize == 20) { 13300 /* 13301 * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1 13302 * with rotateOffset <= 853 13303 */ 13304 unsigned q = (rotateOffset * 25) >> 9; 13305 rotateOffset -= q * 20; 13306 rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20), 13307 20, 0); 13308 } else if (macSize == 32) { 13309 rotateOffset &= 31; 13310 } else if (macSize == 48) { 13311 /* 13312 * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1 13313 * with rotateOffset < 768 13314 */ 13315 unsigned q = (rotateOffset * 10) >> 9; 13316 rotateOffset -= q * 48; 13317 rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48), 13318 48, 0); 13319 } else { 13320 /* 13321 * SHA384 (macSize == 48) is the largest we support. We should never 13322 * get here. 13323 */ 13324 PORT_Assert(0); 13325 rotateOffset = rotateOffset % macSize; 13326 } 13327 13328 memset(rotatedMac, 0, macSize); 13329 for (i = scanStart; i < originalLength;) { 13330 for (j = 0; j < macSize && i < originalLength; i++, j++) { 13331 unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); 13332 unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); 13333 unsigned char b = 0; 13334 b = plaintext->buf[i]; 13335 rotatedMac[j] |= b & macStarted & ~macEnded; 13336 } 13337 } 13338 13339 /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line 13340 * we could line-align |rotatedMac| and rotate in place. */ 13341 memset(out, 0, macSize); 13342 rotateOffset = macSize - rotateOffset; 13343 rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize), 13344 0, rotateOffset); 13345 for (i = 0; i < macSize; i++) { 13346 for (j = 0; j < macSize; j++) { 13347 out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset); 13348 } 13349 rotateOffset++; 13350 rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize), 13351 0, rotateOffset); 13352 } 13353 } 13354 13355 /* MAX_EXPANSION is the amount by which a record might plausibly be expanded 13356 * when protected. It's the worst case estimate, so the sum of block cipher 13357 * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16 13358 * octets for AES). */ 13359 #define MAX_EXPANSION (256 + 48 + 16) 13360 13361 /* Unprotect an SSL3 record and leave the result in plaintext. 13362 * 13363 * If SECFailure is returned, we: 13364 * 1. Set |*alert| to the alert to be sent. 13365 * 2. Call PORT_SetError() with an appropriate code. 13366 * 13367 * Called by ssl3_HandleRecord. Caller must hold the spec read lock. 13368 * Therefore, we MUST not call SSL3_SendAlert(). 13369 * 13370 */ 13371 static SECStatus 13372 ssl3_UnprotectRecord(sslSocket *ss, 13373 ssl3CipherSpec *spec, 13374 SSL3Ciphertext *cText, sslBuffer *plaintext, 13375 SSL3AlertDescription *alert) 13376 { 13377 const ssl3BulkCipherDef *cipher_def = spec->cipherDef; 13378 PRBool isTLS; 13379 unsigned int good; 13380 unsigned int ivLen = 0; 13381 SSLContentType rType; 13382 SSL3ProtocolVersion rVersion; 13383 unsigned int minLength; 13384 unsigned int originalLen = 0; 13385 PRUint8 headerBuf[13]; 13386 sslBuffer header = SSL_BUFFER(headerBuf); 13387 PRUint8 hash[MAX_MAC_LENGTH]; 13388 PRUint8 givenHashBuf[MAX_MAC_LENGTH]; 13389 PRUint8 *givenHash; 13390 unsigned int hashBytes = MAX_MAC_LENGTH + 1; 13391 SECStatus rv; 13392 13393 PORT_Assert(spec->direction == ssl_secret_read); 13394 13395 good = ~0U; 13396 minLength = spec->macDef->mac_size; 13397 if (cipher_def->type == type_block) { 13398 /* CBC records have a padding length byte at the end. */ 13399 minLength++; 13400 if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 13401 /* With >= TLS 1.1, CBC records have an explicit IV. */ 13402 minLength += cipher_def->iv_size; 13403 } 13404 } else if (cipher_def->type == type_aead) { 13405 minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; 13406 } 13407 13408 /* We can perform this test in variable time because the record's total 13409 * length and the ciphersuite are both public knowledge. */ 13410 if (cText->buf->len < minLength) { 13411 goto decrypt_loser; 13412 } 13413 13414 if (cipher_def->type == type_block && 13415 spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 13416 /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states 13417 * "The receiver decrypts the entire GenericBlockCipher structure and 13418 * then discards the first cipher block corresponding to the IV 13419 * component." Instead, we decrypt the first cipher block and then 13420 * discard it before decrypting the rest. 13421 */ 13422 PRUint8 iv[MAX_IV_LENGTH]; 13423 unsigned int decoded; 13424 13425 ivLen = cipher_def->iv_size; 13426 if (ivLen < 8 || ivLen > sizeof(iv)) { 13427 *alert = internal_error; 13428 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 13429 return SECFailure; 13430 } 13431 13432 PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen)); 13433 13434 /* The decryption result is garbage, but since we just throw away 13435 * the block it doesn't matter. The decryption of the next block 13436 * depends only on the ciphertext of the IV block. 13437 */ 13438 rv = spec->cipher(spec->cipherContext, iv, &decoded, 13439 sizeof(iv), cText->buf->buf, ivLen); 13440 13441 good &= SECStatusToMask(rv); 13442 } 13443 13444 PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, 13445 cText->buf->len - ivLen)); 13446 13447 /* Check if the ciphertext can be valid if we assume maximum plaintext and 13448 * add the maximum possible ciphersuite expansion. 13449 * This way we detect overlong plaintexts/padding before decryption. 13450 * This check enforces size limitations more strict than the RFC. 13451 * [RFC5246, Section 6.2.3] */ 13452 if (cText->buf->len > (spec->recordSizeLimit + MAX_EXPANSION)) { 13453 *alert = record_overflow; 13454 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 13455 return SECFailure; 13456 } 13457 13458 isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); 13459 rType = (SSLContentType)cText->hdr[0]; 13460 rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) | 13461 (SSL3ProtocolVersion)cText->hdr[2]; 13462 if (cipher_def->type == type_aead) { 13463 /* XXX For many AEAD ciphers, the plaintext is shorter than the 13464 * ciphertext by a fixed byte count, but it is not true in general. 13465 * Each AEAD cipher should provide a function that returns the 13466 * plaintext length for a given ciphertext. */ 13467 const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size; 13468 const unsigned int tagLen = cipher_def->tag_size; 13469 unsigned int nonceLen = explicitNonceLen; 13470 unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen; 13471 /* even though read doesn't return and IV, we still need a space to put 13472 * the combined iv/nonce n the gcm 1.2 case*/ 13473 unsigned char ivOut[MAX_IV_LENGTH]; 13474 unsigned char *iv = NULL; 13475 unsigned char *nonce = NULL; 13476 13477 ivLen = cipher_def->iv_size; 13478 13479 rv = ssl3_BuildRecordPseudoHeader( 13480 spec->epoch, cText->seqNum, 13481 rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header, spec->version); 13482 PORT_Assert(rv == SECSuccess); 13483 13484 /* build the iv */ 13485 if (explicitNonceLen == 0) { 13486 nonceLen = sizeof(cText->seqNum); 13487 iv = spec->keyMaterial.iv; 13488 nonce = SSL_BUFFER_BASE(&header); 13489 } else { 13490 PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen); 13491 PORT_Memset(ivOut + ivLen, 0, explicitNonceLen); 13492 iv = ivOut; 13493 nonce = cText->buf->buf; 13494 nonceLen = explicitNonceLen; 13495 } 13496 rv = tls13_AEAD(spec->cipherContext, PR_TRUE, 13497 CKG_NO_GENERATE, 0, /* iv generator params 13498 * (not used in decrypt)*/ 13499 iv, /* iv in */ 13500 NULL, /* iv out */ 13501 ivLen + explicitNonceLen, /* full iv length */ 13502 nonce, nonceLen, /* nonce in */ 13503 SSL_BUFFER_BASE(&header), /* aad */ 13504 SSL_BUFFER_LEN(&header), /* aadlen */ 13505 plaintext->buf, /* output */ 13506 &plaintext->len, /* out len */ 13507 plaintext->space, /* max out */ 13508 tagLen, 13509 cText->buf->buf + explicitNonceLen, /* input */ 13510 cText->buf->len - explicitNonceLen); /* input len */ 13511 if (rv != SECSuccess) { 13512 good = 0; 13513 } 13514 } else { 13515 if (cipher_def->type == type_block && 13516 ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { 13517 goto decrypt_loser; 13518 } 13519 13520 /* decrypt from cText buf to plaintext. */ 13521 rv = spec->cipher( 13522 spec->cipherContext, plaintext->buf, &plaintext->len, 13523 plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); 13524 if (rv != SECSuccess) { 13525 goto decrypt_loser; 13526 } 13527 13528 PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); 13529 13530 originalLen = plaintext->len; 13531 13532 /* If it's a block cipher, check and strip the padding. */ 13533 if (cipher_def->type == type_block) { 13534 const unsigned int blockSize = cipher_def->block_size; 13535 const unsigned int macSize = spec->macDef->mac_size; 13536 13537 if (!isTLS) { 13538 good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( 13539 plaintext, blockSize, macSize)); 13540 } else { 13541 good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( 13542 plaintext, macSize)); 13543 } 13544 } 13545 13546 /* compute the MAC */ 13547 rv = ssl3_BuildRecordPseudoHeader( 13548 spec->epoch, cText->seqNum, 13549 rType, isTLS, rVersion, IS_DTLS(ss), 13550 plaintext->len - spec->macDef->mac_size, &header, spec->version); 13551 PORT_Assert(rv == SECSuccess); 13552 if (cipher_def->type == type_block) { 13553 rv = ssl3_ComputeRecordMACConstantTime( 13554 spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header), 13555 plaintext->buf, plaintext->len, originalLen, 13556 hash, &hashBytes); 13557 13558 ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, 13559 spec->macDef->mac_size); 13560 givenHash = givenHashBuf; 13561 13562 /* plaintext->len will always have enough space to remove the MAC 13563 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust 13564 * plaintext->len if the result has enough space for the MAC and we 13565 * tested the unadjusted size against minLength, above. */ 13566 plaintext->len -= spec->macDef->mac_size; 13567 } else { 13568 /* This is safe because we checked the minLength above. */ 13569 plaintext->len -= spec->macDef->mac_size; 13570 13571 rv = ssl3_ComputeRecordMAC( 13572 spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header), 13573 plaintext->buf, plaintext->len, hash, &hashBytes); 13574 13575 /* We can read the MAC directly from the record because its location 13576 * is public when a stream cipher is used. */ 13577 givenHash = plaintext->buf + plaintext->len; 13578 } 13579 13580 good &= SECStatusToMask(rv); 13581 13582 if (hashBytes != (unsigned)spec->macDef->mac_size || 13583 NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) { 13584 /* We're allowed to leak whether or not the MAC check was correct */ 13585 good = 0; 13586 } 13587 } 13588 13589 if (good == 0) { 13590 decrypt_loser: 13591 /* always log mac error, in case attacker can read server logs. */ 13592 PORT_SetError(SSL_ERROR_BAD_MAC_READ); 13593 *alert = bad_record_mac; 13594 return SECFailure; 13595 } 13596 return SECSuccess; 13597 } 13598 13599 SECStatus 13600 ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType, 13601 DTLSEpoch epoch, sslSequenceNumber seqNum, 13602 sslBuffer *databuf) 13603 { 13604 SECStatus rv; 13605 13606 /* check for Token Presence */ 13607 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { 13608 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 13609 return SECFailure; 13610 } 13611 13612 ssl_GetSSL3HandshakeLock(ss); 13613 13614 /* All the functions called in this switch MUST set error code if 13615 ** they return SECFailure. 13616 */ 13617 switch (rType) { 13618 case ssl_ct_change_cipher_spec: 13619 rv = ssl3_HandleChangeCipherSpecs(ss, databuf); 13620 break; 13621 case ssl_ct_alert: 13622 rv = ssl3_HandleAlert(ss, databuf); 13623 break; 13624 case ssl_ct_handshake: 13625 if (!IS_DTLS(ss)) { 13626 rv = ssl3_HandleHandshake(ss, databuf); 13627 } else { 13628 rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf); 13629 } 13630 break; 13631 case ssl_ct_ack: 13632 if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) { 13633 rv = dtls13_HandleAck(ss, databuf); 13634 break; 13635 } 13636 /* Fall through. */ 13637 default: 13638 /* If a TLS implementation receives an unexpected record type, 13639 * it MUST terminate the connection with an "unexpected_message" 13640 * alert [RFC8446, Section 5]. 13641 * 13642 * For TLS 1.3 the outer content type is checked before in 13643 * tls13con.c/tls13_UnprotectRecord(), 13644 * For DTLS 1.3 the outer content type is checked before in 13645 * ssl3gthr.c/dtls_GatherData. 13646 * The inner content types will be checked here. 13647 * 13648 * In DTLS generally invalid records SHOULD be silently discarded, 13649 * no alert is sent [RFC6347, Section 4.1.2.7]. 13650 */ 13651 if (!IS_DTLS(ss)) { 13652 SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13653 } 13654 PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); 13655 SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", 13656 SSL_GETPID(), ss->fd, rType)); 13657 rv = SECFailure; 13658 break; 13659 } 13660 13661 ssl_ReleaseSSL3HandshakeLock(ss); 13662 return rv; 13663 } 13664 13665 /* Find the cipher spec to use for a given record. For TLS, this 13666 * is the current cipherspec. For DTLS, we look up by epoch. 13667 * In DTLS < 1.3 this just means the current epoch or nothing, 13668 * but in DTLS >= 1.3, we keep multiple reading cipherspecs. 13669 * Returns NULL if no appropriate cipher spec is found. 13670 */ 13671 static ssl3CipherSpec * 13672 ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText) 13673 { 13674 ssl3CipherSpec *crSpec = ss->ssl3.crSpec; 13675 ssl3CipherSpec *newSpec = NULL; 13676 DTLSEpoch epoch; 13677 13678 if (!IS_DTLS(ss)) { 13679 return crSpec; 13680 } 13681 epoch = dtls_ReadEpoch(crSpec->version, crSpec->epoch, cText->hdr); 13682 if (crSpec->epoch == epoch) { 13683 return crSpec; 13684 } 13685 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 13686 /* Try to find the cipher spec. */ 13687 newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read, 13688 epoch); 13689 if (newSpec != NULL) { 13690 return newSpec; 13691 } 13692 } 13693 SSL_TRC(10, ("%d: DTLS[%d]: %s couldn't find cipherspec from epoch %d", 13694 SSL_GETPID(), ss->fd, SSL_ROLE(ss), epoch)); 13695 return NULL; 13696 } 13697 13698 /* if cText is non-null, then decipher and check the MAC of the 13699 * SSL record from cText->buf (typically gs->inbuf) 13700 * into databuf (typically gs->buf), and any previous contents of databuf 13701 * is lost. Then handle databuf according to its SSL record type, 13702 * unless it's an application record. 13703 * 13704 * If cText is NULL, then the ciphertext has previously been deciphered and 13705 * checked, and is already sitting in databuf. It is processed as an SSL 13706 * Handshake message. 13707 * 13708 * DOES NOT process the decrypted application data. 13709 * On return, databuf contains the decrypted record. 13710 * 13711 * Called from ssl3_GatherCompleteHandshake 13712 * ssl3_RestartHandshakeAfterCertReq 13713 * 13714 * Caller must hold the RecvBufLock. 13715 * 13716 * This function aquires and releases the SSL3Handshake Lock, holding the 13717 * lock around any calls to functions that handle records other than 13718 * Application Data records. 13719 */ 13720 SECStatus 13721 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText) 13722 { 13723 SECStatus rv = SECFailure; 13724 PRBool isTLS, isTLS13; 13725 DTLSEpoch epoch; 13726 ssl3CipherSpec *spec = NULL; 13727 PRUint16 recordSizeLimit, cTextSizeLimit; 13728 PRBool outOfOrderSpec = PR_FALSE; 13729 SSLContentType rType; 13730 sslBuffer *plaintext = &ss->gs.buf; 13731 SSL3AlertDescription alert = internal_error; 13732 PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 13733 13734 /* check for Token Presence */ 13735 if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { 13736 PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 13737 return SECFailure; 13738 } 13739 13740 /* Clear out the buffer in case this exits early. Any data then won't be 13741 * processed twice. */ 13742 plaintext->len = 0; 13743 13744 /* We're waiting for another ClientHello, which will appear unencrypted. 13745 * Use the content type to tell whether this should be discarded. */ 13746 if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr && 13747 cText->hdr[0] == ssl_ct_application_data) { 13748 PORT_Assert(ss->ssl3.hs.ws == wait_client_hello); 13749 return SECSuccess; 13750 } 13751 13752 ssl_GetSpecReadLock(ss); /******************************************/ 13753 spec = ssl3_GetCipherSpec(ss, cText); 13754 if (!spec) { 13755 PORT_Assert(IS_DTLS(ss)); 13756 ssl_ReleaseSpecReadLock(ss); /*****************************/ 13757 return SECSuccess; 13758 } 13759 if (spec != ss->ssl3.crSpec) { 13760 PORT_Assert(IS_DTLS(ss)); 13761 SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d", 13762 SSL_GETPID(), ss->fd, spec->epoch)); 13763 outOfOrderSpec = PR_TRUE; 13764 } 13765 isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); 13766 if (IS_DTLS(ss)) { 13767 if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr, 13768 SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) { 13769 ssl_ReleaseSpecReadLock(ss); /*****************************/ 13770 /* code already set. */ 13771 return SECFailure; 13772 } 13773 if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) { 13774 ssl_ReleaseSpecReadLock(ss); /*****************************/ 13775 return SECSuccess; 13776 } 13777 } else { 13778 cText->seqNum = spec->nextSeqNum; 13779 } 13780 if (cText->seqNum >= spec->cipherDef->max_records) { 13781 ssl_ReleaseSpecReadLock(ss); /*****************************/ 13782 SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx", 13783 SSL_GETPID(), ss->fd, cText->seqNum)); 13784 PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS); 13785 return SECFailure; 13786 } 13787 13788 isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); 13789 recordSizeLimit = spec->recordSizeLimit; 13790 cTextSizeLimit = recordSizeLimit; 13791 cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION : TLS_1_2_MAX_EXPANSION; 13792 13793 /* Check if the specified recordSizeLimit and the RFC8446 specified max 13794 * expansion are respected. recordSizeLimit is probably at the default for 13795 * the first (hello) handshake message and then set to a smaller size by 13796 * the Record Size Limit Extension. 13797 * Stricter expansion size checks dependent on implemented cipher suites 13798 * are performed in ssl3con.c/ssl3_UnprotectRecord() OR 13799 * tls13con.c/tls13_UnprotextRecord(). 13800 * After Decryption the plaintext size is checked (l. 13424). This also 13801 * applies to unencrypted records. */ 13802 if (cText->buf->len > cTextSizeLimit) { 13803 ssl_ReleaseSpecReadLock(ss); /*****************************/ 13804 /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */ 13805 if (IS_DTLS(ss)) { 13806 return SECSuccess; 13807 } 13808 SSL3_SendAlert(ss, alert_fatal, record_overflow); 13809 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 13810 return SECFailure; 13811 } 13812 13813 #ifdef DEBUG 13814 /* In debug builds the gather buffers are freed after the handling of each 13815 * record for advanced ASAN coverage. Allocate the buffer again to the 13816 * maximum possibly needed size as on gather initialization in 13817 * ssl3gthr.c/ssl3_InitGather(). */ 13818 PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess); 13819 #endif 13820 /* This replaces a dynamic plaintext buffer size check, since the buffer is 13821 * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer 13822 * was always grown to the maximum size at first record gathering before. */ 13823 PR_ASSERT(plaintext->space >= cTextSizeLimit); 13824 13825 /* Most record types aside from protected TLS 1.3 records carry the content 13826 * type in the first octet. TLS 1.3 will override this value later. */ 13827 rType = cText->hdr[0]; 13828 /* Encrypted application data records could arrive before the handshake 13829 * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data 13830 * records in epoch 0, which is never valid. Pretend they didn't decrypt. */ 13831 if (spec->epoch == 0 && ((IS_DTLS(ss) && 13832 dtls_IsDtls13Ciphertext(0, rType)) || 13833 rType == ssl_ct_application_data)) { 13834 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); 13835 alert = unexpected_message; 13836 rv = SECFailure; 13837 } else { 13838 #ifdef UNSAFE_FUZZER_MODE 13839 rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len, 13840 plaintext->space, cText->buf->buf, cText->buf->len); 13841 #else 13842 /* IMPORTANT: 13843 * Unprotect functions MUST NOT send alerts 13844 * because we still hold the spec read lock. Instead, if they 13845 * return SECFailure, they set *alert to the alert to be sent. 13846 * Additionaly, this is used to silently drop DTLS encryption/record 13847 * errors/alerts using the error handling below as suggested in the 13848 * DTLS specification [RFC6347, Section 4.1.2.7]. */ 13849 if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) { 13850 /* Handle a zero-length unprotected record 13851 * In this case, we treat it as a no-op and let later functions decide 13852 * whether to ignore or alert accordingly. */ 13853 PR_ASSERT(plaintext->len == 0); 13854 rv = SECSuccess; 13855 } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 || spec->epoch == 0) { 13856 rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert); 13857 } else { 13858 rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType, 13859 &alert); 13860 } 13861 #endif 13862 } 13863 13864 /* Error/Alert handling for ssl3/tls13_UnprotectRecord */ 13865 if (rv != SECSuccess) { 13866 ssl_ReleaseSpecReadLock(ss); /***************************/ 13867 13868 SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); 13869 13870 /* Ensure that we don't process this data again. */ 13871 plaintext->len = 0; 13872 13873 /* Ignore a CCS if compatibility mode is negotiated. Note that this 13874 * will fail if the server fails to negotiate compatibility mode in a 13875 * 0-RTT session that is resumed from a session that did negotiate it. 13876 * We don't care about that corner case right now. */ 13877 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 13878 cText->hdr[0] == ssl_ct_change_cipher_spec && 13879 ss->ssl3.hs.ws != idle_handshake && 13880 cText->buf->len == 1 && 13881 cText->buf->buf[0] == change_cipher_spec_choice) { 13882 if (!ss->ssl3.hs.rejectCcs) { 13883 /* Allow only the first CCS. */ 13884 ss->ssl3.hs.rejectCcs = PR_TRUE; 13885 return SECSuccess; 13886 } else { 13887 alert = unexpected_message; 13888 PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); 13889 } 13890 } 13891 13892 /* All errors/alerts that might occur during unprotection are related 13893 * to invalid records (e.g. invalid formatting, length, MAC, ...). 13894 * Following the DTLS specification such errors/alerts SHOULD be 13895 * dropped silently [RFC9147, Section 4.5.2]. 13896 * This is done below. */ 13897 13898 if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) || 13899 (!IS_DTLS(ss) && ss->sec.isServer && 13900 ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) { 13901 /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent. 13902 * (Manually or by using functions like 13903 * SSL3_SendAlert(.., alert_fatal,..)) 13904 * This is not currently used in the unprotection functions since 13905 * all TLS and DTLS errors are propagated to this handler. */ 13906 if (ss->ssl3.fatalAlertSent) { 13907 return SECFailure; 13908 } 13909 return SECSuccess; 13910 } 13911 13912 int errCode = PORT_GetError(); 13913 SSL3_SendAlert(ss, alert_fatal, alert); 13914 /* Reset the error code in case SSL3_SendAlert called 13915 * PORT_SetError(). */ 13916 PORT_SetError(errCode); 13917 return SECFailure; 13918 } 13919 13920 /* SECSuccess */ 13921 if (IS_DTLS(ss)) { 13922 dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum); 13923 spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1); 13924 } else { 13925 ++spec->nextSeqNum; 13926 } 13927 epoch = spec->epoch; 13928 13929 ssl_ReleaseSpecReadLock(ss); /*****************************************/ 13930 13931 /* 13932 * The decrypted data is now in plaintext. 13933 */ 13934 13935 /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something 13936 * from the wrong epoch. Divert to a divert processing function to make 13937 * sure we don't accidentally use the data unsafely. */ 13938 13939 /* We temporary allowed reading the records from the previous epoch n-1 13940 until the moment we get a message from the new epoch n. */ 13941 13942 if (outOfOrderSpec) { 13943 PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); 13944 ssl_GetSSL3HandshakeLock(ss); 13945 if (ss->ssl3.hs.allowPreviousEpoch && spec->epoch == ss->ssl3.crSpec->epoch - 1) { 13946 SSL_TRC(30, ("%d: DTLS13[%d]: Out of order message %d is accepted", 13947 SSL_GETPID(), ss->fd, spec->epoch)); 13948 ssl_ReleaseSSL3HandshakeLock(ss); 13949 } else { 13950 ssl_ReleaseSSL3HandshakeLock(ss); 13951 return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext); 13952 } 13953 } else { 13954 ssl_GetSSL3HandshakeLock(ss); 13955 /* Forbid (application) messages from the previous epoch. 13956 From now, messages that arrive out of order will be discarded. */ 13957 ss->ssl3.hs.allowPreviousEpoch = PR_FALSE; 13958 ssl_ReleaseSSL3HandshakeLock(ss); 13959 } 13960 13961 /* Check the length of the plaintext. */ 13962 if (isTLS && plaintext->len > recordSizeLimit) { 13963 plaintext->len = 0; 13964 /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */ 13965 if (IS_DTLS(ss)) { 13966 return SECSuccess; 13967 } 13968 SSL3_SendAlert(ss, alert_fatal, record_overflow); 13969 PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 13970 return SECFailure; 13971 } 13972 13973 /* Application data records are processed by the caller of this 13974 ** function, not by this function. 13975 */ 13976 if (rType == ssl_ct_application_data) { 13977 if (ss->firstHsDone) 13978 return SECSuccess; 13979 if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && 13980 ss->sec.isServer && 13981 ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) { 13982 return tls13_HandleEarlyApplicationData(ss, plaintext); 13983 } 13984 plaintext->len = 0; 13985 (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 13986 PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); 13987 return SECFailure; 13988 } 13989 13990 rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum, 13991 plaintext); 13992 13993 #ifdef DEBUG 13994 /* In Debug builds free and zero gather plaintext buffer after its content 13995 * has been used/copied for advanced ASAN coverage/utilization. 13996 * This frees buffer for non application data records, for application data 13997 * records it is freed in sslsecur.c/DoRecv(). */ 13998 sslBuffer_Clear(&ss->gs.buf); 13999 #endif 14000 14001 return rv; 14002 } 14003 14004 /* 14005 * Initialization functions 14006 */ 14007 14008 void 14009 ssl_InitSecState(sslSecurityInfo *sec) 14010 { 14011 sec->authType = ssl_auth_null; 14012 sec->authKeyBits = 0; 14013 sec->signatureScheme = ssl_sig_none; 14014 sec->keaType = ssl_kea_null; 14015 sec->keaKeyBits = 0; 14016 sec->keaGroup = NULL; 14017 } 14018 14019 SECStatus 14020 ssl3_InitState(sslSocket *ss) 14021 { 14022 SECStatus rv; 14023 14024 ss->ssl3.policy = SSL_ALLOWED; 14025 14026 ssl_InitSecState(&ss->sec); 14027 14028 ssl_GetSpecWriteLock(ss); 14029 PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs); 14030 rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read); 14031 rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write); 14032 ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL; 14033 ssl_ReleaseSpecWriteLock(ss); 14034 if (rv != SECSuccess) { 14035 /* Rely on ssl_CreateNullCipherSpec() to set error code. */ 14036 return SECFailure; 14037 } 14038 14039 ss->ssl3.hs.sendingSCSV = PR_FALSE; 14040 ss->ssl3.hs.preliminaryInfo = 0; 14041 ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake; 14042 14043 ssl3_ResetExtensionData(&ss->xtnData, ss); 14044 PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions); 14045 PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions); 14046 if (IS_DTLS(ss)) { 14047 ss->ssl3.hs.sendMessageSeq = 0; 14048 ss->ssl3.hs.recvMessageSeq = 0; 14049 ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS; 14050 ss->ssl3.hs.rtRetries = 0; 14051 ss->ssl3.hs.recvdHighWater = -1; 14052 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); 14053 dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ 14054 } 14055 14056 ss->ssl3.hs.currentSecret = NULL; 14057 ss->ssl3.hs.resumptionMasterSecret = NULL; 14058 ss->ssl3.hs.dheSecret = NULL; 14059 ss->ssl3.hs.clientEarlyTrafficSecret = NULL; 14060 ss->ssl3.hs.clientHsTrafficSecret = NULL; 14061 ss->ssl3.hs.serverHsTrafficSecret = NULL; 14062 ss->ssl3.hs.clientTrafficSecret = NULL; 14063 ss->ssl3.hs.serverTrafficSecret = NULL; 14064 ss->ssl3.hs.echHpkeCtx = NULL; 14065 ss->ssl3.hs.greaseEchSize = 100; 14066 ss->ssl3.hs.echAccepted = PR_FALSE; 14067 ss->ssl3.hs.echDecided = PR_FALSE; 14068 14069 ss->ssl3.hs.clientAuthSignatureSchemes = NULL; 14070 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0; 14071 14072 PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space); 14073 ss->ssl3.hs.messages.buf = NULL; 14074 ss->ssl3.hs.messages.space = 0; 14075 14076 ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 14077 PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, 14078 sizeof(ss->ssl3.hs.newSessionTicket)); 14079 14080 ss->ssl3.hs.zeroRttState = ssl_0rtt_none; 14081 return SECSuccess; 14082 } 14083 14084 /* record the export policy for this cipher suite */ 14085 SECStatus 14086 ssl3_SetPolicy(ssl3CipherSuite which, int policy) 14087 { 14088 ssl3CipherSuiteCfg *suite; 14089 14090 suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites); 14091 if (suite == NULL) { 14092 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 14093 } 14094 suite->policy = policy; 14095 14096 return SECSuccess; 14097 } 14098 14099 SECStatus 14100 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) 14101 { 14102 const ssl3CipherSuiteCfg *suite; 14103 PRInt32 policy; 14104 SECStatus rv; 14105 14106 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 14107 if (suite) { 14108 policy = suite->policy; 14109 rv = SECSuccess; 14110 } else { 14111 policy = SSL_NOT_ALLOWED; 14112 rv = SECFailure; /* err code was set by Lookup. */ 14113 } 14114 *oPolicy = policy; 14115 return rv; 14116 } 14117 14118 /* record the user preference for this suite */ 14119 SECStatus 14120 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) 14121 { 14122 ssl3CipherSuiteCfg *suite; 14123 14124 suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites); 14125 if (suite == NULL) { 14126 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 14127 } 14128 suite->enabled = enabled; 14129 return SECSuccess; 14130 } 14131 14132 /* return the user preference for this suite */ 14133 SECStatus 14134 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) 14135 { 14136 const ssl3CipherSuiteCfg *suite; 14137 PRBool pref; 14138 SECStatus rv; 14139 14140 suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 14141 if (suite) { 14142 pref = suite->enabled; 14143 rv = SECSuccess; 14144 } else { 14145 pref = SSL_NOT_ALLOWED; 14146 rv = SECFailure; /* err code was set by Lookup. */ 14147 } 14148 *enabled = pref; 14149 return rv; 14150 } 14151 14152 SECStatus 14153 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) 14154 { 14155 ssl3CipherSuiteCfg *suite; 14156 14157 suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites); 14158 if (suite == NULL) { 14159 return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 14160 } 14161 suite->enabled = enabled; 14162 return SECSuccess; 14163 } 14164 14165 SECStatus 14166 ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) 14167 { 14168 const ssl3CipherSuiteCfg *suite; 14169 PRBool pref; 14170 SECStatus rv; 14171 14172 suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); 14173 if (suite) { 14174 pref = suite->enabled; 14175 rv = SECSuccess; 14176 } else { 14177 pref = SSL_NOT_ALLOWED; 14178 rv = SECFailure; /* err code was set by Lookup. */ 14179 } 14180 *enabled = pref; 14181 return rv; 14182 } 14183 14184 SECStatus 14185 SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes, 14186 unsigned int count) 14187 { 14188 sslSocket *ss; 14189 unsigned int i; 14190 unsigned int supported = 0; 14191 14192 ss = ssl_FindSocket(fd); 14193 if (!ss) { 14194 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet", 14195 SSL_GETPID(), fd)); 14196 PORT_SetError(SEC_ERROR_INVALID_ARGS); 14197 return SECFailure; 14198 } 14199 14200 if (!count) { 14201 PORT_SetError(SEC_ERROR_INVALID_ARGS); 14202 return SECFailure; 14203 } 14204 14205 for (i = 0; i < count; ++i) { 14206 if (ssl_IsSupportedSignatureScheme(schemes[i])) { 14207 ++supported; 14208 } 14209 } 14210 /* We don't check for duplicates, so it's possible to get too many. */ 14211 if (supported > MAX_SIGNATURE_SCHEMES) { 14212 PORT_SetError(SEC_ERROR_INVALID_ARGS); 14213 return SECFailure; 14214 } 14215 14216 ss->ssl3.signatureSchemeCount = 0; 14217 for (i = 0; i < count; ++i) { 14218 if (!ssl_IsSupportedSignatureScheme(schemes[i])) { 14219 SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored", 14220 SSL_GETPID(), fd, schemes[i])); 14221 continue; 14222 } 14223 14224 ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i]; 14225 } 14226 14227 if (ss->ssl3.signatureSchemeCount == 0) { 14228 PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); 14229 return SECFailure; 14230 } 14231 return SECSuccess; 14232 } 14233 14234 SECStatus 14235 SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms, 14236 unsigned int count) 14237 { 14238 SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES]; 14239 unsigned int i; 14240 14241 count = PR_MIN(PR_ARRAY_SIZE(schemes), count); 14242 for (i = 0; i < count; ++i) { 14243 schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg; 14244 } 14245 return SSL_SignatureSchemePrefSet(fd, schemes, count); 14246 } 14247 14248 SECStatus 14249 SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes, 14250 unsigned int *count, unsigned int maxCount) 14251 { 14252 sslSocket *ss; 14253 14254 ss = ssl_FindSocket(fd); 14255 if (!ss) { 14256 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet", 14257 SSL_GETPID(), fd)); 14258 PORT_SetError(SEC_ERROR_INVALID_ARGS); 14259 return SECFailure; 14260 } 14261 14262 if (!schemes || !count || 14263 maxCount < ss->ssl3.signatureSchemeCount) { 14264 PORT_SetError(SEC_ERROR_INVALID_ARGS); 14265 return SECFailure; 14266 } 14267 14268 PORT_Memcpy(schemes, ss->ssl3.signatureSchemes, 14269 ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme)); 14270 *count = ss->ssl3.signatureSchemeCount; 14271 return SECSuccess; 14272 } 14273 14274 SECStatus 14275 SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms, 14276 unsigned int *count, unsigned int maxCount) 14277 { 14278 sslSocket *ss; 14279 unsigned int i; 14280 14281 ss = ssl_FindSocket(fd); 14282 if (!ss) { 14283 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet", 14284 SSL_GETPID(), fd)); 14285 PORT_SetError(SEC_ERROR_INVALID_ARGS); 14286 return SECFailure; 14287 } 14288 14289 if (!algorithms || !count || 14290 maxCount < ss->ssl3.signatureSchemeCount) { 14291 PORT_SetError(SEC_ERROR_INVALID_ARGS); 14292 return SECFailure; 14293 } 14294 14295 for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { 14296 algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff; 14297 algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff; 14298 } 14299 *count = ss->ssl3.signatureSchemeCount; 14300 return SECSuccess; 14301 } 14302 14303 unsigned int 14304 SSL_SignatureMaxCount(void) 14305 { 14306 return MAX_SIGNATURE_SCHEMES; 14307 } 14308 14309 /* copy global default policy into socket. */ 14310 void 14311 ssl3_InitSocketPolicy(sslSocket *ss) 14312 { 14313 PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites)); 14314 PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes, 14315 sizeof(defaultSignatureSchemes)); 14316 ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes); 14317 } 14318 14319 /* 14320 ** If ssl3 socket has completed the first handshake, and is in idle state, 14321 ** then start a new handshake. 14322 ** If flushCache is true, the SID cache will be flushed first, forcing a 14323 ** "Full" handshake (not a session restart handshake), to be done. 14324 ** 14325 ** called from SSL_RedoHandshake(), which already holds the handshake locks. 14326 */ 14327 SECStatus 14328 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) 14329 { 14330 sslSessionID *sid = ss->sec.ci.sid; 14331 SECStatus rv; 14332 14333 PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 14334 14335 if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) { 14336 PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); 14337 return SECFailure; 14338 } 14339 14340 if (IS_DTLS(ss)) { 14341 dtls_RehandshakeCleanup(ss); 14342 } 14343 14344 if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER || 14345 ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { 14346 PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 14347 return SECFailure; 14348 } 14349 if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) { 14350 PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); 14351 return SECFailure; 14352 } 14353 14354 if (sid && flushCache) { 14355 ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */ 14356 ssl_FreeSID(sid); /* dec ref count and free if zero. */ 14357 ss->sec.ci.sid = NULL; 14358 } 14359 14360 ssl_GetXmitBufLock(ss); /**************************************/ 14361 14362 /* start off a new handshake. */ 14363 if (ss->sec.isServer) { 14364 rv = ssl3_SendHelloRequest(ss); 14365 } else { 14366 rv = ssl3_SendClientHello(ss, client_hello_renegotiation); 14367 } 14368 14369 ssl_ReleaseXmitBufLock(ss); /**************************************/ 14370 return rv; 14371 } 14372 14373 /* Called from ssl_DestroySocketContents() in sslsock.c */ 14374 void 14375 ssl3_DestroySSL3Info(sslSocket *ss) 14376 { 14377 14378 if (ss->ssl3.clientCertificate != NULL) 14379 CERT_DestroyCertificate(ss->ssl3.clientCertificate); 14380 14381 if (ss->ssl3.clientPrivateKey != NULL) 14382 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 14383 14384 if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) { 14385 PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes); 14386 ss->ssl3.hs.clientAuthSignatureSchemes = NULL; 14387 ss->ssl3.hs.clientAuthSignatureSchemesLen = 0; 14388 } 14389 14390 if (ss->ssl3.peerCertArena != NULL) 14391 ssl3_CleanupPeerCerts(ss); 14392 14393 if (ss->ssl3.clientCertChain != NULL) { 14394 CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 14395 ss->ssl3.clientCertChain = NULL; 14396 } 14397 if (ss->ssl3.ca_list) { 14398 CERT_FreeDistNames(ss->ssl3.ca_list); 14399 } 14400 14401 /* clean up handshake */ 14402 if (ss->ssl3.hs.md5) { 14403 PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); 14404 } 14405 if (ss->ssl3.hs.sha) { 14406 PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); 14407 } 14408 if (ss->ssl3.hs.shaEchInner) { 14409 PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE); 14410 } 14411 if (ss->ssl3.hs.shaPostHandshake) { 14412 PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE); 14413 } 14414 if (ss->ssl3.hs.messages.buf) { 14415 sslBuffer_Clear(&ss->ssl3.hs.messages); 14416 } 14417 if (ss->ssl3.hs.echInnerMessages.buf) { 14418 sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages); 14419 } 14420 if (ss->ssl3.hs.dtls13ClientMessageBuffer.buf) { 14421 sslBuffer_Clear(&ss->ssl3.hs.dtls13ClientMessageBuffer); 14422 } 14423 14424 /* free the SSL3Buffer (msg_body) */ 14425 PORT_Free(ss->ssl3.hs.msg_body.buf); 14426 14427 SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); 14428 SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE); 14429 SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE); 14430 14431 /* Destroy the DTLS data */ 14432 if (IS_DTLS(ss)) { 14433 dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); 14434 if (ss->ssl3.hs.recvdFragments.buf) { 14435 PORT_Free(ss->ssl3.hs.recvdFragments.buf); 14436 } 14437 } 14438 14439 /* Destroy remote extensions */ 14440 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions); 14441 ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions); 14442 ssl3_DestroyExtensionData(&ss->xtnData); 14443 14444 /* Destroy cipher specs */ 14445 ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs); 14446 14447 /* Destroy TLS 1.3 keys */ 14448 if (ss->ssl3.hs.currentSecret) 14449 PK11_FreeSymKey(ss->ssl3.hs.currentSecret); 14450 if (ss->ssl3.hs.resumptionMasterSecret) 14451 PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret); 14452 if (ss->ssl3.hs.dheSecret) 14453 PK11_FreeSymKey(ss->ssl3.hs.dheSecret); 14454 if (ss->ssl3.hs.clientEarlyTrafficSecret) 14455 PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret); 14456 if (ss->ssl3.hs.clientHsTrafficSecret) 14457 PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret); 14458 if (ss->ssl3.hs.serverHsTrafficSecret) 14459 PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret); 14460 if (ss->ssl3.hs.clientTrafficSecret) 14461 PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret); 14462 if (ss->ssl3.hs.serverTrafficSecret) 14463 PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret); 14464 if (ss->ssl3.hs.earlyExporterSecret) 14465 PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret); 14466 if (ss->ssl3.hs.exporterSecret) 14467 PK11_FreeSymKey(ss->ssl3.hs.exporterSecret); 14468 14469 ss->ssl3.hs.zeroRttState = ssl_0rtt_none; 14470 /* Destroy TLS 1.3 buffered early data. */ 14471 tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData); 14472 14473 /* Destroy TLS 1.3 PSKs. */ 14474 tls13_DestroyPskList(&ss->ssl3.hs.psks); 14475 14476 /* TLS 1.3 ECH state. */ 14477 PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE); 14478 PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */ 14479 sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf); 14480 14481 /* TLS 1.3 GREASE (client) state. */ 14482 tls13_ClientGreaseDestroy(ss); 14483 14484 /* TLS ClientHello Extension Permutation state. */ 14485 tls_ClientHelloExtensionPermutationDestroy(ss); 14486 } 14487 14488 /* check if the current cipher spec is FIPS. We only need to 14489 * check the contexts here, if the kea, prf or keys were not FIPS, 14490 * that status would have been rolled up in the create context 14491 * call */ 14492 static PRBool 14493 ssl_cipherSpecIsFips(ssl3CipherSpec *spec) 14494 { 14495 if (!spec || !spec->cipherDef) { 14496 return PR_FALSE; 14497 } 14498 14499 if (spec->cipherDef->type != type_aead) { 14500 if (spec->keyMaterial.macContext == NULL) { 14501 return PR_FALSE; 14502 } 14503 if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) { 14504 return PR_FALSE; 14505 } 14506 } 14507 if (!spec->cipherContext) { 14508 return PR_FALSE; 14509 } 14510 return PK11_ContextGetFIPSStatus(spec->cipherContext); 14511 } 14512 14513 /* return true if the current operation is running in FIPS mode */ 14514 PRBool 14515 ssl_isFIPS(sslSocket *ss) 14516 { 14517 if (!ssl_cipherSpecIsFips(ss->ssl3.crSpec)) { 14518 return PR_FALSE; 14519 } 14520 return ssl_cipherSpecIsFips(ss->ssl3.cwSpec); 14521 } 14522 14523 /* 14524 * parse the policy value for a single algorithm in a cipher_suite, 14525 * return TRUE if we disallow by the cipher suite by policy 14526 * (we don't have to parse any more algorithm policies on this cipher suite), 14527 * otherwise return FALSE. 14528 * 1. If we don't have the required policy, disable by default, disallow by 14529 * policy and return TRUE (no more processing needed). 14530 * 2. If we have the required policy, and we are disabled, return FALSE, 14531 * (if we are disabled, we only need to parse policy, not default). 14532 * 3. If we have the required policy, and we aren't adjusting the defaults 14533 * return FALSE. (only parsing the policy, not default). 14534 * 4. We have the required policy and we are adjusting the defaults. 14535 * If we are setting default = FALSE, set isDisabled to true so that 14536 * we don't try to re-enable the cipher suite based on a different 14537 * algorithm. 14538 */ 14539 PRBool 14540 ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid, 14541 PRUint32 requiredPolicy, PRBool *isDisabled) 14542 { 14543 PRUint32 policy; 14544 SECStatus rv; 14545 14546 /* first fetch the policy for this algorithm */ 14547 rv = NSS_GetAlgorithmPolicy(policyOid, &policy); 14548 if (rv != SECSuccess) { 14549 return PR_FALSE; /* no policy value, continue to the next algorithm */ 14550 } 14551 /* first, are we allowed by policy, if not turn off allow and disable */ 14552 if (!(policy & requiredPolicy)) { 14553 ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE); 14554 ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED); 14555 return PR_TRUE; 14556 } 14557 /* If we are already disabled, or the policy isn't setting a default 14558 * we are done processing this algorithm */ 14559 if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID)) { 14560 return PR_FALSE; 14561 } 14562 /* set the default value for the cipher suite. If we disable the cipher 14563 * suite, remember that so we don't process the next default. This has 14564 * the effect of disabling the whole cipher suite if any of the 14565 * algorithms it uses are disabled by default. We still have to 14566 * process the upper level because the cipher suite is still allowed 14567 * by policy, and we may still have to disallow it based on other 14568 * algorithms in the cipher suite. */ 14569 if (policy & NSS_USE_DEFAULT_SSL_ENABLE) { 14570 ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE); 14571 } else { 14572 *isDisabled = PR_TRUE; 14573 ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE); 14574 } 14575 return PR_FALSE; 14576 } 14577 14578 #define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER) 14579 14580 SECStatus 14581 ssl3_ApplyNSSPolicy(void) 14582 { 14583 unsigned i; 14584 SECStatus rv; 14585 PRUint32 policy = 0; 14586 14587 rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy); 14588 if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) { 14589 return SECSuccess; /* do nothing */ 14590 } 14591 14592 /* disable every ciphersuite */ 14593 for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) { 14594 const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i]; 14595 SECOidTag policyOid; 14596 PRBool isDisabled = PR_FALSE; 14597 14598 /* if we haven't explicitly disabled it below enable by policy */ 14599 ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED); 14600 14601 /* now check the various key exchange, ciphers and macs and 14602 * if we ever disallow by policy, we are done, go to the next cipher 14603 */ 14604 policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid); 14605 if (ssl_HandlePolicy(suite->cipher_suite, policyOid, 14606 NSS_USE_ALG_IN_SSL_KX, &isDisabled)) { 14607 continue; 14608 } 14609 14610 policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid); 14611 if (ssl_HandlePolicy(suite->cipher_suite, policyOid, 14612 NSS_USE_ALG_IN_SSL, &isDisabled)) { 14613 continue; 14614 } 14615 14616 if (ssl_GetBulkCipherDef(suite)->type != type_aead) { 14617 policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid); 14618 if (ssl_HandlePolicy(suite->cipher_suite, policyOid, 14619 NSS_USE_ALG_IN_SSL, &isDisabled)) { 14620 continue; 14621 } 14622 } 14623 } 14624 14625 rv = ssl3_ConstrainRangeByPolicy(); 14626 14627 return rv; 14628 } 14629 14630 /* End of ssl3con.c */