1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/security/nss/lib/ssl/ssl3con.c Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,12143 @@ 1.4 +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ 1.5 +/* 1.6 + * SSL3 Protocol 1.7 + * 1.8 + * This Source Code Form is subject to the terms of the Mozilla Public 1.9 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.10 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.11 + 1.12 +/* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */ 1.13 + 1.14 +#include "cert.h" 1.15 +#include "ssl.h" 1.16 +#include "cryptohi.h" /* for DSAU_ stuff */ 1.17 +#include "keyhi.h" 1.18 +#include "secder.h" 1.19 +#include "secitem.h" 1.20 +#include "sechash.h" 1.21 + 1.22 +#include "sslimpl.h" 1.23 +#include "sslproto.h" 1.24 +#include "sslerr.h" 1.25 +#include "prtime.h" 1.26 +#include "prinrval.h" 1.27 +#include "prerror.h" 1.28 +#include "pratom.h" 1.29 +#include "prthread.h" 1.30 + 1.31 +#include "pk11func.h" 1.32 +#include "secmod.h" 1.33 +#ifndef NO_PKCS11_BYPASS 1.34 +#include "blapi.h" 1.35 +#endif 1.36 + 1.37 +#include <stdio.h> 1.38 +#ifdef NSS_ENABLE_ZLIB 1.39 +#include "zlib.h" 1.40 +#endif 1.41 + 1.42 +#ifndef PK11_SETATTRS 1.43 +#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ 1.44 + (x)->pValue=(v); (x)->ulValueLen = (l); 1.45 +#endif 1.46 + 1.47 +static SECStatus ssl3_AuthCertificate(sslSocket *ss); 1.48 +static void ssl3_CleanupPeerCerts(sslSocket *ss); 1.49 +static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, 1.50 + PK11SlotInfo * serverKeySlot); 1.51 +static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms); 1.52 +static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss); 1.53 +static SECStatus ssl3_HandshakeFailure( sslSocket *ss); 1.54 +static SECStatus ssl3_InitState( sslSocket *ss); 1.55 +static SECStatus ssl3_SendCertificate( sslSocket *ss); 1.56 +static SECStatus ssl3_SendCertificateStatus( sslSocket *ss); 1.57 +static SECStatus ssl3_SendEmptyCertificate( sslSocket *ss); 1.58 +static SECStatus ssl3_SendCertificateRequest(sslSocket *ss); 1.59 +static SECStatus ssl3_SendNextProto( sslSocket *ss); 1.60 +static SECStatus ssl3_SendFinished( sslSocket *ss, PRInt32 flags); 1.61 +static SECStatus ssl3_SendServerHello( sslSocket *ss); 1.62 +static SECStatus ssl3_SendServerHelloDone( sslSocket *ss); 1.63 +static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss); 1.64 +static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss, 1.65 + const unsigned char *b, 1.66 + unsigned int l); 1.67 +static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); 1.68 +static int ssl3_OIDToTLSHashAlgorithm(SECOidTag oid); 1.69 + 1.70 +static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, 1.71 + int maxOutputLen, const unsigned char *input, 1.72 + int inputLen); 1.73 +#ifndef NO_PKCS11_BYPASS 1.74 +static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, 1.75 + unsigned char *out, int *outlen, int maxout, 1.76 + const unsigned char *in, int inlen, 1.77 + const unsigned char *additionalData, 1.78 + int additionalDataLen); 1.79 +#endif 1.80 + 1.81 +#define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ 1.82 +#define MIN_SEND_BUF_LENGTH 4000 1.83 + 1.84 +/* This list of SSL3 cipher suites is sorted in descending order of 1.85 + * precedence (desirability). It only includes cipher suites we implement. 1.86 + * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites 1.87 + * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c) 1.88 + * 1.89 + * Important: See bug 946147 before enabling, reordering, or adding any cipher 1.90 + * suites to this list. 1.91 + */ 1.92 +static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { 1.93 + /* cipher_suite policy enabled isPresent */ 1.94 + 1.95 +#ifndef NSS_DISABLE_ECC 1.96 + { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.97 + { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.98 + /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around 1.99 + * bug 946147. 1.100 + */ 1.101 + { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.102 + { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.103 + { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.104 + { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.105 + { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.106 + { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.107 + { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.108 + { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.109 + { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.110 + { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.111 +#endif /* NSS_DISABLE_ECC */ 1.112 + 1.113 + { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.114 + { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.115 + { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.116 + { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.117 + { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.118 + { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.119 + { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.120 + { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.121 + { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.122 + { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.123 + { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.124 + { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.125 + { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.126 + { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.127 + 1.128 +#ifndef NSS_DISABLE_ECC 1.129 + { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.130 + { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.131 + { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.132 + { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.133 + { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.134 + { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.135 + { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.136 + { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.137 +#endif /* NSS_DISABLE_ECC */ 1.138 + 1.139 + /* RSA */ 1.140 + { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.141 + { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.142 + { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.143 + { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.144 + { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.145 + { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.146 + { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.147 + { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.148 + { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.149 + { TLS_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.150 + { TLS_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.151 + { TLS_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE}, 1.152 + 1.153 + /* 56-bit DES "domestic" cipher suites */ 1.154 + { TLS_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.155 + { TLS_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.156 + { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.157 + { TLS_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.158 + 1.159 + /* export ciphersuites with 1024-bit public key exchange keys */ 1.160 + { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.161 + { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.162 + 1.163 + /* export ciphersuites with 512-bit public key exchange keys */ 1.164 + { TLS_RSA_EXPORT_WITH_RC4_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.165 + { TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.166 + 1.167 + /* ciphersuites with no encryption */ 1.168 +#ifndef NSS_DISABLE_ECC 1.169 + { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.170 + { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.171 + { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.172 + { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.173 +#endif /* NSS_DISABLE_ECC */ 1.174 + { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.175 + { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.176 + { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, 1.177 +}; 1.178 + 1.179 +/* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order. 1.180 + */ 1.181 +#ifdef DEBUG 1.182 +void ssl3_CheckCipherSuiteOrderConsistency() 1.183 +{ 1.184 + unsigned int i; 1.185 + 1.186 + /* Note that SSL_ImplementedCiphers has more elements than cipherSuites 1.187 + * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites. 1.188 + */ 1.189 + PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites)); 1.190 + 1.191 + for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) { 1.192 + PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite); 1.193 + } 1.194 +} 1.195 +#endif 1.196 + 1.197 +/* This list of SSL3 compression methods is sorted in descending order of 1.198 + * precedence (desirability). It only includes compression methods we 1.199 + * implement. 1.200 + */ 1.201 +static const /*SSLCompressionMethod*/ PRUint8 compressions [] = { 1.202 +#ifdef NSS_ENABLE_ZLIB 1.203 + ssl_compression_deflate, 1.204 +#endif 1.205 + ssl_compression_null 1.206 +}; 1.207 + 1.208 +static const int compressionMethodsCount = 1.209 + sizeof(compressions) / sizeof(compressions[0]); 1.210 + 1.211 +/* compressionEnabled returns true iff the compression algorithm is enabled 1.212 + * for the given SSL socket. */ 1.213 +static PRBool 1.214 +compressionEnabled(sslSocket *ss, SSLCompressionMethod compression) 1.215 +{ 1.216 + switch (compression) { 1.217 + case ssl_compression_null: 1.218 + return PR_TRUE; /* Always enabled */ 1.219 +#ifdef NSS_ENABLE_ZLIB 1.220 + case ssl_compression_deflate: 1.221 + return ss->opt.enableDeflate; 1.222 +#endif 1.223 + default: 1.224 + return PR_FALSE; 1.225 + } 1.226 +} 1.227 + 1.228 +static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = { 1.229 + ct_RSA_sign, 1.230 +#ifndef NSS_DISABLE_ECC 1.231 + ct_ECDSA_sign, 1.232 +#endif /* NSS_DISABLE_ECC */ 1.233 + ct_DSS_sign, 1.234 +}; 1.235 + 1.236 +/* This block is the contents of the supported_signature_algorithms field of 1.237 + * our TLS 1.2 CertificateRequest message, in wire format. See 1.238 + * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 1.239 + * 1.240 + * This block contains only sha256 entries because we only support TLS 1.2 1.241 + * CertificateVerify messages that use the handshake hash. */ 1.242 +static const PRUint8 supported_signature_algorithms[] = { 1.243 + tls_hash_sha256, tls_sig_rsa, 1.244 +#ifndef NSS_DISABLE_ECC 1.245 + tls_hash_sha256, tls_sig_ecdsa, 1.246 +#endif 1.247 + tls_hash_sha256, tls_sig_dsa, 1.248 +}; 1.249 + 1.250 +#define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ 1.251 + 1.252 + 1.253 +/* This global item is used only in servers. It is is initialized by 1.254 +** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest(). 1.255 +*/ 1.256 +CERTDistNames *ssl3_server_ca_list = NULL; 1.257 +static SSL3Statistics ssl3stats; 1.258 + 1.259 +/* indexed by SSL3BulkCipher */ 1.260 +static const ssl3BulkCipherDef bulk_cipher_defs[] = { 1.261 + /* |--------- Lengths --------| */ 1.262 + /* cipher calg k s type i b t n */ 1.263 + /* e e v l a o */ 1.264 + /* y c | o g n */ 1.265 + /* | r | c | c */ 1.266 + /* | e | k | e */ 1.267 + /* | t | | | | */ 1.268 + {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, 1.269 + {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, 1.270 + {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, 1.271 + {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, 1.272 + {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, 1.273 + {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, 1.274 + {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, 1.275 + {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, 1.276 + {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, 1.277 + {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, 1.278 + {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, 1.279 + {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, 1.280 + {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, 1.281 + {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, 1.282 + {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, 1.283 + {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, 1.284 + {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, 1.285 +}; 1.286 + 1.287 +static const ssl3KEADef kea_defs[] = 1.288 +{ /* indexed by SSL3KeyExchangeAlgorithm */ 1.289 + /* kea exchKeyType signKeyType is_limited limit tls_keygen */ 1.290 + {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE}, 1.291 + {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE}, 1.292 + {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE}, 1.293 + {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE}, 1.294 + {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE}, 1.295 + {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE}, 1.296 + {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE}, 1.297 + {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE}, 1.298 + {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE}, 1.299 + {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE}, 1.300 + {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE}, 1.301 + {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE}, 1.302 + {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE}, 1.303 + {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE}, 1.304 + {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE }, 1.305 +#ifndef NSS_DISABLE_ECC 1.306 + {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE}, 1.307 + {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE}, 1.308 + {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE}, 1.309 + {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE}, 1.310 + {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE}, 1.311 +#endif /* NSS_DISABLE_ECC */ 1.312 +}; 1.313 + 1.314 +/* must use ssl_LookupCipherSuiteDef to access */ 1.315 +static const ssl3CipherSuiteDef cipher_suite_defs[] = 1.316 +{ 1.317 +/* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg */ 1.318 + 1.319 + {TLS_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null}, 1.320 + {TLS_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa}, 1.321 + {TLS_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa}, 1.322 + {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa}, 1.323 + {TLS_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export}, 1.324 + {TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa}, 1.325 + {TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa}, 1.326 + {TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, 1.327 + cipher_rc2_40, mac_md5, kea_rsa_export}, 1.328 +#if 0 /* not implemented */ 1.329 + {TLS_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa}, 1.330 + {TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, 1.331 + cipher_des40, mac_sha, kea_rsa_export}, 1.332 +#endif 1.333 + {TLS_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa}, 1.334 + {TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa}, 1.335 + {TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss}, 1.336 + {TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, 1.337 + cipher_3des, mac_sha, kea_dhe_dss}, 1.338 + {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss}, 1.339 +#if 0 /* not implemented */ 1.340 + {TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, 1.341 + cipher_des40, mac_sha, kea_dh_dss_export}, 1.342 + {TLS_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss}, 1.343 + {TLS_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss}, 1.344 + {TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, 1.345 + cipher_des40, mac_sha, kea_dh_rsa_export}, 1.346 + {TLS_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa}, 1.347 + {TLS_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa}, 1.348 + {TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, 1.349 + cipher_des40, mac_sha, kea_dh_dss_export}, 1.350 + {TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, 1.351 + cipher_des40, mac_sha, kea_dh_rsa_export}, 1.352 +#endif 1.353 + {TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa}, 1.354 + {TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, 1.355 + cipher_3des, mac_sha, kea_dhe_rsa}, 1.356 +#if 0 1.357 + {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export}, 1.358 + {TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, 1.359 + cipher_des40, mac_sha, kea_dh_anon_export}, 1.360 + {TLS_DH_anon_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon}, 1.361 + {TLS_DH_anon_WITH_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon}, 1.362 +#endif 1.363 + 1.364 + 1.365 +/* New TLS cipher suites */ 1.366 + {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa}, 1.367 + {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa}, 1.368 + {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss}, 1.369 + {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa}, 1.370 + {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa}, 1.371 + {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa}, 1.372 + {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa}, 1.373 + {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss}, 1.374 + {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa}, 1.375 + {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa}, 1.376 +#if 0 1.377 + {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss}, 1.378 + {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa}, 1.379 + {TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon}, 1.380 + {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss}, 1.381 + {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa}, 1.382 + {TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon}, 1.383 +#endif 1.384 + 1.385 + {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa}, 1.386 + 1.387 + {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa}, 1.388 + {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, 1.389 + cipher_camellia_128, mac_sha, kea_dhe_dss}, 1.390 + {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, 1.391 + cipher_camellia_128, mac_sha, kea_dhe_rsa}, 1.392 + {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa}, 1.393 + {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, 1.394 + cipher_camellia_256, mac_sha, kea_dhe_dss}, 1.395 + {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, 1.396 + cipher_camellia_256, mac_sha, kea_dhe_rsa}, 1.397 + 1.398 + {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, 1.399 + cipher_des, mac_sha,kea_rsa_export_1024}, 1.400 + {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, 1.401 + cipher_rc4_56, mac_sha,kea_rsa_export_1024}, 1.402 + 1.403 + {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, 1.404 + {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, 1.405 + 1.406 + {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa}, 1.407 + {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa}, 1.408 + {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa}, 1.409 + {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa}, 1.410 + 1.411 +#ifndef NSS_DISABLE_ECC 1.412 + {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, 1.413 + {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, 1.414 + {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa}, 1.415 + {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa}, 1.416 + {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa}, 1.417 + 1.418 + {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa}, 1.419 + {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa}, 1.420 + {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa}, 1.421 + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa}, 1.422 + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa}, 1.423 + {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa}, 1.424 + 1.425 + {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa}, 1.426 + {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa}, 1.427 + {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa}, 1.428 + {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa}, 1.429 + {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa}, 1.430 + 1.431 + {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa}, 1.432 + {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa}, 1.433 + {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa}, 1.434 + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa}, 1.435 + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa}, 1.436 + {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa}, 1.437 + 1.438 +#if 0 1.439 + {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon}, 1.440 + {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon}, 1.441 + {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon}, 1.442 + {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon}, 1.443 + {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon}, 1.444 +#endif 1.445 +#endif /* NSS_DISABLE_ECC */ 1.446 +}; 1.447 + 1.448 +static const CK_MECHANISM_TYPE kea_alg_defs[] = { 1.449 + 0x80000000L, 1.450 + CKM_RSA_PKCS, 1.451 + CKM_DH_PKCS_DERIVE, 1.452 + CKM_KEA_KEY_DERIVE, 1.453 + CKM_ECDH1_DERIVE 1.454 +}; 1.455 + 1.456 +typedef struct SSLCipher2MechStr { 1.457 + SSLCipherAlgorithm calg; 1.458 + CK_MECHANISM_TYPE cmech; 1.459 +} SSLCipher2Mech; 1.460 + 1.461 +/* indexed by type SSLCipherAlgorithm */ 1.462 +static const SSLCipher2Mech alg2Mech[] = { 1.463 + /* calg, cmech */ 1.464 + { calg_null , (CK_MECHANISM_TYPE)0x80000000L }, 1.465 + { calg_rc4 , CKM_RC4 }, 1.466 + { calg_rc2 , CKM_RC2_CBC }, 1.467 + { calg_des , CKM_DES_CBC }, 1.468 + { calg_3des , CKM_DES3_CBC }, 1.469 + { calg_idea , CKM_IDEA_CBC }, 1.470 + { calg_fortezza , CKM_SKIPJACK_CBC64 }, 1.471 + { calg_aes , CKM_AES_CBC }, 1.472 + { calg_camellia , CKM_CAMELLIA_CBC }, 1.473 + { calg_seed , CKM_SEED_CBC }, 1.474 + { calg_aes_gcm , CKM_AES_GCM }, 1.475 +/* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ 1.476 +}; 1.477 + 1.478 +#define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L 1.479 +#define mmech_md5 CKM_SSL3_MD5_MAC 1.480 +#define mmech_sha CKM_SSL3_SHA1_MAC 1.481 +#define mmech_md5_hmac CKM_MD5_HMAC 1.482 +#define mmech_sha_hmac CKM_SHA_1_HMAC 1.483 +#define mmech_sha256_hmac CKM_SHA256_HMAC 1.484 + 1.485 +static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ 1.486 + /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ 1.487 + /* mac mmech pad_size mac_size */ 1.488 + { mac_null, mmech_invalid, 0, 0 }, 1.489 + { mac_md5, mmech_md5, 48, MD5_LENGTH }, 1.490 + { mac_sha, mmech_sha, 40, SHA1_LENGTH}, 1.491 + {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH }, 1.492 + {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH}, 1.493 + {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH}, 1.494 + { mac_aead, mmech_invalid, 0, 0 }, 1.495 +}; 1.496 + 1.497 +/* indexed by SSL3BulkCipher */ 1.498 +const char * const ssl3_cipherName[] = { 1.499 + "NULL", 1.500 + "RC4", 1.501 + "RC4-40", 1.502 + "RC4-56", 1.503 + "RC2-CBC", 1.504 + "RC2-CBC-40", 1.505 + "DES-CBC", 1.506 + "3DES-EDE-CBC", 1.507 + "DES-CBC-40", 1.508 + "IDEA-CBC", 1.509 + "AES-128", 1.510 + "AES-256", 1.511 + "Camellia-128", 1.512 + "Camellia-256", 1.513 + "SEED-CBC", 1.514 + "AES-128-GCM", 1.515 + "missing" 1.516 +}; 1.517 + 1.518 +#ifndef NSS_DISABLE_ECC 1.519 +/* The ECCWrappedKeyInfo structure defines how various pieces of 1.520 + * information are laid out within wrappedSymmetricWrappingkey 1.521 + * for ECDH key exchange. Since wrappedSymmetricWrappingkey is 1.522 + * a 512-byte buffer (see sslimpl.h), the variable length field 1.523 + * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes. 1.524 + * 1.525 + * XXX For now, NSS only supports named elliptic curves of size 571 bits 1.526 + * or smaller. The public value will fit within 145 bytes and EC params 1.527 + * will fit within 12 bytes. We'll need to revisit this when NSS 1.528 + * supports arbitrary curves. 1.529 + */ 1.530 +#define MAX_EC_WRAPPED_KEY_BUFLEN 504 1.531 + 1.532 +typedef struct ECCWrappedKeyInfoStr { 1.533 + PRUint16 size; /* EC public key size in bits */ 1.534 + PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */ 1.535 + PRUint16 pubValueLen; /* length (in bytes) of EC public value */ 1.536 + PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */ 1.537 + PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */ 1.538 + /* EC public-key params, the EC public value and the wrapped key */ 1.539 +} ECCWrappedKeyInfo; 1.540 +#endif /* NSS_DISABLE_ECC */ 1.541 + 1.542 +#if defined(TRACE) 1.543 + 1.544 +static char * 1.545 +ssl3_DecodeHandshakeType(int msgType) 1.546 +{ 1.547 + char * rv; 1.548 + static char line[40]; 1.549 + 1.550 + switch(msgType) { 1.551 + case hello_request: rv = "hello_request (0)"; break; 1.552 + case client_hello: rv = "client_hello (1)"; break; 1.553 + case server_hello: rv = "server_hello (2)"; break; 1.554 + case hello_verify_request: rv = "hello_verify_request (3)"; break; 1.555 + case certificate: rv = "certificate (11)"; break; 1.556 + case server_key_exchange: rv = "server_key_exchange (12)"; break; 1.557 + case certificate_request: rv = "certificate_request (13)"; break; 1.558 + case server_hello_done: rv = "server_hello_done (14)"; break; 1.559 + case certificate_verify: rv = "certificate_verify (15)"; break; 1.560 + case client_key_exchange: rv = "client_key_exchange (16)"; break; 1.561 + case finished: rv = "finished (20)"; break; 1.562 + default: 1.563 + sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); 1.564 + rv = line; 1.565 + } 1.566 + return rv; 1.567 +} 1.568 + 1.569 +static char * 1.570 +ssl3_DecodeContentType(int msgType) 1.571 +{ 1.572 + char * rv; 1.573 + static char line[40]; 1.574 + 1.575 + switch(msgType) { 1.576 + case content_change_cipher_spec: 1.577 + rv = "change_cipher_spec (20)"; break; 1.578 + case content_alert: rv = "alert (21)"; break; 1.579 + case content_handshake: rv = "handshake (22)"; break; 1.580 + case content_application_data: 1.581 + rv = "application_data (23)"; break; 1.582 + default: 1.583 + sprintf(line, "*UNKNOWN* record type! (%d)", msgType); 1.584 + rv = line; 1.585 + } 1.586 + return rv; 1.587 +} 1.588 + 1.589 +#endif 1.590 + 1.591 +SSL3Statistics * 1.592 +SSL_GetStatistics(void) 1.593 +{ 1.594 + return &ssl3stats; 1.595 +} 1.596 + 1.597 +typedef struct tooLongStr { 1.598 +#if defined(IS_LITTLE_ENDIAN) 1.599 + PRInt32 low; 1.600 + PRInt32 high; 1.601 +#else 1.602 + PRInt32 high; 1.603 + PRInt32 low; 1.604 +#endif 1.605 +} tooLong; 1.606 + 1.607 +void SSL_AtomicIncrementLong(long * x) 1.608 +{ 1.609 + if ((sizeof *x) == sizeof(PRInt32)) { 1.610 + PR_ATOMIC_INCREMENT((PRInt32 *)x); 1.611 + } else { 1.612 + tooLong * tl = (tooLong *)x; 1.613 + if (PR_ATOMIC_INCREMENT(&tl->low) == 0) 1.614 + PR_ATOMIC_INCREMENT(&tl->high); 1.615 + } 1.616 +} 1.617 + 1.618 +static PRBool 1.619 +ssl3_CipherSuiteAllowedForVersionRange( 1.620 + ssl3CipherSuite cipherSuite, 1.621 + const SSLVersionRange *vrange) 1.622 +{ 1.623 + switch (cipherSuite) { 1.624 + /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or 1.625 + * later. This set of cipher suites is similar to, but different from, the 1.626 + * set of cipher suites considered exportable by SSL_IsExportCipherSuite. 1.627 + */ 1.628 + case TLS_RSA_EXPORT_WITH_RC4_40_MD5: 1.629 + case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: 1.630 + /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented 1.631 + * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented 1.632 + * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented 1.633 + * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented 1.634 + * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented 1.635 + * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented 1.636 + * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented 1.637 + */ 1.638 + return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; 1.639 + 1.640 + case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: 1.641 + case TLS_RSA_WITH_AES_256_CBC_SHA256: 1.642 + case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: 1.643 + case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 1.644 + case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: 1.645 + case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 1.646 + case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: 1.647 + case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: 1.648 + case TLS_RSA_WITH_AES_128_CBC_SHA256: 1.649 + case TLS_RSA_WITH_AES_128_GCM_SHA256: 1.650 + case TLS_RSA_WITH_NULL_SHA256: 1.651 + return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2; 1.652 + 1.653 + /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and 1.654 + * point formats.*/ 1.655 + case TLS_ECDH_ECDSA_WITH_NULL_SHA: 1.656 + case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: 1.657 + case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: 1.658 + case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: 1.659 + case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: 1.660 + case TLS_ECDHE_ECDSA_WITH_NULL_SHA: 1.661 + case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: 1.662 + case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: 1.663 + case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: 1.664 + case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: 1.665 + case TLS_ECDH_RSA_WITH_NULL_SHA: 1.666 + case TLS_ECDH_RSA_WITH_RC4_128_SHA: 1.667 + case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: 1.668 + case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: 1.669 + case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: 1.670 + case TLS_ECDHE_RSA_WITH_NULL_SHA: 1.671 + case TLS_ECDHE_RSA_WITH_RC4_128_SHA: 1.672 + case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: 1.673 + case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: 1.674 + case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: 1.675 + return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0; 1.676 + 1.677 + default: 1.678 + return PR_TRUE; 1.679 + } 1.680 +} 1.681 + 1.682 +/* return pointer to ssl3CipherSuiteDef for suite, or NULL */ 1.683 +/* XXX This does a linear search. A binary search would be better. */ 1.684 +static const ssl3CipherSuiteDef * 1.685 +ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) 1.686 +{ 1.687 + int cipher_suite_def_len = 1.688 + sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); 1.689 + int i; 1.690 + 1.691 + for (i = 0; i < cipher_suite_def_len; i++) { 1.692 + if (cipher_suite_defs[i].cipher_suite == suite) 1.693 + return &cipher_suite_defs[i]; 1.694 + } 1.695 + PORT_Assert(PR_FALSE); /* We should never get here. */ 1.696 + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); 1.697 + return NULL; 1.698 +} 1.699 + 1.700 +/* Find the cipher configuration struct associate with suite */ 1.701 +/* XXX This does a linear search. A binary search would be better. */ 1.702 +static ssl3CipherSuiteCfg * 1.703 +ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) 1.704 +{ 1.705 + int i; 1.706 + 1.707 + for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 1.708 + if (suites[i].cipher_suite == suite) 1.709 + return &suites[i]; 1.710 + } 1.711 + /* return NULL and let the caller handle it. */ 1.712 + PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); 1.713 + return NULL; 1.714 +} 1.715 + 1.716 + 1.717 +/* Initialize the suite->isPresent value for config_match 1.718 + * Returns count of enabled ciphers supported by extant tokens, 1.719 + * regardless of policy or user preference. 1.720 + * If this returns zero, the user cannot do SSL v3. 1.721 + */ 1.722 +int 1.723 +ssl3_config_match_init(sslSocket *ss) 1.724 +{ 1.725 + ssl3CipherSuiteCfg * suite; 1.726 + const ssl3CipherSuiteDef *cipher_def; 1.727 + SSLCipherAlgorithm cipher_alg; 1.728 + CK_MECHANISM_TYPE cipher_mech; 1.729 + SSL3KEAType exchKeyType; 1.730 + int i; 1.731 + int numPresent = 0; 1.732 + int numEnabled = 0; 1.733 + PRBool isServer; 1.734 + sslServerCerts *svrAuth; 1.735 + 1.736 + PORT_Assert(ss); 1.737 + if (!ss) { 1.738 + PORT_SetError(SEC_ERROR_INVALID_ARGS); 1.739 + return 0; 1.740 + } 1.741 + if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1.742 + return 0; 1.743 + } 1.744 + isServer = (PRBool)(ss->sec.isServer != 0); 1.745 + 1.746 + for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 1.747 + suite = &ss->cipherSuites[i]; 1.748 + if (suite->enabled) { 1.749 + ++numEnabled; 1.750 + /* We need the cipher defs to see if we have a token that can handle 1.751 + * this cipher. It isn't part of the static definition. 1.752 + */ 1.753 + cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite); 1.754 + if (!cipher_def) { 1.755 + suite->isPresent = PR_FALSE; 1.756 + continue; 1.757 + } 1.758 + cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; 1.759 + PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg); 1.760 + cipher_mech = alg2Mech[cipher_alg].cmech; 1.761 + exchKeyType = 1.762 + kea_defs[cipher_def->key_exchange_alg].exchKeyType; 1.763 +#ifdef NSS_DISABLE_ECC 1.764 + svrAuth = ss->serverCerts + exchKeyType; 1.765 +#else 1.766 + /* XXX SSLKEAType isn't really a good choice for 1.767 + * indexing certificates. It doesn't work for 1.768 + * (EC)DHE-* ciphers. Here we use a hack to ensure 1.769 + * that the server uses an RSA cert for (EC)DHE-RSA. 1.770 + */ 1.771 + switch (cipher_def->key_exchange_alg) { 1.772 + case kea_ecdhe_rsa: 1.773 +#if NSS_SERVER_DHE_IMPLEMENTED 1.774 + /* XXX NSS does not yet implement the server side of _DHE_ 1.775 + * cipher suites. Correcting the computation for svrAuth, 1.776 + * as the case below does, causes NSS SSL servers to begin to 1.777 + * negotiate cipher suites they do not implement. So, until 1.778 + * server side _DHE_ is implemented, keep this disabled. 1.779 + */ 1.780 + case kea_dhe_rsa: 1.781 +#endif 1.782 + svrAuth = ss->serverCerts + kt_rsa; 1.783 + break; 1.784 + case kea_ecdh_ecdsa: 1.785 + case kea_ecdh_rsa: 1.786 + /* 1.787 + * XXX We ought to have different indices for 1.788 + * ECDSA- and RSA-signed EC certificates so 1.789 + * we could support both key exchange mechanisms 1.790 + * simultaneously. For now, both of them use 1.791 + * whatever is in the certificate slot for kt_ecdh 1.792 + */ 1.793 + default: 1.794 + svrAuth = ss->serverCerts + exchKeyType; 1.795 + break; 1.796 + } 1.797 +#endif /* NSS_DISABLE_ECC */ 1.798 + 1.799 + /* Mark the suites that are backed by real tokens, certs and keys */ 1.800 + suite->isPresent = (PRBool) 1.801 + (((exchKeyType == kt_null) || 1.802 + ((!isServer || (svrAuth->serverKeyPair && 1.803 + svrAuth->SERVERKEY && 1.804 + svrAuth->serverCertChain)) && 1.805 + PK11_TokenExists(kea_alg_defs[exchKeyType]))) && 1.806 + ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech))); 1.807 + if (suite->isPresent) 1.808 + ++numPresent; 1.809 + } 1.810 + } 1.811 + PORT_Assert(numPresent > 0 || numEnabled == 0); 1.812 + if (numPresent <= 0) { 1.813 + PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); 1.814 + } 1.815 + return numPresent; 1.816 +} 1.817 + 1.818 + 1.819 +/* return PR_TRUE if suite matches policy, enabled state and is applicable to 1.820 + * the given version range. */ 1.821 +/* It would be a REALLY BAD THING (tm) if we ever permitted the use 1.822 +** of a cipher that was NOT_ALLOWED. So, if this is ever called with 1.823 +** policy == SSL_NOT_ALLOWED, report no match. 1.824 +*/ 1.825 +/* adjust suite enabled to the availability of a token that can do the 1.826 + * cipher suite. */ 1.827 +static PRBool 1.828 +config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, 1.829 + const SSLVersionRange *vrange) 1.830 +{ 1.831 + PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE); 1.832 + if (policy == SSL_NOT_ALLOWED || !enabled) 1.833 + return PR_FALSE; 1.834 + return (PRBool)(suite->enabled && 1.835 + suite->isPresent && 1.836 + suite->policy != SSL_NOT_ALLOWED && 1.837 + suite->policy <= policy && 1.838 + ssl3_CipherSuiteAllowedForVersionRange( 1.839 + suite->cipher_suite, vrange)); 1.840 +} 1.841 + 1.842 +/* return number of cipher suites that match policy, enabled state and are 1.843 + * applicable for the configured protocol version range. */ 1.844 +/* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */ 1.845 +static int 1.846 +count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) 1.847 +{ 1.848 + int i, count = 0; 1.849 + 1.850 + if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1.851 + return 0; 1.852 + } 1.853 + for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 1.854 + if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange)) 1.855 + count++; 1.856 + } 1.857 + if (count <= 0) { 1.858 + PORT_SetError(SSL_ERROR_SSL_DISABLED); 1.859 + } 1.860 + return count; 1.861 +} 1.862 + 1.863 +/* 1.864 + * Null compression, mac and encryption functions 1.865 + */ 1.866 + 1.867 +static SECStatus 1.868 +Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, 1.869 + const unsigned char *input, int inputLen) 1.870 +{ 1.871 + if (inputLen > maxOutputLen) { 1.872 + *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ 1.873 + PORT_SetError(SEC_ERROR_OUTPUT_LEN); 1.874 + return SECFailure; 1.875 + } 1.876 + *outputLen = inputLen; 1.877 + if (input != output) 1.878 + PORT_Memcpy(output, input, inputLen); 1.879 + return SECSuccess; 1.880 +} 1.881 + 1.882 +/* 1.883 + * SSL3 Utility functions 1.884 + */ 1.885 + 1.886 +/* allowLargerPeerVersion controls whether the function will select the 1.887 + * highest enabled SSL version or fail when peerVersion is greater than the 1.888 + * highest enabled version. 1.889 + * 1.890 + * If allowLargerPeerVersion is true, peerVersion is the peer's highest 1.891 + * enabled version rather than the peer's selected version. 1.892 + */ 1.893 +SECStatus 1.894 +ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, 1.895 + PRBool allowLargerPeerVersion) 1.896 +{ 1.897 + if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1.898 + PORT_SetError(SSL_ERROR_SSL_DISABLED); 1.899 + return SECFailure; 1.900 + } 1.901 + 1.902 + if (peerVersion < ss->vrange.min || 1.903 + (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { 1.904 + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 1.905 + return SECFailure; 1.906 + } 1.907 + 1.908 + ss->version = PR_MIN(peerVersion, ss->vrange.max); 1.909 + PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version)); 1.910 + 1.911 + return SECSuccess; 1.912 +} 1.913 + 1.914 +static SECStatus 1.915 +ssl3_GetNewRandom(SSL3Random *random) 1.916 +{ 1.917 + SECStatus rv; 1.918 + 1.919 + /* first 4 bytes are reserverd for time */ 1.920 + rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH); 1.921 + if (rv != SECSuccess) { 1.922 + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 1.923 + } 1.924 + return rv; 1.925 +} 1.926 + 1.927 +/* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ 1.928 +SECStatus 1.929 +ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, 1.930 + PRBool isTLS) 1.931 +{ 1.932 + SECStatus rv = SECFailure; 1.933 + PRBool doDerEncode = PR_FALSE; 1.934 + int signatureLen; 1.935 + SECItem hashItem; 1.936 + 1.937 + buf->data = NULL; 1.938 + 1.939 + switch (key->keyType) { 1.940 + case rsaKey: 1.941 + hashItem.data = hash->u.raw; 1.942 + hashItem.len = hash->len; 1.943 + break; 1.944 + case dsaKey: 1.945 + doDerEncode = isTLS; 1.946 + /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. 1.947 + * In that case, we use just the SHA1 part. */ 1.948 + if (hash->hashAlg == SEC_OID_UNKNOWN) { 1.949 + hashItem.data = hash->u.s.sha; 1.950 + hashItem.len = sizeof(hash->u.s.sha); 1.951 + } else { 1.952 + hashItem.data = hash->u.raw; 1.953 + hashItem.len = hash->len; 1.954 + } 1.955 + break; 1.956 +#ifndef NSS_DISABLE_ECC 1.957 + case ecKey: 1.958 + doDerEncode = PR_TRUE; 1.959 + /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. 1.960 + * In that case, we use just the SHA1 part. */ 1.961 + if (hash->hashAlg == SEC_OID_UNKNOWN) { 1.962 + hashItem.data = hash->u.s.sha; 1.963 + hashItem.len = sizeof(hash->u.s.sha); 1.964 + } else { 1.965 + hashItem.data = hash->u.raw; 1.966 + hashItem.len = hash->len; 1.967 + } 1.968 + break; 1.969 +#endif /* NSS_DISABLE_ECC */ 1.970 + default: 1.971 + PORT_SetError(SEC_ERROR_INVALID_KEY); 1.972 + goto done; 1.973 + } 1.974 + PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len)); 1.975 + 1.976 + if (hash->hashAlg == SEC_OID_UNKNOWN) { 1.977 + signatureLen = PK11_SignatureLen(key); 1.978 + if (signatureLen <= 0) { 1.979 + PORT_SetError(SEC_ERROR_INVALID_KEY); 1.980 + goto done; 1.981 + } 1.982 + 1.983 + buf->len = (unsigned)signatureLen; 1.984 + buf->data = (unsigned char *)PORT_Alloc(signatureLen); 1.985 + if (!buf->data) 1.986 + goto done; /* error code was set. */ 1.987 + 1.988 + rv = PK11_Sign(key, buf, &hashItem); 1.989 + } else { 1.990 + rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem); 1.991 + } 1.992 + if (rv != SECSuccess) { 1.993 + ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); 1.994 + } else if (doDerEncode) { 1.995 + SECItem derSig = {siBuffer, NULL, 0}; 1.996 + 1.997 + /* This also works for an ECDSA signature */ 1.998 + rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len); 1.999 + if (rv == SECSuccess) { 1.1000 + PORT_Free(buf->data); /* discard unencoded signature. */ 1.1001 + *buf = derSig; /* give caller encoded signature. */ 1.1002 + } else if (derSig.data) { 1.1003 + PORT_Free(derSig.data); 1.1004 + } 1.1005 + } 1.1006 + 1.1007 + PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len)); 1.1008 +done: 1.1009 + if (rv != SECSuccess && buf->data) { 1.1010 + PORT_Free(buf->data); 1.1011 + buf->data = NULL; 1.1012 + } 1.1013 + return rv; 1.1014 +} 1.1015 + 1.1016 +/* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ 1.1017 +SECStatus 1.1018 +ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, 1.1019 + SECItem *buf, PRBool isTLS, void *pwArg) 1.1020 +{ 1.1021 + SECKEYPublicKey * key; 1.1022 + SECItem * signature = NULL; 1.1023 + SECStatus rv; 1.1024 + SECItem hashItem; 1.1025 + SECOidTag encAlg; 1.1026 + SECOidTag hashAlg; 1.1027 + 1.1028 + 1.1029 + PRINT_BUF(60, (NULL, "check signed hashes", 1.1030 + buf->data, buf->len)); 1.1031 + 1.1032 + key = CERT_ExtractPublicKey(cert); 1.1033 + if (key == NULL) { 1.1034 + ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 1.1035 + return SECFailure; 1.1036 + } 1.1037 + 1.1038 + hashAlg = hash->hashAlg; 1.1039 + switch (key->keyType) { 1.1040 + case rsaKey: 1.1041 + encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; 1.1042 + hashItem.data = hash->u.raw; 1.1043 + hashItem.len = hash->len; 1.1044 + break; 1.1045 + case dsaKey: 1.1046 + encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE; 1.1047 + /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. 1.1048 + * In that case, we use just the SHA1 part. */ 1.1049 + if (hash->hashAlg == SEC_OID_UNKNOWN) { 1.1050 + hashItem.data = hash->u.s.sha; 1.1051 + hashItem.len = sizeof(hash->u.s.sha); 1.1052 + } else { 1.1053 + hashItem.data = hash->u.raw; 1.1054 + hashItem.len = hash->len; 1.1055 + } 1.1056 + /* Allow DER encoded DSA signatures in SSL 3.0 */ 1.1057 + if (isTLS || buf->len != SECKEY_SignatureLen(key)) { 1.1058 + signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); 1.1059 + if (!signature) { 1.1060 + PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1.1061 + return SECFailure; 1.1062 + } 1.1063 + buf = signature; 1.1064 + } 1.1065 + break; 1.1066 + 1.1067 +#ifndef NSS_DISABLE_ECC 1.1068 + case ecKey: 1.1069 + encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY; 1.1070 + /* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash. 1.1071 + * In that case, we use just the SHA1 part. 1.1072 + * ECDSA signatures always encode the integers r and s using ASN.1 1.1073 + * (unlike DSA where ASN.1 encoding is used with TLS but not with 1.1074 + * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA. 1.1075 + */ 1.1076 + if (hash->hashAlg == SEC_OID_UNKNOWN) { 1.1077 + hashAlg = SEC_OID_SHA1; 1.1078 + hashItem.data = hash->u.s.sha; 1.1079 + hashItem.len = sizeof(hash->u.s.sha); 1.1080 + } else { 1.1081 + hashItem.data = hash->u.raw; 1.1082 + hashItem.len = hash->len; 1.1083 + } 1.1084 + break; 1.1085 +#endif /* NSS_DISABLE_ECC */ 1.1086 + 1.1087 + default: 1.1088 + SECKEY_DestroyPublicKey(key); 1.1089 + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 1.1090 + return SECFailure; 1.1091 + } 1.1092 + 1.1093 + PRINT_BUF(60, (NULL, "hash(es) to be verified", 1.1094 + hashItem.data, hashItem.len)); 1.1095 + 1.1096 + if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) { 1.1097 + /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded. 1.1098 + * DSA signatures are DER-encoded in TLS but not in SSL3 and the code 1.1099 + * above always removes the DER encoding of DSA signatures when 1.1100 + * present. Thus DSA signatures are always verified with PK11_Verify. 1.1101 + */ 1.1102 + rv = PK11_Verify(key, buf, &hashItem, pwArg); 1.1103 + } else { 1.1104 + rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg, 1.1105 + pwArg); 1.1106 + } 1.1107 + SECKEY_DestroyPublicKey(key); 1.1108 + if (signature) { 1.1109 + SECITEM_FreeItem(signature, PR_TRUE); 1.1110 + } 1.1111 + if (rv != SECSuccess) { 1.1112 + ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1.1113 + } 1.1114 + return rv; 1.1115 +} 1.1116 + 1.1117 + 1.1118 +/* Caller must set hiLevel error code. */ 1.1119 +/* Called from ssl3_ComputeExportRSAKeyHash 1.1120 + * ssl3_ComputeDHKeyHash 1.1121 + * which are called from ssl3_HandleServerKeyExchange. 1.1122 + * 1.1123 + * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify 1.1124 + * the pre-1.2, MD5/SHA1 combination hash. 1.1125 + */ 1.1126 +SECStatus 1.1127 +ssl3_ComputeCommonKeyHash(SECOidTag hashAlg, 1.1128 + PRUint8 * hashBuf, unsigned int bufLen, 1.1129 + SSL3Hashes *hashes, PRBool bypassPKCS11) 1.1130 +{ 1.1131 + SECStatus rv = SECSuccess; 1.1132 + 1.1133 +#ifndef NO_PKCS11_BYPASS 1.1134 + if (bypassPKCS11) { 1.1135 + if (hashAlg == SEC_OID_UNKNOWN) { 1.1136 + MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen); 1.1137 + SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen); 1.1138 + hashes->len = MD5_LENGTH + SHA1_LENGTH; 1.1139 + } else if (hashAlg == SEC_OID_SHA1) { 1.1140 + SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen); 1.1141 + hashes->len = SHA1_LENGTH; 1.1142 + } else if (hashAlg == SEC_OID_SHA256) { 1.1143 + SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen); 1.1144 + hashes->len = SHA256_LENGTH; 1.1145 + } else if (hashAlg == SEC_OID_SHA384) { 1.1146 + SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen); 1.1147 + hashes->len = SHA384_LENGTH; 1.1148 + } else if (hashAlg == SEC_OID_SHA512) { 1.1149 + SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen); 1.1150 + hashes->len = SHA512_LENGTH; 1.1151 + } else { 1.1152 + PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1.1153 + return SECFailure; 1.1154 + } 1.1155 + } else 1.1156 +#endif 1.1157 + { 1.1158 + if (hashAlg == SEC_OID_UNKNOWN) { 1.1159 + rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen); 1.1160 + if (rv != SECSuccess) { 1.1161 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.1162 + rv = SECFailure; 1.1163 + goto done; 1.1164 + } 1.1165 + 1.1166 + rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen); 1.1167 + if (rv != SECSuccess) { 1.1168 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.1169 + rv = SECFailure; 1.1170 + } 1.1171 + hashes->len = MD5_LENGTH + SHA1_LENGTH; 1.1172 + } else { 1.1173 + hashes->len = HASH_ResultLenByOidTag(hashAlg); 1.1174 + if (hashes->len > sizeof(hashes->u.raw)) { 1.1175 + ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1.1176 + rv = SECFailure; 1.1177 + goto done; 1.1178 + } 1.1179 + rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen); 1.1180 + if (rv != SECSuccess) { 1.1181 + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1.1182 + rv = SECFailure; 1.1183 + } 1.1184 + } 1.1185 + } 1.1186 + hashes->hashAlg = hashAlg; 1.1187 + 1.1188 +done: 1.1189 + return rv; 1.1190 +} 1.1191 + 1.1192 +/* Caller must set hiLevel error code. 1.1193 +** Called from ssl3_SendServerKeyExchange and 1.1194 +** ssl3_HandleServerKeyExchange. 1.1195 +*/ 1.1196 +static SECStatus 1.1197 +ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg, 1.1198 + SECItem modulus, SECItem publicExponent, 1.1199 + SSL3Random *client_rand, SSL3Random *server_rand, 1.1200 + SSL3Hashes *hashes, PRBool bypassPKCS11) 1.1201 +{ 1.1202 + PRUint8 * hashBuf; 1.1203 + PRUint8 * pBuf; 1.1204 + SECStatus rv = SECSuccess; 1.1205 + unsigned int bufLen; 1.1206 + PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; 1.1207 + 1.1208 + bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len; 1.1209 + if (bufLen <= sizeof buf) { 1.1210 + hashBuf = buf; 1.1211 + } else { 1.1212 + hashBuf = PORT_Alloc(bufLen); 1.1213 + if (!hashBuf) { 1.1214 + return SECFailure; 1.1215 + } 1.1216 + } 1.1217 + 1.1218 + memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 1.1219 + pBuf = hashBuf + SSL3_RANDOM_LENGTH; 1.1220 + memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); 1.1221 + pBuf += SSL3_RANDOM_LENGTH; 1.1222 + pBuf[0] = (PRUint8)(modulus.len >> 8); 1.1223 + pBuf[1] = (PRUint8)(modulus.len); 1.1224 + pBuf += 2; 1.1225 + memcpy(pBuf, modulus.data, modulus.len); 1.1226 + pBuf += modulus.len; 1.1227 + pBuf[0] = (PRUint8)(publicExponent.len >> 8); 1.1228 + pBuf[1] = (PRUint8)(publicExponent.len); 1.1229 + pBuf += 2; 1.1230 + memcpy(pBuf, publicExponent.data, publicExponent.len); 1.1231 + pBuf += publicExponent.len; 1.1232 + PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); 1.1233 + 1.1234 + rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, 1.1235 + bypassPKCS11); 1.1236 + 1.1237 + PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen)); 1.1238 + if (hashAlg == SEC_OID_UNKNOWN) { 1.1239 + PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", 1.1240 + hashes->u.s.md5, MD5_LENGTH)); 1.1241 + PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", 1.1242 + hashes->u.s.sha, SHA1_LENGTH)); 1.1243 + } else { 1.1244 + PRINT_BUF(95, (NULL, "RSAkey hash: result", 1.1245 + hashes->u.raw, hashes->len)); 1.1246 + } 1.1247 + 1.1248 + if (hashBuf != buf && hashBuf != NULL) 1.1249 + PORT_Free(hashBuf); 1.1250 + return rv; 1.1251 +} 1.1252 + 1.1253 +/* Caller must set hiLevel error code. */ 1.1254 +/* Called from ssl3_HandleServerKeyExchange. */ 1.1255 +static SECStatus 1.1256 +ssl3_ComputeDHKeyHash(SECOidTag hashAlg, 1.1257 + SECItem dh_p, SECItem dh_g, SECItem dh_Ys, 1.1258 + SSL3Random *client_rand, SSL3Random *server_rand, 1.1259 + SSL3Hashes *hashes, PRBool bypassPKCS11) 1.1260 +{ 1.1261 + PRUint8 * hashBuf; 1.1262 + PRUint8 * pBuf; 1.1263 + SECStatus rv = SECSuccess; 1.1264 + unsigned int bufLen; 1.1265 + PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; 1.1266 + 1.1267 + bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len; 1.1268 + if (bufLen <= sizeof buf) { 1.1269 + hashBuf = buf; 1.1270 + } else { 1.1271 + hashBuf = PORT_Alloc(bufLen); 1.1272 + if (!hashBuf) { 1.1273 + return SECFailure; 1.1274 + } 1.1275 + } 1.1276 + 1.1277 + memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); 1.1278 + pBuf = hashBuf + SSL3_RANDOM_LENGTH; 1.1279 + memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); 1.1280 + pBuf += SSL3_RANDOM_LENGTH; 1.1281 + pBuf[0] = (PRUint8)(dh_p.len >> 8); 1.1282 + pBuf[1] = (PRUint8)(dh_p.len); 1.1283 + pBuf += 2; 1.1284 + memcpy(pBuf, dh_p.data, dh_p.len); 1.1285 + pBuf += dh_p.len; 1.1286 + pBuf[0] = (PRUint8)(dh_g.len >> 8); 1.1287 + pBuf[1] = (PRUint8)(dh_g.len); 1.1288 + pBuf += 2; 1.1289 + memcpy(pBuf, dh_g.data, dh_g.len); 1.1290 + pBuf += dh_g.len; 1.1291 + pBuf[0] = (PRUint8)(dh_Ys.len >> 8); 1.1292 + pBuf[1] = (PRUint8)(dh_Ys.len); 1.1293 + pBuf += 2; 1.1294 + memcpy(pBuf, dh_Ys.data, dh_Ys.len); 1.1295 + pBuf += dh_Ys.len; 1.1296 + PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); 1.1297 + 1.1298 + rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, 1.1299 + bypassPKCS11); 1.1300 + 1.1301 + PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen)); 1.1302 + if (hashAlg == SEC_OID_UNKNOWN) { 1.1303 + PRINT_BUF(95, (NULL, "DHkey hash: MD5 result", 1.1304 + hashes->u.s.md5, MD5_LENGTH)); 1.1305 + PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result", 1.1306 + hashes->u.s.sha, SHA1_LENGTH)); 1.1307 + } else { 1.1308 + PRINT_BUF(95, (NULL, "DHkey hash: result", 1.1309 + hashes->u.raw, hashes->len)); 1.1310 + } 1.1311 + 1.1312 + if (hashBuf != buf && hashBuf != NULL) 1.1313 + PORT_Free(hashBuf); 1.1314 + return rv; 1.1315 +} 1.1316 + 1.1317 +static void 1.1318 +ssl3_BumpSequenceNumber(SSL3SequenceNumber *num) 1.1319 +{ 1.1320 + num->low++; 1.1321 + if (num->low == 0) 1.1322 + num->high++; 1.1323 +} 1.1324 + 1.1325 +/* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */ 1.1326 +static void 1.1327 +ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat) 1.1328 +{ 1.1329 + if (mat->write_key != NULL) { 1.1330 + PK11_FreeSymKey(mat->write_key); 1.1331 + mat->write_key = NULL; 1.1332 + } 1.1333 + if (mat->write_mac_key != NULL) { 1.1334 + PK11_FreeSymKey(mat->write_mac_key); 1.1335 + mat->write_mac_key = NULL; 1.1336 + } 1.1337 + if (mat->write_mac_context != NULL) { 1.1338 + PK11_DestroyContext(mat->write_mac_context, PR_TRUE); 1.1339 + mat->write_mac_context = NULL; 1.1340 + } 1.1341 +} 1.1342 + 1.1343 +/* Called from ssl3_SendChangeCipherSpecs() and 1.1344 +** ssl3_HandleChangeCipherSpecs() 1.1345 +** ssl3_DestroySSL3Info 1.1346 +** Caller must hold SpecWriteLock. 1.1347 +*/ 1.1348 +void 1.1349 +ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) 1.1350 +{ 1.1351 + PRBool freeit = (PRBool)(!spec->bypassCiphers); 1.1352 +/* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */ 1.1353 + if (spec->destroy) { 1.1354 + spec->destroy(spec->encodeContext, freeit); 1.1355 + spec->destroy(spec->decodeContext, freeit); 1.1356 + spec->encodeContext = NULL; /* paranoia */ 1.1357 + spec->decodeContext = NULL; 1.1358 + } 1.1359 + if (spec->destroyCompressContext && spec->compressContext) { 1.1360 + spec->destroyCompressContext(spec->compressContext, 1); 1.1361 + spec->compressContext = NULL; 1.1362 + } 1.1363 + if (spec->destroyDecompressContext && spec->decompressContext) { 1.1364 + spec->destroyDecompressContext(spec->decompressContext, 1); 1.1365 + spec->decompressContext = NULL; 1.1366 + } 1.1367 + if (freeSrvName && spec->srvVirtName.data) { 1.1368 + SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE); 1.1369 + } 1.1370 + if (spec->master_secret != NULL) { 1.1371 + PK11_FreeSymKey(spec->master_secret); 1.1372 + spec->master_secret = NULL; 1.1373 + } 1.1374 + spec->msItem.data = NULL; 1.1375 + spec->msItem.len = 0; 1.1376 + ssl3_CleanupKeyMaterial(&spec->client); 1.1377 + ssl3_CleanupKeyMaterial(&spec->server); 1.1378 + spec->bypassCiphers = PR_FALSE; 1.1379 + spec->destroy=NULL; 1.1380 + spec->destroyCompressContext = NULL; 1.1381 + spec->destroyDecompressContext = NULL; 1.1382 +} 1.1383 + 1.1384 +/* Fill in the pending cipher spec with info from the selected ciphersuite. 1.1385 +** This is as much initialization as we can do without having key material. 1.1386 +** Called from ssl3_HandleServerHello(), ssl3_SendServerHello() 1.1387 +** Caller must hold the ssl3 handshake lock. 1.1388 +** Acquires & releases SpecWriteLock. 1.1389 +*/ 1.1390 +static SECStatus 1.1391 +ssl3_SetupPendingCipherSpec(sslSocket *ss) 1.1392 +{ 1.1393 + ssl3CipherSpec * pwSpec; 1.1394 + ssl3CipherSpec * cwSpec; 1.1395 + ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; 1.1396 + SSL3MACAlgorithm mac; 1.1397 + SSL3BulkCipher cipher; 1.1398 + SSL3KeyExchangeAlgorithm kea; 1.1399 + const ssl3CipherSuiteDef *suite_def; 1.1400 + PRBool isTLS; 1.1401 + 1.1402 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.1403 + 1.1404 + ssl_GetSpecWriteLock(ss); /*******************************/ 1.1405 + 1.1406 + pwSpec = ss->ssl3.pwSpec; 1.1407 + PORT_Assert(pwSpec == ss->ssl3.prSpec); 1.1408 + 1.1409 + /* This hack provides maximal interoperability with SSL 3 servers. */ 1.1410 + cwSpec = ss->ssl3.cwSpec; 1.1411 + if (cwSpec->mac_def->mac == mac_null) { 1.1412 + /* SSL records are not being MACed. */ 1.1413 + cwSpec->version = ss->version; 1.1414 + } 1.1415 + 1.1416 + pwSpec->version = ss->version; 1.1417 + isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); 1.1418 + 1.1419 + SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", 1.1420 + SSL_GETPID(), ss->fd, suite)); 1.1421 + 1.1422 + suite_def = ssl_LookupCipherSuiteDef(suite); 1.1423 + if (suite_def == NULL) { 1.1424 + ssl_ReleaseSpecWriteLock(ss); 1.1425 + return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ 1.1426 + } 1.1427 + 1.1428 + if (IS_DTLS(ss)) { 1.1429 + /* Double-check that we did not pick an RC4 suite */ 1.1430 + PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && 1.1431 + (suite_def->bulk_cipher_alg != cipher_rc4_40) && 1.1432 + (suite_def->bulk_cipher_alg != cipher_rc4_56)); 1.1433 + } 1.1434 + 1.1435 + cipher = suite_def->bulk_cipher_alg; 1.1436 + kea = suite_def->key_exchange_alg; 1.1437 + mac = suite_def->mac_alg; 1.1438 + if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) 1.1439 + mac += 2; 1.1440 + 1.1441 + ss->ssl3.hs.suite_def = suite_def; 1.1442 + ss->ssl3.hs.kea_def = &kea_defs[kea]; 1.1443 + PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); 1.1444 + 1.1445 + pwSpec->cipher_def = &bulk_cipher_defs[cipher]; 1.1446 + PORT_Assert(pwSpec->cipher_def->cipher == cipher); 1.1447 + 1.1448 + pwSpec->mac_def = &mac_defs[mac]; 1.1449 + PORT_Assert(pwSpec->mac_def->mac == mac); 1.1450 + 1.1451 + ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; 1.1452 + ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB; 1.1453 + ss->sec.cipherType = cipher; 1.1454 + 1.1455 + pwSpec->encodeContext = NULL; 1.1456 + pwSpec->decodeContext = NULL; 1.1457 + 1.1458 + pwSpec->mac_size = pwSpec->mac_def->mac_size; 1.1459 + 1.1460 + pwSpec->compression_method = ss->ssl3.hs.compression; 1.1461 + pwSpec->compressContext = NULL; 1.1462 + pwSpec->decompressContext = NULL; 1.1463 + 1.1464 + ssl_ReleaseSpecWriteLock(ss); /*******************************/ 1.1465 + return SECSuccess; 1.1466 +} 1.1467 + 1.1468 +#ifdef NSS_ENABLE_ZLIB 1.1469 +#define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream) 1.1470 + 1.1471 +static SECStatus 1.1472 +ssl3_MapZlibError(int zlib_error) 1.1473 +{ 1.1474 + switch (zlib_error) { 1.1475 + case Z_OK: 1.1476 + return SECSuccess; 1.1477 + default: 1.1478 + return SECFailure; 1.1479 + } 1.1480 +} 1.1481 + 1.1482 +static SECStatus 1.1483 +ssl3_DeflateInit(void *void_context) 1.1484 +{ 1.1485 + z_stream *context = void_context; 1.1486 + context->zalloc = NULL; 1.1487 + context->zfree = NULL; 1.1488 + context->opaque = NULL; 1.1489 + 1.1490 + return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION)); 1.1491 +} 1.1492 + 1.1493 +static SECStatus 1.1494 +ssl3_InflateInit(void *void_context) 1.1495 +{ 1.1496 + z_stream *context = void_context; 1.1497 + context->zalloc = NULL; 1.1498 + context->zfree = NULL; 1.1499 + context->opaque = NULL; 1.1500 + context->next_in = NULL; 1.1501 + context->avail_in = 0; 1.1502 + 1.1503 + return ssl3_MapZlibError(inflateInit(context)); 1.1504 +} 1.1505 + 1.1506 +static SECStatus 1.1507 +ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len, 1.1508 + int maxout, const unsigned char *in, int inlen) 1.1509 +{ 1.1510 + z_stream *context = void_context; 1.1511 + 1.1512 + if (!inlen) { 1.1513 + *out_len = 0; 1.1514 + return SECSuccess; 1.1515 + } 1.1516 + 1.1517 + context->next_in = (unsigned char*) in; 1.1518 + context->avail_in = inlen; 1.1519 + context->next_out = out; 1.1520 + context->avail_out = maxout; 1.1521 + if (deflate(context, Z_SYNC_FLUSH) != Z_OK) { 1.1522 + return SECFailure; 1.1523 + } 1.1524 + if (context->avail_out == 0) { 1.1525 + /* We ran out of space! */ 1.1526 + SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing", 1.1527 + SSL_GETPID())); 1.1528 + return SECFailure; 1.1529 + } 1.1530 + 1.1531 + *out_len = maxout - context->avail_out; 1.1532 + return SECSuccess; 1.1533 +} 1.1534 + 1.1535 +static SECStatus 1.1536 +ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len, 1.1537 + int maxout, const unsigned char *in, int inlen) 1.1538 +{ 1.1539 + z_stream *context = void_context; 1.1540 + 1.1541 + if (!inlen) { 1.1542 + *out_len = 0; 1.1543 + return SECSuccess; 1.1544 + } 1.1545 + 1.1546 + context->next_in = (unsigned char*) in; 1.1547 + context->avail_in = inlen; 1.1548 + context->next_out = out; 1.1549 + context->avail_out = maxout; 1.1550 + if (inflate(context, Z_SYNC_FLUSH) != Z_OK) { 1.1551 + PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE); 1.1552 + return SECFailure; 1.1553 + } 1.1554 + 1.1555 + *out_len = maxout - context->avail_out; 1.1556 + return SECSuccess; 1.1557 +} 1.1558 + 1.1559 +static SECStatus 1.1560 +ssl3_DestroyCompressContext(void *void_context, PRBool unused) 1.1561 +{ 1.1562 + deflateEnd(void_context); 1.1563 + PORT_Free(void_context); 1.1564 + return SECSuccess; 1.1565 +} 1.1566 + 1.1567 +static SECStatus 1.1568 +ssl3_DestroyDecompressContext(void *void_context, PRBool unused) 1.1569 +{ 1.1570 + inflateEnd(void_context); 1.1571 + PORT_Free(void_context); 1.1572 + return SECSuccess; 1.1573 +} 1.1574 + 1.1575 +#endif /* NSS_ENABLE_ZLIB */ 1.1576 + 1.1577 +/* Initialize the compression functions and contexts for the given 1.1578 + * CipherSpec. */ 1.1579 +static SECStatus 1.1580 +ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) 1.1581 +{ 1.1582 + /* Setup the compression functions */ 1.1583 + switch (pwSpec->compression_method) { 1.1584 + case ssl_compression_null: 1.1585 + pwSpec->compressor = NULL; 1.1586 + pwSpec->decompressor = NULL; 1.1587 + pwSpec->compressContext = NULL; 1.1588 + pwSpec->decompressContext = NULL; 1.1589 + pwSpec->destroyCompressContext = NULL; 1.1590 + pwSpec->destroyDecompressContext = NULL; 1.1591 + break; 1.1592 +#ifdef NSS_ENABLE_ZLIB 1.1593 + case ssl_compression_deflate: 1.1594 + pwSpec->compressor = ssl3_DeflateCompress; 1.1595 + pwSpec->decompressor = ssl3_DeflateDecompress; 1.1596 + pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); 1.1597 + pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); 1.1598 + pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; 1.1599 + pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; 1.1600 + ssl3_DeflateInit(pwSpec->compressContext); 1.1601 + ssl3_InflateInit(pwSpec->decompressContext); 1.1602 + break; 1.1603 +#endif /* NSS_ENABLE_ZLIB */ 1.1604 + default: 1.1605 + PORT_Assert(0); 1.1606 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.1607 + return SECFailure; 1.1608 + } 1.1609 + 1.1610 + return SECSuccess; 1.1611 +} 1.1612 + 1.1613 +#ifndef NO_PKCS11_BYPASS 1.1614 +/* Initialize encryption contexts for pending spec. 1.1615 + * MAC contexts are set up when computing the mac, not here. 1.1616 + * Master Secret already is derived in spec->msItem 1.1617 + * Caller holds Spec write lock. 1.1618 + */ 1.1619 +static SECStatus 1.1620 +ssl3_InitPendingContextsBypass(sslSocket *ss) 1.1621 +{ 1.1622 + ssl3CipherSpec * pwSpec; 1.1623 + const ssl3BulkCipherDef *cipher_def; 1.1624 + void * serverContext = NULL; 1.1625 + void * clientContext = NULL; 1.1626 + BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; 1.1627 + int mode = 0; 1.1628 + unsigned int optArg1 = 0; 1.1629 + unsigned int optArg2 = 0; 1.1630 + PRBool server_encrypts = ss->sec.isServer; 1.1631 + SSLCipherAlgorithm calg; 1.1632 + SECStatus rv; 1.1633 + 1.1634 + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.1635 + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 1.1636 + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 1.1637 + 1.1638 + pwSpec = ss->ssl3.pwSpec; 1.1639 + cipher_def = pwSpec->cipher_def; 1.1640 + 1.1641 + calg = cipher_def->calg; 1.1642 + 1.1643 + if (calg == ssl_calg_aes_gcm) { 1.1644 + pwSpec->encode = NULL; 1.1645 + pwSpec->decode = NULL; 1.1646 + pwSpec->destroy = NULL; 1.1647 + pwSpec->encodeContext = NULL; 1.1648 + pwSpec->decodeContext = NULL; 1.1649 + pwSpec->aead = ssl3_AESGCMBypass; 1.1650 + ssl3_InitCompressionContext(pwSpec); 1.1651 + return SECSuccess; 1.1652 + } 1.1653 + 1.1654 + serverContext = pwSpec->server.cipher_context; 1.1655 + clientContext = pwSpec->client.cipher_context; 1.1656 + 1.1657 + switch (calg) { 1.1658 + case ssl_calg_null: 1.1659 + pwSpec->encode = Null_Cipher; 1.1660 + pwSpec->decode = Null_Cipher; 1.1661 + pwSpec->destroy = NULL; 1.1662 + goto success; 1.1663 + 1.1664 + case ssl_calg_rc4: 1.1665 + initFn = (BLapiInitContextFunc)RC4_InitContext; 1.1666 + pwSpec->encode = (SSLCipher) RC4_Encrypt; 1.1667 + pwSpec->decode = (SSLCipher) RC4_Decrypt; 1.1668 + pwSpec->destroy = (SSLDestroy) RC4_DestroyContext; 1.1669 + break; 1.1670 + case ssl_calg_rc2: 1.1671 + initFn = (BLapiInitContextFunc)RC2_InitContext; 1.1672 + mode = NSS_RC2_CBC; 1.1673 + optArg1 = cipher_def->key_size; 1.1674 + pwSpec->encode = (SSLCipher) RC2_Encrypt; 1.1675 + pwSpec->decode = (SSLCipher) RC2_Decrypt; 1.1676 + pwSpec->destroy = (SSLDestroy) RC2_DestroyContext; 1.1677 + break; 1.1678 + case ssl_calg_des: 1.1679 + initFn = (BLapiInitContextFunc)DES_InitContext; 1.1680 + mode = NSS_DES_CBC; 1.1681 + optArg1 = server_encrypts; 1.1682 + pwSpec->encode = (SSLCipher) DES_Encrypt; 1.1683 + pwSpec->decode = (SSLCipher) DES_Decrypt; 1.1684 + pwSpec->destroy = (SSLDestroy) DES_DestroyContext; 1.1685 + break; 1.1686 + case ssl_calg_3des: 1.1687 + initFn = (BLapiInitContextFunc)DES_InitContext; 1.1688 + mode = NSS_DES_EDE3_CBC; 1.1689 + optArg1 = server_encrypts; 1.1690 + pwSpec->encode = (SSLCipher) DES_Encrypt; 1.1691 + pwSpec->decode = (SSLCipher) DES_Decrypt; 1.1692 + pwSpec->destroy = (SSLDestroy) DES_DestroyContext; 1.1693 + break; 1.1694 + case ssl_calg_aes: 1.1695 + initFn = (BLapiInitContextFunc)AES_InitContext; 1.1696 + mode = NSS_AES_CBC; 1.1697 + optArg1 = server_encrypts; 1.1698 + optArg2 = AES_BLOCK_SIZE; 1.1699 + pwSpec->encode = (SSLCipher) AES_Encrypt; 1.1700 + pwSpec->decode = (SSLCipher) AES_Decrypt; 1.1701 + pwSpec->destroy = (SSLDestroy) AES_DestroyContext; 1.1702 + break; 1.1703 + 1.1704 + case ssl_calg_camellia: 1.1705 + initFn = (BLapiInitContextFunc)Camellia_InitContext; 1.1706 + mode = NSS_CAMELLIA_CBC; 1.1707 + optArg1 = server_encrypts; 1.1708 + optArg2 = CAMELLIA_BLOCK_SIZE; 1.1709 + pwSpec->encode = (SSLCipher) Camellia_Encrypt; 1.1710 + pwSpec->decode = (SSLCipher) Camellia_Decrypt; 1.1711 + pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext; 1.1712 + break; 1.1713 + 1.1714 + case ssl_calg_seed: 1.1715 + initFn = (BLapiInitContextFunc)SEED_InitContext; 1.1716 + mode = NSS_SEED_CBC; 1.1717 + optArg1 = server_encrypts; 1.1718 + optArg2 = SEED_BLOCK_SIZE; 1.1719 + pwSpec->encode = (SSLCipher) SEED_Encrypt; 1.1720 + pwSpec->decode = (SSLCipher) SEED_Decrypt; 1.1721 + pwSpec->destroy = (SSLDestroy) SEED_DestroyContext; 1.1722 + break; 1.1723 + 1.1724 + case ssl_calg_idea: 1.1725 + case ssl_calg_fortezza : 1.1726 + default: 1.1727 + PORT_Assert(0); 1.1728 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.1729 + goto bail_out; 1.1730 + } 1.1731 + rv = (*initFn)(serverContext, 1.1732 + pwSpec->server.write_key_item.data, 1.1733 + pwSpec->server.write_key_item.len, 1.1734 + pwSpec->server.write_iv_item.data, 1.1735 + mode, optArg1, optArg2); 1.1736 + if (rv != SECSuccess) { 1.1737 + PORT_Assert(0); 1.1738 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.1739 + goto bail_out; 1.1740 + } 1.1741 + 1.1742 + switch (calg) { 1.1743 + case ssl_calg_des: 1.1744 + case ssl_calg_3des: 1.1745 + case ssl_calg_aes: 1.1746 + case ssl_calg_camellia: 1.1747 + case ssl_calg_seed: 1.1748 + /* For block ciphers, if the server is encrypting, then the client 1.1749 + * is decrypting, and vice versa. 1.1750 + */ 1.1751 + optArg1 = !optArg1; 1.1752 + break; 1.1753 + /* kill warnings. */ 1.1754 + case ssl_calg_null: 1.1755 + case ssl_calg_rc4: 1.1756 + case ssl_calg_rc2: 1.1757 + case ssl_calg_idea: 1.1758 + case ssl_calg_fortezza: 1.1759 + case ssl_calg_aes_gcm: 1.1760 + break; 1.1761 + } 1.1762 + 1.1763 + rv = (*initFn)(clientContext, 1.1764 + pwSpec->client.write_key_item.data, 1.1765 + pwSpec->client.write_key_item.len, 1.1766 + pwSpec->client.write_iv_item.data, 1.1767 + mode, optArg1, optArg2); 1.1768 + if (rv != SECSuccess) { 1.1769 + PORT_Assert(0); 1.1770 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.1771 + goto bail_out; 1.1772 + } 1.1773 + 1.1774 + pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; 1.1775 + pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; 1.1776 + 1.1777 + ssl3_InitCompressionContext(pwSpec); 1.1778 + 1.1779 +success: 1.1780 + return SECSuccess; 1.1781 + 1.1782 +bail_out: 1.1783 + return SECFailure; 1.1784 +} 1.1785 +#endif 1.1786 + 1.1787 +/* This function should probably be moved to pk11wrap and be named 1.1788 + * PK11_ParamFromIVAndEffectiveKeyBits 1.1789 + */ 1.1790 +static SECItem * 1.1791 +ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) 1.1792 +{ 1.1793 + SECItem * param = PK11_ParamFromIV(mtype, iv); 1.1794 + if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { 1.1795 + switch (mtype) { 1.1796 + case CKM_RC2_KEY_GEN: 1.1797 + case CKM_RC2_ECB: 1.1798 + case CKM_RC2_CBC: 1.1799 + case CKM_RC2_MAC: 1.1800 + case CKM_RC2_MAC_GENERAL: 1.1801 + case CKM_RC2_CBC_PAD: 1.1802 + *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; 1.1803 + default: break; 1.1804 + } 1.1805 + } 1.1806 + return param; 1.1807 +} 1.1808 + 1.1809 +/* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data 1.1810 + * which is included in the MAC or AEAD additional data) to |out| and returns 1.1811 + * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the 1.1812 + * definition of the AEAD additional data. 1.1813 + * 1.1814 + * TLS pseudo-header includes the record's version field, SSL's doesn't. Which 1.1815 + * pseudo-header defintiion to use should be decided based on the version of 1.1816 + * the protocol that was negotiated when the cipher spec became current, NOT 1.1817 + * based on the version value in the record itself, and the decision is passed 1.1818 + * to this function as the |includesVersion| argument. But, the |version| 1.1819 + * argument should be the record's version value. 1.1820 + */ 1.1821 +static unsigned int 1.1822 +ssl3_BuildRecordPseudoHeader(unsigned char *out, 1.1823 + SSL3SequenceNumber seq_num, 1.1824 + SSL3ContentType type, 1.1825 + PRBool includesVersion, 1.1826 + SSL3ProtocolVersion version, 1.1827 + PRBool isDTLS, 1.1828 + int length) 1.1829 +{ 1.1830 + out[0] = (unsigned char)(seq_num.high >> 24); 1.1831 + out[1] = (unsigned char)(seq_num.high >> 16); 1.1832 + out[2] = (unsigned char)(seq_num.high >> 8); 1.1833 + out[3] = (unsigned char)(seq_num.high >> 0); 1.1834 + out[4] = (unsigned char)(seq_num.low >> 24); 1.1835 + out[5] = (unsigned char)(seq_num.low >> 16); 1.1836 + out[6] = (unsigned char)(seq_num.low >> 8); 1.1837 + out[7] = (unsigned char)(seq_num.low >> 0); 1.1838 + out[8] = type; 1.1839 + 1.1840 + /* SSL3 MAC doesn't include the record's version field. */ 1.1841 + if (!includesVersion) { 1.1842 + out[9] = MSB(length); 1.1843 + out[10] = LSB(length); 1.1844 + return 11; 1.1845 + } 1.1846 + 1.1847 + /* TLS MAC and AEAD additional data include version. */ 1.1848 + if (isDTLS) { 1.1849 + SSL3ProtocolVersion dtls_version; 1.1850 + 1.1851 + dtls_version = dtls_TLSVersionToDTLSVersion(version); 1.1852 + out[9] = MSB(dtls_version); 1.1853 + out[10] = LSB(dtls_version); 1.1854 + } else { 1.1855 + out[9] = MSB(version); 1.1856 + out[10] = LSB(version); 1.1857 + } 1.1858 + out[11] = MSB(length); 1.1859 + out[12] = LSB(length); 1.1860 + return 13; 1.1861 +} 1.1862 + 1.1863 +static SECStatus 1.1864 +ssl3_AESGCM(ssl3KeyMaterial *keys, 1.1865 + PRBool doDecrypt, 1.1866 + unsigned char *out, 1.1867 + int *outlen, 1.1868 + int maxout, 1.1869 + const unsigned char *in, 1.1870 + int inlen, 1.1871 + const unsigned char *additionalData, 1.1872 + int additionalDataLen) 1.1873 +{ 1.1874 + SECItem param; 1.1875 + SECStatus rv = SECFailure; 1.1876 + unsigned char nonce[12]; 1.1877 + unsigned int uOutLen; 1.1878 + CK_GCM_PARAMS gcmParams; 1.1879 + 1.1880 + static const int tagSize = 16; 1.1881 + static const int explicitNonceLen = 8; 1.1882 + 1.1883 + /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the 1.1884 + * nonce is formed. */ 1.1885 + memcpy(nonce, keys->write_iv, 4); 1.1886 + if (doDecrypt) { 1.1887 + memcpy(nonce + 4, in, explicitNonceLen); 1.1888 + in += explicitNonceLen; 1.1889 + inlen -= explicitNonceLen; 1.1890 + *outlen = 0; 1.1891 + } else { 1.1892 + if (maxout < explicitNonceLen) { 1.1893 + PORT_SetError(SEC_ERROR_INPUT_LEN); 1.1894 + return SECFailure; 1.1895 + } 1.1896 + /* Use the 64-bit sequence number as the explicit nonce. */ 1.1897 + memcpy(nonce + 4, additionalData, explicitNonceLen); 1.1898 + memcpy(out, additionalData, explicitNonceLen); 1.1899 + out += explicitNonceLen; 1.1900 + maxout -= explicitNonceLen; 1.1901 + *outlen = explicitNonceLen; 1.1902 + } 1.1903 + 1.1904 + param.type = siBuffer; 1.1905 + param.data = (unsigned char *) &gcmParams; 1.1906 + param.len = sizeof(gcmParams); 1.1907 + gcmParams.pIv = nonce; 1.1908 + gcmParams.ulIvLen = sizeof(nonce); 1.1909 + gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ 1.1910 + gcmParams.ulAADLen = additionalDataLen; 1.1911 + gcmParams.ulTagBits = tagSize * 8; 1.1912 + 1.1913 + if (doDecrypt) { 1.1914 + rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, 1.1915 + maxout, in, inlen); 1.1916 + } else { 1.1917 + rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, 1.1918 + maxout, in, inlen); 1.1919 + } 1.1920 + *outlen += (int) uOutLen; 1.1921 + 1.1922 + return rv; 1.1923 +} 1.1924 + 1.1925 +#ifndef NO_PKCS11_BYPASS 1.1926 +static SECStatus 1.1927 +ssl3_AESGCMBypass(ssl3KeyMaterial *keys, 1.1928 + PRBool doDecrypt, 1.1929 + unsigned char *out, 1.1930 + int *outlen, 1.1931 + int maxout, 1.1932 + const unsigned char *in, 1.1933 + int inlen, 1.1934 + const unsigned char *additionalData, 1.1935 + int additionalDataLen) 1.1936 +{ 1.1937 + SECStatus rv = SECFailure; 1.1938 + unsigned char nonce[12]; 1.1939 + unsigned int uOutLen; 1.1940 + AESContext *cx; 1.1941 + CK_GCM_PARAMS gcmParams; 1.1942 + 1.1943 + static const int tagSize = 16; 1.1944 + static const int explicitNonceLen = 8; 1.1945 + 1.1946 + /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the 1.1947 + * nonce is formed. */ 1.1948 + PORT_Assert(keys->write_iv_item.len == 4); 1.1949 + if (keys->write_iv_item.len != 4) { 1.1950 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.1951 + return SECFailure; 1.1952 + } 1.1953 + memcpy(nonce, keys->write_iv_item.data, 4); 1.1954 + if (doDecrypt) { 1.1955 + memcpy(nonce + 4, in, explicitNonceLen); 1.1956 + in += explicitNonceLen; 1.1957 + inlen -= explicitNonceLen; 1.1958 + *outlen = 0; 1.1959 + } else { 1.1960 + if (maxout < explicitNonceLen) { 1.1961 + PORT_SetError(SEC_ERROR_INPUT_LEN); 1.1962 + return SECFailure; 1.1963 + } 1.1964 + /* Use the 64-bit sequence number as the explicit nonce. */ 1.1965 + memcpy(nonce + 4, additionalData, explicitNonceLen); 1.1966 + memcpy(out, additionalData, explicitNonceLen); 1.1967 + out += explicitNonceLen; 1.1968 + maxout -= explicitNonceLen; 1.1969 + *outlen = explicitNonceLen; 1.1970 + } 1.1971 + 1.1972 + gcmParams.pIv = nonce; 1.1973 + gcmParams.ulIvLen = sizeof(nonce); 1.1974 + gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ 1.1975 + gcmParams.ulAADLen = additionalDataLen; 1.1976 + gcmParams.ulTagBits = tagSize * 8; 1.1977 + 1.1978 + cx = (AESContext *)keys->cipher_context; 1.1979 + rv = AES_InitContext(cx, keys->write_key_item.data, 1.1980 + keys->write_key_item.len, 1.1981 + (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, 1.1982 + AES_BLOCK_SIZE); 1.1983 + if (rv != SECSuccess) { 1.1984 + return rv; 1.1985 + } 1.1986 + if (doDecrypt) { 1.1987 + rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); 1.1988 + } else { 1.1989 + rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); 1.1990 + } 1.1991 + AES_DestroyContext(cx, PR_FALSE); 1.1992 + *outlen += (int) uOutLen; 1.1993 + 1.1994 + return rv; 1.1995 +} 1.1996 +#endif 1.1997 + 1.1998 +/* Initialize encryption and MAC contexts for pending spec. 1.1999 + * Master Secret already is derived. 1.2000 + * Caller holds Spec write lock. 1.2001 + */ 1.2002 +static SECStatus 1.2003 +ssl3_InitPendingContextsPKCS11(sslSocket *ss) 1.2004 +{ 1.2005 + ssl3CipherSpec * pwSpec; 1.2006 + const ssl3BulkCipherDef *cipher_def; 1.2007 + PK11Context * serverContext = NULL; 1.2008 + PK11Context * clientContext = NULL; 1.2009 + SECItem * param; 1.2010 + CK_MECHANISM_TYPE mechanism; 1.2011 + CK_MECHANISM_TYPE mac_mech; 1.2012 + CK_ULONG macLength; 1.2013 + CK_ULONG effKeyBits; 1.2014 + SECItem iv; 1.2015 + SECItem mac_param; 1.2016 + SSLCipherAlgorithm calg; 1.2017 + 1.2018 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.2019 + PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 1.2020 + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 1.2021 + 1.2022 + pwSpec = ss->ssl3.pwSpec; 1.2023 + cipher_def = pwSpec->cipher_def; 1.2024 + macLength = pwSpec->mac_size; 1.2025 + calg = cipher_def->calg; 1.2026 + PORT_Assert(alg2Mech[calg].calg == calg); 1.2027 + 1.2028 + pwSpec->client.write_mac_context = NULL; 1.2029 + pwSpec->server.write_mac_context = NULL; 1.2030 + 1.2031 + if (calg == calg_aes_gcm) { 1.2032 + pwSpec->encode = NULL; 1.2033 + pwSpec->decode = NULL; 1.2034 + pwSpec->destroy = NULL; 1.2035 + pwSpec->encodeContext = NULL; 1.2036 + pwSpec->decodeContext = NULL; 1.2037 + pwSpec->aead = ssl3_AESGCM; 1.2038 + return SECSuccess; 1.2039 + } 1.2040 + 1.2041 + /* 1.2042 + ** Now setup the MAC contexts, 1.2043 + ** crypto contexts are setup below. 1.2044 + */ 1.2045 + 1.2046 + mac_mech = pwSpec->mac_def->mmech; 1.2047 + mac_param.data = (unsigned char *)&macLength; 1.2048 + mac_param.len = sizeof(macLength); 1.2049 + mac_param.type = 0; 1.2050 + 1.2051 + pwSpec->client.write_mac_context = PK11_CreateContextBySymKey( 1.2052 + mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); 1.2053 + if (pwSpec->client.write_mac_context == NULL) { 1.2054 + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 1.2055 + goto fail; 1.2056 + } 1.2057 + pwSpec->server.write_mac_context = PK11_CreateContextBySymKey( 1.2058 + mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); 1.2059 + if (pwSpec->server.write_mac_context == NULL) { 1.2060 + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 1.2061 + goto fail; 1.2062 + } 1.2063 + 1.2064 + /* 1.2065 + ** Now setup the crypto contexts. 1.2066 + */ 1.2067 + 1.2068 + if (calg == calg_null) { 1.2069 + pwSpec->encode = Null_Cipher; 1.2070 + pwSpec->decode = Null_Cipher; 1.2071 + pwSpec->destroy = NULL; 1.2072 + return SECSuccess; 1.2073 + } 1.2074 + mechanism = alg2Mech[calg].cmech; 1.2075 + effKeyBits = cipher_def->key_size * BPB; 1.2076 + 1.2077 + /* 1.2078 + * build the server context 1.2079 + */ 1.2080 + iv.data = pwSpec->server.write_iv; 1.2081 + iv.len = cipher_def->iv_size; 1.2082 + param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); 1.2083 + if (param == NULL) { 1.2084 + ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); 1.2085 + goto fail; 1.2086 + } 1.2087 + serverContext = PK11_CreateContextBySymKey(mechanism, 1.2088 + (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT), 1.2089 + pwSpec->server.write_key, param); 1.2090 + iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); 1.2091 + if (iv.data) 1.2092 + PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); 1.2093 + SECITEM_FreeItem(param, PR_TRUE); 1.2094 + if (serverContext == NULL) { 1.2095 + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 1.2096 + goto fail; 1.2097 + } 1.2098 + 1.2099 + /* 1.2100 + * build the client context 1.2101 + */ 1.2102 + iv.data = pwSpec->client.write_iv; 1.2103 + iv.len = cipher_def->iv_size; 1.2104 + 1.2105 + param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); 1.2106 + if (param == NULL) { 1.2107 + ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); 1.2108 + goto fail; 1.2109 + } 1.2110 + clientContext = PK11_CreateContextBySymKey(mechanism, 1.2111 + (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT), 1.2112 + pwSpec->client.write_key, param); 1.2113 + iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); 1.2114 + if (iv.data) 1.2115 + PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); 1.2116 + SECITEM_FreeItem(param,PR_TRUE); 1.2117 + if (clientContext == NULL) { 1.2118 + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); 1.2119 + goto fail; 1.2120 + } 1.2121 + pwSpec->encode = (SSLCipher) PK11_CipherOp; 1.2122 + pwSpec->decode = (SSLCipher) PK11_CipherOp; 1.2123 + pwSpec->destroy = (SSLDestroy) PK11_DestroyContext; 1.2124 + 1.2125 + pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; 1.2126 + pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; 1.2127 + 1.2128 + serverContext = NULL; 1.2129 + clientContext = NULL; 1.2130 + 1.2131 + ssl3_InitCompressionContext(pwSpec); 1.2132 + 1.2133 + return SECSuccess; 1.2134 + 1.2135 +fail: 1.2136 + if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE); 1.2137 + if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE); 1.2138 + if (pwSpec->client.write_mac_context != NULL) { 1.2139 + PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE); 1.2140 + pwSpec->client.write_mac_context = NULL; 1.2141 + } 1.2142 + if (pwSpec->server.write_mac_context != NULL) { 1.2143 + PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE); 1.2144 + pwSpec->server.write_mac_context = NULL; 1.2145 + } 1.2146 + 1.2147 + return SECFailure; 1.2148 +} 1.2149 + 1.2150 +/* Complete the initialization of all keys, ciphers, MACs and their contexts 1.2151 + * for the pending Cipher Spec. 1.2152 + * Called from: ssl3_SendClientKeyExchange (for Full handshake) 1.2153 + * ssl3_HandleRSAClientKeyExchange (for Full handshake) 1.2154 + * ssl3_HandleServerHello (for session restart) 1.2155 + * ssl3_HandleClientHello (for session restart) 1.2156 + * Sets error code, but caller probably should override to disambiguate. 1.2157 + * NULL pms means re-use old master_secret. 1.2158 + * 1.2159 + * This code is common to the bypass and PKCS11 execution paths. 1.2160 + * For the bypass case, pms is NULL. 1.2161 + */ 1.2162 +SECStatus 1.2163 +ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms) 1.2164 +{ 1.2165 + ssl3CipherSpec * pwSpec; 1.2166 + ssl3CipherSpec * cwSpec; 1.2167 + SECStatus rv; 1.2168 + 1.2169 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.2170 + 1.2171 + ssl_GetSpecWriteLock(ss); /**************************************/ 1.2172 + 1.2173 + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 1.2174 + 1.2175 + pwSpec = ss->ssl3.pwSpec; 1.2176 + cwSpec = ss->ssl3.cwSpec; 1.2177 + 1.2178 + if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) { 1.2179 + rv = ssl3_DeriveMasterSecret(ss, pms); 1.2180 + if (rv != SECSuccess) { 1.2181 + goto done; /* err code set by ssl3_DeriveMasterSecret */ 1.2182 + } 1.2183 + } 1.2184 +#ifndef NO_PKCS11_BYPASS 1.2185 + if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) { 1.2186 + /* Double Bypass succeeded in extracting the master_secret */ 1.2187 + const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; 1.2188 + PRBool isTLS = (PRBool)(kea_def->tls_keygen || 1.2189 + (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); 1.2190 + pwSpec->bypassCiphers = PR_TRUE; 1.2191 + rv = ssl3_KeyAndMacDeriveBypass( pwSpec, 1.2192 + (const unsigned char *)&ss->ssl3.hs.client_random, 1.2193 + (const unsigned char *)&ss->ssl3.hs.server_random, 1.2194 + isTLS, 1.2195 + (PRBool)(kea_def->is_limited)); 1.2196 + if (rv == SECSuccess) { 1.2197 + rv = ssl3_InitPendingContextsBypass(ss); 1.2198 + } 1.2199 + } else 1.2200 +#endif 1.2201 + if (pwSpec->master_secret) { 1.2202 + rv = ssl3_DeriveConnectionKeysPKCS11(ss); 1.2203 + if (rv == SECSuccess) { 1.2204 + rv = ssl3_InitPendingContextsPKCS11(ss); 1.2205 + } 1.2206 + } else { 1.2207 + PORT_Assert(pwSpec->master_secret); 1.2208 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.2209 + rv = SECFailure; 1.2210 + } 1.2211 + if (rv != SECSuccess) { 1.2212 + goto done; 1.2213 + } 1.2214 + 1.2215 + /* Generic behaviors -- common to all crypto methods */ 1.2216 + if (!IS_DTLS(ss)) { 1.2217 + pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; 1.2218 + } else { 1.2219 + if (cwSpec->epoch == PR_UINT16_MAX) { 1.2220 + /* The problem here is that we have rehandshaked too many 1.2221 + * times (you are not allowed to wrap the epoch). The 1.2222 + * spec says you should be discarding the connection 1.2223 + * and start over, so not much we can do here. */ 1.2224 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.2225 + rv = SECFailure; 1.2226 + goto done; 1.2227 + } 1.2228 + /* The sequence number has the high 16 bits as the epoch. */ 1.2229 + pwSpec->epoch = cwSpec->epoch + 1; 1.2230 + pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 1.2231 + pwSpec->epoch << 16; 1.2232 + 1.2233 + dtls_InitRecvdRecords(&pwSpec->recvdRecords); 1.2234 + } 1.2235 + pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0; 1.2236 + 1.2237 +done: 1.2238 + ssl_ReleaseSpecWriteLock(ss); /******************************/ 1.2239 + if (rv != SECSuccess) 1.2240 + ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 1.2241 + return rv; 1.2242 +} 1.2243 + 1.2244 +/* 1.2245 + * 60 bytes is 3 times the maximum length MAC size that is supported. 1.2246 + */ 1.2247 +static const unsigned char mac_pad_1 [60] = { 1.2248 + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 1.2249 + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 1.2250 + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 1.2251 + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 1.2252 + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 1.2253 + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 1.2254 + 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 1.2255 + 0x36, 0x36, 0x36, 0x36 1.2256 +}; 1.2257 +static const unsigned char mac_pad_2 [60] = { 1.2258 + 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 1.2259 + 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 1.2260 + 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 1.2261 + 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 1.2262 + 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 1.2263 + 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 1.2264 + 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 1.2265 + 0x5c, 0x5c, 0x5c, 0x5c 1.2266 +}; 1.2267 + 1.2268 +/* Called from: ssl3_SendRecord() 1.2269 +** Caller must already hold the SpecReadLock. (wish we could assert that!) 1.2270 +*/ 1.2271 +static SECStatus 1.2272 +ssl3_ComputeRecordMAC( 1.2273 + ssl3CipherSpec * spec, 1.2274 + PRBool useServerMacKey, 1.2275 + const unsigned char *header, 1.2276 + unsigned int headerLen, 1.2277 + const SSL3Opaque * input, 1.2278 + int inputLength, 1.2279 + unsigned char * outbuf, 1.2280 + unsigned int * outLength) 1.2281 +{ 1.2282 + const ssl3MACDef * mac_def; 1.2283 + SECStatus rv; 1.2284 + 1.2285 + PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); 1.2286 + PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); 1.2287 + 1.2288 + mac_def = spec->mac_def; 1.2289 + if (mac_def->mac == mac_null) { 1.2290 + *outLength = 0; 1.2291 + return SECSuccess; 1.2292 + } 1.2293 +#ifndef NO_PKCS11_BYPASS 1.2294 + if (spec->bypassCiphers) { 1.2295 + /* bypass version */ 1.2296 + const SECHashObject *hashObj = NULL; 1.2297 + unsigned int pad_bytes = 0; 1.2298 + PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; 1.2299 + 1.2300 + switch (mac_def->mac) { 1.2301 + case ssl_mac_null: 1.2302 + *outLength = 0; 1.2303 + return SECSuccess; 1.2304 + case ssl_mac_md5: 1.2305 + pad_bytes = 48; 1.2306 + hashObj = HASH_GetRawHashObject(HASH_AlgMD5); 1.2307 + break; 1.2308 + case ssl_mac_sha: 1.2309 + pad_bytes = 40; 1.2310 + hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); 1.2311 + break; 1.2312 + case ssl_hmac_md5: /* used with TLS */ 1.2313 + hashObj = HASH_GetRawHashObject(HASH_AlgMD5); 1.2314 + break; 1.2315 + case ssl_hmac_sha: /* used with TLS */ 1.2316 + hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); 1.2317 + break; 1.2318 + case ssl_hmac_sha256: /* used with TLS */ 1.2319 + hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); 1.2320 + break; 1.2321 + default: 1.2322 + break; 1.2323 + } 1.2324 + if (!hashObj) { 1.2325 + PORT_Assert(0); 1.2326 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.2327 + return SECFailure; 1.2328 + } 1.2329 + 1.2330 + if (spec->version <= SSL_LIBRARY_VERSION_3_0) { 1.2331 + unsigned int tempLen; 1.2332 + unsigned char temp[MAX_MAC_LENGTH]; 1.2333 + 1.2334 + /* compute "inner" part of SSL3 MAC */ 1.2335 + hashObj->begin(write_mac_context); 1.2336 + if (useServerMacKey) 1.2337 + hashObj->update(write_mac_context, 1.2338 + spec->server.write_mac_key_item.data, 1.2339 + spec->server.write_mac_key_item.len); 1.2340 + else 1.2341 + hashObj->update(write_mac_context, 1.2342 + spec->client.write_mac_key_item.data, 1.2343 + spec->client.write_mac_key_item.len); 1.2344 + hashObj->update(write_mac_context, mac_pad_1, pad_bytes); 1.2345 + hashObj->update(write_mac_context, header, headerLen); 1.2346 + hashObj->update(write_mac_context, input, inputLength); 1.2347 + hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); 1.2348 + 1.2349 + /* compute "outer" part of SSL3 MAC */ 1.2350 + hashObj->begin(write_mac_context); 1.2351 + if (useServerMacKey) 1.2352 + hashObj->update(write_mac_context, 1.2353 + spec->server.write_mac_key_item.data, 1.2354 + spec->server.write_mac_key_item.len); 1.2355 + else 1.2356 + hashObj->update(write_mac_context, 1.2357 + spec->client.write_mac_key_item.data, 1.2358 + spec->client.write_mac_key_item.len); 1.2359 + hashObj->update(write_mac_context, mac_pad_2, pad_bytes); 1.2360 + hashObj->update(write_mac_context, temp, tempLen); 1.2361 + hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); 1.2362 + rv = SECSuccess; 1.2363 + } else { /* is TLS */ 1.2364 +#define cx ((HMACContext *)write_mac_context) 1.2365 + if (useServerMacKey) { 1.2366 + rv = HMAC_Init(cx, hashObj, 1.2367 + spec->server.write_mac_key_item.data, 1.2368 + spec->server.write_mac_key_item.len, PR_FALSE); 1.2369 + } else { 1.2370 + rv = HMAC_Init(cx, hashObj, 1.2371 + spec->client.write_mac_key_item.data, 1.2372 + spec->client.write_mac_key_item.len, PR_FALSE); 1.2373 + } 1.2374 + if (rv == SECSuccess) { 1.2375 + HMAC_Begin(cx); 1.2376 + HMAC_Update(cx, header, headerLen); 1.2377 + HMAC_Update(cx, input, inputLength); 1.2378 + rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); 1.2379 + HMAC_Destroy(cx, PR_FALSE); 1.2380 + } 1.2381 +#undef cx 1.2382 + } 1.2383 + } else 1.2384 +#endif 1.2385 + { 1.2386 + PK11Context *mac_context = 1.2387 + (useServerMacKey ? spec->server.write_mac_context 1.2388 + : spec->client.write_mac_context); 1.2389 + rv = PK11_DigestBegin(mac_context); 1.2390 + rv |= PK11_DigestOp(mac_context, header, headerLen); 1.2391 + rv |= PK11_DigestOp(mac_context, input, inputLength); 1.2392 + rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); 1.2393 + } 1.2394 + 1.2395 + PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size); 1.2396 + 1.2397 + PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength)); 1.2398 + 1.2399 + if (rv != SECSuccess) { 1.2400 + rv = SECFailure; 1.2401 + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 1.2402 + } 1.2403 + return rv; 1.2404 +} 1.2405 + 1.2406 +/* Called from: ssl3_HandleRecord() 1.2407 + * Caller must already hold the SpecReadLock. (wish we could assert that!) 1.2408 + * 1.2409 + * On entry: 1.2410 + * originalLen >= inputLen >= MAC size 1.2411 +*/ 1.2412 +static SECStatus 1.2413 +ssl3_ComputeRecordMACConstantTime( 1.2414 + ssl3CipherSpec * spec, 1.2415 + PRBool useServerMacKey, 1.2416 + const unsigned char *header, 1.2417 + unsigned int headerLen, 1.2418 + const SSL3Opaque * input, 1.2419 + int inputLen, 1.2420 + int originalLen, 1.2421 + unsigned char * outbuf, 1.2422 + unsigned int * outLen) 1.2423 +{ 1.2424 + CK_MECHANISM_TYPE macType; 1.2425 + CK_NSS_MAC_CONSTANT_TIME_PARAMS params; 1.2426 + SECItem param, inputItem, outputItem; 1.2427 + SECStatus rv; 1.2428 + PK11SymKey * key; 1.2429 + 1.2430 + PORT_Assert(inputLen >= spec->mac_size); 1.2431 + PORT_Assert(originalLen >= inputLen); 1.2432 + 1.2433 + if (spec->bypassCiphers) { 1.2434 + /* This function doesn't support PKCS#11 bypass. We fallback on the 1.2435 + * non-constant time version. */ 1.2436 + goto fallback; 1.2437 + } 1.2438 + 1.2439 + if (spec->mac_def->mac == mac_null) { 1.2440 + *outLen = 0; 1.2441 + return SECSuccess; 1.2442 + } 1.2443 + 1.2444 + macType = CKM_NSS_HMAC_CONSTANT_TIME; 1.2445 + if (spec->version <= SSL_LIBRARY_VERSION_3_0) { 1.2446 + macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; 1.2447 + } 1.2448 + 1.2449 + params.macAlg = spec->mac_def->mmech; 1.2450 + params.ulBodyTotalLen = originalLen; 1.2451 + params.pHeader = (unsigned char *) header; /* const cast */ 1.2452 + params.ulHeaderLen = headerLen; 1.2453 + 1.2454 + param.data = (unsigned char*) ¶ms; 1.2455 + param.len = sizeof(params); 1.2456 + param.type = 0; 1.2457 + 1.2458 + inputItem.data = (unsigned char *) input; 1.2459 + inputItem.len = inputLen; 1.2460 + inputItem.type = 0; 1.2461 + 1.2462 + outputItem.data = outbuf; 1.2463 + outputItem.len = *outLen; 1.2464 + outputItem.type = 0; 1.2465 + 1.2466 + key = spec->server.write_mac_key; 1.2467 + if (!useServerMacKey) { 1.2468 + key = spec->client.write_mac_key; 1.2469 + } 1.2470 + 1.2471 + rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem); 1.2472 + if (rv != SECSuccess) { 1.2473 + if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { 1.2474 + goto fallback; 1.2475 + } 1.2476 + 1.2477 + *outLen = 0; 1.2478 + rv = SECFailure; 1.2479 + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 1.2480 + return rv; 1.2481 + } 1.2482 + 1.2483 + PORT_Assert(outputItem.len == (unsigned)spec->mac_size); 1.2484 + *outLen = outputItem.len; 1.2485 + 1.2486 + return rv; 1.2487 + 1.2488 +fallback: 1.2489 + /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the 1.2490 + * length already. */ 1.2491 + inputLen -= spec->mac_size; 1.2492 + return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen, 1.2493 + input, inputLen, outbuf, outLen); 1.2494 +} 1.2495 + 1.2496 +static PRBool 1.2497 +ssl3_ClientAuthTokenPresent(sslSessionID *sid) { 1.2498 + PK11SlotInfo *slot = NULL; 1.2499 + PRBool isPresent = PR_TRUE; 1.2500 + 1.2501 + /* we only care if we are doing client auth */ 1.2502 + if (!sid || !sid->u.ssl3.clAuthValid) { 1.2503 + return PR_TRUE; 1.2504 + } 1.2505 + 1.2506 + /* get the slot */ 1.2507 + slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, 1.2508 + sid->u.ssl3.clAuthSlotID); 1.2509 + if (slot == NULL || 1.2510 + !PK11_IsPresent(slot) || 1.2511 + sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) || 1.2512 + sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) || 1.2513 + sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) || 1.2514 + (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) { 1.2515 + isPresent = PR_FALSE; 1.2516 + } 1.2517 + if (slot) { 1.2518 + PK11_FreeSlot(slot); 1.2519 + } 1.2520 + return isPresent; 1.2521 +} 1.2522 + 1.2523 +/* Caller must hold the spec read lock. */ 1.2524 +SECStatus 1.2525 +ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, 1.2526 + PRBool isServer, 1.2527 + PRBool isDTLS, 1.2528 + PRBool capRecordVersion, 1.2529 + SSL3ContentType type, 1.2530 + const SSL3Opaque * pIn, 1.2531 + PRUint32 contentLen, 1.2532 + sslBuffer * wrBuf) 1.2533 +{ 1.2534 + const ssl3BulkCipherDef * cipher_def; 1.2535 + SECStatus rv; 1.2536 + PRUint32 macLen = 0; 1.2537 + PRUint32 fragLen; 1.2538 + PRUint32 p1Len, p2Len, oddLen = 0; 1.2539 + PRUint16 headerLen; 1.2540 + int ivLen = 0; 1.2541 + int cipherBytes = 0; 1.2542 + unsigned char pseudoHeader[13]; 1.2543 + unsigned int pseudoHeaderLen; 1.2544 + 1.2545 + cipher_def = cwSpec->cipher_def; 1.2546 + headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; 1.2547 + 1.2548 + if (cipher_def->type == type_block && 1.2549 + cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 1.2550 + /* Prepend the per-record explicit IV using technique 2b from 1.2551 + * RFC 4346 section 6.2.3.2: The IV is a cryptographically 1.2552 + * strong random number XORed with the CBC residue from the previous 1.2553 + * record. 1.2554 + */ 1.2555 + ivLen = cipher_def->iv_size; 1.2556 + if (ivLen > wrBuf->space - headerLen) { 1.2557 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.2558 + return SECFailure; 1.2559 + } 1.2560 + rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); 1.2561 + if (rv != SECSuccess) { 1.2562 + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 1.2563 + return rv; 1.2564 + } 1.2565 + rv = cwSpec->encode( cwSpec->encodeContext, 1.2566 + wrBuf->buf + headerLen, 1.2567 + &cipherBytes, /* output and actual outLen */ 1.2568 + ivLen, /* max outlen */ 1.2569 + wrBuf->buf + headerLen, 1.2570 + ivLen); /* input and inputLen*/ 1.2571 + if (rv != SECSuccess || cipherBytes != ivLen) { 1.2572 + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 1.2573 + return SECFailure; 1.2574 + } 1.2575 + } 1.2576 + 1.2577 + if (cwSpec->compressor) { 1.2578 + int outlen; 1.2579 + rv = cwSpec->compressor( 1.2580 + cwSpec->compressContext, 1.2581 + wrBuf->buf + headerLen + ivLen, &outlen, 1.2582 + wrBuf->space - headerLen - ivLen, pIn, contentLen); 1.2583 + if (rv != SECSuccess) 1.2584 + return rv; 1.2585 + pIn = wrBuf->buf + headerLen + ivLen; 1.2586 + contentLen = outlen; 1.2587 + } 1.2588 + 1.2589 + pseudoHeaderLen = ssl3_BuildRecordPseudoHeader( 1.2590 + pseudoHeader, cwSpec->write_seq_num, type, 1.2591 + cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, 1.2592 + isDTLS, contentLen); 1.2593 + PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader)); 1.2594 + if (cipher_def->type == type_aead) { 1.2595 + const int nonceLen = cipher_def->explicit_nonce_size; 1.2596 + const int tagLen = cipher_def->tag_size; 1.2597 + 1.2598 + if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { 1.2599 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.2600 + return SECFailure; 1.2601 + } 1.2602 + 1.2603 + cipherBytes = contentLen; 1.2604 + rv = cwSpec->aead( 1.2605 + isServer ? &cwSpec->server : &cwSpec->client, 1.2606 + PR_FALSE, /* do encrypt */ 1.2607 + wrBuf->buf + headerLen, /* output */ 1.2608 + &cipherBytes, /* out len */ 1.2609 + wrBuf->space - headerLen, /* max out */ 1.2610 + pIn, contentLen, /* input */ 1.2611 + pseudoHeader, pseudoHeaderLen); 1.2612 + if (rv != SECSuccess) { 1.2613 + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 1.2614 + return SECFailure; 1.2615 + } 1.2616 + } else { 1.2617 + /* 1.2618 + * Add the MAC 1.2619 + */ 1.2620 + rv = ssl3_ComputeRecordMAC(cwSpec, isServer, 1.2621 + pseudoHeader, pseudoHeaderLen, pIn, contentLen, 1.2622 + wrBuf->buf + headerLen + ivLen + contentLen, &macLen); 1.2623 + if (rv != SECSuccess) { 1.2624 + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); 1.2625 + return SECFailure; 1.2626 + } 1.2627 + p1Len = contentLen; 1.2628 + p2Len = macLen; 1.2629 + fragLen = contentLen + macLen; /* needs to be encrypted */ 1.2630 + PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024); 1.2631 + 1.2632 + /* 1.2633 + * Pad the text (if we're doing a block cipher) 1.2634 + * then Encrypt it 1.2635 + */ 1.2636 + if (cipher_def->type == type_block) { 1.2637 + unsigned char * pBuf; 1.2638 + int padding_length; 1.2639 + int i; 1.2640 + 1.2641 + oddLen = contentLen % cipher_def->block_size; 1.2642 + /* Assume blockSize is a power of two */ 1.2643 + padding_length = cipher_def->block_size - 1 - 1.2644 + ((fragLen) & (cipher_def->block_size - 1)); 1.2645 + fragLen += padding_length + 1; 1.2646 + PORT_Assert((fragLen % cipher_def->block_size) == 0); 1.2647 + 1.2648 + /* Pad according to TLS rules (also acceptable to SSL3). */ 1.2649 + pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1]; 1.2650 + for (i = padding_length + 1; i > 0; --i) { 1.2651 + *pBuf-- = padding_length; 1.2652 + } 1.2653 + /* now, if contentLen is not a multiple of block size, fix it */ 1.2654 + p2Len = fragLen - p1Len; 1.2655 + } 1.2656 + if (p1Len < 256) { 1.2657 + oddLen = p1Len; 1.2658 + p1Len = 0; 1.2659 + } else { 1.2660 + p1Len -= oddLen; 1.2661 + } 1.2662 + if (oddLen) { 1.2663 + p2Len += oddLen; 1.2664 + PORT_Assert( (cipher_def->block_size < 2) || \ 1.2665 + (p2Len % cipher_def->block_size) == 0); 1.2666 + memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, 1.2667 + oddLen); 1.2668 + } 1.2669 + if (p1Len > 0) { 1.2670 + int cipherBytesPart1 = -1; 1.2671 + rv = cwSpec->encode( cwSpec->encodeContext, 1.2672 + wrBuf->buf + headerLen + ivLen, /* output */ 1.2673 + &cipherBytesPart1, /* actual outlen */ 1.2674 + p1Len, /* max outlen */ 1.2675 + pIn, p1Len); /* input, and inputlen */ 1.2676 + PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); 1.2677 + if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { 1.2678 + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 1.2679 + return SECFailure; 1.2680 + } 1.2681 + cipherBytes += cipherBytesPart1; 1.2682 + } 1.2683 + if (p2Len > 0) { 1.2684 + int cipherBytesPart2 = -1; 1.2685 + rv = cwSpec->encode( cwSpec->encodeContext, 1.2686 + wrBuf->buf + headerLen + ivLen + p1Len, 1.2687 + &cipherBytesPart2, /* output and actual outLen */ 1.2688 + p2Len, /* max outlen */ 1.2689 + wrBuf->buf + headerLen + ivLen + p1Len, 1.2690 + p2Len); /* input and inputLen*/ 1.2691 + PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); 1.2692 + if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { 1.2693 + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); 1.2694 + return SECFailure; 1.2695 + } 1.2696 + cipherBytes += cipherBytesPart2; 1.2697 + } 1.2698 + } 1.2699 + 1.2700 + PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); 1.2701 + 1.2702 + wrBuf->len = cipherBytes + headerLen; 1.2703 + wrBuf->buf[0] = type; 1.2704 + if (isDTLS) { 1.2705 + SSL3ProtocolVersion version; 1.2706 + 1.2707 + version = dtls_TLSVersionToDTLSVersion(cwSpec->version); 1.2708 + wrBuf->buf[1] = MSB(version); 1.2709 + wrBuf->buf[2] = LSB(version); 1.2710 + wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); 1.2711 + wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); 1.2712 + wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); 1.2713 + wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); 1.2714 + wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); 1.2715 + wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); 1.2716 + wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); 1.2717 + wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); 1.2718 + wrBuf->buf[11] = MSB(cipherBytes); 1.2719 + wrBuf->buf[12] = LSB(cipherBytes); 1.2720 + } else { 1.2721 + SSL3ProtocolVersion version = cwSpec->version; 1.2722 + 1.2723 + if (capRecordVersion) { 1.2724 + version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); 1.2725 + } 1.2726 + wrBuf->buf[1] = MSB(version); 1.2727 + wrBuf->buf[2] = LSB(version); 1.2728 + wrBuf->buf[3] = MSB(cipherBytes); 1.2729 + wrBuf->buf[4] = LSB(cipherBytes); 1.2730 + } 1.2731 + 1.2732 + ssl3_BumpSequenceNumber(&cwSpec->write_seq_num); 1.2733 + 1.2734 + return SECSuccess; 1.2735 +} 1.2736 + 1.2737 +/* Process the plain text before sending it. 1.2738 + * Returns the number of bytes of plaintext that were successfully sent 1.2739 + * plus the number of bytes of plaintext that were copied into the 1.2740 + * output (write) buffer. 1.2741 + * Returns SECFailure on a hard IO error, memory error, or crypto error. 1.2742 + * Does NOT return SECWouldBlock. 1.2743 + * 1.2744 + * Notes on the use of the private ssl flags: 1.2745 + * (no private SSL flags) 1.2746 + * Attempt to make and send SSL records for all plaintext 1.2747 + * If non-blocking and a send gets WOULD_BLOCK, 1.2748 + * or if the pending (ciphertext) buffer is not empty, 1.2749 + * then buffer remaining bytes of ciphertext into pending buf, 1.2750 + * and continue to do that for all succssive records until all 1.2751 + * bytes are used. 1.2752 + * ssl_SEND_FLAG_FORCE_INTO_BUFFER 1.2753 + * As above, except this suppresses all write attempts, and forces 1.2754 + * all ciphertext into the pending ciphertext buffer. 1.2755 + * ssl_SEND_FLAG_USE_EPOCH (for DTLS) 1.2756 + * Forces the use of the provided epoch 1.2757 + * ssl_SEND_FLAG_CAP_RECORD_VERSION 1.2758 + * Caps the record layer version number of TLS ClientHello to { 3, 1 } 1.2759 + * (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore 1.2760 + * ClientHello.client_version and use the record layer version number 1.2761 + * (TLSPlaintext.version) instead when negotiating protocol versions. In 1.2762 + * addition, if the record layer version number of ClientHello is { 3, 2 } 1.2763 + * (TLS 1.1) or higher, these servers reset the TCP connections. Lastly, 1.2764 + * some F5 BIG-IP servers hang if a record containing a ClientHello has a 1.2765 + * version greater than { 3, 1 } and a length greater than 255. Set this 1.2766 + * flag to work around such servers. 1.2767 + */ 1.2768 +PRInt32 1.2769 +ssl3_SendRecord( sslSocket * ss, 1.2770 + DTLSEpoch epoch, /* DTLS only */ 1.2771 + SSL3ContentType type, 1.2772 + const SSL3Opaque * pIn, /* input buffer */ 1.2773 + PRInt32 nIn, /* bytes of input */ 1.2774 + PRInt32 flags) 1.2775 +{ 1.2776 + sslBuffer * wrBuf = &ss->sec.writeBuf; 1.2777 + SECStatus rv; 1.2778 + PRInt32 totalSent = 0; 1.2779 + PRBool capRecordVersion; 1.2780 + 1.2781 + SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", 1.2782 + SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), 1.2783 + nIn)); 1.2784 + PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); 1.2785 + 1.2786 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 1.2787 + 1.2788 + capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0); 1.2789 + 1.2790 + if (capRecordVersion) { 1.2791 + /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the 1.2792 + * TLS initial ClientHello. */ 1.2793 + PORT_Assert(!IS_DTLS(ss)); 1.2794 + PORT_Assert(!ss->firstHsDone); 1.2795 + PORT_Assert(type == content_handshake); 1.2796 + PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); 1.2797 + } 1.2798 + 1.2799 + if (ss->ssl3.initialized == PR_FALSE) { 1.2800 + /* This can happen on a server if the very first incoming record 1.2801 + ** looks like a defective ssl3 record (e.g. too long), and we're 1.2802 + ** trying to send an alert. 1.2803 + */ 1.2804 + PR_ASSERT(type == content_alert); 1.2805 + rv = ssl3_InitState(ss); 1.2806 + if (rv != SECSuccess) { 1.2807 + return SECFailure; /* ssl3_InitState has set the error code. */ 1.2808 + } 1.2809 + } 1.2810 + 1.2811 + /* check for Token Presence */ 1.2812 + if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { 1.2813 + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 1.2814 + return SECFailure; 1.2815 + } 1.2816 + 1.2817 + while (nIn > 0) { 1.2818 + PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); 1.2819 + unsigned int spaceNeeded; 1.2820 + unsigned int numRecords; 1.2821 + 1.2822 + ssl_GetSpecReadLock(ss); /********************************/ 1.2823 + 1.2824 + if (nIn > 1 && ss->opt.cbcRandomIV && 1.2825 + ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && 1.2826 + type == content_application_data && 1.2827 + ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { 1.2828 + /* We will split the first byte of the record into its own record, 1.2829 + * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h 1.2830 + */ 1.2831 + numRecords = 2; 1.2832 + } else { 1.2833 + numRecords = 1; 1.2834 + } 1.2835 + 1.2836 + spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); 1.2837 + if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && 1.2838 + ss->ssl3.cwSpec->cipher_def->type == type_block) { 1.2839 + spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; 1.2840 + } 1.2841 + if (spaceNeeded > wrBuf->space) { 1.2842 + rv = sslBuffer_Grow(wrBuf, spaceNeeded); 1.2843 + if (rv != SECSuccess) { 1.2844 + SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", 1.2845 + SSL_GETPID(), ss->fd, spaceNeeded)); 1.2846 + goto spec_locked_loser; /* sslBuffer_Grow set error code. */ 1.2847 + } 1.2848 + } 1.2849 + 1.2850 + if (numRecords == 2) { 1.2851 + sslBuffer secondRecord; 1.2852 + 1.2853 + rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, 1.2854 + ss->sec.isServer, IS_DTLS(ss), 1.2855 + capRecordVersion, type, pIn, 1.2856 + 1, wrBuf); 1.2857 + if (rv != SECSuccess) 1.2858 + goto spec_locked_loser; 1.2859 + 1.2860 + PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", 1.2861 + wrBuf->buf, wrBuf->len)); 1.2862 + 1.2863 + secondRecord.buf = wrBuf->buf + wrBuf->len; 1.2864 + secondRecord.len = 0; 1.2865 + secondRecord.space = wrBuf->space - wrBuf->len; 1.2866 + 1.2867 + rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, 1.2868 + ss->sec.isServer, IS_DTLS(ss), 1.2869 + capRecordVersion, type, 1.2870 + pIn + 1, contentLen - 1, 1.2871 + &secondRecord); 1.2872 + if (rv == SECSuccess) { 1.2873 + PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", 1.2874 + secondRecord.buf, secondRecord.len)); 1.2875 + wrBuf->len += secondRecord.len; 1.2876 + } 1.2877 + } else { 1.2878 + if (!IS_DTLS(ss)) { 1.2879 + rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, 1.2880 + ss->sec.isServer, 1.2881 + IS_DTLS(ss), 1.2882 + capRecordVersion, 1.2883 + type, pIn, 1.2884 + contentLen, wrBuf); 1.2885 + } else { 1.2886 + rv = dtls_CompressMACEncryptRecord(ss, epoch, 1.2887 + !!(flags & ssl_SEND_FLAG_USE_EPOCH), 1.2888 + type, pIn, 1.2889 + contentLen, wrBuf); 1.2890 + } 1.2891 + 1.2892 + if (rv == SECSuccess) { 1.2893 + PRINT_BUF(50, (ss, "send (encrypted) record data:", 1.2894 + wrBuf->buf, wrBuf->len)); 1.2895 + } 1.2896 + } 1.2897 + 1.2898 +spec_locked_loser: 1.2899 + ssl_ReleaseSpecReadLock(ss); /************************************/ 1.2900 + 1.2901 + if (rv != SECSuccess) 1.2902 + return SECFailure; 1.2903 + 1.2904 + pIn += contentLen; 1.2905 + nIn -= contentLen; 1.2906 + PORT_Assert( nIn >= 0 ); 1.2907 + 1.2908 + /* If there's still some previously saved ciphertext, 1.2909 + * or the caller doesn't want us to send the data yet, 1.2910 + * then add all our new ciphertext to the amount previously saved. 1.2911 + */ 1.2912 + if ((ss->pendingBuf.len > 0) || 1.2913 + (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { 1.2914 + 1.2915 + rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len); 1.2916 + if (rv != SECSuccess) { 1.2917 + /* presumably a memory error, SEC_ERROR_NO_MEMORY */ 1.2918 + return SECFailure; 1.2919 + } 1.2920 + wrBuf->len = 0; /* All cipher text is saved away. */ 1.2921 + 1.2922 + if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { 1.2923 + PRInt32 sent; 1.2924 + ss->handshakeBegun = 1; 1.2925 + sent = ssl_SendSavedWriteData(ss); 1.2926 + if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { 1.2927 + ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); 1.2928 + return SECFailure; 1.2929 + } 1.2930 + if (ss->pendingBuf.len) { 1.2931 + flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; 1.2932 + } 1.2933 + } 1.2934 + } else if (wrBuf->len > 0) { 1.2935 + PRInt32 sent; 1.2936 + ss->handshakeBegun = 1; 1.2937 + sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, 1.2938 + flags & ~ssl_SEND_FLAG_MASK); 1.2939 + if (sent < 0) { 1.2940 + if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { 1.2941 + ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); 1.2942 + return SECFailure; 1.2943 + } 1.2944 + /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ 1.2945 + sent = 0; 1.2946 + } 1.2947 + wrBuf->len -= sent; 1.2948 + if (wrBuf->len) { 1.2949 + if (IS_DTLS(ss)) { 1.2950 + /* DTLS just says no in this case. No buffering */ 1.2951 + PR_SetError(PR_WOULD_BLOCK_ERROR, 0); 1.2952 + return SECFailure; 1.2953 + } 1.2954 + /* now take all the remaining unsent new ciphertext and 1.2955 + * append it to the buffer of previously unsent ciphertext. 1.2956 + */ 1.2957 + rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); 1.2958 + if (rv != SECSuccess) { 1.2959 + /* presumably a memory error, SEC_ERROR_NO_MEMORY */ 1.2960 + return SECFailure; 1.2961 + } 1.2962 + } 1.2963 + } 1.2964 + totalSent += contentLen; 1.2965 + } 1.2966 + return totalSent; 1.2967 +} 1.2968 + 1.2969 +#define SSL3_PENDING_HIGH_WATER 1024 1.2970 + 1.2971 +/* Attempt to send the content of "in" in an SSL application_data record. 1.2972 + * Returns "len" or SECFailure, never SECWouldBlock, nor SECSuccess. 1.2973 + */ 1.2974 +int 1.2975 +ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, 1.2976 + PRInt32 len, PRInt32 flags) 1.2977 +{ 1.2978 + PRInt32 totalSent = 0; 1.2979 + PRInt32 discarded = 0; 1.2980 + 1.2981 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 1.2982 + /* These flags for internal use only */ 1.2983 + PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH | 1.2984 + ssl_SEND_FLAG_NO_RETRANSMIT))); 1.2985 + if (len < 0 || !in) { 1.2986 + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 1.2987 + return SECFailure; 1.2988 + } 1.2989 + 1.2990 + if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && 1.2991 + !ssl_SocketIsBlocking(ss)) { 1.2992 + PORT_Assert(!ssl_SocketIsBlocking(ss)); 1.2993 + PORT_SetError(PR_WOULD_BLOCK_ERROR); 1.2994 + return SECFailure; 1.2995 + } 1.2996 + 1.2997 + if (ss->appDataBuffered && len) { 1.2998 + PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered)); 1.2999 + if (in[0] != (unsigned char)(ss->appDataBuffered)) { 1.3000 + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 1.3001 + return SECFailure; 1.3002 + } 1.3003 + in++; 1.3004 + len--; 1.3005 + discarded = 1; 1.3006 + } 1.3007 + while (len > totalSent) { 1.3008 + PRInt32 sent, toSend; 1.3009 + 1.3010 + if (totalSent > 0) { 1.3011 + /* 1.3012 + * The thread yield is intended to give the reader thread a 1.3013 + * chance to get some cycles while the writer thread is in 1.3014 + * the middle of a large application data write. (See 1.3015 + * Bugzilla bug 127740, comment #1.) 1.3016 + */ 1.3017 + ssl_ReleaseXmitBufLock(ss); 1.3018 + PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */ 1.3019 + ssl_GetXmitBufLock(ss); 1.3020 + } 1.3021 + toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH); 1.3022 + /* 1.3023 + * Note that the 0 epoch is OK because flags will never require 1.3024 + * its use, as guaranteed by the PORT_Assert above. 1.3025 + */ 1.3026 + sent = ssl3_SendRecord(ss, 0, content_application_data, 1.3027 + in + totalSent, toSend, flags); 1.3028 + if (sent < 0) { 1.3029 + if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { 1.3030 + PORT_Assert(ss->lastWriteBlocked); 1.3031 + break; 1.3032 + } 1.3033 + return SECFailure; /* error code set by ssl3_SendRecord */ 1.3034 + } 1.3035 + totalSent += sent; 1.3036 + if (ss->pendingBuf.len) { 1.3037 + /* must be a non-blocking socket */ 1.3038 + PORT_Assert(!ssl_SocketIsBlocking(ss)); 1.3039 + PORT_Assert(ss->lastWriteBlocked); 1.3040 + break; 1.3041 + } 1.3042 + } 1.3043 + if (ss->pendingBuf.len) { 1.3044 + /* Must be non-blocking. */ 1.3045 + PORT_Assert(!ssl_SocketIsBlocking(ss)); 1.3046 + if (totalSent > 0) { 1.3047 + ss->appDataBuffered = 0x100 | in[totalSent - 1]; 1.3048 + } 1.3049 + 1.3050 + totalSent = totalSent + discarded - 1; 1.3051 + if (totalSent <= 0) { 1.3052 + PORT_SetError(PR_WOULD_BLOCK_ERROR); 1.3053 + totalSent = SECFailure; 1.3054 + } 1.3055 + return totalSent; 1.3056 + } 1.3057 + ss->appDataBuffered = 0; 1.3058 + return totalSent + discarded; 1.3059 +} 1.3060 + 1.3061 +/* Attempt to send buffered handshake messages. 1.3062 + * This function returns SECSuccess or SECFailure, never SECWouldBlock. 1.3063 + * Always set sendBuf.len to 0, even when returning SECFailure. 1.3064 + * 1.3065 + * Depending on whether we are doing DTLS or not, this either calls 1.3066 + * 1.3067 + * - ssl3_FlushHandshakeMessages if non-DTLS 1.3068 + * - dtls_FlushHandshakeMessages if DTLS 1.3069 + * 1.3070 + * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(), 1.3071 + * ssl3_AppendHandshake(), ssl3_SendClientHello(), 1.3072 + * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(), 1.3073 + * ssl3_SendFinished(), 1.3074 + */ 1.3075 +static SECStatus 1.3076 +ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) 1.3077 +{ 1.3078 + if (IS_DTLS(ss)) { 1.3079 + return dtls_FlushHandshakeMessages(ss, flags); 1.3080 + } else { 1.3081 + return ssl3_FlushHandshakeMessages(ss, flags); 1.3082 + } 1.3083 +} 1.3084 + 1.3085 +/* Attempt to send the content of sendBuf buffer in an SSL handshake record. 1.3086 + * This function returns SECSuccess or SECFailure, never SECWouldBlock. 1.3087 + * Always set sendBuf.len to 0, even when returning SECFailure. 1.3088 + * 1.3089 + * Called from ssl3_FlushHandshake 1.3090 + */ 1.3091 +static SECStatus 1.3092 +ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) 1.3093 +{ 1.3094 + static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER | 1.3095 + ssl_SEND_FLAG_CAP_RECORD_VERSION; 1.3096 + PRInt32 rv = SECSuccess; 1.3097 + 1.3098 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.3099 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 1.3100 + 1.3101 + if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len) 1.3102 + return rv; 1.3103 + 1.3104 + /* only these flags are allowed */ 1.3105 + PORT_Assert(!(flags & ~allowedFlags)); 1.3106 + if ((flags & ~allowedFlags) != 0) { 1.3107 + PORT_SetError(SEC_ERROR_INVALID_ARGS); 1.3108 + rv = SECFailure; 1.3109 + } else { 1.3110 + rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf, 1.3111 + ss->sec.ci.sendBuf.len, flags); 1.3112 + } 1.3113 + if (rv < 0) { 1.3114 + int err = PORT_GetError(); 1.3115 + PORT_Assert(err != PR_WOULD_BLOCK_ERROR); 1.3116 + if (err == PR_WOULD_BLOCK_ERROR) { 1.3117 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.3118 + } 1.3119 + } else if (rv < ss->sec.ci.sendBuf.len) { 1.3120 + /* short write should never happen */ 1.3121 + PORT_Assert(rv >= ss->sec.ci.sendBuf.len); 1.3122 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.3123 + rv = SECFailure; 1.3124 + } else { 1.3125 + rv = SECSuccess; 1.3126 + } 1.3127 + 1.3128 + /* Whether we succeeded or failed, toss the old handshake data. */ 1.3129 + ss->sec.ci.sendBuf.len = 0; 1.3130 + return rv; 1.3131 +} 1.3132 + 1.3133 +/* 1.3134 + * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when 1.3135 + * the remote client sends a negative response to our certificate request. 1.3136 + * Returns SECFailure if the application has required client auth. 1.3137 + * SECSuccess otherwise. 1.3138 + */ 1.3139 +static SECStatus 1.3140 +ssl3_HandleNoCertificate(sslSocket *ss) 1.3141 +{ 1.3142 + if (ss->sec.peerCert != NULL) { 1.3143 + if (ss->sec.peerKey != NULL) { 1.3144 + SECKEY_DestroyPublicKey(ss->sec.peerKey); 1.3145 + ss->sec.peerKey = NULL; 1.3146 + } 1.3147 + CERT_DestroyCertificate(ss->sec.peerCert); 1.3148 + ss->sec.peerCert = NULL; 1.3149 + } 1.3150 + ssl3_CleanupPeerCerts(ss); 1.3151 + 1.3152 + /* If the server has required client-auth blindly but doesn't 1.3153 + * actually look at the certificate it won't know that no 1.3154 + * certificate was presented so we shutdown the socket to ensure 1.3155 + * an error. We only do this if we haven't already completed the 1.3156 + * first handshake because if we're redoing the handshake we 1.3157 + * know the server is paying attention to the certificate. 1.3158 + */ 1.3159 + if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || 1.3160 + (!ss->firstHsDone && 1.3161 + (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { 1.3162 + PRFileDesc * lower; 1.3163 + 1.3164 + if (ss->sec.uncache) 1.3165 + ss->sec.uncache(ss->sec.ci.sid); 1.3166 + SSL3_SendAlert(ss, alert_fatal, bad_certificate); 1.3167 + 1.3168 + lower = ss->fd->lower; 1.3169 +#ifdef _WIN32 1.3170 + lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); 1.3171 +#else 1.3172 + lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); 1.3173 +#endif 1.3174 + PORT_SetError(SSL_ERROR_NO_CERTIFICATE); 1.3175 + return SECFailure; 1.3176 + } 1.3177 + return SECSuccess; 1.3178 +} 1.3179 + 1.3180 +/************************************************************************ 1.3181 + * Alerts 1.3182 + */ 1.3183 + 1.3184 +/* 1.3185 +** Acquires both handshake and XmitBuf locks. 1.3186 +** Called from: ssl3_IllegalParameter <- 1.3187 +** ssl3_HandshakeFailure <- 1.3188 +** ssl3_HandleAlert <- ssl3_HandleRecord. 1.3189 +** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord 1.3190 +** ssl3_ConsumeHandshakeVariable <- 1.3191 +** ssl3_HandleHelloRequest <- 1.3192 +** ssl3_HandleServerHello <- 1.3193 +** ssl3_HandleServerKeyExchange <- 1.3194 +** ssl3_HandleCertificateRequest <- 1.3195 +** ssl3_HandleServerHelloDone <- 1.3196 +** ssl3_HandleClientHello <- 1.3197 +** ssl3_HandleV2ClientHello <- 1.3198 +** ssl3_HandleCertificateVerify <- 1.3199 +** ssl3_HandleClientKeyExchange <- 1.3200 +** ssl3_HandleCertificate <- 1.3201 +** ssl3_HandleFinished <- 1.3202 +** ssl3_HandleHandshakeMessage <- 1.3203 +** ssl3_HandleRecord <- 1.3204 +** 1.3205 +*/ 1.3206 +SECStatus 1.3207 +SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) 1.3208 +{ 1.3209 + PRUint8 bytes[2]; 1.3210 + SECStatus rv; 1.3211 + 1.3212 + SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", 1.3213 + SSL_GETPID(), ss->fd, level, desc)); 1.3214 + 1.3215 + bytes[0] = level; 1.3216 + bytes[1] = desc; 1.3217 + 1.3218 + ssl_GetSSL3HandshakeLock(ss); 1.3219 + if (level == alert_fatal) { 1.3220 + if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { 1.3221 + ss->sec.uncache(ss->sec.ci.sid); 1.3222 + } 1.3223 + } 1.3224 + ssl_GetXmitBufLock(ss); 1.3225 + rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 1.3226 + if (rv == SECSuccess) { 1.3227 + PRInt32 sent; 1.3228 + sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, 1.3229 + desc == no_certificate 1.3230 + ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); 1.3231 + rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; 1.3232 + } 1.3233 + ssl_ReleaseXmitBufLock(ss); 1.3234 + ssl_ReleaseSSL3HandshakeLock(ss); 1.3235 + return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ 1.3236 +} 1.3237 + 1.3238 +/* 1.3239 + * Send illegal_parameter alert. Set generic error number. 1.3240 + */ 1.3241 +static SECStatus 1.3242 +ssl3_IllegalParameter(sslSocket *ss) 1.3243 +{ 1.3244 + (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); 1.3245 + PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 1.3246 + : SSL_ERROR_BAD_SERVER ); 1.3247 + return SECFailure; 1.3248 +} 1.3249 + 1.3250 +/* 1.3251 + * Send handshake_Failure alert. Set generic error number. 1.3252 + */ 1.3253 +static SECStatus 1.3254 +ssl3_HandshakeFailure(sslSocket *ss) 1.3255 +{ 1.3256 + (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); 1.3257 + PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 1.3258 + : SSL_ERROR_BAD_SERVER ); 1.3259 + return SECFailure; 1.3260 +} 1.3261 + 1.3262 +static void 1.3263 +ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode) 1.3264 +{ 1.3265 + SSL3AlertDescription desc = bad_certificate; 1.3266 + PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS; 1.3267 + 1.3268 + switch (errCode) { 1.3269 + case SEC_ERROR_LIBRARY_FAILURE: desc = unsupported_certificate; break; 1.3270 + case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired; break; 1.3271 + case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked; break; 1.3272 + case SEC_ERROR_INADEQUATE_KEY_USAGE: 1.3273 + case SEC_ERROR_INADEQUATE_CERT_TYPE: 1.3274 + desc = certificate_unknown; break; 1.3275 + case SEC_ERROR_UNTRUSTED_CERT: 1.3276 + desc = isTLS ? access_denied : certificate_unknown; break; 1.3277 + case SEC_ERROR_UNKNOWN_ISSUER: 1.3278 + case SEC_ERROR_UNTRUSTED_ISSUER: 1.3279 + desc = isTLS ? unknown_ca : certificate_unknown; break; 1.3280 + case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: 1.3281 + desc = isTLS ? unknown_ca : certificate_expired; break; 1.3282 + 1.3283 + case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: 1.3284 + case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID: 1.3285 + case SEC_ERROR_CA_CERT_INVALID: 1.3286 + case SEC_ERROR_BAD_SIGNATURE: 1.3287 + default: desc = bad_certificate; break; 1.3288 + } 1.3289 + SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d", 1.3290 + SSL_GETPID(), ss->fd, errCode)); 1.3291 + 1.3292 + (void) SSL3_SendAlert(ss, alert_fatal, desc); 1.3293 +} 1.3294 + 1.3295 + 1.3296 +/* 1.3297 + * Send decode_error alert. Set generic error number. 1.3298 + */ 1.3299 +SECStatus 1.3300 +ssl3_DecodeError(sslSocket *ss) 1.3301 +{ 1.3302 + (void)SSL3_SendAlert(ss, alert_fatal, 1.3303 + ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error 1.3304 + : illegal_parameter); 1.3305 + PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT 1.3306 + : SSL_ERROR_BAD_SERVER ); 1.3307 + return SECFailure; 1.3308 +} 1.3309 + 1.3310 +/* Called from ssl3_HandleRecord. 1.3311 +** Caller must hold both RecvBuf and Handshake locks. 1.3312 +*/ 1.3313 +static SECStatus 1.3314 +ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) 1.3315 +{ 1.3316 + SSL3AlertLevel level; 1.3317 + SSL3AlertDescription desc; 1.3318 + int error; 1.3319 + 1.3320 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.3321 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.3322 + 1.3323 + SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd)); 1.3324 + 1.3325 + if (buf->len != 2) { 1.3326 + (void)ssl3_DecodeError(ss); 1.3327 + PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); 1.3328 + return SECFailure; 1.3329 + } 1.3330 + level = (SSL3AlertLevel)buf->buf[0]; 1.3331 + desc = (SSL3AlertDescription)buf->buf[1]; 1.3332 + buf->len = 0; 1.3333 + SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d", 1.3334 + SSL_GETPID(), ss->fd, level, desc)); 1.3335 + 1.3336 + switch (desc) { 1.3337 + case close_notify: ss->recvdCloseNotify = 1; 1.3338 + error = SSL_ERROR_CLOSE_NOTIFY_ALERT; break; 1.3339 + case unexpected_message: error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT; 1.3340 + break; 1.3341 + case bad_record_mac: error = SSL_ERROR_BAD_MAC_ALERT; break; 1.3342 + case decryption_failed_RESERVED: 1.3343 + error = SSL_ERROR_DECRYPTION_FAILED_ALERT; 1.3344 + break; 1.3345 + case record_overflow: error = SSL_ERROR_RECORD_OVERFLOW_ALERT; break; 1.3346 + case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT; 1.3347 + break; 1.3348 + case handshake_failure: error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT; 1.3349 + break; 1.3350 + case no_certificate: error = SSL_ERROR_NO_CERTIFICATE; break; 1.3351 + case bad_certificate: error = SSL_ERROR_BAD_CERT_ALERT; break; 1.3352 + case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break; 1.3353 + case certificate_revoked: error = SSL_ERROR_REVOKED_CERT_ALERT; break; 1.3354 + case certificate_expired: error = SSL_ERROR_EXPIRED_CERT_ALERT; break; 1.3355 + case certificate_unknown: error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT; 1.3356 + break; 1.3357 + case illegal_parameter: error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break; 1.3358 + case inappropriate_fallback: 1.3359 + error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; 1.3360 + break; 1.3361 + 1.3362 + /* All alerts below are TLS only. */ 1.3363 + case unknown_ca: error = SSL_ERROR_UNKNOWN_CA_ALERT; break; 1.3364 + case access_denied: error = SSL_ERROR_ACCESS_DENIED_ALERT; break; 1.3365 + case decode_error: error = SSL_ERROR_DECODE_ERROR_ALERT; break; 1.3366 + case decrypt_error: error = SSL_ERROR_DECRYPT_ERROR_ALERT; break; 1.3367 + case export_restriction: error = SSL_ERROR_EXPORT_RESTRICTION_ALERT; 1.3368 + break; 1.3369 + case protocol_version: error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break; 1.3370 + case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT; 1.3371 + break; 1.3372 + case internal_error: error = SSL_ERROR_INTERNAL_ERROR_ALERT; break; 1.3373 + case user_canceled: error = SSL_ERROR_USER_CANCELED_ALERT; break; 1.3374 + case no_renegotiation: error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break; 1.3375 + 1.3376 + /* Alerts for TLS client hello extensions */ 1.3377 + case unsupported_extension: 1.3378 + error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT; break; 1.3379 + case certificate_unobtainable: 1.3380 + error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break; 1.3381 + case unrecognized_name: 1.3382 + error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; break; 1.3383 + case bad_certificate_status_response: 1.3384 + error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break; 1.3385 + case bad_certificate_hash_value: 1.3386 + error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT; break; 1.3387 + default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break; 1.3388 + } 1.3389 + if (level == alert_fatal) { 1.3390 + if (!ss->opt.noCache) { 1.3391 + if (ss->sec.uncache) 1.3392 + ss->sec.uncache(ss->sec.ci.sid); 1.3393 + } 1.3394 + if ((ss->ssl3.hs.ws == wait_server_hello) && 1.3395 + (desc == handshake_failure)) { 1.3396 + /* XXX This is a hack. We're assuming that any handshake failure 1.3397 + * XXX on the client hello is a failure to match ciphers. 1.3398 + */ 1.3399 + error = SSL_ERROR_NO_CYPHER_OVERLAP; 1.3400 + } 1.3401 + PORT_SetError(error); 1.3402 + return SECFailure; 1.3403 + } 1.3404 + if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) { 1.3405 + /* I'm a server. I've requested a client cert. He hasn't got one. */ 1.3406 + SECStatus rv; 1.3407 + 1.3408 + PORT_Assert(ss->sec.isServer); 1.3409 + ss->ssl3.hs.ws = wait_client_key; 1.3410 + rv = ssl3_HandleNoCertificate(ss); 1.3411 + return rv; 1.3412 + } 1.3413 + return SECSuccess; 1.3414 +} 1.3415 + 1.3416 +/* 1.3417 + * Change Cipher Specs 1.3418 + * Called from ssl3_HandleServerHelloDone, 1.3419 + * ssl3_HandleClientHello, 1.3420 + * and ssl3_HandleFinished 1.3421 + * 1.3422 + * Acquires and releases spec write lock, to protect switching the current 1.3423 + * and pending write spec pointers. 1.3424 + */ 1.3425 + 1.3426 +static SECStatus 1.3427 +ssl3_SendChangeCipherSpecs(sslSocket *ss) 1.3428 +{ 1.3429 + PRUint8 change = change_cipher_spec_choice; 1.3430 + ssl3CipherSpec * pwSpec; 1.3431 + SECStatus rv; 1.3432 + PRInt32 sent; 1.3433 + 1.3434 + SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", 1.3435 + SSL_GETPID(), ss->fd)); 1.3436 + 1.3437 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 1.3438 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.3439 + 1.3440 + rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 1.3441 + if (rv != SECSuccess) { 1.3442 + return rv; /* error code set by ssl3_FlushHandshake */ 1.3443 + } 1.3444 + if (!IS_DTLS(ss)) { 1.3445 + sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, 1.3446 + ssl_SEND_FLAG_FORCE_INTO_BUFFER); 1.3447 + if (sent < 0) { 1.3448 + return (SECStatus)sent; /* error code set by ssl3_SendRecord */ 1.3449 + } 1.3450 + } else { 1.3451 + rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); 1.3452 + if (rv != SECSuccess) { 1.3453 + return rv; 1.3454 + } 1.3455 + } 1.3456 + 1.3457 + /* swap the pending and current write specs. */ 1.3458 + ssl_GetSpecWriteLock(ss); /**************************************/ 1.3459 + pwSpec = ss->ssl3.pwSpec; 1.3460 + 1.3461 + ss->ssl3.pwSpec = ss->ssl3.cwSpec; 1.3462 + ss->ssl3.cwSpec = pwSpec; 1.3463 + 1.3464 + SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", 1.3465 + SSL_GETPID(), ss->fd )); 1.3466 + 1.3467 + /* We need to free up the contexts, keys and certs ! */ 1.3468 + /* If we are really through with the old cipher spec 1.3469 + * (Both the read and write sides have changed) destroy it. 1.3470 + */ 1.3471 + if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { 1.3472 + if (!IS_DTLS(ss)) { 1.3473 + ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/); 1.3474 + } else { 1.3475 + /* With DTLS, we need to set a holddown timer in case the final 1.3476 + * message got lost */ 1.3477 + ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; 1.3478 + dtls_StartTimer(ss, dtls_FinishedTimerCb); 1.3479 + } 1.3480 + } 1.3481 + ssl_ReleaseSpecWriteLock(ss); /**************************************/ 1.3482 + 1.3483 + return SECSuccess; 1.3484 +} 1.3485 + 1.3486 +/* Called from ssl3_HandleRecord. 1.3487 +** Caller must hold both RecvBuf and Handshake locks. 1.3488 + * 1.3489 + * Acquires and releases spec write lock, to protect switching the current 1.3490 + * and pending write spec pointers. 1.3491 +*/ 1.3492 +static SECStatus 1.3493 +ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) 1.3494 +{ 1.3495 + ssl3CipherSpec * prSpec; 1.3496 + SSL3WaitState ws = ss->ssl3.hs.ws; 1.3497 + SSL3ChangeCipherSpecChoice change; 1.3498 + 1.3499 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.3500 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.3501 + 1.3502 + SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record", 1.3503 + SSL_GETPID(), ss->fd)); 1.3504 + 1.3505 + if (ws != wait_change_cipher) { 1.3506 + if (IS_DTLS(ss)) { 1.3507 + /* Ignore this because it's out of order. */ 1.3508 + SSL_TRC(3, ("%d: SSL3[%d]: discard out of order " 1.3509 + "DTLS change_cipher_spec", 1.3510 + SSL_GETPID(), ss->fd)); 1.3511 + buf->len = 0; 1.3512 + return SECSuccess; 1.3513 + } 1.3514 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.3515 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); 1.3516 + return SECFailure; 1.3517 + } 1.3518 + 1.3519 + if(buf->len != 1) { 1.3520 + (void)ssl3_DecodeError(ss); 1.3521 + PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); 1.3522 + return SECFailure; 1.3523 + } 1.3524 + change = (SSL3ChangeCipherSpecChoice)buf->buf[0]; 1.3525 + if (change != change_cipher_spec_choice) { 1.3526 + /* illegal_parameter is correct here for both SSL3 and TLS. */ 1.3527 + (void)ssl3_IllegalParameter(ss); 1.3528 + PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER); 1.3529 + return SECFailure; 1.3530 + } 1.3531 + buf->len = 0; 1.3532 + 1.3533 + /* Swap the pending and current read specs. */ 1.3534 + ssl_GetSpecWriteLock(ss); /*************************************/ 1.3535 + prSpec = ss->ssl3.prSpec; 1.3536 + 1.3537 + ss->ssl3.prSpec = ss->ssl3.crSpec; 1.3538 + ss->ssl3.crSpec = prSpec; 1.3539 + ss->ssl3.hs.ws = wait_finished; 1.3540 + 1.3541 + SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", 1.3542 + SSL_GETPID(), ss->fd )); 1.3543 + 1.3544 + /* If we are really through with the old cipher prSpec 1.3545 + * (Both the read and write sides have changed) destroy it. 1.3546 + */ 1.3547 + if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { 1.3548 + ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/); 1.3549 + } 1.3550 + ssl_ReleaseSpecWriteLock(ss); /*************************************/ 1.3551 + return SECSuccess; 1.3552 +} 1.3553 + 1.3554 +/* This method uses PKCS11 to derive the MS from the PMS, where PMS 1.3555 +** is a PKCS11 symkey. This is used in all cases except the 1.3556 +** "triple bypass" with RSA key exchange. 1.3557 +** Called from ssl3_InitPendingCipherSpec. prSpec is pwSpec. 1.3558 +*/ 1.3559 +static SECStatus 1.3560 +ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) 1.3561 +{ 1.3562 + ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; 1.3563 + const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def; 1.3564 + unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; 1.3565 + unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; 1.3566 + PRBool isTLS = (PRBool)(kea_def->tls_keygen || 1.3567 + (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); 1.3568 + PRBool isTLS12= 1.3569 + (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 1.3570 + /* 1.3571 + * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH 1.3572 + * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size 1.3573 + * data into a 48-byte value. 1.3574 + */ 1.3575 + PRBool isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) || 1.3576 + (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); 1.3577 + SECStatus rv = SECFailure; 1.3578 + CK_MECHANISM_TYPE master_derive; 1.3579 + CK_MECHANISM_TYPE key_derive; 1.3580 + SECItem params; 1.3581 + CK_FLAGS keyFlags; 1.3582 + CK_VERSION pms_version; 1.3583 + CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params; 1.3584 + 1.3585 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.3586 + PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 1.3587 + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 1.3588 + if (isTLS12) { 1.3589 + if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256; 1.3590 + else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256; 1.3591 + key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256; 1.3592 + keyFlags = CKF_SIGN | CKF_VERIFY; 1.3593 + } else if (isTLS) { 1.3594 + if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH; 1.3595 + else master_derive = CKM_TLS_MASTER_KEY_DERIVE; 1.3596 + key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 1.3597 + keyFlags = CKF_SIGN | CKF_VERIFY; 1.3598 + } else { 1.3599 + if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH; 1.3600 + else master_derive = CKM_SSL3_MASTER_KEY_DERIVE; 1.3601 + key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; 1.3602 + keyFlags = 0; 1.3603 + } 1.3604 + 1.3605 + if (pms || !pwSpec->master_secret) { 1.3606 + if (isDH) { 1.3607 + master_params.pVersion = NULL; 1.3608 + } else { 1.3609 + master_params.pVersion = &pms_version; 1.3610 + } 1.3611 + master_params.RandomInfo.pClientRandom = cr; 1.3612 + master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; 1.3613 + master_params.RandomInfo.pServerRandom = sr; 1.3614 + master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; 1.3615 + 1.3616 + params.data = (unsigned char *) &master_params; 1.3617 + params.len = sizeof master_params; 1.3618 + } 1.3619 + 1.3620 + if (pms != NULL) { 1.3621 +#if defined(TRACE) 1.3622 + if (ssl_trace >= 100) { 1.3623 + SECStatus extractRV = PK11_ExtractKeyValue(pms); 1.3624 + if (extractRV == SECSuccess) { 1.3625 + SECItem * keyData = PK11_GetKeyData(pms); 1.3626 + if (keyData && keyData->data && keyData->len) { 1.3627 + ssl_PrintBuf(ss, "Pre-Master Secret", 1.3628 + keyData->data, keyData->len); 1.3629 + } 1.3630 + } 1.3631 + } 1.3632 +#endif 1.3633 + pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive, 1.3634 + ¶ms, key_derive, CKA_DERIVE, 0, keyFlags); 1.3635 + if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) { 1.3636 + SSL3ProtocolVersion client_version; 1.3637 + client_version = pms_version.major << 8 | pms_version.minor; 1.3638 + 1.3639 + if (IS_DTLS(ss)) { 1.3640 + client_version = dtls_DTLSVersionToTLSVersion(client_version); 1.3641 + } 1.3642 + 1.3643 + if (client_version != ss->clientHelloVersion) { 1.3644 + /* Destroy it. Version roll-back detected. */ 1.3645 + PK11_FreeSymKey(pwSpec->master_secret); 1.3646 + pwSpec->master_secret = NULL; 1.3647 + } 1.3648 + } 1.3649 + if (pwSpec->master_secret == NULL) { 1.3650 + /* Generate a faux master secret in the same slot as the old one. */ 1.3651 + PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms); 1.3652 + PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot); 1.3653 + 1.3654 + PK11_FreeSlot(slot); 1.3655 + if (fpms != NULL) { 1.3656 + pwSpec->master_secret = PK11_DeriveWithFlags(fpms, 1.3657 + master_derive, ¶ms, key_derive, 1.3658 + CKA_DERIVE, 0, keyFlags); 1.3659 + PK11_FreeSymKey(fpms); 1.3660 + } 1.3661 + } 1.3662 + } 1.3663 + if (pwSpec->master_secret == NULL) { 1.3664 + /* Generate a faux master secret from the internal slot. */ 1.3665 + PK11SlotInfo * slot = PK11_GetInternalSlot(); 1.3666 + PK11SymKey * fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot); 1.3667 + 1.3668 + PK11_FreeSlot(slot); 1.3669 + if (fpms != NULL) { 1.3670 + pwSpec->master_secret = PK11_DeriveWithFlags(fpms, 1.3671 + master_derive, ¶ms, key_derive, 1.3672 + CKA_DERIVE, 0, keyFlags); 1.3673 + if (pwSpec->master_secret == NULL) { 1.3674 + pwSpec->master_secret = fpms; /* use the fpms as the master. */ 1.3675 + fpms = NULL; 1.3676 + } 1.3677 + } 1.3678 + if (fpms) { 1.3679 + PK11_FreeSymKey(fpms); 1.3680 + } 1.3681 + } 1.3682 + if (pwSpec->master_secret == NULL) { 1.3683 + ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 1.3684 + return rv; 1.3685 + } 1.3686 +#ifndef NO_PKCS11_BYPASS 1.3687 + if (ss->opt.bypassPKCS11) { 1.3688 + SECItem * keydata; 1.3689 + /* In hope of doing a "double bypass", 1.3690 + * need to extract the master secret's value from the key object 1.3691 + * and store it raw in the sslSocket struct. 1.3692 + */ 1.3693 + rv = PK11_ExtractKeyValue(pwSpec->master_secret); 1.3694 + if (rv != SECSuccess) { 1.3695 + return rv; 1.3696 + } 1.3697 + /* This returns the address of the secItem inside the key struct, 1.3698 + * not a copy or a reference. So, there's no need to free it. 1.3699 + */ 1.3700 + keydata = PK11_GetKeyData(pwSpec->master_secret); 1.3701 + if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { 1.3702 + memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); 1.3703 + pwSpec->msItem.data = pwSpec->raw_master_secret; 1.3704 + pwSpec->msItem.len = keydata->len; 1.3705 + } else { 1.3706 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.3707 + return SECFailure; 1.3708 + } 1.3709 + } 1.3710 +#endif 1.3711 + return SECSuccess; 1.3712 +} 1.3713 + 1.3714 + 1.3715 +/* 1.3716 + * Derive encryption and MAC Keys (and IVs) from master secret 1.3717 + * Sets a useful error code when returning SECFailure. 1.3718 + * 1.3719 + * Called only from ssl3_InitPendingCipherSpec(), 1.3720 + * which in turn is called from 1.3721 + * sendRSAClientKeyExchange (for Full handshake) 1.3722 + * sendDHClientKeyExchange (for Full handshake) 1.3723 + * ssl3_HandleClientKeyExchange (for Full handshake) 1.3724 + * ssl3_HandleServerHello (for session restart) 1.3725 + * ssl3_HandleClientHello (for session restart) 1.3726 + * Caller MUST hold the specWriteLock, and SSL3HandshakeLock. 1.3727 + * ssl3_InitPendingCipherSpec does that. 1.3728 + * 1.3729 + */ 1.3730 +static SECStatus 1.3731 +ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) 1.3732 +{ 1.3733 + ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; 1.3734 + const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; 1.3735 + unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; 1.3736 + unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; 1.3737 + PRBool isTLS = (PRBool)(kea_def->tls_keygen || 1.3738 + (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); 1.3739 + PRBool isTLS12= 1.3740 + (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 1.3741 + /* following variables used in PKCS11 path */ 1.3742 + const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; 1.3743 + PK11SlotInfo * slot = NULL; 1.3744 + PK11SymKey * symKey = NULL; 1.3745 + void * pwArg = ss->pkcs11PinArg; 1.3746 + int keySize; 1.3747 + CK_SSL3_KEY_MAT_PARAMS key_material_params; 1.3748 + CK_SSL3_KEY_MAT_OUT returnedKeys; 1.3749 + CK_MECHANISM_TYPE key_derive; 1.3750 + CK_MECHANISM_TYPE bulk_mechanism; 1.3751 + SSLCipherAlgorithm calg; 1.3752 + SECItem params; 1.3753 + PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null); 1.3754 + 1.3755 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.3756 + PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 1.3757 + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 1.3758 + 1.3759 + if (!pwSpec->master_secret) { 1.3760 + PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 1.3761 + return SECFailure; 1.3762 + } 1.3763 + /* 1.3764 + * generate the key material 1.3765 + */ 1.3766 + key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; 1.3767 + key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB; 1.3768 + key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; 1.3769 + if (cipher_def->type == type_block && 1.3770 + pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 1.3771 + /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ 1.3772 + key_material_params.ulIVSizeInBits = 0; 1.3773 + memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); 1.3774 + memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); 1.3775 + } 1.3776 + 1.3777 + key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); 1.3778 + 1.3779 + key_material_params.RandomInfo.pClientRandom = cr; 1.3780 + key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; 1.3781 + key_material_params.RandomInfo.pServerRandom = sr; 1.3782 + key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; 1.3783 + key_material_params.pReturnedKeyMaterial = &returnedKeys; 1.3784 + 1.3785 + returnedKeys.pIVClient = pwSpec->client.write_iv; 1.3786 + returnedKeys.pIVServer = pwSpec->server.write_iv; 1.3787 + keySize = cipher_def->key_size; 1.3788 + 1.3789 + if (skipKeysAndIVs) { 1.3790 + keySize = 0; 1.3791 + key_material_params.ulKeySizeInBits = 0; 1.3792 + key_material_params.ulIVSizeInBits = 0; 1.3793 + returnedKeys.pIVClient = NULL; 1.3794 + returnedKeys.pIVServer = NULL; 1.3795 + } 1.3796 + 1.3797 + calg = cipher_def->calg; 1.3798 + PORT_Assert( alg2Mech[calg].calg == calg); 1.3799 + bulk_mechanism = alg2Mech[calg].cmech; 1.3800 + 1.3801 + params.data = (unsigned char *)&key_material_params; 1.3802 + params.len = sizeof(key_material_params); 1.3803 + 1.3804 + if (isTLS12) { 1.3805 + key_derive = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256; 1.3806 + } else if (isTLS) { 1.3807 + key_derive = CKM_TLS_KEY_AND_MAC_DERIVE; 1.3808 + } else { 1.3809 + key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE; 1.3810 + } 1.3811 + 1.3812 + /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and 1.3813 + * DERIVE by DEFAULT */ 1.3814 + symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms, 1.3815 + bulk_mechanism, CKA_ENCRYPT, keySize); 1.3816 + if (!symKey) { 1.3817 + ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 1.3818 + return SECFailure; 1.3819 + } 1.3820 + /* we really should use the actual mac'ing mechanism here, but we 1.3821 + * don't because these types are used to map keytype anyway and both 1.3822 + * mac's map to the same keytype. 1.3823 + */ 1.3824 + slot = PK11_GetSlotFromKey(symKey); 1.3825 + 1.3826 + PK11_FreeSlot(slot); /* slot is held until the key is freed */ 1.3827 + pwSpec->client.write_mac_key = 1.3828 + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 1.3829 + CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); 1.3830 + if (pwSpec->client.write_mac_key == NULL ) { 1.3831 + goto loser; /* loser sets err */ 1.3832 + } 1.3833 + pwSpec->server.write_mac_key = 1.3834 + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 1.3835 + CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); 1.3836 + if (pwSpec->server.write_mac_key == NULL ) { 1.3837 + goto loser; /* loser sets err */ 1.3838 + } 1.3839 + if (!skipKeysAndIVs) { 1.3840 + pwSpec->client.write_key = 1.3841 + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 1.3842 + bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); 1.3843 + if (pwSpec->client.write_key == NULL ) { 1.3844 + goto loser; /* loser sets err */ 1.3845 + } 1.3846 + pwSpec->server.write_key = 1.3847 + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, 1.3848 + bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); 1.3849 + if (pwSpec->server.write_key == NULL ) { 1.3850 + goto loser; /* loser sets err */ 1.3851 + } 1.3852 + } 1.3853 + PK11_FreeSymKey(symKey); 1.3854 + return SECSuccess; 1.3855 + 1.3856 + 1.3857 +loser: 1.3858 + if (symKey) PK11_FreeSymKey(symKey); 1.3859 + ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); 1.3860 + return SECFailure; 1.3861 +} 1.3862 + 1.3863 +/* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in 1.3864 + * buffered messages in ss->ssl3.hs.messages. */ 1.3865 +static SECStatus 1.3866 +ssl3_InitHandshakeHashes(sslSocket *ss) 1.3867 +{ 1.3868 + SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); 1.3869 + 1.3870 + PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); 1.3871 +#ifndef NO_PKCS11_BYPASS 1.3872 + if (ss->opt.bypassPKCS11) { 1.3873 + PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); 1.3874 + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 1.3875 + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 1.3876 + * then this will need to be updated. */ 1.3877 + ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); 1.3878 + if (!ss->ssl3.hs.sha_obj) { 1.3879 + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1.3880 + return SECFailure; 1.3881 + } 1.3882 + ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; 1.3883 + ss->ssl3.hs.hashType = handshake_hash_single; 1.3884 + ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); 1.3885 + } else { 1.3886 + ss->ssl3.hs.hashType = handshake_hash_combo; 1.3887 + MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); 1.3888 + SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); 1.3889 + } 1.3890 + } else 1.3891 +#endif 1.3892 + { 1.3893 + PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha); 1.3894 + /* 1.3895 + * note: We should probably lookup an SSL3 slot for these 1.3896 + * handshake hashes in hopes that we wind up with the same slots 1.3897 + * that the master secret will wind up in ... 1.3898 + */ 1.3899 + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 1.3900 + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 1.3901 + * then this will need to be updated. */ 1.3902 + ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); 1.3903 + if (ss->ssl3.hs.sha == NULL) { 1.3904 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.3905 + return SECFailure; 1.3906 + } 1.3907 + ss->ssl3.hs.hashType = handshake_hash_single; 1.3908 + 1.3909 + if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { 1.3910 + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1.3911 + return SECFailure; 1.3912 + } 1.3913 + 1.3914 + /* Create a backup SHA-1 hash for a potential client auth 1.3915 + * signature. 1.3916 + * 1.3917 + * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the 1.3918 + * handshake hash function (SHA-256). If the server or the client 1.3919 + * does not support SHA-256 as a signature hash, we can either 1.3920 + * maintain a backup SHA-1 handshake hash or buffer all handshake 1.3921 + * messages. 1.3922 + */ 1.3923 + if (!ss->sec.isServer) { 1.3924 + ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); 1.3925 + if (ss->ssl3.hs.backupHash == NULL) { 1.3926 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.3927 + return SECFailure; 1.3928 + } 1.3929 + 1.3930 + if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { 1.3931 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.3932 + return SECFailure; 1.3933 + } 1.3934 + } 1.3935 + } else { 1.3936 + /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or 1.3937 + * created successfully. */ 1.3938 + ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5); 1.3939 + if (ss->ssl3.hs.md5 == NULL) { 1.3940 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.3941 + return SECFailure; 1.3942 + } 1.3943 + ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1); 1.3944 + if (ss->ssl3.hs.sha == NULL) { 1.3945 + PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE); 1.3946 + ss->ssl3.hs.md5 = NULL; 1.3947 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.3948 + return SECFailure; 1.3949 + } 1.3950 + ss->ssl3.hs.hashType = handshake_hash_combo; 1.3951 + 1.3952 + if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) { 1.3953 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.3954 + return SECFailure; 1.3955 + } 1.3956 + if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) { 1.3957 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.3958 + return SECFailure; 1.3959 + } 1.3960 + } 1.3961 + } 1.3962 + 1.3963 + if (ss->ssl3.hs.messages.len > 0) { 1.3964 + if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, 1.3965 + ss->ssl3.hs.messages.len) != 1.3966 + SECSuccess) { 1.3967 + return SECFailure; 1.3968 + } 1.3969 + PORT_Free(ss->ssl3.hs.messages.buf); 1.3970 + ss->ssl3.hs.messages.buf = NULL; 1.3971 + ss->ssl3.hs.messages.len = 0; 1.3972 + ss->ssl3.hs.messages.space = 0; 1.3973 + } 1.3974 + 1.3975 + return SECSuccess; 1.3976 +} 1.3977 + 1.3978 +static SECStatus 1.3979 +ssl3_RestartHandshakeHashes(sslSocket *ss) 1.3980 +{ 1.3981 + SECStatus rv = SECSuccess; 1.3982 + 1.3983 + SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes", 1.3984 + SSL_GETPID(), ss->fd )); 1.3985 + ss->ssl3.hs.hashType = handshake_hash_unknown; 1.3986 + ss->ssl3.hs.messages.len = 0; 1.3987 +#ifndef NO_PKCS11_BYPASS 1.3988 + ss->ssl3.hs.sha_obj = NULL; 1.3989 + ss->ssl3.hs.sha_clone = NULL; 1.3990 +#endif 1.3991 + if (ss->ssl3.hs.md5) { 1.3992 + PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); 1.3993 + ss->ssl3.hs.md5 = NULL; 1.3994 + } 1.3995 + if (ss->ssl3.hs.sha) { 1.3996 + PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); 1.3997 + ss->ssl3.hs.sha = NULL; 1.3998 + } 1.3999 + return rv; 1.4000 +} 1.4001 + 1.4002 +/* 1.4003 + * Handshake messages 1.4004 + */ 1.4005 +/* Called from ssl3_InitHandshakeHashes() 1.4006 +** ssl3_AppendHandshake() 1.4007 +** ssl3_StartHandshakeHash() 1.4008 +** ssl3_HandleV2ClientHello() 1.4009 +** ssl3_HandleHandshakeMessage() 1.4010 +** Caller must hold the ssl3Handshake lock. 1.4011 +*/ 1.4012 +static SECStatus 1.4013 +ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, 1.4014 + unsigned int l) 1.4015 +{ 1.4016 + SECStatus rv = SECSuccess; 1.4017 + 1.4018 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.4019 + 1.4020 + /* We need to buffer the handshake messages until we have established 1.4021 + * which handshake hash function to use. */ 1.4022 + if (ss->ssl3.hs.hashType == handshake_hash_unknown) { 1.4023 + return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); 1.4024 + } 1.4025 + 1.4026 + PRINT_BUF(90, (NULL, "handshake hash input:", b, l)); 1.4027 + 1.4028 +#ifndef NO_PKCS11_BYPASS 1.4029 + if (ss->opt.bypassPKCS11) { 1.4030 + if (ss->ssl3.hs.hashType == handshake_hash_single) { 1.4031 + ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); 1.4032 + } else { 1.4033 + MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); 1.4034 + SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); 1.4035 + } 1.4036 + return rv; 1.4037 + } 1.4038 +#endif 1.4039 + if (ss->ssl3.hs.hashType == handshake_hash_single) { 1.4040 + rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); 1.4041 + if (rv != SECSuccess) { 1.4042 + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1.4043 + return rv; 1.4044 + } 1.4045 + if (ss->ssl3.hs.backupHash) { 1.4046 + rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); 1.4047 + if (rv != SECSuccess) { 1.4048 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.4049 + return rv; 1.4050 + } 1.4051 + } 1.4052 + } else { 1.4053 + rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l); 1.4054 + if (rv != SECSuccess) { 1.4055 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.4056 + return rv; 1.4057 + } 1.4058 + rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); 1.4059 + if (rv != SECSuccess) { 1.4060 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.4061 + return rv; 1.4062 + } 1.4063 + } 1.4064 + return rv; 1.4065 +} 1.4066 + 1.4067 +/************************************************************************** 1.4068 + * Append Handshake functions. 1.4069 + * All these functions set appropriate error codes. 1.4070 + * Most rely on ssl3_AppendHandshake to set the error code. 1.4071 + **************************************************************************/ 1.4072 +SECStatus 1.4073 +ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes) 1.4074 +{ 1.4075 + unsigned char * src = (unsigned char *)void_src; 1.4076 + int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; 1.4077 + SECStatus rv; 1.4078 + 1.4079 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */ 1.4080 + 1.4081 + if (!bytes) 1.4082 + return SECSuccess; 1.4083 + if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) { 1.4084 + rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH, 1.4085 + PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes))); 1.4086 + if (rv != SECSuccess) 1.4087 + return rv; /* sslBuffer_Grow has set a memory error code. */ 1.4088 + room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; 1.4089 + } 1.4090 + 1.4091 + PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes)); 1.4092 + rv = ssl3_UpdateHandshakeHashes(ss, src, bytes); 1.4093 + if (rv != SECSuccess) 1.4094 + return rv; /* error code set by ssl3_UpdateHandshakeHashes */ 1.4095 + 1.4096 + while (bytes > room) { 1.4097 + if (room > 0) 1.4098 + PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, 1.4099 + room); 1.4100 + ss->sec.ci.sendBuf.len += room; 1.4101 + rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); 1.4102 + if (rv != SECSuccess) { 1.4103 + return rv; /* error code set by ssl3_FlushHandshake */ 1.4104 + } 1.4105 + bytes -= room; 1.4106 + src += room; 1.4107 + room = ss->sec.ci.sendBuf.space; 1.4108 + PORT_Assert(ss->sec.ci.sendBuf.len == 0); 1.4109 + } 1.4110 + PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes); 1.4111 + ss->sec.ci.sendBuf.len += bytes; 1.4112 + return SECSuccess; 1.4113 +} 1.4114 + 1.4115 +SECStatus 1.4116 +ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) 1.4117 +{ 1.4118 + SECStatus rv; 1.4119 + PRUint8 b[4]; 1.4120 + PRUint8 * p = b; 1.4121 + 1.4122 + switch (lenSize) { 1.4123 + case 4: 1.4124 + *p++ = (num >> 24) & 0xff; 1.4125 + case 3: 1.4126 + *p++ = (num >> 16) & 0xff; 1.4127 + case 2: 1.4128 + *p++ = (num >> 8) & 0xff; 1.4129 + case 1: 1.4130 + *p = num & 0xff; 1.4131 + } 1.4132 + SSL_TRC(60, ("%d: number:", SSL_GETPID())); 1.4133 + rv = ssl3_AppendHandshake(ss, &b[0], lenSize); 1.4134 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4135 +} 1.4136 + 1.4137 +SECStatus 1.4138 +ssl3_AppendHandshakeVariable( 1.4139 + sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize) 1.4140 +{ 1.4141 + SECStatus rv; 1.4142 + 1.4143 + PORT_Assert((bytes < (1<<8) && lenSize == 1) || 1.4144 + (bytes < (1L<<16) && lenSize == 2) || 1.4145 + (bytes < (1L<<24) && lenSize == 3)); 1.4146 + 1.4147 + SSL_TRC(60,("%d: append variable:", SSL_GETPID())); 1.4148 + rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize); 1.4149 + if (rv != SECSuccess) { 1.4150 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4151 + } 1.4152 + SSL_TRC(60, ("data:")); 1.4153 + rv = ssl3_AppendHandshake(ss, src, bytes); 1.4154 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4155 +} 1.4156 + 1.4157 +SECStatus 1.4158 +ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length) 1.4159 +{ 1.4160 + SECStatus rv; 1.4161 + 1.4162 + /* If we already have a message in place, we need to enqueue it. 1.4163 + * This empties the buffer. This is a convenient place to call 1.4164 + * dtls_StageHandshakeMessage to mark the message boundary. 1.4165 + */ 1.4166 + if (IS_DTLS(ss)) { 1.4167 + rv = dtls_StageHandshakeMessage(ss); 1.4168 + if (rv != SECSuccess) { 1.4169 + return rv; 1.4170 + } 1.4171 + } 1.4172 + 1.4173 + SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s", 1.4174 + SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t))); 1.4175 + 1.4176 + rv = ssl3_AppendHandshakeNumber(ss, t, 1); 1.4177 + if (rv != SECSuccess) { 1.4178 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4179 + } 1.4180 + rv = ssl3_AppendHandshakeNumber(ss, length, 3); 1.4181 + if (rv != SECSuccess) { 1.4182 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4183 + } 1.4184 + 1.4185 + if (IS_DTLS(ss)) { 1.4186 + /* Note that we make an unfragmented message here. We fragment in the 1.4187 + * transmission code, if necessary */ 1.4188 + rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2); 1.4189 + if (rv != SECSuccess) { 1.4190 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4191 + } 1.4192 + ss->ssl3.hs.sendMessageSeq++; 1.4193 + 1.4194 + /* 0 is the fragment offset, because it's not fragmented yet */ 1.4195 + rv = ssl3_AppendHandshakeNumber(ss, 0, 3); 1.4196 + if (rv != SECSuccess) { 1.4197 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4198 + } 1.4199 + 1.4200 + /* Fragment length -- set to the packet length because not fragmented */ 1.4201 + rv = ssl3_AppendHandshakeNumber(ss, length, 3); 1.4202 + if (rv != SECSuccess) { 1.4203 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4204 + } 1.4205 + } 1.4206 + 1.4207 + return rv; /* error code set by AppendHandshake, if applicable. */ 1.4208 +} 1.4209 + 1.4210 +/* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of 1.4211 + * |sigAndHash| to the current handshake message. */ 1.4212 +SECStatus 1.4213 +ssl3_AppendSignatureAndHashAlgorithm( 1.4214 + sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash) 1.4215 +{ 1.4216 + unsigned char serialized[2]; 1.4217 + 1.4218 + serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg); 1.4219 + if (serialized[0] == 0) { 1.4220 + PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1.4221 + return SECFailure; 1.4222 + } 1.4223 + 1.4224 + serialized[1] = sigAndHash->sigAlg; 1.4225 + 1.4226 + return ssl3_AppendHandshake(ss, serialized, sizeof(serialized)); 1.4227 +} 1.4228 + 1.4229 +/************************************************************************** 1.4230 + * Consume Handshake functions. 1.4231 + * 1.4232 + * All data used in these functions is protected by two locks, 1.4233 + * the RecvBufLock and the SSL3HandshakeLock 1.4234 + **************************************************************************/ 1.4235 + 1.4236 +/* Read up the next "bytes" number of bytes from the (decrypted) input 1.4237 + * stream "b" (which is *length bytes long). Copy them into buffer "v". 1.4238 + * Reduces *length by bytes. Advances *b by bytes. 1.4239 + * 1.4240 + * If this function returns SECFailure, it has already sent an alert, 1.4241 + * and has set a generic error code. The caller should probably 1.4242 + * override the generic error code by setting another. 1.4243 + */ 1.4244 +SECStatus 1.4245 +ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, 1.4246 + PRUint32 *length) 1.4247 +{ 1.4248 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.4249 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.4250 + 1.4251 + if ((PRUint32)bytes > *length) { 1.4252 + return ssl3_DecodeError(ss); 1.4253 + } 1.4254 + PORT_Memcpy(v, *b, bytes); 1.4255 + PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); 1.4256 + *b += bytes; 1.4257 + *length -= bytes; 1.4258 + return SECSuccess; 1.4259 +} 1.4260 + 1.4261 +/* Read up the next "bytes" number of bytes from the (decrypted) input 1.4262 + * stream "b" (which is *length bytes long), and interpret them as an 1.4263 + * integer in network byte order. Returns the received value. 1.4264 + * Reduces *length by bytes. Advances *b by bytes. 1.4265 + * 1.4266 + * Returns SECFailure (-1) on failure. 1.4267 + * This value is indistinguishable from the equivalent received value. 1.4268 + * Only positive numbers are to be received this way. 1.4269 + * Thus, the largest value that may be sent this way is 0x7fffffff. 1.4270 + * On error, an alert has been sent, and a generic error code has been set. 1.4271 + */ 1.4272 +PRInt32 1.4273 +ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, 1.4274 + PRUint32 *length) 1.4275 +{ 1.4276 + PRUint8 *buf = *b; 1.4277 + int i; 1.4278 + PRInt32 num = 0; 1.4279 + 1.4280 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.4281 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.4282 + PORT_Assert( bytes <= sizeof num); 1.4283 + 1.4284 + if ((PRUint32)bytes > *length) { 1.4285 + return ssl3_DecodeError(ss); 1.4286 + } 1.4287 + PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); 1.4288 + 1.4289 + for (i = 0; i < bytes; i++) 1.4290 + num = (num << 8) + buf[i]; 1.4291 + *b += bytes; 1.4292 + *length -= bytes; 1.4293 + return num; 1.4294 +} 1.4295 + 1.4296 +/* Read in two values from the incoming decrypted byte stream "b", which is 1.4297 + * *length bytes long. The first value is a number whose size is "bytes" 1.4298 + * bytes long. The second value is a byte-string whose size is the value 1.4299 + * of the first number received. The latter byte-string, and its length, 1.4300 + * is returned in the SECItem i. 1.4301 + * 1.4302 + * Returns SECFailure (-1) on failure. 1.4303 + * On error, an alert has been sent, and a generic error code has been set. 1.4304 + * 1.4305 + * RADICAL CHANGE for NSS 3.11. All callers of this function make copies 1.4306 + * of the data returned in the SECItem *i, so making a copy of it here 1.4307 + * is simply wasteful. So, This function now just sets SECItem *i to 1.4308 + * point to the values in the buffer **b. 1.4309 + */ 1.4310 +SECStatus 1.4311 +ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes, 1.4312 + SSL3Opaque **b, PRUint32 *length) 1.4313 +{ 1.4314 + PRInt32 count; 1.4315 + 1.4316 + PORT_Assert(bytes <= 3); 1.4317 + i->len = 0; 1.4318 + i->data = NULL; 1.4319 + count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length); 1.4320 + if (count < 0) { /* Can't test for SECSuccess here. */ 1.4321 + return SECFailure; 1.4322 + } 1.4323 + if (count > 0) { 1.4324 + if ((PRUint32)count > *length) { 1.4325 + return ssl3_DecodeError(ss); 1.4326 + } 1.4327 + i->data = *b; 1.4328 + i->len = count; 1.4329 + *b += count; 1.4330 + *length -= count; 1.4331 + } 1.4332 + return SECSuccess; 1.4333 +} 1.4334 + 1.4335 +/* tlsHashOIDMap contains the mapping between TLS hash identifiers and the 1.4336 + * SECOidTag used internally by NSS. */ 1.4337 +static const struct { 1.4338 + int tlsHash; 1.4339 + SECOidTag oid; 1.4340 +} tlsHashOIDMap[] = { 1.4341 + { tls_hash_md5, SEC_OID_MD5 }, 1.4342 + { tls_hash_sha1, SEC_OID_SHA1 }, 1.4343 + { tls_hash_sha224, SEC_OID_SHA224 }, 1.4344 + { tls_hash_sha256, SEC_OID_SHA256 }, 1.4345 + { tls_hash_sha384, SEC_OID_SHA384 }, 1.4346 + { tls_hash_sha512, SEC_OID_SHA512 } 1.4347 +}; 1.4348 + 1.4349 +/* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value. 1.4350 + * If the hash is not recognised, SEC_OID_UNKNOWN is returned. 1.4351 + * 1.4352 + * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 1.4353 +SECOidTag 1.4354 +ssl3_TLSHashAlgorithmToOID(int hashFunc) 1.4355 +{ 1.4356 + unsigned int i; 1.4357 + 1.4358 + for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { 1.4359 + if (hashFunc == tlsHashOIDMap[i].tlsHash) { 1.4360 + return tlsHashOIDMap[i].oid; 1.4361 + } 1.4362 + } 1.4363 + return SEC_OID_UNKNOWN; 1.4364 +} 1.4365 + 1.4366 +/* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm 1.4367 + * identifier. If the hash is not recognised, zero is returned. 1.4368 + * 1.4369 + * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 1.4370 +static int 1.4371 +ssl3_OIDToTLSHashAlgorithm(SECOidTag oid) 1.4372 +{ 1.4373 + unsigned int i; 1.4374 + 1.4375 + for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { 1.4376 + if (oid == tlsHashOIDMap[i].oid) { 1.4377 + return tlsHashOIDMap[i].tlsHash; 1.4378 + } 1.4379 + } 1.4380 + return 0; 1.4381 +} 1.4382 + 1.4383 +/* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm 1.4384 + * identifier for a given KeyType. */ 1.4385 +static SECStatus 1.4386 +ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, 1.4387 + TLSSignatureAlgorithm *out) 1.4388 +{ 1.4389 + switch (keyType) { 1.4390 + case rsaKey: 1.4391 + *out = tls_sig_rsa; 1.4392 + return SECSuccess; 1.4393 + case dsaKey: 1.4394 + *out = tls_sig_dsa; 1.4395 + return SECSuccess; 1.4396 + case ecKey: 1.4397 + *out = tls_sig_ecdsa; 1.4398 + return SECSuccess; 1.4399 + default: 1.4400 + PORT_SetError(SEC_ERROR_INVALID_KEY); 1.4401 + return SECFailure; 1.4402 + } 1.4403 +} 1.4404 + 1.4405 +/* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature 1.4406 + * algorithm identifier for the given certificate. */ 1.4407 +static SECStatus 1.4408 +ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert, 1.4409 + TLSSignatureAlgorithm *out) 1.4410 +{ 1.4411 + SECKEYPublicKey *key; 1.4412 + KeyType keyType; 1.4413 + 1.4414 + key = CERT_ExtractPublicKey(cert); 1.4415 + if (key == NULL) { 1.4416 + ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 1.4417 + return SECFailure; 1.4418 + } 1.4419 + 1.4420 + keyType = key->keyType; 1.4421 + SECKEY_DestroyPublicKey(key); 1.4422 + return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out); 1.4423 +} 1.4424 + 1.4425 +/* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature 1.4426 + * algorithm identifier in |sigAndHash| is consistent with the public key in 1.4427 + * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called 1.4428 + * and SECFailure is returned. */ 1.4429 +SECStatus 1.4430 +ssl3_CheckSignatureAndHashAlgorithmConsistency( 1.4431 + const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert) 1.4432 +{ 1.4433 + SECStatus rv; 1.4434 + TLSSignatureAlgorithm sigAlg; 1.4435 + 1.4436 + rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg); 1.4437 + if (rv != SECSuccess) { 1.4438 + return rv; 1.4439 + } 1.4440 + if (sigAlg != sigAndHash->sigAlg) { 1.4441 + PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); 1.4442 + return SECFailure; 1.4443 + } 1.4444 + return SECSuccess; 1.4445 +} 1.4446 + 1.4447 +/* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm 1.4448 + * structure from |b| and puts the resulting value into |out|. |b| and |length| 1.4449 + * are updated accordingly. 1.4450 + * 1.4451 + * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 1.4452 +SECStatus 1.4453 +ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, 1.4454 + SSL3Opaque **b, 1.4455 + PRUint32 *length, 1.4456 + SSL3SignatureAndHashAlgorithm *out) 1.4457 +{ 1.4458 + unsigned char bytes[2]; 1.4459 + SECStatus rv; 1.4460 + 1.4461 + rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length); 1.4462 + if (rv != SECSuccess) { 1.4463 + return rv; 1.4464 + } 1.4465 + 1.4466 + out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]); 1.4467 + if (out->hashAlg == SEC_OID_UNKNOWN) { 1.4468 + PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1.4469 + return SECFailure; 1.4470 + } 1.4471 + 1.4472 + out->sigAlg = bytes[1]; 1.4473 + return SECSuccess; 1.4474 +} 1.4475 + 1.4476 +/************************************************************************** 1.4477 + * end of Consume Handshake functions. 1.4478 + **************************************************************************/ 1.4479 + 1.4480 +/* Extract the hashes of handshake messages to this point. 1.4481 + * Called from ssl3_SendCertificateVerify 1.4482 + * ssl3_SendFinished 1.4483 + * ssl3_HandleHandshakeMessage 1.4484 + * 1.4485 + * Caller must hold the SSL3HandshakeLock. 1.4486 + * Caller must hold a read or write lock on the Spec R/W lock. 1.4487 + * (There is presently no way to assert on a Read lock.) 1.4488 + */ 1.4489 +static SECStatus 1.4490 +ssl3_ComputeHandshakeHashes(sslSocket * ss, 1.4491 + ssl3CipherSpec *spec, /* uses ->master_secret */ 1.4492 + SSL3Hashes * hashes, /* output goes here. */ 1.4493 + PRUint32 sender) 1.4494 +{ 1.4495 + SECStatus rv = SECSuccess; 1.4496 + PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0); 1.4497 + unsigned int outLength; 1.4498 + SSL3Opaque md5_inner[MAX_MAC_LENGTH]; 1.4499 + SSL3Opaque sha_inner[MAX_MAC_LENGTH]; 1.4500 + 1.4501 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.4502 + hashes->hashAlg = SEC_OID_UNKNOWN; 1.4503 + 1.4504 +#ifndef NO_PKCS11_BYPASS 1.4505 + if (ss->opt.bypassPKCS11 && 1.4506 + ss->ssl3.hs.hashType == handshake_hash_single) { 1.4507 + /* compute them without PKCS11 */ 1.4508 + PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; 1.4509 + 1.4510 + if (!spec->msItem.data) { 1.4511 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 1.4512 + return SECFailure; 1.4513 + } 1.4514 + 1.4515 + ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); 1.4516 + ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, 1.4517 + sizeof(hashes->u.raw)); 1.4518 + 1.4519 + PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); 1.4520 + 1.4521 + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 1.4522 + * then this will need to be updated. */ 1.4523 + hashes->hashAlg = SEC_OID_SHA256; 1.4524 + rv = SECSuccess; 1.4525 + } else if (ss->opt.bypassPKCS11) { 1.4526 + /* compute them without PKCS11 */ 1.4527 + PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; 1.4528 + PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; 1.4529 + 1.4530 +#define md5cx ((MD5Context *)md5_cx) 1.4531 +#define shacx ((SHA1Context *)sha_cx) 1.4532 + 1.4533 + if (!spec->msItem.data) { 1.4534 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 1.4535 + return SECFailure; 1.4536 + } 1.4537 + 1.4538 + MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); 1.4539 + SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); 1.4540 + 1.4541 + if (!isTLS) { 1.4542 + /* compute hashes for SSL3. */ 1.4543 + unsigned char s[4]; 1.4544 + 1.4545 + s[0] = (unsigned char)(sender >> 24); 1.4546 + s[1] = (unsigned char)(sender >> 16); 1.4547 + s[2] = (unsigned char)(sender >> 8); 1.4548 + s[3] = (unsigned char)sender; 1.4549 + 1.4550 + if (sender != 0) { 1.4551 + MD5_Update(md5cx, s, 4); 1.4552 + PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); 1.4553 + } 1.4554 + 1.4555 + PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 1.4556 + mac_defs[mac_md5].pad_size)); 1.4557 + 1.4558 + MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); 1.4559 + MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); 1.4560 + MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); 1.4561 + 1.4562 + PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); 1.4563 + 1.4564 + if (sender != 0) { 1.4565 + SHA1_Update(shacx, s, 4); 1.4566 + PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); 1.4567 + } 1.4568 + 1.4569 + PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 1.4570 + mac_defs[mac_sha].pad_size)); 1.4571 + 1.4572 + SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); 1.4573 + SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); 1.4574 + SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); 1.4575 + 1.4576 + PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); 1.4577 + PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 1.4578 + mac_defs[mac_md5].pad_size)); 1.4579 + PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); 1.4580 + 1.4581 + MD5_Begin(md5cx); 1.4582 + MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); 1.4583 + MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); 1.4584 + MD5_Update(md5cx, md5_inner, MD5_LENGTH); 1.4585 + } 1.4586 + MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); 1.4587 + 1.4588 + PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); 1.4589 + 1.4590 + if (!isTLS) { 1.4591 + PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 1.4592 + mac_defs[mac_sha].pad_size)); 1.4593 + PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); 1.4594 + 1.4595 + SHA1_Begin(shacx); 1.4596 + SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); 1.4597 + SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); 1.4598 + SHA1_Update(shacx, sha_inner, SHA1_LENGTH); 1.4599 + } 1.4600 + SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); 1.4601 + 1.4602 + PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); 1.4603 + 1.4604 + hashes->len = MD5_LENGTH + SHA1_LENGTH; 1.4605 + rv = SECSuccess; 1.4606 +#undef md5cx 1.4607 +#undef shacx 1.4608 + } else 1.4609 +#endif 1.4610 + if (ss->ssl3.hs.hashType == handshake_hash_single) { 1.4611 + /* compute hashes with PKCS11 */ 1.4612 + PK11Context *h; 1.4613 + unsigned int stateLen; 1.4614 + unsigned char stackBuf[1024]; 1.4615 + unsigned char *stateBuf = NULL; 1.4616 + 1.4617 + if (!spec->master_secret) { 1.4618 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 1.4619 + return SECFailure; 1.4620 + } 1.4621 + 1.4622 + h = ss->ssl3.hs.sha; 1.4623 + stateBuf = PK11_SaveContextAlloc(h, stackBuf, 1.4624 + sizeof(stackBuf), &stateLen); 1.4625 + if (stateBuf == NULL) { 1.4626 + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1.4627 + goto tls12_loser; 1.4628 + } 1.4629 + rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len, 1.4630 + sizeof(hashes->u.raw)); 1.4631 + if (rv != SECSuccess) { 1.4632 + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1.4633 + rv = SECFailure; 1.4634 + goto tls12_loser; 1.4635 + } 1.4636 + /* If we ever support ciphersuites where the PRF hash isn't SHA-256 1.4637 + * then this will need to be updated. */ 1.4638 + hashes->hashAlg = SEC_OID_SHA256; 1.4639 + rv = SECSuccess; 1.4640 + 1.4641 +tls12_loser: 1.4642 + if (stateBuf) { 1.4643 + if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) { 1.4644 + ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); 1.4645 + rv = SECFailure; 1.4646 + } 1.4647 + if (stateBuf != stackBuf) { 1.4648 + PORT_ZFree(stateBuf, stateLen); 1.4649 + } 1.4650 + } 1.4651 + } else { 1.4652 + /* compute hashes with PKCS11 */ 1.4653 + PK11Context * md5; 1.4654 + PK11Context * sha = NULL; 1.4655 + unsigned char *md5StateBuf = NULL; 1.4656 + unsigned char *shaStateBuf = NULL; 1.4657 + unsigned int md5StateLen, shaStateLen; 1.4658 + unsigned char md5StackBuf[256]; 1.4659 + unsigned char shaStackBuf[512]; 1.4660 + 1.4661 + if (!spec->master_secret) { 1.4662 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); 1.4663 + return SECFailure; 1.4664 + } 1.4665 + 1.4666 + md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, 1.4667 + sizeof md5StackBuf, &md5StateLen); 1.4668 + if (md5StateBuf == NULL) { 1.4669 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.4670 + goto loser; 1.4671 + } 1.4672 + md5 = ss->ssl3.hs.md5; 1.4673 + 1.4674 + shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, 1.4675 + sizeof shaStackBuf, &shaStateLen); 1.4676 + if (shaStateBuf == NULL) { 1.4677 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.4678 + goto loser; 1.4679 + } 1.4680 + sha = ss->ssl3.hs.sha; 1.4681 + 1.4682 + if (!isTLS) { 1.4683 + /* compute hashes for SSL3. */ 1.4684 + unsigned char s[4]; 1.4685 + 1.4686 + s[0] = (unsigned char)(sender >> 24); 1.4687 + s[1] = (unsigned char)(sender >> 16); 1.4688 + s[2] = (unsigned char)(sender >> 8); 1.4689 + s[3] = (unsigned char)sender; 1.4690 + 1.4691 + if (sender != 0) { 1.4692 + rv |= PK11_DigestOp(md5, s, 4); 1.4693 + PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); 1.4694 + } 1.4695 + 1.4696 + PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, 1.4697 + mac_defs[mac_md5].pad_size)); 1.4698 + 1.4699 + rv |= PK11_DigestKey(md5,spec->master_secret); 1.4700 + rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); 1.4701 + rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH); 1.4702 + PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); 1.4703 + if (rv != SECSuccess) { 1.4704 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.4705 + rv = SECFailure; 1.4706 + goto loser; 1.4707 + } 1.4708 + 1.4709 + PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); 1.4710 + 1.4711 + if (sender != 0) { 1.4712 + rv |= PK11_DigestOp(sha, s, 4); 1.4713 + PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); 1.4714 + } 1.4715 + 1.4716 + PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, 1.4717 + mac_defs[mac_sha].pad_size)); 1.4718 + 1.4719 + rv |= PK11_DigestKey(sha, spec->master_secret); 1.4720 + rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); 1.4721 + rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH); 1.4722 + PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); 1.4723 + if (rv != SECSuccess) { 1.4724 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.4725 + rv = SECFailure; 1.4726 + goto loser; 1.4727 + } 1.4728 + 1.4729 + PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); 1.4730 + 1.4731 + PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, 1.4732 + mac_defs[mac_md5].pad_size)); 1.4733 + PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); 1.4734 + 1.4735 + rv |= PK11_DigestBegin(md5); 1.4736 + rv |= PK11_DigestKey(md5, spec->master_secret); 1.4737 + rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); 1.4738 + rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH); 1.4739 + } 1.4740 + rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH); 1.4741 + PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH); 1.4742 + if (rv != SECSuccess) { 1.4743 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.4744 + rv = SECFailure; 1.4745 + goto loser; 1.4746 + } 1.4747 + 1.4748 + PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); 1.4749 + 1.4750 + if (!isTLS) { 1.4751 + PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, 1.4752 + mac_defs[mac_sha].pad_size)); 1.4753 + PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); 1.4754 + 1.4755 + rv |= PK11_DigestBegin(sha); 1.4756 + rv |= PK11_DigestKey(sha,spec->master_secret); 1.4757 + rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); 1.4758 + rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH); 1.4759 + } 1.4760 + rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH); 1.4761 + PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH); 1.4762 + if (rv != SECSuccess) { 1.4763 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.4764 + rv = SECFailure; 1.4765 + goto loser; 1.4766 + } 1.4767 + 1.4768 + PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); 1.4769 + 1.4770 + hashes->len = MD5_LENGTH + SHA1_LENGTH; 1.4771 + rv = SECSuccess; 1.4772 + 1.4773 + loser: 1.4774 + if (md5StateBuf) { 1.4775 + if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) 1.4776 + != SECSuccess) 1.4777 + { 1.4778 + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); 1.4779 + rv = SECFailure; 1.4780 + } 1.4781 + if (md5StateBuf != md5StackBuf) { 1.4782 + PORT_ZFree(md5StateBuf, md5StateLen); 1.4783 + } 1.4784 + } 1.4785 + if (shaStateBuf) { 1.4786 + if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) 1.4787 + != SECSuccess) 1.4788 + { 1.4789 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.4790 + rv = SECFailure; 1.4791 + } 1.4792 + if (shaStateBuf != shaStackBuf) { 1.4793 + PORT_ZFree(shaStateBuf, shaStateLen); 1.4794 + } 1.4795 + } 1.4796 + } 1.4797 + return rv; 1.4798 +} 1.4799 + 1.4800 +static SECStatus 1.4801 +ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, 1.4802 + SSL3Hashes * hashes) /* output goes here. */ 1.4803 +{ 1.4804 + SECStatus rv = SECSuccess; 1.4805 + 1.4806 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.4807 + PORT_Assert( !ss->sec.isServer ); 1.4808 + PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); 1.4809 + 1.4810 + rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len, 1.4811 + sizeof(hashes->u.raw)); 1.4812 + if (rv != SECSuccess) { 1.4813 + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); 1.4814 + rv = SECFailure; 1.4815 + goto loser; 1.4816 + } 1.4817 + hashes->hashAlg = SEC_OID_SHA1; 1.4818 + 1.4819 +loser: 1.4820 + PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); 1.4821 + ss->ssl3.hs.backupHash = NULL; 1.4822 + return rv; 1.4823 +} 1.4824 + 1.4825 +/* 1.4826 + * SSL 2 based implementations pass in the initial outbound buffer 1.4827 + * so that the handshake hash can contain the included information. 1.4828 + * 1.4829 + * Called from ssl2_BeginClientHandshake() in sslcon.c 1.4830 + */ 1.4831 +SECStatus 1.4832 +ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length) 1.4833 +{ 1.4834 + SECStatus rv; 1.4835 + 1.4836 + ssl_GetSSL3HandshakeLock(ss); /**************************************/ 1.4837 + 1.4838 + rv = ssl3_InitState(ss); 1.4839 + if (rv != SECSuccess) { 1.4840 + goto done; /* ssl3_InitState has set the error code. */ 1.4841 + } 1.4842 + rv = ssl3_RestartHandshakeHashes(ss); 1.4843 + if (rv != SECSuccess) { 1.4844 + goto done; 1.4845 + } 1.4846 + 1.4847 + PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); 1.4848 + PORT_Memcpy( 1.4849 + &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES], 1.4850 + &ss->sec.ci.clientChallenge, 1.4851 + SSL_CHALLENGE_BYTES); 1.4852 + 1.4853 + rv = ssl3_UpdateHandshakeHashes(ss, buf, length); 1.4854 + /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */ 1.4855 + 1.4856 +done: 1.4857 + ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ 1.4858 + return rv; 1.4859 +} 1.4860 + 1.4861 +/************************************************************************** 1.4862 + * end of Handshake Hash functions. 1.4863 + * Begin Send and Handle functions for handshakes. 1.4864 + **************************************************************************/ 1.4865 + 1.4866 +/* Called from ssl3_HandleHelloRequest(), 1.4867 + * ssl3_RedoHandshake() 1.4868 + * ssl2_BeginClientHandshake (when resuming ssl3 session) 1.4869 + * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) 1.4870 + */ 1.4871 +SECStatus 1.4872 +ssl3_SendClientHello(sslSocket *ss, PRBool resending) 1.4873 +{ 1.4874 + sslSessionID * sid; 1.4875 + ssl3CipherSpec * cwSpec; 1.4876 + SECStatus rv; 1.4877 + int i; 1.4878 + int length; 1.4879 + int num_suites; 1.4880 + int actual_count = 0; 1.4881 + PRBool isTLS = PR_FALSE; 1.4882 + PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; 1.4883 + PRInt32 total_exten_len = 0; 1.4884 + unsigned paddingExtensionLen; 1.4885 + unsigned numCompressionMethods; 1.4886 + PRInt32 flags; 1.4887 + 1.4888 + SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(), 1.4889 + ss->fd)); 1.4890 + 1.4891 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.4892 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 1.4893 + 1.4894 + rv = ssl3_InitState(ss); 1.4895 + if (rv != SECSuccess) { 1.4896 + return rv; /* ssl3_InitState has set the error code. */ 1.4897 + } 1.4898 + ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */ 1.4899 + PORT_Assert(IS_DTLS(ss) || !resending); 1.4900 + 1.4901 + SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); 1.4902 + ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 1.4903 + 1.4904 + /* We might be starting a session renegotiation in which case we should 1.4905 + * clear previous state. 1.4906 + */ 1.4907 + PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 1.4908 + 1.4909 + rv = ssl3_RestartHandshakeHashes(ss); 1.4910 + if (rv != SECSuccess) { 1.4911 + return rv; 1.4912 + } 1.4913 + 1.4914 + /* 1.4915 + * During a renegotiation, ss->clientHelloVersion will be used again to 1.4916 + * work around a Windows SChannel bug. Ensure that it is still enabled. 1.4917 + */ 1.4918 + if (ss->firstHsDone) { 1.4919 + if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1.4920 + PORT_SetError(SSL_ERROR_SSL_DISABLED); 1.4921 + return SECFailure; 1.4922 + } 1.4923 + 1.4924 + if (ss->clientHelloVersion < ss->vrange.min || 1.4925 + ss->clientHelloVersion > ss->vrange.max) { 1.4926 + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 1.4927 + return SECFailure; 1.4928 + } 1.4929 + } 1.4930 + 1.4931 + /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup 1.4932 + * handles expired entries and other details. 1.4933 + * XXX If we've been called from ssl2_BeginClientHandshake, then 1.4934 + * this lookup is duplicative and wasteful. 1.4935 + */ 1.4936 + sid = (ss->opt.noCache) ? NULL 1.4937 + : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url); 1.4938 + 1.4939 + /* We can't resume based on a different token. If the sid exists, 1.4940 + * make sure the token that holds the master secret still exists ... 1.4941 + * If we previously did client-auth, make sure that the token that holds 1.4942 + * the private key still exists, is logged in, hasn't been removed, etc. 1.4943 + */ 1.4944 + if (sid) { 1.4945 + PRBool sidOK = PR_TRUE; 1.4946 + if (sid->u.ssl3.keys.msIsWrapped) { 1.4947 + /* Session key was wrapped, which means it was using PKCS11, */ 1.4948 + PK11SlotInfo *slot = NULL; 1.4949 + if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { 1.4950 + slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, 1.4951 + sid->u.ssl3.masterSlotID); 1.4952 + } 1.4953 + if (slot == NULL) { 1.4954 + sidOK = PR_FALSE; 1.4955 + } else { 1.4956 + PK11SymKey *wrapKey = NULL; 1.4957 + if (!PK11_IsPresent(slot) || 1.4958 + ((wrapKey = PK11_GetWrapKey(slot, 1.4959 + sid->u.ssl3.masterWrapIndex, 1.4960 + sid->u.ssl3.masterWrapMech, 1.4961 + sid->u.ssl3.masterWrapSeries, 1.4962 + ss->pkcs11PinArg)) == NULL) ) { 1.4963 + sidOK = PR_FALSE; 1.4964 + } 1.4965 + if (wrapKey) PK11_FreeSymKey(wrapKey); 1.4966 + PK11_FreeSlot(slot); 1.4967 + slot = NULL; 1.4968 + } 1.4969 + } 1.4970 + /* If we previously did client-auth, make sure that the token that 1.4971 + ** holds the private key still exists, is logged in, hasn't been 1.4972 + ** removed, etc. 1.4973 + */ 1.4974 + if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) { 1.4975 + sidOK = PR_FALSE; 1.4976 + } 1.4977 + 1.4978 + /* TLS 1.0 (RFC 2246) Appendix E says: 1.4979 + * Whenever a client already knows the highest protocol known to 1.4980 + * a server (for example, when resuming a session), it should 1.4981 + * initiate the connection in that native protocol. 1.4982 + * So we pass sid->version to ssl3_NegotiateVersion() here, except 1.4983 + * when renegotiating. 1.4984 + * 1.4985 + * Windows SChannel compares the client_version inside the RSA 1.4986 + * EncryptedPreMasterSecret of a renegotiation with the 1.4987 + * client_version of the initial ClientHello rather than the 1.4988 + * ClientHello in the renegotiation. To work around this bug, we 1.4989 + * continue to use the client_version used in the initial 1.4990 + * ClientHello when renegotiating. 1.4991 + */ 1.4992 + if (sidOK) { 1.4993 + if (ss->firstHsDone) { 1.4994 + /* 1.4995 + * The client_version of the initial ClientHello is still 1.4996 + * available in ss->clientHelloVersion. Ensure that 1.4997 + * sid->version is bounded within 1.4998 + * [ss->vrange.min, ss->clientHelloVersion], otherwise we 1.4999 + * can't use sid. 1.5000 + */ 1.5001 + if (sid->version >= ss->vrange.min && 1.5002 + sid->version <= ss->clientHelloVersion) { 1.5003 + ss->version = ss->clientHelloVersion; 1.5004 + } else { 1.5005 + sidOK = PR_FALSE; 1.5006 + } 1.5007 + } else { 1.5008 + if (ssl3_NegotiateVersion(ss, sid->version, 1.5009 + PR_FALSE) != SECSuccess) { 1.5010 + sidOK = PR_FALSE; 1.5011 + } 1.5012 + } 1.5013 + } 1.5014 + 1.5015 + if (!sidOK) { 1.5016 + SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok ); 1.5017 + if (ss->sec.uncache) 1.5018 + (*ss->sec.uncache)(sid); 1.5019 + ssl_FreeSID(sid); 1.5020 + sid = NULL; 1.5021 + } 1.5022 + } 1.5023 + 1.5024 + if (sid) { 1.5025 + requestingResume = PR_TRUE; 1.5026 + SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits ); 1.5027 + 1.5028 + PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, 1.5029 + sid->u.ssl3.sessionIDLength)); 1.5030 + 1.5031 + ss->ssl3.policy = sid->u.ssl3.policy; 1.5032 + } else { 1.5033 + SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses ); 1.5034 + 1.5035 + /* 1.5036 + * Windows SChannel compares the client_version inside the RSA 1.5037 + * EncryptedPreMasterSecret of a renegotiation with the 1.5038 + * client_version of the initial ClientHello rather than the 1.5039 + * ClientHello in the renegotiation. To work around this bug, we 1.5040 + * continue to use the client_version used in the initial 1.5041 + * ClientHello when renegotiating. 1.5042 + */ 1.5043 + if (ss->firstHsDone) { 1.5044 + ss->version = ss->clientHelloVersion; 1.5045 + } else { 1.5046 + rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, 1.5047 + PR_TRUE); 1.5048 + if (rv != SECSuccess) 1.5049 + return rv; /* error code was set */ 1.5050 + } 1.5051 + 1.5052 + sid = ssl3_NewSessionID(ss, PR_FALSE); 1.5053 + if (!sid) { 1.5054 + return SECFailure; /* memory error is set */ 1.5055 + } 1.5056 + } 1.5057 + 1.5058 + isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); 1.5059 + ssl_GetSpecWriteLock(ss); 1.5060 + cwSpec = ss->ssl3.cwSpec; 1.5061 + if (cwSpec->mac_def->mac == mac_null) { 1.5062 + /* SSL records are not being MACed. */ 1.5063 + cwSpec->version = ss->version; 1.5064 + } 1.5065 + ssl_ReleaseSpecWriteLock(ss); 1.5066 + 1.5067 + if (ss->sec.ci.sid != NULL) { 1.5068 + ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ 1.5069 + } 1.5070 + ss->sec.ci.sid = sid; 1.5071 + 1.5072 + ss->sec.send = ssl3_SendApplicationData; 1.5073 + 1.5074 + /* shouldn't get here if SSL3 is disabled, but ... */ 1.5075 + if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1.5076 + PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled"); 1.5077 + PORT_SetError(SSL_ERROR_SSL_DISABLED); 1.5078 + return SECFailure; 1.5079 + } 1.5080 + 1.5081 + /* how many suites does our PKCS11 support (regardless of policy)? */ 1.5082 + num_suites = ssl3_config_match_init(ss); 1.5083 + if (!num_suites) 1.5084 + return SECFailure; /* ssl3_config_match_init has set error code. */ 1.5085 + 1.5086 + /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV, 1.5087 + * only if TLS is disabled. 1.5088 + */ 1.5089 + if (!ss->firstHsDone && !isTLS) { 1.5090 + /* Must set this before calling Hello Extension Senders, 1.5091 + * to suppress sending of empty RI extension. 1.5092 + */ 1.5093 + ss->ssl3.hs.sendingSCSV = PR_TRUE; 1.5094 + } 1.5095 + 1.5096 + /* When we attempt session resumption (only), we must lock the sid to 1.5097 + * prevent races with other resumption connections that receive a 1.5098 + * NewSessionTicket that will cause the ticket in the sid to be replaced. 1.5099 + * Once we've copied the session ticket into our ClientHello message, it 1.5100 + * is OK for the ticket to change, so we just need to make sure we hold 1.5101 + * the lock across the calls to ssl3_CallHelloExtensionSenders. 1.5102 + */ 1.5103 + if (sid->u.ssl3.lock) { 1.5104 + PR_RWLock_Rlock(sid->u.ssl3.lock); 1.5105 + } 1.5106 + 1.5107 + if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { 1.5108 + PRUint32 maxBytes = 65535; /* 2^16 - 1 */ 1.5109 + PRInt32 extLen; 1.5110 + 1.5111 + extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); 1.5112 + if (extLen < 0) { 1.5113 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5114 + return SECFailure; 1.5115 + } 1.5116 + maxBytes -= extLen; 1.5117 + total_exten_len += extLen; 1.5118 + 1.5119 + if (total_exten_len > 0) 1.5120 + total_exten_len += 2; 1.5121 + } 1.5122 + 1.5123 +#ifndef NSS_DISABLE_ECC 1.5124 + if (!total_exten_len || !isTLS) { 1.5125 + /* not sending the elliptic_curves and ec_point_formats extensions */ 1.5126 + ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ 1.5127 + } 1.5128 +#endif /* NSS_DISABLE_ECC */ 1.5129 + 1.5130 + if (IS_DTLS(ss)) { 1.5131 + ssl3_DisableNonDTLSSuites(ss); 1.5132 + } 1.5133 + 1.5134 + /* how many suites are permitted by policy and user preference? */ 1.5135 + num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); 1.5136 + if (!num_suites) { 1.5137 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5138 + return SECFailure; /* count_cipher_suites has set error code. */ 1.5139 + } 1.5140 + 1.5141 + fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume || 1.5142 + ss->version < sid->version); 1.5143 + /* make room for SCSV */ 1.5144 + if (ss->ssl3.hs.sendingSCSV) { 1.5145 + ++num_suites; 1.5146 + } 1.5147 + if (fallbackSCSV) { 1.5148 + ++num_suites; 1.5149 + } 1.5150 + 1.5151 + /* count compression methods */ 1.5152 + numCompressionMethods = 0; 1.5153 + for (i = 0; i < compressionMethodsCount; i++) { 1.5154 + if (compressionEnabled(ss, compressions[i])) 1.5155 + numCompressionMethods++; 1.5156 + } 1.5157 + 1.5158 + length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1.5159 + 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + 1.5160 + 2 + num_suites*sizeof(ssl3CipherSuite) + 1.5161 + 1 + numCompressionMethods + total_exten_len; 1.5162 + if (IS_DTLS(ss)) { 1.5163 + length += 1 + ss->ssl3.hs.cookieLen; 1.5164 + } 1.5165 + 1.5166 + /* A padding extension may be included to ensure that the record containing 1.5167 + * the ClientHello doesn't have a length between 256 and 511 bytes 1.5168 + * (inclusive). Initial, ClientHello records with such lengths trigger bugs 1.5169 + * in F5 devices. 1.5170 + * 1.5171 + * This is not done for DTLS nor for renegotiation. */ 1.5172 + if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) { 1.5173 + paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length); 1.5174 + total_exten_len += paddingExtensionLen; 1.5175 + length += paddingExtensionLen; 1.5176 + } else { 1.5177 + paddingExtensionLen = 0; 1.5178 + } 1.5179 + 1.5180 + rv = ssl3_AppendHandshakeHeader(ss, client_hello, length); 1.5181 + if (rv != SECSuccess) { 1.5182 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5183 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5184 + } 1.5185 + 1.5186 + if (ss->firstHsDone) { 1.5187 + /* The client hello version must stay unchanged to work around 1.5188 + * the Windows SChannel bug described above. */ 1.5189 + PORT_Assert(ss->version == ss->clientHelloVersion); 1.5190 + } 1.5191 + ss->clientHelloVersion = ss->version; 1.5192 + if (IS_DTLS(ss)) { 1.5193 + PRUint16 version; 1.5194 + 1.5195 + version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); 1.5196 + rv = ssl3_AppendHandshakeNumber(ss, version, 2); 1.5197 + } else { 1.5198 + rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); 1.5199 + } 1.5200 + if (rv != SECSuccess) { 1.5201 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5202 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5203 + } 1.5204 + 1.5205 + if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */ 1.5206 + rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); 1.5207 + if (rv != SECSuccess) { 1.5208 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5209 + return rv; /* err set by GetNewRandom. */ 1.5210 + } 1.5211 + } 1.5212 + rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random, 1.5213 + SSL3_RANDOM_LENGTH); 1.5214 + if (rv != SECSuccess) { 1.5215 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5216 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5217 + } 1.5218 + 1.5219 + if (sid) 1.5220 + rv = ssl3_AppendHandshakeVariable( 1.5221 + ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); 1.5222 + else 1.5223 + rv = ssl3_AppendHandshakeNumber(ss, 0, 1); 1.5224 + if (rv != SECSuccess) { 1.5225 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5226 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5227 + } 1.5228 + 1.5229 + if (IS_DTLS(ss)) { 1.5230 + rv = ssl3_AppendHandshakeVariable( 1.5231 + ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); 1.5232 + if (rv != SECSuccess) { 1.5233 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5234 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5235 + } 1.5236 + } 1.5237 + 1.5238 + rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2); 1.5239 + if (rv != SECSuccess) { 1.5240 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5241 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5242 + } 1.5243 + 1.5244 + if (ss->ssl3.hs.sendingSCSV) { 1.5245 + /* Add the actual SCSV */ 1.5246 + rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, 1.5247 + sizeof(ssl3CipherSuite)); 1.5248 + if (rv != SECSuccess) { 1.5249 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5250 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5251 + } 1.5252 + actual_count++; 1.5253 + } 1.5254 + if (fallbackSCSV) { 1.5255 + rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, 1.5256 + sizeof(ssl3CipherSuite)); 1.5257 + if (rv != SECSuccess) { 1.5258 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5259 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5260 + } 1.5261 + actual_count++; 1.5262 + } 1.5263 + for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 1.5264 + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 1.5265 + if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange)) { 1.5266 + actual_count++; 1.5267 + if (actual_count > num_suites) { 1.5268 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5269 + /* set error card removal/insertion error */ 1.5270 + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 1.5271 + return SECFailure; 1.5272 + } 1.5273 + rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, 1.5274 + sizeof(ssl3CipherSuite)); 1.5275 + if (rv != SECSuccess) { 1.5276 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5277 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5278 + } 1.5279 + } 1.5280 + } 1.5281 + 1.5282 + /* if cards were removed or inserted between count_cipher_suites and 1.5283 + * generating our list, detect the error here rather than send it off to 1.5284 + * the server.. */ 1.5285 + if (actual_count != num_suites) { 1.5286 + /* Card removal/insertion error */ 1.5287 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5288 + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 1.5289 + return SECFailure; 1.5290 + } 1.5291 + 1.5292 + rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1); 1.5293 + if (rv != SECSuccess) { 1.5294 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5295 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5296 + } 1.5297 + for (i = 0; i < compressionMethodsCount; i++) { 1.5298 + if (!compressionEnabled(ss, compressions[i])) 1.5299 + continue; 1.5300 + rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); 1.5301 + if (rv != SECSuccess) { 1.5302 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5303 + return rv; /* err set by ssl3_AppendHandshake* */ 1.5304 + } 1.5305 + } 1.5306 + 1.5307 + if (total_exten_len) { 1.5308 + PRUint32 maxBytes = total_exten_len - 2; 1.5309 + PRInt32 extLen; 1.5310 + 1.5311 + rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); 1.5312 + if (rv != SECSuccess) { 1.5313 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5314 + return rv; /* err set by AppendHandshake. */ 1.5315 + } 1.5316 + 1.5317 + extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); 1.5318 + if (extLen < 0) { 1.5319 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5320 + return SECFailure; 1.5321 + } 1.5322 + maxBytes -= extLen; 1.5323 + 1.5324 + extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); 1.5325 + if (extLen < 0) { 1.5326 + if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } 1.5327 + return SECFailure; 1.5328 + } 1.5329 + maxBytes -= extLen; 1.5330 + 1.5331 + PORT_Assert(!maxBytes); 1.5332 + } 1.5333 + 1.5334 + if (sid->u.ssl3.lock) { 1.5335 + PR_RWLock_Unlock(sid->u.ssl3.lock); 1.5336 + } 1.5337 + 1.5338 + if (ss->xtnData.sentSessionTicketInClientHello) { 1.5339 + SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes); 1.5340 + } 1.5341 + 1.5342 + if (ss->ssl3.hs.sendingSCSV) { 1.5343 + /* Since we sent the SCSV, pretend we sent empty RI extension. */ 1.5344 + TLSExtensionData *xtnData = &ss->xtnData; 1.5345 + xtnData->advertised[xtnData->numAdvertised++] = 1.5346 + ssl_renegotiation_info_xtn; 1.5347 + } 1.5348 + 1.5349 + flags = 0; 1.5350 + if (!ss->firstHsDone && !IS_DTLS(ss)) { 1.5351 + flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; 1.5352 + } 1.5353 + rv = ssl3_FlushHandshake(ss, flags); 1.5354 + if (rv != SECSuccess) { 1.5355 + return rv; /* error code set by ssl3_FlushHandshake */ 1.5356 + } 1.5357 + 1.5358 + ss->ssl3.hs.ws = wait_server_hello; 1.5359 + return rv; 1.5360 +} 1.5361 + 1.5362 + 1.5363 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.5364 + * ssl3 Hello Request. 1.5365 + * Caller must hold Handshake and RecvBuf locks. 1.5366 + */ 1.5367 +static SECStatus 1.5368 +ssl3_HandleHelloRequest(sslSocket *ss) 1.5369 +{ 1.5370 + sslSessionID *sid = ss->sec.ci.sid; 1.5371 + SECStatus rv; 1.5372 + 1.5373 + SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake", 1.5374 + SSL_GETPID(), ss->fd)); 1.5375 + 1.5376 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.5377 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.5378 + 1.5379 + if (ss->ssl3.hs.ws == wait_server_hello) 1.5380 + return SECSuccess; 1.5381 + if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) { 1.5382 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.5383 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); 1.5384 + return SECFailure; 1.5385 + } 1.5386 + if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 1.5387 + ssl_GetXmitBufLock(ss); 1.5388 + rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation); 1.5389 + ssl_ReleaseXmitBufLock(ss); 1.5390 + PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 1.5391 + return SECFailure; 1.5392 + } 1.5393 + 1.5394 + if (sid) { 1.5395 + if (ss->sec.uncache) 1.5396 + ss->sec.uncache(sid); 1.5397 + ssl_FreeSID(sid); 1.5398 + ss->sec.ci.sid = NULL; 1.5399 + } 1.5400 + 1.5401 + if (IS_DTLS(ss)) { 1.5402 + dtls_RehandshakeCleanup(ss); 1.5403 + } 1.5404 + 1.5405 + ssl_GetXmitBufLock(ss); 1.5406 + rv = ssl3_SendClientHello(ss, PR_FALSE); 1.5407 + ssl_ReleaseXmitBufLock(ss); 1.5408 + 1.5409 + return rv; 1.5410 +} 1.5411 + 1.5412 +#define UNKNOWN_WRAP_MECHANISM 0x7fffffff 1.5413 + 1.5414 +static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = { 1.5415 + CKM_DES3_ECB, 1.5416 + CKM_CAST5_ECB, 1.5417 + CKM_DES_ECB, 1.5418 + CKM_KEY_WRAP_LYNKS, 1.5419 + CKM_IDEA_ECB, 1.5420 + CKM_CAST3_ECB, 1.5421 + CKM_CAST_ECB, 1.5422 + CKM_RC5_ECB, 1.5423 + CKM_RC2_ECB, 1.5424 + CKM_CDMF_ECB, 1.5425 + CKM_SKIPJACK_WRAP, 1.5426 + CKM_SKIPJACK_CBC64, 1.5427 + CKM_AES_ECB, 1.5428 + CKM_CAMELLIA_ECB, 1.5429 + CKM_SEED_ECB, 1.5430 + UNKNOWN_WRAP_MECHANISM 1.5431 +}; 1.5432 + 1.5433 +static int 1.5434 +ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) 1.5435 +{ 1.5436 + const CK_MECHANISM_TYPE *pMech = wrapMechanismList; 1.5437 + 1.5438 + while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) { 1.5439 + ++pMech; 1.5440 + } 1.5441 + return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1 1.5442 + : (pMech - wrapMechanismList); 1.5443 +} 1.5444 + 1.5445 +static PK11SymKey * 1.5446 +ssl_UnwrapSymWrappingKey( 1.5447 + SSLWrappedSymWrappingKey *pWswk, 1.5448 + SECKEYPrivateKey * svrPrivKey, 1.5449 + SSL3KEAType exchKeyType, 1.5450 + CK_MECHANISM_TYPE masterWrapMech, 1.5451 + void * pwArg) 1.5452 +{ 1.5453 + PK11SymKey * unwrappedWrappingKey = NULL; 1.5454 + SECItem wrappedKey; 1.5455 +#ifndef NSS_DISABLE_ECC 1.5456 + PK11SymKey * Ks; 1.5457 + SECKEYPublicKey pubWrapKey; 1.5458 + ECCWrappedKeyInfo *ecWrapped; 1.5459 +#endif /* NSS_DISABLE_ECC */ 1.5460 + 1.5461 + /* found the wrapping key on disk. */ 1.5462 + PORT_Assert(pWswk->symWrapMechanism == masterWrapMech); 1.5463 + PORT_Assert(pWswk->exchKeyType == exchKeyType); 1.5464 + if (pWswk->symWrapMechanism != masterWrapMech || 1.5465 + pWswk->exchKeyType != exchKeyType) { 1.5466 + goto loser; 1.5467 + } 1.5468 + wrappedKey.type = siBuffer; 1.5469 + wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; 1.5470 + wrappedKey.len = pWswk->wrappedSymKeyLen; 1.5471 + PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); 1.5472 + 1.5473 + switch (exchKeyType) { 1.5474 + 1.5475 + case kt_rsa: 1.5476 + unwrappedWrappingKey = 1.5477 + PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, 1.5478 + masterWrapMech, CKA_UNWRAP, 0); 1.5479 + break; 1.5480 + 1.5481 +#ifndef NSS_DISABLE_ECC 1.5482 + case kt_ecdh: 1.5483 + /* 1.5484 + * For kt_ecdh, we first create an EC public key based on 1.5485 + * data stored with the wrappedSymmetricWrappingkey. Next, 1.5486 + * we do an ECDH computation involving this public key and 1.5487 + * the SSL server's (long-term) EC private key. The resulting 1.5488 + * shared secret is treated the same way as Fortezza's Ks, i.e., 1.5489 + * it is used to recover the symmetric wrapping key. 1.5490 + * 1.5491 + * The data in wrappedSymmetricWrappingkey is laid out as defined 1.5492 + * in the ECCWrappedKeyInfo structure. 1.5493 + */ 1.5494 + ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey; 1.5495 + 1.5496 + PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 1.5497 + ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN); 1.5498 + 1.5499 + if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + 1.5500 + ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { 1.5501 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.5502 + goto loser; 1.5503 + } 1.5504 + 1.5505 + pubWrapKey.keyType = ecKey; 1.5506 + pubWrapKey.u.ec.size = ecWrapped->size; 1.5507 + pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen; 1.5508 + pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var; 1.5509 + pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen; 1.5510 + pubWrapKey.u.ec.publicValue.data = ecWrapped->var + 1.5511 + ecWrapped->encodedParamLen; 1.5512 + 1.5513 + wrappedKey.len = ecWrapped->wrappedKeyLen; 1.5514 + wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 1.5515 + ecWrapped->pubValueLen; 1.5516 + 1.5517 + /* Derive Ks using ECDH */ 1.5518 + Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL, 1.5519 + NULL, CKM_ECDH1_DERIVE, masterWrapMech, 1.5520 + CKA_DERIVE, 0, CKD_NULL, NULL, NULL); 1.5521 + if (Ks == NULL) { 1.5522 + goto loser; 1.5523 + } 1.5524 + 1.5525 + /* Use Ks to unwrap the wrapping key */ 1.5526 + unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, 1.5527 + &wrappedKey, masterWrapMech, 1.5528 + CKA_UNWRAP, 0); 1.5529 + PK11_FreeSymKey(Ks); 1.5530 + 1.5531 + break; 1.5532 +#endif 1.5533 + 1.5534 + default: 1.5535 + /* Assert? */ 1.5536 + SET_ERROR_CODE 1.5537 + goto loser; 1.5538 + } 1.5539 +loser: 1.5540 + return unwrappedWrappingKey; 1.5541 +} 1.5542 + 1.5543 +/* Each process sharing the server session ID cache has its own array of 1.5544 + * SymKey pointers for the symmetric wrapping keys that are used to wrap 1.5545 + * the master secrets. There is one key for each KEA type. These Symkeys 1.5546 + * correspond to the wrapped SymKeys kept in the server session cache. 1.5547 + */ 1.5548 + 1.5549 +typedef struct { 1.5550 + PK11SymKey * symWrapKey[kt_kea_size]; 1.5551 +} ssl3SymWrapKey; 1.5552 + 1.5553 +static PZLock * symWrapKeysLock = NULL; 1.5554 +static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; 1.5555 + 1.5556 +SECStatus ssl_FreeSymWrapKeysLock(void) 1.5557 +{ 1.5558 + if (symWrapKeysLock) { 1.5559 + PZ_DestroyLock(symWrapKeysLock); 1.5560 + symWrapKeysLock = NULL; 1.5561 + return SECSuccess; 1.5562 + } 1.5563 + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); 1.5564 + return SECFailure; 1.5565 +} 1.5566 + 1.5567 +SECStatus 1.5568 +SSL3_ShutdownServerCache(void) 1.5569 +{ 1.5570 + int i, j; 1.5571 + 1.5572 + if (!symWrapKeysLock) 1.5573 + return SECSuccess; /* lock was never initialized */ 1.5574 + PZ_Lock(symWrapKeysLock); 1.5575 + /* get rid of all symWrapKeys */ 1.5576 + for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) { 1.5577 + for (j = 0; j < kt_kea_size; ++j) { 1.5578 + PK11SymKey ** pSymWrapKey; 1.5579 + pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; 1.5580 + if (*pSymWrapKey) { 1.5581 + PK11_FreeSymKey(*pSymWrapKey); 1.5582 + *pSymWrapKey = NULL; 1.5583 + } 1.5584 + } 1.5585 + } 1.5586 + 1.5587 + PZ_Unlock(symWrapKeysLock); 1.5588 + ssl_FreeSessionCacheLocks(); 1.5589 + return SECSuccess; 1.5590 +} 1.5591 + 1.5592 +SECStatus ssl_InitSymWrapKeysLock(void) 1.5593 +{ 1.5594 + symWrapKeysLock = PZ_NewLock(nssILockOther); 1.5595 + return symWrapKeysLock ? SECSuccess : SECFailure; 1.5596 +} 1.5597 + 1.5598 +/* Try to get wrapping key for mechanism from in-memory array. 1.5599 + * If that fails, look for one on disk. 1.5600 + * If that fails, generate a new one, put the new one on disk, 1.5601 + * Put the new key in the in-memory array. 1.5602 + */ 1.5603 +static PK11SymKey * 1.5604 +getWrappingKey( sslSocket * ss, 1.5605 + PK11SlotInfo * masterSecretSlot, 1.5606 + SSL3KEAType exchKeyType, 1.5607 + CK_MECHANISM_TYPE masterWrapMech, 1.5608 + void * pwArg) 1.5609 +{ 1.5610 + SECKEYPrivateKey * svrPrivKey; 1.5611 + SECKEYPublicKey * svrPubKey = NULL; 1.5612 + PK11SymKey * unwrappedWrappingKey = NULL; 1.5613 + PK11SymKey ** pSymWrapKey; 1.5614 + CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; 1.5615 + int length; 1.5616 + int symWrapMechIndex; 1.5617 + SECStatus rv; 1.5618 + SECItem wrappedKey; 1.5619 + SSLWrappedSymWrappingKey wswk; 1.5620 +#ifndef NSS_DISABLE_ECC 1.5621 + PK11SymKey * Ks = NULL; 1.5622 + SECKEYPublicKey *pubWrapKey = NULL; 1.5623 + SECKEYPrivateKey *privWrapKey = NULL; 1.5624 + ECCWrappedKeyInfo *ecWrapped; 1.5625 +#endif /* NSS_DISABLE_ECC */ 1.5626 + 1.5627 + svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; 1.5628 + PORT_Assert(svrPrivKey != NULL); 1.5629 + if (!svrPrivKey) { 1.5630 + return NULL; /* why are we here?!? */ 1.5631 + } 1.5632 + 1.5633 + symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech); 1.5634 + PORT_Assert(symWrapMechIndex >= 0); 1.5635 + if (symWrapMechIndex < 0) 1.5636 + return NULL; /* invalid masterWrapMech. */ 1.5637 + 1.5638 + pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType]; 1.5639 + 1.5640 + ssl_InitSessionCacheLocks(PR_TRUE); 1.5641 + 1.5642 + PZ_Lock(symWrapKeysLock); 1.5643 + 1.5644 + unwrappedWrappingKey = *pSymWrapKey; 1.5645 + if (unwrappedWrappingKey != NULL) { 1.5646 + if (PK11_VerifyKeyOK(unwrappedWrappingKey)) { 1.5647 + unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey); 1.5648 + goto done; 1.5649 + } 1.5650 + /* slot series has changed, so this key is no good any more. */ 1.5651 + PK11_FreeSymKey(unwrappedWrappingKey); 1.5652 + *pSymWrapKey = unwrappedWrappingKey = NULL; 1.5653 + } 1.5654 + 1.5655 + /* Try to get wrapped SymWrapping key out of the (disk) cache. */ 1.5656 + /* Following call fills in wswk on success. */ 1.5657 + if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) { 1.5658 + /* found the wrapped sym wrapping key on disk. */ 1.5659 + unwrappedWrappingKey = 1.5660 + ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, 1.5661 + masterWrapMech, pwArg); 1.5662 + if (unwrappedWrappingKey) { 1.5663 + goto install; 1.5664 + } 1.5665 + } 1.5666 + 1.5667 + if (!masterSecretSlot) /* caller doesn't want to create a new one. */ 1.5668 + goto loser; 1.5669 + 1.5670 + length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech); 1.5671 + /* Zero length means fixed key length algorithm, or error. 1.5672 + * It's ambiguous. 1.5673 + */ 1.5674 + unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, 1.5675 + length, pwArg); 1.5676 + if (!unwrappedWrappingKey) { 1.5677 + goto loser; 1.5678 + } 1.5679 + 1.5680 + /* Prepare the buffer to receive the wrappedWrappingKey, 1.5681 + * the symmetric wrapping key wrapped using the server's pub key. 1.5682 + */ 1.5683 + PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ 1.5684 + 1.5685 + if (ss->serverCerts[exchKeyType].serverKeyPair) { 1.5686 + svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; 1.5687 + } 1.5688 + if (svrPubKey == NULL) { 1.5689 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.5690 + goto loser; 1.5691 + } 1.5692 + wrappedKey.type = siBuffer; 1.5693 + wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); 1.5694 + wrappedKey.data = wswk.wrappedSymmetricWrappingkey; 1.5695 + 1.5696 + PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); 1.5697 + if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) 1.5698 + goto loser; 1.5699 + 1.5700 + /* wrap symmetric wrapping key in server's public key. */ 1.5701 + switch (exchKeyType) { 1.5702 + case kt_rsa: 1.5703 + asymWrapMechanism = CKM_RSA_PKCS; 1.5704 + rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, 1.5705 + unwrappedWrappingKey, &wrappedKey); 1.5706 + break; 1.5707 + 1.5708 +#ifndef NSS_DISABLE_ECC 1.5709 + case kt_ecdh: 1.5710 + /* 1.5711 + * We generate an ephemeral EC key pair. Perform an ECDH 1.5712 + * computation involving this ephemeral EC public key and 1.5713 + * the SSL server's (long-term) EC private key. The resulting 1.5714 + * shared secret is treated in the same way as Fortezza's Ks, 1.5715 + * i.e., it is used to wrap the wrapping key. To facilitate 1.5716 + * unwrapping in ssl_UnwrapWrappingKey, we also store all 1.5717 + * relevant info about the ephemeral EC public key in 1.5718 + * wswk.wrappedSymmetricWrappingkey and lay it out as 1.5719 + * described in the ECCWrappedKeyInfo structure. 1.5720 + */ 1.5721 + PORT_Assert(svrPubKey->keyType == ecKey); 1.5722 + if (svrPubKey->keyType != ecKey) { 1.5723 + /* something is wrong in sslsecur.c if this isn't an ecKey */ 1.5724 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.5725 + rv = SECFailure; 1.5726 + goto ec_cleanup; 1.5727 + } 1.5728 + 1.5729 + privWrapKey = SECKEY_CreateECPrivateKey( 1.5730 + &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL); 1.5731 + if ((privWrapKey == NULL) || (pubWrapKey == NULL)) { 1.5732 + rv = SECFailure; 1.5733 + goto ec_cleanup; 1.5734 + } 1.5735 + 1.5736 + /* Set the key size in bits */ 1.5737 + if (pubWrapKey->u.ec.size == 0) { 1.5738 + pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey); 1.5739 + } 1.5740 + 1.5741 + PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len + 1.5742 + pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN); 1.5743 + if (pubWrapKey->u.ec.DEREncodedParams.len + 1.5744 + pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) { 1.5745 + PORT_SetError(SEC_ERROR_INVALID_KEY); 1.5746 + rv = SECFailure; 1.5747 + goto ec_cleanup; 1.5748 + } 1.5749 + 1.5750 + /* Derive Ks using ECDH */ 1.5751 + Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL, 1.5752 + NULL, CKM_ECDH1_DERIVE, masterWrapMech, 1.5753 + CKA_DERIVE, 0, CKD_NULL, NULL, NULL); 1.5754 + if (Ks == NULL) { 1.5755 + rv = SECFailure; 1.5756 + goto ec_cleanup; 1.5757 + } 1.5758 + 1.5759 + ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey); 1.5760 + ecWrapped->size = pubWrapKey->u.ec.size; 1.5761 + ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len; 1.5762 + PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data, 1.5763 + pubWrapKey->u.ec.DEREncodedParams.len); 1.5764 + 1.5765 + ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len; 1.5766 + PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen, 1.5767 + pubWrapKey->u.ec.publicValue.data, 1.5768 + pubWrapKey->u.ec.publicValue.len); 1.5769 + 1.5770 + wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN - 1.5771 + (ecWrapped->encodedParamLen + ecWrapped->pubValueLen); 1.5772 + wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen + 1.5773 + ecWrapped->pubValueLen; 1.5774 + 1.5775 + /* wrap symmetricWrapping key with the local Ks */ 1.5776 + rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks, 1.5777 + unwrappedWrappingKey, &wrappedKey); 1.5778 + 1.5779 + if (rv != SECSuccess) { 1.5780 + goto ec_cleanup; 1.5781 + } 1.5782 + 1.5783 + /* Write down the length of wrapped key in the buffer 1.5784 + * wswk.wrappedSymmetricWrappingkey at the appropriate offset 1.5785 + */ 1.5786 + ecWrapped->wrappedKeyLen = wrappedKey.len; 1.5787 + 1.5788 +ec_cleanup: 1.5789 + if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey); 1.5790 + if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey); 1.5791 + if (Ks) PK11_FreeSymKey(Ks); 1.5792 + asymWrapMechanism = masterWrapMech; 1.5793 + break; 1.5794 +#endif /* NSS_DISABLE_ECC */ 1.5795 + 1.5796 + default: 1.5797 + rv = SECFailure; 1.5798 + break; 1.5799 + } 1.5800 + 1.5801 + if (rv != SECSuccess) { 1.5802 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.5803 + goto loser; 1.5804 + } 1.5805 + 1.5806 + PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); 1.5807 + 1.5808 + wswk.symWrapMechanism = masterWrapMech; 1.5809 + wswk.symWrapMechIndex = symWrapMechIndex; 1.5810 + wswk.asymWrapMechanism = asymWrapMechanism; 1.5811 + wswk.exchKeyType = exchKeyType; 1.5812 + wswk.wrappedSymKeyLen = wrappedKey.len; 1.5813 + 1.5814 + /* put it on disk. */ 1.5815 + /* If the wrapping key for this KEA type has already been set, 1.5816 + * then abandon the value we just computed and 1.5817 + * use the one we got from the disk. 1.5818 + */ 1.5819 + if (ssl_SetWrappingKey(&wswk)) { 1.5820 + /* somebody beat us to it. The original contents of our wswk 1.5821 + * has been replaced with the content on disk. Now, discard 1.5822 + * the key we just created and unwrap this new one. 1.5823 + */ 1.5824 + PK11_FreeSymKey(unwrappedWrappingKey); 1.5825 + 1.5826 + unwrappedWrappingKey = 1.5827 + ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, 1.5828 + masterWrapMech, pwArg); 1.5829 + } 1.5830 + 1.5831 +install: 1.5832 + if (unwrappedWrappingKey) { 1.5833 + *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); 1.5834 + } 1.5835 + 1.5836 +loser: 1.5837 +done: 1.5838 + PZ_Unlock(symWrapKeysLock); 1.5839 + return unwrappedWrappingKey; 1.5840 +} 1.5841 + 1.5842 +/* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2| 1.5843 + * bytes to |out|. */ 1.5844 +static void 1.5845 +hexEncode(char *out, const unsigned char *in, unsigned int length) 1.5846 +{ 1.5847 + static const char hextable[] = "0123456789abcdef"; 1.5848 + unsigned int i; 1.5849 + 1.5850 + for (i = 0; i < length; i++) { 1.5851 + *(out++) = hextable[in[i] >> 4]; 1.5852 + *(out++) = hextable[in[i] & 15]; 1.5853 + } 1.5854 +} 1.5855 + 1.5856 +/* Called from ssl3_SendClientKeyExchange(). */ 1.5857 +/* Presently, this always uses PKCS11. There is no bypass for this. */ 1.5858 +static SECStatus 1.5859 +sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) 1.5860 +{ 1.5861 + PK11SymKey * pms = NULL; 1.5862 + SECStatus rv = SECFailure; 1.5863 + SECItem enc_pms = {siBuffer, NULL, 0}; 1.5864 + PRBool isTLS; 1.5865 + 1.5866 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.5867 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.5868 + 1.5869 + /* Generate the pre-master secret ... */ 1.5870 + ssl_GetSpecWriteLock(ss); 1.5871 + isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 1.5872 + 1.5873 + pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); 1.5874 + ssl_ReleaseSpecWriteLock(ss); 1.5875 + if (pms == NULL) { 1.5876 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.5877 + goto loser; 1.5878 + } 1.5879 + 1.5880 + /* Get the wrapped (encrypted) pre-master secret, enc_pms */ 1.5881 + enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); 1.5882 + enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len); 1.5883 + if (enc_pms.data == NULL) { 1.5884 + goto loser; /* err set by PORT_Alloc */ 1.5885 + } 1.5886 + 1.5887 + /* wrap pre-master secret in server's public key. */ 1.5888 + rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms); 1.5889 + if (rv != SECSuccess) { 1.5890 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.5891 + goto loser; 1.5892 + } 1.5893 + 1.5894 + if (ssl_keylog_iob) { 1.5895 + SECStatus extractRV = PK11_ExtractKeyValue(pms); 1.5896 + if (extractRV == SECSuccess) { 1.5897 + SECItem * keyData = PK11_GetKeyData(pms); 1.5898 + if (keyData && keyData->data && keyData->len) { 1.5899 +#ifdef TRACE 1.5900 + if (ssl_trace >= 100) { 1.5901 + ssl_PrintBuf(ss, "Pre-Master Secret", 1.5902 + keyData->data, keyData->len); 1.5903 + } 1.5904 +#endif 1.5905 + if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { 1.5906 + /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ 1.5907 + 1.5908 + /* There could be multiple, concurrent writers to the 1.5909 + * keylog, so we have to do everything in a single call to 1.5910 + * fwrite. */ 1.5911 + char buf[4 + 8*2 + 1 + 48*2 + 1]; 1.5912 + 1.5913 + strcpy(buf, "RSA "); 1.5914 + hexEncode(buf + 4, enc_pms.data, 8); 1.5915 + buf[20] = ' '; 1.5916 + hexEncode(buf + 21, keyData->data, 48); 1.5917 + buf[sizeof(buf) - 1] = '\n'; 1.5918 + 1.5919 + fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); 1.5920 + fflush(ssl_keylog_iob); 1.5921 + } 1.5922 + } 1.5923 + } 1.5924 + } 1.5925 + 1.5926 + rv = ssl3_InitPendingCipherSpec(ss, pms); 1.5927 + PK11_FreeSymKey(pms); pms = NULL; 1.5928 + 1.5929 + if (rv != SECSuccess) { 1.5930 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.5931 + goto loser; 1.5932 + } 1.5933 + 1.5934 + rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 1.5935 + isTLS ? enc_pms.len + 2 : enc_pms.len); 1.5936 + if (rv != SECSuccess) { 1.5937 + goto loser; /* err set by ssl3_AppendHandshake* */ 1.5938 + } 1.5939 + if (isTLS) { 1.5940 + rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); 1.5941 + } else { 1.5942 + rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); 1.5943 + } 1.5944 + if (rv != SECSuccess) { 1.5945 + goto loser; /* err set by ssl3_AppendHandshake* */ 1.5946 + } 1.5947 + 1.5948 + rv = SECSuccess; 1.5949 + 1.5950 +loser: 1.5951 + if (enc_pms.data != NULL) { 1.5952 + PORT_Free(enc_pms.data); 1.5953 + } 1.5954 + if (pms != NULL) { 1.5955 + PK11_FreeSymKey(pms); 1.5956 + } 1.5957 + return rv; 1.5958 +} 1.5959 + 1.5960 +/* Called from ssl3_SendClientKeyExchange(). */ 1.5961 +/* Presently, this always uses PKCS11. There is no bypass for this. */ 1.5962 +static SECStatus 1.5963 +sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) 1.5964 +{ 1.5965 + PK11SymKey * pms = NULL; 1.5966 + SECStatus rv = SECFailure; 1.5967 + PRBool isTLS; 1.5968 + CK_MECHANISM_TYPE target; 1.5969 + 1.5970 + SECKEYDHParams dhParam; /* DH parameters */ 1.5971 + SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ 1.5972 + SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ 1.5973 + 1.5974 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.5975 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.5976 + 1.5977 + isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 1.5978 + 1.5979 + /* Copy DH parameters from server key */ 1.5980 + 1.5981 + if (svrPubKey->keyType != dhKey) { 1.5982 + PORT_SetError(SEC_ERROR_BAD_KEY); 1.5983 + goto loser; 1.5984 + } 1.5985 + dhParam.prime.data = svrPubKey->u.dh.prime.data; 1.5986 + dhParam.prime.len = svrPubKey->u.dh.prime.len; 1.5987 + dhParam.base.data = svrPubKey->u.dh.base.data; 1.5988 + dhParam.base.len = svrPubKey->u.dh.base.len; 1.5989 + 1.5990 + /* Generate ephemeral DH keypair */ 1.5991 + privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); 1.5992 + if (!privKey || !pubKey) { 1.5993 + ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); 1.5994 + rv = SECFailure; 1.5995 + goto loser; 1.5996 + } 1.5997 + PRINT_BUF(50, (ss, "DH public value:", 1.5998 + pubKey->u.dh.publicValue.data, 1.5999 + pubKey->u.dh.publicValue.len)); 1.6000 + 1.6001 + if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH; 1.6002 + else target = CKM_SSL3_MASTER_KEY_DERIVE_DH; 1.6003 + 1.6004 + /* Determine the PMS */ 1.6005 + 1.6006 + pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL, 1.6007 + CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); 1.6008 + 1.6009 + if (pms == NULL) { 1.6010 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.6011 + goto loser; 1.6012 + } 1.6013 + 1.6014 + SECKEY_DestroyPrivateKey(privKey); 1.6015 + privKey = NULL; 1.6016 + 1.6017 + rv = ssl3_InitPendingCipherSpec(ss, pms); 1.6018 + PK11_FreeSymKey(pms); pms = NULL; 1.6019 + 1.6020 + if (rv != SECSuccess) { 1.6021 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.6022 + goto loser; 1.6023 + } 1.6024 + 1.6025 + rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, 1.6026 + pubKey->u.dh.publicValue.len + 2); 1.6027 + if (rv != SECSuccess) { 1.6028 + goto loser; /* err set by ssl3_AppendHandshake* */ 1.6029 + } 1.6030 + rv = ssl3_AppendHandshakeVariable(ss, 1.6031 + pubKey->u.dh.publicValue.data, 1.6032 + pubKey->u.dh.publicValue.len, 2); 1.6033 + SECKEY_DestroyPublicKey(pubKey); 1.6034 + pubKey = NULL; 1.6035 + 1.6036 + if (rv != SECSuccess) { 1.6037 + goto loser; /* err set by ssl3_AppendHandshake* */ 1.6038 + } 1.6039 + 1.6040 + rv = SECSuccess; 1.6041 + 1.6042 + 1.6043 +loser: 1.6044 + 1.6045 + if(pms) PK11_FreeSymKey(pms); 1.6046 + if(privKey) SECKEY_DestroyPrivateKey(privKey); 1.6047 + if(pubKey) SECKEY_DestroyPublicKey(pubKey); 1.6048 + return rv; 1.6049 +} 1.6050 + 1.6051 + 1.6052 + 1.6053 + 1.6054 + 1.6055 +/* Called from ssl3_HandleServerHelloDone(). */ 1.6056 +static SECStatus 1.6057 +ssl3_SendClientKeyExchange(sslSocket *ss) 1.6058 +{ 1.6059 + SECKEYPublicKey * serverKey = NULL; 1.6060 + SECStatus rv = SECFailure; 1.6061 + PRBool isTLS; 1.6062 + 1.6063 + SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", 1.6064 + SSL_GETPID(), ss->fd)); 1.6065 + 1.6066 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.6067 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.6068 + 1.6069 + if (ss->sec.peerKey == NULL) { 1.6070 + serverKey = CERT_ExtractPublicKey(ss->sec.peerCert); 1.6071 + if (serverKey == NULL) { 1.6072 + ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 1.6073 + return SECFailure; 1.6074 + } 1.6075 + } else { 1.6076 + serverKey = ss->sec.peerKey; 1.6077 + ss->sec.peerKey = NULL; /* we're done with it now */ 1.6078 + } 1.6079 + 1.6080 + isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 1.6081 + /* enforce limits on kea key sizes. */ 1.6082 + if (ss->ssl3.hs.kea_def->is_limited) { 1.6083 + int keyLen = SECKEY_PublicKeyStrength(serverKey); /* bytes */ 1.6084 + 1.6085 + if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) { 1.6086 + if (isTLS) 1.6087 + (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); 1.6088 + else 1.6089 + (void)ssl3_HandshakeFailure(ss); 1.6090 + PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); 1.6091 + goto loser; 1.6092 + } 1.6093 + } 1.6094 + 1.6095 + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; 1.6096 + ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); 1.6097 + 1.6098 + switch (ss->ssl3.hs.kea_def->exchKeyType) { 1.6099 + case kt_rsa: 1.6100 + rv = sendRSAClientKeyExchange(ss, serverKey); 1.6101 + break; 1.6102 + 1.6103 + case kt_dh: 1.6104 + rv = sendDHClientKeyExchange(ss, serverKey); 1.6105 + break; 1.6106 + 1.6107 +#ifndef NSS_DISABLE_ECC 1.6108 + case kt_ecdh: 1.6109 + rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); 1.6110 + break; 1.6111 +#endif /* NSS_DISABLE_ECC */ 1.6112 + 1.6113 + default: 1.6114 + /* got an unknown or unsupported Key Exchange Algorithm. */ 1.6115 + SEND_ALERT 1.6116 + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 1.6117 + break; 1.6118 + } 1.6119 + 1.6120 + SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange", 1.6121 + SSL_GETPID(), ss->fd)); 1.6122 + 1.6123 +loser: 1.6124 + if (serverKey) 1.6125 + SECKEY_DestroyPublicKey(serverKey); 1.6126 + return rv; /* err code already set. */ 1.6127 +} 1.6128 + 1.6129 +/* Called from ssl3_HandleServerHelloDone(). */ 1.6130 +static SECStatus 1.6131 +ssl3_SendCertificateVerify(sslSocket *ss) 1.6132 +{ 1.6133 + SECStatus rv = SECFailure; 1.6134 + PRBool isTLS; 1.6135 + PRBool isTLS12; 1.6136 + SECItem buf = {siBuffer, NULL, 0}; 1.6137 + SSL3Hashes hashes; 1.6138 + KeyType keyType; 1.6139 + unsigned int len; 1.6140 + SSL3SignatureAndHashAlgorithm sigAndHash; 1.6141 + 1.6142 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.6143 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.6144 + 1.6145 + SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake", 1.6146 + SSL_GETPID(), ss->fd)); 1.6147 + 1.6148 + ssl_GetSpecReadLock(ss); 1.6149 + if (ss->ssl3.hs.hashType == handshake_hash_single && 1.6150 + ss->ssl3.hs.backupHash) { 1.6151 + rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); 1.6152 + PORT_Assert(!ss->ssl3.hs.backupHash); 1.6153 + } else { 1.6154 + rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); 1.6155 + } 1.6156 + ssl_ReleaseSpecReadLock(ss); 1.6157 + if (rv != SECSuccess) { 1.6158 + goto done; /* err code was set by ssl3_ComputeHandshakeHashes */ 1.6159 + } 1.6160 + 1.6161 + isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 1.6162 + isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 1.6163 + keyType = ss->ssl3.clientPrivateKey->keyType; 1.6164 + rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS); 1.6165 + if (rv == SECSuccess) { 1.6166 + PK11SlotInfo * slot; 1.6167 + sslSessionID * sid = ss->sec.ci.sid; 1.6168 + 1.6169 + /* Remember the info about the slot that did the signing. 1.6170 + ** Later, when doing an SSL restart handshake, verify this. 1.6171 + ** These calls are mere accessors, and can't fail. 1.6172 + */ 1.6173 + slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey); 1.6174 + sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot); 1.6175 + sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot); 1.6176 + sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot); 1.6177 + sid->u.ssl3.clAuthValid = PR_TRUE; 1.6178 + PK11_FreeSlot(slot); 1.6179 + } 1.6180 + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 1.6181 + ss->ssl3.clientPrivateKey = NULL; 1.6182 + if (rv != SECSuccess) { 1.6183 + goto done; /* err code was set by ssl3_SignHashes */ 1.6184 + } 1.6185 + 1.6186 + len = buf.len + 2 + (isTLS12 ? 2 : 0); 1.6187 + 1.6188 + rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len); 1.6189 + if (rv != SECSuccess) { 1.6190 + goto done; /* error code set by AppendHandshake */ 1.6191 + } 1.6192 + if (isTLS12) { 1.6193 + rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, 1.6194 + &sigAndHash.sigAlg); 1.6195 + if (rv != SECSuccess) { 1.6196 + goto done; 1.6197 + } 1.6198 + sigAndHash.hashAlg = hashes.hashAlg; 1.6199 + 1.6200 + rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); 1.6201 + if (rv != SECSuccess) { 1.6202 + goto done; /* err set by AppendHandshake. */ 1.6203 + } 1.6204 + } 1.6205 + rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2); 1.6206 + if (rv != SECSuccess) { 1.6207 + goto done; /* error code set by AppendHandshake */ 1.6208 + } 1.6209 + 1.6210 +done: 1.6211 + if (buf.data) 1.6212 + PORT_Free(buf.data); 1.6213 + return rv; 1.6214 +} 1.6215 + 1.6216 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.6217 + * ssl3 ServerHello message. 1.6218 + * Caller must hold Handshake and RecvBuf locks. 1.6219 + */ 1.6220 +static SECStatus 1.6221 +ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.6222 +{ 1.6223 + sslSessionID *sid = ss->sec.ci.sid; 1.6224 + PRInt32 temp; /* allow for consume number failure */ 1.6225 + PRBool suite_found = PR_FALSE; 1.6226 + int i; 1.6227 + int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; 1.6228 + SECStatus rv; 1.6229 + SECItem sidBytes = {siBuffer, NULL, 0}; 1.6230 + PRBool sid_match; 1.6231 + PRBool isTLS = PR_FALSE; 1.6232 + SSL3AlertDescription desc = illegal_parameter; 1.6233 + SSL3ProtocolVersion version; 1.6234 + 1.6235 + SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake", 1.6236 + SSL_GETPID(), ss->fd)); 1.6237 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.6238 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.6239 + PORT_Assert( ss->ssl3.initialized ); 1.6240 + 1.6241 + if (ss->ssl3.hs.ws != wait_server_hello) { 1.6242 + errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; 1.6243 + desc = unexpected_message; 1.6244 + goto alert_loser; 1.6245 + } 1.6246 + 1.6247 + /* clean up anything left from previous handshake. */ 1.6248 + if (ss->ssl3.clientCertChain != NULL) { 1.6249 + CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 1.6250 + ss->ssl3.clientCertChain = NULL; 1.6251 + } 1.6252 + if (ss->ssl3.clientCertificate != NULL) { 1.6253 + CERT_DestroyCertificate(ss->ssl3.clientCertificate); 1.6254 + ss->ssl3.clientCertificate = NULL; 1.6255 + } 1.6256 + if (ss->ssl3.clientPrivateKey != NULL) { 1.6257 + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 1.6258 + ss->ssl3.clientPrivateKey = NULL; 1.6259 + } 1.6260 + 1.6261 + temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 1.6262 + if (temp < 0) { 1.6263 + goto loser; /* alert has been sent */ 1.6264 + } 1.6265 + version = (SSL3ProtocolVersion)temp; 1.6266 + 1.6267 + if (IS_DTLS(ss)) { 1.6268 + /* RFC 4347 required that you verify that the server versions 1.6269 + * match (Section 4.2.1) in the HelloVerifyRequest and the 1.6270 + * ServerHello. 1.6271 + * 1.6272 + * RFC 6347 suggests (SHOULD) that servers always use 1.0 1.6273 + * in HelloVerifyRequest and allows the versions not to match, 1.6274 + * especially when 1.2 is being negotiated. 1.6275 + * 1.6276 + * Therefore we do not check for matching here. 1.6277 + */ 1.6278 + version = dtls_DTLSVersionToTLSVersion(version); 1.6279 + if (version == 0) { /* Insane version number */ 1.6280 + goto alert_loser; 1.6281 + } 1.6282 + } 1.6283 + 1.6284 + rv = ssl3_NegotiateVersion(ss, version, PR_FALSE); 1.6285 + if (rv != SECSuccess) { 1.6286 + desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 1.6287 + : handshake_failure; 1.6288 + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 1.6289 + goto alert_loser; 1.6290 + } 1.6291 + isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); 1.6292 + 1.6293 + rv = ssl3_InitHandshakeHashes(ss); 1.6294 + if (rv != SECSuccess) { 1.6295 + desc = internal_error; 1.6296 + errCode = PORT_GetError(); 1.6297 + goto alert_loser; 1.6298 + } 1.6299 + 1.6300 + rv = ssl3_ConsumeHandshake( 1.6301 + ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); 1.6302 + if (rv != SECSuccess) { 1.6303 + goto loser; /* alert has been sent */ 1.6304 + } 1.6305 + 1.6306 + rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); 1.6307 + if (rv != SECSuccess) { 1.6308 + goto loser; /* alert has been sent */ 1.6309 + } 1.6310 + if (sidBytes.len > SSL3_SESSIONID_BYTES) { 1.6311 + if (isTLS) 1.6312 + desc = decode_error; 1.6313 + goto alert_loser; /* malformed. */ 1.6314 + } 1.6315 + 1.6316 + /* find selected cipher suite in our list. */ 1.6317 + temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 1.6318 + if (temp < 0) { 1.6319 + goto loser; /* alert has been sent */ 1.6320 + } 1.6321 + ssl3_config_match_init(ss); 1.6322 + for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 1.6323 + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 1.6324 + if (temp == suite->cipher_suite) { 1.6325 + SSLVersionRange vrange = {ss->version, ss->version}; 1.6326 + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { 1.6327 + /* config_match already checks whether the cipher suite is 1.6328 + * acceptable for the version, but the check is repeated here 1.6329 + * in order to give a more precise error code. */ 1.6330 + if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) { 1.6331 + desc = handshake_failure; 1.6332 + errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; 1.6333 + goto alert_loser; 1.6334 + } 1.6335 + 1.6336 + break; /* failure */ 1.6337 + } 1.6338 + 1.6339 + suite_found = PR_TRUE; 1.6340 + break; /* success */ 1.6341 + } 1.6342 + } 1.6343 + if (!suite_found) { 1.6344 + desc = handshake_failure; 1.6345 + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 1.6346 + goto alert_loser; 1.6347 + } 1.6348 + ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp; 1.6349 + ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); 1.6350 + PORT_Assert(ss->ssl3.hs.suite_def); 1.6351 + if (!ss->ssl3.hs.suite_def) { 1.6352 + PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE); 1.6353 + goto loser; /* we don't send alerts for our screw-ups. */ 1.6354 + } 1.6355 + 1.6356 + /* find selected compression method in our list. */ 1.6357 + temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); 1.6358 + if (temp < 0) { 1.6359 + goto loser; /* alert has been sent */ 1.6360 + } 1.6361 + suite_found = PR_FALSE; 1.6362 + for (i = 0; i < compressionMethodsCount; i++) { 1.6363 + if (temp == compressions[i]) { 1.6364 + if (!compressionEnabled(ss, compressions[i])) { 1.6365 + break; /* failure */ 1.6366 + } 1.6367 + suite_found = PR_TRUE; 1.6368 + break; /* success */ 1.6369 + } 1.6370 + } 1.6371 + if (!suite_found) { 1.6372 + desc = handshake_failure; 1.6373 + errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; 1.6374 + goto alert_loser; 1.6375 + } 1.6376 + ss->ssl3.hs.compression = (SSLCompressionMethod)temp; 1.6377 + 1.6378 + /* Note that if !isTLS and the extra stuff is not extensions, we 1.6379 + * do NOT goto alert_loser. 1.6380 + * There are some old SSL 3.0 implementations that do send stuff 1.6381 + * after the end of the server hello, and we deliberately ignore 1.6382 + * such stuff in the interest of maximal interoperability (being 1.6383 + * "generous in what you accept"). 1.6384 + * Update: Starting in NSS 3.12.6, we handle the renegotiation_info 1.6385 + * extension in SSL 3.0. 1.6386 + */ 1.6387 + if (length != 0) { 1.6388 + SECItem extensions; 1.6389 + rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); 1.6390 + if (rv != SECSuccess || length != 0) { 1.6391 + if (isTLS) 1.6392 + goto alert_loser; 1.6393 + } else { 1.6394 + rv = ssl3_HandleHelloExtensions(ss, &extensions.data, 1.6395 + &extensions.len); 1.6396 + if (rv != SECSuccess) 1.6397 + goto alert_loser; 1.6398 + } 1.6399 + } 1.6400 + if ((ss->opt.requireSafeNegotiation || 1.6401 + (ss->firstHsDone && (ss->peerRequestedProtection || 1.6402 + ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) && 1.6403 + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 1.6404 + desc = handshake_failure; 1.6405 + errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED 1.6406 + : SSL_ERROR_UNSAFE_NEGOTIATION; 1.6407 + goto alert_loser; 1.6408 + } 1.6409 + 1.6410 + /* Any errors after this point are not "malformed" errors. */ 1.6411 + desc = handshake_failure; 1.6412 + 1.6413 + /* we need to call ssl3_SetupPendingCipherSpec here so we can check the 1.6414 + * key exchange algorithm. */ 1.6415 + rv = ssl3_SetupPendingCipherSpec(ss); 1.6416 + if (rv != SECSuccess) { 1.6417 + goto alert_loser; /* error code is set. */ 1.6418 + } 1.6419 + 1.6420 + /* We may or may not have sent a session id, we may get one back or 1.6421 + * not and if so it may match the one we sent. 1.6422 + * Attempt to restore the master secret to see if this is so... 1.6423 + * Don't consider failure to find a matching SID an error. 1.6424 + */ 1.6425 + sid_match = (PRBool)(sidBytes.len > 0 && 1.6426 + sidBytes.len == sid->u.ssl3.sessionIDLength && 1.6427 + !PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len)); 1.6428 + 1.6429 + if (sid_match && 1.6430 + sid->version == ss->version && 1.6431 + sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do { 1.6432 + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; 1.6433 + 1.6434 + SECItem wrappedMS; /* wrapped master secret. */ 1.6435 + 1.6436 + ss->sec.authAlgorithm = sid->authAlgorithm; 1.6437 + ss->sec.authKeyBits = sid->authKeyBits; 1.6438 + ss->sec.keaType = sid->keaType; 1.6439 + ss->sec.keaKeyBits = sid->keaKeyBits; 1.6440 + 1.6441 + /* 3 cases here: 1.6442 + * a) key is wrapped (implies using PKCS11) 1.6443 + * b) key is unwrapped, but we're still using PKCS11 1.6444 + * c) key is unwrapped, and we're bypassing PKCS11. 1.6445 + */ 1.6446 + if (sid->u.ssl3.keys.msIsWrapped) { 1.6447 + PK11SlotInfo *slot; 1.6448 + PK11SymKey * wrapKey; /* wrapping key */ 1.6449 + CK_FLAGS keyFlags = 0; 1.6450 + 1.6451 +#ifndef NO_PKCS11_BYPASS 1.6452 + if (ss->opt.bypassPKCS11) { 1.6453 + /* we cannot restart a non-bypass session in a 1.6454 + ** bypass socket. 1.6455 + */ 1.6456 + break; 1.6457 + } 1.6458 +#endif 1.6459 + /* unwrap master secret with PKCS11 */ 1.6460 + slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, 1.6461 + sid->u.ssl3.masterSlotID); 1.6462 + if (slot == NULL) { 1.6463 + break; /* not considered an error. */ 1.6464 + } 1.6465 + if (!PK11_IsPresent(slot)) { 1.6466 + PK11_FreeSlot(slot); 1.6467 + break; /* not considered an error. */ 1.6468 + } 1.6469 + wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, 1.6470 + sid->u.ssl3.masterWrapMech, 1.6471 + sid->u.ssl3.masterWrapSeries, 1.6472 + ss->pkcs11PinArg); 1.6473 + PK11_FreeSlot(slot); 1.6474 + if (wrapKey == NULL) { 1.6475 + break; /* not considered an error. */ 1.6476 + } 1.6477 + 1.6478 + if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ 1.6479 + keyFlags = CKF_SIGN | CKF_VERIFY; 1.6480 + } 1.6481 + 1.6482 + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 1.6483 + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 1.6484 + pwSpec->master_secret = 1.6485 + PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 1.6486 + NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, 1.6487 + CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); 1.6488 + errCode = PORT_GetError(); 1.6489 + PK11_FreeSymKey(wrapKey); 1.6490 + if (pwSpec->master_secret == NULL) { 1.6491 + break; /* errorCode set just after call to UnwrapSymKey. */ 1.6492 + } 1.6493 +#ifndef NO_PKCS11_BYPASS 1.6494 + } else if (ss->opt.bypassPKCS11) { 1.6495 + /* MS is not wrapped */ 1.6496 + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 1.6497 + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 1.6498 + memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); 1.6499 + pwSpec->msItem.data = pwSpec->raw_master_secret; 1.6500 + pwSpec->msItem.len = wrappedMS.len; 1.6501 +#endif 1.6502 + } else { 1.6503 + /* We CAN restart a bypass session in a non-bypass socket. */ 1.6504 + /* need to import the raw master secret to session object */ 1.6505 + PK11SlotInfo *slot = PK11_GetInternalSlot(); 1.6506 + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 1.6507 + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 1.6508 + pwSpec->master_secret = 1.6509 + PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 1.6510 + PK11_OriginUnwrap, CKA_ENCRYPT, 1.6511 + &wrappedMS, NULL); 1.6512 + PK11_FreeSlot(slot); 1.6513 + if (pwSpec->master_secret == NULL) { 1.6514 + break; 1.6515 + } 1.6516 + } 1.6517 + 1.6518 + /* Got a Match */ 1.6519 + SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits ); 1.6520 + 1.6521 + /* If we sent a session ticket, then this is a stateless resume. */ 1.6522 + if (ss->xtnData.sentSessionTicketInClientHello) 1.6523 + SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes ); 1.6524 + 1.6525 + if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) 1.6526 + ss->ssl3.hs.ws = wait_new_session_ticket; 1.6527 + else 1.6528 + ss->ssl3.hs.ws = wait_change_cipher; 1.6529 + 1.6530 + ss->ssl3.hs.isResuming = PR_TRUE; 1.6531 + 1.6532 + /* copy the peer cert from the SID */ 1.6533 + if (sid->peerCert != NULL) { 1.6534 + ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); 1.6535 + } 1.6536 + 1.6537 + /* NULL value for PMS signifies re-use of the old MS */ 1.6538 + rv = ssl3_InitPendingCipherSpec(ss, NULL); 1.6539 + if (rv != SECSuccess) { 1.6540 + goto alert_loser; /* err code was set */ 1.6541 + } 1.6542 + return SECSuccess; 1.6543 + } while (0); 1.6544 + 1.6545 + if (sid_match) 1.6546 + SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok ); 1.6547 + else 1.6548 + SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses ); 1.6549 + 1.6550 + /* throw the old one away */ 1.6551 + sid->u.ssl3.keys.resumable = PR_FALSE; 1.6552 + if (ss->sec.uncache) 1.6553 + (*ss->sec.uncache)(sid); 1.6554 + ssl_FreeSID(sid); 1.6555 + 1.6556 + /* get a new sid */ 1.6557 + ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE); 1.6558 + if (sid == NULL) { 1.6559 + goto alert_loser; /* memory error is set. */ 1.6560 + } 1.6561 + 1.6562 + sid->version = ss->version; 1.6563 + sid->u.ssl3.sessionIDLength = sidBytes.len; 1.6564 + PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len); 1.6565 + 1.6566 + ss->ssl3.hs.isResuming = PR_FALSE; 1.6567 + ss->ssl3.hs.ws = wait_server_cert; 1.6568 + return SECSuccess; 1.6569 + 1.6570 +alert_loser: 1.6571 + (void)SSL3_SendAlert(ss, alert_fatal, desc); 1.6572 + 1.6573 +loser: 1.6574 + errCode = ssl_MapLowLevelError(errCode); 1.6575 + return SECFailure; 1.6576 +} 1.6577 + 1.6578 +/* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned, 1.6579 + * big-endian integer is > 1 */ 1.6580 +static PRBool 1.6581 +ssl3_BigIntGreaterThanOne(const SECItem* mpint) { 1.6582 + unsigned char firstNonZeroByte = 0; 1.6583 + unsigned int i; 1.6584 + 1.6585 + for (i = 0; i < mpint->len; i++) { 1.6586 + if (mpint->data[i]) { 1.6587 + firstNonZeroByte = mpint->data[i]; 1.6588 + break; 1.6589 + } 1.6590 + } 1.6591 + 1.6592 + if (firstNonZeroByte == 0) 1.6593 + return PR_FALSE; 1.6594 + if (firstNonZeroByte > 1) 1.6595 + return PR_TRUE; 1.6596 + 1.6597 + /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte 1.6598 + * is followed by another byte. */ 1.6599 + return (i < mpint->len - 1); 1.6600 +} 1.6601 + 1.6602 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.6603 + * ssl3 ServerKeyExchange message. 1.6604 + * Caller must hold Handshake and RecvBuf locks. 1.6605 + */ 1.6606 +static SECStatus 1.6607 +ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.6608 +{ 1.6609 + PLArenaPool * arena = NULL; 1.6610 + SECKEYPublicKey *peerKey = NULL; 1.6611 + PRBool isTLS, isTLS12; 1.6612 + SECStatus rv; 1.6613 + int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; 1.6614 + SSL3AlertDescription desc = illegal_parameter; 1.6615 + SSL3Hashes hashes; 1.6616 + SECItem signature = {siBuffer, NULL, 0}; 1.6617 + SSL3SignatureAndHashAlgorithm sigAndHash; 1.6618 + 1.6619 + sigAndHash.hashAlg = SEC_OID_UNKNOWN; 1.6620 + 1.6621 + SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake", 1.6622 + SSL_GETPID(), ss->fd)); 1.6623 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.6624 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.6625 + 1.6626 + if (ss->ssl3.hs.ws != wait_server_key && 1.6627 + ss->ssl3.hs.ws != wait_server_cert) { 1.6628 + errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; 1.6629 + desc = unexpected_message; 1.6630 + goto alert_loser; 1.6631 + } 1.6632 + if (ss->sec.peerCert == NULL) { 1.6633 + errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; 1.6634 + desc = unexpected_message; 1.6635 + goto alert_loser; 1.6636 + } 1.6637 + 1.6638 + isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 1.6639 + isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 1.6640 + 1.6641 + switch (ss->ssl3.hs.kea_def->exchKeyType) { 1.6642 + 1.6643 + case kt_rsa: { 1.6644 + SECItem modulus = {siBuffer, NULL, 0}; 1.6645 + SECItem exponent = {siBuffer, NULL, 0}; 1.6646 + 1.6647 + rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); 1.6648 + if (rv != SECSuccess) { 1.6649 + goto loser; /* malformed. */ 1.6650 + } 1.6651 + rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length); 1.6652 + if (rv != SECSuccess) { 1.6653 + goto loser; /* malformed. */ 1.6654 + } 1.6655 + if (isTLS12) { 1.6656 + rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, 1.6657 + &sigAndHash); 1.6658 + if (rv != SECSuccess) { 1.6659 + goto loser; /* malformed or unsupported. */ 1.6660 + } 1.6661 + rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( 1.6662 + &sigAndHash, ss->sec.peerCert); 1.6663 + if (rv != SECSuccess) { 1.6664 + goto loser; 1.6665 + } 1.6666 + } 1.6667 + rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); 1.6668 + if (rv != SECSuccess) { 1.6669 + goto loser; /* malformed. */ 1.6670 + } 1.6671 + if (length != 0) { 1.6672 + if (isTLS) 1.6673 + desc = decode_error; 1.6674 + goto alert_loser; /* malformed. */ 1.6675 + } 1.6676 + 1.6677 + /* failures after this point are not malformed handshakes. */ 1.6678 + /* TLS: send decrypt_error if signature failed. */ 1.6679 + desc = isTLS ? decrypt_error : handshake_failure; 1.6680 + 1.6681 + /* 1.6682 + * check to make sure the hash is signed by right guy 1.6683 + */ 1.6684 + rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent, 1.6685 + &ss->ssl3.hs.client_random, 1.6686 + &ss->ssl3.hs.server_random, 1.6687 + &hashes, ss->opt.bypassPKCS11); 1.6688 + if (rv != SECSuccess) { 1.6689 + errCode = 1.6690 + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.6691 + goto alert_loser; 1.6692 + } 1.6693 + rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, 1.6694 + isTLS, ss->pkcs11PinArg); 1.6695 + if (rv != SECSuccess) { 1.6696 + errCode = 1.6697 + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.6698 + goto alert_loser; 1.6699 + } 1.6700 + 1.6701 + /* 1.6702 + * we really need to build a new key here because we can no longer 1.6703 + * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate 1.6704 + * pkcs11 slots and ID's. 1.6705 + */ 1.6706 + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 1.6707 + if (arena == NULL) { 1.6708 + goto no_memory; 1.6709 + } 1.6710 + 1.6711 + peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); 1.6712 + if (peerKey == NULL) { 1.6713 + PORT_FreeArena(arena, PR_FALSE); 1.6714 + goto no_memory; 1.6715 + } 1.6716 + 1.6717 + peerKey->arena = arena; 1.6718 + peerKey->keyType = rsaKey; 1.6719 + peerKey->pkcs11Slot = NULL; 1.6720 + peerKey->pkcs11ID = CK_INVALID_HANDLE; 1.6721 + if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || 1.6722 + SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent)) 1.6723 + { 1.6724 + PORT_FreeArena(arena, PR_FALSE); 1.6725 + goto no_memory; 1.6726 + } 1.6727 + ss->sec.peerKey = peerKey; 1.6728 + ss->ssl3.hs.ws = wait_cert_request; 1.6729 + return SECSuccess; 1.6730 + } 1.6731 + 1.6732 + case kt_dh: { 1.6733 + SECItem dh_p = {siBuffer, NULL, 0}; 1.6734 + SECItem dh_g = {siBuffer, NULL, 0}; 1.6735 + SECItem dh_Ys = {siBuffer, NULL, 0}; 1.6736 + 1.6737 + rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); 1.6738 + if (rv != SECSuccess) { 1.6739 + goto loser; /* malformed. */ 1.6740 + } 1.6741 + if (dh_p.len < 512/8) { 1.6742 + errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; 1.6743 + goto alert_loser; 1.6744 + } 1.6745 + rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length); 1.6746 + if (rv != SECSuccess) { 1.6747 + goto loser; /* malformed. */ 1.6748 + } 1.6749 + if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g)) 1.6750 + goto alert_loser; 1.6751 + rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); 1.6752 + if (rv != SECSuccess) { 1.6753 + goto loser; /* malformed. */ 1.6754 + } 1.6755 + if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys)) 1.6756 + goto alert_loser; 1.6757 + if (isTLS12) { 1.6758 + rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, 1.6759 + &sigAndHash); 1.6760 + if (rv != SECSuccess) { 1.6761 + goto loser; /* malformed or unsupported. */ 1.6762 + } 1.6763 + rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( 1.6764 + &sigAndHash, ss->sec.peerCert); 1.6765 + if (rv != SECSuccess) { 1.6766 + goto loser; 1.6767 + } 1.6768 + } 1.6769 + rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length); 1.6770 + if (rv != SECSuccess) { 1.6771 + goto loser; /* malformed. */ 1.6772 + } 1.6773 + if (length != 0) { 1.6774 + if (isTLS) 1.6775 + desc = decode_error; 1.6776 + goto alert_loser; /* malformed. */ 1.6777 + } 1.6778 + 1.6779 + PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len)); 1.6780 + PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len)); 1.6781 + PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len)); 1.6782 + 1.6783 + /* failures after this point are not malformed handshakes. */ 1.6784 + /* TLS: send decrypt_error if signature failed. */ 1.6785 + desc = isTLS ? decrypt_error : handshake_failure; 1.6786 + 1.6787 + /* 1.6788 + * check to make sure the hash is signed by right guy 1.6789 + */ 1.6790 + rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys, 1.6791 + &ss->ssl3.hs.client_random, 1.6792 + &ss->ssl3.hs.server_random, 1.6793 + &hashes, ss->opt.bypassPKCS11); 1.6794 + if (rv != SECSuccess) { 1.6795 + errCode = 1.6796 + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.6797 + goto alert_loser; 1.6798 + } 1.6799 + rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, 1.6800 + isTLS, ss->pkcs11PinArg); 1.6801 + if (rv != SECSuccess) { 1.6802 + errCode = 1.6803 + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.6804 + goto alert_loser; 1.6805 + } 1.6806 + 1.6807 + /* 1.6808 + * we really need to build a new key here because we can no longer 1.6809 + * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate 1.6810 + * pkcs11 slots and ID's. 1.6811 + */ 1.6812 + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 1.6813 + if (arena == NULL) { 1.6814 + goto no_memory; 1.6815 + } 1.6816 + 1.6817 + ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); 1.6818 + if (peerKey == NULL) { 1.6819 + goto no_memory; 1.6820 + } 1.6821 + 1.6822 + peerKey->arena = arena; 1.6823 + peerKey->keyType = dhKey; 1.6824 + peerKey->pkcs11Slot = NULL; 1.6825 + peerKey->pkcs11ID = CK_INVALID_HANDLE; 1.6826 + 1.6827 + if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) || 1.6828 + SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) || 1.6829 + SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) 1.6830 + { 1.6831 + PORT_FreeArena(arena, PR_FALSE); 1.6832 + goto no_memory; 1.6833 + } 1.6834 + ss->sec.peerKey = peerKey; 1.6835 + ss->ssl3.hs.ws = wait_cert_request; 1.6836 + return SECSuccess; 1.6837 + } 1.6838 + 1.6839 +#ifndef NSS_DISABLE_ECC 1.6840 + case kt_ecdh: 1.6841 + rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); 1.6842 + return rv; 1.6843 +#endif /* NSS_DISABLE_ECC */ 1.6844 + 1.6845 + default: 1.6846 + desc = handshake_failure; 1.6847 + errCode = SEC_ERROR_UNSUPPORTED_KEYALG; 1.6848 + break; /* goto alert_loser; */ 1.6849 + } 1.6850 + 1.6851 +alert_loser: 1.6852 + (void)SSL3_SendAlert(ss, alert_fatal, desc); 1.6853 +loser: 1.6854 + PORT_SetError( errCode ); 1.6855 + return SECFailure; 1.6856 + 1.6857 +no_memory: /* no-memory error has already been set. */ 1.6858 + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.6859 + return SECFailure; 1.6860 +} 1.6861 + 1.6862 + 1.6863 +/* 1.6864 + * Returns the TLS signature algorithm for the client authentication key and 1.6865 + * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes. 1.6866 + */ 1.6867 +static SECStatus 1.6868 +ssl3_ExtractClientKeyInfo(sslSocket *ss, 1.6869 + TLSSignatureAlgorithm *sigAlg, 1.6870 + PRBool *preferSha1) 1.6871 +{ 1.6872 + SECStatus rv = SECSuccess; 1.6873 + SECKEYPublicKey *pubk; 1.6874 + 1.6875 + pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); 1.6876 + if (pubk == NULL) { 1.6877 + rv = SECFailure; 1.6878 + goto done; 1.6879 + } 1.6880 + 1.6881 + rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg); 1.6882 + if (rv != SECSuccess) { 1.6883 + goto done; 1.6884 + } 1.6885 + 1.6886 + /* If the key is a 1024-bit RSA or DSA key, assume conservatively that 1.6887 + * it may be unable to sign SHA-256 hashes. This is the case for older 1.6888 + * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and 1.6889 + * older, DSA key size is at most 1024 bits and the hash function must 1.6890 + * be SHA-1. 1.6891 + */ 1.6892 + if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { 1.6893 + *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; 1.6894 + } else { 1.6895 + *preferSha1 = PR_FALSE; 1.6896 + } 1.6897 + 1.6898 +done: 1.6899 + if (pubk) 1.6900 + SECKEY_DestroyPublicKey(pubk); 1.6901 + return rv; 1.6902 +} 1.6903 + 1.6904 +/* Destroys the backup handshake hash context if we don't need it. Note that 1.6905 + * this function selects the hash algorithm for client authentication 1.6906 + * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash 1.6907 + * to determine whether to use SHA-1 or SHA-256. */ 1.6908 +static void 1.6909 +ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, 1.6910 + const SECItem *algorithms) 1.6911 +{ 1.6912 + SECStatus rv; 1.6913 + TLSSignatureAlgorithm sigAlg; 1.6914 + PRBool preferSha1; 1.6915 + PRBool supportsSha1 = PR_FALSE; 1.6916 + PRBool supportsSha256 = PR_FALSE; 1.6917 + PRBool needBackupHash = PR_FALSE; 1.6918 + unsigned int i; 1.6919 + 1.6920 +#ifndef NO_PKCS11_BYPASS 1.6921 + /* Backup handshake hash is not supported in PKCS #11 bypass mode. */ 1.6922 + if (ss->opt.bypassPKCS11) { 1.6923 + PORT_Assert(!ss->ssl3.hs.backupHash); 1.6924 + return; 1.6925 + } 1.6926 +#endif 1.6927 + PORT_Assert(ss->ssl3.hs.backupHash); 1.6928 + 1.6929 + /* Determine the key's signature algorithm and whether it prefers SHA-1. */ 1.6930 + rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1); 1.6931 + if (rv != SECSuccess) { 1.6932 + goto done; 1.6933 + } 1.6934 + 1.6935 + /* Determine the server's hash support for that signature algorithm. */ 1.6936 + for (i = 0; i < algorithms->len; i += 2) { 1.6937 + if (algorithms->data[i+1] == sigAlg) { 1.6938 + if (algorithms->data[i] == tls_hash_sha1) { 1.6939 + supportsSha1 = PR_TRUE; 1.6940 + } else if (algorithms->data[i] == tls_hash_sha256) { 1.6941 + supportsSha256 = PR_TRUE; 1.6942 + } 1.6943 + } 1.6944 + } 1.6945 + 1.6946 + /* If either the server does not support SHA-256 or the client key prefers 1.6947 + * SHA-1, leave the backup hash. */ 1.6948 + if (supportsSha1 && (preferSha1 || !supportsSha256)) { 1.6949 + needBackupHash = PR_TRUE; 1.6950 + } 1.6951 + 1.6952 +done: 1.6953 + if (!needBackupHash) { 1.6954 + PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); 1.6955 + ss->ssl3.hs.backupHash = NULL; 1.6956 + } 1.6957 +} 1.6958 + 1.6959 +typedef struct dnameNode { 1.6960 + struct dnameNode *next; 1.6961 + SECItem name; 1.6962 +} dnameNode; 1.6963 + 1.6964 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.6965 + * ssl3 Certificate Request message. 1.6966 + * Caller must hold Handshake and RecvBuf locks. 1.6967 + */ 1.6968 +static SECStatus 1.6969 +ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.6970 +{ 1.6971 + PLArenaPool * arena = NULL; 1.6972 + dnameNode * node; 1.6973 + PRInt32 remaining; 1.6974 + PRBool isTLS = PR_FALSE; 1.6975 + PRBool isTLS12 = PR_FALSE; 1.6976 + int i; 1.6977 + int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; 1.6978 + int nnames = 0; 1.6979 + SECStatus rv; 1.6980 + SSL3AlertDescription desc = illegal_parameter; 1.6981 + SECItem cert_types = {siBuffer, NULL, 0}; 1.6982 + SECItem algorithms = {siBuffer, NULL, 0}; 1.6983 + CERTDistNames ca_list; 1.6984 + 1.6985 + SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake", 1.6986 + SSL_GETPID(), ss->fd)); 1.6987 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.6988 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.6989 + 1.6990 + if (ss->ssl3.hs.ws != wait_cert_request && 1.6991 + ss->ssl3.hs.ws != wait_server_key) { 1.6992 + desc = unexpected_message; 1.6993 + errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST; 1.6994 + goto alert_loser; 1.6995 + } 1.6996 + 1.6997 + PORT_Assert(ss->ssl3.clientCertChain == NULL); 1.6998 + PORT_Assert(ss->ssl3.clientCertificate == NULL); 1.6999 + PORT_Assert(ss->ssl3.clientPrivateKey == NULL); 1.7000 + 1.7001 + isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 1.7002 + isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 1.7003 + rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length); 1.7004 + if (rv != SECSuccess) 1.7005 + goto loser; /* malformed, alert has been sent */ 1.7006 + 1.7007 + if (isTLS12) { 1.7008 + rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); 1.7009 + if (rv != SECSuccess) 1.7010 + goto loser; /* malformed, alert has been sent */ 1.7011 + /* An empty or odd-length value is invalid. 1.7012 + * SignatureAndHashAlgorithm 1.7013 + * supported_signature_algorithms<2..2^16-2>; 1.7014 + */ 1.7015 + if (algorithms.len == 0 || (algorithms.len & 1) != 0) 1.7016 + goto alert_loser; 1.7017 + } 1.7018 + 1.7019 + arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 1.7020 + if (arena == NULL) 1.7021 + goto no_mem; 1.7022 + 1.7023 + remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 1.7024 + if (remaining < 0) 1.7025 + goto loser; /* malformed, alert has been sent */ 1.7026 + 1.7027 + if ((PRUint32)remaining > length) 1.7028 + goto alert_loser; 1.7029 + 1.7030 + ca_list.head = node = PORT_ArenaZNew(arena, dnameNode); 1.7031 + if (node == NULL) 1.7032 + goto no_mem; 1.7033 + 1.7034 + while (remaining > 0) { 1.7035 + PRInt32 len; 1.7036 + 1.7037 + if (remaining < 2) 1.7038 + goto alert_loser; /* malformed */ 1.7039 + 1.7040 + node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 1.7041 + if (len <= 0) 1.7042 + goto loser; /* malformed, alert has been sent */ 1.7043 + 1.7044 + remaining -= 2; 1.7045 + if (remaining < len) 1.7046 + goto alert_loser; /* malformed */ 1.7047 + 1.7048 + node->name.data = b; 1.7049 + b += len; 1.7050 + length -= len; 1.7051 + remaining -= len; 1.7052 + nnames++; 1.7053 + if (remaining <= 0) 1.7054 + break; /* success */ 1.7055 + 1.7056 + node->next = PORT_ArenaZNew(arena, dnameNode); 1.7057 + node = node->next; 1.7058 + if (node == NULL) 1.7059 + goto no_mem; 1.7060 + } 1.7061 + 1.7062 + ca_list.nnames = nnames; 1.7063 + ca_list.names = PORT_ArenaNewArray(arena, SECItem, nnames); 1.7064 + if (nnames > 0 && ca_list.names == NULL) 1.7065 + goto no_mem; 1.7066 + 1.7067 + for(i = 0, node = (dnameNode*)ca_list.head; 1.7068 + i < nnames; 1.7069 + i++, node = node->next) { 1.7070 + ca_list.names[i] = node->name; 1.7071 + } 1.7072 + 1.7073 + if (length != 0) 1.7074 + goto alert_loser; /* malformed */ 1.7075 + 1.7076 + desc = no_certificate; 1.7077 + ss->ssl3.hs.ws = wait_hello_done; 1.7078 + 1.7079 + if (ss->getClientAuthData != NULL) { 1.7080 + /* XXX Should pass cert_types and algorithms in this call!! */ 1.7081 + rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg, 1.7082 + ss->fd, &ca_list, 1.7083 + &ss->ssl3.clientCertificate, 1.7084 + &ss->ssl3.clientPrivateKey); 1.7085 + } else { 1.7086 + rv = SECFailure; /* force it to send a no_certificate alert */ 1.7087 + } 1.7088 + switch (rv) { 1.7089 + case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ 1.7090 + ssl3_SetAlwaysBlock(ss); 1.7091 + break; /* not an error */ 1.7092 + 1.7093 + case SECSuccess: 1.7094 + /* check what the callback function returned */ 1.7095 + if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { 1.7096 + /* we are missing either the key or cert */ 1.7097 + if (ss->ssl3.clientCertificate) { 1.7098 + /* got a cert, but no key - free it */ 1.7099 + CERT_DestroyCertificate(ss->ssl3.clientCertificate); 1.7100 + ss->ssl3.clientCertificate = NULL; 1.7101 + } 1.7102 + if (ss->ssl3.clientPrivateKey) { 1.7103 + /* got a key, but no cert - free it */ 1.7104 + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 1.7105 + ss->ssl3.clientPrivateKey = NULL; 1.7106 + } 1.7107 + goto send_no_certificate; 1.7108 + } 1.7109 + /* Setting ssl3.clientCertChain non-NULL will cause 1.7110 + * ssl3_HandleServerHelloDone to call SendCertificate. 1.7111 + */ 1.7112 + ss->ssl3.clientCertChain = CERT_CertChainFromCert( 1.7113 + ss->ssl3.clientCertificate, 1.7114 + certUsageSSLClient, PR_FALSE); 1.7115 + if (ss->ssl3.clientCertChain == NULL) { 1.7116 + CERT_DestroyCertificate(ss->ssl3.clientCertificate); 1.7117 + ss->ssl3.clientCertificate = NULL; 1.7118 + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 1.7119 + ss->ssl3.clientPrivateKey = NULL; 1.7120 + goto send_no_certificate; 1.7121 + } 1.7122 + if (ss->ssl3.hs.hashType == handshake_hash_single) { 1.7123 + ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); 1.7124 + } 1.7125 + break; /* not an error */ 1.7126 + 1.7127 + case SECFailure: 1.7128 + default: 1.7129 +send_no_certificate: 1.7130 + if (isTLS) { 1.7131 + ss->ssl3.sendEmptyCert = PR_TRUE; 1.7132 + } else { 1.7133 + (void)SSL3_SendAlert(ss, alert_warning, no_certificate); 1.7134 + } 1.7135 + rv = SECSuccess; 1.7136 + break; 1.7137 + } 1.7138 + goto done; 1.7139 + 1.7140 +no_mem: 1.7141 + rv = SECFailure; 1.7142 + PORT_SetError(SEC_ERROR_NO_MEMORY); 1.7143 + goto done; 1.7144 + 1.7145 +alert_loser: 1.7146 + if (isTLS && desc == illegal_parameter) 1.7147 + desc = decode_error; 1.7148 + (void)SSL3_SendAlert(ss, alert_fatal, desc); 1.7149 +loser: 1.7150 + PORT_SetError(errCode); 1.7151 + rv = SECFailure; 1.7152 +done: 1.7153 + if (arena != NULL) 1.7154 + PORT_FreeArena(arena, PR_FALSE); 1.7155 + return rv; 1.7156 +} 1.7157 + 1.7158 +static SECStatus 1.7159 +ssl3_CheckFalseStart(sslSocket *ss) 1.7160 +{ 1.7161 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.7162 + PORT_Assert( !ss->ssl3.hs.authCertificatePending ); 1.7163 + PORT_Assert( !ss->ssl3.hs.canFalseStart ); 1.7164 + 1.7165 + if (!ss->canFalseStartCallback) { 1.7166 + SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", 1.7167 + SSL_GETPID(), ss->fd)); 1.7168 + } else { 1.7169 + PRBool maybeFalseStart; 1.7170 + SECStatus rv; 1.7171 + 1.7172 + /* An attacker can control the selected ciphersuite so we only wish to 1.7173 + * do False Start in the case that the selected ciphersuite is 1.7174 + * sufficiently strong that the attack can gain no advantage. 1.7175 + * Therefore we always require an 80-bit cipher. */ 1.7176 + ssl_GetSpecReadLock(ss); 1.7177 + maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10; 1.7178 + ssl_ReleaseSpecReadLock(ss); 1.7179 + 1.7180 + if (!maybeFalseStart) { 1.7181 + SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", 1.7182 + SSL_GETPID(), ss->fd)); 1.7183 + } else { 1.7184 + rv = (ss->canFalseStartCallback)(ss->fd, 1.7185 + ss->canFalseStartCallbackData, 1.7186 + &ss->ssl3.hs.canFalseStart); 1.7187 + if (rv == SECSuccess) { 1.7188 + SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s", 1.7189 + SSL_GETPID(), ss->fd, 1.7190 + ss->ssl3.hs.canFalseStart ? "TRUE" : "FALSE")); 1.7191 + } else { 1.7192 + SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)", 1.7193 + SSL_GETPID(), ss->fd, 1.7194 + PR_ErrorToName(PR_GetError()))); 1.7195 + } 1.7196 + return rv; 1.7197 + } 1.7198 + } 1.7199 + 1.7200 + ss->ssl3.hs.canFalseStart = PR_FALSE; 1.7201 + return SECSuccess; 1.7202 +} 1.7203 + 1.7204 +PRBool 1.7205 +ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss) 1.7206 +{ 1.7207 + PRBool result; 1.7208 + 1.7209 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.7210 + 1.7211 + switch (ss->ssl3.hs.ws) { 1.7212 + case wait_new_session_ticket: 1.7213 + result = PR_TRUE; 1.7214 + break; 1.7215 + case wait_change_cipher: 1.7216 + result = !ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn); 1.7217 + break; 1.7218 + default: 1.7219 + result = PR_FALSE; 1.7220 + break; 1.7221 + } 1.7222 + 1.7223 + return result; 1.7224 +} 1.7225 + 1.7226 +static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); 1.7227 + 1.7228 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.7229 + * ssl3 Server Hello Done message. 1.7230 + * Caller must hold Handshake and RecvBuf locks. 1.7231 + */ 1.7232 +static SECStatus 1.7233 +ssl3_HandleServerHelloDone(sslSocket *ss) 1.7234 +{ 1.7235 + SECStatus rv; 1.7236 + SSL3WaitState ws = ss->ssl3.hs.ws; 1.7237 + 1.7238 + SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake", 1.7239 + SSL_GETPID(), ss->fd)); 1.7240 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.7241 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.7242 + 1.7243 + if (ws != wait_hello_done && 1.7244 + ws != wait_server_cert && 1.7245 + ws != wait_server_key && 1.7246 + ws != wait_cert_request) { 1.7247 + SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.7248 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); 1.7249 + return SECFailure; 1.7250 + } 1.7251 + 1.7252 + rv = ssl3_SendClientSecondRound(ss); 1.7253 + 1.7254 + return rv; 1.7255 +} 1.7256 + 1.7257 +/* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete. 1.7258 + * 1.7259 + * Caller must hold Handshake and RecvBuf locks. 1.7260 + */ 1.7261 +static SECStatus 1.7262 +ssl3_SendClientSecondRound(sslSocket *ss) 1.7263 +{ 1.7264 + SECStatus rv; 1.7265 + PRBool sendClientCert; 1.7266 + 1.7267 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.7268 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.7269 + 1.7270 + sendClientCert = !ss->ssl3.sendEmptyCert && 1.7271 + ss->ssl3.clientCertChain != NULL && 1.7272 + ss->ssl3.clientPrivateKey != NULL; 1.7273 + 1.7274 + if (!sendClientCert && 1.7275 + ss->ssl3.hs.hashType == handshake_hash_single && 1.7276 + ss->ssl3.hs.backupHash) { 1.7277 + /* Don't need the backup handshake hash. */ 1.7278 + PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); 1.7279 + ss->ssl3.hs.backupHash = NULL; 1.7280 + } 1.7281 + 1.7282 + /* We must wait for the server's certificate to be authenticated before 1.7283 + * sending the client certificate in order to disclosing the client 1.7284 + * certificate to an attacker that does not have a valid cert for the 1.7285 + * domain we are connecting to. 1.7286 + * 1.7287 + * XXX: We should do the same for the NPN extension, but for that we 1.7288 + * need an option to give the application the ability to leak the NPN 1.7289 + * information to get better performance. 1.7290 + * 1.7291 + * During the initial handshake on a connection, we never send/receive 1.7292 + * application data until we have authenticated the server's certificate; 1.7293 + * i.e. we have fully authenticated the handshake before using the cipher 1.7294 + * specs agreed upon for that handshake. During a renegotiation, we may 1.7295 + * continue sending and receiving application data during the handshake 1.7296 + * interleaved with the handshake records. If we were to send the client's 1.7297 + * second round for a renegotiation before the server's certificate was 1.7298 + * authenticated, then the application data sent/received after this point 1.7299 + * would be using cipher spec that hadn't been authenticated. By waiting 1.7300 + * until the server's certificate has been authenticated during 1.7301 + * renegotiations, we ensure that renegotiations have the same property 1.7302 + * as initial handshakes; i.e. we have fully authenticated the handshake 1.7303 + * before using the cipher specs agreed upon for that handshake for 1.7304 + * application data. 1.7305 + */ 1.7306 + if (ss->ssl3.hs.restartTarget) { 1.7307 + PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); 1.7308 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.7309 + return SECFailure; 1.7310 + } 1.7311 + if (ss->ssl3.hs.authCertificatePending && 1.7312 + (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) { 1.7313 + SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because" 1.7314 + " certificate authentication is still pending.", 1.7315 + SSL_GETPID(), ss->fd)); 1.7316 + ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound; 1.7317 + return SECWouldBlock; 1.7318 + } 1.7319 + 1.7320 + ssl_GetXmitBufLock(ss); /*******************************/ 1.7321 + 1.7322 + if (ss->ssl3.sendEmptyCert) { 1.7323 + ss->ssl3.sendEmptyCert = PR_FALSE; 1.7324 + rv = ssl3_SendEmptyCertificate(ss); 1.7325 + /* Don't send verify */ 1.7326 + if (rv != SECSuccess) { 1.7327 + goto loser; /* error code is set. */ 1.7328 + } 1.7329 + } else if (sendClientCert) { 1.7330 + rv = ssl3_SendCertificate(ss); 1.7331 + if (rv != SECSuccess) { 1.7332 + goto loser; /* error code is set. */ 1.7333 + } 1.7334 + } 1.7335 + 1.7336 + rv = ssl3_SendClientKeyExchange(ss); 1.7337 + if (rv != SECSuccess) { 1.7338 + goto loser; /* err is set. */ 1.7339 + } 1.7340 + 1.7341 + if (sendClientCert) { 1.7342 + rv = ssl3_SendCertificateVerify(ss); 1.7343 + if (rv != SECSuccess) { 1.7344 + goto loser; /* err is set. */ 1.7345 + } 1.7346 + } 1.7347 + 1.7348 + rv = ssl3_SendChangeCipherSpecs(ss); 1.7349 + if (rv != SECSuccess) { 1.7350 + goto loser; /* err code was set. */ 1.7351 + } 1.7352 + 1.7353 + /* This must be done after we've set ss->ssl3.cwSpec in 1.7354 + * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information 1.7355 + * from cwSpec. This must be done before we call ssl3_CheckFalseStart 1.7356 + * because the false start callback (if any) may need the information from 1.7357 + * the functions that depend on this being set. 1.7358 + */ 1.7359 + ss->enoughFirstHsDone = PR_TRUE; 1.7360 + 1.7361 + if (!ss->firstHsDone) { 1.7362 + /* XXX: If the server's certificate hasn't been authenticated by this 1.7363 + * point, then we may be leaking this NPN message to an attacker. 1.7364 + */ 1.7365 + rv = ssl3_SendNextProto(ss); 1.7366 + if (rv != SECSuccess) { 1.7367 + goto loser; /* err code was set. */ 1.7368 + } 1.7369 + 1.7370 + if (ss->opt.enableFalseStart) { 1.7371 + if (!ss->ssl3.hs.authCertificatePending) { 1.7372 + /* When we fix bug 589047, we will need to know whether we are 1.7373 + * false starting before we try to flush the client second 1.7374 + * round to the network. With that in mind, we purposefully 1.7375 + * call ssl3_CheckFalseStart before calling ssl3_SendFinished, 1.7376 + * which includes a call to ssl3_FlushHandshake, so that 1.7377 + * no application develops a reliance on such flushing being 1.7378 + * done before its false start callback is called. 1.7379 + */ 1.7380 + ssl_ReleaseXmitBufLock(ss); 1.7381 + rv = ssl3_CheckFalseStart(ss); 1.7382 + ssl_GetXmitBufLock(ss); 1.7383 + if (rv != SECSuccess) { 1.7384 + goto loser; 1.7385 + } 1.7386 + } else { 1.7387 + /* The certificate authentication and the server's Finished 1.7388 + * message are racing each other. If the certificate 1.7389 + * authentication wins, then we will try to false start in 1.7390 + * ssl3_AuthCertificateComplete. 1.7391 + */ 1.7392 + SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because" 1.7393 + " certificate authentication is still pending.", 1.7394 + SSL_GETPID(), ss->fd)); 1.7395 + } 1.7396 + } 1.7397 + } 1.7398 + 1.7399 + rv = ssl3_SendFinished(ss, 0); 1.7400 + if (rv != SECSuccess) { 1.7401 + goto loser; /* err code was set. */ 1.7402 + } 1.7403 + 1.7404 + ssl_ReleaseXmitBufLock(ss); /*******************************/ 1.7405 + 1.7406 + if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) 1.7407 + ss->ssl3.hs.ws = wait_new_session_ticket; 1.7408 + else 1.7409 + ss->ssl3.hs.ws = wait_change_cipher; 1.7410 + 1.7411 + PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss)); 1.7412 + 1.7413 + return SECSuccess; 1.7414 + 1.7415 +loser: 1.7416 + ssl_ReleaseXmitBufLock(ss); 1.7417 + return rv; 1.7418 +} 1.7419 + 1.7420 +/* 1.7421 + * Routines used by servers 1.7422 + */ 1.7423 +static SECStatus 1.7424 +ssl3_SendHelloRequest(sslSocket *ss) 1.7425 +{ 1.7426 + SECStatus rv; 1.7427 + 1.7428 + SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), 1.7429 + ss->fd)); 1.7430 + 1.7431 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.7432 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 1.7433 + 1.7434 + rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0); 1.7435 + if (rv != SECSuccess) { 1.7436 + return rv; /* err set by AppendHandshake */ 1.7437 + } 1.7438 + rv = ssl3_FlushHandshake(ss, 0); 1.7439 + if (rv != SECSuccess) { 1.7440 + return rv; /* error code set by ssl3_FlushHandshake */ 1.7441 + } 1.7442 + ss->ssl3.hs.ws = wait_client_hello; 1.7443 + return SECSuccess; 1.7444 +} 1.7445 + 1.7446 +/* 1.7447 + * Called from: 1.7448 + * ssl3_HandleClientHello() 1.7449 + */ 1.7450 +static SECComparison 1.7451 +ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) 1.7452 +{ 1.7453 + if (!name1 != !name2) { 1.7454 + return SECLessThan; 1.7455 + } 1.7456 + if (!name1) { 1.7457 + return SECEqual; 1.7458 + } 1.7459 + if (name1->type != name2->type) { 1.7460 + return SECLessThan; 1.7461 + } 1.7462 + return SECITEM_CompareItem(name1, name2); 1.7463 +} 1.7464 + 1.7465 +/* Sets memory error when returning NULL. 1.7466 + * Called from: 1.7467 + * ssl3_SendClientHello() 1.7468 + * ssl3_HandleServerHello() 1.7469 + * ssl3_HandleClientHello() 1.7470 + * ssl3_HandleV2ClientHello() 1.7471 + */ 1.7472 +sslSessionID * 1.7473 +ssl3_NewSessionID(sslSocket *ss, PRBool is_server) 1.7474 +{ 1.7475 + sslSessionID *sid; 1.7476 + 1.7477 + sid = PORT_ZNew(sslSessionID); 1.7478 + if (sid == NULL) 1.7479 + return sid; 1.7480 + 1.7481 + if (is_server) { 1.7482 + const SECItem * srvName; 1.7483 + SECStatus rv = SECSuccess; 1.7484 + 1.7485 + ssl_GetSpecReadLock(ss); /********************************/ 1.7486 + srvName = &ss->ssl3.prSpec->srvVirtName; 1.7487 + if (srvName->len && srvName->data) { 1.7488 + rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); 1.7489 + } 1.7490 + ssl_ReleaseSpecReadLock(ss); /************************************/ 1.7491 + if (rv != SECSuccess) { 1.7492 + PORT_Free(sid); 1.7493 + return NULL; 1.7494 + } 1.7495 + } 1.7496 + sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID); 1.7497 + sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url); 1.7498 + sid->addr = ss->sec.ci.peer; 1.7499 + sid->port = ss->sec.ci.port; 1.7500 + sid->references = 1; 1.7501 + sid->cached = never_cached; 1.7502 + sid->version = ss->version; 1.7503 + 1.7504 + sid->u.ssl3.keys.resumable = PR_TRUE; 1.7505 + sid->u.ssl3.policy = SSL_ALLOWED; 1.7506 + sid->u.ssl3.clientWriteKey = NULL; 1.7507 + sid->u.ssl3.serverWriteKey = NULL; 1.7508 + 1.7509 + if (is_server) { 1.7510 + SECStatus rv; 1.7511 + int pid = SSL_GETPID(); 1.7512 + 1.7513 + sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES; 1.7514 + sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff; 1.7515 + sid->u.ssl3.sessionID[1] = pid & 0xff; 1.7516 + rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2, 1.7517 + SSL3_SESSIONID_BYTES -2); 1.7518 + if (rv != SECSuccess) { 1.7519 + ssl_FreeSID(sid); 1.7520 + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 1.7521 + return NULL; 1.7522 + } 1.7523 + } 1.7524 + return sid; 1.7525 +} 1.7526 + 1.7527 +/* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */ 1.7528 +static SECStatus 1.7529 +ssl3_SendServerHelloSequence(sslSocket *ss) 1.7530 +{ 1.7531 + const ssl3KEADef *kea_def; 1.7532 + SECStatus rv; 1.7533 + 1.7534 + SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", 1.7535 + SSL_GETPID(), ss->fd)); 1.7536 + 1.7537 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.7538 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); 1.7539 + 1.7540 + rv = ssl3_SendServerHello(ss); 1.7541 + if (rv != SECSuccess) { 1.7542 + return rv; /* err code is set. */ 1.7543 + } 1.7544 + rv = ssl3_SendCertificate(ss); 1.7545 + if (rv != SECSuccess) { 1.7546 + return rv; /* error code is set. */ 1.7547 + } 1.7548 + rv = ssl3_SendCertificateStatus(ss); 1.7549 + if (rv != SECSuccess) { 1.7550 + return rv; /* error code is set. */ 1.7551 + } 1.7552 + /* We have to do this after the call to ssl3_SendServerHello, 1.7553 + * because kea_def is set up by ssl3_SendServerHello(). 1.7554 + */ 1.7555 + kea_def = ss->ssl3.hs.kea_def; 1.7556 + ss->ssl3.hs.usedStepDownKey = PR_FALSE; 1.7557 + 1.7558 + if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) { 1.7559 + /* see if we can legally use the key in the cert. */ 1.7560 + int keyLen; /* bytes */ 1.7561 + 1.7562 + keyLen = PK11_GetPrivateModulusLen( 1.7563 + ss->serverCerts[kea_def->exchKeyType].SERVERKEY); 1.7564 + 1.7565 + if (keyLen > 0 && 1.7566 + keyLen * BPB <= kea_def->key_size_limit ) { 1.7567 + /* XXX AND cert is not signing only!! */ 1.7568 + /* just fall through and use it. */ 1.7569 + } else if (ss->stepDownKeyPair != NULL) { 1.7570 + ss->ssl3.hs.usedStepDownKey = PR_TRUE; 1.7571 + rv = ssl3_SendServerKeyExchange(ss); 1.7572 + if (rv != SECSuccess) { 1.7573 + return rv; /* err code was set. */ 1.7574 + } 1.7575 + } else { 1.7576 +#ifndef HACKED_EXPORT_SERVER 1.7577 + PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); 1.7578 + return rv; 1.7579 +#endif 1.7580 + } 1.7581 +#ifndef NSS_DISABLE_ECC 1.7582 + } else if ((kea_def->kea == kea_ecdhe_rsa) || 1.7583 + (kea_def->kea == kea_ecdhe_ecdsa)) { 1.7584 + rv = ssl3_SendServerKeyExchange(ss); 1.7585 + if (rv != SECSuccess) { 1.7586 + return rv; /* err code was set. */ 1.7587 + } 1.7588 +#endif /* NSS_DISABLE_ECC */ 1.7589 + } 1.7590 + 1.7591 + if (ss->opt.requestCertificate) { 1.7592 + rv = ssl3_SendCertificateRequest(ss); 1.7593 + if (rv != SECSuccess) { 1.7594 + return rv; /* err code is set. */ 1.7595 + } 1.7596 + } 1.7597 + rv = ssl3_SendServerHelloDone(ss); 1.7598 + if (rv != SECSuccess) { 1.7599 + return rv; /* err code is set. */ 1.7600 + } 1.7601 + 1.7602 + ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert 1.7603 + : wait_client_key; 1.7604 + return SECSuccess; 1.7605 +} 1.7606 + 1.7607 +/* An empty TLS Renegotiation Info (RI) extension */ 1.7608 +static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00}; 1.7609 + 1.7610 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.7611 + * ssl3 Client Hello message. 1.7612 + * Caller must hold Handshake and RecvBuf locks. 1.7613 + */ 1.7614 +static SECStatus 1.7615 +ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.7616 +{ 1.7617 + sslSessionID * sid = NULL; 1.7618 + PRInt32 tmp; 1.7619 + unsigned int i; 1.7620 + int j; 1.7621 + SECStatus rv; 1.7622 + int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 1.7623 + SSL3AlertDescription desc = illegal_parameter; 1.7624 + SSL3AlertLevel level = alert_fatal; 1.7625 + SSL3ProtocolVersion version; 1.7626 + SECItem sidBytes = {siBuffer, NULL, 0}; 1.7627 + SECItem cookieBytes = {siBuffer, NULL, 0}; 1.7628 + SECItem suites = {siBuffer, NULL, 0}; 1.7629 + SECItem comps = {siBuffer, NULL, 0}; 1.7630 + PRBool haveSpecWriteLock = PR_FALSE; 1.7631 + PRBool haveXmitBufLock = PR_FALSE; 1.7632 + 1.7633 + SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake", 1.7634 + SSL_GETPID(), ss->fd)); 1.7635 + 1.7636 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.7637 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.7638 + PORT_Assert( ss->ssl3.initialized ); 1.7639 + 1.7640 + /* Get peer name of client */ 1.7641 + rv = ssl_GetPeerInfo(ss); 1.7642 + if (rv != SECSuccess) { 1.7643 + return rv; /* error code is set. */ 1.7644 + } 1.7645 + 1.7646 + /* Clearing the handshake pointers so that ssl_Do1stHandshake won't 1.7647 + * call ssl2_HandleMessage. 1.7648 + * 1.7649 + * The issue here is that TLS ordinarily starts out in 1.7650 + * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility 1.7651 + * code paths. That function zeroes these next pointers. But with DTLS, 1.7652 + * we don't even try to do the v2 ClientHello so we skip that function 1.7653 + * and need to reset these values here. 1.7654 + */ 1.7655 + if (IS_DTLS(ss)) { 1.7656 + ss->nextHandshake = 0; 1.7657 + ss->securityHandshake = 0; 1.7658 + } 1.7659 + 1.7660 + /* We might be starting session renegotiation in which case we should 1.7661 + * clear previous state. 1.7662 + */ 1.7663 + PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 1.7664 + ss->statelessResume = PR_FALSE; 1.7665 + 1.7666 + if ((ss->ssl3.hs.ws != wait_client_hello) && 1.7667 + (ss->ssl3.hs.ws != idle_handshake)) { 1.7668 + desc = unexpected_message; 1.7669 + errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; 1.7670 + goto alert_loser; 1.7671 + } 1.7672 + if (ss->ssl3.hs.ws == idle_handshake && 1.7673 + ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 1.7674 + desc = no_renegotiation; 1.7675 + level = alert_warning; 1.7676 + errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 1.7677 + goto alert_loser; 1.7678 + } 1.7679 + 1.7680 + if (IS_DTLS(ss)) { 1.7681 + dtls_RehandshakeCleanup(ss); 1.7682 + } 1.7683 + 1.7684 + tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 1.7685 + if (tmp < 0) 1.7686 + goto loser; /* malformed, alert already sent */ 1.7687 + 1.7688 + /* Translate the version */ 1.7689 + if (IS_DTLS(ss)) { 1.7690 + ss->clientHelloVersion = version = 1.7691 + dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); 1.7692 + } else { 1.7693 + ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; 1.7694 + } 1.7695 + 1.7696 + rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); 1.7697 + if (rv != SECSuccess) { 1.7698 + desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version 1.7699 + : handshake_failure; 1.7700 + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 1.7701 + goto alert_loser; 1.7702 + } 1.7703 + 1.7704 + rv = ssl3_InitHandshakeHashes(ss); 1.7705 + if (rv != SECSuccess) { 1.7706 + desc = internal_error; 1.7707 + errCode = PORT_GetError(); 1.7708 + goto alert_loser; 1.7709 + } 1.7710 + 1.7711 + /* grab the client random data. */ 1.7712 + rv = ssl3_ConsumeHandshake( 1.7713 + ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); 1.7714 + if (rv != SECSuccess) { 1.7715 + goto loser; /* malformed */ 1.7716 + } 1.7717 + 1.7718 + /* grab the client's SID, if present. */ 1.7719 + rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); 1.7720 + if (rv != SECSuccess) { 1.7721 + goto loser; /* malformed */ 1.7722 + } 1.7723 + 1.7724 + /* grab the client's cookie, if present. */ 1.7725 + if (IS_DTLS(ss)) { 1.7726 + rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); 1.7727 + if (rv != SECSuccess) { 1.7728 + goto loser; /* malformed */ 1.7729 + } 1.7730 + } 1.7731 + 1.7732 + /* grab the list of cipher suites. */ 1.7733 + rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length); 1.7734 + if (rv != SECSuccess) { 1.7735 + goto loser; /* malformed */ 1.7736 + } 1.7737 + 1.7738 + /* If the ClientHello version is less than our maximum version, check for a 1.7739 + * TLS_FALLBACK_SCSV and reject the connection if found. */ 1.7740 + if (ss->vrange.max > ss->clientHelloVersion) { 1.7741 + for (i = 0; i + 1 < suites.len; i += 2) { 1.7742 + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 1.7743 + if (suite_i != TLS_FALLBACK_SCSV) 1.7744 + continue; 1.7745 + desc = inappropriate_fallback; 1.7746 + errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT; 1.7747 + goto alert_loser; 1.7748 + } 1.7749 + } 1.7750 + 1.7751 + /* grab the list of compression methods. */ 1.7752 + rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length); 1.7753 + if (rv != SECSuccess) { 1.7754 + goto loser; /* malformed */ 1.7755 + } 1.7756 + 1.7757 + desc = handshake_failure; 1.7758 + 1.7759 + /* Handle TLS hello extensions for SSL3 & TLS. We do not know if 1.7760 + * we are restarting a previous session until extensions have been 1.7761 + * parsed, since we might have received a SessionTicket extension. 1.7762 + * Note: we allow extensions even when negotiating SSL3 for the sake 1.7763 + * of interoperability (and backwards compatibility). 1.7764 + */ 1.7765 + 1.7766 + if (length) { 1.7767 + /* Get length of hello extensions */ 1.7768 + PRInt32 extension_length; 1.7769 + extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); 1.7770 + if (extension_length < 0) { 1.7771 + goto loser; /* alert already sent */ 1.7772 + } 1.7773 + if (extension_length != length) { 1.7774 + ssl3_DecodeError(ss); /* send alert */ 1.7775 + goto loser; 1.7776 + } 1.7777 + rv = ssl3_HandleHelloExtensions(ss, &b, &length); 1.7778 + if (rv != SECSuccess) { 1.7779 + goto loser; /* malformed */ 1.7780 + } 1.7781 + } 1.7782 + if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 1.7783 + /* If we didn't receive an RI extension, look for the SCSV, 1.7784 + * and if found, treat it just like an empty RI extension 1.7785 + * by processing a local copy of an empty RI extension. 1.7786 + */ 1.7787 + for (i = 0; i + 1 < suites.len; i += 2) { 1.7788 + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 1.7789 + if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { 1.7790 + SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; 1.7791 + PRUint32 L2 = sizeof emptyRIext; 1.7792 + (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); 1.7793 + break; 1.7794 + } 1.7795 + } 1.7796 + } 1.7797 + if (ss->firstHsDone && 1.7798 + (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN || 1.7799 + ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) && 1.7800 + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 1.7801 + desc = no_renegotiation; 1.7802 + level = alert_warning; 1.7803 + errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; 1.7804 + goto alert_loser; 1.7805 + } 1.7806 + if ((ss->opt.requireSafeNegotiation || 1.7807 + (ss->firstHsDone && ss->peerRequestedProtection)) && 1.7808 + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 1.7809 + desc = handshake_failure; 1.7810 + errCode = SSL_ERROR_UNSAFE_NEGOTIATION; 1.7811 + goto alert_loser; 1.7812 + } 1.7813 + 1.7814 + /* We do stateful resumes only if either of the following 1.7815 + * conditions are satisfied: (1) the client does not support the 1.7816 + * session ticket extension, or (2) the client support the session 1.7817 + * ticket extension, but sent an empty ticket. 1.7818 + */ 1.7819 + if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) || 1.7820 + ss->xtnData.emptySessionTicket) { 1.7821 + if (sidBytes.len > 0 && !ss->opt.noCache) { 1.7822 + SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x", 1.7823 + SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0], 1.7824 + ss->sec.ci.peer.pr_s6_addr32[1], 1.7825 + ss->sec.ci.peer.pr_s6_addr32[2], 1.7826 + ss->sec.ci.peer.pr_s6_addr32[3])); 1.7827 + if (ssl_sid_lookup) { 1.7828 + sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data, 1.7829 + sidBytes.len, ss->dbHandle); 1.7830 + } else { 1.7831 + errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; 1.7832 + goto loser; 1.7833 + } 1.7834 + } 1.7835 + } else if (ss->statelessResume) { 1.7836 + /* Fill in the client's session ID if doing a stateless resume. 1.7837 + * (When doing stateless resumes, server echos client's SessionID.) 1.7838 + */ 1.7839 + sid = ss->sec.ci.sid; 1.7840 + PORT_Assert(sid != NULL); /* Should have already been filled in.*/ 1.7841 + 1.7842 + if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) { 1.7843 + sid->u.ssl3.sessionIDLength = sidBytes.len; 1.7844 + PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, 1.7845 + sidBytes.len); 1.7846 + sid->u.ssl3.sessionIDLength = sidBytes.len; 1.7847 + } else { 1.7848 + sid->u.ssl3.sessionIDLength = 0; 1.7849 + } 1.7850 + ss->sec.ci.sid = NULL; 1.7851 + } 1.7852 + 1.7853 + /* We only send a session ticket extension if the client supports 1.7854 + * the extension and we are unable to do either a stateful or 1.7855 + * stateless resume. 1.7856 + * 1.7857 + * TODO: send a session ticket if performing a stateful 1.7858 + * resumption. (As per RFC4507, a server may issue a session 1.7859 + * ticket while doing a (stateless or stateful) session resume, 1.7860 + * but OpenSSL-0.9.8g does not accept session tickets while 1.7861 + * resuming.) 1.7862 + */ 1.7863 + if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) { 1.7864 + ssl3_RegisterServerHelloExtensionSender(ss, 1.7865 + ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn); 1.7866 + } 1.7867 + 1.7868 + if (sid != NULL) { 1.7869 + /* We've found a session cache entry for this client. 1.7870 + * Now, if we're going to require a client-auth cert, 1.7871 + * and we don't already have this client's cert in the session cache, 1.7872 + * and this is the first handshake on this connection (not a redo), 1.7873 + * then drop this old cache entry and start a new session. 1.7874 + */ 1.7875 + if ((sid->peerCert == NULL) && ss->opt.requestCertificate && 1.7876 + ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) || 1.7877 + (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) || 1.7878 + ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) 1.7879 + && !ss->firstHsDone))) { 1.7880 + 1.7881 + SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); 1.7882 + if (ss->sec.uncache) 1.7883 + ss->sec.uncache(sid); 1.7884 + ssl_FreeSID(sid); 1.7885 + sid = NULL; 1.7886 + } 1.7887 + } 1.7888 + 1.7889 +#ifndef NSS_DISABLE_ECC 1.7890 + /* Disable any ECC cipher suites for which we have no cert. */ 1.7891 + ssl3_FilterECCipherSuitesByServerCerts(ss); 1.7892 +#endif 1.7893 + 1.7894 + if (IS_DTLS(ss)) { 1.7895 + ssl3_DisableNonDTLSSuites(ss); 1.7896 + } 1.7897 + 1.7898 +#ifdef PARANOID 1.7899 + /* Look for a matching cipher suite. */ 1.7900 + j = ssl3_config_match_init(ss); 1.7901 + if (j <= 0) { /* no ciphers are working/supported by PK11 */ 1.7902 + errCode = PORT_GetError(); /* error code is already set. */ 1.7903 + goto alert_loser; 1.7904 + } 1.7905 +#endif 1.7906 + 1.7907 + /* If we already have a session for this client, be sure to pick the 1.7908 + ** same cipher suite and compression method we picked before. 1.7909 + ** This is not a loop, despite appearances. 1.7910 + */ 1.7911 + if (sid) do { 1.7912 + ssl3CipherSuiteCfg *suite; 1.7913 +#ifdef PARANOID 1.7914 + SSLVersionRange vrange = {ss->version, ss->version}; 1.7915 +#endif 1.7916 + 1.7917 + /* Check that the cached compression method is still enabled. */ 1.7918 + if (!compressionEnabled(ss, sid->u.ssl3.compression)) 1.7919 + break; 1.7920 + 1.7921 + /* Check that the cached compression method is in the client's list */ 1.7922 + for (i = 0; i < comps.len; i++) { 1.7923 + if (comps.data[i] == sid->u.ssl3.compression) 1.7924 + break; 1.7925 + } 1.7926 + if (i == comps.len) 1.7927 + break; 1.7928 + 1.7929 + suite = ss->cipherSuites; 1.7930 + /* Find the entry for the cipher suite used in the cached session. */ 1.7931 + for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) { 1.7932 + if (suite->cipher_suite == sid->u.ssl3.cipherSuite) 1.7933 + break; 1.7934 + } 1.7935 + PORT_Assert(j > 0); 1.7936 + if (j <= 0) 1.7937 + break; 1.7938 +#ifdef PARANOID 1.7939 + /* Double check that the cached cipher suite is still enabled, 1.7940 + * implemented, and allowed by policy. Might have been disabled. 1.7941 + * The product policy won't change during the process lifetime. 1.7942 + * Implemented ("isPresent") shouldn't change for servers. 1.7943 + */ 1.7944 + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) 1.7945 + break; 1.7946 +#else 1.7947 + if (!suite->enabled) 1.7948 + break; 1.7949 +#endif 1.7950 + /* Double check that the cached cipher suite is in the client's list */ 1.7951 + for (i = 0; i + 1 < suites.len; i += 2) { 1.7952 + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 1.7953 + if (suite_i == suite->cipher_suite) { 1.7954 + ss->ssl3.hs.cipher_suite = suite->cipher_suite; 1.7955 + ss->ssl3.hs.suite_def = 1.7956 + ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); 1.7957 + 1.7958 + /* Use the cached compression method. */ 1.7959 + ss->ssl3.hs.compression = sid->u.ssl3.compression; 1.7960 + goto compression_found; 1.7961 + } 1.7962 + } 1.7963 + } while (0); 1.7964 + 1.7965 + /* START A NEW SESSION */ 1.7966 + 1.7967 +#ifndef PARANOID 1.7968 + /* Look for a matching cipher suite. */ 1.7969 + j = ssl3_config_match_init(ss); 1.7970 + if (j <= 0) { /* no ciphers are working/supported by PK11 */ 1.7971 + errCode = PORT_GetError(); /* error code is already set. */ 1.7972 + goto alert_loser; 1.7973 + } 1.7974 +#endif 1.7975 + 1.7976 + /* Select a cipher suite. 1.7977 + ** 1.7978 + ** NOTE: This suite selection algorithm should be the same as the one in 1.7979 + ** ssl3_HandleV2ClientHello(). 1.7980 + ** 1.7981 + ** If TLS 1.0 is enabled, we could handle the case where the client 1.7982 + ** offered TLS 1.1 but offered only export cipher suites by choosing TLS 1.7983 + ** 1.0 and selecting one of those export cipher suites. However, a secure 1.7984 + ** TLS 1.1 client should not have export cipher suites enabled at all, 1.7985 + ** and a TLS 1.1 client should definitely not be offering *only* export 1.7986 + ** cipher suites. Therefore, we refuse to negotiate export cipher suites 1.7987 + ** with any client that indicates support for TLS 1.1 or higher when we 1.7988 + ** (the server) have TLS 1.1 support enabled. 1.7989 + */ 1.7990 + for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { 1.7991 + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; 1.7992 + SSLVersionRange vrange = {ss->version, ss->version}; 1.7993 + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { 1.7994 + continue; 1.7995 + } 1.7996 + for (i = 0; i + 1 < suites.len; i += 2) { 1.7997 + PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1]; 1.7998 + if (suite_i == suite->cipher_suite) { 1.7999 + ss->ssl3.hs.cipher_suite = suite->cipher_suite; 1.8000 + ss->ssl3.hs.suite_def = 1.8001 + ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); 1.8002 + goto suite_found; 1.8003 + } 1.8004 + } 1.8005 + } 1.8006 + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 1.8007 + goto alert_loser; 1.8008 + 1.8009 +suite_found: 1.8010 + /* Select a compression algorithm. */ 1.8011 + for (i = 0; i < comps.len; i++) { 1.8012 + if (!compressionEnabled(ss, comps.data[i])) 1.8013 + continue; 1.8014 + for (j = 0; j < compressionMethodsCount; j++) { 1.8015 + if (comps.data[i] == compressions[j]) { 1.8016 + ss->ssl3.hs.compression = 1.8017 + (SSLCompressionMethod)compressions[j]; 1.8018 + goto compression_found; 1.8019 + } 1.8020 + } 1.8021 + } 1.8022 + errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; 1.8023 + /* null compression must be supported */ 1.8024 + goto alert_loser; 1.8025 + 1.8026 +compression_found: 1.8027 + suites.data = NULL; 1.8028 + comps.data = NULL; 1.8029 + 1.8030 + ss->sec.send = ssl3_SendApplicationData; 1.8031 + 1.8032 + /* If there are any failures while processing the old sid, 1.8033 + * we don't consider them to be errors. Instead, We just behave 1.8034 + * as if the client had sent us no sid to begin with, and make a new one. 1.8035 + */ 1.8036 + if (sid != NULL) do { 1.8037 + ssl3CipherSpec *pwSpec; 1.8038 + SECItem wrappedMS; /* wrapped key */ 1.8039 + 1.8040 + if (sid->version != ss->version || 1.8041 + sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || 1.8042 + sid->u.ssl3.compression != ss->ssl3.hs.compression) { 1.8043 + break; /* not an error */ 1.8044 + } 1.8045 + 1.8046 + if (ss->sec.ci.sid) { 1.8047 + if (ss->sec.uncache) 1.8048 + ss->sec.uncache(ss->sec.ci.sid); 1.8049 + PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */ 1.8050 + if (ss->sec.ci.sid != sid) { 1.8051 + ssl_FreeSID(ss->sec.ci.sid); 1.8052 + } 1.8053 + ss->sec.ci.sid = NULL; 1.8054 + } 1.8055 + /* we need to resurrect the master secret.... */ 1.8056 + 1.8057 + ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE; 1.8058 + pwSpec = ss->ssl3.pwSpec; 1.8059 + if (sid->u.ssl3.keys.msIsWrapped) { 1.8060 + PK11SymKey * wrapKey; /* wrapping key */ 1.8061 + CK_FLAGS keyFlags = 0; 1.8062 +#ifndef NO_PKCS11_BYPASS 1.8063 + if (ss->opt.bypassPKCS11) { 1.8064 + /* we cannot restart a non-bypass session in a 1.8065 + ** bypass socket. 1.8066 + */ 1.8067 + break; 1.8068 + } 1.8069 +#endif 1.8070 + 1.8071 + wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, 1.8072 + sid->u.ssl3.masterWrapMech, 1.8073 + ss->pkcs11PinArg); 1.8074 + if (!wrapKey) { 1.8075 + /* we have a SID cache entry, but no wrapping key for it??? */ 1.8076 + break; 1.8077 + } 1.8078 + 1.8079 + if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ 1.8080 + keyFlags = CKF_SIGN | CKF_VERIFY; 1.8081 + } 1.8082 + 1.8083 + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 1.8084 + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 1.8085 + 1.8086 + /* unwrap the master secret. */ 1.8087 + pwSpec->master_secret = 1.8088 + PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, 1.8089 + NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, 1.8090 + CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); 1.8091 + PK11_FreeSymKey(wrapKey); 1.8092 + if (pwSpec->master_secret == NULL) { 1.8093 + break; /* not an error */ 1.8094 + } 1.8095 +#ifndef NO_PKCS11_BYPASS 1.8096 + } else if (ss->opt.bypassPKCS11) { 1.8097 + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 1.8098 + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 1.8099 + memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); 1.8100 + pwSpec->msItem.data = pwSpec->raw_master_secret; 1.8101 + pwSpec->msItem.len = wrappedMS.len; 1.8102 +#endif 1.8103 + } else { 1.8104 + /* We CAN restart a bypass session in a non-bypass socket. */ 1.8105 + /* need to import the raw master secret to session object */ 1.8106 + PK11SlotInfo * slot; 1.8107 + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; 1.8108 + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; 1.8109 + slot = PK11_GetInternalSlot(); 1.8110 + pwSpec->master_secret = 1.8111 + PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, 1.8112 + PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, 1.8113 + NULL); 1.8114 + PK11_FreeSlot(slot); 1.8115 + if (pwSpec->master_secret == NULL) { 1.8116 + break; /* not an error */ 1.8117 + } 1.8118 + } 1.8119 + ss->sec.ci.sid = sid; 1.8120 + if (sid->peerCert != NULL) { 1.8121 + ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); 1.8122 + } 1.8123 + 1.8124 + /* 1.8125 + * Old SID passed all tests, so resume this old session. 1.8126 + * 1.8127 + * XXX make sure compression still matches 1.8128 + */ 1.8129 + SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits ); 1.8130 + if (ss->statelessResume) 1.8131 + SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes ); 1.8132 + ss->ssl3.hs.isResuming = PR_TRUE; 1.8133 + 1.8134 + ss->sec.authAlgorithm = sid->authAlgorithm; 1.8135 + ss->sec.authKeyBits = sid->authKeyBits; 1.8136 + ss->sec.keaType = sid->keaType; 1.8137 + ss->sec.keaKeyBits = sid->keaKeyBits; 1.8138 + 1.8139 + /* server sids don't remember the server cert we previously sent, 1.8140 + ** but they do remember the kea type we originally used, so we 1.8141 + ** can locate it again, provided that the current ssl socket 1.8142 + ** has had its server certs configured the same as the previous one. 1.8143 + */ 1.8144 + ss->sec.localCert = 1.8145 + CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert); 1.8146 + 1.8147 + /* Copy cached name in to pending spec */ 1.8148 + if (sid != NULL && 1.8149 + sid->version > SSL_LIBRARY_VERSION_3_0 && 1.8150 + sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) { 1.8151 + /* Set server name from sid */ 1.8152 + SECItem *sidName = &sid->u.ssl3.srvName; 1.8153 + SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName; 1.8154 + if (pwsName->data) { 1.8155 + SECITEM_FreeItem(pwsName, PR_FALSE); 1.8156 + } 1.8157 + rv = SECITEM_CopyItem(NULL, pwsName, sidName); 1.8158 + if (rv != SECSuccess) { 1.8159 + errCode = PORT_GetError(); 1.8160 + desc = internal_error; 1.8161 + goto alert_loser; 1.8162 + } 1.8163 + } 1.8164 + 1.8165 + /* Clean up sni name array */ 1.8166 + if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && 1.8167 + ss->xtnData.sniNameArr) { 1.8168 + PORT_Free(ss->xtnData.sniNameArr); 1.8169 + ss->xtnData.sniNameArr = NULL; 1.8170 + ss->xtnData.sniNameArrSize = 0; 1.8171 + } 1.8172 + 1.8173 + ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE; 1.8174 + 1.8175 + rv = ssl3_SendServerHello(ss); 1.8176 + if (rv != SECSuccess) { 1.8177 + errCode = PORT_GetError(); 1.8178 + goto loser; 1.8179 + } 1.8180 + 1.8181 + if (haveSpecWriteLock) { 1.8182 + ssl_ReleaseSpecWriteLock(ss); 1.8183 + haveSpecWriteLock = PR_FALSE; 1.8184 + } 1.8185 + 1.8186 + /* NULL value for PMS signifies re-use of the old MS */ 1.8187 + rv = ssl3_InitPendingCipherSpec(ss, NULL); 1.8188 + if (rv != SECSuccess) { 1.8189 + errCode = PORT_GetError(); 1.8190 + goto loser; 1.8191 + } 1.8192 + 1.8193 + rv = ssl3_SendChangeCipherSpecs(ss); 1.8194 + if (rv != SECSuccess) { 1.8195 + errCode = PORT_GetError(); 1.8196 + goto loser; 1.8197 + } 1.8198 + rv = ssl3_SendFinished(ss, 0); 1.8199 + ss->ssl3.hs.ws = wait_change_cipher; 1.8200 + if (rv != SECSuccess) { 1.8201 + errCode = PORT_GetError(); 1.8202 + goto loser; 1.8203 + } 1.8204 + 1.8205 + if (haveXmitBufLock) { 1.8206 + ssl_ReleaseXmitBufLock(ss); 1.8207 + haveXmitBufLock = PR_FALSE; 1.8208 + } 1.8209 + 1.8210 + return SECSuccess; 1.8211 + } while (0); 1.8212 + 1.8213 + if (haveSpecWriteLock) { 1.8214 + ssl_ReleaseSpecWriteLock(ss); 1.8215 + haveSpecWriteLock = PR_FALSE; 1.8216 + } 1.8217 + 1.8218 + if (sid) { /* we had a sid, but it's no longer valid, free it */ 1.8219 + SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); 1.8220 + if (ss->sec.uncache) 1.8221 + ss->sec.uncache(sid); 1.8222 + ssl_FreeSID(sid); 1.8223 + sid = NULL; 1.8224 + } 1.8225 + SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); 1.8226 + 1.8227 + if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { 1.8228 + int ret = 0; 1.8229 + if (ss->sniSocketConfig) do { /* not a loop */ 1.8230 + ret = SSL_SNI_SEND_ALERT; 1.8231 + /* If extension is negotiated, the len of names should > 0. */ 1.8232 + if (ss->xtnData.sniNameArrSize) { 1.8233 + /* Calling client callback to reconfigure the socket. */ 1.8234 + ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd, 1.8235 + ss->xtnData.sniNameArr, 1.8236 + ss->xtnData.sniNameArrSize, 1.8237 + ss->sniSocketConfigArg); 1.8238 + } 1.8239 + if (ret <= SSL_SNI_SEND_ALERT) { 1.8240 + /* Application does not know the name or was not able to 1.8241 + * properly reconfigure the socket. */ 1.8242 + errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 1.8243 + desc = unrecognized_name; 1.8244 + break; 1.8245 + } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { 1.8246 + SECStatus rv = SECSuccess; 1.8247 + SECItem * cwsName, *pwsName; 1.8248 + 1.8249 + ssl_GetSpecWriteLock(ss); /*******************************/ 1.8250 + pwsName = &ss->ssl3.pwSpec->srvVirtName; 1.8251 + cwsName = &ss->ssl3.cwSpec->srvVirtName; 1.8252 +#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS 1.8253 + /* not allow name change on the 2d HS */ 1.8254 + if (ss->firstHsDone) { 1.8255 + if (ssl3_ServerNameCompare(pwsName, cwsName)) { 1.8256 + ssl_ReleaseSpecWriteLock(ss); /******************/ 1.8257 + errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 1.8258 + desc = handshake_failure; 1.8259 + ret = SSL_SNI_SEND_ALERT; 1.8260 + break; 1.8261 + } 1.8262 + } 1.8263 +#endif 1.8264 + if (pwsName->data) { 1.8265 + SECITEM_FreeItem(pwsName, PR_FALSE); 1.8266 + } 1.8267 + if (cwsName->data) { 1.8268 + rv = SECITEM_CopyItem(NULL, pwsName, cwsName); 1.8269 + } 1.8270 + ssl_ReleaseSpecWriteLock(ss); /**************************/ 1.8271 + if (rv != SECSuccess) { 1.8272 + errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; 1.8273 + desc = internal_error; 1.8274 + ret = SSL_SNI_SEND_ALERT; 1.8275 + break; 1.8276 + } 1.8277 + } else if (ret < ss->xtnData.sniNameArrSize) { 1.8278 + /* Application has configured new socket info. Lets check it 1.8279 + * and save the name. */ 1.8280 + SECStatus rv; 1.8281 + SECItem * name = &ss->xtnData.sniNameArr[ret]; 1.8282 + int configedCiphers; 1.8283 + SECItem * pwsName; 1.8284 + 1.8285 + /* get rid of the old name and save the newly picked. */ 1.8286 + /* This code is protected by ssl3HandshakeLock. */ 1.8287 + ssl_GetSpecWriteLock(ss); /*******************************/ 1.8288 +#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS 1.8289 + /* not allow name change on the 2d HS */ 1.8290 + if (ss->firstHsDone) { 1.8291 + SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName; 1.8292 + if (ssl3_ServerNameCompare(name, cwsName)) { 1.8293 + ssl_ReleaseSpecWriteLock(ss); /******************/ 1.8294 + errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 1.8295 + desc = handshake_failure; 1.8296 + ret = SSL_SNI_SEND_ALERT; 1.8297 + break; 1.8298 + } 1.8299 + } 1.8300 +#endif 1.8301 + pwsName = &ss->ssl3.pwSpec->srvVirtName; 1.8302 + if (pwsName->data) { 1.8303 + SECITEM_FreeItem(pwsName, PR_FALSE); 1.8304 + } 1.8305 + rv = SECITEM_CopyItem(NULL, pwsName, name); 1.8306 + ssl_ReleaseSpecWriteLock(ss); /***************************/ 1.8307 + if (rv != SECSuccess) { 1.8308 + errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; 1.8309 + desc = internal_error; 1.8310 + ret = SSL_SNI_SEND_ALERT; 1.8311 + break; 1.8312 + } 1.8313 + configedCiphers = ssl3_config_match_init(ss); 1.8314 + if (configedCiphers <= 0) { 1.8315 + /* no ciphers are working/supported */ 1.8316 + errCode = PORT_GetError(); 1.8317 + desc = handshake_failure; 1.8318 + ret = SSL_SNI_SEND_ALERT; 1.8319 + break; 1.8320 + } 1.8321 + /* Need to tell the client that application has picked 1.8322 + * the name from the offered list and reconfigured the socket. 1.8323 + */ 1.8324 + ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn, 1.8325 + ssl3_SendServerNameXtn); 1.8326 + } else { 1.8327 + /* Callback returned index outside of the boundary. */ 1.8328 + PORT_Assert(ret < ss->xtnData.sniNameArrSize); 1.8329 + errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; 1.8330 + desc = internal_error; 1.8331 + ret = SSL_SNI_SEND_ALERT; 1.8332 + break; 1.8333 + } 1.8334 + } while (0); 1.8335 + /* Free sniNameArr. The data that each SECItem in the array 1.8336 + * points into is the data from the input buffer "b". It will 1.8337 + * not be available outside the scope of this or it's child 1.8338 + * functions.*/ 1.8339 + if (ss->xtnData.sniNameArr) { 1.8340 + PORT_Free(ss->xtnData.sniNameArr); 1.8341 + ss->xtnData.sniNameArr = NULL; 1.8342 + ss->xtnData.sniNameArrSize = 0; 1.8343 + } 1.8344 + if (ret <= SSL_SNI_SEND_ALERT) { 1.8345 + /* desc and errCode should be set. */ 1.8346 + goto alert_loser; 1.8347 + } 1.8348 + } 1.8349 +#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS 1.8350 + else if (ss->firstHsDone) { 1.8351 + /* Check that we don't have the name is current spec 1.8352 + * if this extension was not negotiated on the 2d hs. */ 1.8353 + PRBool passed = PR_TRUE; 1.8354 + ssl_GetSpecReadLock(ss); /*******************************/ 1.8355 + if (ss->ssl3.cwSpec->srvVirtName.data) { 1.8356 + passed = PR_FALSE; 1.8357 + } 1.8358 + ssl_ReleaseSpecReadLock(ss); /***************************/ 1.8359 + if (!passed) { 1.8360 + errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; 1.8361 + desc = handshake_failure; 1.8362 + goto alert_loser; 1.8363 + } 1.8364 + } 1.8365 +#endif 1.8366 + 1.8367 + sid = ssl3_NewSessionID(ss, PR_TRUE); 1.8368 + if (sid == NULL) { 1.8369 + errCode = PORT_GetError(); 1.8370 + goto loser; /* memory error is set. */ 1.8371 + } 1.8372 + ss->sec.ci.sid = sid; 1.8373 + 1.8374 + ss->ssl3.hs.isResuming = PR_FALSE; 1.8375 + ssl_GetXmitBufLock(ss); 1.8376 + rv = ssl3_SendServerHelloSequence(ss); 1.8377 + ssl_ReleaseXmitBufLock(ss); 1.8378 + if (rv != SECSuccess) { 1.8379 + errCode = PORT_GetError(); 1.8380 + goto loser; 1.8381 + } 1.8382 + 1.8383 + if (haveXmitBufLock) { 1.8384 + ssl_ReleaseXmitBufLock(ss); 1.8385 + haveXmitBufLock = PR_FALSE; 1.8386 + } 1.8387 + 1.8388 + return SECSuccess; 1.8389 + 1.8390 +alert_loser: 1.8391 + if (haveSpecWriteLock) { 1.8392 + ssl_ReleaseSpecWriteLock(ss); 1.8393 + haveSpecWriteLock = PR_FALSE; 1.8394 + } 1.8395 + (void)SSL3_SendAlert(ss, level, desc); 1.8396 + /* FALLTHRU */ 1.8397 +loser: 1.8398 + if (haveSpecWriteLock) { 1.8399 + ssl_ReleaseSpecWriteLock(ss); 1.8400 + haveSpecWriteLock = PR_FALSE; 1.8401 + } 1.8402 + 1.8403 + if (haveXmitBufLock) { 1.8404 + ssl_ReleaseXmitBufLock(ss); 1.8405 + haveXmitBufLock = PR_FALSE; 1.8406 + } 1.8407 + 1.8408 + PORT_SetError(errCode); 1.8409 + return SECFailure; 1.8410 +} 1.8411 + 1.8412 +/* 1.8413 + * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes 1.8414 + * in asking to use the V3 handshake. 1.8415 + * Called from ssl2_HandleClientHelloMessage() in sslcon.c 1.8416 + */ 1.8417 +SECStatus 1.8418 +ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) 1.8419 +{ 1.8420 + sslSessionID * sid = NULL; 1.8421 + unsigned char * suites; 1.8422 + unsigned char * random; 1.8423 + SSL3ProtocolVersion version; 1.8424 + SECStatus rv; 1.8425 + int i; 1.8426 + int j; 1.8427 + int sid_length; 1.8428 + int suite_length; 1.8429 + int rand_length; 1.8430 + int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; 1.8431 + SSL3AlertDescription desc = handshake_failure; 1.8432 + 1.8433 + SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd)); 1.8434 + 1.8435 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.8436 + 1.8437 + ssl_GetSSL3HandshakeLock(ss); 1.8438 + 1.8439 + PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 1.8440 + 1.8441 + rv = ssl3_InitState(ss); 1.8442 + if (rv != SECSuccess) { 1.8443 + ssl_ReleaseSSL3HandshakeLock(ss); 1.8444 + return rv; /* ssl3_InitState has set the error code. */ 1.8445 + } 1.8446 + rv = ssl3_RestartHandshakeHashes(ss); 1.8447 + if (rv != SECSuccess) { 1.8448 + ssl_ReleaseSSL3HandshakeLock(ss); 1.8449 + return rv; 1.8450 + } 1.8451 + 1.8452 + if (ss->ssl3.hs.ws != wait_client_hello) { 1.8453 + desc = unexpected_message; 1.8454 + errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; 1.8455 + goto loser; /* alert_loser */ 1.8456 + } 1.8457 + 1.8458 + version = (buffer[1] << 8) | buffer[2]; 1.8459 + suite_length = (buffer[3] << 8) | buffer[4]; 1.8460 + sid_length = (buffer[5] << 8) | buffer[6]; 1.8461 + rand_length = (buffer[7] << 8) | buffer[8]; 1.8462 + ss->clientHelloVersion = version; 1.8463 + 1.8464 + rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); 1.8465 + if (rv != SECSuccess) { 1.8466 + /* send back which ever alert client will understand. */ 1.8467 + desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure; 1.8468 + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 1.8469 + goto alert_loser; 1.8470 + } 1.8471 + 1.8472 + rv = ssl3_InitHandshakeHashes(ss); 1.8473 + if (rv != SECSuccess) { 1.8474 + desc = internal_error; 1.8475 + errCode = PORT_GetError(); 1.8476 + goto alert_loser; 1.8477 + } 1.8478 + 1.8479 + /* if we get a non-zero SID, just ignore it. */ 1.8480 + if (length != 1.8481 + SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) { 1.8482 + SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", 1.8483 + SSL_GETPID(), ss->fd, length, 1.8484 + SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + 1.8485 + rand_length)); 1.8486 + goto loser; /* malformed */ /* alert_loser */ 1.8487 + } 1.8488 + 1.8489 + suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES; 1.8490 + random = suites + suite_length + sid_length; 1.8491 + 1.8492 + if (rand_length < SSL_MIN_CHALLENGE_BYTES || 1.8493 + rand_length > SSL_MAX_CHALLENGE_BYTES) { 1.8494 + goto loser; /* malformed */ /* alert_loser */ 1.8495 + } 1.8496 + 1.8497 + PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH); 1.8498 + 1.8499 + PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); 1.8500 + PORT_Memcpy( 1.8501 + &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], 1.8502 + random, rand_length); 1.8503 + 1.8504 + PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0], 1.8505 + SSL3_RANDOM_LENGTH)); 1.8506 +#ifndef NSS_DISABLE_ECC 1.8507 + /* Disable any ECC cipher suites for which we have no cert. */ 1.8508 + ssl3_FilterECCipherSuitesByServerCerts(ss); 1.8509 +#endif 1.8510 + i = ssl3_config_match_init(ss); 1.8511 + if (i <= 0) { 1.8512 + errCode = PORT_GetError(); /* error code is already set. */ 1.8513 + goto alert_loser; 1.8514 + } 1.8515 + 1.8516 + /* Select a cipher suite. 1.8517 + ** 1.8518 + ** NOTE: This suite selection algorithm should be the same as the one in 1.8519 + ** ssl3_HandleClientHello(). 1.8520 + ** 1.8521 + ** See the comments about export cipher suites in ssl3_HandleClientHello(). 1.8522 + */ 1.8523 + for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { 1.8524 + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; 1.8525 + SSLVersionRange vrange = {ss->version, ss->version}; 1.8526 + if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) { 1.8527 + continue; 1.8528 + } 1.8529 + for (i = 0; i+2 < suite_length; i += 3) { 1.8530 + PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2]; 1.8531 + if (suite_i == suite->cipher_suite) { 1.8532 + ss->ssl3.hs.cipher_suite = suite->cipher_suite; 1.8533 + ss->ssl3.hs.suite_def = 1.8534 + ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); 1.8535 + goto suite_found; 1.8536 + } 1.8537 + } 1.8538 + } 1.8539 + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; 1.8540 + goto alert_loser; 1.8541 + 1.8542 +suite_found: 1.8543 + 1.8544 + /* Look for the SCSV, and if found, treat it just like an empty RI 1.8545 + * extension by processing a local copy of an empty RI extension. 1.8546 + */ 1.8547 + for (i = 0; i+2 < suite_length; i += 3) { 1.8548 + PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2]; 1.8549 + if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { 1.8550 + SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; 1.8551 + PRUint32 L2 = sizeof emptyRIext; 1.8552 + (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); 1.8553 + break; 1.8554 + } 1.8555 + } 1.8556 + 1.8557 + if (ss->opt.requireSafeNegotiation && 1.8558 + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { 1.8559 + desc = handshake_failure; 1.8560 + errCode = SSL_ERROR_UNSAFE_NEGOTIATION; 1.8561 + goto alert_loser; 1.8562 + } 1.8563 + 1.8564 + ss->ssl3.hs.compression = ssl_compression_null; 1.8565 + ss->sec.send = ssl3_SendApplicationData; 1.8566 + 1.8567 + /* we don't even search for a cache hit here. It's just a miss. */ 1.8568 + SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); 1.8569 + sid = ssl3_NewSessionID(ss, PR_TRUE); 1.8570 + if (sid == NULL) { 1.8571 + errCode = PORT_GetError(); 1.8572 + goto loser; /* memory error is set. */ 1.8573 + } 1.8574 + ss->sec.ci.sid = sid; 1.8575 + /* do not worry about memory leak of sid since it now belongs to ci */ 1.8576 + 1.8577 + /* We have to update the handshake hashes before we can send stuff */ 1.8578 + rv = ssl3_UpdateHandshakeHashes(ss, buffer, length); 1.8579 + if (rv != SECSuccess) { 1.8580 + errCode = PORT_GetError(); 1.8581 + goto loser; 1.8582 + } 1.8583 + 1.8584 + ssl_GetXmitBufLock(ss); 1.8585 + rv = ssl3_SendServerHelloSequence(ss); 1.8586 + ssl_ReleaseXmitBufLock(ss); 1.8587 + if (rv != SECSuccess) { 1.8588 + errCode = PORT_GetError(); 1.8589 + goto loser; 1.8590 + } 1.8591 + 1.8592 + /* XXX_1 The call stack to here is: 1.8593 + * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here. 1.8594 + * ssl2_HandleClientHelloMessage returns whatever we return here. 1.8595 + * ssl_Do1stHandshake will continue looping if it gets back either 1.8596 + * SECSuccess or SECWouldBlock. 1.8597 + * SECSuccess is preferable here. See XXX_1 in sslgathr.c. 1.8598 + */ 1.8599 + ssl_ReleaseSSL3HandshakeLock(ss); 1.8600 + return SECSuccess; 1.8601 + 1.8602 +alert_loser: 1.8603 + SSL3_SendAlert(ss, alert_fatal, desc); 1.8604 +loser: 1.8605 + ssl_ReleaseSSL3HandshakeLock(ss); 1.8606 + PORT_SetError(errCode); 1.8607 + return SECFailure; 1.8608 +} 1.8609 + 1.8610 +/* The negotiated version number has been already placed in ss->version. 1.8611 +** 1.8612 +** Called from: ssl3_HandleClientHello (resuming session), 1.8613 +** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), 1.8614 +** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) 1.8615 +*/ 1.8616 +static SECStatus 1.8617 +ssl3_SendServerHello(sslSocket *ss) 1.8618 +{ 1.8619 + sslSessionID *sid; 1.8620 + SECStatus rv; 1.8621 + PRUint32 maxBytes = 65535; 1.8622 + PRUint32 length; 1.8623 + PRInt32 extensions_len = 0; 1.8624 + SSL3ProtocolVersion version; 1.8625 + 1.8626 + SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), 1.8627 + ss->fd)); 1.8628 + 1.8629 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.8630 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.8631 + 1.8632 + if (!IS_DTLS(ss)) { 1.8633 + PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0)); 1.8634 + 1.8635 + if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) { 1.8636 + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 1.8637 + return SECFailure; 1.8638 + } 1.8639 + } else { 1.8640 + PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); 1.8641 + 1.8642 + if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { 1.8643 + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); 1.8644 + return SECFailure; 1.8645 + } 1.8646 + } 1.8647 + 1.8648 + sid = ss->sec.ci.sid; 1.8649 + 1.8650 + extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, 1.8651 + &ss->xtnData.serverSenders[0]); 1.8652 + if (extensions_len > 0) 1.8653 + extensions_len += 2; /* Add sizeof total extension length */ 1.8654 + 1.8655 + length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 + 1.8656 + ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) + 1.8657 + sizeof(ssl3CipherSuite) + 1 + extensions_len; 1.8658 + rv = ssl3_AppendHandshakeHeader(ss, server_hello, length); 1.8659 + if (rv != SECSuccess) { 1.8660 + return rv; /* err set by AppendHandshake. */ 1.8661 + } 1.8662 + 1.8663 + if (IS_DTLS(ss)) { 1.8664 + version = dtls_TLSVersionToDTLSVersion(ss->version); 1.8665 + } else { 1.8666 + version = ss->version; 1.8667 + } 1.8668 + 1.8669 + rv = ssl3_AppendHandshakeNumber(ss, version, 2); 1.8670 + if (rv != SECSuccess) { 1.8671 + return rv; /* err set by AppendHandshake. */ 1.8672 + } 1.8673 + rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random); 1.8674 + if (rv != SECSuccess) { 1.8675 + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); 1.8676 + return rv; 1.8677 + } 1.8678 + rv = ssl3_AppendHandshake( 1.8679 + ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); 1.8680 + if (rv != SECSuccess) { 1.8681 + return rv; /* err set by AppendHandshake. */ 1.8682 + } 1.8683 + 1.8684 + if (sid) 1.8685 + rv = ssl3_AppendHandshakeVariable( 1.8686 + ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); 1.8687 + else 1.8688 + rv = ssl3_AppendHandshakeNumber(ss, 0, 1); 1.8689 + if (rv != SECSuccess) { 1.8690 + return rv; /* err set by AppendHandshake. */ 1.8691 + } 1.8692 + 1.8693 + rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2); 1.8694 + if (rv != SECSuccess) { 1.8695 + return rv; /* err set by AppendHandshake. */ 1.8696 + } 1.8697 + rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); 1.8698 + if (rv != SECSuccess) { 1.8699 + return rv; /* err set by AppendHandshake. */ 1.8700 + } 1.8701 + if (extensions_len) { 1.8702 + PRInt32 sent_len; 1.8703 + 1.8704 + extensions_len -= 2; 1.8705 + rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); 1.8706 + if (rv != SECSuccess) 1.8707 + return rv; /* err set by ssl3_SetupPendingCipherSpec */ 1.8708 + sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, 1.8709 + &ss->xtnData.serverSenders[0]); 1.8710 + PORT_Assert(sent_len == extensions_len); 1.8711 + if (sent_len != extensions_len) { 1.8712 + if (sent_len >= 0) 1.8713 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.8714 + return SECFailure; 1.8715 + } 1.8716 + } 1.8717 + rv = ssl3_SetupPendingCipherSpec(ss); 1.8718 + if (rv != SECSuccess) { 1.8719 + return rv; /* err set by ssl3_SetupPendingCipherSpec */ 1.8720 + } 1.8721 + 1.8722 + return SECSuccess; 1.8723 +} 1.8724 + 1.8725 +/* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing 1.8726 + * elements of the handshake. (The negotiated cipher suite determines the 1.8727 + * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always 1.8728 + * used. With TLS 1.2, a client may advertise its support for signature and 1.8729 + * hash combinations. */ 1.8730 +static SECStatus 1.8731 +ssl3_PickSignatureHashAlgorithm(sslSocket *ss, 1.8732 + SSL3SignatureAndHashAlgorithm* out) 1.8733 +{ 1.8734 + TLSSignatureAlgorithm sigAlg; 1.8735 + unsigned int i, j; 1.8736 + /* hashPreference expresses our preferences for hash algorithms, most 1.8737 + * preferable first. */ 1.8738 + static const PRUint8 hashPreference[] = { 1.8739 + tls_hash_sha256, 1.8740 + tls_hash_sha384, 1.8741 + tls_hash_sha512, 1.8742 + tls_hash_sha1, 1.8743 + }; 1.8744 + 1.8745 + switch (ss->ssl3.hs.kea_def->kea) { 1.8746 + case kea_rsa: 1.8747 + case kea_rsa_export: 1.8748 + case kea_rsa_export_1024: 1.8749 + case kea_dh_rsa: 1.8750 + case kea_dh_rsa_export: 1.8751 + case kea_dhe_rsa: 1.8752 + case kea_dhe_rsa_export: 1.8753 + case kea_rsa_fips: 1.8754 + case kea_ecdh_rsa: 1.8755 + case kea_ecdhe_rsa: 1.8756 + sigAlg = tls_sig_rsa; 1.8757 + break; 1.8758 + case kea_dh_dss: 1.8759 + case kea_dh_dss_export: 1.8760 + case kea_dhe_dss: 1.8761 + case kea_dhe_dss_export: 1.8762 + sigAlg = tls_sig_dsa; 1.8763 + break; 1.8764 + case kea_ecdh_ecdsa: 1.8765 + case kea_ecdhe_ecdsa: 1.8766 + sigAlg = tls_sig_ecdsa; 1.8767 + break; 1.8768 + default: 1.8769 + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 1.8770 + return SECFailure; 1.8771 + } 1.8772 + out->sigAlg = sigAlg; 1.8773 + 1.8774 + if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) { 1.8775 + /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and 1.8776 + * prior. */ 1.8777 + out->hashAlg = SEC_OID_UNKNOWN; 1.8778 + return SECSuccess; 1.8779 + } 1.8780 + 1.8781 + if (ss->ssl3.hs.numClientSigAndHash == 0) { 1.8782 + /* If the client didn't provide any signature_algorithms extension then 1.8783 + * we can assume that they support SHA-1: 1.8784 + * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ 1.8785 + out->hashAlg = SEC_OID_SHA1; 1.8786 + return SECSuccess; 1.8787 + } 1.8788 + 1.8789 + for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) { 1.8790 + for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) { 1.8791 + const SSL3SignatureAndHashAlgorithm* sh = 1.8792 + &ss->ssl3.hs.clientSigAndHash[j]; 1.8793 + if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) { 1.8794 + out->hashAlg = sh->hashAlg; 1.8795 + return SECSuccess; 1.8796 + } 1.8797 + } 1.8798 + } 1.8799 + 1.8800 + PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); 1.8801 + return SECFailure; 1.8802 +} 1.8803 + 1.8804 + 1.8805 +static SECStatus 1.8806 +ssl3_SendServerKeyExchange(sslSocket *ss) 1.8807 +{ 1.8808 + const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; 1.8809 + SECStatus rv = SECFailure; 1.8810 + int length; 1.8811 + PRBool isTLS; 1.8812 + SECItem signed_hash = {siBuffer, NULL, 0}; 1.8813 + SSL3Hashes hashes; 1.8814 + SECKEYPublicKey * sdPub; /* public key for step-down */ 1.8815 + SSL3SignatureAndHashAlgorithm sigAndHash; 1.8816 + 1.8817 + SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", 1.8818 + SSL_GETPID(), ss->fd)); 1.8819 + 1.8820 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.8821 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.8822 + 1.8823 + if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { 1.8824 + return SECFailure; 1.8825 + } 1.8826 + 1.8827 + switch (kea_def->exchKeyType) { 1.8828 + case kt_rsa: 1.8829 + /* Perform SSL Step-Down here. */ 1.8830 + sdPub = ss->stepDownKeyPair->pubKey; 1.8831 + PORT_Assert(sdPub != NULL); 1.8832 + if (!sdPub) { 1.8833 + PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.8834 + return SECFailure; 1.8835 + } 1.8836 + rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, 1.8837 + sdPub->u.rsa.modulus, 1.8838 + sdPub->u.rsa.publicExponent, 1.8839 + &ss->ssl3.hs.client_random, 1.8840 + &ss->ssl3.hs.server_random, 1.8841 + &hashes, ss->opt.bypassPKCS11); 1.8842 + if (rv != SECSuccess) { 1.8843 + ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.8844 + return rv; 1.8845 + } 1.8846 + 1.8847 + isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); 1.8848 + rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, 1.8849 + &signed_hash, isTLS); 1.8850 + if (rv != SECSuccess) { 1.8851 + goto loser; /* ssl3_SignHashes has set err. */ 1.8852 + } 1.8853 + if (signed_hash.data == NULL) { 1.8854 + /* how can this happen and rv == SECSuccess ?? */ 1.8855 + PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); 1.8856 + goto loser; 1.8857 + } 1.8858 + length = 2 + sdPub->u.rsa.modulus.len + 1.8859 + 2 + sdPub->u.rsa.publicExponent.len + 1.8860 + 2 + signed_hash.len; 1.8861 + 1.8862 + rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); 1.8863 + if (rv != SECSuccess) { 1.8864 + goto loser; /* err set by AppendHandshake. */ 1.8865 + } 1.8866 + 1.8867 + rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, 1.8868 + sdPub->u.rsa.modulus.len, 2); 1.8869 + if (rv != SECSuccess) { 1.8870 + goto loser; /* err set by AppendHandshake. */ 1.8871 + } 1.8872 + 1.8873 + rv = ssl3_AppendHandshakeVariable( 1.8874 + ss, sdPub->u.rsa.publicExponent.data, 1.8875 + sdPub->u.rsa.publicExponent.len, 2); 1.8876 + if (rv != SECSuccess) { 1.8877 + goto loser; /* err set by AppendHandshake. */ 1.8878 + } 1.8879 + 1.8880 + if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 1.8881 + rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); 1.8882 + if (rv != SECSuccess) { 1.8883 + goto loser; /* err set by AppendHandshake. */ 1.8884 + } 1.8885 + } 1.8886 + 1.8887 + rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data, 1.8888 + signed_hash.len, 2); 1.8889 + if (rv != SECSuccess) { 1.8890 + goto loser; /* err set by AppendHandshake. */ 1.8891 + } 1.8892 + PORT_Free(signed_hash.data); 1.8893 + return SECSuccess; 1.8894 + 1.8895 +#ifndef NSS_DISABLE_ECC 1.8896 + case kt_ecdh: { 1.8897 + rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); 1.8898 + return rv; 1.8899 + } 1.8900 +#endif /* NSS_DISABLE_ECC */ 1.8901 + 1.8902 + case kt_dh: 1.8903 + case kt_null: 1.8904 + default: 1.8905 + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 1.8906 + break; 1.8907 + } 1.8908 +loser: 1.8909 + if (signed_hash.data != NULL) 1.8910 + PORT_Free(signed_hash.data); 1.8911 + return SECFailure; 1.8912 +} 1.8913 + 1.8914 + 1.8915 +static SECStatus 1.8916 +ssl3_SendCertificateRequest(sslSocket *ss) 1.8917 +{ 1.8918 + PRBool isTLS12; 1.8919 + SECItem * name; 1.8920 + CERTDistNames *ca_list; 1.8921 + const PRUint8 *certTypes; 1.8922 + const PRUint8 *sigAlgs; 1.8923 + SECItem * names = NULL; 1.8924 + SECStatus rv; 1.8925 + int length; 1.8926 + int i; 1.8927 + int calen = 0; 1.8928 + int nnames = 0; 1.8929 + int certTypesLength; 1.8930 + int sigAlgsLength; 1.8931 + 1.8932 + SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", 1.8933 + SSL_GETPID(), ss->fd)); 1.8934 + 1.8935 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.8936 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.8937 + 1.8938 + isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 1.8939 + 1.8940 + /* ssl3.ca_list is initialized to NULL, and never changed. */ 1.8941 + ca_list = ss->ssl3.ca_list; 1.8942 + if (!ca_list) { 1.8943 + ca_list = ssl3_server_ca_list; 1.8944 + } 1.8945 + 1.8946 + if (ca_list != NULL) { 1.8947 + names = ca_list->names; 1.8948 + nnames = ca_list->nnames; 1.8949 + } 1.8950 + 1.8951 + for (i = 0, name = names; i < nnames; i++, name++) { 1.8952 + calen += 2 + name->len; 1.8953 + } 1.8954 + 1.8955 + certTypes = certificate_types; 1.8956 + certTypesLength = sizeof certificate_types; 1.8957 + sigAlgs = supported_signature_algorithms; 1.8958 + sigAlgsLength = sizeof supported_signature_algorithms; 1.8959 + 1.8960 + length = 1 + certTypesLength + 2 + calen; 1.8961 + if (isTLS12) { 1.8962 + length += 2 + sigAlgsLength; 1.8963 + } 1.8964 + 1.8965 + rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); 1.8966 + if (rv != SECSuccess) { 1.8967 + return rv; /* err set by AppendHandshake. */ 1.8968 + } 1.8969 + rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); 1.8970 + if (rv != SECSuccess) { 1.8971 + return rv; /* err set by AppendHandshake. */ 1.8972 + } 1.8973 + if (isTLS12) { 1.8974 + rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); 1.8975 + if (rv != SECSuccess) { 1.8976 + return rv; /* err set by AppendHandshake. */ 1.8977 + } 1.8978 + } 1.8979 + rv = ssl3_AppendHandshakeNumber(ss, calen, 2); 1.8980 + if (rv != SECSuccess) { 1.8981 + return rv; /* err set by AppendHandshake. */ 1.8982 + } 1.8983 + for (i = 0, name = names; i < nnames; i++, name++) { 1.8984 + rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); 1.8985 + if (rv != SECSuccess) { 1.8986 + return rv; /* err set by AppendHandshake. */ 1.8987 + } 1.8988 + } 1.8989 + 1.8990 + return SECSuccess; 1.8991 +} 1.8992 + 1.8993 +static SECStatus 1.8994 +ssl3_SendServerHelloDone(sslSocket *ss) 1.8995 +{ 1.8996 + SECStatus rv; 1.8997 + 1.8998 + SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", 1.8999 + SSL_GETPID(), ss->fd)); 1.9000 + 1.9001 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.9002 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.9003 + 1.9004 + rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0); 1.9005 + if (rv != SECSuccess) { 1.9006 + return rv; /* err set by AppendHandshake. */ 1.9007 + } 1.9008 + rv = ssl3_FlushHandshake(ss, 0); 1.9009 + if (rv != SECSuccess) { 1.9010 + return rv; /* error code set by ssl3_FlushHandshake */ 1.9011 + } 1.9012 + return SECSuccess; 1.9013 +} 1.9014 + 1.9015 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.9016 + * ssl3 Certificate Verify message 1.9017 + * Caller must hold Handshake and RecvBuf locks. 1.9018 + */ 1.9019 +static SECStatus 1.9020 +ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length, 1.9021 + SSL3Hashes *hashes) 1.9022 +{ 1.9023 + SECItem signed_hash = {siBuffer, NULL, 0}; 1.9024 + SECStatus rv; 1.9025 + int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; 1.9026 + SSL3AlertDescription desc = handshake_failure; 1.9027 + PRBool isTLS, isTLS12; 1.9028 + SSL3SignatureAndHashAlgorithm sigAndHash; 1.9029 + 1.9030 + SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake", 1.9031 + SSL_GETPID(), ss->fd)); 1.9032 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.9033 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.9034 + 1.9035 + isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 1.9036 + isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); 1.9037 + 1.9038 + if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) { 1.9039 + desc = unexpected_message; 1.9040 + errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; 1.9041 + goto alert_loser; 1.9042 + } 1.9043 + 1.9044 + if (isTLS12) { 1.9045 + rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, 1.9046 + &sigAndHash); 1.9047 + if (rv != SECSuccess) { 1.9048 + goto loser; /* malformed or unsupported. */ 1.9049 + } 1.9050 + rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( 1.9051 + &sigAndHash, ss->sec.peerCert); 1.9052 + if (rv != SECSuccess) { 1.9053 + errCode = PORT_GetError(); 1.9054 + desc = decrypt_error; 1.9055 + goto alert_loser; 1.9056 + } 1.9057 + 1.9058 + /* We only support CertificateVerify messages that use the handshake 1.9059 + * hash. */ 1.9060 + if (sigAndHash.hashAlg != hashes->hashAlg) { 1.9061 + errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; 1.9062 + desc = decrypt_error; 1.9063 + goto alert_loser; 1.9064 + } 1.9065 + } 1.9066 + 1.9067 + rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); 1.9068 + if (rv != SECSuccess) { 1.9069 + goto loser; /* malformed. */ 1.9070 + } 1.9071 + 1.9072 + /* XXX verify that the key & kea match */ 1.9073 + rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash, 1.9074 + isTLS, ss->pkcs11PinArg); 1.9075 + if (rv != SECSuccess) { 1.9076 + errCode = PORT_GetError(); 1.9077 + desc = isTLS ? decrypt_error : handshake_failure; 1.9078 + goto alert_loser; 1.9079 + } 1.9080 + 1.9081 + signed_hash.data = NULL; 1.9082 + 1.9083 + if (length != 0) { 1.9084 + desc = isTLS ? decode_error : illegal_parameter; 1.9085 + goto alert_loser; /* malformed */ 1.9086 + } 1.9087 + ss->ssl3.hs.ws = wait_change_cipher; 1.9088 + return SECSuccess; 1.9089 + 1.9090 +alert_loser: 1.9091 + SSL3_SendAlert(ss, alert_fatal, desc); 1.9092 +loser: 1.9093 + PORT_SetError(errCode); 1.9094 + return SECFailure; 1.9095 +} 1.9096 + 1.9097 + 1.9098 +/* find a slot that is able to generate a PMS and wrap it with RSA. 1.9099 + * Then generate and return the PMS. 1.9100 + * If the serverKeySlot parameter is non-null, this function will use 1.9101 + * that slot to do the job, otherwise it will find a slot. 1.9102 + * 1.9103 + * Called from ssl3_DeriveConnectionKeysPKCS11() (above) 1.9104 + * sendRSAClientKeyExchange() (above) 1.9105 + * ssl3_HandleRSAClientKeyExchange() (below) 1.9106 + * Caller must hold the SpecWriteLock, the SSL3HandshakeLock 1.9107 + */ 1.9108 +static PK11SymKey * 1.9109 +ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, 1.9110 + PK11SlotInfo * serverKeySlot) 1.9111 +{ 1.9112 + PK11SymKey * pms = NULL; 1.9113 + PK11SlotInfo * slot = serverKeySlot; 1.9114 + void * pwArg = ss->pkcs11PinArg; 1.9115 + SECItem param; 1.9116 + CK_VERSION version; 1.9117 + CK_MECHANISM_TYPE mechanism_array[3]; 1.9118 + 1.9119 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.9120 + 1.9121 + if (slot == NULL) { 1.9122 + SSLCipherAlgorithm calg; 1.9123 + /* The specReadLock would suffice here, but we cannot assert on 1.9124 + ** read locks. Also, all the callers who call with a non-null 1.9125 + ** slot already hold the SpecWriteLock. 1.9126 + */ 1.9127 + PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); 1.9128 + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); 1.9129 + 1.9130 + calg = spec->cipher_def->calg; 1.9131 + PORT_Assert(alg2Mech[calg].calg == calg); 1.9132 + 1.9133 + /* First get an appropriate slot. */ 1.9134 + mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; 1.9135 + mechanism_array[1] = CKM_RSA_PKCS; 1.9136 + mechanism_array[2] = alg2Mech[calg].cmech; 1.9137 + 1.9138 + slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg); 1.9139 + if (slot == NULL) { 1.9140 + /* can't find a slot with all three, find a slot with the minimum */ 1.9141 + slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); 1.9142 + if (slot == NULL) { 1.9143 + PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); 1.9144 + return pms; /* which is NULL */ 1.9145 + } 1.9146 + } 1.9147 + } 1.9148 + 1.9149 + /* Generate the pre-master secret ... */ 1.9150 + if (IS_DTLS(ss)) { 1.9151 + SSL3ProtocolVersion temp; 1.9152 + 1.9153 + temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); 1.9154 + version.major = MSB(temp); 1.9155 + version.minor = LSB(temp); 1.9156 + } else { 1.9157 + version.major = MSB(ss->clientHelloVersion); 1.9158 + version.minor = LSB(ss->clientHelloVersion); 1.9159 + } 1.9160 + 1.9161 + param.data = (unsigned char *)&version; 1.9162 + param.len = sizeof version; 1.9163 + 1.9164 + pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); 1.9165 + if (!serverKeySlot) 1.9166 + PK11_FreeSlot(slot); 1.9167 + if (pms == NULL) { 1.9168 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.9169 + } 1.9170 + return pms; 1.9171 +} 1.9172 + 1.9173 +/* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER 1.9174 + * return any indication of failure of the Client Key Exchange message, 1.9175 + * where that failure is caused by the content of the client's message. 1.9176 + * This function must not return SECFailure for any reason that is directly 1.9177 + * or indirectly caused by the content of the client's encrypted PMS. 1.9178 + * We must not send an alert and also not drop the connection. 1.9179 + * Instead, we generate a random PMS. This will cause a failure 1.9180 + * in the processing the finished message, which is exactly where 1.9181 + * the failure must occur. 1.9182 + * 1.9183 + * Called from ssl3_HandleClientKeyExchange 1.9184 + */ 1.9185 +static SECStatus 1.9186 +ssl3_HandleRSAClientKeyExchange(sslSocket *ss, 1.9187 + SSL3Opaque *b, 1.9188 + PRUint32 length, 1.9189 + SECKEYPrivateKey *serverKey) 1.9190 +{ 1.9191 + PK11SymKey * pms; 1.9192 +#ifndef NO_PKCS11_BYPASS 1.9193 + unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; 1.9194 + unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; 1.9195 + ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; 1.9196 + unsigned int outLen = 0; 1.9197 +#endif 1.9198 + PRBool isTLS = PR_FALSE; 1.9199 + SECStatus rv; 1.9200 + SECItem enc_pms; 1.9201 + unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; 1.9202 + SECItem pmsItem = {siBuffer, NULL, 0}; 1.9203 + 1.9204 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.9205 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.9206 + PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec ); 1.9207 + 1.9208 + enc_pms.data = b; 1.9209 + enc_pms.len = length; 1.9210 + pmsItem.data = rsaPmsBuf; 1.9211 + pmsItem.len = sizeof rsaPmsBuf; 1.9212 + 1.9213 + if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ 1.9214 + PRInt32 kLen; 1.9215 + kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); 1.9216 + if (kLen < 0) { 1.9217 + PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.9218 + return SECFailure; 1.9219 + } 1.9220 + if ((unsigned)kLen < enc_pms.len) { 1.9221 + enc_pms.len = kLen; 1.9222 + } 1.9223 + isTLS = PR_TRUE; 1.9224 + } else { 1.9225 + isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); 1.9226 + } 1.9227 + 1.9228 +#ifndef NO_PKCS11_BYPASS 1.9229 + if (ss->opt.bypassPKCS11) { 1.9230 + /* TRIPLE BYPASS, get PMS directly from RSA decryption. 1.9231 + * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, 1.9232 + * then, check for version rollback attack, then 1.9233 + * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in 1.9234 + * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with 1.9235 + * ss and NULL, so that it will use the MS we've already derived here. 1.9236 + */ 1.9237 + 1.9238 + rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, 1.9239 + sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); 1.9240 + if (rv != SECSuccess) { 1.9241 + /* triple bypass failed. Let's try for a double bypass. */ 1.9242 + goto double_bypass; 1.9243 + } else if (ss->opt.detectRollBack) { 1.9244 + SSL3ProtocolVersion client_version = 1.9245 + (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; 1.9246 + 1.9247 + if (IS_DTLS(ss)) { 1.9248 + client_version = dtls_DTLSVersionToTLSVersion(client_version); 1.9249 + } 1.9250 + 1.9251 + if (client_version != ss->clientHelloVersion) { 1.9252 + /* Version roll-back detected. ensure failure. */ 1.9253 + rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); 1.9254 + } 1.9255 + } 1.9256 + /* have PMS, build MS without PKCS11 */ 1.9257 + rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, 1.9258 + PR_TRUE); 1.9259 + if (rv != SECSuccess) { 1.9260 + pwSpec->msItem.data = pwSpec->raw_master_secret; 1.9261 + pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; 1.9262 + PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); 1.9263 + } 1.9264 + rv = ssl3_InitPendingCipherSpec(ss, NULL); 1.9265 + } else 1.9266 +#endif 1.9267 + { 1.9268 +#ifndef NO_PKCS11_BYPASS 1.9269 +double_bypass: 1.9270 +#endif 1.9271 + /* 1.9272 + * unwrap pms out of the incoming buffer 1.9273 + * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do 1.9274 + * the unwrap. Rather, it is the mechanism with which the 1.9275 + * unwrapped pms will be used. 1.9276 + */ 1.9277 + pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, 1.9278 + CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); 1.9279 + if (pms != NULL) { 1.9280 + PRINT_BUF(60, (ss, "decrypted premaster secret:", 1.9281 + PK11_GetKeyData(pms)->data, 1.9282 + PK11_GetKeyData(pms)->len)); 1.9283 + } else { 1.9284 + /* unwrap failed. Generate a bogus PMS and carry on. */ 1.9285 + PK11SlotInfo * slot = PK11_GetSlotFromPrivateKey(serverKey); 1.9286 + 1.9287 + ssl_GetSpecWriteLock(ss); 1.9288 + pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot); 1.9289 + ssl_ReleaseSpecWriteLock(ss); 1.9290 + PK11_FreeSlot(slot); 1.9291 + } 1.9292 + 1.9293 + if (pms == NULL) { 1.9294 + /* last gasp. */ 1.9295 + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); 1.9296 + return SECFailure; 1.9297 + } 1.9298 + 1.9299 + /* This step will derive the MS from the PMS, among other things. */ 1.9300 + rv = ssl3_InitPendingCipherSpec(ss, pms); 1.9301 + PK11_FreeSymKey(pms); 1.9302 + } 1.9303 + 1.9304 + if (rv != SECSuccess) { 1.9305 + SEND_ALERT 1.9306 + return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ 1.9307 + } 1.9308 + return SECSuccess; 1.9309 +} 1.9310 + 1.9311 + 1.9312 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.9313 + * ssl3 ClientKeyExchange message from the remote client 1.9314 + * Caller must hold Handshake and RecvBuf locks. 1.9315 + */ 1.9316 +static SECStatus 1.9317 +ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.9318 +{ 1.9319 + SECKEYPrivateKey *serverKey = NULL; 1.9320 + SECStatus rv; 1.9321 + const ssl3KEADef *kea_def; 1.9322 + ssl3KeyPair *serverKeyPair = NULL; 1.9323 +#ifndef NSS_DISABLE_ECC 1.9324 + SECKEYPublicKey *serverPubKey = NULL; 1.9325 +#endif /* NSS_DISABLE_ECC */ 1.9326 + 1.9327 + SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake", 1.9328 + SSL_GETPID(), ss->fd)); 1.9329 + 1.9330 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.9331 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.9332 + 1.9333 + if (ss->ssl3.hs.ws != wait_client_key) { 1.9334 + SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.9335 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); 1.9336 + return SECFailure; 1.9337 + } 1.9338 + 1.9339 + kea_def = ss->ssl3.hs.kea_def; 1.9340 + 1.9341 + if (ss->ssl3.hs.usedStepDownKey) { 1.9342 + PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ 1.9343 + && kea_def->exchKeyType == kt_rsa 1.9344 + && ss->stepDownKeyPair != NULL); 1.9345 + if (!kea_def->is_limited || 1.9346 + kea_def->exchKeyType != kt_rsa || 1.9347 + ss->stepDownKeyPair == NULL) { 1.9348 + /* shouldn't happen, don't use step down if it does */ 1.9349 + goto skip; 1.9350 + } 1.9351 + serverKeyPair = ss->stepDownKeyPair; 1.9352 + ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; 1.9353 + } else 1.9354 +skip: 1.9355 +#ifndef NSS_DISABLE_ECC 1.9356 + /* XXX Using SSLKEAType to index server certifiates 1.9357 + * does not work for (EC)DHE ciphers. Until we have 1.9358 + * an indexing mechanism general enough for all key 1.9359 + * exchange algorithms, we'll need to deal with each 1.9360 + * one seprately. 1.9361 + */ 1.9362 + if ((kea_def->kea == kea_ecdhe_rsa) || 1.9363 + (kea_def->kea == kea_ecdhe_ecdsa)) { 1.9364 + if (ss->ephemeralECDHKeyPair != NULL) { 1.9365 + serverKeyPair = ss->ephemeralECDHKeyPair; 1.9366 + if (serverKeyPair->pubKey) { 1.9367 + ss->sec.keaKeyBits = 1.9368 + SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); 1.9369 + } 1.9370 + } 1.9371 + } else 1.9372 +#endif 1.9373 + { 1.9374 + sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType; 1.9375 + serverKeyPair = sc->serverKeyPair; 1.9376 + ss->sec.keaKeyBits = sc->serverKeyBits; 1.9377 + } 1.9378 + 1.9379 + if (serverKeyPair) { 1.9380 + serverKey = serverKeyPair->privKey; 1.9381 + } 1.9382 + 1.9383 + if (serverKey == NULL) { 1.9384 + SEND_ALERT 1.9385 + PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); 1.9386 + return SECFailure; 1.9387 + } 1.9388 + 1.9389 + ss->sec.keaType = kea_def->exchKeyType; 1.9390 + 1.9391 + switch (kea_def->exchKeyType) { 1.9392 + case kt_rsa: 1.9393 + rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); 1.9394 + if (rv != SECSuccess) { 1.9395 + SEND_ALERT 1.9396 + return SECFailure; /* error code set */ 1.9397 + } 1.9398 + break; 1.9399 + 1.9400 + 1.9401 +#ifndef NSS_DISABLE_ECC 1.9402 + case kt_ecdh: 1.9403 + /* XXX We really ought to be able to store multiple 1.9404 + * EC certs (a requirement if we wish to support both 1.9405 + * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). 1.9406 + * When we make that change, we'll need an index other 1.9407 + * than kt_ecdh to pick the right EC certificate. 1.9408 + */ 1.9409 + if (serverKeyPair) { 1.9410 + serverPubKey = serverKeyPair->pubKey; 1.9411 + } 1.9412 + if (serverPubKey == NULL) { 1.9413 + /* XXX Is this the right error code? */ 1.9414 + PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); 1.9415 + return SECFailure; 1.9416 + } 1.9417 + rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, 1.9418 + serverPubKey, serverKey); 1.9419 + if (rv != SECSuccess) { 1.9420 + return SECFailure; /* error code set */ 1.9421 + } 1.9422 + break; 1.9423 +#endif /* NSS_DISABLE_ECC */ 1.9424 + 1.9425 + default: 1.9426 + (void) ssl3_HandshakeFailure(ss); 1.9427 + PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); 1.9428 + return SECFailure; 1.9429 + } 1.9430 + ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; 1.9431 + return SECSuccess; 1.9432 + 1.9433 +} 1.9434 + 1.9435 +/* This is TLS's equivalent of sending a no_certificate alert. */ 1.9436 +static SECStatus 1.9437 +ssl3_SendEmptyCertificate(sslSocket *ss) 1.9438 +{ 1.9439 + SECStatus rv; 1.9440 + 1.9441 + rv = ssl3_AppendHandshakeHeader(ss, certificate, 3); 1.9442 + if (rv == SECSuccess) { 1.9443 + rv = ssl3_AppendHandshakeNumber(ss, 0, 3); 1.9444 + } 1.9445 + return rv; /* error, if any, set by functions called above. */ 1.9446 +} 1.9447 + 1.9448 +SECStatus 1.9449 +ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.9450 +{ 1.9451 + SECStatus rv; 1.9452 + SECItem ticketData; 1.9453 + 1.9454 + SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake", 1.9455 + SSL_GETPID(), ss->fd)); 1.9456 + 1.9457 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.9458 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.9459 + 1.9460 + PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); 1.9461 + PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket); 1.9462 + 1.9463 + if (ss->ssl3.hs.ws != wait_new_session_ticket) { 1.9464 + SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.9465 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); 1.9466 + return SECFailure; 1.9467 + } 1.9468 + 1.9469 + /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid 1.9470 + * until it has verified the server's Finished message." See the comment in 1.9471 + * ssl3_FinishHandshake for more details. 1.9472 + */ 1.9473 + ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(); 1.9474 + if (length < 4) { 1.9475 + (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 1.9476 + PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); 1.9477 + return SECFailure; 1.9478 + } 1.9479 + ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = 1.9480 + (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); 1.9481 + 1.9482 + rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length); 1.9483 + if (rv != SECSuccess || length != 0) { 1.9484 + (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 1.9485 + PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); 1.9486 + return SECFailure; /* malformed */ 1.9487 + } 1.9488 + /* If the server sent a zero-length ticket, ignore it and keep the 1.9489 + * existing ticket. */ 1.9490 + if (ticketData.len != 0) { 1.9491 + rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket, 1.9492 + &ticketData); 1.9493 + if (rv != SECSuccess) { 1.9494 + return rv; 1.9495 + } 1.9496 + ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE; 1.9497 + } 1.9498 + 1.9499 + ss->ssl3.hs.ws = wait_change_cipher; 1.9500 + return SECSuccess; 1.9501 +} 1.9502 + 1.9503 +#ifdef NISCC_TEST 1.9504 +static PRInt32 connNum = 0; 1.9505 + 1.9506 +static SECStatus 1.9507 +get_fake_cert(SECItem *pCertItem, int *pIndex) 1.9508 +{ 1.9509 + PRFileDesc *cf; 1.9510 + char * testdir; 1.9511 + char * startat; 1.9512 + char * stopat; 1.9513 + const char *extension; 1.9514 + int fileNum; 1.9515 + PRInt32 numBytes = 0; 1.9516 + PRStatus prStatus; 1.9517 + PRFileInfo info; 1.9518 + char cfn[100]; 1.9519 + 1.9520 + pCertItem->data = 0; 1.9521 + if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) { 1.9522 + return SECSuccess; 1.9523 + } 1.9524 + *pIndex = (NULL != strstr(testdir, "root")); 1.9525 + extension = (strstr(testdir, "simple") ? "" : ".der"); 1.9526 + fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; 1.9527 + if ((startat = PR_GetEnv("START_AT")) != NULL) { 1.9528 + fileNum += atoi(startat); 1.9529 + } 1.9530 + if ((stopat = PR_GetEnv("STOP_AT")) != NULL && 1.9531 + fileNum >= atoi(stopat)) { 1.9532 + *pIndex = -1; 1.9533 + return SECSuccess; 1.9534 + } 1.9535 + sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension); 1.9536 + cf = PR_Open(cfn, PR_RDONLY, 0); 1.9537 + if (!cf) { 1.9538 + goto loser; 1.9539 + } 1.9540 + prStatus = PR_GetOpenFileInfo(cf, &info); 1.9541 + if (prStatus != PR_SUCCESS) { 1.9542 + PR_Close(cf); 1.9543 + goto loser; 1.9544 + } 1.9545 + pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); 1.9546 + if (pCertItem) { 1.9547 + numBytes = PR_Read(cf, pCertItem->data, info.size); 1.9548 + } 1.9549 + PR_Close(cf); 1.9550 + if (numBytes != info.size) { 1.9551 + SECITEM_FreeItem(pCertItem, PR_FALSE); 1.9552 + PORT_SetError(SEC_ERROR_IO); 1.9553 + goto loser; 1.9554 + } 1.9555 + fprintf(stderr, "using %s\n", cfn); 1.9556 + return SECSuccess; 1.9557 + 1.9558 +loser: 1.9559 + fprintf(stderr, "failed to use %s\n", cfn); 1.9560 + *pIndex = -1; 1.9561 + return SECFailure; 1.9562 +} 1.9563 +#endif 1.9564 + 1.9565 +/* 1.9566 + * Used by both client and server. 1.9567 + * Called from HandleServerHelloDone and from SendServerHelloSequence. 1.9568 + */ 1.9569 +static SECStatus 1.9570 +ssl3_SendCertificate(sslSocket *ss) 1.9571 +{ 1.9572 + SECStatus rv; 1.9573 + CERTCertificateList *certChain; 1.9574 + int len = 0; 1.9575 + int i; 1.9576 + SSL3KEAType certIndex; 1.9577 +#ifdef NISCC_TEST 1.9578 + SECItem fakeCert; 1.9579 + int ndex = -1; 1.9580 +#endif 1.9581 + 1.9582 + SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake", 1.9583 + SSL_GETPID(), ss->fd)); 1.9584 + 1.9585 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.9586 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.9587 + 1.9588 + if (ss->sec.localCert) 1.9589 + CERT_DestroyCertificate(ss->sec.localCert); 1.9590 + if (ss->sec.isServer) { 1.9591 + sslServerCerts * sc = NULL; 1.9592 + 1.9593 + /* XXX SSLKEAType isn't really a good choice for 1.9594 + * indexing certificates (it breaks when we deal 1.9595 + * with (EC)DHE-* cipher suites. This hack ensures 1.9596 + * the RSA cert is picked for (EC)DHE-RSA. 1.9597 + * Revisit this when we add server side support 1.9598 + * for ECDHE-ECDSA or client-side authentication 1.9599 + * using EC certificates. 1.9600 + */ 1.9601 + if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || 1.9602 + (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { 1.9603 + certIndex = kt_rsa; 1.9604 + } else { 1.9605 + certIndex = ss->ssl3.hs.kea_def->exchKeyType; 1.9606 + } 1.9607 + sc = ss->serverCerts + certIndex; 1.9608 + certChain = sc->serverCertChain; 1.9609 + ss->sec.authKeyBits = sc->serverKeyBits; 1.9610 + ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; 1.9611 + ss->sec.localCert = CERT_DupCertificate(sc->serverCert); 1.9612 + } else { 1.9613 + certChain = ss->ssl3.clientCertChain; 1.9614 + ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate); 1.9615 + } 1.9616 + 1.9617 +#ifdef NISCC_TEST 1.9618 + rv = get_fake_cert(&fakeCert, &ndex); 1.9619 +#endif 1.9620 + 1.9621 + if (certChain) { 1.9622 + for (i = 0; i < certChain->len; i++) { 1.9623 +#ifdef NISCC_TEST 1.9624 + if (fakeCert.len > 0 && i == ndex) { 1.9625 + len += fakeCert.len + 3; 1.9626 + } else { 1.9627 + len += certChain->certs[i].len + 3; 1.9628 + } 1.9629 +#else 1.9630 + len += certChain->certs[i].len + 3; 1.9631 +#endif 1.9632 + } 1.9633 + } 1.9634 + 1.9635 + rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3); 1.9636 + if (rv != SECSuccess) { 1.9637 + return rv; /* err set by AppendHandshake. */ 1.9638 + } 1.9639 + rv = ssl3_AppendHandshakeNumber(ss, len, 3); 1.9640 + if (rv != SECSuccess) { 1.9641 + return rv; /* err set by AppendHandshake. */ 1.9642 + } 1.9643 + if (certChain) { 1.9644 + for (i = 0; i < certChain->len; i++) { 1.9645 +#ifdef NISCC_TEST 1.9646 + if (fakeCert.len > 0 && i == ndex) { 1.9647 + rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data, 1.9648 + fakeCert.len, 3); 1.9649 + SECITEM_FreeItem(&fakeCert, PR_FALSE); 1.9650 + } else { 1.9651 + rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, 1.9652 + certChain->certs[i].len, 3); 1.9653 + } 1.9654 +#else 1.9655 + rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, 1.9656 + certChain->certs[i].len, 3); 1.9657 +#endif 1.9658 + if (rv != SECSuccess) { 1.9659 + return rv; /* err set by AppendHandshake. */ 1.9660 + } 1.9661 + } 1.9662 + } 1.9663 + 1.9664 + return SECSuccess; 1.9665 +} 1.9666 + 1.9667 +/* 1.9668 + * Used by server only. 1.9669 + * single-stapling, send only a single cert status 1.9670 + */ 1.9671 +static SECStatus 1.9672 +ssl3_SendCertificateStatus(sslSocket *ss) 1.9673 +{ 1.9674 + SECStatus rv; 1.9675 + int len = 0; 1.9676 + SECItemArray *statusToSend = NULL; 1.9677 + SSL3KEAType certIndex; 1.9678 + 1.9679 + SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", 1.9680 + SSL_GETPID(), ss->fd)); 1.9681 + 1.9682 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.9683 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.9684 + PORT_Assert( ss->sec.isServer); 1.9685 + 1.9686 + if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) 1.9687 + return SECSuccess; 1.9688 + 1.9689 + /* Use certStatus based on the cert being used. */ 1.9690 + if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || 1.9691 + (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { 1.9692 + certIndex = kt_rsa; 1.9693 + } else { 1.9694 + certIndex = ss->ssl3.hs.kea_def->exchKeyType; 1.9695 + } 1.9696 + if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) { 1.9697 + statusToSend = ss->certStatusArray[certIndex]; 1.9698 + } 1.9699 + if (!statusToSend) 1.9700 + return SECSuccess; 1.9701 + 1.9702 + /* Use the array's first item only (single stapling) */ 1.9703 + len = 1 + statusToSend->items[0].len + 3; 1.9704 + 1.9705 + rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len); 1.9706 + if (rv != SECSuccess) { 1.9707 + return rv; /* err set by AppendHandshake. */ 1.9708 + } 1.9709 + rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); 1.9710 + if (rv != SECSuccess) 1.9711 + return rv; /* err set by AppendHandshake. */ 1.9712 + 1.9713 + rv = ssl3_AppendHandshakeVariable(ss, 1.9714 + statusToSend->items[0].data, 1.9715 + statusToSend->items[0].len, 1.9716 + 3); 1.9717 + if (rv != SECSuccess) 1.9718 + return rv; /* err set by AppendHandshake. */ 1.9719 + 1.9720 + return SECSuccess; 1.9721 +} 1.9722 + 1.9723 +/* This is used to delete the CA certificates in the peer certificate chain 1.9724 + * from the cert database after they've been validated. 1.9725 + */ 1.9726 +static void 1.9727 +ssl3_CleanupPeerCerts(sslSocket *ss) 1.9728 +{ 1.9729 + PLArenaPool * arena = ss->ssl3.peerCertArena; 1.9730 + ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain; 1.9731 + 1.9732 + for (; certs; certs = certs->next) { 1.9733 + CERT_DestroyCertificate(certs->cert); 1.9734 + } 1.9735 + if (arena) PORT_FreeArena(arena, PR_FALSE); 1.9736 + ss->ssl3.peerCertArena = NULL; 1.9737 + ss->ssl3.peerCertChain = NULL; 1.9738 +} 1.9739 + 1.9740 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.9741 + * ssl3 CertificateStatus message. 1.9742 + * Caller must hold Handshake and RecvBuf locks. 1.9743 + * This is always called before ssl3_HandleCertificate, even if the Certificate 1.9744 + * message is sent first. 1.9745 + */ 1.9746 +static SECStatus 1.9747 +ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.9748 +{ 1.9749 + PRInt32 status, len; 1.9750 + 1.9751 + if (ss->ssl3.hs.ws != wait_certificate_status) { 1.9752 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.9753 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS); 1.9754 + return SECFailure; 1.9755 + } 1.9756 + 1.9757 + PORT_Assert(!ss->sec.isServer); 1.9758 + 1.9759 + /* Consume the CertificateStatusType enum */ 1.9760 + status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); 1.9761 + if (status != 1 /* ocsp */) { 1.9762 + goto format_loser; 1.9763 + } 1.9764 + 1.9765 + len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 1.9766 + if (len != length) { 1.9767 + goto format_loser; 1.9768 + } 1.9769 + 1.9770 +#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ 1.9771 + if (length > MAX_CERTSTATUS_LEN) 1.9772 + goto format_loser; 1.9773 +#undef MAX_CERTSTATUS_LEN 1.9774 + 1.9775 + /* Array size 1, because we currently implement single-stapling only */ 1.9776 + SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1); 1.9777 + if (!ss->sec.ci.sid->peerCertStatus.items) 1.9778 + return SECFailure; 1.9779 + 1.9780 + ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length); 1.9781 + 1.9782 + if (!ss->sec.ci.sid->peerCertStatus.items[0].data) { 1.9783 + SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE); 1.9784 + return SECFailure; 1.9785 + } 1.9786 + 1.9787 + PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length); 1.9788 + ss->sec.ci.sid->peerCertStatus.items[0].len = length; 1.9789 + ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer; 1.9790 + 1.9791 + return ssl3_AuthCertificate(ss); 1.9792 + 1.9793 +format_loser: 1.9794 + return ssl3_DecodeError(ss); 1.9795 +} 1.9796 + 1.9797 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.9798 + * ssl3 Certificate message. 1.9799 + * Caller must hold Handshake and RecvBuf locks. 1.9800 + */ 1.9801 +static SECStatus 1.9802 +ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.9803 +{ 1.9804 + ssl3CertNode * c; 1.9805 + ssl3CertNode * lastCert = NULL; 1.9806 + PRInt32 remaining = 0; 1.9807 + PRInt32 size; 1.9808 + SECStatus rv; 1.9809 + PRBool isServer = (PRBool)(!!ss->sec.isServer); 1.9810 + PRBool isTLS; 1.9811 + SSL3AlertDescription desc; 1.9812 + int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; 1.9813 + SECItem certItem; 1.9814 + 1.9815 + SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake", 1.9816 + SSL_GETPID(), ss->fd)); 1.9817 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.9818 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.9819 + 1.9820 + if ((ss->ssl3.hs.ws != wait_server_cert) && 1.9821 + (ss->ssl3.hs.ws != wait_client_cert)) { 1.9822 + desc = unexpected_message; 1.9823 + errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE; 1.9824 + goto alert_loser; 1.9825 + } 1.9826 + 1.9827 + if (ss->sec.peerCert != NULL) { 1.9828 + if (ss->sec.peerKey) { 1.9829 + SECKEY_DestroyPublicKey(ss->sec.peerKey); 1.9830 + ss->sec.peerKey = NULL; 1.9831 + } 1.9832 + CERT_DestroyCertificate(ss->sec.peerCert); 1.9833 + ss->sec.peerCert = NULL; 1.9834 + } 1.9835 + 1.9836 + ssl3_CleanupPeerCerts(ss); 1.9837 + isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); 1.9838 + 1.9839 + /* It is reported that some TLS client sends a Certificate message 1.9840 + ** with a zero-length message body. We'll treat that case like a 1.9841 + ** normal no_certificates message to maximize interoperability. 1.9842 + */ 1.9843 + if (length) { 1.9844 + remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 1.9845 + if (remaining < 0) 1.9846 + goto loser; /* fatal alert already sent by ConsumeHandshake. */ 1.9847 + if ((PRUint32)remaining > length) 1.9848 + goto decode_loser; 1.9849 + } 1.9850 + 1.9851 + if (!remaining) { 1.9852 + if (!(isTLS && isServer)) { 1.9853 + desc = bad_certificate; 1.9854 + goto alert_loser; 1.9855 + } 1.9856 + /* This is TLS's version of a no_certificate alert. */ 1.9857 + /* I'm a server. I've requested a client cert. He hasn't got one. */ 1.9858 + rv = ssl3_HandleNoCertificate(ss); 1.9859 + if (rv != SECSuccess) { 1.9860 + errCode = PORT_GetError(); 1.9861 + goto loser; 1.9862 + } 1.9863 + ss->ssl3.hs.ws = wait_client_key; 1.9864 + return SECSuccess; 1.9865 + } 1.9866 + 1.9867 + ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); 1.9868 + if (ss->ssl3.peerCertArena == NULL) { 1.9869 + goto loser; /* don't send alerts on memory errors */ 1.9870 + } 1.9871 + 1.9872 + /* First get the peer cert. */ 1.9873 + remaining -= 3; 1.9874 + if (remaining < 0) 1.9875 + goto decode_loser; 1.9876 + 1.9877 + size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 1.9878 + if (size <= 0) 1.9879 + goto loser; /* fatal alert already sent by ConsumeHandshake. */ 1.9880 + 1.9881 + if (remaining < size) 1.9882 + goto decode_loser; 1.9883 + 1.9884 + certItem.data = b; 1.9885 + certItem.len = size; 1.9886 + b += size; 1.9887 + length -= size; 1.9888 + remaining -= size; 1.9889 + 1.9890 + ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, 1.9891 + PR_FALSE, PR_TRUE); 1.9892 + if (ss->sec.peerCert == NULL) { 1.9893 + /* We should report an alert if the cert was bad, but not if the 1.9894 + * problem was just some local problem, like memory error. 1.9895 + */ 1.9896 + goto ambiguous_err; 1.9897 + } 1.9898 + 1.9899 + /* Now get all of the CA certs. */ 1.9900 + while (remaining > 0) { 1.9901 + remaining -= 3; 1.9902 + if (remaining < 0) 1.9903 + goto decode_loser; 1.9904 + 1.9905 + size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); 1.9906 + if (size <= 0) 1.9907 + goto loser; /* fatal alert already sent by ConsumeHandshake. */ 1.9908 + 1.9909 + if (remaining < size) 1.9910 + goto decode_loser; 1.9911 + 1.9912 + certItem.data = b; 1.9913 + certItem.len = size; 1.9914 + b += size; 1.9915 + length -= size; 1.9916 + remaining -= size; 1.9917 + 1.9918 + c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode); 1.9919 + if (c == NULL) { 1.9920 + goto loser; /* don't send alerts on memory errors */ 1.9921 + } 1.9922 + 1.9923 + c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, 1.9924 + PR_FALSE, PR_TRUE); 1.9925 + if (c->cert == NULL) { 1.9926 + goto ambiguous_err; 1.9927 + } 1.9928 + 1.9929 + c->next = NULL; 1.9930 + if (lastCert) { 1.9931 + lastCert->next = c; 1.9932 + } else { 1.9933 + ss->ssl3.peerCertChain = c; 1.9934 + } 1.9935 + lastCert = c; 1.9936 + } 1.9937 + 1.9938 + if (remaining != 0) 1.9939 + goto decode_loser; 1.9940 + 1.9941 + SECKEY_UpdateCertPQG(ss->sec.peerCert); 1.9942 + 1.9943 + if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { 1.9944 + ss->ssl3.hs.ws = wait_certificate_status; 1.9945 + rv = SECSuccess; 1.9946 + } else { 1.9947 + rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ 1.9948 + } 1.9949 + 1.9950 + return rv; 1.9951 + 1.9952 +ambiguous_err: 1.9953 + errCode = PORT_GetError(); 1.9954 + switch (errCode) { 1.9955 + case PR_OUT_OF_MEMORY_ERROR: 1.9956 + case SEC_ERROR_BAD_DATABASE: 1.9957 + case SEC_ERROR_NO_MEMORY: 1.9958 + if (isTLS) { 1.9959 + desc = internal_error; 1.9960 + goto alert_loser; 1.9961 + } 1.9962 + goto loser; 1.9963 + } 1.9964 + ssl3_SendAlertForCertError(ss, errCode); 1.9965 + goto loser; 1.9966 + 1.9967 +decode_loser: 1.9968 + desc = isTLS ? decode_error : bad_certificate; 1.9969 + 1.9970 +alert_loser: 1.9971 + (void)SSL3_SendAlert(ss, alert_fatal, desc); 1.9972 + 1.9973 +loser: 1.9974 + (void)ssl_MapLowLevelError(errCode); 1.9975 + return SECFailure; 1.9976 +} 1.9977 + 1.9978 +static SECStatus 1.9979 +ssl3_AuthCertificate(sslSocket *ss) 1.9980 +{ 1.9981 + SECStatus rv; 1.9982 + PRBool isServer = (PRBool)(!!ss->sec.isServer); 1.9983 + int errCode; 1.9984 + 1.9985 + ss->ssl3.hs.authCertificatePending = PR_FALSE; 1.9986 + 1.9987 + /* 1.9988 + * Ask caller-supplied callback function to validate cert chain. 1.9989 + */ 1.9990 + rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, 1.9991 + PR_TRUE, isServer); 1.9992 + if (rv) { 1.9993 + errCode = PORT_GetError(); 1.9994 + if (rv != SECWouldBlock) { 1.9995 + if (ss->handleBadCert) { 1.9996 + rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); 1.9997 + } 1.9998 + } 1.9999 + 1.10000 + if (rv == SECWouldBlock) { 1.10001 + if (ss->sec.isServer) { 1.10002 + errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS; 1.10003 + rv = SECFailure; 1.10004 + goto loser; 1.10005 + } 1.10006 + 1.10007 + ss->ssl3.hs.authCertificatePending = PR_TRUE; 1.10008 + rv = SECSuccess; 1.10009 + } 1.10010 + 1.10011 + if (rv != SECSuccess) { 1.10012 + ssl3_SendAlertForCertError(ss, errCode); 1.10013 + goto loser; 1.10014 + } 1.10015 + } 1.10016 + 1.10017 + ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); 1.10018 + 1.10019 + if (!ss->sec.isServer) { 1.10020 + CERTCertificate *cert = ss->sec.peerCert; 1.10021 + 1.10022 + /* set the server authentication and key exchange types and sizes 1.10023 + ** from the value in the cert. If the key exchange key is different, 1.10024 + ** it will get fixed when we handle the server key exchange message. 1.10025 + */ 1.10026 + SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert); 1.10027 + ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; 1.10028 + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; 1.10029 + if (pubKey) { 1.10030 + ss->sec.keaKeyBits = ss->sec.authKeyBits = 1.10031 + SECKEY_PublicKeyStrengthInBits(pubKey); 1.10032 +#ifndef NSS_DISABLE_ECC 1.10033 + if (ss->sec.keaType == kt_ecdh) { 1.10034 + /* Get authKeyBits from signing key. 1.10035 + * XXX The code below uses a quick approximation of 1.10036 + * key size based on cert->signatureWrap.signature.data 1.10037 + * (which contains the DER encoded signature). The field 1.10038 + * cert->signatureWrap.signature.len contains the 1.10039 + * length of the encoded signature in bits. 1.10040 + */ 1.10041 + if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) { 1.10042 + ss->sec.authKeyBits = 1.10043 + cert->signatureWrap.signature.data[3]*8; 1.10044 + if (cert->signatureWrap.signature.data[4] == 0x00) 1.10045 + ss->sec.authKeyBits -= 8; 1.10046 + /* 1.10047 + * XXX: if cert is not signed by ecdsa we should 1.10048 + * destroy pubKey and goto bad_cert 1.10049 + */ 1.10050 + } else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) { 1.10051 + ss->sec.authKeyBits = cert->signatureWrap.signature.len; 1.10052 + /* 1.10053 + * XXX: if cert is not signed by rsa we should 1.10054 + * destroy pubKey and goto bad_cert 1.10055 + */ 1.10056 + } 1.10057 + } 1.10058 +#endif /* NSS_DISABLE_ECC */ 1.10059 + SECKEY_DestroyPublicKey(pubKey); 1.10060 + pubKey = NULL; 1.10061 + } 1.10062 + 1.10063 + ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */ 1.10064 + if (ss->ssl3.hs.kea_def->is_limited || 1.10065 + /* XXX OR server cert is signing only. */ 1.10066 +#ifndef NSS_DISABLE_ECC 1.10067 + ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa || 1.10068 + ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || 1.10069 +#endif /* NSS_DISABLE_ECC */ 1.10070 + ss->ssl3.hs.kea_def->exchKeyType == kt_dh) { 1.10071 + ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */ 1.10072 + } 1.10073 + } else { 1.10074 + ss->ssl3.hs.ws = wait_client_key; 1.10075 + } 1.10076 + 1.10077 + PORT_Assert(rv == SECSuccess); 1.10078 + if (rv != SECSuccess) { 1.10079 + errCode = SEC_ERROR_LIBRARY_FAILURE; 1.10080 + rv = SECFailure; 1.10081 + goto loser; 1.10082 + } 1.10083 + 1.10084 + return rv; 1.10085 + 1.10086 +loser: 1.10087 + (void)ssl_MapLowLevelError(errCode); 1.10088 + return SECFailure; 1.10089 +} 1.10090 + 1.10091 +static SECStatus ssl3_FinishHandshake(sslSocket *ss); 1.10092 + 1.10093 +static SECStatus 1.10094 +ssl3_AlwaysFail(sslSocket * ss) 1.10095 +{ 1.10096 + PORT_SetError(PR_INVALID_STATE_ERROR); 1.10097 + return SECFailure; 1.10098 +} 1.10099 + 1.10100 +/* Caller must hold 1stHandshakeLock. 1.10101 +*/ 1.10102 +SECStatus 1.10103 +ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) 1.10104 +{ 1.10105 + SECStatus rv; 1.10106 + 1.10107 + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); 1.10108 + 1.10109 + if (ss->sec.isServer) { 1.10110 + PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); 1.10111 + return SECFailure; 1.10112 + } 1.10113 + 1.10114 + ssl_GetRecvBufLock(ss); 1.10115 + ssl_GetSSL3HandshakeLock(ss); 1.10116 + 1.10117 + if (!ss->ssl3.hs.authCertificatePending) { 1.10118 + PORT_SetError(PR_INVALID_STATE_ERROR); 1.10119 + rv = SECFailure; 1.10120 + goto done; 1.10121 + } 1.10122 + 1.10123 + ss->ssl3.hs.authCertificatePending = PR_FALSE; 1.10124 + 1.10125 + if (error != 0) { 1.10126 + ss->ssl3.hs.restartTarget = ssl3_AlwaysFail; 1.10127 + ssl3_SendAlertForCertError(ss, error); 1.10128 + rv = SECSuccess; 1.10129 + } else if (ss->ssl3.hs.restartTarget != NULL) { 1.10130 + sslRestartTarget target = ss->ssl3.hs.restartTarget; 1.10131 + ss->ssl3.hs.restartTarget = NULL; 1.10132 + 1.10133 + if (target == ssl3_FinishHandshake) { 1.10134 + SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race" 1.10135 + " with peer's finished message", SSL_GETPID(), ss->fd)); 1.10136 + } 1.10137 + 1.10138 + rv = target(ss); 1.10139 + /* Even if we blocked here, we have accomplished enough to claim 1.10140 + * success. Any remaining work will be taken care of by subsequent 1.10141 + * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. 1.10142 + */ 1.10143 + if (rv == SECWouldBlock) { 1.10144 + rv = SECSuccess; 1.10145 + } 1.10146 + } else { 1.10147 + SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with" 1.10148 + " peer's finished message", SSL_GETPID(), ss->fd)); 1.10149 + 1.10150 + PORT_Assert(!ss->ssl3.hs.isResuming); 1.10151 + PORT_Assert(ss->ssl3.hs.ws != idle_handshake); 1.10152 + 1.10153 + if (ss->opt.enableFalseStart && 1.10154 + !ss->firstHsDone && 1.10155 + !ss->ssl3.hs.isResuming && 1.10156 + ssl3_WaitingForStartOfServerSecondRound(ss)) { 1.10157 + /* ssl3_SendClientSecondRound deferred the false start check because 1.10158 + * certificate authentication was pending, so we do it now if we still 1.10159 + * haven't received any of the server's second round yet. 1.10160 + */ 1.10161 + rv = ssl3_CheckFalseStart(ss); 1.10162 + } else { 1.10163 + rv = SECSuccess; 1.10164 + } 1.10165 + } 1.10166 + 1.10167 +done: 1.10168 + ssl_ReleaseSSL3HandshakeLock(ss); 1.10169 + ssl_ReleaseRecvBufLock(ss); 1.10170 + 1.10171 + return rv; 1.10172 +} 1.10173 + 1.10174 +static SECStatus 1.10175 +ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, 1.10176 + PRBool isServer, 1.10177 + const SSL3Hashes * hashes, 1.10178 + TLSFinished * tlsFinished) 1.10179 +{ 1.10180 + const char * label; 1.10181 + unsigned int len; 1.10182 + SECStatus rv; 1.10183 + 1.10184 + label = isServer ? "server finished" : "client finished"; 1.10185 + len = 15; 1.10186 + 1.10187 + rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, 1.10188 + hashes->len, tlsFinished->verify_data, 1.10189 + sizeof tlsFinished->verify_data); 1.10190 + 1.10191 + return rv; 1.10192 +} 1.10193 + 1.10194 +/* The calling function must acquire and release the appropriate 1.10195 + * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for 1.10196 + * ss->ssl3.crSpec). 1.10197 + */ 1.10198 +SECStatus 1.10199 +ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, 1.10200 + unsigned int labelLen, const unsigned char *val, unsigned int valLen, 1.10201 + unsigned char *out, unsigned int outLen) 1.10202 +{ 1.10203 + SECStatus rv = SECSuccess; 1.10204 + 1.10205 + if (spec->master_secret && !spec->bypassCiphers) { 1.10206 + SECItem param = {siBuffer, NULL, 0}; 1.10207 + CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; 1.10208 + PK11Context *prf_context; 1.10209 + unsigned int retLen; 1.10210 + 1.10211 + if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 1.10212 + mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; 1.10213 + } 1.10214 + prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, 1.10215 + spec->master_secret, ¶m); 1.10216 + if (!prf_context) 1.10217 + return SECFailure; 1.10218 + 1.10219 + rv = PK11_DigestBegin(prf_context); 1.10220 + rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen); 1.10221 + rv |= PK11_DigestOp(prf_context, val, valLen); 1.10222 + rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen); 1.10223 + PORT_Assert(rv != SECSuccess || retLen == outLen); 1.10224 + 1.10225 + PK11_DestroyContext(prf_context, PR_TRUE); 1.10226 + } else { 1.10227 + /* bypass PKCS11 */ 1.10228 +#ifdef NO_PKCS11_BYPASS 1.10229 + PORT_Assert(spec->master_secret); 1.10230 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.10231 + rv = SECFailure; 1.10232 +#else 1.10233 + SECItem inData = { siBuffer, }; 1.10234 + SECItem outData = { siBuffer, }; 1.10235 + PRBool isFIPS = PR_FALSE; 1.10236 + 1.10237 + inData.data = (unsigned char *) val; 1.10238 + inData.len = valLen; 1.10239 + outData.data = out; 1.10240 + outData.len = outLen; 1.10241 + if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { 1.10242 + rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, 1.10243 + &outData, isFIPS); 1.10244 + } else { 1.10245 + rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); 1.10246 + } 1.10247 + PORT_Assert(rv != SECSuccess || outData.len == outLen); 1.10248 +#endif 1.10249 + } 1.10250 + return rv; 1.10251 +} 1.10252 + 1.10253 +/* called from ssl3_SendClientSecondRound 1.10254 + * ssl3_HandleFinished 1.10255 + */ 1.10256 +static SECStatus 1.10257 +ssl3_SendNextProto(sslSocket *ss) 1.10258 +{ 1.10259 + SECStatus rv; 1.10260 + int padding_len; 1.10261 + static const unsigned char padding[32] = {0}; 1.10262 + 1.10263 + if (ss->ssl3.nextProto.len == 0 || 1.10264 + ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { 1.10265 + return SECSuccess; 1.10266 + } 1.10267 + 1.10268 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.10269 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.10270 + 1.10271 + padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32); 1.10272 + 1.10273 + rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len + 1.10274 + 2 + padding_len); 1.10275 + if (rv != SECSuccess) { 1.10276 + return rv; /* error code set by AppendHandshakeHeader */ 1.10277 + } 1.10278 + rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, 1.10279 + ss->ssl3.nextProto.len, 1); 1.10280 + if (rv != SECSuccess) { 1.10281 + return rv; /* error code set by AppendHandshake */ 1.10282 + } 1.10283 + rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1); 1.10284 + if (rv != SECSuccess) { 1.10285 + return rv; /* error code set by AppendHandshake */ 1.10286 + } 1.10287 + return rv; 1.10288 +} 1.10289 + 1.10290 +/* called from ssl3_SendFinished 1.10291 + * 1.10292 + * This function is simply a debugging aid and therefore does not return a 1.10293 + * SECStatus. */ 1.10294 +static void 1.10295 +ssl3_RecordKeyLog(sslSocket *ss) 1.10296 +{ 1.10297 + SECStatus rv; 1.10298 + SECItem *keyData; 1.10299 + char buf[14 /* "CLIENT_RANDOM " */ + 1.10300 + SSL3_RANDOM_LENGTH*2 /* client_random */ + 1.10301 + 1 /* " " */ + 1.10302 + 48*2 /* master secret */ + 1.10303 + 1 /* new line */]; 1.10304 + unsigned int j; 1.10305 + 1.10306 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.10307 + 1.10308 + if (!ssl_keylog_iob) 1.10309 + return; 1.10310 + 1.10311 + rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret); 1.10312 + if (rv != SECSuccess) 1.10313 + return; 1.10314 + 1.10315 + ssl_GetSpecReadLock(ss); 1.10316 + 1.10317 + /* keyData does not need to be freed. */ 1.10318 + keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret); 1.10319 + if (!keyData || !keyData->data || keyData->len != 48) { 1.10320 + ssl_ReleaseSpecReadLock(ss); 1.10321 + return; 1.10322 + } 1.10323 + 1.10324 + /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ 1.10325 + 1.10326 + /* There could be multiple, concurrent writers to the 1.10327 + * keylog, so we have to do everything in a single call to 1.10328 + * fwrite. */ 1.10329 + 1.10330 + memcpy(buf, "CLIENT_RANDOM ", 14); 1.10331 + j = 14; 1.10332 + hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); 1.10333 + j += SSL3_RANDOM_LENGTH*2; 1.10334 + buf[j++] = ' '; 1.10335 + hexEncode(buf + j, keyData->data, 48); 1.10336 + j += 48*2; 1.10337 + buf[j++] = '\n'; 1.10338 + 1.10339 + PORT_Assert(j == sizeof(buf)); 1.10340 + 1.10341 + ssl_ReleaseSpecReadLock(ss); 1.10342 + 1.10343 + if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1) 1.10344 + return; 1.10345 + fflush(ssl_keylog_iob); 1.10346 + return; 1.10347 +} 1.10348 + 1.10349 +/* called from ssl3_SendClientSecondRound 1.10350 + * ssl3_HandleClientHello 1.10351 + * ssl3_HandleFinished 1.10352 + */ 1.10353 +static SECStatus 1.10354 +ssl3_SendFinished(sslSocket *ss, PRInt32 flags) 1.10355 +{ 1.10356 + ssl3CipherSpec *cwSpec; 1.10357 + PRBool isTLS; 1.10358 + PRBool isServer = ss->sec.isServer; 1.10359 + SECStatus rv; 1.10360 + SSL3Sender sender = isServer ? sender_server : sender_client; 1.10361 + SSL3Hashes hashes; 1.10362 + TLSFinished tlsFinished; 1.10363 + 1.10364 + SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd)); 1.10365 + 1.10366 + PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); 1.10367 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.10368 + 1.10369 + ssl_GetSpecReadLock(ss); 1.10370 + cwSpec = ss->ssl3.cwSpec; 1.10371 + isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0); 1.10372 + rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender); 1.10373 + if (isTLS && rv == SECSuccess) { 1.10374 + rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished); 1.10375 + } 1.10376 + ssl_ReleaseSpecReadLock(ss); 1.10377 + if (rv != SECSuccess) { 1.10378 + goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ 1.10379 + } 1.10380 + 1.10381 + if (isTLS) { 1.10382 + if (isServer) 1.10383 + ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; 1.10384 + else 1.10385 + ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; 1.10386 + ss->ssl3.hs.finishedBytes = sizeof tlsFinished; 1.10387 + rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished); 1.10388 + if (rv != SECSuccess) 1.10389 + goto fail; /* err set by AppendHandshake. */ 1.10390 + rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished); 1.10391 + if (rv != SECSuccess) 1.10392 + goto fail; /* err set by AppendHandshake. */ 1.10393 + } else { 1.10394 + if (isServer) 1.10395 + ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s; 1.10396 + else 1.10397 + ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s; 1.10398 + PORT_Assert(hashes.len == sizeof hashes.u.s); 1.10399 + ss->ssl3.hs.finishedBytes = sizeof hashes.u.s; 1.10400 + rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s); 1.10401 + if (rv != SECSuccess) 1.10402 + goto fail; /* err set by AppendHandshake. */ 1.10403 + rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s); 1.10404 + if (rv != SECSuccess) 1.10405 + goto fail; /* err set by AppendHandshake. */ 1.10406 + } 1.10407 + rv = ssl3_FlushHandshake(ss, flags); 1.10408 + if (rv != SECSuccess) { 1.10409 + goto fail; /* error code set by ssl3_FlushHandshake */ 1.10410 + } 1.10411 + 1.10412 + ssl3_RecordKeyLog(ss); 1.10413 + 1.10414 + return SECSuccess; 1.10415 + 1.10416 +fail: 1.10417 + return rv; 1.10418 +} 1.10419 + 1.10420 +/* wrap the master secret, and put it into the SID. 1.10421 + * Caller holds the Spec read lock. 1.10422 + */ 1.10423 +SECStatus 1.10424 +ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, 1.10425 + ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType) 1.10426 +{ 1.10427 + PK11SymKey * wrappingKey = NULL; 1.10428 + PK11SlotInfo * symKeySlot; 1.10429 + void * pwArg = ss->pkcs11PinArg; 1.10430 + SECStatus rv = SECFailure; 1.10431 + PRBool isServer = ss->sec.isServer; 1.10432 + CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; 1.10433 + symKeySlot = PK11_GetSlotFromKey(spec->master_secret); 1.10434 + if (!isServer) { 1.10435 + int wrapKeyIndex; 1.10436 + int incarnation; 1.10437 + 1.10438 + /* these next few functions are mere accessors and don't fail. */ 1.10439 + sid->u.ssl3.masterWrapIndex = wrapKeyIndex = 1.10440 + PK11_GetCurrentWrapIndex(symKeySlot); 1.10441 + PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */ 1.10442 + 1.10443 + sid->u.ssl3.masterWrapSeries = incarnation = 1.10444 + PK11_GetSlotSeries(symKeySlot); 1.10445 + sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot); 1.10446 + sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot); 1.10447 + sid->u.ssl3.masterValid = PR_TRUE; 1.10448 + /* Get the default wrapping key, for wrapping the master secret before 1.10449 + * placing it in the SID cache entry. */ 1.10450 + wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex, 1.10451 + CKM_INVALID_MECHANISM, incarnation, 1.10452 + pwArg); 1.10453 + if (wrappingKey) { 1.10454 + mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ 1.10455 + } else { 1.10456 + int keyLength; 1.10457 + /* if the wrappingKey doesn't exist, attempt to create it. 1.10458 + * Note: we intentionally ignore errors here. If we cannot 1.10459 + * generate a wrapping key, it is not fatal to this SSL connection, 1.10460 + * but we will not be able to restart this session. 1.10461 + */ 1.10462 + mechanism = PK11_GetBestWrapMechanism(symKeySlot); 1.10463 + keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism); 1.10464 + /* Zero length means fixed key length algorithm, or error. 1.10465 + * It's ambiguous. 1.10466 + */ 1.10467 + wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL, 1.10468 + keyLength, pwArg); 1.10469 + if (wrappingKey) { 1.10470 + PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); 1.10471 + } 1.10472 + } 1.10473 + } else { 1.10474 + /* server socket using session cache. */ 1.10475 + mechanism = PK11_GetBestWrapMechanism(symKeySlot); 1.10476 + if (mechanism != CKM_INVALID_MECHANISM) { 1.10477 + wrappingKey = 1.10478 + getWrappingKey(ss, symKeySlot, effectiveExchKeyType, 1.10479 + mechanism, pwArg); 1.10480 + if (wrappingKey) { 1.10481 + mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ 1.10482 + } 1.10483 + } 1.10484 + } 1.10485 + 1.10486 + sid->u.ssl3.masterWrapMech = mechanism; 1.10487 + PK11_FreeSlot(symKeySlot); 1.10488 + 1.10489 + if (wrappingKey) { 1.10490 + SECItem wmsItem; 1.10491 + 1.10492 + wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret; 1.10493 + wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret; 1.10494 + rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey, 1.10495 + spec->master_secret, &wmsItem); 1.10496 + /* rv is examined below. */ 1.10497 + sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; 1.10498 + PK11_FreeSymKey(wrappingKey); 1.10499 + } 1.10500 + return rv; 1.10501 +} 1.10502 + 1.10503 +/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete 1.10504 + * ssl3 Finished message from the peer. 1.10505 + * Caller must hold Handshake and RecvBuf locks. 1.10506 + */ 1.10507 +static SECStatus 1.10508 +ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, 1.10509 + const SSL3Hashes *hashes) 1.10510 +{ 1.10511 + sslSessionID * sid = ss->sec.ci.sid; 1.10512 + SECStatus rv = SECSuccess; 1.10513 + PRBool isServer = ss->sec.isServer; 1.10514 + PRBool isTLS; 1.10515 + SSL3KEAType effectiveExchKeyType; 1.10516 + 1.10517 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.10518 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.10519 + 1.10520 + SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake", 1.10521 + SSL_GETPID(), ss->fd)); 1.10522 + 1.10523 + if (ss->ssl3.hs.ws != wait_finished) { 1.10524 + SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10525 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); 1.10526 + return SECFailure; 1.10527 + } 1.10528 + 1.10529 + isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); 1.10530 + if (isTLS) { 1.10531 + TLSFinished tlsFinished; 1.10532 + 1.10533 + if (length != sizeof tlsFinished) { 1.10534 + (void)SSL3_SendAlert(ss, alert_fatal, decode_error); 1.10535 + PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); 1.10536 + return SECFailure; 1.10537 + } 1.10538 + rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer, 1.10539 + hashes, &tlsFinished); 1.10540 + if (!isServer) 1.10541 + ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished; 1.10542 + else 1.10543 + ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished; 1.10544 + ss->ssl3.hs.finishedBytes = sizeof tlsFinished; 1.10545 + if (rv != SECSuccess || 1.10546 + 0 != NSS_SecureMemcmp(&tlsFinished, b, length)) { 1.10547 + (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); 1.10548 + PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1.10549 + return SECFailure; 1.10550 + } 1.10551 + } else { 1.10552 + if (length != sizeof(SSL3Finished)) { 1.10553 + (void)ssl3_IllegalParameter(ss); 1.10554 + PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); 1.10555 + return SECFailure; 1.10556 + } 1.10557 + 1.10558 + if (!isServer) 1.10559 + ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s; 1.10560 + else 1.10561 + ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s; 1.10562 + PORT_Assert(hashes->len == sizeof hashes->u.s); 1.10563 + ss->ssl3.hs.finishedBytes = sizeof hashes->u.s; 1.10564 + if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) { 1.10565 + (void)ssl3_HandshakeFailure(ss); 1.10566 + PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); 1.10567 + return SECFailure; 1.10568 + } 1.10569 + } 1.10570 + 1.10571 + ssl_GetXmitBufLock(ss); /*************************************/ 1.10572 + 1.10573 + if ((isServer && !ss->ssl3.hs.isResuming) || 1.10574 + (!isServer && ss->ssl3.hs.isResuming)) { 1.10575 + PRInt32 flags = 0; 1.10576 + 1.10577 + /* Send a NewSessionTicket message if the client sent us 1.10578 + * either an empty session ticket, or one that did not verify. 1.10579 + * (Note that if either of these conditions was met, then the 1.10580 + * server has sent a SessionTicket extension in the 1.10581 + * ServerHello message.) 1.10582 + */ 1.10583 + if (isServer && !ss->ssl3.hs.isResuming && 1.10584 + ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) { 1.10585 + /* RFC 5077 Section 3.3: "In the case of a full handshake, the 1.10586 + * server MUST verify the client's Finished message before sending 1.10587 + * the ticket." Presumably, this also means that the client's 1.10588 + * certificate, if any, must be verified beforehand too. 1.10589 + */ 1.10590 + rv = ssl3_SendNewSessionTicket(ss); 1.10591 + if (rv != SECSuccess) { 1.10592 + goto xmit_loser; 1.10593 + } 1.10594 + } 1.10595 + 1.10596 + rv = ssl3_SendChangeCipherSpecs(ss); 1.10597 + if (rv != SECSuccess) { 1.10598 + goto xmit_loser; /* err is set. */ 1.10599 + } 1.10600 + /* If this thread is in SSL_SecureSend (trying to write some data) 1.10601 + ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the 1.10602 + ** last two handshake messages (change cipher spec and finished) 1.10603 + ** will be sent in the same send/write call as the application data. 1.10604 + */ 1.10605 + if (ss->writerThread == PR_GetCurrentThread()) { 1.10606 + flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER; 1.10607 + } 1.10608 + 1.10609 + if (!isServer && !ss->firstHsDone) { 1.10610 + rv = ssl3_SendNextProto(ss); 1.10611 + if (rv != SECSuccess) { 1.10612 + goto xmit_loser; /* err code was set. */ 1.10613 + } 1.10614 + } 1.10615 + 1.10616 + if (IS_DTLS(ss)) { 1.10617 + flags |= ssl_SEND_FLAG_NO_RETRANSMIT; 1.10618 + } 1.10619 + 1.10620 + rv = ssl3_SendFinished(ss, flags); 1.10621 + if (rv != SECSuccess) { 1.10622 + goto xmit_loser; /* err is set. */ 1.10623 + } 1.10624 + } 1.10625 + 1.10626 +xmit_loser: 1.10627 + ssl_ReleaseXmitBufLock(ss); /*************************************/ 1.10628 + if (rv != SECSuccess) { 1.10629 + return rv; 1.10630 + } 1.10631 + 1.10632 + if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) { 1.10633 + effectiveExchKeyType = kt_rsa; 1.10634 + } else { 1.10635 + effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; 1.10636 + } 1.10637 + 1.10638 + if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) { 1.10639 + /* fill in the sid */ 1.10640 + sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; 1.10641 + sid->u.ssl3.compression = ss->ssl3.hs.compression; 1.10642 + sid->u.ssl3.policy = ss->ssl3.policy; 1.10643 +#ifndef NSS_DISABLE_ECC 1.10644 + sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; 1.10645 +#endif 1.10646 + sid->u.ssl3.exchKeyType = effectiveExchKeyType; 1.10647 + sid->version = ss->version; 1.10648 + sid->authAlgorithm = ss->sec.authAlgorithm; 1.10649 + sid->authKeyBits = ss->sec.authKeyBits; 1.10650 + sid->keaType = ss->sec.keaType; 1.10651 + sid->keaKeyBits = ss->sec.keaKeyBits; 1.10652 + sid->lastAccessTime = sid->creationTime = ssl_Time(); 1.10653 + sid->expirationTime = sid->creationTime + ssl3_sid_timeout; 1.10654 + sid->localCert = CERT_DupCertificate(ss->sec.localCert); 1.10655 + 1.10656 + ssl_GetSpecReadLock(ss); /*************************************/ 1.10657 + 1.10658 + /* Copy the master secret (wrapped or unwrapped) into the sid */ 1.10659 + if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { 1.10660 + sid->u.ssl3.keys.wrapped_master_secret_len = 1.10661 + ss->ssl3.crSpec->msItem.len; 1.10662 + memcpy(sid->u.ssl3.keys.wrapped_master_secret, 1.10663 + ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); 1.10664 + sid->u.ssl3.masterValid = PR_TRUE; 1.10665 + sid->u.ssl3.keys.msIsWrapped = PR_FALSE; 1.10666 + rv = SECSuccess; 1.10667 + } else { 1.10668 + rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, 1.10669 + ss->ssl3.crSpec, 1.10670 + effectiveExchKeyType); 1.10671 + sid->u.ssl3.keys.msIsWrapped = PR_TRUE; 1.10672 + } 1.10673 + ssl_ReleaseSpecReadLock(ss); /*************************************/ 1.10674 + 1.10675 + /* If the wrap failed, we don't cache the sid. 1.10676 + * The connection continues normally however. 1.10677 + */ 1.10678 + ss->ssl3.hs.cacheSID = rv == SECSuccess; 1.10679 + } 1.10680 + 1.10681 + if (ss->ssl3.hs.authCertificatePending) { 1.10682 + if (ss->ssl3.hs.restartTarget) { 1.10683 + PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget"); 1.10684 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.10685 + return SECFailure; 1.10686 + } 1.10687 + 1.10688 + ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; 1.10689 + return SECWouldBlock; 1.10690 + } 1.10691 + 1.10692 + rv = ssl3_FinishHandshake(ss); 1.10693 + return rv; 1.10694 +} 1.10695 + 1.10696 +/* The return type is SECStatus instead of void because this function needs 1.10697 + * to have type sslRestartTarget. 1.10698 + */ 1.10699 +SECStatus 1.10700 +ssl3_FinishHandshake(sslSocket * ss) 1.10701 +{ 1.10702 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.10703 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.10704 + PORT_Assert( ss->ssl3.hs.restartTarget == NULL ); 1.10705 + 1.10706 + /* The first handshake is now completed. */ 1.10707 + ss->handshake = NULL; 1.10708 + 1.10709 + /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid 1.10710 + * until it has verified the server's Finished message." When the server 1.10711 + * sends a NewSessionTicket in a resumption handshake, we must wait until 1.10712 + * the handshake is finished (we have verified the server's Finished 1.10713 + * AND the server's certificate) before we update the ticket in the sid. 1.10714 + * 1.10715 + * This must be done before we call (*ss->sec.cache)(ss->sec.ci.sid) 1.10716 + * because CacheSID requires the session ticket to already be set, and also 1.10717 + * because of the lazy lock creation scheme used by CacheSID and 1.10718 + * ssl3_SetSIDSessionTicket. 1.10719 + */ 1.10720 + if (ss->ssl3.hs.receivedNewSessionTicket) { 1.10721 + PORT_Assert(!ss->sec.isServer); 1.10722 + ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); 1.10723 + /* The sid took over the ticket data */ 1.10724 + PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); 1.10725 + ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 1.10726 + } 1.10727 + 1.10728 + if (ss->ssl3.hs.cacheSID) { 1.10729 + PORT_Assert(ss->sec.ci.sid->cached == never_cached); 1.10730 + (*ss->sec.cache)(ss->sec.ci.sid); 1.10731 + ss->ssl3.hs.cacheSID = PR_FALSE; 1.10732 + } 1.10733 + 1.10734 + ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ 1.10735 + ss->ssl3.hs.ws = idle_handshake; 1.10736 + 1.10737 + ssl_FinishHandshake(ss); 1.10738 + 1.10739 + return SECSuccess; 1.10740 +} 1.10741 + 1.10742 +/* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3 1.10743 + * hanshake message. 1.10744 + * Caller must hold Handshake and RecvBuf locks. 1.10745 + */ 1.10746 +SECStatus 1.10747 +ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 1.10748 +{ 1.10749 + SECStatus rv = SECSuccess; 1.10750 + SSL3HandshakeType type = ss->ssl3.hs.msg_type; 1.10751 + SSL3Hashes hashes; /* computed hashes are put here. */ 1.10752 + PRUint8 hdr[4]; 1.10753 + PRUint8 dtlsData[8]; 1.10754 + 1.10755 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.10756 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.10757 + /* 1.10758 + * We have to compute the hashes before we update them with the 1.10759 + * current message. 1.10760 + */ 1.10761 + ssl_GetSpecReadLock(ss); /************************************/ 1.10762 + if((type == finished) || (type == certificate_verify)) { 1.10763 + SSL3Sender sender = (SSL3Sender)0; 1.10764 + ssl3CipherSpec *rSpec = ss->ssl3.prSpec; 1.10765 + 1.10766 + if (type == finished) { 1.10767 + sender = ss->sec.isServer ? sender_client : sender_server; 1.10768 + rSpec = ss->ssl3.crSpec; 1.10769 + } 1.10770 + rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); 1.10771 + } 1.10772 + ssl_ReleaseSpecReadLock(ss); /************************************/ 1.10773 + if (rv != SECSuccess) { 1.10774 + return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ 1.10775 + } 1.10776 + SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), 1.10777 + ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); 1.10778 + 1.10779 + hdr[0] = (PRUint8)ss->ssl3.hs.msg_type; 1.10780 + hdr[1] = (PRUint8)(length >> 16); 1.10781 + hdr[2] = (PRUint8)(length >> 8); 1.10782 + hdr[3] = (PRUint8)(length ); 1.10783 + 1.10784 + /* Start new handshake hashes when we start a new handshake */ 1.10785 + if (ss->ssl3.hs.msg_type == client_hello) { 1.10786 + rv = ssl3_RestartHandshakeHashes(ss); 1.10787 + if (rv != SECSuccess) { 1.10788 + return rv; 1.10789 + } 1.10790 + } 1.10791 + /* We should not include hello_request and hello_verify_request messages 1.10792 + * in the handshake hashes */ 1.10793 + if ((ss->ssl3.hs.msg_type != hello_request) && 1.10794 + (ss->ssl3.hs.msg_type != hello_verify_request)) { 1.10795 + rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4); 1.10796 + if (rv != SECSuccess) return rv; /* err code already set. */ 1.10797 + 1.10798 + /* Extra data to simulate a complete DTLS handshake fragment */ 1.10799 + if (IS_DTLS(ss)) { 1.10800 + /* Sequence number */ 1.10801 + dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq); 1.10802 + dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); 1.10803 + 1.10804 + /* Fragment offset */ 1.10805 + dtlsData[2] = 0; 1.10806 + dtlsData[3] = 0; 1.10807 + dtlsData[4] = 0; 1.10808 + 1.10809 + /* Fragment length */ 1.10810 + dtlsData[5] = (PRUint8)(length >> 16); 1.10811 + dtlsData[6] = (PRUint8)(length >> 8); 1.10812 + dtlsData[7] = (PRUint8)(length ); 1.10813 + 1.10814 + rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData, 1.10815 + sizeof(dtlsData)); 1.10816 + if (rv != SECSuccess) return rv; /* err code already set. */ 1.10817 + } 1.10818 + 1.10819 + /* The message body */ 1.10820 + rv = ssl3_UpdateHandshakeHashes(ss, b, length); 1.10821 + if (rv != SECSuccess) return rv; /* err code already set. */ 1.10822 + } 1.10823 + 1.10824 + PORT_SetError(0); /* each message starts with no error. */ 1.10825 + 1.10826 + if (ss->ssl3.hs.ws == wait_certificate_status && 1.10827 + ss->ssl3.hs.msg_type != certificate_status) { 1.10828 + /* If we negotiated the certificate_status extension then we deferred 1.10829 + * certificate validation until we get the CertificateStatus messsage. 1.10830 + * But the CertificateStatus message is optional. If the server did 1.10831 + * not send it then we need to validate the certificate now. If the 1.10832 + * server does send the CertificateStatus message then we will 1.10833 + * authenticate the certificate in ssl3_HandleCertificateStatus. 1.10834 + */ 1.10835 + rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ 1.10836 + PORT_Assert(rv != SECWouldBlock); 1.10837 + if (rv != SECSuccess) { 1.10838 + return rv; 1.10839 + } 1.10840 + } 1.10841 + 1.10842 + switch (ss->ssl3.hs.msg_type) { 1.10843 + case hello_request: 1.10844 + if (length != 0) { 1.10845 + (void)ssl3_DecodeError(ss); 1.10846 + PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST); 1.10847 + return SECFailure; 1.10848 + } 1.10849 + if (ss->sec.isServer) { 1.10850 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10851 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST); 1.10852 + return SECFailure; 1.10853 + } 1.10854 + rv = ssl3_HandleHelloRequest(ss); 1.10855 + break; 1.10856 + case client_hello: 1.10857 + if (!ss->sec.isServer) { 1.10858 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10859 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO); 1.10860 + return SECFailure; 1.10861 + } 1.10862 + rv = ssl3_HandleClientHello(ss, b, length); 1.10863 + break; 1.10864 + case server_hello: 1.10865 + if (ss->sec.isServer) { 1.10866 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10867 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO); 1.10868 + return SECFailure; 1.10869 + } 1.10870 + rv = ssl3_HandleServerHello(ss, b, length); 1.10871 + break; 1.10872 + case hello_verify_request: 1.10873 + if (!IS_DTLS(ss) || ss->sec.isServer) { 1.10874 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10875 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST); 1.10876 + return SECFailure; 1.10877 + } 1.10878 + rv = dtls_HandleHelloVerifyRequest(ss, b, length); 1.10879 + break; 1.10880 + case certificate: 1.10881 + rv = ssl3_HandleCertificate(ss, b, length); 1.10882 + break; 1.10883 + case certificate_status: 1.10884 + rv = ssl3_HandleCertificateStatus(ss, b, length); 1.10885 + break; 1.10886 + case server_key_exchange: 1.10887 + if (ss->sec.isServer) { 1.10888 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10889 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH); 1.10890 + return SECFailure; 1.10891 + } 1.10892 + rv = ssl3_HandleServerKeyExchange(ss, b, length); 1.10893 + break; 1.10894 + case certificate_request: 1.10895 + if (ss->sec.isServer) { 1.10896 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10897 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST); 1.10898 + return SECFailure; 1.10899 + } 1.10900 + rv = ssl3_HandleCertificateRequest(ss, b, length); 1.10901 + break; 1.10902 + case server_hello_done: 1.10903 + if (length != 0) { 1.10904 + (void)ssl3_DecodeError(ss); 1.10905 + PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE); 1.10906 + return SECFailure; 1.10907 + } 1.10908 + if (ss->sec.isServer) { 1.10909 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10910 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE); 1.10911 + return SECFailure; 1.10912 + } 1.10913 + rv = ssl3_HandleServerHelloDone(ss); 1.10914 + break; 1.10915 + case certificate_verify: 1.10916 + if (!ss->sec.isServer) { 1.10917 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10918 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY); 1.10919 + return SECFailure; 1.10920 + } 1.10921 + rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes); 1.10922 + break; 1.10923 + case client_key_exchange: 1.10924 + if (!ss->sec.isServer) { 1.10925 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10926 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); 1.10927 + return SECFailure; 1.10928 + } 1.10929 + rv = ssl3_HandleClientKeyExchange(ss, b, length); 1.10930 + break; 1.10931 + case new_session_ticket: 1.10932 + if (ss->sec.isServer) { 1.10933 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10934 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET); 1.10935 + return SECFailure; 1.10936 + } 1.10937 + rv = ssl3_HandleNewSessionTicket(ss, b, length); 1.10938 + break; 1.10939 + case finished: 1.10940 + rv = ssl3_HandleFinished(ss, b, length, &hashes); 1.10941 + break; 1.10942 + default: 1.10943 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.10944 + PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); 1.10945 + rv = SECFailure; 1.10946 + } 1.10947 + 1.10948 + if (IS_DTLS(ss) && (rv != SECFailure)) { 1.10949 + /* Increment the expected sequence number */ 1.10950 + ss->ssl3.hs.recvMessageSeq++; 1.10951 + } 1.10952 + 1.10953 + return rv; 1.10954 +} 1.10955 + 1.10956 +/* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record. 1.10957 + * origBuf is the decrypted ssl record content. 1.10958 + * Caller must hold the handshake and RecvBuf locks. 1.10959 + */ 1.10960 +static SECStatus 1.10961 +ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) 1.10962 +{ 1.10963 + /* 1.10964 + * There may be a partial handshake message already in the handshake 1.10965 + * state. The incoming buffer may contain another portion, or a 1.10966 + * complete message or several messages followed by another portion. 1.10967 + * 1.10968 + * Each message is made contiguous before being passed to the actual 1.10969 + * message parser. 1.10970 + */ 1.10971 + sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */ 1.10972 + SECStatus rv; 1.10973 + 1.10974 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.10975 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.10976 + 1.10977 + if (buf->buf == NULL) { 1.10978 + *buf = *origBuf; 1.10979 + } 1.10980 + while (buf->len > 0) { 1.10981 + if (ss->ssl3.hs.header_bytes < 4) { 1.10982 + PRUint8 t; 1.10983 + t = *(buf->buf++); 1.10984 + buf->len--; 1.10985 + if (ss->ssl3.hs.header_bytes++ == 0) 1.10986 + ss->ssl3.hs.msg_type = (SSL3HandshakeType)t; 1.10987 + else 1.10988 + ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t; 1.10989 + if (ss->ssl3.hs.header_bytes < 4) 1.10990 + continue; 1.10991 + 1.10992 +#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */ 1.10993 + if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) { 1.10994 + (void)ssl3_DecodeError(ss); 1.10995 + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 1.10996 + return SECFailure; 1.10997 + } 1.10998 +#undef MAX_HANDSHAKE_MSG_LEN 1.10999 + 1.11000 + /* If msg_len is zero, be sure we fall through, 1.11001 + ** even if buf->len is zero. 1.11002 + */ 1.11003 + if (ss->ssl3.hs.msg_len > 0) 1.11004 + continue; 1.11005 + } 1.11006 + 1.11007 + /* 1.11008 + * Header has been gathered and there is at least one byte of new 1.11009 + * data available for this message. If it can be done right out 1.11010 + * of the original buffer, then use it from there. 1.11011 + */ 1.11012 + if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) { 1.11013 + /* handle it from input buffer */ 1.11014 + rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len); 1.11015 + if (rv == SECFailure) { 1.11016 + /* This test wants to fall through on either 1.11017 + * SECSuccess or SECWouldBlock. 1.11018 + * ssl3_HandleHandshakeMessage MUST set the error code. 1.11019 + */ 1.11020 + return rv; 1.11021 + } 1.11022 + buf->buf += ss->ssl3.hs.msg_len; 1.11023 + buf->len -= ss->ssl3.hs.msg_len; 1.11024 + ss->ssl3.hs.msg_len = 0; 1.11025 + ss->ssl3.hs.header_bytes = 0; 1.11026 + if (rv != SECSuccess) { /* return if SECWouldBlock. */ 1.11027 + return rv; 1.11028 + } 1.11029 + } else { 1.11030 + /* must be copied to msg_body and dealt with from there */ 1.11031 + unsigned int bytes; 1.11032 + 1.11033 + PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len); 1.11034 + bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len); 1.11035 + 1.11036 + /* Grow the buffer if needed */ 1.11037 + rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len); 1.11038 + if (rv != SECSuccess) { 1.11039 + /* sslBuffer_Grow has set a memory error code. */ 1.11040 + return SECFailure; 1.11041 + } 1.11042 + 1.11043 + PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len, 1.11044 + buf->buf, bytes); 1.11045 + ss->ssl3.hs.msg_body.len += bytes; 1.11046 + buf->buf += bytes; 1.11047 + buf->len -= bytes; 1.11048 + 1.11049 + PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len); 1.11050 + 1.11051 + /* if we have a whole message, do it */ 1.11052 + if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) { 1.11053 + rv = ssl3_HandleHandshakeMessage( 1.11054 + ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len); 1.11055 + if (rv == SECFailure) { 1.11056 + /* This test wants to fall through on either 1.11057 + * SECSuccess or SECWouldBlock. 1.11058 + * ssl3_HandleHandshakeMessage MUST set error code. 1.11059 + */ 1.11060 + return rv; 1.11061 + } 1.11062 + ss->ssl3.hs.msg_body.len = 0; 1.11063 + ss->ssl3.hs.msg_len = 0; 1.11064 + ss->ssl3.hs.header_bytes = 0; 1.11065 + if (rv != SECSuccess) { /* return if SECWouldBlock. */ 1.11066 + return rv; 1.11067 + } 1.11068 + } else { 1.11069 + PORT_Assert(buf->len == 0); 1.11070 + break; 1.11071 + } 1.11072 + } 1.11073 + } /* end loop */ 1.11074 + 1.11075 + origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ 1.11076 + buf->buf = NULL; /* not a leak. */ 1.11077 + return SECSuccess; 1.11078 +} 1.11079 + 1.11080 +/* These macros return the given value with the MSB copied to all the other 1.11081 + * bits. They use the fact that arithmetic shift shifts-in the sign bit. 1.11082 + * However, this is not ensured by the C standard so you may need to replace 1.11083 + * them with something else for odd compilers. */ 1.11084 +#define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) ) 1.11085 +#define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x))) 1.11086 + 1.11087 +/* SECStatusToMask returns, in constant time, a mask value of all ones if 1.11088 + * rv == SECSuccess. Otherwise it returns zero. */ 1.11089 +static unsigned int 1.11090 +SECStatusToMask(SECStatus rv) 1.11091 +{ 1.11092 + unsigned int good; 1.11093 + /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results 1.11094 + * in the MSB being set to one iff it was zero before. */ 1.11095 + good = rv ^ SECSuccess; 1.11096 + good--; 1.11097 + return DUPLICATE_MSB_TO_ALL(good); 1.11098 +} 1.11099 + 1.11100 +/* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */ 1.11101 +static unsigned char 1.11102 +ssl_ConstantTimeGE(unsigned int a, unsigned int b) 1.11103 +{ 1.11104 + a -= b; 1.11105 + return DUPLICATE_MSB_TO_ALL(~a); 1.11106 +} 1.11107 + 1.11108 +/* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */ 1.11109 +static unsigned char 1.11110 +ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) 1.11111 +{ 1.11112 + unsigned int c = a ^ b; 1.11113 + c--; 1.11114 + return DUPLICATE_MSB_TO_ALL_8(c); 1.11115 +} 1.11116 + 1.11117 +static SECStatus 1.11118 +ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, 1.11119 + unsigned int blockSize, 1.11120 + unsigned int macSize) 1.11121 +{ 1.11122 + unsigned int paddingLength, good, t; 1.11123 + const unsigned int overhead = 1 /* padding length byte */ + macSize; 1.11124 + 1.11125 + /* These lengths are all public so we can test them in non-constant 1.11126 + * time. */ 1.11127 + if (overhead > plaintext->len) { 1.11128 + return SECFailure; 1.11129 + } 1.11130 + 1.11131 + paddingLength = plaintext->buf[plaintext->len-1]; 1.11132 + /* SSLv3 padding bytes are random and cannot be checked. */ 1.11133 + t = plaintext->len; 1.11134 + t -= paddingLength+overhead; 1.11135 + /* If len >= paddingLength+overhead then the MSB of t is zero. */ 1.11136 + good = DUPLICATE_MSB_TO_ALL(~t); 1.11137 + /* SSLv3 requires that the padding is minimal. */ 1.11138 + t = blockSize - (paddingLength+1); 1.11139 + good &= DUPLICATE_MSB_TO_ALL(~t); 1.11140 + plaintext->len -= good & (paddingLength+1); 1.11141 + return (good & SECSuccess) | (~good & SECFailure); 1.11142 +} 1.11143 + 1.11144 +static SECStatus 1.11145 +ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) 1.11146 +{ 1.11147 + unsigned int paddingLength, good, t, toCheck, i; 1.11148 + const unsigned int overhead = 1 /* padding length byte */ + macSize; 1.11149 + 1.11150 + /* These lengths are all public so we can test them in non-constant 1.11151 + * time. */ 1.11152 + if (overhead > plaintext->len) { 1.11153 + return SECFailure; 1.11154 + } 1.11155 + 1.11156 + paddingLength = plaintext->buf[plaintext->len-1]; 1.11157 + t = plaintext->len; 1.11158 + t -= paddingLength+overhead; 1.11159 + /* If len >= paddingLength+overhead then the MSB of t is zero. */ 1.11160 + good = DUPLICATE_MSB_TO_ALL(~t); 1.11161 + 1.11162 + /* The padding consists of a length byte at the end of the record and then 1.11163 + * that many bytes of padding, all with the same value as the length byte. 1.11164 + * Thus, with the length byte included, there are paddingLength+1 bytes of 1.11165 + * padding. 1.11166 + * 1.11167 + * We can't check just |paddingLength+1| bytes because that leaks 1.11168 + * decrypted information. Therefore we always have to check the maximum 1.11169 + * amount of padding possible. (Again, the length of the record is 1.11170 + * public information so we can use it.) */ 1.11171 + toCheck = 255; /* maximum amount of padding. */ 1.11172 + if (toCheck > plaintext->len-1) { 1.11173 + toCheck = plaintext->len-1; 1.11174 + } 1.11175 + 1.11176 + for (i = 0; i < toCheck; i++) { 1.11177 + unsigned int t = paddingLength - i; 1.11178 + /* If i <= paddingLength then the MSB of t is zero and mask is 1.11179 + * 0xff. Otherwise, mask is 0. */ 1.11180 + unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); 1.11181 + unsigned char b = plaintext->buf[plaintext->len-1-i]; 1.11182 + /* The final |paddingLength+1| bytes should all have the value 1.11183 + * |paddingLength|. Therefore the XOR should be zero. */ 1.11184 + good &= ~(mask&(paddingLength ^ b)); 1.11185 + } 1.11186 + 1.11187 + /* If any of the final |paddingLength+1| bytes had the wrong value, 1.11188 + * one or more of the lower eight bits of |good| will be cleared. We 1.11189 + * AND the bottom 8 bits together and duplicate the result to all the 1.11190 + * bits. */ 1.11191 + good &= good >> 4; 1.11192 + good &= good >> 2; 1.11193 + good &= good >> 1; 1.11194 + good <<= sizeof(good)*8-1; 1.11195 + good = DUPLICATE_MSB_TO_ALL(good); 1.11196 + 1.11197 + plaintext->len -= good & (paddingLength+1); 1.11198 + return (good & SECSuccess) | (~good & SECFailure); 1.11199 +} 1.11200 + 1.11201 +/* On entry: 1.11202 + * originalLength >= macSize 1.11203 + * macSize <= MAX_MAC_LENGTH 1.11204 + * plaintext->len >= macSize 1.11205 + */ 1.11206 +static void 1.11207 +ssl_CBCExtractMAC(sslBuffer *plaintext, 1.11208 + unsigned int originalLength, 1.11209 + SSL3Opaque* out, 1.11210 + unsigned int macSize) 1.11211 +{ 1.11212 + unsigned char rotatedMac[MAX_MAC_LENGTH]; 1.11213 + /* macEnd is the index of |plaintext->buf| just after the end of the 1.11214 + * MAC. */ 1.11215 + unsigned macEnd = plaintext->len; 1.11216 + unsigned macStart = macEnd - macSize; 1.11217 + /* scanStart contains the number of bytes that we can ignore because 1.11218 + * the MAC's position can only vary by 255 bytes. */ 1.11219 + unsigned scanStart = 0; 1.11220 + unsigned i, j, divSpoiler; 1.11221 + unsigned char rotateOffset; 1.11222 + 1.11223 + if (originalLength > macSize + 255 + 1) 1.11224 + scanStart = originalLength - (macSize + 255 + 1); 1.11225 + 1.11226 + /* divSpoiler contains a multiple of macSize that is used to cause the 1.11227 + * modulo operation to be constant time. Without this, the time varies 1.11228 + * based on the amount of padding when running on Intel chips at least. 1.11229 + * 1.11230 + * The aim of right-shifting macSize is so that the compiler doesn't 1.11231 + * figure out that it can remove divSpoiler as that would require it 1.11232 + * to prove that macSize is always even, which I hope is beyond it. */ 1.11233 + divSpoiler = macSize >> 1; 1.11234 + divSpoiler <<= (sizeof(divSpoiler)-1)*8; 1.11235 + rotateOffset = (divSpoiler + macStart - scanStart) % macSize; 1.11236 + 1.11237 + memset(rotatedMac, 0, macSize); 1.11238 + for (i = scanStart; i < originalLength;) { 1.11239 + for (j = 0; j < macSize && i < originalLength; i++, j++) { 1.11240 + unsigned char macStarted = ssl_ConstantTimeGE(i, macStart); 1.11241 + unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd); 1.11242 + unsigned char b = 0; 1.11243 + b = plaintext->buf[i]; 1.11244 + rotatedMac[j] |= b & macStarted & ~macEnded; 1.11245 + } 1.11246 + } 1.11247 + 1.11248 + /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line 1.11249 + * we could line-align |rotatedMac| and rotate in place. */ 1.11250 + memset(out, 0, macSize); 1.11251 + for (i = 0; i < macSize; i++) { 1.11252 + unsigned char offset = 1.11253 + (divSpoiler + macSize - rotateOffset + i) % macSize; 1.11254 + for (j = 0; j < macSize; j++) { 1.11255 + out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); 1.11256 + } 1.11257 + } 1.11258 +} 1.11259 + 1.11260 +/* if cText is non-null, then decipher, check MAC, and decompress the 1.11261 + * SSL record from cText->buf (typically gs->inbuf) 1.11262 + * into databuf (typically gs->buf), and any previous contents of databuf 1.11263 + * is lost. Then handle databuf according to its SSL record type, 1.11264 + * unless it's an application record. 1.11265 + * 1.11266 + * If cText is NULL, then the ciphertext has previously been deciphered and 1.11267 + * checked, and is already sitting in databuf. It is processed as an SSL 1.11268 + * Handshake message. 1.11269 + * 1.11270 + * DOES NOT process the decrypted/decompressed application data. 1.11271 + * On return, databuf contains the decrypted/decompressed record. 1.11272 + * 1.11273 + * Called from ssl3_GatherCompleteHandshake 1.11274 + * ssl3_RestartHandshakeAfterCertReq 1.11275 + * 1.11276 + * Caller must hold the RecvBufLock. 1.11277 + * 1.11278 + * This function aquires and releases the SSL3Handshake Lock, holding the 1.11279 + * lock around any calls to functions that handle records other than 1.11280 + * Application Data records. 1.11281 + */ 1.11282 +SECStatus 1.11283 +ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) 1.11284 +{ 1.11285 + const ssl3BulkCipherDef *cipher_def; 1.11286 + ssl3CipherSpec * crSpec; 1.11287 + SECStatus rv; 1.11288 + unsigned int hashBytes = MAX_MAC_LENGTH + 1; 1.11289 + PRBool isTLS; 1.11290 + SSL3ContentType rType; 1.11291 + SSL3Opaque hash[MAX_MAC_LENGTH]; 1.11292 + SSL3Opaque givenHashBuf[MAX_MAC_LENGTH]; 1.11293 + SSL3Opaque *givenHash; 1.11294 + sslBuffer *plaintext; 1.11295 + sslBuffer temp_buf; 1.11296 + PRUint64 dtls_seq_num; 1.11297 + unsigned int ivLen = 0; 1.11298 + unsigned int originalLen = 0; 1.11299 + unsigned int good; 1.11300 + unsigned int minLength; 1.11301 + unsigned char header[13]; 1.11302 + unsigned int headerLen; 1.11303 + 1.11304 + PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); 1.11305 + 1.11306 + if (!ss->ssl3.initialized) { 1.11307 + ssl_GetSSL3HandshakeLock(ss); 1.11308 + rv = ssl3_InitState(ss); 1.11309 + ssl_ReleaseSSL3HandshakeLock(ss); 1.11310 + if (rv != SECSuccess) { 1.11311 + return rv; /* ssl3_InitState has set the error code. */ 1.11312 + } 1.11313 + } 1.11314 + 1.11315 + /* check for Token Presence */ 1.11316 + if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { 1.11317 + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); 1.11318 + return SECFailure; 1.11319 + } 1.11320 + 1.11321 + /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX(). 1.11322 + * This implies that databuf holds a previously deciphered SSL Handshake 1.11323 + * message. 1.11324 + */ 1.11325 + if (cText == NULL) { 1.11326 + SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", 1.11327 + SSL_GETPID(), ss->fd)); 1.11328 + rType = content_handshake; 1.11329 + goto process_it; 1.11330 + } 1.11331 + 1.11332 + ssl_GetSpecReadLock(ss); /******************************************/ 1.11333 + 1.11334 + crSpec = ss->ssl3.crSpec; 1.11335 + cipher_def = crSpec->cipher_def; 1.11336 + 1.11337 + /* 1.11338 + * DTLS relevance checks: 1.11339 + * Note that this code currently ignores all out-of-epoch packets, 1.11340 + * which means we lose some in the case of rehandshake + 1.11341 + * loss/reordering. Since DTLS is explicitly unreliable, this 1.11342 + * seems like a good tradeoff for implementation effort and is 1.11343 + * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1 1.11344 + */ 1.11345 + if (IS_DTLS(ss)) { 1.11346 + DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff; 1.11347 + 1.11348 + if (crSpec->epoch != epoch) { 1.11349 + ssl_ReleaseSpecReadLock(ss); 1.11350 + SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet " 1.11351 + "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch)); 1.11352 + /* Silently drop the packet */ 1.11353 + databuf->len = 0; /* Needed to ensure data not left around */ 1.11354 + return SECSuccess; 1.11355 + } 1.11356 + 1.11357 + dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) | 1.11358 + ((PRUint64)cText->seq_num.low); 1.11359 + 1.11360 + if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) { 1.11361 + ssl_ReleaseSpecReadLock(ss); 1.11362 + SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting " 1.11363 + "potentially replayed packet", SSL_GETPID(), ss->fd)); 1.11364 + /* Silently drop the packet */ 1.11365 + databuf->len = 0; /* Needed to ensure data not left around */ 1.11366 + return SECSuccess; 1.11367 + } 1.11368 + } 1.11369 + 1.11370 + good = ~0U; 1.11371 + minLength = crSpec->mac_size; 1.11372 + if (cipher_def->type == type_block) { 1.11373 + /* CBC records have a padding length byte at the end. */ 1.11374 + minLength++; 1.11375 + if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 1.11376 + /* With >= TLS 1.1, CBC records have an explicit IV. */ 1.11377 + minLength += cipher_def->iv_size; 1.11378 + } 1.11379 + } else if (cipher_def->type == type_aead) { 1.11380 + minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size; 1.11381 + } 1.11382 + 1.11383 + /* We can perform this test in variable time because the record's total 1.11384 + * length and the ciphersuite are both public knowledge. */ 1.11385 + if (cText->buf->len < minLength) { 1.11386 + goto decrypt_loser; 1.11387 + } 1.11388 + 1.11389 + if (cipher_def->type == type_block && 1.11390 + crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { 1.11391 + /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states 1.11392 + * "The receiver decrypts the entire GenericBlockCipher structure and 1.11393 + * then discards the first cipher block corresponding to the IV 1.11394 + * component." Instead, we decrypt the first cipher block and then 1.11395 + * discard it before decrypting the rest. 1.11396 + */ 1.11397 + SSL3Opaque iv[MAX_IV_LENGTH]; 1.11398 + int decoded; 1.11399 + 1.11400 + ivLen = cipher_def->iv_size; 1.11401 + if (ivLen < 8 || ivLen > sizeof(iv)) { 1.11402 + ssl_ReleaseSpecReadLock(ss); 1.11403 + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); 1.11404 + return SECFailure; 1.11405 + } 1.11406 + 1.11407 + PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen)); 1.11408 + 1.11409 + /* The decryption result is garbage, but since we just throw away 1.11410 + * the block it doesn't matter. The decryption of the next block 1.11411 + * depends only on the ciphertext of the IV block. 1.11412 + */ 1.11413 + rv = crSpec->decode(crSpec->decodeContext, iv, &decoded, 1.11414 + sizeof(iv), cText->buf->buf, ivLen); 1.11415 + 1.11416 + good &= SECStatusToMask(rv); 1.11417 + } 1.11418 + 1.11419 + /* If we will be decompressing the buffer we need to decrypt somewhere 1.11420 + * other than into databuf */ 1.11421 + if (crSpec->decompressor) { 1.11422 + temp_buf.buf = NULL; 1.11423 + temp_buf.space = 0; 1.11424 + plaintext = &temp_buf; 1.11425 + } else { 1.11426 + plaintext = databuf; 1.11427 + } 1.11428 + 1.11429 + plaintext->len = 0; /* filled in by decode call below. */ 1.11430 + if (plaintext->space < MAX_FRAGMENT_LENGTH) { 1.11431 + rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); 1.11432 + if (rv != SECSuccess) { 1.11433 + ssl_ReleaseSpecReadLock(ss); 1.11434 + SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", 1.11435 + SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); 1.11436 + /* sslBuffer_Grow has set a memory error code. */ 1.11437 + /* Perhaps we should send an alert. (but we have no memory!) */ 1.11438 + return SECFailure; 1.11439 + } 1.11440 + } 1.11441 + 1.11442 + PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, 1.11443 + cText->buf->len - ivLen)); 1.11444 + 1.11445 + isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); 1.11446 + 1.11447 + if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { 1.11448 + ssl_ReleaseSpecReadLock(ss); 1.11449 + SSL3_SendAlert(ss, alert_fatal, record_overflow); 1.11450 + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 1.11451 + return SECFailure; 1.11452 + } 1.11453 + 1.11454 + rType = cText->type; 1.11455 + if (cipher_def->type == type_aead) { 1.11456 + /* XXX For many AEAD ciphers, the plaintext is shorter than the 1.11457 + * ciphertext by a fixed byte count, but it is not true in general. 1.11458 + * Each AEAD cipher should provide a function that returns the 1.11459 + * plaintext length for a given ciphertext. */ 1.11460 + unsigned int decryptedLen = 1.11461 + cText->buf->len - cipher_def->explicit_nonce_size - 1.11462 + cipher_def->tag_size; 1.11463 + headerLen = ssl3_BuildRecordPseudoHeader( 1.11464 + header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, 1.11465 + rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); 1.11466 + PORT_Assert(headerLen <= sizeof(header)); 1.11467 + rv = crSpec->aead( 1.11468 + ss->sec.isServer ? &crSpec->client : &crSpec->server, 1.11469 + PR_TRUE, /* do decrypt */ 1.11470 + plaintext->buf, /* out */ 1.11471 + (int*) &plaintext->len, /* outlen */ 1.11472 + plaintext->space, /* maxout */ 1.11473 + cText->buf->buf, /* in */ 1.11474 + cText->buf->len, /* inlen */ 1.11475 + header, headerLen); 1.11476 + if (rv != SECSuccess) { 1.11477 + good = 0; 1.11478 + } 1.11479 + } else { 1.11480 + if (cipher_def->type == type_block && 1.11481 + ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) { 1.11482 + goto decrypt_loser; 1.11483 + } 1.11484 + 1.11485 + /* decrypt from cText buf to plaintext. */ 1.11486 + rv = crSpec->decode( 1.11487 + crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len, 1.11488 + plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen); 1.11489 + if (rv != SECSuccess) { 1.11490 + goto decrypt_loser; 1.11491 + } 1.11492 + 1.11493 + PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len)); 1.11494 + 1.11495 + originalLen = plaintext->len; 1.11496 + 1.11497 + /* If it's a block cipher, check and strip the padding. */ 1.11498 + if (cipher_def->type == type_block) { 1.11499 + const unsigned int blockSize = cipher_def->block_size; 1.11500 + const unsigned int macSize = crSpec->mac_size; 1.11501 + 1.11502 + if (!isTLS) { 1.11503 + good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( 1.11504 + plaintext, blockSize, macSize)); 1.11505 + } else { 1.11506 + good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( 1.11507 + plaintext, macSize)); 1.11508 + } 1.11509 + } 1.11510 + 1.11511 + /* compute the MAC */ 1.11512 + headerLen = ssl3_BuildRecordPseudoHeader( 1.11513 + header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, 1.11514 + rType, isTLS, cText->version, IS_DTLS(ss), 1.11515 + plaintext->len - crSpec->mac_size); 1.11516 + PORT_Assert(headerLen <= sizeof(header)); 1.11517 + if (cipher_def->type == type_block) { 1.11518 + rv = ssl3_ComputeRecordMACConstantTime( 1.11519 + crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, 1.11520 + plaintext->buf, plaintext->len, originalLen, 1.11521 + hash, &hashBytes); 1.11522 + 1.11523 + ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, 1.11524 + crSpec->mac_size); 1.11525 + givenHash = givenHashBuf; 1.11526 + 1.11527 + /* plaintext->len will always have enough space to remove the MAC 1.11528 + * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust 1.11529 + * plaintext->len if the result has enough space for the MAC and we 1.11530 + * tested the unadjusted size against minLength, above. */ 1.11531 + plaintext->len -= crSpec->mac_size; 1.11532 + } else { 1.11533 + /* This is safe because we checked the minLength above. */ 1.11534 + plaintext->len -= crSpec->mac_size; 1.11535 + 1.11536 + rv = ssl3_ComputeRecordMAC( 1.11537 + crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, 1.11538 + plaintext->buf, plaintext->len, hash, &hashBytes); 1.11539 + 1.11540 + /* We can read the MAC directly from the record because its location 1.11541 + * is public when a stream cipher is used. */ 1.11542 + givenHash = plaintext->buf + plaintext->len; 1.11543 + } 1.11544 + 1.11545 + good &= SECStatusToMask(rv); 1.11546 + 1.11547 + if (hashBytes != (unsigned)crSpec->mac_size || 1.11548 + NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { 1.11549 + /* We're allowed to leak whether or not the MAC check was correct */ 1.11550 + good = 0; 1.11551 + } 1.11552 + } 1.11553 + 1.11554 + if (good == 0) { 1.11555 +decrypt_loser: 1.11556 + /* must not hold spec lock when calling SSL3_SendAlert. */ 1.11557 + ssl_ReleaseSpecReadLock(ss); 1.11558 + 1.11559 + SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); 1.11560 + 1.11561 + if (!IS_DTLS(ss)) { 1.11562 + SSL3_SendAlert(ss, alert_fatal, bad_record_mac); 1.11563 + /* always log mac error, in case attacker can read server logs. */ 1.11564 + PORT_SetError(SSL_ERROR_BAD_MAC_READ); 1.11565 + return SECFailure; 1.11566 + } else { 1.11567 + /* Silently drop the packet */ 1.11568 + databuf->len = 0; /* Needed to ensure data not left around */ 1.11569 + return SECSuccess; 1.11570 + } 1.11571 + } 1.11572 + 1.11573 + if (!IS_DTLS(ss)) { 1.11574 + ssl3_BumpSequenceNumber(&crSpec->read_seq_num); 1.11575 + } else { 1.11576 + dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); 1.11577 + } 1.11578 + 1.11579 + ssl_ReleaseSpecReadLock(ss); /*****************************************/ 1.11580 + 1.11581 + /* 1.11582 + * The decrypted data is now in plaintext. 1.11583 + */ 1.11584 + 1.11585 + /* possibly decompress the record. If we aren't using compression then 1.11586 + * plaintext == databuf and so the uncompressed data is already in 1.11587 + * databuf. */ 1.11588 + if (crSpec->decompressor) { 1.11589 + if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { 1.11590 + rv = sslBuffer_Grow( 1.11591 + databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); 1.11592 + if (rv != SECSuccess) { 1.11593 + SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", 1.11594 + SSL_GETPID(), ss->fd, 1.11595 + plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION)); 1.11596 + /* sslBuffer_Grow has set a memory error code. */ 1.11597 + /* Perhaps we should send an alert. (but we have no memory!) */ 1.11598 + PORT_Free(plaintext->buf); 1.11599 + return SECFailure; 1.11600 + } 1.11601 + } 1.11602 + 1.11603 + rv = crSpec->decompressor(crSpec->decompressContext, 1.11604 + databuf->buf, 1.11605 + (int*) &databuf->len, 1.11606 + databuf->space, 1.11607 + plaintext->buf, 1.11608 + plaintext->len); 1.11609 + 1.11610 + if (rv != SECSuccess) { 1.11611 + int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); 1.11612 + SSL3_SendAlert(ss, alert_fatal, 1.11613 + isTLS ? decompression_failure : bad_record_mac); 1.11614 + 1.11615 + /* There appears to be a bug with (at least) Apache + OpenSSL where 1.11616 + * resumed SSLv3 connections don't actually use compression. See 1.11617 + * comments 93-95 of 1.11618 + * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 1.11619 + * 1.11620 + * So, if we get a decompression error, and the record appears to 1.11621 + * be already uncompressed, then we return a more specific error 1.11622 + * code to hopefully save somebody some debugging time in the 1.11623 + * future. 1.11624 + */ 1.11625 + if (plaintext->len >= 4) { 1.11626 + unsigned int len = ((unsigned int) plaintext->buf[1] << 16) | 1.11627 + ((unsigned int) plaintext->buf[2] << 8) | 1.11628 + (unsigned int) plaintext->buf[3]; 1.11629 + if (len == plaintext->len - 4) { 1.11630 + /* This appears to be uncompressed already */ 1.11631 + err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; 1.11632 + } 1.11633 + } 1.11634 + 1.11635 + PORT_Free(plaintext->buf); 1.11636 + PORT_SetError(err); 1.11637 + return SECFailure; 1.11638 + } 1.11639 + 1.11640 + PORT_Free(plaintext->buf); 1.11641 + } 1.11642 + 1.11643 + /* 1.11644 + ** Having completed the decompression, check the length again. 1.11645 + */ 1.11646 + if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) { 1.11647 + SSL3_SendAlert(ss, alert_fatal, record_overflow); 1.11648 + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); 1.11649 + return SECFailure; 1.11650 + } 1.11651 + 1.11652 + /* Application data records are processed by the caller of this 1.11653 + ** function, not by this function. 1.11654 + */ 1.11655 + if (rType == content_application_data) { 1.11656 + if (ss->firstHsDone) 1.11657 + return SECSuccess; 1.11658 + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); 1.11659 + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); 1.11660 + return SECFailure; 1.11661 + } 1.11662 + 1.11663 + /* It's a record that must be handled by ssl itself, not the application. 1.11664 + */ 1.11665 +process_it: 1.11666 + /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting 1.11667 + * data ang getting the xmit lock here prevents deadlocks. 1.11668 + */ 1.11669 + ssl_GetSSL3HandshakeLock(ss); 1.11670 + 1.11671 + /* All the functions called in this switch MUST set error code if 1.11672 + ** they return SECFailure or SECWouldBlock. 1.11673 + */ 1.11674 + switch (rType) { 1.11675 + case content_change_cipher_spec: 1.11676 + rv = ssl3_HandleChangeCipherSpecs(ss, databuf); 1.11677 + break; 1.11678 + case content_alert: 1.11679 + rv = ssl3_HandleAlert(ss, databuf); 1.11680 + break; 1.11681 + case content_handshake: 1.11682 + if (!IS_DTLS(ss)) { 1.11683 + rv = ssl3_HandleHandshake(ss, databuf); 1.11684 + } else { 1.11685 + rv = dtls_HandleHandshake(ss, databuf); 1.11686 + } 1.11687 + break; 1.11688 + /* 1.11689 + case content_application_data is handled before this switch 1.11690 + */ 1.11691 + default: 1.11692 + SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", 1.11693 + SSL_GETPID(), ss->fd, cText->type)); 1.11694 + /* XXX Send an alert ??? */ 1.11695 + PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); 1.11696 + rv = SECFailure; 1.11697 + break; 1.11698 + } 1.11699 + 1.11700 + ssl_ReleaseSSL3HandshakeLock(ss); 1.11701 + return rv; 1.11702 +} 1.11703 + 1.11704 +/* 1.11705 + * Initialization functions 1.11706 + */ 1.11707 + 1.11708 +/* Called from ssl3_InitState, immediately below. */ 1.11709 +/* Caller must hold the SpecWriteLock. */ 1.11710 +static void 1.11711 +ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) 1.11712 +{ 1.11713 + spec->cipher_def = &bulk_cipher_defs[cipher_null]; 1.11714 + PORT_Assert(spec->cipher_def->cipher == cipher_null); 1.11715 + spec->mac_def = &mac_defs[mac_null]; 1.11716 + PORT_Assert(spec->mac_def->mac == mac_null); 1.11717 + spec->encode = Null_Cipher; 1.11718 + spec->decode = Null_Cipher; 1.11719 + spec->destroy = NULL; 1.11720 + spec->compressor = NULL; 1.11721 + spec->decompressor = NULL; 1.11722 + spec->destroyCompressContext = NULL; 1.11723 + spec->destroyDecompressContext = NULL; 1.11724 + spec->mac_size = 0; 1.11725 + spec->master_secret = NULL; 1.11726 + spec->bypassCiphers = PR_FALSE; 1.11727 + 1.11728 + spec->msItem.data = NULL; 1.11729 + spec->msItem.len = 0; 1.11730 + 1.11731 + spec->client.write_key = NULL; 1.11732 + spec->client.write_mac_key = NULL; 1.11733 + spec->client.write_mac_context = NULL; 1.11734 + 1.11735 + spec->server.write_key = NULL; 1.11736 + spec->server.write_mac_key = NULL; 1.11737 + spec->server.write_mac_context = NULL; 1.11738 + 1.11739 + spec->write_seq_num.high = 0; 1.11740 + spec->write_seq_num.low = 0; 1.11741 + 1.11742 + spec->read_seq_num.high = 0; 1.11743 + spec->read_seq_num.low = 0; 1.11744 + 1.11745 + spec->epoch = 0; 1.11746 + dtls_InitRecvdRecords(&spec->recvdRecords); 1.11747 + 1.11748 + spec->version = ss->vrange.max; 1.11749 +} 1.11750 + 1.11751 +/* Called from: ssl3_SendRecord 1.11752 +** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() 1.11753 +** ssl3_SendClientHello() 1.11754 +** ssl3_HandleV2ClientHello() 1.11755 +** ssl3_HandleRecord() 1.11756 +** 1.11757 +** This function should perhaps acquire and release the SpecWriteLock. 1.11758 +** 1.11759 +** 1.11760 +*/ 1.11761 +static SECStatus 1.11762 +ssl3_InitState(sslSocket *ss) 1.11763 +{ 1.11764 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 1.11765 + 1.11766 + if (ss->ssl3.initialized) 1.11767 + return SECSuccess; /* Function should be idempotent */ 1.11768 + 1.11769 + ss->ssl3.policy = SSL_ALLOWED; 1.11770 + 1.11771 + ssl_GetSpecWriteLock(ss); 1.11772 + ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0]; 1.11773 + ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1]; 1.11774 + ss->ssl3.hs.sendingSCSV = PR_FALSE; 1.11775 + ssl3_InitCipherSpec(ss, ss->ssl3.crSpec); 1.11776 + ssl3_InitCipherSpec(ss, ss->ssl3.prSpec); 1.11777 + 1.11778 + ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello; 1.11779 +#ifndef NSS_DISABLE_ECC 1.11780 + ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss); 1.11781 +#endif 1.11782 + ssl_ReleaseSpecWriteLock(ss); 1.11783 + 1.11784 + PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); 1.11785 + 1.11786 + if (IS_DTLS(ss)) { 1.11787 + ss->ssl3.hs.sendMessageSeq = 0; 1.11788 + ss->ssl3.hs.recvMessageSeq = 0; 1.11789 + ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; 1.11790 + ss->ssl3.hs.rtRetries = 0; 1.11791 + ss->ssl3.hs.recvdHighWater = -1; 1.11792 + PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); 1.11793 + dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */ 1.11794 + } 1.11795 + 1.11796 + PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space); 1.11797 + ss->ssl3.hs.messages.buf = NULL; 1.11798 + ss->ssl3.hs.messages.space = 0; 1.11799 + 1.11800 + ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; 1.11801 + PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, 1.11802 + sizeof(ss->ssl3.hs.newSessionTicket)); 1.11803 + 1.11804 + ss->ssl3.initialized = PR_TRUE; 1.11805 + return SECSuccess; 1.11806 +} 1.11807 + 1.11808 +/* Returns a reference counted object that contains a key pair. 1.11809 + * Or NULL on failure. Initial ref count is 1. 1.11810 + * Uses the keys in the pair as input. 1.11811 + */ 1.11812 +ssl3KeyPair * 1.11813 +ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey) 1.11814 +{ 1.11815 + ssl3KeyPair * pair; 1.11816 + 1.11817 + if (!privKey || !pubKey) { 1.11818 + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 1.11819 + return NULL; 1.11820 + } 1.11821 + pair = PORT_ZNew(ssl3KeyPair); 1.11822 + if (!pair) 1.11823 + return NULL; /* error code is set. */ 1.11824 + pair->refCount = 1; 1.11825 + pair->privKey = privKey; 1.11826 + pair->pubKey = pubKey; 1.11827 + return pair; /* success */ 1.11828 +} 1.11829 + 1.11830 +ssl3KeyPair * 1.11831 +ssl3_GetKeyPairRef(ssl3KeyPair * keyPair) 1.11832 +{ 1.11833 + PR_ATOMIC_INCREMENT(&keyPair->refCount); 1.11834 + return keyPair; 1.11835 +} 1.11836 + 1.11837 +void 1.11838 +ssl3_FreeKeyPair(ssl3KeyPair * keyPair) 1.11839 +{ 1.11840 + PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); 1.11841 + if (!newCount) { 1.11842 + if (keyPair->privKey) 1.11843 + SECKEY_DestroyPrivateKey(keyPair->privKey); 1.11844 + if (keyPair->pubKey) 1.11845 + SECKEY_DestroyPublicKey( keyPair->pubKey); 1.11846 + PORT_Free(keyPair); 1.11847 + } 1.11848 +} 1.11849 + 1.11850 + 1.11851 + 1.11852 +/* 1.11853 + * Creates the public and private RSA keys for SSL Step down. 1.11854 + * Called from SSL_ConfigSecureServer in sslsecur.c 1.11855 + */ 1.11856 +SECStatus 1.11857 +ssl3_CreateRSAStepDownKeys(sslSocket *ss) 1.11858 +{ 1.11859 + SECStatus rv = SECSuccess; 1.11860 + SECKEYPrivateKey * privKey; /* RSA step down key */ 1.11861 + SECKEYPublicKey * pubKey; /* RSA step down key */ 1.11862 + 1.11863 + if (ss->stepDownKeyPair) 1.11864 + ssl3_FreeKeyPair(ss->stepDownKeyPair); 1.11865 + ss->stepDownKeyPair = NULL; 1.11866 +#ifndef HACKED_EXPORT_SERVER 1.11867 + /* Sigh, should have a get key strength call for private keys */ 1.11868 + if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) > 1.11869 + EXPORT_RSA_KEY_LENGTH) { 1.11870 + /* need to ask for the key size in bits */ 1.11871 + privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, 1.11872 + &pubKey, NULL); 1.11873 + if (!privKey || !pubKey || 1.11874 + !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { 1.11875 + ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); 1.11876 + rv = SECFailure; 1.11877 + } 1.11878 + } 1.11879 +#endif 1.11880 + return rv; 1.11881 +} 1.11882 + 1.11883 + 1.11884 +/* record the export policy for this cipher suite */ 1.11885 +SECStatus 1.11886 +ssl3_SetPolicy(ssl3CipherSuite which, int policy) 1.11887 +{ 1.11888 + ssl3CipherSuiteCfg *suite; 1.11889 + 1.11890 + suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 1.11891 + if (suite == NULL) { 1.11892 + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 1.11893 + } 1.11894 + suite->policy = policy; 1.11895 + 1.11896 + return SECSuccess; 1.11897 +} 1.11898 + 1.11899 +SECStatus 1.11900 +ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) 1.11901 +{ 1.11902 + ssl3CipherSuiteCfg *suite; 1.11903 + PRInt32 policy; 1.11904 + SECStatus rv; 1.11905 + 1.11906 + suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 1.11907 + if (suite) { 1.11908 + policy = suite->policy; 1.11909 + rv = SECSuccess; 1.11910 + } else { 1.11911 + policy = SSL_NOT_ALLOWED; 1.11912 + rv = SECFailure; /* err code was set by Lookup. */ 1.11913 + } 1.11914 + *oPolicy = policy; 1.11915 + return rv; 1.11916 +} 1.11917 + 1.11918 +/* record the user preference for this suite */ 1.11919 +SECStatus 1.11920 +ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) 1.11921 +{ 1.11922 + ssl3CipherSuiteCfg *suite; 1.11923 + 1.11924 + suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 1.11925 + if (suite == NULL) { 1.11926 + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 1.11927 + } 1.11928 + suite->enabled = enabled; 1.11929 + return SECSuccess; 1.11930 +} 1.11931 + 1.11932 +/* return the user preference for this suite */ 1.11933 +SECStatus 1.11934 +ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) 1.11935 +{ 1.11936 + ssl3CipherSuiteCfg *suite; 1.11937 + PRBool pref; 1.11938 + SECStatus rv; 1.11939 + 1.11940 + suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); 1.11941 + if (suite) { 1.11942 + pref = suite->enabled; 1.11943 + rv = SECSuccess; 1.11944 + } else { 1.11945 + pref = SSL_NOT_ALLOWED; 1.11946 + rv = SECFailure; /* err code was set by Lookup. */ 1.11947 + } 1.11948 + *enabled = pref; 1.11949 + return rv; 1.11950 +} 1.11951 + 1.11952 +SECStatus 1.11953 +ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) 1.11954 +{ 1.11955 + ssl3CipherSuiteCfg *suite; 1.11956 + 1.11957 + suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); 1.11958 + if (suite == NULL) { 1.11959 + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ 1.11960 + } 1.11961 + suite->enabled = enabled; 1.11962 + return SECSuccess; 1.11963 +} 1.11964 + 1.11965 +SECStatus 1.11966 +ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) 1.11967 +{ 1.11968 + ssl3CipherSuiteCfg *suite; 1.11969 + PRBool pref; 1.11970 + SECStatus rv; 1.11971 + 1.11972 + suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); 1.11973 + if (suite) { 1.11974 + pref = suite->enabled; 1.11975 + rv = SECSuccess; 1.11976 + } else { 1.11977 + pref = SSL_NOT_ALLOWED; 1.11978 + rv = SECFailure; /* err code was set by Lookup. */ 1.11979 + } 1.11980 + *enabled = pref; 1.11981 + return rv; 1.11982 +} 1.11983 + 1.11984 +/* copy global default policy into socket. */ 1.11985 +void 1.11986 +ssl3_InitSocketPolicy(sslSocket *ss) 1.11987 +{ 1.11988 + PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites); 1.11989 +} 1.11990 + 1.11991 +/* ssl3_config_match_init must have already been called by 1.11992 + * the caller of this function. 1.11993 + */ 1.11994 +SECStatus 1.11995 +ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) 1.11996 +{ 1.11997 + int i, count = 0; 1.11998 + 1.11999 + PORT_Assert(ss != 0); 1.12000 + if (!ss) { 1.12001 + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); 1.12002 + return SECFailure; 1.12003 + } 1.12004 + if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { 1.12005 + *size = 0; 1.12006 + return SECSuccess; 1.12007 + } 1.12008 + if (cs == NULL) { 1.12009 + *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); 1.12010 + return SECSuccess; 1.12011 + } 1.12012 + 1.12013 + /* ssl3_config_match_init was called by the caller of this function. */ 1.12014 + for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { 1.12015 + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; 1.12016 + if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange)) { 1.12017 + if (cs != NULL) { 1.12018 + *cs++ = 0x00; 1.12019 + *cs++ = (suite->cipher_suite >> 8) & 0xFF; 1.12020 + *cs++ = suite->cipher_suite & 0xFF; 1.12021 + } 1.12022 + count++; 1.12023 + } 1.12024 + } 1.12025 + *size = count; 1.12026 + return SECSuccess; 1.12027 +} 1.12028 + 1.12029 +/* 1.12030 +** If ssl3 socket has completed the first handshake, and is in idle state, 1.12031 +** then start a new handshake. 1.12032 +** If flushCache is true, the SID cache will be flushed first, forcing a 1.12033 +** "Full" handshake (not a session restart handshake), to be done. 1.12034 +** 1.12035 +** called from SSL_RedoHandshake(), which already holds the handshake locks. 1.12036 +*/ 1.12037 +SECStatus 1.12038 +ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) 1.12039 +{ 1.12040 + sslSessionID * sid = ss->sec.ci.sid; 1.12041 + SECStatus rv; 1.12042 + 1.12043 + PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); 1.12044 + 1.12045 + if (!ss->firstHsDone || 1.12046 + ((ss->version >= SSL_LIBRARY_VERSION_3_0) && 1.12047 + ss->ssl3.initialized && 1.12048 + (ss->ssl3.hs.ws != idle_handshake))) { 1.12049 + PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); 1.12050 + return SECFailure; 1.12051 + } 1.12052 + 1.12053 + if (IS_DTLS(ss)) { 1.12054 + dtls_RehandshakeCleanup(ss); 1.12055 + } 1.12056 + 1.12057 + if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { 1.12058 + PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); 1.12059 + return SECFailure; 1.12060 + } 1.12061 + if (sid && flushCache) { 1.12062 + if (ss->sec.uncache) 1.12063 + ss->sec.uncache(sid); /* remove it from whichever cache it's in. */ 1.12064 + ssl_FreeSID(sid); /* dec ref count and free if zero. */ 1.12065 + ss->sec.ci.sid = NULL; 1.12066 + } 1.12067 + 1.12068 + ssl_GetXmitBufLock(ss); /**************************************/ 1.12069 + 1.12070 + /* start off a new handshake. */ 1.12071 + rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss) 1.12072 + : ssl3_SendClientHello(ss, PR_FALSE); 1.12073 + 1.12074 + ssl_ReleaseXmitBufLock(ss); /**************************************/ 1.12075 + return rv; 1.12076 +} 1.12077 + 1.12078 +/* Called from ssl_DestroySocketContents() in sslsock.c */ 1.12079 +void 1.12080 +ssl3_DestroySSL3Info(sslSocket *ss) 1.12081 +{ 1.12082 + 1.12083 + if (ss->ssl3.clientCertificate != NULL) 1.12084 + CERT_DestroyCertificate(ss->ssl3.clientCertificate); 1.12085 + 1.12086 + if (ss->ssl3.clientPrivateKey != NULL) 1.12087 + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); 1.12088 + 1.12089 + if (ss->ssl3.peerCertArena != NULL) 1.12090 + ssl3_CleanupPeerCerts(ss); 1.12091 + 1.12092 + if (ss->ssl3.clientCertChain != NULL) { 1.12093 + CERT_DestroyCertificateList(ss->ssl3.clientCertChain); 1.12094 + ss->ssl3.clientCertChain = NULL; 1.12095 + } 1.12096 + 1.12097 + /* clean up handshake */ 1.12098 +#ifndef NO_PKCS11_BYPASS 1.12099 + if (ss->opt.bypassPKCS11) { 1.12100 + if (ss->ssl3.hs.hashType == handshake_hash_combo) { 1.12101 + SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); 1.12102 + MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); 1.12103 + } else if (ss->ssl3.hs.hashType == handshake_hash_single) { 1.12104 + ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); 1.12105 + } 1.12106 + } 1.12107 +#endif 1.12108 + if (ss->ssl3.hs.md5) { 1.12109 + PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); 1.12110 + } 1.12111 + if (ss->ssl3.hs.sha) { 1.12112 + PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE); 1.12113 + } 1.12114 + if (ss->ssl3.hs.clientSigAndHash) { 1.12115 + PORT_Free(ss->ssl3.hs.clientSigAndHash); 1.12116 + } 1.12117 + if (ss->ssl3.hs.messages.buf) { 1.12118 + PORT_Free(ss->ssl3.hs.messages.buf); 1.12119 + ss->ssl3.hs.messages.buf = NULL; 1.12120 + ss->ssl3.hs.messages.len = 0; 1.12121 + ss->ssl3.hs.messages.space = 0; 1.12122 + } 1.12123 + 1.12124 + /* free the SSL3Buffer (msg_body) */ 1.12125 + PORT_Free(ss->ssl3.hs.msg_body.buf); 1.12126 + 1.12127 + SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); 1.12128 + 1.12129 + /* free up the CipherSpecs */ 1.12130 + ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/); 1.12131 + ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/); 1.12132 + 1.12133 + /* Destroy the DTLS data */ 1.12134 + if (IS_DTLS(ss)) { 1.12135 + dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); 1.12136 + if (ss->ssl3.hs.recvdFragments.buf) { 1.12137 + PORT_Free(ss->ssl3.hs.recvdFragments.buf); 1.12138 + } 1.12139 + } 1.12140 + 1.12141 + ss->ssl3.initialized = PR_FALSE; 1.12142 + 1.12143 + SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); 1.12144 +} 1.12145 + 1.12146 +/* End of ssl3con.c */